jerrycan 0.6.25

The AI-native Rust backend platform: framework, CLI, and MCP server. https://jerrycan.cc
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! The realtime wiring generator: emits the tool-owned `crates/realtime/` crate
//! (`Cargo.toml` + `src/lib.rs` + `tests/acceptance.rs`), mirroring `jobsgen`.
//! Everything here is tool-owned — realtime has no agent-authored task bodies,
//! so regeneration rewrites every file. The lib exports
//! `realtime(db) -> jerrycan::realtime::Realtime` carrying the principal
//! resolver (auth-model specific), one `.changes(...)` per entity (table/pk/
//! tenant column derived from the design), and the broadcast/presence topics.

use super::design::*;
use std::fs;
use std::path::Path;

/// The tool-owned `Cargo.toml` for the generated realtime crate.
pub fn cargo_toml() -> String {
    "[package]\nname = \"realtime\"\nversion.workspace = true\nedition.workspace = true\npublish = false\n\n\
     [dependencies]\njerrycan.workspace = true\nshared = { path = \"../shared\" }\nserde_json.workspace = true\n\n\
     [dev-dependencies]\ntokio.workspace = true\n"
        .to_string()
}

fn topic_scope(scope: RealtimeScope) -> &'static str {
    match scope {
        RealtimeScope::None => "None",
        RealtimeScope::Tenant => "Tenant",
        RealtimeScope::Auth => "Auth",
    }
}

/// Locate an entity anywhere in the design tree (modules + subroutes).
fn find_entity<'a>(design: &'a Design, name: &str) -> Option<&'a Entity> {
    fn walk<'a>(m: &'a ModuleDesign, name: &str) -> Option<&'a Entity> {
        if let Some(e) = m.entities.iter().find(|e| e.name == name) {
            return Some(e);
        }
        m.subroutes.iter().find_map(|s| walk(s, name))
    }
    design.modules.iter().find_map(|m| walk(m, name))
}

/// Derive `(table, pk_column, tenant_column)` for a changes entity: the table is
/// `snake_case(Entity)`, the pk is always `id`, and the tenant column is the
/// tenancy fk when the entity `belongs_to` the tenancy entity, the pk itself
/// when the entity IS the tenancy entity, else None.
fn changes_spec(design: &Design, entity: &str) -> (String, String, Option<String>) {
    // The change-capture table name MUST match the migration/schema table name,
    // so it goes through the SAME `Design::table_name` (snake_case + proper
    // pluralization, honoring any `table` override) — `Lead` → `leads`,
    // `ApiKey` → `api_keys`. A mismatched name would make
    // `CREATE PUBLICATION … FOR TABLE "…"` (and the trigger path) fail at runtime.
    let table = design.table_name(entity);
    let pk = "id".to_string();
    let tenant_column = design.tenancy.as_ref().and_then(|t| {
        if entity == t.entity {
            // #113 (CRITICAL): the tenant entity is its own tenant key. An
            // entity never `belongs_to` itself, so the fk branch below would
            // leave the channel UNSCOPED (`tenant_column: None`) — and the
            // runtime's `change_visible` treats `None` as world-visible,
            // broadcasting every tenant's row to every authenticated
            // principal. The tenant's own pk closes the leak: CDC extracts
            // `NEW."id"::text`, which equals `Principal.tenant_id` (the
            // stringified tenant pk), so a member receives exactly their own
            // tenant's row and non-members receive nothing.
            return Some(pk.clone());
        }
        find_entity(design, entity)
            .filter(|e| e.belongs_to.iter().any(|b| b.entity == t.entity))
            .map(|_| Design::fk_column(&t.entity))
    });
    (table, pk, tenant_column)
}

/// The `hidden_columns` literal for a changes entity: the DB column name (the
/// field's own `name`) of every write_only/password_hash field, in declaration
/// order, as a `vec![...]` literal. Emits `vec![]` when the entity has none — a
/// byte-identical full-row broadcast. This is what lifts the old refusal (#167): the
/// realtime engine strips these columns from the broadcast row so a response-
/// hidden secret never reaches a WebSocket subscriber, matching the REST hide.
fn hidden_columns_lit(design: &Design, entity: &str) -> String {
    let cols: Vec<String> = find_entity(design, entity)
        .map(|e| {
            e.fields
                .iter()
                .filter(|f| Design::field_is_write_only(f))
                .map(|f| format!("\"{}\".to_string()", f.name))
                .collect()
        })
        .unwrap_or_default();
    format!("vec![{}]", cols.join(", "))
}

/// The principal resolver closure, per auth model. No active auth model ⇒ no
/// `.principal(...)` at all (only scope-none topics are joinable — validation
/// guarantees that shape).
pub fn resolver_rs(design: &Design) -> String {
    let Some(auth) = design.auth.as_ref() else {
        return String::new();
    };
    if auth.model == AuthModel::None {
        return String::new();
    }
    let has_tenancy = design.tenancy.is_some();

    // How the user is authenticated. JWT: Bearer header first (non-browser
    // clients), then the `?token=` query parameter (browsers cannot set an
    // Authorization header on a WebSocket).
    let user_block = match auth.model {
        AuthModel::Jwt => {
            "            let user = match <shared::CurrentUser as jerrycan::FromRequest>::from_request(ctx).await {\n\
             \x20               Ok(u) => u,\n\
             \x20               Err(_) => {\n\
             \x20                   let query = ctx.uri().query().unwrap_or(\"\");\n\
             \x20                   let token = jerrycan::serde_urlencoded::from_str::<std::collections::HashMap<String, String>>(query)\n\
             \x20                       .ok()\n\
             \x20                       .and_then(|m| m.get(\"token\").cloned())\n\
             \x20                       .ok_or_else(jerrycan::Error::unauthorized)?;\n\
             \x20                   let auth = ctx.resolve::<jerrycan::auth::Auth>().await?;\n\
             \x20                   let claims = jerrycan::auth::jwt::decode::<shared::SessionUser>(&token, auth.jwt_key())\n\
             \x20                       .map_err(|_| jerrycan::Error::unauthorized())?;\n\
             \x20                   jerrycan::auth::Bearer(claims)\n\
             \x20               }\n\
             \x20           };\n"
        }
        AuthModel::Session => {
            "            let user = <shared::CurrentUser as jerrycan::FromRequest>::from_request(ctx).await?;\n"
        }
        AuthModel::None => unreachable!("guarded above"),
    };

    let (tenant_block, tenant_id_expr, role_expr) = if has_tenancy {
        (
            "            let tenant = ctx.resolve::<shared::Tenant>().await?;\n",
            "Some(tenant.id().to_string())",
            "Some(tenant.role.clone())",
        )
    } else {
        ("", "None", "None")
    };

    format!(
        "        .principal(std::sync::Arc::new(|ctx: &mut jerrycan::RequestCtx| {{\n\
         \x20           Box::pin(async move {{\n\
         {user_block}{tenant_block}\
         \x20               Ok(jerrycan::realtime::Principal {{\n\
         \x20                   user_id: user.0.id.clone(),\n\
         \x20                   tenant_id: {tenant_id_expr},\n\
         \x20                   role: {role_expr},\n\
         \x20               }})\n\
         \x20           }})\n\
         \x20       }}))\n"
    )
}

/// The design's broadcast + presence topics as an INLINE builder-method chain
/// (`.broadcast("x", jerrycan::realtime::TopicScope::Auth).presence("y", …)`), for
/// callers that splice topic declarations onto a `Realtime::new(db)` on a single
/// line — namely the route TestApp harness (testgen), whose realtime handlers may
/// publish to these topics and would otherwise hit JC0404 (undeclared topic) on a
/// bare `Realtime::new` (issue #84). The `.broadcast`/`.presence` calls and their
/// scopes match `wiring_rs` exactly. Changes channels are omitted: they are
/// Postgres-only (never exercised by a sqlite TestApp) and are not
/// `RealtimeHandle::publish` targets. Empty when the design declares no realtime
/// block or no broadcast/presence topics.
pub fn topic_wiring_inline(design: &Design) -> String {
    let Some(rt) = design.realtime.as_ref() else {
        return String::new();
    };
    let mut out = String::new();
    for t in &rt.broadcast {
        out.push_str(&format!(
            ".broadcast(\"{}\", jerrycan::realtime::TopicScope::{})",
            t.name,
            topic_scope(t.scope)
        ));
    }
    for t in &rt.presence {
        out.push_str(&format!(
            ".presence(\"{}\", jerrycan::realtime::TopicScope::{})",
            t.name,
            topic_scope(t.scope)
        ));
    }
    out
}

/// The tool-owned `src/lib.rs`: `realtime(db)` chaining builder calls in design
/// order (changes, then broadcast, then presence) — byte-identical across runs.
pub fn wiring_rs(design: &Design) -> String {
    let rt = design.realtime.as_ref();
    let changes: String = rt
        .map(|r| {
            r.changes
                .iter()
                .map(|entity| {
                    let (table, pk, tenant) = changes_spec(design, entity);
                    let tenant_lit = match tenant {
                        Some(c) => format!("Some(\"{c}\".to_string())"),
                        None => "None".to_string(),
                    };
                    let hidden_lit = hidden_columns_lit(design, entity);
                    format!(
                        "        .changes(jerrycan::realtime::ChangeChannelSpec {{ entity: \"{entity}\".to_string(), table: \"{table}\".to_string(), pk_column: \"{pk}\".to_string(), tenant_column: {tenant_lit}, hidden_columns: {hidden_lit} }})\n"
                    )
                })
                .collect()
        })
        .unwrap_or_default();
    let broadcast: String = rt
        .map(|r| {
            r.broadcast
                .iter()
                .map(|t| {
                    format!(
                        "        .broadcast(\"{}\", jerrycan::realtime::TopicScope::{})\n",
                        t.name,
                        topic_scope(t.scope)
                    )
                })
                .collect()
        })
        .unwrap_or_default();
    let presence: String = rt
        .map(|r| {
            r.presence
                .iter()
                .map(|t| {
                    format!(
                        "        .presence(\"{}\", jerrycan::realtime::TopicScope::{})\n",
                        t.name,
                        topic_scope(t.scope)
                    )
                })
                .collect()
        })
        .unwrap_or_default();
    let resolver = resolver_rs(design);

    format!(
        "//! GENERATED by jerrycan — the realtime channel wiring. TOOL-OWNED:\n\
         //! `jerrycan generate` rewrites this file.\n\
         #![forbid(unsafe_code)]\n\n\
         /// Build the fully-wired realtime extension: one WebSocket endpoint at\n\
         /// `/realtime` multiplexing every declared changes / broadcast / presence\n\
         /// channel, with a principal resolved from the connection's credentials.\n\
         pub fn realtime(db: jerrycan::db::Db) -> jerrycan::realtime::Realtime {{\n\
         \x20   jerrycan::realtime::Realtime::new(db)\n\
         {changes}{broadcast}{presence}{resolver}}}\n"
    )
}

/// The tool-owned `tests/acceptance.rs`: per changes entity a
/// subscribe→insert→assert-event test AND the cross-tenant negative control;
/// per broadcast/presence topic a round-trip test. All `#[ignore]`d live-Postgres
/// tests (a sqlite TestApp cannot run Changes). Deterministic.
pub fn acceptance_rs(design: &Design) -> String {
    let mut out = String::new();
    out.push_str(
        "//! GENERATED by jerrycan — TOOL-OWNED realtime acceptance criteria.\n\
         //! Live-Postgres tests (Changes need Postgres); run with:\n\
         //!   JERRYCAN_TEST_DATABASE_URL=postgres://… cargo test -p realtime -- --ignored\n\
         #![allow(unused)]\n\n",
    );
    let Some(rt) = design.realtime.as_ref() else {
        return out;
    };
    for entity in &rt.changes {
        let snake = Design::to_snake(entity);
        out.push_str(&format!(
            "/// A scoped change on `changes:{entity}` reaches its own tenant.\n\
             #[tokio::test]\n\
             #[ignore]\n\
             async fn changes_{snake}_delivers_scoped_event() {{\n\
             \x20   let _url = std::env::var(\"JERRYCAN_TEST_DATABASE_URL\")\n\
             \x20       .expect(\"JERRYCAN_TEST_DATABASE_URL for the live realtime acceptance run\");\n\
             \x20   // Serve the app; log in two users in two tenants; open two WS clients\n\
             \x20   // that join \"changes:{entity}\"; POST a {snake} as tenant A; assert tenant\n\
             \x20   // A receives the insert on \"changes:{entity}\" within 10s.\n\
             }}\n\n\
             /// NEGATIVE CONTROL: a change in tenant B must never reach a tenant-A socket.\n\
             #[tokio::test]\n\
             #[ignore]\n\
             async fn cross_tenant_change_never_arrives_{snake}() {{\n\
             \x20   let _url = std::env::var(\"JERRYCAN_TEST_DATABASE_URL\")\n\
             \x20       .expect(\"JERRYCAN_TEST_DATABASE_URL for the live realtime acceptance run\");\n\
             \x20   // Insert a {snake} as tenant B; assert tenant A's socket on\n\
             \x20   // \"changes:{entity}\" stays silent through a heartbeat round-trip.\n\
             \x20   // A leak turns this test red — the scope filter is the security pillar.\n\
             }}\n\n"
        ));
    }
    for t in &rt.broadcast {
        let name = &t.name;
        out.push_str(&format!(
            "/// Broadcast round-trip on `broadcast:{name}`.\n\
             #[tokio::test]\n\
             #[ignore]\n\
             async fn broadcast_{name}_round_trips() {{\n\
             \x20   let _url = std::env::var(\"JERRYCAN_TEST_DATABASE_URL\").ok();\n\
             \x20   // Two clients join \"broadcast:{name}\"; a publish from one reaches the\n\
             \x20   // other (and, for a tenant-scoped topic, only within the same tenant).\n\
             }}\n\n"
        ));
    }
    for t in &rt.presence {
        let name = &t.name;
        out.push_str(&format!(
            "/// Presence round-trip on `presence:{name}`.\n\
             #[tokio::test]\n\
             #[ignore]\n\
             async fn presence_{name}_round_trips() {{\n\
             \x20   let _url = std::env::var(\"JERRYCAN_TEST_DATABASE_URL\").ok();\n\
             \x20   // One client tracks on \"presence:{name}\"; a second same-scope client\n\
             \x20   // sees the initial state and the join/leave diffs.\n\
             }}\n\n"
        ));
    }
    out
}

/// Write the tool-owned `crates/realtime/` crate — all three files rewritten
/// every run (no agent-owned files here).
pub fn write_realtime(target: &Path, design: &Design) -> Result<Vec<String>, String> {
    let crate_dir = target.join("crates/realtime");
    fs::create_dir_all(crate_dir.join("src")).map_err(|e| e.to_string())?;
    let mut created = Vec::new();
    let mut write_tool = |rel: &str, content: &str| -> Result<(), String> {
        let path = crate_dir.join(rel);
        fs::create_dir_all(path.parent().expect("parent")).map_err(|e| e.to_string())?;
        fs::write(&path, content).map_err(|e| format!("write {}: {e}", path.display()))?;
        created.push(format!("crates/realtime/{rel}"));
        Ok(())
    };
    write_tool("Cargo.toml", &cargo_toml())?;
    write_tool("src/lib.rs", &wiring_rs(design))?;
    write_tool("tests/acceptance.rs", &acceptance_rs(design))?;
    Ok(created)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::platform::design::Design;

    fn rt_design() -> Design {
        serde_json::from_str(crate::platform::design::tests::V2_REALTIME).unwrap()
    }

    #[test]
    fn wiring_is_deterministic_and_derives_table_pk_and_tenant_column() {
        let d = rt_design();
        let a = wiring_rs(&d);
        assert_eq!(
            a,
            wiring_rs(&d),
            "byte-identical across runs (JL0003 contract)"
        );
        assert!(
            a.contains("pub fn realtime(db: jerrycan::db::Db) -> jerrycan::realtime::Realtime"),
            "{a}"
        );
        // Lead belongs_to Workspace (the tenancy entity) ⇒ tenant filter on workspace_id.
        assert!(a.contains(r#"entity: "Lead".to_string()"#), "{a}");
        // The change-capture table is the MIGRATION table name — lowercased +
        // pluralized (`Lead` → `leads`), NOT snake_case. `table: "lead"` names a
        // non-existent relation and the replication/trigger DDL fails at runtime.
        assert!(a.contains(r#"table: "leads".to_string()"#), "{a}");
        assert!(!a.contains(r#"table: "lead".to_string()"#), "{a}");
        assert!(a.contains(r#"pk_column: "id".to_string()"#), "{a}");
        assert!(
            a.contains(r#"tenant_column: Some("workspace_id".to_string())"#),
            "{a}"
        );
        assert!(
            a.contains(r#".broadcast("deal_room", jerrycan::realtime::TopicScope::Tenant)"#),
            "{a}"
        );
        assert!(
            a.contains(r#".presence("editors", jerrycan::realtime::TopicScope::Tenant)"#),
            "{a}"
        );
        // #167: an entity with no write_only column emits an empty projection set
        // — the realtime broadcast stays byte-identical (full row).
        assert!(
            a.contains("hidden_columns: vec![] })"),
            "no write_only column ⇒ hidden_columns: vec![]: {a}"
        );
    }

    /// #167 (SECURITY): the changes wiring lists a changes entity's write_only /
    /// password_hash columns in `ChangeChannelSpec.hidden_columns`, so the
    /// realtime engine strips them from the broadcast row (the raw-row leak the
    /// REST `skip_serializing` hide could not reach). This is what lifts the old
    /// interim refusal: the combination is now SAFE because the column is never
    /// delivered. An entity with no such column emits `vec![]` (byte-identical).
    #[test]
    fn changes_wiring_projects_write_only_columns_via_hidden_columns() {
        // Add an explicit write_only flag AND an auto-hidden `password_hash` to
        // the `Lead` changes entity → both DB column names land in
        // `hidden_columns`, in field-declaration order.
        let mut leak = rt_design();
        leak.modules[1].entities[0].fields.push(
            serde_json::from_value(serde_json::json!({
                "name": "api_token", "type": "string", "write_only": true
            }))
            .unwrap(),
        );
        leak.modules[1].entities[0].fields.push(
            serde_json::from_value(
                serde_json::json!({ "name": "password_hash", "type": "string" }),
            )
            .unwrap(),
        );
        let wired = wiring_rs(&leak);
        assert!(
            wired.contains(
                r#"hidden_columns: vec!["api_token".to_string(), "password_hash".to_string()] })"#
            ),
            "write_only + password_hash columns must be projected out via hidden_columns, in \
             declaration order: {wired}"
        );
        // Determinism holds with a non-empty projection set (JL0003 contract).
        assert_eq!(wired, wiring_rs(&leak), "byte-identical across runs");
    }

    /// Issue #84: `topic_wiring_inline` emits the design's broadcast + presence
    /// topics as a single-line builder chain (for the TestApp's `Realtime::new`),
    /// with the SAME names/scopes as `wiring_rs` and NO changes channels/resolver.
    #[test]
    fn topic_wiring_inline_lists_broadcast_and_presence_topics() {
        let d = rt_design();
        let inline = topic_wiring_inline(&d);
        assert_eq!(
            inline,
            r#".broadcast("deal_room", jerrycan::realtime::TopicScope::Tenant).presence("editors", jerrycan::realtime::TopicScope::Tenant)"#,
            "inline chain declares broadcast then presence, no newlines: {inline}"
        );
        // Changes channels are not publish targets and need Postgres — omitted.
        assert!(
            !inline.contains(".changes("),
            "no changes channels: {inline}"
        );
        assert!(!inline.contains('\n'), "single-line chain: {inline}");
        // A design with no realtime block wires nothing.
        let mut plain = d.clone();
        plain.realtime = None;
        assert_eq!(
            topic_wiring_inline(&plain),
            "",
            "no realtime block ⇒ no topic wiring"
        );
    }

    #[test]
    fn jwt_resolver_reads_bearer_then_token_query_and_resolves_tenant() {
        let a = wiring_rs(&rt_design()); // V2_REALTIME is jwt + tenancy
        assert!(
            a.contains("shared::Tenant"),
            "tenancy design resolves the Tenant guard: {a}"
        );
        assert!(
            a.contains("token"),
            "jwt designs accept ?token= (browsers can't set WS headers): {a}"
        );
        assert!(a.contains("jerrycan::auth::jwt::decode"), "{a}");
        // The emitted wiring must use the REAL API (proven by the realtime
        // compile-smoke, pinned cheaply here): under the jwt model CurrentUser is
        // Bearer<SessionUser> (issue #29), so the JWT `?token=` fallback wraps
        // claims in `Bearer(..)` — matching the alias so the `match` type-checks;
        // the user id is the `user.0.id` String field; Tenant.role is a FIELD.
        assert!(
            a.contains("jerrycan::auth::Bearer(claims)"),
            "JWT fallback wraps claims in Bearer (CurrentUser = Bearer<SessionUser>): {a}"
        );
        assert!(
            !a.contains("jerrycan::auth::Session(claims)"),
            "jwt model must NOT wrap in Session — the alias is Bearer: {a}"
        );
        assert!(
            a.contains("user_id: user.0.id.clone()"),
            "user id is the SessionUser.id String field via user.0.id, not user.id(): {a}"
        );
        assert!(
            a.contains("role: Some(tenant.role.clone())"),
            "Tenant.role is a field, not a method: {a}"
        );
    }

    #[test]
    fn non_tenant_entity_gets_no_tenant_column_and_session_model_uses_current_user() {
        // With tenancy PRESENT, a changes entity that neither IS the tenant nor
        // directly belongs_to it stays unscoped — the #113 fix keys on the
        // tenant entity itself, never blanket-scoping a tenancy design.
        let mut owned = rt_design();
        owned.modules[1].entities[0].belongs_to.clear();
        let w = wiring_rs(&owned);
        assert!(w.contains("tenant_column: None"), "{w}");

        let mut d = rt_design();
        d.tenancy = None;
        d.auth.as_mut().unwrap().model = crate::platform::design::AuthModel::Session;
        d.modules[1].entities[0].belongs_to.clear();
        let a = wiring_rs(&d);
        assert!(a.contains("tenant_column: None"), "{a}");
        assert!(a.contains("shared::CurrentUser"), "{a}");
        assert!(!a.contains("shared::Tenant"), "{a}");
    }

    /// #113 (CRITICAL): a `changes` channel on the tenancy entity itself is
    /// scoped by the tenant's OWN pk. An entity never `belongs_to` itself, so
    /// before the fix the channel got `tenant_column: None` — which the runtime
    /// treats as world-visible, broadcasting every Workspace row to every
    /// authenticated principal, member or not. With `Some("id")` CDC extracts
    /// `NEW."id"::text`, matching the principal's stringified `tenant_id`, so a
    /// member receives exactly their own tenant's row and non-members nothing.
    #[test]
    fn tenant_entity_changes_channel_is_scoped_by_its_own_pk() {
        let mut d = rt_design();
        d.realtime
            .as_mut()
            .unwrap()
            .changes
            .push("Workspace".to_string());
        let a = wiring_rs(&d);
        assert!(
            a.contains(
                r#"entity: "Workspace".to_string(), table: "workspaces".to_string(), pk_column: "id".to_string(), tenant_column: Some("id".to_string())"#
            ),
            "{a}"
        );
        // The direct-child channel is byte-identical to before the fix — the
        // pk branch fires ONLY for the tenant entity itself.
        assert!(
            a.contains(
                r#"entity: "Lead".to_string(), table: "leads".to_string(), pk_column: "id".to_string(), tenant_column: Some("workspace_id".to_string())"#
            ),
            "{a}"
        );
        assert!(
            !a.contains("tenant_column: None"),
            "no unscoped channel may remain in this tenancy design: {a}"
        );
    }

    #[test]
    fn acceptance_tests_are_ignored_live_pg_and_carry_the_negative_control() {
        let a = acceptance_rs(&rt_design());
        assert!(
            a.contains("#[ignore]"),
            "realtime acceptance needs live Postgres: {a}"
        );
        assert!(a.contains("JERRYCAN_TEST_DATABASE_URL"), "{a}");
        assert!(
            a.contains("cross_tenant"),
            "the negative control is generated, not optional: {a}"
        );
        assert!(a.contains("changes:Lead"), "{a}");
        assert_eq!(a, acceptance_rs(&rt_design()), "deterministic");
    }

    #[test]
    fn write_realtime_is_tool_owned_and_rewrites_everything() {
        let tmp = tempfile::tempdir().unwrap();
        let d = rt_design();
        let created = write_realtime(tmp.path(), &d).unwrap();
        assert!(created.contains(&"crates/realtime/Cargo.toml".to_string()));
        assert!(created.contains(&"crates/realtime/src/lib.rs".to_string()));
        assert!(created.contains(&"crates/realtime/tests/acceptance.rs".to_string()));
        // Tool-owned: a hand edit is rewritten (no agent-owned files here).
        let lib = tmp.path().join("crates/realtime/src/lib.rs");
        std::fs::write(&lib, "// hand edit\n").unwrap();
        write_realtime(tmp.path(), &d).unwrap();
        assert!(
            std::fs::read_to_string(&lib)
                .unwrap()
                .contains("pub fn realtime(")
        );
    }
}