Per-Layer Authorization: Move authorized_dids from SubscriberInfo to LayerUnit
Context
Problem: Dynamic layer sync is broken on the viewer side. When a viewer receives a layer permit from the node, it's stored in butler DB but never communicated to the local Scribe. The observer's can_receive_layer() check fails, so local writes to dynamic layers never reach the node.
Deeper issue: The current authorization model is subscriber-centric (SubscriberInfo holds permits, checked per-subscriber per-broadcast). On the node with many subscribers and many dynamic layers, this means N×M permit checks on every broadcast. The natural question is layer-centric: "who can access THIS layer?"
Decision: Move authorization to LayerUnit for ALL layers (static + dynamic), creating one code path. Authorization is computed once (at subscription/permit-issuance time) and looked up O(1) at broadcast time.
Step 1: Add authorized_dids to LayerUnit
File: scribe/src/layer_unit/mod.rs
rust
pub struct LayerUnit {
layer: Layer,
dirty: bool,
is_local_only: bool,
pub is_dynamic: bool,
loro_sub: Option<loro::Subscription>,
/// Which subscriber DIDs are authorized to receive updates for this layer.
/// Arc<RwLock> because the observer async task needs shared read access.
/// Populated at subscription time (page permit) and permit issuance (layer permits).
authorized_dids: Arc<RwLock<HashSet<String>>>,
}
Add methods:
pub fn authorized_dids(&self) -> &Arc<RwLock<HashSet<String>>> — for observer to clone the Arc
pub fn authorize_did(&self, did: &str) — insert DID (takes &self via RwLock)
After inserting the subscriber into state.subscribers, iterate all existing LayerUnits and check the new subscriber's permit:
rust
// Populate authorized_dids on existing LayerUnits for this subscriber
for (layer_name, unit) in &state.units {
// Skip local-only layers
if unit.is_local_only() { continue; }
// Presence layer: only if can_see_others
if (layer_name == "presence" || layer_name.ends_with("/presence")) && !can_see_others {
continue;
}
// no_incoming_updates check
if permit.sync_facts().no_incoming_updates.contains(&layer_name.to_string()) {
continue;
}
// Check if page permit covers this layer
if permit.can_read_layer(layer_name, &state.page_id, &permit_holder_did) {
unit.authorize_did(&user_did);
}
}
Extract this into a helper: fn authorize_subscriber_for_layers(state, user_did, permit, permit_holder_did, can_see_others).
Step 3: Populate authorized_dids at layer creation time
When new LayerUnits are created, check existing subscribers.
After creating a new static LayerUnit and inserting into state.units:
rust
// Authorize existing subscribers for this new layer
if let Ok(subs) = state.subscribers.read() {
for ((did, _), info) in subs.iter() {
if info.can_receive_layer(layer_name, &state.page_id) {
unit.authorize_did(did);
}
}
}
Note: During initial setup (before any subscribers), this is a no-op. That's fine.
3b: Dynamic layer creation from peer (scribe/src/sync/apply.rs — create_layer_from_peer())
Same pattern — authorize existing subscribers who have matching permits.
3c: Dynamic layer creation from Lua (scribe/src/layer_unit/dynamic.rs — handle_create_dynamic_layer())
For viewer-created dynamic layers:
rust
// Creator can sync — authorize all current subscribers (viewer mode: just the node)
if let Ok(subs) = state.subscribers.read() {
for ((did, _), _) in subs.iter() {
unit.authorize_did(did);
}
}
Step 4: Populate authorized_dids when layer permits are issued (node side)
4a: emit_dynamic_layer_permits() in scribe/src/sync/apply.rs
Replace the block that adds layer permits to SubscriberInfo (lines 506-530) with:
rust
// Add recipient DIDs to LayerUnit's authorized_dids
if let Some(unit) = state.units.get(layer_name) {
for (recipient_did, _token) in &permits {
unit.authorize_did(recipient_did);
}
}
4b: handle_add_layer_access() in scribe/src/layer_unit/dynamic.rs
// Add to LayerUnit's authorized_dids
let bare_name = normalize_layer_name(layer_name, &state.page_id);
if let Some(unit) = state.units.get(&bare_name) {
unit.authorize_did(did);
}
4c: issue_pending_layer_permits() in scribe/src/sync/subscription.rs
// Add to LayerUnit's authorized_dids
let bare_name = normalize_layer_name(layer_name, &state.page_id);
if let Some(unit) = state.units.get(&bare_name) {
unit.authorize_did(user_did);
}
Step 5: New ScribeMessage for viewer-side layer permit reception
File: scribe/src/message.rs
Add variant:
rust
/// Authorize a subscriber DID for a specific layer
///
/// **Context**: Viewer received LayerPermit from node. Authorize the node
/// (subscriber) on the local Scribe's LayerUnit so the observer broadcasts to it.
AuthorizeLayerSubscriber {
layer_name: String,
subscriber_did: String,
},
File: scribe/src/actor.rs
Handle the message:
rust
ScribeMessage::AuthorizeLayerSubscriber { layer_name, subscriber_did } => {
let bare = normalize_layer_name(&layer_name, &state.page_id);
if let Some(unit) = state.units.get(&bare) {
unit.authorize_did(&subscriber_did);
info!(layer = %bare, did = %subscriber_did, "Authorized subscriber for layer");
} else {
// Layer doesn't exist yet — store pending authorization
state.pending_layer_authorizations
.entry(bare)
.or_insert_with(Vec::new)
.push(subscriber_did);
}
}
Add pending_layer_authorizations: HashMap<String, Vec<String>> to ScribeState. When a layer is later created (in create_layer_from_peer), check and apply pending authorizations.
After storing in butler and before issuing consent (around line 522), add:
rust
// Authorize this layer on local Scribe so observer can broadcast
if let Some(subscription) = state.page_subscriptions.get(page_id) {
let bare_name = layer_name.strip_prefix(&format!("{}/", page_id)).unwrap_or(layer_name);
subscription.scribe.cast(butler::ScribeMessage::AuthorizeLayerSubscriber {
layer_name: bare_name.to_string(),
subscriber_did: node_did.clone(), // The node is our subscriber
}).ok();
}
After removing from subscribers, remove DID from all LayerUnits:
rust
for (_, unit) in &state.units {
unit.revoke_did(user_did);
}
Step 10: Clean up SubscriberInfo
File: scribe/src/state.rs
Remove layer_permits: Vec<gurkha::Permit> field from SubscriberInfo
Remove can_receive_layer() method (replaced by LayerUnit check)
Remove add_layer_permit() method
Keep permit field (still used for: write checks, role extraction, sync facts, initial state delivery)
Keep can_write_layer() (write auth stays subscriber-centric for now)
Keep subscriber_did, is_visible, can_see_others (presence still per-subscriber)
Note: can_write_layer() still uses gurkha::can_access_with_layer_permits() but with empty layer_permits. For dynamic layer writes, the node trusts sync_target (path 2 in Permissions::can_write). This is fine for now — write auth can move to LayerUnit in a follow-up.
Also remove Permissions::can_receive() from scribe/src/permit.rs (dead code, marked #[allow(dead_code)]).
Step 11: Update send_initial_state_to_subscriber
File: scribe/src/sync/subscription.rs
After we populate authorized_dids in Step 2, send_initial_state_to_subscriber can use the same check:
rust
// OLD: if !permit.can_read_layer(layer_name, &state.page_id, subscriber_did) { continue; }
// NEW:
if !unit.is_authorized(user_did) { continue; }
But note: the no_incoming_updates check is already handled in Step 2 (we skip those when populating). The presence check is also handled. So this simplification works.
Integration Tests
File: integration_tests/src/tests/layer_sync.rs
The 8 existing tests should NOT require changes — they test end-to-end sync behavior, not internal authorization structures. The observable behavior is:
Static layers sync ✓ (authorized_dids populated from page permit at subscription)
Dynamic layers sync ✓ (authorized_dids populated when permits are issued)
Viewer receives data ✓ (AuthorizeLayerSubscriber message from PeerActor)
test_custom_channel_data_syncs_to_viewer — was previously failing (the bug!), should now pass
test_static_channel_layer_syncs_to_viewer — static channels through the new path
Risk: If can_write_layer() on SubscriberInfo breaks for dynamic layers (since layer_permits is removed), writes could be rejected. Mitigation: Permissions::can_write has 3 paths — path 2 (sync_target trust) covers viewer→node, path 3 (stored permit lookup) covers node→viewer. Both bypass SubscriberInfo.can_write_layer().
Send AuthorizeLayerSubscriber to local Scribe on layer permit receipt
Verification
bash
# Build check
cargo check --workspace
# Scribe unit tests
cargo test -p scribe
# Gurkha tests (unchanged, but verify no regressions)
cargo test -p gurkha
# Integration tests (the real validation)
cargo test -p integration_tests
# Manual test: dynamic channels
python scripts/test_chat.py
Key manual validation: Alice creates custom channel, Carol writes a message → message syncs to all peers.
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/abe/.claude/projects/-home-abe-osvauld/76e9a3e9-b971-4142-b3e3-974ced98c479.jsonl
Assistant
I'll start by reading all the key files I need to modify to understand the current state. Let me read them in parallel.
Assistant
Now let me read the remaining files I need.
Assistant
Let me check how page_subscriptions works in the peer actor and look at the scribe operations module.
Assistant
Let me check the Scribe lib.rs for exports and the ScribeMessage re-export path.
Assistant
Now I have a complete picture. Let me create tasks to track this work and start implementing.
Assistant
Now let me start implementing. Step 1: Add authorized_dids to LayerUnit.
Assistant
Now add the accessor methods. I'll add them after the observer lifecycle section:
Assistant
Good, the diagnostic for authorized_dids being never read is expected - we'll use it soon. Let me also check that the test_fixtures create LayerUnit properly:
Assistant
Good - LayerUnit is only created via new() and new_empty(), so the diagnostics about missing field are just from the old constructor code which I've already fixed.
Assistant
Now Step 2: Add AuthorizeLayerSubscriber message and pending_layer_authorizations.
Assistant
First, add the message variant to scribe/src/message.rs:
Assistant
Now add pending_layer_authorizations to ScribeState:
Assistant
Initialize the new field in actor.rs pre_start:
Assistant
Now handle the AuthorizeLayerSubscriber message in actor.rs. I'll add it before the Shutdown handler:
Assistant
The compiler says there's another match that's missing the new variant. Let me find it.
Assistant
Hmm, the diagnostics say there are two separate errors - one from rustc and one from rust-analyzer, both pointing at the same line. Let me re-read the actor.rs around the match:
Assistant
The match arm is there. The diagnostics might be stale. Let me continue with the implementation. The diagnostics likely haven't caught up yet.
Assistant
Now Step 3: Populate authorized_dids at subscribe time, layer creation time, and permit issuance time.
Assistant
Step 2 (plan): Populate at subscribe time in subscription.rs
After inserting the subscriber, I need to iterate all existing LayerUnits and authorize this subscriber for layers they can access. I'll also update send_initial_state_to_subscriber to use the new check, and update issue_pending_layer_permits and handle_unsubscribe.
Assistant
Now update send_initial_state_to_subscriber to use unit.is_authorized():
Assistant
Good - the signature change is correct and the caller is already updated. The error is likely from a stale check. Let me verify the call site was updated:
Assistant
Good, only called in one place. Now update handle_unsubscribe (Step 9) to revoke DIDs:
Assistant
Now update issue_pending_layer_permits to authorize via LayerUnit instead of add_layer_permit:
Assistant
Step 3b: Populate at layer creation time (apply.rs — create_layer_from_peer())
When a new layer is created from a peer, authorize existing subscribers:
Assistant
Step 4a: Update emit_dynamic_layer_permits to authorize via LayerUnit
Assistant
Step 4b: Update handle_add_layer_access in dynamic.rs
Assistant
Step 3c: Populate at dynamic layer creation from Lua
For viewer-created dynamic layers, authorize all current subscribers:
Assistant
Now Step 4: Replace broadcast checks and clean up SubscriberInfo.
There's still a reference to Permissions in loro_observer.rs. Let me find it:
Assistant
Permissions is still used for can_local_write — I need to keep that import:
Assistant
Step 8: Replace reconcile check (reconcile.rs)
Assistant
Step 10: Clean up SubscriberInfo
Remove layer_permits, can_receive_layer(), and add_layer_permit() from SubscriberInfo:
Assistant
Now remove the layer_permits: Vec::new() from the subscriber insertion in subscription.rs:
Assistant
Good, there are layer_permits references in test_fixtures.rs too. Let me fix those:
Assistant
Fix the two test fixtures that reference layer_permits:
Assistant
Let me check if there are more references to layer_permits or add_layer_permit anywhere:
Assistant
Good — layer_permits only appears in function names (like prepare_layer_permits) and in comments. No more struct field references. Now let me also remove the dead Permissions::can_receive() from permit.rs:
Assistant
Now let me also check if there are references to can_access_with_layer_permits that need updating:
Assistant
Good - all references to can_access_with_layer_permits have been removed from scribe.
Let me also check if SubscriberInfo is used anywhere else that might reference layer_permits:
Assistant
The layer_permits in gurkha/, butler/, courier/, sthalam/, kunki/, and integration_tests/ are all part of other code paths (butler permit storage, gurkha permit logic, etc.) — not SubscriberInfo.layer_permits. Those are fine.
Let me verify the scribe references only — they should all be function names now:
Assistant
All function/method names — no field references. Now fix the unused device_id warning in issue_pending_layer_permits:
Assistant
The device_id parameter was used to look up SubscriberInfo for add_layer_permit, which we removed. Now we just need user_did. But since it's called with device_id, let me check if removing it breaks the call site:
Assistant
I'll just prefix it with underscore to suppress the warning since removing it would be a bigger change:
Assistant
Now Step 5: Wire courier peer_actor to send AuthorizeLayerSubscriber on layer permit receipt.
Assistant
I need to add code in on_layer_permit to send AuthorizeLayerSubscriber to the local Scribe. Let me look at the full on_layer_permit again to find the right insertion point:
Assistant
I need to add the AuthorizeLayerSubscriber message after storing the permit and before issuing consent. The node is the subscriber on the viewer's Scribe:
Assistant
Now let me verify the butler::ScribeMessage path is correct — butler re-exports ScribeMessage:
Assistant
Good, butler::ScribeMessage is valid. Now let me check if page_subscriptions is accessible from the consent module:
Assistant
Good. Let me also verify the butler import exists in this file:
Assistant
The file doesn't directly import butler. Let me check what's available from crate::message::*:
Assistant
The butler crate is available. Let me check the Cargo.toml for courier to confirm:
Assistant
Good, butler is a dependency. And from peer_actor/mod.rs, butler::ScribeMessage is imported. Since the consent module is part of peer_actor, it can access it via super. But simpler — I can just use butler::ScribeMessage directly since butler is a crate dependency. Let me verify the compiler will be happy — the cast call needs ractor::ActorRef, and PageSubscription.scribe is ActorRef<butler::ScribeMessage>:
This should work. But I realize I should check if butler::ScribeMessage::AuthorizeLayerSubscriber is actually the right path — it's a re-export from scribe. Let me verify:
Assistant
butler::ScribeMessage is the correct path and includes the AuthorizeLayerSubscriber variant. The code in consent.rs should work.
Assistant
Now let's build and test.
Assistant
No errors! Only pre-existing warnings. Let me run the Scribe tests:
Assistant
All 18 tests pass. Let me also run gurkha tests to verify no regressions:
Assistant
All 55 gurkha tests pass. Let me also quickly check the app_test crate builds since it uses SubscriberInfo:
Assistant
Everything builds clean. Let me run the integration tests:
Assistant
All 32 integration tests pass, including the layer sync tests. Let me also run the app_test crate:
Assistant
All 16 app_test tests pass.
Assistant
All tasks complete. Here's a summary of what was implemented:
Summary
What changed
Core: LayerUnit now owns authorization (scribe/src/layer_unit/mod.rs)
Added authorized_dids: Arc<RwLock<HashSet<String>>> field
Dynamic layer from Lua (layer_unit/dynamic.rs) — authorizes all current subscribers
Permit issuance (sync/apply.rs, layer_unit/dynamic.rs, sync/subscription.rs) — directly authorizes on LayerUnit instead of adding to SubscriberInfo
Broadcast checks replaced (3 files):
loro_observer.rs — captures authorized_dids Arc, reads once per broadcast cycle
sync/broadcast.rs — reads authorized_dids once before subscriber loop
sync/reconcile.rs — reads per-layer authorization for divergence check
Unsubscribe cleanup (sync/subscription.rs) — revokes DID from all LayerUnits
Viewer-side wiring (courier/src/peer_actor/consent.rs) — on_layer_permit() sends AuthorizeLayerSubscriber to local Scribe
Dead code removed:
Permissions::can_receive() from permit.rs
Test results
18/18 scribe unit tests pass
55/55 gurkha tests pass
32/32 integration tests pass (including all 8 layer_sync tests)
16/16 app_test tests pass
User
Verification
bash
# Build check
cargo check --workspace
# Scribe unit tests
cargo test -p scribe
# Gurkha tests (unchanged, but verify no regressions)
cargo test -p gurkha
# Integration tests (the real validation)
cargo test -p integration_tests
# Manual test: dynamic channels
python scripts/test_chat.py
Key manual validation: Alice creates custom channel, Carol writes a message → message syncs to all peers.
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/abe/.claude/projects/-home-abe-osvauld/76e9a3e9-b971-4142-b3e3-974ced98c479.jsonl
Send AuthorizeLayerSubscriber to local Scribe on layer permit receipt
User
Integration Tests
File: integration_tests/src/tests/layer_sync.rs
The 8 existing tests should NOT require changes — they test end-to-end sync behavior, not internal authorization structures. The observable behavior is:
Static layers sync ✓ (authorized_dids populated from page permit at subscription)
Dynamic layers sync ✓ (authorized_dids populated when permits are issued)
Viewer receives data ✓ (AuthorizeLayerSubscriber message from PeerActor)
test_custom_channel_data_syncs_to_viewer — was previously failing (the bug!), should now pass
test_static_channel_layer_syncs_to_viewer — static channels through the new path
Risk: If can_write_layer() on SubscriberInfo breaks for dynamic layers (since layer_permits is removed), writes could be rejected. Mitigation: Permissions::can_write has 3 paths — path 2 (sync_target trust) covers viewer→node, path 3 (stored permit lookup) covers node→viewer. Both bypass SubscriberInfo.can_write_layer().
User
Step 11: Update send_initial_state_to_subscriber
File: scribe/src/sync/subscription.rs
After we populate authorized_dids in Step 2, send_initial_state_to_subscriber can use the same check:
rust
// OLD: if !permit.can_read_layer(layer_name, &state.page_id, subscriber_did) { continue; }
// NEW:
if !unit.is_authorized(user_did) { continue; }
But note: the no_incoming_updates check is already handled in Step 2 (we skip those when populating). The presence check is also handled. So this simplification works.
User
Step 10: Clean up SubscriberInfo
File: scribe/src/state.rs
Remove layer_permits: Vec<gurkha::Permit> field from SubscriberInfo
Remove can_receive_layer() method (replaced by LayerUnit check)
Remove add_layer_permit() method
Keep permit field (still used for: write checks, role extraction, sync facts, initial state delivery)
Keep can_write_layer() (write auth stays subscriber-centric for now)
Keep subscriber_did, is_visible, can_see_others (presence still per-subscriber)
Note: can_write_layer() still uses gurkha::can_access_with_layer_permits() but with empty layer_permits. For dynamic layer writes, the node trusts sync_target (path 2 in Permissions::can_write). This is fine for now — write auth can move to LayerUnit in a follow-up.
Also remove Permissions::can_receive() from scribe/src/permit.rs (dead code, marked #[allow(dead_code)]).
Currently the observer captures subscribers_for_task and checks info.can_receive_layer(). Change to:
rust
// Capture authorized_dids Arc at setup time
let authorized_dids_for_task = state.units.get(layer_name).unwrap().authorized_dids().clone();
// Inside the async task, replace:
// if !info.can_receive_layer(...) { continue; }
// with:
let authorized = authorized_dids_for_task.read().unwrap_or_else(|e| e.into_inner());
for ((user_did, device_id), info) in subs.iter() {
if !authorized.contains(user_did) {
continue;
}
// ... broadcast
}
User
Step 5: New ScribeMessage for viewer-side layer permit reception
File: scribe/src/message.rs
Add variant:
rust
/// Authorize a subscriber DID for a specific layer
///
/// **Context**: Viewer received LayerPermit from node. Authorize the node
/// (subscriber) on the local Scribe's LayerUnit so the observer broadcasts to it.
AuthorizeLayerSubscriber {
layer_name: String,
subscriber_did: String,
},
File: scribe/src/actor.rs
Handle the message:
rust
ScribeMessage::AuthorizeLayerSubscriber { layer_name, subscriber_did } => {
let bare = normalize_layer_name(&layer_name, &state.page_id);
if let Some(unit) = state.units.get(&bare) {
unit.authorize_did(&subscriber_did);
info!(layer = %bare, did = %subscriber_did, "Authorized subscriber for layer");
} else {
// Layer doesn't exist yet — store pending authorization
state.pending_layer_authorizations
.entry(bare)
.or_insert_with(Vec::new)
.push(subscriber_did);
}
}
Add pending_layer_authorizations: HashMap<String, Vec<String>> to ScribeState. When a layer is later created (in create_layer_from_peer), check and apply pending authorizations.
After storing in butler and before issuing consent (around line 522), add:
rust
// Authorize this layer on local Scribe so observer can broadcast
if let Some(subscription) = state.page_subscriptions.get(page_id) {
let bare_name = layer_name.strip_prefix(&format!("{}/", page_id)).unwrap_or(layer_name);
subscription.scribe.cast(butler::ScribeMessage::AuthorizeLayerSubscriber {
layer_name: bare_name.to_string(),
subscriber_did: node_did.clone(), // The node is our subscriber
}).ok();
}
User
Step 4: Populate authorized_dids when layer permits are issued (node side)
4a: emit_dynamic_layer_permits() in scribe/src/sync/apply.rs
Replace the block that adds layer permits to SubscriberInfo (lines 506-530) with:
rust
// Add recipient DIDs to LayerUnit's authorized_dids
if let Some(unit) = state.units.get(layer_name) {
for (recipient_did, _token) in &permits {
unit.authorize_did(recipient_did);
}
}
4b: handle_add_layer_access() in scribe/src/layer_unit/dynamic.rs
// Add to LayerUnit's authorized_dids
let bare_name = normalize_layer_name(layer_name, &state.page_id);
if let Some(unit) = state.units.get(&bare_name) {
unit.authorize_did(did);
}
4c: issue_pending_layer_permits() in scribe/src/sync/subscription.rs
// Add to LayerUnit's authorized_dids
let bare_name = normalize_layer_name(layer_name, &state.page_id);
if let Some(unit) = state.units.get(&bare_name) {
unit.authorize_did(user_did);
}
User
Step 3: Populate authorized_dids at layer creation time
When new LayerUnits are created, check existing subscribers.
After creating a new static LayerUnit and inserting into state.units:
rust
// Authorize existing subscribers for this new layer
if let Ok(subs) = state.subscribers.read() {
for ((did, _), info) in subs.iter() {
if info.can_receive_layer(layer_name, &state.page_id) {
unit.authorize_did(did);
}
}
}
Note: During initial setup (before any subscribers), this is a no-op. That's fine.
3b: Dynamic layer creation from peer (scribe/src/sync/apply.rs — create_layer_from_peer())
Same pattern — authorize existing subscribers who have matching permits.
3c: Dynamic layer creation from Lua (scribe/src/layer_unit/dynamic.rs — handle_create_dynamic_layer())
For viewer-created dynamic layers:
rust
// Creator can sync — authorize all current subscribers (viewer mode: just the node)
if let Ok(subs) = state.subscribers.read() {
for ((did, _), _) in subs.iter() {
unit.authorize_did(did);
}
}
User
Step 2: Populate authorized_dids at subscription time
After inserting the subscriber into state.subscribers, iterate all existing LayerUnits and check the new subscriber's permit:
rust
// Populate authorized_dids on existing LayerUnits for this subscriber
for (layer_name, unit) in &state.units {
// Skip local-only layers
if unit.is_local_only() { continue; }
// Presence layer: only if can_see_others
if (layer_name == "presence" || layer_name.ends_with("/presence")) && !can_see_others {
continue;
}
// no_incoming_updates check
if permit.sync_facts().no_incoming_updates.contains(&layer_name.to_string()) {
continue;
}
// Check if page permit covers this layer
if permit.can_read_layer(layer_name, &state.page_id, &permit_holder_did) {
unit.authorize_did(&user_did);
}
}
Extract this into a helper: fn authorize_subscriber_for_layers(state, user_did, permit, permit_holder_did, can_see_others).
User
Step 1: Add authorized_dids to LayerUnit
File: scribe/src/layer_unit/mod.rs
rust
pub struct LayerUnit {
layer: Layer,
dirty: bool,
is_local_only: bool,
pub is_dynamic: bool,
loro_sub: Option<loro::Subscription>,
/// Which subscriber DIDs are authorized to receive updates for this layer.
/// Arc<RwLock> because the observer async task needs shared read access.
/// Populated at subscription time (page permit) and permit issuance (layer permits).
authorized_dids: Arc<RwLock<HashSet<String>>>,
}
Add methods:
pub fn authorized_dids(&self) -> &Arc<RwLock<HashSet<String>>> — for observer to clone the Arc
pub fn authorize_did(&self, did: &str) — insert DID (takes &self via RwLock)
Update new() and new_empty() to initialize authorized_dids: Arc::new(RwLock::new(HashSet::new())).
User
e2e_tests/test_custom_channel.py check this out, so now also we still have no data sync from other users, only alice data goes to them. refer the jsonl Captured 342 events -> /tmp/custom_channel_test/captures/custom_channel_merged.jsonl so we have the events here. can you check analyze it and check whats the issue?
Assistant
Let me look at the test script and the captured events.
Assistant
Let me dig deeper into the specific per-instance captures. The analysis shows AuthorizeLayerSubscriber wasn't captured and Bob/Carol writes never reach the node. Let me trace the issue.
Assistant
Let me continue by adding deeper observability for the authorization flow. First, let me read the current state of key files to understand the capture infrastructure.
Assistant
Now let me read the other key files to understand the full flow.
User
[Request interrupted by user]
User
check again in the captures we have added observability to there as well.
Assistant
Let me read the capture files to see what we already have.
Assistant
Good - I can see we now have layer_auth events (line 9 in Bob's capture). Let me check all event types we're capturing and look at the node's events for the critical flow.
Assistant
Great, we have layer_auth events. Now let me trace the critical flow: Bob writes, then what happens on the node side.
Assistant
Now let me check what page_updates the node sees for the dynamic layer specifically.
Assistant
Critical finding: the node receives read_positions data from Bob just fine, but NEVER sees Bob's message on the dynamic layer. The SyncOffer/SyncAccept happens but we can't tell WHICH layer it's for. Let me check what data the message traces include.
Assistant
The message traces don't capture which layer the SyncOffer is for - that's a gap. But the critical finding is: the node never sees Bob's message data arrive on the dynamic layer (only read_positions changes appear). Let me check the sync/apply path to understand why.
Assistant
Now I see the picture clearly. Let me check the permit template to confirm my theory about why Bob's writes are rejected.
Assistant
I've found the root cause. Let me answer your questions about observability and explain what's actually broken.
Analysis of Current Captures
The current capture events are revealing enough to identify the problem. Here's the timeline from Bob's perspective:
LayerPermit received (16:28:22.325) - Bob gets the permit
layer_auth: authorized - node DID authorized on Bob's local Scribe
Bob writes (16:28:25.266) - message appears locally
But on the node: no page_update for Bob's message on the dynamic layer. The node only sees read_positions changes from Bob. The node receives and processes Bob's SyncOffer for read_positions successfully, but silently drops Bob's write to the dynamic layer.
Root Cause
The issue is not in the authorized_dids / broadcast path. It's in Permissions::can_write() in scribe/src/permit.rs:175-218. When Bob sends data to the node:
Path 1 (subscriber permit): Bob's page permit only has fixed layers like channels/general/messages. It does NOT have channels/did:key:alice.../project-x/messages
Path 2 (sync_target): Node is Broadcast mode - no sync_target - N/A
Path 3 (stored permit): Same page permit, same result - doesn't cover dynamic layers
The dynamic_layer_schemas section grants write: true for collaborator role, but can_write_layer() only checks the layers section, not dynamic_layer_schemas. So the node rejects Bob's write silently.
What Observability Events to Add
Two things would have made this immediately obvious:
Write permission decision capture - When Permissions::can_write() returns false, emit a layer_auth event with action: "write_denied"
Apply update outcome capture - When handle_apply_update rejects, emit an event with the rejection reason
For filtering, adding the layer name to message_trace for SyncOffer/SyncAccept would let us correlate which syncs succeed and which fail.
Let me add these observability events AND fix the root cause. Let me check gurkha's can_write_layer to understand how to make it cover dynamic schemas.
User
[Request interrupted by user]
User
only give me a detailed description of what all do you think we should add, now that you have used it, what extra convinience tags could we add etc as well please. be detailed about it.
Assistant
Observability Gaps: What I Needed But Didn't Have
After spending significant time tracing the captures to find the root cause, here's a comprehensive breakdown.
This is the single biggest gap. The node silently rejected Bob's write to the dynamic layer, and there was zero trace of it in the captures. I had to read the source code of Permissions::can_write() and mentally simulate all 3 paths to figure out the rejection.
Where to add:scribe/src/permit.rs — Permissions::can_write()
When result is "denied", include which paths were tried and why they failed. When result is "allowed", include which path granted access. This would have immediately told me "the node denied Bob's write to the dynamic layer via all 3 paths."
Also add the same for Permissions::can_local_write() in loro_observer.rs — this catches cases where the local Scribe blocks writes.
2. Apply Update Outcomes (type: "apply_update")
When handle_apply_update completes (success or rejection), there's no capture event. I could only infer rejection from the absence of a page_update for the dynamic layer on the node — which is error-prone when you're scanning 87 lines.
Where to add:scribe/src/sync/apply.rs — end of handle_apply_update()
Fields needed:
json
User
okay now lets add the fix as well please.
Assistant
Let me first understand the current state of all the files I need to modify for both the fix and observability.
Assistant
Now let me read the apply.rs get_peer_role function and check what's needed for the fix.
Assistant
Now I have the full picture. Let me create tasks and implement everything.
Assistant
Task 1: Add matches_dynamic_schema_for_role to gurkha
Assistant
Now export the new function from the decision module.
Assistant
Now export from the gurkha lib as well.
Assistant
Now add tests for the new function.
Assistant
Now let me check the shop_owner test fixture to see what dynamic_layer_schemas it has.
Assistant
I need to fix my tests based on the actual shop.json schema. The owner's schema has grant: "explicit" with permissions (not role_permissions), so any role would match the explicit permissions. Let me use the admin fixture for role-based testing.
Assistant
Task 2: Fix Permissions::can_write for dynamic layers
Assistant
Task 3: Add P0 observability events
First, add a permission_check capture method to ScribeState, then emit it from can_write. Then add apply_update capture to handle_apply_update.
Assistant
Now wire in the permission_check capture to Permissions::can_write:
Assistant
Now add the apply_update capture to handle_apply_update:
Assistant
Task 4: Build and test
Assistant
Compiles. Now run the tests:
Assistant
All 58 gurkha tests and 18 scribe tests pass. Now run integration tests:
Assistant
All 32 integration tests pass. Let me also run the app_test crate:
Assistant
All tests pass:
58 gurkha tests (including 3 new tests for dynamic schema role matching)
18 scribe tests
32 integration tests
16 app_test tests
Assistant
Summary
Root Cause Fix
The node's Permissions::can_write() was rejecting writes from viewers (Bob, Carol) to dynamic layers. The dynamic layer path channels/did:key:alice/project-x/messages contains Alice's DID, but Bob's page permit only covers layers with Bob's own DID. None of the 3 existing paths in can_write() handled this.
Fix: Added path 4 to Permissions::can_write() that checks the node's own permit's dynamic_layer_schemas against the peer's role. The schema channels/{id}/messages has role_permissions.collaborator.write = true, so Bob (collaborator) is now authorized.
I could see Bob sent SyncOffer and the node sent SyncAccept. But I couldn't tell which layer each was for. Bob was syncing both read_positions (which worked) and the dynamic layer (which was silently rejected). Without the layer name, I had to correlate timestamps and infer from page_update events.
Where to add:courier/src/trace.rs or wherever message traces are emitted.
The layer and page_id fields would let me immediately correlate: "Bob sent SyncOffer for the dynamic layer → node received it → but no apply_update success for that layer → look at permission_check."
4. Subscriber State Events (type: "subscriber_state")
When the node subscribes Bob, what does the subscriber state look like? What layers is Bob authorized for? Currently I can see individual layer_auth events, but there's no snapshot of "here's the full authorization state for this subscriber."
Where to add:scribe/src/sync/subscription.rs — end of handle_subscribe()
In loro_observer.rs, the observer decides per-subscriber whether to broadcast. Currently there's no trace when a subscriber is skipped (not in authorized_dids). This would have been useful to see "observer fired for dynamic layer, but Bob was not in authorized_dids."
Where to add:scribe/src/loro_observer.rs — inside the subscriber loop
Fields needed (only emit on skip, not on success — too noisy):
Also emit when skipping due to is_local_only or from_peer (remote update sender exclusion), but with reason: "local_only" or reason: "sender_exclusion".
And in broadcast_update (broadcast.rs) and handle_reconcile_with_peers (reconcile.rs) — same pattern.
Full DIDs are 50+ characters long. Every time I analyzed events, I had to manually figure out which DID was Alice, Bob, Carol, or the node. A one-time mapping event emitted at connection time would save enormous time.
Where to add:courier/src/peer_actor/mod.rs — on successful authentication, or in the capture system when capture starts.
This allows building a lookup table at the start of any analysis session. Would also be useful to add "peer_name" or "short_did" as a convenience field on ALL events that have a DID, so you don't have to cross-reference.
The layer name channels/did:key:REDACTED is very long. A shortened version like channels/.../project-x/messages or just project-x/messages would help scanning.
Add event_id or seq for ordering:
Timestamps have millisecond resolution. Multiple events happen in the same millisecond (e.g., the node emitting 3 authorized_dynamic_permit events all at 1770827302323). A monotonic sequence number per instance would make ordering unambiguous.
Add phase tag for grouping:
Events naturally cluster into phases. A tag like:
"phase": "handshake" — Hello, Welcome, SyncOffer, SyncAccept during initial connect
"phase": "steady_state" — regular SyncOffer/Accept during ongoing operation
This would let you filter grep '"phase": "dynamic_layer"' to see just the channel creation flow.
8. Pending Authorizations State
When AuthorizeLayerSubscriber arrives before the layer exists, it goes to pending_layer_authorizations. But there's no event showing this. Later when the layer is created and pending authorizations are applied, there is an applied_pending event — but if the layer never gets created, the pending authorization silently vanishes.
Where to add:scribe/src/actor.rs — in the AuthorizeLayerSubscriber handler