Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-29T04:13:36.330Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

omega_deltas.rs

7166 lines · 314.3 KB · rust
1//! Mechanical checks for every deliberate Omega divergence from Zed.
2//!
3//! A fork accumulates silent divergence: someone changes a default, a rebase
4//! quietly reverts it, and nobody notices until an owner sees upstream
5//! behaviour again in a release candidate. A code comment does not survive
6//! that, because a merge can drop the comment and the value together.
7//!
8//! Each delta in `OMEGA_DELTAS.md` has a test here that fails if the Omega
9//! value reverts to the upstream one. The tests name the upstream value they
10//! replace, so the diff stays legible to whoever is doing the rebase.
11
12/// Repository-root-relative path of the shipped default settings.
13pub const DEFAULT_SETTINGS_PATH: &str = "assets/settings/default.json";
14
15/// The registry document every delta is recorded in.
16pub const DELTA_REGISTRY_PATH: &str = "OMEGA_DELTAS.md";
17
18/// Every delta ID enforced by a test in this crate.
19///
20/// Kept in sync in both directions by `the_registry_and_the_checks_agree`:
21/// an ID here with no `### <ID>` heading in the registry fails, and a heading
22/// in the registry with no ID here fails too. An earlier version of this
23/// comment claimed a check that did not exist, which an adversarial review
24/// caught.
25///
26/// Uniqueness is a separate check. Two lanes once allocated `0010` and `0011`
27/// at the same time, so four entries shared two IDs and none of them could be
28/// cited; `delta_ids_are_unique` fails on a repeat rather than letting the set
29/// comparison above swallow it.
30pub const ENFORCED_DELTAS: &[&str] = &[
31    "OMEGA-DELTA-0001",
32    "OMEGA-DELTA-0002",
33    "OMEGA-DELTA-0003",
34    "OMEGA-DELTA-0004",
35    "OMEGA-DELTA-0005",
36    "OMEGA-DELTA-0006",
37    "OMEGA-DELTA-0007",
38    "OMEGA-DELTA-0008",
39    "OMEGA-DELTA-0009",
40    "OMEGA-DELTA-0010",
41    "OMEGA-DELTA-0011",
42    "OMEGA-DELTA-0012",
43    "OMEGA-DELTA-0013",
44    "OMEGA-DELTA-0014",
45    "OMEGA-DELTA-0015",
46    "OMEGA-DELTA-0016",
47    "OMEGA-DELTA-0017",
48    "OMEGA-DELTA-0018",
49    "OMEGA-DELTA-0019",
50    "OMEGA-DELTA-0020",
51    "OMEGA-DELTA-0021",
52    "OMEGA-DELTA-0022",
53    "OMEGA-DELTA-0023",
54    "OMEGA-DELTA-0024",
55    "OMEGA-DELTA-0025",
56    "OMEGA-DELTA-0026",
57    "OMEGA-DELTA-0027",
58    "OMEGA-DELTA-0028",
59    "OMEGA-DELTA-0029",
60    "OMEGA-DELTA-0030",
61    "OMEGA-DELTA-0031",
62    "OMEGA-DELTA-0032",
63    "OMEGA-DELTA-0033",
64    "OMEGA-DELTA-0034",
65    "OMEGA-DELTA-0035",
66    "OMEGA-DELTA-0036",
67    "OMEGA-DELTA-0037",
68    "OMEGA-DELTA-0038",
69    "OMEGA-DELTA-0039",
70    "OMEGA-DELTA-0040",
71    "OMEGA-DELTA-0041",
72    "OMEGA-DELTA-0042",
73    "OMEGA-DELTA-0043",
74    "OMEGA-DELTA-0044",
75    "OMEGA-DELTA-0045",
76    "OMEGA-DELTA-0046",
77];
78
79/// OMEGA-DELTA-0036. The uninstall script embedded in the shipped `cli`.
80pub const UNINSTALL_SCRIPT_PATH: &str = "script/uninstall.sh";
81
82/// OMEGA-DELTA-0036. Where the removal plan is derived from `paths::`.
83pub const UNINSTALL_PLAN_PATH: &str = "crates/cli/src/uninstall.rs";
84
85/// OMEGA-DELTA-0043, OMEGA-DELTA-0044. The CLI binary: it derives the
86/// uninstall plan and renders the open-behavior prompt.
87pub const CLI_MAIN_PATH: &str = "crates/cli/src/main.rs";
88
89/// OMEGA-DELTA-0037. Outbound attribution on OpenRouter requests.
90pub const OPEN_ROUTER_PATH: &str = "crates/open_router/src/open_router.rs";
91
92/// OMEGA-DELTA-0039. The installed-proof secret tripwire collector.
93pub const INSTALLED_TRIPWIRE_PATH: &str = "script/collect-omega-installed-tripwires";
94
95/// OMEGA-DELTA-0039. The installed-proof observation collector.
96pub const INSTALLED_OBSERVATION_PATH: &str = "script/collect-omega-installed-observations";
97
98/// OMEGA-DELTA-0025. The file that declares the measured digest.
99pub const MEASURED_DIGEST_PATH: &str = "crates/omega_harness/src/measured.rs";
100
101/// OMEGA-DELTA-0025. Every admitted way into `MeasuredDigest`.
102///
103/// A closed list, not a denylist. The invariant is "there is no path from a
104/// string into this type", and a denylist of `From<String>`, `FromStr`,
105/// `Deserialize` and `new` would be a list of the four ways somebody already
106/// thought of. Naming the admitted constructors instead makes a fifth one fail
107/// by existing.
108pub const MEASURED_DIGEST_CONSTRUCTORS: &[&str] = &["measure", "measure_tree"];
109
110/// OMEGA-DELTA-0025. The filesystem half of harness maintenance.
111pub const HARNESS_MAINTENANCE_PATH: &str = "crates/project/src/harness_maintenance.rs";
112
113/// OMEGA-DELTA-0025. The launch path the provenance gate sits in.
114pub const AGENT_SERVER_STORE_PATH: &str = "crates/project/src/agent_server_store.rs";
115
116/// OMEGA-DELTA-0033. The decision layer for what the owner's front door shows.
117pub const HARNESS_FRONT_DOOR_PATH: &str = "crates/omega_harness/src/front_door.rs";
118
119/// OMEGA-DELTA-0033. The page that renders it.
120pub const EXTERNAL_AGENTS_PAGE_PATH: &str = "crates/settings_ui/src/pages/external_agents_page.rs";
121
122/// OMEGA-DELTA-0026. Shipped defaults that would otherwise point a running
123/// Omega at one of Zed's production hosts, as
124/// `(dotted key, upstream JSON, Omega JSON)`.
125///
126/// The values are written as JSON text rather than typed constants because they
127/// are not all the same type — a URL, a boolean, an enum string and an object —
128/// and a table that can hold all four is what makes this one check rather than
129/// four.
130pub const SERVICE_ISOLATION_DEFAULTS: &[(&str, &str, &str)] = &[
131    (
132        "server_url",
133        "\"https://zed.dev\"",
134        "\"https://services.openagents.invalid\"",
135    ),
136    ("auto_update", "true", "false"),
137    ("edit_predictions.provider", "\"zed\"", "\"none\""),
138    ("auto_install_extensions", "{\"html\": true}", "{}"),
139];
140
141/// The service-isolation test the registry cites for `OMEGA-DELTA-0026` and
142/// `OMEGA-DELTA-0027`.
143pub const SERVICE_ISOLATION_TEST_PATH: &str = "crates/app_identity/src/service_isolation.rs";
144
145/// Assertions in `SERVICE_ISOLATION_TEST_PATH` that two delta entries cite.
146///
147/// Citing an existing check instead of duplicating it is the right call, and it
148/// creates a new way to fail: the cited assertion can be deleted. `auto_update`
149/// and `auto_install_extensions` read as off-topic inside a test named for Zed
150/// service isolation, so they are the first lines a tidy-up drops — and nothing
151/// would notice, because deleting an assertion turns a test green.
152///
153/// Matched with whitespace removed, so rustfmt rewrapping a long `assert_eq!`
154/// does not read as somebody deleting it.
155pub const PINNED_SERVICE_ISOLATION_ASSERTIONS: &[(&str, &str)] = &[
156    (
157        "OMEGA-DELTA-0026",
158        "assert_eq!(settings[\"server_url\"], \"https://services.openagents.invalid\");",
159    ),
160    (
161        "OMEGA-DELTA-0026",
162        "assert_eq!(settings[\"auto_update\"], false);",
163    ),
164    (
165        "OMEGA-DELTA-0026",
166        "assert_eq!(settings[\"edit_predictions\"][\"provider\"], \"none\");",
167    ),
168    (
169        "OMEGA-DELTA-0026",
170        "assert_eq!(settings[\"auto_install_extensions\"], serde_json::json!({}));",
171    ),
172    (
173        "OMEGA-DELTA-0027",
174        "assert_eq!(settings[\"agent_servers\"][\"codex-acp\"][\"type\"], \"registry\");",
175    ),
176];
177
178/// OMEGA-DELTA-0016. Every shipped settings file that names a theme.
179///
180/// `default.json` is the base settings layer. `initial_user_settings.json` is
181/// the template copied verbatim into a new user's own settings file on first
182/// start, where it becomes a user-layer value that overrides the base layer for
183/// good — so a revert there survives being corrected in `default.json` later,
184/// and is the more durable of the two.
185pub const SHIPPED_THEME_SETTINGS_FILES: &[&str] = &[
186    DEFAULT_SETTINGS_PATH,
187    "assets/settings/initial_user_settings.json",
188];
189
190/// OMEGA-DELTA-0028. The file that declares the built-in icon theme's name.
191///
192/// The shipped `icon_theme` setting has to name the same theme, or the lookup
193/// in `configured_icon_theme` misses and falls back with a logged error.
194pub const DEFAULT_ICON_THEME_SOURCE: &str = "crates/theme/src/icon_theme.rs";
195
196/// OMEGA-DELTA-0021. The file that holds the executor-disclosure record.
197pub const EXECUTOR_DISCLOSURE_RECORD_PATH: &str = "crates/omega_front_door/src/omega_front_door.rs";
198
199/// OMEGA-DELTA-0021. The file that binds the record to a live thread.
200pub const EXECUTOR_DISCLOSURE_BINDING_PATH: &str =
201    "crates/agent_ui/src/omega_executor_disclosure.rs";
202
203/// OMEGA-DELTA-0021. The thread surface that has to render the line.
204pub const THREAD_VIEW_PATH: &str = "crates/agent_ui/src/conversation_view/thread_view.rs";
205
206/// OMEGA-DELTA-0045. The host method the engine calls to disclose a handoff.
207pub const HOST_BRIDGE_PATH: &str = "crates/agent_ui/src/omega_host_bridge.rs";
208
209/// OMEGA-DELTA-0045. The shared thread crate that carries the entry kinds.
210pub const THREAD_ENTRY_PATH: &str = "crates/acp_thread/src/acp_thread.rs";
211
212/// OMEGA-DELTA-0045. The refusal that shipped in every candidate through
213/// `0.2.0-rc17`.
214///
215/// Named as a literal so the check fails on the exact bytes an independent
216/// reviewer found in the shipped binary, rather than on a paraphrase. The
217/// prose in `omega_host_bridge.rs` still quotes it in order to say why it is
218/// gone, so the scan reads `code_of` and not the raw file.
219pub const SYSTEM_NOTE_REFUSAL: &str =
220    "Agent threads do not expose an owner-visible system-note authority.";
221
222/// OMEGA-DELTA-0046. The native Metal proof for the Exo workspace.
223pub const VISUAL_TEST_RUNNER_PATH: &str = "crates/zed/src/visual_test_runner.rs";
224
225/// OMEGA-DELTA-0030. The typed start command sent to `omega-effectd`.
226pub const FULL_AUTO_DISPATCH_PATH: &str = "crates/full_auto_ui/src/dispatch.rs";
227
228/// OMEGA-DELTA-0030. The thread's projection of its linked engine run.
229pub const THREAD_RUN_LINK_PATH: &str = "crates/full_auto_ui/src/thread_run_link.rs";
230
231/// OMEGA-DELTA-0030. Every field a start request is allowed to carry.
232///
233/// A closed list for the same reason as `EXECUTOR_DISCLOSURE_FIELDS`: the
234/// property that matters is "these parts and nothing else". A start request
235/// that could name an `evidence` block, a `decision_ref`, or an
236/// `authority_receipt_ref` would let a requester forge the very records the
237/// host mints at the completion-admission gate, and omega#47 watched a live
238/// engine ignore exactly that forgery. Here it cannot be written at all.
239pub const FULL_AUTO_DISPATCH_FIELDS: &[(&str, &str)] = &[
240    ("origin", "LaunchOrigin"),
241    ("workspace_ref", "PublicRef"),
242    ("project_ref", "PublicRef"),
243    ("worktree_ref", "PublicRef"),
244    ("lane", "String"),
245    ("title", "String"),
246    ("objective", "String"),
247    ("done_condition", "String"),
248    ("turn_cap", "u32"),
249];
250
251/// OMEGA-DELTA-0030. Crates allowed to name the Full Auto start command.
252///
253/// A dispatch is reachable only from the Full Auto surface and the panel that
254/// hosts it. A tool crate, a language-model crate, or a context-server crate
255/// appearing here would mean a model-authored path can reach run authority,
256/// which owner gate 8 forbids.
257///
258/// `omega_deltas` is listed because this file names the symbol in order to
259/// check for it. It declares no dependency on `full_auto_ui`, so naming the
260/// type here cannot build one.
261pub const FULL_AUTO_DISPATCH_CALLERS: &[&str] = &["full_auto_ui", "omega_deltas"];
262
263/// OMEGA-DELTA-0021. Every field the disclosure record is allowed to hold.
264///
265/// A closed list, not a forbidden-substring scan. The owner's condition on
266/// omega#74 is that disclosure is *a record a label renders*, so the check that
267/// matters is "these parts and nothing else" — a `line`, `text`, `summary` or
268/// `display` field would be a rendered label under a name no denylist thought
269/// of. Adding a genuine new part is a one-line edit here, and that edit is the
270/// record that somebody decided it was a part rather than a caption.
271pub const EXECUTOR_DISCLOSURE_FIELDS: &[(&str, &str)] = &[
272    ("class", "ExecutorClass"),
273    ("agent_id", "String"),
274    ("provider", "Option<String>"),
275    ("model", "Option<String>"),
276    ("run_ref", "Option<String>"),
277    // OMEGA-DELTA-0029. Why the router sent the thread here. A typed reason
278    // from a closed set, not a sentence: the same law as every other part.
279    ("route", "Option<RouteReason>"),
280];
281
282/// OMEGA-DELTA-0029. The routing law.
283pub const ROUTE_DECISION_PATH: &str = "crates/omega_front_door/src/router.rs";
284
285/// OMEGA-DELTA-0029. The dispatch half of the router.
286pub const ROUTER_DISPATCH_PATH: &str = "crates/agent_ui/src/omega_router.rs";
287
288/// OMEGA-DELTA-0034. The panel that owns the front door.
289pub const AGENT_PANEL_PATH: &str = "crates/agent_ui/src/agent_panel.rs";
290
291/// OMEGA-DELTA-0034. Front-door entry points that must work with no project.
292///
293/// Each of these stood between a fresh install and a composer. The check is on
294/// the *function body*, not the file, because a `has_open_project` line
295/// elsewhere in a six-thousand-line panel is fine and one of these is not.
296pub const PROJECT_OPTIONAL_FRONT_DOOR_FNS: &[&str] = &[
297    "activate_new_thread",
298    "activate_draft",
299    "new_thread",
300    "ensure_native_agent_connection",
301    "toggle_new_thread_menu",
302];
303
304/// OMEGA-DELTA-0034. Paths that must keep requiring a project.
305///
306/// Removing the guard from these would not be project-optional threads; it
307/// would be threads that fail later and less legibly. Asserted in the opposite
308/// direction from `PROJECT_OPTIONAL_FRONT_DOOR_FNS` so a blanket deletion of
309/// every guard fails as loudly as restoring one.
310pub const PROJECT_REQUIRED_FNS: &[&str] = &[
311    "restore_new_draft",
312    "new_external_agent_thread",
313    "refresh_skills",
314    "load_thread_from_clipboard",
315    "initialize_from_source_workspace_if_needed",
316    // Not `should_create_terminal_for_new_entry`: it asks `supports_terminal`,
317    // which is where the requirement lives. `project.supports_terminal` is
318    // `true` for any local project, worktree or not, so the check has to be on
319    // the panel's wrapper.
320    "supports_terminal",
321];
322
323/// OMEGA-DELTA-0035. Where the native agent entry is built.
324pub const AGENT_SERVER_FACTORY_PATH: &str = "crates/agent_ui/src/agent_ui.rs";
325
326/// OMEGA-DELTA-0035. The pin-setting methods that must name a human gesture.
327pub const PIN_SETTING_CALLS: &[&str] = &["pin_session(", "unpin_session(", "pin_next_session("];
328
329/// OMEGA-DELTA-0013. The chord that opens a new agent thread, per platform.
330///
331/// omega#76's exit is that this chord reaches the New Agent Thread surface from
332/// the editor, the welcome surface and the panel. All three live inside
333/// `Workspace`, so the property is "bound window-globally and not shadowed by
334/// anything narrower", which is what `the_new_thread_chord_is_window_global`
335/// checks.
336pub const NEW_THREAD_CHORDS: &[(&str, &str)] = &[
337    ("assets/keymaps/default-macos.json", "cmd-shift-a"),
338    ("assets/keymaps/default-linux.json", "ctrl-shift-a"),
339    ("assets/keymaps/default-windows.json", "ctrl-shift-a"),
340];
341
342/// OMEGA-DELTA-0013. The narrower surfaces admitted to take the chord back.
343///
344/// An allowlist and not a count. omega#76 asked for the shadowed lower-priority
345/// bindings to be *resolved deliberately*, and the deliberate resolution is
346/// that a modal the user opened on purpose, and a terminal whose select-all is
347/// a decades-old convention, may keep the chord while they have focus — but
348/// nothing else may take it, and an `Editor` or `AgentPanel` binding appearing
349/// here would put the chord back to being focus-dependent everywhere.
350pub const NEW_THREAD_CHORD_NARROW_CONTEXTS: &[&str] = &[
351    "ToolchainSelector",
352    "RecentProjects || (RecentProjects > Picker > Editor)",
353    "Terminal",
354];
355
356/// OMEGA-DELTA-0041. The crate that owns the served ACP socket.
357pub const ACP_SERVER_PATH: &str = "crates/omega_acp_server/src/omega_acp_server.rs";
358
359/// OMEGA-DELTA-0041. That crate's manifest, which must not reach GPUI.
360pub const ACP_SERVER_MANIFEST_PATH: &str = "crates/omega_acp_server/Cargo.toml";
361
362/// OMEGA-DELTA-0041. The supervisor layer that owns the listener's lifecycle.
363pub const EFFECTD_PATH: &str = "crates/omega_effectd/src/omega_effectd.rs";
364
365/// OMEGA-DELTA-0041. Where the first-party agent identity is declared.
366pub const NATIVE_AGENT_IDENTITY_PATH: &str = "crates/agent/src/agent.rs";
367
368/// OMEGA-DELTA-0040. The startup path that opens Omega's first window.
369pub const STARTUP_PATH: &str = "crates/zed/src/main.rs";
370
371/// OMEGA-DELTA-0040. First-run onboarding, which that startup path waits on.
372pub const ONBOARDING_PATH: &str = "crates/onboarding/src/onboarding.rs";
373
374/// OMEGA-DELTA-0040. The coordinator that releases the startup path.
375pub const IDENTITY_STARTUP_PATH: &str = "crates/onboarding/src/identity_startup.rs";
376
377/// OMEGA-DELTA-0029. Vocabulary that would make a route irreproducible.
378///
379/// The packet's exit is a *deterministic* router, and determinism is not a
380/// property a unit test can establish on its own: a test can only show that the
381/// inputs it happened to try gave the same answer twice. This scan covers the
382/// ways the answer could stop depending only on its inputs at all, so a later
383/// edit that reaches for a clock or a hash map fails here rather than making
384/// two identical threads route differently in a way nobody reproduces.
385pub const NON_DETERMINISTIC_ROUTING_TOKENS: &[(&str, &str)] = &[
386    ("a clock", "SystemTime"),
387    ("a clock", "Instant"),
388    ("a clock", "::now("),
389    ("a clock", "chrono"),
390    ("a clock", "timestamp"),
391    ("randomness", "rand::"),
392    ("hash iteration order", "HashMap"),
393    ("hash iteration order", "HashSet"),
394    ("the environment", "std::env"),
395];
396
397/// OMEGA-DELTA-0029. Vocabulary that would mean the router started executing.
398///
399/// omega#74 admitted Omega Agent as a router that owns routing, disclosure and
400/// receipts and owns **no execution**. "Owns no execution" is a property of the
401/// source, not of its author's intent, so it is read off the source. The last
402/// four entries are owner gate 8: the router must not be able to start, stop,
403/// or resume run authority, because only an explicit human action may.
404pub const ROUTER_EXECUTION_TOKENS: &[&str] = &[
405    "LanguageModel",
406    "stream_completion",
407    "system_prompt",
408    "run_turn",
409    "start_run",
410    "stop_run",
411    "resume_run",
412    "LaunchOrigin",
413];
414
415/// OMEGA-DELTA-0029. Methods of the router's `AgentConnection` impl that are
416/// allowed not to delegate, and why.
417///
418/// `into_any` is the trait's own downcast escape hatch: it hands back the
419/// router itself by definition, so requiring it to delegate would require it to
420/// lie about what it is.
421pub const ROUTER_NON_DELEGATING_METHODS: &[&str] = &["into_any"];
422
423/// OMEGA-DELTA-0029. How a router method is allowed to reach an executor.
424pub const ROUTER_DELEGATION_MARKERS: &[&str] = &[
425    "self.native",
426    "self.executor(",
427    "self.executor_for(",
428    "self.agent_id",
429    "executor.new_session",
430];
431
432/// Files deleted from the fork, checked by absence.
433///
434/// A deletion is the easiest kind of delta for a rebase to undo, because the
435/// file simply reappears and nothing else references it yet.
436pub const REMOVED_FILES: &[&str] = &[
437    // OMEGA-DELTA-0005
438    "crates/ai_onboarding/src/plan_definitions.rs",
439    "crates/ai_onboarding/src/young_account_banner.rs",
440    "crates/agent_ui/src/ui/end_trial_upsell.rs",
441    // OMEGA-DELTA-0006
442    "crates/extensions_ui/src/extension_suggest.rs",
443    "crates/recent_projects/src/dev_container_suggest.rs",
444    "crates/zed/src/zed/move_to_applications.rs",
445    // OMEGA-DELTA-0009
446    "crates/workspace/src/security_modal.rs",
447    // OMEGA-DELTA-0012
448    "crates/collab_ui/src/collab_panel.rs",
449    "crates/collab/Cargo.toml",
450];
451
452/// Strings that must not appear anywhere under `crates/`.
453///
454/// These are checked across the whole source tree rather than in one file,
455/// because the last two both survived a source-level review and were caught
456/// only by scanning the packaged binary.
457/// Action namespaces whose crates Omega deleted.
458///
459/// A keybinding naming one of these is not a cosmetic leftover: the built-in
460/// keymap is loaded and unwrapped at startup, so an unresolvable action is a
461/// hard panic before any window opens. `cargo check --workspace` passes
462/// happily, because keymaps are runtime assets rather than compiled code.
463/// This was shipped once, in 0.2.0-rc6.
464pub const FORBIDDEN_KEYMAP_NAMESPACES: &[(&str, &str)] = &[
465    ("OMEGA-DELTA-0012", "collab_panel::"),
466    ("OMEGA-DELTA-0012", "channel_modal::"),
467];
468
469/// A keybinding Omega adds, checked by presence, scope, and resolvability.
470///
471/// The mirror image of `FORBIDDEN_KEYMAP_NAMESPACES`: that table catches
472/// bindings whose action was deleted, this one catches an added binding being
473/// dropped, rescoped, or pointed at an action that no longer exists.
474pub struct RequiredKeymapBinding {
475    /// Delta this binding belongs to.
476    pub delta: &'static str,
477    /// Keymap asset the binding must appear in.
478    pub keymap: &'static str,
479    /// Keystroke, exactly as written in the keymap.
480    pub keystroke: &'static str,
481    /// Fully qualified action name the keystroke must dispatch.
482    pub action: &'static str,
483    /// Source file whose `actions!` declaration must still define `action`.
484    ///
485    /// A keymap naming an undeclared action is a hard panic at startup, not a
486    /// compile error, so the binding is resolved back to its declaration here.
487    pub declared_in: &'static str,
488}
489
490/// Contexts that match from anywhere inside a window.
491///
492/// `Workspace` is the root context of the window tree, so a binding declared
493/// there fires from an editor, a terminal, or any panel — the same scope
494/// `workspace::Save` and `agent::NewThread` use. A section with no context at
495/// all is equally global and is also accepted. Anything narrower (`Editor`,
496/// `Terminal`, `Pane`) would make the binding depend on focus, which is what
497/// `REQUIRED_KEYMAP_BINDINGS` exists to forbid.
498pub const WINDOW_GLOBAL_KEYMAP_CONTEXTS: &[&str] = &["Workspace"];
499
500/// OMEGA-DELTA-0015. Opening the Sarah workroom must not depend on focus, so
501/// each of these is asserted to live in a window-global section.
502///
503/// Each of these chords was `workspace::SaveAs` upstream. Taking them is a
504/// real trade, and `SAVE_AS_MENU_ITEM` holds the mitigation in place.
505pub const REQUIRED_KEYMAP_BINDINGS: &[RequiredKeymapBinding] = &[
506    RequiredKeymapBinding {
507        delta: "OMEGA-DELTA-0015",
508        keymap: "assets/keymaps/default-macos.json",
509        keystroke: "cmd-shift-s",
510        action: "workroom::OpenPanel",
511        declared_in: "crates/zed_actions/src/lib.rs",
512    },
513    // OMEGA-DELTA-0034. `cmd-?` is macOS's reserved Help chord, so the agent
514    // panel's toggle was bound to a keystroke Omega cannot win. Checked here
515    // rather than only moved, because a rebase that restores upstream's
516    // `cmd-?` line would otherwise be invisible.
517    RequiredKeymapBinding {
518        delta: "OMEGA-DELTA-0034",
519        keymap: "assets/keymaps/default-macos.json",
520        keystroke: "ctrl-cmd-a",
521        action: "agent::ToggleFocus",
522        declared_in: "crates/zed_actions/src/lib.rs",
523    },
524    RequiredKeymapBinding {
525        delta: "OMEGA-DELTA-0015",
526        keymap: "assets/keymaps/default-linux.json",
527        keystroke: "ctrl-shift-s",
528        action: "workroom::OpenPanel",
529        declared_in: "crates/zed_actions/src/lib.rs",
530    },
531    RequiredKeymapBinding {
532        delta: "OMEGA-DELTA-0015",
533        keymap: "assets/keymaps/default-windows.json",
534        keystroke: "ctrl-shift-s",
535        action: "workroom::OpenPanel",
536        declared_in: "crates/zed_actions/src/lib.rs",
537    },
538];
539
540/// OMEGA-DELTA-0015. Where Save As went when the workroom took its chord.
541///
542/// `cmd-shift-s` / `ctrl-shift-s` was `workspace::SaveAs` in all three default
543/// keymaps, so macOS and Windows now have no Save As keystroke at all and
544/// Linux keeps only the `shift-save` media key. The File menu is the whole
545/// mitigation. If it goes, Save As is reachable only by knowing its command
546/// name, and this delta is recording a fallback that no longer exists.
547pub const SAVE_AS_MENU_ITEM: (&str, &str) = (
548    "crates/zed/src/zed/app_menus.rs",
549    "MenuItem::action(\"Save As…\", workspace::SaveAs)",
550);
551
552pub const FORBIDDEN_SOURCE_STRINGS: &[(&str, &str)] = &[
553    ("OMEGA-DELTA-0008", "Zed\u{27}s hosted models"),
554    ("OMEGA-DELTA-0008", "14 day free trial"),
555    ("OMEGA-DELTA-0009", "Review .zed/settings.json"),
556];
557
558/// Restricted Mode UI and key bindings removed by OMEGA-DELTA-0009.
559pub const FORBIDDEN_RESTRICTED_MODE_UI: &[(&str, &str)] = &[
560    ("crates/agent_ui/src/profile_selector.rs", "Restricted Mode"),
561    ("crates/language_tools/src/lsp_button.rs", "Restricted Mode"),
562    (
563        "crates/workspace/src/workspace.rs",
564        "ToggleWorktreeSecurity",
565    ),
566    (
567        "assets/keymaps/default-linux.json",
568        "workspace::ToggleWorktreeSecurity",
569    ),
570    (
571        "assets/keymaps/default-macos.json",
572        "workspace::ToggleWorktreeSecurity",
573    ),
574    (
575        "assets/keymaps/default-windows.json",
576        "workspace::ToggleWorktreeSecurity",
577    ),
578];
579
580/// Read a repository file relative to the workspace root.
581///
582/// `CARGO_MANIFEST_DIR` is `crates/omega_deltas`, so the root is two levels up.
583/// Resolving it this way keeps the checks runnable from any working directory.
584#[must_use]
585pub fn repository_path(relative: &str) -> std::path::PathBuf {
586    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
587        .join("../..")
588        .join(relative)
589}
590
591/// Parse the shipped default settings, which are JSONC: `//` comments and
592/// trailing commas, neither of which `serde_json` accepts.
593///
594/// The normalizer is string-aware on purpose. A naive strip would corrupt any
595/// setting whose value legitimately contains `//` (a URL) or a comma before a
596/// brace, and would do it silently — producing a parse that succeeds with the
597/// wrong values, which is worse than failing.
598///
599/// # Errors
600///
601/// Returns an error when the file cannot be read or does not parse.
602pub fn default_settings() -> Result<serde_json::Value, String> {
603    let path = repository_path(DEFAULT_SETTINGS_PATH);
604    let raw = std::fs::read_to_string(&path)
605        .map_err(|error| format!("cannot read {}: {error}", path.display()))?;
606    serde_json::from_str(&strip_jsonc(&raw))
607        .map_err(|error| format!("cannot parse {}: {error}", path.display()))
608}
609
610/// Remove `//` comments and trailing commas without touching string contents.
611///
612/// Two passes, because a trailing comma may be separated from its closing
613/// brace by a comment. Removing comments first makes the comma visible.
614#[must_use]
615pub fn strip_jsonc(source: &str) -> String {
616    strip_trailing_commas(&strip_line_comments(source))
617}
618
619/// Scan `source`, applying `visit` to each character outside a string literal.
620///
621/// Shared so both passes agree on what "inside a string" means; two separate
622/// scanners would be two chances to disagree.
623fn scan_outside_strings(
624    source: &str,
625    mut visit: impl FnMut(&[char], usize, &mut String) -> usize,
626) -> String {
627    let characters: Vec<char> = source.chars().collect();
628    let mut output = String::with_capacity(source.len());
629    let mut index = 0;
630    let mut in_string = false;
631
632    while index < characters.len() {
633        let character = characters[index];
634        if in_string {
635            output.push(character);
636            if character == '\\' && index + 1 < characters.len() {
637                output.push(characters[index + 1]);
638                index += 2;
639                continue;
640            }
641            if character == '"' {
642                in_string = false;
643            }
644            index += 1;
645            continue;
646        }
647        if character == '"' {
648            in_string = true;
649            output.push(character);
650            index += 1;
651            continue;
652        }
653        index = visit(&characters, index, &mut output);
654    }
655    output
656}
657
658fn strip_line_comments(source: &str) -> String {
659    scan_outside_strings(source, |characters, index, output| {
660        if characters[index] == '/' && characters.get(index + 1) == Some(&'/') {
661            let mut cursor = index;
662            while cursor < characters.len() && characters[cursor] != '\n' {
663                cursor += 1;
664            }
665            return cursor;
666        }
667        output.push(characters[index]);
668        index + 1
669    })
670}
671
672fn strip_trailing_commas(source: &str) -> String {
673    scan_outside_strings(source, |characters, index, output| {
674        if characters[index] == ',' {
675            let mut lookahead = index + 1;
676            while lookahead < characters.len() && characters[lookahead].is_whitespace() {
677                lookahead += 1;
678            }
679            if matches!(characters.get(lookahead), Some('}') | Some(']')) {
680                return index + 1;
681            }
682        }
683        output.push(characters[index]);
684        index + 1
685    })
686}
687
688/// Look up a dotted path in the default settings.
689#[must_use]
690pub fn default_setting<'a>(
691    settings: &'a serde_json::Value,
692    dotted: &str,
693) -> Option<&'a serde_json::Value> {
694    let mut cursor = settings;
695    for segment in dotted.split('.') {
696        cursor = cursor.get(segment)?;
697    }
698    Some(cursor)
699}
700
701/// Every action declared by an `actions!(namespace, [..])` macro in `source`,
702/// as fully qualified `namespace::Name` strings.
703///
704/// Textual rather than compiled on purpose: `omega_deltas` deliberately
705/// depends on nothing but `serde_json`, so that a check cannot be made to pass
706/// by a change to the crate it is checking. Doc comments are stripped before
707/// parsing, because a comma inside one would otherwise split an entry.
708#[must_use]
709pub fn declared_actions(source: &str) -> std::collections::BTreeSet<String> {
710    let stripped: String = source
711        .lines()
712        // Attribute lines are dropped as well as comments. An `#[action(...)]`
713        // attribute may carry a bracketed list — `deprecated_aliases = [..]` —
714        // and the `]` that closes it would otherwise end the `actions!` body
715        // early, hiding every action declared after it. `agent::ToggleFocus` was
716        // exactly that: declared, and invisible to this parser.
717        .filter(|line| {
718            let line = line.trim_start();
719            !line.starts_with("//") && !line.starts_with("#[")
720        })
721        .collect::<Vec<_>>()
722        .join("\n");
723
724    let mut declared = std::collections::BTreeSet::new();
725    let mut rest = stripped.as_str();
726    while let Some(start) = rest.find("actions!(") {
727        rest = &rest[start + "actions!(".len()..];
728        let Some(close) = rest.find(']') else {
729            break;
730        };
731        let (body, remainder) = rest.split_at(close);
732        rest = remainder;
733        let Some((namespace, names)) = body.split_once('[') else {
734            continue;
735        };
736        let namespace = namespace.trim().trim_end_matches(',').trim();
737        if namespace.is_empty() {
738            continue;
739        }
740        for name in names.split(',').map(str::trim) {
741            // Guard against a stray fragment being read as an action name.
742            let is_identifier = name.starts_with(char::is_uppercase)
743                && name.chars().all(|c| c.is_alphanumeric() || c == '_');
744            if is_identifier {
745                declared.insert(format!("{namespace}::{name}"));
746            }
747        }
748    }
749    declared
750}
751
752/// Every theme name declared by the shipped theme families under
753/// `assets/themes/`.
754///
755/// # Errors
756///
757/// Returns an error when a shipped theme file cannot be read or parsed. A
758/// silent skip would make the default-theme check vacuous.
759pub fn shipped_theme_names() -> Result<std::collections::BTreeSet<String>, String> {
760    let root = repository_path("assets/themes");
761    let families = std::fs::read_dir(&root)
762        .map_err(|error| format!("cannot read {}: {error}", root.display()))?;
763    let mut names = std::collections::BTreeSet::new();
764    for family in families.flatten() {
765        let Ok(entries) = std::fs::read_dir(family.path()) else {
766            continue;
767        };
768        for entry in entries.flatten() {
769            let path = entry.path();
770            if path.extension().is_none_or(|extension| extension != "json") {
771                continue;
772            }
773            let raw = std::fs::read_to_string(&path)
774                .map_err(|error| format!("cannot read {}: {error}", path.display()))?;
775            let value: serde_json::Value = serde_json::from_str(&strip_jsonc(&raw))
776                .map_err(|error| format!("cannot parse {}: {error}", path.display()))?;
777            let themes = value
778                .get("themes")
779                .and_then(serde_json::Value::as_array)
780                .ok_or_else(|| format!("{} has no themes array", path.display()))?;
781            for theme in themes {
782                let name = theme
783                    .get("name")
784                    .and_then(serde_json::Value::as_str)
785                    .ok_or_else(|| format!("{} has an unnamed theme", path.display()))?;
786                names.insert(name.to_owned());
787            }
788        }
789    }
790    Ok(names)
791}
792
793/// Shared brand-gate policy.
794///
795/// OMEGA-DELTA-0017 and OMEGA-DELTA-0018. The same file is read by the tests
796/// here, which check the source tree, and by `script/verify-omega-brand`,
797/// which checks the packaged application. One file so the two sides cannot
798/// come to disagree about what counts as a competitor's name.
799pub const BRAND_GATE_POLICY_PATH: &str = "script/omega-brand-gate.json";
800
801/// The packaged-side brand gate.
802pub const BRAND_VERIFIER_PATH: &str = "script/verify-omega-brand";
803
804/// The RC packaging entry point the brand gate has to be wired into.
805pub const RC_BUNDLE_SCRIPT_PATH: &str = "script/bundle-omega-rc";
806
807/// Parse the shared brand-gate policy.
808///
809/// # Errors
810/// If the policy file is unreadable or is not valid JSON.
811pub fn brand_policy() -> Result<serde_json::Value, String> {
812    let path = repository_path(BRAND_GATE_POLICY_PATH);
813    let raw = std::fs::read_to_string(&path)
814        .map_err(|error| format!("cannot read {}: {error}", path.display()))?;
815    serde_json::from_str(&raw).map_err(|error| format!("cannot parse {}: {error}", path.display()))
816}
817
818fn policy_strings(policy: &serde_json::Value, first: &str, second: &str) -> Vec<String> {
819    policy
820        .get(first)
821        .and_then(|value| value.get(second))
822        .and_then(serde_json::Value::as_array)
823        .map(|values| {
824            values
825                .iter()
826                .filter_map(serde_json::Value::as_str)
827                .map(str::to_owned)
828                .collect()
829        })
830        .unwrap_or_default()
831}
832
833/// Competitor brand names appearing in `text`.
834///
835/// `brand.words` match case-sensitively at ASCII alphanumeric boundaries, so
836/// `Zed` and `Zed's` match while `Zedd` does not. Lowercase `zed` is
837/// deliberately not a word: it is a substring of `authorized`, `organized` and
838/// `normalized`, and a gate that cries wolf gets deleted rather than fixed.
839/// `brand.substrings` match case-insensitively.
840#[must_use]
841pub fn brand_hits(text: &str, policy: &serde_json::Value) -> Vec<String> {
842    let mut hits = Vec::new();
843    for word in policy_strings(policy, "brand", "words") {
844        if text.match_indices(&word).any(|(at, _)| {
845            let before = text[..at].chars().next_back();
846            let after = text[at + word.len()..].chars().next();
847            !before.is_some_and(|character| character.is_ascii_alphanumeric())
848                && !after.is_some_and(|character| character.is_ascii_alphanumeric())
849        }) {
850            hits.push(word);
851        }
852    }
853    let lowered = text.to_lowercase();
854    for substring in policy_strings(policy, "brand", "substrings") {
855        if lowered.contains(&substring.to_lowercase()) {
856            hits.push(substring);
857        }
858    }
859    hits
860}
861
862/// Every `<string>` in an `Info.plist` fragment, paired with the `<key>` that
863/// most recently preceded it.
864///
865/// Values, not a list of known keys: a brand-new key carrying a competitor's
866/// name has to fail the same as `NSMicrophoneUsageDescription` does.
867#[must_use]
868pub fn plist_fragment_values(source: &str) -> Vec<(String, String)> {
869    let mut values = Vec::new();
870    let mut key = "<unkeyed>".to_owned();
871    let mut rest = source;
872    loop {
873        let next_key = next_element(rest, "key");
874        let next_string = next_element(rest, "string");
875        match (next_key, next_string) {
876            (Some((_, content, after)), None) => {
877                key = content.trim().to_owned();
878                rest = &rest[after..];
879            }
880            (None, Some((_, content, after))) => {
881                values.push((key.clone(), content.to_owned()));
882                rest = &rest[after..];
883            }
884            (
885                Some((key_at, key_content, key_after)),
886                Some((string_at, string_content, string_after)),
887            ) => {
888                if key_at < string_at {
889                    key = key_content.trim().to_owned();
890                    rest = &rest[key_after..];
891                } else {
892                    values.push((key.clone(), string_content.to_owned()));
893                    rest = &rest[string_after..];
894                }
895            }
896            (None, None) => break,
897        }
898    }
899    values
900}
901
902/// `(start of the opening tag, content, offset just past the closing tag)`.
903fn next_element<'a>(source: &'a str, tag: &str) -> Option<(usize, &'a str, usize)> {
904    let open = format!("<{tag}>");
905    let close = format!("</{tag}>");
906    let start = source.find(&open)?;
907    let content_start = start + open.len();
908    let end = source[content_start..].find(&close)? + content_start;
909    Some((start, &source[content_start..end], end + close.len()))
910}
911
912/// `source` with every whitespace character removed.
913///
914/// Used to match a pinned assertion against a source file without asserting
915/// rustfmt's current line wrapping, which is not the thing being protected.
916#[must_use]
917pub fn without_whitespace(source: &str) -> String {
918    source
919        .chars()
920        .filter(|character| !character.is_whitespace())
921        .collect()
922}
923
924/// `source` with every `<tag>…</tag>` block removed.
925#[must_use]
926pub fn without_elements(source: &str, tag: &str) -> String {
927    let mut remaining = source;
928    let mut out = String::new();
929    while let Some((start, _, after)) = next_element(remaining, tag) {
930        out.push_str(&remaining[..start]);
931        remaining = &remaining[after..];
932    }
933    out.push_str(remaining);
934    out
935}
936
937/// Lowercase hex SHA-256 of `bytes`, the form the pins are written in.
938#[must_use]
939pub fn sha256_hex(bytes: &[u8]) -> String {
940    use sha2::Digest as _;
941    let mut hasher = sha2::Sha256::new();
942    hasher.update(bytes);
943    hasher
944        .finalize()
945        .iter()
946        .map(|byte| format!("{byte:02x}"))
947        .collect()
948}
949
950/// `OmegaAgentTwo` -> `omega_agent_two`, the mapping `IconName::path` uses.
951#[must_use]
952pub fn icon_stem(variant: &str) -> String {
953    let mut stem = String::new();
954    for (index, character) in variant.char_indices() {
955        if character.is_ascii_uppercase() && index != 0 {
956            stem.push('_');
957        }
958        stem.push(character.to_ascii_lowercase());
959    }
960    stem
961}
962
963/// Every variant of the `IconName` enum, in declaration order.
964#[must_use]
965pub fn icon_name_variants(source: &str) -> Vec<String> {
966    let Some((_, body, _)) = next_enum_body(source, "IconName") else {
967        return Vec::new();
968    };
969    body.lines()
970        .map(str::trim)
971        .filter(|line| !line.is_empty())
972        .map(|line| line.trim_end_matches(',').to_owned())
973        .filter(|name| {
974            name.chars()
975                .all(|character| character.is_ascii_alphanumeric())
976        })
977        .collect()
978}
979
980/// The declared fields of a `pub struct NAME { … }`, as `(name, type)`.
981///
982/// Doc comments, attributes and blank lines are skipped, so the result is the
983/// data the struct actually holds. Returns an empty vector if the struct is not
984/// found, which the callers assert against separately — a check that reads no
985/// fields must fail loudly rather than pass vacuously.
986#[must_use]
987pub fn struct_fields(source: &str, name: &str) -> Vec<(String, String)> {
988    let header = format!("pub struct {name} {{\n");
989    let Some(start) = source.find(&header) else {
990        return Vec::new();
991    };
992    let body_start = start + header.len();
993    let Some(end) = source[body_start..].find("\n}") else {
994        return Vec::new();
995    };
996    source[body_start..body_start + end]
997        .lines()
998        .map(str::trim)
999        .filter(|line| {
1000            !line.is_empty()
1001                && !line.starts_with("///")
1002                && !line.starts_with("//")
1003                && !line.starts_with("#[")
1004        })
1005        .filter_map(|line| {
1006            let line = line.trim_end_matches(',');
1007            let (field, type_name) = line.split_once(':')?;
1008            Some((
1009                field.trim_start_matches("pub ").trim().to_owned(),
1010                type_name.trim().to_owned(),
1011            ))
1012        })
1013        .collect()
1014}
1015
1016fn next_enum_body<'a>(source: &'a str, name: &str) -> Option<(usize, &'a str, usize)> {
1017    let header = format!("pub enum {name} {{\n");
1018    let start = source.find(&header)?;
1019    let body_start = start + header.len();
1020    let end = source[body_start..].find("\n}")? + body_start;
1021    Some((start, &source[body_start..end], end))
1022}
1023
1024/// A source file with its line comments removed.
1025///
1026/// OMEGA-DELTA-0029's scans read code, not prose: the doc comments in the
1027/// router deliberately name the tokens they forbid, in the course of saying why
1028/// they are not there. A scan that could not tell the two apart would force the
1029/// explanation out of the file, which is the opposite of what these checks are
1030/// for.
1031#[must_use]
1032pub fn code_of(source: &str) -> String {
1033    source
1034        .lines()
1035        .filter(|line| !line.trim_start().starts_with("//"))
1036        .collect::<Vec<_>>()
1037        .join("\n")
1038}
1039
1040/// Read the value of a `pub const NAME: &str = "value";` declaration.
1041#[must_use]
1042pub fn string_constant(source: &str, name: &str) -> Option<String> {
1043    source
1044        .lines()
1045        .find(|line| line.contains(&format!("const {name}:")))
1046        .and_then(|line| line.split_once('='))
1047        .and_then(|(_, value)| value.split('"').nth(1))
1048        .map(str::to_owned)
1049}
1050
1051/// Visit every file under `root` whose extension is in `extensions`.
1052///
1053/// Symlinks and `target` directories are skipped, and unreadable or non-UTF-8
1054/// files are ignored, matching the tree walk the Zed-copy check already uses.
1055pub fn for_each_source_file(
1056    root: &std::path::Path,
1057    extensions: &[&str],
1058    mut visit: impl FnMut(&std::path::Path, &str),
1059) {
1060    let mut stack = vec![root.to_path_buf()];
1061    while let Some(directory) = stack.pop() {
1062        let Ok(entries) = std::fs::read_dir(&directory) else {
1063            continue;
1064        };
1065        for entry in entries.flatten() {
1066            let path = entry.path();
1067            if path.is_symlink() {
1068                continue;
1069            }
1070            if path.is_dir() {
1071                if path.file_name().is_some_and(|name| name == "target") {
1072                    continue;
1073                }
1074                stack.push(path);
1075                continue;
1076            }
1077            let matches = path
1078                .extension()
1079                .and_then(std::ffi::OsStr::to_str)
1080                .is_some_and(|extension| extensions.contains(&extension));
1081            if !matches {
1082                continue;
1083            }
1084            let Ok(source) = std::fs::read_to_string(&path) else {
1085                continue;
1086            };
1087            visit(&path, &source);
1088        }
1089    }
1090}
1091
1092// ------------------------------------------------------------ OMEGA-DELTA-0022
1093
1094/// Every `#[folder = "…"]` in the repository, as (declaring file, folder).
1095///
1096/// `rust-embed` resolves the attribute against `CARGO_MANIFEST_DIR`, so the
1097/// base is the crate root rather than the directory the attribute is written
1098/// in. Deriving the embed roots instead of listing them is the whole point:
1099/// `assets/images/` was never in a list, and that is where the Zed artwork sat
1100/// while `OMEGA-DELTA-0018` reported `assets/icons/` clean.
1101#[must_use]
1102pub fn embed_folders() -> Vec<(String, std::path::PathBuf)> {
1103    let root = repository_path("crates");
1104    let mut found = Vec::new();
1105    for_each_source_file(&root, &["rs"], |path, source| {
1106        let mut folders = Vec::new();
1107        let mut rest = source;
1108        while let Some(at) = rest.find("#[folder") {
1109            rest = &rest[at..];
1110            let Some((_, after_equals)) = rest.split_once('=') else {
1111                break;
1112            };
1113            let Some(value) = after_equals.split('"').nth(1) else {
1114                break;
1115            };
1116            folders.push(value.to_owned());
1117            rest = &rest[1..];
1118        }
1119        if folders.is_empty() {
1120            return;
1121        }
1122        let crate_root = path
1123            .ancestors()
1124            .find(|ancestor| ancestor.join("Cargo.toml").is_file())
1125            .unwrap_or_else(|| path.parent().unwrap_or(path));
1126        for folder in folders {
1127            found.push((
1128                path.display().to_string(),
1129                normalize_path(&crate_root.join(folder)),
1130            ));
1131        }
1132    });
1133    found.sort();
1134    found
1135}
1136
1137/// Lexically resolve `.` and `..` without touching the filesystem.
1138fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
1139    let mut out = std::path::PathBuf::new();
1140    for component in path.components() {
1141        match component {
1142            std::path::Component::ParentDir => {
1143                out.pop();
1144            }
1145            std::path::Component::CurDir => {}
1146            other => out.push(other),
1147        }
1148    }
1149    out
1150}
1151
1152/// Every file `rust-embed` can ship, as a repository-relative path.
1153///
1154/// The assets tree plus every directory an embed declaration points at. A
1155/// subdirectory list would be a claim about the subdirectories somebody
1156/// remembered; this is the set the embed macros actually read.
1157#[must_use]
1158pub fn embedded_asset_inventory() -> Vec<String> {
1159    let repository = normalize_path(&repository_path("."));
1160    let mut roots = vec![normalize_path(&repository_path("assets"))];
1161    roots.extend(embed_folders().into_iter().map(|(_, folder)| folder));
1162    let mut files = std::collections::BTreeSet::new();
1163    for root in roots {
1164        let mut stack = vec![root];
1165        while let Some(directory) = stack.pop() {
1166            let Ok(entries) = std::fs::read_dir(&directory) else {
1167                continue;
1168            };
1169            for entry in entries.flatten() {
1170                let path = entry.path();
1171                if path.is_symlink() {
1172                    continue;
1173                }
1174                if path.is_dir() {
1175                    stack.push(path);
1176                    continue;
1177                }
1178                if path.file_name().is_some_and(|name| name == ".DS_Store") {
1179                    continue;
1180                }
1181                if let Ok(relative) = normalize_path(&path).strip_prefix(&repository) {
1182                    files.insert(relative.display().to_string());
1183                }
1184            }
1185        }
1186    }
1187    files.into_iter().collect()
1188}
1189
1190/// Every gpui action in the repository, as `(namespace, name, file)`.
1191///
1192/// There are exactly two ways to declare one — `actions!(namespace, [..])` and
1193/// `#[action(namespace = ..)]` on a derive — and both are read here, so this
1194/// is the complete set of `namespace: action name` labels the command palette
1195/// can display. Nothing had ever read an action declaration before
1196/// `0.2.0-rc11` offered `zed: about`, `zed: quit` and `zed: get merch`.
1197#[must_use]
1198pub fn action_declarations() -> Vec<(String, String, String)> {
1199    let root = repository_path("crates");
1200    let mut declarations = Vec::new();
1201    for_each_source_file(&root, &["rs"], |path, source| {
1202        let file = path.display().to_string();
1203        let mut rest = source;
1204        while let Some(at) = rest.find("actions!(") {
1205            let after = &rest[at + "actions!(".len()..];
1206            rest = after;
1207            let Some((namespace, body)) = actions_macro_body(after) else {
1208                continue;
1209            };
1210            for line in body.lines() {
1211                let name = line.trim().trim_end_matches(',');
1212                if is_action_variant(name) {
1213                    declarations.push((namespace.clone(), name.to_owned(), file.clone()));
1214                }
1215            }
1216        }
1217        for (namespace, name) in derived_actions(source) {
1218            declarations.push((namespace, name, file.clone()));
1219        }
1220    });
1221    declarations.sort();
1222    declarations
1223}
1224
1225/// `namespace` and the bracketed body of an `actions!(namespace, [ .. ])` call.
1226fn actions_macro_body(after_open: &str) -> Option<(String, &str)> {
1227    let (head, rest) = after_open.split_once(",")?;
1228    let namespace = head.trim().to_owned();
1229    if namespace.is_empty()
1230        || !namespace
1231            .chars()
1232            .all(|character| character.is_ascii_alphanumeric() || character == '_')
1233    {
1234        return None;
1235    }
1236    let open = rest.find('[')?;
1237    let mut depth = 1_usize;
1238    let bytes = rest.as_bytes();
1239    let mut index = open + 1;
1240    while index < bytes.len() && depth > 0 {
1241        match bytes[index] {
1242            b'[' => depth += 1,
1243            b']' => depth -= 1,
1244            _ => {}
1245        }
1246        index += 1;
1247    }
1248    Some((namespace, &rest[open + 1..index.saturating_sub(1)]))
1249}
1250
1251fn is_action_variant(name: &str) -> bool {
1252    !name.is_empty()
1253        && name.starts_with(|character: char| character.is_ascii_uppercase())
1254        && name
1255            .chars()
1256            .all(|character| character.is_ascii_alphanumeric())
1257}
1258
1259/// Actions declared with `#[action(namespace = ..)]` on a struct or enum.
1260fn derived_actions(source: &str) -> Vec<(String, String)> {
1261    let mut found = Vec::new();
1262    let mut rest = source;
1263    while let Some(at) = rest.find("#[action(") {
1264        let after = &rest[at + "#[action(".len()..];
1265        rest = &rest[at + 1..];
1266        let Some(close) = after.find(")]") else {
1267            continue;
1268        };
1269        let attribute = &after[..close];
1270        let Some(namespace) = attribute
1271            .split("namespace")
1272            .nth(1)
1273            .and_then(|tail| tail.trim_start().strip_prefix('='))
1274            .map(|tail| {
1275                tail.trim_start()
1276                    .chars()
1277                    .take_while(|character| character.is_ascii_alphanumeric() || *character == '_')
1278                    .collect::<String>()
1279            })
1280            .filter(|namespace| !namespace.is_empty())
1281        else {
1282            continue;
1283        };
1284        let tail = &after[close + 2..];
1285        let mut name = None;
1286        for keyword in ["pub struct ", "pub enum "] {
1287            if let Some(at) = tail.find(keyword) {
1288                // Only accept a declaration that follows immediately, allowing
1289                // for other attributes in between but not a whole other item.
1290                if tail[..at].contains("\n\n") {
1291                    continue;
1292                }
1293                let candidate: String = tail[at + keyword.len()..]
1294                    .chars()
1295                    .take_while(|character| character.is_ascii_alphanumeric() || *character == '_')
1296                    .collect();
1297                if !candidate.is_empty() && name.is_none() {
1298                    name = Some(candidate);
1299                }
1300            }
1301        }
1302        if let Some(name) = name {
1303            found.push((namespace, name));
1304        }
1305    }
1306    found
1307}
1308
1309/// Old action names kept resolvable for existing user keymaps.
1310///
1311/// A `deprecated_aliases` entry names the action Omega used to have. It is
1312/// never shown in the palette, so it is exempt from the label rules — and only
1313/// the strings actually inside such a list are.
1314#[must_use]
1315pub fn deprecated_action_aliases() -> std::collections::BTreeSet<String> {
1316    let root = repository_path("crates");
1317    let mut aliases = std::collections::BTreeSet::new();
1318    for_each_source_file(&root, &["rs"], |_path, source| {
1319        let mut rest = source;
1320        while let Some(at) = rest.find("deprecated_aliases") {
1321            let after = &rest[at..];
1322            rest = &rest[at + 1..];
1323            let Some(open) = after.find('[') else {
1324                continue;
1325            };
1326            let Some(close) = after[open..].find(']') else {
1327                continue;
1328            };
1329            let list = &after[open..open + close];
1330            for (index, part) in list.split('"').enumerate() {
1331                if index % 2 == 1 {
1332                    aliases.insert(part.to_owned());
1333                }
1334            }
1335        }
1336    });
1337    aliases
1338}
1339
1340/// Enums whose `impl` builds an embedded asset path, and their variants.
1341///
1342/// Discovered, not listed. `OMEGA-DELTA-0018` named `crates/icons/src/icons.rs`
1343/// in the policy file; `VectorName` in `crates/ui/src/components/image.rs` does
1344/// the identical job for `assets/images/` and was outside the gate, which is
1345/// how `VectorName::ZedLogo` and `VectorName::ZedXCopilot` survived
1346/// `0.2.0-rc11`.
1347#[must_use]
1348pub fn asset_name_enums() -> std::collections::BTreeMap<String, Vec<String>> {
1349    let directories: std::collections::BTreeSet<String> = embedded_asset_inventory()
1350        .iter()
1351        .filter_map(|relative| {
1352            let mut parts = relative.split('/');
1353            if parts.next()? != "assets" {
1354                return None;
1355            }
1356            let directory = parts.next()?;
1357            parts.next()?;
1358            Some(directory.to_owned())
1359        })
1360        .collect();
1361
1362    let root = repository_path("crates");
1363    let mut discovered = std::collections::BTreeMap::new();
1364    for_each_source_file(&root, &["rs"], |_path, source| {
1365        let names_an_asset = directories
1366            .iter()
1367            .any(|directory| source.contains(&format!("format!(\"{directory}/{{")));
1368        if !names_an_asset {
1369            return;
1370        }
1371        let mut rest = source;
1372        while let Some(at) = rest.find("pub enum ") {
1373            let after = &rest[at + "pub enum ".len()..];
1374            rest = &rest[at + 1..];
1375            let name: String = after
1376                .chars()
1377                .take_while(|character| character.is_ascii_alphanumeric() || *character == '_')
1378                .collect();
1379            if name.is_empty() {
1380                continue;
1381            }
1382            let Some((_, body, _)) = next_enum_body(source, &name) else {
1383                continue;
1384            };
1385            let variants: Vec<String> = body
1386                .lines()
1387                .map(str::trim)
1388                .map(|line| line.trim_end_matches(','))
1389                .filter(|line| is_action_variant(line))
1390                .map(str::to_owned)
1391                .collect();
1392            if !variants.is_empty() {
1393                discovered.insert(name, variants);
1394            }
1395        }
1396    });
1397    discovered
1398}
1399
1400/// Public product claims the compatibility allow-list records as `blocked`.
1401///
1402/// The allow-list is the reviewed record of every retained Zed identifier, and
1403/// `blocked` is its strongest disposition — but until `OMEGA-DELTA-0022`
1404/// nothing read those entries back against the tree, so `Welcome to Zed` was
1405/// listed while `Use GitHub Copilot in Zed` shipped in three places.
1406pub const COMPATIBILITY_ALLOWLIST_PATH: &str =
1407    "crates/app_identity/fixtures/compatibility_allowlist.json";
1408
1409/// Files whose job is to hold the forbidden strings.
1410///
1411/// A corpus file names a blocked claim on purpose, to assert it is absent
1412/// everywhere else. Exempting them by path is not a hole: each one is a test
1413/// or a policy record, and each is checked by name here so the list cannot
1414/// quietly grow to cover a real surface.
1415pub const BLOCKED_COPY_CORPUS: &[&str] = &[
1416    COMPATIBILITY_ALLOWLIST_PATH,
1417    "crates/app_identity/src/public_branding.rs",
1418    "crates/app_identity/src/shell_branding.rs",
1419    "crates/omega_deltas/src/omega_deltas.rs",
1420];
1421
1422// ------------------------------------------------------------ OMEGA-DELTA-0031
1423
1424/// One brand-bearing prose literal that can reach a user.
1425#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1426pub struct ProseLiteral {
1427    /// Which mechanism puts this text in front of a user.
1428    pub kind: &'static str,
1429    /// Repository-relative file it was read from.
1430    pub file: String,
1431    /// Line the literal starts on.
1432    pub line: usize,
1433    /// The literal, with runs of whitespace collapsed.
1434    pub text: String,
1435}
1436
1437/// What the prose scanners read, as opposed to what they found.
1438///
1439/// The anti-vacuity guard. A clean tree yields almost no brand-bearing prose
1440/// and so does a scanner that stopped parsing, and those two must not look the
1441/// same from the outside.
1442#[derive(Debug, Default, Clone, Copy)]
1443pub struct ProseReadCounts {
1444    /// Rust sources walked.
1445    pub rust_files: usize,
1446    /// Rust string literals lexed.
1447    pub literals: usize,
1448    /// Doc lines in files that really derive `JsonSchema`.
1449    pub schema_docs: usize,
1450    /// Doc lines inside an action declaration.
1451    pub action_docs: usize,
1452    /// Doc lines in files clap prints as `--help`.
1453    pub clap_docs: usize,
1454    /// Files in the embedded-asset inventory.
1455    pub embedded: usize,
1456}
1457
1458/// Collapse runs of whitespace so a literal has one spelling.
1459///
1460/// A multi-line literal is indented to wherever it happens to sit in the
1461/// source, and that indentation is not part of the sentence.
1462#[must_use]
1463pub fn normalize_prose(text: &str) -> String {
1464    text.split_whitespace().collect::<Vec<_>>().join(" ")
1465}
1466
1467/// Whether `text` reads as a sentence rather than an identifier or a path.
1468///
1469/// Three tokens or more, at least two of them plain alphabetic words. This is
1470/// the one judgement in the whole derivation: it keeps `crates/zed/src` and
1471/// `X-Zed-Predict-Edits-Mode` out of a registry that would otherwise be mostly
1472/// noise. It is deliberately loose — `Zed Plex Sans` is three words and is in
1473/// the inventory, classified, rather than quietly filtered away.
1474#[must_use]
1475pub fn is_prose(text: &str) -> bool {
1476    let tokens: Vec<&str> = text.split_whitespace().collect();
1477    if tokens.len() < 3 {
1478        return false;
1479    }
1480    let plain = tokens
1481        .iter()
1482        .filter(|token| {
1483            let trimmed = token.trim_matches(|character: char| {
1484                !character.is_ascii_alphabetic() && character != '\''
1485            });
1486            !trimmed.is_empty()
1487                && trimmed
1488                    .chars()
1489                    .all(|character| character.is_ascii_alphabetic() || character == '\'')
1490        })
1491        .count();
1492    plain >= 2
1493}
1494
1495/// Whether `text` is a command line whose program name is a competitor's
1496/// binary.
1497///
1498/// OMEGA-DELTA-0044. `is_prose` needs three tokens, so `zed --existing`,
1499/// `zed --classic` and `zed <path>` were invisible to it — and all three
1500/// shipped in the signed `cli` of `0.2.0-rc16`, in an interactive panel whose
1501/// surrounding copy says "Omega window" and "Omega settings" around them
1502/// (omega#93). Substitute our own name and each stays true, so by the rule
1503/// this gate is written around they are product claims, not references.
1504///
1505/// This admits the narrow shape only: a brand word standing in `argv[0]`,
1506/// followed by flags, placeholders or paths. Admitting every two-token literal
1507/// that starts with a brand word instead adds 8 more across the tree — `Zed
1508/// Pro`, `Zed (Default)`, `Zed Repository` — which are genuine references to
1509/// somebody else's product; admitting a bare brand token adds 55. This shape
1510/// adds exactly the three, which is why the gate can afford to carry it
1511/// instead of writing the three literals into a denylist.
1512#[must_use]
1513pub fn is_command_form(text: &str, policy: &serde_json::Value) -> bool {
1514    let words: Vec<&str> = policy["brand"]["words"]
1515        .as_array()
1516        .map(|values| {
1517            values
1518                .iter()
1519                .filter_map(serde_json::Value::as_str)
1520                .collect()
1521        })
1522        .unwrap_or_default();
1523    let tokens: Vec<&str> = text.split_whitespace().collect();
1524    if tokens.len() < 2 || !words.contains(&tokens[0]) {
1525        return false;
1526    }
1527    tokens[1..].iter().all(|token| is_command_argument(token))
1528}
1529
1530/// A flag (`-n`, `--existing`), a placeholder (`<path>`, `[FILE]`), or a path
1531/// (`.`, `..`, `~/x`, `./x`, `/x`).
1532fn is_command_argument(token: &str) -> bool {
1533    let flag = token.strip_prefix("--").or_else(|| token.strip_prefix('-'));
1534    if let Some(rest) = flag {
1535        return rest
1536            .chars()
1537            .next()
1538            .is_some_and(|character| character.is_ascii_alphanumeric())
1539            && rest
1540                .chars()
1541                .all(|character| character.is_ascii_alphanumeric() || "-_.".contains(character));
1542    }
1543    let placeholder = matches!(token.chars().next(), Some('<' | '[' | '{'))
1544        && matches!(token.chars().last(), Some('>' | ']' | '}'))
1545        && token.len() >= 2
1546        && !token[1..token.len() - 1].contains(['>', ']', '}']);
1547    if placeholder {
1548        return true;
1549    }
1550    token == "." || token == ".." || token.starts_with(['~', '/']) || token.starts_with("./")
1551}
1552
1553/// Prose, or a command form. What the prose inventory admits.
1554#[must_use]
1555pub fn is_user_facing_text(text: &str, policy: &serde_json::Value) -> bool {
1556    is_prose(text) || is_command_form(&normalize_prose(text), policy)
1557}
1558
1559/// Every Rust string literal in `source`, as `(start line, contents)`.
1560///
1561/// Raw and multi-line literals included, comments skipped. A regex over single
1562/// lines misses exactly the literals carrying the longest copy: the OAuth
1563/// callback page, the run-as-root warning and four provider error messages are
1564/// all multi-line, and every one of them named a competitor as the product.
1565#[must_use]
1566pub fn rust_string_literals(source: &str) -> Vec<(usize, String)> {
1567    let mut out = Vec::new();
1568    let mut index = 0;
1569    let mut line = 1usize;
1570    while index < source.len() {
1571        let rest = &source[index..];
1572        let character = rest.as_bytes()[0];
1573        if character == b'\n' {
1574            line += 1;
1575            index += 1;
1576        } else if rest.starts_with("//") {
1577            index += rest.find('\n').unwrap_or(rest.len());
1578        } else if rest.starts_with("/*") {
1579            let (consumed, newlines) = skip_block_comment(rest);
1580            line += newlines;
1581            index += consumed;
1582        } else if character == b'r'
1583            && matches!(rest.as_bytes().get(1), Some(b'"' | b'#'))
1584            && let Some((body, consumed)) = raw_string_literal(rest)
1585        {
1586            let start = line;
1587            line += body.matches('\n').count();
1588            out.push((start, body));
1589            index += consumed;
1590        } else if character == b'"' {
1591            let (body, consumed) = quoted_string_literal(rest);
1592            let start = line;
1593            line += body.matches('\n').count();
1594            out.push((start, body));
1595            index += consumed;
1596        } else if character == b'\'' {
1597            // A char literal or a lifetime; neither can hold prose. Only
1598            // `'"'` has to be stepped over as a unit, so that its quote does
1599            // not read as the start of a string.
1600            index += if rest.as_bytes().get(1) == Some(&b'"')
1601                && rest.as_bytes().get(2) == Some(&b'\'')
1602            {
1603                3
1604            } else {
1605                1
1606            };
1607        } else {
1608            index += rest.chars().next().map_or(1, char::len_utf8);
1609        }
1610    }
1611    out
1612}
1613
1614/// Consume a possibly nested block comment, returning `(bytes, newlines)`.
1615fn skip_block_comment(source: &str) -> (usize, usize) {
1616    let mut depth = 1;
1617    let mut index = 2;
1618    let mut newlines = 0;
1619    while index < source.len() && depth > 0 {
1620        let rest = &source[index..];
1621        if rest.starts_with("/*") {
1622            depth += 1;
1623            index += 2;
1624        } else if rest.starts_with("*/") {
1625            depth -= 1;
1626            index += 2;
1627        } else {
1628            let character = rest.chars().next().unwrap_or('*');
1629            if character == '\n' {
1630                newlines += 1;
1631            }
1632            index += character.len_utf8();
1633        }
1634    }
1635    (index, newlines)
1636}
1637
1638/// Parse `r"..."` / `r#"..."#` at the start of `source`.
1639fn raw_string_literal(source: &str) -> Option<(String, usize)> {
1640    let bytes = source.as_bytes();
1641    let mut cursor = 1;
1642    while bytes.get(cursor) == Some(&b'#') {
1643        cursor += 1;
1644    }
1645    if bytes.get(cursor) != Some(&b'"') {
1646        return None;
1647    }
1648    cursor += 1;
1649    let close = format!("\"{}", "#".repeat(cursor - 2));
1650    let end = source[cursor..].find(&close)? + cursor;
1651    Some((source[cursor..end].to_owned(), end + close.len()))
1652}
1653
1654/// Parse `"..."` at the start of `source`, keeping escapes as written.
1655///
1656/// Escapes are kept rather than resolved because the source is what a reviewer
1657/// reads and what the classification registry records. The packaged half of
1658/// the gate resolves them, because the binary holds the value.
1659fn quoted_string_literal(source: &str) -> (String, usize) {
1660    let mut body = String::new();
1661    let mut cursor = 1;
1662    while cursor < source.len() {
1663        let rest = &source[cursor..];
1664        if let Some(escaped) = rest.strip_prefix('\\') {
1665            let width = 1 + escaped.chars().next().map_or(0, char::len_utf8);
1666            body.push_str(&rest[..width]);
1667            cursor += width;
1668        } else if rest.starts_with('"') {
1669            cursor += 1;
1670            break;
1671        } else {
1672            let character = rest.chars().next().unwrap_or('"');
1673            body.push(character);
1674            cursor += character.len_utf8();
1675        }
1676    }
1677    (body, cursor)
1678}
1679
1680/// Line numbers inside a `#[cfg(test)]` item, which a release build drops.
1681///
1682/// Over-excluding here would be a hole, which is why the packaged half of the
1683/// gate reads the binary that was actually built and honours none of this.
1684#[must_use]
1685pub fn cfg_test_lines(source: &str) -> std::collections::BTreeSet<usize> {
1686    let lines: Vec<&str> = source.lines().collect();
1687    let mut out = std::collections::BTreeSet::new();
1688    for (start, line) in lines.iter().enumerate() {
1689        let trimmed = line.trim_start();
1690        if !trimmed.starts_with("#[cfg(") || !trimmed.contains("test") {
1691            continue;
1692        }
1693        let mut depth: i64 = 0;
1694        let mut opened = false;
1695        for (cursor, item) in lines.iter().enumerate().skip(start) {
1696            depth += i64::try_from(item.matches('{').count()).unwrap_or(0);
1697            depth -= i64::try_from(item.matches('}').count()).unwrap_or(0);
1698            if item.contains('{') {
1699                opened = true;
1700            }
1701            out.insert(cursor + 1);
1702            if opened && depth <= 0 {
1703                break;
1704            }
1705        }
1706    }
1707    out
1708}
1709
1710/// Doc lines the keymap editor renders as an action's description.
1711///
1712/// Inside an `actions!(..)` body, or immediately above an `#[action(..)]`
1713/// derive. `OMEGA-DELTA-0022` recorded action doc comments as unchecked;
1714/// `client::SignIn` describes itself as signing in to a *Zed* account, which
1715/// is true, and only a check that reads them can say so on purpose.
1716#[must_use]
1717pub fn action_doc_lines(source: &str) -> std::collections::BTreeSet<usize> {
1718    let mut out = std::collections::BTreeSet::new();
1719    let lines: Vec<&str> = source.lines().collect();
1720    let mut rest = source;
1721    let mut base = 0;
1722    while let Some(at) = rest.find("actions!(") {
1723        let open = base + at + "actions!(".len() - 1;
1724        let mut depth = 0;
1725        let mut index = open;
1726        let bytes = source.as_bytes();
1727        while index < bytes.len() {
1728            match bytes[index] {
1729                b'(' => depth += 1,
1730                b')' => {
1731                    depth -= 1;
1732                    if depth == 0 {
1733                        break;
1734                    }
1735                }
1736                _ => {}
1737            }
1738            index += 1;
1739        }
1740        let first = source[..open].matches('\n').count() + 1;
1741        let last = source[..index.min(source.len())].matches('\n').count() + 1;
1742        out.extend(first..=last);
1743        base += at + "actions!(".len();
1744        rest = &source[base..];
1745    }
1746    for (index, line) in lines.iter().enumerate() {
1747        if !line.contains("#[action(") {
1748            continue;
1749        }
1750        let mut cursor = index;
1751        while cursor > 0 {
1752            cursor -= 1;
1753            let trimmed = lines[cursor].trim_start();
1754            if doc_comment_body(lines[cursor]).is_some() {
1755                out.insert(cursor + 1);
1756            } else if !trimmed.starts_with("#[") {
1757                break;
1758            }
1759        }
1760    }
1761    out
1762}
1763
1764/// The text of a doc comment, however it was spelled.
1765///
1766/// `///` and `//!` are sugar. `#[doc = "..."]` and
1767/// `#[cfg_attr(<predicate>, doc = "...")]` are the same thing written the long
1768/// way, and both clap and schemars read them identically. This function did not,
1769/// which is why every candidate up to `0.2.0-rc14` printed
1770/// `~/Library/Application Support/Zed` as the data directory from `cli --help`
1771/// while the gate reported green: the line is a `cfg_attr`, and nothing here
1772/// had ever looked inside one (omega#89).
1773fn doc_comment_body(line: &str) -> Option<&str> {
1774    let trimmed = line.trim_start();
1775    if let Some(body) = trimmed
1776        .strip_prefix("///")
1777        .or_else(|| trimmed.strip_prefix("//!"))
1778    {
1779        return Some(body);
1780    }
1781    attribute_doc_body(trimmed)
1782}
1783
1784/// The string in a `doc = "..."` attribute, or the `doc = "..."` line of an
1785/// attribute written across several lines.
1786///
1787/// Anchored at the start of the trimmed line so a Rust `let doc = "..."`
1788/// binding is not mistaken for documentation.
1789fn attribute_doc_body(trimmed: &str) -> Option<&str> {
1790    let rest = if let Some(rest) = trimmed.strip_prefix("#[") {
1791        let at = rest.find("doc")?;
1792        &rest[at..]
1793    } else if trimmed.starts_with("doc") {
1794        trimmed
1795    } else {
1796        return None;
1797    };
1798    let rest = rest.strip_prefix("doc")?;
1799    let rest = rest.trim_start();
1800    let rest = rest.strip_prefix('=')?.trim_start();
1801    let rest = rest.strip_prefix('"')?;
1802    let mut end = 0;
1803    let bytes = rest.as_bytes();
1804    while end < bytes.len() {
1805        match bytes[end] {
1806            b'\\' => end += 2,
1807            b'"' => return Some(&rest[..end]),
1808            _ => end += 1,
1809        }
1810    }
1811    None
1812}
1813
1814/// Every brand-bearing prose literal that can reach a user, plus read counts.
1815///
1816/// Five streams, each derived from a mechanism that exists in the tree rather
1817/// than from a list of files somebody remembered. See the `prose` section of
1818/// `script/omega-brand-gate.json`, which both halves of the gate read.
1819#[must_use]
1820pub fn prose_inventory(policy: &serde_json::Value) -> (Vec<ProseLiteral>, ProseReadCounts) {
1821    let mut items = Vec::new();
1822    let mut read = ProseReadCounts::default();
1823    let repository = normalize_path(&repository_path("."));
1824    let rust_root = policy["prose"]["rust_root"].as_str().unwrap_or("crates");
1825
1826    for_each_source_file(&repository_path(rust_root), &["rs"], |path, source| {
1827        read.rust_files += 1;
1828        let literals = rust_string_literals(source);
1829        read.literals += literals.len();
1830        let lines: Vec<&str> = source.lines().collect();
1831        let code: String = lines
1832            .iter()
1833            .map(|line| {
1834                if doc_comment_body(line).is_some() {
1835                    ""
1836                } else {
1837                    *line
1838                }
1839            })
1840            .collect::<Vec<_>>()
1841            .join("\n");
1842        let schema = derives_any(&code, &["JsonSchema"]);
1843        let clap = derives_any(&code, &["Parser", "Args", "Subcommand"])
1844            || code.contains("#[command(")
1845            || code.contains("clap::Parser");
1846        let actions = action_doc_lines(source);
1847        for (number, _line) in lines.iter().enumerate() {
1848            if doc_comment_body(lines[number]).is_none() {
1849                continue;
1850            }
1851            if actions.contains(&(number + 1)) {
1852                read.action_docs += 1;
1853            } else if schema {
1854                read.schema_docs += 1;
1855            } else if clap {
1856                read.clap_docs += 1;
1857            }
1858        }
1859        if brand_hits(source, policy).is_empty() {
1860            return;
1861        }
1862        let relative = normalize_path(path).strip_prefix(&repository).map_or_else(
1863            |_| path.display().to_string(),
1864            |tail| tail.display().to_string(),
1865        );
1866        let is_test_file = is_test_path(&relative);
1867        let skipped = if is_test_file {
1868            std::collections::BTreeSet::new()
1869        } else {
1870            cfg_test_lines(source)
1871        };
1872        for (number, body) in literals {
1873            if is_test_file || skipped.contains(&number) {
1874                continue;
1875            }
1876            if !brand_hits(&body, policy).is_empty() && is_user_facing_text(&body, policy) {
1877                items.push(ProseLiteral {
1878                    kind: "rust_string",
1879                    file: relative.clone(),
1880                    line: number,
1881                    text: normalize_prose(&body),
1882                });
1883            }
1884        }
1885        for (index, line) in lines.iter().enumerate() {
1886            let number = index + 1;
1887            if is_test_file || skipped.contains(&number) {
1888                continue;
1889            }
1890            let Some(body) = doc_comment_body(line) else {
1891                continue;
1892            };
1893            if brand_hits(body, policy).is_empty() || !is_user_facing_text(body, policy) {
1894                continue;
1895            }
1896            let kind = if actions.contains(&number) {
1897                "action_doc"
1898            } else if schema {
1899                "schema_doc"
1900            } else if clap {
1901                "clap_doc"
1902            } else {
1903                continue;
1904            };
1905            items.push(ProseLiteral {
1906                kind,
1907                file: relative.clone(),
1908                line: number,
1909                text: normalize_prose(body),
1910            });
1911        }
1912    });
1913
1914    for relative in embedded_asset_inventory() {
1915        read.embedded += 1;
1916        let Ok(source) = std::fs::read_to_string(repository_path(&relative)) else {
1917            continue;
1918        };
1919        if brand_hits(&source, policy).is_empty() {
1920            continue;
1921        }
1922        for (index, line) in source.lines().enumerate() {
1923            if !brand_hits(line, policy).is_empty() && is_user_facing_text(line, policy) {
1924                items.push(ProseLiteral {
1925                    kind: "asset",
1926                    file: relative.clone(),
1927                    line: index + 1,
1928                    text: normalize_prose(line),
1929                });
1930            }
1931        }
1932    }
1933    items.sort();
1934    (items, read)
1935}
1936
1937/// Whether any `#[derive(..)]` in `code` names one of `traits`.
1938///
1939/// Doc lines are stripped by the caller before this runs, so a derive written
1940/// inside a rustdoc EXAMPLE does not pull a whole framework crate's internal
1941/// documentation into the inventory. `gpui/src/action.rs` documents
1942/// `#[derive(.., schemars::JsonSchema, Action)]` in a code sample and has no
1943/// settings type in it at all.
1944fn derives_any(code: &str, traits: &[&str]) -> bool {
1945    let mut rest = code;
1946    while let Some(at) = rest.find("#[derive(") {
1947        rest = &rest[at + "#[derive(".len()..];
1948        let list = rest.split(')').next().unwrap_or("");
1949        if traits.iter().any(|name| list.contains(name)) {
1950            return true;
1951        }
1952    }
1953    false
1954}
1955
1956/// Whether `relative` names a file a release build never compiles.
1957fn is_test_path(relative: &str) -> bool {
1958    let normalized = relative.replace('\\', "/");
1959    normalized.ends_with("_test.rs")
1960        || normalized.ends_with("_tests.rs")
1961        || ["/tests/", "/test/", "/benches/", "/examples/", "/fixtures/"]
1962            .iter()
1963            .any(|segment| normalized.contains(segment))
1964}
1965
1966// ------ OMEGA-DELTA-0042
1967
1968/// OMEGA-DELTA-0042. The Exo harness lane's law. A leaf, checkable in a second.
1969pub const EXO_LANE_LAW_PATH: &str = "crates/omega_exo_lane/src/omega_exo_lane.rs";
1970
1971/// OMEGA-DELTA-0042. Which Exo the lane admits.
1972pub const EXO_LANE_PIN_PATH: &str = "crates/omega_exo_lane/src/pin.rs";
1973
1974/// OMEGA-DELTA-0042. Every command line the lane can produce.
1975pub const EXO_LANE_COMMAND_PATH: &str = "crates/omega_exo_lane/src/command.rs";
1976
1977/// OMEGA-DELTA-0042. The half that spawns a process and builds a thread.
1978pub const EXO_CONNECTION_PATH: &str = "crates/agent_ui/src/omega_exo_connection.rs";
1979
1980/// OMEGA-DELTA-0042. The two Exos, which share only a name.
1981///
1982/// omega#86 was closed for targeting the wrong one — exo labs'
1983/// `exo-explore/exo` cluster-inference appliance — and omega#87 supersedes it
1984/// with `exoharness/exo`, the agent harness. A repository name is a cheap thing
1985/// to get wrong twice, so it is a checked fact rather than a remembered one.
1986pub const EXO_HARNESS_UPSTREAM: &str = "exoharness/exo";
1987
1988/// OMEGA-DELTA-0042. The maintained fork can carry the ACP transport while
1989/// its contribution is under review upstream.
1990pub const EXO_HARNESS_MAINTAINED_FORK: &str = "OpenAgentsInc/exo";
1991
1992/// OMEGA-DELTA-0042. The other Exo, which must appear nowhere as a target.
1993pub const EXO_CLUSTER_UPSTREAM: &str = "exo-explore";
1994
1995/// OMEGA-DELTA-0042. Placeholders in `ADMITTED_LANE_ARGV` that stand for text
1996/// reachable from a person or a model.
1997///
1998/// Exo accepts its global options *after* the subcommand, so an unterminated
1999/// prompt is not a string Exo receives — it is Exo's command line. Driven
2000/// against the pinned Exo, a prompt of `--help` exits 0, prints usage, and runs
2001/// no turn.
2002pub const EXO_LANE_USER_TEXT_SLOTS: &[&str] = &["<agent>", "<conversation>", "<prompt>"];
2003
2004/// OMEGA-DELTA-0042. Vocabulary that would mean Omega is standing between Exo's
2005/// unauthenticated endpoint and something else.
2006///
2007/// `exo serve` has no authentication and full secret access; its own
2008/// documentation says loopback is the entire boundary. Tier A needs no address
2009/// at all — the CLI reaches the state root on disk — so any of this appearing in
2010/// the lane is a surface nobody asked for.
2011pub const EXO_OFF_MACHINE_TOKENS: &[(&str, &str)] = &[
2012    ("a listener", "TcpListener"),
2013    ("a listener", "bind("),
2014    ("a listener", "0.0.0.0"),
2015    ("a proxy", "proxy"),
2016    ("a bearer token Exo never checks", "bearer"),
2017];
2018
2019/// OMEGA-DELTA-0042. Flags that would point Exo somewhere other than the state
2020/// root on disk.
2021///
2022/// Checked against the *argv table* rather than the whole lane, because the
2023/// lane has to be able to name `EXO_EXOHARNESS_URL` in order to refuse an
2024/// off-loopback one it inherited from the environment. Omega passing the flag
2025/// and Omega refusing the variable are opposite acts that share a spelling.
2026pub const EXO_REDIRECTING_FLAGS: &[&str] = &["exoharness-url", "--url", "serve", "bearer-env"];
2027
2028/// OMEGA-DELTA-0042, and owner gate 8 behind it.
2029///
2030/// *No model-initiated path may start Full Auto authority.* Three such paths
2031/// were removed from OpenAgents Desktop on 2026-07-25, one of them a rename of
2032/// another. An Exo agent has an unrestricted networked shell and can rebuild
2033/// itself, which makes it exactly the caller that gate exists for — so adding an
2034/// executor lane must not open a fourth door. The lane names none of this
2035/// vocabulary, and the check is that it cannot start naming it quietly.
2036pub const EXO_FULL_AUTO_TOKENS: &[&str] = &[
2037    "LaunchOrigin",
2038    "full_auto",
2039    "FullAuto",
2040    "PinGesture",
2041    "EngineLane",
2042    "run_ref: Some",
2043];
2044
2045// ------ OMEGA-DELTA-0032
2046
2047/// OMEGA-DELTA-0032. The law that decides what a send during a turn does.
2048pub const SEND_DURING_TURN_PATH: &str = "crates/omega_front_door/src/send_during_turn.rs";
2049
2050/// OMEGA-DELTA-0032. The durable half of the queue.
2051pub const SEND_QUEUE_JOURNAL_PATH: &str = "crates/agent_ui/src/omega_send_queue.rs";
2052
2053/// OMEGA-DELTA-0032. Where the composer decides what to do with a queued
2054/// message.
2055pub const CONVERSATION_SEND_PATH: &str = "crates/agent_ui/src/conversation_view/thread_view.rs";
2056
2057/// OMEGA-DELTA-0032. Vocabulary that would make the queue law irreproducible,
2058/// for the same reason `NON_DETERMINISTIC_ROUTING_TOKENS` exists: a queue whose
2059/// decision depends on a clock or on hash order cannot be replayed from a
2060/// journal, and a journal that cannot be replayed is not a durable admission.
2061pub const NON_DETERMINISTIC_QUEUE_TOKENS: &[(&str, &str)] = &[
2062    ("a clock", "SystemTime"),
2063    ("a clock", "Instant"),
2064    ("a clock", "::now("),
2065    ("a clock", "chrono"),
2066    ("randomness", "rand::"),
2067    ("hash iteration order", "HashMap"),
2068    ("hash iteration order", "HashSet"),
2069    ("the environment", "std::env"),
2070];
2071
2072/// OMEGA-DELTA-0032. Every executor class the send law must answer for.
2073pub const SEND_LAW_EXECUTOR_TOKENS: &[&str] = &["NativeLoop", "ExternalAcp", "EngineLane"];
2074
2075#[cfg(test)]
2076mod tests {
2077    use super::*;
2078
2079    /// OMEGA-DELTA-0001. Upstream Zed defaults this to `false` and shows the
2080    /// "Unrecognized Project" Restricted Mode modal. Omega never restricts.
2081    #[test]
2082    fn trust_all_worktrees_defaults_to_true() {
2083        let settings = default_settings().expect("default settings parse");
2084        let value = default_setting(&settings, "session.trust_all_worktrees")
2085            .expect("session.trust_all_worktrees is present in default settings");
2086        assert_eq!(
2087            value.as_bool(),
2088            Some(true),
2089            "OMEGA-DELTA-0001: Omega must default session.trust_all_worktrees to \
2090             true. Upstream Zed defaults it to false, which restricts \
2091             unrecognized projects and shows the trust prompt the owner \
2092             removed. If a rebase reverted this, restore it rather than \
2093             editing this test."
2094        );
2095    }
2096
2097    /// OMEGA-DELTA-0002. Upstream Zed defaults to "confirm", which asks before
2098    /// every agent tool action. Omega runs agents unattended, where a prompt
2099    /// is a hang rather than a safeguard.
2100    #[test]
2101    fn agent_tool_permissions_default_to_allow() {
2102        let settings = default_settings().expect("default settings parse");
2103        let value = default_setting(&settings, "agent.tool_permissions.default")
2104            .expect("agent.tool_permissions.default is present in default settings");
2105        assert_eq!(
2106            value.as_str(),
2107            Some("allow"),
2108            "OMEGA-DELTA-0002: Omega must default agent.tool_permissions.default \
2109             to \"allow\". Upstream Zed defaults to \"confirm\", which blocks \
2110             unattended agent work entirely. Draw lines with always_confirm / \
2111             always_deny patterns instead of by reverting this default."
2112        );
2113    }
2114
2115    /// OMEGA-DELTA-0003. Already correct upstream-divergent value, locked so a
2116    /// rebase cannot quietly reintroduce the quit prompt.
2117    #[test]
2118    fn quitting_is_never_confirmed() {
2119        let settings = default_settings().expect("default settings parse");
2120        assert_eq!(
2121            default_setting(&settings, "confirm_quit").and_then(serde_json::Value::as_bool),
2122            Some(false),
2123            "OMEGA-DELTA-0003: Omega must not ask for confirmation on quit."
2124        );
2125    }
2126
2127    /// OMEGA-DELTA-0004. Telemetry stays off. This is a privacy posture, so it
2128    /// is locked rather than left to whatever upstream ships next.
2129    #[test]
2130    fn telemetry_stays_off() {
2131        let settings = default_settings().expect("default settings parse");
2132        for key in ["telemetry.diagnostics", "telemetry.metrics"] {
2133            assert_eq!(
2134                default_setting(&settings, key).and_then(serde_json::Value::as_bool),
2135                Some(false),
2136                "OMEGA-DELTA-0004: {key} must default to false in Omega."
2137            );
2138        }
2139    }
2140
2141    /// The normalizer must not touch string contents. If it did, a setting
2142    /// whose value contains `//` or a comma would be silently corrupted and
2143    /// every check above would be reading the wrong document.
2144    #[test]
2145    fn the_normalizer_leaves_string_contents_alone() {
2146        let parsed: serde_json::Value = serde_json::from_str(&strip_jsonc(
2147            r#"{
2148                // a leading comment
2149                "url": "https://example.com/a//b",
2150                "text": "a, b",
2151                "glob": "**/*.pem",
2152                "trailing": [1, 2,],
2153            }"#,
2154        ))
2155        .expect("normalized JSONC parses");
2156        assert_eq!(parsed["url"], "https://example.com/a//b");
2157        assert_eq!(parsed["text"], "a, b");
2158        // default.json really does contain this shape; a naive block-comment
2159        // patch would treat the `/*` as an opening delimiter.
2160        assert_eq!(parsed["glob"], "**/*.pem");
2161        assert_eq!(parsed["trailing"], serde_json::json!([1, 2]));
2162    }
2163
2164    /// A trailing comma separated from its brace by a comment is the case that
2165    /// a single-pass normalizer gets wrong.
2166    #[test]
2167    fn the_normalizer_handles_a_comma_then_comment_then_brace() {
2168        let parsed: serde_json::Value =
2169            serde_json::from_str(&strip_jsonc("{\n  \"a\": 1,\n  // trailing note\n}"))
2170                .expect("normalized JSONC parses");
2171        assert_eq!(parsed["a"], 1);
2172    }
2173
2174    /// Block comments are not supported, and must fail loudly rather than
2175    /// truncate the document into something that still parses.
2176    #[test]
2177    fn a_block_comment_fails_closed() {
2178        let normalized = strip_jsonc("{ /* note */ \"a\": 1 }");
2179        assert!(
2180            serde_json::from_str::<serde_json::Value>(&normalized).is_err(),
2181            "an unsupported block comment must fail the check, never parse to \
2182             a different document"
2183        );
2184    }
2185
2186    /// The delta check has to be able to fail, or it proves nothing.
2187    #[test]
2188    fn the_delta_check_detects_a_reverted_default() {
2189        let reverted: serde_json::Value = serde_json::from_str(&strip_jsonc(
2190            "{ \"session\": { \"trust_all_worktrees\": false } }",
2191        ))
2192        .expect("parses");
2193        assert_eq!(
2194            default_setting(&reverted, "session.trust_all_worktrees")
2195                .and_then(serde_json::Value::as_bool),
2196            Some(false),
2197            "the lookup used by the delta check must observe an upstream revert"
2198        );
2199    }
2200
2201    /// OMEGA-DELTA-0005 and 0006. Deleted surfaces stay deleted.
2202    #[test]
2203    fn removed_surfaces_stay_removed() {
2204        for relative in REMOVED_FILES {
2205            let path = repository_path(relative);
2206            assert!(
2207                !path.exists(),
2208                "{relative} was deleted from Omega and has come back. If a \
2209                 rebase restored it, delete it again rather than editing this \
2210                 test; see OMEGA_DELTAS.md."
2211            );
2212        }
2213    }
2214
2215    /// OMEGA-DELTA-0007. Terminating a debug session must not ask first.
2216    #[test]
2217    fn debug_terminate_never_prompts() {
2218        let path = repository_path("crates/debugger_ui/src/debugger_panel.rs");
2219        let source = std::fs::read_to_string(&path).expect("debugger panel is readable");
2220        assert!(
2221            !source.contains("Are you sure you want to terminate it?"),
2222            "OMEGA-DELTA-0007: the debug-session terminate confirmation has \
2223             returned to {}",
2224            path.display()
2225        );
2226    }
2227
2228    /// OMEGA-DELTA-0008 and 0009. Strings that must not ship.
2229    ///
2230    /// Checked across the tree rather than per file: both of these survived a
2231    /// source-level review and were caught only by scanning the binary.
2232    #[test]
2233    fn no_zed_product_copy_survives_anywhere() {
2234        let crates_root = repository_path("crates");
2235        let mut offenders: Vec<String> = Vec::new();
2236        let mut stack = vec![crates_root];
2237        while let Some(directory) = stack.pop() {
2238            let Ok(entries) = std::fs::read_dir(&directory) else {
2239                continue;
2240            };
2241            for entry in entries.flatten() {
2242                let path = entry.path();
2243                if path.is_symlink() {
2244                    continue;
2245                }
2246                if path.is_dir() {
2247                    if path.file_name().is_some_and(|name| name == "target") {
2248                        continue;
2249                    }
2250                    stack.push(path);
2251                    continue;
2252                }
2253                if path.extension().is_none_or(|extension| extension != "rs") {
2254                    continue;
2255                }
2256                // This crate names the strings in order to forbid them.
2257                if path.ends_with("omega_deltas.rs") {
2258                    continue;
2259                }
2260                let Ok(source) = std::fs::read_to_string(&path) else {
2261                    continue;
2262                };
2263                for (delta, needle) in FORBIDDEN_SOURCE_STRINGS {
2264                    if source.contains(needle) {
2265                        offenders.push(format!("{delta}: {needle:?} in {}", path.display()));
2266                    }
2267                }
2268            }
2269        }
2270        assert!(
2271            offenders.is_empty(),
2272            "forbidden Zed product copy has returned:\n{}",
2273            offenders.join("\n")
2274        );
2275    }
2276
2277    /// OMEGA-DELTA-0009. Restricted Mode cannot return through a surviving
2278    /// profile selector, language-server status, workspace action, or key binding.
2279    #[test]
2280    fn restricted_mode_ui_and_shortcuts_are_absent() {
2281        let mut offenders = Vec::new();
2282        for (relative_path, needle) in FORBIDDEN_RESTRICTED_MODE_UI {
2283            let path = repository_path(relative_path);
2284            let source = std::fs::read_to_string(&path)
2285                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2286            if source.contains(needle) {
2287                offenders.push(format!("{needle:?} in {}", path.display()));
2288            }
2289        }
2290        assert!(
2291            offenders.is_empty(),
2292            "OMEGA-DELTA-0009 Restricted Mode UI or shortcuts returned:\n{}",
2293            offenders.join("\n")
2294        );
2295    }
2296
2297    /// OMEGA-DELTA-0010. The title-bar identity entry stays local instead of
2298    /// invoking the inherited hosted-account sign-in flow.
2299    #[test]
2300    fn title_bar_identity_entry_opens_onboarding() {
2301        let path = repository_path("crates/title_bar/src/title_bar.rs");
2302        let source = std::fs::read_to_string(&path)
2303            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2304        assert!(
2305            source.contains("Button::new(\"omega_identity\", \"Omega Identity\")")
2306                && source.contains("dispatch_action(OpenOnboarding.boxed_clone()"),
2307            "OMEGA-DELTA-0010: the title-bar identity entry must dispatch local Omega onboarding"
2308        );
2309        assert!(
2310            !source.contains("Button::new(\"sign_in\", \"Sign In\")")
2311                && !source.contains(".sign_in_with_optional_connect(true"),
2312            "OMEGA-DELTA-0010: the title bar must not restore hosted account sign-in"
2313        );
2314    }
2315
2316    /// OMEGA-DELTA-0011. Agent onboarding keeps direct provider setup and
2317    /// excludes the inherited hosted account and plan path.
2318    #[test]
2319    fn ai_onboarding_is_provider_only() {
2320        let crate_root = repository_path("crates/ai_onboarding");
2321        let mut source = String::new();
2322        for relative_path in [
2323            "src/ai_onboarding.rs",
2324            "src/agent_api_keys_onboarding.rs",
2325            "src/agent_panel_onboarding_content.rs",
2326            "src/edit_prediction_onboarding_content.rs",
2327            "Cargo.toml",
2328        ] {
2329            let path = crate_root.join(relative_path);
2330            source.push_str(
2331                &std::fs::read_to_string(&path)
2332                    .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display())),
2333            );
2334        }
2335        let agent_panel_path = repository_path("crates/agent_ui/src/agent_panel.rs");
2336        source.push_str(
2337            &std::fs::read_to_string(&agent_panel_path).unwrap_or_else(|error| {
2338                panic!("cannot read {}: {error}", agent_panel_path.display())
2339            }),
2340        );
2341
2342        for forbidden in [
2343            "ZedAiOnboarding",
2344            "Plan::Zed",
2345            "sign_in_with_optional_connect",
2346            "Hosted agent plans",
2347            "client.workspace = true",
2348            "cloud_api_types.workspace = true",
2349        ] {
2350            assert!(
2351                !source.contains(forbidden),
2352                "OMEGA-DELTA-0011: hosted onboarding path returned: {forbidden:?}"
2353            );
2354        }
2355        for required in [
2356            "Connect an AI provider",
2357            "Configure Providers",
2358            "zed_actions::agent::OpenSettings",
2359            "Configure edit predictions",
2360            "Configure Copilot",
2361        ] {
2362            assert!(
2363                source.contains(required),
2364                "OMEGA-DELTA-0011: required provider setup disappeared: {required:?}"
2365            );
2366        }
2367    }
2368
2369    /// A deleted crate must not leave keybindings behind.
2370    ///
2371    /// The built-in keymap is loaded and unwrapped during startup, so a
2372    /// binding naming an action whose crate is gone panics before any window
2373    /// opens. The workspace still compiles, which is exactly why this needs
2374    /// its own check rather than trusting the build.
2375    #[test]
2376    fn keymaps_name_no_deleted_action() {
2377        let mut offenders: Vec<String> = Vec::new();
2378        for keymap in [
2379            "assets/keymaps/default-macos.json",
2380            "assets/keymaps/default-linux.json",
2381            "assets/keymaps/default-windows.json",
2382        ] {
2383            let path = repository_path(keymap);
2384            let Ok(source) = std::fs::read_to_string(&path) else {
2385                offenders.push(format!("{keymap} is unreadable"));
2386                continue;
2387            };
2388            for (delta, namespace) in FORBIDDEN_KEYMAP_NAMESPACES {
2389                if source.contains(namespace) {
2390                    offenders.push(format!("{delta}: {namespace:?} still bound in {keymap}"));
2391                }
2392            }
2393        }
2394        assert!(
2395            offenders.is_empty(),
2396            "a deleted crate left keybindings behind, which panics Omega at \
2397             startup:\n{}",
2398            offenders.join("\n")
2399        );
2400    }
2401
2402    /// OMEGA-DELTA-0013. The agent ships reachable.
2403    ///
2404    /// `enabled: false` also strips the agent namespaces from the command
2405    /// palette, and the Settings UI exposes only `agent.button`, so a
2406    /// regression here makes the feature unreachable rather than merely off.
2407    #[test]
2408    fn the_agent_ships_enabled() {
2409        let settings = default_settings().expect("default settings parse");
2410        for key in ["agent.enabled", "agent.button"] {
2411            assert_eq!(
2412                default_setting(&settings, key).and_then(serde_json::Value::as_bool),
2413                Some(true),
2414                "OMEGA-DELTA-0013: {key} must default to true. With it false the \
2415                 agent is not reachable from the command palette or the panel, \
2416                 and no Settings control turns it back on."
2417            );
2418        }
2419    }
2420
2421    /// OMEGA-DELTA-0013. The shipped default model is pinned by name.
2422    ///
2423    /// The service-isolation test asserts only that the default provider is
2424    /// `google`, because what it protects is that the default never points at
2425    /// a Zed service. That leaves the model string free: a rebase could swap
2426    /// `gemini-3.6-flash` for any other Google model and every existing check
2427    /// would still pass. The owner chose this model specifically, so it is
2428    /// pinned here by name.
2429    ///
2430    /// Changing the default model is a real decision. Update this constant and
2431    /// the `OMEGA-DELTA-0013` entry together, so the registry never disagrees
2432    /// with what ships.
2433    #[test]
2434    fn the_default_model_is_pinned() {
2435        const EXPECTED_PROVIDER: &str = "google";
2436        const EXPECTED_MODEL: &str = "gemini-3.6-flash";
2437
2438        let settings = default_settings().expect("default settings parse");
2439        let default_model = default_setting(&settings, "agent.default_model")
2440            .expect("agent.default_model must be present in the shipped defaults");
2441
2442        for (key, expected) in [("provider", EXPECTED_PROVIDER), ("model", EXPECTED_MODEL)] {
2443            assert_eq!(
2444                default_model.get(key).and_then(serde_json::Value::as_str),
2445                Some(expected),
2446                "OMEGA-DELTA-0013: agent.default_model.{key} must be \
2447                 {expected:?}. The owner selected {EXPECTED_PROVIDER}/\
2448                 {EXPECTED_MODEL} deliberately; the service-isolation test \
2449                 pins only the provider, so without this the model can change \
2450                 silently."
2451            );
2452        }
2453    }
2454
2455    /// OMEGA-DELTA-0014. A protected recovery must not present a control whose
2456    /// label claims the protection has not happened.
2457    ///
2458    /// The behavioural assertion lives in the `onboarding` crate, where the
2459    /// presentation function is. This one is source-level so that it survives
2460    /// a rebase of that crate, and it also pins the behavioural test in place,
2461    /// because deleting the test is the cheapest way to revert the fix.
2462    #[test]
2463    fn protected_recovery_offers_a_different_action() {
2464        let path = repository_path("crates/onboarding/src/identity_section.rs");
2465        let source = std::fs::read_to_string(&path)
2466            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2467
2468        for required in [
2469            "ReplaceRecovery,",
2470            "\"Replace recovery file\"",
2471            "actions: vec![if needs_recovery {",
2472            "assert_ne!(protected.actions, needed.actions)",
2473        ] {
2474            assert!(
2475                source.contains(required),
2476                "OMEGA-DELTA-0014: the recovery-state split lost {required:?}. \
2477                 A protected identity must offer replacement, not protection; \
2478                 see omega#68."
2479            );
2480        }
2481        assert!(
2482            !source.contains("actions: vec![IdentityAction::Protect],"),
2483            "OMEGA-DELTA-0014: the Ready branch emits a constant Protect \
2484             action again, so a protected identity shows \"Protect recovery\" \
2485             beneath \"Recovery protected\". That is the omega#68 defect."
2486        );
2487    }
2488
2489    /// OMEGA-DELTA-0015. The workroom binding exists, is unscoped, and names an
2490    /// action that still exists.
2491    ///
2492    /// Presence alone would not be enough. A keymap naming an undeclared action
2493    /// panics Omega before any window opens and compiles fine, which is how
2494    /// 0.2.0-rc6 shipped 27 dead bindings, so the action is resolved back to
2495    /// its declaration. The context is checked because a binding that only
2496    /// fires from one pane is the falsifier omega#69 named.
2497    #[test]
2498    fn required_keymap_bindings_resolve() {
2499        for binding in REQUIRED_KEYMAP_BINDINGS {
2500            let RequiredKeymapBinding {
2501                delta,
2502                keymap,
2503                keystroke,
2504                action,
2505                declared_in,
2506            } = binding;
2507
2508            let path = repository_path(keymap);
2509            let raw = std::fs::read_to_string(&path)
2510                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2511            let sections: serde_json::Value = serde_json::from_str(&strip_jsonc(&raw))
2512                .unwrap_or_else(|error| panic!("cannot parse {}: {error}", path.display()));
2513            let sections = sections
2514                .as_array()
2515                .unwrap_or_else(|| panic!("{keymap} is not an array of sections"));
2516
2517            let bound: Vec<(Option<&str>, &serde_json::Value)> = sections
2518                .iter()
2519                .filter_map(|section| {
2520                    let binding = section.get("bindings")?.get(*keystroke)?;
2521                    Some((
2522                        section.get("context").and_then(serde_json::Value::as_str),
2523                        binding,
2524                    ))
2525                })
2526                .collect();
2527            assert_eq!(
2528                bound.len(),
2529                1,
2530                "{delta}: {keymap} must bind {keystroke:?} exactly once. A \
2531                 second, narrower binding shadows the global one depending on \
2532                 focus. Found: {bound:?}"
2533            );
2534            let (context, dispatched) = bound[0];
2535            assert_eq!(
2536                dispatched.as_str(),
2537                Some(*action),
2538                "{delta}: {keymap} must bind {keystroke:?} to {action:?}"
2539            );
2540            assert!(
2541                context.is_none_or(|context| WINDOW_GLOBAL_KEYMAP_CONTEXTS.contains(&context)),
2542                "{delta}: {keymap} binds {keystroke:?} in context {context:?}, \
2543                 which is narrower than the window. The binding must fire from \
2544                 an editor, a terminal, or any panel; a focus-dependent one is \
2545                 the omega#69 falsifier. Window-global contexts: \
2546                 {WINDOW_GLOBAL_KEYMAP_CONTEXTS:?}"
2547            );
2548
2549            let declaration_path = repository_path(declared_in);
2550            let declaration = std::fs::read_to_string(&declaration_path).unwrap_or_else(|error| {
2551                panic!("cannot read {}: {error}", declaration_path.display())
2552            });
2553            assert!(
2554                declared_actions(&declaration).contains(*action),
2555                "{delta}: {keymap} binds {keystroke:?} to {action:?}, which is \
2556                 no longer declared in {declared_in}. The built-in keymap is \
2557                 unwrapped at startup, so this panics Omega before any window \
2558                 opens — the 0.2.0-rc6 failure."
2559            );
2560        }
2561
2562        let (relative_path, menu_item) = SAVE_AS_MENU_ITEM;
2563        let path = repository_path(relative_path);
2564        let source = std::fs::read_to_string(&path)
2565            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2566        assert!(
2567            source.contains(menu_item),
2568            "OMEGA-DELTA-0015: the workroom binding took the chord that was \
2569             workspace::SaveAs in all three default keymaps, leaving the File \
2570             menu as the only discoverable Save As on macOS and Windows. That \
2571             menu item has gone from {relative_path}, so the trade this delta \
2572             recorded is no longer the trade being made."
2573        );
2574    }
2575
2576    /// The action parser has to actually find actions, or the resolvability
2577    /// check above passes on an empty set and proves nothing.
2578    #[test]
2579    fn the_action_parser_reaches_real_declarations() {
2580        let declared = declared_actions(
2581            "pub mod workroom {\n    use gpui::actions;\n    actions!(\n        workroom,\n \
2582             [\n            /// Opens it, and then, having opened it, focuses.\n            \
2583             OpenPanel,\n            FocusComposer\n        ]\n    );\n}",
2584        );
2585        assert!(declared.contains("workroom::OpenPanel"));
2586        assert!(declared.contains("workroom::FocusComposer"));
2587        assert!(
2588            !declared.contains("workroom::Opens"),
2589            "a doc comment must not be parsed as an action name"
2590        );
2591    }
2592
2593    /// OMEGA-DELTA-0016. Aiur is one dark theme, and no light variant can be
2594    /// reintroduced without failing here.
2595    #[test]
2596    fn aiur_is_a_single_dark_theme() {
2597        let path = repository_path("assets/themes/aiur/aiur.json");
2598        let raw = std::fs::read_to_string(&path)
2599            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2600        let family: serde_json::Value = serde_json::from_str(&strip_jsonc(&raw))
2601            .unwrap_or_else(|error| panic!("cannot parse {}: {error}", path.display()));
2602
2603        assert_eq!(
2604            family.get("name").and_then(serde_json::Value::as_str),
2605            Some("Aiur"),
2606            "OMEGA-DELTA-0016: the shipped family must be named Aiur"
2607        );
2608        let themes = family
2609            .get("themes")
2610            .and_then(serde_json::Value::as_array)
2611            .expect("aiur.json declares a themes array");
2612        assert_eq!(
2613            themes.len(),
2614            1,
2615            "OMEGA-DELTA-0016: Aiur is dark-only, so it declares exactly one \
2616             theme. A second variant has returned; see omega#70."
2617        );
2618        assert_eq!(
2619            themes[0].get("name").and_then(serde_json::Value::as_str),
2620            Some("Aiur"),
2621            "OMEGA-DELTA-0016: the theme is named exactly Aiur, with no suffix"
2622        );
2623        assert_eq!(
2624            themes[0]
2625                .get("appearance")
2626                .and_then(serde_json::Value::as_str),
2627            Some("dark"),
2628            "OMEGA-DELTA-0016: Aiur is a dark theme"
2629        );
2630
2631        let mut offenders: Vec<String> = Vec::new();
2632        for root in ["assets", "crates"] {
2633            for_each_source_file(
2634                &repository_path(root),
2635                &["rs", "json", "toml", "md"],
2636                |path, source| {
2637                    // This crate names the strings in order to forbid them.
2638                    if path.ends_with("omega_deltas.rs") {
2639                        return;
2640                    }
2641                    for needle in ["Aiur Light", "Aiur Dark"] {
2642                        if source.contains(needle) {
2643                            offenders.push(format!("{needle:?} in {}", path.display()));
2644                        }
2645                    }
2646                },
2647            );
2648        }
2649        assert!(
2650            offenders.is_empty(),
2651            "OMEGA-DELTA-0016: a suffixed Aiur name has returned:\n{}",
2652            offenders.join("\n")
2653        );
2654    }
2655
2656    /// OMEGA-DELTA-0016. Both appearance defaults must name a theme Omega
2657    /// actually ships.
2658    ///
2659    /// This is omega#70's falsifier stated as a check: deleting a variant
2660    /// without repointing the default that named it fails here rather than at
2661    /// the owner's first light-mode launch.
2662    #[test]
2663    fn default_themes_exist_in_shipped_assets() {
2664        let shipped = shipped_theme_names().expect("shipped themes parse");
2665        assert!(
2666            shipped.contains("Aiur"),
2667            "OMEGA-DELTA-0016: Aiur must ship; found {shipped:?}"
2668        );
2669
2670        let mut dark_defaults: Vec<(&str, String)> = Vec::new();
2671        for (relative_path, constant) in [
2672            (
2673                "crates/settings_content/src/theme.rs",
2674                "DEFAULT_LIGHT_THEME",
2675            ),
2676            ("crates/settings_content/src/theme.rs", "DEFAULT_DARK_THEME"),
2677            ("crates/theme/src/theme.rs", "DEFAULT_DARK_THEME"),
2678        ] {
2679            let path = repository_path(relative_path);
2680            let source = std::fs::read_to_string(&path)
2681                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2682            let value = string_constant(&source, constant).unwrap_or_else(|| {
2683                panic!("{constant} is not declared as a string literal in {relative_path}")
2684            });
2685            assert!(
2686                shipped.contains(&value),
2687                "OMEGA-DELTA-0016: {constant} in {relative_path} names {value:?}, \
2688                 which no shipped theme declares. Omega would fall back to a \
2689                 missing theme on that appearance. Shipped: {shipped:?}"
2690            );
2691            if constant == "DEFAULT_DARK_THEME" {
2692                dark_defaults.push((relative_path, value));
2693            }
2694        }
2695
2696        assert_eq!(
2697            dark_defaults[0].1, dark_defaults[1].1,
2698            "OMEGA-DELTA-0016: the two DEFAULT_DARK_THEME constants disagree \
2699             ({dark_defaults:?}); they are read by different crates and must \
2700             name the same theme."
2701        );
2702        assert_eq!(
2703            dark_defaults[0].1, "Aiur",
2704            "OMEGA-DELTA-0016: the dark default must be Aiur"
2705        );
2706    }
2707
2708    /// OMEGA-DELTA-0016. The theme values that actually decide are the shipped
2709    /// ones, not the constants.
2710    ///
2711    /// `default_themes_exist_in_shipped_assets` reads `DEFAULT_LIGHT_THEME` and
2712    /// `DEFAULT_DARK_THEME`, which `theme_settings` consults only when no
2713    /// settings layer supplies a theme selection at all.
2714    /// `assets/settings/default.json` is the base layer and always supplies
2715    /// one, so it is what ships. A rebase restoring `"One Light"` / `"One Dark"`
2716    /// there would have shipped One Dark with every check green: One Dark is
2717    /// still a shipped theme, and both constants would still have said Aiur.
2718    ///
2719    /// Both shipped settings files are read, because the theme divergence lives
2720    /// in two of them and only one had ever been looked at.
2721    #[test]
2722    fn the_shipped_theme_defaults_are_the_omega_themes() {
2723        let shipped = shipped_theme_names().expect("shipped themes parse");
2724
2725        for settings_file in SHIPPED_THEME_SETTINGS_FILES {
2726            let settings_path = repository_path(settings_file);
2727            let raw = std::fs::read_to_string(&settings_path)
2728                .unwrap_or_else(|error| panic!("cannot read {}: {error}", settings_path.display()));
2729            let settings: serde_json::Value = serde_json::from_str(&strip_jsonc(&raw))
2730                .unwrap_or_else(|error| {
2731                    panic!("cannot parse {}: {error}", settings_path.display())
2732                });
2733
2734            for (key, relative_path, constant) in [
2735                (
2736                    "theme.light",
2737                    "crates/settings_content/src/theme.rs",
2738                    "DEFAULT_LIGHT_THEME",
2739                ),
2740                (
2741                    "theme.dark",
2742                    "crates/settings_content/src/theme.rs",
2743                    "DEFAULT_DARK_THEME",
2744                ),
2745            ] {
2746                let configured = default_setting(&settings, key)
2747                    .and_then(serde_json::Value::as_str)
2748                    .unwrap_or_else(|| {
2749                        panic!("OMEGA-DELTA-0016: {settings_file} no longer names {key}")
2750                    });
2751                assert!(
2752                    shipped.contains(configured),
2753                    "OMEGA-DELTA-0016: {settings_file} sets {key} to \
2754                     {configured:?}, which no theme under assets/themes/ \
2755                     declares. Omega would resolve to a missing theme on that \
2756                     appearance. Shipped: {shipped:?}"
2757                );
2758
2759                let path = repository_path(relative_path);
2760                let source = std::fs::read_to_string(&path)
2761                    .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2762                let declared = string_constant(&source, constant).unwrap_or_else(|| {
2763                    panic!("{constant} is not declared as a string literal in {relative_path}")
2764                });
2765                assert_eq!(
2766                    configured, declared,
2767                    "OMEGA-DELTA-0016: {settings_file} sets {key} to \
2768                     {configured:?} but {constant} in {relative_path} is \
2769                     {declared:?}. These are two mechanisms for one decision — \
2770                     the setting decides, the constant is the fallback for an \
2771                     absent selection — and a rebase that reverts one and not \
2772                     the other ships the reverted one silently."
2773                );
2774            }
2775        }
2776    }
2777
2778    /// OMEGA-DELTA-0026. The shipped defaults still point away from Zed's
2779    /// production hosts.
2780    ///
2781    /// Four values from one commit, `9e585569cb`. They are asserted here as
2782    /// well as in `SERVICE_ISOLATION_TEST_PATH` because `cargo test -p
2783    /// omega_deltas` is what the registry tells a reader to run: a delta whose
2784    /// only value assertion lives in another crate is green under the command
2785    /// this file documents.
2786    #[test]
2787    fn the_service_isolation_defaults_are_still_the_omega_values() {
2788        let settings = default_settings().expect("default settings parse");
2789        for (key, upstream, omega) in SERVICE_ISOLATION_DEFAULTS {
2790            let expected: serde_json::Value =
2791                serde_json::from_str(omega).expect("the recorded Omega value is JSON");
2792            let actual = default_setting(&settings, key).unwrap_or_else(|| {
2793                panic!("OMEGA-DELTA-0026: {key} is absent from the shipped defaults")
2794            });
2795            assert_eq!(
2796                actual, &expected,
2797                "OMEGA-DELTA-0026: {key} must default to {omega}. Upstream Zed \
2798                 ships {upstream}, which points a running Omega at one of Zed's \
2799                 production hosts — for auto_update, at the one that can replace \
2800                 the binary."
2801            );
2802        }
2803    }
2804
2805    /// OMEGA-DELTA-0027. The Codex ACP executor is configured out of the box.
2806    ///
2807    /// Full Auto dispatches to `codex-acp`, so an empty `agent_servers` is not
2808    /// a neutral default here: it is Full Auto failing on a missing agent.
2809    #[test]
2810    fn codex_acp_is_configured_by_default() {
2811        let settings = default_settings().expect("default settings parse");
2812        let entry = default_setting(&settings, "agent_servers.codex-acp").unwrap_or_else(|| {
2813            panic!(
2814                "OMEGA-DELTA-0027: agent_servers no longer declares codex-acp. \
2815                 Upstream Zed ships agent_servers as {{}}; Full Auto is routed \
2816                 through this agent, so an empty map is a Full Auto run that \
2817                 cannot start."
2818            )
2819        });
2820        assert_eq!(
2821            entry.get("type").and_then(serde_json::Value::as_str),
2822            Some("registry"),
2823            "OMEGA-DELTA-0027: codex-acp must resolve from the ACP registry. \
2824             Any other type is a different agent than the one the endpoint \
2825             allow-list approved."
2826        );
2827    }
2828
2829    /// OMEGA-DELTA-0026 and OMEGA-DELTA-0027. The cited check still asserts
2830    /// what the registry says it asserts.
2831    ///
2832    /// Citing an existing check rather than duplicating it is right, and it
2833    /// adds a failure mode: the cited assertion can be deleted, and deleting an
2834    /// assertion turns a test green. This also requires the delta ID to appear
2835    /// beside it, so a reader who finds the assertion finds the reason.
2836    #[test]
2837    fn the_service_isolation_test_still_asserts_the_registered_defaults() {
2838        let path = repository_path(SERVICE_ISOLATION_TEST_PATH);
2839        let source = std::fs::read_to_string(&path)
2840            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2841        let compact = without_whitespace(&source);
2842
2843        for (delta, assertion) in PINNED_SERVICE_ISOLATION_ASSERTIONS {
2844            assert!(
2845                compact.contains(&without_whitespace(assertion)),
2846                "{delta}: {SERVICE_ISOLATION_TEST_PATH} no longer asserts \
2847                 {assertion:?}. That is the check the registry entry cites, and \
2848                 it reads as off-topic inside a test named for Zed service \
2849                 isolation, so it is the first line a tidy-up drops."
2850            );
2851            assert!(
2852                source.contains(delta),
2853                "{delta}: {SERVICE_ISOLATION_TEST_PATH} carries an assertion \
2854                 this delta cites but never names the delta, so a reader who \
2855                 finds the assertion cannot find the reason for it."
2856            );
2857        }
2858    }
2859
2860    /// OMEGA-DELTA-0028. The default icon theme is Omega's own, in both places
2861    /// that have to agree about its name.
2862    ///
2863    /// `configured_icon_theme` looks the settings value up in the registry, and
2864    /// the only built-in icon theme is registered under
2865    /// `DEFAULT_ICON_THEME_NAME`. Reverting one and not the other does not
2866    /// break anything visible — the lookup misses, the error is logged, the
2867    /// fallback renders — so the product keeps working while the settings file
2868    /// the owner opens names a competitor. Agreement is therefore the check,
2869    /// and the brand rule catches a revert of both.
2870    #[test]
2871    fn the_default_icon_theme_is_omegas() {
2872        let policy = brand_policy().expect("brand gate policy parses");
2873        let settings = default_settings().expect("default settings parse");
2874        let configured = default_setting(&settings, "icon_theme")
2875            .and_then(serde_json::Value::as_str)
2876            .expect("icon_theme is present in the shipped defaults");
2877
2878        let path = repository_path(DEFAULT_ICON_THEME_SOURCE);
2879        let source = std::fs::read_to_string(&path)
2880            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2881        let declared = string_constant(&source, "DEFAULT_ICON_THEME_NAME").unwrap_or_else(|| {
2882            panic!("DEFAULT_ICON_THEME_NAME is not a string literal in {DEFAULT_ICON_THEME_SOURCE}")
2883        });
2884
2885        assert_eq!(
2886            configured, declared,
2887            "OMEGA-DELTA-0028: the shipped icon_theme is {configured:?} but \
2888             DEFAULT_ICON_THEME_NAME in {DEFAULT_ICON_THEME_SOURCE} is \
2889             {declared:?}. The registry has exactly one built-in icon theme, \
2890             registered under the constant, so a settings value that disagrees \
2891             misses the lookup and falls back with a logged error rather than \
2892             failing."
2893        );
2894
2895        for (what, value) in [
2896            ("the shipped icon_theme setting", configured),
2897            ("DEFAULT_ICON_THEME_NAME", declared.as_str()),
2898        ] {
2899            let hits = brand_hits(value, &policy);
2900            assert!(
2901                hits.is_empty(),
2902                "OMEGA-DELTA-0028: {what} is {value:?}, which names {hits:?}. \
2903                 The icon theme name is rendered by the icon-theme selector and \
2904                 written into the settings file the owner opens, so it is \
2905                 product copy. base_keymap: \"Zed\" stays and is why this reads \
2906                 one key rather than scanning the file: that value names Zed's \
2907                 keybinding scheme, offered beside VS Code and JetBrains."
2908            );
2909        }
2910    }
2911
2912    /// OMEGA-DELTA-0017. No merged `Info.plist` value names a competitor.
2913    ///
2914    /// Every file in the fragment directory is merged into the packaged
2915    /// `Info.plist` by cargo-bundle, so the directory is walked rather than a
2916    /// list of known files, and every `<string>` is read rather than a list of
2917    /// known keys. `0.2.0-rc10` shipped thirteen of these signed and
2918    /// notarized, and macOS renders `NS*UsageDescription` inside its own
2919    /// permission dialog: the operating system told the owner that an
2920    /// application in Zed wanted the microphone.
2921    #[test]
2922    fn no_info_plist_value_names_a_competitor() {
2923        let policy = brand_policy().expect("brand gate policy parses");
2924        let directory = repository_path(
2925            policy["info_plist"]["fragment_dir"]
2926                .as_str()
2927                .expect("info_plist.fragment_dir is a string"),
2928        );
2929        let mut fragments: Vec<std::path::PathBuf> = std::fs::read_dir(&directory)
2930            .unwrap_or_else(|error| panic!("cannot read {}: {error}", directory.display()))
2931            .flatten()
2932            .map(|entry| entry.path())
2933            .filter(|path| path.is_file())
2934            .collect();
2935        fragments.sort();
2936        assert!(
2937            !fragments.is_empty(),
2938            "OMEGA-DELTA-0017: {} is empty, so this check would be vacuous",
2939            directory.display()
2940        );
2941
2942        let mut offenders: Vec<String> = Vec::new();
2943        for path in &fragments {
2944            let source = std::fs::read_to_string(path)
2945                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
2946            for (key, value) in plist_fragment_values(&source) {
2947                for hit in brand_hits(&value, &policy) {
2948                    offenders.push(format!("{}:{key} names {hit:?}: {value:?}", path.display()));
2949                }
2950            }
2951            // A brand name in a key, comment or attribute would not appear in
2952            // a dialog, but it is still a rebase restoring upstream identity.
2953            for hit in brand_hits(&without_elements(&source, "string"), &policy) {
2954                offenders.push(format!(
2955                    "{} names {hit:?} outside a <string> value",
2956                    path.display()
2957                ));
2958            }
2959        }
2960        assert!(
2961            offenders.is_empty(),
2962            "OMEGA-DELTA-0017: a competitor's name is back in the packaged \
2963             Info.plist:\n{}",
2964            offenders.join("\n")
2965        );
2966    }
2967
2968    /// The plist parser has to reach real values, or the check above passes on
2969    /// an empty list and reports a clean tree that was never read.
2970    #[test]
2971    fn the_plist_fragment_parser_reaches_real_values() {
2972        let policy = brand_policy().expect("brand gate policy parses");
2973        let path = repository_path("crates/zed/resources/info/Permissions.plist");
2974        let source = std::fs::read_to_string(&path).expect("Permissions.plist is readable");
2975        let values = plist_fragment_values(&source);
2976        let microphone = values
2977            .iter()
2978            .find(|(key, _)| key == "NSMicrophoneUsageDescription")
2979            .map(|(_, value)| value.clone())
2980            .expect("NSMicrophoneUsageDescription is present and keyed");
2981        assert!(
2982            microphone.contains("Omega"),
2983            "the microphone permission dialog must name Omega, got {microphone:?}"
2984        );
2985        assert!(
2986            !brand_hits(
2987                "An application in Zed wants to use your microphone.",
2988                &policy
2989            )
2990            .is_empty(),
2991            "the brand matcher must still recognise the string 0.2.0-rc10 shipped"
2992        );
2993        assert!(
2994            brand_hits(
2995                "The request was not authorized and is now normalized.",
2996                &policy
2997            )
2998            .is_empty(),
2999            "the brand matcher must not fire on 'authorized' or 'normalized'"
3000        );
3001    }
3002
3003    /// OMEGA-DELTA-0018. No shipped icon carries a competitor's name.
3004    ///
3005    /// `assets/icons` and the `IconName` enum are a bijection, enforced by the
3006    /// icons crate's own `test_all_icons_exist` and `test_no_dangling_icons`,
3007    /// so scanning both is a complete inventory of every icon that can ship.
3008    /// Both halves are checked because renaming only the file leaves the next
3009    /// rebase an identifier to restore the artwork under.
3010    #[test]
3011    fn no_shipped_icon_carries_a_competitor_name() {
3012        let policy = brand_policy().expect("brand gate policy parses");
3013        let icons = &policy["icons"];
3014        let allowed: std::collections::BTreeSet<String> = icons["third_party_allowances"]
3015            .as_object()
3016            .expect("icons.third_party_allowances is an object")
3017            .keys()
3018            .cloned()
3019            .collect();
3020        let stem_tokens: Vec<String> = policy_strings(&policy, "icons", "forbidden_stem_tokens");
3021        let variant_tokens: Vec<String> =
3022            policy_strings(&policy, "icons", "forbidden_variant_tokens");
3023        assert!(
3024            !stem_tokens.is_empty() && !variant_tokens.is_empty(),
3025            "OMEGA-DELTA-0018: an empty token list makes this check vacuous"
3026        );
3027
3028        let asset_dir = repository_path(icons["asset_dir"].as_str().expect("icons.asset_dir"));
3029        let mut stems: Vec<String> = std::fs::read_dir(&asset_dir)
3030            .unwrap_or_else(|error| panic!("cannot read {}: {error}", asset_dir.display()))
3031            .flatten()
3032            .map(|entry| entry.path())
3033            .filter(|path| path.extension().is_some_and(|extension| extension == "svg"))
3034            .filter_map(|path| path.file_stem()?.to_str().map(str::to_owned))
3035            .collect();
3036        stems.sort();
3037        assert!(
3038            !stems.is_empty(),
3039            "OMEGA-DELTA-0018: {} holds no icons, so this check would be vacuous",
3040            asset_dir.display()
3041        );
3042
3043        let mut offenders: Vec<String> = Vec::new();
3044        for stem in &stems {
3045            if allowed.contains(stem) {
3046                continue;
3047            }
3048            let lowered = stem.to_lowercase();
3049            if stem_tokens.iter().any(|token| lowered.contains(token)) {
3050                offenders.push(format!("asset {stem}.svg"));
3051            }
3052        }
3053
3054        let enum_source =
3055            repository_path(icons["enum_source"].as_str().expect("icons.enum_source"));
3056        let source = std::fs::read_to_string(&enum_source)
3057            .unwrap_or_else(|error| panic!("cannot read {}: {error}", enum_source.display()));
3058        let variants = icon_name_variants(&source);
3059        assert!(
3060            variants.len() > 100,
3061            "OMEGA-DELTA-0018: parsed {} IconName variants, which means the \
3062             enum parser broke and this check is vacuous",
3063            variants.len()
3064        );
3065        for variant in &variants {
3066            if allowed.contains(&icon_stem(variant)) {
3067                continue;
3068            }
3069            if variant_tokens.iter().any(|token| variant.contains(token)) {
3070                offenders.push(format!("IconName::{variant}"));
3071            }
3072        }
3073
3074        assert!(
3075            offenders.is_empty(),
3076            "OMEGA-DELTA-0018: a competitor's name is back in the shipped icon \
3077             set: {offenders:?}. Replace the artwork and the name, or record in \
3078             {} why it identifies somebody else's product.",
3079            BRAND_GATE_POLICY_PATH
3080        );
3081    }
3082
3083    /// OMEGA-DELTA-0018. The Omega marks are the artwork that was looked at.
3084    ///
3085    /// A name check cannot see a logo. Three Zed marks shipped on the status
3086    /// bar of `0.2.0-rc10` while every brand check on omega#16 passed, because
3087    /// all of them were string comparisons. Pinning the bytes is the only part
3088    /// of this delta that can tell one drawing from another, so swapping the
3089    /// artwork back under an Omega file name fails here.
3090    #[test]
3091    fn the_omega_marks_are_the_reviewed_artwork() {
3092        let policy = brand_policy().expect("brand gate policy parses");
3093        let marks = policy["icons"]["reviewed_marks"]
3094            .as_object()
3095            .expect("icons.reviewed_marks is an object");
3096        assert!(
3097            !marks.is_empty(),
3098            "OMEGA-DELTA-0018: no artwork is pinned, so nothing checks the marks"
3099        );
3100
3101        let mut offenders: Vec<String> = Vec::new();
3102        for (relative, expected) in marks {
3103            let expected = expected.as_str().expect("a pinned digest is a string");
3104            let path = repository_path(relative);
3105            let Ok(bytes) = std::fs::read(&path) else {
3106                offenders.push(format!("{relative} is missing"));
3107                continue;
3108            };
3109            let actual = sha256_hex(&bytes);
3110            if actual != expected {
3111                offenders.push(format!("{relative}: {actual} != {expected}"));
3112            }
3113        }
3114        assert!(
3115            offenders.is_empty(),
3116            "OMEGA-DELTA-0018: shipped Omega artwork is not the reviewed \
3117             artwork:\n{}\nIf the change is deliberate, look at the rendered \
3118             icon and update the pin in {} in the same commit.",
3119            offenders.join("\n"),
3120            BRAND_GATE_POLICY_PATH
3121        );
3122    }
3123
3124    /// OMEGA-DELTA-0022. No file `rust-embed` ships names a competitor.
3125    ///
3126    /// The inventory is the assets tree plus every directory an embed
3127    /// declaration points at, not a list of asset directories. `0.2.0-rc11`
3128    /// shipped `assets/images/zed_logo.svg` and `zed_x_copilot.svg` embedded in
3129    /// its signed binary while `OMEGA-DELTA-0018` reported `assets/icons/`
3130    /// clean — truthfully, because `assets/images/` was in no list.
3131    #[test]
3132    fn no_embedded_asset_carries_a_competitor_name() {
3133        let policy = brand_policy().expect("brand gate policy parses");
3134        let embedded = &policy["embedded_assets"];
3135        let allowed: std::collections::BTreeSet<String> = embedded["third_party_allowances"]
3136            .as_object()
3137            .expect("embedded_assets.third_party_allowances is an object")
3138            .keys()
3139            .cloned()
3140            .collect();
3141        let tokens: Vec<String> =
3142            policy_strings(&policy, "embedded_assets", "forbidden_path_tokens")
3143                .iter()
3144                .map(|token| token.to_lowercase())
3145                .collect();
3146        assert!(
3147            !tokens.is_empty(),
3148            "OMEGA-DELTA-0022: an empty token list makes this check vacuous"
3149        );
3150
3151        let folders = embed_folders();
3152        assert!(
3153            !folders.is_empty(),
3154            "OMEGA-DELTA-0022: no rust-embed #[folder] declarations were found, \
3155             so the inventory is no longer derived from what decides what ships"
3156        );
3157
3158        let inventory = embedded_asset_inventory();
3159        let minimum = usize::try_from(
3160            embedded["minimum_inventory"]
3161                .as_u64()
3162                .expect("embedded_assets.minimum_inventory is a number"),
3163        )
3164        .expect("minimum_inventory fits in usize");
3165        assert!(
3166            inventory.len() >= minimum,
3167            "OMEGA-DELTA-0022: only {} embeddable files were found, below the \
3168             {minimum} floor. The walk broke and this check is reporting green \
3169             about nothing.",
3170            inventory.len()
3171        );
3172
3173        let offenders: Vec<&String> = inventory
3174            .iter()
3175            .filter(|relative| !allowed.contains(*relative))
3176            .filter(|relative| {
3177                let lowered = relative.to_lowercase();
3178                tokens.iter().any(|token| lowered.contains(token))
3179            })
3180            .collect();
3181        assert!(
3182            offenders.is_empty(),
3183            "OMEGA-DELTA-0022: a competitor's name is back in a directory \
3184             rust-embed ships: {offenders:?}. Replace the artwork and the file \
3185             name, or record in {BRAND_GATE_POLICY_PATH} why it identifies \
3186             somebody else's product."
3187        );
3188    }
3189
3190    /// OMEGA-DELTA-0022. No enum that names a shipped asset names a competitor.
3191    ///
3192    /// The enums are discovered from the source. Listing them is what left
3193    /// `VectorName` outside `OMEGA-DELTA-0018` while `IconName` was inside it,
3194    /// which is the entire reason `VectorName::ZedLogo` reached rc11.
3195    #[test]
3196    fn no_asset_name_enum_carries_a_competitor_name() {
3197        let policy = brand_policy().expect("brand gate policy parses");
3198        let section = &policy["asset_name_enums"];
3199        let allowed: std::collections::BTreeSet<String> = section["third_party_allowances"]
3200            .as_object()
3201            .expect("asset_name_enums.third_party_allowances is an object")
3202            .keys()
3203            .cloned()
3204            .collect();
3205        let tokens: Vec<String> =
3206            policy_strings(&policy, "asset_name_enums", "forbidden_variant_tokens");
3207        assert!(
3208            !tokens.is_empty(),
3209            "OMEGA-DELTA-0022: an empty token list makes this check vacuous"
3210        );
3211
3212        let discovered = asset_name_enums();
3213        for required in policy_strings(&policy, "asset_name_enums", "required_discoveries") {
3214            assert!(
3215                discovered.contains_key(&required),
3216                "OMEGA-DELTA-0022: the asset-name-enum discovery no longer finds \
3217                 {required}. The parser broke and this check is reporting green \
3218                 about nothing. Found: {:?}",
3219                discovered.keys().collect::<Vec<_>>()
3220            );
3221        }
3222
3223        let mut offenders: Vec<String> = Vec::new();
3224        for (name, variants) in &discovered {
3225            assert!(
3226                variants.len() >= 2,
3227                "OMEGA-DELTA-0022: {name} parsed as {} variants",
3228                variants.len()
3229            );
3230            for variant in variants {
3231                let label = format!("{name}::{variant}");
3232                if allowed.contains(&label) {
3233                    continue;
3234                }
3235                if tokens.iter().any(|token| variant.contains(token)) {
3236                    offenders.push(label);
3237                }
3238            }
3239        }
3240        assert!(
3241            offenders.is_empty(),
3242            "OMEGA-DELTA-0022: an identifier that resolves to a shipped asset \
3243             names a competitor: {offenders:?}. Renaming the file without \
3244             renaming the identifier leaves the next rebase a name to restore \
3245             the artwork under."
3246        );
3247    }
3248
3249    /// OMEGA-DELTA-0022. No command-palette label names a competitor.
3250    ///
3251    /// The palette renders `namespace: action name` for every registered
3252    /// action. `0.2.0-rc11` offered `zed: about`, `zed: quit` and
3253    /// `zed: get merch` while the compatibility allow-list recorded that
3254    /// namespace as "not user-facing product copy". The targets were already
3255    /// correct; the label was the defect, and nothing had ever read an action
3256    /// declaration.
3257    #[test]
3258    fn no_command_palette_label_names_a_competitor() {
3259        let policy = brand_policy().expect("brand gate policy parses");
3260        let section = &policy["actions"];
3261        let declarations = action_declarations();
3262        let minimum = usize::try_from(
3263            section["minimum_inventory"]
3264                .as_u64()
3265                .expect("actions.minimum_inventory is a number"),
3266        )
3267        .expect("minimum_inventory fits in usize");
3268        assert!(
3269            declarations.len() >= minimum,
3270            "OMEGA-DELTA-0022: only {} action declarations were parsed, below \
3271             the {minimum} floor; this check is vacuous",
3272            declarations.len()
3273        );
3274
3275        let labels: std::collections::BTreeSet<String> = declarations
3276            .iter()
3277            .map(|(namespace, name, _)| format!("{namespace}::{name}"))
3278            .collect();
3279        for required in policy_strings(&policy, "actions", "required_actions") {
3280            assert!(
3281                labels.contains(&required),
3282                "OMEGA-DELTA-0022: {required} is not in the parsed action set, \
3283                 so the parser is not reading the declarations it claims to"
3284            );
3285        }
3286
3287        let allowed: std::collections::BTreeSet<String> = section["third_party_allowances"]
3288            .as_object()
3289            .expect("actions.third_party_allowances is an object")
3290            .keys()
3291            .cloned()
3292            .collect();
3293        let namespace_tokens: Vec<String> =
3294            policy_strings(&policy, "actions", "forbidden_namespace_tokens")
3295                .iter()
3296                .map(|token| token.to_lowercase())
3297                .collect();
3298        let name_tokens: Vec<String> = policy_strings(&policy, "actions", "forbidden_name_tokens");
3299        assert!(
3300            !namespace_tokens.is_empty() && !name_tokens.is_empty(),
3301            "OMEGA-DELTA-0022: an empty token list makes this check vacuous"
3302        );
3303
3304        let mut offenders: Vec<String> = Vec::new();
3305        for (namespace, name, file) in &declarations {
3306            if allowed.contains(&format!("{namespace}::{name}")) {
3307                continue;
3308            }
3309            let lowered = namespace.to_lowercase();
3310            if namespace_tokens.iter().any(|token| lowered.contains(token)) {
3311                offenders.push(format!("{namespace}: … (declared in {file})"));
3312            }
3313            if name_tokens.iter().any(|token| name.contains(token)) {
3314                offenders.push(format!("{namespace}::{name} (declared in {file})"));
3315            }
3316        }
3317        offenders.sort();
3318        offenders.dedup();
3319        assert!(
3320            offenders.is_empty(),
3321            "OMEGA-DELTA-0022: the command palette would offer a competitor's \
3322             name to the owner: {offenders:?}. An action namespace is a \
3323             user-facing label, not an internal seam. Rename it and keep the \
3324             old name as a deprecated alias so existing keymaps resolve."
3325        );
3326    }
3327
3328    /// OMEGA-DELTA-0022. Renaming an action keeps existing keymaps working.
3329    ///
3330    /// The built-in keymap is loaded and unwrapped at startup, so an
3331    /// unresolvable action is a hard panic before any window opens — the same
3332    /// shape that shipped in `0.2.0-rc6`. Every `zed::` name the namespace
3333    /// rename retired therefore has to survive as a deprecated alias.
3334    #[test]
3335    fn the_retired_action_namespace_still_resolves() {
3336        let aliases = deprecated_action_aliases();
3337        for retired in [
3338            "zed::About",
3339            "zed::Quit",
3340            "zed::GetMerch",
3341            "zed::OpenSettings",
3342            "zed::NoAction",
3343            "zed::Unbind",
3344        ] {
3345            assert!(
3346                aliases.contains(retired),
3347                "OMEGA-DELTA-0022: {retired} is not a deprecated alias any more. \
3348                 An existing user keymap naming it would stop resolving, and an \
3349                 unresolvable action in the built-in keymap panics at startup."
3350            );
3351        }
3352
3353        let keymaps = repository_path("assets/keymaps");
3354        let mut offenders = Vec::new();
3355        for_each_source_file(&keymaps, &["json"], |path, source| {
3356            if source.contains("\"zed::") {
3357                offenders.push(path.display().to_string());
3358            }
3359        });
3360        assert!(
3361            offenders.is_empty(),
3362            "OMEGA-DELTA-0022: a shipped keymap still dispatches a retired \
3363             `zed::` action: {offenders:?}. Aliases exist for the owner's own \
3364             keymap, not for ours."
3365        );
3366    }
3367
3368    /// OMEGA-DELTA-0022. A blocked public claim appears nowhere in the tree.
3369    ///
3370    /// The compatibility allow-list has recorded `blocked` claims since the
3371    /// identity work began, but nothing read them back against the source, so
3372    /// `Welcome to Zed` and `About Zed` were listed while
3373    /// `Use GitHub Copilot in Zed` shipped in `0.2.0-rc11` as a window title,
3374    /// as a modal `Headline`, and beside the Zed x Copilot lockup — one
3375    /// surface, three presentations, in no entry at all.
3376    #[test]
3377    fn blocked_public_copy_appears_nowhere_in_the_tree() {
3378        let path = repository_path(COMPATIBILITY_ALLOWLIST_PATH);
3379        let raw = std::fs::read_to_string(&path)
3380            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
3381        let allowlist: serde_json::Value =
3382            serde_json::from_str(&raw).expect("compatibility allow-list parses");
3383        let blocked: Vec<String> = allowlist["entries"]
3384            .as_array()
3385            .expect("the allow-list has entries")
3386            .iter()
3387            .filter(|entry| entry["disposition"] == "blocked")
3388            .filter_map(|entry| entry["match"].as_str())
3389            .map(str::to_owned)
3390            .collect();
3391        assert!(
3392            blocked.len() >= 4,
3393            "OMEGA-DELTA-0022: only {} blocked claims are recorded, so this \
3394             check has almost nothing to enforce",
3395            blocked.len()
3396        );
3397        assert!(
3398            blocked
3399                .iter()
3400                .any(|claim| claim == "Use GitHub Copilot in Zed"),
3401            "OMEGA-DELTA-0022: the claim that shipped in rc11 must stay recorded \
3402             as blocked, or the next lane has no record that it was a defect"
3403        );
3404
3405        let corpus: std::collections::BTreeSet<&str> =
3406            BLOCKED_COPY_CORPUS.iter().copied().collect();
3407        for relative in &corpus {
3408            assert!(
3409                repository_path(relative).is_file(),
3410                "OMEGA-DELTA-0022: exempt corpus file {relative} does not exist, \
3411                 so the exemption is hiding nothing and should be deleted"
3412            );
3413        }
3414
3415        let mut offenders: Vec<String> = Vec::new();
3416        for directory in ["crates", "assets"] {
3417            let root = repository_path(directory);
3418            for_each_source_file(&root, &["rs", "json", "md", "toml"], |path, source| {
3419                let normalized = normalize_path(path);
3420                let relative = normalized
3421                    .strip_prefix(normalize_path(&repository_path(".")))
3422                    .map_or_else(
3423                        |_| normalized.display().to_string(),
3424                        |tail| tail.display().to_string(),
3425                    );
3426                if corpus.contains(relative.as_str()) {
3427                    return;
3428                }
3429                for claim in &blocked {
3430                    if source.contains(claim.as_str()) {
3431                        offenders.push(format!("{relative}: {claim:?}"));
3432                    }
3433                }
3434            });
3435        }
3436        offenders.sort();
3437        assert!(
3438            offenders.is_empty(),
3439            "OMEGA-DELTA-0022: a public product claim the allow-list records as \
3440             blocked is back in the tree:\n{}",
3441            offenders.join("\n")
3442        );
3443    }
3444
3445    /// OMEGA-DELTA-0022. The component preview is not in the release palette.
3446    ///
3447    /// It renders every component's developer-authored `preview` fn, which is
3448    /// not reviewed as product copy or product artwork. It shipped in the
3449    /// release palette of `0.2.0-rc11` with no dev gate — unlike
3450    /// `dev::ToggleInspector` and `dev::ResetOnboarding`, both of which are
3451    /// gated — and opening it drew the Zed `Z` through the `Vector` preview.
3452    #[test]
3453    fn the_component_preview_is_gated_to_dev_builds() {
3454        let path = repository_path("crates/component_preview/src/component_preview.rs");
3455        let source = std::fs::read_to_string(&path)
3456            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
3457        for required in [
3458            "#[cfg(not(debug_assertions))]",
3459            "hide_action_types",
3460            "OpenComponentPreview",
3461        ] {
3462            assert!(
3463                source.contains(required),
3464                "OMEGA-DELTA-0022: {} no longer contains {required:?}, so a \
3465                 release build would offer `workspace: open component preview` \
3466                 and render unreviewed developer previews to the owner.",
3467                path.display()
3468            );
3469        }
3470    }
3471
3472    /// OMEGA-DELTA-0017 and OMEGA-DELTA-0018. The packaging path runs the gate.
3473    ///
3474    /// The source checks above cannot see a packaging regression, and the
3475    /// packaged gate cannot run if nothing calls it. `0.2.0-rc6` hard-panicked
3476    /// at startup on assets that `cargo check --workspace` had been happy with
3477    /// all along, which is the same shape of gap. This asserts the wiring
3478    /// itself, so deleting the call from the bundle script fails here.
3479    #[test]
3480    fn the_packaging_path_runs_the_brand_gate() {
3481        let verifier = repository_path(BRAND_VERIFIER_PATH);
3482        assert!(
3483            verifier.is_file(),
3484            "OMEGA-DELTA-0017: {BRAND_VERIFIER_PATH} is missing"
3485        );
3486        #[cfg(unix)]
3487        {
3488            use std::os::unix::fs::PermissionsExt as _;
3489            let mode = std::fs::metadata(&verifier)
3490                .expect("brand verifier metadata")
3491                .permissions()
3492                .mode();
3493            assert!(
3494                mode & 0o111 != 0,
3495                "OMEGA-DELTA-0017: {BRAND_VERIFIER_PATH} is not executable, so \
3496                 the packaging path cannot run it"
3497            );
3498        }
3499
3500        let bundle = repository_path(RC_BUNDLE_SCRIPT_PATH);
3501        let script = std::fs::read_to_string(&bundle)
3502            .unwrap_or_else(|error| panic!("cannot read {}: {error}", bundle.display()));
3503        for required in [
3504            "verify_source_brand\n",
3505            "verify_packaged_brand \"${app_path}\"\n",
3506            BRAND_VERIFIER_PATH,
3507            BRAND_GATE_POLICY_PATH,
3508        ] {
3509            assert!(
3510                script.contains(required),
3511                "OMEGA-DELTA-0017: {RC_BUNDLE_SCRIPT_PATH} no longer contains \
3512                 {required:?}. A candidate could be packaged without the brand \
3513                 gate ever reading its Info.plist or its icons."
3514            );
3515        }
3516    }
3517
3518    /// OMEGA-DELTA-0023. The packaging path staples the application.
3519    ///
3520    /// `script/bundle-omega-rc` stapled the DMG only. A DMG ticket covers the
3521    /// disk image the owner throws away; it does not travel with the
3522    /// application that ends up in `/Applications`, so
3523    /// `stapler validate /Applications/Omega.app` reported no ticket and
3524    /// Gatekeeper acceptance could rest on an online lookup with Apple —
3525    /// which cannot prove the offline first start omega#16 requires.
3526    ///
3527    /// The order matters as much as the call: the app has to be stapled
3528    /// *before* the disk image is built, or the DMG is assembled from an
3529    /// unstapled bundle and the ticket never reaches the installed product.
3530    #[test]
3531    fn the_packaging_path_staples_the_application() {
3532        let path = repository_path(RC_BUNDLE_SCRIPT_PATH);
3533        let script = std::fs::read_to_string(&path)
3534            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
3535
3536        for required in [
3537            "stapler\" staple \"${app_path}\"",
3538            "stapler\" validate \"${app_path}\"",
3539            "stapler\" validate \"${DMG_PATH}\"",
3540            "stapler\" validate \"${stapled_app_path}\"",
3541            "OMEGA_RC_NOTARIZATION_APP_STAPLED",
3542            "notarization.app_stapled is required",
3543        ] {
3544            assert!(
3545                script.contains(required),
3546                "OMEGA-DELTA-0023: {RC_BUNDLE_SCRIPT_PATH} no longer contains \
3547                 {required:?}. A candidate could be published with a stapled \
3548                 disk image and an unstapled application, which is exactly the \
3549                 state that blocks the offline-start proof on omega#16."
3550            );
3551        }
3552
3553        let staple_app = script
3554            .find("stapler\" staple \"${app_path}\"")
3555            .expect("the app staple call was asserted above");
3556        let create_dmg = script
3557            .find("hdiutil create")
3558            .expect("the bundle script creates a disk image");
3559        assert!(
3560            staple_app < create_dmg,
3561            "OMEGA-DELTA-0023: the disk image is built before the application is \
3562             stapled, so it would be assembled from an unstapled bundle and the \
3563             ticket would never reach /Applications."
3564        );
3565
3566        let record = repository_path("crates/app_identity/fixtures/release_record_v1.json");
3567        let fixture = std::fs::read_to_string(&record)
3568            .unwrap_or_else(|error| panic!("cannot read {}: {error}", record.display()));
3569        let parsed: serde_json::Value =
3570            serde_json::from_str(&fixture).expect("release record fixture parses");
3571        assert!(
3572            parsed["notarization"].get("app_stapled").is_some(),
3573            "OMEGA-DELTA-0023: the release record must carry app_stapled \
3574             separately from stapled, or the two get conflated again"
3575        );
3576    }
3577
3578    /// OMEGA-DELTA-0024. The first-party identity is Omega Agent everywhere a
3579    /// user can select, configure, or inspect the native executor.
3580    #[test]
3581    fn the_first_party_agent_identity_is_omega_agent() {
3582        let agent_path = repository_path("crates/agent/src/agent.rs");
3583        let agent_source = std::fs::read_to_string(&agent_path)
3584            .unwrap_or_else(|error| panic!("cannot read {}: {error}", agent_path.display()));
3585        assert!(
3586            agent_source.contains(r#"AgentId::new("Omega Agent")"#),
3587            "OMEGA-DELTA-0024: the native AgentId must be Omega Agent"
3588        );
3589
3590        let agent_ui_path = repository_path("crates/agent_ui/src/agent_ui.rs");
3591        let agent_ui_source = std::fs::read_to_string(&agent_ui_path)
3592            .unwrap_or_else(|error| panic!("cannot read {}: {error}", agent_ui_path.display()));
3593        for required in [
3594            r#"Self::NativeAgent => "Omega Agent".into()"#,
3595            "Self::NativeAgent => Some(IconName::OmegaAgent)",
3596        ] {
3597            assert!(
3598                agent_ui_source.contains(required),
3599                "OMEGA-DELTA-0024: the native Agent projection lost {required:?}"
3600            );
3601        }
3602
3603        for (relative_path, required) in [
3604            (
3605                "crates/agent_ui/src/agent_panel.rs",
3606                r#"ContextMenuEntry::new("Omega Agent")"#,
3607            ),
3608            (
3609                "crates/ui/src/components/ai/agent_setup_button.rs",
3610                r#".name("Omega Agent")"#,
3611            ),
3612            (
3613                "crates/eval_cli/src/headless.rs",
3614                r#""Omega Agent CLI/{} ({}; {})""#,
3615            ),
3616        ] {
3617            let path = repository_path(relative_path);
3618            let source = std::fs::read_to_string(&path)
3619                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
3620            assert!(
3621                source.contains(required),
3622                "OMEGA-DELTA-0024: {relative_path} lost {required:?}"
3623            );
3624        }
3625
3626        // Read from the policy rather than spelling the symbol here. A
3627        // tree-wide rename would rewrite this test's own literal along with
3628        // the code it guards, and the check would rename itself into
3629        // agreement. That is not hypothetical: it is what happened the first
3630        // time this arm was falsified.
3631        let policy = brand_policy().expect("brand gate policy parses");
3632        let symbol = policy["first_party_agent"]["symbol"]
3633            .as_str()
3634            .expect("first_party_agent.symbol is a string");
3635        assert!(
3636            agent_source.contains(&format!("pub static {symbol}")),
3637            "OMEGA-DELTA-0024: the identity symbol must be {symbol}. Renaming \
3638             only the string it holds leaves the next upstream rebase an \
3639             obvious symbol to restore Zed's identity under"
3640        );
3641    }
3642
3643    /// OMEGA-DELTA-0024. No phrasing of the first-party agent names Zed.
3644    ///
3645    /// Separate from the pins above because it is a different kind of failure.
3646    /// Those say the identity is present; this says the old one is gone, which
3647    /// is the half that `0.2.0-rc10` got wrong: an evidence table truthfully
3648    /// reported a clean binary while 13 Zed strings shipped in the signed
3649    /// `Info.plist`, because the scan knew exactly three literals.
3650    ///
3651    /// So this matches a phrase family from `script/omega-brand-gate.json`,
3652    /// not one string, and the references we deliberately keep are named there
3653    /// with a reason rather than skipped silently. Zed still exists; it is
3654    /// just not us.
3655    #[test]
3656    fn no_phrasing_presents_zed_as_the_first_party_agent() {
3657        let policy = brand_policy().expect("brand gate policy parses");
3658        let phrases = policy_strings(&policy, "first_party_agent", "phrases");
3659        let symbols = policy_strings(&policy, "first_party_agent", "symbols");
3660        let roots = policy_strings(&policy, "first_party_agent", "scan_roots");
3661        let extensions = policy_strings(&policy, "first_party_agent", "extensions");
3662        assert!(
3663            !phrases.is_empty() && !symbols.is_empty() && !roots.is_empty(),
3664            "OMEGA-DELTA-0024: {BRAND_GATE_POLICY_PATH} declares no phrases, \
3665             symbols, or roots, so this gate checks nothing"
3666        );
3667
3668        let allowances = policy["first_party_agent"]["allowances"]
3669            .as_object()
3670            .expect("first_party_agent.allowances is an object");
3671        for relative in allowances.keys() {
3672            assert!(
3673                repository_path(relative).exists(),
3674                "OMEGA-DELTA-0024: allowance for {relative} outlived the file. \
3675                 A stale allowance is a hole nobody is watching"
3676            );
3677        }
3678
3679        let stems = policy_strings(&policy, "first_party_agent", "forbidden_path_stems");
3680        assert!(
3681            !stems.is_empty(),
3682            "OMEGA-DELTA-0024: no forbidden path stems, so a file could carry \
3683             the old identity in its name"
3684        );
3685
3686        let extensions: Vec<&str> = extensions.iter().map(String::as_str).collect();
3687        let repository_root = repository_path(".");
3688        let mut offenders: Vec<String> = Vec::new();
3689        for root in &roots {
3690            for_each_source_file(&repository_path(root), &extensions, |path, source| {
3691                let relative = path
3692                    .strip_prefix(&repository_root)
3693                    .unwrap_or(path)
3694                    .display()
3695                    .to_string();
3696
3697                // The name before the contents. A renamed file reads as clean
3698                // either way, so a content scan cannot tell `zed-agent.md`
3699                // from `omega-agent.md`. Falsifying this delta found exactly
3700                // that: restoring the old file name passed everything.
3701                let stem = path
3702                    .file_stem()
3703                    .and_then(std::ffi::OsStr::to_str)
3704                    .unwrap_or_default()
3705                    .to_lowercase();
3706                for forbidden in &stems {
3707                    if stem.contains(&forbidden.to_lowercase()) {
3708                        offenders.push(format!("{relative}: file name {forbidden:?}"));
3709                    }
3710                }
3711
3712                if allowances.contains_key(&relative) {
3713                    return;
3714                }
3715                let lowercased = source.to_lowercase();
3716                for phrase in &phrases {
3717                    if lowercased.contains(&phrase.to_lowercase()) {
3718                        offenders.push(format!("{relative}: {phrase:?}"));
3719                    }
3720                }
3721                for symbol in &symbols {
3722                    if source.contains(symbol) {
3723                        offenders.push(format!("{relative}: {symbol:?}"));
3724                    }
3725                }
3726            });
3727        }
3728
3729        assert!(
3730            offenders.is_empty(),
3731            "OMEGA-DELTA-0024: Zed is presented as the first-party agent \
3732             again. Rename it, or — only if the text names Zed's own product \
3733             or Zed's history the way ai_zed.svg does — add an allowance with \
3734             a reason to {BRAND_GATE_POLICY_PATH}:\n{}",
3735            offenders.join("\n")
3736        );
3737    }
3738
3739    /// OMEGA-DELTA-0024. The inherited telemetry id is not a product identity.
3740    ///
3741    /// `NativeAgentConnection::telemetry_id` still reports `"zed"`, because it
3742    /// keys inherited analytics and rewriting it would silently break the
3743    /// series rather than rename anything a user sees. The rule that matters
3744    /// is that it stays out of the identity path: the product name comes from
3745    /// `OMEGA_AGENT_ID`, and the two are not allowed to become the same value.
3746    #[test]
3747    fn the_inherited_telemetry_id_is_not_the_product_identity() {
3748        let policy = brand_policy().expect("brand gate policy parses");
3749        let identity = policy["first_party_agent"]["identity"]
3750            .as_str()
3751            .expect("first_party_agent.identity is a string");
3752
3753        let path = repository_path("crates/agent/src/agent.rs");
3754        let source = std::fs::read_to_string(&path)
3755            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
3756        let telemetry_body = source
3757            .split_once("fn telemetry_id(&self) -> SharedString {")
3758            .map(|(_, rest)| rest.split_once('}').map_or(rest, |(body, _)| body))
3759            .expect("the native connection reports a telemetry id");
3760
3761        assert!(
3762            telemetry_body.contains(r#""zed""#),
3763            "OMEGA-DELTA-0024: the native telemetry id is no longer the \
3764             inherited \"zed\" key. Changing it breaks the analytics series \
3765             without renaming anything a user sees"
3766        );
3767        assert!(
3768            !telemetry_body.contains(identity),
3769            "OMEGA-DELTA-0024: the inherited telemetry id now reports \
3770             {identity:?}, which presents an inherited analytics key as an \
3771             OpenAgents service identity"
3772        );
3773    }
3774
3775    /// An ID that names two entries names none of them.
3776    ///
3777    /// `the_registry_and_the_checks_agree` compares sets, so a duplicate is
3778    /// invisible to it. Two lanes allocating numbers at the same time produced
3779    /// exactly that: two `OMEGA-DELTA-0010` entries and two `0011` entries,
3780    /// which shipped uncaught.
3781    /// OMEGA-DELTA-0019. Upstream Zed answers an empty window with
3782    /// `Editor::new_file`. Omega answers it with the agent.
3783    ///
3784    /// Checked in both directions, because either half alone is weak: the
3785    /// absence of `Editor::new_file` would also pass if somebody deleted the
3786    /// startup path entirely, and the presence of `open_front_door` would also
3787    /// pass if it were added beside the buffer rather than instead of it.
3788    #[test]
3789    fn a_fresh_window_opens_on_the_agent() {
3790        let path = repository_path("crates/zed/src/main.rs");
3791        let source = std::fs::read_to_string(&path).expect("zed main is readable");
3792
3793        assert!(
3794            !source.contains("Editor::new_file("),
3795            "{} calls Editor::new_file again. Upstream Zed opens an empty \
3796             untitled buffer on a window with nothing to restore; Omega opens \
3797             the agent front door (OMEGA-DELTA-0019).",
3798            path.display()
3799        );
3800
3801        let openings = source.matches("AgentPanel::open_front_door(").count();
3802        assert_eq!(
3803            openings,
3804            2,
3805            "{} reaches the front door {openings} time(s); \
3806             restore_or_create_workspace has two no-restorable-session paths \
3807             and both must land there (OMEGA-DELTA-0019).",
3808            path.display()
3809        );
3810
3811        // The launchpad behaviour opens no content at all upstream, and Omega
3812        // does not override a setting the user set.
3813        assert!(
3814            source.contains("RestoreOnStartupBehavior::Launchpad => {}"),
3815            "{} no longer leaves the launchpad startup behaviour alone \
3816             (OMEGA-DELTA-0019).",
3817            path.display()
3818        );
3819    }
3820
3821    /// OMEGA-DELTA-0020. Full Auto is a surface of the chat panel now.
3822    ///
3823    /// The owner asked for the dock panel to go. The failure this guards is a
3824    /// rebase or a well-meaning cleanup putting it back — or, worse, removing
3825    /// the dock panel without moving its two actions, which would silently
3826    /// break a user keybinding rather than fail anything.
3827    #[test]
3828    fn full_auto_is_folded_into_the_chat_panel() {
3829        let zed_path = repository_path("crates/zed/src/zed.rs");
3830        let zed = std::fs::read_to_string(&zed_path).expect("zed.rs is readable");
3831        assert!(
3832            !zed.contains("FullAutoPanel"),
3833            "{} registers a Full Auto dock panel again. The owner asked for \
3834             Full Auto to be folded into the Omega chat UI \
3835             (OMEGA-DELTA-0020).",
3836            zed_path.display()
3837        );
3838
3839        let panel_path = repository_path("crates/agent_ui/src/agent_panel.rs");
3840        let panel = std::fs::read_to_string(&panel_path).expect("agent panel is readable");
3841        assert!(
3842            panel.contains("FullAutoPanel::new("),
3843            "{} no longer constructs the Full Auto surface. Folding it in is \
3844             what makes the dock panel's removal a move rather than a deletion \
3845             (OMEGA-DELTA-0020).",
3846            panel_path.display()
3847        );
3848
3849        // Both actions outlived their panel on purpose: a user keymap may name
3850        // them, and the fold moves where Full Auto lives without taking a
3851        // binding away. An unanswered action is a silent no-op, not an error,
3852        // which is exactly why this needs a test.
3853        for action in ["OpenLauncher", "ToggleFullAutoFocus"] {
3854            assert!(
3855                panel.contains(&format!("_: &{action},")),
3856                "{} does not answer the {action} action. It was answered by \
3857                 the retired full_auto_ui::init, so dropping it here makes a \
3858                 keybinding silently do nothing (OMEGA-DELTA-0020).",
3859                panel_path.display()
3860            );
3861        }
3862
3863        let lib_path = repository_path("crates/full_auto_ui/src/full_auto_ui.rs");
3864        let lib = std::fs::read_to_string(&lib_path).expect("full_auto_ui is readable");
3865        assert!(
3866            !lib.contains("pub use panel::{init"),
3867            "{} exports a panel init again; there is no dock panel to \
3868             register (OMEGA-DELTA-0020).",
3869            lib_path.display()
3870        );
3871    }
3872
3873    /// OMEGA-DELTA-0020, and owner gate 8 behind it.
3874    ///
3875    /// Only an explicit human action may start Full Auto authority. Folding
3876    /// the surface into chat moves where that action lives; it must not add a
3877    /// second way to reach it. The strongest mechanical form of that is a call
3878    /// count: `start_run` is reached from exactly one place in the GPUI tree,
3879    /// and that place is a click handler.
3880    ///
3881    /// This deliberately scans every crate rather than the one file, because
3882    /// the failure worth catching is a *new* caller somewhere else — a tool, a
3883    /// slash command, a restored draft — not a change to the known one.
3884    ///
3885    /// Two distinct calls are counted, because they are two distinct hazards.
3886    /// `guard.start_run(` is the supervisor call that creates run authority; a
3887    /// second one of those means a second way to create a run. `this.start_run(`
3888    /// is the UI entry into it; a second one of those means a second gesture
3889    /// can reach the first.
3890    #[test]
3891    fn only_a_click_listener_starts_a_full_auto_run() {
3892        let crates = repository_path("crates");
3893        let mut authority: Vec<(String, String)> = Vec::new();
3894        let mut entries: Vec<(String, String)> = Vec::new();
3895        for_each_source_file(&crates, &["rs"], |path, source| {
3896            // `repository_path` yields `…/crates/omega_deltas/../../crates/x`,
3897            // so a plain `contains` would see `omega_deltas` in every path.
3898            // The crate-relative tail is what identifies the file.
3899            let display = path
3900                .display()
3901                .to_string()
3902                .rsplit("crates/")
3903                .next()
3904                .unwrap_or_default()
3905                .to_owned();
3906            // `omega_effectd` declares and transports the call; it does not
3907            // decide to make one. This file is the check itself, and matching
3908            // its own needles would make the count meaningless.
3909            if display.starts_with("omega_effectd/") || display.starts_with("omega_deltas/") {
3910                return;
3911            }
3912            for line in source.lines() {
3913                let line = line.trim();
3914                if line.contains("guard.start_run(") {
3915                    authority.push((display.clone(), line.to_owned()));
3916                } else if line.contains(".start_run(") {
3917                    entries.push((display.clone(), line.to_owned()));
3918                }
3919            }
3920        });
3921
3922        assert_eq!(
3923            authority.len(),
3924            1,
3925            "Full Auto run authority is created from {} place(s): \
3926             {authority:#?}. `omega-effectd` is the sole run authority and the \
3927             launch surface is the sole way to ask it for a run \
3928             (OMEGA-DELTA-0020).",
3929            authority.len()
3930        );
3931        assert!(
3932            authority[0].0.ends_with("full_auto_ui/src/panel.rs"),
3933            "Full Auto's run-start moved to {}. It belongs on the launch \
3934             surface (OMEGA-DELTA-0020).",
3935            authority[0].0
3936        );
3937
3938        assert_eq!(
3939            entries.len(),
3940            1,
3941            "Full Auto's run-start is reachable from {} place(s): {entries:#?}. \
3942             Owner gate 8 admits exactly one, and it is a human clicking Start \
3943             (OMEGA-DELTA-0020).",
3944            entries.len()
3945        );
3946        assert_eq!(
3947            entries[0].1, ".on_click(cx.listener(|this, _, _, cx| this.start_run(cx))),",
3948            "Full Auto's run-start is no longer behind a click. Reaching the \
3949             launch surface is one human act and starting the run is a second; \
3950             collapsing them, or moving the start behind an action, a timer, or \
3951             a message handler, is what owner gate 8 forbids \
3952             (OMEGA-DELTA-0020)."
3953        );
3954    }
3955
3956    /// OMEGA-DELTA-0031. Every brand-bearing prose literal is classified.
3957    ///
3958    /// `OMEGA-DELTA-0022` named this class and could not close it. The string
3959    /// rule it shipped enforces the compatibility allow-list's `blocked`
3960    /// claims, which is a written-down denylist: a *new* sentence naming a
3961    /// competitor as the product passes until somebody remembers to add it.
3962    /// That is exactly how "Use GitHub Copilot in Zed" reached a signed,
3963    /// notarized `0.2.0-rc11`, and why the signed, notarized `0.2.0-rc13`
3964    /// still told the user "Click 'Connect' below to start using Ollama in
3965    /// Zed" from two provider onboarding pages, titled the OAuth callback page
3966    /// in their browser after somebody else's product, and handed the model a
3967    /// system prompt beginning "You are the Zed coding agent running inside
3968    /// the Zed editor".
3969    ///
3970    /// This inverts the default. The inventory is derived from five shipping
3971    /// mechanisms; everything in it must be *classified* in the policy; an
3972    /// unclassified literal fails. A new sentence is unclassified the moment
3973    /// it is written.
3974    #[test]
3975    fn no_unclassified_prose_names_a_competitor() {
3976        let policy = brand_policy().expect("brand policy parses");
3977        let prose = &policy["prose"];
3978        let (items, read) = prose_inventory(&policy);
3979
3980        for (key, actual, label) in [
3981            ("minimum_rust_files", read.rust_files, "Rust sources"),
3982            (
3983                "minimum_rust_string_literals",
3984                read.literals,
3985                "Rust string literals",
3986            ),
3987            (
3988                "minimum_schema_doc_lines",
3989                read.schema_docs,
3990                "settings-schema doc lines",
3991            ),
3992            (
3993                "minimum_action_doc_lines",
3994                read.action_docs,
3995                "action doc lines",
3996            ),
3997            ("minimum_clap_doc_lines", read.clap_docs, "--help doc lines"),
3998            (
3999                "minimum_embedded_files",
4000                read.embedded,
4001                "embedded asset files",
4002            ),
4003        ] {
4004            let floor = prose[key].as_u64().unwrap_or(u64::MAX) as usize;
4005            assert!(
4006                actual >= floor,
4007                "OMEGA-DELTA-0034: only {actual} {label} were read, below the \
4008                 {floor} floor in {BRAND_GATE_POLICY_PATH}. That parser broke, \
4009                 and a check that reads nothing reports green about nothing."
4010            );
4011        }
4012
4013        let classified = prose["classified"]
4014            .as_object()
4015            .expect("prose.classified is an object");
4016        assert!(
4017            classified.len() >= 20,
4018            "OMEGA-DELTA-0034: only {} prose literals are classified, so this \
4019             registry is not a record of anybody having read the tree",
4020            classified.len()
4021        );
4022        for (text, entry) in classified {
4023            assert!(
4024                entry["class"].is_string() && entry["reason"].is_string(),
4025                "OMEGA-DELTA-0034: prose.classified[{text:?}] needs a class and \
4026                 a reason. An entry is a record that somebody read the sentence \
4027                 and decided it names somebody else rather than us."
4028            );
4029            let class = entry["class"].as_str().unwrap_or_default();
4030            assert!(
4031                prose["classes"].get(class).is_some(),
4032                "OMEGA-DELTA-0034: prose.classified[{text:?}] uses class \
4033                 {class:?}, which prose.classes does not define"
4034            );
4035        }
4036
4037        let corpus: std::collections::BTreeSet<&str> = prose["corpus_files"]
4038            .as_object()
4039            .expect("prose.corpus_files is an object")
4040            .keys()
4041            .map(String::as_str)
4042            .collect();
4043        for relative in &corpus {
4044            assert!(
4045                repository_path(relative).is_file(),
4046                "OMEGA-DELTA-0034: exempt corpus file {relative} does not exist, \
4047                 so the exemption is hiding nothing and should be deleted"
4048            );
4049        }
4050
4051        let mut unclassified: Vec<String> = items
4052            .iter()
4053            .filter(|item| {
4054                !corpus.contains(item.file.as_str()) && !classified.contains_key(&item.text)
4055            })
4056            .map(|item| {
4057                format!(
4058                    "{}:{} [{}] {:?}",
4059                    item.file,
4060                    item.line,
4061                    item.kind,
4062                    item.text.chars().take(160).collect::<String>()
4063                )
4064            })
4065            .collect();
4066        unclassified.sort();
4067        unclassified.dedup();
4068        assert!(
4069            unclassified.is_empty(),
4070            "OMEGA-DELTA-0034: brand-bearing prose that nobody has classified. \
4071             Substitute our own name: if the sentence stays true with 'Omega' \
4072             in it, the brand was standing where our product's name belongs, so \
4073             rewrite it. If it becomes false, it names somebody else's product \
4074             and belongs in prose.classified in {BRAND_GATE_POLICY_PATH} with a \
4075             class and a reason.\n{}",
4076            unclassified.join("\n")
4077        );
4078
4079        let present: std::collections::BTreeSet<&str> =
4080            items.iter().map(|item| item.text.as_str()).collect();
4081        let mut stale: Vec<&String> = classified
4082            .iter()
4083            .filter(|(text, entry)| {
4084                entry["packaged_only"] != serde_json::Value::Bool(true)
4085                    && !present.contains(text.as_str())
4086            })
4087            .map(|(text, _)| text)
4088            .collect();
4089        stale.sort();
4090        assert!(
4091            stale.is_empty(),
4092            "OMEGA-DELTA-0034: these classified literals are no longer anywhere \
4093             in the tree. Either the sentence went and the entry should go with \
4094             it, or a scanner stopped reading the stream that used to find it — \
4095             which is what this assertion exists to catch.\n{}",
4096            stale
4097                .iter()
4098                .map(|text| text.chars().take(100).collect::<String>())
4099                .collect::<Vec<_>>()
4100                .join("\n")
4101        );
4102    }
4103
4104    /// OMEGA-DELTA-0031. The prose lexer reads what it claims to read.
4105    ///
4106    /// The first version of this scanner counted lines wrongly across a `\`
4107    /// line continuation, so six multi-line literals — four provider error
4108    /// toasts among them — were attributed to the wrong line and silently
4109    /// skipped by the rewrite that was supposed to fix them.
4110    #[test]
4111    fn the_prose_lexer_reads_multi_line_and_raw_literals() {
4112        let source = concat!(
4113            "fn demo() {\n",
4114            "    // \"not a literal\"\n",
4115            "    let a = \"first\";\n",
4116            "    let b = \"second \\\n",
4117            "        continued\";\n",
4118            "    let c = r#\"raw \"quoted\" body\"#;\n",
4119            "    let d = \"after\";\n",
4120            "}\n",
4121        );
4122        let literals = rust_string_literals(source);
4123        let found: Vec<(usize, &str)> = literals
4124            .iter()
4125            .map(|(line, body)| (*line, body.as_str()))
4126            .collect();
4127        assert_eq!(found[0], (3, "first"), "single-line literal and its line");
4128        assert_eq!(
4129            found[1].0, 4,
4130            "a continued literal starts on its first line"
4131        );
4132        assert!(
4133            found[1].1.contains("continued"),
4134            "the continuation is part of the literal: {:?}",
4135            found[1].1
4136        );
4137        assert_eq!(
4138            found[2],
4139            (6, "raw \"quoted\" body"),
4140            "a raw literal keeps its inner quotes"
4141        );
4142        assert_eq!(
4143            found[3],
4144            (7, "after"),
4145            "the line count survives the raw literal"
4146        );
4147        assert!(
4148            !found.iter().any(|(_, body)| body.contains("not a literal")),
4149            "a comment is not a literal"
4150        );
4151
4152        assert!(is_prose(
4153            "Click 'Connect' below to start using Ollama in Omega"
4154        ));
4155        assert!(!is_prose("crates/zed/src/main.rs"));
4156        assert!(!is_prose("X-Zed-Predict-Edits-Mode"));
4157        assert!(
4158            is_prose("Zed Plex Sans"),
4159            "a three-word font family name stays in the inventory to be classified, \
4160             not filtered out of it"
4161        );
4162    }
4163
4164    /// OMEGA-DELTA-0044. A brand-bearing command form is user-facing text.
4165    ///
4166    /// `is_prose` needs three tokens, and `0.2.0-rc16` shipped three two-token
4167    /// command literals in the signed `cli` because of it: `zed --existing`,
4168    /// `zed --classic` and `zed <path>`, rendered by an interactive panel that
4169    /// says "Omega window" and "Omega settings" around them (omega#93). They
4170    /// were in neither `prose.classified` nor the compatibility allow-list, and
4171    /// `verify-omega-brand --app` exited 0.
4172    ///
4173    /// Both directions matter. Widening this to "any two tokens beginning with
4174    /// a brand word" pulls in eight more literals that really are references to
4175    /// somebody else's product, and widening it to a bare brand token pulls in
4176    /// 55; a rule that cries wolf gets deleted, which is how the blind spot
4177    /// stayed open once it was known about.
4178    #[test]
4179    fn a_brand_bearing_command_form_is_user_facing_text() {
4180        let policy = brand_policy().expect("brand policy parses");
4181
4182        for shipped in ["zed --existing", "zed --classic", "zed <path>"] {
4183            assert!(
4184                !is_prose(shipped),
4185                "OMEGA-DELTA-0044: {shipped:?} is being kept out of the \
4186                 inventory by the three-token rule, which is the blind spot \
4187                 this exists to close"
4188            );
4189            assert!(
4190                is_command_form(shipped, &policy),
4191                "OMEGA-DELTA-0044: {shipped:?} shipped in a signed `cli` and \
4192                 the inventory still cannot see it"
4193            );
4194            assert!(is_user_facing_text(shipped, &policy));
4195        }
4196        for form in ["zed .", "zed ~/project", "zed -n", "Zed --help"] {
4197            assert!(
4198                is_command_form(form, &policy),
4199                "OMEGA-DELTA-0044: {form:?} is a command form"
4200            );
4201        }
4202
4203        // The other direction: the shapes that would make this noisy enough to
4204        // be deleted, and are therefore excluded on purpose.
4205        for benign in [
4206            "Zed Pro",
4207            "Zed (Default)",
4208            "Zed Repository",
4209            "zed",
4210            "crates/zed/src",
4211            "X-Zed-Predict-Edits-Mode",
4212            "zed_llm_client",
4213        ] {
4214            assert!(
4215                !is_command_form(benign, &policy),
4216                "OMEGA-DELTA-0044: {benign:?} is not a command form. This rule \
4217                 covers a brand word standing in argv[0]; a two-word label is \
4218                 either prose already or a reference to be classified."
4219            );
4220        }
4221
4222        // The shell gate carries the same rule, on the same three streams, or
4223        // the source and packaged sides disagree about what is inventoried.
4224        let verifier =
4225            std::fs::read_to_string(repository_path(BRAND_VERIFIER_PATH)).expect("brand verifier");
4226        assert!(
4227            verifier.contains("def is_command_form("),
4228            "OMEGA-DELTA-0044: {BRAND_VERIFIER_PATH} does not carry the \
4229             command-form rule, so `verify-omega-brand` and these tests \
4230             inventory different things."
4231        );
4232        let wired = verifier.matches("is_user_facing_text(").count();
4233        assert!(
4234            wired >= 4,
4235            "OMEGA-DELTA-0044: {BRAND_VERIFIER_PATH} calls is_user_facing_text \
4236             {wired} time(s) — one definition and one call per stream (Rust \
4237             literals, doc lines, embedded assets) is the minimum. A predicate \
4238             that is defined and never called is the state \
4239             first_party_agent.phrases was in for four release candidates."
4240        );
4241        assert!(
4242            !verifier.contains("and is_prose(body)") && !verifier.contains("not is_prose(doc)"),
4243            "OMEGA-DELTA-0044: a stream in {BRAND_VERIFIER_PATH} still filters \
4244             on is_prose alone, so command forms are invisible to it."
4245        );
4246    }
4247
4248    /// OMEGA-DELTA-0044. The prompt spells its command forms with the binary's
4249    /// own name.
4250    ///
4251    /// Fixing the three literals is not the same as making them unable to come
4252    /// back. Any command form written out by hand can drift from the binary it
4253    /// describes; one built from `paths::BINARY_NAME` cannot.
4254    #[test]
4255    fn the_cli_prompt_names_our_own_binary() {
4256        let path = repository_path(CLI_MAIN_PATH);
4257        let source = std::fs::read_to_string(&path)
4258            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4259        let prompt = source
4260            .split("fn prompt_open_behavior()")
4261            .nth(1)
4262            .expect("OMEGA-DELTA-0044: prompt_open_behavior is gone");
4263        let prompt = &prompt[..prompt.find("\n}\n").unwrap_or(prompt.len())];
4264        // Ordinary comments are dropped, doc comments are not: a `//` line does
4265        // not reach a user, and the comment recording what shipped here has to
4266        // be able to quote it. `///` and `//!` stay, because clap and schemars
4267        // print those.
4268        let rendered: String = prompt
4269            .lines()
4270            .filter(|line| {
4271                let trimmed = line.trim_start();
4272                !trimmed.starts_with("//")
4273                    || trimmed.starts_with("///")
4274                    || trimmed.starts_with("//!")
4275            })
4276            .collect::<Vec<_>>()
4277            .join("\n");
4278
4279        let policy = brand_policy().expect("brand policy parses");
4280        let hits = brand_hits(&rendered, &policy);
4281        assert!(
4282            hits.is_empty(),
4283            "OMEGA-DELTA-0044: the open-behavior prompt in {} names {hits:?}. \
4284             This panel already says \"Omega window\" and \"Omega settings\"; \
4285             the commands beside them have to be ours too (omega#93).",
4286            path.display()
4287        );
4288        let derived = rendered.matches("paths::BINARY_NAME").count();
4289        assert!(
4290            derived >= 3,
4291            "OMEGA-DELTA-0044: the prompt builds only {derived} of its command \
4292             forms from paths::BINARY_NAME. All three — the two choices and the \
4293             heading — come from the binary's own name, so a rename cannot \
4294             leave one behind."
4295        );
4296    }
4297
4298    #[test]
4299    fn delta_ids_are_unique() {
4300        let mut seen = std::collections::BTreeSet::new();
4301        let repeated: Vec<&&str> = ENFORCED_DELTAS
4302            .iter()
4303            .filter(|id| !seen.insert(**id))
4304            .collect();
4305        assert!(
4306            repeated.is_empty(),
4307            "ENFORCED_DELTAS lists an ID more than once: {repeated:?}. \
4308             Allocate the next free number instead of reusing one."
4309        );
4310
4311        let path = repository_path(DELTA_REGISTRY_PATH);
4312        let registry = std::fs::read_to_string(&path).expect("delta registry is readable");
4313        let mut seen_headings = std::collections::BTreeSet::new();
4314        let repeated_headings: Vec<String> = registry
4315            .lines()
4316            .filter_map(|line| line.strip_prefix("### "))
4317            .filter_map(|heading| heading.split_whitespace().next())
4318            .filter(|token| token.starts_with("OMEGA-DELTA-"))
4319            .filter(|token| !seen_headings.insert((*token).to_owned()))
4320            .map(str::to_owned)
4321            .collect();
4322        assert!(
4323            repeated_headings.is_empty(),
4324            "{} has more than one entry for: {repeated_headings:?}",
4325            path.display()
4326        );
4327    }
4328
4329    /// The registry and the checks must agree, in both directions.
4330    ///
4331    /// A check with no registry entry is an unexplained rule. A registry entry
4332    /// with no check is a promise nothing keeps — and the registry's own rules
4333    /// require every delta to have one.
4334    #[test]
4335    fn the_registry_and_the_checks_agree() {
4336        let path = repository_path(DELTA_REGISTRY_PATH);
4337        let registry = std::fs::read_to_string(&path).expect("delta registry is readable");
4338
4339        // Match the heading that opens an entry, not any mention of the ID.
4340        // A substring match would accept "OMEGA-DELTA-0001 was withdrawn".
4341        let documented: std::collections::BTreeSet<String> = registry
4342            .lines()
4343            .filter_map(|line| line.strip_prefix("### "))
4344            .filter_map(|heading| heading.split_whitespace().next())
4345            .filter(|token| token.starts_with("OMEGA-DELTA-"))
4346            .map(str::to_owned)
4347            .collect();
4348        let enforced: std::collections::BTreeSet<String> =
4349            ENFORCED_DELTAS.iter().map(|id| (*id).to_owned()).collect();
4350
4351        let undocumented: Vec<&String> = enforced.difference(&documented).collect();
4352        assert!(
4353            undocumented.is_empty(),
4354            "enforced but missing a `### <ID>` entry in {}: {undocumented:?}",
4355            path.display()
4356        );
4357        let unenforced: Vec<&String> = documented.difference(&enforced).collect();
4358        assert!(
4359            unenforced.is_empty(),
4360            "documented in {} but not listed in ENFORCED_DELTAS: {unenforced:?}",
4361            path.display()
4362        );
4363    }
4364
4365    /// OMEGA-DELTA-0021. Disclosure is a typed record, never a label string.
4366    ///
4367    /// This is the owner's binding condition from omega#74, mechanised. The
4368    /// owner accepted that the first-party agent does not sign with its own
4369    /// principal *on the condition* that disclosure is stored as a record a
4370    /// label renders. A stored label would make that reversible decision
4371    /// irreversible: switching to a signing principal would then mean parsing
4372    /// prose back into parts for every thread, instead of adding a signer.
4373    ///
4374    /// So the field set is asserted exactly, and `label` is asserted to be a
4375    /// method. Upstream Zed has no equivalent — there is nothing to revert to
4376    /// here, only something to quietly add.
4377    #[test]
4378    fn executor_disclosure_is_a_typed_record_not_a_label_string() {
4379        let path = repository_path(EXECUTOR_DISCLOSURE_RECORD_PATH);
4380        let source = std::fs::read_to_string(&path)
4381            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4382
4383        let fields = struct_fields(&source, "ExecutorDisclosure");
4384        assert!(
4385            !fields.is_empty(),
4386            "OMEGA-DELTA-0021: no ExecutorDisclosure struct found in {}. \
4387             The check would be vacuous, so it fails instead.",
4388            path.display()
4389        );
4390
4391        let found: Vec<(&str, &str)> = fields
4392            .iter()
4393            .map(|(name, type_name)| (name.as_str(), type_name.as_str()))
4394            .collect();
4395        assert_eq!(
4396            found, EXECUTOR_DISCLOSURE_FIELDS,
4397            "OMEGA-DELTA-0021: ExecutorDisclosure holds different parts than \
4398             the ones recorded. If a part was genuinely added, add it to \
4399             EXECUTOR_DISCLOSURE_FIELDS and say so in the delta. If a rendered \
4400             line was added, that is the failure this test exists for: the \
4401             owner's identity decision on omega#74 stays reversible only while \
4402             disclosure is a record a label renders."
4403        );
4404
4405        assert!(
4406            source.contains("pub fn label(&self) -> String"),
4407            "OMEGA-DELTA-0021: {} must render the line from the record with a \
4408             `label` method.",
4409            path.display()
4410        );
4411    }
4412
4413    /// OMEGA-DELTA-0029. The routing law reads nothing but its inputs.
4414    ///
4415    /// Determinism is the packet's exit and the hardest half to establish: a
4416    /// unit test shows only that the inputs it tried gave the same answer
4417    /// twice. This reads the source for the ways the answer could stop
4418    /// depending on its inputs at all.
4419    #[test]
4420    fn the_routing_law_has_no_clock_no_randomness_and_no_hash_order() {
4421        for path in [ROUTE_DECISION_PATH, ROUTER_DISPATCH_PATH] {
4422            let full = repository_path(path);
4423            let source = std::fs::read_to_string(&full)
4424                .unwrap_or_else(|error| panic!("cannot read {}: {error}", full.display()));
4425            assert!(
4426                source.contains("pub fn route(") || source.contains("route(&self.inputs_for("),
4427                "OMEGA-DELTA-0029: {path} does not look like part of the \
4428                 routing path any more; the scan below would be vacuous."
4429            );
4430            // Code only: the doc comments name several of these tokens in the
4431            // course of explaining why they are not there.
4432            let code = code_of(&source);
4433            for (what, token) in NON_DETERMINISTIC_ROUTING_TOKENS {
4434                assert!(
4435                    !code.contains(token),
4436                    "OMEGA-DELTA-0029: {path} reaches for {what} (`{token}`). \
4437                     The router's exit is that the same inputs give the same \
4438                     route; anything here that is not an input breaks that in \
4439                     a way nobody can reproduce afterwards."
4440                );
4441            }
4442        }
4443    }
4444
4445    /// OMEGA-DELTA-0029. The router owns no execution.
4446    ///
4447    /// omega#74 admitted Omega Agent as a router that owns routing, disclosure
4448    /// and receipts and owns no execution. The last four tokens are owner gate
4449    /// 8: the router must not be able to start run authority at all, because
4450    /// only an explicit human action may — and today three model-callable
4451    /// starts were removed from Desktop, one of them a rename of another.
4452    #[test]
4453    fn the_router_owns_no_execution_and_starts_no_run() {
4454        let path = repository_path(ROUTER_DISPATCH_PATH);
4455        let source = std::fs::read_to_string(&path)
4456            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4457        assert!(
4458            source.contains("impl AgentConnection for OmegaAgentConnection"),
4459            "OMEGA-DELTA-0029: {} no longer implements the seam it routes at.",
4460            path.display()
4461        );
4462        // Doc comments name several of these tokens on purpose, so the scan
4463        // reads code only.
4464        let code = code_of(&source);
4465        for token in ROUTER_EXECUTION_TOKENS {
4466            assert!(
4467                !code.contains(token),
4468                "OMEGA-DELTA-0029: the router reaches for `{token}`. It routes, \
4469                 discloses, and records; it does not execute, and it does not \
4470                 start run authority."
4471            );
4472        }
4473    }
4474
4475    /// OMEGA-DELTA-0029. Every routed method hands the work to an executor.
4476    ///
4477    /// A method that stopped delegating would be the router quietly becoming an
4478    /// executor — the packet's falsifier — and it would still compile, still
4479    /// pass every behavioural test that did not happen to call it, and still
4480    /// read as a router from its module docs.
4481    #[test]
4482    fn the_router_delegates_every_agent_connection_method() {
4483        let path = repository_path(ROUTER_DISPATCH_PATH);
4484        let source = std::fs::read_to_string(&path)
4485            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4486
4487        let header = "impl AgentConnection for OmegaAgentConnection {\n";
4488        let start = source
4489            .find(header)
4490            .unwrap_or_else(|| panic!("{} has no router impl block", path.display()))
4491            + header.len();
4492        let end = source[start..]
4493            .find("\n}")
4494            .unwrap_or_else(|| panic!("{} has an unterminated impl block", path.display()))
4495            + start;
4496        let block = &source[start..end];
4497
4498        let mut checked = 0;
4499        for item in block.split("\n    fn ").skip(1) {
4500            let name = item
4501                .split(['(', '<'])
4502                .next()
4503                .unwrap_or_default()
4504                .trim()
4505                .to_owned();
4506            if ROUTER_NON_DELEGATING_METHODS.contains(&name.as_str()) {
4507                continue;
4508            }
4509            checked += 1;
4510            assert!(
4511                ROUTER_DELEGATION_MARKERS
4512                    .iter()
4513                    .any(|marker| item.contains(marker)),
4514                "OMEGA-DELTA-0029: `{name}` in {} does not hand its work to an \
4515                 executor. The router owns no execution, so every method of the \
4516                 seam it implements has to reach one of {ROUTER_DELEGATION_MARKERS:?}.",
4517                path.display()
4518            );
4519        }
4520        assert!(
4521            checked >= 10,
4522            "OMEGA-DELTA-0029: only {checked} router methods were checked. The \
4523             impl block parse is finding almost nothing, so this check is close \
4524             to vacuous."
4525        );
4526    }
4527
4528    /// OMEGA-DELTA-0029. The decision record is a record, like the disclosure.
4529    ///
4530    /// Same law, same reason: a stored sentence cannot be re-rendered, re-read,
4531    /// or handed to a later signer, and the whole point of writing a route down
4532    /// is that somebody can ask it a question later.
4533    #[test]
4534    fn the_route_decision_is_a_record_that_round_trips() {
4535        let path = repository_path(ROUTE_DECISION_PATH);
4536        let source = std::fs::read_to_string(&path)
4537            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4538
4539        let fields = struct_fields(&source, "RouteDecision");
4540        let found: Vec<(&str, &str)> = fields
4541            .iter()
4542            .map(|(name, type_name)| (name.as_str(), type_name.as_str()))
4543            .collect();
4544        assert_eq!(
4545            found,
4546            [
4547                ("chosen", "ExecutorClass"),
4548                ("reason", "RouteReason"),
4549                ("pin", "Option<ExecutorPin>"),
4550                ("lane_ref", "Option<String>"),
4551            ],
4552            "OMEGA-DELTA-0029: RouteDecision holds different parts than the \
4553             ones recorded. A rendered explanation stored as a field is the \
4554             failure this exists for."
4555        );
4556        for required in [
4557            "pub fn canonical_record(&self) -> String",
4558            "pub fn parse_canonical_record(record: &str) -> Option<Self>",
4559            "pub fn is_coherent(&self) -> bool",
4560        ] {
4561            assert!(
4562                source.contains(required),
4563                "OMEGA-DELTA-0029: {} must define `{required}`; a record that \
4564                 cannot be read back is a log line.",
4565                path.display()
4566            );
4567        }
4568    }
4569
4570    /// OMEGA-DELTA-0021. The thread surface renders the line, from the record.
4571    ///
4572    /// omega#77's falsifier is a thread surface showing work without naming its
4573    /// executor. A record nothing draws satisfies every other check here and
4574    /// discloses nothing, so the call site is pinned as well as the type.
4575    #[test]
4576    fn the_thread_surface_renders_the_executor_line_from_the_record() {
4577        let path = repository_path(THREAD_VIEW_PATH);
4578        let source = std::fs::read_to_string(&path)
4579            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4580
4581        assert!(
4582            source.contains("fn render_executor_disclosure("),
4583            "OMEGA-DELTA-0021: {} must define the executor line.",
4584            path.display()
4585        );
4586        assert!(
4587            source.contains(".child(self.render_executor_disclosure(cx))"),
4588            "OMEGA-DELTA-0021: {} must draw the executor line in the thread. \
4589             Defining it without rendering it discloses nothing.",
4590            path.display()
4591        );
4592        assert!(
4593            source.contains("Label::new(disclosure.label())"),
4594            "OMEGA-DELTA-0021: the executor line must be rendered from the \
4595             disclosure record in {}, not from a stored or hand-built string.",
4596            path.display()
4597        );
4598    }
4599
4600    /// OMEGA-DELTA-0021. The disclosure rides an extension trait, not a fork.
4601    ///
4602    /// omega#77 requires the disclosure to be carried "via an Omega extension
4603    /// trait behind a checked downcast on the shared thread types — never a
4604    /// fork of `AcpThread`". Two halves: the `impl` exists here, and the
4605    /// upstream crate stays clean. Putting the record into `crates/acp_thread`
4606    /// would work fine and would make every future rebase of that crate an
4607    /// Omega merge conflict.
4608    #[test]
4609    fn the_disclosure_is_an_extension_trait_and_not_a_fork_of_the_shared_thread() {
4610        let path = repository_path(EXECUTOR_DISCLOSURE_BINDING_PATH);
4611        let source = std::fs::read_to_string(&path)
4612            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4613        assert!(
4614            source.contains("impl ThreadExecutorDisclosure for AcpThread"),
4615            "OMEGA-DELTA-0021: {} must implement the Omega extension trait for \
4616             the shared thread type.",
4617            path.display()
4618        );
4619        assert!(
4620            source.contains("downcast::<NativeAgentConnection>()"),
4621            "OMEGA-DELTA-0021: {} must classify the executor by a checked \
4622             downcast. Matching on the agent's display name would make the \
4623             disclosure a string comparison on a label #75 is renaming.",
4624            path.display()
4625        );
4626
4627        let mut offenders = Vec::new();
4628        for_each_source_file(
4629            &repository_path("crates/acp_thread"),
4630            &["rs"],
4631            |file, contents| {
4632                if contents.contains("ExecutorDisclosure") {
4633                    offenders.push(file.display().to_string());
4634                }
4635            },
4636        );
4637        assert!(
4638            offenders.is_empty(),
4639            "OMEGA-DELTA-0021: the disclosure record leaked into the shared \
4640             thread crate, which is the fork omega#77 forbids: {offenders:?}"
4641        );
4642    }
4643
4644    // ------------------------------------------------------ OMEGA-DELTA-0025
4645
4646    /// OMEGA-DELTA-0025. A digest is a measurement, never a parsed claim.
4647    ///
4648    /// The whole provenance packet rests on this. If a `MeasuredDigest` can be
4649    /// built from a string, then a receipt saying "this update was applied at
4650    /// this digest" can be written by code that read a registry document
4651    /// instead of the bytes, and the receipt stops meaning anything a reader
4652    /// could act on — while continuing to look identical on the wire.
4653    ///
4654    /// This is the kind of invariant a convenience constructor undoes in good
4655    /// faith: `impl From<String>` to make a test fixture shorter, or a
4656    /// `Deserialize` derive to reuse the type in the pin ledger. So the
4657    /// admitted constructors are named, and anything that returns the type
4658    /// another way fails.
4659    #[test]
4660    fn a_measured_digest_cannot_be_built_from_a_string() {
4661        let path = repository_path(MEASURED_DIGEST_PATH);
4662        let source = std::fs::read_to_string(&path)
4663            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4664
4665        let header = "impl MeasuredDigest {\n";
4666        let start = source.find(header).unwrap_or_else(|| {
4667            panic!(
4668                "OMEGA-DELTA-0025: no `impl MeasuredDigest` block in {}. The \
4669                 check would be vacuous, so it fails instead.",
4670                path.display()
4671            )
4672        });
4673        let body_start = start + header.len();
4674        let end = source[body_start..]
4675            .find("\n}")
4676            .expect("the impl block closes");
4677        let body = &source[body_start..body_start + end];
4678
4679        // Every associated function that hands back a `MeasuredDigest`.
4680        let mut constructors: Vec<String> = Vec::new();
4681        let mut lines = body.lines().peekable();
4682        while let Some(line) = lines.next() {
4683            let trimmed = line.trim();
4684            let Some(rest) = trimmed
4685                .strip_prefix("pub fn ")
4686                .or_else(|| trimmed.strip_prefix("fn "))
4687            else {
4688                continue;
4689            };
4690            let Some((name, signature)) = rest.split_once('(') else {
4691                continue;
4692            };
4693            // A one-line signature, or the return type on the following line.
4694            let returns_self = signature.contains("-> Self")
4695                || signature.contains("-> MeasuredDigest")
4696                || lines.peek().is_some_and(|next| {
4697                    next.contains("-> Self") || next.contains("-> MeasuredDigest")
4698                });
4699            if returns_self {
4700                constructors.push(name.trim().to_owned());
4701            }
4702        }
4703        constructors.sort();
4704        constructors.dedup();
4705
4706        let mut admitted: Vec<String> = MEASURED_DIGEST_CONSTRUCTORS
4707            .iter()
4708            .map(|name| (*name).to_owned())
4709            .collect();
4710        admitted.sort();
4711        assert_eq!(
4712            constructors,
4713            admitted,
4714            "OMEGA-DELTA-0025: {} declares a different set of ways to obtain a \
4715             MeasuredDigest than the admitted one. Every entry has to take \
4716             bytes or already-measured digests; a constructor that takes a \
4717             digest string turns every receipt into a claim.",
4718            path.display()
4719        );
4720
4721        // The primitive constructor takes bytes. Without this the closed list
4722        // above would still pass if `measure` were changed to take a `&str`
4723        // digest.
4724        assert!(
4725            source.contains("pub fn measure(bytes: &[u8]) -> Self"),
4726            "OMEGA-DELTA-0025: MeasuredDigest::measure no longer takes bytes in {}",
4727            path.display()
4728        );
4729        assert!(
4730            source.contains("pub fn measure_tree(files: &mut [(String, MeasuredDigest)]) -> Self"),
4731            "OMEGA-DELTA-0025: MeasuredDigest::measure_tree no longer folds \
4732             already-measured digests in {}",
4733            path.display()
4734        );
4735
4736        // A trait implementation is not a `fn` in the inherent block, so the
4737        // closed list above cannot see one. These are the three that would
4738        // reintroduce a string path.
4739        //
4740        // Read from the code only: this module's own documentation explains
4741        // why `Deserialize` is absent, and a whole-file scan reads that
4742        // explanation as the violation it describes. The first run of this
4743        // check did exactly that.
4744        let source: String = source
4745            .lines()
4746            .filter(|line| !line.trim_start().starts_with("//"))
4747            .collect::<Vec<_>>()
4748            .join("\n");
4749        for forbidden in [
4750            "impl From<String> for MeasuredDigest",
4751            "impl From<&str> for MeasuredDigest",
4752            "impl std::str::FromStr for MeasuredDigest",
4753        ] {
4754            assert!(
4755                !source.contains(forbidden),
4756                "OMEGA-DELTA-0025: {forbidden} reintroduces a path from a claim \
4757                 into a measurement, in {}",
4758                path.display()
4759            );
4760        }
4761        assert!(
4762            !source.contains("Deserialize"),
4763            "OMEGA-DELTA-0025: MeasuredDigest became deserializable in {}. A \
4764             value that arrived as text is not a measurement this host made.",
4765            path.display()
4766        );
4767    }
4768
4769    /// OMEGA-DELTA-0025. An external harness does not run unmeasured.
4770    ///
4771    /// Upstream resolves whichever version the ACP registry advertises,
4772    /// downloads it, and returns the command. A registry agent then runs with
4773    /// the tool permissions of the thread that started it, which is exactly the
4774    /// falsifier omega#81 names: a binary swapped under an auto-update path
4775    /// with no verifiable provenance record.
4776    ///
4777    /// So the gate has to sit between the installed tree and the returned
4778    /// command, and its refusal has to propagate. A gate whose result is logged
4779    /// and dropped is the rc11 defect — `appendSystemNote` bound to `() => {}`
4780    /// — in a different file.
4781    #[test]
4782    fn the_external_harness_launch_path_is_gated_on_a_measurement() {
4783        let path = repository_path(AGENT_SERVER_STORE_PATH);
4784        let source = std::fs::read_to_string(&path)
4785            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4786
4787        let gate = source
4788            .find("authorize_installed_harness(")
4789            .unwrap_or_else(|| {
4790                panic!(
4791                    "OMEGA-DELTA-0025: {} no longer measures an installed harness \
4792                 before returning its command",
4793                    path.display()
4794                )
4795            });
4796        let prefetch_gate = source.find("authorize_version_fetch(").unwrap_or_else(|| {
4797            panic!(
4798                "OMEGA-DELTA-0025: {} no longer consults the pin before fetching \
4799                 a harness version",
4800                path.display()
4801            )
4802        });
4803
4804        // The archive agent is the only registry path that installs a tree
4805        // Omega controls, and its command construction must come after the
4806        // gate.
4807        let command = source[gate..]
4808            .find("let command = AgentServerCommand {")
4809            .map(|offset| gate + offset)
4810            .unwrap_or_else(|| {
4811                panic!(
4812                    "OMEGA-DELTA-0025: no AgentServerCommand is constructed after \
4813                     the provenance gate in {}. Either the gate moved below the \
4814                     command it is supposed to gate, or the command moved out of \
4815                     reach of this check.",
4816                    path.display()
4817                )
4818            });
4819        assert!(
4820            gate < command,
4821            "OMEGA-DELTA-0025: the provenance gate no longer precedes the \
4822             command it gates in {}",
4823            path.display()
4824        );
4825        assert!(
4826            prefetch_gate < gate,
4827            "OMEGA-DELTA-0025: the pin is consulted after the download rather \
4828             than before it in {}",
4829            path.display()
4830        );
4831
4832        // The refusal has to be propagated, not logged. `.log_err()` on either
4833        // call would leave the harness running.
4834        for call in ["authorize_version_fetch(", "authorize_installed_harness("] {
4835            let start = source.find(call).expect("call site located above");
4836            let tail = &source[start..];
4837            let end = tail.find(";").expect("the call statement ends");
4838            assert!(
4839                tail[..end].contains(".await?") || tail[..end].ends_with(".await?"),
4840                "OMEGA-DELTA-0025: the result of {call} is not propagated in {}. \
4841                 A refusal that does not stop the launch is not a refusal.",
4842                path.display()
4843            );
4844        }
4845    }
4846
4847    /// OMEGA-DELTA-0025. One decision, one receipt.
4848    ///
4849    /// `receipt_for_decision` takes the gate's own output, so a receipt cannot
4850    /// describe an outcome the gate did not reach. Calling the lower-level
4851    /// emitter from the enforcement path would reopen that gap: the receipt
4852    /// would be assembled from whatever the caller believed, beside a decision
4853    /// made somewhere else.
4854    #[test]
4855    fn the_enforcement_path_writes_receipts_only_from_decisions() {
4856        let path = repository_path(HARNESS_MAINTENANCE_PATH);
4857        let source = std::fs::read_to_string(&path)
4858            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4859
4860        assert!(
4861            source.contains("receipt_for_decision("),
4862            "OMEGA-DELTA-0025: {} no longer writes maintenance receipts",
4863            path.display()
4864        );
4865        let code_only: String = source
4866            .lines()
4867            .filter(|line| !line.trim_start().starts_with("//"))
4868            .collect::<Vec<_>>()
4869            .join("\n");
4870        assert!(
4871            !code_only.contains("build_harness_maintenance_receipt("),
4872            "OMEGA-DELTA-0025: {} builds a receipt without a decision. The \
4873             receipt and the enforcement would then be two answers to the same \
4874             question, and nothing on the wire would say which one ran.",
4875            path.display()
4876        );
4877        assert!(
4878            code_only.contains("decide_maintenance("),
4879            "OMEGA-DELTA-0025: {} no longer consults the maintenance gate",
4880            path.display()
4881        );
4882    }
4883
4884    // ------------------------------------------------------ OMEGA-DELTA-0030
4885
4886    /// OMEGA-DELTA-0030. A start request cannot carry what the host mints.
4887    ///
4888    /// omega#47 watched a live engine refuse a start request that deliberately
4889    /// carried a forged `evidence` block, a forged `decisionRef` and a forged
4890    /// `authorityReceiptRef`. That proof is about the host. This one is about
4891    /// the desktop: the request has no field to write the forgery into, so the
4892    /// claim holds before anything reaches the wire.
4893    #[test]
4894    fn a_full_auto_dispatch_carries_no_evidence() {
4895        let path = repository_path(FULL_AUTO_DISPATCH_PATH);
4896        let source = std::fs::read_to_string(&path)
4897            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4898
4899        let fields = struct_fields(&source, "FullAutoDispatch");
4900        assert!(
4901            !fields.is_empty(),
4902            "OMEGA-DELTA-0030: no FullAutoDispatch struct found in {}. The \
4903             check would be vacuous, so it fails instead.",
4904            path.display()
4905        );
4906        let found: Vec<(&str, &str)> = fields
4907            .iter()
4908            .map(|(name, type_name)| (name.as_str(), type_name.as_str()))
4909            .collect();
4910        assert_eq!(
4911            found, FULL_AUTO_DISPATCH_FIELDS,
4912            "OMEGA-DELTA-0030: FullAutoDispatch carries different parts than \
4913             the ones recorded. Evidence is minted by the host at the \
4914             completion-admission gate; a requester that can name it can forge \
4915             it. If a genuine request field was added, record it here and say \
4916             in the delta what the requester knows that the host does not."
4917        );
4918
4919        // The origin is the whole of owner gate 8 at this layer: the only
4920        // constructor takes one, and every variant is a human gesture.
4921        assert!(
4922            source.contains("origin: LaunchOrigin,"),
4923            "OMEGA-DELTA-0030: a dispatch must record the human gesture that \
4924             produced it, in {}",
4925            path.display()
4926        );
4927        assert!(
4928            source.contains("pub fn from_validated("),
4929            "OMEGA-DELTA-0030: {} must expose exactly one constructor, so a \
4930             dispatch without an origin is not expressible.",
4931            path.display()
4932        );
4933    }
4934
4935    /// OMEGA-DELTA-0030. Only the Full Auto surface can dispatch a run.
4936    ///
4937    /// Owner gate 8 says only an explicit human action starts Full Auto
4938    /// authority. The type enforces that a dispatch needs a `LaunchOrigin`;
4939    /// this enforces that no tool, model, or context-server crate is in a
4940    /// position to build one at all.
4941    #[test]
4942    fn no_model_callable_crate_can_dispatch_full_auto() {
4943        let mut offenders = Vec::new();
4944        let crates_root = repository_path("crates");
4945        for entry in std::fs::read_dir(&crates_root).expect("crates directory is readable") {
4946            let path = entry.expect("directory entry").path();
4947            if !path.is_dir() {
4948                continue;
4949            }
4950            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
4951                continue;
4952            };
4953            if FULL_AUTO_DISPATCH_CALLERS.contains(&name) {
4954                continue;
4955            }
4956            let name = name.to_owned();
4957            for_each_source_file(&path, &["rs"], |file, contents| {
4958                if contents.contains("FullAutoDispatch") {
4959                    offenders.push(format!("{name}: {}", file.display()));
4960                }
4961            });
4962        }
4963        assert!(
4964            offenders.is_empty(),
4965            "OMEGA-DELTA-0030: the Full Auto start command is reachable from \
4966             crates that are not the Full Auto surface: {offenders:?}. Owner \
4967             gate 8 allows only an explicit human action to start Full Auto \
4968             authority, and a crate that can build the command is a crate that \
4969             can start a run."
4970        );
4971    }
4972
4973    /// OMEGA-DELTA-0030. A thread shows the receipt chain of the run it names.
4974    ///
4975    /// omega#77 gave a thread its run reference. A reference the reader has to
4976    /// go elsewhere to resolve is not accountability, so the chain renders in
4977    /// the thread — and renders whatever it says, including a refusal.
4978    #[test]
4979    fn a_thread_renders_the_receipt_chain_of_its_linked_run() {
4980        let path = repository_path(THREAD_VIEW_PATH);
4981        let source = std::fs::read_to_string(&path)
4982            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
4983
4984        assert!(
4985            source.contains("fn render_omega_run_link("),
4986            "OMEGA-DELTA-0030: {} must define the linked-run surface.",
4987            path.display()
4988        );
4989        assert!(
4990            source.contains(".children(self.render_omega_run_link(cx))"),
4991            "OMEGA-DELTA-0030: {} must draw the linked run in the thread. \
4992             Defining it without rendering it shows the reader nothing.",
4993            path.display()
4994        );
4995        assert!(
4996            source.contains("project_thread_run_link("),
4997            "OMEGA-DELTA-0030: the linked run in {} must be projected from the \
4998             engine's records on every draw, not read from a stored view.",
4999            path.display()
5000        );
5001    }
5002
5003    /// OMEGA-DELTA-0030. The thread projects a run; it never owns one.
5004    ///
5005    /// omega#80's falsifier is "a run's source of truth ends up in a panel
5006    /// entity". Two halves. The thread stores the engine's *records* and their
5007    /// read time, never a projected link — a cached record can be re-derived
5008    /// and can expire, a cached conclusion silently outlives its source. And
5009    /// the projection module holds no state and no control: pause, resume and
5010    /// stop live on the Full Auto surface, bound to the run generation the host
5011    /// minted them for.
5012    #[test]
5013    fn the_thread_run_link_is_a_projection_and_not_a_second_authority() {
5014        let thread_view_path = repository_path(THREAD_VIEW_PATH);
5015        let thread_view = std::fs::read_to_string(&thread_view_path)
5016            .unwrap_or_else(|error| panic!("cannot read {}: {error}", thread_view_path.display()));
5017        assert!(
5018            thread_view.contains("omega_run_records: Option<ThreadRunRecords>,"),
5019            "OMEGA-DELTA-0030: {} must hold the engine's own records, so the \
5020             link can be re-derived and can go stale.",
5021            thread_view_path.display()
5022        );
5023        for stored_conclusion in [
5024            "omega_run_link: Option<ThreadRunLink>",
5025            "omega_run_state:",
5026            "omega_run_chain:",
5027        ] {
5028            assert!(
5029                !thread_view.contains(stored_conclusion),
5030                "OMEGA-DELTA-0030: {} stores `{stored_conclusion}`. A cached \
5031                 conclusion about a run is the panel entity becoming the \
5032                 source of truth that omega#80 forbids.",
5033                thread_view_path.display()
5034            );
5035        }
5036
5037        let link_path = repository_path(THREAD_RUN_LINK_PATH);
5038        let link = std::fs::read_to_string(&link_path)
5039            .unwrap_or_else(|error| panic!("cannot read {}: {error}", link_path.display()));
5040        // Tests are excluded (they deliberately name refusals), and so are
5041        // comments: an earlier version of this check passed after the
5042        // constant was renamed, because the module documentation still
5043        // mentioned the old name. A check a comment can satisfy is not a
5044        // check.
5045        let body: String = link
5046            .split("#[cfg(test)]")
5047            .next()
5048            .unwrap_or(&link)
5049            .lines()
5050            .filter(|line| !line.trim_start().starts_with("//"))
5051            .collect::<Vec<_>>()
5052            .join("\n");
5053        let body = body.as_str();
5054        // `&'static str` is fine and common; a `static` *item* is process state.
5055        for forbidden in [
5056            "\nstatic ",
5057            "\npub static ",
5058            "thread_local!",
5059            "LazyLock",
5060            "Mutex",
5061            "RefCell",
5062            "supervisor",
5063            "pause_run",
5064            "stop_run",
5065            "resume_run",
5066            "start_run",
5067        ] {
5068            assert!(
5069                !body.contains(forbidden),
5070                "OMEGA-DELTA-0030: {} contains `{forbidden}`. The thread's run \
5071                 link is a pure projection: state would let it disagree with \
5072                 the engine, and a control would make it a second place that \
5073                 believes it can command a run.",
5074                link_path.display()
5075            );
5076        }
5077        assert!(
5078            body.contains("THREAD_RUN_LINK_MAX_AGE_MS"),
5079            "OMEGA-DELTA-0030: {} must expire the engine's answer. A thread \
5080             that keeps rendering the last chain it saw has outlived the \
5081             authority it is projecting.",
5082            link_path.display()
5083        );
5084        assert!(
5085            body.contains("project_issue31_evidence_pair"),
5086            "OMEGA-DELTA-0030: {} must read the chain through the omega#47 \
5087             producer. A second chain implementation is a second opinion about \
5088             one run, and the desktop and the phone would drift.",
5089            link_path.display()
5090        );
5091    }
5092
5093    /// Read one `fn` body out of a Rust source file, by brace depth.
5094    ///
5095    /// A `contains` over the whole file cannot answer "does *this* function
5096    /// still refuse a projectless window", because the panel legitimately
5097    /// checks `has_open_project` in a dozen other places. Depth counting is
5098    /// crude but honest: it stops at the closing brace of the function it
5099    /// started on, and the test asserts it found a plausible body rather than
5100    /// an empty string, so a parse that silently matched nothing fails instead
5101    /// of passing.
5102    fn function_body<'a>(source: &'a str, name: &str) -> Option<&'a str> {
5103        let needle = format!(" fn {name}(");
5104        let start = source.find(&needle)? + needle.len();
5105        let open = source[start..].find('{')? + start;
5106        let mut depth = 0usize;
5107        for (offset, character) in source[open..].char_indices() {
5108            match character {
5109                '{' => depth += 1,
5110                '}' => {
5111                    depth -= 1;
5112                    if depth == 0 {
5113                        return Some(&source[open..open + offset]);
5114                    }
5115                }
5116                _ => {}
5117            }
5118        }
5119        None
5120    }
5121
5122    /// OMEGA-DELTA-0042. A source file with its test module removed.
5123    ///
5124    /// Every scan below asks "does the shipped lane name this?", and the tests
5125    /// beside it must be free to name exactly the things it refuses — a test
5126    /// that asserts the wrong Exo is rejected has to write the wrong Exo down.
5127    /// Scanning the whole file would make those tests unwritable, which is the
5128    /// wrong pressure: it would push the refusals out of the file rather than
5129    /// into it.
5130    fn production_source(source: &str) -> &str {
5131        source
5132            .split_once("\n#[cfg(test)]")
5133            .map_or(source, |(before, _)| before)
5134    }
5135
5136    /// OMEGA-DELTA-0042. Whether a token is named in code rather than in prose.
5137    fn named_in_code(source: &str, token: &str) -> bool {
5138        production_source(source)
5139            .lines()
5140            .filter(|line| line.contains(token))
5141            .any(|line| {
5142                let line = line.trim_start();
5143                !line.starts_with("//") && !line.starts_with("*")
5144            })
5145    }
5146
5147    /// OMEGA-DELTA-0034. The front door works with no project open.
5148    ///
5149    /// Checked in both directions. Upstream's guard restored on a front-door
5150    /// path is the omega#76 defect coming back — a fresh install lands on the
5151    /// agent and has no composer to type into. A guard *removed* from a
5152    /// workspace-touching path is the opposite mistake: a terminal with no
5153    /// working directory, or a clipboard thread with nowhere to put its files,
5154    /// failing later and less legibly than a refusal would have.
5155    #[test]
5156    fn the_front_door_does_not_require_an_open_project() {
5157        let path = repository_path(AGENT_PANEL_PATH);
5158        let source = std::fs::read_to_string(&path)
5159            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
5160
5161        for name in PROJECT_OPTIONAL_FRONT_DOOR_FNS {
5162            let body = function_body(&source, name).unwrap_or_else(|| {
5163                panic!(
5164                    "OMEGA-DELTA-0034: {} no longer has a `{name}` to check. \
5165                     If it was renamed, rename it here too; a check that \
5166                     cannot find its subject passes for the wrong reason.",
5167                    path.display()
5168                )
5169            });
5170            assert!(
5171                !body.contains("has_open_project"),
5172                "OMEGA-DELTA-0034: `{name}` in {} refuses a window with no \
5173                 project again. A window with nothing to restore is by \
5174                 definition a window with no project, so this is omega#76's \
5175                 exit failing: the front door opens and there is no composer \
5176                 to type into.",
5177                path.display()
5178            );
5179        }
5180
5181        for name in PROJECT_REQUIRED_FNS {
5182            let body = function_body(&source, name).unwrap_or_else(|| {
5183                panic!(
5184                    "OMEGA-DELTA-0034: {} no longer has a `{name}` to check.",
5185                    path.display()
5186                )
5187            });
5188            assert!(
5189                body.contains("has_open_project"),
5190                "OMEGA-DELTA-0034: `{name}` in {} stopped requiring an open \
5191                 project. Project-optional *threads* is the delta; a terminal \
5192                 with no working directory, a resumed draft with no worktree, \
5193                 or a clipboard import with nowhere to land is not.",
5194                path.display()
5195            );
5196        }
5197    }
5198
5199    /// OMEGA-DELTA-0013. The new-thread chord fires from anywhere in the window.
5200    ///
5201    /// Upstream binds `agent::NewThread` to `cmd-n` inside panel-scoped
5202    /// contexts only, so it cannot start a thread unless the panel already has
5203    /// focus. Omega's chord is window-global, which is the whole of omega#76's
5204    /// "from every context" — editor, welcome and panel are all inside
5205    /// `Workspace`.
5206    ///
5207    /// The check is two-sided, because each side alone is weak. A global
5208    /// binding that exists proves nothing if something narrower shadows it, and
5209    /// counting bindings would either forbid the modal pickers that legitimately
5210    /// hold the chord or permit any new binding at all.
5211    #[test]
5212    fn the_new_thread_chord_is_window_global() {
5213        for (keymap, chord) in NEW_THREAD_CHORDS {
5214            let path = repository_path(keymap);
5215            let raw = std::fs::read_to_string(&path)
5216                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
5217            let sections: serde_json::Value = serde_json::from_str(&strip_jsonc(&raw))
5218                .unwrap_or_else(|error| panic!("cannot parse {}: {error}", path.display()));
5219            let sections = sections
5220                .as_array()
5221                .unwrap_or_else(|| panic!("{keymap} is not an array of sections"));
5222
5223            let bound: Vec<(Option<&str>, Option<&str>)> = sections
5224                .iter()
5225                .filter_map(|section| {
5226                    let binding = section.get("bindings")?.get(*chord)?;
5227                    Some((
5228                        section.get("context").and_then(serde_json::Value::as_str),
5229                        binding.as_str(),
5230                    ))
5231                })
5232                .collect();
5233
5234            let global: Vec<&(Option<&str>, Option<&str>)> = bound
5235                .iter()
5236                .filter(|(context, _)| {
5237                    context.is_none_or(|context| WINDOW_GLOBAL_KEYMAP_CONTEXTS.contains(&context))
5238                })
5239                .collect();
5240            assert_eq!(
5241                global.len(),
5242                1,
5243                "OMEGA-DELTA-0013: {keymap} must bind {chord:?} window-globally \
5244                 exactly once. Found: {global:?}"
5245            );
5246            assert_eq!(
5247                global[0].1,
5248                Some("agent::NewThread"),
5249                "OMEGA-DELTA-0013: {keymap} binds {chord:?} window-globally to \
5250                 something other than the new agent thread, so omega#76's \
5251                 chord no longer reaches the front door."
5252            );
5253
5254            for (context, action) in &bound {
5255                let Some(context) = context else { continue };
5256                if WINDOW_GLOBAL_KEYMAP_CONTEXTS.contains(context) {
5257                    continue;
5258                }
5259                assert!(
5260                    NEW_THREAD_CHORD_NARROW_CONTEXTS.contains(context),
5261                    "OMEGA-DELTA-0013: {keymap} binds {chord:?} to {action:?} in \
5262                     context {context:?}, which shadows the window-global new-thread \
5263                     chord while that surface has focus. omega#76 asked for the \
5264                     shadowed bindings to be resolved deliberately; a new one \
5265                     appearing is not a deliberate resolution. Admitted: \
5266                     {NEW_THREAD_CHORD_NARROW_CONTEXTS:?}"
5267                );
5268            }
5269        }
5270    }
5271
5272    /// OMEGA-DELTA-0040. A first-ever launch lands on identity onboarding, and
5273    /// finishing it opens the front door.
5274    ///
5275    /// The owner decided the ordering: Omega is identity-first, so an agent
5276    /// thread before an identity would invert the thing omega#9's packet exists
5277    /// to establish. That decision is only sound while the handoff is real —
5278    /// "onboarding first" and "onboarding instead" are the same picture on a
5279    /// first launch and completely different products on the second.
5280    ///
5281    /// So the chain is checked link by link, because each link fails silently
5282    /// on its own:
5283    ///
5284    /// - the startup path *waits* — without the await, the front door would
5285    ///   open behind onboarding and Omega would be asking for an identity over
5286    ///   the top of a composer;
5287    /// - finishing *releases* the wait — without the release, completing setup
5288    ///   would leave the user on the launchpad with nothing else ever opening,
5289    ///   and no test that only looks at the front door would notice;
5290    /// - releasing *completes the channel* the startup path is parked on —
5291    ///   without that, `release_identity_waiters` is a call that returns.
5292    #[test]
5293    fn first_run_onboarding_hands_the_startup_off_to_the_front_door() {
5294        let startup_path = repository_path(STARTUP_PATH);
5295        let startup = std::fs::read_to_string(&startup_path)
5296            .unwrap_or_else(|error| panic!("cannot read {}: {error}", startup_path.display()));
5297        let restore = function_body(&startup, "restore_or_create_workspace").unwrap_or_else(|| {
5298            panic!(
5299                "OMEGA-DELTA-0040: {} no longer has a `restore_or_create_workspace`. \
5300                 A check that cannot find its subject passes for the wrong reason.",
5301                startup_path.display()
5302            )
5303        });
5304
5305        let waits_at = restore.find("await_identity_ready(").unwrap_or_else(|| {
5306            panic!(
5307                "OMEGA-DELTA-0040: `restore_or_create_workspace` in {} no longer \
5308                 waits for identity. The front door would open behind first-run \
5309                 onboarding, which is Omega asking for an identity on top of a \
5310                 composer — the inversion the owner's ordering decision rejects.",
5311                startup_path.display()
5312            )
5313        });
5314        let opens_at = restore
5315            .find("AgentPanel::open_front_door(")
5316            .unwrap_or_else(|| {
5317                panic!(
5318                    "OMEGA-DELTA-0040: `restore_or_create_workspace` in {} no \
5319                     longer opens the front door at all (OMEGA-DELTA-0019).",
5320                    startup_path.display()
5321                )
5322            });
5323        assert!(
5324            waits_at < opens_at,
5325            "OMEGA-DELTA-0040: {} opens the front door before it waits for \
5326             identity. Onboarding is first *and* the agent is what follows it; \
5327             reversing them makes the first-run window a race.",
5328            startup_path.display()
5329        );
5330
5331        let onboarding_path = repository_path(ONBOARDING_PATH);
5332        let onboarding = std::fs::read_to_string(&onboarding_path)
5333            .unwrap_or_else(|error| panic!("cannot read {}: {error}", onboarding_path.display()));
5334        let finish = function_body(&onboarding, "on_finish").unwrap_or_else(|| {
5335            panic!(
5336                "OMEGA-DELTA-0040: {} no longer has an `on_finish` to check.",
5337                onboarding_path.display()
5338            )
5339        });
5340        // The **first-run** arm specifically. `on_finish` releases the waiters
5341        // on both journeys, and the editor-setup journey is not the one the
5342        // startup path is parked on — asserting against the whole function
5343        // would let the first-run release be deleted while the check stayed
5344        // green on the other arm's copy of the same call.
5345        let first_run_arm = finish
5346            .split_once("OnboardingMode::FirstRun(window_handle) => {")
5347            .and_then(|(_, rest)| rest.split_once("OnboardingMode::EditorSetup"))
5348            .map(|(arm, _)| arm)
5349            .unwrap_or_else(|| {
5350                panic!(
5351                    "OMEGA-DELTA-0040: `on_finish` in {} no longer has a \
5352                     first-run arm to check.",
5353                    onboarding_path.display()
5354                )
5355            });
5356        assert!(
5357            first_run_arm.contains("release_identity_waiters(cx)"),
5358            "OMEGA-DELTA-0040: finishing first-run onboarding in {} no longer \
5359             releases the startup path. Setup would complete and nothing would \
5360             open: the user is left on the launchpad, the agent dock closed, \
5361             and the only way forward is relaunching the app.",
5362            onboarding_path.display()
5363        );
5364        assert!(
5365            first_run_arm.contains("window.remove_window()"),
5366            "OMEGA-DELTA-0040: the first-run branch of `on_finish` in {} no \
5367             longer closes its own window, so the front door would open beside \
5368             a finished onboarding screen rather than instead of it.",
5369            onboarding_path.display()
5370        );
5371
5372        let coordinator_path = repository_path(IDENTITY_STARTUP_PATH);
5373        let coordinator = std::fs::read_to_string(&coordinator_path)
5374            .unwrap_or_else(|error| panic!("cannot read {}: {error}", coordinator_path.display()));
5375        let release =
5376            function_body(&coordinator, "release_identity_waiters").unwrap_or_else(|| {
5377                panic!(
5378                    "OMEGA-DELTA-0040: {} no longer has a `release_identity_waiters`.",
5379                    coordinator_path.display()
5380                )
5381            });
5382        assert!(
5383            release.contains("finish(Ok(()), cx)"),
5384            "OMEGA-DELTA-0040: `release_identity_waiters` in {} no longer \
5385             completes the startup channel, so it releases nobody.",
5386            coordinator_path.display()
5387        );
5388    }
5389
5390    /// OMEGA-DELTA-0035. The router is what the native agent entry resolves to.
5391    ///
5392    /// omega#78 shipped the router unwired, which is the failure this guards:
5393    /// every piece present, tested, and reachable by nobody. Three facts, and
5394    /// each one alone is weak — the server could be built and never connected,
5395    /// the poll could exist and feed nothing, the pin could exist and be
5396    /// unreachable.
5397    #[test]
5398    fn the_router_is_wired_into_the_native_agent_entry() {
5399        let factory_path = repository_path(AGENT_SERVER_FACTORY_PATH);
5400        let factory = std::fs::read_to_string(&factory_path)
5401            .unwrap_or_else(|error| panic!("cannot read {}: {error}", factory_path.display()));
5402        assert!(
5403            factory.contains("omega_router::OmegaRouterServer::new("),
5404            "OMEGA-DELTA-0035: {} builds the native agent server directly \
5405             again, so nothing constructs an OmegaAgentConnection and every \
5406             thread discloses `route: None` with an empty journal — the state \
5407             omega#78 shipped in.",
5408            factory_path.display()
5409        );
5410
5411        let panel_path = repository_path(AGENT_PANEL_PATH);
5412        let panel = std::fs::read_to_string(&panel_path)
5413            .unwrap_or_else(|error| panic!("cannot read {}: {error}", panel_path.display()));
5414        assert!(
5415            panel.contains("observe_capacity(Ok(capacity))") && panel.contains("get_capacity()"),
5416            "OMEGA-DELTA-0035: {} no longer feeds the engine's framed \
5417             get_capacity answer into the router. Without it every engine-lane \
5418             pin is decided against a default of \"not running\" whatever \
5419             omega-effectd is actually doing.",
5420            panel_path.display()
5421        );
5422
5423        let disclosure_path = repository_path(THREAD_VIEW_PATH);
5424        let disclosure = std::fs::read_to_string(&disclosure_path)
5425            .unwrap_or_else(|error| panic!("cannot read {}: {error}", disclosure_path.display()));
5426        assert!(
5427            disclosure.contains("\"omega-executor-pin\""),
5428            "OMEGA-DELTA-0035: {} no longer renders the executor pin control. \
5429             A pin is the only way a thread reaches anything but the native \
5430             loop, so with no control there is no route to honour.",
5431            disclosure_path.display()
5432        );
5433    }
5434
5435    /// OMEGA-DELTA-0035, and owner gate 8 behind it.
5436    ///
5437    /// A pin is the only door to an engine lane and an engine lane *is* Full
5438    /// Auto authority, so the gate reaches the pin as directly as it reaches
5439    /// the Start button. The guard is the argument type: every pin-setting call
5440    /// must pass a literal `PinGesture::` variant, so a caller cannot launder
5441    /// a gesture it was handed by something model-facing.
5442    ///
5443    /// Scanned across every crate rather than the one file, because the failure
5444    /// worth catching is a *new* caller somewhere else.
5445    #[test]
5446    fn only_a_named_human_gesture_can_pin_an_executor() {
5447        let crates = repository_path("crates");
5448        let mut calls: Vec<(String, String)> = Vec::new();
5449        for_each_source_file(&crates, &["rs"], |path, source| {
5450            let display = path
5451                .display()
5452                .to_string()
5453                .rsplit("crates/")
5454                .next()
5455                .unwrap_or_default()
5456                .to_owned();
5457            // This file is the check itself; matching its own needles would
5458            // make the count meaningless.
5459            if display.starts_with("omega_deltas/") {
5460                return;
5461            }
5462            for (index, line) in source.lines().enumerate() {
5463                let trimmed = line.trim();
5464                // The declarations are not calls. `fn pin_session(` and a
5465                // doc-comment mentioning it are both skipped here so the scan
5466                // counts callers only.
5467                if trimmed.starts_with("//")
5468                    || trimmed.starts_with("pub fn ")
5469                    || trimmed.starts_with("fn ")
5470                {
5471                    continue;
5472                }
5473                if !PIN_SETTING_CALLS.iter().any(|call| trimmed.contains(call)) {
5474                    continue;
5475                }
5476                // Reassemble the whole call, because rustfmt puts the arguments
5477                // of a nested call on their own lines. Walking forward to the
5478                // line whose parens balance is what makes this a check on the
5479                // *argument list* rather than on one line of it — the earlier
5480                // draft accepted any line ending in `(` or `,`, which passed
5481                // for every multi-line call regardless of its arguments.
5482                let mut statement = String::new();
5483                let mut depth = 0i32;
5484                for following in source.lines().skip(index) {
5485                    statement.push_str(following.trim());
5486                    statement.push(' ');
5487                    for character in following.chars() {
5488                        match character {
5489                            '(' => depth += 1,
5490                            ')' => depth -= 1,
5491                            _ => {}
5492                        }
5493                    }
5494                    if depth <= 0 {
5495                        break;
5496                    }
5497                }
5498                calls.push((display.clone(), statement));
5499            }
5500        });
5501
5502        assert!(
5503            !calls.is_empty(),
5504            "OMEGA-DELTA-0035: no pin-setting call was found anywhere. Either \
5505             the pin control is gone or this scan stopped matching, and both \
5506             make the gate vacuous."
5507        );
5508
5509        for (file, statement) in &calls {
5510            assert!(
5511                statement.contains("PinGesture::"),
5512                "OMEGA-DELTA-0035: {file} sets a pin without naming a literal \
5513                 PinGesture: {statement:?}. Owner gate 8 admits only an \
5514                 explicit human action into Full Auto authority, a pin is the \
5515                 only door to an engine lane, and a gesture the caller was \
5516                 *handed* is exactly the laundering the literal forbids."
5517            );
5518        }
5519    }
5520
5521    /// OMEGA-DELTA-0035. Nothing asks "is this the native agent?" with a bare
5522    /// downcast.
5523    ///
5524    /// The first-party agent is a router over the native server now. A bare
5525    /// `downcast::<NativeAgentServer>()` on it returns `None`, which reads as
5526    /// "this is an external agent" — a silently wrong `false`, not a compile
5527    /// error. The two call sites that ask this question go through
5528    /// `is_native_agent_server`, and this fails if a third appears.
5529    #[test]
5530    fn nothing_asks_for_the_native_agent_with_a_bare_downcast() {
5531        let crates = repository_path("crates");
5532        let mut bare: Vec<(String, String)> = Vec::new();
5533        for_each_source_file(&crates, &["rs"], |path, source| {
5534            let display = path
5535                .display()
5536                .to_string()
5537                .rsplit("crates/")
5538                .next()
5539                .unwrap_or_default()
5540                .to_owned();
5541            if display.starts_with("omega_deltas/")
5542                // The unwrapping helpers are where the bare downcast belongs.
5543                || display.starts_with("agent_ui/src/omega_router.rs")
5544                // omega#77's disclosure classifies a *thread's* connection,
5545                // which is the executor's and never the router's.
5546                || display.starts_with("agent_ui/src/omega_executor_disclosure.rs")
5547            {
5548                return;
5549            }
5550            for line in source.lines() {
5551                let line = line.trim();
5552                if line.contains("downcast::<agent::NativeAgentServer>()")
5553                    || line.contains("downcast::<NativeAgentServer>()")
5554                {
5555                    bare.push((display.clone(), line.to_owned()));
5556                }
5557            }
5558        });
5559        assert!(
5560            bare.is_empty(),
5561            "OMEGA-DELTA-0035: {} place(s) still ask for the native agent \
5562             server with a bare downcast: {bare:#?}. The native agent is \
5563             wrapped by the router, so this answers `false` for the \
5564             first-party agent instead of failing to compile. Use \
5565             `omega_router::is_native_agent_server`.",
5566            bare.len()
5567        );
5568    }
5569
5570    /// The parser has to actually strip comments, or every check reads `None`
5571    /// and silently passes.
5572    #[test]
5573    fn the_settings_parser_reaches_real_values() {
5574        let settings = default_settings().expect("default settings parse");
5575        assert!(
5576            default_setting(&settings, "session.restore_unsaved_buffers").is_some(),
5577            "settings parser did not reach a known key; the checks would be vacuous"
5578        );
5579        assert!(
5580            default_setting(&settings, "session.no_such_key").is_none(),
5581            "settings lookup must return None for an absent key"
5582        );
5583    }
5584
5585    // ------ OMEGA-DELTA-0032
5586
5587    /// OMEGA-DELTA-0032. Upstream Zed decides a send during a running turn in
5588    /// the view: `MessageQueue::front_wants_steer` sets a boundary flag on the
5589    /// native thread, and every other executor falls through to a cancel. That
5590    /// is three different behaviours behind one button, and the user cannot
5591    /// tell which one they got.
5592    ///
5593    /// Omega decides it with a total law over all three executor classes. This
5594    /// checks the law is where the delta says it is and answers for each class
5595    /// by name — a law that never mentions a class cannot have declared
5596    /// anything for it.
5597    #[test]
5598    fn the_send_during_turn_law_answers_for_every_executor_class() {
5599        let path = repository_path(SEND_DURING_TURN_PATH);
5600        let source = std::fs::read_to_string(&path).expect("the send law is readable");
5601        for token in SEND_LAW_EXECUTOR_TOKENS {
5602            assert!(
5603                source.contains(&format!("ExecutorClass::{token}")),
5604                "OMEGA-DELTA-0035: {} does not answer for ExecutorClass::{token}.                  A class the law does not name has no declared behaviour, which                  is the state this delta replaces.",
5605                path.display()
5606            );
5607        }
5608        assert!(
5609            source.contains("pub const fn disposition("),
5610            "OMEGA-DELTA-0035: the law must be a const fn of its inputs. A              disposition that can read anything else is not reproducible from a              journal."
5611        );
5612    }
5613
5614    /// OMEGA-DELTA-0032. The law and the journal are pure the way the router is
5615    /// pure. A queued message restored from disk re-derives its disposition, so
5616    /// a clock or a hash order in either file would make the same record decide
5617    /// differently on the next launch.
5618    #[test]
5619    fn the_queue_law_and_its_journal_read_nothing_but_their_inputs() {
5620        for relative in [SEND_DURING_TURN_PATH, SEND_QUEUE_JOURNAL_PATH] {
5621            let path = repository_path(relative);
5622            let source = std::fs::read_to_string(&path).expect("readable");
5623            // The test module is allowed a temporary directory and its own
5624            // scaffolding; the law is not.
5625            let production = source
5626                .split("#[cfg(test)]")
5627                .next()
5628                .expect("a file has a first section");
5629            for (why, token) in NON_DETERMINISTIC_QUEUE_TOKENS {
5630                assert!(
5631                    !production.contains(token),
5632                    "OMEGA-DELTA-0035: {} reads {why} (`{token}`). The queue is                      replayed from a journal, and a decision that depends on                      {why} does not replay.",
5633                    path.display()
5634                );
5635            }
5636        }
5637    }
5638
5639    /// OMEGA-DELTA-0032. The composer asks the law rather than reading the
5640    /// steer flag.
5641    ///
5642    /// This is the exact upstream line the delta replaces. Reading
5643    /// `front_wants_steer` to set the boundary flag is what made "steer" mean
5644    /// "end at a boundary" on the native loop and "cancel the turn" everywhere
5645    /// else, and it is why an engine lane and an external ACP peer both got a
5646    /// behaviour nobody declared for them.
5647    #[test]
5648    fn the_composer_decides_a_mid_turn_send_through_the_law() {
5649        let path = repository_path(CONVERSATION_SEND_PATH);
5650        let source = std::fs::read_to_string(&path).expect("the composer is readable");
5651        assert!(
5652            source.contains("omega_front_door::disposition("),
5653            "OMEGA-DELTA-0035: {} no longer calls the send law. Deciding a              mid-turn send in the view is the upstream behaviour this delta              replaces.",
5654            path.display()
5655        );
5656        assert!(
5657            source.contains("SendDisposition::SteerAtMessageBoundary"),
5658            "OMEGA-DELTA-0035: the boundary flag must be set from the law's              own answer, not from a steer flag the other two classes never see."
5659        );
5660        assert!(
5661            source.contains(".reaches_running_turn()"),
5662            "OMEGA-DELTA-0035: {} must gate its cancel on whether this              executor's declared answer reaches the running turn. An              unconditional cancel turns a refused steer into an interrupted              turn.",
5663            path.display()
5664        );
5665    }
5666
5667    /// OMEGA-DELTA-0032. Queue state is durable, and its acknowledgement is the
5668    /// write.
5669    ///
5670    /// Upstream holds the queue on the view: `Entity<MessageEditor>` handles in
5671    /// a `VecDeque` that dies with the panel. A message the composer had
5672    /// already called "queued" did not exist after a restart. The falsifier for
5673    /// omega#79 names this directly.
5674    #[test]
5675    fn the_send_queue_is_a_durable_record_and_not_renderer_memory() {
5676        let path = repository_path(SEND_QUEUE_JOURNAL_PATH);
5677        let source = std::fs::read_to_string(&path).expect("the journal is readable");
5678        assert!(
5679            source.contains("openagents.omega.agent_send_queue.v1"),
5680            "OMEGA-DELTA-0035: the durable queue must carry a schema, so a              foreign document is refused rather than adopted."
5681        );
5682        assert!(
5683            source.contains("std::fs::rename(&temporary, &self.path)"),
5684            "OMEGA-DELTA-0035: {} must rewrite atomically. A crash mid-write              must leave the previous queue, not a truncated one.",
5685            path.display()
5686        );
5687        assert!(
5688            !source.contains("Entity<MessageEditor>"),
5689            "OMEGA-DELTA-0035: a live GPUI handle cannot be a durable fact.              That is exactly what made the upstream queue renderer-only."
5690        );
5691    }
5692
5693    // ------------------------------------------------------ OMEGA-DELTA-0033
5694
5695    /// OMEGA-DELTA-0033. The front door renders the decision; it does not make
5696    /// one.
5697    ///
5698    /// omega#81 landed a decision layer nothing rendered, and the settings page
5699    /// is the first thing to render it. The risk that creates is a page that
5700    /// starts deciding: an `if` on a pin, a locally composed reason, a control
5701    /// enabled because the widget thought it should be. Any of those and the
5702    /// front door and the launch gate can disagree, which shows up to an owner
5703    /// as a button that looks live and then fails.
5704    ///
5705    /// So the page may match on the decision layer's types and may not call the
5706    /// decision functions itself.
5707    #[test]
5708    fn the_front_door_page_renders_decisions_it_did_not_make() {
5709        let path = repository_path(EXTERNAL_AGENTS_PAGE_PATH);
5710        let source = std::fs::read_to_string(&path)
5711            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
5712
5713        assert!(
5714            source.contains("PinControl::Take")
5715                && source.contains("PinControl::Remove")
5716                && source.contains("PinControl::Unavailable"),
5717            "OMEGA-DELTA-0033: {} must render all three pin-control states. A \
5718             page that renders two of them silently drops the case where the \
5719             control is withheld, which is the case that needs a sentence most.",
5720            path.display()
5721        );
5722        for decider in [
5723            "decide_maintenance(",
5724            "admits_version(",
5725            "admits_package_manager_launch(",
5726            "update_affordance(",
5727            "harness_front_door_state(",
5728        ] {
5729            assert!(
5730                !source.contains(decider),
5731                "OMEGA-DELTA-0033: {} calls {decider} itself. The page must \
5732                 render the state the store computed, or the row and the gate \
5733                 become two answers to the same question.",
5734                path.display()
5735            );
5736        }
5737        assert!(
5738            !source.contains("MaintenanceAffordance::Disabled"),
5739            "OMEGA-DELTA-0033: {} constructs a refusal of its own. Every \
5740             sentence on this page comes from omega_harness.",
5741            path.display()
5742        );
5743    }
5744
5745    /// OMEGA-DELTA-0033. A withheld control still says why.
5746    ///
5747    /// The reason `MaintenanceAffordance::Disabled` carries a `String` rather
5748    /// than an `Option<String>` is that omega 0.2.0-rc11 shipped a refusal
5749    /// nobody could see. [`PinControl`] has to hold the same shape, and the
5750    /// page has to put both sentences somewhere a person reads.
5751    #[test]
5752    fn a_withheld_control_carries_a_sentence_all_the_way_to_the_widget() {
5753        let decisions = repository_path(HARNESS_FRONT_DOOR_PATH);
5754        let source = std::fs::read_to_string(&decisions)
5755            .unwrap_or_else(|error| panic!("cannot read {}: {error}", decisions.display()));
5756        assert!(
5757            source.contains("Unavailable { reason: String }")
5758                || source.contains("Unavailable {\n        /// The sentence")
5759                || source.contains("Unavailable { reason: String },"),
5760            "OMEGA-DELTA-0033: {} must make the withheld pin control carry its \
5761             reason by construction. An `Option` here is a control that can be \
5762             withheld silently.",
5763            decisions.display()
5764        );
5765
5766        let page = repository_path(EXTERNAL_AGENTS_PAGE_PATH);
5767        let rendered = std::fs::read_to_string(&page)
5768            .unwrap_or_else(|error| panic!("cannot read {}: {error}", page.display()));
5769        assert!(
5770            rendered.contains("state.launch.reason()"),
5771            "OMEGA-DELTA-0033: {} no longer renders the launch refusal. A \
5772             refusal that reaches the owner only as agent-launch error text is \
5773             the gap omega#81 stayed open for.",
5774            page.display()
5775        );
5776        assert!(
5777            rendered.contains("PinControl::Unavailable { reason }")
5778                && rendered
5779                    .contains("Tooltip::with_meta(\"Cannot Pin\", None, reason.clone(), cx)"),
5780            "OMEGA-DELTA-0033: {} must show the withheld control's reason. A \
5781             disabled button with no sentence reads as a bug in Omega rather \
5782             than as a fact about the owner's machine.",
5783            page.display()
5784        );
5785    }
5786
5787    /// OMEGA-DELTA-0033. The pin controls exist in production code.
5788    ///
5789    /// `HarnessPinLedger::set_pin` and `remove_pin` existed before this delta
5790    /// and were called only by tests: the ledger was a JSON file with no writer
5791    /// Omega shipped. A "pin" an owner can only take by hand-editing a file is
5792    /// not a control, and the standing rule is that owner-facing operations get
5793    /// working controls rather than a runbook.
5794    #[test]
5795    fn the_pin_ledger_has_a_writer_the_owner_can_reach() {
5796        let filesystem = repository_path(HARNESS_MAINTENANCE_PATH);
5797        let source = std::fs::read_to_string(&filesystem)
5798            .unwrap_or_else(|error| panic!("cannot read {}: {error}", filesystem.display()));
5799        for writer in [
5800            "pub async fn pin_installed_harness(",
5801            "pub async fn unpin_harness(",
5802        ] {
5803            assert!(
5804                source.contains(writer),
5805                "OMEGA-DELTA-0033: {} no longer offers {writer}. Without it the \
5806                 ledger is a file the owner must edit by hand.",
5807                filesystem.display()
5808            );
5809        }
5810        assert!(
5811            source.contains("encode_harness_pin_ledger(ledger)?"),
5812            "OMEGA-DELTA-0033: {} must write the ledger through its own \
5813             encoder, which routes back through the reader. A writer that can \
5814             emit a file its reader refuses turns the next restart into the \
5815             moment every pin fails closed.",
5816            filesystem.display()
5817        );
5818
5819        let page = repository_path(EXTERNAL_AGENTS_PAGE_PATH);
5820        let rendered = std::fs::read_to_string(&page)
5821            .unwrap_or_else(|error| panic!("cannot read {}: {error}", page.display()));
5822        assert!(
5823            rendered.contains("this.pin_harness(&id, cx)")
5824                && rendered.contains("this.unpin_harness(&id, cx)"),
5825            "OMEGA-DELTA-0033: {} must wire both pin controls to something a \
5826             person can press.",
5827            page.display()
5828        );
5829    }
5830
5831    /// OMEGA-DELTA-0033. The npx launch path consults the ledger.
5832    ///
5833    /// `LocalRegistryNpxAgent` resolves its package inside the node runtime's
5834    /// own cache, so there is no tree for the measured gate to hash — and
5835    /// before this delta that meant pinning such a harness did nothing at all.
5836    /// The owner's "not that one" has to refuse even where Omega cannot verify
5837    /// the bytes, or the pin is a decoration.
5838    #[test]
5839    fn the_package_manager_launch_path_is_gated_on_the_pin() {
5840        let path = repository_path(AGENT_SERVER_STORE_PATH);
5841        let source = std::fs::read_to_string(&path)
5842            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
5843
5844        let gate = source
5845            .find("authorize_package_manager_launch(")
5846            .unwrap_or_else(|| {
5847                panic!(
5848                    "OMEGA-DELTA-0033: {} no longer consults the pin on the \
5849                     package-manager launch path",
5850                    path.display()
5851                )
5852            });
5853        // Same rule as OMEGA-DELTA-0025: the refusal must stop the launch, not
5854        // be logged beside it.
5855        let tail = &source[gate..];
5856        let end = tail.find(';').expect("the call statement ends");
5857        assert!(
5858            tail[..end].contains(".await?"),
5859            "OMEGA-DELTA-0033: the result of authorize_package_manager_launch \
5860             is not propagated in {}. A refusal that does not stop the launch \
5861             is not a refusal.",
5862            path.display()
5863        );
5864
5865        let npx_command = source
5866            .find("let command = AgentServerCommand {")
5867            .map(|_| {
5868                source[gate..]
5869                    .find("let command = AgentServerCommand {")
5870                    .map(|offset| gate + offset)
5871                    .expect("the npx command is constructed after the gate")
5872            })
5873            .expect("a command is constructed somewhere");
5874        assert!(
5875            gate < npx_command,
5876            "OMEGA-DELTA-0033: the package-manager gate no longer precedes the \
5877             command it gates in {}",
5878            path.display()
5879        );
5880    }
5881
5882    /// OMEGA-DELTA-0033. Resolving the channel is its own recorded action.
5883    ///
5884    /// omega#81's first deliverable named four actions and landed three.
5885    /// Resolving what the channel advertises happens when nothing is about to
5886    /// launch, so if it is not recorded there it is not recorded at all — and a
5887    /// frozen harness offered an update it will refuse is the front door
5888    /// promising what the gate takes back.
5889    #[test]
5890    fn resolving_a_channel_is_a_recorded_action_that_gates_the_offer() {
5891        let filesystem = repository_path(HARNESS_MAINTENANCE_PATH);
5892        let source = std::fs::read_to_string(&filesystem)
5893            .unwrap_or_else(|error| panic!("cannot read {}: {error}", filesystem.display()));
5894        assert!(
5895            source.contains("MaintenanceAction::ResolveChannel"),
5896            "OMEGA-DELTA-0033: {} no longer records channel resolution under \
5897             its own action.",
5898            filesystem.display()
5899        );
5900        assert!(
5901            source.contains("MaintenanceAction::ReprobeCapability"),
5902            "OMEGA-DELTA-0033: {} no longer records a re-probe under its own \
5903             action. Collapsing it into Verify would leave the log unable to \
5904             say whether a measurement was taken because something was about \
5905             to run or because a person asked.",
5906            filesystem.display()
5907        );
5908
5909        let store = repository_path(AGENT_SERVER_STORE_PATH);
5910        let launch = std::fs::read_to_string(&store)
5911            .unwrap_or_else(|error| panic!("cannot read {}: {error}", store.display()));
5912        let resolve = launch.find("resolve_channel(").unwrap_or_else(|| {
5913            panic!(
5914                "OMEGA-DELTA-0033: {} no longer resolves the channel before \
5915                 announcing a new version",
5916                store.display()
5917            )
5918        });
5919        let announce = launch[resolve..]
5920            .find("tx.send(Some(version))")
5921            .map(|offset| resolve + offset)
5922            .unwrap_or_else(|| {
5923                panic!(
5924                    "OMEGA-DELTA-0033: no version is announced after the \
5925                     channel is resolved in {}. Either the announcement moved \
5926                     above the gate or it moved out of reach of this check.",
5927                    store.display()
5928                )
5929            });
5930        assert!(
5931            resolve < announce,
5932            "OMEGA-DELTA-0033: a version is announced before the pin is \
5933             consulted in {}",
5934            store.display()
5935        );
5936    }
5937
5938    /// OMEGA-DELTA-0033. The front door measures the tree the launch path
5939    /// gates.
5940    ///
5941    /// The measured tree is not the installation directory — it is a version
5942    /// directory whose name is derived from the version, the archive URL and
5943    /// its checksum. A settings page that measured the parent would attest a
5944    /// different set of bytes than the gate reads, and would then show
5945    /// "verified" for an installation the launch path refuses.
5946    #[test]
5947    fn the_front_door_measures_the_tree_the_launch_path_gates() {
5948        let path = repository_path(AGENT_SERVER_STORE_PATH);
5949        let source = std::fs::read_to_string(&path)
5950            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
5951        // Tests call it freely; production must not. Two derivations of the
5952        // measured tree outside the test module are the launch path's and the
5953        // front door's, and they are what this check pins.
5954        let production = source
5955            .split_once("#[cfg(test)]")
5956            .map(|(before, _)| before)
5957            .unwrap_or(source.as_str());
5958        assert_eq!(
5959            production.matches("versioned_archive_cache_dir(").count(),
5960            3,
5961            "OMEGA-DELTA-0033: {} must derive the measured tree in exactly the \
5962             places this check knows about — the definition, the launch path, \
5963             and the front door's target. A new caller is a new way for the row \
5964             and the gate to disagree.",
5965            path.display()
5966        );
5967        assert!(
5968            source.contains("fn installed_version_dir(&self) -> Option<PathBuf>"),
5969            "OMEGA-DELTA-0033: {} no longer tells the front door which tree the \
5970             launch path measures.",
5971            path.display()
5972        );
5973    }
5974
5975    /// OMEGA-DELTA-0036. `--uninstall` removes Omega and nothing else.
5976    ///
5977    /// The shipped, signed `0.2.0-rc14` advertised `--uninstall` as "Uninstall
5978    /// Omega from user system" and ran upstream's uninstaller verbatim: it
5979    /// deleted the other editor's application bundle, its whole
5980    /// application-support tree, its logs, caches, preferences and saved state,
5981    /// asked whether to keep *that* product's preferences, printed that *that*
5982    /// product had been uninstalled — and removed no Omega path at all
5983    /// (omega#88).
5984    ///
5985    /// The end-to-end proof lives in `crates/cli/src/uninstall.rs`, where the
5986    /// real script runs against a fabricated home holding both an Omega
5987    /// installation and another product's, and both halves are read back. This
5988    /// asserts the two structural properties that made the defect possible: the
5989    /// script names no other product, and it has no path table of its own.
5990    #[test]
5991    fn the_uninstall_path_removes_omega_and_names_no_competitor() {
5992        let policy = brand_policy().expect("brand policy parses");
5993        let script_path = repository_path(UNINSTALL_SCRIPT_PATH);
5994        let script = std::fs::read_to_string(&script_path)
5995            .unwrap_or_else(|error| panic!("cannot read {}: {error}", script_path.display()));
5996
5997        let hits = brand_hits(&script, &policy);
5998        assert!(
5999            hits.is_empty(),
6000            "OMEGA-DELTA-0036: {UNINSTALL_SCRIPT_PATH} names {hits:?}. It is \
6001             embedded in the signed `cli` binary with include_bytes! and it \
6002             removes whatever it names, so a competitor's directory appearing \
6003             here is a destructive regression, not a copy regression."
6004        );
6005
6006        for required in ["OMEGA_UNINSTALL_PATHS", "OMEGA_UNINSTALL_PRODUCT"] {
6007            assert!(
6008                script.contains(required),
6009                "OMEGA-DELTA-0036: {UNINSTALL_SCRIPT_PATH} no longer reads \
6010                 {required} from the caller, so it has a hand-written path \
6011                 table again. A table disconnected from the code that creates \
6012                 those directories is exactly how omega#88 shipped."
6013            );
6014        }
6015
6016        // Every root the plan removes is read from the function that writes it.
6017        let plan_path = repository_path(UNINSTALL_PLAN_PATH);
6018        let plan = std::fs::read_to_string(&plan_path)
6019            .unwrap_or_else(|error| panic!("cannot read {}: {error}", plan_path.display()));
6020        let constructor = plan
6021            .split("pub fn from_installed_paths")
6022            .nth(1)
6023            .expect("OMEGA-DELTA-0036: from_installed_paths is gone");
6024        let derived = constructor.matches("paths::").count();
6025        assert!(
6026            derived >= 6,
6027            "OMEGA-DELTA-0036: from_installed_paths makes only {derived} \
6028             `paths::` calls. Every root has to come from the function that \
6029             writes it; a literal path here is a second source of truth, and \
6030             the first one that disagreed cost a user their other editor."
6031        );
6032        assert!(
6033            plan.contains("let Self {"),
6034            "OMEGA-DELTA-0036: {} no longer destructures UninstallRoots \
6035             exhaustively in `plan`, so a root can be added to the struct and \
6036             silently left out of the plan.",
6037            plan_path.display()
6038        );
6039
6040        // The script itself, run for real, refuses a plan it cannot trust.
6041        #[allow(
6042            clippy::disallowed_methods,
6043            reason = "A gate that only reads the script cannot tell whether it \
6044                      refuses; this one runs it. There is no async runtime here."
6045        )]
6046        let output = std::process::Command::new("sh")
6047            .arg(&script_path)
6048            .env("OMEGA_UNINSTALL_PRODUCT", "Omega RC")
6049            .env("OMEGA_UNINSTALL_PATHS", "")
6050            .output()
6051            .expect("run the uninstall script");
6052        assert!(
6053            !output.status.success(),
6054            "OMEGA-DELTA-0036: the uninstall script accepted an empty plan. \
6055             Refusing is the safe direction; every default this file has ever \
6056             had belonged to somebody else's product."
6057        );
6058    }
6059
6060    /// OMEGA-DELTA-0043. `--uninstall` plans the installation, not one file.
6061    ///
6062    /// `0.2.0-rc16` fixed the destructive half of omega#88 and still did not
6063    /// remove Omega: `main.rs` handed `app.path()` — `Omega.app/Contents/MacOS/
6064    /// omega` — to a field documented as "the application bundle or executable",
6065    /// so a completed uninstall left `/Applications/Omega.app` in place with
6066    /// 130.9 MB, five executables including a `cli` that still carries
6067    /// `--uninstall`, and a bundled Node runtime (omega#92).
6068    ///
6069    /// The behavioural proof is in `crates/cli/src/uninstall.rs`, where the
6070    /// shipped script runs against a fabricated home whose bundle holds several
6071    /// executables and every one of them is read back. This asserts the two
6072    /// structural properties: the call site asks for the installation rather
6073    /// than the executable, and the constructor normalizes what it is given so
6074    /// a caller cannot reintroduce the defect from outside.
6075    #[test]
6076    fn the_uninstall_plan_names_the_installation_root() {
6077        let plan_path = repository_path(UNINSTALL_PLAN_PATH);
6078        let plan = std::fs::read_to_string(&plan_path)
6079            .unwrap_or_else(|error| panic!("cannot read {}: {error}", plan_path.display()));
6080        assert!(
6081            plan.contains("pub fn installation_root("),
6082            "OMEGA-DELTA-0043: {} no longer derives an installation root, so \
6083             whatever path a caller happens to be holding is what gets removed.",
6084            plan_path.display()
6085        );
6086        let constructor = plan
6087            .split("pub fn from_installed_paths")
6088            .nth(1)
6089            .and_then(|tail| tail.split("\n    }").next())
6090            .expect("OMEGA-DELTA-0043: from_installed_paths is gone");
6091        assert!(
6092            constructor.contains("installation_root"),
6093            "OMEGA-DELTA-0043: from_installed_paths takes the caller's path as \
6094             the installation root. Every macOS caller holds an executable \
6095             inside the bundle, and removing it is not an uninstall."
6096        );
6097
6098        let main_path = repository_path(CLI_MAIN_PATH);
6099        let main = std::fs::read_to_string(&main_path)
6100            .unwrap_or_else(|error| panic!("cannot read {}: {error}", main_path.display()));
6101        let call = main
6102            .split("from_installed_paths(")
6103            .nth(1)
6104            .expect("OMEGA-DELTA-0043: the uninstall call site is gone");
6105        let call = &call[..call.find(')').unwrap_or(call.len())];
6106        assert!(
6107            call.contains("installation_root"),
6108            "OMEGA-DELTA-0043: {} passes {call:?} to the uninstaller. \
6109             `path()` is one executable inside `Omega.app`; \
6110             `installation_root()` is the installation.",
6111            main_path.display()
6112        );
6113        assert!(
6114            main.contains("fn installation_root(&self) -> PathBuf;"),
6115            "OMEGA-DELTA-0043: InstalledApp no longer distinguishes the \
6116             executable from the installation. One method answering both \
6117             questions is what shipped omega#92."
6118        );
6119    }
6120
6121    /// OMEGA-DELTA-0037. Omega identifies itself to third parties as Omega.
6122    ///
6123    /// `X-Title` is displayed to the account holder in their own OpenRouter
6124    /// dashboard, so it is outbound product identity rather than a wire
6125    /// contract. Every request Omega made through `0.2.0-rc14` announced a
6126    /// different editor, and `HTTP-Referer` pointed at that editor's site
6127    /// (omega#89).
6128    #[test]
6129    fn outbound_attribution_names_omega() {
6130        let path = repository_path(OPEN_ROUTER_PATH);
6131        let source = std::fs::read_to_string(&path)
6132            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6133        let titles = source.matches(".header(\"X-Title\"").count();
6134        assert!(
6135            titles >= 2,
6136            "OMEGA-DELTA-0037: {} sets X-Title on {titles} request paths; both \
6137             the streaming and the non-streaming call carry it.",
6138            path.display()
6139        );
6140        assert!(
6141            !source.contains("\"Zed Editor\"") && !source.contains("\"https://zed.dev\""),
6142            "OMEGA-DELTA-0037: {} identifies Omega to OpenRouter as a different \
6143             product. The user reads this value in their own dashboard.",
6144            path.display()
6145        );
6146        assert_eq!(
6147            source.matches("app_identity::PRODUCT_NAME").count(),
6148            titles,
6149            "OMEGA-DELTA-0037: every X-Title must come from the identity \
6150             constant, so a rebase cannot restore a literal on one path only."
6151        );
6152    }
6153
6154    /// OMEGA-DELTA-0038. The packaged gate opens every executable that ships,
6155    /// and reads help as clap renders it.
6156    ///
6157    /// Both halves of this delta are the same failure. `script/bundle-omega-rc`
6158    /// copies and signs three binaries into `Contents/MacOS`; every packaged
6159    /// check in the brand gate opened one of them, so the uninstaller inside
6160    /// `cli` was outside every check that had ever run (omega#88). And every
6161    /// prose stream reads *source*, while clap builds the sentence a person
6162    /// reads at run time — joining doc lines, resolving `cfg_attr`, printing
6163    /// the flag name beside the text — so `--zed <ZED>`, `Run zed in the
6164    /// foreground` and a `--user-data-dir` line naming the wrong product's data
6165    /// directory all shipped under a green gate (omega#89).
6166    #[test]
6167    fn the_packaged_gate_opens_every_shipped_executable_and_reads_rendered_help() {
6168        let verifier =
6169            std::fs::read_to_string(repository_path(BRAND_VERIFIER_PATH)).expect("brand verifier");
6170        let bundler =
6171            std::fs::read_to_string(repository_path(RC_BUNDLE_SCRIPT_PATH)).expect("bundle script");
6172
6173        // Derived, not listed: whatever the packaging script writes into
6174        // Contents/MacOS is what the gate has to be able to open.
6175        let marker = "${app_path}/Contents/MacOS/";
6176        let mut shipped: Vec<&str> = bundler
6177            .match_indices(marker)
6178            .filter_map(|(at, _)| {
6179                bundler[at + marker.len()..]
6180                    .split(['"', '\'', ' ', '\n'])
6181                    .next()
6182                    .filter(|name| !name.is_empty() && !name.contains('/'))
6183            })
6184            .collect();
6185        shipped.sort_unstable();
6186        shipped.dedup();
6187        assert!(
6188            shipped.len() >= 3,
6189            "OMEGA-DELTA-0038: only {shipped:?} were found being written into \
6190             Contents/MacOS by {RC_BUNDLE_SCRIPT_PATH}; the parser broke and \
6191             this check is reporting green about nothing."
6192        );
6193
6194        let policy = brand_policy().expect("brand policy parses");
6195        let floor = policy["packaged"]["minimum_executables"]
6196            .as_u64()
6197            .expect("packaged.minimum_executables") as usize;
6198        assert!(
6199            floor >= shipped.len(),
6200            "OMEGA-DELTA-0038: the bundle ships {} executables ({shipped:?}) \
6201             but the gate's floor is {floor}. A bundle that ships a companion \
6202             binary and a scan that expects fewer is the shape omega#88 \
6203             shipped in.",
6204            shipped.len()
6205        );
6206
6207        assert!(
6208            verifier.contains("def bundle_executables("),
6209            "OMEGA-DELTA-0038: {BRAND_VERIFIER_PATH} no longer derives the set \
6210             of executables it opens by walking the bundle."
6211        );
6212        // One accessor names the main binary; nothing else may name a binary.
6213        // The code form is counted, not the prose form, so the docstring that
6214        // explains why is not itself a violation.
6215        let hardcoded = verifier.matches("app / \"Contents/MacOS/").count();
6216        assert_eq!(
6217            hardcoded, 1,
6218            "OMEGA-DELTA-0038: {BRAND_VERIFIER_PATH} names a path under \
6219             Contents/MacOS {hardcoded} times. Exactly one — the `main_binary` \
6220             accessor — is allowed; every other check reads the derived \
6221             inventory, because a check that opens one remembered binary is \
6222             what let a destructive uninstaller ship twice."
6223        );
6224        for required in [
6225            "def check_rendered_help(",
6226            "def check_packaged_first_party_agent(",
6227            "def check_packaged_executable_inventory(",
6228            "check_rendered_help(APP)",
6229            "check_packaged_first_party_agent(APP)",
6230            "check_packaged_executable_inventory(APP)",
6231        ] {
6232            assert!(
6233                verifier.contains(required),
6234                "OMEGA-DELTA-0038: {BRAND_VERIFIER_PATH} is missing {required:?}. \
6235                 A check that is defined and never called is the state \
6236                 first_party_agent.phrases was in for four release candidates."
6237            );
6238        }
6239        assert!(
6240            verifier.contains("\"--version\"") && verifier.contains("\"--help\""),
6241            "OMEGA-DELTA-0038: the rendered-output gate no longer runs the \
6242             shipped binaries with --help and --version, so it is reading \
6243             source again."
6244        );
6245    }
6246
6247    /// OMEGA-DELTA-0031, widened. Lowercase `zed`, and doc comments written the
6248    /// long way.
6249    ///
6250    /// Two structural causes behind omega#89, both of which would have survived
6251    /// a fix that only edited the offending strings.
6252    ///
6253    /// `brand.words` held `Zed` alone, and the reason recorded for excluding
6254    /// the lowercase spelling — that it is a substring of `authorized` — was
6255    /// false, because the boundary rule already excludes that. The exclusion is
6256    /// what hid the rendered `--help` of both shipped binaries.
6257    ///
6258    /// And the doc scanner matched `///` and `//!` only, so it never read
6259    /// `#[cfg_attr(target_os = "macos", doc = "…")]` — which is exactly where
6260    /// `cli --help` took the wrong product's data directory from.
6261    #[test]
6262    fn the_doc_scanner_reads_every_spelling_of_a_doc_comment() {
6263        let policy = brand_policy().expect("brand policy parses");
6264        let words: Vec<&str> = policy["brand"]["words"]
6265            .as_array()
6266            .expect("brand.words")
6267            .iter()
6268            .filter_map(serde_json::Value::as_str)
6269            .collect();
6270        assert!(
6271            words.contains(&"zed"),
6272            "OMEGA-DELTA-0031: brand.words is {words:?}. The lowercase spelling \
6273             is what `Run zed in the foreground` is written in, and it is the \
6274             boundary rule — not the case — that keeps `authorized` out."
6275        );
6276        for benign in ["authorized", "normalized", "organized", "customized"] {
6277            assert!(
6278                brand_hits(benign, &policy).is_empty(),
6279                "OMEGA-DELTA-0031: {benign:?} is reported as a brand hit. The \
6280                 boundary rule has to carry the lowercase word, or the gate \
6281                 cries wolf and gets deleted."
6282            );
6283        }
6284        assert_eq!(
6285            brand_hits("Run zed in the foreground", &policy),
6286            vec!["zed".to_owned()],
6287            "OMEGA-DELTA-0031: the sentence that shipped in two published \
6288             prereleases is not reported as a hit"
6289        );
6290
6291        assert_eq!(
6292            doc_comment_body(r#"    #[cfg_attr(target_os = "macos", doc = "`~/Library/x`.")]"#),
6293            Some("`~/Library/x`."),
6294            "a cfg_attr doc attribute is a doc comment"
6295        );
6296        assert_eq!(
6297            doc_comment_body(r#"        doc = "the long way""#),
6298            Some("the long way"),
6299            "an attribute written across several lines is still a doc comment"
6300        );
6301        assert_eq!(
6302            doc_comment_body(r#"    #[doc = "plain"]"#),
6303            Some("plain"),
6304            "a plain doc attribute is a doc comment"
6305        );
6306        assert_eq!(doc_comment_body("    /// sugar"), Some(" sugar"));
6307        assert_eq!(
6308            doc_comment_body(r#"    let doc = "not documentation";"#),
6309            None,
6310            "a Rust binding named `doc` is not documentation"
6311        );
6312        assert_eq!(doc_comment_body("    let x = 1;"), None);
6313    }
6314
6315    /// OMEGA-DELTA-0039. The installed-proof harness observes what it records.
6316    ///
6317    /// Three checks in the harness could not fail (omega#90). The secret
6318    /// tripwire made a pipe, wrote a fresh random needle into it, closed both
6319    /// ends in the same function and then searched the disk for it, so `pass`
6320    /// was guaranteed by construction. Four of its six surfaces resolved under
6321    /// the data root, where Omega writes no logs, no telemetry and no crash
6322    /// reports, and recorded `absent` — which did not fail the receipt. And the
6323    /// `light-theme` / `dark-theme` observations wrote `content_legible: True`
6324    /// as a literal, with zero OCR calls and zero pixel comparisons, so a
6325    /// frozen or blank window passed both.
6326    ///
6327    /// This asserts the shape of the corrections. The scripts' own
6328    /// `--self-test` paths carry the behavioural oracles.
6329    #[test]
6330    fn the_installed_proof_harness_observes_what_it_records() {
6331        let tripwires = std::fs::read_to_string(repository_path(INSTALLED_TRIPWIRE_PATH))
6332            .expect("tripwire collector");
6333        assert!(
6334            !tripwires.contains("secrets.token_hex"),
6335            "OMEGA-DELTA-0039: {INSTALLED_TRIPWIRE_PATH} mints its own needle \
6336             again. A needle no other process has ever seen cannot be found, \
6337             so the scan passes whatever the product does."
6338        );
6339        assert!(
6340            tripwires.contains("--needle-fd"),
6341            "OMEGA-DELTA-0039: {INSTALLED_TRIPWIRE_PATH} no longer takes the \
6342             needle from the caller through a descriptor."
6343        );
6344        for required in ["Library/Logs", "DiagnosticReports"] {
6345            assert!(
6346                tripwires.contains(required),
6347                "OMEGA-DELTA-0039: {INSTALLED_TRIPWIRE_PATH} no longer scans \
6348                 {required:?}. On macOS `paths::logs_dir()` is \
6349                 ~/Library/Logs/<slug> and `paths::crashes_dir()` is \
6350                 ~/Library/Logs/DiagnosticReports; a surface resolved anywhere \
6351                 else records `absent` about a directory the product never \
6352                 writes."
6353            );
6354        }
6355        assert!(
6356            tripwires.contains("blocked"),
6357            "OMEGA-DELTA-0039: a surface that cannot be observed has to block. \
6358             'nothing was found there' and 'nobody looked' must not read the \
6359             same in a receipt."
6360        );
6361
6362        let observations = std::fs::read_to_string(repository_path(INSTALLED_OBSERVATION_PATH))
6363            .expect("observation collector");
6364        let appearance = observations
6365            .split("# ---- appearance ---")
6366            .nth(1)
6367            .expect("OMEGA-DELTA-0039: the appearance block is gone");
6368        for required in ["ocr_lines(", "differing_pixels("] {
6369            assert!(
6370                appearance.contains(required),
6371                "OMEGA-DELTA-0039: the appearance block does not call \
6372                 {required:?}. `content_legible` was a Python literal there \
6373                 through 0.2.0-rc14: a fact about the host's appearance setting \
6374                 and about a file existing, filed as a fact about the product."
6375            );
6376        }
6377        assert!(
6378            !appearance.contains("\"content_legible\": True,"),
6379            "OMEGA-DELTA-0039: `content_legible` is a constant in the \
6380             appearance block again."
6381        );
6382
6383        let bundler =
6384            std::fs::read_to_string(repository_path(RC_BUNDLE_SCRIPT_PATH)).expect("bundle script");
6385        assert!(
6386            !bundler.contains("\"dirty\": False"),
6387            "OMEGA-DELTA-0039: the release record states `dirty` as a literal. \
6388             It is a field that reads like an observation, so it has to be one."
6389        );
6390    }
6391
6392    // ------ OMEGA-DELTA-0042
6393
6394    /// OMEGA-DELTA-0042. The Exo the lane drives is the agent harness.
6395    ///
6396    /// omega#86 was closed for integrating exo labs' cluster-inference
6397    /// appliance, which shares a name with the harness and nothing else. The
6398    /// pin therefore carries the repository as a *field*, and this reads it, so
6399    /// the distinction survives somebody skimming a doc comment.
6400    #[test]
6401    fn the_exo_lane_drives_the_harness_exo_and_not_the_cluster_one() {
6402        let path = repository_path(EXO_LANE_PIN_PATH);
6403        let source = std::fs::read_to_string(&path)
6404            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6405        let upstream = source
6406            .split_once("upstream: \"")
6407            .and_then(|(_, rest)| rest.split_once('"'))
6408            .expect("EXO_PIN names an upstream")
6409            .0;
6410        assert!(
6411            [EXO_HARNESS_UPSTREAM, EXO_HARNESS_MAINTAINED_FORK]
6412                .iter()
6413                .any(|repository| upstream.ends_with(repository)),
6414            "OMEGA-DELTA-0042: the Exo pin names {upstream}, which is neither \
6415             {EXO_HARNESS_UPSTREAM} nor its reviewed maintained fork \
6416             {EXO_HARNESS_MAINTAINED_FORK}. omega#86 made this mistake once."
6417        );
6418
6419        for relative in [EXO_LANE_LAW_PATH, EXO_LANE_PIN_PATH, EXO_CONNECTION_PATH] {
6420            let path = repository_path(relative);
6421            let source = std::fs::read_to_string(&path)
6422                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6423            let targeted = named_in_code(&source, EXO_CLUSTER_UPSTREAM);
6424            assert!(
6425                !targeted,
6426                "OMEGA-DELTA-0042: {} names {EXO_CLUSTER_UPSTREAM} outside a \
6427                 comment, which would make the wrong Exo a target rather than \
6428                 a warning.",
6429                path.display()
6430            );
6431        }
6432    }
6433
6434    /// OMEGA-DELTA-0042. No text from outside Omega can become an Exo flag.
6435    ///
6436    /// Read off the written shapes rather than off the builder, because the
6437    /// shapes are what a reviewer reads. Exo takes its global options after the
6438    /// subcommand, so a shape that put `<prompt>` before the terminator would
6439    /// hand the command line to whoever typed the prompt — and at this pin that
6440    /// failure is *silent*: `--help` as a prompt exits 0 with usage text and no
6441    /// turn.
6442    #[test]
6443    fn the_exo_lane_puts_no_user_text_before_the_argument_terminator() {
6444        let path = repository_path(EXO_LANE_COMMAND_PATH);
6445        let source = std::fs::read_to_string(&path)
6446            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6447        let table = source
6448            .split_once("pub const ADMITTED_LANE_ARGV")
6449            .and_then(|(_, rest)| rest.split_once("\n];"))
6450            .expect("the admitted argv table is present")
6451            .0;
6452
6453        let mut shapes = 0usize;
6454        for shape in table.split("    (\n").skip(1) {
6455            shapes += 1;
6456            let tokens: Vec<&str> = shape
6457                .match_indices('"')
6458                .map(|(offset, _)| offset)
6459                .collect::<Vec<_>>()
6460                .chunks_exact(2)
6461                .map(|pair| &shape[pair[0] + 1..pair[1]])
6462                .collect();
6463            let terminator = tokens.iter().position(|token| *token == "--");
6464            for slot in EXO_LANE_USER_TEXT_SLOTS {
6465                let Some(at) = tokens.iter().position(|token| token == slot) else {
6466                    continue;
6467                };
6468                let Some(terminator) = terminator else {
6469                    panic!(
6470                        "OMEGA-DELTA-0042: an admitted Exo command carries {slot} \
6471                         and emits no argument terminator, so the value is Exo's \
6472                         command line rather than its input: {tokens:?}"
6473                    );
6474                };
6475                assert!(
6476                    at > terminator,
6477                    "OMEGA-DELTA-0042: an admitted Exo command puts {slot} \
6478                     before the argument terminator: {tokens:?}"
6479                );
6480            }
6481        }
6482        assert!(
6483            shapes >= 4,
6484            "OMEGA-DELTA-0042: the admitted argv table parsed as {shapes} \
6485             shapes, so this check is reading nothing."
6486        );
6487    }
6488
6489    /// OMEGA-DELTA-0042. Omega never puts Exo on a network.
6490    ///
6491    /// Exo's one server has no authentication and full access to its secrets;
6492    /// loopback is the entire boundary and Exo's own documentation says so.
6493    /// Tier A needs no address at all, so anything here is a surface that was
6494    /// added rather than required.
6495    #[test]
6496    fn the_exo_lane_exposes_no_endpoint_off_this_machine() {
6497        for relative in [
6498            EXO_CONNECTION_PATH,
6499            EXO_LANE_LAW_PATH,
6500            EXO_LANE_COMMAND_PATH,
6501        ] {
6502            let path = repository_path(relative);
6503            let source = std::fs::read_to_string(&path)
6504                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6505            for (what, token) in EXO_OFF_MACHINE_TOKENS {
6506                assert!(
6507                    !named_in_code(&source, token),
6508                    "OMEGA-DELTA-0042: {} names {what} (`{token}`) outside a \
6509                     comment. Exo's endpoint is unauthenticated and Omega must \
6510                     never proxy it off-machine.",
6511                    path.display()
6512                );
6513            }
6514        }
6515
6516        // The flags that would redirect Exo, checked where they would have to
6517        // appear to do any harm: the command lines Omega actually builds.
6518        let command_path = repository_path(EXO_LANE_COMMAND_PATH);
6519        let command = std::fs::read_to_string(&command_path)
6520            .unwrap_or_else(|error| panic!("cannot read {}: {error}", command_path.display()));
6521        let table = command
6522            .split_once("pub const ADMITTED_LANE_ARGV")
6523            .and_then(|(_, rest)| rest.split_once("\n];"))
6524            .expect("the admitted argv table is present")
6525            .0;
6526        for flag in EXO_REDIRECTING_FLAGS {
6527            assert!(
6528                !table.contains(flag),
6529                "OMEGA-DELTA-0042: an admitted Exo command line carries \
6530                 `{flag}`, which points Exo away from the state root on disk \
6531                 and at a server with no authentication."
6532            );
6533        }
6534
6535        // And the positive half: the lane refuses an off-loopback endpoint it
6536        // inherited. Without this the check above is satisfied by a lane that
6537        // simply never looked.
6538        let connection_path = repository_path(EXO_CONNECTION_PATH);
6539        let connection = std::fs::read_to_string(&connection_path)
6540            .unwrap_or_else(|error| panic!("cannot read {}: {error}", connection_path.display()));
6541        let body = function_body(&connection, "check_endpoint").unwrap_or_else(|| {
6542            panic!(
6543                "OMEGA-DELTA-0042: {} no longer checks where Exo is. \
6544                 `EXO_EXOHARNESS_URL` in the inherited environment redirects \
6545                 the lane off-machine with no Omega command line changing.",
6546                connection_path.display()
6547            )
6548        });
6549        assert!(
6550            body.contains("EXO_EXOHARNESS_URL") && body.contains("LoopbackEndpoint::parse"),
6551            "OMEGA-DELTA-0042: `check_endpoint` no longer parses the inherited \
6552             endpoint through the type that refuses a non-loopback one."
6553        );
6554        let turn = function_body(&connection, "observe").expect("the ACP observation exists");
6555        assert!(
6556            turn.contains("self.check_endpoint()"),
6557            "OMEGA-DELTA-0042: the ACP preflight no longer checks where Exo is."
6558        );
6559        let prompt = function_body(&connection, "prompt").expect("the ACP prompt path exists");
6560        assert!(
6561            prompt.contains("driver.preflight().await") && prompt.contains("acp.prompt(params"),
6562            "OMEGA-DELTA-0042: the ACP prompt must finish its preflight before it sends."
6563        );
6564    }
6565
6566    /// OMEGA-DELTA-0042, and owner gate 8 behind it.
6567    ///
6568    /// Adding an executor lane must not open a fourth model-initiated path into
6569    /// Full Auto authority. The lane reaches nothing that starts a run: it names
6570    /// no launch origin, constructs no pin gesture, and never writes a run
6571    /// reference — a record that carried one would be claiming engine-lane
6572    /// authority Exo does not have.
6573    #[test]
6574    fn the_exo_lane_opens_no_path_into_full_auto_authority() {
6575        for relative in [EXO_CONNECTION_PATH, EXO_LANE_LAW_PATH] {
6576            let path = repository_path(relative);
6577            let source = std::fs::read_to_string(&path)
6578                .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6579            for token in EXO_FULL_AUTO_TOKENS {
6580                let named = named_in_code(&source, token);
6581                assert!(
6582                    !named,
6583                    "OMEGA-DELTA-0042: {} names `{token}` in code. An Exo agent \
6584                     has an unrestricted networked shell; it is exactly the \
6585                     caller owner gate 8 exists for.",
6586                    path.display()
6587                );
6588            }
6589        }
6590    }
6591
6592    /// OMEGA-DELTA-0042. Every turn is gated before it is sent.
6593    ///
6594    /// Three refusals, in order, and the order matters: an agent read after the
6595    /// send would report a capability the turn already used. Checked on the
6596    /// function body, because the calls existing somewhere in a file is not the
6597    /// same claim as the turn path running them.
6598    #[test]
6599    fn an_exo_turn_checks_the_pin_and_the_agent_before_it_sends() {
6600        let path = repository_path(EXO_CONNECTION_PATH);
6601        let source = std::fs::read_to_string(&path)
6602            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
6603        let body = function_body(&source, "observe").unwrap_or_else(|| {
6604            panic!(
6605                "OMEGA-DELTA-0042: {} has no exact Exo observation, so nothing \
6606                 gates the streamed turn any more.",
6607                path.display()
6608            )
6609        });
6610        let pin = body
6611            .find("self.check_pin()")
6612            .expect("OMEGA-DELTA-0042: a turn no longer checks which Exo it is driving");
6613        let agent = body
6614            .find("ExoCommand::ShowAgent")
6615            .expect("OMEGA-DELTA-0042: a turn no longer reads the exact Exo agent");
6616        let conversation = body
6617            .find("ExoCommand::ShowConversation")
6618            .expect("OMEGA-DELTA-0042: a turn no longer reads the exact Exo conversation");
6619        let prompt = function_body(&source, "prompt")
6620            .expect("OMEGA-DELTA-0042: the streamed ACP prompt path is absent");
6621        let preflight = prompt
6622            .find("driver.preflight().await")
6623            .expect("OMEGA-DELTA-0042: an ACP turn no longer runs its preflight");
6624        let send = prompt
6625            .find("acp.prompt(params")
6626            .expect("OMEGA-DELTA-0042: an ACP turn no longer sends");
6627        assert!(
6628            pin < agent && agent < conversation && preflight < send,
6629            "OMEGA-DELTA-0042: the exact pin, agent, and conversation checks \
6630             must run before the complete preflight permits the ACP send."
6631        );
6632    }
6633
6634    #[test]
6635    fn an_exo_turn_streams_cancels_and_requires_exact_one_use_authority() {
6636        let connection_path = repository_path(EXO_CONNECTION_PATH);
6637        let connection = std::fs::read_to_string(&connection_path)
6638            .unwrap_or_else(|error| panic!("cannot read {}: {error}", connection_path.display()));
6639        let compact_connection = without_whitespace(&connection);
6640        for token in [
6641            "AcpConnection::stdio",
6642            "\"acp\".to_owned()",
6643            "acp.prompt(params",
6644            "self.acp.cancel(session_id",
6645            "grant.consume(&observed.observed, &turn_ref",
6646            "persist_tier_c_receipt",
6647        ] {
6648            assert!(
6649                compact_connection.contains(&without_whitespace(token)),
6650                "OMEGA-DELTA-0042: the Exo ACP and authority path lost `{token}`"
6651            );
6652        }
6653
6654        let thread_path = repository_path(THREAD_VIEW_PATH);
6655        let thread = std::fs::read_to_string(&thread_path)
6656            .unwrap_or_else(|error| panic!("cannot read {}: {error}", thread_path.display()));
6657        for token in [
6658            "omega-exo-authorize-self-modification",
6659            "Allow this Exo agent to modify itself for one turn?",
6660            "self_modification_request",
6661            "confirm_self_modification",
6662        ] {
6663            assert!(
6664                thread.contains(token),
6665                "OMEGA-DELTA-0042: the visible one-turn Exo confirmation lost `{token}`"
6666            );
6667        }
6668    }
6669
6670    /// OMEGA-DELTA-0042. The lane is wired, not merely built.
6671    ///
6672    /// omega#78 shipped a router nobody constructed, and `OMEGA-DELTA-0035`
6673    /// exists because of it. The same failure is available here: a lane with a
6674    /// law, a connection, and tests, reachable by nobody.
6675    #[test]
6676    fn the_exo_lane_is_reachable_from_omega_agent() {
6677        let router_path = repository_path(ROUTER_DISPATCH_PATH);
6678        let router = std::fs::read_to_string(&router_path)
6679            .unwrap_or_else(|error| panic!("cannot read {}: {error}", router_path.display()));
6680        assert!(
6681            router.contains("omega_exo_connection::connect_configured_lane")
6682                && router.contains("with_external_acp(exo)"),
6683            "OMEGA-DELTA-0042: {} no longer registers the Exo lane as the \
6684             router's external executor, so a pin to it can never be honoured.",
6685            router_path.display()
6686        );
6687
6688        let factory_path = repository_path(AGENT_SERVER_FACTORY_PATH);
6689        let factory = std::fs::read_to_string(&factory_path)
6690            .unwrap_or_else(|error| panic!("cannot read {}: {error}", factory_path.display()));
6691        assert!(
6692            factory.contains("omega_exo_connection::ExoLaneConfig::data_dir_path()"),
6693            "OMEGA-DELTA-0042: {} no longer hands the router the Exo lane's \
6694             configuration path, so the lane is never found.",
6695            factory_path.display()
6696        );
6697
6698        let disclosure_path = repository_path(EXECUTOR_DISCLOSURE_BINDING_PATH);
6699        let disclosure = std::fs::read_to_string(&disclosure_path)
6700            .unwrap_or_else(|error| panic!("cannot read {}: {error}", disclosure_path.display()));
6701        assert!(
6702            disclosure.contains("downcast::<crate::omega_exo_connection::ExoHarnessConnection>()"),
6703            "OMEGA-DELTA-0042: {} no longer recognises the Exo connection by \
6704             its concrete type. `agent_id()` on that connection is derived from \
6705             what Exo said about itself, so classifying by it would let an Exo \
6706             install choose its own executor class.",
6707            disclosure_path.display()
6708        );
6709    }
6710
6711    // ------ OMEGA-DELTA-0046
6712
6713    /// OMEGA-DELTA-0046. An Exo thread is a usable workspace, not one label.
6714    ///
6715    /// The workspace must keep Omega's standard transcript and composer. Its
6716    /// inspector must project facts from the same preflight that gates a turn.
6717    /// Its controls must reuse the existing cancel and exact one-turn authority
6718    /// paths. This source check catches the cheap failure modes: a mock panel,
6719    /// a second message implementation, or controls that only look active.
6720    #[test]
6721    fn an_exo_thread_has_a_live_workspace_and_exact_runtime_inspector() {
6722        let thread_path = repository_path(THREAD_VIEW_PATH);
6723        let thread = std::fs::read_to_string(&thread_path)
6724            .unwrap_or_else(|error| panic!("cannot read {}: {error}", thread_path.display()));
6725        for token in [
6726            "omega-exo-workspace-header",
6727            "omega-exo-inspector",
6728            "Runtime inspector",
6729            "render_entries(cx)",
6730            "render_message_editor(window, cx)",
6731            "cancel_generation",
6732            "refresh_exo_inspection",
6733            "authorize_exo_self_modification",
6734            "ObservedExoCapabilityState::requested_capabilities",
6735        ] {
6736            assert!(
6737                thread.contains(token),
6738                "OMEGA-DELTA-0046: the Exo workspace lost `{token}`"
6739            );
6740        }
6741
6742        let connection_path = repository_path(EXO_CONNECTION_PATH);
6743        let connection = std::fs::read_to_string(&connection_path)
6744            .unwrap_or_else(|error| panic!("cannot read {}: {error}", connection_path.display()));
6745        for token in [
6746            "ExoInspectionSnapshot",
6747            "ExoTurnPhase",
6748            "driver.observe().await",
6749            "driver.preflight().await",
6750            "acp.prompt(params",
6751            "meta_value(meta, \"exo.session_id\")",
6752            "meta_value(meta, \"exo.turn_id\")",
6753            "meta_value(meta, \"exo.latest_event_id\")",
6754        ] {
6755            assert!(
6756                connection.contains(token),
6757                "OMEGA-DELTA-0046: the Exo workspace state lost `{token}`"
6758            );
6759        }
6760
6761        let visual_path = repository_path(VISUAL_TEST_RUNNER_PATH);
6762        let visual = std::fs::read_to_string(&visual_path)
6763            .unwrap_or_else(|error| panic!("cannot read {}: {error}", visual_path.display()));
6764        for token in [
6765            "OMEGA_EXO_VISUAL_ONLY",
6766            "run_omega_exo_visual_tests",
6767            "omega_exo_workspace_wide",
6768            "omega_exo_workspace_narrow",
6769            "the real Exo visual turn failed",
6770            "turn.exo_session_id.is_some()",
6771            "turn.exo_turn_id.is_some()",
6772            "turn.latest_event_id.is_some()",
6773        ] {
6774            assert!(
6775                visual.contains(token),
6776                "OMEGA-DELTA-0046: the real Exo visual proof lost `{token}`"
6777            );
6778        }
6779    }
6780
6781    // ---------------------------------------------------------------------
6782    // OMEGA-DELTA-0041 — Omega Agent served over ACP on a loopback socket
6783    // ---------------------------------------------------------------------
6784
6785    /// OMEGA-DELTA-0041. The served ACP surface is off unless the flag says
6786    /// exactly `1`, and the source says so.
6787    ///
6788    /// `omega_acp_server` proves the behaviour with its own unit test. This
6789    /// checks the *shape* the behaviour depends on, in the file, because a
6790    /// later edit that made the flag truthy-tolerant — `is_some`,
6791    /// `unwrap_or("1")`, a `parse::<bool>()` — would keep every one of that
6792    /// crate's tests passing for the values it happened to list while turning
6793    /// a listener on for values it did not.
6794    #[test]
6795    fn the_served_acp_surface_is_off_unless_the_flag_is_exact() {
6796        let source = std::fs::read_to_string(repository_path(ACP_SERVER_PATH))
6797            .expect("the served ACP surface is readable");
6798
6799        assert!(
6800            source.contains("None => Enablement::Off(OffReason::FlagUnset)"),
6801            "OMEGA-DELTA-0041: an unset OMEGA_ACP_SERVER must be off. A              listener that is on by default is a different product."
6802        );
6803        assert!(
6804            source.contains("Some(ENABLE_VALUE) => Enablement::On")
6805                && source.contains("Some(_) => Enablement::Off(OffReason::FlagNotExactlyOne)"),
6806            "OMEGA-DELTA-0041: the enable flag must be an exact match on              ENABLE_VALUE with everything else off. A truthy-tolerant flag is              a flag whose default nobody can state."
6807        );
6808        for tolerant in [
6809            "to_lowercase()",
6810            "eq_ignore_ascii_case",
6811            "parse::<bool>",
6812            "unwrap_or(ENABLE_VALUE)",
6813            "flag.is_some()",
6814        ] {
6815            assert!(
6816                !source.contains(tolerant),
6817                "OMEGA-DELTA-0041: the enable flag reads {tolerant}, which                  widens the set of values that open an unauthenticated socket."
6818            );
6819        }
6820    }
6821
6822    /// OMEGA-DELTA-0041. The socket is the supervisor's, and GPUI cannot reach
6823    /// the crate that opens it.
6824    ///
6825    /// omega#82's falsifier is *GPUI owns the socket*. Two things make that
6826    /// false and both are checked here rather than asserted in prose: the
6827    /// crate that binds declares no GPUI dependency at all, and the only
6828    /// production caller of `start_if_enabled` is `crates/omega_effectd`.
6829    #[test]
6830    fn only_the_supervisor_opens_the_served_acp_socket() {
6831        let manifest = std::fs::read_to_string(repository_path(ACP_SERVER_MANIFEST_PATH))
6832            .expect("the served ACP surface's manifest is readable");
6833        for reaching_into_the_app in [
6834            "gpui.workspace",
6835            "workspace.workspace",
6836            "agent_ui.workspace",
6837            "project.workspace",
6838            "ui.workspace",
6839            "editor.workspace",
6840        ] {
6841            assert!(
6842                !manifest.contains(reaching_into_the_app),
6843                "OMEGA-DELTA-0041: crates/omega_acp_server depends on                  {reaching_into_the_app}. The crate that opens the                  unauthenticated loopback socket must not be reachable from                  the UI layer — that is exactly what omega#82's falsifier                  names."
6844            );
6845        }
6846
6847        let crates = repository_path("crates");
6848        let mut binders: Vec<String> = Vec::new();
6849        let mut starters: Vec<String> = Vec::new();
6850        for_each_source_file(&crates, &["rs"], |path, source| {
6851            let display = path
6852                .display()
6853                .to_string()
6854                .rsplit("crates/")
6855                .next()
6856                .unwrap_or_default()
6857                .to_owned();
6858            if display.starts_with("omega_deltas/") {
6859                return;
6860            }
6861            for line in source.lines() {
6862                let trimmed = line.trim();
6863                if trimmed.starts_with("//") || trimmed.starts_with("///") {
6864                    continue;
6865                }
6866                if trimmed.contains("LoopbackAcpServer::bind(") {
6867                    binders.push(display.clone());
6868                }
6869                if trimmed.contains("start_if_enabled()") && !trimmed.starts_with("pub fn ") {
6870                    starters.push(display.clone());
6871                }
6872            }
6873        });
6874
6875        assert!(
6876            !binders.is_empty() && !starters.is_empty(),
6877            "OMEGA-DELTA-0041: the scan found no bind and no start, so this              check is vacuous. Either the served surface is gone or the              needles stopped matching."
6878        );
6879        for file in &binders {
6880            assert!(
6881                file.starts_with("omega_acp_server/"),
6882                "OMEGA-DELTA-0041: {file} binds the served ACP listener. Only                  crates/omega_acp_server may."
6883            );
6884        }
6885        for file in &starters {
6886            assert!(
6887                file.starts_with("omega_effectd/") || file.starts_with("omega_acp_server/"),
6888                "OMEGA-DELTA-0041: {file} starts the served ACP listener. The                  supervisor layer owns the lifecycle; GPUI never opens its own                  socket."
6889            );
6890        }
6891    }
6892
6893    /// OMEGA-DELTA-0041. Nothing reachable over the socket can take an
6894    /// executor pin.
6895    ///
6896    /// Owner gate 8 at the socket. An engine lane *is* Full Auto authority, a
6897    /// pin is the only door to one, and `OMEGA-DELTA-0035` already requires
6898    /// every pin-setting call to name a literal `PinGesture`. This closes the
6899    /// other end: the crate serving an unauthenticated surface never names a
6900    /// pin at all, so there is nothing there for a later edit to reach for.
6901    #[test]
6902    fn nothing_over_the_served_acp_surface_can_take_a_pin() {
6903        let source = std::fs::read_to_string(repository_path(ACP_SERVER_PATH))
6904            .expect("the served ACP surface is readable");
6905        // The shipped half only. The test module below it reads the pin ledger
6906        // on purpose, to prove every pin gesture is classified as unexposed.
6907        let shipped = source
6908            .split_once("#[cfg(test)]")
6909            .map(|(shipped, _)| shipped)
6910            .expect("the served ACP surface has a test module");
6911        for line in shipped.lines() {
6912            let trimmed = line.trim();
6913            // The doc comments explain *why* there is no pin here, and must be
6914            // allowed to say the word.
6915            if trimmed.starts_with("//") {
6916                continue;
6917            }
6918            for pin_reaching in [
6919                "PinGesture",
6920                "pin_session(",
6921                "pin_next_session(",
6922                "ExecutorPin::",
6923            ] {
6924                assert!(
6925                    !trimmed.contains(pin_reaching),
6926                    "OMEGA-DELTA-0041: the served ACP surface names                      {pin_reaching}. Nothing an external host can reach may                      set a pin: a pin is the only door to an engine lane and                      an engine lane is Full Auto authority, which owner gate 8                      admits only an explicit human action into."
6927                );
6928            }
6929        }
6930        assert!(
6931            source.contains("pin: None,"),
6932            "OMEGA-DELTA-0041: the served route inputs no longer pin nothing.              If this moved, the check above is watching the wrong thing."
6933        );
6934    }
6935
6936    /// OMEGA-DELTA-0041. The served surface presents the first-party agent's
6937    /// own identity, not a second one.
6938    ///
6939    /// An attached host is told it is talking to Omega Agent. If the served
6940    /// identity drifted from the one `crates/agent` declares, the served
6941    /// surface would be disclosing an agent that does not exist — which is the
6942    /// same defect class as a rendered label in the record.
6943    #[test]
6944    fn the_served_surface_presents_the_first_party_agent_id() {
6945        let identity = std::fs::read_to_string(repository_path(NATIVE_AGENT_IDENTITY_PATH))
6946            .expect("the native agent is readable");
6947        let served = std::fs::read_to_string(repository_path(ACP_SERVER_PATH))
6948            .expect("the served ACP surface is readable");
6949
6950        let declared = identity
6951            .lines()
6952            .find_map(|line| {
6953                let line = line.trim();
6954                let rest = line.strip_prefix("pub static OMEGA_AGENT_ID")?;
6955                let start = rest.find("AgentId::new(\"")? + "AgentId::new(\"".len();
6956                let tail = &rest[start..];
6957                let end = tail.find('"')?;
6958                Some(tail[..end].to_owned())
6959            })
6960            .expect("crates/agent declares OMEGA_AGENT_ID as a literal");
6961
6962        assert!(
6963            served.contains(&format!(
6964                "pub const SERVED_AGENT_ID: &str = \"{declared}\";"
6965            )),
6966            "OMEGA-DELTA-0041: the served ACP surface presents an identity              other than {declared:?}, which is what crates/agent declares. An              attached host would be disclosed an agent that does not exist."
6967        );
6968    }
6969
6970    /// OMEGA-DELTA-0041. The supervisor's start is not conditional on anything
6971    /// but the flag.
6972    ///
6973    /// A start hidden behind "and the engine is available" would make the
6974    /// surface's default depend on packaging rather than on the flag, so the
6975    /// default nobody could state would be back.
6976    #[test]
6977    fn the_supervisor_starts_the_served_surface_before_it_resolves_the_engine() {
6978        let source = std::fs::read_to_string(repository_path(EFFECTD_PATH))
6979            .expect("the supervisor is readable");
6980        let start = source
6981            .find("start_served_acp_surface();")
6982            .expect("OMEGA-DELTA-0041: the supervisor no longer starts the served surface");
6983        let resolve = source
6984            .find("resolve_effectd_command(")
6985            .expect("the supervisor resolves the packaged component");
6986        assert!(
6987            start < resolve,
6988            "OMEGA-DELTA-0041: the served surface is started after the              packaged component is resolved, so whether it listens depends on              packaging as well as on the flag."
6989        );
6990    }
6991
6992    // ------------------------------------------------------ OMEGA-DELTA-0045
6993
6994    /// OMEGA-DELTA-0045. A host-authored note is an entry kind, not a caption.
6995    ///
6996    /// `AgentThreadEntry` had six variants and every one of them was something
6997    /// a model or a user said. There was nowhere to put a line the *host*
6998    /// wrote, so the host had nothing to write into and refused. The variant is
6999    /// the seam; without it the refusal is the only honest answer, which is
7000    /// exactly the state rc11 through rc17 shipped.
7001    ///
7002    /// `push_system_note` is asserted to return `bool` and to be keyed on the
7003    /// engine-supplied id. Last-write-wins would let a retry rewrite a
7004    /// disclosure the owner had already been shown; an unkeyed append would
7005    /// show it twice.
7006    #[test]
7007    fn a_host_authored_note_is_a_thread_entry_kind() {
7008        let path = repository_path(THREAD_ENTRY_PATH);
7009        let source = std::fs::read_to_string(&path)
7010            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
7011
7012        let (_, body, _) = next_enum_body(&source, "AgentThreadEntry").unwrap_or_else(|| {
7013            panic!(
7014                "OMEGA-DELTA-0045: no AgentThreadEntry enum found in {}. The \
7015                 check would be vacuous, so it fails instead.",
7016                path.display()
7017            )
7018        });
7019        assert!(
7020            body.lines()
7021                .map(str::trim)
7022                .any(|line| line == "SystemNote(SystemNote),"),
7023            "OMEGA-DELTA-0045: AgentThreadEntry has no SystemNote variant in \
7024             {}. Without an entry kind a non-model disclosure can be, the host \
7025             has nowhere to write a provider handoff and the thread the owner \
7026             reads goes silent — the rc11 defect FA-07 gate 5 forbids.",
7027            path.display()
7028        );
7029
7030        let code = code_of(&source);
7031        assert!(
7032            code.contains(
7033                "pub fn push_system_note(&mut self, note: SystemNote, cx: &mut Context<Self>) -> bool"
7034            ),
7035            "OMEGA-DELTA-0045: {} must expose push_system_note returning \
7036             whether it appended.",
7037            path.display()
7038        );
7039        assert!(
7040            code.contains("existing.id == note.id"),
7041            "OMEGA-DELTA-0045: push_system_note in {} no longer keys on the \
7042             engine-supplied note id. Unkeyed, a retried append shows the owner \
7043             the same disclosure twice; last-write-wins lets a retry rewrite a \
7044             disclosure the owner has already read.",
7045            path.display()
7046        );
7047    }
7048
7049    /// OMEGA-DELTA-0045. The host writes the note instead of refusing it.
7050    ///
7051    /// The refusal was typed and honest — better than rc11's silent
7052    /// `() => {}` — and it was still silence in the place that matters. An
7053    /// independent reviewer found `SYSTEM_NOTE_REFUSAL` in the shipped bytes of
7054    /// both `0.2.0-rc15` and `0.2.0-rc16`, so no candidate to date discloses a
7055    /// cross-provider handoff to the owner reading the thread.
7056    ///
7057    /// Two halves, because either alone is passable and useless: the refusal is
7058    /// gone, and the method reaches `push_system_note` on the thread named by
7059    /// `threadRef`. A handoff is addressed to the *target* thread; filing it
7060    /// against the source one would put the disclosure where the owner is no
7061    /// longer reading.
7062    #[test]
7063    fn the_host_appends_a_provider_handoff_note_rather_than_refusing_it() {
7064        let path = repository_path(HOST_BRIDGE_PATH);
7065        let source = std::fs::read_to_string(&path)
7066            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
7067        let code = code_of(&source);
7068
7069        assert!(
7070            !code.contains(SYSTEM_NOTE_REFUSAL),
7071            "OMEGA-DELTA-0045: {} still refuses the system-note method with \
7072             {SYSTEM_NOTE_REFUSAL:?}. That refusal is the rc11 silence in a \
7073             typed wrapper: the engine emits a provider-handoff note naming \
7074             both lanes and the host drops it, so a run that changed which \
7075             model spends the owner's budget leaves no trace in the transcript.",
7076            path.display()
7077        );
7078        assert!(
7079            code.contains("HostMethod::AppendSystemNote => append_system_note("),
7080            "OMEGA-DELTA-0045: {} no longer routes AppendSystemNote to \
7081             append_system_note.",
7082            path.display()
7083        );
7084        assert!(
7085            code.contains("thread.push_system_note("),
7086            "OMEGA-DELTA-0045: append_system_note in {} does not reach \
7087             push_system_note. A method that validates its params and returns \
7088             `{{\"appended\": true}}` without writing anything is a refusal \
7089             that lies rather than a refusal that is honest.",
7090            path.display()
7091        );
7092        assert!(
7093            code.contains("thread.thread_id.to_key_string() == params.thread_ref"),
7094            "OMEGA-DELTA-0045: append_system_note in {} no longer resolves the \
7095             thread named by threadRef. A handoff is addressed to the target \
7096             thread; filing it against whichever thread is nearest puts the \
7097             disclosure where the owner has stopped reading.",
7098            path.display()
7099        );
7100    }
7101
7102    /// OMEGA-DELTA-0045. The thread surface draws the note, unconditionally.
7103    ///
7104    /// An entry kind nothing renders satisfies every other check here and
7105    /// discloses nothing, which is the same failure shape omega#77 pinned for
7106    /// the executor line. So the call site is pinned as well as the variant.
7107    ///
7108    /// And it is pinned as an *unconditional* draw. The gate is owner
7109    /// visibility; a note behind a disclosure triangle, a hover, or a collapsed
7110    /// section is a note the rc11 handoff would also have passed. The body is
7111    /// read for the expansion vocabulary the compaction entry uses, because
7112    /// that is the nearest thing in this file to copy by accident.
7113    #[test]
7114    fn the_thread_surface_draws_a_host_authored_note_unconditionally() {
7115        let path = repository_path(THREAD_VIEW_PATH);
7116        let source = std::fs::read_to_string(&path)
7117            .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()));
7118        let code = code_of(&source);
7119
7120        assert!(
7121            code.contains("fn render_system_note("),
7122            "OMEGA-DELTA-0045: {} must define the host-authored note line.",
7123            path.display()
7124        );
7125        assert!(
7126            code.contains(
7127                "AgentThreadEntry::SystemNote(note) => self.render_system_note(entry_ix, note),"
7128            ),
7129            "OMEGA-DELTA-0045: {} must draw a SystemNote entry from the entry \
7130             match. Defining the renderer without dispatching to it discloses \
7131             nothing, and every other check in this delta would still pass.",
7132            path.display()
7133        );
7134
7135        let start = code
7136            .find("fn render_system_note(")
7137            .expect("the renderer was just asserted to exist");
7138        let body = &code[start..];
7139        let end = body.find("\n    fn ").expect(
7140            "OMEGA-DELTA-0045: no method follows render_system_note, so its \
7141             body cannot be bounded and the scan below would read the rest of \
7142             the file",
7143        );
7144        let body = &body[..end];
7145
7146        assert!(
7147            body.contains("Label::new(note.text.clone())"),
7148            "OMEGA-DELTA-0045: the note line in {} must be drawn from the \
7149             entry's own text as a Label. Rendering it as Markdown would let \
7150             provider-supplied content style a host-authored disclosure or pass \
7151             itself off as one.",
7152            path.display()
7153        );
7154        for hideable in ["is_expanded", "expansion", "toggle", "tooltip", "hover"] {
7155            assert!(
7156                !body.contains(hideable),
7157                "OMEGA-DELTA-0045: the note line in {} names {hideable:?}. The \
7158                 gate is owner visibility, and anything the owner has to click, \
7159                 expand, or hover to see is a disclosure the rc11 handoff would \
7160                 also have passed.",
7161                path.display()
7162            );
7163        }
7164    }
7165}
7166
Served at tenant.openagents/omega Member data and write actions are omitted.