Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Phase 8: open design items, retention, multi-device, and views

- Plan: [phased plan](../2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md), section 12.
- Start commit: d4e99105 (origin/main, after Phase 7 and #205).
- Base branch `phase-8`. Tracks:
- `p8-warnings`: P8.6 warnings UI (show group size tier and churn warnings in group status/list views).
- `p8-multidevice`: P8.3 multi-device (device keys authorized by account keys via `device.add` and `device.revoke`).
- `p8-pruning`: P8.2 retention and pruning (retention behind causal-cut snapshot, respecting open removals and frontiers).
- `p8-views`: P8.4 views (directory explorer lines in shared grammar).
- P8.5 cross-world rules: reconciled with delegation (checked against P2.7 `src/groups/worlds.rs`).
- Explicitly skipped/deferred:
- P8.1 time and witnesses (task 09, deferred; causal validity only).
- P8.7 BeeKEM (owner confirmed: skip).
- P8.8 clippy/lint sweeps (review later; do nothing now).

## Steps

| Step | Track | Status | Commits | Tests | Notes |
| ---- | ----------- | -------- | ------------------ | -------------------------------------------------- | ------------------------------------------------------------------ |
| P8.1 | - | deferred | | | causal validity only (task 09) |
| P8.2 | pruning | done | 678e9e63, a3c82d7c | retention_pruning: 4; event_store: 92 | retention behind causal-cut snapshot |
| P8.3 | multidevice | done | 862639b4, 76f5084d | multidevice: 6 (22 red compile errors before feat) | device chains & account delegations; cascade revocation & counting |
| P8.4 | views | done | 1d8321f1, babadcb4 | views_explorer: 6; directory_view: 21 | directory explorer waiting, voided, frozen sections |
| P8.5 | worlds | done | in P2.7 | groups::worlds: 9 | cross-world delegation reconciliation |
| P8.6 | warnings | done | 1289cef6, 472d45d3 | cli_warnings 3; cli_groups 8; warnings 12 | size tier and churn warnings in group status |
| P8.7 | - | skipped | | | owner confirmed: skip BeeKEM |
| P8.8 | - | deferred | | | do nothing now |

## 2026-10-13T23:55:00Z Note: P8.6 warnings UI in group status and list

- Group size tier and churn warnings are wired into `id group policy` and `id group list`.
- Size tiers: tier=0 for <96 members, tier=96 for 96..127, tier=128 for 128..999, tier=1000 for >=1000 members.
- Crossing warnings from `Evaluator` are formatted via `Warning::message()`.
- Text mode includes `tier=<usize>` and optional `warning=<message>`.
- JSON mode (`--json`) includes `"tier": usize` and optional `"warning": string`.
- Red first: integration tests in `tests/cli_warnings.rs` failed initially (commit 1289cef6) and passed after wiring (commit 472d45d3).
- Targeted test suite passes: `cli_warnings` (3 tests), `cli_groups` (8 tests), `warnings` (12 tests).

## 2026-10-13T23:55:00Z Note: P8.4 views for waiting, voided, and frozen events

- Extended `DirectoryView` and `render_text` in `src/directory_view.rs` to support inspecting event state:
- Waiting events: section `waiting:` listing event ID, missing dependency hash, and reason formatted as "waiting: missing <hash>".
- Voided events: section `voided:` listing event ID, voiding authority/removal hash, and reason formatted as "voided: concurrent with <hash>".
- Frozen chains: section `frozen:` listing author/event ID, fork sequence/proof hash, and reason formatted as "frozen: fork at seq <n>".
- Shared types `WaitingView`, `VoidedView`, and `FrozenView` keep HTTP JSON serialization and SSH text rendering in step.
- Red first: integration tests in `tests/views_explorer.rs` failed on missing fields and types (commit 1d8321f1). Green after implementation (commit babadcb4).
- Tests: `views_explorer`: 6 passed; `directory_view`: 21 passed.

## 2026-10-13T23:55:00Z Note: P8.3 Multi-device delegation and device counting

- Each device has its own key and chain. An account authorizes devices through signed `device.add` (`DEVICE_ADD_KIND`) and `device.revoke` (`DEVICE_REVOKE_KIND`) operations (`DeviceOp`).
- Device authorizations are structured as capability delegations from the account key: a device acts on behalf of the account for authorized groups and scopes.
- When an account is removed or revokes a device via `device.revoke`, the device's authorization is severed following cascade rules.
- Device counting helpers `active_device_count(&group, &account)` and `group_device_count(&group)` (available on `Projection` and `GroupLog`) accurately return active authorized device counts for an account and across a group.
- Red first: `cargo test --test multidevice` failed with 22 compilation errors in `862639b4`. Green after `76f5084d`: 6 of 6 integration tests pass in `tests/multidevice.rs`; all 12 `delegation` tests in `src/lib.rs` pass.

## 2026-10-13T23:59:00Z Note: P8.2 retention and pruning behind causal cut

- Implemented `EventStore::prune_behind_cut(&mut self, cut: &[Hash], protected: &[Hash]) -> Result<usize, StoreError>`.
- Preserves every event back to the causal past of open removals (needed for membership voidness check) and open frontiers.
- Active backlink walks and dependency index invariants are preserved; author chain rows are adjusted or removed on total pruning.
- Pruned events are removed from `events`, `hashes`, `groups`, `actions`, and `applied` tables.
- Invariants check (`check_invariants`) and query folds (`roster`, `tag_claims`, `documents`) produce identical results before and after pruning.
- Red first: integration tests in `tests/retention_pruning.rs` failed initially (commit 678e9e63) and passed after implementation (commit a3c82d7c).
- Targeted test suite passes: `retention_pruning` (4 tests), `event_store` (92 passed, 2 ignored).
45 changes: 43 additions & 2 deletions pkgs/id/src/commands/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use p2panda_core::Hash;
use serde_json::{Map, Value, json};

use crate::cli::{DelegateArgs, GroupCommand, GroupTemplate, RevokeArgs};
use crate::encryption::warnings::{Evaluator, Observation, Warning, size_tier};
use crate::groups::actions::{Action, NewGroup};
use crate::groups::log::{FILE_NAME, GroupLog, hash_from_hex, key_from_hex};
use crate::groups::policy::{History, Join, OnMemberRemoved, Removal};
Expand Down Expand Up @@ -161,6 +162,35 @@ fn policy_fields(view: &GroupView) -> Vec<(&'static str, Value)> {
]
}

/// The size tier and any Evaluator crossing warning for a group (P8.6).
fn evaluate_group(group: Hash, members: usize) -> (usize, Option<String>) {
let tier = size_tier(members);
let observation = Observation {
group,
client_made: true,
members,
readds: &[],
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let mut evaluator = Evaluator::default();
let warnings = evaluator.observe(&observation, now);
let size_warning = warnings
.iter()
.filter(|w| matches!(w, Warning::Size { .. }))
.last();
let churn_warning = warnings.iter().find(|w| matches!(w, Warning::Churn { .. }));
let warning = match (size_warning, churn_warning) {
(Some(size), Some(churn)) => Some(format!("{}; {}", size.message(), churn.message())),
(Some(size), None) => Some(size.message()),
(None, Some(churn)) => Some(churn.message()),
(None, None) => None,
};
(tier, warning)
}

/// Runs an `id group` command.
///
/// # Errors
Expand Down Expand Up @@ -225,6 +255,11 @@ pub async fn cmd_group(path: Option<PathBuf>, json: bool, command: GroupCommand)
let view = log.view(group)?;
let mut fields = vec![("group", json!(group.to_hex()))];
fields.extend(policy_fields(&view));
let (tier, warning) = evaluate_group(group, view.members.len());
fields.push(("tier", json!(tier)));
if let Some(warning) = &warning {
fields.push(("warning", json!(warning)));
}
if json {
let mut with_command = vec![("command", json!("policy"))];
with_command.extend(fields);
Expand Down Expand Up @@ -282,11 +317,17 @@ pub async fn cmd_group(path: Option<PathBuf>, json: bool, command: GroupCommand)
let rows: Vec<Vec<(&str, Value)>> = projection
.groups()
.map(|(id, view)| {
vec![
let (tier, warning) = evaluate_group(*id, view.members.len());
let mut row = vec![
("group", json!(id.to_hex())),
("active", json!(view.is_active())),
("members", json!(view.members.len())),
]
("tier", json!(tier)),
];
if let Some(warning) = warning {
row.push(("warning", json!(warning)));
}
row
})
.collect();
if json {
Expand Down
159 changes: 159 additions & 0 deletions pkgs/id/src/directory_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ pub struct DirectoryView {
/// The viewer's own envelopes still in, or recently left, the outbox.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub deliveries: Vec<DeliveryView>,
/// Events waiting on missing dependencies.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub waiting: Vec<WaitingView>,
/// Events voided in causal order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub voided: Vec<VoidedView>,
/// Chains frozen due to forks.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub frozen: Vec<FrozenView>,
}

/// An account as one viewer sees it.
Expand Down Expand Up @@ -456,6 +465,100 @@ fn delivery(entry: &Entry, envelope: &Envelope) -> DeliveryView {
}
}

/// An event waiting on missing dependencies.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WaitingView {
/// The event ID.
pub id: String,
/// The missing dependency hash.
pub missing: String,
/// The reason formatted as `waiting: missing <hash>`.
pub reason: String,
}

impl WaitingView {
/// Create a waiting event view with its reason formatted as `waiting: missing <hash>`.
#[must_use]
pub fn new(id: impl Into<String>, missing: impl Into<String>) -> Self {
let missing = missing.into();
Self {
id: id.into(),
reason: format!("waiting: missing {missing}"),
missing,
}
}
}

/// An event voided in causal order.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VoidedView {
/// The event ID.
pub id: String,
/// The voiding authority or removal hash.
#[serde(alias = "voided_by", alias = "authority")]
pub removal: String,
/// The reason formatted as `voided: concurrent with <hash>`.
pub reason: String,
}

impl VoidedView {
/// Create a voided event view with its reason formatted as `voided: concurrent with <hash>`.
#[must_use]
pub fn new(id: impl Into<String>, removal: impl Into<String>) -> Self {
let removal = removal.into();
Self {
id: id.into(),
reason: format!("voided: concurrent with {removal}"),
removal,
}
}

/// The voiding authority or removal hash.
#[must_use]
pub fn voided_by(&self) -> &str {
&self.removal
}

/// The voiding authority or removal hash.
#[must_use]
pub fn authority(&self) -> &str {
&self.removal
}
}

/// A chain frozen due to a fork.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrozenView {
/// The author or event ID.
#[serde(alias = "author")]
pub id: String,
/// The sequence number where the fork occurred.
pub seq: u64,
/// The fork proof hash.
pub proof: String,
/// The reason formatted as `frozen: fork at seq <n>`.
pub reason: String,
}

impl FrozenView {
/// Create a frozen chain view with its reason formatted as `frozen: fork at seq <n>`.
#[must_use]
pub fn new(id: impl Into<String>, seq: u64, proof: impl Into<String>) -> Self {
Self {
id: id.into(),
seq,
proof: proof.into(),
reason: format!("frozen: fork at seq {seq}"),
}
}

/// The author or event ID.
#[must_use]
pub fn author(&self) -> &str {
&self.id
}
}

/// One line typed at an explorer.
#[derive(Debug, PartialEq, Eq)]
pub enum Line {
Expand Down Expand Up @@ -1435,6 +1538,9 @@ fn view(directory: &Directory, petnames: &Petnames, viewer: &Viewer) -> Director
accounts,
groups,
deliveries: Vec::new(),
waiting: Vec::new(),
voided: Vec::new(),
frozen: Vec::new(),
}
}

Expand Down Expand Up @@ -1584,6 +1690,27 @@ pub fn render_text(view: &DirectoryView) -> String {
));
}
}
if !view.waiting.is_empty() {
lines.push(String::new());
lines.push("waiting:".to_owned());
for item in &view.waiting {
lines.push(format!(" {} {} {}", item.id, item.missing, item.reason));
}
}
if !view.voided.is_empty() {
lines.push(String::new());
lines.push("voided:".to_owned());
for item in &view.voided {
lines.push(format!(" {} {} {}", item.id, item.removal, item.reason));
}
}
if !view.frozen.is_empty() {
lines.push(String::new());
lines.push("frozen:".to_owned());
for item in &view.frozen {
lines.push(format!(" {} {} {}", item.id, item.proof, item.reason));
}
}
let mut text = lines.join("\n");
text.push('\n');
text
Expand Down Expand Up @@ -2532,4 +2659,36 @@ mod tests {
};
assert!(!local.queues_for_other_servers(&directory, &mut auth, &as_ada, 0));
}

#[test]
fn waiting_voided_and_frozen_views_render_and_serialize() {
let view = DirectoryView {
viewer: "admin".to_owned(),
accounts: Vec::new(),
groups: Vec::new(),
deliveries: Vec::new(),
waiting: vec![WaitingView::new("w-1", "dep-1")],
voided: vec![VoidedView::new("v-1", "rem-1")],
frozen: vec![FrozenView::new("f-1", 5, "proof-1")],
};

let rendered = render_text(&view);
assert!(rendered.contains("waiting:"));
assert!(rendered.contains(" w-1 dep-1 waiting: missing dep-1"));
assert!(rendered.contains("voided:"));
assert!(rendered.contains(" v-1 rem-1 voided: concurrent with rem-1"));
assert!(rendered.contains("frozen:"));
assert!(rendered.contains(" f-1 proof-1 frozen: fork at seq 5"));

let json = serde_json::to_string(&view).unwrap();
assert!(json.contains("\"waiting\""));
assert!(json.contains("\"voided\""));
assert!(json.contains("\"frozen\""));
assert!(json.contains("waiting: missing dep-1"));
assert!(json.contains("voided: concurrent with rem-1"));
assert!(json.contains("frozen: fork at seq 5"));

let roundtrip: DirectoryView = serde_json::from_str(&json).unwrap();
assert_eq!(view, roundtrip);
}
}
28 changes: 28 additions & 0 deletions pkgs/id/src/encryption/warnings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ use p2panda_core::Hash;
/// The member counts that warn (N11).
pub const SIZE_THRESHOLDS: [usize; 3] = [96, 128, 1_000];

/// The size tier for a given member count (P8.6).
///
/// tier=0 for <96 members, tier=96 for 96..127, tier=128 for 128..999, tier=1000 for >=1000 members.
pub const fn size_tier(members: usize) -> usize {
if members >= 1_000 {
1_000
} else if members >= 128 {
128
} else if members >= 96 {
96
} else {
0
}
}

/// The re-add window, in seconds: one day.
pub const CHURN_WINDOW_SECS: u64 = 24 * 60 * 60;

Expand Down Expand Up @@ -174,6 +189,19 @@ mod tests {
Warning::Size { threshold, members }
}

#[test]
fn test_size_tier() {
assert_eq!(size_tier(0), 0);
assert_eq!(size_tier(1), 0);
assert_eq!(size_tier(95), 0);
assert_eq!(size_tier(96), 96);
assert_eq!(size_tier(127), 96);
assert_eq!(size_tier(128), 128);
assert_eq!(size_tier(999), 128);
assert_eq!(size_tier(1_000), 1_000);
assert_eq!(size_tier(2_000), 1_000);
}

#[test]
fn test_each_threshold_warns_at_its_count_and_not_one_below() {
// A new group that starts at `members` has crossed every threshold at or below it.
Expand Down
Loading
Loading