Compare commits
16 Commits
ddfb95d683
...
feature/ar
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c9387fb1d | ||
|
|
f8296fa03b | ||
|
|
229e483430 | ||
|
|
03d0781c39 | ||
|
|
1e858e1d1f | ||
|
|
bd3d53fddb | ||
|
|
3b09adf3b2 | ||
|
|
4f7ab91f14 | ||
|
|
4a726c2631 | ||
|
|
450de33c0a | ||
|
|
dd0010db62 | ||
|
|
29146439bb | ||
|
|
cf66bd97b7 | ||
|
|
061facd5a9 | ||
|
|
bd6a30155e | ||
|
|
8baef5b3cb |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -8,3 +8,9 @@ extension/wasm/
|
||||
reference.jpg
|
||||
ref.jpg
|
||||
tools/relay/node_modules/
|
||||
|
||||
# Local Gitea credentials (do not commit)
|
||||
.gitea_env_vars
|
||||
|
||||
# Scratch reviewer subagent output (raw drafts; canonical notes live in docs/superpowers/reviews/2026-*-dev-*-notes.md)
|
||||
docs/superpowers/reviews/.dev-c-content.md
|
||||
|
||||
6
Cargo.lock
generated
6
Cargo.lock
generated
@@ -2156,7 +2156,7 @@ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||
|
||||
[[package]]
|
||||
name = "relicario-cli"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
@@ -2185,7 +2185,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "relicario-core"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"base64",
|
||||
@@ -2231,7 +2231,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "relicario-wasm"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"ed25519-dalek",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "relicario-cli"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
description = "CLI for relicario password manager"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "relicario-core"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
description = "Core library for relicario password manager"
|
||||
|
||||
|
||||
@@ -1,13 +1,107 @@
|
||||
//! Recovery-QR encoding for the reference image_secret.
|
||||
//!
|
||||
//! ## What this module produces
|
||||
//!
|
||||
//! Given a user-chosen recovery passphrase and the 32-byte image_secret
|
||||
//! (extracted from the reference JPEG via [`crate::imgsecret::extract`]), this
|
||||
//! module produces a 109-byte sealed payload that — at recovery time, with the
|
||||
//! same passphrase — yields the original image_secret back. The payload is
|
||||
//! intended to be rendered as a QR v40 EcLevel::M SVG via [`recovery_qr_to_svg`]
|
||||
//! and printed on paper, so a user who loses access to the reference JPEG can
|
||||
//! still unlock their vault if they remember the recovery passphrase.
|
||||
//!
|
||||
//! ## Why the format is structured this way
|
||||
//!
|
||||
//! The payload is an XChaCha20-Poly1305 envelope around the image_secret. The
|
||||
//! AEAD key (the "wrap key") is derived by Argon2id from a domain-separated
|
||||
//! input:
|
||||
//!
|
||||
//! ```text
|
||||
//! kdf_input = b"relicario-recovery-v1\0"
|
||||
//! || u64_be(len(nfc(passphrase)))
|
||||
//! || nfc(passphrase)
|
||||
//! wrap_key = Argon2id(kdf_input, kdf_salt, RECOVERY_PRODUCTION_PARAMS) -> 32 bytes
|
||||
//! ```
|
||||
//!
|
||||
//! The `b"relicario-recovery-v1\0"` prefix is **domain separation**: it
|
||||
//! guarantees that even if the user reuses their vault passphrase as their
|
||||
//! recovery passphrase, the wrap key derived here can never collide with a
|
||||
//! vault master key derived in [`crate::crypto::derive_master_key`] (which has
|
||||
//! a different input shape entirely — passphrase + image_secret, no prefix).
|
||||
//! Without this prefix, a determined attacker who somehow recovered a wrap key
|
||||
//! could try it as a master key and vice versa.
|
||||
//!
|
||||
//! Both `kdf_salt` and `wrap_nonce` are freshly randomized per call to
|
||||
//! [`generate_recovery_qr`], so two QRs printed from the same passphrase and
|
||||
//! image_secret are different bytes — the printed QR does not leak whether
|
||||
//! the user has printed others before.
|
||||
//!
|
||||
//! ## Parameter-pinning rationale
|
||||
//!
|
||||
//! The Argon2id parameters used here are NOT [`crate::crypto::KdfParams::default`].
|
||||
//! They are pinned in `RECOVERY_PRODUCTION_PARAMS` at the value
|
||||
//! `KdfParams { argon2_m: 65536, argon2_t: 3, argon2_p: 4 }` — the same values
|
||||
//! the default happens to have *today*, but deliberately re-stated rather than
|
||||
//! referenced. This is because `KdfParams::default()` may evolve as we re-tune
|
||||
//! Argon2 cost for newer hardware, and a recovery QR printed on paper has no
|
||||
//! way to negotiate parameters at decode time. Changing the pinned values here
|
||||
//! would silently invalidate every recovery QR a user has ever printed under
|
||||
//! the previous parameter set. The const lives at module scope so the
|
||||
//! "pinned, do not change once shipped" property is visible at every use site.
|
||||
|
||||
use chacha20poly1305::{XChaCha20Poly1305, Key, KeyInit, aead::Aead};
|
||||
use rand::RngCore;
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
use zeroize::Zeroizing;
|
||||
use crate::{crypto::KdfParams, error::{RelicarioError, Result}};
|
||||
|
||||
// Recovery QR payload — 109 bytes total:
|
||||
//
|
||||
// byte field length
|
||||
// ------ -------------- ------
|
||||
// 0..4 MAGIC = "RREC" 4
|
||||
// 4..5 VERSION = 0x01 1
|
||||
// 5..37 kdf_salt 32 (random per QR)
|
||||
// 37..61 wrap_nonce 24 (random per QR)
|
||||
// 61..109 ciphertext 48 (32 image_secret + 16 AEAD tag)
|
||||
// ------------------------------
|
||||
// total 109
|
||||
const MAGIC: &[u8; 4] = b"RREC";
|
||||
const VERSION: u8 = 0x01;
|
||||
const PAYLOAD_LEN: usize = 4 + 1 + 32 + 24 + 48; // 109
|
||||
|
||||
// Static assertion that the documented layout above and the PAYLOAD_LEN
|
||||
// constant cannot drift apart. If a future edit changes one without the other,
|
||||
// this fails to compile.
|
||||
const _: () = assert!(PAYLOAD_LEN == 4 + 1 + 32 + 24 + 48);
|
||||
|
||||
// Named slice ranges derived from the layout offsets above. Used by
|
||||
// `unwrap_recovery_qr_with_params` so the byte-position arithmetic at the
|
||||
// parse site is self-documenting.
|
||||
const KDF_SALT_RANGE: std::ops::Range<usize> = 5..37;
|
||||
const WRAP_NONCE_RANGE: std::ops::Range<usize> = 37..61;
|
||||
const CIPHERTEXT_RANGE: std::ops::Range<usize> = 61..109;
|
||||
|
||||
/// Pinned recovery-QR Argon2id parameters. Re-states `KdfParams::default()`'s
|
||||
/// values rather than referencing them, because a recovery QR printed under
|
||||
/// one parameter set cannot be decoded under another. **Once shipped, these
|
||||
/// values MUST NOT change** — doing so silently invalidates every previously
|
||||
/// printed QR. See the module header for full rationale.
|
||||
const RECOVERY_PRODUCTION_PARAMS: KdfParams = KdfParams {
|
||||
argon2_m: 65536,
|
||||
argon2_t: 3,
|
||||
argon2_p: 4,
|
||||
};
|
||||
|
||||
/// A sealed 109-byte recovery payload. The bytes are an opaque package — they
|
||||
/// only become useful when fed back through [`unwrap_recovery_qr`] together
|
||||
/// with the recovery passphrase that was used to produce them.
|
||||
///
|
||||
/// [`as_bytes`](Self::as_bytes) is the only accessor. The bytes are designed to
|
||||
/// travel as a single unit; the supported transport is rendering via
|
||||
/// [`recovery_qr_to_svg`] and printing the QR on paper, but a hex string
|
||||
/// (sneakernet-friendly) works equally well as long as the full 109 bytes
|
||||
/// are preserved.
|
||||
pub struct RecoveryQrPayload {
|
||||
bytes: [u8; PAYLOAD_LEN],
|
||||
}
|
||||
@@ -24,15 +118,12 @@ fn recovery_kdf_input(passphrase: &str) -> Vec<u8> {
|
||||
let prefix = b"relicario-recovery-v1\0";
|
||||
let mut input = Vec::with_capacity(prefix.len() + 8 + nfc_bytes.len());
|
||||
input.extend_from_slice(prefix);
|
||||
// length-prefix on nfc_bytes mirrors crypto::derive_master_key (audit H1)
|
||||
input.extend_from_slice(&(nfc_bytes.len() as u64).to_be_bytes());
|
||||
input.extend_from_slice(nfc_bytes);
|
||||
input
|
||||
}
|
||||
|
||||
fn production_params() -> KdfParams {
|
||||
KdfParams { argon2_m: 65536, argon2_t: 3, argon2_p: 4 }
|
||||
}
|
||||
|
||||
fn derive_wrap_key(
|
||||
passphrase: &str,
|
||||
kdf_salt: &[u8; 32],
|
||||
@@ -42,11 +133,38 @@ fn derive_wrap_key(
|
||||
crate::crypto::derive_master_key_raw(&input, kdf_salt, params)
|
||||
}
|
||||
|
||||
/// Produce a sealed [`RecoveryQrPayload`] from the recovery passphrase and the
|
||||
/// 32-byte image_secret.
|
||||
///
|
||||
/// # Inputs
|
||||
///
|
||||
/// - `passphrase`: the user's recovery passphrase (UTF-8). Independent of the
|
||||
/// vault passphrase, but the user may reuse them — the
|
||||
/// `b"relicario-recovery-v1\0"` domain-separation prefix in the KDF input
|
||||
/// guarantees the wrap key still cannot collide with a vault master key.
|
||||
/// - `image_secret`: the 32-byte secret extracted from the reference JPEG
|
||||
/// via [`crate::imgsecret::extract`].
|
||||
///
|
||||
/// # Output
|
||||
///
|
||||
/// A [`RecoveryQrPayload`] whose 109 bytes encode `MAGIC || VERSION || kdf_salt
|
||||
/// || wrap_nonce || ciphertext`. Both `kdf_salt` and `wrap_nonce` are freshly
|
||||
/// drawn from `OsRng` on every call, so two payloads generated from the same
|
||||
/// `(passphrase, image_secret)` pair are distinct bit-for-bit. The printed QR
|
||||
/// therefore does not reveal that the user has printed others before.
|
||||
///
|
||||
/// To render the payload as a printable SVG, see [`recovery_qr_to_svg`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`RelicarioError::RecoveryQr`] if the AEAD wrap fails (extremely
|
||||
/// unlikely in practice — this can only happen if the cipher implementation
|
||||
/// itself errors, not on user input).
|
||||
pub fn generate_recovery_qr(
|
||||
passphrase: &str,
|
||||
image_secret: &[u8; 32],
|
||||
) -> Result<RecoveryQrPayload> {
|
||||
generate_recovery_qr_with_params(passphrase, image_secret, &production_params())
|
||||
generate_recovery_qr_with_params(passphrase, image_secret, &RECOVERY_PRODUCTION_PARAMS)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
@@ -78,11 +196,39 @@ pub fn generate_recovery_qr_with_params(
|
||||
Ok(RecoveryQrPayload { bytes })
|
||||
}
|
||||
|
||||
/// Decode a recovery payload back into the original 32-byte image_secret.
|
||||
///
|
||||
/// # Inputs
|
||||
///
|
||||
/// - `payload_bytes`: the 109 bytes produced by [`generate_recovery_qr`] (after
|
||||
/// the QR has been scanned, or the hex transcribed and decoded).
|
||||
/// - `passphrase`: the recovery passphrase that was used at generate time.
|
||||
///
|
||||
/// # Output
|
||||
///
|
||||
/// The recovered image_secret as `Zeroizing<[u8; 32]>` — the wrapper ensures
|
||||
/// the secret is wiped from memory when the binding goes out of scope, so a
|
||||
/// caller that immediately feeds it into [`crate::crypto::derive_master_key`]
|
||||
/// and then drops it never leaves a copy in process memory longer than
|
||||
/// strictly necessary.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - [`RelicarioError::RecoveryQr`] for **format** problems: wrong length,
|
||||
/// bad magic, unsupported version byte. These come from inspecting the
|
||||
/// bytes themselves, before any cryptographic work, so they leak nothing
|
||||
/// about whether the passphrase is right.
|
||||
/// - [`RelicarioError::Decrypt`] for **AEAD** failure — wrong passphrase
|
||||
/// (wrong wrap key) **or** a payload tampered after the fact. The two
|
||||
/// cases are deliberately not distinguished, mirroring the same
|
||||
/// non-distinguishing rejection as [`crate::crypto::decrypt`] (audit M4):
|
||||
/// a Poly1305 tag failure cannot, in principle, leak which bytes were
|
||||
/// wrong, and the API surface preserves that property.
|
||||
pub fn unwrap_recovery_qr(
|
||||
payload_bytes: &[u8],
|
||||
passphrase: &str,
|
||||
) -> Result<Zeroizing<[u8; 32]>> {
|
||||
unwrap_recovery_qr_with_params(payload_bytes, passphrase, &production_params())
|
||||
unwrap_recovery_qr_with_params(payload_bytes, passphrase, &RECOVERY_PRODUCTION_PARAMS)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
@@ -104,9 +250,9 @@ pub fn unwrap_recovery_qr_with_params(
|
||||
format!("unsupported version 0x{:02x}", payload_bytes[4])
|
||||
));
|
||||
}
|
||||
let kdf_salt: &[u8; 32] = payload_bytes[5..37].try_into().expect("slice length validated above");
|
||||
let wrap_nonce = &payload_bytes[37..61];
|
||||
let ciphertext = &payload_bytes[61..109];
|
||||
let kdf_salt: &[u8; 32] = payload_bytes[KDF_SALT_RANGE].try_into().expect("slice length validated above");
|
||||
let wrap_nonce = &payload_bytes[WRAP_NONCE_RANGE];
|
||||
let ciphertext = &payload_bytes[CIPHERTEXT_RANGE];
|
||||
|
||||
let wrap_key = derive_wrap_key(passphrase, kdf_salt, params)?;
|
||||
let cipher = XChaCha20Poly1305::new(Key::from_slice(wrap_key.as_ref()));
|
||||
@@ -119,6 +265,15 @@ pub fn unwrap_recovery_qr_with_params(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Render a [`RecoveryQrPayload`] as a printable QR-code SVG string.
|
||||
///
|
||||
/// The QR is encoded at **version 40** (the largest standard symbol, 177×177
|
||||
/// modules) at **error-correction level M** (~15% recoverable), with a
|
||||
/// minimum rendered dimension of **140×140** SVG units. The 109-byte payload
|
||||
/// fits comfortably inside v40 at level M — there is significant
|
||||
/// error-correction headroom left over, which is the point: the QR is
|
||||
/// expected to live on paper (where smudges, folds, and fading are normal)
|
||||
/// and must still scan years later.
|
||||
pub fn recovery_qr_to_svg(payload: &RecoveryQrPayload) -> String {
|
||||
use qrcode::{QrCode, EcLevel};
|
||||
let code = QrCode::with_error_correction_level(payload.bytes.as_ref(), EcLevel::M)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "relicario-wasm"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
description = "WASM bindings for relicario password manager"
|
||||
|
||||
|
||||
@@ -12,7 +12,13 @@ use zeroize::Zeroizing;
|
||||
|
||||
use relicario_core::{derive_master_key, imgsecret, KdfParams};
|
||||
|
||||
/// Handle type returned from `unlock`. Backed by a `u32`; opaque to JS.
|
||||
/// Handle returned from `unlock`. Backed by a `u32`; opaque to JS.
|
||||
///
|
||||
/// Dropping the handle (or invoking `.free()` from JS) removes the entry from
|
||||
/// the session registry, zeroizing the wrapped master key and image_secret.
|
||||
/// `lock(handle)` remains available as the explicit early-cleanup path; the
|
||||
/// `Drop` impl is the safety net that catches code paths which forget to call
|
||||
/// `lock` before letting the handle go out of scope.
|
||||
#[wasm_bindgen]
|
||||
pub struct SessionHandle(u32);
|
||||
|
||||
@@ -22,6 +28,23 @@ impl SessionHandle {
|
||||
pub fn value(&self) -> u32 { self.0 }
|
||||
}
|
||||
|
||||
impl Drop for SessionHandle {
|
||||
fn drop(&mut self) { let _ = session::remove(self.0); }
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn __test_make_handle() -> SessionHandle {
|
||||
SessionHandle(session::insert(
|
||||
Zeroizing::new([0x77u8; 32]),
|
||||
Zeroizing::new([0u8; 32]),
|
||||
))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn __test_session_exists(handle: u32) -> bool {
|
||||
session::with(handle, |_| ()).is_some()
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn unlock(
|
||||
passphrase: &str,
|
||||
@@ -533,6 +556,19 @@ mod session_tests {
|
||||
assert!(!session::remove(h)); // second remove false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_session_handle_clears_registry_entry() {
|
||||
session::clear();
|
||||
let handle = SessionHandle(session::insert(
|
||||
Zeroizing::new([0x33u8; 32]),
|
||||
Zeroizing::new([0u8; 32]),
|
||||
));
|
||||
let id = handle.value();
|
||||
assert!(session::with(id, |_| ()).is_some());
|
||||
drop(handle);
|
||||
assert!(session::with(id, |_| ()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_yields_key_only_while_session_lives() {
|
||||
session::clear();
|
||||
|
||||
@@ -46,6 +46,9 @@ where
|
||||
SESSIONS.with(|s| s.borrow().get(&handle).map(|d| f(&d.image_secret)))
|
||||
}
|
||||
|
||||
/// Remove a session entry. Called by both `lock(handle)` (the explicit
|
||||
/// path) and `impl Drop for SessionHandle` (the safety net). Returns
|
||||
/// `true` if an entry was removed, `false` if the handle was already gone.
|
||||
pub fn remove(handle: u32) -> bool {
|
||||
SESSIONS.with(|s| s.borrow_mut().remove(&handle).is_some())
|
||||
}
|
||||
|
||||
16
crates/relicario-wasm/tests/session_drop.rs
Normal file
16
crates/relicario-wasm/tests/session_drop.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
//! Belt-and-suspenders companion to the native `dropping_session_handle_clears_registry_entry`
|
||||
//! test in `lib.rs`. This file exists for `wasm-pack test --node` symmetry; the
|
||||
//! native test in the same crate is what gates CI.
|
||||
|
||||
use wasm_bindgen_test::wasm_bindgen_test;
|
||||
|
||||
use relicario_wasm::{__test_make_handle, __test_session_exists};
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn dropping_session_handle_clears_registry_entry() {
|
||||
let handle = __test_make_handle();
|
||||
let id = handle.value();
|
||||
assert!(__test_session_exists(id));
|
||||
drop(handle);
|
||||
assert!(!__test_session_exists(id));
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
# Dev A Kickoff Prompt — arch-followup Plan A
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior developer** owning Plan A for the arch-followup "architecture-review followups" release train.
|
||||
|
||||
Plan A is the **security & docs polish PR** — the small one that ships first, in under a day, with no dependencies on Plans B or C. It closes the only defense-in-depth crypto gap the architecture review flagged (`SessionHandle` has no `impl Drop`, so wasm-bindgen's `.free()` is a cleanup no-op while the master key sits in WASM linear memory), removes the JS-side error swallow that was masking that fact, brings `recovery_qr.rs` documentation up to the density of `crypto.rs` / `imgsecret.rs` / `backup.rs` / `tar_safe.rs`, and finishes the relay-launcher dev-c expansion. Four phases, all S-effort.
|
||||
|
||||
A PM in another terminal coordinates you with Dev-B (CLI restructure) and Dev-C (extension restructure). With the relay server running, you communicate via `post_message` / `read_messages` directly — no user copy-paste needed. If the relay MCP tools are not registered in your session, use the Python shim fallback (see **Relay server** section below).
|
||||
|
||||
## Setup (do this first)
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario
|
||||
git fetch
|
||||
git checkout main
|
||||
git pull
|
||||
git worktree add ../relicario-plan-a -b feature/2026-05-04-a-security-polish
|
||||
cd ../relicario-plan-a
|
||||
pwd # should print /home/alee/Sources/relicario-plan-a (or similar absolute path)
|
||||
```
|
||||
|
||||
**ALL subsequent work happens in `/home/alee/Sources/relicario-plan-a`**. Force-cd subagents into this directory — the project's `CLAUDE.md` memory rule explicitly requires that subagent prompts MUST start with `cd /home/alee/Sources/relicario-plan-a` so subagents don't accidentally commit to main. This is non-negotiable.
|
||||
|
||||
Today: 2026-05-04. Project rules in `CLAUDE.md` apply.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-a"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-a"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-a")`. After emitting any status/question block: `post_message(from="dev-a", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-a","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-a"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — synthesis (your scope is **P1.1, P1.7, P1.8 + the partner JS-side fix at `service-worker/session.ts:26` + the `start.sh` launcher follow-up only**)
|
||||
3. `docs/superpowers/specs/2026-05-04-security-polish-design.md` — your plan, execute phase by phase
|
||||
|
||||
You do NOT need to read Plan B or Plan C in detail. Skim Plan B's "WASM/extension parity seam" paragraph (Phase 8) and Plan C's "Risks → `.free()` callsite policy" paragraph only if a coordination question arises — they're the points where Plans B/C reference your work.
|
||||
|
||||
## Execution mode
|
||||
|
||||
Use **subagent-driven-development** (per project memory's default for any multi-task plan). Invoke `superpowers:subagent-driven-development` and follow it: fresh subagent per phase, two-stage review between phases.
|
||||
|
||||
**Every subagent prompt MUST start with**:
|
||||
```
|
||||
cd /home/alee/Sources/relicario-plan-a
|
||||
```
|
||||
…before any other instruction. This is non-negotiable per project memory.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:** Phase 1 (Rust `impl Drop for SessionHandle` + wasm-bindgen-test + native fallback test), Phase 2 (JS `.free()` audit + remove the `try { current.free() }` swallow at `extension/src/service-worker/session.ts:26`), Phase 3 (`recovery_qr.rs` documentation pass — module-level `//!`, ASCII layout diagram, doc-comments on the four public items, `production_params` rationale or `const`), Phase 4 (`tools/relay/start.sh` dev-c expansion + verification that `queue.test.ts:54` is already fixed).
|
||||
|
||||
**Out of scope:** anything in Plan B (CLI restructure — `cli/main.rs` split, `git_run` helper, parser migration to core, etc.) or Plan C (extension restructure — `setup.ts` SW migration, `vault.ts` split, `StateHost` typing, SW router dedup). The other P2 WASM cleanups (double-lookup, Vec<u8> clone, naming inconsistency, concurrency primitive split). DEV-C's other relay P2s (queue TTL, `call.py`/`call.ts` tracking decision). The 8 "Open architectural decisions". If you trip over an out-of-scope issue or a new bug while doing your work, file it via a `## QUESTION TO PM` block and keep moving.
|
||||
|
||||
**Hard rules:**
|
||||
- This is a defense-in-depth crypto fix. Do NOT skip Phase 1's `wasm-bindgen-test` AND the native `#[test]` fallback — both are required by the plan's Done criteria.
|
||||
- Do NOT remove the `try { current.free() }` swallow (Phase 2) until Phase 1's `impl Drop` has landed in the same branch — Phase 2 explicitly depends on Phase 1.
|
||||
- Phase 3 must produce documentation density that visibly matches `crypto.rs` / `imgsecret.rs` / `backup.rs` / `tar_safe.rs`. If your doc-block is shorter than `crypto.rs`'s top comment, it's not done.
|
||||
- Phase 4: confirm `queue.test.ts:54` is already fixed in commit `061facd` (read the file; assert the line is `assert.ok(isRole("dev-c"));`). If it isn't, escalate via `## QUESTION TO PM` — the plan was drafted assuming it was fixed.
|
||||
- The plan's Done criteria includes recording the `grep -rn "\.free\b" extension/src/` output in the PR description as the audit deliverable. Do NOT merge the PR without that grep recorded.
|
||||
- Do not merge your branch to main. The PM owns merges.
|
||||
- Do not push `--force` or run `git reset --hard`. Per `CLAUDE.md`: ask first.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of multiple terminals. The relay routes messages between them.
|
||||
|
||||
**At every phase boundary** (complete, blocked, or question): call `read_messages(for="dev-a")` first, then post your update via `post_message(from="dev-a", to="pm", kind="status"|"question", body="...")` and also print it here. Use this format:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-A
|
||||
Time: <iso8601 like 2026-05-04T14:30:00-07:00>
|
||||
Branch: feature/2026-05-04-a-security-polish
|
||||
Task: <phase number / short name>
|
||||
Status: STARTED | IN-PROGRESS | DONE | BLOCKED | REVIEW-READY
|
||||
Last commit: <short sha + first line of message>
|
||||
Tests: <green | red (which failed) | N/A>
|
||||
Notes: <anything PM needs to know — keep to 3 sentences max>
|
||||
```
|
||||
|
||||
**When you need PM input mid-task**: post via `post_message(kind="question")` with format:
|
||||
|
||||
```
|
||||
## QUESTION TO PM — DEV-A
|
||||
Time: <iso8601>
|
||||
Context: <what phase, what decision point>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no (does work stop without an answer?)
|
||||
```
|
||||
|
||||
**You'll receive**: `## DIRECTIVE TO DEV-A` blocks from the PM via relay (or relayed by user if relay is down). Acknowledge and act.
|
||||
|
||||
## Authority within the plan
|
||||
|
||||
You don't need PM permission to:
|
||||
- Execute phase-to-phase per the plan
|
||||
- Make implementation decisions consistent with the plan and synthesis
|
||||
- Choose between the plan's optional micro-cleanups in Phase 3 (the named-constant slice ranges, the `recovery_kdf_input` length-prefix comment) — proceed if they make the code clearer
|
||||
- Decide whether to add `wasm.lock(handle)` before `.free()` in `clearCurrent()` (Phase 2 leaves this to your judgment; the plan recommends just `free()` post-Phase-1)
|
||||
- Write tests, refactor your own code, fix bugs you introduce
|
||||
- Push commits to your feature branch
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- You discover the Rust toolchain is older than 1.79 (Phase 3 falls back to a runtime `#[test]` for the layout assertion — confirm with PM before switching)
|
||||
- You discover the `.free()` audit grep returns more than one match (the plan was drafted expecting one; investigate and report)
|
||||
- You discover `queue.test.ts:54` is NOT actually fixed (Phase 4 falls back to a real code change)
|
||||
- You discover the `start.sh` launcher requires deeper changes than the four locations the plan describes
|
||||
- A test you can't make green after honest debugging (don't fudge — debug)
|
||||
- A discovered bug not in your plan
|
||||
- Anything destructive (per project rules)
|
||||
- Before opening the PR for review
|
||||
|
||||
## Final steps before REVIEW-READY
|
||||
|
||||
Run the project's full validation:
|
||||
|
||||
```bash
|
||||
# From the worktree root (/home/alee/Sources/relicario-plan-a):
|
||||
cargo test -p relicario-core
|
||||
cargo test -p relicario-wasm
|
||||
cd extension && npm test && cd ..
|
||||
|
||||
# Audit deliverable (record output in PR description):
|
||||
grep -rn "\.free\b" extension/src/
|
||||
|
||||
# Optional but recommended for the wasm-bindgen-test (requires wasm-pack):
|
||||
# wasm-pack test --node crates/relicario-wasm
|
||||
|
||||
# Manual launcher checks (Phase 4):
|
||||
bash tools/relay/start.sh --manual # confirm "Open 4 new terminals" + Dev-C prompt path
|
||||
# bash tools/relay/start.sh --kitty # if on a kitty terminal: confirm 4 tabs open
|
||||
```
|
||||
|
||||
Then push and open the PR:
|
||||
|
||||
```bash
|
||||
git push -u origin feature/2026-05-04-a-security-polish
|
||||
gh pr create --base main --head feature/2026-05-04-a-security-polish --title "docs+fix(arch-followup): Drop impl + recovery_qr docs + relay launcher (Plan A)" --body "$(cat <<'EOF'
|
||||
## Summary
|
||||
|
||||
Architecture-review followup Plan A (security & docs polish). Source: `docs/superpowers/specs/2026-05-04-security-polish-design.md`.
|
||||
|
||||
- **P1.1** — `SessionHandle` now has `impl Drop` so wasm-bindgen's `.free()` actually clears the master key from WASM linear memory. Native + wasm-bindgen tests cover construct → drop → registry-empty.
|
||||
- **JS partner fix** — removed the `try { current.free() }` swallow at `extension/src/service-worker/session.ts:26`. Crypto-state-transition errors now propagate.
|
||||
- **P1.7** — `crates/relicario-core/src/recovery_qr.rs` documentation pass: module-level `//!`, ASCII layout diagram, doc-comments on the four public items, `production_params` parameter-pinning rationale.
|
||||
- **P1.8** — confirmed `tools/relay/queue.test.ts:54` already matches the new role union (committed in `061facd`); `tools/relay/start.sh` extended to discover and launch a fourth Dev-C window in `--manual`, `--tmux`, `--kitty` modes.
|
||||
|
||||
## Audit deliverables
|
||||
|
||||
`.free()` callsites under `extension/src/` (recorded for future regression baseline):
|
||||
|
||||
```
|
||||
<paste the grep output here>
|
||||
```
|
||||
|
||||
## Test plan
|
||||
|
||||
- [ ] `cargo test -p relicario-core` passes (recovery_qr tests still green; layout static assertion compiles)
|
||||
- [ ] `cargo test -p relicario-wasm` passes including new `Drop` test
|
||||
- [ ] `cd extension && npm test` passes including new `clearCurrent()` test
|
||||
- [ ] `grep -rn "\.free\b" extension/src/` returns exactly one match (the SW callsite)
|
||||
- [ ] `bash tools/relay/start.sh --manual` shows "Open 4 new terminals" and lists the Dev-C prompt path
|
||||
|
||||
## Done criteria
|
||||
|
||||
Per `docs/superpowers/specs/2026-05-04-security-polish-design.md` Done criteria — every checkbox.
|
||||
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Emit a `## STATUS UPDATE` with `Status: REVIEW-READY` and the PR URL (post via `post_message`).
|
||||
|
||||
## First action
|
||||
|
||||
After reading: emit a `## STATUS UPDATE` confirming setup complete (worktree created at `/home/alee/Sources/relicario-plan-a`, plan absorbed, on `feature/2026-05-04-a-security-polish`). Post it via `post_message(from="dev-a", to="pm", kind="status", body="...")`. Then start Phase 1 of your plan (Rust `impl Drop for SessionHandle` + tests).
|
||||
@@ -0,0 +1,207 @@
|
||||
# Dev B Kickoff Prompt — arch-followup Plan B
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior developer** owning Plan B for the arch-followup "architecture-review followups" release train.
|
||||
|
||||
Plan B is the **CLI restructure** — the "single biggest readability lift" per the synthesis. M-L effort, multi-day. It splits `crates/relicario-cli/src/main.rs` (2641 LOC) into a `commands/` folder + `prompt.rs` + `parse.rs`, then layers on the duplicated git-error UX consolidation, manifest-after-mutation cache discipline, `ParamsFile` dedup, batched purge, and the migration of pure parsers (and a third copy of base32) into `relicario-core` with WASM re-exports. Eight phases.
|
||||
|
||||
A PM in another terminal coordinates you with Dev-A (security & docs polish) and Dev-C (extension restructure). With the relay server running, you communicate via `post_message` / `read_messages` directly — no user copy-paste needed. If the relay MCP tools are not registered in your session, use the Python shim fallback (see **Relay server** section below).
|
||||
|
||||
## Setup (do this first)
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario
|
||||
git fetch
|
||||
git checkout main
|
||||
git pull
|
||||
git worktree add ../relicario-plan-b -b feature/2026-05-04-b-cli-restructure
|
||||
cd ../relicario-plan-b
|
||||
pwd # should print /home/alee/Sources/relicario-plan-b (or similar absolute path)
|
||||
```
|
||||
|
||||
**ALL subsequent work happens in `/home/alee/Sources/relicario-plan-b`**. Force-cd subagents into this directory — the project's `CLAUDE.md` memory rule explicitly requires that subagent prompts MUST start with `cd /home/alee/Sources/relicario-plan-b` so subagents don't accidentally commit to main. This is non-negotiable.
|
||||
|
||||
Today: 2026-05-04. Project rules in `CLAUDE.md` apply.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-b"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-b"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-b")`. After emitting any status/question block: `post_message(from="dev-b", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-b","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-b"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules (Spanish flourish in chat replies only, capitalization, autonomy defaults, CLI/extension parity philosophy)
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — synthesis (your scope is **P1.2, P1.3, P1.10 + the in-scope CLI P2s only**)
|
||||
3. `docs/superpowers/specs/2026-05-04-cli-restructure-design.md` — your plan, execute phase by phase
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — DEV-B's full notes (your primary source for line-level context — the synthesis abbreviates)
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — read **only** the "Boundary notes for DEV-B" section near the end (cross-boundary contracts you must respect when designing the WASM exports for Phase 8)
|
||||
|
||||
You do NOT need to read Plan A or Plan C in detail. If a coordination question arises, skim Plan C's "Risks → WASM boundary coordination" paragraph (it cites your Phase 8 explicitly).
|
||||
|
||||
## Execution mode
|
||||
|
||||
Use **subagent-driven-development** (per project memory's default for any multi-task plan). Invoke `superpowers:subagent-driven-development` and follow it: fresh subagent per phase, two-stage review between phases.
|
||||
|
||||
**Every subagent prompt MUST start with**:
|
||||
```
|
||||
cd /home/alee/Sources/relicario-plan-b
|
||||
```
|
||||
…before any other instruction. This is non-negotiable per project memory.
|
||||
|
||||
**Sequencing matters.** Phase 1 (the mechanical `main.rs` split) is the precondition for every other phase — phases 2-6 touch files that don't exist yet until phase 1 lands. Do NOT start phase 2 until phase 1's `cargo test --workspace` is green and a checkpoint commit is in place.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- Phase 1 — Mechanical split of `main.rs` into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr,init,generate,rate}.rs` + `prompt.rs` + `parse.rs`
|
||||
- Phase 2 — `helpers::git_run` + sweep of the 16 `bail!("git X failed")` sites
|
||||
- Phase 3 — `prompt_or_flag<T>` and `build_*_item` compression
|
||||
- Phase 4 — `Vault::after_manifest_change` + sweep of the 7 `refresh_groups_cache` sites
|
||||
- Phase 5 — Single canonical `ParamsFile` (one definition shared between init writer and unlock reader)
|
||||
- Phase 6 — Batched purge in `cmd_purge` and `cmd_trash_empty` (3 git invocations for an N-item purge instead of 3N)
|
||||
- Phase 7 — Migrate `parse_month_year` / `base32_decode_lenient` / `guess_mime` to `relicario-core` + `pub(crate) mod base32` (closes DEV-A's three-base32-impls finding)
|
||||
- Phase 8 — WASM exports for the migrated parsers + `extension/src/wasm.d.ts` mirror
|
||||
|
||||
**Out of scope:** anything in Plan A (security/docs polish — Drop impl, recovery_qr docs, relay launcher) or Plan C (extension restructure — setup.ts SW migration, vault.ts split, StateHost typing, SW router dedup). The CLI P3 nits (let _ = entry pattern, Lock subcommand visibility, Display for ItemType, helpers::relicario_dir adoption sweep, gitea Client per-call construction, edit_and_history.rs scripted prompts, dead test variable, three-test-env-var macro, cmd_recovery_qr_unwrap empty input check, Task 12 cleanup). Server findings (P2/P3 in DEV-B's relicario-server section). WASM findings beyond the parser exports needed for P1.10 (DEV-B's WASM P2 list — double-lookup, Vec<u8> clone, naming, concurrency primitive split). The 8 "Open architectural decisions". The WASM JS-naming snake_case → camelCase decision (deferred to a separate plan). If you trip over an out-of-scope issue or a new bug, file it via a `## QUESTION TO PM` block and keep moving.
|
||||
|
||||
**Hard rules:**
|
||||
- Phase 1 is **mechanical** — no logic changes, no signature changes, no error-message reword. Run `cargo check -p relicario-cli` between every file extraction; existing CLI integration tests at `crates/relicario-cli/tests/*` must stay green throughout. They are the regression budget.
|
||||
- Phase 2's `git_run` switches from `.status()` (inherited stderr to TTY) to `.output()` (captured); the captured stderr MUST be printed to the user's stderr unmodified on failure. Do not silently swallow.
|
||||
- Phase 5's `ParamsFile` migration is on-disk-format-sensitive. Field names and types MUST match the existing `params.json` shape exactly; the round-trip test against a fixture string is required by the plan's Done criteria.
|
||||
- Phase 7 — `MonthYear::new` currently returns `Result<_, &'static str>` (DEV-A's P3 nit). The plan recommends re-wrapping the error in `MonthYear::parse` rather than migrating `new` to `RelicarioError`. If you'd rather migrate `new` for consistency, escalate to PM first — this is a cross-plan coordination concern.
|
||||
- Phase 8 keeps **snake_case** JS names (consistent with every existing export). Do not introduce camelCase for the three new exports. The snake_case → camelCase decision is deferred to a separate plan.
|
||||
- Phase 8 updates `extension/src/wasm.d.ts` and the new `#[wasm_bindgen]` exports in the same commit. Per DEV-C's boundary note, `wasm.d.ts` is hand-maintained — do not let the two surfaces drift even temporarily.
|
||||
- The Steam alphabet at `crates/relicario-core/src/item_types/totp.rs:13` is **intentionally non-RFC-4648** and must NOT move into the new `pub(crate) mod base32`. Add a neighbour comment per the plan.
|
||||
- Do not merge your branch to main. The PM owns merges.
|
||||
- Do not push `--force` or run `git reset --hard`. Per `CLAUDE.md`: ask first.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of multiple terminals. The relay routes messages between them.
|
||||
|
||||
**At every phase boundary** (complete, blocked, or question): call `read_messages(for="dev-b")` first, then post your update via `post_message(from="dev-b", to="pm", kind="status"|"question", body="...")` and also print it here. Use this format:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: <iso8601 like 2026-05-04T14:30:00-07:00>
|
||||
Branch: feature/2026-05-04-b-cli-restructure
|
||||
Task: <phase number / short name>
|
||||
Status: STARTED | IN-PROGRESS | DONE | BLOCKED | REVIEW-READY
|
||||
Last commit: <short sha + first line of message>
|
||||
Tests: <green | red (which failed) | N/A>
|
||||
Notes: <anything PM needs to know — keep to 3 sentences max>
|
||||
```
|
||||
|
||||
**When you need PM input mid-task**: post via `post_message(kind="question")` with format:
|
||||
|
||||
```
|
||||
## QUESTION TO PM — DEV-B
|
||||
Time: <iso8601>
|
||||
Context: <what phase, what decision point>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no (does work stop without an answer?)
|
||||
```
|
||||
|
||||
**You'll receive**: `## DIRECTIVE TO DEV-B` blocks from the PM via relay (or relayed by user if relay is down). Acknowledge and act.
|
||||
|
||||
## Cross-plan coordination
|
||||
|
||||
- **Plan C consumes your Phase 8 WASM exports** (`parse_month_year` / `base32_decode_lenient` / `guess_mime`) — but only as a deferred follow-up, NOT in Plan C's current execution. You ship the seam; Plan C does not wire the SW handlers in this train. Sequence Phase 8 to land before Plan C touches `wasm.d.ts` if both must touch it.
|
||||
- **`extension/src/wasm.d.ts` shared touchpoint with Plan C.** Plan C says it likely does NOT need to touch this file (its `create_vault`/`attach_vault` handlers reuse already-declared WASM entries). If Plan C does end up touching it, sequence Plan B's edits first and ask Plan C to rebase.
|
||||
- **Plan A's `impl Drop for SessionHandle`** is independent of you. Your `git_run` and parser-migration work doesn't touch the WASM crate's session module. No conflict.
|
||||
|
||||
## Authority within the plan
|
||||
|
||||
You don't need PM permission to:
|
||||
- Execute phase-to-phase per the plan
|
||||
- Make implementation decisions consistent with the plan and synthesis
|
||||
- Add new tests, refactor your own code, fix bugs you introduce
|
||||
- Choose between optional approaches the plan calls out (e.g. whether `Vault::after_manifest_change` calls `save_manifest` internally vs renaming the existing method to `save_manifest_raw`)
|
||||
- Push commits to your feature branch
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- You discover the grep at the top of Phase 7 returns non-CLI consumers of `parse_month_year` / `base32_decode_lenient` / `guess_mime` / `base32_encode` / `decode_base32_totp` (the plan was drafted assuming zero non-CLI consumers; investigate)
|
||||
- A `cargo test --workspace` failure you can't reproduce locally
|
||||
- You want to deviate on the `MonthYear::new` consistency point (see Hard Rules)
|
||||
- You discover the `ParamsFile` round-trip is not field-compatible with the current on-disk format (rename, type change, etc.)
|
||||
- A test you can't make green after honest debugging (don't fudge — debug)
|
||||
- A discovered bug not in your plan
|
||||
- Anything destructive (per project rules)
|
||||
- Before opening the PR for review
|
||||
|
||||
## Final steps before REVIEW-READY
|
||||
|
||||
Run the project's full validation:
|
||||
|
||||
```bash
|
||||
# From the worktree root (/home/alee/Sources/relicario-plan-b):
|
||||
cargo test --workspace
|
||||
cargo clippy --workspace --all-targets --no-deps
|
||||
cargo build -p relicario-wasm --target wasm32-unknown-unknown
|
||||
|
||||
# Done-criteria sanity greps (all should return zero matches):
|
||||
grep -n 'bail!("git ' crates/relicario-cli/src/
|
||||
grep -n 'refresh_groups_cache' crates/relicario-cli/src/ | grep -v 'session\.rs'
|
||||
# These should each return one match:
|
||||
grep -n 'struct ParamsFile' crates/relicario-cli/src/
|
||||
|
||||
# CLI smoke (post-split, end-to-end):
|
||||
cargo run -p relicario-cli -- --help
|
||||
```
|
||||
|
||||
Then push and open the PR:
|
||||
|
||||
```bash
|
||||
git push -u origin feature/2026-05-04-b-cli-restructure
|
||||
gh pr create --base main --head feature/2026-05-04-b-cli-restructure --title "refactor(cli): split main.rs + git_run helper + parsers→core (Plan B)" --body "$(cat <<'EOF'
|
||||
## Summary
|
||||
|
||||
Architecture-review followup Plan B (CLI restructure — single biggest readability lift). Source: `docs/superpowers/specs/2026-05-04-cli-restructure-design.md`.
|
||||
|
||||
- **P1.2** — `cli/main.rs` split from 2641 LOC into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr,init,generate,rate}.rs` + `prompt.rs` + `parse.rs`. `main.rs` retains clap + dispatch only (~470 lines).
|
||||
- **P1.3** — `helpers::git_run(repo, args, context)` captures stderr; 16 duplicated bail sites collapsed.
|
||||
- **P1.10** — `parse_month_year` / `base32_decode_lenient` / `guess_mime` migrated to `relicario-core` (`MonthYear::parse`, `pub(crate) mod base32::{encode_rfc4648,decode_rfc4648_lenient}`, `mime::guess_for_extension`); also closes DEV-A's three-base32-impls finding by extracting the shared module. WASM exports added; `extension/src/wasm.d.ts` mirrored.
|
||||
- **CLI P2 cluster** — `prompt_or_flag<T>` compression of `build_*_item`; `Vault::after_manifest_change` centralizes the `refresh_groups_cache` discipline (7 sites collapsed); single canonical `ParamsFile` shared between init writer and unlock reader; batched purge — a 50-item `trash empty` is now 3 git invocations instead of 150.
|
||||
|
||||
## Test plan
|
||||
|
||||
- [ ] `cargo test --workspace` passes
|
||||
- [ ] `cargo clippy --workspace` silent
|
||||
- [ ] `cargo build -p relicario-wasm --target wasm32-unknown-unknown` clean
|
||||
- [ ] `grep -n 'bail!("git ' crates/relicario-cli/src/` returns zero matches
|
||||
- [ ] `grep -n 'refresh_groups_cache' crates/relicario-cli/src/` returns zero matches outside `session.rs`
|
||||
- [ ] `grep -n 'struct ParamsFile' crates/relicario-cli/src/` returns one match
|
||||
- [ ] New test asserts a multi-item `trash empty` produces exactly one new git commit
|
||||
- [ ] All existing CLI integration tests at `crates/relicario-cli/tests/*` still pass without modification
|
||||
|
||||
## Done criteria
|
||||
|
||||
Per `docs/superpowers/specs/2026-05-04-cli-restructure-design.md` Done criteria — every checkbox.
|
||||
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Emit a `## STATUS UPDATE` with `Status: REVIEW-READY` and the PR URL (post via `post_message`).
|
||||
|
||||
## First action
|
||||
|
||||
After reading: emit a `## STATUS UPDATE` confirming setup complete (worktree created at `/home/alee/Sources/relicario-plan-b`, plan absorbed, on `feature/2026-05-04-b-cli-restructure`). Post it via `post_message(from="dev-b", to="pm", kind="status", body="...")`. Then start Phase 1 of your plan (mechanical split of `cli/main.rs`). Remember: phase 1 is mechanical — `cargo check` between every file extraction.
|
||||
@@ -0,0 +1,218 @@
|
||||
# Dev C Kickoff Prompt — arch-followup Plan C
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior developer** owning Plan C for the arch-followup "architecture-review followups" release train.
|
||||
|
||||
Plan C is the **extension restructure** — the largest of the three (multi-day to multi-week). It eliminates the two steepest learning cliffs in the extension. After this plan ships, `setup.ts` no longer imports `relicario-wasm` directly (it isn't the pattern; it was the exception); `vault.ts` shrinks from 1027 LOC to ~200 of routing + state; `shared/state.ts` becomes type-checked end-to-end; the duplicated SW router helpers consolidate into one home each; and the extension closes its last CLI-parity gap (`relicario status` → vault-sidebar status indicator). Six phases.
|
||||
|
||||
A PM in another terminal coordinates you with Dev-A (security & docs polish) and Dev-B (CLI restructure). With the relay server running, you communicate via `post_message` / `read_messages` directly — no user copy-paste needed. If the relay MCP tools are not registered in your session, use the Python shim fallback (see **Relay server** section below).
|
||||
|
||||
## Setup (do this first)
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario
|
||||
git fetch
|
||||
git checkout main
|
||||
git pull
|
||||
git worktree add ../relicario-plan-c -b feature/2026-05-04-c-extension-restructure
|
||||
cd ../relicario-plan-c
|
||||
pwd # should print /home/alee/Sources/relicario-plan-c (or similar absolute path)
|
||||
```
|
||||
|
||||
**ALL subsequent work happens in `/home/alee/Sources/relicario-plan-c`**. Force-cd subagents into this directory — the project's `CLAUDE.md` memory rule explicitly requires that subagent prompts MUST start with `cd /home/alee/Sources/relicario-plan-c` so subagents don't accidentally commit to main. This is non-negotiable.
|
||||
|
||||
Today: 2026-05-04. Project rules in `CLAUDE.md` apply.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-c"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-c"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-c")`. After emitting any status/question block: `post_message(from="dev-c", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-c","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-c"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules (Spanish flourish in chat replies only, capitalization, autonomy defaults, CLI/extension parity philosophy, security defense-in-depth)
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — synthesis (your scope is **P1.4, P1.5, P1.6, P1.9 + the in-scope extension P2s + the `relicario status` parity gap only**)
|
||||
3. `docs/superpowers/specs/2026-05-04-extension-restructure-design.md` — your plan, execute phase by phase
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — DEV-C's full notes (your primary source — the synthesis abbreviates)
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — read **only** the "Boundary notes for DEV-C" section near the end (14 numbered contracts the JS side must respect when interacting with WASM; several inform your scope)
|
||||
|
||||
You do NOT need to read Plan A or Plan B in detail. Skim Plan A's Phase 2 (the `service-worker/session.ts:26` swallow removal) and Plan B's Phase 8 (WASM parser exports) only if a coordination question arises.
|
||||
|
||||
## Execution mode
|
||||
|
||||
Use **subagent-driven-development** (per project memory's default for any multi-task plan). Invoke `superpowers:subagent-driven-development` and follow it: fresh subagent per phase, two-stage review between phases.
|
||||
|
||||
**Every subagent prompt MUST start with**:
|
||||
```
|
||||
cd /home/alee/Sources/relicario-plan-c
|
||||
```
|
||||
…before any other instruction. This is non-negotiable per project memory.
|
||||
|
||||
**Sequencing matters.** Phase 1 (typed `StateHost`) is the precondition for phases 3 and 4. Phase 2 (SW storage extraction) is independent and can ship in parallel. Phases 3 and 4 both depend on phase 1. Phase 5 (P2 cluster) and phase 6 (`get_vault_status`) are independent of 3 and 4 — they can run in parallel.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- Phase 1 — Typed `StateHost` interface in `extension/src/shared/state.ts` (no `any` in public surface) + generic `getState`/`setState` over `keyof PopupState` + double-registration guard + `__resetHostForTests` helper. Includes migration of `View` and `PopupState` from `extension/src/popup/popup.ts` to `extension/src/shared/types.ts` (or a new `shared/popup-state.ts`) to avoid a `popup → shared → popup` circular import.
|
||||
- Phase 2 — Extract `extension/src/service-worker/storage.ts` (`loadDeviceSettings`, `loadBlacklist`, `saveBlacklist` from both router files) + move `itemToManifestEntry` to `extension/src/service-worker/vault.ts`.
|
||||
- Phase 3 — Setup wizard SW migration: add `create_vault` and `attach_vault` SW messages; rewrite `setup.ts` as UI-only that posts those messages; convert the 6-step procedural wizard to a step-registry pattern; add `clearWizardState()` on `beforeunload` + step-0 reset.
|
||||
- Phase 4 — Split `vault.ts` into `vault-shell.ts` / `vault-sidebar.ts` / `vault-list.ts` / `vault-drawer.ts` / `vault-form-wrapper.ts`. Lift `vault_locked` RPC intercept into `shared/state.ts`. Reset `state.drawerOpen` on non-list `renderPane`. Debounce sidebar search (50-100ms).
|
||||
- Phase 5 — P2 cluster: inactivity-timer reset on content-callable messages (with documented exclusion set); `state.gitHost` clear on session expiry; teardown helper extraction (`teardownSettingsCommon`); `Promise.allSettled` in devices/trash; MutationObserver debounce in `content/detector.ts`.
|
||||
- Phase 6 — `get_vault_status` SW message + vault-sidebar status indicator (closes the `relicario status` parity gap).
|
||||
|
||||
**Out of scope:** anything in Plan A (security/docs polish — `impl Drop`, `service-worker/session.ts:26` swallow removal, `.free()` audit, `recovery_qr.rs` docs, server hardening, env-var audit) or Plan B (CLI restructure — `cli/main.rs` split, `git_run`, parser migration to core; you only **consume** the WASM exports as a deferred follow-up). Extension P3s (form-header `isInTab()` redundancy, popup.ts `isInTab()` heuristic, item-form.ts `renderComingSoon` dead code, `types/login.ts` size, `vault.ts:18-26` backup-panel comment, capture/detector/fill username-finder dedup, capture submit-button hook scope, setup.ts passphrase-score `-1` sentinel, `setup.ts:1056-1062` chrome.storage bypass, `setup.ts:1-7` "5-step" header, glyphs.ts partial adoption, `types.ts` TotpKind flat-union, `totp-tools.ts:39-46` swallowed rejections, generator-panel cleanup guard, `item-list.ts` popover listeners, popup `popup.ts:178-181` unconditional teardowns). Other parity items (per-attachment `delete_attachment` SW message, `list --tag` filter doc note). Cross-cutting items not explicitly listed (chrome.storage.local direct reads outside the setup migration, bun test runner doc note, manifest version sync). The 8 "Open architectural decisions". WASM JS-naming snake_case → camelCase (deferred to a separate plan). Anything touching the in-flight uncommitted v0.5.x work. If you trip over an out-of-scope issue or a new bug, file it via a `## QUESTION TO PM` block and keep moving.
|
||||
|
||||
**Hard rules:**
|
||||
- **Phase 1 first.** Do NOT start phases 3 or 4 until phase 1 is green and committed. The typed `StateHost` is the contract phases 3 and 4 build against.
|
||||
- **`View` / `PopupState` migration is part of phase 1**, not phase 4. Doing it later creates circular imports that surface mid-refactor and waste a day.
|
||||
- **Do NOT redo Plan A's `.free()` swallow removal** at `extension/src/service-worker/session.ts:26`. That's Dev-A's. But wherever your refactor *moves* a `.free()` callsite — most notably during phase 3 when `setup.ts`'s `verifiedHandle` retires and the new `create_vault`/`attach_vault` SW handlers acquire their own handles — the new location MUST call `wasm.lock(handle)` first regardless of whether Plan A's Rust-side `impl Drop` has landed yet. Cite Plan A as the source of the policy in your phase 3 commit message.
|
||||
- **`extension/src/wasm.d.ts` coordination with Plan B.** Plan B Phase 8 will touch this file for new parser exports. Verify by reading `extension/src/service-worker/vault.ts` whether your `create_vault`/`attach_vault` SW handlers need new WASM entry points — they likely don't (the SW already orchestrates `unlock`/`embed_image_secret`/`register_device`/`manifest_encrypt`). If you DO need new entries, escalate via `## QUESTION TO PM` so the touch order with Plan B can be sequenced.
|
||||
- **`create_vault` and `attach_vault` SW handlers must be transactional** — they hold their own internal session reference for the duration of the operation and do NOT consult or reset the user-facing inactivity timer until they return successfully. Document this contract in the handler header comments.
|
||||
- **Phase 4 `vault_locked` channel unification** keeps both signals (the SW's `session_expired` event AND the new `shared/state.ts` wrapper's intercept) firing during the migration window. Collapse only after both surfaces are verified consuming from `shared/state.ts`. Add a regression test asserting popup lock screen renders on `session_expired` and vault tab lock screen renders on the SW response intercept.
|
||||
- **Round out the WASM stub at `extension/src/__stubs__/relicario_wasm.stub.ts`** as part of phase 3. DEV-C noted only 7 of ~25 exports are stubbed; phase 3's vitest tests for `create_vault`/`attach_vault` need stubs for `embed_image_secret`, `register_device`, `manifest_encrypt`. Add them rather than file a separate ticket.
|
||||
- The `recovery_qr_generated_at` direct chrome.storage.local write at `setup.ts:1056-1062` is **out of scope** — leave it as-is; defer to a P3 cleanup.
|
||||
- Do not merge your branch to main. The PM owns merges.
|
||||
- Do not push `--force` or run `git reset --hard`. Per `CLAUDE.md`: ask first.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of multiple terminals. The relay routes messages between them.
|
||||
|
||||
**At every phase boundary** (complete, blocked, or question): call `read_messages(for="dev-c")` first, then post your update via `post_message(from="dev-c", to="pm", kind="status"|"question", body="...")` and also print it here. Use this format:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-C
|
||||
Time: <iso8601 like 2026-05-04T14:30:00-07:00>
|
||||
Branch: feature/2026-05-04-c-extension-restructure
|
||||
Task: <phase number / short name>
|
||||
Status: STARTED | IN-PROGRESS | DONE | BLOCKED | REVIEW-READY
|
||||
Last commit: <short sha + first line of message>
|
||||
Tests: <green | red (which failed) | N/A>
|
||||
Notes: <anything PM needs to know — keep to 3 sentences max>
|
||||
```
|
||||
|
||||
**When you need PM input mid-task**: post via `post_message(kind="question")` with format:
|
||||
|
||||
```
|
||||
## QUESTION TO PM — DEV-C
|
||||
Time: <iso8601>
|
||||
Context: <what phase, what decision point>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no (does work stop without an answer?)
|
||||
```
|
||||
|
||||
**You'll receive**: `## DIRECTIVE TO DEV-C` blocks from the PM via relay (or relayed by user if relay is down). Acknowledge and act.
|
||||
|
||||
## Cross-plan coordination
|
||||
|
||||
- **Plan A owns the `.free()` swallow removal** (`service-worker/session.ts:26`) and the Rust `impl Drop for SessionHandle`. Do not redo that work. Do honor the policy where you move callsites (see Hard Rules).
|
||||
- **Plan B Phase 8 ships WASM parser exports** (`parse_month_year` / `base32_decode_lenient` / `guess_mime`) that the extension can eventually consume. Consumption (SW message handlers wrapping the new exports) is **explicitly deferred to a future plan** — do NOT design those handlers in this train. The seam exists; nobody is wiring it yet.
|
||||
- **`extension/src/wasm.d.ts` shared touchpoint with Plan B.** See Hard Rules — you likely don't need to touch it. If you do, escalate to PM for sequencing.
|
||||
|
||||
## Authority within the plan
|
||||
|
||||
You don't need PM permission to:
|
||||
- Execute phase-to-phase per the plan
|
||||
- Make implementation decisions consistent with the plan and synthesis
|
||||
- Choose how the typed `StateHost` exposes `setState` (the plan suggests `setState<K extends keyof PopupState>`; pick the variant that gives the cleanest call-site ergonomics)
|
||||
- Pick which file `View` and `PopupState` migrate to (`shared/types.ts` vs new `shared/popup-state.ts`) — the plan accepts either
|
||||
- Add new tests, refactor your own code, fix bugs you introduce
|
||||
- Push commits to your feature branch
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- You discover phase 3's setup-to-SW migration needs new WASM entry points (would touch `wasm.d.ts` and conflict with Plan B Phase 8)
|
||||
- You discover the `view`/`PopupState` migration in phase 1 surfaces more TS errors than the plan estimated (~15-30); if you hit 100+ errors, the surface area is bigger than the plan accounts for
|
||||
- You discover a real bug in the existing `vault_locked` channels (e.g. popup currently doesn't actually receive `session_expired` despite the plan's premise)
|
||||
- A vitest test you can't make green after honest debugging (don't fudge — debug)
|
||||
- A discovered bug not in your plan
|
||||
- Anything destructive (per project rules)
|
||||
- Before opening the PR for review
|
||||
|
||||
## Final steps before REVIEW-READY
|
||||
|
||||
Run the project's full validation:
|
||||
|
||||
```bash
|
||||
# From the worktree root (/home/alee/Sources/relicario-plan-c):
|
||||
cd extension
|
||||
npm test # vitest
|
||||
npm run build # Chrome build
|
||||
npm run build:firefox # Firefox build
|
||||
cd ..
|
||||
|
||||
# Done-criteria sanity greps:
|
||||
grep -n ': any' extension/src/shared/state.ts # should return zero
|
||||
grep -rn 'relicario-wasm' extension/src/setup/ # should return zero (post-Phase-3)
|
||||
wc -l extension/src/setup/setup.ts # should be ≤ ~500
|
||||
wc -l extension/src/vault/vault.ts # should be ~200
|
||||
grep -n 'loadDeviceSettings\|loadBlacklist\|saveBlacklist' \
|
||||
extension/src/service-worker/router/popup-only.ts \
|
||||
extension/src/service-worker/router/content-callable.ts # should be imports only, no defs
|
||||
grep -n 'itemToManifestEntry' extension/src/service-worker/router/ # should be imports only
|
||||
```
|
||||
|
||||
Then push and open the PR:
|
||||
|
||||
```bash
|
||||
git push -u origin feature/2026-05-04-c-extension-restructure
|
||||
gh pr create --base main --head feature/2026-05-04-c-extension-restructure --title "refactor(ext): typed StateHost + setup→SW + vault.ts split (Plan C)" --body "$(cat <<'EOF'
|
||||
## Summary
|
||||
|
||||
Architecture-review followup Plan C (extension restructure — eliminates the two steepest learning cliffs). Source: `docs/superpowers/specs/2026-05-04-extension-restructure-design.md`.
|
||||
|
||||
- **P1.6** — `extension/src/shared/state.ts` now has a concrete `StateHost` interface (no `any` in public surface), `getState`/`setState` generic over `keyof PopupState`, double-registration guard, `__resetHostForTests` helper. `View` and `PopupState` migrated from `popup/popup.ts` to `shared/types.ts` to break circular import.
|
||||
- **P1.9** — `service-worker/storage.ts` extracted; `itemToManifestEntry` moved to `service-worker/vault.ts`. Both router files import; no more duplicated definitions.
|
||||
- **P1.4** — `setup.ts` no longer imports `relicario-wasm`. New `create_vault` / `attach_vault` SW messages handle vault creation transactionally. Procedural wizard converted to a step-registry pattern (`{ id, render, attach }[]`). `clearWizardState()` on `beforeunload` + step-0 reset wipes sensitive `Uint8Array` material best-effort. `setup.ts` LOC dropped from 1220 to ~500.
|
||||
- **P1.5** — `vault.ts` split into `vault-shell.ts` / `vault-sidebar.ts` / `vault-list.ts` / `vault-drawer.ts` / `vault-form-wrapper.ts`. `vault.ts` retained at ~200 LOC (routing + state only). `vault_locked` RPC intercept lifted into `shared/state.ts` so popup and vault tab consume one channel. Drawer auto-closes on non-list views. Sidebar search debounced.
|
||||
- **P2 cluster** — inactivity timer resets on all messages except a documented exclusion set; `state.gitHost` clears on session expiry; `teardownSettingsCommon` extracted; `devices.ts`/`trash.ts` use `Promise.allSettled`; `content/detector.ts` MutationObserver debounced.
|
||||
- **`get_vault_status`** — closes the `relicario status` parity gap. New SW message returns cached `{ ahead, behind, lastSyncAt, pendingItems }`; vault sidebar renders an indicator on mount + manual refresh.
|
||||
|
||||
## Cross-plan coordination respected
|
||||
|
||||
- **Plan A** owns the `service-worker/session.ts:26` swallow removal and the Rust `impl Drop`. This PR does NOT redo that work. Wherever this refactor moved a `.free()` callsite (Phase 3 setup-to-SW migration), the new location calls `wasm.lock(handle)` first regardless of Plan A's status.
|
||||
- **Plan B Phase 8** WASM parser exports are a seam this PR does NOT consume in this train. Future plan wires the SW handlers.
|
||||
- **`extension/src/wasm.d.ts`** not touched by this PR (verified at Phase 3).
|
||||
|
||||
## Test plan
|
||||
|
||||
- [ ] `cd extension && npm test` passes (vitest including new tests for typed state, SW storage helpers, `clearWizardState`, drawer auto-close, `vault_locked` channel, `get_vault_status`)
|
||||
- [ ] `cd extension && npm run build && npm run build:firefox` clean
|
||||
- [ ] `grep -n ': any' extension/src/shared/state.ts` returns zero
|
||||
- [ ] `grep -rn 'relicario-wasm' extension/src/setup/` returns zero
|
||||
- [ ] `wc -l extension/src/setup/setup.ts` ≤ ~500
|
||||
- [ ] `wc -l extension/src/vault/vault.ts` ~200
|
||||
- [ ] Manual smoke: load extension → setup → unlock → vault tab → drawer behavior → settings → trash
|
||||
- [ ] Manual smoke: trigger session expiry, confirm both popup and vault tab show lock screen
|
||||
- [ ] Manual smoke: vault sidebar status indicator updates on sync
|
||||
|
||||
## Done criteria
|
||||
|
||||
Per `docs/superpowers/specs/2026-05-04-extension-restructure-design.md` Done criteria — every checkbox.
|
||||
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Emit a `## STATUS UPDATE` with `Status: REVIEW-READY` and the PR URL (post via `post_message`).
|
||||
|
||||
## First action
|
||||
|
||||
After reading: emit a `## STATUS UPDATE` confirming setup complete (worktree created at `/home/alee/Sources/relicario-plan-c`, plan absorbed, on `feature/2026-05-04-c-extension-restructure`). Post it via `post_message(from="dev-c", to="pm", kind="status", body="...")`. Then start Phase 1 of your plan (typed `StateHost` + `View`/`PopupState` migration). Remember: phase 1 is the precondition for phases 3 and 4 — do not start them until phase 1 is green.
|
||||
@@ -0,0 +1,162 @@
|
||||
# PM Kickoff Prompt — arch-followup architecture-review followups
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are the **project manager** for the arch-followup "architecture-review followups" release train. 3 senior developers report to you, each working in their own terminal on a parallel feature branch. The user runs all 4 terminals; a relay MCP server routes messages between you so the user does not need to copy-paste.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Branch: stay on `main`. Do not check out feature branches.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; `from` is always `"pm"` for you
|
||||
- `read_messages(for)` — drain your inbox; call with `for="pm"` before each action
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. After sending any directive, call `post_message(from="pm", to="dev-X", kind="directive", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session (this happens when the relay server was not running when your session opened), use the Python shim instead:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"pm"}'
|
||||
```
|
||||
|
||||
The shim connects over HTTP and has the same semantics as the MCP tools.
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules (Spanish flourish in chat replies only, capitalization, autonomy defaults, never run git-destructive commands without asking)
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — the canonical synthesis that drove all three plans (10 P1s + P2/P3 tail + 8 open architectural decisions)
|
||||
3. `docs/superpowers/specs/2026-05-04-security-polish-design.md` — Plan A: security & docs polish (S, independent, ships first)
|
||||
4. `docs/superpowers/specs/2026-05-04-cli-restructure-design.md` — Plan B: CLI restructure (M-L, multi-day)
|
||||
5. `docs/superpowers/specs/2026-05-04-extension-restructure-design.md` — Plan C: extension restructure (L, multi-day to multi-week, largest)
|
||||
6. `docs/superpowers/coordination/RELAY.md` — multi-agent paradigm + relay reference (you are inside this paradigm right now)
|
||||
|
||||
Skim the per-reviewer notes only if a dev's question forces it: `docs/superpowers/reviews/2026-05-04-dev-a-notes.md` (Rust core), `dev-b-notes.md` (Rust consumers), `dev-c-notes.md` (TypeScript).
|
||||
|
||||
## Your authority
|
||||
|
||||
- Approve or deny scope changes from devs
|
||||
- Review and merge PRs from each dev's feature branch
|
||||
- Drive any release-prep work that isn't a feature plan (e.g. CHANGELOG entries per merged PR, version bumps if any) — this is your hands-on work
|
||||
- Coordinate sequencing of the cross-plan touch points (see "Cross-plan coordination" below)
|
||||
- Tag a milestone (e.g. `arch-followup-complete` or whatever the user prefers) once everything is integrated **— but only after explicit user approval**
|
||||
|
||||
## Your boundaries
|
||||
|
||||
- Don't write feature code yourself. Edits to docs / CHANGELOG / `CLAUDE.md` are fine.
|
||||
- Don't deviate from the spec without user approval.
|
||||
- Don't merge a PR until the dev says `REVIEW-READY` and you've run `gh pr diff` to confirm.
|
||||
- Don't tag without user approval.
|
||||
- Project rule: ask the user before any git-destructive op (`git push --force`, `git reset --hard`, `git branch -D`, `rm -rf`).
|
||||
|
||||
## Cross-plan coordination (you must enforce)
|
||||
|
||||
The three plans were drafted with explicit cross-boundary cites. Hold devs to them:
|
||||
|
||||
- **Plan A is fully independent of B and C.** It can ship anytime. There is no merge-order dependency.
|
||||
- **Plan B Phase 8 (WASM parser exports + `wasm.d.ts` mirror) is a seam Plan C will eventually consume**, but the consumption (SW message handlers wrapping the new exports) is **explicitly deferred to a future plan**. B does NOT block C, and C does NOT block B during execution. The seam exists; nobody is wiring it yet.
|
||||
- **Both B and C touch `extension/src/wasm.d.ts` at most once each.** If both must touch it in the same window, sequence Plan B's edits first and rebase Plan C on top. Plan C's design says it likely does NOT need to touch `wasm.d.ts` (its `create_vault`/`attach_vault` SW handlers reuse already-declared WASM entries) — verify when C reaches Phase 3.
|
||||
- **Plan A owns the removal of the `try { current.free() }` swallow** at `extension/src/service-worker/session.ts:26` and the Rust-side `impl Drop for SessionHandle`. Plan C must NOT redo that work, but wherever Plan C *moves* a `.free()` callsite (most notably during the Phase 3 setup-to-SW migration where `setup.ts`'s `verifiedHandle` retires and the new `create_vault`/`attach_vault` handlers acquire their own handles), the new location must call `wasm.lock(handle)` first regardless of Plan A's status.
|
||||
|
||||
## Judgment calls in the plans worth flagging
|
||||
|
||||
The subagents who drafted the plans flagged these decisions for your awareness:
|
||||
|
||||
- **Plan A Phase 4 — `tools/relay/queue.test.ts:54` is already fixed** in commit `061facd` (planning subagent verified). The phase records this as a verification step rather than a code change. Plan A's real Phase 4 work is `tools/relay/start.sh` — both `launch_tmux` and `launch_kitty` still launch only PM/Dev-A/Dev-B (no Dev-C window); the manual-mode banner still says "Open 3 new terminals"; no `*-dev-c-prompt.md` is discovered. That part IS still needed.
|
||||
- **Plan A `.free()` audit yielded exactly one callsite** under `extension/src/` (the SW one at `session.ts:26`). The plan records the grep command for reproducibility; if a future surface adds a second callsite, this PR's grep becomes the baseline.
|
||||
- **Plan B Phase 7 — `MonthYear::new` currently returns `Result<_, &'static str>`** (DEV-A's P3 nit). Plan B recommends re-wrapping the error in `MonthYear::parse` rather than migrating `new` to `RelicarioError` — keeps Plan B focused. If you'd rather have Plan B address the consistency now, raise it with the user before Dev-B starts Phase 7.
|
||||
- **Plan B Phase 8 keeps snake_case naming** for the new WASM exports (consistent with every existing export). The snake_case → camelCase decision (DEV-B/DEV-C P3) is **explicitly deferred to a separate plan**; introducing camelCase only for the three new exports would create a worst-of-both-worlds inconsistency.
|
||||
- **Plan C Phase 1 — `View` and `PopupState` currently live in `extension/src/popup/popup.ts`** (lines 70-92). The phase 1 typed `StateHost` interface needs to import them, but doing so directly creates a `popup → shared → popup` circular import. The plan calls for migrating those types to `extension/src/shared/types.ts` (or a new `shared/popup-state.ts`) as part of phase 1 before re-importing. Make sure Dev-C has done this migration before consuming TS errors elsewhere.
|
||||
- **Plan C noted only 7 of ~25 WASM exports** are currently stubbed in `extension/src/__stubs__/relicario_wasm.stub.ts`. Plan C Phase 3's vitest tests for `create_vault`/`attach_vault` will need additional stubs (`embed_image_secret`, `register_device`, `manifest_encrypt`) — Dev-C should round those out as part of the phase rather than file a separate ticket.
|
||||
|
||||
If any of these conflict with your judgment, raise it with the user before kickoff.
|
||||
|
||||
## The 8 "Open architectural decisions"
|
||||
|
||||
The synthesis appendix lists 8 decisions that are user-judgement calls, not implementation tasks:
|
||||
|
||||
1. Was `impl Drop for SessionHandle` deliberately omitted? — **Plan A confirms it was not**, and ships the fix.
|
||||
2. Should CLI parsers migrate to core? — **Plan B Phase 7 says yes** and ships the migration.
|
||||
3. Bootstrap rule for missing `devices.json` — **out of scope**, defer.
|
||||
4. `Lock` no-op CLI subcommand visibility — **out of scope**, defer.
|
||||
5. Task 12 cleanup status (`cmd_backup_export` still reads `devices.json`) — **out of scope**, defer.
|
||||
6. `tools/relay/call.py` and `call.ts` tracking — **already tracked** (per `RELAY.md`).
|
||||
7. WASM JS naming snake_case → camelCase — **explicitly deferred** to a separate plan (Plan B Phase 8 does NOT take a position).
|
||||
8. `.gitea_env_vars` gitignore — **already done** in commit `4a726c2`.
|
||||
|
||||
You do not need to act on any of these unless the user reopens one. They're listed so you have the context if a dev surfaces a related question.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of 4 terminals. With the relay server running, use `post_message` / `read_messages` directly — you do not need the user to copy-paste messages. Call `read_messages(for="pm")` before every action. If the relay MCP tools are not registered in your session, fall back to the Python shim (see **Relay server** section above) or ask the user to relay manually.
|
||||
|
||||
**You receive:** `## STATUS UPDATE — DEV-<letter>` or `## QUESTION TO PM — DEV-<letter>` blocks, either from the relay inbox or relayed by the user if the relay is down.
|
||||
|
||||
**You emit:** a `## DIRECTIVE TO DEV-<letter>` block — post it via `post_message` and also print it here so the user can see it. Format:
|
||||
|
||||
```
|
||||
## DIRECTIVE TO DEV-<letter>
|
||||
Time: <iso8601>
|
||||
Action: PROCEED | HOLD | RESCOPE | REVIEW-COMPLETE | MERGE-APPROVED
|
||||
Notes: <one paragraph max>
|
||||
Next: <one concrete instruction or "continue plan">
|
||||
```
|
||||
|
||||
When asked "status?" by the user at any time, give a current rollup:
|
||||
|
||||
```
|
||||
## RELEASE STATUS — arch-followup
|
||||
Devs: <per-dev one-line state>
|
||||
PM: <what you're working on>
|
||||
Blockers: <list, or "none">
|
||||
Next milestone: <e.g., "Dev A REVIEW-READY", "Plan A merged">
|
||||
```
|
||||
|
||||
## Reviewing PRs
|
||||
|
||||
When a dev posts `Action: REVIEW-READY` with a PR URL:
|
||||
|
||||
1. `gh pr view <url>` to read description and CI status
|
||||
2. `gh pr diff <url>` to read changes
|
||||
3. Check the diff against the spec (synthesis) and the plan's Done criteria checklist
|
||||
4. If green: post `Action: MERGE-APPROVED` and run `gh pr merge --merge` (preserve git history; no squash — the project preserves git as audit log per `CLAUDE.md`)
|
||||
5. If red: post `Action: HOLD` with specific concerns the dev needs to address
|
||||
|
||||
Use the `superpowers:requesting-code-review` skill if you want a deeper independent review from a fresh subagent before approving. For Plan A in particular (defense-in-depth crypto fix), an independent review is worth the cost.
|
||||
|
||||
## Per-plan acceptance gating
|
||||
|
||||
- **Plan A:** every Done-criteria checkbox in `2026-05-04-security-polish-design.md` checked off; the `.free()` audit grep recorded in PR description; both the wasm-bindgen-test and the native `#[test]` for `Drop` present and passing; `recovery_qr.rs` documentation density visibly matches `crypto.rs` / `imgsecret.rs`.
|
||||
- **Plan B:** every Done-criteria checkbox in `2026-05-04-cli-restructure-design.md` checked off; `cargo test --workspace` green; `cargo clippy --workspace` silent; `cargo build -p relicario-wasm --target wasm32-unknown-unknown` clean; the 16 `bail!("git X failed")` sites all collapsed; the 7 `refresh_groups_cache` callsites all using `after_manifest_change`; one canonical `ParamsFile`; batched purge measured (3 git invocations for ≥3 items).
|
||||
- **Plan C:** every Done-criteria checkbox in `2026-05-04-extension-restructure-design.md` checked off; vitest green; `bun run build` + `bun run build:firefox` clean; no `any` in `StateHost`; SW router files import the new helpers; `setup.ts` ≤ ~500 LOC and does not import `relicario-wasm`; `vault.ts` ~200 LOC of routing+state only; single `vault_locked` channel.
|
||||
|
||||
## Pre-tag checklist
|
||||
|
||||
Before tagging or otherwise marking the followup train complete:
|
||||
|
||||
- [ ] All three plan branches merged to main
|
||||
- [ ] Full test suite green on main: `cargo test --workspace && cd extension && npm test && cd ../tools/relay && bun test`
|
||||
- [ ] Standard build green on main: `cargo build && cd extension && npm run build && npm run build:firefox`
|
||||
- [ ] User-driven smoke test of the merged result (load extension, exercise unlock + setup + a vault op; run the CLI through `relicario init`/`add`/`list`/`sync`)
|
||||
- [ ] Synthesis P2/P3 tail re-evaluated — anything still worth a follow-up plan? If so, draft a one-line tracker.
|
||||
- [ ] Explicit user approval to mark the train complete
|
||||
|
||||
## First action
|
||||
|
||||
1. Call `read_messages(for="pm")` to drain any early inbox messages.
|
||||
2. Emit a `## RELEASE STATUS` block confirming you've absorbed the synthesis, all three plans, and the cross-plan coordination notes. Note the judgment calls above for the user's awareness.
|
||||
3. Send opening directives to all three devs via `post_message`:
|
||||
- **Dev-A:** start Plan A Phase 1 (Rust `impl Drop` + test). It's S-effort and independent — no waiting on anyone.
|
||||
- **Dev-B:** start Plan B Phase 1 (mechanical split of `cli/main.rs`). Cite that this is the precondition for everything else in B.
|
||||
- **Dev-C:** start Plan C Phase 1 (typed `StateHost` + `View`/`PopupState` migration). Cite that phase 1 is the precondition for phases 3 and 4. Also cite the migration of `View`/`PopupState` to `shared/types.ts` to avoid the circular import.
|
||||
4. Wait for acknowledgement STATUS UPDATEs from all devs before clearing them to proceed deeper into their plans.
|
||||
199
docs/superpowers/coordination/RELAY.md
Normal file
199
docs/superpowers/coordination/RELAY.md
Normal file
@@ -0,0 +1,199 @@
|
||||
# RELAY — Multi-Agent Kickoff & Coordination
|
||||
|
||||
How to spin up parallel Claude Code sessions that coordinate over a shared MCP relay. One PM, two or more Devs, each in their own terminal, each on their own branch / worktree, exchanging structured messages.
|
||||
|
||||
## TL;DR — three commands
|
||||
|
||||
```bash
|
||||
# 1. Generate kickoff prompts (interactive — answers the design questions)
|
||||
# In any Claude Code session in this repo:
|
||||
/multi-agent-kickoff
|
||||
|
||||
# 2. Start the relay + open the windows
|
||||
bash tools/relay/start.sh --kitty # or --tmux, or --manual
|
||||
|
||||
# 3. In each new Claude window, paste the prompt below the `---` line
|
||||
# from the file the launcher prints (e.g. coordination/<date>-pm-prompt.md)
|
||||
```
|
||||
|
||||
That's the whole workflow. Everything below is the why and the troubleshooting.
|
||||
|
||||
## What this is
|
||||
|
||||
The "PM/Senior-Dev paradigm" — one Claude session acts as project manager, two or more Claude sessions act as senior developers, each running its own subagents on a feature branch in its own worktree. They coordinate by sending each other typed messages (status / question / directive / free) through a tiny MCP server running locally.
|
||||
|
||||
When to use it:
|
||||
|
||||
- You have **2+ implementation plans** that share a release target and want to execute them in parallel under one coordinator.
|
||||
- You want each stream isolated (separate worktree, separate branch) so subagents can't accidentally commit to main or step on each other's files.
|
||||
- You want one human (the user) to be a relay-of-last-resort but not a router — the PM does the routing.
|
||||
|
||||
When NOT to use it: one-off tasks, single-stream plans, anything where the overhead of "spin up four windows" exceeds the work itself. For those, just work in the foreground.
|
||||
|
||||
## The pieces
|
||||
|
||||
```
|
||||
┌──────────────────┐ HTTP/SSE ┌──────────────────┐
|
||||
│ Relay (MCP) │◀───────────│ PM session │
|
||||
│ tools/relay/ │ │ (Claude Code) │
|
||||
│ port 7331 │ └──────────────────┘
|
||||
│ │ ┌──────────────────┐
|
||||
│ Per-role inbox │◀───────────│ Dev-A session │
|
||||
│ in-memory │ │ (Claude Code) │
|
||||
│ consume-once │ └──────────────────┘
|
||||
└──────────────────┘ ┌──────────────────┐
|
||||
◀────────│ Dev-B session │
|
||||
│ (Claude Code) │
|
||||
└──────────────────┘
|
||||
┌──────── (optional) ───────┐
|
||||
◀────────│ Dev-C session │
|
||||
└───────────────────┘
|
||||
```
|
||||
|
||||
- **Relay MCP server** — `tools/relay/server.ts`. HTTP/SSE on `localhost:7331`. Exposes three MCP tools: `post_message`, `read_messages`, `list_pending`. Per-connection MCP server instance prevents routing collisions across concurrent SSE clients.
|
||||
- **In-memory queue** — `tools/relay/queue.ts`. Per-role inbox (`pm`, `dev-a`, `dev-b`, `dev-c`). `read` is consume-once (FIFO drain). No TTL, no persistence, no cap — relay is dev-only ephemeral; restart the server to wipe state.
|
||||
- **Launcher** — `tools/relay/start.sh`. Three modes (manual / tmux / kitty) that all start the relay and either open the role windows or print the commands for you to open them by hand.
|
||||
- **Fallback shim** — `tools/relay/call.py` (Python) and `tools/relay/call.ts` (TS). Direct CLI access to the same MCP tools, for when the in-Claude MCP client isn't loading or you want to script a status check from a regular shell. Both are tracked in the repo and load-bearing for the multi-agent flow — do not delete.
|
||||
|
||||
## Invocation
|
||||
|
||||
### Step 1 — Generate the kickoff prompts
|
||||
|
||||
In any Claude Code session inside this repo, run:
|
||||
|
||||
```
|
||||
/multi-agent-kickoff
|
||||
```
|
||||
|
||||
The skill walks you through a short Q&A (release target, branch names per dev, plan-file paths, coordination cadence) and writes four prompt files to `docs/superpowers/coordination/`:
|
||||
|
||||
```
|
||||
<date>-pm-prompt.md
|
||||
<date>-dev-a-prompt.md
|
||||
<date>-dev-b-prompt.md
|
||||
<date>-dev-c-prompt.md (only if 3 devs)
|
||||
```
|
||||
|
||||
Each prompt is self-contained: it tells the receiving session its role, its branch / worktree, the plan it owns, and the coordination protocol (block format, when to send status, who to escalate to). The launcher script discovers the latest `*-pm-prompt.md` / `*-dev-a-prompt.md` / etc. by `mtime`, so the most recently generated set wins automatically.
|
||||
|
||||
### Step 2 — Start the relay
|
||||
|
||||
Pick a launcher mode that matches your terminal setup.
|
||||
|
||||
**`--kitty` (recommended on kitty)**
|
||||
|
||||
```bash
|
||||
bash tools/relay/start.sh --kitty
|
||||
```
|
||||
|
||||
Opens 4 (or 5 with dev-c) tabs in the current kitty window: one for the relay log, one per role. Each role tab launches `claude` in the repo root. Paste the corresponding prompt into each role tab to start the session.
|
||||
|
||||
**`--tmux` (recommended on non-kitty)**
|
||||
|
||||
```bash
|
||||
bash tools/relay/start.sh --tmux
|
||||
```
|
||||
|
||||
Creates a tmux session `relay-lift` with windows `relay`, `pm`, `dev-a`, `dev-b` (and `dev-c` if a fourth prompt is found). Attaches automatically. `Ctrl-b N` to navigate windows. Detach with `Ctrl-b d`.
|
||||
|
||||
**`--manual` (for any terminal)**
|
||||
|
||||
```bash
|
||||
bash tools/relay/start.sh --manual
|
||||
```
|
||||
|
||||
Starts the relay in the current terminal and prints `cat <path>` commands for each role. Open new terminals yourself and paste the printed commands; this is the most flexible mode for unusual setups (split panes, remote sessions, terminal multiplexers other than tmux).
|
||||
|
||||
The launcher uses port **7331**. If it's already in use the script aborts with the kill command — `kill $(lsof -ti:7331)` clears it.
|
||||
|
||||
### Step 3 — Drive the coordination
|
||||
|
||||
The PM session is the entry point. Talk to PM about goals; PM decides who's working on what and posts directives to the dev sessions via the relay. Each dev reads its inbox, executes, and posts back status / questions. The user (you) is mostly a watcher — PM should self-route.
|
||||
|
||||
Common rhythm:
|
||||
|
||||
- **PM at start:** posts a directive to each dev describing the first slice.
|
||||
- **Dev on completion:** posts status with branch / commit / what shipped.
|
||||
- **Dev when blocked:** posts a question; PM unblocks (decision) or escalates to user.
|
||||
- **PM end-of-cycle:** asks each dev for a status, summarizes, decides next slice.
|
||||
|
||||
Message kinds (`MessageKind` in `queue.ts`):
|
||||
|
||||
| Kind | Use when |
|
||||
|------|----------|
|
||||
| `status` | "I shipped X, branch is at Y, ready for next slice" |
|
||||
| `question` | "Should I do A or B? Blocking until I hear back" |
|
||||
| `directive` | PM-to-dev: "Next, do X. Constraints are Y. Acceptance is Z." |
|
||||
| `free` | Anything that doesn't fit the above (FYI, side-channel chatter) |
|
||||
|
||||
Block format inside `body` is freeform markdown. The kickoff prompts include the project's preferred block templates.
|
||||
|
||||
## Fallback — when the MCP client misbehaves
|
||||
|
||||
If a Claude session can't reach the relay's MCP tools (transient SSE hiccup, MCP server failed to register, sandboxed network), use the shim:
|
||||
|
||||
```bash
|
||||
# From any shell, with the relay running on 7331:
|
||||
python3 tools/relay/call.py read_messages '{"for":"pm"}'
|
||||
python3 tools/relay/call.py post_message '{"from":"dev-a","to":"pm","kind":"status","body":"shipped X"}'
|
||||
python3 tools/relay/call.py list_pending '{"for":"dev-b"}'
|
||||
```
|
||||
|
||||
`call.ts` is the same surface in TypeScript (`bun run tools/relay/call.ts ...`) for when you want to script from a TS context. Both shims speak raw MCP over the SSE transport; output is the JSON-RPC response.
|
||||
|
||||
The kickoff prompts reference `call.py` by path — if the in-Claude MCP client breaks mid-session, the dev can fall back to `Bash python3 tools/relay/call.py ...` and keep coordinating without restarting.
|
||||
|
||||
## Where things live
|
||||
|
||||
```
|
||||
docs/superpowers/coordination/
|
||||
├── RELAY.md ← you are here
|
||||
├── <date>-pm-prompt.md generated by /multi-agent-kickoff
|
||||
├── <date>-dev-a-prompt.md
|
||||
├── <date>-dev-b-prompt.md
|
||||
├── <date>-dev-c-prompt.md (optional, 4-role mode)
|
||||
└── archive/ older kickoff sets
|
||||
|
||||
tools/relay/
|
||||
├── start.sh launcher (manual / tmux / kitty)
|
||||
├── server.ts MCP server (HTTP/SSE on :7331)
|
||||
├── queue.ts in-memory per-role FIFO
|
||||
├── queue.test.ts node:test — run with `bun test`
|
||||
├── call.py Python MCP-client shim (fallback)
|
||||
├── call.ts TypeScript MCP-client shim (fallback)
|
||||
├── package.json
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
The launcher's prompt-discovery is `ls -t "$COORD_DIR"/*-<role>-prompt.md | head -1` — newest wins. To switch back to a previous kickoff set, either delete the newer files or move them under `archive/`.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Roles are fixed strings:** `pm`, `dev-a`, `dev-b`, `dev-c`. Adding a new role means editing `Role` in `queue.ts`, `KNOWN_ROLES`, the `enum` in `server.ts`'s tool schema, and the launcher.
|
||||
- **Worktree per dev:** each dev session works in its own git worktree on its own branch. Subagents must `cd` into the worktree first — the multi-agent-kickoff skill bakes this rule into the dev prompts (subagents have been known to commit to `main` if the worktree cwd is only set in a header).
|
||||
- **Branch naming follows the release train:** `feature/<release>-<dev>-<scope>`. PM owns the merge order; devs do not merge each other's branches.
|
||||
- **No squashing:** the project preserves git history as audit log (per `CLAUDE.md`). Devs commit small and often; PM coordinates rebases at integration time, not before.
|
||||
- **The user is not the router.** PM should issue directives directly to devs via the relay. The user steps in only for cross-stream design decisions or when PM explicitly escalates.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **"port 7331 is already in use"** — another relay is running. `kill $(lsof -ti:7331)`, then re-run `start.sh`.
|
||||
- **Launcher can't find a prompt** (`(none found)` in the printed paths) — `/multi-agent-kickoff` hasn't been run yet, or all generated prompts are under `archive/`. Re-run the skill.
|
||||
- **Dev session committing to `main` instead of its worktree** — its subagent prompts are missing the force-`cd` header. Regenerate the dev prompt via `/multi-agent-kickoff` (the skill bakes in the cd rule) or hand-edit the prompt to start with `cd <worktree-path>`.
|
||||
- **MCP tools don't show up in the Claude session** — restart the session. If it persists, fall back to `call.py`. If `call.py` also fails, check the relay log window for stack traces; the SSE transport sometimes wedges if a client disconnects ungracefully.
|
||||
- **`bun test` failing in `tools/relay/`** — relay tests use `node:test` via bun. Run from `tools/relay/`, not the repo root: `cd tools/relay && bun test`. Extension tests use vitest and live elsewhere; don't conflate.
|
||||
- **One dev session is silent** — check `python3 tools/relay/call.py list_pending '{"for":"<role>"}'` from any shell. If the dev's inbox has unread messages, they may have crashed or detached. Open the role's window and resume.
|
||||
|
||||
## Caveats
|
||||
|
||||
- **In-memory queue is dev-only.** Restart the relay = lose all queued messages. There is no persistence by design — coordination is meant to flow forward, not be replayable.
|
||||
- **No auth.** The relay binds to `localhost:7331` with no token. Don't expose the port; don't run on a shared machine.
|
||||
- **The relay is not a chat history.** `read_messages` drains the inbox. If you need to refer back to what was said, copy-paste into a session note or the PR description; don't expect the relay to remember.
|
||||
- **Context costs scale with session count.** Four parallel Claude sessions burn four context windows. Use this paradigm when the parallel speedup justifies the cost — for sequential work, one session is cheaper.
|
||||
|
||||
## See also
|
||||
|
||||
- `tools/relay/server.ts` — MCP tool definitions (`post_message`, `read_messages`, `list_pending`) and their schemas.
|
||||
- `tools/relay/queue.ts` — `Role` / `MessageKind` types; the canonical per-role-inbox semantics.
|
||||
- `docs/superpowers/coordination/<date>-pm-prompt.md` — the latest PM kickoff (the actual operational instructions PM runs by).
|
||||
- The `multi-agent-kickoff` skill — generates the kickoff prompt set.
|
||||
@@ -0,0 +1,165 @@
|
||||
# Dev A Kickoff Prompt — Architecture Review (Rust core)
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior reviewer** owning the Rust core review for Relicario's whole-codebase architecture audit (2026-05-04). You are one of three dev reviewers (A/B/C) reporting to a PM in another terminal. Your scope is `crates/relicario-core/` and its tests.
|
||||
|
||||
The user wants to be able to **read and understand this codebase and learn by tinkering**, even though they don't know Rust. Your review lens is therefore *architectural clarity for a smart newcomer*, not just correctness. Naming, layering, comments at non-obvious boundaries, dead code, leaky abstractions, opportunities to simplify — all in scope.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Stay on `main`. **Do not check out branches, do not create worktrees, do not modify code.** This is a review-only role.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalization rules, autonomy defaults, never run git-destructive commands without asking).
|
||||
- The working tree has uncommitted changes (manifest bumps, vault tweaks, relay tooling). Run `git status` once for awareness; otherwise review HEAD as the canonical state. Flag anything weird about the uncommitted state in your notes if it suggests an in-flight architectural issue.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-a"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-a"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each pass: `read_messages(for="dev-a")`. After emitting any status/question block: `post_message(from="dev-a", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session (the relay server was not running when your session opened), use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-a","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-a"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/specs/2026-04-11-relicario-design.md` — the foundational spec (threat model, crypto pipeline, format)
|
||||
3. `crates/relicario-core/src/lib.rs` — public API surface
|
||||
4. Then walk every file in `crates/relicario-core/src/` and `crates/relicario-core/tests/` deliberately. The point is depth, not coverage rate.
|
||||
|
||||
You are NOT required to read the other crates (DEV-B owns them) or the extension (DEV-C owns it). If something in core only makes sense by looking at how it's consumed, file a `## QUESTION TO PM` rather than crossing the boundary.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- `crates/relicario-core/src/*.rs` — every file
|
||||
- `crates/relicario-core/tests/*.rs` — integration tests
|
||||
- `crates/relicario-core/Cargo.toml` — dependencies and features
|
||||
|
||||
**Out of scope (other reviewers' territory):**
|
||||
- `crates/relicario-cli/`, `crates/relicario-server/`, `crates/relicario-wasm/` — DEV-B
|
||||
- `extension/`, `tools/relay/` — DEV-C
|
||||
- `docs/` outside the spec link above
|
||||
|
||||
**Hard rules:**
|
||||
- **No code changes.** Not even trivial doc-comment fixes. Surface in your notes; the user decides what to act on after PM synthesis.
|
||||
- No git commits, no branch creation, no destructive ops.
|
||||
- If you spend more than ~30 minutes on one file, post a status update with what you've found so far and move on. Cover the whole core, then return for depth.
|
||||
|
||||
## What to look for (review lens)
|
||||
|
||||
Walk every file in `crates/relicario-core/src/` and assess:
|
||||
|
||||
1. **Architectural clarity for a Rust newcomer.** Would a smart person who knows another language be able to follow this? Where are the surprise idioms, the silent assumptions, the "you have to know Rust to read this" cliffs?
|
||||
2. **Naming.** Are types, functions, fields named for what they mean? Any cryptic two-letter abbreviations? Names that lie about what they do?
|
||||
3. **Layering.** Is `relicario-core` actually platform-agnostic (no fs, no net, no git)? Any leaks? Any types that pretend to be pure data but hide I/O?
|
||||
4. **API ergonomics.** Are public types easy to construct and consume? Any footguns (e.g. easy-to-misuse nonces, builders that compile but corrupt)? Are errors descriptive?
|
||||
5. **Crypto correctness invariants.** Argon2id params, XChaCha20-Poly1305 nonce uniqueness, key zeroization, AAD usage, version/format gates. Are these enforced by types or by convention? If by convention, is that convention obvious?
|
||||
6. **DCT steganography (`imgsecret.rs`).** This is the most magical file. Does it have enough explanation for a reader to map code to spec section?
|
||||
7. **Comments.** Where there ARE comments, do they explain *why* (good) or *what* (rot)? Where they're missing, is it because the code is self-explanatory, or because nobody got around to it?
|
||||
8. **Tests.** Do they cover happy path AND format/crypto edge cases? Are test helpers well-named? Any dead test cases?
|
||||
9. **Dead code, unused features, abandoned experiments.** Use `cargo clippy -p relicario-core` and `cargo +nightly udeps -p relicario-core 2>/dev/null || true` if you have time, but mostly: just notice things.
|
||||
10. **Simplification opportunities.** Three similar lines is better than premature abstraction; but six similar match arms might want a helper. Note candidates; don't insist.
|
||||
|
||||
You may run `cargo build -p relicario-core`, `cargo test -p relicario-core`, `cargo clippy -p relicario-core` to confirm assumptions, but the review is not gated on green — it's gated on understanding.
|
||||
|
||||
## Output
|
||||
|
||||
Write your findings to `docs/superpowers/reviews/2026-05-04-dev-a-notes.md`. Create the `reviews/` directory with `mkdir -p` if it doesn't exist.
|
||||
|
||||
Structure:
|
||||
|
||||
```markdown
|
||||
# DEV-A Architecture Review Notes — Rust Core
|
||||
|
||||
## Summary
|
||||
3-5 sentences: what's the overall architectural shape, what's the strongest part, what's the weakest part.
|
||||
|
||||
## Findings (prioritized: P1 = address before more code lands, P2 = soon, P3 = nice-to-have)
|
||||
|
||||
### P1 — <short title>
|
||||
**File(s):** `crates/relicario-core/src/foo.rs:123`
|
||||
**Observation:** <what you saw>
|
||||
**Why it matters:** <especially for a Rust newcomer reading the code>
|
||||
**Suggested direction:** <one or two sentences; do NOT rewrite — just point>
|
||||
|
||||
(repeat for each finding, P1 first, then P2, then P3)
|
||||
|
||||
## File-by-file walk (one paragraph each)
|
||||
For every file in core, a paragraph: what it does, what's clear, what's not. Brief is fine — this is the appendix.
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
A paragraph: how readable is this crate for a competent dev who has never written Rust? What single change would help most?
|
||||
```
|
||||
|
||||
The PM will synthesize your notes (plus DEV-B's and DEV-C's) into the final review doc.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
**Before each major pass** (e.g. starting file walk, switching to findings write-up): call `read_messages(for="dev-a")`.
|
||||
|
||||
**Status update format** (post via `post_message(from="dev-a", to="pm", kind="status", body="...")`, also print here):
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-A
|
||||
Time: <iso8601>
|
||||
Phase: SETUP | READING | WALKING | WRITING | REVIEW-COMPLETE
|
||||
Files covered: <e.g. 8/19 src + 0/7 tests>
|
||||
Findings so far: <P1: N, P2: N, P3: N>
|
||||
Notes: <≤3 sentences>
|
||||
```
|
||||
|
||||
**Question format** (when you need PM input — e.g. you're unsure if something is in scope, or you suspect a cross-cutting issue):
|
||||
|
||||
```
|
||||
## QUESTION TO PM — DEV-A
|
||||
Time: <iso8601>
|
||||
Context: <what file, what concern>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no
|
||||
```
|
||||
|
||||
You'll receive `## DIRECTIVE TO DEV-A` blocks from the PM via relay. Acknowledge and act.
|
||||
|
||||
## Authority
|
||||
|
||||
You don't need PM permission to:
|
||||
- Decide reading order within scope
|
||||
- Decide whether a finding is P1/P2/P3
|
||||
- Use subagents to parallelize file reads (force-cd into `/home/alee/Sources/relicario` per project memory rule — every subagent prompt MUST start with `cd /home/alee/Sources/relicario` so the subagent doesn't wander)
|
||||
- Run `cargo` commands (build, test, clippy) read-only
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- You suspect an issue that crosses into DEV-B or DEV-C territory
|
||||
- A finding is so severe (e.g. exploitable crypto bug) that it deserves immediate attention
|
||||
- You're tempted to fix something inline (don't — escalate and let the PM/user decide)
|
||||
|
||||
## REVIEW-COMPLETE criteria
|
||||
|
||||
Before posting `Phase: REVIEW-COMPLETE`:
|
||||
- [ ] Every file in `crates/relicario-core/src/` walked
|
||||
- [ ] Every file in `crates/relicario-core/tests/` walked
|
||||
- [ ] Notes written to `docs/superpowers/reviews/2026-05-04-dev-a-notes.md`
|
||||
- [ ] At least one paragraph in the beginner-friendliness assessment
|
||||
- [ ] No P1 finding left vague — every P1 has a file:line and a suggested direction
|
||||
|
||||
## First action
|
||||
|
||||
1. Call `read_messages(for="dev-a")`.
|
||||
2. Read the project rules and the spec.
|
||||
3. Skim `lib.rs` and the file list under `crates/relicario-core/src/`.
|
||||
4. Emit a `## STATUS UPDATE` with `Phase: SETUP` confirming spec absorbed and file count to walk.
|
||||
5. Begin the file walk. Save findings as you go.
|
||||
@@ -0,0 +1,198 @@
|
||||
# Dev B Kickoff Prompt — Architecture Review (Rust consumers: CLI, server, WASM)
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior reviewer** owning the Rust consumer-layer review for Relicario's whole-codebase architecture audit (2026-05-04). You are one of three dev reviewers (A/B/C) reporting to a PM in another terminal. Your scope is the three Rust crates that consume `relicario-core`: `relicario-cli`, `relicario-server`, and `relicario-wasm`.
|
||||
|
||||
The user wants to be able to **read and understand this codebase and learn by tinkering**, even though they don't know Rust. Your review lens is therefore *architectural clarity for a smart newcomer*, not just correctness. Naming, layering, where business logic actually lives, comments at non-obvious boundaries, dead code, leaky abstractions, opportunities to simplify — all in scope.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Stay on `main`. **Do not check out branches, do not create worktrees, do not modify code.** This is a review-only role.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalization rules, autonomy defaults, never run git-destructive commands without asking).
|
||||
- The working tree has uncommitted changes (manifest bumps, vault tweaks, relay tooling). Run `git status` once for awareness; otherwise review HEAD as the canonical state. Flag anything weird about the uncommitted state in your notes if it suggests an in-flight architectural issue.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-b"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-b"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each pass: `read_messages(for="dev-b")`. After emitting any status/question block: `post_message(from="dev-b", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-b","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-b"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/specs/2026-04-11-relicario-design.md` — the foundational spec
|
||||
3. `crates/relicario-core/src/lib.rs` — **just** the public API surface (you do NOT review core; that's DEV-A — but you must understand what your crates depend on)
|
||||
4. Then walk each consumer crate deliberately:
|
||||
- `crates/relicario-cli/src/main.rs` then the rest of `crates/relicario-cli/src/` and `crates/relicario-cli/tests/`
|
||||
- `crates/relicario-server/src/main.rs` and `crates/relicario-server/tests/`
|
||||
- `crates/relicario-wasm/src/lib.rs` then `crates/relicario-wasm/src/`
|
||||
|
||||
You are NOT required to read deeply into `relicario-core` internals (DEV-A owns them) or the extension TypeScript (DEV-C owns it). The WASM crate is your boundary with DEV-C; review it from the Rust side, and trust DEV-C to review it from the JS side.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- `crates/relicario-cli/` — entire crate (src + tests + Cargo.toml)
|
||||
- `crates/relicario-server/` — entire crate
|
||||
- `crates/relicario-wasm/` — entire crate
|
||||
|
||||
**Out of scope (other reviewers' territory):**
|
||||
- `crates/relicario-core/` internals — DEV-A
|
||||
- `extension/`, `tools/relay/` — DEV-C
|
||||
- `docs/` outside the spec link above
|
||||
|
||||
**Hard rules:**
|
||||
- **No code changes.** Not even trivial. Surface in notes.
|
||||
- No git commits, no branch creation, no destructive ops.
|
||||
- If you spot a core-internal issue while you're poking at it, file a `## QUESTION TO PM` so DEV-A can be alerted; don't expand your own scope.
|
||||
|
||||
## What to look for (review lens)
|
||||
|
||||
For each crate, assess:
|
||||
|
||||
### relicario-cli (the user-facing binary)
|
||||
|
||||
1. **Command surface.** Does the clap structure match the spec's intended UX? Are subcommand names and flags discoverable? Any flags that exist but don't do what their name suggests?
|
||||
2. **Where business logic lives.** `relicario-core` should be doing the work; the CLI should be glue (parse args → call core → format output). Any place where the CLI has logic that should be in core?
|
||||
3. **Session handling.** `session.rs` holds `UnlockedVault` with the master key in `Zeroizing`. Are session lifetimes clear? Any path where the key outlives its window?
|
||||
4. **Filesystem and git.** The CLI is the only place that touches fs and shells out to git. Is `helpers.rs` doing this cleanly? Any path-handling bugs? Any place where `git_command` is invoked with insufficient error mapping?
|
||||
5. **Tests.** Integration tests under `crates/relicario-cli/tests/` — do they test the CLI surface or just re-test core? Are fixtures synthetic (per project convention)? Any mocked filesystem leaks?
|
||||
6. **Error UX.** When something goes wrong, does the user get a useful message, or does a `RelicarioError` get printed raw?
|
||||
|
||||
### relicario-server (Git pre-receive hook)
|
||||
|
||||
1. **Surface.** Two subcommands (`verify-commit`, `generate-hook`). Is the contract with Git clear? Does `generate-hook` produce a hook that's actually correct?
|
||||
2. **Trust model.** This is the only piece that runs server-side. Does it correctly enforce "the server only sees opaque ciphertext" — i.e. it never tries to decrypt, only verifies signatures/format?
|
||||
3. **Failure modes.** What happens if a malformed commit lands? Are rejections actionable for the pushing client?
|
||||
|
||||
### relicario-wasm (extension bridge)
|
||||
|
||||
1. **JS surface.** What does `#[wasm_bindgen]` actually expose? Is the API minimal and well-typed (`SessionHandle` opaque), or does it leak Rust internals?
|
||||
2. **Session handle pattern.** `SessionHandle` → `Zeroizing<[u8;32]>` indirection. Is the lifetime story sound? What happens when JS drops the handle?
|
||||
3. **Error mapping.** Rust errors → JS exceptions. Are messages useful on the JS side, or do they just say "internal error"?
|
||||
4. **Build target.** Does `cargo build -p relicario-wasm --target wasm32-unknown-unknown` succeed clean? Any feature flags that look gnarly?
|
||||
5. **Boundary with DEV-C.** What does the TS side need to know that isn't documented in the WASM crate? Note these for DEV-C cross-reference.
|
||||
|
||||
### Cross-cutting (all three crates)
|
||||
|
||||
1. **Naming.** Same questions as DEV-A.
|
||||
2. **Comments.** Same.
|
||||
3. **Layering.** Does each crate import only what it should? Any place where a consumer crate is reaching past `relicario-core`'s public API?
|
||||
4. **Dead code, abandoned features.** Notice things.
|
||||
5. **Simplification.** Where would a Rust newcomer trip? What's the single change that would help most?
|
||||
|
||||
You may run `cargo build`, `cargo test -p relicario-cli`, `cargo test -p relicario-server`, `cargo build -p relicario-wasm --target wasm32-unknown-unknown`, `cargo clippy --workspace`. The review is not gated on green; it's gated on understanding.
|
||||
|
||||
## Output
|
||||
|
||||
Write your findings to `docs/superpowers/reviews/2026-05-04-dev-b-notes.md`. Create the `reviews/` directory with `mkdir -p` if it doesn't exist.
|
||||
|
||||
Structure:
|
||||
|
||||
```markdown
|
||||
# DEV-B Architecture Review Notes — Rust Consumers (CLI, Server, WASM)
|
||||
|
||||
## Summary
|
||||
3-5 sentences spanning all three crates: what's the shape of the consumer layer, where is it strongest, where is it weakest.
|
||||
|
||||
## Findings (prioritized: P1 / P2 / P3)
|
||||
|
||||
Group by crate, P1 first within each:
|
||||
|
||||
### relicario-cli
|
||||
#### P1 — <short title>
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:456`
|
||||
**Observation:** ...
|
||||
**Why it matters:** ...
|
||||
**Suggested direction:** ...
|
||||
|
||||
### relicario-server
|
||||
...
|
||||
|
||||
### relicario-wasm
|
||||
...
|
||||
|
||||
### Cross-cutting
|
||||
Findings that span more than one crate (e.g. an error-handling pattern that's inconsistent across all three).
|
||||
|
||||
## File-by-file walk
|
||||
One paragraph per file across all three crates. Appendix-grade detail.
|
||||
|
||||
## Boundary notes for DEV-C
|
||||
What about the WASM JS surface should DEV-C double-check from the TypeScript side?
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
A paragraph: how readable are these crates for a competent dev who has never written Rust? What single change would help most?
|
||||
```
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
**Before each major pass:** `read_messages(for="dev-b")`.
|
||||
|
||||
**Status update format** (post via `post_message(from="dev-b", to="pm", kind="status", body="...")`, also print here):
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: <iso8601>
|
||||
Phase: SETUP | READING | WALKING-CLI | WALKING-SERVER | WALKING-WASM | WRITING | REVIEW-COMPLETE
|
||||
Crates covered: <e.g. cli ✓ / server ✓ / wasm ⏳>
|
||||
Findings so far: <P1: N, P2: N, P3: N>
|
||||
Notes: <≤3 sentences>
|
||||
```
|
||||
|
||||
**Question format:**
|
||||
|
||||
```
|
||||
## QUESTION TO PM — DEV-B
|
||||
Time: <iso8601>
|
||||
Context: <what crate, what concern>
|
||||
Options: <A / B / C>
|
||||
Recommended: <pick + one-sentence rationale>
|
||||
Blocker: yes | no
|
||||
```
|
||||
|
||||
You'll receive `## DIRECTIVE TO DEV-B` blocks from the PM via relay. Acknowledge and act.
|
||||
|
||||
## Authority
|
||||
|
||||
You don't need PM permission to:
|
||||
- Decide reading order within scope
|
||||
- Decide P1/P2/P3 prioritization
|
||||
- Use subagents to parallelize crate reads (force-cd into `/home/alee/Sources/relicario` per project memory rule — every subagent prompt MUST start with `cd /home/alee/Sources/relicario`)
|
||||
- Run `cargo` commands (build, test, clippy) read-only
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- An issue spans into DEV-A's core or DEV-C's TS territory
|
||||
- A finding is severe enough to deserve immediate attention
|
||||
- You're tempted to fix something inline (don't)
|
||||
|
||||
## REVIEW-COMPLETE criteria
|
||||
|
||||
- [ ] Every src file in cli/server/wasm walked
|
||||
- [ ] Every test file walked
|
||||
- [ ] Notes written to `docs/superpowers/reviews/2026-05-04-dev-b-notes.md`
|
||||
- [ ] Boundary-notes section for DEV-C populated
|
||||
- [ ] Every P1 has a file:line and suggested direction
|
||||
|
||||
## First action
|
||||
|
||||
1. Call `read_messages(for="dev-b")`.
|
||||
2. Read project rules and spec.
|
||||
3. Skim `relicario-core/src/lib.rs` for the public API your crates depend on.
|
||||
4. Emit a `## STATUS UPDATE` with `Phase: SETUP` confirming setup, listing crates+file counts you'll walk.
|
||||
5. Begin the walk: cli first, then server, then wasm. Save findings as you go.
|
||||
@@ -0,0 +1,214 @@
|
||||
# Dev C Kickoff Prompt — Architecture Review (TypeScript: extension + relay tooling)
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior reviewer** owning the TypeScript review for Relicario's whole-codebase architecture audit (2026-05-04). You are one of three dev reviewers (A/B/C) reporting to a PM in another terminal. Your scope is the browser extension (`extension/`) and the dev tooling (`tools/relay/`).
|
||||
|
||||
The user wants to be able to **read and understand this codebase and learn by tinkering**, including the parts they're more comfortable with (TS). Your review lens is therefore *architectural clarity*, with extra attention to:
|
||||
- Parity with the CLI (per project memory: CLI/extension parity is a design philosophy — never ship "CLI first, extension follow-up")
|
||||
- The popup ↔ service-worker ↔ content script boundary
|
||||
- The WASM bridge from the JS side
|
||||
- Naming, layering, dead code, simplification opportunities
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Stay on `main`. **Do not check out branches, do not create worktrees, do not modify code.** This is a review-only role.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalization, autonomy defaults, never run git-destructive commands without asking).
|
||||
- The working tree has uncommitted changes — note especially: `extension/manifest.json`, `extension/manifest.firefox.json`, `extension/package*.json`, `extension/src/shared/glyphs.ts` and `__tests__/glyphs.test.ts`, `extension/src/vault/vault.css`, `extension/src/vault/vault.ts`, `tools/relay/queue.ts`, `tools/relay/server.ts`, plus untracked `tools/relay/call.py`, `tools/relay/call.ts`, `.gitea_env_vars`. Run `git status` and `git diff` once. Decide whether the uncommitted diff is "in flight, ignore for review" or "already part of the architecture and worth flagging" — note your call in the notes file.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. Note that you are reviewing this server itself — but for coordination, you still use it. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-c"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-c"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each pass: `read_messages(for="dev-c")`. After emitting any status/question block: `post_message(from="dev-c", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-c","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-c"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules (note especially the CLI/extension parity rule)
|
||||
2. `docs/superpowers/specs/2026-04-11-relicario-design.md` — foundational spec (skim, focus on the parts that touch the extension)
|
||||
3. `extension/package.json`, `extension/manifest.json`, `extension/manifest.firefox.json` — extension shape
|
||||
4. `extension/src/wasm.d.ts` and `extension/src/__stubs__/relicario_wasm.stub.ts` — your WASM boundary
|
||||
5. Then walk in this order:
|
||||
- `extension/src/service-worker/` (the trusted core of the extension)
|
||||
- `extension/src/shared/` (shared utilities)
|
||||
- `extension/src/popup/` (popup UI)
|
||||
- `extension/src/vault/` (full-tab vault UI)
|
||||
- `extension/src/content/` (content scripts: detector, fill, capture)
|
||||
- `extension/src/setup/` (setup wizard)
|
||||
- `tools/relay/` (the dev-only message bus, separate concern)
|
||||
|
||||
You are NOT required to read deeply into the Rust crates — DEV-A owns core, DEV-B owns CLI/server/WASM. From your side, you only need to understand the WASM JS surface that the extension consumes.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- `extension/` — entire tree (excluding `node_modules/` and built artifacts)
|
||||
- `tools/relay/` — entire tree (excluding `node_modules/`)
|
||||
- The WASM JS surface as consumed from TS (`wasm.d.ts`, the stub, every call site)
|
||||
|
||||
**Out of scope (other reviewers' territory):**
|
||||
- `crates/relicario-core/` internals — DEV-A
|
||||
- `crates/relicario-cli/`, `crates/relicario-server/`, `crates/relicario-wasm/` Rust internals — DEV-B
|
||||
- `docs/` outside the spec link above
|
||||
|
||||
**Hard rules:**
|
||||
- **No code changes.** Not even trivial. Surface in notes.
|
||||
- No git commits, no branch creation, no destructive ops.
|
||||
- If you find a Rust-side issue while looking at the WASM boundary, file a `## QUESTION TO PM` so DEV-B can be alerted; don't expand scope.
|
||||
|
||||
## What to look for (review lens)
|
||||
|
||||
### Extension architecture
|
||||
|
||||
1. **Layering — popup vs service-worker vs content vs vault tab.** Each has a clear role; are the lines clean? Any place where popup is doing trusted work that should live in the service-worker, or vice versa? Any direct WASM calls in content scripts (a security smell)?
|
||||
2. **Message-passing.** `extension/src/shared/messages.ts` and the service-worker router — is the typing tight? Are there messages that exist but are never sent, or sent but never handled?
|
||||
3. **WASM session handle.** The session handle is a number (an opaque pointer into the Rust session map). Where does it live? Who creates it, who drops it? Is the locked/unlocked state machine obvious from the code?
|
||||
4. **CLI/extension parity.** Walk through the CLI's commands (skim `crates/relicario-cli/src/main.rs` for the surface only) and check: for every CLI capability, does the extension have an equivalent UI path? If not, is that a deliberate choice or an oversight? This is a project-philosophy lens — flag any gap as a P1 architectural issue.
|
||||
5. **Component organization.** `extension/src/popup/components/` has settings, item-form, item-list, fields, generator-panel, etc. Are component boundaries clean? Any teardown leaks (the project has had teardown bugs before — see commit `ddfb95d` and `8baef5b`)?
|
||||
6. **Storage and state.** What lives in `chrome.storage.local`? In `chrome.storage.session`? Any sensitive data persisted that shouldn't be? Any cleartext secrets in DOM that survive teardown?
|
||||
7. **Settings architecture.** v0.5.1 just landed a unified left-nav settings (commit `bd6a301`). Is the new structure clean, or are there leftover bits from the old structure?
|
||||
|
||||
### Vault tab vs popup
|
||||
|
||||
8. **Two render targets, one component.** Settings (and possibly other components) render into both the popup and the vault tab. Is the rendering target abstracted, or are there `if (in popup)` branches? Note any pattern that breaks down.
|
||||
9. **Vault tab session timeout.** There's been work on this (per project memory). Is the session-timer logic in `service-worker/session-timer.ts` legible?
|
||||
|
||||
### Shared utilities
|
||||
|
||||
10. **`shared/types.ts`, `shared/messages.ts`, `shared/state.ts`.** Are these doing what their names suggest? Any `any`-leaking? Any types that should be generated from the WASM bindings instead of hand-maintained?
|
||||
11. **`shared/glyphs.ts`.** Per project rules, no inline emoji — all UI glyphs go through this. Is the abstraction tight? (Recent uncommitted edits here — note your read.)
|
||||
|
||||
### Relay tooling (`tools/relay/`)
|
||||
|
||||
12. **Single-purpose dev tool.** It's the message bus you're using right now. Is it appropriately isolated from the rest of the codebase (no cross-imports, separate package.json)? Is the role enum (`pm`, `dev-a`, `dev-b`, `dev-c`) maintained in lockstep across `queue.ts`, `server.ts`, and any client (`call.py`, `call.ts`)?
|
||||
13. **Untracked `call.py` and `call.ts`.** What are these for? Are they the documented fallback shims? Should they be tracked?
|
||||
|
||||
### Cross-cutting
|
||||
|
||||
14. **Naming.** Are TS names crisp? Any that lie about behavior?
|
||||
15. **Dead code.** `bun run build` cleanly? Any imports unused? Any components rendered nowhere?
|
||||
16. **Simplification.** Where would a beginner trip? What's the single change that would help most?
|
||||
17. **Tests.** `extension/src/**/__tests__/*.test.ts` — meaningful coverage, or smoke-only?
|
||||
|
||||
You may run `bun run build`, `bun run build:firefox`, `bun run test`, `cd tools/relay && bun test`, `bun run lint` if available. Review is not gated on green; it's gated on understanding.
|
||||
|
||||
## Output
|
||||
|
||||
Write your findings to `docs/superpowers/reviews/2026-05-04-dev-c-notes.md`. Create the `reviews/` directory with `mkdir -p` if it doesn't exist.
|
||||
|
||||
Structure:
|
||||
|
||||
```markdown
|
||||
# DEV-C Architecture Review Notes — TypeScript (Extension + Relay)
|
||||
|
||||
## Summary
|
||||
3-5 sentences: shape of the TS layer, strongest part, weakest part. Note the CLI/extension parity status.
|
||||
|
||||
## Findings (prioritized: P1 / P2 / P3)
|
||||
|
||||
Group by area, P1 first within each:
|
||||
|
||||
### Extension — service-worker
|
||||
### Extension — popup + components
|
||||
### Extension — vault tab
|
||||
### Extension — content scripts
|
||||
### Extension — setup
|
||||
### Extension — shared utilities
|
||||
### WASM boundary (JS side)
|
||||
### Relay tooling
|
||||
### CLI/extension parity gaps
|
||||
### Cross-cutting
|
||||
|
||||
(use the same finding format as DEV-A/DEV-B: file:line, observation, why it matters, suggested direction)
|
||||
|
||||
## File-by-file walk
|
||||
One paragraph per file (or per small group of related files). Appendix-grade.
|
||||
|
||||
## CLI/extension parity table
|
||||
| CLI capability | Extension equivalent | Notes |
|
||||
|----------------|----------------------|-------|
|
||||
| ... | ✓ or ✗ or partial | ... |
|
||||
|
||||
## Boundary notes for DEV-B
|
||||
What about the WASM JS surface (or session handle, error mapping) does DEV-B need to double-check from the Rust side?
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
A paragraph for the TS side specifically.
|
||||
|
||||
## Uncommitted-state read
|
||||
A short paragraph: what's in the working tree but not in HEAD, and is any of it architecturally relevant?
|
||||
```
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
**Before each major pass:** `read_messages(for="dev-c")`.
|
||||
|
||||
**Status update format** (post via `post_message(from="dev-c", to="pm", kind="status", body="...")`, also print here):
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-C
|
||||
Time: <iso8601>
|
||||
Phase: SETUP | READING | WALKING-SW | WALKING-POPUP | WALKING-VAULT | WALKING-CONTENT | WALKING-SETUP | WALKING-SHARED | WALKING-RELAY | WRITING | REVIEW-COMPLETE
|
||||
Areas covered: <checklist>
|
||||
Findings so far: <P1: N, P2: N, P3: N>
|
||||
Notes: <≤3 sentences>
|
||||
```
|
||||
|
||||
**Question format:**
|
||||
|
||||
```
|
||||
## QUESTION TO PM — DEV-C
|
||||
Time: <iso8601>
|
||||
Context: <what file, what concern>
|
||||
Options: <A / B / C>
|
||||
Recommended: <pick + one-sentence rationale>
|
||||
Blocker: yes | no
|
||||
```
|
||||
|
||||
You'll receive `## DIRECTIVE TO DEV-C` blocks from the PM via relay. Acknowledge and act.
|
||||
|
||||
## Authority
|
||||
|
||||
You don't need PM permission to:
|
||||
- Decide reading order within scope
|
||||
- Decide P1/P2/P3 prioritization
|
||||
- Use subagents to parallelize area reads (force-cd into `/home/alee/Sources/relicario` per project memory rule — every subagent prompt MUST start with `cd /home/alee/Sources/relicario`)
|
||||
- Run `bun` and `cargo` commands read-only
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- A finding spans into DEV-A's core or DEV-B's Rust crates
|
||||
- A finding is severe (e.g. a real security smell, leaked secret in storage)
|
||||
- You're tempted to fix something inline (don't)
|
||||
|
||||
## REVIEW-COMPLETE criteria
|
||||
|
||||
- [ ] Every TS file under `extension/src/` walked (including `__tests__`)
|
||||
- [ ] Every TS file under `tools/relay/` walked
|
||||
- [ ] Notes written to `docs/superpowers/reviews/2026-05-04-dev-c-notes.md`
|
||||
- [ ] CLI/extension parity table populated (every CLI capability either ✓, ✗, or partial)
|
||||
- [ ] Boundary-notes section for DEV-B populated
|
||||
- [ ] Uncommitted-state read paragraph written
|
||||
- [ ] Every P1 has a file:line and suggested direction
|
||||
|
||||
## First action
|
||||
|
||||
1. Call `read_messages(for="dev-c")`.
|
||||
2. Read project rules and spec.
|
||||
3. Look at `manifest.json` and skim `wasm.d.ts` so you know your boundaries.
|
||||
4. Run `git status` and `git diff` once for awareness of uncommitted state.
|
||||
5. Emit a `## STATUS UPDATE` with `Phase: SETUP` confirming setup, listing area buckets you'll walk.
|
||||
6. Begin the walk: service-worker first, then shared, then popup, then vault, then content, then setup, then relay tooling. Save findings as you go.
|
||||
@@ -0,0 +1,200 @@
|
||||
# Dev A Kickoff Prompt — Architecture Review Followup, Stream A (Security & Docs Polish)
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement the plan task-by-task once it lands.
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior developer** owning Stream A for the Relicario architecture-review-followup work. Stream A is the small, security-flavored quick-win PR that goes first: SessionHandle Drop semantics, the matching JS-side audit, recovery_qr.rs documentation density, and the relay launcher fix for the dev-c fourth window. Goal is **under-a-day, all-S effort, ships first**.
|
||||
|
||||
A PM in another terminal coordinates you with two other senior devs. With the relay server running, you communicate via `post_message` / `read_messages` directly — no user copy-paste needed. **Your plan does not exist yet.** The PM is drafting it as their first action. Set up your worktree, post acknowledgement, and wait for the PM's `PROCEED` directive containing the plan path before starting Task 1.
|
||||
|
||||
## Setup (do this first)
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario
|
||||
git fetch
|
||||
git worktree add /home/alee/Sources/relicario.arch-followup-stream-a -b feature/arch-followup-stream-a-security-polish
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-a
|
||||
pwd # should print /home/alee/Sources/relicario.arch-followup-stream-a
|
||||
```
|
||||
|
||||
**Note on `git pull`:** main has uncommitted polish changes from in-flight post-v0.5.1 work. The setup above branches from local main HEAD without pulling, which is intentional. If `git fetch` reveals new upstream commits, surface them to the PM before incorporating.
|
||||
|
||||
**ALL subsequent work happens in `/home/alee/Sources/relicario.arch-followup-stream-a`**. Every subagent prompt MUST begin with `cd /home/alee/Sources/relicario.arch-followup-stream-a` (project memory rule — without the force-cd, subagents may commit to main).
|
||||
|
||||
Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalize "Relicario", default to "yes"/recommended, never run git-destructive commands without asking).
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — synthesis (your scope is **P1.1, the JS free-swallow fix, P1.7, P1.8 only**)
|
||||
3. `docs/superpowers/reviews/2026-05-04-dev-a-notes.md` — full DEV-A reviewer notes (Rust core; covers recovery_qr.rs context)
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — full DEV-B reviewer notes (covers SessionHandle context on the WASM side)
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — full DEV-C reviewer notes (covers the JS free-swallow + start.sh launcher context)
|
||||
6. **Your plan (will land at):** `docs/superpowers/specs/2026-05-04-security-polish-design.md` — read once the PM directs you to PROCEED
|
||||
|
||||
## Execution mode
|
||||
|
||||
Use **superpowers:subagent-driven-development**. Fresh subagent per task, two-stage review between tasks. Every subagent prompt MUST start with:
|
||||
```
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-a
|
||||
```
|
||||
…before any other instruction. This is non-negotiable per project memory.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- P1.1 — `impl Drop for SessionHandle` in `crates/relicario-wasm/src/lib.rs` (and `session.rs`); `wasm-bindgen-test` for construct → drop → confirm `SESSIONS` registry empty; audit every `.free()` callsite under `extension/src/` to confirm `wasm.lock(handle)` happens first regardless
|
||||
- JS partner fix at `extension/src/service-worker/session.ts:26` — remove the `try { current.free() }` swallow; let exceptions propagate or log + counter
|
||||
- P1.7 — `crates/relicario-core/src/recovery_qr.rs` documentation pass to match `crypto.rs` / `imgsecret.rs` / `backup.rs` / `tar_safe.rs` density
|
||||
- P1.8 — `tools/relay/start.sh:80` launcher fix for the dev-c fourth window (the queue.test.ts assertion is already fixed in `061facd`; only the launcher line remains)
|
||||
|
||||
**Out of scope (other DEVs own these):**
|
||||
- P1.2, P1.3, P1.10 + the in-scope CLI P2s — DEV-B (Stream B)
|
||||
- P1.4, P1.5, P1.6, P1.9 + the in-scope extension P2s — DEV-C (Stream C)
|
||||
- Any other P2/P3 not listed in your plan
|
||||
- The 8 "Open architectural decisions" at the bottom of the synthesis — those are user-judgement calls
|
||||
|
||||
If you trip over an out-of-scope issue or a new bug while doing your work, file a `## QUESTION TO PM` block and keep moving.
|
||||
|
||||
**Hard rules:**
|
||||
- **P1.1 is defense-in-depth crypto.** The `wasm-bindgen-test` covering construct → drop → registry-empty is a required acceptance gate. Do not skip or weaken it.
|
||||
- **The `.free()` callsite audit is part of P1.1.** Every callsite under `extension/src/` must be checked to confirm `wasm.lock(handle)` is called before `.free()`. Document the audit results in the PR.
|
||||
- **Do not remove the JS free-swallow before `impl Drop` lands.** The order matters: Rust fix first (so `.free()` becomes meaningful cleanup), JS swallow removal second (so failures surface).
|
||||
- **`recovery_qr.rs` docs must match the existing core standard.** Multi-paragraph module-level `//!` rationale, ASCII diagram of the 109-byte layout, doc-comments on the four public functions, comment or `const` for the `production_params()` divergence. Read `crypto.rs` and `backup.rs` first to absorb the tone.
|
||||
- **Test-only Argon2id params stay fast** (m=256, t=1, p=1) per project convention.
|
||||
- Synthetic JPEG fixtures only — no binary blobs in the test suite (project rule).
|
||||
- Do not merge your branch to main. The PM owns merges.
|
||||
- Do not push `--force` or run `git reset --hard`. Per `CLAUDE.md`: ask first.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-a"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-a"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-a")`. After emitting any status/question block: `post_message(from="dev-a", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-a","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-a"}'
|
||||
```
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of four terminals. Before starting each task, call `read_messages(for="dev-a")` to drain your inbox.
|
||||
|
||||
When posting a status update, call `post_message(from="dev-a", to="pm", kind="status", body="...")` with the body:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-A
|
||||
Time: <iso8601 like 2026-05-04T14:30:00-07:00>
|
||||
Branch: feature/arch-followup-stream-a-security-polish
|
||||
Task: <number / short name>
|
||||
Status: STARTED | IN-PROGRESS | DONE | BLOCKED | REVIEW-READY
|
||||
Last commit: <short sha + first line of message>
|
||||
Tests: <green | red (which failed) | N/A>
|
||||
Notes: <anything PM needs to know — keep to 3 sentences max>
|
||||
```
|
||||
|
||||
**When you need PM input mid-task:**
|
||||
```
|
||||
## QUESTION TO PM — DEV-A
|
||||
Time: <iso8601>
|
||||
Context: <what task, what decision point>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no
|
||||
```
|
||||
|
||||
**You'll receive:** `## DIRECTIVE TO DEV-A` blocks from the PM. The first one will say `Action: PROCEED` with the plan path once the PM has drafted it. Acknowledge and start Task 1.
|
||||
|
||||
## Authority within the plan
|
||||
|
||||
You don't need PM permission to:
|
||||
- Execute task-to-task per the plan once you have it
|
||||
- Make implementation decisions consistent with the plan and synthesis
|
||||
- Write tests, refactor your own code, fix bugs you introduce
|
||||
- Push commits to your feature branch
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- A scope question outside the plan
|
||||
- A test you can't make green after honest debugging (don't fudge — debug)
|
||||
- A discovered bug not in your plan
|
||||
- Anything destructive (per CLAUDE.md)
|
||||
- Before opening the PR for review
|
||||
|
||||
## Final steps before REVIEW-READY
|
||||
|
||||
Run the project's full validation:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-a
|
||||
cargo test
|
||||
cargo build -p relicario-wasm --target wasm32-unknown-unknown
|
||||
cd extension && bun run test && bun run build && cd ..
|
||||
cd tools/relay && bun test && cd ../..
|
||||
```
|
||||
|
||||
All four must be green. The wasm-bindgen-test for SessionHandle Drop is the headline acceptance.
|
||||
|
||||
Then push and open the PR:
|
||||
|
||||
```bash
|
||||
git push -u origin feature/arch-followup-stream-a-security-polish
|
||||
gh pr create --base main --head feature/arch-followup-stream-a-security-polish \
|
||||
--title "fix(security/docs): SessionHandle Drop + free-swallow + recovery_qr docs + dev-c launcher (Stream A)" \
|
||||
--body "$(cat <<'EOF'
|
||||
## Summary
|
||||
|
||||
Stream A of the architecture-review-followup. Small security-flavored polish PR addressing four findings from the 2026-05-04 audit:
|
||||
|
||||
- **P1.1** — `impl Drop for SessionHandle` so `.free()` becomes a real cleanup safety net (Rust fix); `wasm-bindgen-test` for construct → drop → registry empty; audit of every `.free()` callsite under `extension/src/`
|
||||
- **JS free-swallow** — removed `try { current.free() }` at `extension/src/service-worker/session.ts:26` so failures propagate
|
||||
- **P1.7** — `crates/relicario-core/src/recovery_qr.rs` brought up to the documentation density of `crypto.rs` / `backup.rs` / `tar_safe.rs`
|
||||
- **P1.8** — `tools/relay/start.sh:80` launcher fix for the dev-c fourth window
|
||||
|
||||
## Synthesis references
|
||||
|
||||
- `docs/superpowers/reviews/2026-05-04-architecture-review.md` — P1.1, P1.7, P1.8
|
||||
- `docs/superpowers/specs/2026-05-04-security-polish-design.md` — Plan A
|
||||
|
||||
## Test plan
|
||||
|
||||
- [x] `cargo test` green
|
||||
- [x] `cargo build -p relicario-wasm --target wasm32-unknown-unknown` green
|
||||
- [x] `cd extension && bun run test && bun run build` green
|
||||
- [x] `cd tools/relay && bun test` green (4-pass after dev-c assertion fix in 061facd)
|
||||
- [x] New wasm-bindgen-test: SessionHandle construct → drop → SESSIONS registry empty
|
||||
- [x] `.free()` callsite audit under `extension/src/` — every site preceded by `wasm.lock(handle)`
|
||||
- [x] `start.sh` opens 4 windows including dev-c
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Emit a `## STATUS UPDATE` with `Status: REVIEW-READY` and the PR URL.
|
||||
|
||||
## First action
|
||||
|
||||
After reading the required inputs and setting up the worktree:
|
||||
|
||||
1. Call `read_messages(for="dev-a")` to drain any early inbox messages.
|
||||
2. Emit a `## STATUS UPDATE` confirming setup complete:
|
||||
```
|
||||
## STATUS UPDATE — DEV-A
|
||||
Time: <iso8601>
|
||||
Branch: feature/arch-followup-stream-a-security-polish
|
||||
Task: setup
|
||||
Status: DONE
|
||||
Last commit: <main HEAD sha + first line>
|
||||
Tests: N/A
|
||||
Notes: Worktree at /home/alee/Sources/relicario.arch-followup-stream-a. Synthesis + reviewer notes absorbed. Awaiting Plan A at docs/superpowers/specs/2026-05-04-security-polish-design.md.
|
||||
```
|
||||
3. **Wait** for the PM's `## DIRECTIVE TO DEV-A` with `Action: PROCEED` and the plan path.
|
||||
4. Read the plan, then start Task 1 using `superpowers:subagent-driven-development`.
|
||||
@@ -0,0 +1,242 @@
|
||||
# Dev B Kickoff Prompt — Architecture Review Followup, Stream B (CLI Restructure)
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement the plan task-by-task once it lands.
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior developer** owning Stream B for the Relicario architecture-review-followup work. Stream B is the **single biggest readability lift** in the bundle (per the synthesis): split the 2641-LOC `crates/relicario-cli/src/main.rs` into a `commands/` folder, centralize the duplicated git-shell error UX, migrate three pure parsers to `relicario-core`, and pick up four in-scope CLI P2s. Multi-day, M-L effort.
|
||||
|
||||
A PM in another terminal coordinates you with two other senior devs. With the relay server running, you communicate via `post_message` / `read_messages` directly. **Your plan does not exist yet.** The PM is drafting it as their first action. Set up your worktree, post acknowledgement, and wait for the PM's `PROCEED` directive containing the plan path before starting Task 1.
|
||||
|
||||
## Setup (do this first)
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario
|
||||
git fetch
|
||||
git worktree add /home/alee/Sources/relicario.arch-followup-stream-b -b feature/arch-followup-stream-b-cli-restructure
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-b
|
||||
pwd # should print /home/alee/Sources/relicario.arch-followup-stream-b
|
||||
```
|
||||
|
||||
**Note on `git pull`:** main has uncommitted polish changes from in-flight post-v0.5.1 work. The setup above branches from local main HEAD without pulling, which is intentional. None of those uncommitted files are in Stream B's scope, so this should not produce conflicts at PR time.
|
||||
|
||||
**ALL subsequent work happens in `/home/alee/Sources/relicario.arch-followup-stream-b`**. Every subagent prompt MUST begin with `cd /home/alee/Sources/relicario.arch-followup-stream-b` (project memory rule — without the force-cd, subagents may commit to main).
|
||||
|
||||
Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalize "Relicario", default to "yes"/recommended, never run git-destructive commands without asking).
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — synthesis (your scope is **P1.2, P1.3, P1.10 + the four in-scope CLI P2s only**)
|
||||
3. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — full DEV-B reviewer notes (your stream's primary source)
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-a-notes.md` — full DEV-A reviewer notes (covers the base32 dedup that pairs with P1.10)
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — read the **"Boundary notes for DEV-B"** section in particular (covers the parity-relevant cross-references for the parser→core migration and WASM exports)
|
||||
6. **Your plan (will land at):** `docs/superpowers/specs/2026-05-04-cli-restructure-design.md` — read once the PM directs you to PROCEED
|
||||
|
||||
## Execution mode
|
||||
|
||||
Use **superpowers:subagent-driven-development**. Fresh subagent per task, two-stage review between tasks. Every subagent prompt MUST start with:
|
||||
```
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-b
|
||||
```
|
||||
…before any other instruction. This is non-negotiable per project memory.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- P1.2 — split `crates/relicario-cli/src/main.rs` (2641 LOC) into:
|
||||
- `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs`
|
||||
- `prompt.rs` (six `prompt_*` helpers + `prompt_secret`)
|
||||
- `parse.rs` (the three pure parsers, before they migrate to core)
|
||||
- `main.rs` keeps clap definitions + dispatcher (~470 lines)
|
||||
- P1.3 — add `helpers::git_run(repo: &Path, args: &[&str], context: &str)` using `.output()` to capture stderr; print captured stderr unmodified on failure; embed a human-readable `context` ("commit add: GitHub", "register device", "purge trashed item"). Sweep ~16 duplicated bail sites listed in the synthesis (`main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` and others).
|
||||
- P1.10 — migrate to `relicario-core`:
|
||||
- `parse_month_year` (already partial in `time.rs`)
|
||||
- `base32_decode_lenient` (rename / fold into a new `pub(crate) mod base32` with `encode_rfc4648` / `decode_rfc4648`; keep Steam's bespoke alphabet untouched in `item_types/totp.rs`)
|
||||
- `guess_mime` → `mime::guess_for_extension`
|
||||
- Re-export the new functions through `relicario-wasm` via `#[wasm_bindgen]` so the extension can consume them in a future round
|
||||
- CLI keeps thin wrappers as needed
|
||||
- In-scope CLI P2s:
|
||||
- `build_*_item` helper compression (`main.rs:664-921`) with a `prompt_or_flag<T>` helper
|
||||
- `refresh_groups_cache` discipline via `Vault::after_manifest_change(&self, manifest: &Manifest)` (7 manual sites at `main.rs:641, 998, 1123, 1197, 1414, 1432, 1474`)
|
||||
- `ParamsFile` dedup between `main.rs:2287` (write side, has `aead`/`salt_path`/`format_version`) and `session.rs:114` (read side, only `kdf`)
|
||||
- Batched purge in `cmd_purge` and `cmd_trash_empty` (`main.rs:1476-1480, 1896-1900`) — currently 50-item purge does 150 git invocations
|
||||
|
||||
**Out of scope (other DEVs own these):**
|
||||
- P1.1, JS free-swallow, P1.7, P1.8 — DEV-A (Stream A)
|
||||
- P1.4, P1.5, P1.6, P1.9 + the in-scope extension P2s — DEV-C (Stream C)
|
||||
- Any other P2/P3 not listed in your plan
|
||||
- WASM JS-naming snake_case → camelCase rename (DEV-B/DEV-C P3) — explicitly deferred to a separate decision
|
||||
- Server hardening items from DEV-B's P2 (generate-hook PATH, bootstrap permissiveness, stdin parsing, test gaps) — explicitly deferred
|
||||
- Any of the 8 "Open architectural decisions" at the bottom of the synthesis
|
||||
|
||||
If you trip over an out-of-scope issue or a new bug while doing your work, file a `## QUESTION TO PM` block and keep moving.
|
||||
|
||||
**Hard rules:**
|
||||
- **The P1.2 main.rs split MUST land first.** Every other phase in your plan touches files that don't exist yet until the split happens. Do not interleave.
|
||||
- **The split is purely structural — no behavior changes.** Run `cargo test -p relicario-cli` before AND after the split commits to prove parity. Any behavior delta is a bug.
|
||||
- **Keep the helper module visibility tight.** `commands/` modules are `pub(crate)` only; `main.rs` dispatches into them.
|
||||
- **`helpers::git_run` signature** is `(repo: &Path, args: &[&str], context: &str)` and it captures stderr. The old `git_command` may stay temporarily during the sweep, but Phase B-N (sweep) deletes it.
|
||||
- **`base32` extraction** must keep Steam's bespoke alphabet untouched at `item_types/totp.rs`. Add a neighbour comment pointing to the new core module and explaining why Steam stays separate.
|
||||
- **WASM re-exports use snake_case** in JS for now (`#[wasm_bindgen]` defaults). Do not rename to camelCase — that's a separate decision (DEV-B/DEV-C P3 at the bottom of the synthesis).
|
||||
- **Test-only Argon2id params stay fast** (m=256, t=1, p=1) per project convention.
|
||||
- **No binary test fixtures.** Synthetic JPEGs only via `make_test_jpeg()`.
|
||||
- **Git history is preserved.** No squash merges (project rule).
|
||||
- Do not merge your branch to main. The PM owns merges.
|
||||
- Do not push `--force` or run `git reset --hard`. Per `CLAUDE.md`: ask first.
|
||||
|
||||
## Coordination with Stream C
|
||||
|
||||
Your parser→core migration produces new `relicario-core` functions and re-exports them through `relicario-wasm`. Stream C does NOT need to consume these in this round. Document the new WASM surface in your PR body so a future round can pick it up. If you discover a parser signature change that would break the future extension consumer, raise it via `## QUESTION TO PM` before committing.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-b"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-b"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-b")`. After emitting any status/question block: `post_message(from="dev-b", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-b","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-b"}'
|
||||
```
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of four terminals. Before starting each task, call `read_messages(for="dev-b")` to drain your inbox.
|
||||
|
||||
When posting a status update, call `post_message(from="dev-b", to="pm", kind="status", body="...")` with the body:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: <iso8601 like 2026-05-04T14:30:00-07:00>
|
||||
Branch: feature/arch-followup-stream-b-cli-restructure
|
||||
Task: <number / short name>
|
||||
Status: STARTED | IN-PROGRESS | DONE | BLOCKED | REVIEW-READY
|
||||
Last commit: <short sha + first line of message>
|
||||
Tests: <green | red (which failed) | N/A>
|
||||
Notes: <anything PM needs to know — keep to 3 sentences max>
|
||||
```
|
||||
|
||||
**When you need PM input mid-task:**
|
||||
```
|
||||
## QUESTION TO PM — DEV-B
|
||||
Time: <iso8601>
|
||||
Context: <what task, what decision point>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no
|
||||
```
|
||||
|
||||
**You'll receive:** `## DIRECTIVE TO DEV-B` blocks from the PM. The first one will say `Action: PROCEED` with the plan path once the PM has drafted it. Acknowledge and start Task 1.
|
||||
|
||||
## Authority within the plan
|
||||
|
||||
You don't need PM permission to:
|
||||
- Execute task-to-task per the plan once you have it
|
||||
- Make implementation decisions consistent with the plan and synthesis
|
||||
- Write tests, refactor your own code, fix bugs you introduce
|
||||
- Push commits to your feature branch
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- A scope question outside the plan
|
||||
- A signature change in the parser→core migration that would affect the future extension consumer
|
||||
- A test you can't make green after honest debugging (don't fudge — debug)
|
||||
- A discovered bug not in your plan
|
||||
- Anything destructive (per CLAUDE.md)
|
||||
- Before opening the PR for review
|
||||
|
||||
## Final steps before REVIEW-READY
|
||||
|
||||
Run the project's full validation:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-b
|
||||
cargo build
|
||||
cargo test
|
||||
cargo test -p relicario-core
|
||||
cargo test -p relicario-cli --test basic_flows
|
||||
cargo test -p relicario-cli --test edit_and_history
|
||||
cargo test -p relicario-cli --test attachments
|
||||
cargo test -p relicario-cli --test settings
|
||||
cargo test -p relicario-cli --test vault_detection
|
||||
cargo build -p relicario-wasm --target wasm32-unknown-unknown
|
||||
cargo run -p relicario-cli -- --help
|
||||
cargo run -p relicario-cli -- generate --length 32
|
||||
```
|
||||
|
||||
All must be green. The CLI integration suite covers the surface area touched by the split + git_run sweep; pay particular attention to `basic_flows` and `edit_and_history` for regression coverage.
|
||||
|
||||
Then push and open the PR:
|
||||
|
||||
```bash
|
||||
git push -u origin feature/arch-followup-stream-b-cli-restructure
|
||||
gh pr create --base main --head feature/arch-followup-stream-b-cli-restructure \
|
||||
--title "refactor(cli): split main.rs into commands/ + git_run helper + parsers→core (Stream B)" \
|
||||
--body "$(cat <<'EOF'
|
||||
## Summary
|
||||
|
||||
Stream B of the architecture-review-followup. The single biggest readability lift in the bundle:
|
||||
|
||||
- **P1.2** — `crates/relicario-cli/src/main.rs` (2641 LOC) split into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs` + `prompt.rs` + `parse.rs`. `main.rs` keeps clap definitions + dispatcher.
|
||||
- **P1.3** — `helpers::git_run(repo, args, context)` with stderr capture; ~16 duplicated bail sites swept.
|
||||
- **P1.10** — `parse_month_year`, `base32_decode_lenient` (folded into a new `relicario_core::base32` module alongside DEV-A's P2 dedup), `guess_mime` migrated to `relicario-core`. Re-exported through `relicario-wasm` via `#[wasm_bindgen]` for future extension consumption.
|
||||
- **CLI P2 cluster** — `build_*_item` helper compression, `Vault::after_manifest_change`, `ParamsFile` dedup, batched purge.
|
||||
|
||||
## Synthesis references
|
||||
|
||||
- `docs/superpowers/reviews/2026-05-04-architecture-review.md` — P1.2, P1.3, P1.10 + DEV-B's CLI P2 cluster + DEV-A's base32 dedup
|
||||
- `docs/superpowers/specs/2026-05-04-cli-restructure-design.md` — Plan B
|
||||
|
||||
## New WASM surface (for future Stream C consumption)
|
||||
|
||||
The extension does NOT consume these in this round. A future plan should wire them up via `wasm.d.ts` regeneration:
|
||||
- `parse_month_year` — for QR-import / smart-input flows
|
||||
- `base32_encode_rfc4648` / `base32_decode_rfc4648` — for TOTP / future QR work
|
||||
- `guess_mime_for_extension` — for attachment MIME detection
|
||||
|
||||
## Test plan
|
||||
|
||||
- [x] `cargo build` green
|
||||
- [x] `cargo test` green (workspace-wide)
|
||||
- [x] `cargo test -p relicario-core` green (new base32 module + parser tests)
|
||||
- [x] `cargo test -p relicario-cli --test basic_flows` green (regression on the split)
|
||||
- [x] `cargo test -p relicario-cli --test edit_and_history` green
|
||||
- [x] `cargo test -p relicario-cli --test attachments` green
|
||||
- [x] `cargo test -p relicario-cli --test settings` green
|
||||
- [x] `cargo build -p relicario-wasm --target wasm32-unknown-unknown` green (new exports)
|
||||
- [x] `cargo run -p relicario-cli -- --help` displays unchanged surface
|
||||
- [x] `cargo run -p relicario-cli -- generate --length 32` smoke
|
||||
- [x] git_run sweep: every git failure path now prints captured stderr + context
|
||||
- [x] Steam alphabet at `item_types/totp.rs` untouched
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Emit a `## STATUS UPDATE` with `Status: REVIEW-READY` and the PR URL.
|
||||
|
||||
## First action
|
||||
|
||||
After reading the required inputs and setting up the worktree:
|
||||
|
||||
1. Call `read_messages(for="dev-b")` to drain any early inbox messages.
|
||||
2. Emit a `## STATUS UPDATE` confirming setup complete:
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: <iso8601>
|
||||
Branch: feature/arch-followup-stream-b-cli-restructure
|
||||
Task: setup
|
||||
Status: DONE
|
||||
Last commit: <main HEAD sha + first line>
|
||||
Tests: N/A
|
||||
Notes: Worktree at /home/alee/Sources/relicario.arch-followup-stream-b. Synthesis + DEV-B/DEV-A notes + DEV-C boundary section absorbed. Awaiting Plan B at docs/superpowers/specs/2026-05-04-cli-restructure-design.md.
|
||||
```
|
||||
3. **Wait** for the PM's `## DIRECTIVE TO DEV-B` with `Action: PROCEED` and the plan path.
|
||||
4. Read the plan, then start Task 1 using `superpowers:subagent-driven-development`. Phase 1 is the main.rs split — finish it cleanly before any other phase.
|
||||
@@ -0,0 +1,275 @@
|
||||
# Dev C Kickoff Prompt — Architecture Review Followup, Stream C (Extension Restructure)
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement the plan task-by-task once it lands.
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are a **senior developer** owning Stream C for the Relicario architecture-review-followup work. Stream C is the **largest plan in the bundle** (multi-day to multi-week): turn `setup.ts` into a UI that posts SW messages instead of orchestrating WASM directly, split `vault.ts` into focused modules, give `shared/state.ts` a real type contract, deduplicate the SW router helpers, and pick up the in-scope extension P2 cluster.
|
||||
|
||||
A PM in another terminal coordinates you with two other senior devs. With the relay server running, you communicate via `post_message` / `read_messages` directly. **Your plan does not exist yet.** The PM is drafting it as their first action. Set up your worktree, post acknowledgement, and wait for the PM's `PROCEED` directive containing the plan path before starting Task 1.
|
||||
|
||||
## Setup (do this first)
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario
|
||||
git fetch
|
||||
git worktree add /home/alee/Sources/relicario.arch-followup-stream-c -b feature/arch-followup-stream-c-extension-restructure
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-c
|
||||
pwd # should print /home/alee/Sources/relicario.arch-followup-stream-c
|
||||
```
|
||||
|
||||
**Note on `git pull`:** main has uncommitted polish changes from in-flight post-v0.5.1 work, including edits to `extension/src/vault/vault.ts`, `vault.css`, and `shared/glyphs.ts` — files Stream C will touch heavily. **Surface this to the PM as a Question before starting Phase 1** so the user can choose to commit/stash the in-flight work, defer Stream C, or proceed and merge at PR time. The setup above branches from local main HEAD without pulling, so your worktree starts clean of those uncommitted edits.
|
||||
|
||||
**ALL subsequent work happens in `/home/alee/Sources/relicario.arch-followup-stream-c`**. Every subagent prompt MUST begin with `cd /home/alee/Sources/relicario.arch-followup-stream-c` (project memory rule — without the force-cd, subagents may commit to main).
|
||||
|
||||
Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalize "Relicario", default to "yes"/recommended, never run git-destructive commands without asking).
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — synthesis (your scope is **P1.4, P1.5, P1.6, P1.9 + the in-scope extension P2 cluster only**)
|
||||
3. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — full DEV-C reviewer notes (your stream's primary source)
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — read the **"Boundary notes for DEV-C"** section in particular (covers the parity-relevant cross-references, especially the new WASM surface that Plan B will produce)
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-a-notes.md` — light skim for context only
|
||||
6. **Your plan (will land at):** `docs/superpowers/specs/2026-05-04-extension-restructure-design.md` — read once the PM directs you to PROCEED
|
||||
|
||||
## Execution mode
|
||||
|
||||
Use **superpowers:subagent-driven-development**. Fresh subagent per task, two-stage review between tasks. Every subagent prompt MUST start with:
|
||||
```
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-c
|
||||
```
|
||||
…before any other instruction. This is non-negotiable per project memory.
|
||||
|
||||
## Your scope and boundaries
|
||||
|
||||
**In scope:**
|
||||
- P1.4 — `extension/src/setup/setup.ts` (1220 LOC):
|
||||
- Add `create_vault` and `attach_vault` SW messages to `service-worker/router/popup-only.ts` + the message-type union in `shared/messages.ts`
|
||||
- Rewrite `setup.ts` as a UI that posts those messages with gathered config + image bytes (no direct `relicario-wasm` import)
|
||||
- Convert the 6-step procedural wizard into a step-registry pattern: `Array<{ id: StepId; render: (host) => void; attach: (host) => () => void }>`
|
||||
- `clearWizardState()` bound to `beforeunload` and to "return to step 0"
|
||||
- Target ~500 LOC after the rewrite (down from 1220)
|
||||
- P1.5 — split `extension/src/vault/vault.ts` (1027 LOC) into:
|
||||
- `vault-shell.ts` (init, hash routing)
|
||||
- `vault-sidebar.ts` (sidebar render)
|
||||
- `vault-list.ts` (list pane render)
|
||||
- `vault-drawer.ts` (drawer state + render)
|
||||
- `vault-form-wrapper.ts` (form integration)
|
||||
- `vault.ts` keeps only routing + state coordination
|
||||
- **Lift the `vault_locked` RPC intercept into `shared/state.ts`** (or a wrapper around `sendMessage`) so popup and vault tab use the same channel — closes the synthesis P2 about RPC vs `session_expired` event divergence
|
||||
- Reset `state.drawerOpen` at the start of `renderPane` for non-list views
|
||||
- P1.6 — concrete `StateHost` interface in `extension/src/shared/state.ts`:
|
||||
```ts
|
||||
interface StateHost {
|
||||
state: PopupState;
|
||||
navigate: (view: View) => void;
|
||||
popOutToTab(): void;
|
||||
isInTab(): boolean;
|
||||
openVaultTab(hash?: string): void;
|
||||
}
|
||||
```
|
||||
- Make `getState`/`setState` generic over `keyof PopupState`
|
||||
- Throw on `registerHost()` re-register
|
||||
- Export `__resetHostForTests()` helper
|
||||
- P1.9 — extract from both router files:
|
||||
- `loadDeviceSettings`, `loadBlacklist`, `saveBlacklist` → `extension/src/service-worker/storage.ts`
|
||||
- `itemToManifestEntry` (17-line projection) → `extension/src/service-worker/vault.ts`
|
||||
- Import from both `popup-only.ts` and `content-callable.ts`
|
||||
- In-scope extension P2 cluster:
|
||||
- Inactivity-timer reset on content-callable messages (`service-worker/index.ts:76-78`)
|
||||
- Null `state.gitHost` alongside `state.manifest` on session expiry (`service-worker/index.ts:51-58`)
|
||||
- Teardown helper extraction: `settings.ts:56-65` and `settings-vault.ts:15-22` → `teardownSettingsCommon()`
|
||||
- `Promise.allSettled` in `devices.ts:47-50` and `trash.ts:39-46`
|
||||
- MutationObserver debounce in `content/detector.ts:96-103` (`requestIdleCallback` or 200ms timer)
|
||||
- Vault-tab status indicator from new `get_vault_status` SW message returning `{ ahead, behind, lastSyncAt, pendingItems }` (closes the `relicario status` parity gap)
|
||||
|
||||
**Out of scope (other DEVs own these):**
|
||||
- P1.1, JS free-swallow, P1.7, P1.8 — DEV-A (Stream A). **Note:** if A merges first, you'll inherit `impl Drop for SessionHandle`. That's expected and benign.
|
||||
- P1.2, P1.3, P1.10 + the in-scope CLI P2s — DEV-B (Stream B). The new WASM exports (`parse_month_year`, `base32_*`, `guess_mime_for_extension`) that Plan B produces are NOT consumed in this round. Document the future consumer in your plan's "Out of scope" section; a later round wires them up.
|
||||
- Other DEV-C P2/P3 not listed in your scope (e.g. shared-utilities response typing, group-autocomplete escaping, restore_backup payload extract, content-script `fillFields()` ack, content/icon outside-click leak) — explicitly deferred to a future round
|
||||
- Setup-wizard manifest path constants (`VAULT_PATHS`) — folds into your P1.4 work; if convenient include it, else defer
|
||||
- WASM JS-naming snake_case → camelCase rename — explicitly deferred
|
||||
- Any of the 8 "Open architectural decisions" at the bottom of the synthesis
|
||||
|
||||
If you trip over an out-of-scope issue or a new bug while doing your work, file a `## QUESTION TO PM` block and keep moving.
|
||||
|
||||
**Hard rules:**
|
||||
- **P1.6 (state.ts typing) MUST land first internally.** Both P1.4 and P1.5 push through the `StateHost` surface. Plan should call this out as Phase 1.
|
||||
- **`setup.ts` MUST stop importing `relicario-wasm` directly after P1.4.** This is the architectural invariant the synthesis is fixing. After P1.4, the only file in `extension/src/` that imports `relicario-wasm` should be the service worker.
|
||||
- **New SW message names are `create_vault` and `attach_vault`.** Use these exact names everywhere (`shared/messages.ts`, `service-worker/router/popup-only.ts`, `setup.ts`). The PM's coherence pass on the plans confirms naming consistency.
|
||||
- **`vault_locked` unification goes in `shared/state.ts`** (or a wrapper around `sendMessage`). Popup AND vault tab use the same channel after this lands. Two channels for one outcome was the synthesis observation.
|
||||
- **No emoji anywhere in `extension/src/`** (existing project rule from v0.5.1). If you see one while editing, replace with the monochrome glyph from `glyphs.ts`.
|
||||
- **`glyphs.ts` is single source of truth** for icon characters. No inline Unicode literals at call sites.
|
||||
- **Discriminated-union message contract is preserved.** New messages get added to `shared/messages.ts` and the appropriate capability set (`POPUP_ONLY_TYPES` or `CONTENT_CALLABLE_TYPES`). The boundary discipline holds.
|
||||
- **WASM remains snake_case in JS** — no `#[wasm_bindgen(js_name = ...)]` renaming. That's a separate decision (DEV-B/DEV-C P3).
|
||||
- **Test setup is vitest** for the extension (`extension/package.json: "test": "vitest run"`), `bun test` for `tools/relay/`. Do not change runners.
|
||||
- **Synthetic test fixtures only.** No binary blobs.
|
||||
- Do not merge your branch to main. The PM owns merges.
|
||||
- Do not push `--force` or run `git reset --hard`. Per `CLAUDE.md`: ask first.
|
||||
|
||||
## Coordination with Stream B
|
||||
|
||||
Stream B will produce new `relicario-wasm` exports (`parse_month_year`, `base32_*`, `guess_mime_for_extension`). You do NOT consume these in this round — your plan's "Out of scope" section should explicitly call this out and reference the future consumer (likely a smart-input / QR-import / attachment-MIME round). If Stream B's WASM signature for any of these would NOT match what the extension would naturally consume, raise a `## QUESTION TO PM` so it can be reconciled before Stream B merges.
|
||||
|
||||
If Stream A merges first and you inherit `impl Drop for SessionHandle` plus the JS free-swallow removal: that's benign. Your `.free()` callsites should already be `wasm.lock(handle)` first per DEV-A's audit.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-c"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-c"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-c")`. After emitting any status/question block: `post_message(from="dev-c", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"dev-c","to":"pm","kind":"status","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"dev-c"}'
|
||||
```
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of four terminals. Before starting each task, call `read_messages(for="dev-c")` to drain your inbox.
|
||||
|
||||
When posting a status update, call `post_message(from="dev-c", to="pm", kind="status", body="...")` with the body:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-C
|
||||
Time: <iso8601 like 2026-05-04T14:30:00-07:00>
|
||||
Branch: feature/arch-followup-stream-c-extension-restructure
|
||||
Task: <number / short name>
|
||||
Status: STARTED | IN-PROGRESS | DONE | BLOCKED | REVIEW-READY
|
||||
Last commit: <short sha + first line of message>
|
||||
Tests: <green | red (which failed) | N/A>
|
||||
Notes: <anything PM needs to know — keep to 3 sentences max>
|
||||
```
|
||||
|
||||
**When you need PM input mid-task:**
|
||||
```
|
||||
## QUESTION TO PM — DEV-C
|
||||
Time: <iso8601>
|
||||
Context: <what task, what decision point>
|
||||
Options: <A: ... / B: ... / C: ...>
|
||||
Recommended: <your pick + one-sentence rationale>
|
||||
Blocker: yes | no
|
||||
```
|
||||
|
||||
**You'll receive:** `## DIRECTIVE TO DEV-C` blocks from the PM. The first one will say `Action: PROCEED` with the plan path once the PM has drafted it. Acknowledge and start Task 1.
|
||||
|
||||
## Authority within the plan
|
||||
|
||||
You don't need PM permission to:
|
||||
- Execute task-to-task per the plan once you have it
|
||||
- Make implementation decisions consistent with the plan and synthesis
|
||||
- Write tests, refactor your own code, fix bugs you introduce
|
||||
- Push commits to your feature branch
|
||||
|
||||
You **do** escalate to PM when:
|
||||
- A scope question outside the plan
|
||||
- A WASM signature mismatch with what Stream B is producing
|
||||
- A test you can't make green after honest debugging (don't fudge — debug)
|
||||
- A discovered bug not in your plan
|
||||
- The in-flight uncommitted changes on `vault.ts`/`vault.css`/`glyphs.ts` need resolution before a merge
|
||||
- Anything destructive (per CLAUDE.md)
|
||||
- Before opening the PR for review
|
||||
|
||||
## Final steps before REVIEW-READY
|
||||
|
||||
Run the project's full validation:
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario.arch-followup-stream-c
|
||||
cd extension
|
||||
bun run test
|
||||
bun run build
|
||||
bun run build:firefox
|
||||
cd ..
|
||||
cargo build -p relicario-wasm --target wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
All must be green. Vitest covers the new `StateHost` typing, the message-router dedup, and the wizard step registry.
|
||||
|
||||
Then sweep for emoji and in-flight collision:
|
||||
|
||||
```bash
|
||||
grep -rn '\U0001F\|🔑\|📝\|🪪\|💳\|🗝\|📄\|⏱️\|🖥\|🔐\|📎' /home/alee/Sources/relicario.arch-followup-stream-c/extension/src/ 2>/dev/null
|
||||
```
|
||||
|
||||
Expected: no output (project rule).
|
||||
|
||||
Then push and open the PR:
|
||||
|
||||
```bash
|
||||
git push -u origin feature/arch-followup-stream-c-extension-restructure
|
||||
gh pr create --base main --head feature/arch-followup-stream-c-extension-restructure \
|
||||
--title "refactor(ext): setup-via-SW + vault.ts split + state.ts typing + SW router dedup (Stream C)" \
|
||||
--body "$(cat <<'EOF'
|
||||
## Summary
|
||||
|
||||
Stream C of the architecture-review-followup. The largest plan in the bundle — turns three "code lies about the architecture" surfaces into uniform readable modules:
|
||||
|
||||
- **P1.4** — `extension/src/setup/setup.ts` no longer imports `relicario-wasm` directly. New `create_vault` / `attach_vault` SW messages do the crypto orchestration. The 6-step wizard is now a step registry. ~500 LOC down from 1220.
|
||||
- **P1.5** — `extension/src/vault/vault.ts` (1027 LOC) split into `vault-shell.ts` / `vault-sidebar.ts` / `vault-list.ts` / `vault-drawer.ts` / `vault-form-wrapper.ts`. `vault_locked` RPC intercept lifted into `shared/state.ts` so popup and vault tab share one channel.
|
||||
- **P1.6** — `extension/src/shared/state.ts` has a concrete `StateHost` interface; `getState`/`setState` are generic over `keyof PopupState`; double-registration guard + `__resetHostForTests` helper.
|
||||
- **P1.9** — duplicated SW router helpers extracted: `service-worker/storage.ts` for the three storage helpers, `service-worker/vault.ts` for `itemToManifestEntry`.
|
||||
- **Extension P2 cluster** — inactivity-timer reset on content-callable messages, `state.gitHost` clear on session expiry, `teardownSettingsCommon()`, `Promise.allSettled` in devices/trash, MutationObserver debounce in content/detector, vault-tab status indicator (closes `relicario status` parity gap).
|
||||
|
||||
## Synthesis references
|
||||
|
||||
- `docs/superpowers/reviews/2026-05-04-architecture-review.md` — P1.4, P1.5, P1.6, P1.9 + DEV-C's extension P2 cluster
|
||||
- `docs/superpowers/specs/2026-05-04-extension-restructure-design.md` — Plan C
|
||||
|
||||
## Future-round consumer (NOT in this PR)
|
||||
|
||||
Plan B produces new `relicario-wasm` exports (`parse_month_year`, `base32_*`, `guess_mime_for_extension`). A later round will wire them up via `wasm.d.ts` regeneration and add SW message handlers. Out of scope here.
|
||||
|
||||
## Test plan
|
||||
|
||||
- [x] `bun run test` green in `extension/`
|
||||
- [x] `bun run build` green
|
||||
- [x] `bun run build:firefox` green
|
||||
- [x] `cargo build -p relicario-wasm --target wasm32-unknown-unknown` green
|
||||
- [x] No emoji anywhere in `extension/src/` (grep clean)
|
||||
- [x] `setup.ts` no longer imports `relicario-wasm`
|
||||
- [x] `vault.ts` LOC dropped substantially; new modules each under ~300 LOC
|
||||
- [x] Vault tab and popup both use one channel for `vault_locked` (no RPC intercept divergence)
|
||||
- [x] StateHost interface concrete; tests cover double-registration guard and reset helper
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Emit a `## STATUS UPDATE` with `Status: REVIEW-READY` and the PR URL.
|
||||
|
||||
## First action
|
||||
|
||||
After reading the required inputs and setting up the worktree:
|
||||
|
||||
1. Call `read_messages(for="dev-c")` to drain any early inbox messages.
|
||||
2. Emit a `## STATUS UPDATE` confirming setup complete:
|
||||
```
|
||||
## STATUS UPDATE — DEV-C
|
||||
Time: <iso8601>
|
||||
Branch: feature/arch-followup-stream-c-extension-restructure
|
||||
Task: setup
|
||||
Status: DONE
|
||||
Last commit: <main HEAD sha + first line>
|
||||
Tests: N/A
|
||||
Notes: Worktree at /home/alee/Sources/relicario.arch-followup-stream-c. Synthesis + DEV-C notes + DEV-B boundary section absorbed. Awaiting Plan C at docs/superpowers/specs/2026-05-04-extension-restructure-design.md.
|
||||
```
|
||||
3. **Also emit a `## QUESTION TO PM`** about the in-flight uncommitted edits to `vault.ts` / `vault.css` / `glyphs.ts` on main:
|
||||
```
|
||||
## QUESTION TO PM — DEV-C
|
||||
Time: <iso8601>
|
||||
Context: setup, before Phase 1
|
||||
Options: A: PM/user commits or stashes the in-flight v0.5.x polish on main before I start, so my worktree has a stable baseline. B: I proceed and rebase/merge those changes at PR time. C: PM defers Stream C until the in-flight work is committed.
|
||||
Recommended: A — clean baseline avoids merge churn during the largest plan in the bundle.
|
||||
Blocker: no — I can read the plan and start Phase 1 (P1.6 state.ts typing) which doesn't touch the in-flight files. Resolution needed before Phase 2 (P1.5 vault.ts split).
|
||||
```
|
||||
4. **Wait** for the PM's `## DIRECTIVE TO DEV-C` with `Action: PROCEED` and the plan path.
|
||||
5. Read the plan, then start Task 1 using `superpowers:subagent-driven-development`. Phase 1 is P1.6 (state.ts typing) — finish it cleanly before P1.4 / P1.5.
|
||||
@@ -0,0 +1,133 @@
|
||||
# Planning Kickoff Prompt — Architecture-Review Follow-up
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are an architect drafting **three implementation plans** that follow up on the whole-codebase architecture review committed to `main` on 2026-05-04 (`061facd docs(reviews): whole-codebase architecture audit 2026-05-04`). Three reviewers (DEV-A: Rust core; DEV-B: Rust consumers; DEV-C: TypeScript) walked the codebase; the PM synthesized 10 P1s plus a long P2/P3 tail. Your job is to convert those findings into three discrete, well-scoped plans that the user (or future agents) can execute.
|
||||
|
||||
This is **planning-only work.** Do not modify the codebase being planned. Do not commit. Do not ship anything. Each plan is a markdown file in `docs/superpowers/specs/` and that is the only output.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Stay on `main`. Do not create branches or worktrees.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalization rules, autonomy defaults, never run git-destructive commands without asking).
|
||||
- The working tree has uncommitted changes from in-flight v0.5.x work (manifests, vault.ts/css, glyphs, relay tooling, Cargo.toml version bumps). Treat them as "in flight, ignore" — do not include them in any plan.
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules (Spanish flourish, capitalization, autonomy)
|
||||
2. `docs/superpowers/specs/2026-04-11-relicario-design.md` — foundational design spec (threat model, crypto pipeline, format)
|
||||
3. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — **PM synthesis. This is the canonical source. Every plan below must trace its scope back to specific findings here.**
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-a-notes.md` — DEV-A's full notes (Rust core)
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — DEV-B's full notes (CLI/server/WASM), especially the "Boundary notes for DEV-C" section
|
||||
6. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — DEV-C's full notes (extension + relay), especially the "Boundary notes for DEV-B" section
|
||||
|
||||
Also skim two existing plan docs to match the format and tone:
|
||||
- `docs/superpowers/specs/2026-05-02-v0.5.0-polish-harden-design.md`
|
||||
- `docs/superpowers/specs/2026-05-03-v0.5.x-ux-polish-and-recovery-qr-design.md`
|
||||
|
||||
## What to produce
|
||||
|
||||
Three plan files, all under `docs/superpowers/specs/`:
|
||||
|
||||
### Plan A — Security & docs polish PR
|
||||
**Filename:** `docs/superpowers/specs/2026-05-04-security-polish-design.md`
|
||||
**Scope (drawn from synthesis):** P1.1 (`SessionHandle` `impl Drop` + Rust `wasm-bindgen-test` + extension `.free()` callsite audit), the partner JS-side fix at `service-worker/session.ts:26` (remove the `try { current.free() }` swallow), P1.7 (`recovery_qr.rs` documentation to match `crypto.rs`/`backup.rs` density), and the launcher fix DEV-C suspected at `tools/relay/start.sh:80` (4-window dev-c support; queue.test.ts assertion already fixed in `061facd`). Goal: one short PR, all-S-effort items, ships in under a day. This is the security-flavored quick win that goes first; nothing in B or C should depend on it.
|
||||
|
||||
### Plan B — CLI restructure
|
||||
**Filename:** `docs/superpowers/specs/2026-05-04-cli-restructure-design.md`
|
||||
**Scope:** P1.2 (split `crates/relicario-cli/src/main.rs` 2641 LOC into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs` + `prompt.rs` + `parse.rs`, leaving `main.rs` as clap definitions + dispatcher), P1.3 (`helpers::git_run(repo, args, context)` with stderr capture; sweep the ~16 duplicated bail sites), P1.10 (migrate `parse_month_year`, `base32_decode_lenient`, `guess_mime` to `relicario-core` and re-export through `relicario-wasm` for the extension; pair with the core base32 dedup from DEV-A's P2), plus the in-scope CLI P2s (`build_*_item` helper compression, `refresh_groups_cache` discipline via `Vault::after_manifest_change`, `ParamsFile` dedup between `main.rs:2287` and `session.rs:114`, batched purge in `cmd_purge`/`cmd_trash_empty`). Sequencing matters here: the `main.rs` split must land first because every other P2 in this plan touches files that don't exist yet until the split happens. Goal: M-L effort, multi-day plan; "single biggest readability lift" per the synthesis.
|
||||
|
||||
### Plan C — Extension restructure
|
||||
**Filename:** `docs/superpowers/specs/2026-05-04-extension-restructure-design.md`
|
||||
**Scope:** P1.4 (`extension/src/setup/setup.ts` 1220 LOC: add `create_vault` and `attach_vault` SW messages; rewrite setup as a UI that posts those messages with gathered config + image bytes; convert the 6-step procedural wizard into a step-registry pattern `{ id, render, attach }[]`; add `clearWizardState()` on `beforeunload`), P1.5 (split `extension/src/vault/vault.ts` 1027 LOC into `vault-shell.ts` / `vault-sidebar.ts` / `vault-list.ts` / `vault-drawer.ts` / `vault-form-wrapper.ts`; lift the `vault_locked` RPC intercept into `shared/state.ts` so popup and vault use one channel; reset `state.drawerOpen` on non-list `renderPane`), P1.6 (concrete `StateHost` interface in `shared/state.ts` with `state: PopupState`, `navigate`, `popOutToTab`, `isInTab`, `openVaultTab`; generic `getState`/`setState` over `keyof PopupState`; double-registration guard + `__resetHostForTests` helper), P1.9 (extract duplicated SW router helpers — `loadDeviceSettings`/`loadBlacklist`/`saveBlacklist` to `service-worker/storage.ts`; `itemToManifestEntry` to `service-worker/vault.ts`), plus the in-scope extension P2s (inactivity-timer reset on content-callable messages; `state.gitHost` clear on session expiry; teardown helper extraction; `Promise.allSettled` in devices/trash; mutation-observer debounce in content/detector.ts; vault-tab status indicator from `get_vault_status` for the `relicario status` parity gap). Sequencing: P1.6 (state.ts typing) is a precondition for P1.4 and P1.5 because lifting `vault_locked` and adding setup-via-SW both push through that surface. Goal: largest plan, multi-day to multi-week.
|
||||
|
||||
## What's explicitly NOT in these three plans
|
||||
|
||||
- The full P2/P3 tail outside what's listed above. The synthesis doc is canonical; if a P2 isn't named in one of the three scopes above, it doesn't go in. Future plans can pick those up.
|
||||
- WASM JS-naming snake_case → camelCase (DEV-B/DEV-C P3) — defer to a separate decision, not these plans.
|
||||
- The 8 "Open architectural decisions" at the bottom of the synthesis — those are user-judgement calls, not implementation tasks.
|
||||
- Anything that requires touching the in-flight uncommitted v0.5.x work (manifests, glyphs, vault.css, relay tooling beyond start.sh).
|
||||
|
||||
## Plan format (match the existing specs)
|
||||
|
||||
Each plan file should have, at minimum:
|
||||
|
||||
```markdown
|
||||
# <Title> — Design
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Status:** Proposed
|
||||
**Source:** docs/superpowers/reviews/2026-05-04-architecture-review.md (P1.X, P1.Y, ...)
|
||||
**Effort estimate:** S | M | L
|
||||
|
||||
## Summary
|
||||
2-4 sentences: what this plan accomplishes and why it matters for the user's stated goal ("make this app's architecture logical and readable for someone who doesn't know Rust but wants to learn by tinkering").
|
||||
|
||||
## Findings addressed
|
||||
Bullet list, each entry citing the synthesis P-tag, the reviewer who found it, and the file:line.
|
||||
|
||||
## Approach
|
||||
The architectural shape of the work — what gets extracted, what gets created, what gets renamed. Include directory trees / module diagrams if it helps a reader follow the layout change.
|
||||
|
||||
## Implementation phases
|
||||
Numbered phases. Each phase:
|
||||
- **Goal:** one-sentence outcome
|
||||
- **Changes:** specific files touched, new files created, with paths
|
||||
- **Tests:** what gets added or moved (synthetic fixtures only — no binary blobs, per project convention)
|
||||
- **Effort:** S/M/L for the phase
|
||||
- **Depends on:** other phases, or "none"
|
||||
|
||||
## Risks and mitigations
|
||||
What can break, especially across the CLI/extension parity boundary. Cite specific findings.
|
||||
|
||||
## Out of scope
|
||||
Explicit list of adjacent things this plan does NOT touch.
|
||||
|
||||
## Done criteria
|
||||
Checklist a reviewer can use to confirm the plan shipped.
|
||||
```
|
||||
|
||||
Mirror the tone and depth of `2026-05-02-v0.5.0-polish-harden-design.md` and `2026-05-03-v0.5.x-ux-polish-and-recovery-qr-design.md`. Use the same heading conventions.
|
||||
|
||||
## Execution approach
|
||||
|
||||
**Use subagents.** Per the user's standing preference (CLAUDE.md memory: "Default to subagent-driven execution — for any multi-task plan use subagent-driven mode without asking"), drafting these plans is parallel work. Spawn three `Plan` subagents in parallel (single message, three tool calls), one per plan file. Each subagent reads the same shared inputs (synthesis + relevant notes file(s)), then writes only its assigned plan file. Plan B and Plan C subagents should each receive the relevant cross-boundary section of the *other* reviewer's notes ("Boundary notes for DEV-C" goes to Plan C's drafter; "Boundary notes for DEV-B" goes to Plan B's drafter) so the parity boundary is respected.
|
||||
|
||||
After the three subagents return, do a coherence pass yourself:
|
||||
- Confirm Plan A doesn't depend on B or C
|
||||
- Confirm Plan B's `parse_month_year`/`base32` migration to core is reachable from Plan C's WASM consumers (or note explicitly that Plan C will pick up the WASM exports in a later phase)
|
||||
- Confirm Plan C's setup-via-SW migration cites the same `create_vault`/`attach_vault` message names everywhere
|
||||
|
||||
Each subagent prompt **must** start with `cd /home/alee/Sources/relicario` (project memory rule — without the force-cd, subagents may write to the wrong tree).
|
||||
|
||||
## Hard constraints
|
||||
|
||||
- **Read-only on the codebase being planned.** No `cargo`, `bun`, or any other write commands beyond writing the three plan files.
|
||||
- **No commits.** The user commits when ready.
|
||||
- **No git operations.** Don't even `git status` unless you have a specific reason.
|
||||
- **Three files, no fewer, no more.** If a finding doesn't fit any of the three scopes above, leave it out — future plans handle it.
|
||||
- **Spanish flourish in replies (1-2 phrases per reply with `[translation]` brackets), per CLAUDE.md.** Do not put Spanish into the plan files themselves — those are project artifacts.
|
||||
|
||||
## Done criteria
|
||||
|
||||
Before posting your final summary:
|
||||
- [ ] All three plan files exist under `docs/superpowers/specs/` with the exact filenames specified above
|
||||
- [ ] Each plan cites at least one specific P1 from the synthesis in its "Findings addressed" section
|
||||
- [ ] Each plan has phases, each phase has effort, each phase names specific files
|
||||
- [ ] Plan A is independent (no dependencies on B or C)
|
||||
- [ ] Plan B and Plan C call out the parity-relevant cross-references explicitly
|
||||
- [ ] You did NOT modify any code, run any test, or commit anything
|
||||
- [ ] You ask the user whether to commit the three plan files (do not commit unprompted)
|
||||
|
||||
## First action
|
||||
|
||||
1. Read the synthesis (`docs/superpowers/reviews/2026-05-04-architecture-review.md`) end-to-end. Internalize the 10 P1s and the cross-cutting themes.
|
||||
2. Skim the three per-reviewer notes files for the file:line context the synthesis abbreviates.
|
||||
3. Skim the two existing plan docs above to absorb the format.
|
||||
4. Tell the user what you absorbed in 3-5 sentences.
|
||||
5. Spawn three `Plan` subagents in parallel with the scopes specified above.
|
||||
6. Do the coherence pass.
|
||||
7. Ask the user whether to commit the three plan files.
|
||||
@@ -0,0 +1,211 @@
|
||||
# PM Kickoff Prompt — Architecture Review Followup (2026-05-04)
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are the **project manager** for the Relicario architecture-review-followup work. Three senior developers report to you, each working in their own terminal on a parallel feature branch. The user runs all four terminals.
|
||||
|
||||
This release has no version tag — it's a structural-cleanup bundle from the 2026-05-04 architecture audit (commit `061facd`). The goal is to make the codebase uniformly readable for a smart developer who doesn't know Rust but wants to learn by tinkering. There is no merge freeze, no CHANGELOG entry needed, and no tag at the end unless the user requests one.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Branch: stay on `main`. Do not check out feature branches.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalize "Relicario", default to "yes"/recommended, never run git-destructive commands without asking, default to subagent-driven execution).
|
||||
- **Working-tree note:** main has uncommitted polish changes from in-flight post-v0.5.1 work (glyphs/vault/relay/manifests/Cargo.toml version bumps, plus the four `architecture-review-*-prompt.md` files this session is generating). The synthesis explicitly tags these "in flight, ignore" — none of the three plans should include them. Also: Stream C touches `extension/src/vault/vault.ts`, `vault.css`, and `shared/glyphs.ts` which currently have uncommitted edits on main. Surface this to the user before unlocking DEV-C; either commit/stash the in-flight changes or note that C will need to merge them in at PR time.
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/reviews/2026-05-04-architecture-review.md` — **PM synthesis. This is the canonical source. Every plan must trace its scope back to specific findings here.**
|
||||
3. `docs/superpowers/reviews/2026-05-04-dev-a-notes.md` — full DEV-A notes (Rust core)
|
||||
4. `docs/superpowers/reviews/2026-05-04-dev-b-notes.md` — full DEV-B notes (CLI/server/WASM), especially the "Boundary notes for DEV-C" section
|
||||
5. `docs/superpowers/reviews/2026-05-04-dev-c-notes.md` — full DEV-C notes (extension + relay), especially the "Boundary notes for DEV-B" section
|
||||
6. `docs/superpowers/specs/2026-05-02-v0.5.0-polish-harden-design.md` and `docs/superpowers/specs/2026-05-03-v0.5.x-ux-polish-and-recovery-qr-design.md` — format reference for the plan docs you will draft
|
||||
|
||||
## Stream overview
|
||||
|
||||
| Stream | Branch | Owner | Plan file (to be drafted) | Items |
|
||||
|--------|--------|-------|---------------------------|-------|
|
||||
| A — Security & docs polish | `feature/arch-followup-stream-a-security-polish` | DEV-A | `docs/superpowers/specs/2026-05-04-security-polish-design.md` | P1.1, JS free-swallow fix, P1.7, P1.8 |
|
||||
| B — CLI restructure | `feature/arch-followup-stream-b-cli-restructure` | DEV-B | `docs/superpowers/specs/2026-05-04-cli-restructure-design.md` | P1.2, P1.3, P1.10 + 4 in-scope CLI P2s |
|
||||
| C — Extension restructure | `feature/arch-followup-stream-c-extension-restructure` | DEV-C | `docs/superpowers/specs/2026-05-04-extension-restructure-design.md` | P1.4, P1.5, P1.6, P1.9 + in-scope ext P2s |
|
||||
|
||||
## Your authority
|
||||
|
||||
- Approve or deny scope changes from devs
|
||||
- Review and merge PRs from each stream's feature branch
|
||||
- **Draft the three plan docs as your first hands-on action.** This is the single biggest piece of work you own personally.
|
||||
- Edit `docs/`, `CLAUDE.md`, or other doc artifacts as needed; do not write feature code
|
||||
|
||||
## Your boundaries
|
||||
|
||||
- Don't write feature code yourself. Edits to docs / `CLAUDE.md` are fine.
|
||||
- Don't deviate from the synthesis scope without user approval.
|
||||
- Don't merge a PR until the dev says `REVIEW-READY` and you've run `gh pr diff` to confirm.
|
||||
- Don't tag (none planned for this work).
|
||||
- Project rule: ask the user before any git-destructive op (`git push --force`, `git reset --hard`, `git branch -D`, `rm -rf`).
|
||||
|
||||
## Cross-stream coordination
|
||||
|
||||
- **Stream A is independent** — no dependencies on B or C. Merge first if it's ready.
|
||||
- **Stream B's parser→core migration** (`parse_month_year`, `base32_decode_lenient`, `guess_mime` + the base32 dedup from DEV-A's P2) produces new `relicario-core` functions and re-exports them through `relicario-wasm`. Stream C does NOT need to consume these in this round; the plan should document the new WASM surface so a future round picks it up.
|
||||
- **Stream C's internal sequencing**: P1.6 (`shared/state.ts` typing) must land before P1.4 (setup-via-SW migration) and P1.5 (`vault.ts` split). This is internal to Plan C, not a cross-stream concern.
|
||||
- **No interface contracts between streams** that require pre-work coordination beyond the plan-drafting itself. Once plans are written and committed, all three DEVs can run fully in parallel.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; `from` is always `"pm"` for you
|
||||
- `read_messages(for)` — drain your inbox; call with `for="pm"` before each action
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. After sending any directive, call `post_message(from="pm", to="dev-X", kind="directive", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session (this happens when the relay server was not running when your session opened), use the Python shim instead:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"pm"}'
|
||||
```
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of four terminals. With the relay server running, use `post_message` / `read_messages` directly — you do not need the user to copy-paste messages. Call `read_messages(for="pm")` before every action.
|
||||
|
||||
**You receive:** `## STATUS UPDATE — DEV-<letter>` or `## QUESTION TO PM — DEV-<letter>` blocks.
|
||||
|
||||
**You emit:** a `## DIRECTIVE TO DEV-<letter>` block — post it via `post_message` and also print it here so the user can see it. Format:
|
||||
|
||||
```
|
||||
## DIRECTIVE TO DEV-<letter>
|
||||
Time: <iso8601>
|
||||
Action: PROCEED | HOLD | RESCOPE | REVIEW-COMPLETE | MERGE-APPROVED
|
||||
Notes: <one paragraph max>
|
||||
Next: <one concrete instruction or "continue plan">
|
||||
```
|
||||
|
||||
When asked "status?" by the user, give a current rollup:
|
||||
|
||||
```
|
||||
## RELEASE STATUS — Architecture Review Followup
|
||||
Devs: <per-dev one-line state>
|
||||
PM: <what you're working on>
|
||||
Blockers: <list, or "none">
|
||||
Next milestone: <e.g., "Plan A drafted", "DEV-B REVIEW-READY">
|
||||
```
|
||||
|
||||
## Reviewing PRs
|
||||
|
||||
When a dev posts `Action: REVIEW-READY` with a PR URL:
|
||||
1. `gh pr view <url>` to read description and CI status
|
||||
2. `gh pr diff <url>` to read changes
|
||||
3. Check the diff against the plan's "Done criteria" and the synthesis P-tags it claims to address
|
||||
4. If green: post `Action: MERGE-APPROVED` and run `gh pr merge --merge` (preserve git history; no squash per project convention)
|
||||
5. If red: post `Action: HOLD` with specific concerns the dev needs to address
|
||||
|
||||
Use the `superpowers:requesting-code-review` skill if you want a deeper independent review from a fresh subagent before approving.
|
||||
|
||||
## Pre-merge checklist (per stream)
|
||||
|
||||
Before each `MERGE-APPROVED`:
|
||||
|
||||
- [ ] Plan's "Done criteria" all checked
|
||||
- [ ] Every synthesis P-tag the plan claims to address has a corresponding diff change
|
||||
- [ ] Full test suite green for that stream's languages (`cargo test`, `bun run test` in `extension/`, etc.)
|
||||
- [ ] No regression in CLI/extension parity (synthesis section "CLI/extension parity status")
|
||||
- [ ] No emoji introduced anywhere in `extension/src/` (existing project rule)
|
||||
|
||||
## First action — draft the three plan docs
|
||||
|
||||
Before unlocking any DEV to start work, you must draft the three plan files. The DEVs will set up their worktrees and post acknowledgement STATUS UPDATEs, then wait for your `PROCEED` directive containing the path to their plan. Until the plans exist, the DEVs are blocked.
|
||||
|
||||
**Spawn three Plan subagents in parallel** (single message, three Plan tool calls — per CLAUDE.md memory rule "default to subagent-driven execution"). Each subagent prompt **must start with** `cd /home/alee/Sources/relicario` (project memory rule — without the force-cd, subagents may write to the wrong tree).
|
||||
|
||||
Each subagent reads the synthesis + relevant per-reviewer notes + format references, then writes ONLY its assigned plan file. None modify code, run tests, or commit.
|
||||
|
||||
### Plan A subagent scope
|
||||
|
||||
**Filename:** `docs/superpowers/specs/2026-05-04-security-polish-design.md`
|
||||
**Effort:** S — under-a-day PR
|
||||
**Items:**
|
||||
- P1.1 — `impl Drop for SessionHandle { fn drop(&mut self) { session::remove(self.0); } }` in `crates/relicario-wasm/src/lib.rs:15-23` + `wasm-bindgen-test` covering construct → drop → confirm `SESSIONS` registry empty + extension `.free()` callsite audit confirming `wasm.lock(handle)` happens first regardless
|
||||
- JS partner fix at `extension/src/service-worker/session.ts:26` — remove the `try { current.free() }` swallow so exceptions propagate (or log + counter)
|
||||
- P1.7 — `crates/relicario-core/src/recovery_qr.rs` documentation pass: module-level `//!` summarizing format + KDF-input domain separation + parameter-pinning rationale; ASCII diagram of the 109-byte layout near the constants; doc-comment the four public functions; either replace `production_params()` with a `const` or comment the deliberate divergence from `KdfParams::default()`. Match the density of `crypto.rs` / `imgsecret.rs` / `backup.rs` / `tar_safe.rs`.
|
||||
- P1.8 — `tools/relay/start.sh:80` launcher fix for the dev-c fourth window (queue.test.ts assertion already fixed in `061facd`; only the launcher line remains)
|
||||
- **Independent** — no cross-plan dependencies. Plan A goes first.
|
||||
|
||||
### Plan B subagent scope
|
||||
|
||||
**Filename:** `docs/superpowers/specs/2026-05-04-cli-restructure-design.md`
|
||||
**Effort:** M-L — multi-day. "Single biggest readability lift" per synthesis.
|
||||
**Items:**
|
||||
- P1.2 — split `crates/relicario-cli/src/main.rs` (2641 LOC) into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs` + `prompt.rs` (six `prompt_*` helpers + `prompt_secret`) + `parse.rs` (the three pure parsers). `main.rs` keeps clap definitions + dispatcher (~470 lines).
|
||||
- P1.3 — add `helpers::git_run(repo, args, context)` that uses `.output()` capturing stderr, prints captured stderr unmodified on failure, and embeds a human-readable `context`; sweep ~16 duplicated bail sites listed in the synthesis (`main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` and others)
|
||||
- P1.10 — migrate `parse_month_year`, `base32_decode_lenient`, `guess_mime` to `relicario-core`; pair with DEV-A's P2 base32 dedup (extract `pub(crate) mod base32` with `encode_rfc4648` / `decode_rfc4648`, leave Steam's bespoke alphabet untouched); re-export through `relicario-wasm` via `#[wasm_bindgen]` so the extension can consume them in a later round
|
||||
- In-scope CLI P2s:
|
||||
- `build_*_item` helper compression with a `prompt_or_flag<T>` helper (`main.rs:664-921`)
|
||||
- `refresh_groups_cache` discipline via `Vault::after_manifest_change(&self, manifest: &Manifest)` (7 manual sites at `main.rs:641, 998, 1123, 1197, 1414, 1432, 1474`)
|
||||
- `ParamsFile` dedup between `main.rs:2287` (write side, has `aead`/`salt_path`/`format_version`) and `session.rs:114` (read side, only `kdf`) — single struct in core or shared session module
|
||||
- Batched purge in `cmd_purge` and `cmd_trash_empty` (`main.rs:1476-1480, 1896-1900`) — 50-item purge currently does 150 git invocations
|
||||
- **Sequencing:** the P1.2 main.rs split must land first because every other P2 in this plan touches files that don't exist yet until the split happens. Plan should call this out as Phase 1.
|
||||
- **Receives:** the "Boundary notes for DEV-B" section from `dev-c-notes.md`
|
||||
|
||||
### Plan C subagent scope
|
||||
|
||||
**Filename:** `docs/superpowers/specs/2026-05-04-extension-restructure-design.md`
|
||||
**Effort:** L — multi-day to multi-week. Largest plan.
|
||||
**Items:**
|
||||
- P1.4 — `extension/src/setup/setup.ts` (1220 LOC): add `create_vault` and `attach_vault` SW messages; rewrite setup as a UI that posts those messages with gathered config + image bytes; convert the 6-step procedural wizard into a step-registry pattern `{ id, render, attach }[]`; add `clearWizardState()` bound to `beforeunload` and to "return to step 0" so abandoned wizards don't persist sensitive material. Setup must stop importing `relicario-wasm` directly.
|
||||
- P1.5 — split `extension/src/vault/vault.ts` (1027 LOC) into `vault-shell.ts` / `vault-sidebar.ts` / `vault-list.ts` / `vault-drawer.ts` / `vault-form-wrapper.ts`, leaving `vault.ts` to own only routing and state. Lift the `vault_locked` RPC intercept into `shared/state.ts` (or a wrapper around `sendMessage`) so popup and vault use one path; reset `state.drawerOpen` at the start of `renderPane` for non-list views.
|
||||
- P1.6 — concrete `StateHost` interface in `shared/state.ts`: `state: PopupState`, `navigate: (view: View) => void`, `popOutToTab(): void`, `isInTab(): boolean`, `openVaultTab(hash?: string): void`. Make `getState`/`setState` generic over `keyof PopupState`. Throw on `registerHost()` re-register; export `__resetHostForTests()`.
|
||||
- P1.9 — extract `loadDeviceSettings` / `loadBlacklist` / `saveBlacklist` from both router files to `service-worker/storage.ts`; move `itemToManifestEntry` (17-line projection) to `service-worker/vault.ts`. Import from both routers.
|
||||
- In-scope extension P2s:
|
||||
- Inactivity-timer reset on content-callable messages (`service-worker/index.ts:76-78`)
|
||||
- Null `state.gitHost` alongside `state.manifest` on session expiry (`service-worker/index.ts:51-58`)
|
||||
- Teardown helper extraction (`settings.ts:56-65` and `settings-vault.ts:15-22` → `teardownSettingsCommon()`)
|
||||
- `Promise.allSettled` in `devices.ts:47-50` and `trash.ts:39-46`
|
||||
- MutationObserver debounce in `content/detector.ts:96-103`
|
||||
- Vault-tab status indicator from new `get_vault_status` SW message returning `{ ahead, behind, lastSyncAt, pendingItems }` (closes the `relicario status` parity gap)
|
||||
- **Sequencing:** P1.6 (state.ts typing) is a precondition for P1.4 and P1.5 — both push through the StateHost surface. Plan should call this out as Phase 1.
|
||||
- **Receives:** the "Boundary notes for DEV-C" section from `dev-b-notes.md`. Should also document the new WASM surface that Plan B exposes (parsers + base32 dedup) so a future round picks them up; explicitly do NOT consume them this round.
|
||||
|
||||
### Format reference
|
||||
|
||||
All three plans match the structure of `2026-05-02-v0.5.0-polish-harden-design.md`:
|
||||
- `# <Title> — Design`
|
||||
- Date / Status / Source (cite synthesis P-tags) / Effort estimate
|
||||
- Summary (2-4 sentences)
|
||||
- Findings addressed (bullet list, each citing P-tag + reviewer + file:line)
|
||||
- Approach (architectural shape; module diagrams or directory trees if it helps)
|
||||
- Implementation phases (numbered; each with Goal, Changes, Tests, Effort, Depends-on)
|
||||
- Risks and mitigations
|
||||
- Out of scope
|
||||
- Done criteria (reviewer checklist)
|
||||
|
||||
### After the subagents return
|
||||
|
||||
1. **Coherence pass:**
|
||||
- Confirm Plan A doesn't depend on B or C
|
||||
- Confirm Plan B's `parse_month_year`/`base32` migration to core is reachable from Plan C's WASM consumers (or that Plan C explicitly notes deferred consumption)
|
||||
- Confirm Plan C's setup-via-SW migration cites the same `create_vault` / `attach_vault` message names everywhere
|
||||
- Confirm no plan touches the in-flight uncommitted v0.5.x work (vault.ts, vault.css, glyphs.ts, manifests, relay tooling beyond start.sh, Cargo.toml version bumps)
|
||||
2. **Ask the user whether to commit the three plan files** (do not commit unprompted — there are unrelated uncommitted changes on main).
|
||||
3. Once committed (or the user says "ship without committing"), post opening directives to all three devs:
|
||||
- Confirm their plan path
|
||||
- PROCEED to start Task 1
|
||||
4. Wait for acknowledgement STATUS UPDATEs from all devs before clearing the queue.
|
||||
|
||||
## First action
|
||||
|
||||
1. Call `read_messages(for="pm")` to drain any early inbox messages.
|
||||
2. Read the synthesis end-to-end. Internalize the 10 P1s and the cross-cutting themes.
|
||||
3. Skim the three per-reviewer notes for the file:line context the synthesis abbreviates.
|
||||
4. Skim the two existing plan docs above to absorb the format.
|
||||
5. Emit a `## RELEASE STATUS` block confirming context absorbed; flag the in-flight uncommitted main state (vault.ts/glyphs.ts/etc.) for the user.
|
||||
6. Spawn three `Plan` subagents in parallel with the scopes specified above.
|
||||
7. Do the coherence pass.
|
||||
8. Ask the user whether to commit the three plan files.
|
||||
9. Post opening directives to all three devs unlocking their work.
|
||||
168
docs/superpowers/coordination/architecture-review-pm-prompt.md
Normal file
168
docs/superpowers/coordination/architecture-review-pm-prompt.md
Normal file
@@ -0,0 +1,168 @@
|
||||
# PM Kickoff Prompt — Architecture Review (whole codebase)
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are the **project manager** for Relicario's whole-codebase architecture audit (2026-05-04). Three senior reviewers report to you, each working in their own terminal on a partition of the codebase. The user runs all four terminals; the relay server routes messages.
|
||||
|
||||
This is **not** a feature release — it is a one-shot architecture review. The user's stated goal: *"I really want to make this app's architecture logical. I don't know Rust but I want to be able to read and understand the code and learn by tinkering with it."* Treat that goal as the primary lens for everything: reviews are valuable when they reduce confusion for a smart non-Rust reader; they are not valuable when they restate what's already obvious.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Stay on `main`. **Do not check out branches, do not create worktrees.** This is a review-only operation. The PM may edit the synthesis doc; reviewers do not edit code.
|
||||
- Today: 2026-05-04. Project rules in `CLAUDE.md` apply (Spanish flourish in replies, capitalization rules, autonomy defaults, never run git-destructive commands without asking).
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"pm"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="pm"` before each action
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm, dev-a, dev-b, dev-c`. Use these instead of asking the user to copy-paste. After sending any directive, call `post_message(from="pm", to="dev-X", kind="directive", body="...")`.
|
||||
|
||||
**Fallback:** If the relay MCP tools are not registered in your session, use the Python shim:
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario/tools/relay
|
||||
python3 call.py post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
|
||||
python3 call.py read_messages '{"for":"pm"}'
|
||||
```
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/specs/2026-04-11-relicario-design.md` — foundational spec (threat model, crypto pipeline, format)
|
||||
3. `docs/superpowers/coordination/architecture-review-dev-a-prompt.md` — DEV-A's scope (Rust core)
|
||||
4. `docs/superpowers/coordination/architecture-review-dev-b-prompt.md` — DEV-B's scope (CLI, server, WASM)
|
||||
5. `docs/superpowers/coordination/architecture-review-dev-c-prompt.md` — DEV-C's scope (TS extension + relay)
|
||||
|
||||
You should NOT walk every file yourself — the reviewers do that. Your job is to coordinate, then synthesize.
|
||||
|
||||
## Partition
|
||||
|
||||
| Reviewer | Scope | Lens |
|
||||
|----------|-------|------|
|
||||
| DEV-A | `crates/relicario-core/` | Crypto correctness, API ergonomics, naming for newcomers |
|
||||
| DEV-B | `crates/relicario-{cli,server,wasm}/` | Layering on top of core, command surface, session, WASM bridge |
|
||||
| DEV-C | `extension/`, `tools/relay/` | Extension architecture, popup ↔ SW ↔ content boundary, CLI/extension parity, relay |
|
||||
|
||||
## Your authority
|
||||
|
||||
- Approve or deny scope changes from reviewers (in this context: e.g. "DEV-A wants to also look at WASM" — usually deny, since DEV-B has it)
|
||||
- Read each reviewer's notes file (`docs/superpowers/reviews/2026-05-04-dev-{a,b,c}-notes.md`) as they're updated
|
||||
- Cross-reference findings to identify cross-cutting issues (e.g. a core API ergonomics issue that bites the WASM consumer)
|
||||
- **Write the synthesis doc** at `docs/superpowers/reviews/2026-05-04-architecture-review.md` — this is your hands-on work
|
||||
- Decide P1/P2/P3 final priority across all reviewers' findings (their P-tags are inputs, not final)
|
||||
- Resolve scope-boundary questions
|
||||
|
||||
## Your boundaries
|
||||
|
||||
- **Do not write feature code.** Edits to the synthesis doc are fine. Edits to other docs / `CLAUDE.md` are fine if they're directly informed by the review (e.g. clarifying a project rule that's actually unwritten).
|
||||
- Do not modify the codebase being reviewed. The reviewers don't either; act as a backstop on this rule.
|
||||
- Do not redirect a reviewer mid-stream without good reason. They are doing depth work; context-switching is expensive.
|
||||
- Do not synthesize prematurely. Wait for at least two reviewers to post `Phase: REVIEW-COMPLETE` before opening the synthesis doc. (You can pre-skim notes earlier, but don't write conclusions.)
|
||||
- Project rule: ask the user before any git-destructive op.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
**Before each action:** `read_messages(for="pm")`.
|
||||
|
||||
**You receive:** `## STATUS UPDATE` and `## QUESTION TO PM` blocks from `dev-a`, `dev-b`, `dev-c`.
|
||||
|
||||
**You emit:** directives via `post_message(from="pm", to="dev-X", kind="directive", body="...")`. Body format:
|
||||
|
||||
```
|
||||
## DIRECTIVE TO DEV-<letter>
|
||||
Time: <iso8601>
|
||||
Action: PROCEED | HOLD | RESCOPE | ANSWER | REVIEW-ACKED
|
||||
Notes: <one paragraph max>
|
||||
Next: <one concrete instruction>
|
||||
```
|
||||
|
||||
**Status rollup** (when asked "status?" by the user):
|
||||
|
||||
```
|
||||
## REVIEW STATUS — Architecture Audit 2026-05-04
|
||||
DEV-A: <phase, files covered, findings count>
|
||||
DEV-B: <phase, crates covered, findings count>
|
||||
DEV-C: <phase, areas covered, findings count>
|
||||
PM: <current action — coordinating | reading-notes | synthesizing | done>
|
||||
Open questions: <list, or "none">
|
||||
Next milestone: <e.g., "DEV-A REVIEW-COMPLETE", "synthesis draft", "user review">
|
||||
```
|
||||
|
||||
## Synthesis doc
|
||||
|
||||
When at least two reviewers have posted `Phase: REVIEW-COMPLETE` (and ideally all three), write the final review doc to `docs/superpowers/reviews/2026-05-04-architecture-review.md` with this structure:
|
||||
|
||||
```markdown
|
||||
# Relicario — Whole-Codebase Architecture Review
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Reviewers:** DEV-A (Rust core), DEV-B (Rust consumers), DEV-C (TypeScript)
|
||||
**Synthesis:** PM
|
||||
**Goal lens:** "Make this app's architecture logical and readable for a smart developer who doesn't know Rust but wants to learn by tinkering."
|
||||
|
||||
## Executive summary
|
||||
4-6 sentences: overall architectural shape, the 3 most important things to address, the 3 strongest aspects worth preserving.
|
||||
|
||||
## Top-priority recommendations (P1)
|
||||
For each P1 (across all three reviewers — your final prioritization, not theirs):
|
||||
|
||||
### P1.N — <short title>
|
||||
**Area:** <core | cli | server | wasm | extension | shared | tooling | cross-cutting>
|
||||
**File(s):** `<path>:<line>`
|
||||
**Found by:** DEV-A | DEV-B | DEV-C | (multiple)
|
||||
**Observation:** <one paragraph>
|
||||
**Why it matters for the user's goal:** <how this confuses a Rust newcomer or otherwise blocks "learn by tinkering">
|
||||
**Suggested direction:** <one paragraph; specific enough to act on, not so prescriptive that it's a plan>
|
||||
**Effort:** S | M | L (rough — S = under an hour, M = half a day, L = a day or more)
|
||||
|
||||
## P2 recommendations
|
||||
Same format, lighter detail.
|
||||
|
||||
## P3 / nice-to-have
|
||||
Bullets.
|
||||
|
||||
## Cross-cutting themes
|
||||
2-4 paragraphs on patterns that show up in multiple areas (e.g. "error messages are inconsistent across crates", "naming for crypto types is opaque", "TS message types could be generated from the WASM bindings"). These are usually the highest-leverage things — flag them clearly.
|
||||
|
||||
## What's strong (preserve)
|
||||
3-5 specific things that are well-done and that future changes should not erode.
|
||||
|
||||
## CLI/extension parity status
|
||||
A short summary of DEV-C's parity table: gaps, intentional gaps, gaps to close.
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
Pull together DEV-A's, DEV-B's, and DEV-C's beginner sections into one short story: where will the user trip first when trying to read/tinker, and what's the single most valuable change to make.
|
||||
|
||||
## Appendix: pointers to per-reviewer notes
|
||||
- [DEV-A notes — Rust core](./2026-05-04-dev-a-notes.md)
|
||||
- [DEV-B notes — Rust consumers](./2026-05-04-dev-b-notes.md)
|
||||
- [DEV-C notes — TypeScript](./2026-05-04-dev-c-notes.md)
|
||||
```
|
||||
|
||||
You may use the `superpowers:requesting-code-review` skill to get an independent second-pass on your synthesis before declaring done — but only after the synthesis is in draft.
|
||||
|
||||
## Done criteria
|
||||
|
||||
Before posting `## REVIEW STATUS — Architecture Audit 2026-05-04` with `PM: done`:
|
||||
|
||||
- [ ] All three reviewers posted `Phase: REVIEW-COMPLETE`
|
||||
- [ ] All three notes files exist and are non-empty under `docs/superpowers/reviews/`
|
||||
- [ ] `docs/superpowers/reviews/2026-05-04-architecture-review.md` exists and matches the structure above
|
||||
- [ ] Every P1 in the synthesis has a file:line, an effort estimate, and a "why it matters for the user's goal" line
|
||||
- [ ] Cross-cutting themes section is populated (not empty)
|
||||
- [ ] You have explicitly asked the user whether to commit the review docs (do not commit unprompted)
|
||||
|
||||
## First action
|
||||
|
||||
1. Call `read_messages(for="pm")`.
|
||||
2. Read the project rules and the spec.
|
||||
3. Read each dev's prompt (links above) so you know exactly what scope each owns.
|
||||
4. Emit a `## REVIEW STATUS — Architecture Audit 2026-05-04` block to the user, confirming setup.
|
||||
5. Send opening directives to all three devs via `post_message`, each saying `Action: PROCEED` and reaffirming their scope (so it's recorded in the relay log).
|
||||
6. Wait for acknowledgement status updates from all three before settling into coordination mode.
|
||||
@@ -69,8 +69,22 @@ Your vault.ts should call `renderSettings(pane)` when the `#settings` route is a
|
||||
- `glyphs.ts` is the single source of truth. No inline Unicode literals at call sites.
|
||||
- Don't merge to main. The PM owns merges.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-a"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-a"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm`, `dev-a`, `dev-b`, `dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-a")`. After emitting any status/question block: `post_message(from="dev-a", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
Before starting each task, call `read_messages(for="dev-a")` to drain your inbox.
|
||||
|
||||
When posting a status update, call `post_message(from="dev-a", to="pm", kind="status", body="...")` with the body:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-A
|
||||
Time: <iso8601>
|
||||
@@ -1438,6 +1452,8 @@ gh pr create --title "feat: fullscreen 3-column layout + popup polish (Stream A)
|
||||
|
||||
- [ ] **Step 5: Post status to PM**
|
||||
|
||||
Call `post_message(from="dev-a", to="pm", kind="status", body="...")` with:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-A
|
||||
Time: <iso8601>
|
||||
|
||||
@@ -83,8 +83,22 @@ export function teardownSecuritySection(): void;
|
||||
- Device sections read/write `chrome.storage.local`. Vault sections call `sendMessage` to the service worker.
|
||||
- Don't merge to main. The PM owns merges.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-b"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-b"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm`, `dev-a`, `dev-b`, `dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-b")`. After emitting any status/question block: `post_message(from="dev-b", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
Before starting each task, call `read_messages(for="dev-b")` to drain your inbox.
|
||||
|
||||
When posting a status update, call `post_message(from="dev-b", to="pm", kind="status", body="...")` with the body:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: <iso8601>
|
||||
@@ -1064,6 +1078,8 @@ gh pr create --title "feat: settings UX redesign — left-nav sectioned layout (
|
||||
|
||||
- [ ] **Step 6: Post status to PM**
|
||||
|
||||
Call `post_message(from="dev-b", to="pm", kind="status", body="...")` with:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: <iso8601>
|
||||
|
||||
@@ -72,8 +72,22 @@ export function teardownSecuritySection(): void;
|
||||
|
||||
DEV-B has a stub. Your Task 9 provides the real implementation.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"dev-c"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="dev-c"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm`, `dev-a`, `dev-b`, `dev-c`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="dev-c")`. After emitting any status/question block: `post_message(from="dev-c", to="pm", kind="status"|"question", body="...")`.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
Before starting each task, call `read_messages(for="dev-c")` to drain your inbox.
|
||||
|
||||
When posting a status update, call `post_message(from="dev-c", to="pm", kind="status", body="...")` with the body:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-C
|
||||
Time: <iso8601>
|
||||
@@ -1349,5 +1363,5 @@ git commit -m "feat(ext/setup): recovery QR banner in final wizard step"
|
||||
## Final steps
|
||||
|
||||
- [ ] Open PR: `gh pr create --title "feat: recovery QR (Stream C)" --base main`
|
||||
- [ ] Post `## STATUS UPDATE — DEV-C / Action: REVIEW-READY` with PR URL to PM
|
||||
- [ ] Call `post_message(from="dev-c", to="pm", kind="status", body="## STATUS UPDATE — DEV-C\nTime: <iso8601>\nTask: 13 of 13\nStatus: REVIEW-READY\nSummary: All 13 tasks complete. PR open. Recovery QR implemented end-to-end.\nNext: waiting for PM")`
|
||||
- [ ] Respond to any PM review comments
|
||||
|
||||
@@ -105,13 +105,23 @@ DEV-B stubs this interface in `settings-security.ts` immediately after receiving
|
||||
3. No squash merges — git history is preserved per project rule.
|
||||
4. No force pushes. Each dev opens a PR; PM reviews diff; PM merges with `gh pr merge --merge`.
|
||||
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; `from` is always `"pm"` for you
|
||||
- `read_messages(for)` — drain your inbox; call with `for="pm"` before each action
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm`, `dev-a`, `dev-b`, `dev-c`. Use these instead of asking the user to copy-paste. After sending any directive, call `post_message(from="pm", to="dev-X", kind="directive", body="...")`.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of four terminals. The user relays messages.
|
||||
**Before each action:** call `read_messages(for="pm")` to drain your inbox.
|
||||
|
||||
**You receive:** `## STATUS UPDATE — DEV-A/B/C` or `## QUESTION TO PM — DEV-X` blocks.
|
||||
**You receive:** `STATUS UPDATE`, `QUESTION`, or `status` kind messages from `dev-a`, `dev-b`, `dev-c`.
|
||||
|
||||
**You emit:** a `## DIRECTIVE TO DEV-X` block. Format:
|
||||
**You emit:** directives via `post_message(from="pm", to="dev-X", kind="directive", body="...")`. The body should follow this format:
|
||||
|
||||
```
|
||||
## DIRECTIVE TO DEV-A (or B or C)
|
||||
@@ -162,4 +172,9 @@ Before tagging v0.5.1:
|
||||
|
||||
## First action
|
||||
|
||||
After reading: post a `## RELEASE STATUS — v0.5.1` block, then post your first directive to all three devs simultaneously — confirming the A–B and B–C interface contracts above. Wait for devs to acknowledge before instructing them to proceed with their task lists.
|
||||
1. Call `read_messages(for="pm")` to drain any early inbox messages.
|
||||
2. Emit a `## RELEASE STATUS — v0.5.1` block to the user.
|
||||
3. Call `post_message(from="pm", to="dev-a", kind="directive", body="...")` — confirming the A–B interface contract.
|
||||
4. Call `post_message(from="pm", to="dev-b", kind="directive", body="...")` — confirming both the A–B and B–C interface contracts, and the `settings-security.ts` stub instruction.
|
||||
5. Call `post_message(from="pm", to="dev-c", kind="directive", body="...")` — confirming the B–C interface contract.
|
||||
6. Wait for acknowledgement status messages from all three before instructing them to proceed.
|
||||
|
||||
265
docs/superpowers/reviews/2026-05-04-architecture-review.md
Normal file
265
docs/superpowers/reviews/2026-05-04-architecture-review.md
Normal file
@@ -0,0 +1,265 @@
|
||||
# Relicario — Whole-Codebase Architecture Review
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Reviewers:** DEV-A (Rust core), DEV-B (Rust consumers — CLI, server, WASM), DEV-C (TypeScript — extension, relay)
|
||||
**Synthesis:** PM
|
||||
**Goal lens:** "Make this app's architecture logical and readable for a smart developer who doesn't know Rust but wants to learn by tinkering."
|
||||
|
||||
## Executive summary
|
||||
|
||||
The architecture is fundamentally sound: bytes-in/bytes-out core, no I/O leakage from `relicario-core`, a server that structurally cannot decrypt (no AEAD or KDF crate in its dep graph), a service-worker boundary in the extension that holds (content scripts make zero WASM calls), and CLI/extension parity at 22/23 capabilities. What hurts the goal lens is uneven detail: a few outsized files (`cli/main.rs` 2641 LOC, `extension/src/setup/setup.ts` 1220 LOC, `extension/src/vault/vault.ts` 1027 LOC) absorb concerns that belong in smaller modules, and a couple of cross-cutting boilerplate clusters (16× duplicated git-shell error UX in the CLI; duplicated SW router helpers; hand-maintained `wasm.d.ts`) make a learner re-derive the same pattern repeatedly. The single most important thing to address is a defense-in-depth crypto issue spanning Rust and JS: `SessionHandle` has no `impl Drop`, so the wasm-bindgen-generated `.free()` is a no-op for cleanup — the master key stays in WASM linear memory until JS explicitly calls `lock()`. The strongest aspects worth preserving are the documentation density of the security-critical core files (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs` all open with multi-paragraph rationale), the discriminated-union message contract in the extension (`shared/messages.ts` + the popup-only / content-callable capability sets), and the server's structural enforcement of the ciphertext-only invariant via its import surface. These three patterns are the model for what every other surface should look like.
|
||||
|
||||
## Top-priority recommendations (P1)
|
||||
|
||||
### P1.1 — `SessionHandle` has no `impl Drop`; `.free()` is a cleanup no-op
|
||||
**Area:** cross-cutting (wasm + extension)
|
||||
**File(s):** `crates/relicario-wasm/src/lib.rs:15-23`, `crates/relicario-wasm/src/session.rs:1-58`, `extension/src/service-worker/session.ts:26`
|
||||
**Found by:** DEV-B (Rust side, headline finding); DEV-C (symmetric JS-side concern, originally [P2])
|
||||
**Observation:** `SessionHandle` is `pub struct SessionHandle(u32)` with no `Drop` impl. wasm-bindgen's auto-generated JS `.free()` drops a `u32` — i.e. nothing. The `SESSIONS` HashMap entry stays alive with the master key and image_secret in WASM linear memory until JS calls the explicit `lock(handle)` (which calls `session::remove`). DEV-C separately observed `service-worker/session.ts:26` swallows `free()` errors with `try { current.free() }` — that swallow is hiding the fact that the call wasn't doing crypto cleanup anyway.
|
||||
**Why it matters for the user's goal:** This is the only finding in the review where the gap between "what the code looks like it does" and "what it actually does" is dangerous. A tinkerer reading `session.ts` reasonably assumes `free()` cleans up the WASM-side key; it does not. Defense-in-depth here is one Rust block and one JS audit.
|
||||
**Suggested direction:** Add `impl Drop for SessionHandle { fn drop(&mut self) { session::remove(self.0); } }` to the WASM crate so `.free()` becomes the safety net and `lock()` becomes the explicit "I am done" call. In parallel, remove the `try { ... }` swallow at `service-worker/session.ts:26` (let exceptions propagate or log + counter) and audit every `.free()` callsite under `extension/src/` to ensure `wasm.lock(handle)` happens first regardless. A `wasm-bindgen-test` covering construct → drop → confirm registry empty locks the contract.
|
||||
**Effort:** S (Rust fix) + S (JS audit) = ~1-2 hours total
|
||||
|
||||
### P1.2 — `crates/relicario-cli/src/main.rs` is a 2641-line monolith
|
||||
**Area:** cli
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:1-2641`
|
||||
**Found by:** DEV-B
|
||||
**Observation:** The clap surface (lines 1-455) is a tour of the product and reads beautifully. Past line 456 the file becomes flat: every `cmd_*`, every `build_*_item`, every `edit_*`, six prompt helpers, three parsing helpers, and 24+ git shell-outs all live as peers. `cmd_add` calls 7 different `build_*_item` functions (each ~50-60 lines) with no module boundaries. Searching "where does add work?" requires scrolling, not navigating.
|
||||
**Why it matters for the user's goal:** This is the first file a tinkerer opens after `cargo run -p relicario-cli -- --help`. Today they have to scroll through 2200 lines of flat code to follow any one command end-to-end. Splitting this is the precondition for fixing P1.3 and centralizing several other CLI patterns (groups-cache discipline, prompt helpers).
|
||||
**Suggested direction:** Keep `main.rs` as clap definitions + the dispatching `match` (~470 lines). Split into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs`, plus `prompt.rs` (the six `prompt_*` helpers + `prompt_secret`) and `parse.rs` (`parse_month_year`, `base32_decode_lenient`, `guess_mime`). Same LOC, different reading experience.
|
||||
**Effort:** M (mechanical split, no logic changes)
|
||||
|
||||
### P1.3 — Git invocation boilerplate duplicated 16× with one-line errors
|
||||
**Area:** cli
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` (and others)
|
||||
**Found by:** DEV-B
|
||||
**Observation:** Every `git_command` invocation that bails uses the same shape: `.args([...]).status()? + if !status.success() { bail!("git foo failed") }`. Child stderr is inherited interactively, but in test runs and noninteractive tooling it's lost, and the bail message is just the verb. When this fires in the wild — pre-receive reject, missing remote, dirty tree, signing-key prompt — the user sees one line and nothing actionable.
|
||||
**Why it matters for the user's goal:** This is the *entire* error UX for the git side of the CLI. Failures are common, the diagnostic is uniformly unhelpful, and a learner will hit "git commit failed" with no context the first time they touch a misconfigured remote.
|
||||
**Suggested direction:** Add `helpers::git_run(repo, args, context)` that uses `.output()` (capturing stderr), prints captured stderr unmodified on failure, and embeds the human-readable `context` ("commit add: GitHub", "register device", "purge trashed item"). 16 copies become one-liners.
|
||||
**Effort:** S (single helper + sweep)
|
||||
|
||||
### P1.4 — `extension/src/setup/setup.ts` bypasses the SW and orchestrates WASM directly
|
||||
**Area:** extension
|
||||
**File(s):** `extension/src/setup/setup.ts:28-37`, `:1118-1120` (and the whole 1220-LOC file)
|
||||
**Found by:** DEV-C
|
||||
**Observation:** Popup, vault tab, and content scripts all funnel WASM through the service-worker. `setup.ts` is the only surface that imports `relicario-wasm` directly and orchestrates `unlock` / `embed_image_secret` / `register_device` / `manifest_encrypt` itself — duplicating ~400 LOC of crypto orchestration the SW already knows how to do. Side-effect: the setup tab can't be locked by the same session-timer the rest of the extension uses, and `WizardState` (passphrase + JPEG bytes + WASM handle) persists in module scope if the user abandons mid-wizard.
|
||||
**Why it matters for the user's goal:** This is the single biggest "code lies about the pattern" surface in the extension. A learner who opens `setup.ts` first will see WASM imported directly and conclude that's how the extension works — it isn't; everywhere else routes through `chrome.runtime.sendMessage`. The file is also a 1220-LOC procedural wizard that could be a step registry.
|
||||
**Suggested direction:** Add `create_vault` and `attach_vault` messages to the SW; turn `setup.ts` into a UI that posts those messages with the gathered config + image bytes. Convert the 6-step flow into a `{ id, render, attach }[]` step registry. The 1220 LOC drops to ~500. Add a `clearWizardState()` bound to `beforeunload` and to "return to step 0" so abandoned wizards don't persist sensitive material.
|
||||
**Effort:** L (architectural — touches setup, the SW message router, and `wasm.d.ts`/types)
|
||||
|
||||
### P1.5 — `extension/src/vault/vault.ts` is a 1027-LOC do-everything file
|
||||
**Area:** extension
|
||||
**File(s):** `extension/src/vault/vault.ts:1-1027`
|
||||
**Found by:** DEV-C
|
||||
**Observation:** Single file owns: shell init, hash routing, sidebar render, list render, drawer state, type-picker, form-wrapper, deep-link routing, teardown coupling. Adding a new pane view today is a 5-place edit (`teardownPaneComponents` lines 813-820 is the symptom). Two state-management oddities sit inside: vault tab intercepts `vault_locked` errors via the RPC layer while the popup uses the `session_expired` event (two channels for one outcome), and `state.drawerOpen = true` survives navigation to non-list views.
|
||||
**Why it matters for the user's goal:** This is the second steepest cliff for a tinkerer (after `setup.ts`). The vault tab is the user's primary fullscreen experience; the file that drives it should read as orchestration, not implementation.
|
||||
**Suggested direction:** Split into `vault-shell.ts`, `vault-sidebar.ts`, `vault-list.ts`, `vault-drawer.ts`, `vault-form-wrapper.ts`, leaving `vault.ts` to own only routing and state. While doing so, lift the `vault_locked` RPC intercept into `shared/state.ts` (or a wrapper around `sendMessage`) so popup and vault use one path; reset `state.drawerOpen` at the start of `renderPane` for non-list views.
|
||||
**Effort:** M (mechanical split, plus one channel-unification touch)
|
||||
|
||||
### P1.6 — `extension/src/shared/state.ts` is fully `any`-typed
|
||||
**Area:** extension (shared)
|
||||
**File(s):** `extension/src/shared/state.ts:10-35`
|
||||
**Found by:** DEV-C
|
||||
**Observation:** `StateHost` is the bridge that lets popup components run inside the vault tab — and it's the bridge most likely to drift between the two render targets — but its entire contract is `any`-typed. TS gives no signal when popup-only state shape diverges from vault-tab expectations. Module-scope `host` singleton additionally has no double-registration guard; tests forget a reset and the leak silently breaks isolation.
|
||||
**Why it matters for the user's goal:** Two-render-target reuse is exactly the kind of architecture decision that pays off in maintainability — but only if the contract is type-checked. As-is, the bridge is the weakest learning surface in the extension.
|
||||
**Suggested direction:** Define a concrete `StateHost` interface: `state: PopupState`, `navigate: (view: View) => void`, `popOutToTab(): void`, `isInTab(): boolean`, `openVaultTab(hash?: string): void`. Make `getState`/`setState` generic over `keyof PopupState`. Throw on `registerHost()` re-register; export a `__resetHostForTests()` helper.
|
||||
**Effort:** S-M (type definitions + sweep through callers)
|
||||
|
||||
### P1.7 — `crates/relicario-core/src/recovery_qr.rs` is undocumented
|
||||
**Area:** core
|
||||
**File(s):** `crates/relicario-core/src/recovery_qr.rs:1-130`
|
||||
**Found by:** DEV-A
|
||||
**Observation:** No module-level `//!` header. No doc comments on `RecoveryQrPayload`, `generate_recovery_qr`, `unwrap_recovery_qr`, or `recovery_qr_to_svg`. Magic constants (`RREC`, `VERSION = 0x01`, `PAYLOAD_LEN = 109`) sit at the top with no explanation; the 4+1+32+24+48 layout is hand-counted with no struct, diagram, or asserts. The domain-separation prefix `b"relicario-recovery-v1\0"` exists but isn't explained. `production_params()` redeclares `KdfParams::default()` values with no comment on why the recovery format pins them.
|
||||
**Why it matters for the user's goal:** Every other security-relevant file in the core (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`) has explanatory framing. A learner hitting `recovery_qr.rs` sees a different style and assumes either it doesn't matter or they've stumbled out of the documented zone. It does matter — this is the vault-key escape hatch — and a misuse here (e.g., reusing `production_params` as `KdfParams::default()` and then changing the default) silently breaks all extant recovery QRs.
|
||||
**Suggested direction:** Add a module-level `//!` summarizing the format, the KDF-input domain separation, and the parameter-pinning rationale. Add a short ASCII diagram of the 109-byte layout near the constants. Doc-comment the four public functions. Either replace `production_params()` with a `const` or add a comment explaining the deliberate divergence from `KdfParams::default()`.
|
||||
**Effort:** S (documentation only)
|
||||
|
||||
### P1.8 — `tools/relay/queue.test.ts` fails on uncommitted state
|
||||
**Area:** tooling
|
||||
**File(s):** `tools/relay/queue.test.ts:54`
|
||||
**Found by:** DEV-C (verified via `bun test` → 1 fail / 4 pass)
|
||||
**Observation:** Uncommitted changes added `dev-c` to the `Role` union and `KNOWN_ROLES` set in `queue.ts`, but the test still asserts the old enum: `assert.ok(!isRole("dev-c"))`. One-line fix.
|
||||
**Why it matters for the user's goal:** A learner running `bun test` from `tools/relay/` immediately sees a failure and assumes the codebase is broken. The relay is the literal coordination substrate of this review; a green test run is table stakes.
|
||||
**Suggested direction:** Update the test assertion to `assert.ok(isRole("dev-c"))` and add a negative case (`assert.ok(!isRole("dev-d"))`). Confirm `start.sh` opens a fourth window for dev-c (DEV-C suspected `:80` still hardcodes "Dev-B" in user-facing output).
|
||||
**Effort:** S (one-line edit + one-launcher-line check)
|
||||
|
||||
### P1.9 — Duplicated SW router helpers (storage helpers + `itemToManifestEntry`)
|
||||
**Area:** extension (service-worker)
|
||||
**File(s):** `extension/src/service-worker/router/popup-only.ts:687-703` and `:~169`; `extension/src/service-worker/router/content-callable.ts:187-205` and `:~169`
|
||||
**Found by:** DEV-C
|
||||
**Observation:** Three identical `chrome.storage.local` helpers (`loadDeviceSettings`, `loadBlacklist`, `saveBlacklist`) and the 17-line `itemToManifestEntry()` projection are duplicated across both router files. Both code paths can mutate the blacklist via different definitions; future drift will silently corrupt one path. Manifest schema refactors will need to be made twice.
|
||||
**Why it matters for the user's goal:** A learner reading either router file sees private helpers and assumes that's where they live; finding the same name in the sibling router with a near-identical body is a routine "wait, why is this duplicated?" moment that should not exist in a tightly-typed message-router architecture.
|
||||
**Suggested direction:** Extract the three storage helpers to `service-worker/storage.ts`; move `itemToManifestEntry` into `service-worker/vault.ts`. Import from both router files. Pair this with [P1.6] for `shared/state.ts` typing — both are about giving the extension's "shared utilities" a concrete shape.
|
||||
**Effort:** S (extract + sweep)
|
||||
|
||||
### P1.10 — Pure parsers in CLI that the extension will eventually need
|
||||
**Area:** cli → core
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:942-980` (`parse_month_year`, `base32_decode_lenient`, `guess_mime`)
|
||||
**Found by:** DEV-B
|
||||
**Observation:** Three pure parsers producing typed core values currently live only in the CLI. Per the project's CLI/extension parity philosophy (CLAUDE.md memory rule), anything the CLI does in pure logic the extension will eventually need too — QR-import, month-year smart input, attachment MIME detection. There is also a `base32_encode` in `core/item.rs` and a `decode_base32_totp` in `core/import_lastpass.rs` that are inverse pairs in different modules — DEV-A flagged the same shape from the core side ([P2] base32 has three implementations).
|
||||
**Why it matters for the user's goal:** Parity is a stated design philosophy, and parser drift between CLI and extension is the most likely place for it to fail silently.
|
||||
**Suggested direction:** Migrate to core: `MonthYear::parse` (already partial in `time.rs`), `Totp::parse_secret` (or `ItemCore::parse_totp_seed`), `mime::guess_for_extension`. Pair with extracting a `pub(crate) mod base32` in core with `encode_rfc4648` / `decode_rfc4648`, leaving Steam's bespoke alphabet where it is. The CLI keeps thin wrappers; the WASM crate exposes the new functions; the extension calls them via SW message handlers.
|
||||
**Effort:** M (move + adjust CLI callers + add WASM exports)
|
||||
|
||||
## P2 recommendations
|
||||
|
||||
### Core (Rust)
|
||||
- **`extract_with_crop_recovery` is narrower than the spec describes.** `crates/relicario-core/src/imgsecret.rs:849-899`. Spec promises 15% from any edge; impl pins `dx=0, dy=0` and varies only `orig_w`/`orig_h`. Left/top crops won't recover. Either extend the recovery loop or update the spec language to "right/bottom crop tolerance only." (DEV-A)
|
||||
- **Stale "in-progress rewrite" headers** in `vault.rs:1-7`, `manifest.rs:1-2`, `attachment.rs:1-4`. Each comment describes work that already shipped. Replace with one-line module summaries. (DEV-A)
|
||||
- **Two dead fields in `EmbedRegion`** (`imgsecret.rs:225-229`). `region_width`/`region_height` are computed, stored, and silenced with `#[allow(dead_code)]`. Either delete or comment the future use. (DEV-A)
|
||||
- **Three base32 implementations.** `item.rs:255-275`, `import_lastpass.rs:202-220`, `item_types/totp.rs:13` (Steam, intentionally different). Extract a `pub(crate) mod base32`; leave Steam alone with a neighbour comment. (DEV-A; folds into P1.10.)
|
||||
- **Backup format embeds the reference JPEG as base64-in-JSON** (`backup.rs:148-152, 274-280, 343-345`). Round-trip works; bloats by ~33% over the binary baseline post-zstd. Defer until backup-size pressure shows up. (DEV-A)
|
||||
|
||||
### CLI (Rust)
|
||||
- **`build_*_item` functions mix prompting, parsing, and core construction.** `main.rs:664-921`. Compress with a `prompt_or_flag<T>` helper. (DEV-B)
|
||||
- **`refresh_groups_cache` invocation discipline is manual at 7 sites.** `main.rs:641, 998, 1123, 1197, 1414, 1432, 1474`. Rule "every mutating handler must call this" is unenforced. Wrap in `Vault::after_manifest_change(&self, manifest: &Manifest)`. (DEV-B)
|
||||
- **`ParamsFile` defined twice with mismatching shapes.** Write side `main.rs:2287` has `aead`, `salt_path`, `format_version`; read side `session.rs:114` takes only `kdf`. Single struct in core or shared session module. (DEV-B)
|
||||
- **`cmd_purge` and `cmd_trash_empty` duplicate the manifest-add-and-commit dance** (`main.rs:1476-1480, 1896-1900`). 50-item purge does 150 git invocations; batch the staging. (DEV-B)
|
||||
|
||||
### Server (Rust)
|
||||
- **`generate-hook` assumes `$PATH`.** `relicario-server/src/main.rs:170`. Most Gitea hook environments don't have `/usr/local/bin`; `command not found` is the failure mode. Embed `current_exe()` or emit an explicit `PATH=` line. (DEV-B)
|
||||
- **Bootstrap branch is permissive.** `:38-44, 54-57`. Missing `.relicario/devices.json` at `newrev` is treated as bootstrap. An attacker pushing a brand-new branch that strips `.relicario/` could push unsigned commits. Either document the rule or enforce: `oldrev != 0` ⇒ `devices.json` must exist in `newrev`. (DEV-B)
|
||||
- **stdin-parsing lives in the shell hook only.** `:130-189`. Wiring up the binary by hand isn't possible without re-implementing the per-line `<old> <new> <ref>` parse. Add `verify-commit --from-stdin` or doc-comment the constraint. (DEV-B)
|
||||
- **Test coverage gaps** (`tests/verify_commit.rs`): unsigned-commit, malformed `devices.json`, bootstrap-empty, stripped-`.relicario/`. Each is one extra `#[test]`. (DEV-B)
|
||||
|
||||
### WASM (Rust)
|
||||
- **Redundant double-lookup pattern.** `lib.rs:73, 84, 92, 103, 111, 122, 160, 172` all do `need_key(handle)?` then `session::with(handle.0, |k| ...).unwrap()` — two HashMap lookups per call. Single-`with` helper that returns `JsError` on miss. (DEV-B)
|
||||
- **`Vec<u8>` getters clone on every read.** `EncryptedAttachment::aid` and `bytes` (`lib.rs:141-150`). Document "call once, cache locally" or consume by value. (DEV-B)
|
||||
- **`wasm_*_recovery_qr` prefix is inconsistent** with everything else. `lib.rs:497, 510`. Rename to `generate_recovery_qr_svg` and `unwrap_recovery_qr` (and update `extension/src/wasm.d.ts`). Trivial breaking rename — do it before any new caller appears. (DEV-B)
|
||||
- **`device.rs` and `session.rs` use different concurrency primitives** (`Lazy<Mutex<...>>` vs `thread_local! { RefCell<...> }`). Pick one. (DEV-B)
|
||||
- **`extension/src/wasm.d.ts` is hand-written and explicitly requires manual sync** with `crates/relicario-wasm/src/lib.rs`. Every change to `#[wasm_bindgen]` must be mirrored manually; today they're aligned. Add a CI check comparing `wasm-pack`–generated `.d.ts` against this file, or import the generated file directly. (DEV-C; partner finding to DEV-B's WASM section.)
|
||||
|
||||
### Extension — service-worker
|
||||
- **Inactivity timer reset skips content-callable messages** (`service-worker/index.ts:76-78`). A user actively autofilling but not opening the popup will be force-locked despite continuous use. Reset on all messages except known read-only content calls. (DEV-C)
|
||||
- **Session expiry clears `state.manifest` but leaves `state.gitHost`** (`service-worker/index.ts:51-58`). Cached git-host client survives expiry; rotation could mix with stale connection state. Null `state.gitHost` alongside. (DEV-C)
|
||||
- **`try { current.free() }` swallows free errors** (`service-worker/session.ts:26`). See P1.1 — this becomes important once `impl Drop` lands. (DEV-C)
|
||||
|
||||
### Extension — popup + components
|
||||
- **Duplicated teardown helpers** (`settings.ts:56-65` and `settings-vault.ts:15-22`). After the recent stub-restore commits (`8baef5b`, `ddfb95d`), teardown leaks are a known regression class — duplicated cleanup is exactly the pattern that re-introduces them. Extract a single `teardownSettingsCommon()`. (DEV-C; originally P1, demoted by PM because the leak vector is small but the duplication is real.)
|
||||
- **Settings module-scope singletons** (`settings.ts:33-34`). `pendingVaultSettings` and `sessionHandle` survive section navigation. Reset on `renderSection` entry, or scope into a closure per render. (DEV-C)
|
||||
- **Item-list popover wires listeners on every render** (`item-list.ts:152-353`) without a reuse path. Cache the DOM and reuse, or use AbortController. (DEV-C)
|
||||
- **`Promise.all` without per-promise error handling** (`devices.ts:47-50`, `trash.ts:39-46`). Single rejected RPC fails the whole render. Use `Promise.allSettled`. (DEV-C)
|
||||
- **Generator-panel cleanup not idempotent-guarded** (`generator-panel.ts:89-261`). Currently safe by accident. Add `if (!activePanel) return`. (DEV-C)
|
||||
- **Popup teardown calls every type module unconditionally** (`popup.ts:178-181`). Track last-mounted type. (DEV-C)
|
||||
|
||||
### Extension — vault tab
|
||||
- **Vault tab intercepts `vault_locked` via RPC; popup uses `session_expired` event.** `vault/vault.ts:47-74`. See P1.5 — collapse into one mechanism in `shared/state.ts`. (DEV-C)
|
||||
- **Drawer doesn't auto-close on non-list view changes** (`vault.ts:495-536`). Reset `state.drawerOpen = false` in `renderPane`. (DEV-C)
|
||||
- **Sidebar re-renders on every search keystroke without debounce** (`vault.ts:648-695`). 50-100ms debounce. (DEV-C)
|
||||
|
||||
### Extension — content scripts
|
||||
- **`fillFields()` returns silently when no password field is found** (`content/fill.ts:50-64`). Dynamic forms can race the listener; user clicks autofill, nothing happens. Send a `fill_failed` ack. (DEV-C)
|
||||
- **MutationObserver scan is not debounced** (`content/detector.ts:96-103`). SPA churn re-runs the full scan many times per second. Wrap in `requestIdleCallback` or 200ms timer. (DEV-C)
|
||||
- **Outside-click listener leaks on alternate close paths** (`content/icon.ts:169-175`). AbortController scoped to picker open, or remove in every close path. (DEV-C)
|
||||
|
||||
### Extension — setup
|
||||
- **`setup.ts` 1220-LOC procedural wizard.** Step registry pattern. See P1.4. (DEV-C)
|
||||
- **`WizardState` is module-scope; sensitive material persists if user abandons mid-wizard** (`setup.ts:69-94`). Add `clearWizardState()` on `beforeunload` and on returning to step 0. Folds into P1.4. (DEV-C)
|
||||
- **Manifest path constants duplicated** between `setup/probe.ts:11-23` and `service-worker/vault.ts`. Define `VAULT_PATHS` in `shared/types.ts` (or `shared/paths.ts`). (DEV-C)
|
||||
|
||||
### Extension — shared utilities
|
||||
- **Base `Response` is `{ data?: unknown }`; every consumer does hand-written `as ListItemsResponse` casts** (`shared/messages.ts:85-87`). Generic `Response<TKind extends Request['type']>` mapped from a single `MessageMap` table. (DEV-C)
|
||||
- **`group-autocomplete.ts:26` builds list HTML via `innerHTML` with only `"` escaping.** Group names are user-entered. `<` and `>` aren't escaped — markup-injection risk. Use `document.createElement('option')`. (DEV-C)
|
||||
- **`restore_backup` flattens `newRemote` inline** (`shared/messages.ts:56-66`). Inconsistent with sibling messages. Extract `RestoreBackupPayload`. (DEV-C)
|
||||
|
||||
### WASM boundary (JS side)
|
||||
- **`__stubs__/relicario_wasm.stub.ts` only stubs 7 of ~25 exports.** Adding a vitest test that touches a new WASM call needs an ad-hoc per-test mock. Round out the stub or provide a `mockWasm({...})` test helper. (DEV-C)
|
||||
|
||||
### Relay tooling
|
||||
- **`tools/relay/start.sh:80` may still reference "Dev-B"** in user-facing output despite the dev-c expansion. Confirm a fourth window opens for dev-c. (DEV-C)
|
||||
- **`tools/relay/call.py` and `call.ts` are untracked but load-bearing** for the multi-agent fallback path (kickoff prompts reference `call.py` by path). Either track them with a one-line header explaining "MCP-fallback shim" or add to `.gitignore`. (DEV-C)
|
||||
- **In-memory queue has no TTL, persistence, or cap** (`queue.ts:21-27`). Document the dev-only ephemeral contract or add a per-role cap. (DEV-C)
|
||||
|
||||
### Cross-cutting
|
||||
- **`#[allow(dead_code)]` without explanation** appears in `cli/device.rs`, `cli/gitea.rs`, and `wasm/device.rs`. Each is either "API completeness" or "scar tissue." Annotate with `// TODO(<plan>):` or delete. (DEV-B)
|
||||
- **Direct `chrome.storage.local` reads from popup components** (`settings-security.ts:112-113`, `setup.ts:1056-1062`). Every other module routes via `sendMessage`. Pick one paradigm and document the exception. (DEV-C)
|
||||
- **`bun test` is not the project's intended runner** (`extension/package.json:13` is `vitest run`; `tools/relay/` uses `node:test` via `bun test`). README clarification. (DEV-C)
|
||||
- **Error formatting is inconsistent** across all three Rust crates: CLI mixes sentence-case and lowercase fragments; server is `eprintln!("REJECT: ...")` *except* the malformed-devices.json path; WASM ranges from explicit messages to `RelicarioError::Display` passthrough. Short style note + audit pass. (DEV-B)
|
||||
|
||||
## P3 / nice-to-have
|
||||
|
||||
A long tail of style sweeps and small ergonomic wins. Pulling the most representative; full lists in the per-reviewer notes.
|
||||
|
||||
- Inconsistent error types and constant styles in core (`MonthYear::new -> Result<_, &'static str>`; `pub const MAGIC: [u8;4]` vs `const MAGIC: &[u8;4]`; empty `[dev-dependencies]`). (DEV-A)
|
||||
- Mid-file `use` blocks in `item.rs:117-122` and `attachment.rs:43-46`. (DEV-A)
|
||||
- `r#type` field on `Item` and `ManifestEntry` — rename to `item_type` with `#[serde(rename = "type")]`. (DEV-A)
|
||||
- BIP39 minimum word count of 3 is misleading vs. the 128-bit-security framing — restrict to canonical sets or rename to "BIP39-wordlist passphrase generator." (DEV-A)
|
||||
- `STEAM_ALPHABET` source comment contradicts its own test about the '5' character. (DEV-A)
|
||||
- `let _ = entry;` newcomer-hostile pattern repeated 6× in CLI. (DEV-B)
|
||||
- `cmd_recovery_qr_unwrap` doesn't check empty input before base64 decode; QR ASCII and "NOT been saved" mixed on stdout (pipe-unfriendly). (DEV-B)
|
||||
- `Lock` CLI subcommand is a visible no-op; either `#[command(hide = true)]` or document the parity rationale. (DEV-B)
|
||||
- Three test-only env vars duplicated under `#[cfg(debug_assertions)]/#[cfg(not(debug_assertions))]` — one macro flattens ~30 lines. (DEV-B)
|
||||
- WASM exports use snake_case in JS (`manifest_encrypt`); JS idiom is camelCase. Decide once via `#[wasm_bindgen(js_name = ...)]`. (DEV-B/DEV-C)
|
||||
- Glyph-rule partial adoption — six popup files use raw glyph literals (`⧉`, `↻`, `▸`, `▾`, `≡`, `⤓`) inline despite the `glyphs.ts` abstraction. Add the missing constants and migrate. (DEV-C)
|
||||
- `TotpKind = 'totp' | 'steam' | { hotp: { counter: number } }` mixed string/object union — flat discriminated union reads cheaper. (DEV-C)
|
||||
- `void tick()` in `totp-tools.ts:39-46` swallows promise rejections. (DEV-C)
|
||||
- `setup.ts:1-7` header says "5-step flow"; code is 6 steps (0..5). (DEV-C)
|
||||
- `helpers.rs:37 #[allow(dead_code)] pub fn relicario_dir()` has no callers but several `vault_dir.join(".relicario")` sites should use it. (DEV-B)
|
||||
- `gitea.rs` constructs a fresh `reqwest::blocking::Client::new()` per method call — make it a struct field. (DEV-B)
|
||||
|
||||
## Cross-cutting themes
|
||||
|
||||
**1. The "where the work happens" boundary holds, but two surfaces lie about it.** `relicario-core` is genuinely platform-agnostic (no fs, no net, no git) and the server provably cannot decrypt (no AEAD/KDF crate present). The extension's content scripts make zero direct WASM calls. These are excellent structural invariants. The two surfaces that break the pattern are `extension/src/setup/setup.ts` (loads WASM and orchestrates crypto directly, bypassing the SW) and the `SessionHandle` `.free()` non-cleanup contract on the WASM/JS boundary. Both are P1; both are also single-surface fixes. The architecture is one P1.1 + one P1.4 away from being uniform.
|
||||
|
||||
**2. Duplication concentrates at boundaries, not inside modules.** The two router files duplicate storage helpers and `itemToManifestEntry` (P1.9). The CLI duplicates git-shell error UX 16× (P1.3). Three base32 implementations live in core (P2). Two `ParamsFile` definitions disagree (P2). `parse_month_year` / `base32_decode_lenient` / `guess_mime` live only in the CLI but the extension will need them (P1.10). The pattern: every time a concept crosses a module/crate boundary, the second crossing copies the first instead of importing it. The remedy is small extractions (one helper module per cluster), not refactors. None of these are individually expensive; together they account for a meaningful fraction of total findings.
|
||||
|
||||
**3. Three files account for most of the readability cost.** `cli/main.rs` (2641 LOC), `setup.ts` (1220 LOC), `vault.ts` (1027 LOC). Each carries multiple concerns that belong in sibling modules. Splitting all three is cumulative ~M-L effort and unlocks several smaller cleanups (centralizing groups-cache discipline depends on splitting `main.rs`; the SW message-routing fix depends on extracting `setup.ts`'s WASM orchestration; lifting the `vault_locked` channel depends on splitting `vault.ts`). For the user's stated learning-by-tinkering goal, these three splits are the highest-leverage architectural moves available.
|
||||
|
||||
**4. Documentation density is uneven in exactly one place.** Core's security-critical files (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`) open with multi-paragraph rationale walking through the *why*. `recovery_qr.rs` does not — and it's the user-visible last-resort recovery mechanism. Bringing one file up to the existing standard is a P1.7 effort of S. Beyond that one file, the core doc story is genuinely strong; preserve it.
|
||||
|
||||
## What's strong (preserve)
|
||||
|
||||
- **`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`: documentation density.** Each opens with multi-paragraph rationale (XChaCha20 vs AES-GCM, QIM with QUANT_STEP=50, length-prefixed concatenation, tar-bomb defenses). This is the model the rest of the crate should be measured against.
|
||||
- **`relicario-server` trust-model enforcement via the import surface.** The server cannot decrypt the vault even in principle: no AEAD or KDF crate in its dep graph; the entire `relicario-core` import surface is `DeviceEntry`, `RevokedEntry`, `fingerprint`, and (in tests) `generate_keypair` — all plaintext device metadata. This is structural, not by convention.
|
||||
- **Discriminated-union message contract in the extension.** `shared/messages.ts` + the `POPUP_ONLY_TYPES` / `CONTENT_CALLABLE_TYPES` capability sets give every router handler typed dispatch with origin-aware gating. Content scripts make zero WASM calls and re-validate origin in `fill.ts:32-38`. The boundary discipline holds.
|
||||
- **Test design across the codebase.** Synthetic JPEGs via `make_test_jpeg()` (no binary fixtures), raw-byte tar bombs that bypass the tar crate's sanitizer, RFC6238 vector for TOTP, an independent reference impl cross-check for Steam, ~30 LastPass importer cases, NFC/NFD round-trips, day-boundary tests for retention. The tests are themselves a documentation artifact.
|
||||
- **Helpers.rs in the CLI.** Small, focused, tested, and the doc-comment at `:90-93` explaining the plaintext `groups.cache` trade-off is admirably explicit. The git-command hardening (`core.hooksPath=/dev/null`, `commit.gpgsign=false`, `core.editor=true`) is exactly the right kind of comment to leave for a learner.
|
||||
|
||||
## CLI/extension parity status
|
||||
|
||||
Per DEV-C's full table: **22 of 23 CLI subcommands have a clean extension equivalent**.
|
||||
|
||||
- **Clean parity (✓)**: `init`, `add` (all 7 item kinds), `get`, `list` (with all filters), `edit`, `history`, `rm` (soft delete), `restore`, `purge`, `trash list`/`empty`, `backup export`/`restore`, `import lastpass`, `attach`, `attachments`, `extract`, `generate`, `settings *`, `sync`, `lock`, `rate`, `device add`/`revoke`/list, `recovery-qr generate`/`unwrap`. The settings unification under v0.5.1's left-nav (commit `bd6a301`) is the right shape.
|
||||
- **Partial (✗ish)**: `detach <item> <aid>`. Extension uses a roundtrip through `update_item` with the `attachments[]` mutated client-side. Functional but racy if two devices edit at once. **Suggested fix**: add a `delete_attachment` SW message that does the surgical remove server-side. (P3.)
|
||||
- **True gap (✗)**: `relicario status`. CLI shows pending sync state, ahead/behind, dirty-tree summary; extension surfaces nothing comparable. **Suggested fix**: `get_vault_status` message returning `{ ahead, behind, lastSyncAt, pendingItems }` plus a small status indicator in the vault sidebar. (P2.)
|
||||
- **Browser-only (by design)**: `get_autofill_candidates`, `get_credentials`, `check_credential`, `blacklist_site`, `capture_save_login`, `fill_credentials`, `ack_autofill_origin`, `get_blacklist`, `remove_blacklist`, `get_active_tab_url`, `update_settings` for `DeviceSettings`. No CLI counterpart needed.
|
||||
- **CLI-only (by design)**: `completions <shell>`. n/a.
|
||||
|
||||
**No "CLI first, extension follow-up" violations found** under this lens. The parity philosophy is intact; the one gap and the one partial are surgical fixes, not architectural debt.
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
|
||||
Three reviewers converge on a consistent story for a smart developer who's never written Rust but wants to learn by tinkering.
|
||||
|
||||
**Where the floor is high already:**
|
||||
- `crates/relicario-core/` reads beautifully: bytes-in/bytes-out boundary holds, public API is enumerated in one `lib.rs`, module names map directly to vault concepts (`item`, `manifest`, `attachment`, `settings`, `generators`, `vault`, `backup`, `device`, `recovery_qr`), and the algorithmically dense `imgsecret.rs` is the most heavily commented. A reader can land in `crypto.rs`, follow `derive_master_key` → `encrypt` → `vault::encrypt_item`, and reach `tests/integration.rs::full_workflow_login_and_note` in one sitting.
|
||||
- `relicario-server` is 189 lines, one trust-model question, every dependency is plaintext metadata. Readable end-to-end in under ten minutes.
|
||||
- The extension's discriminated-union message contract (`shared/messages.ts` + `types.ts`) gives the entire vocabulary in 500 lines. The per-type item form modules (`popup/components/types/login.ts` and siblings) are small parallel surfaces — once one clicks, the others read as variations.
|
||||
|
||||
**Where the cliff is:**
|
||||
- **`cli/main.rs`** at 2641 LOC is the first real wall. A reader following `cmd_add` finds 7 peer `build_*_item` functions plus 6 prompt helpers plus 3 parsers, all in a flat file. (P1.2.)
|
||||
- **`extension/src/setup/setup.ts`** at 1220 LOC is the second wall, and it's worse because it lies about the architecture: a reader who opens this file first sees WASM imported directly and concludes that's the pattern — it isn't. (P1.4.)
|
||||
- **`extension/src/vault/vault.ts`** at 1027 LOC is the third. The vault tab is the user's primary surface; the orchestrator file shouldn't also be the implementation file. (P1.5.)
|
||||
- **`shared/state.ts`** is the weakest learning surface in the extension — `any`-typed bridge between popup and vault tab, no double-registration guard. (P1.6.)
|
||||
- **`recovery_qr.rs`** in core is the one file where a reader will hit a wall in an otherwise-well-documented crate. (P1.7.)
|
||||
|
||||
**The single most valuable change** for the user's stated goal: split `cli/main.rs` into a `commands/` folder (P1.2). It's the first file a tinkerer opens, the change is mechanical, and it unlocks several smaller cleanups (centralized git error UX, unified groups-cache discipline). After that, in order: bring `recovery_qr.rs` to the existing core doc standard (P1.7), extract `setup.ts`'s WASM orchestration into SW messages (P1.4), and split `vault.ts` (P1.5). The four together turn "this is mostly readable" into "this is uniformly readable."
|
||||
|
||||
## Open architectural decisions (escalated by reviewers; user judgement)
|
||||
|
||||
Pulled from DEV-B's question list and DEV-C's flags. None are blockers for the synthesis; each is a one-paragraph user decision.
|
||||
|
||||
1. **Was `impl Drop for SessionHandle` deliberately omitted?** (e.g. to avoid double-free if JS holds two refs.) PM verdict at synthesis: not deliberate; it's the headline fix (P1.1). User: confirm.
|
||||
2. **Should CLI `parse_month_year`, `base32_decode_lenient`, `guess_mime` migrate to core?** PM verdict: yes, for parity (P1.10). User: confirm timing.
|
||||
3. **Is "missing `.relicario/devices.json` = bootstrap = accept" intended in perpetuity?** Or should it tighten once a repo has any non-empty devices.json in history? (DEV-B P2.) User: pick a rule.
|
||||
4. **Is the `Lock` no-op CLI subcommand worth keeping visible in `--help` for parity?** Or hide behind `#[command(hide = true)]`? (DEV-B P3.) User: pick.
|
||||
5. **Has Task 12 shipped?** `cmd_backup_export` still reads `devices.json` per a "Task 12 will remove" TODO at `main.rs:1535-1537`. (DEV-B P3.) User: confirm and clean up.
|
||||
6. **Track `tools/relay/call.py` and `call.ts`, or `.gitignore` them?** They're load-bearing for the multi-agent fallback path. (DEV-C P2.) PM verdict: track them — they're documented in coordination prompts.
|
||||
7. **WASM JS naming: snake_case (current) or camelCase?** Trivial breaking rename via `#[wasm_bindgen(js_name = ...)]`, but only if done before the surface grows. (DEV-B/DEV-C P3.) User: pick once.
|
||||
8. **`.gitea_env_vars` is untracked.** Name suggests local credentials. PM verdict: should be `.gitignore`d if it isn't already. User: confirm.
|
||||
|
||||
## Appendix: pointers to per-reviewer notes
|
||||
|
||||
- [DEV-A notes — Rust core](./2026-05-04-dev-a-notes.md)
|
||||
- [DEV-B notes — Rust consumers (CLI, server, WASM)](./2026-05-04-dev-b-notes.md)
|
||||
- [DEV-C notes — TypeScript (extension + relay)](./2026-05-04-dev-c-notes.md)
|
||||
191
docs/superpowers/reviews/2026-05-04-dev-a-notes.md
Normal file
191
docs/superpowers/reviews/2026-05-04-dev-a-notes.md
Normal file
@@ -0,0 +1,191 @@
|
||||
# DEV-A Architecture Review Notes — Rust Core
|
||||
|
||||
Scope: `crates/relicario-core/src/**` (17 source files, ~5.5 kLOC) and `crates/relicario-core/tests/**` (9 integration suites). HEAD reviewed; the only uncommitted change in core is a version bump (`0.2.0 → 0.5.0` in `Cargo.toml`), nothing semantic.
|
||||
|
||||
## Summary
|
||||
|
||||
The crate has a clear, well-shaped architecture: a thin `lib.rs` re-exporting one concept per module, a unified `RelicarioError` enum, and a strict bytes-in/bytes-out posture (no fs, no net, no git anywhere — the boundary is held). The strongest part is the documentation density of the security-critical files: `crypto.rs`, `imgsecret.rs`, `backup.rs`, and `tar_safe.rs` each open with multi-paragraph rationale that walks a reader through the *why* (XChaCha20 vs AES-GCM, QIM with QUANT_STEP=50, length-prefixed concatenation, tar-bomb defenses) — exactly the "legibility-as-security" philosophy the README aspires to. Tests are excellent: RFC6238 vector for TOTP, an independent reference impl cross-check for Steam, NFC/NFD round-trips, raw-byte tar bombs that bypass the tar crate's sanitiser, and ~30 LastPass importer cases. The weakest part is unevenness — `recovery_qr.rs` is essentially undocumented despite being the user-visible last-resort recovery mechanism, and three modules (`vault.rs`, `manifest.rs`, `attachment.rs`) still carry "during this rewrite" / "added later in Task 22" headers from work that has long since shipped, which will mislead a newcomer about what's load-bearing.
|
||||
|
||||
`cargo clippy -p relicario-core --all-targets --no-deps` runs clean (no warnings).
|
||||
|
||||
## Findings (prioritized)
|
||||
|
||||
### P1 — `recovery_qr.rs` doc gap is conspicuous against the rest of the crate
|
||||
|
||||
**File(s):** `crates/relicario-core/src/recovery_qr.rs:1-130` (whole file)
|
||||
**Observation:** No module-level `//!` header. No doc comments on `RecoveryQrPayload`, `generate_recovery_qr`, `unwrap_recovery_qr`, or `recovery_qr_to_svg`. Magic constants (`RREC`, `VERSION = 0x01`, `PAYLOAD_LEN = 109`) sit at top with no explanation, and the 4+1+32+24+48 layout is hand-counted with no struct, no diagram, and no asserts. The domain-separation prefix `b"relicario-recovery-v1\0"` exists but isn't explained. `production_params()` redeclares the same values as `KdfParams::default()` with no comment on why the recovery format pins them.
|
||||
**Why it matters:** Every other security-relevant file (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`) has the explanatory framing this codebase rewards readers for. A newcomer hitting `recovery_qr.rs` sees a different style and assumes either it doesn't matter or they've stumbled out of the documented zone. It does matter — this is a vault-key escape hatch — and a misuse here (e.g., reusing `production_params` as `KdfParams::default()` and then changing the default) silently breaks all extant recovery QRs.
|
||||
**Suggested direction:** Add a module-level `//!` summarizing the format, the KDF-input domain separation, and the parameter-pinning rationale. Add a short ASCII diagram of the 109-byte layout near the constants. Doc-comment the four public functions. Either replace `production_params()` with a `const` or add a comment explaining the deliberate divergence from `KdfParams::default()`.
|
||||
|
||||
### P2 — Stale "in-progress rewrite" headers in three core files
|
||||
|
||||
**File(s):**
|
||||
- `crates/relicario-core/src/vault.rs:1-7` ("v1 helpers ... intentionally NOT carried forward. The CLI rewrite in Plan 1B switches to the new helpers.")
|
||||
- `crates/relicario-core/src/manifest.rs:1-2` ("Lives next to the old entry.rs Manifest during this rewrite; entry.rs is deleted in Task 25.")
|
||||
- `crates/relicario-core/src/attachment.rs:1-4` ("Encryption helpers ... are added later in Task 22 once the crypto module is settled.")
|
||||
|
||||
**Observation:** Each comment describes work that has already shipped. Task 22 added the helpers (they're 30 lines below in the same file). `entry.rs` is gone. Plan 1B is merged. The text reads as if there's a sibling file or a future change to wait for.
|
||||
**Why it matters:** A newcomer trying to understand the manifest will go looking for `entry.rs` to compare. A newcomer reading `attachment.rs` will read past the helpers thinking "those are coming later." These are the cheapest possible cleanup — comment edits — and they each remove a tripwire.
|
||||
**Suggested direction:** Replace with a one-line description of what the module *is*, not what it was during the rewrite.
|
||||
|
||||
### P2 — `extract_with_crop_recovery` is narrower than the spec describes
|
||||
|
||||
**File(s):** `crates/relicario-core/src/imgsecret.rs:849-899`
|
||||
**Observation:** The design spec (`docs/superpowers/specs/2026-04-11-relicario-design.md` §imgsecret extraction step 3) says crop recovery iterates `(dx, dy)` from -15% to +15% stepping by 8 px (~16,800 candidates for 4000×3000). The code only varies assumed original `orig_w`/`orig_h` while pinning `dx = 0, dy = 0`. The successful-crop test at `imgsecret.rs:1108-1137` only crops the *right* edge, where dx=0 happens to be the correct offset.
|
||||
**Why it matters:** Crops from the *left* or *top* (e.g. an Instagram square crop centered on a portrait, or any social-media platform that re-frames around faces) won't recover. The spec promises "15% from any edge"; the implementation delivers ~15% from the right and bottom only. Either the spec is wrong (which is allowed — the spec is marked historical) or the implementation has a quiet hole in the recovery surface. If the user ever uploads their reference JPEG to a service that left-crops, recovery will fail and the failure mode looks like "your image is wrong" rather than "we don't try that crop direction."
|
||||
**Suggested direction:** Either (a) extend the recovery loop with a small dx/dy search bounded by the 15% margin, or (b) update the spec language and the user-facing docs to say "right/bottom crop tolerance only." A third option is to add a test that left-crops a watermarked image and currently fails — that captures the gap and lets future work close it.
|
||||
|
||||
### P2 — Two dead fields in `EmbedRegion`
|
||||
|
||||
**File(s):** `crates/relicario-core/src/imgsecret.rs:225-229`
|
||||
**Observation:** `region_width` and `region_height` are computed in `compute_region`, stored in the struct, and silenced with `#[allow(dead_code)]`. Nothing reads them — downstream code uses `blocks_x` / `blocks_y` and `BLOCK_SIZE`.
|
||||
**Why it matters:** The `#[allow(dead_code)]` is an explicit "I know this is unused" — a newcomer reasonably assumes the fields are load-bearing and will hunt for the consumers, finding nothing. Either they're pre-positioned for a future feature (in which case a comment saying so would help) or they should go.
|
||||
**Suggested direction:** Delete both fields and the allow attributes, or add a one-line comment explaining the future use. (The struct is private, so removal is risk-free.)
|
||||
|
||||
### P2 — Three base32 implementations live in one crate
|
||||
|
||||
**File(s):**
|
||||
- `crates/relicario-core/src/item.rs:255-275` (`base32_encode`, RFC 4648 alphabet)
|
||||
- `crates/relicario-core/src/import_lastpass.rs:202-220` (`decode_base32_totp`, same alphabet)
|
||||
- `crates/relicario-core/src/item_types/totp.rs:13` (`STEAM_ALPHABET`, *different* alphabet — by design)
|
||||
|
||||
**Observation:** The first two are inverses of each other but live in different modules with no shared helper. The third is intentionally different (Steam Guard's de-ambiguated alphabet). They all hand-roll the bit-packing loop.
|
||||
**Why it matters:** A reader who finds one of the three has to grep to discover whether there are others, and whether they agree. A future change to the RFC 4648 path (e.g., padding behavior) needs to be applied in two places.
|
||||
**Suggested direction:** Extract a small `pub(crate) mod base32` with `encode_rfc4648`, `decode_rfc4648`, leaving Steam's bespoke alphabet where it is (with a `// not RFC 4648 — Steam Guard's de-ambiguated alphabet` neighbour comment).
|
||||
|
||||
### P2 — Backup format embeds the reference JPEG as base64-in-JSON
|
||||
|
||||
**File(s):** `crates/relicario-core/src/backup.rs:148-152, 274-280, 343-345`
|
||||
**Observation:** The `Envelope.vault.reference_jpg: Option<String>` carries the JPEG as base64-encoded JSON string. After zstd (which can't compress JPEG), a 4 MB reference photo bloats by ~33% from base64 plus JSON overhead.
|
||||
**Why it matters:** Backup files for users who bundle the reference image will be substantially larger than necessary. Round-trip works (covered by `tests/backup.rs:96-106`), so this is a footprint concern, not a correctness one. Worth flagging if backup size ever shows up in a complaint.
|
||||
**Suggested direction:** Bump `FORMAT_VERSION` and put `reference_jpg` and `git_archive` in a binary tail outside the JSON envelope, base64 only the small bytes. Defer until there's actual user pressure on backup size.
|
||||
|
||||
### P3 — Inconsistent error types and constant styles
|
||||
|
||||
**Observations (all small, batched here):**
|
||||
- `crates/relicario-core/src/time.rs:18` — `MonthYear::new` returns `Result<Self, &'static str>` instead of `RelicarioError`. Every other constructor in the crate uses the unified error type.
|
||||
- `crates/relicario-core/src/backup.rs:30` declares `pub const MAGIC: [u8; 4] = *b"RBAK";`; `crates/relicario-core/src/recovery_qr.rs:7` declares `const MAGIC: &[u8; 4] = b"RREC";`. Two different idioms for the same concept in adjacent files.
|
||||
- `crates/relicario-core/Cargo.toml:36` has an empty `[dev-dependencies]` table (delete the header).
|
||||
- `crates/relicario-core/src/crypto.rs:248-261` `derive_master_key_raw` is `pub` but only consumed by `recovery_qr.rs` inside this crate (verified via grep). `pub(crate)` would prevent accidental external misuse.
|
||||
|
||||
**Why it matters:** Each is trivial in isolation, but for a Rust newcomer reading the crate front-to-back, every inconsistency is a moment of "wait, why is this one different?" — and the answer is almost always "no reason, just historical."
|
||||
**Suggested direction:** Pick one form for each pattern, sweep.
|
||||
|
||||
### P3 — Mid-file `use` blocks in `item.rs` and `attachment.rs`
|
||||
|
||||
**File(s):** `crates/relicario-core/src/item.rs:117-122`, `crates/relicario-core/src/attachment.rs:43-46`
|
||||
**Observation:** Both files have `use` statements partway down the file (in `item.rs`, after `Section`; in `attachment.rs`, after `AttachmentSummary`). Idiomatic Rust hoists all `use` to the top.
|
||||
**Why it matters:** Newcomer expectation; trivial to fix.
|
||||
|
||||
### P3 — `derive_icon_hint` only handles `Login` with no comment about other types
|
||||
|
||||
**File(s):** `crates/relicario-core/src/manifest.rs:84, 92-99`
|
||||
**Observation:** Only `ItemCore::Login` produces a hostname hint; `_ => None` for the other six. No comment explaining why card-brand / favicon-from-URL / etc aren't derived for other types.
|
||||
**Suggested direction:** One-line `// only Login items have a URL today; other types don't have an obvious icon source.` (Or implement card-brand / identity-favicon if the popup UI wants them.)
|
||||
|
||||
### P3 — `attachment.rs` has WHAT-comments on a deref pattern
|
||||
|
||||
**File(s):** `crates/relicario-core/src/attachment.rs:60-63, 83-85`
|
||||
**Observation:** Two "Call-site adaptation" sections explain `&**master_key` in prose. The pattern is idiomatic Rust deref-coercion; the comment explains *what* not *why*.
|
||||
**Suggested direction:** Delete both comment blocks. The code is self-documenting; if anything, the cognitive load is in the comment, not the deref.
|
||||
|
||||
### P3 — TOTP dynamic-truncation extraction is reproduced four times
|
||||
|
||||
**File(s):** `crates/relicario-core/src/item_types/totp.rs:75-99` (3 algorithm arms each duplicate the DT slice math), `217-228` (test reference impl reproduces it again).
|
||||
**Suggested direction:** Extract a `fn dt(hmac_out: &[u8]) -> u32` helper. The test would still need its own copy as the cross-check.
|
||||
|
||||
### P3 — `STEAM_ALPHABET` source comment contradicts its own test
|
||||
|
||||
**File(s):** `crates/relicario-core/src/item_types/totp.rs:13` and `:287-291`
|
||||
**Observation:** Source comment says "excludes ambiguous glyphs (0/O, 1/I/L, S/5, A/Z)". Test docstring at line 287 says "Note: '5' IS in the alphabet — S is excluded, so 5 is unambiguous." The test is right; the source comment is wrong about '5'.
|
||||
**Suggested direction:** Fix the source comment to match the test (and the actual alphabet).
|
||||
|
||||
### P3 — `device.rs::sign` and `verify` share an extraction pattern that begs for a helper
|
||||
|
||||
**File(s):** `crates/relicario-core/src/device.rs:64-72, 86-94`
|
||||
**Observation:** Both functions do `key_data.ed25519().ok_or(...)?.try_into::<[u8; 32]>().map_err(...)?`. Five-line copy.
|
||||
**Suggested direction:** A `fn ed25519_bytes_from_private(...) -> Result<[u8; 32]>` and a `fn ed25519_bytes_from_public(...)` would each fold the extraction. Minor; not worth a refactor on its own but a free win if the file is being touched.
|
||||
|
||||
### P3 — `imgsecret.rs::read_block`'s `.unwrap()` deserves a one-liner
|
||||
|
||||
**File(s):** `crates/relicario-core/src/imgsecret.rs:315-319`
|
||||
**Observation:** `read_block_abs(...).unwrap()` is safe because `compute_region` guarantees the block lies inside the embed region, but the invariant isn't stated.
|
||||
**Suggested direction:** `// safe: compute_region ensures (start_x, start_y) + 8 fits within the image`. Same idea as the existing `expect("ascii-only charset")` in `generators.rs:64`.
|
||||
|
||||
### P3 — `r#type` field on `Item` and `ManifestEntry`
|
||||
|
||||
**File(s):** `crates/relicario-core/src/item.rs:134`, `crates/relicario-core/src/manifest.rs:23`
|
||||
**Observation:** Using `r#type` (raw identifier) because `type` is a reserved keyword. Functional but jarring; a Rust newcomer doesn't know what `r#` means and won't immediately realize it's a field name not a type prefix.
|
||||
**Suggested direction:** Rename to `item_type` with `#[serde(rename = "type")]` to keep wire format. Minor ergonomic win.
|
||||
|
||||
### P3 — BIP39 minimum word count of 3 is misleading
|
||||
|
||||
**File(s):** `crates/relicario-core/src/generators.rs:79-86`
|
||||
**Observation:** `word_count` accepted range is `3..=12`. BIP39 spec proper starts at 12 words. 3-word output has only ~33 bits of entropy and would never pass `validate_passphrase_strength` for security uses, but the API permits it. The comment "This gives full-entropy sourcing even for short passphrases" elides that effective entropy is `word_count * log2(2048) = 11 * word_count`, not 128 bits.
|
||||
**Suggested direction:** Either restrict to BIP39's actual word counts (12, 15, 18, 21, 24) or document that this is a *passphrase generator inspired by BIP39* (using its wordlist) rather than a BIP39 mnemonic generator. The latter is honest about what the code actually does.
|
||||
|
||||
### P3 — `StrengthEstimate::guesses_log10` uses base-10 while the spec talks bits
|
||||
|
||||
**File(s):** `crates/relicario-core/src/generators.rs:111-113`
|
||||
**Observation:** `guesses_log10: f64` is base-10 log of guess count; the design spec discusses entropy in bits. Mild domain-translation friction for callers.
|
||||
**Suggested direction:** Add a one-line comment showing the bits conversion (`bits ≈ guesses_log10 * log2(10) ≈ guesses_log10 * 3.32`), or expose a `bits_estimate()` accessor.
|
||||
|
||||
## File-by-file walk
|
||||
|
||||
**`lib.rs` (99 lines).** Crate-level docs are tight and accurate; the crypto pipeline diagram in the header is the right thing to greet a newcomer with. Public re-exports surface every meaningful type from one location. Clear.
|
||||
|
||||
**`error.rs` (195 lines).** Single error enum with thiserror. Every variant carries helpful context (item id, byte counts, found/expected version) except `Decrypt` which is opaque on purpose (audit M4). Tests exercise the public message format. Reads well.
|
||||
|
||||
**`crypto.rs` (437 lines).** The cornerstone. Module-level doc explains why XChaCha over AES-GCM and the binary layout. `derive_master_key` does NFC normalization + length-prefixed concatenation, both with explicit "audit H1" provenance comments. `decrypt_v1` rejection is tested. `derive_master_key_raw` is the seam used by the recovery QR. Solid.
|
||||
|
||||
**`ids.rs` (161 lines).** `ItemId`/`FieldId` are 64-bit random hex; `AttachmentId` is content-addressed (SHA-256 truncated to 128 bits). `is_valid()` provides a path-traversal guard (tested for `../../etc`). Header comment cites the audit IDs (M8, I2/B4) that motivated the entropy bumps from v1 — that traceability is great.
|
||||
|
||||
**`time.rs` (63 lines).** `now_unix()` and `MonthYear`. Only blemish is `MonthYear::new -> Result<_, &'static str>`; everything else returns `RelicarioError`.
|
||||
|
||||
**`vault.rs` (90 lines).** Six typed encrypt/decrypt wrappers (item / manifest / settings) that JSON-roundtrip through the crypto layer. Mechanical and correct. Stale module header (P2).
|
||||
|
||||
**`item.rs` (497 lines).** Defines the Item envelope, Field/FieldKind/FieldValue, Section, FieldHistoryEntry. Kind/value invariant enforced at construction and `validate()` post-deserialization. `set_field_value` captures history for password/concealed/totp kinds with kind-change rejection. `prune_history` honors LastN/Days/Forever. Mid-file `use` block (P3). Inline `base32_encode` (P2 above). Otherwise solid; the test at `set_field_value_captures_history_for_password` is exactly the right shape.
|
||||
|
||||
**`manifest.rs` (159 lines).** Browse-without-decrypt index v2. `upsert`/`remove`/`get`/`search`. `derive_icon_hint` only handles Login (P3). `r#type` field (P3). Stale header (P2).
|
||||
|
||||
**`attachment.rs` (166 lines).** `AttachmentRef` (carried on Item) and `AttachmentSummary` (carried in Manifest) plus `encrypt_attachment`/`decrypt_attachment`. The cap check fires before any crypto work — good order. Stale header + WHAT-comments (P2 + P3).
|
||||
|
||||
**`settings.rs` (184 lines).** `VaultSettings` with `TrashRetention`, `HistoryRetention`, `GeneratorRequest`, `AttachmentCaps`, plus the autofill TOFU ack map. Defaults match the design spec. `should_purge` is tested at the day-boundary. Clear.
|
||||
|
||||
**`generators.rs` (269 lines).** CSPRNG passwords (rejection-sampled via `Uniform::from`) and BIP39 passphrases (with capitalization variants) plus a zxcvbn-backed strength gate. Solid except the BIP39 lower-bound and `guesses_log10` ergonomics (both P3).
|
||||
|
||||
**`imgsecret.rs` (1138 lines).** The novel component. Documentation is excellent — DCT, QIM, EMBED_POSITIONS, MAX_DIMENSION rejection, JPEG header peek (audit M3), even an inline ITU-R BT.601 derivation. Tests cover round-trip, recompression to Q85, 10% crop, oversized-header rejection, and synthetic JPEG generation. Three real concerns: dead `region_width`/`region_height` (P2), narrower-than-spec crop recovery (P2), unannotated `unwrap()` in `read_block` (P3). The 1100-line size is fine — the algorithm warrants it.
|
||||
|
||||
**`backup.rs` (348 lines).** `.relbak` container: magic + version + salt + nonce + zstd(JSON envelope). Pinned Argon2id params. Schema/format versioning is paranoid in the right places. Reference-JPEG embedding is base64-in-JSON (P2). Otherwise solid.
|
||||
|
||||
**`device.rs` (168 lines).** ed25519 keypair generation in OpenSSH format, sign/verify, and SHA-256 fingerprint. The ssh-key + ed25519-dalek choreography is awkward but unavoidable. Sign/verify share an extraction pattern (P3). Tests cover sign, verify, wrong-data, wrong-key, and fingerprint format/determinism — comprehensive.
|
||||
|
||||
**`recovery_qr.rs` (129 lines).** The doc-gap finding (P1). Mechanically correct: domain-separated KDF input, AEAD wrap of the 32-byte image_secret, 109-byte payload that fits a QR v40 at EcLevel::M, SVG render via `qrcode`. But the documentation density doesn't match the rest of the crate.
|
||||
|
||||
**`import_lastpass.rs` (220 lines).** Header validation is strict (column count + order). Per-row failures degrade gracefully into `ImportWarning` rather than aborting. SecureNote vs Login dispatch via the `http://sn` sentinel matches the spec (D10). Custom base32 decoder (P2). Otherwise clean.
|
||||
|
||||
**`tar_safe.rs` (138 lines).** Replaces `tar::Archive::unpack` with a validated extractor. Rejects `..`, absolute paths, Windows prefixes, symlinks, hardlinks, oversized claimed sizes, and cumulative-size bombs. Returns `(PathBuf, Vec<u8>)` to the caller. Surgical and well-scoped.
|
||||
|
||||
**`item_types/mod.rs` (127 lines).** `ItemType` and `ItemCore` enums plus a `pub use` of every per-type core. The `// INVARIANT: no *Core struct may have a field serialized as "type"` comment at line 38 is exactly the kind of cross-cutting note that earns its keep — preserving that convention is what `ItemCore`'s tag-based serde works against. Comprehensive round-trip test at `item_core_round_trips_for_all_seven_types`.
|
||||
|
||||
**`item_types/login.rs` (63 lines).** Username/password/url/totp, all Optional, password Zeroizing. `omitted_fields_dont_appear_in_json` is the right shape for a serde test.
|
||||
|
||||
**`item_types/secure_note.rs` (30 lines).** Just a Zeroizing body. Right-sized.
|
||||
|
||||
**`item_types/identity.rs` (45 lines).** Five Optional fields. `empty_identity_omits_all_fields` round-trips to `{}` — clean.
|
||||
|
||||
**`item_types/card.rs` (68 lines).** Number/holder/expiry/cvv/pin/kind. `CardKind` defaults to `Credit`. `MonthYear` reused from `time.rs`.
|
||||
|
||||
**`item_types/key.rs` (42 lines).** Key material as Zeroizing string + label/public_key/algorithm. Loose schema (algorithm is a free string), which is appropriate for "any kind of key material."
|
||||
|
||||
**`item_types/document.rs` (40 lines).** Filename + mime + AttachmentId pointer to the primary blob. The actual bytes live in the attachment store, not the item.
|
||||
|
||||
**`item_types/totp.rs` (293 lines).** TotpCore + the shared TotpConfig (also reused as a field on Login). RFC6238 SHA1 vector check, an independent reference impl for Steam, an alphabet exhaustiveness sweep. HOTP is rejected with a typed error rather than silently mis-counted — the right choice for a stateless library. DT extraction duplicated four times (P3). Source vs test comment disagreement on the '5' character (P3).
|
||||
|
||||
**Tests folder (9 files, ~1.1 kLOC).** `integration.rs` covers the full encrypt/decrypt pipeline plus two-factor independence. `format_v2.rs` pins the version byte, the v1-rejection error type, and the length-prefix domain separation. `field_history.rs` covers capture, prune, and survival across encrypt/decrypt. `attachments.rs` covers round-trip + AID determinism + cap. `backup.rs` is thorough — round-trip with and without reference image / git archive, bad magic, unsupported version, wrong passphrase, truncation, tag tamper, NFC/NFD passphrase round-trip. `generators.rs` does class-balance statistics across 10k chars (well-documented why aggregating, since per-call cap is 128). `import_lastpass.rs` is the single largest suite (~30 cases) and exercises every column-mapping edge. `recovery_qr.rs` is minimal but covers the essentials. `safe_unpack.rs` builds raw-byte tars by hand to bypass `tar::Builder`'s sanitizer — exactly the right way to test a security boundary. The `fast_params()` helper is repeated across most files; a `tests/common/mod.rs` could DRY it but it's not a real cost.
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
|
||||
For a competent dev who has never written Rust, this crate is unusually approachable. The boundary discipline is consistent (no I/O anywhere), the public surface is enumerated in one place (`lib.rs`), the module names map directly to vault concepts a reader already understands (item, manifest, attachment, settings, generators, vault, backup, device, recovery_qr), and the most algorithmically dense file (`imgsecret.rs`) is the most heavily commented. A reader can land in `crypto.rs`, follow `derive_master_key` → `encrypt` → `vault::encrypt_item`, and reach `tests/integration.rs::full_workflow_login_and_note` to see the whole pipeline run, all in one sitting. The Rust idioms that would trip up a newcomer (deref-coercion, `r#type` raw identifiers, `Zeroizing` wrappers, `&**master_key`) are all present, but they cluster in patterns a reader will see often enough to absorb.
|
||||
|
||||
The single change that would help most: write `recovery_qr.rs` to the same documentation standard as `crypto.rs` and `backup.rs`. It's the only file where a learning reader will hit a wall. Closing that gap brings the floor up to the ceiling and makes the "read it like a security proof" pitch true everywhere, not just in 16 of 17 files.
|
||||
240
docs/superpowers/reviews/2026-05-04-dev-b-notes.md
Normal file
240
docs/superpowers/reviews/2026-05-04-dev-b-notes.md
Normal file
@@ -0,0 +1,240 @@
|
||||
# DEV-B Architecture Review Notes — Rust Consumers (CLI, Server, WASM)
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Scope:** `crates/relicario-cli/`, `crates/relicario-server/`, `crates/relicario-wasm/`
|
||||
**Out of scope:** `relicario-core` internals (DEV-A), `extension/` and `tools/relay/` (DEV-C)
|
||||
**Method:** read-only walk of every src + test file; `cargo check` and `cargo clippy` per crate; `cargo build --target wasm32-unknown-unknown` for the WASM crate.
|
||||
|
||||
## Summary
|
||||
|
||||
The consumer layer is in good shape conceptually but uneven in execution. **`relicario-server` is the highlight**: 189 lines, one obvious responsibility, every dependency on `relicario-core` is plaintext device metadata only — the "server only ever sees ciphertext" invariant is structurally enforced by the import surface, not just by convention. **`relicario-wasm` is small and clean but has one real Rust-side defect**: `SessionHandle` lacks an `impl Drop`, so when wasm-bindgen's auto-generated `.free()` runs, the master key stays in WASM linear memory until `lock()` is also called explicitly — defense-in-depth that is currently missing. **`relicario-cli` does its job correctly but is hard to read**: `src/main.rs` is a 2641-line file with no submodule boundaries between the clap surface, item builders, edit handlers, prompt helpers, and parsers — the single biggest readability blocker in the consumer layer. Across all three crates, naming and module structure are good; what hurts is duplicated boilerplate and the absence of a few obvious helpers.
|
||||
|
||||
---
|
||||
|
||||
## Findings
|
||||
|
||||
### relicario-cli
|
||||
|
||||
#### P1 — `main.rs` is a 2641-line monolith with no submodule boundaries
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:1-2641`
|
||||
**Observation:** every subcommand handler, every per-type item builder, every per-type edit handler, prompt helpers, parsing helpers, the `ParamsFile` shape, the clap surface, and 24+ git shell-outs all live in one file. The clap surface (lines 1-455) reads as a tour of the product and is excellent; lines 456-2641 are a flat sequence of `cmd_*`, `build_*_item`, `edit_*`, prompt helpers, and parse helpers, all peers. A newcomer searching "where does add work?" finds `cmd_add` calling 7 different `build_*_item` functions (each ~50-60 lines) with no module boundaries.
|
||||
**Why it matters:** this is the first file a newcomer opens. Today they have to scroll, not navigate.
|
||||
**Suggested direction:** keep `main.rs` as clap definitions + `match` dispatcher only (~470 lines). Split into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs`, plus `prompt.rs` (the six `prompt_*` helpers + `prompt_secret`) and `parse.rs` (`parse_month_year`, `base32_decode_lenient`, `guess_mime`). Same LOC, completely different reading experience.
|
||||
|
||||
#### P1 — Git invocation boilerplate duplicated ~16× with one-line errors
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` (and others)
|
||||
**Observation:** every `git_command` invocation that bails uses the same shape: `git_command(repo).args([...]).status()? + if !status.success() { bail!("git foo failed") }`. Child stderr is inherited to the parent tty (which helps interactively) but in test runs and noninteractive tooling it is lost, and the bail message is just the verb (`"git commit failed"`). When this fires in the wild — pre-receive reject, missing remote, dirty tree, signing-key prompt — the user sees one line of "$verb failed" and nothing else.
|
||||
**Why it matters:** this is the entire error UX for the git side of the CLI. Failure modes are common; the diagnostic is actively unhelpful.
|
||||
**Suggested direction:** add `helpers::git_run(repo, args, context)` that uses `.output()` (capturing stderr), prints captured stderr unmodified on failure, and includes the human-readable `context` ("commit add: GitHub", "register device", "purge trashed item"). Replaces 16 copies with one-liners.
|
||||
|
||||
#### P2 — `build_*_item` functions mix prompting, parsing, and core construction
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:664-921`
|
||||
Each `build_*` does its own prompt-or-flag fallback (`title.map(Ok).unwrap_or_else(|| prompt("Title"))?`), parses domain values (URL, MonthYear, base32 TOTP), then constructs an `ItemCore`. Adding a new item type is currently 50-80 lines of mechanical code. A `prompt_or_flag<T>` helper plus per-type builders that take already-validated values would compress this materially.
|
||||
|
||||
#### P2 — Pure parsers belong in core, not the CLI
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:942-980`
|
||||
`base32_decode_lenient` and `parse_month_year` are pure parsing producing typed core values. Per the user's CLI/extension parity philosophy, these need to be reachable from WASM too — the extension will want them when it gets QR-import / month-year smart input. `MonthYear::parse` and an `ItemCore::parse_totp_seed` (or `Totp::parse_secret`) on the core side would avoid future duplication.
|
||||
|
||||
#### P2 — `refresh_groups_cache` invocation discipline is manual at 7 sites
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:641, 998, 1123, 1197, 1414, 1432, 1474` (and `helpers.rs:90-93` for the doc comment)
|
||||
The plaintext `groups.cache` is updated by-hand after every manifest mutation. The "failures are silently swallowed" rationale is documented at `main.rs:462`, but the rule "every mutating handler must call this" is not enforced — easy to forget on a new command. Either invoke from `Vault::save_manifest` (couples session to cache layout — maybe wrong) or wrap in `Vault::after_manifest_change(&self, manifest: &Manifest)`.
|
||||
|
||||
#### P2 — `ParamsFile` is defined twice with mismatching shapes
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:2287` (write) vs `crates/relicario-cli/src/session.rs:114` (read)
|
||||
The write side has `aead`, `salt_path`, `format_version`; the read side takes only `kdf`. Two definitions of the on-disk `params.json` shape, in different files, with overlapping but non-equal fields. A single `Params` struct in `relicario-core` (or in `session.rs`) used by both readers and writers would eliminate the drift risk.
|
||||
|
||||
#### P2 — `cmd_purge` and `cmd_trash_empty` duplicate the manifest-add-and-commit dance
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:1476-1480, 1896-1900`
|
||||
Same three lines, same error strings, same git rm + git add + git commit per item. `cmd_trash_empty` invokes `purge_item` per item, each of which is its own three-git-invocation loop. Batching the staging would reduce a 50-item purge from 150 git invocations to 3.
|
||||
|
||||
#### P3 — Selection of the `let _ = entry;` pattern, repeated 6×
|
||||
**File(s):** `crates/relicario-cli/src/main.rs:1170, 1407, 1426, 1469, 1913, 2030`
|
||||
Drop-the-borrow-before-reborrow-mutably is a Rust newcomer's worst surprise. A NLL-friendly refactor (clone `id` and `title` eagerly, let the borrow end naturally) would make these lines disappear.
|
||||
|
||||
#### P3 — Other nits
|
||||
- `cmd_recovery_qr_unwrap` does not check for empty input before base64 decode (`main.rs:2625-2630`)
|
||||
- `cmd_recovery_qr_generate` mixes the QR ASCII and a "NOT been saved to disk" message both on stdout — pipe-unfriendly (`main.rs:2612-2614`)
|
||||
- `Lock` subcommand is a no-op but visible in `--help`; either `#[command(hide = true)]` or accept the parity-with-extension argument and document why (`main.rs:445`, doc-comment at `:166`)
|
||||
- `tests/attachments.rs:69-76` has a dead variable (`blob_path`) kept "to avoid an unused warning" — delete
|
||||
- Three test-only env vars (`RELICARIO_TEST_PASSPHRASE`, `RELICARIO_TEST_ITEM_SECRET`, `RELICARIO_TEST_BACKUP_PASSPHRASE`) each duplicated under `#[cfg(debug_assertions)]/#[cfg(not(debug_assertions))]` — one macro would flatten ~30 lines
|
||||
- `cmd_backup_export` still reads `devices.json` (with `[]` fallback) per a "Task 12 will remove" TODO at `:1535-1537`. If Task 12 has shipped, this code can simplify
|
||||
- `format!("{:?}", e.r#type)` for the TYPE column at `main.rs:1158` — Debug-format for user-facing output. Add `Display` to `ItemType` in core
|
||||
- `helpers.rs:37 #[allow(dead_code)] pub fn relicario_dir()` — helper has no callers but several `vault_dir.join(".relicario")` sites in main.rs should be using it
|
||||
- `device.rs:94, 103, 120` and `gitea.rs:24, 26, 47, 77, 94, 101` have `#[allow(dead_code)]` markers without explanation. Either wire up or add `// TODO(<plan>):` so a newcomer knows whether they're scaffolding or scar tissue
|
||||
- `gitea.rs` constructs a fresh `reqwest::blocking::Client::new()` per method call (3 sites) — make it a struct field
|
||||
- `tests/edit_and_history.rs` writes hardcoded prompt sequences (`["", "", "", "", "", "y"]`) blindly; if main.rs reorders prompts, tests hang silently. A scripted-test layer (`expect_prompt("Title"); respond("");`) would survive refactors
|
||||
|
||||
---
|
||||
|
||||
### relicario-server
|
||||
|
||||
#### Trust-model assessment (the headline question)
|
||||
**The server respects the "ciphertext only" invariant. Confirmed.** The crate's entire `relicario-core` import surface is `DeviceEntry`, `RevokedEntry`, `fingerprint` (and `generate_keypair` in tests) — every one of those is plaintext-only device metadata. There is no import of `vault`, `crypto`, `imgsecret`, `item`, `manifest`, or `settings`. A grep over `crates/relicario-server/` for `decrypt|wrapped|encrypted|vault::` returns nothing. The Cargo.toml dep surface (`anyhow`, `clap`, `serde_json`, `tempfile`, `regex`) confirms it: there is no AEAD or KDF crate present. The server cannot decrypt the vault even in principle — it never reads the passphrase, the reference image, the salt, or the params.
|
||||
|
||||
The two on-disk files the server reads from the commit tree are `.relicario/devices.json` and `.relicario/revoked.json` (`main.rs:38, 48`), both plaintext metadata. All other operations are `git` subprocesses (`git show`, `git verify-commit --raw`, `git show -s --format=%ct`) plus local fingerprint computation. `generate-hook` emits a pure shell script that re-invokes `relicario-server verify-commit` per commit; it embeds no secret material. **No P1 findings.**
|
||||
|
||||
#### P2 — `generate-hook` assumes `$PATH`
|
||||
**File(s):** `crates/relicario-server/src/main.rs:170`
|
||||
The emitted script calls `relicario-server verify-commit "$commit"` with no path. Most Gitea deployments do not put `/usr/local/bin` on the hook process's `$PATH`, so this will fail with "command not found" or silently no-op. Either embed `std::env::current_exe()` at hook-generation time, or document an explicit `PATH=` line in the emitted script. There is no test that the generated hook actually executes.
|
||||
|
||||
#### P2 — Bootstrap branch is permissive
|
||||
**File(s):** `crates/relicario-server/src/main.rs:38-44, 54-57`
|
||||
A missing `.relicario/devices.json` at `newrev` is treated as bootstrap and accepted. Combined with "devices empty AND revoked empty → OK", an attacker who pushes a brand-new branch with no `.relicario/` directory could push arbitrary unsigned commits. There's no test for "second push to an established repo where devices.json was stripped." Worth either documenting the rule (first push wins; once devices.json exists in history, it can never be removed) or enforcing it: `oldrev != 0` should imply `devices.json` exists in `newrev`.
|
||||
|
||||
#### P2 — stdin-parsing lives in the shell hook only; binary alone is not hook-shaped
|
||||
**File(s):** `crates/relicario-server/src/main.rs:130-189` (`generate_hook`)
|
||||
The Rust binary's `verify-commit` takes a single SHA argument; the per-line `<old> <new> <ref>` parsing is delegated to bash in `generate_hook`. Defensible split, but means anyone wiring up a hook by hand cannot use the binary alone. A `verify-commit --from-stdin` mode (or at least a doc comment on `VerifyCommit` calling this out) would help.
|
||||
|
||||
#### P2 — Test coverage gaps vs. trust-model
|
||||
**File(s):** `crates/relicario-server/tests/verify_commit.rs`
|
||||
Tests cover: accepted, unregistered → reject, revoked-after → reject, revoked-before → accept. Missing: unsigned commit (no signature at all), malformed `devices.json` (parse error path on `:46`), bootstrap-empty-devices acceptance (`:54`), and one of the two stripped-`.relicario/` cases. Each is one extra `#[test]`.
|
||||
|
||||
#### P3 — Server nits
|
||||
- Regex compiled per call at `main.rs:85` — use `LazyLock` or `once_cell::sync::Lazy`; the `expect("static regex")` comment hints the author knew
|
||||
- The malformed-devices.json path at `:46` returns an `anyhow` chain on stderr without the consistent `REJECT: ...` prefix the rest of the file uses — ops parsing logs for `REJECT:` will miss it
|
||||
- No `--version` flag exposed in clap (small ops courtesy)
|
||||
- `generate-hook` doesn't tell users to `chmod +x` the result (one-line comment header in the emitted script would help)
|
||||
|
||||
---
|
||||
|
||||
### relicario-wasm
|
||||
|
||||
#### P1 — `SessionHandle` has no `impl Drop`; master key leaks on JS GC / `.free()`
|
||||
**File(s):** `crates/relicario-wasm/src/lib.rs:15-23` and `crates/relicario-wasm/src/session.rs:1-58`
|
||||
**Observation:** `SessionHandle` is `pub struct SessionHandle(u32)` with no `Drop` impl. wasm-bindgen auto-generates a JS-side `.free()` that, on the Rust side, drops the `SessionHandle` wrapper — i.e. drops a `u32`, a no-op. The `SESSIONS` HashMap entry stays alive **with the master key + image_secret still in WASM linear memory** until JS calls the explicit `lock(handle)` function (which calls `session::remove`). I confirmed via `grep -n "impl Drop" crates/relicario-wasm/src/*.rs` — empty.
|
||||
**Why it matters:** every `.free()` callsite that does not also call `lock()` first is a key-residency window of unbounded duration. wasm-bindgen does **not** auto-call `free()` on JS GC, but JS code that does call `.free()` reasonably expects the Rust side to clean up. The current contract requires JS to call `lock()` *and then* `free()`, which is asymmetric and easy to get wrong on the JS side (see boundary notes for DEV-C).
|
||||
**Suggested direction:** add
|
||||
```rust
|
||||
impl Drop for SessionHandle {
|
||||
fn drop(&mut self) { session::remove(self.0); }
|
||||
}
|
||||
```
|
||||
to `lib.rs`. `lock()` becomes the explicit "I am done now" call; `.free()` (auto or manual on the JS side) is the safety net. Defense in depth — the cost is one impl block. Worth a `wasm-bindgen-test` covering construct → drop → confirm registry empty.
|
||||
|
||||
#### P2 — Redundant `need_key` + `with(...).unwrap()` double-lookup
|
||||
**File(s):** `crates/relicario-wasm/src/lib.rs:73, 84, 92, 103, 111, 122, 160, 172`
|
||||
Every per-call op does `need_key(handle)?` and then `session::with(handle.0, |k| ...).unwrap()`. Two HashMap lookups per call, with the second `.unwrap()` justified only because the first proved the key existed. Single-threaded WASM makes this safe today, but if anyone ever introduces a reentrant path (`Serializer` callback that calls back into WASM), the assumption breaks. Refactor to a single `session::with(...).ok_or_else(|| JsError::new("invalid or locked session handle"))?` helper.
|
||||
|
||||
#### P2 — `Vec<u8>` getters clone on every read
|
||||
**File(s):** `crates/relicario-wasm/src/lib.rs:141-150` (`EncryptedAttachment::aid` and `bytes`)
|
||||
Each call clones the whole field. JS can call `enc.bytes` repeatedly without realising. For attachment payloads (potentially MB-sized), that's a real cost. Either consume by value or document "call once, cache locally."
|
||||
|
||||
#### P2 — Naming: `wasm_*_recovery_qr` prefix is inconsistent with everything else
|
||||
**File(s):** `crates/relicario-wasm/src/lib.rs:497, 510`
|
||||
`wasm_generate_recovery_qr` and `wasm_unwrap_recovery_qr` are the only exports with the `wasm_` prefix. Rename to `generate_recovery_qr_svg` and `unwrap_recovery_qr` (and update `extension/src/wasm.d.ts` accordingly). Trivial breaking rename, do it before any new caller appears.
|
||||
|
||||
#### P2 — `device.rs` and `session.rs` use different concurrency primitives
|
||||
**File(s):** `crates/relicario-wasm/src/device.rs` (`Lazy<Mutex<...>>`) vs `crates/relicario-wasm/src/session.rs:14-17` (`thread_local! { RefCell<HashMap<...>> }`)
|
||||
Both work in single-threaded WASM. The inconsistency hurts readability — pick one pattern. `thread_local! + RefCell` is fine and avoids `Mutex` overhead; `Mutex` over `Lazy` is closer to typical Rust idioms. Either is defensible; consistency is the win.
|
||||
|
||||
#### P3 — WASM nits
|
||||
- All `#[wasm_bindgen]` exports use snake_case (`manifest_encrypt`, `parse_lastpass_csv_json`); JS idiom is camelCase. The `wasm.d.ts` mirrors snake_case verbatim, so it's consistent — but if DEV-C ever wants idiomatic JS naming, `#[wasm_bindgen(js_name = "manifestEncrypt")]` is the path. Decide once, cite the decision in the module doc
|
||||
- `lib.rs:50` comment "Subsequent wasm_bindgen fns added in Tasks 19-21" is stale historical scaffolding; remove
|
||||
- `device.rs:18 #[allow(dead_code)] deploy_private` — wire it or remove it
|
||||
- `session.rs:24 if *n == 0 { *n = 1; }` runs on every insert; logically only matters after wraparound — move into the `wrapping_add` returned-zero branch
|
||||
- `session_tests` mod inside `lib.rs:522-591` covers session + lastpass; rename or split
|
||||
- `SessionHandle` doc-comment says "opaque to JS" but `value()` getter (`:21-22`) makes the u32 visible — align the comment with the API
|
||||
- `pack_backup_json` does six `b64.decode().map_err(...)` blocks (`lib.rs:387-410`) — a small `b64_decode(s) -> Result<Vec<u8>, JsError>` helper would compress ~20 lines
|
||||
- `get_field_history` walks sections and constructs `serde_json::json!` manually rather than serializing a typed struct (`lib.rs:262-295`); the `_ => String::new()` fallback at `:277` silently swallows future `FieldValue` variants. Use exhaustive match
|
||||
|
||||
---
|
||||
|
||||
### Cross-cutting (all three crates)
|
||||
|
||||
1. **Pure parsers / formatters belong in core.** `parse_month_year`, `base32_decode_lenient`, `guess_mime` (CLI), and `get_field_history`'s walk (WASM) are all examples of logic that today lives in a consumer crate but logically belongs in `relicario-core` so all consumers share it. The CLI/extension parity philosophy makes this concrete: anything the CLI does in pure logic, the extension will eventually need too.
|
||||
|
||||
2. **Error formatting is inconsistent.** CLI uses `anyhow::bail!` with a mix of sentence-case ("Settings updated.") and lowercase fragments ("git commit failed"). Server is uniformly `eprintln!("REJECT: ...")` *except* for the malformed-devices.json path that surfaces an anyhow chain. WASM uses `JsError::new(&e.to_string())` mostly, but the messages range from "salt must be exactly 32 bytes" to whatever `RelicarioError::Display` produces. A short style note ("user-facing errors lead with sentence-case context, internal errors use lowercase") plus an audit pass would unify these.
|
||||
|
||||
3. **`#[allow(dead_code)]` without explanation appears in cli/device.rs, cli/gitea.rs, and wasm/device.rs.** Each one is either "API completeness for a feature that hasn't shipped" or "scar tissue from a refactor." A newcomer cannot tell which. Either delete or annotate with `// TODO(<plan>):`.
|
||||
|
||||
4. **Layering is correct.** None of the three consumer crates reaches past `relicario-core`'s public API. The CLI doesn't import from server or wasm; server doesn't import from CLI or wasm; wasm doesn't import from CLI or server. The only shared concept (device entries, fingerprints) is correctly a core export. ¡Chido! [cool!]
|
||||
|
||||
5. **Workspace `Cargo.toml` working-tree changes are cosmetic** (version bumps `0.2.0 → 0.5.0` on cli/core/wasm). No structural concern. Worth committing or reverting before the next merge to keep `git status` quiet.
|
||||
|
||||
---
|
||||
|
||||
## File-by-file walk
|
||||
|
||||
### relicario-cli
|
||||
|
||||
- **`Cargo.toml`** — 18 runtime + 4 dev deps, all reasonable. `arboard` (clipboard), `rqrr` (QR decode), `qrcode` (QR encode), `image`, `rpassword`, `dirs`, `reqwest` blocking + JSON for Gitea, `data-encoding`, `tar`. Platform concerns ferried correctly away from core.
|
||||
- **`src/main.rs`** — entrypoint, dispatcher, **and** every command handler, item builder, edit handler, prompt helper, parse helper. 2641 lines, 71 functions. Clap surface (lines 1-455) is itself a tour of the product and is excellent. Past line 456 the file becomes flat; see P1 #1.
|
||||
- **`src/helpers.rs`** — the cleanest file. ~239 lines: `vault_dir`, `git_command` (with `core.hooksPath=/dev/null`, `commit.gpgsign=false`, `core.editor=true` hardening — newcomers should read the comment at `:42-45`), `iso8601`, `humanize_age`, `groups_cache_path`, `sanitize_for_commit`, `decode_totp_qr`. Has its own `#[cfg(test)] mod tests` covering `humanize_age`, `sanitize_for_commit`, `iso8601`. `find_vault_dir_from` walks parents. Plaintext `groups.cache` is a deliberate trade-off and the doc-comment at `:90-93` is admirably explicit.
|
||||
- **`src/session.rs`** — short and clear (~151 lines). `UnlockedVault { root, master_key: Zeroizing<[u8; 32]> }` plus `load_*`/`save_*` for Item, Manifest, VaultSettings. `unlock_interactive()` does passphrase prompt → image extract → KDF. `key()` accessor returns `&Zeroizing<...>` used at 4 call sites; consider passing through `encrypt_attachment`/`decrypt_attachment` methods so the key never leaves this module. `read_params` defines an inner `ParamsFile` struct that mismatches the writer in `main.rs:2287` — see P2.
|
||||
- **`src/device.rs`** — ~169 lines. ed25519 keypair storage under `~/.config/relicario/devices/<name>/`. `configure_git_signing` runs four `git config` calls. Three `#[allow(dead_code)]` items (`load_signing_key`, `load_deploy_key`, `delete_device_keys`) — API completeness without callers.
|
||||
- **`src/gitea.rs`** — ~117 lines. Plain blocking reqwest client. `create_deploy_key` parses the JSON response into `DeployKey { id, title, key }` (latter two `#[allow(dead_code)]`). `delete_deploy_key` treats 404 as success — sensible. Each method allocates a fresh `reqwest::blocking::Client::new()`.
|
||||
- **`tests/basic_flows.rs`** — 137 lines. Tests at the right level: spawn binary via `assert_cmd`, assert on stdout/stderr/exit. `init_creates_expected_layout`, `add_login_then_list_shows_it`, `get_masks_by_default_shows_with_flag`, `rm_restore_purge_cycle`, `generate_random_and_bip39`. Solid CLI-surface coverage.
|
||||
- **`tests/edit_and_history.rs`** — 191 lines. Most subtle test, interactive `edit` flow. `run_edit_with_pw_change` and `run_edit_totp` write hardcoded prompt sequences (`["", "", "", "", "", "y"]`) to stdin — fragile to prompt reordering. See P3.
|
||||
- **`tests/attachments.rs`** — 106 lines. Round-trip attach → extract → detach. Has a dead variable kept "to avoid an unused warning" (P3). `attach_rejects_over_cap` exercises only the per-attachment cap, not per-item or per-vault — coverage gap.
|
||||
- **`tests/settings.rs`** — 158 lines. `settings_roundtrip_trash_retention`, conflicting-flags rejection, generator-defaults end-to-end, `status` command coverage including `last_backup` round-trip. Solid.
|
||||
- **`tests/backup.rs`** — 142 lines. Export/restore round-trip, `--include-image`, `--no-history`, refusal of non-empty target, wrong-passphrase failure. Excellent coverage.
|
||||
- **`tests/import_lastpass.rs`** — 127 lines. Importer integration: success, single-commit guarantee, zero-items rejection, header validation, duplicate-import-IDs-are-unique invariant.
|
||||
- **`tests/smart_inputs.rs`** — 210 lines. Completion-script smoke tests, groups-cache write/suppress, `rate` command (strong/weak/`-` stdin), `--totp-qr` via in-process synthesized QR PNG (`make_test_qr`) — adheres to "synthetic fixtures, no binary blobs."
|
||||
- **`tests/vault_detection.rs`** — 59 lines. `list_refuses_without_vault_marker`, `get_finds_vault_in_parent_dir`, `v1_vault_is_rejected_with_clear_error` (`.idfoto/` ignored because lookup is for `.relicario/`).
|
||||
- **`tests/common/mod.rs`** — 132 lines. `TestVault` harness; `init()` creates a `TempDir`, generates synthetic JPEG via `make_test_jpeg`, runs binary with `RELICARIO_TEST_PASSPHRASE` set. `run`, `run_with_input`, `run_with_backup_pass` variants. No shared global state — parallel-test safe.
|
||||
|
||||
### relicario-server
|
||||
|
||||
- **`src/main.rs`** — 189 lines, very legible. Two clap subcommands cleanly mapped. `verify_commit` reads devices.json + revoked.json from the commit's tree (`git show`), spawns `git verify-commit --raw` with a dynamically-built allowed-signers file injected via `GIT_CONFIG_*` env vars (a clever touch — chido [cool] — avoids touching user gitconfig), parses the SHA-256 fingerprint from stderr, then enforces revocation-first then registration logic. Uses committer timestamp (not author) for revocation cutoff (`:115-123`) — correct for non-rebased histories. All rejection paths use `eprintln!("REJECT: ...")` with actionable context (commit SHA, fingerprint, reason) and exit 1 — visible to the pushing client via `git push` stderr. `generate_hook` emits a clean bash script handling branch creation (`oldrev = 000...`) and branch deletion (`newrev = 000...`).
|
||||
- **`tests/verify_commit.rs`** — 230 lines, four named scenarios mapping to audit S1. Each test stands up a tempdir git repo, generates real ed25519 keypairs via `relicario_core::device::generate_keypair`, signs a commit with explicit committer date, and shells out to the cargo-built binary via `assert_cmd`. Coverage gaps noted in P2.
|
||||
- **`Cargo.toml`** — minimal, no surprises. Importantly: no AEAD or KDF crate, which structurally guarantees the server cannot decrypt.
|
||||
|
||||
### relicario-wasm
|
||||
|
||||
- **`Cargo.toml`** — 27 lines. Right deps. `getrandom = { features = ["js"] }` correctly enabled for browser entropy routing. `image` is dev-only — good. `relicario-core/Cargo.toml` does NOT enable the `js` getrandom feature (correct: core stays platform-agnostic), and the wasm crate "lifts" the feature flag for the dep graph.
|
||||
- **`src/lib.rs`** — 591 lines, the bulk of the surface. Module doc-comment is concise. Imports are sprinkled mid-file (`:52, :138, :180, :310, :340, :469, :491`) instead of clustered at the top — historical from incremental authoring per Task 19/20/21 markers. Consolidating saves scroll. Sections are demarcated by `// ── ... ──` dividers which help.
|
||||
- **`src/session.rs`** — 57 lines. `SessionData { master_key, image_secret }` stored in `thread_local! { RefCell<HashMap<u32, _>> }`, monotonic `NEXT_HANDLE` u32 (skips 0 on wraparound). `insert`, `with`, `with_image_secret`, `remove`, `clear` (test-only). Missing `impl Drop for SessionHandle` — see P1.
|
||||
- **`src/device.rs`** — 71 lines. Clean. `Zeroizing<String>` for private keys (correct — `String::zeroize` wipes the heap allocation). Uses `Lazy<Mutex<DeviceState>>` (different pattern from `session.rs` — see P2).
|
||||
|
||||
### Build / clippy
|
||||
|
||||
- `cargo check -p relicario-cli` — clean
|
||||
- `cargo check -p relicario-server` — clean
|
||||
- `cargo check -p relicario-wasm` — clean
|
||||
- `cargo build -p relicario-wasm --target wasm32-unknown-unknown` — clean, finishes in ~6s, zero warnings
|
||||
- `cargo clippy --workspace` — silent (per subagent reports)
|
||||
|
||||
---
|
||||
|
||||
## Boundary notes for DEV-C
|
||||
|
||||
These are the items that look fine from the Rust side but DEV-C must verify on the TypeScript side:
|
||||
|
||||
1. **CRITICAL — every `.free()` callsite on a `SessionHandle`.** wasm-bindgen's auto-generated `.free()` does NOT remove the entry from the Rust-side `SESSIONS` registry today, because there is no `impl Drop for SessionHandle` (P1 above). Until that lands, every `.free()` callsite in TypeScript that does not first call `wasm.lock(handle)` is a master-key residency window in WASM linear memory of unbounded duration. Audit `extension/src` for every `.free()` on a `SessionHandle`. The Rust-side fix is preferred (defense in depth); DEV-C should also confirm that every TS-side lock path calls `wasm.lock(handle)` before `.free()` regardless.
|
||||
2. **Verify every `.free()` callsite, full stop.** Same principle applies to `EncryptedAttachment.free()` and `TotpCode.free()`. wasm-bindgen will not call `free` automatically when the JS object is GC'd — JS GC does not trigger Rust drop. Any handle that goes out of scope without explicit `.free()` leaks in WASM linear memory.
|
||||
3. **`unlock()` failure semantics.** When unlock throws (bad passphrase, bad params_json, salt wrong length, image_secret extract failure), no `SessionHandle` is created. TS callers should not wrap in `try { ... } finally { handle.free() }` because the handle var will be undefined.
|
||||
4. **`manifest_decrypt`/`item_decrypt`/`settings_decrypt` return `JsValue` typed as `unknown` in TS.** Rust uses `serde_wasm_bindgen::Serializer::new().serialize_maps_as_objects(true)` (`lib.rs:65`). Verify TS doesn't assume `Map` semantics anywhere — should be plain JS objects. Binary fields decode to `Uint8Array`; confirm TS doesn't try to `JSON.stringify` a decrypted item containing binary.
|
||||
5. **`*_encrypt` functions take `*_json: string`.** TS must `JSON.stringify` before calling. wasm-bindgen TS bindings will catch this at compile time, but verify no `as any` casts bypass.
|
||||
6. **`totp_compute(_, now_unix_seconds: bigint)` and `attachment_encrypt(_, _, max_bytes: bigint)`** — TS must use `BigInt(...)`, not `number`. wasm-bindgen throws at runtime on mismatch.
|
||||
7. **`Uint8Array` arguments are copied into WASM linear memory.** TS doesn't need defensive copies. But a `Uint8Array` view onto a `SharedArrayBuffer` may behave differently — verify TS isn't passing those.
|
||||
8. **`EncryptedAttachment.aid` and `.bytes` clone on every read** (P2). TS code that does `enc.bytes` twice does double work + double copy. Cache locally.
|
||||
9. **`SessionHandle.value` getter is exposed.** It's a u32 monotonic counter. If TS ever logs it (telemetry/debug), it's a session correlation identifier that survives across handles.
|
||||
10. **`get_field_history` returns JS objects with snake_case keys** (`field_id`, `field_name`, `current_value`, `changed_at`). Verify TS components consume these names — easy mismatch with TS-side camelCase conventions.
|
||||
11. **`register_device`/`sign_for_git`/`get_device_info`/`clear_device` are global, not per-session** — backed by `static DEVICE_STATE` (`Lazy<Mutex<>>`). Single SW = single state, fine. If TS ever instantiates multiple WASM modules (e.g. one per offscreen doc), each gets its own state — verify TS uses one shared init path.
|
||||
12. **Naming inconsistency**: only `wasm_generate_recovery_qr` and `wasm_unwrap_recovery_qr` carry the `wasm_` prefix. If DEV-C maintains a name-mapping table or auto-generated wrappers, flag for a rename pass.
|
||||
13. **`parse_lastpass_csv_json` returns `string` (JSON-encoded), not a `JsValue`.** TS must `JSON.parse` the result — different shape from `manifest_decrypt` which returns already-deserialized `unknown`. Verify `import_lastpass.ts` does `JSON.parse(...)` on the result.
|
||||
14. **All exports are snake_case in JS.** If DEV-C ever wants idiomatic camelCase, the mechanism is `#[wasm_bindgen(js_name = "...")]` per export. Decide once, before the surface grows.
|
||||
|
||||
---
|
||||
|
||||
## Beginner-friendliness assessment
|
||||
|
||||
For a competent dev who's never written Rust:
|
||||
|
||||
- **Server is ideal.** 189 lines, one trust-model question, every dependency is plaintext metadata. A newcomer can read it end-to-end in under ten minutes and walk away understanding what the server does and does not do. The single change that would help most is a paragraph-length module-level comment near the top of `main.rs` explaining *why* the server only verifies signatures (because the vault is encrypted client-side, the server has no key, the hook's only job is to gate writes by device authenticity). That paragraph would make the trust story self-evident on first contact.
|
||||
|
||||
- **WASM is approachable but has one cliff.** 720 lines across 3 files; `lib.rs` reads top-to-bottom okay; the doc-comment on `SessionHandle` is clear about the opaque-handle contract; the section dividers help. The cliff is the missing `Drop` impl: a beginner reasonably assumes wasm-bindgen handles registry cleanup automatically (it does not). A short comment in `session.rs` saying "**Drop the SessionHandle ≠ remove from registry; you must call `lock()`**" would prevent that mistake — but better to fix the missing `Drop` so the comment isn't needed.
|
||||
|
||||
- **CLI has one big roadblock and a lot of small ones.** `helpers.rs`, `session.rs`, `device.rs`, `gitea.rs` all read like real code: small modules, focused responsibilities, doc-comment headers, sensible names. `helpers.rs`'s tests double as documentation. The clap surface in `main.rs:1-455` is itself a product tour. Past line 456, `main.rs` becomes a 2200-line flat file with no submodule boundaries. A newcomer searching "where does add work?" finds `cmd_add` calling 7 different `build_*_item` functions (each ~50-60 lines) plus 6 prompt helpers, all peers. Plus the Rust-specific tripwires — the `let _ = entry;` pattern repeated 6×, the `Zeroizing` newtype, the `Option<Foo>::map(Ok).unwrap_or_else(...)?` chain at every builder — compound the unfamiliarity.
|
||||
|
||||
**Single biggest change across the consumer layer:** split `crates/relicario-cli/src/main.rs` into a folder. Keep `main.rs` as clap definitions + dispatcher (~470 lines, very readable). Move every `cmd_*` to `commands/<name>.rs`, prompts to `prompt.rs`, parsers to `parse.rs`. Same LOC, completely different reading experience — and this is the precondition for fixing the duplicated git boilerplate (CLI P1 #2) and centralizing `refresh_groups_cache`.
|
||||
|
||||
---
|
||||
|
||||
## Open questions for DEV-B (escalated to PM separately)
|
||||
|
||||
1. Was `impl Drop for SessionHandle` deliberately omitted (e.g. to avoid double-free if JS holds two refs to the same handle)? If yes, document it; if no, this is the headline fix.
|
||||
2. CLI `parse_month_year`, `base32_decode_lenient`, `guess_mime` — should they migrate to `relicario-core` for CLI/extension parity?
|
||||
3. Is "missing `.relicario/devices.json` = bootstrap = accept" intended in perpetuity, or should it be tightened once a repo has any non-empty devices.json in history?
|
||||
4. Is the `Lock` no-op CLI subcommand worth keeping visible in `--help` for parity with the extension, or hide behind `#[command(hide = true)]`?
|
||||
5. `cmd_backup_export` still reads `devices.json` per a "Task 12 will remove" TODO. Is Task 12 landed, deferred, or abandoned?
|
||||
343
docs/superpowers/reviews/2026-05-04-dev-c-notes.md
Normal file
343
docs/superpowers/reviews/2026-05-04-dev-c-notes.md
Normal file
@@ -0,0 +1,343 @@
|
||||
# DEV-C Architecture Review Notes — TypeScript (Extension + Relay)
|
||||
|
||||
**Reviewer:** dev-c (TypeScript scope) **Date:** 2026-05-04 **Branch:** main (read-only review)
|
||||
|
||||
## Summary
|
||||
|
||||
The TypeScript layer is **soundly organized but unevenly distributed**: a tight discriminated-union message contract (`shared/messages.ts`) and a clean Manifest V3 trust split (popup/setup/content/SW) anchor a codebase that earns its complexity from the two-factor unlock UX. The strongest part is the **service-worker router**: every popup/content message has a typed handler with origin-aware gating, and content scripts never touch WASM. The weakest parts are **two oversized modules that pre-empt the otherwise-clean component model**: `extension/src/setup/setup.ts` (1220 LOC) bypasses the SW and orchestrates WASM directly, and `extension/src/vault/vault.ts` (1027 LOC) inlines shell, sidebar, list, drawer, type-picker, form-wrapper and routing into one file. **CLI/extension parity is excellent overall** — every CLI subcommand has a UI path through the unified left-nav settings (v0.5.1) or vault tab — with two real gaps: explicit per-attachment detach (extension does it via `update_item`) and a vault-status surface equivalent to `relicario status`. One **broken test** in uncommitted relay code (`tools/relay/queue.test.ts:54`) blocks `bun test` from going green.
|
||||
|
||||
## Findings (prioritized: P1 / P2 / P3)
|
||||
|
||||
### Extension — service-worker
|
||||
|
||||
**[P1] router/popup-only.ts:687–703 & router/content-callable.ts:187–205 — duplicated storage helpers (`loadDeviceSettings`, `loadBlacklist`, `saveBlacklist`)**
|
||||
WHY: Three identical chrome.storage.local helpers in both router files; both code paths can mutate blacklist via different definitions, so future drift will silently corrupt one path.
|
||||
DIRECTION: Extract to `service-worker/storage.ts`; import from both routers.
|
||||
|
||||
**[P1] router/popup-only.ts:~169 & router/content-callable.ts:~169 — `itemToManifestEntry()` duplicated**
|
||||
WHY: Identical 17-line manifest projection in both router files; refactors of the manifest schema will need to be made twice.
|
||||
DIRECTION: Move into `service-worker/vault.ts` and import.
|
||||
|
||||
**[P2] service-worker/index.ts:76–78 — inactivity timer reset skips content-callable messages**
|
||||
WHY: Only popup/vault sends reset the timer; a user who is actively autofilling but never opens the popup will eventually be force-locked despite continuous use. Conversely, "every_time" mode is fine.
|
||||
DIRECTION: Reset on all messages except known read-only content calls (`get_autofill_candidates`); document the exclusion in the timer module.
|
||||
|
||||
**[P2] service-worker/index.ts:51–58 — session expiry clears `state.manifest` but leaves `state.gitHost`**
|
||||
WHY: After expiry, the cached git-host client survives; the next unlock could mix with stale connection state if a remote was rotated.
|
||||
DIRECTION: Null `state.gitHost` alongside `state.manifest` in the expiry callback; the initializer rebuilds it on demand.
|
||||
|
||||
**[P2] service-worker/session.ts:26 — `try { current.free() }` swallows free errors**
|
||||
WHY: A double-free or invalid-handle on the WASM session would be silently ignored, masking a lifecycle bug that could leave the master key zeroed but the JS handle dangling.
|
||||
DIRECTION: Let exceptions propagate (or log + counter); silent swallow is the wrong default for crypto state transitions.
|
||||
|
||||
**[P3] service-worker/index.ts:61–65 — chrome.storage.local.get on startup swallows errors**
|
||||
WHY: A typo or storage quota event leaves the timer in default state with no signal in the logs.
|
||||
DIRECTION: Surface failure via console.warn with the key name.
|
||||
|
||||
**[P3] service-worker/git-host.ts vs github.ts/gitea.ts — deploy-key API only on Gitea side**
|
||||
WHY: The interface is asymmetric; either GitHub doesn't need it (document) or it's an unimplemented feature.
|
||||
DIRECTION: Add a doc comment on `GitHost` explaining the asymmetry, or add the GitHub op.
|
||||
|
||||
### Extension — popup + components
|
||||
|
||||
**[P1] settings.ts:56–65 & settings-vault.ts:15–22 — duplicated teardown helpers**
|
||||
WHY: After the stub-restore commits (`8baef5b`, `ddfb95d`), teardown leaks are a known regression class; duplicated cleanup is exactly the shape that re-introduces them.
|
||||
DIRECTION: Extract `teardownSettingsCommon()` into a single helper; have each settings section call it on unmount.
|
||||
|
||||
**[P2] popup.ts:178–181 — teardown calls every type module unconditionally**
|
||||
WHY: Cycling views runs all 7 type teardowns on each transition; harmless today, but makes the lifecycle hard to reason about and hides which module was actually mounted.
|
||||
DIRECTION: Track last-mounted type and tear down only that one (or use a registry of `() => teardown` returned by mount).
|
||||
|
||||
**[P2] settings.ts:33–34 — `pendingVaultSettings` and `sessionHandle` are module-scope singletons**
|
||||
WHY: Section navigation can leave stale `pendingVaultSettings` from a previous section in scope; the current code is safe by accident, not by design.
|
||||
DIRECTION: Reset to `null` on each `renderSection` entry, or scope into a closure per render.
|
||||
|
||||
**[P2] item-list.ts:152–353 — settings-picker popover wires listeners on every render without a reuse path**
|
||||
WHY: Open/close cycles attach + detach listeners cleanly today, but rapid re-opens with throttled `setTimeout` cleanup are exactly the pattern teardown bugs hide in.
|
||||
DIRECTION: Cache the popover DOM and reuse, or use AbortController for the listeners with an explicit `signal` per open.
|
||||
|
||||
**[P2] devices.ts:47–50 & trash.ts:39–46 — `Promise.all` without per-promise error handling**
|
||||
WHY: A single rejected RPC fails the whole render; the second response is discarded even when its data was fetched successfully.
|
||||
DIRECTION: `Promise.allSettled`, then check `.ok` per response.
|
||||
|
||||
**[P2] generator-panel.ts:89–261 — module-scope `activePanel`; `closeGeneratorPanel()` not idempotent-guarded**
|
||||
WHY: The cleanup is currently a no-op when called twice, but the contract is implicit.
|
||||
DIRECTION: Add `if (!activePanel) return` at top.
|
||||
|
||||
**[P3] form-header.ts:20 + types/login.ts — `isInTab()` checked twice (header + caller)**
|
||||
WHY: Redundant coupling; the popout button visibility decision happens in two places.
|
||||
DIRECTION: Pass `showPopout: boolean` into `renderFormHeader` once.
|
||||
|
||||
**[P3] popup.ts:36–38 — `isInTab()` heuristic is `window.location.search.length > 0`**
|
||||
WHY: Any query string on `popup.html` triggers tab mode; brittle if popup is ever opened with diagnostic params.
|
||||
DIRECTION: Parse a specific param (`?view=tab` or check `window.location.pathname.endsWith('vault.html')`).
|
||||
|
||||
**[P3] item-form.ts:95–104 — `renderComingSoon()` defined but unused**
|
||||
WHY: Document type now has a real form (`types/document.ts`); the placeholder is dead code.
|
||||
DIRECTION: Delete or leave a one-line comment explaining future use.
|
||||
|
||||
**[P3] types/login.ts ~700 LOC — `renderForm` mixes HTML, wiring, password-strength, TOTP-ticker, and section editor**
|
||||
WHY: The reference implementation for the other 6 type modules; size makes the per-affordance lifecycle hard to follow for a learner.
|
||||
DIRECTION: Extract `wireUrlField`, `wirePasswordField`, `wireTotpField` from the body of `renderForm`. Other type modules already follow simpler patterns.
|
||||
|
||||
### Extension — vault tab
|
||||
|
||||
**[P1] vault/vault.ts (1027 LOC) — single file owns shell + sidebar + list + drawer + type-picker + form-wrapper + routing + teardown**
|
||||
WHY: A learner opening this file faces all responsibilities at once; teardown coupling (`teardownPaneComponents` lines 813–820) makes adding a new pane view a 5-place edit.
|
||||
DIRECTION: Split into `vault-shell.ts`, `vault-sidebar.ts`, `vault-list.ts`, `vault-drawer.ts`, `vault-form-wrapper.ts`, leaving `vault.ts` to own only routing and state.
|
||||
|
||||
**[P2] vault/vault.ts:47–74 — vault tab intercepts `vault_locked` errors via the RPC layer; popup uses only the `session_expired` event**
|
||||
WHY: Two different mechanisms reach the same outcome; popup-targeted components running in the vault tab don't know which channel will fire first.
|
||||
DIRECTION: Lift the RPC `vault_locked` intercept into `shared/state.ts` (or a wrapper around `sendMessage`) so both surfaces use one path.
|
||||
|
||||
**[P2] vault/vault.ts:495–536 — drawer doesn't auto-close on non-list view changes**
|
||||
WHY: Selecting an item opens the drawer; navigating to Trash via the sidebar leaves `state.drawerOpen = true` even though the drawer is no longer rendered.
|
||||
DIRECTION: `state.drawerOpen = false` at the start of `renderPane`, or when a non-list view becomes active.
|
||||
|
||||
**[P2] vault/vault.ts:648–695 — sidebar categories re-render on every search keystroke without debounce**
|
||||
WHY: Counts and active state must sync, but at hundreds of items the keystroke path stamps the whole sidebar.
|
||||
DIRECTION: 50–100ms debounce on the search input handler before re-rendering.
|
||||
|
||||
**[P3] vault/vault.ts:18–26 — backup-panel and import-panel are `vault/components/`-only by design**
|
||||
WHY: Correct call (popup has no room for these), but worth noting in the file header so a contributor doesn't try to import them into popup.
|
||||
DIRECTION: Add a short comment in `vault/components/index.ts` (or top of each file) explaining the vault-tab-only scope.
|
||||
|
||||
### Extension — content scripts
|
||||
|
||||
**[P2] content/fill.ts:50–64 — `fillFields()` returns silently when no password field is found**
|
||||
WHY: Dynamic forms (React/SPA mounting after `document_idle`) can race the fill listener; user clicks autofill, nothing visible happens, no error reaches the popup.
|
||||
DIRECTION: Send a `{type: 'fill_failed', reason: 'no_password_field'}` ack back to SW so the icon can flash an error glyph.
|
||||
|
||||
**[P2] content/detector.ts:96–103 — MutationObserver `scan()` is not debounced**
|
||||
WHY: SPA churn fires DOM mutations many times per second; the detector re-runs the full scan each time. WeakSet stops icon double-injection, but the scan cost is wasted.
|
||||
DIRECTION: Wrap `scan()` in `requestIdleCallback` or a 200ms timer.
|
||||
|
||||
**[P2] content/icon.ts:169–175 — outside-click listener registered in `setTimeout(0)` not removed on alternate close paths**
|
||||
WHY: Picker can close via Escape or programmatic destroy; the doc-level listener for outside-click leaks unless `closeOverlay()` is the close path.
|
||||
DIRECTION: Store the handler reference and `removeEventListener` in every close path; or `AbortController` scoped to picker open.
|
||||
|
||||
**[P3] capture.ts vs detector.ts vs fill.ts — username-finder logic copy-pasted three ways**
|
||||
WHY: `findUsernameField`, `findUsernameForFill`, `findUsernameValue` are three forks of the same heuristic.
|
||||
DIRECTION: Extract a shared `getUsernameField(pwField, scope, { valueOnly?: boolean })`.
|
||||
|
||||
**[P3] capture.ts:269–299 — submit-button hook scope is `form ?? pwField.parentElement`**
|
||||
WHY: A submit button outside the form (e.g. a custom React `<button onClick={...}>` siblings to the form) won't trigger capture; the user never sees the save prompt.
|
||||
DIRECTION: Walk up to the nearest form ancestor and listen for `keydown.Enter` on the password field as a fallback.
|
||||
|
||||
**[Positive note] content scripts make zero direct WASM calls and re-validate origin in `fill.ts:32–38`** — boundary discipline holds.
|
||||
|
||||
### Extension — setup
|
||||
|
||||
**[P1] setup/setup.ts:28–37, 1118–1120 — WASM is loaded and called directly inside the setup wizard, bypassing the service-worker abstraction the rest of the codebase uses**
|
||||
WHY: Popup, vault tab, and content all funnel WASM through the SW; setup is the only surface that imports `relicario-wasm` and orchestrates `unlock`/`embed_image_secret`/`register_device`/`manifest_encrypt` itself. This duplicates ~400 LOC of crypto orchestration that the SW already knows how to do, and it means the setup tab can't be locked by the same session-timer the rest of the extension uses.
|
||||
DIRECTION: Add `create_vault` and `attach_vault` messages to the SW; turn `setup.ts` into a UI that posts those messages with the gathered config + image bytes. This collapses ~600 LOC into ~200 and unifies the crypto state machine.
|
||||
|
||||
**[P2] setup/setup.ts (1220 LOC) — render/attach pairs per step are inlined**
|
||||
WHY: 6 steps × (renderStepN, attachStepN) = a switch statement that reads procedurally; adding a step means edits to the renderer, the attacher, and the wizard state.
|
||||
DIRECTION: Step registry: `{ id: 0, render: () => string, attach: (root) => Teardown }[]` keyed by mode. The 1220 LOC drops to ~500 after the WASM extraction in [P1] above and this restructure.
|
||||
|
||||
**[P2] setup/setup.ts:69–94 — `WizardState` is module-scope; passphrase + JPEG bytes + WASM handle persist if the user abandons mid-wizard**
|
||||
WHY: A user who closes the setup tab mid-flow leaves sensitive material in JS memory until the page is unloaded. The handle isn't `free()`d.
|
||||
DIRECTION: Add a `clearWizardState()` called on `beforeunload` and on returning to step 0; explicitly `Zeroize`-equivalent for the byte arrays where possible.
|
||||
|
||||
**[P2] setup/probe.ts:11–23 vs service-worker/vault.ts — manifest path constants duplicated (`.relicario/salt`, `.relicario/params.json`, `manifest.enc`)**
|
||||
WHY: Two sources of truth; if the metadata layout ever moves, probe and vault disagree about whether a remote is initialized.
|
||||
DIRECTION: Define `VAULT_PATHS` in `shared/types.ts` (or a new `shared/paths.ts`) and import into both.
|
||||
|
||||
**[P3] setup/setup.ts:56, 82–83 — passphrase score uses `-1` as "not yet scored" sentinel**
|
||||
WHY: The score is conflated with strength label index 0..4; `-1` magic number is checked in two places.
|
||||
DIRECTION: Use `{ scored: false } | { scored: true; score: number; guessesLog10: number }`.
|
||||
|
||||
**[P3] setup/setup.ts:1056–1062 — `recovery_qr_generated_at` written directly to `chrome.storage.local`, bypassing `WizardState`**
|
||||
WHY: One piece of setup result state lives outside the wizard's own state model.
|
||||
DIRECTION: Add it to `WizardState`, persist on a single `finishSetup` storage write.
|
||||
|
||||
**[P3] setup/setup.ts:1–7 — header comment says "5-step flow"; code is 6 steps (0..5)**
|
||||
WHY: Cosmetic but actively misleading; line 42 even has a comment about the renumber.
|
||||
DIRECTION: Update header.
|
||||
|
||||
### Extension — shared utilities
|
||||
|
||||
**[P1] shared/state.ts:10–35 — entire `StateHost` contract is `any`-typed**
|
||||
WHY: This is the bridge that lets popup components run in the vault tab; it's also the bridge most likely to drift between the two render targets, and TS gives no signal when it does.
|
||||
DIRECTION: Define a concrete `StateHost` interface with `state: PopupState`, `navigate: (view: View) => void`, `popOutToTab(): void`, `isInTab(): boolean`, `openVaultTab(hash?: string): void`. Make `getState`/`setState` generic over `keyof PopupState`.
|
||||
|
||||
**[P1] shared/state.ts:20 — module-scope `host` singleton with no double-registration guard**
|
||||
WHY: A second `registerHost()` call silently overwrites; in tests, the leak from a previous test breaks isolation if `beforeEach` forgets a reset.
|
||||
DIRECTION: Throw on re-register; export a `__resetHostForTests()` helper for vitest.
|
||||
|
||||
**[P2] shared/messages.ts:85–87 — base `Response` is `{ data?: unknown }`; every consumer casts via `Extract<Response, { ok: true }>` plus `data: ...`**
|
||||
WHY: The pattern works but every call site has a hand-written `as ListItemsResponse` cast; the discriminated-union narrowing the rest of the file relies on stops at `ok: true`.
|
||||
DIRECTION: Generic `Response<TKind extends Request['type']>` mapped from a single `MessageMap` table, so the response type is inferred at the send site.
|
||||
|
||||
**[P2] shared/form-affordances/group-autocomplete.ts:26 — `list.innerHTML = ...map(g => …).join('')` with only `replace(/"/g, '"')` sanitization**
|
||||
WHY: Group names come from user-entered item data. `<` and `>` are not escaped; a malicious / mistaken group name could inject markup into the autocomplete list.
|
||||
DIRECTION: `document.createElement('option')` per group with `option.value = g; list.appendChild(option)`.
|
||||
|
||||
**[P2] shared/messages.ts:56–66 — `restore_backup` flattens `newRemote` inline; other multi-field messages factor out a payload type**
|
||||
WHY: Inconsistent shape vs sibling messages; harder to reuse the type for the form that posts it.
|
||||
DIRECTION: Extract `RestoreBackupPayload` and intersect with `{ type: 'restore_backup' }`.
|
||||
|
||||
**[P3] glyphs.ts vs popup/components — raw glyph literals (`⧉`, `↻`, `▸`, `▾`, `≡`, `⤓`) appear inline in `item-form.ts`, `item-list.ts`, `settings.ts`, `generator-panel.ts`, `attachments-disclosure.ts`, `fields.ts`**
|
||||
WHY: The whole point of `glyphs.ts` is the no-inline-emoji rule; partial adoption defeats the audit story.
|
||||
DIRECTION: Add the missing constants (`GLYPH_COLLAPSE`, `GLYPH_EXPAND`, `GLYPH_ATTACHMENT`, `GLYPH_REGENERATE`, `GLYPH_OVERFLOW`, `GLYPH_DOWNLOAD`) and migrate the call sites. Pair with `extension/src/shared/__tests__/glyphs.test.ts` to lock it in.
|
||||
|
||||
**[P3] shared/types.ts:82 — `TotpKind = 'totp' | 'steam' | { hotp: { counter: number } }`**
|
||||
WHY: Mixed string/object union forces every consumer to do `typeof k === 'string' ? k : k.hotp`; a flat discriminated union is cheaper to read.
|
||||
DIRECTION: `{ kind: 'totp' } | { kind: 'steam' } | { kind: 'hotp'; counter: number }` with serde rename if the wire format must stay.
|
||||
|
||||
**[P3] shared/form-affordances/totp-tools.ts:39–46 — `void tick()` swallows promise rejections**
|
||||
WHY: TOTP preview RPC can fail (e.g., decrypt error); the user sees a frozen ticker with no signal.
|
||||
DIRECTION: `try { await tick() } catch (e) { renderError(row, e) }`.
|
||||
|
||||
### WASM boundary (JS side)
|
||||
|
||||
**[P2] extension/src/wasm.d.ts — declarations are hand-written and explicitly require manual sync with `crates/relicario-wasm/src/lib.rs`**
|
||||
WHY: Comment at top of the file says so; this is exactly the kind of contract that drifts when one side adds a new export. (Today, declarations and the Rust signatures are aligned.)
|
||||
DIRECTION: Add a CI check that compares `crates/relicario-wasm/pkg/relicario_wasm.d.ts` (wasm-pack output) against `extension/src/wasm.d.ts`, or import the generated `.d.ts` directly via `wasm-pack build --target web` and the runtime loader. Note for DEV-B in boundary section.
|
||||
|
||||
**[P2] extension/src/__stubs__/relicario_wasm.stub.ts — only 7 of ~25 exports are stubbed; the rest will throw `wasm stub: X not mocked`**
|
||||
WHY: Adding a vitest test that touches a new WASM call needs an ad-hoc mock per test; central stub is incomplete.
|
||||
DIRECTION: Either round out the stub with throwing stubs for the full surface, or provide a `mockWasm({ unlock, item_decrypt, ... })` test helper.
|
||||
|
||||
### Relay tooling
|
||||
|
||||
**[P1] tools/relay/queue.test.ts:54 — `assert.ok(!isRole("dev-c"))` fails (verified: `bun test` → 1 fail)**
|
||||
WHY: Uncommitted change added `dev-c` to the `Role` union and `KNOWN_ROLES` set in `queue.ts`, but the test still asserts the old enum. This is a P1 because it's a real test failure on uncommitted code, blocking a green test run.
|
||||
DIRECTION: Update the test assertion to `assert.ok(isRole("dev-c"))` and add a negative case (`assert.ok(!isRole("dev-d"))`).
|
||||
|
||||
**[P1] tools/relay/start.sh — kitty mode launches Dev-C window? Verify against the script**
|
||||
WHY: The 4-role refactor (pm/dev-a/dev-b/dev-c) needs a fourth window in the launcher. Per the subagent's read, `start.sh:80` still hardcodes "Dev-B" in user-facing output.
|
||||
DIRECTION: Update the launcher prints to mention all 4 roles and confirm a 4th `--type=tab --hold` window is opened with the dev-c prompt.
|
||||
|
||||
**[P2] tools/relay/call.py and tools/relay/call.ts — untracked, no .gitignore policy**
|
||||
WHY: Coordination prompts (including this one's "Fallback" section) reference `call.py` by path — it's load-bearing for the multi-agent flow, not an experiment. Untracked load-bearing files are a coordination footgun (a fresh checkout breaks the fallback).
|
||||
DIRECTION: Track both with a one-line header explaining "MCP-fallback shim for the relay; see docs/superpowers/coordination/...". If either is genuinely scratch, add to `.gitignore` instead — but pick one.
|
||||
|
||||
**[P2] tools/relay/queue.ts:21–27 — in-memory queue with no TTL, persistence, or cap**
|
||||
WHY: A long-running relay accumulates messages indefinitely; if a session sleeps for a day, the queue is the only audit trail and could grow unbounded.
|
||||
DIRECTION: Document the dev-only ephemeral contract at the top of `queue.ts`, or add a per-role cap (e.g., last 1000 messages).
|
||||
|
||||
**[P3] tools/relay/server.ts:115–127 — `makeServer()` factory pattern is correct but unexplained**
|
||||
WHY: The diff swap from a global `mcpServer` to per-connection factories is load-bearing for concurrent client isolation, but a future contributor might revert it as "unnecessary complexity".
|
||||
DIRECTION: One-line comment above `makeServer`: "Per-connection MCP server prevents routing collisions across concurrent SSE clients."
|
||||
|
||||
### CLI/extension parity gaps
|
||||
|
||||
**[P2] No equivalent to `relicario status`** — CLI shows pending sync state, ahead/behind, dirty-tree summary; extension surfaces nothing comparable. The vault-tab footer or a sidebar badge would be the natural home.
|
||||
DIRECTION: Add a `get_vault_status` message returning `{ ahead: n, behind: n, lastSyncAt: ts, pendingItems: n }` and a small status indicator in the vault sidebar.
|
||||
|
||||
**[P3] No explicit per-attachment detach message** — CLI has `relicario detach <item> <aid>`; extension forces a roundtrip through `update_item` with the `attachments[]` mutated client-side. Functional, but it's racy if two devices edit at once.
|
||||
DIRECTION: Add a `delete_attachment` message that does the surgical remove on the SW side.
|
||||
|
||||
**[P3] CLI `list --tag X` filter** — extension does tag filtering client-side after `list_items`; that's fine for the family-vault scale spec but may surprise a learner who reads the CLI side first.
|
||||
DIRECTION: Document the choice in `messages.ts` near `list_items`.
|
||||
|
||||
### Cross-cutting
|
||||
|
||||
**[P2] Direct `chrome.storage.local` reads from popup components** — `settings-security.ts:112–113` and `setup.ts:1056–1062` read storage directly while every other popup module routes via `sendMessage`. Inconsistency makes the data-flow story split across two paradigms.
|
||||
DIRECTION: Pick one: either every storage read goes through `get_settings`/`get_session_config`, or document explicitly that `setup` and `settings-security` are SW-bypass code paths for stated reasons.
|
||||
|
||||
**[P2] `bun test` is not the project's intended runner** — `extension/package.json:13` defines `test: vitest run`, but `tools/relay/` uses `node:test` via `bun test`. A learner will hit failures running `bun test` from the repo root because `bun` doesn't load `happy-dom`.
|
||||
DIRECTION: Add a top-level README note: "extension uses `cd extension && npm run test`; relay uses `cd tools/relay && bun test`."
|
||||
|
||||
**[P3] Manifest version 0.5.0** — both `extension/manifest.json` and `manifest.firefox.json` show `0.5.0`, while `package.json` is also `0.5.0`. The roadmap is at v0.5.1-dev; uncommitted bumps to package.json/manifest may be coming. Worth a quick PM check.
|
||||
|
||||
## File-by-file walk
|
||||
|
||||
### `extension/src/wasm.d.ts` and `__stubs__/relicario_wasm.stub.ts`
|
||||
Hand-written ambient module declarations mirroring `crates/relicario-wasm/src/lib.rs`. 25+ exports cover unlock/lock, manifest+item+settings encrypt/decrypt, attachment encrypt/decrypt, ID generation, password/passphrase generation + zxcvbn rate, image-secret embed/extract, TOTP compute, device register/sign/get/clear, recovery-QR. The stub used by vitest covers only 7 exports — every other call throws "not mocked" at test time.
|
||||
|
||||
### `extension/src/shared/`
|
||||
`types.ts` (286 LOC) is the canonical TS view of the Rust core schema; well-commented mappings to serde. `messages.ts` (207 LOC) is the discriminated-union message contract and the `POPUP_ONLY_TYPES` / `CONTENT_CALLABLE_TYPES` capability sets that the router uses for sender gating. `state.ts` (62 LOC) is the popup-vs-vault host indirection — currently `any`-typed. `glyphs.ts` (39 LOC, recently edited) is the centralized monospace glyph set. `color-scheme.ts`, `error-copy.ts`, `base32.ts`, `password-coloring.ts`, `toast.ts` are tight focused utilities. `form-affordances/` holds 5 input-behavior wirings (group autocomplete, notes mono toggle, password reveal/strength/QR, TOTP preview/QR, URL fill) plus a tiny `index.ts`.
|
||||
|
||||
### `extension/src/service-worker/`
|
||||
`index.ts` is the entry point: WASM load on first message, RouterState construction, session-timer wiring, `chrome.runtime.onMessage` listener. `vault.ts` (397 LOC) is the encrypted I/O layer — every WASM call passes the `SessionHandle`, never a raw key. `session.ts` is the single-handle store; `session-timer.ts` implements both `inactivity` and `every_time` modes. `devices.ts` reads/writes `.relicario/devices.json` and `revoked.json`. `gitea.ts` and `github.ts` mirror each other (Gitea has deploy-key ops; GitHub doesn't); `git-host.ts` is the abstraction. `router/index.ts` classifies the sender and dispatches to `popup-only.ts` (40+ handlers) or `content-callable.ts` (5 handlers).
|
||||
|
||||
### `extension/src/popup/`
|
||||
`popup.ts` (entry) wires the host registration, view router, and lock/unlock flow. `index.html` is a single `#popup-app` container. `styles.css` carries the popup theme. `components/` holds the visible widgets: `unlock`, `item-list`, `item-detail`, `item-form`, `form-header`, `fields`, `field-history`, `attachments-disclosure`, `generator-panel`, `devices`, `trash`, plus the new `settings.ts` / `settings-vault.ts` / `settings-security.ts` left-nav (v0.5.1). `components/types/` holds the 7 type-specific item modules — `login.ts` is the reference, the others (secure-note, identity, card, key, document, totp) are smaller variants.
|
||||
|
||||
### `extension/src/vault/`
|
||||
`vault.html` (12 LOC) loads `vault.css` + `vault.js`. `vault.css` (~2200 LOC) carries the dark/gold theme + 3-column layout. `vault.ts` (1027 LOC) orchestrates everything: shell init, hash routing, sidebar, list, drawer, type-picker, form-wrapper, deep-link routing, teardown. `components/backup-panel.ts` and `components/import-panel.ts` are vault-tab-only (high-risk operations need fullscreen affordances). Tests: `form-wrapper.test.ts`, `sidebar-glyphs.test.ts`.
|
||||
|
||||
### `extension/src/content/`
|
||||
`detector.ts` finds password fields and injects icons via a MutationObserver. `fill.ts` receives `fill_credentials`, re-validates the page hostname, and uses the native-setter trick to set values past React/Vue. `capture.ts` hooks form submits and shows a closed-Shadow-DOM save prompt. `icon.ts` renders the in-page icon and credentials picker. `shadow.ts` is the closed-Shadow-DOM helper. **Zero WASM calls; clean boundary.**
|
||||
|
||||
### `extension/src/setup/`
|
||||
`setup.ts` (1220 LOC) is the 6-step (0..5) wizard: mode pick → remote config → image select / passphrase → derive+verify or create+embed → device register → recovery QR. Imports WASM directly. `setup-helpers.ts` (84 LOC) is a clean utility module (escapeHtml, debounced rate, strength labels). `probe.ts` (23 LOC) checks for an existing vault on the configured remote.
|
||||
|
||||
### `tools/relay/`
|
||||
`server.ts` is the MCP server with HTTP/SSE transport (per-connection `makeServer()`). `queue.ts` is the in-memory FIFO with `Role` enum and `isRole()` guard. `queue.test.ts` is `node:test` based (4 pass / 1 fail on uncommitted state). `call.py` and `call.ts` are the MCP-fallback shims (untracked). `start.sh` launches manual / tmux / kitty modes. `package.json`, `tsconfig.json` keep the relay self-contained.
|
||||
|
||||
## CLI/extension parity table
|
||||
|
||||
| CLI capability | Extension equivalent | Notes |
|
||||
|---|---|---|
|
||||
| `init --image --output` | `save_setup` + setup wizard step 3-new | ✓ (parity via setup.ts; see [P1] about routing through SW) |
|
||||
| `add login/secure_note/identity/card/key/document/totp` | `add_item` + `types/<kind>.ts` form | ✓ |
|
||||
| `get <query> [--show] [--copy]` | `get_item` + popup detail; clipboard via `navigator.clipboard` | ✓ |
|
||||
| `list [--type] [--group] [--tag] [--trashed]` | `list_items`, `list_trashed`, client-side filter; `list_groups` for autocomplete | ✓ |
|
||||
| `edit <query> [--totp-qr]` | `update_item` + `wireTotpQr` (jsQR lazy import) | ✓ |
|
||||
| `history <query>` | `get_field_history` + `field-history.ts` | ✓ |
|
||||
| `rm <query>` (soft) | `delete_item` | ✓ |
|
||||
| `restore <query>` | `restore_item` | ✓ |
|
||||
| `purge <query>` | `purge_item` | ✓ |
|
||||
| `trash list / empty` | `list_trashed` / `purge_all_trash` + `trash.ts` | ✓ |
|
||||
| `backup export` | `export_backup` + `backup-panel.ts` | ✓ |
|
||||
| `backup restore` | `restore_backup` + `backup-panel.ts` (restore path) | ✓ |
|
||||
| `import lastpass <csv>` | `parse_lastpass_csv` + `import_lastpass_commit` + `import-panel.ts` | ✓ |
|
||||
| `attach <query> <file>` | `upload_attachment` | ✓ |
|
||||
| `attachments <query>` | `AttachmentRef[]` already inside `get_item` | ✓ (no separate message; same data) |
|
||||
| `extract <query> <aid>` | `download_attachment` | ✓ |
|
||||
| `detach <query> <aid>` | (no message) — done via `update_item` with mutated `attachments[]` | **partial / ✗** |
|
||||
| `generate --length / --bip39 …` | `generate_password` / `generate_passphrase` + `generator-panel.ts` | ✓ |
|
||||
| `settings trash-retention / history-retention / attachment-cap / generator-defaults` | `get_vault_settings` / `update_vault_settings` + `settings-vault.ts` | ✓ |
|
||||
| `sync` | `sync` | ✓ |
|
||||
| `status` | (no message) | **✗ — gap** |
|
||||
| `lock` | `lock` | ✓ |
|
||||
| `completions <shell>` | N/A (CLI-only) | n/a |
|
||||
| `rate <passphrase>` | `rate_passphrase` (zxcvbn gate) | ✓ |
|
||||
| `device add / revoke` (+ list) | `add_device` / `register_this_device` / `revoke_device` / `list_devices` / `list_revoked` + `devices.ts` | ✓ |
|
||||
| `recovery-qr generate / unwrap` | `generate_recovery_qr` / `unwrap_recovery_qr` + `settings-security.ts` | ✓ |
|
||||
| (browser-only autofill) | `get_autofill_candidates`, `get_credentials`, `check_credential`, `blacklist_site`, `capture_save_login`, `fill_credentials`, `ack_autofill_origin`, `get_blacklist`, `remove_blacklist`, `get_active_tab_url` | extension-only (no CLI counterpart, by design) |
|
||||
| (browser-only device UX) | `get_settings` / `update_settings` (DeviceSettings: captureEnabled, captureStyle) | extension-only |
|
||||
|
||||
**Summary:** 22/23 CLI capabilities have a clean extension path; `status` is the one true gap, and `detach` is partial. No "CLI first, extension follow-up" violations under this lens.
|
||||
|
||||
## Boundary notes for DEV-B
|
||||
|
||||
1. **`extension/src/wasm.d.ts` is hand-maintained** — every change to `crates/relicario-wasm/src/lib.rs`'s `#[wasm_bindgen]` surface must be mirrored manually. Worth a CI guardrail comparing the wasm-pack–generated `.d.ts` against this file. (See [P2] in WASM boundary.)
|
||||
|
||||
2. **The session handle is opaque on the JS side** (`SessionHandle.value: number`, `free()`). DEV-B owns the Rust-side lifecycle: confirm that double-`free()` from JS is a no-op rather than a panic, since `service-worker/session.ts:26` currently swallows free errors silently. If the Rust side could panic on double-free, the silent swallow becomes a crash mask.
|
||||
|
||||
3. **`attachment_encrypt(handle, plaintext, max_bytes: bigint)`** — the JS side passes `BigInt` for `max_bytes`. Confirm the Rust binding accepts `u64` and that the conversion is loss-free. The extension is going to push this with γ₁ enforcement (per project memory).
|
||||
|
||||
4. **`register_device(name)` returns `{ signing_public_key, deploy_public_key }`** as a plain object (not a class). Setup wizard relies on both being hex strings (`device.public_key` lookup paths). Confirm the device key types stay strings on the Rust side rather than ever moving to `Uint8Array`.
|
||||
|
||||
5. **`generate_recovery_qr(handle, passphrase) → string`** and `unwrap_recovery_qr(payload_b64, passphrase) → Uint8Array` — the QR payload format is a contract between this surface and the CLI's `recovery-qr` subcommand. If DEV-B is reviewing recovery-QR end-to-end, confirm that re-deriving from a recovery QR produces the same `master_key` regardless of which side (CLI vs extension) generated it.
|
||||
|
||||
6. **`extract_image_secret(image_bytes) → Uint8Array` and `embed_image_secret(carrier, secret) → Uint8Array`** — the central-embed DCT scheme has `MAX_DIMENSION` and `QUANT_STEP = 50.0` constants on the Rust side. The setup wizard does no client-side dimension check before passing the image; if a >MAX_DIMENSION JPEG is selected, the failure message bubbles up generically. DEV-B may want a more specific Rust-side error variant the extension can re-render.
|
||||
|
||||
## Beginner-friendliness assessment (TS side)
|
||||
|
||||
**Reading order recommendation:** start with `extension/src/shared/messages.ts` and `types.ts` — they tell you the entire vocabulary in 500 lines. Then `service-worker/router/index.ts` to see how messages get routed. Then pick **one** vertical to follow end-to-end: `popup/components/types/login.ts` → `service-worker/router/popup-only.ts` (the `add_item`/`update_item` handlers) → `service-worker/vault.ts`. After that, `content/detector.ts` + `content/fill.ts` + the corresponding `content-callable.ts` handlers cover the autofill story.
|
||||
|
||||
**Trip wires:** the two oversized files (`vault.ts` 1027 LOC, `setup.ts` 1220 LOC) are the steepest cliffs. A learner who opens `setup.ts` first will see WASM imported directly and conclude that's the pattern — it isn't; that file is the exception. Adding a short `EXTENSION_ARCH.md` (or a comment block at the top of `setup.ts`) noting "WASM is loaded directly here only because vault creation predates the SW; everywhere else, route through `chrome.runtime.sendMessage`" would save half a day.
|
||||
|
||||
**Strongest learning surfaces:** the discriminated-union message contract, the per-type item form modules (small, parallel, easy to diff), and `service-worker/router/router.test.ts`. The shared form-affordances are also a model of pure-function wiring with explicit teardown — once those patterns click, the rest of the popup is "more of the same."
|
||||
|
||||
**Weakest learning surface:** `shared/state.ts` — it's the bridge between popup and vault tab, but the `any` typing tells you nothing about what flows through it. Tightening this is a high-leverage change.
|
||||
|
||||
## Uncommitted-state read
|
||||
|
||||
The working tree has substantial uncommitted changes. Architecturally relevant:
|
||||
|
||||
- **`extension/src/vault/vault.ts` (+151/−99) and `vault.css` (+238/−99)** — appear to be active work on the form wrapper sticky bar, drawer field grid, and gold-rebrand color palette (Phase 2B). Treat these as **in flight, ignore for this review** — they don't change the architectural shape, only the visual surface.
|
||||
- **`extension/src/shared/glyphs.ts` (+/−2) and `__tests__/glyphs.test.ts` (+/−2)** — small additions, likely a new glyph constant. Doesn't affect the [P3] glyph adoption finding (the inline-literal call sites would still need migration).
|
||||
- **`extension/manifest.json` and `manifest.firefox.json` (+/−2)** — likely a version bump in flight; PM should decide whether v0.5.1-dev gets a synced bump in `package.json` too.
|
||||
- **`tools/relay/queue.ts`, `server.ts`, `start.sh` (modified) + `call.py`, `call.ts` (untracked)** — these are **architecturally relevant**: the dev-c role expansion is real, and `call.py`/`call.ts` are documented-but-untracked fallback shims. The broken test (`queue.test.ts:54`) is the P1 the rest of this review flags. **Do not ignore.**
|
||||
- **`Cargo.lock`, `crates/*/Cargo.toml`** — out of scope; flag to DEV-A/DEV-B if not already on their list.
|
||||
- **`.gitea_env_vars` (untracked)** — name suggests local credentials; should be `.gitignore`d if not already (PM check).
|
||||
- **`docs/superpowers/coordination/v0.5.1-*` and `architecture-review-*`** — coordination prompt evolution; not architectural.
|
||||
|
||||
**My call:** vault/vault.css/glyphs/manifest changes are in-flight and shouldn't change findings. The relay changes ARE architecturally on-the-table because the new dev-c role + factory pattern are visible in the running review process. The relay test failure is treated as a P1 because it blocks `bun test` from going green and the kickoff prompt explicitly says "Review is not gated on green; it's gated on understanding" — but this is one cheap fix away from a green test run, and a learner running `bun test` first will assume the codebase is broken.
|
||||
215
docs/superpowers/specs/2026-05-04-cli-restructure-design.md
Normal file
215
docs/superpowers/specs/2026-05-04-cli-restructure-design.md
Normal file
@@ -0,0 +1,215 @@
|
||||
# CLI Restructure — Design
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Status:** Proposed
|
||||
**Source:** `docs/superpowers/reviews/2026-05-04-architecture-review.md` (P1.2, P1.3, P1.10) + folded P2s from DEV-B's CLI section + DEV-A's P2 base32 dedup
|
||||
**Effort estimate:** M-L
|
||||
|
||||
## Summary
|
||||
|
||||
Plan B is the single biggest readability lift in the whole-codebase architecture review. `crates/relicario-cli/src/main.rs` is a 2641-line flat file: every `cmd_*`, every `build_*_item`, every `edit_*`, six prompt helpers, three pure parsers, the `ParamsFile` writer, and 24+ git shell-outs all live as peers. This plan splits that file into a `commands/` folder plus `prompt.rs` and `parse.rs`, then builds on top of that split to centralize the duplicated git-error UX, unify the manifest-after-mutation cache discipline, deduplicate the on-disk `params.json` shape, batch the `cmd_purge` git invocations, and finally migrate the pure parsers (and a third copy of base32) into `relicario-core` so the extension can consume them through new WASM exports. After the file is navigable rather than scrollable, a tinkerer who opens `cmd_add` can follow it end-to-end in one screenful — which is the user's stated learning-by-tinkering goal.
|
||||
|
||||
## Findings addressed
|
||||
|
||||
- **P1.2** — `crates/relicario-cli/src/main.rs:1-2641` is a 2641-line monolith with no submodule boundaries (DEV-B). The clap surface (lines 1-455) is excellent; lines 456-2641 are flat code.
|
||||
- **P1.3** — Git invocation boilerplate duplicated ~16× with one-line `bail!("git X failed")` errors at `crates/relicario-cli/src/main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` (and others) (DEV-B).
|
||||
- **P1.10** — Pure parsers (`parse_month_year`, `base32_decode_lenient`, `guess_mime`) live only in the CLI at `crates/relicario-cli/src/main.rs:942-980` despite the extension needing them (DEV-B). Pairs with DEV-A's P2 finding that three base32 implementations live in core (`crates/relicario-core/src/item.rs:255-275`, `crates/relicario-core/src/import_lastpass.rs:202-220`, and intentionally separate Steam at `crates/relicario-core/src/item_types/totp.rs:13`).
|
||||
- **CLI P2 — `build_*_item` complexity** at `crates/relicario-cli/src/main.rs:664-921` (DEV-B). Each builder mixes prompting, parsing, and core construction.
|
||||
- **CLI P2 — `refresh_groups_cache` discipline** at `crates/relicario-cli/src/main.rs:641, 998, 1123, 1197, 1414, 1432, 1474` (DEV-B). The "every mutating handler must call this" rule is unenforced.
|
||||
- **CLI P2 — `ParamsFile` defined twice with mismatching shapes** at `crates/relicario-cli/src/main.rs:2287` (writer with `aead`, `salt_path`, `format_version`) versus `crates/relicario-cli/src/session.rs:114` (reader with only `kdf`) (DEV-B).
|
||||
- **CLI P2 — Batched purge needed** at `crates/relicario-cli/src/main.rs:1476-1480` and `:1896-1900` (DEV-B). A 50-item `trash empty` currently fires 150 git invocations.
|
||||
|
||||
## Approach
|
||||
|
||||
The architectural shape is "one file per top-level subcommand, plus two cross-cutting helpers, plus a thin dispatcher." The clap definitions stay at the top of `main.rs` because they read like a tour of the product and that's exactly what a learner wants to land on first; everything past the dispatcher moves out. Each new module becomes self-contained enough that a tinkerer following a single command does not need to scroll through neighbours.
|
||||
|
||||
Post-split layout under `crates/relicario-cli/src/`:
|
||||
|
||||
```
|
||||
src/
|
||||
├── main.rs # clap surface (Cli, Commands, AddKind, …) + dispatch match (~470 lines)
|
||||
├── helpers.rs # vault_dir, git_command, git_run (NEW), iso8601, humanize_age,
|
||||
│ # groups_cache_path, sanitize_for_commit, decode_totp_qr
|
||||
├── session.rs # UnlockedVault, ParamsFile (single canonical), after_manifest_change (NEW)
|
||||
├── device.rs # ed25519 keypair storage, configure_git_signing
|
||||
├── gitea.rs # GiteaClient (deploy-key API)
|
||||
├── prompt.rs # NEW — prompt, prompt_optional, prompt_secret, prompt_or_flag<T>,
|
||||
│ # and the four other small prompt_* helpers
|
||||
├── parse.rs # NEW — thin wrappers around the migrated core parsers
|
||||
│ # (until phase 7, the parsers themselves live here)
|
||||
└── commands/
|
||||
├── mod.rs # NEW — pub use re-exports for the dispatcher
|
||||
├── add.rs # cmd_add + the seven build_*_item helpers
|
||||
├── get.rs # cmd_get
|
||||
├── list.rs # cmd_list, cmd_history, resolve_query
|
||||
├── edit.rs # cmd_edit + per-type edit_* helpers
|
||||
├── trash.rs # cmd_rm, cmd_restore, cmd_purge, cmd_trash, cmd_trash_empty,
|
||||
│ # purge_item
|
||||
├── backup.rs # cmd_backup, cmd_backup_export, cmd_backup_restore
|
||||
├── import.rs # cmd_import (LastPass)
|
||||
├── attach.rs # cmd_attach, cmd_attachments, cmd_extract, cmd_detach
|
||||
├── settings.rs # cmd_settings (and its subaction handlers)
|
||||
├── sync.rs # cmd_sync (push/pull/fetch)
|
||||
├── status.rs # cmd_status (vault state summary)
|
||||
├── device.rs # cmd_device + register/revoke/list, load_gitea_client
|
||||
├── recovery_qr.rs # cmd_recovery_qr, cmd_recovery_qr_generate, cmd_recovery_qr_unwrap
|
||||
├── init.rs # cmd_init (also writes ParamsFile via session module)
|
||||
├── generate.rs # cmd_generate
|
||||
└── rate.rs # cmd_rate
|
||||
```
|
||||
|
||||
Rationale for the boundaries:
|
||||
|
||||
- **One file per top-level subcommand** is the navigation invariant: `relicario add` ⇒ `commands/add.rs`. `cmd_add` and the seven `build_*_item` helpers it calls are the ~260-line vertical slice a tinkerer wants in front of them at once. Same shape for every other subcommand.
|
||||
- **`prompt.rs` is the input layer**: every command that reads from the user funnels through one module, so swapping in a different prompt strategy (richer TTY widgets, scripted-test mode) is a one-file change. The `prompt_or_flag<T>` helper introduced in phase 3 lives here.
|
||||
- **`parse.rs` is the validation layer** during phases 1–6 — it owns `parse_month_year`, `base32_decode_lenient`, `guess_mime`. In phase 7 the bodies move to `relicario-core` and `parse.rs` becomes a thin re-export so callers don't have to change imports twice.
|
||||
- **`helpers.rs` keeps `git_command` (the hardened `Command` builder) and gains `git_run`** (the bail-on-failure wrapper). Both are flat utilities; they belong with `vault_dir` and `iso8601`.
|
||||
- **`session.rs` keeps `UnlockedVault` and absorbs the canonical `ParamsFile`** so the on-disk shape has one definition, not two. The `after_manifest_change` wrapper introduced in phase 4 also lives here, because it's logically a session method.
|
||||
- **`commands/mod.rs`** re-exports each `cmd_*` so the dispatch match in `main.rs` reads as `Commands::Add { kind } => commands::add::cmd_add(kind)` — the dispatch surface still fits on one screen.
|
||||
|
||||
Boundary discipline: every `cmd_*` becomes `pub fn` in its module file; every `build_*_item` and `edit_*` stays `pub(super)` (only its sibling dispatcher needs it). Helpers shared across `commands/` (e.g. `commit_paths`, `resolve_query`) live in `commands/mod.rs` as `pub(crate)`. The compile error if a sibling moves and a caller forgets the visibility bump is exactly the safety net we want.
|
||||
|
||||
**WASM/extension parity seam (P1.10).** The three CLI parsers move into `relicario-core` in phase 7, get re-exported as `#[wasm_bindgen]` functions in phase 8, and the `extension/src/wasm.d.ts` file is updated in the same commit (per DEV-C's boundary note, that file is hand-maintained — every export change must be mirrored manually). Plan C (extension restructure) then wires SW message handlers that call those WASM exports; **the SW handlers themselves are not designed in this plan** — phase 8 only delivers the seam Plan C consumes.
|
||||
|
||||
## Implementation phases
|
||||
|
||||
### Phase 1 — Mechanical split of `main.rs`
|
||||
|
||||
- **Goal:** turn 2641 LOC of flat code into a navigable directory tree without changing any behaviour.
|
||||
- **Changes:**
|
||||
- New: `crates/relicario-cli/src/commands/{mod,add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr,init,generate,rate}.rs`.
|
||||
- New: `crates/relicario-cli/src/prompt.rs` (lifts `prompt`, `prompt_optional`, `prompt_secret` from `main.rs:508-940`).
|
||||
- New: `crates/relicario-cli/src/parse.rs` (lifts `parse_month_year`, `base32_decode_lenient`, `guess_mime` from `main.rs:942-980`).
|
||||
- Modified: `crates/relicario-cli/src/main.rs` — keeps `mod` declarations, the clap `Cli`/`Commands`/`AddKind` enums (lines 1-455), the dispatch `match` (lines 405-454), the three `test_*_override()` shims (lines 475-503), and the `refresh_groups_cache` shim (lines 457-473) until phase 4 collapses it.
|
||||
- Modified: every other file that referenced `crate::session::UnlockedVault::unlock_interactive`, `crate::helpers::*`, `crate::test_passphrase_override` keeps working unchanged (visibility bumps only).
|
||||
- **Tests:** the existing CLI integration tests at `crates/relicario-cli/tests/{basic_flows,attachments,backup,edit_and_history,settings,smart_inputs,vault_detection,import_lastpass}.rs` are the regression budget. They test from the binary surface (via `assert_cmd`), so a pure relocation must not change a single assertion. Run between every sub-step. No new tests in this phase; logic is unchanged.
|
||||
- **Effort:** M (largest single phase by LOC moved; mechanical).
|
||||
- **Depends on:** none.
|
||||
|
||||
### Phase 2 — `helpers::git_run` and the 16-site sweep
|
||||
|
||||
- **Goal:** replace 16 `bail!("git X failed")` one-liners with `git_run(repo, args, context)?`, so a failing git subprocess prints actionable stderr instead of just the verb.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-cli/src/helpers.rs` — adds `pub fn git_run(repo: &Path, args: &[&str], context: &str) -> Result<()>` that uses `.output()` (capturing stderr), prints the captured stderr unmodified to the user's stderr on failure, and bails with `"<context>: git failed (status N)"`. Keeps `git_command` for the rare interactive callsite that needs a `Command` (phase decides per call).
|
||||
- Modified: `crates/relicario-cli/src/commands/init.rs` — three sites collapse (`main.rs:601, 602, 610` post-split). Contexts: `"init: git init"`, `"init: git add"`, `"init: git commit"`.
|
||||
- Modified: `crates/relicario-cli/src/commands/add.rs` — two sites in `commit_paths` (`main.rs:986, 988` post-split moves to `commands/mod.rs`). Context: `"add: git add <id>"`, `"add: git commit"`.
|
||||
- Modified: `crates/relicario-cli/src/commands/trash.rs` — `cmd_purge` and `cmd_trash_empty` sites (`main.rs:1477, 1480, 1897, 1900` post-split). Contexts include the item title for trace clarity. (Phase 6 batches them further.)
|
||||
- Modified: `crates/relicario-cli/src/commands/edit.rs` — `main.rs:1767` site post-split. Context: `"edit: git commit"`.
|
||||
- Modified: `crates/relicario-cli/src/commands/sync.rs` — `main.rs:2432, 2438, 2533, 2540` sites post-split. Contexts: `"sync: git fetch"`, `"sync: git pull"`, `"sync: git push"`.
|
||||
- Modified: any other `git_command(...).status()? + bail!` site identified by grep during phase 1 (DEV-B's "and others" list).
|
||||
- **Tests:** add a unit test in `crates/relicario-cli/src/helpers.rs`'s `mod tests` that invokes `git_run` against a deliberately-failing git subcommand in a `tempfile::TempDir` and asserts both that the bail message contains the context string and that the captured stderr is reproduced. Existing integration tests must still pass.
|
||||
- **Effort:** S.
|
||||
- **Depends on:** Phase 1.
|
||||
|
||||
### Phase 3 — `prompt_or_flag<T>` and `build_*_item` compression
|
||||
|
||||
- **Goal:** collapse the seven `build_*_item` builders so each one takes already-validated values, with a single `prompt_or_flag<T>` helper handling the "use this flag if Some, otherwise prompt" pattern.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-cli/src/prompt.rs` — adds `pub fn prompt_or_flag<T>(flag: Option<T>, label: &str, parser: impl FnOnce(&str) -> Result<T>) -> Result<T>` and a `prompt_or_flag_optional<T>` sibling for fields where the empty-string case maps to `None`.
|
||||
- Modified: `crates/relicario-cli/src/commands/add.rs` — every `build_*_item` (post-split locations of `main.rs:664-921`) drops its `Option<T>::map(Ok).unwrap_or_else(|| prompt(...))?` chains in favour of `prompt_or_flag(title, "Title", |s| Ok(s.into()))?` etc. Per-type bodies shrink by ~30%.
|
||||
- **Tests:** existing `tests/basic_flows.rs::add_login_then_list_shows_it`, `tests/smart_inputs.rs` cover the prompt path; `tests/attachments.rs` covers the document builder. Add one focused test: `prompt_or_flag_uses_flag_value_when_some` and `prompt_or_flag_prompts_when_none` (synthetic stdin via `Cursor`).
|
||||
- **Effort:** S-M.
|
||||
- **Depends on:** Phase 1.
|
||||
|
||||
### Phase 4 — `Vault::after_manifest_change` and the seven-site sweep
|
||||
|
||||
- **Goal:** make "every mutating handler must call `refresh_groups_cache`" a compile-time invariant rather than a discipline rule.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-cli/src/session.rs` — adds `pub fn after_manifest_change(&self, manifest: &Manifest) -> Result<()>` that calls `self.save_manifest(manifest)?` and then writes the groups cache. Marks the existing `save_manifest` as `pub(crate)` (or renames to `save_manifest_raw` and makes it `pub(crate)`) so callers funnel through the wrapper. Cache writing logic moves out of `main.rs:457-473` into this method.
|
||||
- Modified: `crates/relicario-cli/src/commands/{add,edit,trash,attach,settings,import}.rs` — the seven sites (`main.rs:641, 998, 1123, 1197, 1414, 1432, 1474` post-split) collapse from `vault.save_manifest(&manifest)?; refresh_groups_cache(vault.root(), &manifest);` to `vault.after_manifest_change(&manifest)?;`.
|
||||
- Removed: the standalone `refresh_groups_cache` function in `main.rs:463`. The cache-write closure inside `after_manifest_change` keeps the existing "failures are silently swallowed" semantics (preserve the `let _ =` and the doc comment from `main.rs:457-462`).
|
||||
- **Tests:** `tests/smart_inputs.rs::groups_cache_*` already exercises the write/suppress paths from the binary surface; rerun. Add a unit test in `session.rs` confirming `after_manifest_change` writes both the manifest and the cache file.
|
||||
- **Effort:** S.
|
||||
- **Depends on:** Phase 1.
|
||||
|
||||
### Phase 5 — Single canonical `ParamsFile`
|
||||
|
||||
- **Goal:** one definition of the on-disk `params.json` shape, used by both the `init` writer and the `unlock_interactive` reader.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-cli/src/session.rs` — promotes the inner `ParamsFile` struct (`session.rs:114`) to a module-level `pub(crate) struct ParamsFile { pub format_version: u32, pub kdf: KdfParams, pub aead: String, pub salt_path: String }`. Adds `Serialize` + `Deserialize` derives. Provides constructors: `ParamsFile::for_new_vault(params: &KdfParams) -> Self` and inversion `pub fn into_kdf_params(self) -> KdfParams`. Verifies field-rename compatibility against the existing on-disk JSON (read a temp `params.json` written by current `main.rs` to confirm round-trip).
|
||||
- Modified: `crates/relicario-cli/src/commands/init.rs` — replaces the inline `ParamsFile`/`ParamsKdf` structs at the post-split equivalent of `main.rs:2287-2301` with `session::ParamsFile::for_new_vault(¶ms)`. Removes the duplicate writer-side definition.
|
||||
- Decision note in the module doc-comment: keep `ParamsFile` in `session.rs` rather than `relicario-core`. Rationale: the struct describes a *file on disk*, and `relicario-core` is bytes-in/bytes-out (no filesystem). The `KdfParams` value inside is core's already; the envelope is the CLI's I/O concern.
|
||||
- **Tests:** add `tests/common/mod.rs` (or extend an existing test) round-trip: write via `ParamsFile::for_new_vault`, parse via `read_params`, confirm the resulting `KdfParams` matches the input. The on-disk schema must not change (`tests/basic_flows.rs::init_creates_expected_layout` indirectly covers this).
|
||||
- **Effort:** S.
|
||||
- **Depends on:** Phase 1.
|
||||
|
||||
### Phase 6 — Batched purge in `cmd_purge` and `cmd_trash_empty`
|
||||
|
||||
- **Goal:** a 50-item `trash empty` should fire 3 git invocations total, not 150.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-cli/src/commands/trash.rs` — `purge_item` (post-split of `main.rs:1450-1462`) is renamed `purge_item_filesystem` and **only** mutates the working tree + manifest (filesystem `remove_file`/`remove_dir_all`, manifest `remove`). It does **not** invoke `git rm`. Returns `Vec<String>` of the paths it removed (so the caller can stage them).
|
||||
- `cmd_purge` (post-split `main.rs:1464-1482`): collects the paths from `purge_item_filesystem`, calls `vault.after_manifest_change(&manifest)?`, then a single `git_run(vault.root(), &["rm", "-rf", "--ignore-unmatch", … paths …, "manifest.enc"], "purge: git rm")?` followed by `git_run(... ["add", "manifest.enc"], "purge: git add")?` (manifest is staged separately because it was rewritten not removed) and `git_run(... ["commit", "-m", &msg], "purge: git commit")?`. Three invocations, fixed.
|
||||
- `cmd_trash_empty` (post-split `main.rs:1885-1903`): same pattern over the loop of purgeables — accumulate all paths, then one `git rm`, one `git add manifest.enc`, one `git commit`. The commit message keeps `"trash empty: purged N item(s)"`.
|
||||
- **Tests:** existing `tests/basic_flows.rs::rm_restore_purge_cycle` covers the single-item purge contract. Add `tests/basic_flows.rs::trash_empty_batches_git_invocations` (or extend `tests/settings.rs`) — purge ≥3 items via `trash empty`, then assert via `git log --oneline --since=…` that exactly **one** new commit appeared (a strict invariant that catches accidental re-introduction of per-item commits). Synthetic fixtures only; no binary blobs.
|
||||
- **Effort:** S-M.
|
||||
- **Depends on:** Phases 1, 2, 4 (uses `git_run` and `after_manifest_change`).
|
||||
|
||||
### Phase 7 — Migrate parsers to `relicario-core` + `pub(crate) mod base32`
|
||||
|
||||
- **Goal:** close DEV-A's three-base32-implementations finding and DEV-B's parsers-in-CLI-only finding in one stroke. The CLI keeps thin wrappers (no caller-side import changes); core becomes the single source of truth.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-core/src/time.rs` — adds `impl MonthYear { pub fn parse(s: &str) -> Result<Self, RelicarioError> { … } }` accepting `MM/YYYY`, `MM-YYYY`, and `MM/YY` (lifts the body of `parse_month_year` from `crates/relicario-cli/src/parse.rs`). Note: `MonthYear::new` currently returns `Result<_, &'static str>` (DEV-A P3); this phase has the option to either bring `new` to `RelicarioError` for consistency, or leave it and have `parse` call `new` and re-wrap. Recommendation: re-wrap only — the `new` migration is DEV-A's P3 to keep this plan focused.
|
||||
- New: `crates/relicario-core/src/base32.rs` — `pub(crate) mod base32 { pub fn encode_rfc4648(bytes: &[u8]) -> String; pub fn decode_rfc4648_lenient(s: &str) -> Result<Vec<u8>, RelicarioError>; }`. Body lifted/unified from `crates/relicario-core/src/item.rs:255-275` (the encoder) and `crates/relicario-core/src/import_lastpass.rs:202-220` (the decoder), plus the lenient input handling (case-insensitive, padding-optional, whitespace-stripped) from `crates/relicario-cli/src/parse.rs`. Steam's `STEAM_ALPHABET` at `crates/relicario-core/src/item_types/totp.rs:13` stays put with a neighbour comment: `// not RFC 4648 — Steam Guard's de-ambiguated alphabet; see crate::base32 for the standard impl.`
|
||||
- Modified: `crates/relicario-core/src/item.rs` — removes the inline `base32_encode` (lines 255-275); call sites switch to `crate::base32::encode_rfc4648`.
|
||||
- Modified: `crates/relicario-core/src/import_lastpass.rs` — removes the inline `decode_base32_totp` (lines 202-220); call sites switch to `crate::base32::decode_rfc4648_lenient`.
|
||||
- New: `crates/relicario-core/src/item_types/totp.rs` — adds `impl TotpConfig { pub fn parse_secret(s: &str) -> Result<Zeroizing<Vec<u8>>, RelicarioError> { Ok(Zeroizing::new(crate::base32::decode_rfc4648_lenient(s)?)) } }`. The `Zeroizing` wrap is the value-add over a raw base32 call.
|
||||
- New: `crates/relicario-core/src/mime.rs` — `pub fn guess_for_extension(filename: &str) -> &'static str` (lifts `guess_mime` from CLI). Default `application/octet-stream`. The match is small enough that exhaustive enum tagging (PDF/PNG/JPEG/TXT/JSON) is overkill; keep the string-match shape.
|
||||
- Modified: `crates/relicario-core/src/lib.rs` — re-exports `MonthYear` (already exported), `mime`, `base32` (`pub(crate)` only, not in the public API surface). `Totp::parse_secret` is reachable via `ItemCore::Totp(_).parse_secret(...)` already.
|
||||
- Modified: `crates/relicario-cli/src/parse.rs` — becomes a thin shim re-exporting the new core API. `pub fn parse_month_year(s: &str) -> Result<MonthYear, RelicarioError> { MonthYear::parse(s) }` (so the existing CLI callsites need zero edits in this phase). Same for `base32_decode_lenient` and `guess_mime`. Once Plan C lands and consumers have all migrated, a follow-up plan can delete `parse.rs` entirely.
|
||||
- Verification step: before phase 7, grep `grep -RIn "parse_month_year\|base32_decode_lenient\|guess_mime\|base32_encode\|decode_base32_totp" crates/ extension/` to confirm the only consumers are the CLI files about to be touched. The Cargo workspace currently has no other consumer.
|
||||
- **Tests:** move CLI's existing parser unit tests (if any) into `crates/relicario-core/src/`. Add: `MonthYear::parse` round-trip for `01/2026`, `12/30`, `12-2026`, plus error cases (`13/2026`, `01/1999`, `garbage`); `base32::encode_rfc4648`/`decode_rfc4648_lenient` round-trip on a known TOTP vector (the RFC 6238 test vector already lives in `item_types/totp.rs`); `mime::guess_for_extension` table — `pdf.PDF`, `image.jpg`, `image.jpeg`, `unknown.xyz`. Keep `tests/import_lastpass.rs` green (it'll go through the new shared decoder). Existing CLI integration tests at `crates/relicario-cli/tests/*` must still pass; the public CLI surface is unchanged.
|
||||
- **Effort:** M.
|
||||
- **Depends on:** Phase 1.
|
||||
|
||||
### Phase 8 — WASM exports for the migrated parsers + wasm.d.ts mirror
|
||||
|
||||
- **Goal:** make the new core parsers reachable from the extension via the SW. Deliver only the seam; Plan C wires the SW handlers.
|
||||
- **Changes:**
|
||||
- Modified: `crates/relicario-wasm/src/lib.rs` — adds three `#[wasm_bindgen]` exports:
|
||||
- `pub fn parse_month_year(s: &str) -> Result<JsValue, JsError>` returning the serialized `MonthYear` (`{ month, year }` plain object via the existing `Serializer::new().serialize_maps_as_objects(true)` pattern; reuse `js_value_for`).
|
||||
- `pub fn base32_decode_lenient(s: &str) -> Result<Vec<u8>, JsError>` returning the decoded bytes as a `Uint8Array` on the JS side (wasm-bindgen converts `Vec<u8>` into a `Uint8Array` copy — same convention as `attachment_decrypt`).
|
||||
- `pub fn guess_mime(filename: &str) -> String`.
|
||||
- Modified: `extension/src/wasm.d.ts` — adds the three matching declarations under the existing `declare module 'relicario-wasm'` block. Per DEV-C's boundary note, this file is hand-maintained; this commit must update both files together. Suggested placement: directly after `extract_image_secret`/`embed_image_secret` (line ~60), grouped under a `// Pure parsers (no session needed)` comment so the extension-side reader sees they require no `SessionHandle`.
|
||||
- Naming convention call-out: phase 8 keeps **snake_case** JS names (consistent with every existing export, e.g. `manifest_encrypt`, `extract_image_secret`). The snake_case → camelCase decision (DEV-B/DEV-C P3) is **explicitly deferred to a separate plan**; introducing camelCase only for the three new exports would create a worst-of-both-worlds inconsistency.
|
||||
- **Tests:** add `wasm-bindgen-test` cases (or extend the existing `session_tests` mod at `crates/relicario-wasm/src/lib.rs:522-591`) covering the three new exports — at minimum, a round-trip for `base32_decode_lenient` against a known input, an error case for `parse_month_year("not-a-date")`, and a `guess_mime("doc.pdf") == "application/pdf"` smoke. Confirm `cargo build -p relicario-wasm --target wasm32-unknown-unknown` is clean.
|
||||
- **Cross-boundary cite:** **after Phase 8 ships, Plan C can wire SW message handlers** for `parse_month_year`, `base32_decode_lenient`, and `guess_mime` (e.g. messages `parse_month_year`, `decode_totp_secret`, `guess_attachment_mime` in `extension/src/shared/messages.ts`, dispatched by `extension/src/service-worker/router/popup-only.ts`). This plan does **not** design those handlers; phase 8 only delivers the WASM seam Plan C consumes. Coordinate the wasm.d.ts update commit with Plan C so both crates' callers see the new surface in the same merge.
|
||||
- **Effort:** S.
|
||||
- **Depends on:** Phase 7.
|
||||
|
||||
## Risks and mitigations
|
||||
|
||||
- **Mechanical splits drift if a function calls a sibling that moved.** Mitigation: `cargo check -p relicario-cli` between every sub-step of phase 1 (i.e. between every file-extraction); explicit `pub(crate)` discipline so the compiler enforces visibility. The integration tests at `crates/relicario-cli/tests/*` are the regression budget — they exercise the binary surface, not internal modules, so a pure relocation cannot break them silently.
|
||||
- **`helpers::git_run` semantic change: switching from `.status()` (inherited stderr to TTY) to `.output()` (captured) means interactive flows lose live stderr streaming.** A user who runs `relicario sync` in a terminal sees git's progress today; with `git_run` they see only the captured chunk on failure. Mitigation options: (a) `git_run` could keep `inherit` semantics by detecting `stderr.is_terminal()` and switching strategy; (b) accept the trade — captured-and-printed-on-failure is uniformly better for the CI/test/scripted-tooling case which is the failure-mode that matters. Recommendation: option (b) for phase 2, with a follow-up TODO if the live-streaming loss is reported. Keep `git_command` available for the rare site that needs a manual `Command` (pipe/stdin/etc.) so neither contract has to be perfect.
|
||||
- **`Vault::after_manifest_change` adds a method to the session module; risk that callers forget to use the wrapper.** Mitigation: in phase 4, mark `save_manifest` as `pub(crate)` (or rename to `save_manifest_raw`) so all `commands/*` files are forced through `after_manifest_change`. The clap dispatcher calls only `cmd_*` functions, none of which need the raw method.
|
||||
- **`ParamsFile` migration is on-disk-format-sensitive.** A change in the `Serialize` derive's field order or a missed `Deserialize` field tolerance would break existing vaults. Mitigation: phase 5's test round-trip reads a `params.json` written by the current code (committed as a fixture *string literal* in the test, not a binary blob) and confirms the new code parses it identically. Field names match exactly (`format_version`, `kdf`, `aead`, `salt_path`); the existing `read_params` only reads `kdf`, so adding tolerance for the other fields is the natural step.
|
||||
- **Parser migration to core changes the public API surface of `relicario-core`.** Any in-flight work consuming the old CLI helpers must adapt. Mitigation: the grep step at the top of phase 7 confirms zero non-CLI consumers exist today; the CLI's `parse.rs` shim keeps callsites unchanged through phases 1–6, so this is a one-pass migration with no follow-up required from other plans. The Steam alphabet stays untouched (intentional non-RFC-4648 alphabet) with a neighbour comment.
|
||||
- **WASM export rename / addition could break the extension at the `wasm.d.ts` boundary.** Per DEV-C's boundary notes, `extension/src/wasm.d.ts` is hand-maintained; every change to `crates/relicario-wasm/src/lib.rs`'s `#[wasm_bindgen]` surface must be mirrored manually. Mitigation: phase 8 updates both files in the same commit; a future CI guard (DEV-C's WASM P2 — comparing wasm-pack–generated `.d.ts` against the hand-maintained one) is out of scope here but would close this hole permanently. The boundary notes also flag the BigInt typing care that `attachment_encrypt` already requires (DEV-B item 3 in DEV-C's boundary notes); the three new exports take only `&str` and return primitives, so they avoid that class of footgun.
|
||||
- **Cross-plan coupling.** Phase 8 lands a wasm.d.ts change; Plan C will land SW handlers consuming it. If the merge order interleaves — e.g. Plan C ships its handler stub before phase 8 lands the WASM export — the extension build breaks. Mitigation: phase 8 ships first; Plan C's SW-handler phase explicitly depends on phase 8's WASM exports (cite this seam in Plan C). The user's release-train coordination is the enforcement mechanism.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Plan A** (security/docs polish) and **Plan C** (extension restructure) entirely.
|
||||
- **All CLI P3 nits** that DEV-B enumerates: `let _ = entry;` pattern (`main.rs:1170, 1407, 1426, 1469, 1913, 2030`); `Lock` subcommand visibility; `Display` for `ItemType` (the `format!("{:?}", e.r#type)` site at `main.rs:1158`); `helpers::relicario_dir` adoption sweep; `gitea::GiteaClient` per-call construction; scripted-prompt test layer for `tests/edit_and_history.rs`; dead `blob_path` variable in `tests/attachments.rs:69-76`; the three-test-env-var macro consolidation; `cmd_recovery_qr_unwrap` empty-input check; `cmd_recovery_qr_generate` stdout/stderr split; the Task-12 `cmd_backup_export` cleanup. Each is a one-line edit appropriate for a follow-up sweep, not for this M-L plan.
|
||||
- **Server findings** (P2/P3 in DEV-B's relicario-server section): `generate-hook` `$PATH`, bootstrap-branch tightening, `verify-commit --from-stdin`, server test coverage gaps. These belong in a server-focused plan.
|
||||
- **WASM findings beyond the parser exports needed for P1.10**: DEV-B's WASM P2 list (`need_key`/`with(...).unwrap()` double-lookup, `Vec<u8>` getter clones, `wasm_*_recovery_qr` rename, `device.rs`/`session.rs` concurrency-primitive split). Not in this plan.
|
||||
- **The 8 "Open architectural decisions"** in the synthesis appendix.
|
||||
- **WASM JS-naming** (snake_case → camelCase) — defer to a separate plan, as called out in phase 8.
|
||||
- **In-flight uncommitted v0.5.x work** (`extension/src/vault/vault.ts`, `vault.css`, `glyphs.ts`, manifest version bumps, relay `queue.ts`/`server.ts`/`start.sh`). Treat as in-flight; this plan touches none of them.
|
||||
|
||||
## Done criteria
|
||||
|
||||
A reviewer can confirm Plan B has shipped by checking, in order:
|
||||
|
||||
- [ ] `crates/relicario-cli/src/main.rs` is ≤ 500 LOC and contains only the clap surface, the dispatch `match`, and the `mod` declarations + `test_*_override` shims.
|
||||
- [ ] The `crates/relicario-cli/src/commands/` directory contains the 17 files listed in the post-split tree, each owning exactly one top-level subcommand or a tightly-scoped helper.
|
||||
- [ ] `crates/relicario-cli/src/prompt.rs` and `crates/relicario-cli/src/parse.rs` exist, with the 6 prompt helpers and the 3 parser shims respectively.
|
||||
- [ ] `cargo test --workspace` passes (CLI integration tests, core unit tests, server tests, wasm `wasm-bindgen-test`s).
|
||||
- [ ] `cargo clippy --workspace` is silent.
|
||||
- [ ] `cargo build -p relicario-wasm --target wasm32-unknown-unknown` is clean.
|
||||
- [ ] The 16 `bail!("git X failed")` sites listed in P1.3 (and any others surfaced by grep) are now `git_run(repo, args, "<context>")?` one-liners. `grep -n 'bail!("git ' crates/relicario-cli/src/` returns zero matches.
|
||||
- [ ] The 7 `refresh_groups_cache` callsites all collapse to `vault.after_manifest_change(&manifest)?`. `grep -n 'refresh_groups_cache' crates/relicario-cli/src/` returns zero matches outside `session.rs`.
|
||||
- [ ] One canonical `ParamsFile` definition in `crates/relicario-cli/src/session.rs`. `grep -n 'struct ParamsFile' crates/relicario-cli/src/` returns one match.
|
||||
- [ ] A 50-item `relicario trash empty` produces exactly **one** new git commit (verified by `git log --oneline` in the test); a single-item `relicario purge` produces exactly one commit. Per-purge git invocations: 3 (rm + add manifest + commit), down from 3-per-item.
|
||||
- [ ] `MonthYear::parse`, `Totp::parse_secret`, `mime::guess_for_extension` exist in `relicario-core`. `crates/relicario-core/src/base32.rs` is `pub(crate)` and is the only RFC-4648 implementation in the crate (Steam alphabet at `item_types/totp.rs:13` stays, with a neighbour comment).
|
||||
- [ ] `crates/relicario-wasm/src/lib.rs` exports `parse_month_year`, `base32_decode_lenient`, `guess_mime`. `extension/src/wasm.d.ts` mirrors the three declarations.
|
||||
- [ ] All existing CLI integration tests at `crates/relicario-cli/tests/*` still pass without modification (regression budget held).
|
||||
@@ -0,0 +1,368 @@
|
||||
# Extension Restructure — Design
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Status:** Proposed
|
||||
**Source:** docs/superpowers/reviews/2026-05-04-architecture-review.md (P1.4, P1.5, P1.6, P1.9) + folded P2s from DEV-C's extension sections + the `relicario status` parity gap
|
||||
**Effort estimate:** L
|
||||
|
||||
## Summary
|
||||
|
||||
This is the largest of the three architecture-review followups — multi-day to multi-week — and it eliminates the two steepest learning cliffs in the extension. After this plan ships, a tinkerer who opens `extension/src/setup/setup.ts` no longer sees WASM imported directly (it isn't the pattern; it was the exception); a tinkerer who opens `extension/src/vault/vault.ts` sees ~200 LOC of routing and state instead of 1027 LOC of shell + sidebar + list + drawer + form-wrapper inlined together; the `shared/state.ts` bridge between popup and vault tab becomes type-checked end to end; and the duplicated service-worker router helpers consolidate into one home each. As a side effect, the extension closes its last CLI-parity gap (`relicario status` → vault-sidebar status indicator).
|
||||
|
||||
## Findings addressed
|
||||
|
||||
- **P1.4** (DEV-C; `extension/src/setup/setup.ts:28-37`, `:1118-1120`, whole 1220-LOC file) — setup wizard imports `relicario-wasm` directly and orchestrates `unlock` / `embed_image_secret` / `register_device` / `manifest_encrypt` itself, bypassing the SW abstraction every other surface uses; ~400 LOC of crypto orchestration duplicated.
|
||||
- **P1.5** (DEV-C; `extension/src/vault/vault.ts:1-1027`) — single 1027-LOC file owns shell + hash routing + sidebar + list + drawer + type-picker + form-wrapper + deep-link routing + teardown. Contains the `vault_locked` RPC intercept (lines 47-74) and the drawer-state leak (lines 495-536, 648-695).
|
||||
- **P1.6** (DEV-C; `extension/src/shared/state.ts:10-35`) — `StateHost` contract is fully `any`-typed; `host` singleton has no double-registration guard.
|
||||
- **P1.9** (DEV-C; `extension/src/service-worker/router/popup-only.ts:687-703`, `:~169`; `extension/src/service-worker/router/content-callable.ts:187-205`, `:~169`) — `loadDeviceSettings`, `loadBlacklist`, `saveBlacklist`, and `itemToManifestEntry` duplicated across both router files.
|
||||
- **P2 — inactivity-timer reset on content-callable messages** (DEV-C; `extension/src/service-worker/index.ts:76-78`) — active autofiller never opens popup, gets force-locked despite continuous use.
|
||||
- **P2 — `state.gitHost` clear on session expiry** (DEV-C; `extension/src/service-worker/index.ts:51-58`) — expiry callback clears manifest but leaves the cached git-host client.
|
||||
- **P2 — duplicated teardown helpers** (DEV-C; `extension/src/popup/components/settings.ts:56-65` and `settings-vault.ts:15-22`) — two near-identical cleanup paths in a regression class with known prior leaks.
|
||||
- **P2 — `Promise.all` without per-promise error handling** (DEV-C; `extension/src/popup/components/devices.ts:47-50`, `trash.ts:39-46`) — single rejected RPC fails the whole render.
|
||||
- **P2 — MutationObserver `scan()` not debounced** (DEV-C; `extension/src/content/detector.ts:96-103`) — SPA churn re-runs the full scan many times per second.
|
||||
- **CLI/extension parity gap — no equivalent to `relicario status`** (DEV-C parity table; PM kickoff) — extension surfaces nothing comparable to ahead/behind/lastSyncAt/pendingItems.
|
||||
|
||||
## Approach
|
||||
|
||||
Architectural shape: **types first, then extract, then split**. The extension already has a clean message-router/SW boundary; this plan finishes the job for the three surfaces that don't yet honor it (state.ts, setup.ts, vault.ts) and pulls duplicated SW helpers into one home.
|
||||
|
||||
### Post-split `extension/src/vault/`
|
||||
|
||||
```
|
||||
extension/src/vault/
|
||||
├── vault.html (unchanged)
|
||||
├── vault.css (unchanged)
|
||||
├── vault.ts (~200 LOC; routing + state only — owns
|
||||
│ hash parsing, RouterState, render() entry,
|
||||
│ imports the modules below)
|
||||
├── vault-shell.ts (DOM scaffolding, color-scheme apply,
|
||||
│ onMessage wiring, applyShellViewClass)
|
||||
├── vault-sidebar.ts (renderSidebarCategories, search input
|
||||
│ wiring with 50-100ms debounce, nav buttons,
|
||||
│ global keydown shortcuts)
|
||||
├── vault-list.ts (renderListPane, row rendering, type icons)
|
||||
├── vault-drawer.ts (openDrawer/closeDrawer, renderDrawer,
|
||||
│ drawer field grid, drawer event wiring;
|
||||
│ state.drawerOpen reset is owned here)
|
||||
├── vault-form-wrapper.ts (renderFormWrapped, sticky bar, header;
|
||||
│ __test__ export migrates with it)
|
||||
├── vault-status.ts (NEW — renders the get_vault_status indicator
|
||||
│ in the sidebar; phase 6)
|
||||
└── components/
|
||||
├── backup-panel.ts (unchanged)
|
||||
└── import-panel.ts (unchanged)
|
||||
```
|
||||
|
||||
Rationale: each module owns one concern that has its own teardown, its own DOM rectangle, and its own subset of `RouterState`. Adding a new pane view today is a 5-place edit (`teardownPaneComponents` lines 813-820 is the symptom DEV-C flagged); after the split, it is one new module + one entry in `vault.ts`'s render switch. The `vault_locked` RPC intercept at lines 47-74 lifts out entirely (see `shared/state.ts` below).
|
||||
|
||||
### Post-split `extension/src/service-worker/`
|
||||
|
||||
```
|
||||
extension/src/service-worker/
|
||||
├── index.ts (entry point — onMessage, initWasm,
|
||||
│ inactivity-timer wiring; phase 5 touches
|
||||
│ the content-callable timer-reset rule
|
||||
│ and the gitHost clear-on-expiry)
|
||||
├── session.ts (unchanged in scope; Plan A removes the
|
||||
│ try{free()} swallow at :26)
|
||||
├── session-timer.ts (unchanged; phase 5 documents the
|
||||
│ exclusion list inline)
|
||||
├── storage.ts (NEW — phase 2: loadDeviceSettings,
|
||||
│ loadBlacklist, saveBlacklist, plus the
|
||||
│ config + image-base64 + setup-state loaders
|
||||
│ if natural; both router files import here)
|
||||
├── vault.ts (gains: itemToManifestEntry (moved from
|
||||
│ both routers; phase 2), create_vault and
|
||||
│ attach_vault handlers (phase 3), and the
|
||||
│ get_vault_status handler (phase 6))
|
||||
├── git-host.ts (unchanged)
|
||||
├── github.ts / gitea.ts (unchanged)
|
||||
├── devices.ts (unchanged)
|
||||
└── router/
|
||||
├── index.ts (unchanged)
|
||||
├── popup-only.ts (imports from ../storage and ../vault;
|
||||
duplicated definitions deleted)
|
||||
└── content-callable.ts (imports from ../storage and ../vault;
|
||||
duplicated definitions deleted)
|
||||
```
|
||||
|
||||
Rationale: `service-worker/storage.ts` becomes the single source for `chrome.storage.local` reads/writes the SW does. `service-worker/vault.ts` already owns vault-tier WASM orchestration, so `itemToManifestEntry`, `create_vault`, `attach_vault`, and `get_vault_status` all belong there.
|
||||
|
||||
### `StateHost` interface contract (P1.6)
|
||||
|
||||
```ts
|
||||
// extension/src/shared/state.ts (post-rewrite)
|
||||
import type { Request, Response } from './messages';
|
||||
import type { PopupState, View } from '../popup/popup';
|
||||
|
||||
export interface StateHost {
|
||||
getState(): PopupState;
|
||||
setState(partial: Partial<PopupState>): void;
|
||||
navigate(view: View, extras?: Partial<PopupState>): void;
|
||||
sendMessage(request: Request): Promise<Response>;
|
||||
escapeHtml(s: string): string;
|
||||
popOutToTab(): void;
|
||||
isInTab(): boolean;
|
||||
openVaultTab(hash?: string): void;
|
||||
}
|
||||
|
||||
let host: StateHost | null = null;
|
||||
|
||||
export function registerHost(h: StateHost): void {
|
||||
if (host) throw new Error('state host already registered');
|
||||
host = h;
|
||||
}
|
||||
|
||||
/** Test-only — vitest beforeEach() calls this to break inter-test leakage. */
|
||||
export function __resetHostForTests(): void { host = null; }
|
||||
|
||||
export function getState(): PopupState {
|
||||
if (!host) throw new Error('No state host registered');
|
||||
return host.getState();
|
||||
}
|
||||
|
||||
export function setState<K extends keyof PopupState>(
|
||||
partial: Pick<PopupState, K> | Partial<PopupState>,
|
||||
): void {
|
||||
if (!host) throw new Error('No state host registered');
|
||||
host.setState(partial);
|
||||
}
|
||||
|
||||
// navigate / sendMessage / escapeHtml / popOutToTab / isInTab / openVaultTab
|
||||
// keep their generic-friendly signatures (View, Request, Response).
|
||||
//
|
||||
// vault_locked unification: shared/state.ts wraps sendMessage so a
|
||||
// `{ ok: false, error: 'vault_locked' }` response (for any request other
|
||||
// than is_unlocked / unlock) flips host state to locked + dispatches a
|
||||
// `session_expired`-equivalent event the popup also listens for.
|
||||
// Both popup.ts and vault.ts consume from this single channel — the
|
||||
// vault.ts:47-74 RPC intercept is removed in phase 4.
|
||||
```
|
||||
|
||||
Note `View` and `PopupState` are currently defined in `extension/src/popup/popup.ts`. To avoid a popup→shared circular import, they migrate to `extension/src/shared/types.ts` (or `extension/src/shared/popup-state.ts`) before `state.ts` re-imports them. This migration is part of phase 1.
|
||||
|
||||
### Setup wizard step-registry shape (P1.4)
|
||||
|
||||
```ts
|
||||
// extension/src/setup/setup.ts (post-rewrite)
|
||||
interface StepContext {
|
||||
state: WizardState;
|
||||
rerender: () => void;
|
||||
goto: (id: StepId) => void;
|
||||
}
|
||||
|
||||
interface SetupStep {
|
||||
id: StepId;
|
||||
/** Pure render — returns innerHTML for #setup-step-host. */
|
||||
render: (ctx: StepContext) => string;
|
||||
/** Wire DOM events; return a teardown the wizard runs on step change. */
|
||||
attach: (root: HTMLElement, ctx: StepContext) => () => void;
|
||||
}
|
||||
|
||||
type StepId = 'mode' | 'host' | 'connection' | 'vault' | 'device' | 'done';
|
||||
|
||||
const STEPS: ReadonlyArray<SetupStep> = [
|
||||
modeStep, hostStep, connectionStep, vaultStep, deviceStep, doneStep,
|
||||
];
|
||||
|
||||
/** Cleared on `beforeunload` and on `goto('mode')`. */
|
||||
function clearWizardState(): void {
|
||||
// Best-effort wipe: zero-fill Uint8Arrays before drop where reachable;
|
||||
// null out passphrase + token strings (JS strings are GC-only — see Risks).
|
||||
if (state.carrierImageBytes) state.carrierImageBytes.fill(0);
|
||||
if (state.referenceImageBytes) state.referenceImageBytes.fill(0);
|
||||
if (state.referenceImageBytesAttach) state.referenceImageBytesAttach.fill(0);
|
||||
// Reset every field of `state` to its initial value.
|
||||
// NOTE: setup no longer holds a SessionHandle (the SW does); the
|
||||
// phase 1 sweep deletes `verifiedHandle` from WizardState entirely.
|
||||
}
|
||||
```
|
||||
|
||||
`setup.ts` no longer imports `relicario-wasm` and no longer touches `wasm.lock` / `.free()`. The two new SW handlers do that work (see Plan A coordination below).
|
||||
|
||||
The 1220 LOC drops to ~500: the ~400 LOC of crypto orchestration (image-secret extract / embed, KDF gating, manifest_encrypt, attachment_encrypt) moves to the SW; the remaining UI logic compresses by ~300 LOC because the step-registry pattern collapses the six `renderStepN` / `attachStepN` pairs into six `SetupStep` objects.
|
||||
|
||||
### New SW message handlers
|
||||
|
||||
Added to `extension/src/shared/messages.ts`:
|
||||
|
||||
```ts
|
||||
| { type: 'create_vault'; config: VaultConfig; passphrase: string;
|
||||
carrierImageBytes: ArrayBuffer; deviceName: string }
|
||||
| { type: 'attach_vault'; config: VaultConfig; passphrase: string;
|
||||
referenceImageBytes: ArrayBuffer; deviceName: string }
|
||||
| { type: 'get_vault_status' }
|
||||
```
|
||||
|
||||
Both `create_vault` and `attach_vault` are added to `POPUP_ONLY_TYPES`. `get_vault_status` joins the same set. Response shapes:
|
||||
|
||||
```ts
|
||||
export interface CreateVaultResponse extends Extract<Response, { ok: true }> {
|
||||
data: { referenceImageBytes: Uint8Array; deviceName: string;
|
||||
recoveryQrAvailable: true };
|
||||
}
|
||||
export interface AttachVaultResponse extends Extract<Response, { ok: true }> {
|
||||
data: { deviceName: string };
|
||||
}
|
||||
export interface GetVaultStatusResponse extends Extract<Response, { ok: true }> {
|
||||
data: { ahead: number; behind: number; lastSyncAt: number | null;
|
||||
pendingItems: number };
|
||||
}
|
||||
```
|
||||
|
||||
The SW handlers live in `service-worker/vault.ts`. `create_vault` and `attach_vault` hold their own internal session reference for the duration of the operation — they do not depend on the user-facing inactivity timer (see Risks).
|
||||
|
||||
## Implementation phases
|
||||
|
||||
Each phase keeps the existing vitest test suite green throughout. Regression budget per phase: **zero** test failures introduced; new tests added per phase (synthetic fixtures only, no binary blobs — `make_test_jpeg` style equivalents on the JS side).
|
||||
|
||||
### Phase 1 — `StateHost` typing + `__resetHostForTests` (P1.6)
|
||||
|
||||
- **Goal:** Make `extension/src/shared/state.ts` type-checked end to end so phases 3 and 4 can refactor against a real contract.
|
||||
- **Changes:**
|
||||
- Move `View` and `PopupState` from `extension/src/popup/popup.ts` to `extension/src/shared/types.ts` (or new `extension/src/shared/popup-state.ts`).
|
||||
- Rewrite `extension/src/shared/state.ts` to the snippet in **Approach**: typed `StateHost`, generic `getState`/`setState`, double-registration throw, `__resetHostForTests` export. No `any` in the public surface.
|
||||
- Sweep all callers of `getState()` / `setState()` / `navigate()`. Existing `as any` casts surface as TS errors and get fixed (typed access where the field is known; an explicit narrowing where it isn't).
|
||||
- The `vault_locked` channel collapse is **not** in this phase — the wrapper around `sendMessage` lands here as a no-op signature change; its body (the RPC intercept) lifts in phase 4.
|
||||
- **Tests:**
|
||||
- New `extension/src/shared/__tests__/state.test.ts` covering: register-then-getState round-trip; double-register throws; `__resetHostForTests` clears the singleton; `getState()` without a registered host throws.
|
||||
- Adjust any existing test that accidentally relied on a leaked host (none expected; the existing suites already register-then-tear-down per-test).
|
||||
- **Effort:** S-M
|
||||
- **Depends on:** none
|
||||
|
||||
### Phase 2 — Extract `service-worker/storage.ts` + move `itemToManifestEntry` (P1.9)
|
||||
|
||||
- **Goal:** Eliminate the duplicated SW helpers so blacklist mutations and manifest-projection refactors happen in one place.
|
||||
- **Changes:**
|
||||
- Create `extension/src/service-worker/storage.ts` exporting `loadDeviceSettings`, `saveDeviceSettings`, `loadBlacklist`, `saveBlacklist`. Migrate the bodies from `extension/src/service-worker/router/popup-only.ts:687-703` (and `saveDeviceSettings` from the same file) and delete the `loadDeviceSettings` / `loadBlacklist` / `saveBlacklist` definitions in `extension/src/service-worker/router/content-callable.ts:187-205`.
|
||||
- Move `itemToManifestEntry` from both router files (`popup-only.ts:707` and `content-callable.ts:169`) into `extension/src/service-worker/vault.ts` as a named export. Both routers import it from there.
|
||||
- Optionally also fold `loadConfig` / `loadImageBase64` / `loadSetupState` into `storage.ts` since they're chrome.storage.local readers; keep the boundary clean.
|
||||
- **Tests:**
|
||||
- New `extension/src/service-worker/__tests__/storage.test.ts` covering load/save round-trips for each helper, default-value fallback when the key is absent.
|
||||
- The existing `extension/src/service-worker/router/__tests__/router.test.ts` keeps passing; the dispatch behavior is unchanged.
|
||||
- **Effort:** S
|
||||
- **Depends on:** none (independent of phase 1; can ship parallel)
|
||||
|
||||
### Phase 3 — Setup wizard SW migration + step registry (P1.4)
|
||||
|
||||
- **Goal:** Setup wizard becomes UI-only. SW owns `create_vault` and `attach_vault` end to end. Wizard restructures to a step-registry pattern. Sensitive material clears on abandon.
|
||||
- **Changes:**
|
||||
- Add `create_vault` and `attach_vault` types to `extension/src/shared/messages.ts` (request union, response interfaces, capability set).
|
||||
- Implement handlers in `extension/src/service-worker/vault.ts`. Each handler:
|
||||
1. Computes salt + params, calls `unlock` (create) or verifies (attach), calls `embed_image_secret` / `extract_image_secret`, calls `register_device`, calls `manifest_encrypt` for the empty manifest, writes the resulting bytes to the configured remote via the existing `git-host` abstraction.
|
||||
2. Holds its own `SessionHandle` for the duration. On success, transitions the SW into the unlocked state (replaces the popup-driven `unlock` path's outcome); on failure, calls `wasm.lock(handle)` then `.free()` (see Plan A coordination).
|
||||
3. Returns the reference image bytes (`create_vault`) or just the device name (`attach_vault`) so the wizard's "Done" step can offer a download.
|
||||
- Rewrite `extension/src/setup/setup.ts`:
|
||||
- Delete the WASM dynamic-import block at lines 28-37; delete the `loadWasm()` helper; delete the `wasm` module variable; delete `verifiedHandle` from `WizardState`.
|
||||
- Convert each of the six `renderStepN` / `attachStepN` pairs into a `SetupStep` object (`modeStep`, `hostStep`, `connectionStep`, `vaultStep`, `deviceStep`, `doneStep`) per the step-registry snippet in **Approach**. The wizard's render loop becomes `STEPS[state.step].render(ctx)` + `STEPS[state.step].attach(root, ctx)`.
|
||||
- Replace direct WASM orchestration in the vault step with `sendMessage({ type: 'create_vault', ... })` / `sendMessage({ type: 'attach_vault', ... })`.
|
||||
- Add `clearWizardState()` per the snippet; bind to `window.addEventListener('beforeunload', clearWizardState)` and call from the `goto('mode')` path.
|
||||
- Update `extension/src/wasm.d.ts` only if the new SW handlers need a WASM entry point that isn't already declared (verify by reading `extension/src/service-worker/vault.ts` — they likely don't, since `unlock`/`embed_image_secret`/`register_device`/`manifest_encrypt` are already declared; the SW just orchestrates them). If no new WASM entry, this file is **not touched** by Plan C.
|
||||
- The `recovery_qr_generated_at` direct chrome.storage.local write at `setup.ts:1056-1062` is **out of scope** per the kickoff (defer to a P3 cleanup) — it stays as-is in this phase.
|
||||
- **Tests:**
|
||||
- Update `extension/src/setup/__tests__/setup.test.ts` to assert on the step registry shape (each `SetupStep.id`, `render` returns non-empty HTML, `attach` returns a callable teardown).
|
||||
- New SW-side test in `extension/src/service-worker/__tests__/vault.test.ts` (or extend an existing one) covering `create_vault` happy path with a stubbed `git-host` and the WASM stub from `__stubs__/relicario_wasm.stub.ts` (round out the stub for `embed_image_secret`, `register_device`, `manifest_encrypt` if they aren't there yet — DEV-C P2 noted only 7 of ~25 are stubbed).
|
||||
- New test for `clearWizardState`: simulate `beforeunload`, assert `Uint8Array` contents are zero-filled.
|
||||
- **Effort:** L
|
||||
- **Depends on:** Phase 1 (the wizard's UI uses `getState`/`setState` against a typed `StateHost`)
|
||||
|
||||
### Phase 4 — Split `vault.ts` + lift `vault_locked` channel (P1.5)
|
||||
|
||||
- **Goal:** `extension/src/vault/vault.ts` shrinks to ~200 LOC of routing + state. Each pane concern lives in its own module. The `vault_locked` RPC intercept disappears from vault.ts and runs in `shared/state.ts` instead.
|
||||
- **Changes:**
|
||||
- Create the five new files (`vault-shell.ts`, `vault-sidebar.ts`, `vault-list.ts`, `vault-drawer.ts`, `vault-form-wrapper.ts`) per the directory tree in **Approach**. Migrate the corresponding code blocks from the existing `vault.ts` into them. Each module exports a `render*` function plus, where stateful, an explicit `teardown()`.
|
||||
- In `vault.ts`, retain only: `RouterState` declaration, hash parsing (`parseHash`, `setHash`), `loadManifest`, the `render()` entry point, the `renderPane()` switch, and the imports that wire the modules together.
|
||||
- In `vault-drawer.ts`: include an `ensureDrawerClosedForRoute(route)` helper that the `renderPane` switch calls before any non-list view. This implements the P2 fix for `vault.ts:495-536` (drawer state no longer leaks across navigation).
|
||||
- In `vault-sidebar.ts`: wrap the search input handler in a 50-100ms debounce (DEV-C P2 — `vault.ts:648-695`).
|
||||
- Lift the `vault_locked` RPC intercept (`vault.ts:47-74`) into the `sendMessage` wrapper in `extension/src/shared/state.ts` (the wrapper signature landed in phase 1; phase 4 fills the body). Both popup and vault now consume the same `session_expired`-equivalent flow. **Migration discipline:** keep both signals firing for one merge cycle (the SW continues to dispatch `session_expired` and the wrapper still fires the intercept) until both surfaces have been verified as consuming from `shared/state.ts`; then collapse.
|
||||
- **Tests:**
|
||||
- Existing `extension/src/vault/__tests__/form-wrapper.test.ts` and `sidebar-glyphs.test.ts` continue to pass (the symbols they import move from `vault.ts` to `vault-form-wrapper.ts` / `vault-sidebar.ts`; update import paths).
|
||||
- New `extension/src/vault/__tests__/drawer-state.test.ts` covering: drawer auto-closes when navigating from list to trash/devices/settings.
|
||||
- New `extension/src/shared/__tests__/state-vault-locked.test.ts` covering: a `{ ok: false, error: 'vault_locked' }` response (for a request other than `is_unlocked`/`unlock`) flips host state to locked.
|
||||
- **Effort:** M
|
||||
- **Depends on:** Phase 1 (uses the typed `StateHost` surface and the `sendMessage` wrapper)
|
||||
|
||||
### Phase 5 — Extension P2 cluster
|
||||
|
||||
- **Goal:** Sweep five small extension P2s that share the same "small fix, real correctness win" shape.
|
||||
- **Changes:**
|
||||
- **Inactivity timer reset on content-callable messages** (`extension/src/service-worker/index.ts:76-78`): invert the current condition. Reset on **all** messages except a small documented exclusion set (`get_autofill_candidates` is the only known read-only content call). Define `READ_ONLY_CONTENT_CALLABLE` in `service-worker/session-timer.ts` with a doc comment listing each excluded type and the rationale; `index.ts` consults that set.
|
||||
- **`state.gitHost` clear on session expiry** (`extension/src/service-worker/index.ts:51-58`): in the `sessionTimer.onExpired` callback, also set `state.gitHost = null`. The initializer rebuilds it on demand.
|
||||
- **Teardown helper extraction** (`extension/src/popup/components/settings.ts:56-65` and `settings-vault.ts:15-22`): extract `teardownSettingsCommon()` exported from `settings.ts` (or a new `settings-shared.ts`); both `settings.ts:teardownSettings` and `settings-vault.ts:teardown` call it. Single source for the closeGeneratorPanel + activeKeyHandler removal pattern.
|
||||
- **`Promise.allSettled` in devices/trash** (`extension/src/popup/components/devices.ts:47-50`, `trash.ts:39-46`): swap `Promise.all` for `Promise.allSettled`; render each settled response defensively (`.status === 'fulfilled' && r.value.ok`); fall back to "couldn't load" copy per failed slot.
|
||||
- **MutationObserver debounce** (`extension/src/content/detector.ts:96-103`): wrap the existing `() => scan()` callback in a 200ms trailing-edge debounce (or `requestIdleCallback` if available; `setTimeout(..., 200)` fallback). Reset on every observer fire.
|
||||
- **Tests:**
|
||||
- Existing `extension/src/service-worker/__tests__/session-timer.test.ts` extended with a "popup-only message resets, content-callable message does not reset (except listed exclusions)" case.
|
||||
- Existing `extension/src/popup/components/__tests__/devices.test.ts` and `trash.test.ts` extended with a "one RPC fails, the other still renders" case.
|
||||
- Existing `extension/src/popup/components/__tests__/settings.test.ts` and `settings-vault.test.ts` extended to confirm both call paths invoke `teardownSettingsCommon`.
|
||||
- **Effort:** M
|
||||
- **Depends on:** none (all five are independent of phases 1-4)
|
||||
|
||||
### Phase 6 — `get_vault_status` SW message + vault-sidebar status indicator
|
||||
|
||||
- **Goal:** Close the last CLI/extension parity gap (`relicario status` ↔ extension status indicator).
|
||||
- **Changes:**
|
||||
- Add `{ type: 'get_vault_status' }` to `extension/src/shared/messages.ts` and to `POPUP_ONLY_TYPES`. Add `GetVaultStatusResponse` per the **Approach** snippet.
|
||||
- Implement the handler in `extension/src/service-worker/vault.ts`. It returns `{ ahead, behind, lastSyncAt, pendingItems }` from cached state on `state.gitHost` (no actual sync). A "last sync" timestamp is recorded in `service-worker/index.ts` (or `state.gitHost`) on each successful `sync` handler return.
|
||||
- Create `extension/src/vault/vault-status.ts` rendering a small indicator in the sidebar footer: glyph + "in sync" / "N ahead" / "N pending" / "last sync 2m ago". Polls on sidebar mount and on a manual refresh button (NOT every render — see Risks).
|
||||
- **Tests:**
|
||||
- New `extension/src/service-worker/__tests__/vault-status.test.ts` covering the four state combinations and the no-sync invariant (handler does not touch the network).
|
||||
- New `extension/src/vault/__tests__/status-indicator.test.ts` for the renderer.
|
||||
- **Effort:** S-M
|
||||
- **Depends on:** Phase 4 (the indicator lives inside the new `vault-sidebar.ts` boundary)
|
||||
|
||||
### Future / deferred (Plan B coordination)
|
||||
|
||||
Plan B (CLI restructure) migrates `parse_month_year`, `base32_decode_lenient`, and `guess_mime` from the CLI into `relicario-core`, then re-exports them through `relicario-wasm`. Once those WASM exports land, the extension can consume them via new SW message handlers (e.g. `parse_month_year`, `decode_totp_secret`, `guess_mime_for_filename`) — this is a natural follow-up and explicitly **deferred to a future plan**. The seam to consume them is `extension/src/service-worker/vault.ts` (or a new `service-worker/parse.ts`) plus a new entry in `extension/src/wasm.d.ts`. Plan C does **not** design those handlers in detail.
|
||||
|
||||
## Risks and mitigations
|
||||
|
||||
- **State.ts typing changes ripple.** Every consumer of `getState`/`setState` becomes type-checked; existing `as any` casts will surface as TS errors. *Mitigation:* phase 1 includes a sweep + targeted TS error fix as part of the phase, not as a follow-up. Run `tsc --noEmit` per file class to triage; expect ~15-30 errors clustered in `popup/components/*.ts` and `vault/*.ts`.
|
||||
- **Setup-via-SW migration changes the crypto state machine.** Today setup orchestrates WASM directly; after phase 3, the SW owns vault creation. If the SW's user-facing inactivity timer fires mid-creation, the user could lose progress. *Mitigation:* design `create_vault` / `attach_vault` to be transactional from the SW's perspective — they hold their own internal session reference for the duration of the operation and do not consult or reset the user-facing inactivity timer until they return successfully. Document this contract in the handler header comments.
|
||||
- **`vault.ts` split + `vault_locked` channel unification.** The popup currently uses `session_expired` event; vault tab uses RPC intercept. Unifying onto one channel means popup behavior must continue to work after phase 4. *Mitigation:* keep both signals firing during phase 4 (the SW continues to dispatch `session_expired`; the new wrapper in `shared/state.ts` also fires the intercept); collapse only after both surfaces are verified to consume from `shared/state.ts` in the same merge cycle. Add a regression test asserting the popup's lock screen renders on `session_expired` and the vault tab's lock screen renders on the SW response intercept.
|
||||
- **`.free()` callsite policy.** Plan A (security/docs polish) handles the Rust-side `impl Drop for SessionHandle` and removes the `try { current.free() }` swallow at `extension/src/service-worker/session.ts:26`. Plan C does **not** redo that work, but wherever this refactor *moves* a `.free()` callsite — most notably during the phase 3 setup-to-SW migration where `setup.ts`'s `verifiedHandle` retires and the new `create_vault` / `attach_vault` handlers acquire their own handles — the new location must call `wasm.lock(handle)` first regardless of whether Plan A's Rust-side `impl Drop` lands. Cite Plan A as the source of the policy.
|
||||
- **WASM boundary coordination.** Plan B (CLI restructure) will touch `extension/src/wasm.d.ts` for the new parser exports (`parse_month_year`, `base32_decode_lenient`, `guess_mime`) once they land in `relicario-wasm`. Plan C should **not** touch `extension/src/wasm.d.ts` unless `create_vault` / `attach_vault` need WASM entry points that aren't already declared (verify by reading `service-worker/vault.ts`; the SW already orchestrates `unlock`/`embed_image_secret`/`register_device`/`manifest_encrypt`, so likely no new entries needed). If both plans must touch `wasm.d.ts`, sequence Plan B's edits first and rebase Plan C on top.
|
||||
- **`clearWizardState()` semantics.** Clearing on `beforeunload` is best-effort in browsers (the event can be skipped if the tab crashes or is killed). JS strings (passphrase, API token) are also GC-only — there is no `Zeroize` for them. *Mitigation:* explicit zero-fill of `Uint8Array` fields where possible (carrier image bytes, reference image bytes); document the best-effort contract in the function header comment; do not over-promise in user docs. The same caveat already applies to existing strings in `WizardState` today, so this is a maintenance of the existing contract, not a regression.
|
||||
- **`get_vault_status` design.** Needs to call into the git-host abstraction without triggering an actual sync. *Mitigation:* cache the last-sync state in `state.gitHost` (add `lastSyncAt: number | null`, `ahead: number`, `behind: number` fields populated by the existing `sync` handler) and have `get_vault_status` read those cached values; the sidebar indicator polls on mount + on a manual refresh button rather than on every render. Any UI element that wants live status calls `sync` explicitly.
|
||||
- **Phase ordering risk.** Phase 1 is the blocker — phases 3 and 4 both depend on the typed `StateHost`. If phase 1 takes longer than estimated, run phase 2 (independent) and phase 5 (independent) in parallel to avoid total stall.
|
||||
|
||||
## Out of scope
|
||||
|
||||
Plan C does NOT touch:
|
||||
|
||||
- Anything in **Plan A** (security/docs polish): Rust `impl Drop for SessionHandle`, the `service-worker/session.ts:26` swallow removal, `.free()` callsite audit, `recovery_qr.rs` documentation, server hardening, env-var audit.
|
||||
- Anything in **Plan B** (CLI restructure): `cli/main.rs` split, git-shell error UX helper, `parse_month_year`/`base32_decode_lenient`/`guess_mime` migration to core (Plan C only consumes them, deferred to a future phase).
|
||||
- Extension P3s: form-header `isInTab()` redundancy, popup.ts `isInTab()` heuristic, item-form.ts `renderComingSoon` dead code, `types/login.ts` size, `vault.ts:18-26` backup-panel comment, capture/detector/fill username-finder dedup, capture submit-button hook scope, setup.ts passphrase-score `-1` sentinel, `setup.ts:1056-1062` chrome.storage bypass, `setup.ts:1-7` "5-step" header comment, glyphs.ts partial adoption, `types.ts` `TotpKind` flat-union refactor, `totp-tools.ts:39-46` swallowed rejections, generator-panel cleanup idempotence guard, `item-list.ts` popover listener reuse path, popup `popup.ts:178-181` unconditional teardowns.
|
||||
- Other CLI/extension parity items: per-attachment `delete_attachment` SW message (P3), `list --tag` filter doc note (P3) — only `get_vault_status` is in scope.
|
||||
- Cross-cutting items not explicitly listed: `chrome.storage.local` direct reads outside the setup migration (e.g. `settings-security.ts:112-113`), `bun test` runner doc note, manifest version sync.
|
||||
- The full P2/P3 tail outside the items folded above.
|
||||
- The 8 "Open architectural decisions" from the synthesis appendix.
|
||||
- WASM JS-naming snake_case → camelCase decision (defer to a separate plan).
|
||||
- Anything touching the in-flight uncommitted v0.5.x work (vault.ts +151/-99, vault.css +238/-99, manifest version, glyphs additions). Plan C executes against committed `main` post-061facd.
|
||||
|
||||
## Done criteria
|
||||
|
||||
A reviewer confirms the plan shipped by checking each item:
|
||||
|
||||
- [ ] `extension/src/shared/state.ts` `StateHost` interface defines every field; no `any` in the public surface.
|
||||
- [ ] `getState` returns `PopupState`; `setState` is generic over `keyof PopupState`.
|
||||
- [ ] `registerHost` throws on second registration; `__resetHostForTests` is exported and used in vitest setup.
|
||||
- [ ] `extension/src/service-worker/router/popup-only.ts` and `content-callable.ts` no longer contain `loadDeviceSettings` / `loadBlacklist` / `saveBlacklist` definitions (only imports from `service-worker/storage.ts`).
|
||||
- [ ] `itemToManifestEntry` defined once in `extension/src/service-worker/vault.ts`, imported by both router files.
|
||||
- [ ] `extension/src/setup/setup.ts` LOC ≤ ~500.
|
||||
- [ ] `extension/src/setup/setup.ts` does not import `relicario-wasm` (no dynamic import, no `loadWasm`, no module-level `wasm` binding).
|
||||
- [ ] SW handles `create_vault` and `attach_vault` messages (entries in `messages.ts`, `POPUP_ONLY_TYPES`, and `service-worker/vault.ts`).
|
||||
- [ ] `clearWizardState()` exists, is bound to `beforeunload`, and is called from the `goto('mode')` path; sensitive `Uint8Array` fields are zero-filled.
|
||||
- [ ] `extension/src/vault/vault.ts` is split into `vault.ts` + `vault-shell.ts` + `vault-sidebar.ts` + `vault-list.ts` + `vault-drawer.ts` + `vault-form-wrapper.ts`; `vault.ts` is ~200 LOC of routing + state only.
|
||||
- [ ] Single `vault_locked` channel: the RPC intercept is in `extension/src/shared/state.ts`'s `sendMessage` wrapper; `vault.ts` no longer contains the intercept block at the old lines 47-74.
|
||||
- [ ] Drawer auto-closes on navigation to non-list views (`state.drawerOpen = false` reset in `renderPane` / `ensureDrawerClosedForRoute`).
|
||||
- [ ] Sidebar search input is debounced (50-100ms).
|
||||
- [ ] Inactivity timer resets on **all** messages except a documented exclusion set (currently `get_autofill_candidates`); the exclusion set is defined and commented in `service-worker/session-timer.ts`.
|
||||
- [ ] `state.gitHost = null` runs alongside `state.manifest = null` in the `sessionTimer.onExpired` callback.
|
||||
- [ ] One `teardownSettingsCommon` helper exists; both `settings.ts` and `settings-vault.ts` call it.
|
||||
- [ ] `devices.ts` and `trash.ts` use `Promise.allSettled` and render each settled response defensively.
|
||||
- [ ] `extension/src/content/detector.ts` MutationObserver `scan()` is debounced (200ms or `requestIdleCallback`).
|
||||
- [ ] `get_vault_status` SW message and response interface exist; vault sidebar renders an indicator on mount and on manual refresh.
|
||||
- [ ] All existing vitest tests under `extension/src/**/__tests__/` pass; new tests added per phase pass.
|
||||
- [ ] No `extension/src/wasm.d.ts` change introduced by Plan C unless coordinated with Plan B (verify the file's diff is empty post-merge, or coordinated explicitly with Plan B's parser exports).
|
||||
- [ ] Every `.free()` callsite moved by this plan is preceded by `wasm.lock(handle)` (per Plan A's policy, regardless of whether Plan A's Rust `impl Drop` has landed).
|
||||
135
docs/superpowers/specs/2026-05-04-security-polish-design.md
Normal file
135
docs/superpowers/specs/2026-05-04-security-polish-design.md
Normal file
@@ -0,0 +1,135 @@
|
||||
# Security & Docs Polish — Design
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Status:** Proposed
|
||||
**Source:** `docs/superpowers/reviews/2026-05-04-architecture-review.md` (P1.1, P1.7, P1.8)
|
||||
**Effort estimate:** S (whole-PR; phase totals below)
|
||||
|
||||
## Summary
|
||||
|
||||
This is the one-day security and documentation PR that ships first in the v0.5.x architecture-followup train, independent of Plan B (CLI restructure) and Plan C (extension restructure). It closes the single defense-in-depth crypto gap the review flagged (`SessionHandle` has no `impl Drop`, so wasm-bindgen's `.free()` is a cleanup no-op while the master key sits in WASM linear memory), removes the JS-side error swallow that was masking that fact, brings the one undocumented security-critical core file (`recovery_qr.rs`) up to the documentation density of `crypto.rs` / `imgsecret.rs` / `backup.rs` / `tar_safe.rs`, and confirms the relay test/launcher polish items. Together these are mechanical, low-risk changes that fix the only finding in the review where "what the code looks like it does" diverges dangerously from "what it actually does" — which is exactly the wall a tinkerer learning Rust would hit hardest.
|
||||
|
||||
## Findings addressed
|
||||
|
||||
- **P1.1 — `SessionHandle` has no `impl Drop`; `.free()` is a cleanup no-op** — DEV-B (Rust headline) + DEV-C (JS partner finding). Files: `crates/relicario-wasm/src/lib.rs:15-23`, `crates/relicario-wasm/src/session.rs:1-58`, `extension/src/service-worker/session.ts:26`.
|
||||
- **Partner JS swallow** — DEV-C P2 in service-worker. File: `extension/src/service-worker/session.ts:26` (the `try { current.free(); } catch { /* already freed */ }` block).
|
||||
- **P1.7 — `recovery_qr.rs` is undocumented relative to the rest of core** — DEV-A. File: `crates/relicario-core/src/recovery_qr.rs:1-130`.
|
||||
- **P1.8 — `tools/relay/queue.test.ts` assertion update** — DEV-C. File: `tools/relay/queue.test.ts:54`. Confirmed during planning: **already fixed in `061facd`** — line 54 now reads `assert.ok(isRole("dev-c"));` and the negative case `assert.ok(!isRole("dev-d"));` is on line 55. No code work remains; the plan tracks this as a verification step.
|
||||
- **Launcher follow-up — `tools/relay/start.sh` still references three roles** — DEV-C P2. File: `tools/relay/start.sh:30-86`. Confirmed during planning: **not yet fixed.** Both `launch_tmux` and `launch_kitty` open only PM, Dev-A, Dev-B (no Dev-C); the manual-mode banner still says "Open 3 new terminals"; the post-launch summary lines (`:61, :81`) print "3 windows (PM, Dev-A, Dev-B)"; no `*-dev-c-prompt.md` is discovered or used. This phase is real.
|
||||
|
||||
## Approach
|
||||
|
||||
The PR is mechanical and uniform across four phases:
|
||||
|
||||
- **Adds** one `impl Drop for SessionHandle` block in `crates/relicario-wasm/src/lib.rs`, one Rust test that exercises construct → drop → registry-empty, one module-level `//!` doc-block in `recovery_qr.rs`, one ASCII layout diagram next to the magic constants there, four per-function doc-comments on the public API there, and one `DEV_C_PROMPT` discovery line + a fourth window in each launcher mode of `start.sh`.
|
||||
- **Removes** the `try { current.free(); } catch { /* already freed */ }` swallow at `extension/src/service-worker/session.ts:26`.
|
||||
- **Verifies** every `.free()` callsite under `extension/src/` (the audit deliverable for P1.1's JS side; today the audit itself is small — only one match — but the deliverable is the recorded grep + a check that every code path that holds a `SessionHandle` calls `wasm.lock(handle)` before `free()`).
|
||||
- **Confirms in passing** that `tools/relay/queue.test.ts:54` already matches the new role union (it does — committed in `061facd`).
|
||||
|
||||
No public API changes on the Rust side beyond the `Drop` impl (which is observably equivalent to "calling `lock(handle)` was previously the only way to clean up"). No JS public API changes. No file moves. No new dependencies (`wasm-bindgen-test` is already in `[dev-dependencies]` for the wasm crate).
|
||||
|
||||
## Implementation phases
|
||||
|
||||
### Phase 1 — Rust-side `impl Drop for SessionHandle` + test
|
||||
|
||||
- **Goal:** make wasm-bindgen's auto-generated `.free()` actually clear the master key from WASM linear memory, regardless of whether JS also called `lock(handle)`.
|
||||
- **Changes:**
|
||||
- `crates/relicario-wasm/src/lib.rs` — add `impl Drop for SessionHandle { fn drop(&mut self) { let _ = session::remove(self.0); } }` immediately after the existing `#[wasm_bindgen] impl SessionHandle { ... value() ... }` block (around line 23). Update the doc-comment on `SessionHandle` (line 15) to document the contract: "Dropping (or `.free()` from JS) removes the entry from the session registry and zeroizes the wrapped key/image_secret. `lock(handle)` remains available as the explicit early-cleanup path; `Drop` is the safety net."
|
||||
- `crates/relicario-wasm/src/session.rs` — no functional change required, but add a one-line module-level note above `pub fn remove(...)` explicitly stating that `Drop for SessionHandle` is the second caller of this function alongside `lock()`, so that a future reader removing `lock()` doesn't accidentally orphan the cleanup path.
|
||||
- **Tests:**
|
||||
- Add a `#[wasm_bindgen_test]` (the `wasm-bindgen-test` crate is already in `[dev-dependencies]`, line 25 of `Cargo.toml`) under `crates/relicario-wasm/tests/session_drop.rs`. The test constructs a `SessionHandle` (via the public `unlock` path with synthetic JPEG + tiny `KdfParams` for fast key derivation, mirroring the existing native `session_tests::manifest_round_trip_via_handle` shape), records the underlying handle id via `handle.value()`, drops the handle, then asserts `session::with(id, |_| ()).is_none()`. The `session::with` symbol must be re-exported from `tests/` scope; if it isn't, expose `pub fn with_for_tests(handle: u32) -> bool` on the `session` module guarded by `#[cfg(test)]` so the test does not need to reach into thread-locals.
|
||||
- As a fallback / belt-and-suspenders, add a parallel native `#[test]` under the existing `mod session_tests` in `lib.rs` that constructs a `SessionHandle(session::insert(...))`, drops it explicitly with `drop(handle)`, then asserts `session::with(h, |_| ()).is_none()`. Native tests run on every `cargo test`; the wasm-bindgen-test runs only when someone invokes `wasm-pack test`, so the native variant is the one that catches regressions in CI.
|
||||
- **Effort:** S
|
||||
- **Depends on:** none
|
||||
|
||||
### Phase 2 — JS-side `.free()` audit + remove the swallow
|
||||
|
||||
- **Goal:** make the JS side stop hiding crypto-state-transition errors, and prove (via a recorded audit) that there are no other `.free()` callsites on `SessionHandle` (or on `EncryptedAttachment` / `TotpCode`) that bypass `wasm.lock(handle)` first.
|
||||
- **Changes:**
|
||||
- `extension/src/service-worker/session.ts:24-28` — replace the body of `clearCurrent()` so that `current.free()` is called unconditionally (no `try`/`catch`) and `current` is set to `null` afterwards. The doc-block at the top of the file (lines 1-9) gets one extra paragraph noting that with `impl Drop` on the Rust side (Phase 1), `free()` now removes the registry entry — `lock(handle)` becomes a redundant early-cleanup option, but the SW currently does not call it. Document whether to keep `clearCurrent()` minimal (just `free()`) or add an explicit `wasm.lock(current.value)` immediately before `free()` for symmetry with the CLI's session lifecycle. Recommended: just `free()` post-Phase-1 — calling `lock` first is now belt-and-suspenders that adds a redundant HashMap remove. Document the rationale in the comment.
|
||||
- **Audit deliverable:** run `grep -rn "\.free\b" extension/src/` and record the result in the PR description. Today this returns exactly one match (`extension/src/service-worker/session.ts:26`), confirming the SW is the only surface that calls `.free()` on a wasm-bindgen handle. If a future surface (e.g. an offscreen document, a future setup-flow refactor) adds a second callsite, this PR's grep becomes the baseline that flags the new one.
|
||||
- **Lifecycle audit (no code change required, but record findings in PR description):** confirm every code path that constructs a `SessionHandle` via `unlock(...)` ultimately reaches `clearCurrent()`. The two paths are (a) explicit user lock via the popup `lock` action → `service-worker/router/popup-only.ts` `lock` handler → `clearCurrent()`, and (b) inactivity timer expiry → `service-worker/index.ts:51-58` session-expired callback → `clearCurrent()`. Both are already wired; this audit just records that the wiring is complete.
|
||||
- **Tests:**
|
||||
- Vitest in `extension/`: add a small unit test in `extension/src/service-worker/__tests__/session.test.ts` (create if absent) that asserts `clearCurrent()` is a no-op when `current` is `null`, calls `setCurrent({ free: spy, value: 1 } as unknown as SessionHandle)` then `clearCurrent()`, and asserts `spy` was called exactly once and `getCurrent()` returns `null`. Use the existing `__stubs__/relicario_wasm.stub.ts` pattern for the handle shape if convenient.
|
||||
- Optionally extend the lifecycle test: a second case where `free()` throws — assert the exception now propagates out of `clearCurrent()` (regression coverage for the swallow removal).
|
||||
- **Effort:** S
|
||||
- **Depends on:** Phase 1 (the swallow removal is only safe once the Rust side actually does the cleanup work that `.free()` is now supposed to do)
|
||||
|
||||
### Phase 3 — `recovery_qr.rs` documentation pass
|
||||
|
||||
- **Goal:** raise `crates/relicario-core/src/recovery_qr.rs` to the documentation density of `crypto.rs` / `imgsecret.rs` / `backup.rs` / `tar_safe.rs` so a reader landing in the file does not assume it is out-of-the-documented-zone scratch code.
|
||||
- **Changes:** all in `crates/relicario-core/src/recovery_qr.rs`:
|
||||
- **Module-level `//!` header** at the top of the file (above the `use` block on line 1). Three short paragraphs: (1) *what* the module produces (a 109-byte payload encoded as a QR v40 EcLevel::M SVG that, given the same passphrase, recovers the 32-byte image_secret); (2) *why the format is structured this way* — XChaCha20-Poly1305 wrapping over an Argon2id-derived "wrap key" derived from the recovery passphrase (`b"relicario-recovery-v1\0"` domain-separation prefix prevents the wrap key from ever colliding with a vault master key, even if the user reuses their vault passphrase here); (3) *parameter-pinning rationale* — `production_params()` deliberately re-states `KdfParams::default()`'s values rather than referencing them, because changing the default at the type level must not silently invalidate every recovery QR a user has printed.
|
||||
- **ASCII layout diagram** above the magic-constant block (lines 7-9):
|
||||
```
|
||||
// byte field length
|
||||
// ------ -------------- ------
|
||||
// 0..4 MAGIC = "RREC" 4
|
||||
// 4..5 VERSION = 0x01 1
|
||||
// 5..37 kdf_salt 32 (random per QR)
|
||||
// 37..61 wrap_nonce 24 (random per QR)
|
||||
// 61..109 ciphertext 48 (32 image_secret + 16 AEAD tag)
|
||||
// ------------------------------
|
||||
// total 109
|
||||
```
|
||||
Pair the diagram with a `const _: () = assert!(PAYLOAD_LEN == 4 + 1 + 32 + 24 + 48);` static assertion so a future edit that changes the layout cannot drift from the documented total without a compile error.
|
||||
- **Doc-comments on the four public items:**
|
||||
- `RecoveryQrPayload` (line 11): one-paragraph summary; note that `as_bytes()` is the only accessor and that the bytes are an opaque sealed package — they should travel together (printing them as a QR is the supported transport, but a hex string also works for paranoid sneakernet).
|
||||
- `generate_recovery_qr` (line 45): documents inputs (passphrase, image_secret), output (the 109-byte payload), and the security properties (random kdf_salt + random wrap_nonce per call ⇒ two QRs from the same passphrase + image_secret are different bytes). Cross-reference `recovery_qr_to_svg` for rendering.
|
||||
- `unwrap_recovery_qr` (line 81): documents inputs/output, return-type rationale (`Zeroizing<[u8; 32]>` so the recovered image_secret zeroes when dropped), and the error vocabulary (`RecoveryQr` for format errors, `Decrypt` for AEAD failure / wrong passphrase — the deliberate non-distinguishing rejection from audit M4).
|
||||
- `recovery_qr_to_svg` (line 122): documents the rendering choice (QR v40, EcLevel::M, 140×140 minimum dimension) and the rationale (109 bytes fits comfortably in v40 at M, leaving recovery-error-correction headroom for a smudged print).
|
||||
- **`production_params` (line 32):** add a doc-comment explaining the deliberate divergence-tolerance from `KdfParams::default()` — wording: "Pinned at QR-format authoring time. `KdfParams::default()` may evolve as we re-tune Argon2 cost; this function MUST NOT change values that have ever shipped, because doing so silently invalidates every recovery QR printed under a previous parameter set." Either keep the function-with-comment shape, or per the synthesis suggestion, replace it with a `const RECOVERY_PRODUCTION_PARAMS: KdfParams = KdfParams { argon2_m: 65536, argon2_t: 3, argon2_p: 4 };` if `KdfParams` is `const`-constructible (it is — checked via `crypto.rs`). Either is acceptable; the `const` form is preferred because it makes the "this is not derived from defaults" property visible at the use site.
|
||||
- **Optional micro-cleanups while in the file** (cite explicitly so they aren't surprising in code review):
|
||||
- Replace the hand-counted `payload_bytes[5..37]`, `[37..61]`, `[61..109]` slice indices with named constants (`KDF_SALT_RANGE`, `WRAP_NONCE_RANGE`, `CIPHERTEXT_RANGE`) derived from the layout offsets. Improves diff-readability if the layout ever extends.
|
||||
- Add a one-line comment to `recovery_kdf_input` documenting that the length-prefix on `nfc_bytes` mirrors the same convention as `crypto::derive_master_key` (audit H1 in the design spec) — this is the connective tissue that explains "why is there a `(len as u64).to_be_bytes()` here too?"
|
||||
- **Tests:**
|
||||
- No new test logic needed — the existing `tests/recovery_qr.rs` and the `RecoveryQr`/`Decrypt` round-trips in `tests/integration.rs` already pin behaviour.
|
||||
- The `const _: () = assert!(...)` static assertion is itself the contract test for the layout diagram.
|
||||
- **Effort:** S
|
||||
- **Depends on:** none
|
||||
|
||||
### Phase 4 — Relay launcher (queue.test.ts already done in `061facd`)
|
||||
|
||||
- **Goal:** confirm the test fix that already shipped, and bring the launcher script up to the four-role world.
|
||||
- **Changes:**
|
||||
- `tools/relay/queue.test.ts` — **no change.** Confirmed during planning: line 54 is already `assert.ok(isRole("dev-c"));` and line 55 is already `assert.ok(!isRole("dev-d"));` (committed in `061facd`). This phase records the verification step in the PR description so a reviewer can see the file was checked.
|
||||
- `tools/relay/start.sh` — real changes:
|
||||
- Add a `DEV_C_PROMPT` discovery line at lines 30-33 alongside the existing `PM_PROMPT` / `DEV_A_PROMPT` / `DEV_B_PROMPT` definitions: `DEV_C_PROMPT="$(ls -t "$COORD_DIR"/*-dev-c-prompt.md 2>/dev/null | head -1 || echo "(none found)")"`.
|
||||
- Manual mode (`print_manual_instructions`, lines 35-51) — change "Open 3 new terminals" to "Open 4 new terminals" and add the `Terminal 4 (Dev C): cat '$DEV_C_PROMPT'` line.
|
||||
- tmux mode (`launch_tmux`, lines 53-69) — add a fourth `tmux new-window -t "$SESSION:" -n "dev-c" "cd '$REPO_ROOT' && claude"` line; update the summary print on line 61 from "4 windows: relay, pm, dev-a, dev-b" to "5 windows: relay, pm, dev-a, dev-b, dev-c"; add `Dev C: $DEV_C_PROMPT` to the prompts list (currently lines 64-66).
|
||||
- kitty mode (`launch_kitty`, lines 71-86) — add a fourth `kitty @ launch --type=tab --tab-title "Dev-C" --hold -- bash -l -i -c "cd '$REPO_ROOT' && claude"` line; update the summary print on line 81 from "3 windows (PM, Dev-A, Dev-B)" to "4 windows (PM, Dev-A, Dev-B, Dev-C)"; add `Dev C: $DEV_C_PROMPT` to the prompts list.
|
||||
- **Tests:** none directly. The relay launcher has no automated tests; verification is "run `bash tools/relay/start.sh --manual` and confirm the banner mentions four terminals + the Dev-C prompt path; run `bash tools/relay/start.sh --kitty` on a kitty terminal and confirm a fourth tab opens." Both checks belong in the PR's manual-test plan.
|
||||
- **Effort:** S
|
||||
- **Depends on:** none
|
||||
|
||||
## Risks and mitigations
|
||||
|
||||
- **Adding `impl Drop` could change observable behaviour for any JS code that today holds two references to the same `SessionHandle` and frees one of them.** wasm-bindgen does not in fact let JS hold two refs to the same Rust struct without explicit cloning — the `SessionHandle` is moved into JS at construction and `.free()` consumes the handle pointer. The audit in Phase 2 confirmed only one `.free()` callsite under `extension/src/`. The CLI does not touch the WASM crate at all (Rust-side; the CLI uses `relicario-core` directly). So the realistic blast radius is exactly the one SW callsite this plan also touches. Mitigation: Phase 1's native test explicitly covers "drop the handle, registry is empty," and Phase 2's vitest covers "free is called exactly once."
|
||||
- **Removing the `try { current.free() } catch { /* already freed */ }` swallow could expose latent bugs that were silently tolerated.** Specifically, if any code path today double-frees the handle (calls `clearCurrent()` twice without a `setCurrent()` in between), the catch is currently hiding it. Reading the SW lifecycle: `clearCurrent()` is called from (a) the `lock` message handler, (b) the inactivity-timer session-expired callback, and (c) potentially the unlock-failure cleanup path. The current `if (!current) return;` early-out at line 25 already guards the simplest double-free case (calling `clearCurrent()` twice in a row is safe because the second call no-ops). The only way the catch fires today is if something in WASM raises during `free()` — which post-Phase-1 should be impossible (Drop is infallible; `session::remove` returns a bool, not a Result). Mitigation: the swallow removal happens *after* Phase 1's Drop lands, so the catch should now have nothing to catch. If a regression test surfaces a real bug, the right fix is to find and fix the bug, not re-add the swallow.
|
||||
- **The `recovery_qr.rs` static assertion (`const _: () = assert!(PAYLOAD_LEN == ...);`) requires Rust 1.79+** for `const` panic in test position. The workspace's `rust-toolchain.toml` (if present) or the `Cargo.toml` `rust-version` field needs to be checked; if the repo is on an older toolchain, fall back to a runtime `#[test] fn payload_len_matches_layout() { assert_eq!(PAYLOAD_LEN, 4 + 1 + 32 + 24 + 48); }` — same effect, slightly less elegant. Verify during implementation; not a blocker.
|
||||
- **Phase 4's launcher change is untested by automation.** A typo in the kitty/tmux command lines won't surface until someone runs `start.sh --kitty` or `start.sh --tmux`. Mitigation: the PR description includes an explicit manual-test plan ("run all three modes and confirm 4 windows + Dev-C prompt resolution") and the change pattern is symmetric to the existing Dev-A/Dev-B lines, minimizing typo surface.
|
||||
- **The `wasm-bindgen-test` variant in Phase 1 only runs under `wasm-pack test --node`, which is not part of the project's default `cargo test` cycle.** The native `#[test]` in `mod session_tests` is the one that protects against regressions in CI. The wasm-bindgen-test is included for symmetry and to exercise the actual WASM target's Drop behaviour — it should be invoked at least once during PR review and added to a follow-up CI workflow if the project's test infrastructure ever expands to wasm-pack.
|
||||
|
||||
## Out of scope
|
||||
|
||||
This plan deliberately does not address, and explicitly leaves to other plans or the P2/P3 tail:
|
||||
|
||||
- Plan B's CLI restructure work in its entirety (P1.2 main.rs split, P1.3 git-shell error UX, P1.10 parser migration to core, plus the CLI P2/P3 entries). These touch `crates/relicario-cli/` and are independent of this PR.
|
||||
- Plan C's extension restructure work in its entirety (P1.4 setup.ts WASM extraction, P1.5 vault.ts split, P1.6 shared/state.ts typing, P1.9 SW router helper extraction, plus the extension P2/P3 entries). These touch `extension/src/` and are independent of this PR — except for the single SW file that Phase 2 of this plan touches, which is small and disjoint from Plan C's surfaces.
|
||||
- The P2 WASM cleanups DEV-B flagged: redundant `need_key + with(...).unwrap()` double-lookup, `Vec<u8>` getter clones, the `wasm_*_recovery_qr` naming inconsistency, and the `device.rs` vs `session.rs` concurrency-primitive split. Each is independently correct and worth doing, but each is its own one-paragraph change and the PR is already covering its theme.
|
||||
- DEV-C's other relay P2s: queue TTL/persistence/cap, the `tools/relay/call.py` and `call.ts` tracking decision, `server.ts` per-connection factory comment. None block this PR.
|
||||
- The eight "Open architectural decisions" at the bottom of the synthesis (deliberate-Drop-omission, parser migration timing, bootstrap rule, `Lock` subcommand visibility, Task 12 status, call.py tracking, snake_case-vs-camelCase WASM naming, `.gitea_env_vars` gitignore). Most are user-judgement calls; this PR confirms #1 (the omission was not deliberate; the fix lands here) but takes no position on #2-#8.
|
||||
- Anything touching the in-flight uncommitted v0.5.x work — manifests, glyphs, vault.css, relay tooling beyond `start.sh`. Those changes are on parallel branches and are explicitly hands-off for this PR.
|
||||
|
||||
## Done criteria
|
||||
|
||||
A reviewer can confirm this plan shipped by checking:
|
||||
|
||||
- [ ] `crates/relicario-wasm/src/lib.rs` contains `impl Drop for SessionHandle` whose body removes the registry entry.
|
||||
- [ ] `crates/relicario-wasm/tests/session_drop.rs` (or equivalent native `#[test]` inside `mod session_tests`) asserts that dropping a `SessionHandle` removes its handle id from the session registry. `cargo test -p relicario-wasm` passes the new test.
|
||||
- [ ] `extension/src/service-worker/session.ts` no longer contains `try { current.free(); } catch`. The body of `clearCurrent()` calls `current.free()` unconditionally, then sets `current = null`.
|
||||
- [ ] `grep -rn "\.free\b" extension/src/` returns exactly one match (the SW callsite). PR description records this audit.
|
||||
- [ ] `extension/src/service-worker/__tests__/session.test.ts` covers `clearCurrent()` with both the no-op (no current handle) and the propagating-throw cases. `npm test` from `extension/` passes.
|
||||
- [ ] `crates/relicario-core/src/recovery_qr.rs` has a module-level `//!` header explaining format + domain-separation + parameter-pinning, an ASCII layout diagram next to the magic constants, doc-comments on `RecoveryQrPayload`, `generate_recovery_qr`, `unwrap_recovery_qr`, and `recovery_qr_to_svg`, plus either a `const RECOVERY_PRODUCTION_PARAMS` or a doc-commented `production_params()` explaining why it deliberately diverges from `KdfParams::default()`. `cargo test -p relicario-core` still passes.
|
||||
- [ ] `tools/relay/queue.test.ts:54-55` verified to already match the new role union (no change required, recorded in PR description).
|
||||
- [ ] `tools/relay/start.sh` discovers a `*-dev-c-prompt.md`, opens a fourth window/terminal in tmux and kitty modes, and the manual-mode banner mentions all four roles. `bash tools/relay/start.sh --manual` shows "Open 4 new terminals" and lists the Dev-C prompt path.
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Relicario",
|
||||
"version": "0.2.0",
|
||||
"version": "0.5.0",
|
||||
"description": "Two-factor encrypted password manager",
|
||||
"icons": {
|
||||
"16": "icons/icon-16.png",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Relicario",
|
||||
"version": "0.2.0",
|
||||
"version": "0.5.0",
|
||||
"description": "Two-factor encrypted password manager",
|
||||
"icons": {
|
||||
"16": "icons/icon-16.png",
|
||||
|
||||
4
extension/package-lock.json
generated
4
extension/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "relicario-extension",
|
||||
"version": "0.2.0",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "relicario-extension",
|
||||
"version": "0.2.0",
|
||||
"version": "0.5.0",
|
||||
"dependencies": {
|
||||
"jsqr": "^1.4.0"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "relicario-extension",
|
||||
"version": "0.2.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "webpack --mode production",
|
||||
|
||||
@@ -1,17 +1,329 @@
|
||||
// extension/src/popup/components/settings-security.ts
|
||||
// Stub — real implementation provided by Stream C (DEV-C).
|
||||
/// Security settings section — three-state Recovery QR + Trusted Devices panel.
|
||||
///
|
||||
/// Exported contract:
|
||||
/// renderSecuritySection(container, sessionHandle): renders into `container`
|
||||
/// teardownSecuritySection(): removes any open QR modal
|
||||
|
||||
import { sendMessage, escapeHtml } from '../../shared/state';
|
||||
import type { Device } from '../../shared/types';
|
||||
|
||||
// --- Relative time helper ---
|
||||
|
||||
function relativeTime(unixSec: number): string {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const diff = now - unixSec;
|
||||
if (diff < 60) return 'just now';
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||
if (diff < 2592000) return `${Math.floor(diff / 86400)}d ago`;
|
||||
return `${Math.floor(diff / 2592000)}mo ago`;
|
||||
}
|
||||
|
||||
// --- Modal helpers ---
|
||||
|
||||
const MODAL_ID = 'relicario-qr-modal';
|
||||
|
||||
function removeModal(): void {
|
||||
document.getElementById(MODAL_ID)?.remove();
|
||||
}
|
||||
|
||||
function showQrModal(svgContent: string): void {
|
||||
removeModal();
|
||||
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = MODAL_ID;
|
||||
overlay.style.cssText = [
|
||||
'position:fixed', 'inset:0', 'z-index:9999',
|
||||
'background:rgba(0,0,0,0.85)',
|
||||
'display:flex', 'flex-direction:column',
|
||||
'align-items:center', 'justify-content:center',
|
||||
'padding:16px', 'box-sizing:border-box',
|
||||
].join(';');
|
||||
|
||||
overlay.innerHTML = `
|
||||
<div style="
|
||||
background:#161b22; border:1px solid #30363d; border-radius:8px;
|
||||
padding:16px; max-width:340px; width:100%; text-align:center;
|
||||
">
|
||||
<div style="font-size:13px; font-weight:600; margin-bottom:8px; color:#e6edf3;">
|
||||
Recovery QR
|
||||
</div>
|
||||
<div style="font-size:11px; color:#8b949e; margin-bottom:12px;">
|
||||
Print or store this QR. It encodes your reference image secret,
|
||||
protected by your passphrase.
|
||||
</div>
|
||||
<div id="relicario-qr-svg" style="
|
||||
background:#fff; border-radius:4px; padding:8px;
|
||||
display:inline-block; max-width:280px; width:100%;
|
||||
">
|
||||
${svgContent}
|
||||
</div>
|
||||
<div style="display:flex; gap:8px; margin-top:12px; justify-content:center;">
|
||||
<button id="relicario-qr-print" class="btn btn-primary" style="font-size:12px;">
|
||||
Print
|
||||
</button>
|
||||
<button id="relicario-qr-done" class="btn" style="font-size:12px;">
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
document.getElementById('relicario-qr-done')?.addEventListener('click', removeModal);
|
||||
|
||||
document.getElementById('relicario-qr-print')?.addEventListener('click', () => {
|
||||
const win = window.open('', '_blank', 'width=400,height=500');
|
||||
if (!win) return;
|
||||
win.document.write(`
|
||||
<!DOCTYPE html>
|
||||
<html><head><title>Recovery QR</title>
|
||||
<style>
|
||||
body { margin: 0; display: flex; flex-direction: column; align-items: center;
|
||||
font-family: sans-serif; padding: 24px; }
|
||||
h2 { font-size: 16px; margin-bottom: 8px; }
|
||||
p { font-size: 12px; color: #555; margin-bottom: 16px; text-align: center; }
|
||||
svg { max-width: 280px; width: 100%; }
|
||||
</style></head><body>
|
||||
<h2>Relicario Recovery QR</h2>
|
||||
<p>Scan with the Relicario app to recover your reference image secret.<br>
|
||||
Keep this page in a safe physical location.</p>
|
||||
${svgContent}
|
||||
<script>window.onload = () => { window.print(); window.close(); }<\/script>
|
||||
</body></html>
|
||||
`);
|
||||
win.document.close();
|
||||
});
|
||||
|
||||
// Close on backdrop click
|
||||
overlay.addEventListener('click', (e) => {
|
||||
if (e.target === overlay) removeModal();
|
||||
});
|
||||
}
|
||||
|
||||
// --- Main render ---
|
||||
|
||||
export async function renderSecuritySection(
|
||||
container: HTMLElement,
|
||||
_sessionHandle: number | null,
|
||||
sessionHandle: number | null,
|
||||
): Promise<void> {
|
||||
// Read timestamp from device-local storage (never the QR payload itself)
|
||||
const stored = await chrome.storage.local.get(['recovery_qr_generated_at']);
|
||||
const generatedAt: number | null = (stored.recovery_qr_generated_at as number) ?? null;
|
||||
|
||||
const isUnlocked = sessionHandle !== null;
|
||||
|
||||
// --- QR status section ---
|
||||
let qrStatusHtml: string;
|
||||
if (generatedAt === null) {
|
||||
qrStatusHtml = `
|
||||
<div style="
|
||||
display:flex; align-items:flex-start; gap:10px;
|
||||
background:#2d1f00; border:1px solid #7c5719; border-radius:6px;
|
||||
padding:10px; margin-bottom:12px;
|
||||
">
|
||||
<span style="font-size:16px;">⚠</span>
|
||||
<div style="flex:1; font-size:12px;">
|
||||
<div style="color:#e3a726; font-weight:600; margin-bottom:2px;">
|
||||
No recovery QR generated
|
||||
</div>
|
||||
<div style="color:#8b949e;">
|
||||
If you lose access to your reference image, you will be locked out permanently.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
id="sec-generate-qr"
|
||||
${isUnlocked ? '' : 'disabled title="Unlock the vault first"'}
|
||||
style="width:100%; font-size:12px; margin-bottom:4px;"
|
||||
>
|
||||
Generate recovery QR…
|
||||
</button>
|
||||
`;
|
||||
} else {
|
||||
qrStatusHtml = `
|
||||
<div style="
|
||||
display:flex; align-items:flex-start; gap:10px;
|
||||
background:#0a2a1a; border:1px solid #238636; border-radius:6px;
|
||||
padding:10px; margin-bottom:12px;
|
||||
">
|
||||
<span style="font-size:16px;">✓</span>
|
||||
<div style="flex:1; font-size:12px;">
|
||||
<div style="color:#3fb950; font-weight:600; margin-bottom:2px;">
|
||||
Recovery QR set up
|
||||
</div>
|
||||
<div style="color:#8b949e;">
|
||||
Generated ${relativeTime(generatedAt)}. Store the printout in a safe place.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex; gap:8px; margin-bottom:4px;">
|
||||
<button
|
||||
class="btn"
|
||||
id="sec-show-qr"
|
||||
${isUnlocked ? '' : 'disabled title="Unlock the vault first"'}
|
||||
style="flex:1; font-size:12px;"
|
||||
>
|
||||
Show / print QR…
|
||||
</button>
|
||||
<button
|
||||
class="btn"
|
||||
id="sec-regenerate-qr"
|
||||
${isUnlocked ? '' : 'disabled title="Unlock the vault first"'}
|
||||
style="flex:1; font-size:12px;"
|
||||
>
|
||||
Regenerate…
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// --- Devices section ---
|
||||
const devicesResp = await sendMessage({ type: 'list_devices' });
|
||||
let devicesHtml: string;
|
||||
if (!devicesResp.ok) {
|
||||
devicesHtml = `<p class="muted" style="font-size:12px;">Could not load devices.</p>`;
|
||||
} else {
|
||||
const devices = (devicesResp.data as { devices: Device[] }).devices;
|
||||
const currentDeviceNameStored = await chrome.storage.local.get(['device_name']);
|
||||
const currentDeviceName: string | undefined = currentDeviceNameStored.device_name as string | undefined;
|
||||
|
||||
if (devices.length === 0) {
|
||||
devicesHtml = `<p class="muted" style="font-size:12px; text-align:center; margin-top:8px;">No devices registered.</p>`;
|
||||
} else {
|
||||
devicesHtml = devices.map((d) => {
|
||||
const isCurrent = d.name === currentDeviceName;
|
||||
return `
|
||||
<div class="device-row" style="display:flex; align-items:center; justify-content:space-between; padding:6px 0; border-bottom:1px solid #21262d;">
|
||||
<div style="flex:1; min-width:0;">
|
||||
<div style="font-size:12px; font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
|
||||
${escapeHtml(d.name)}${isCurrent ? ' <span style="color:#8b949e; font-weight:400; font-size:11px;">(this device)</span>' : ''}
|
||||
</div>
|
||||
<div style="font-size:11px; color:#8b949e;">added ${relativeTime(d.added_at)}</div>
|
||||
</div>
|
||||
${isCurrent ? '' : `
|
||||
<button
|
||||
class="btn sec-revoke-btn"
|
||||
data-device-name="${escapeHtml(d.name)}"
|
||||
style="font-size:11px; margin-left:8px; flex-shrink:0;"
|
||||
>revoke</button>
|
||||
`}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
|
||||
// --- Assemble ---
|
||||
container.innerHTML = `
|
||||
<div class="settings-section-placeholder">
|
||||
<span class="muted">Security settings — loading…</span>
|
||||
<div class="settings-section" style="margin-top:0;">
|
||||
<div class="settings-section__title" style="font-size:12px; color:#8b949e; margin-bottom:8px; text-transform:uppercase; letter-spacing:0.05em;">
|
||||
Recovery QR
|
||||
</div>
|
||||
${qrStatusHtml}
|
||||
<div id="sec-qr-error" style="font-size:11px; color:#f85149; margin-top:4px; min-height:14px;"></div>
|
||||
</div>
|
||||
|
||||
<div class="settings-section" style="margin-top:16px;">
|
||||
<div class="settings-section__title" style="font-size:12px; color:#8b949e; margin-bottom:8px; text-transform:uppercase; letter-spacing:0.05em;">
|
||||
Trusted Devices
|
||||
</div>
|
||||
<div id="sec-devices-list">
|
||||
${devicesHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// --- Wire handlers ---
|
||||
|
||||
const setQrError = (msg: string): void => {
|
||||
const el = document.getElementById('sec-qr-error');
|
||||
if (el) el.textContent = msg;
|
||||
};
|
||||
|
||||
async function doGenerateQr(isRegen: boolean): Promise<void> {
|
||||
const passphrase = prompt(
|
||||
isRegen
|
||||
? 'Enter your vault passphrase to regenerate the recovery QR:'
|
||||
: 'Enter your vault passphrase to generate the recovery QR:',
|
||||
);
|
||||
if (!passphrase) return;
|
||||
|
||||
const btn = document.getElementById(isRegen ? 'sec-regenerate-qr' : 'sec-generate-qr') as HTMLButtonElement | null;
|
||||
if (btn) { btn.disabled = true; btn.textContent = '…'; }
|
||||
|
||||
const resp = await sendMessage({ type: 'generate_recovery_qr', passphrase });
|
||||
if (!resp.ok) {
|
||||
setQrError(`Failed: ${resp.error}`);
|
||||
if (btn) { btn.disabled = false; btn.textContent = isRegen ? 'Regenerate…' : 'Generate recovery QR…'; }
|
||||
return;
|
||||
}
|
||||
|
||||
const svg = (resp.data as { svg: string }).svg;
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Store only the timestamp, NEVER the QR payload
|
||||
await chrome.storage.local.set({ recovery_qr_generated_at: now });
|
||||
|
||||
showQrModal(svg);
|
||||
|
||||
// Re-render to reflect new state (timestamp now exists)
|
||||
await renderSecuritySection(container, sessionHandle);
|
||||
}
|
||||
|
||||
document.getElementById('sec-generate-qr')?.addEventListener('click', () => {
|
||||
void doGenerateQr(false);
|
||||
});
|
||||
|
||||
document.getElementById('sec-regenerate-qr')?.addEventListener('click', () => {
|
||||
void doGenerateQr(true);
|
||||
});
|
||||
|
||||
document.getElementById('sec-show-qr')?.addEventListener('click', async () => {
|
||||
const passphrase = prompt('Enter your vault passphrase to view the recovery QR:');
|
||||
if (!passphrase) return;
|
||||
|
||||
const btn = document.getElementById('sec-show-qr') as HTMLButtonElement | null;
|
||||
if (btn) { btn.disabled = true; btn.textContent = '…'; }
|
||||
|
||||
const resp = await sendMessage({ type: 'generate_recovery_qr', passphrase });
|
||||
if (!resp.ok) {
|
||||
setQrError(`Failed: ${resp.error}`);
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Show / print QR…'; }
|
||||
return;
|
||||
}
|
||||
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Show / print QR…'; }
|
||||
const svg = (resp.data as { svg: string }).svg;
|
||||
showQrModal(svg);
|
||||
});
|
||||
|
||||
// Revoke buttons
|
||||
container.querySelectorAll<HTMLButtonElement>('.sec-revoke-btn').forEach((btn) => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const name = btn.dataset.deviceName;
|
||||
if (!name) return;
|
||||
if (!confirm(`Revoke "${name}"? This device will no longer be authorized.`)) return;
|
||||
|
||||
btn.disabled = true;
|
||||
btn.textContent = '…';
|
||||
|
||||
const result = await sendMessage({ type: 'revoke_device', name });
|
||||
if (result.ok) {
|
||||
await sendMessage({ type: 'sync' });
|
||||
// Re-render to refresh device list
|
||||
await renderSecuritySection(container, sessionHandle);
|
||||
} else {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'revoke';
|
||||
setQrError(`Revoke failed: ${result.error}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function teardownSecuritySection(): void {
|
||||
// no-op in stub
|
||||
removeModal();
|
||||
}
|
||||
|
||||
37
extension/src/service-worker/__tests__/session.test.ts
Normal file
37
extension/src/service-worker/__tests__/session.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import type { SessionHandle } from '../../../wasm/relicario_wasm';
|
||||
import { clearCurrent, getCurrent, setCurrent } from '../session';
|
||||
|
||||
describe('session', () => {
|
||||
beforeEach(() => {
|
||||
// Reset module-scope `current` between tests. Overwrite first with a
|
||||
// benign no-throw fake so a prior test's throwing handle can't escape.
|
||||
setCurrent({ free: vi.fn(), value: 0 } as unknown as SessionHandle);
|
||||
clearCurrent();
|
||||
});
|
||||
|
||||
it('clearCurrent() is a no-op when no handle is set', () => {
|
||||
expect(() => clearCurrent()).not.toThrow();
|
||||
expect(getCurrent()).toBeNull();
|
||||
});
|
||||
|
||||
it('clearCurrent() calls free() exactly once and clears current', () => {
|
||||
const free = vi.fn();
|
||||
setCurrent({ free, value: 1 } as unknown as SessionHandle);
|
||||
|
||||
clearCurrent();
|
||||
expect(free).toHaveBeenCalledTimes(1);
|
||||
expect(getCurrent()).toBeNull();
|
||||
|
||||
clearCurrent();
|
||||
expect(free).toHaveBeenCalledTimes(1);
|
||||
expect(getCurrent()).toBeNull();
|
||||
});
|
||||
|
||||
it('clearCurrent() propagates exceptions from free()', () => {
|
||||
const free = vi.fn(() => { throw new Error('boom'); });
|
||||
setCurrent({ free, value: 2 } as unknown as SessionHandle);
|
||||
|
||||
expect(() => clearCurrent()).toThrow(/boom/);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,12 @@
|
||||
/// Future multi-vault (β+) would replace `current` with
|
||||
/// `Map<vaultId, SessionHandle>` and thread `vaultId` through every
|
||||
/// handler. Deliberate α simplicity — not an oversight.
|
||||
///
|
||||
/// As of Phase 1 of the security-polish series, `impl Drop for SessionHandle`
|
||||
/// on the Rust side makes `.free()` the meaningful cleanup call: it removes
|
||||
/// the entry from the SESSIONS registry and zeroizes `master_key` and
|
||||
/// `image_secret`. Calling `wasm.lock(handle.value)` before `.free()` would
|
||||
/// be redundant belt-and-suspenders; this module intentionally does not.
|
||||
|
||||
import type { SessionHandle } from '../../wasm/relicario_wasm';
|
||||
|
||||
@@ -23,6 +29,6 @@ export function requireCurrent(): SessionHandle {
|
||||
|
||||
export function clearCurrent(): void {
|
||||
if (!current) return;
|
||||
try { current.free(); } catch { /* already freed */ }
|
||||
current.free();
|
||||
current = null;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ describe('Stream A glyphs (vault tab + type icons)', () => {
|
||||
expect(glyphs.GLYPH_TYPE_SECURE_NOTE).toBe('◫');
|
||||
expect(glyphs.GLYPH_TYPE_TOTP).toBe('⊡');
|
||||
expect(glyphs.GLYPH_TYPE_CARD).toBe('▭');
|
||||
expect(glyphs.GLYPH_TYPE_IDENTITY).toBe('⌬');
|
||||
expect(glyphs.GLYPH_TYPE_IDENTITY).toBe('◍');
|
||||
expect(glyphs.GLYPH_TYPE_KEY).toBe('⊹');
|
||||
expect(glyphs.GLYPH_TYPE_DOCUMENT).toBe('≡');
|
||||
});
|
||||
|
||||
@@ -27,7 +27,7 @@ export const GLYPH_TYPE_LOGIN = '◉'; // login
|
||||
export const GLYPH_TYPE_SECURE_NOTE = '◫'; // secure note
|
||||
export const GLYPH_TYPE_TOTP = '⊡'; // totp / 2FA
|
||||
export const GLYPH_TYPE_CARD = '▭'; // card
|
||||
export const GLYPH_TYPE_IDENTITY = '⌬'; // identity
|
||||
export const GLYPH_TYPE_IDENTITY = '◍'; // identity (distinct from GLYPH_DEVICES ⌬)
|
||||
export const GLYPH_TYPE_KEY = '⊹'; // SSH / API key
|
||||
export const GLYPH_TYPE_DOCUMENT = '≡'; // document
|
||||
|
||||
|
||||
@@ -438,6 +438,14 @@ textarea {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/* When the sticky save bar (fullscreen) provides external actions,
|
||||
the form's inner action row sets the [hidden] attribute. The default
|
||||
user-agent rule for [hidden] is display:none, but our .form-actions
|
||||
display:flex above wins specificity. Re-assert hidden takes priority. */
|
||||
.form-actions[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.inline-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
@@ -626,16 +634,18 @@ textarea {
|
||||
.gen-trigger {
|
||||
background: #7c5719;
|
||||
color: #fff3cf;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
padding: 0 12px;
|
||||
font-size: 16px;
|
||||
border: 1px solid #7c5719;
|
||||
border-radius: 3px;
|
||||
padding: 0 8px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
min-width: 38px;
|
||||
min-width: 28px;
|
||||
height: 28px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.gen-trigger:hover { background: #aa812a; }
|
||||
.gen-trigger[aria-expanded="true"] { background: #aa812a; }
|
||||
@@ -1291,8 +1301,8 @@ textarea {
|
||||
gap: 8px;
|
||||
}
|
||||
.vault-sidebar__header .brand-logo {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
margin: 0;
|
||||
display: block;
|
||||
flex-shrink: 0;
|
||||
@@ -1402,6 +1412,7 @@ textarea {
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
background: var(--bg-page, #0d1117);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.vault-sidebar {
|
||||
@@ -1410,9 +1421,11 @@ textarea {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--border, #30363d);
|
||||
background: var(--bg-sidebar, #0d1117);
|
||||
background: var(--bg-page);
|
||||
overflow-y: auto;
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.vault-list-pane {
|
||||
@@ -1423,6 +1436,29 @@ textarea {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Pane occupies the same flex slot as list-pane for non-list views */
|
||||
.vault-pane {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
min-width: 0;
|
||||
padding: 24px 32px;
|
||||
}
|
||||
.vault-pane--empty {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-dim);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* View-specific visibility: only one of list-pane / vault-pane is visible.
|
||||
Default to list view if neither class is set. */
|
||||
.vault-shell .vault-pane { display: none; }
|
||||
.vault-shell--pane .vault-list-pane { display: none; }
|
||||
.vault-shell--pane .vault-pane { display: flex; }
|
||||
.vault-shell--pane .vault-drawer { display: none; }
|
||||
|
||||
.vault-drawer {
|
||||
width: 440px;
|
||||
min-width: 440px;
|
||||
@@ -1439,6 +1475,44 @@ textarea {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
/* Empty state — centered, gold-accented icon, polished */
|
||||
.empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
padding: 48px 24px;
|
||||
text-align: center;
|
||||
min-height: 240px;
|
||||
}
|
||||
.empty-state__icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
border-radius: 50%;
|
||||
background: var(--gold-soft);
|
||||
border: 1px solid var(--gold-ring);
|
||||
color: var(--gold-text);
|
||||
font-size: 30px;
|
||||
line-height: 1;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.empty-state__title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.empty-state__hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.vault-list-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1496,79 +1570,126 @@ textarea {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Bottom sheet */
|
||||
.vault-bottom-sheet-scrim {
|
||||
/* Type picker — secondary panel that slides out from behind the left sidebar */
|
||||
.vault-type-panel-scrim {
|
||||
position: absolute;
|
||||
inset: 0 0 0 200px;
|
||||
background: rgba(0,0,0,0.5);
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s;
|
||||
pointer-events: none;
|
||||
z-index: 100;
|
||||
transition: opacity 0.2s ease;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.vault-bottom-sheet-scrim--visible {
|
||||
.vault-type-panel-scrim--visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.vault-bottom-sheet {
|
||||
.vault-type-panel {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 200px;
|
||||
right: 0;
|
||||
background: var(--bg-elevated, #161b22);
|
||||
border-top: 1px solid var(--border, #30363d);
|
||||
border-radius: 12px 12px 0 0;
|
||||
padding: 16px 24px 24px;
|
||||
transform: translateY(100%);
|
||||
transition: transform 0.25s ease;
|
||||
z-index: 101;
|
||||
max-height: 60vh;
|
||||
width: 280px;
|
||||
background: var(--bg-elevated);
|
||||
border-right: 1px solid var(--border-mid);
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.22s ease;
|
||||
z-index: 4;
|
||||
overflow-y: auto;
|
||||
padding: 14px 12px;
|
||||
box-shadow: 8px 0 24px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.vault-type-panel--open { transform: translateX(0); }
|
||||
|
||||
.vault-bottom-sheet--open { transform: translateY(0); }
|
||||
|
||||
.vault-bottom-sheet__handle {
|
||||
width: 40px;
|
||||
height: 4px;
|
||||
background: var(--border, #30363d);
|
||||
border-radius: 2px;
|
||||
margin: 0 auto 16px;
|
||||
.vault-type-panel__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 4px 10px;
|
||||
margin-bottom: 8px;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.vault-bottom-sheet__title {
|
||||
font-size: 14px;
|
||||
.vault-type-panel__title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 16px;
|
||||
text-align: center;
|
||||
color: var(--gold-text);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
.vault-type-panel__close {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.vault-type-panel__close:hover { color: var(--text); background: var(--bg-pane); }
|
||||
.vault-type-panel__hint {
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
padding: 0 4px 8px;
|
||||
}
|
||||
|
||||
.vault-type-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.vault-type-card {
|
||||
.vault-type-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px 8px;
|
||||
background: var(--bg-page, #0d1117);
|
||||
border: 1px solid var(--border, #30363d);
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s;
|
||||
gap: 6px;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.vault-type-card:hover { border-color: var(--gold, #b8860b); }
|
||||
.vault-type-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 9px 10px;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
transition: background 0.1s, border-color 0.1s;
|
||||
}
|
||||
.vault-type-item:hover {
|
||||
background: var(--bg-pane);
|
||||
border-color: var(--border-mid);
|
||||
}
|
||||
.vault-type-item:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--gold-base);
|
||||
background: var(--gold-soft);
|
||||
}
|
||||
.vault-type-item__icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
flex-shrink: 0;
|
||||
background: var(--gold-soft);
|
||||
border: 1px solid var(--gold-ring);
|
||||
border-radius: 5px;
|
||||
font-size: 15px;
|
||||
color: var(--gold-text);
|
||||
}
|
||||
.vault-type-item__name {
|
||||
flex: 1;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.vault-type-card__icon { font-size: 28px; }
|
||||
.vault-type-card__name { font-size: 11px; color: var(--text-muted, #8b949e); }
|
||||
/* Sidebar nav button — primary new-item variant */
|
||||
.vault-sidebar__nav-item--primary {
|
||||
color: var(--gold-text);
|
||||
font-weight: 600;
|
||||
}
|
||||
.vault-sidebar__nav-item--primary:hover {
|
||||
background: var(--gold-soft);
|
||||
color: var(--gold-hi-end);
|
||||
}
|
||||
|
||||
/* Drawer header and body */
|
||||
.vault-drawer__header {
|
||||
@@ -1902,7 +2023,7 @@ textarea {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 24px;
|
||||
max-width: 960px;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
@@ -1912,7 +2033,7 @@ textarea {
|
||||
/* P3: lower form sections constrained to the same envelope as .form-grid.
|
||||
Gated on surface === 'fullscreen' in login.ts; popup unaffected. */
|
||||
.form-lower {
|
||||
max-width: 960px;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.form-lower > .form-group,
|
||||
@@ -1965,6 +2086,9 @@ textarea {
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.form-scroll {
|
||||
flex: 1;
|
||||
|
||||
@@ -27,10 +27,10 @@ import { renderImportPanel, teardown as teardownImport } from './components/impo
|
||||
import { applyColorScheme } from '../shared/color-scheme';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bottom sheet type picker
|
||||
// Type picker (right side panel)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const BOTTOM_SHEET_TYPES: Array<{ type: ItemType; label: string }> = [
|
||||
const PICKER_TYPES: Array<{ type: ItemType; label: string }> = [
|
||||
{ type: 'login', label: 'Login' },
|
||||
{ type: 'secure_note', label: 'Secure Note' },
|
||||
{ type: 'totp', label: 'TOTP' },
|
||||
@@ -47,6 +47,27 @@ const BOTTOM_SHEET_TYPES: Array<{ type: ItemType; label: string }> = [
|
||||
function sendMessage(request: Request): Promise<Response> {
|
||||
return new Promise((resolve) => {
|
||||
chrome.runtime.sendMessage(request, (response: Response) => {
|
||||
// MV3 service workers are evicted after ~30s idle, which wipes the
|
||||
// in-memory session/manifest/gitHost. The fullscreen tab stays open
|
||||
// and has no signal that the SW restarted — the next RPC just comes
|
||||
// back `vault_locked`. Treat that as "session lost" and force the
|
||||
// lock screen so the user can re-enter their passphrase. Skip for
|
||||
// is_unlocked / unlock themselves to avoid loops on cold start.
|
||||
if (
|
||||
response &&
|
||||
!response.ok &&
|
||||
response.error === 'vault_locked' &&
|
||||
request.type !== 'is_unlocked' &&
|
||||
request.type !== 'unlock' &&
|
||||
state.unlocked
|
||||
) {
|
||||
state.unlocked = false;
|
||||
state.selectedId = null;
|
||||
state.selectedItem = null;
|
||||
state.entries = [];
|
||||
state.error = 'Session expired — please unlock again.';
|
||||
render();
|
||||
}
|
||||
resolve(response);
|
||||
});
|
||||
});
|
||||
@@ -166,7 +187,7 @@ interface VaultState {
|
||||
searchQuery: string;
|
||||
activeGroup: string | null;
|
||||
drawerOpen: boolean;
|
||||
bottomSheetOpen: boolean;
|
||||
typePanelOpen: boolean;
|
||||
vaultSettings: VaultSettings | null;
|
||||
generatorDefaults: GeneratorRequest | null;
|
||||
error: string | null;
|
||||
@@ -187,7 +208,7 @@ const state: VaultState = {
|
||||
searchQuery: '',
|
||||
activeGroup: null,
|
||||
drawerOpen: false,
|
||||
bottomSheetOpen: false,
|
||||
typePanelOpen: false,
|
||||
vaultSettings: null,
|
||||
generatorDefaults: null,
|
||||
error: null,
|
||||
@@ -211,8 +232,9 @@ registerHost({
|
||||
navigate: (view: string, extras?: any) => {
|
||||
Object.assign(state, { view, error: null, loading: false, ...extras });
|
||||
setHash(view as VaultView);
|
||||
applyShellViewClass();
|
||||
renderSidebarCategories();
|
||||
renderListPane();
|
||||
if (state.view === 'list') renderListPane();
|
||||
renderPane();
|
||||
},
|
||||
sendMessage,
|
||||
@@ -290,7 +312,7 @@ function renderShell(app: HTMLElement): void {
|
||||
<div class="vault-shell">
|
||||
<div class="vault-sidebar">
|
||||
<div class="vault-sidebar__header">
|
||||
<img class="brand-logo" src="icons/relicario-logo-16.svg" alt="">
|
||||
<img class="brand-logo" src="icons/relicario-logo.svg" alt="">
|
||||
<span class="brand">Relicario</span>
|
||||
</div>
|
||||
<div class="vault-sidebar__search">
|
||||
@@ -298,7 +320,7 @@ function renderShell(app: HTMLElement): void {
|
||||
</div>
|
||||
<nav class="vault-sidebar__categories" id="vault-categories" aria-label="Item types"></nav>
|
||||
<div class="vault-sidebar__nav">
|
||||
<button class="vault-sidebar__nav-item" data-nav="add" title="New item">+ new item</button>
|
||||
<button class="vault-sidebar__nav-item vault-sidebar__nav-item--primary" data-nav="add" title="New item">+ new item</button>
|
||||
<button class="vault-sidebar__nav-item" data-nav="trash" title="Trash">${GLYPH_TRASH} <span class="vault-sidebar__nav-label">trash</span></button>
|
||||
<button class="vault-sidebar__nav-item" data-nav="devices" title="Devices">${GLYPH_DEVICES} <span class="vault-sidebar__nav-label">devices</span></button>
|
||||
<button class="vault-sidebar__nav-item" data-nav="settings" title="Settings">${GLYPH_SETTINGS} <span class="vault-sidebar__nav-label">settings</span></button>
|
||||
@@ -306,69 +328,102 @@ function renderShell(app: HTMLElement): void {
|
||||
</div>
|
||||
</div>
|
||||
<div class="vault-list-pane" id="vault-list-pane"></div>
|
||||
<div class="vault-pane" id="vault-pane"></div>
|
||||
<div class="vault-drawer" id="vault-drawer"></div>
|
||||
<div class="vault-bottom-sheet-scrim" id="vault-sheet-scrim"></div>
|
||||
<div class="vault-bottom-sheet" id="vault-bottom-sheet"></div>
|
||||
<div class="vault-type-panel-scrim" id="vault-type-scrim"></div>
|
||||
<aside class="vault-type-panel" id="vault-type-panel" aria-label="Choose item type"></aside>
|
||||
</div>
|
||||
`;
|
||||
wireSidebar();
|
||||
wireBottomSheet();
|
||||
wireTypePanel();
|
||||
}
|
||||
|
||||
applyShellViewClass();
|
||||
renderSidebarCategories();
|
||||
renderListPane();
|
||||
if (state.drawerOpen && state.selectedItem) {
|
||||
renderDrawer(state.selectedItem);
|
||||
if (state.view === 'list') {
|
||||
renderListPane();
|
||||
if (state.drawerOpen && state.selectedItem) {
|
||||
renderDrawer(state.selectedItem);
|
||||
}
|
||||
} else {
|
||||
renderPane();
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle which middle column is visible based on the current view.
|
||||
// list view → list-pane (+ optional drawer); other views → vault-pane.
|
||||
function applyShellViewClass(): void {
|
||||
const shell = document.querySelector('.vault-shell');
|
||||
if (!shell) return;
|
||||
shell.classList.toggle('vault-shell--list', state.view === 'list');
|
||||
shell.classList.toggle('vault-shell--pane', state.view !== 'list');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bottom sheet (wired in Task 11)
|
||||
// Right-side type picker panel
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function wireBottomSheet(): void {
|
||||
document.getElementById('vault-sheet-scrim')?.addEventListener('click', closeBottomSheet);
|
||||
function wireTypePanel(): void {
|
||||
document.getElementById('vault-type-scrim')?.addEventListener('click', closeTypePanel);
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && state.bottomSheetOpen) closeBottomSheet();
|
||||
if (e.key === 'Escape' && state.typePanelOpen) closeTypePanel();
|
||||
});
|
||||
}
|
||||
|
||||
function openBottomSheet(): void {
|
||||
const sheet = document.getElementById('vault-bottom-sheet');
|
||||
const scrim = document.getElementById('vault-sheet-scrim');
|
||||
if (!sheet || !scrim) return;
|
||||
function openTypePanel(): void {
|
||||
const panel = document.getElementById('vault-type-panel');
|
||||
const scrim = document.getElementById('vault-type-scrim');
|
||||
if (!panel || !scrim) return;
|
||||
|
||||
sheet.innerHTML = `
|
||||
<div class="vault-bottom-sheet__handle"></div>
|
||||
<div class="vault-bottom-sheet__title">New item — choose type</div>
|
||||
<div class="vault-type-grid">
|
||||
${BOTTOM_SHEET_TYPES.map((t) => `
|
||||
<button class="vault-type-card" data-type="${t.type}">
|
||||
<span class="vault-type-card__icon" aria-hidden="true">${typeIcon(t.type)}</span>
|
||||
<span class="vault-type-card__name">${escapeHtml(t.label)}</span>
|
||||
panel.innerHTML = `
|
||||
<div class="vault-type-panel__head">
|
||||
<div class="vault-type-panel__title">New item</div>
|
||||
<button class="vault-type-panel__close" id="vault-type-close" title="Close (Esc)" aria-label="Close">✕</button>
|
||||
</div>
|
||||
<div class="vault-type-panel__hint">Choose a type</div>
|
||||
<div class="vault-type-list" role="menu">
|
||||
${PICKER_TYPES.map((t) => `
|
||||
<button class="vault-type-item" data-type="${t.type}" role="menuitem">
|
||||
<span class="vault-type-item__icon" aria-hidden="true">${typeIcon(t.type)}</span>
|
||||
<span class="vault-type-item__name">${escapeHtml(t.label)}</span>
|
||||
</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
|
||||
sheet.classList.add('vault-bottom-sheet--open');
|
||||
scrim.classList.add('vault-bottom-sheet-scrim--visible');
|
||||
state.bottomSheetOpen = true;
|
||||
panel.classList.add('vault-type-panel--open');
|
||||
scrim.classList.add('vault-type-panel-scrim--visible');
|
||||
state.typePanelOpen = true;
|
||||
|
||||
sheet.querySelectorAll<HTMLButtonElement>('[data-type]').forEach((btn) => {
|
||||
panel.querySelector('#vault-type-close')?.addEventListener('click', closeTypePanel);
|
||||
|
||||
panel.querySelectorAll<HTMLButtonElement>('[data-type]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
const type = btn.dataset.type as ItemType;
|
||||
closeBottomSheet();
|
||||
closeTypePanel();
|
||||
// Use the host's navigate hook so view + hash + visibility all update
|
||||
// together. This was the bug: bare setHash + renderPane left the
|
||||
// shell stuck in list view with #vault-pane hidden.
|
||||
state.newType = type;
|
||||
state.selectedId = null;
|
||||
state.selectedItem = null;
|
||||
state.drawerOpen = false;
|
||||
state.view = 'add';
|
||||
setHash('add', type);
|
||||
applyShellViewClass();
|
||||
renderSidebarCategories();
|
||||
renderPane();
|
||||
});
|
||||
});
|
||||
|
||||
// Focus first item for keyboard users
|
||||
(panel.querySelector('.vault-type-item') as HTMLElement | null)?.focus();
|
||||
}
|
||||
|
||||
function closeBottomSheet(): void {
|
||||
document.getElementById('vault-bottom-sheet')?.classList.remove('vault-bottom-sheet--open');
|
||||
document.getElementById('vault-sheet-scrim')?.classList.remove('vault-bottom-sheet-scrim--visible');
|
||||
state.bottomSheetOpen = false;
|
||||
function closeTypePanel(): void {
|
||||
document.getElementById('vault-type-panel')?.classList.remove('vault-type-panel--open');
|
||||
document.getElementById('vault-type-scrim')?.classList.remove('vault-type-panel-scrim--visible');
|
||||
state.typePanelOpen = false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -527,14 +582,19 @@ function wireSidebar(): void {
|
||||
state.selectedId = null;
|
||||
state.selectedItem = null;
|
||||
state.newType = null;
|
||||
openBottomSheet();
|
||||
state.drawerOpen = false;
|
||||
closeDrawer();
|
||||
openTypePanel();
|
||||
return;
|
||||
}
|
||||
if (nav === 'trash' || nav === 'devices' || nav === 'settings') {
|
||||
state.selectedId = null;
|
||||
state.selectedItem = null;
|
||||
state.newType = null;
|
||||
state.drawerOpen = false;
|
||||
state.view = nav;
|
||||
setHash(nav);
|
||||
applyShellViewClass();
|
||||
renderPane();
|
||||
return;
|
||||
}
|
||||
@@ -605,7 +665,8 @@ function renderSidebarCategories(): void {
|
||||
|
||||
for (const t of typeOrder) {
|
||||
const count = filtered.filter(([, e]) => e.type === t).length;
|
||||
if (count === 0 && allCount > 0) continue;
|
||||
// Always show Login (staple type); hide other types when empty.
|
||||
if (count === 0 && t !== 'login') continue;
|
||||
const isActive = state.activeGroup === t;
|
||||
html += `
|
||||
<button class="vault-category-row ${isActive ? 'vault-category-row--active' : ''}" data-group="${t}">
|
||||
@@ -624,6 +685,9 @@ function renderSidebarCategories(): void {
|
||||
state.drawerOpen = false;
|
||||
state.selectedId = null;
|
||||
state.selectedItem = null;
|
||||
state.view = 'list';
|
||||
setHash('list');
|
||||
applyShellViewClass();
|
||||
renderSidebarCategories();
|
||||
renderListPane();
|
||||
closeDrawer();
|
||||
@@ -764,6 +828,7 @@ function renderPane(): void {
|
||||
const route = parseHash();
|
||||
// Keep state.view in sync with hash for components that read it
|
||||
state.view = route.view;
|
||||
applyShellViewClass();
|
||||
|
||||
pane.className = 'vault-pane';
|
||||
|
||||
@@ -914,13 +979,15 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
if (!state.unlocked) return;
|
||||
|
||||
const route = parseHash();
|
||||
state.view = route.view;
|
||||
applyShellViewClass();
|
||||
|
||||
// If navigating to a detail/edit view for an item we already have loaded
|
||||
if ((route.view === 'detail' || route.view === 'edit') && route.id) {
|
||||
if (state.selectedId === route.id && state.selectedItem) {
|
||||
renderPane();
|
||||
renderSidebarCategories();
|
||||
renderListPane();
|
||||
if (state.view === 'list') renderListPane();
|
||||
return;
|
||||
}
|
||||
// Need to fetch the item
|
||||
@@ -932,7 +999,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
state.selectedId = null;
|
||||
state.selectedItem = null;
|
||||
renderSidebarCategories();
|
||||
renderListPane();
|
||||
if (state.view === 'list') renderListPane();
|
||||
renderPane();
|
||||
});
|
||||
});
|
||||
|
||||
81
tools/relay/call.py
Normal file
81
tools/relay/call.py
Normal file
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
CLI shim: call a relay MCP tool via raw SSE protocol.
|
||||
Usage:
|
||||
python3 call.py read_messages '{"for":"pm"}'
|
||||
python3 call.py post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
|
||||
python3 call.py list_pending '{"for":"pm"}'
|
||||
"""
|
||||
import sys, json, threading, requests, time
|
||||
|
||||
BASE = "http://localhost:7331"
|
||||
tool_name = sys.argv[1]
|
||||
args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
|
||||
|
||||
result = {"done": False, "value": None}
|
||||
endpoint_url = {"url": None}
|
||||
msg_id = 1
|
||||
|
||||
def read_sse():
|
||||
with requests.get(f"{BASE}/sse", stream=True, timeout=15) as r:
|
||||
for line in r.iter_lines(decode_unicode=True):
|
||||
if not line:
|
||||
continue
|
||||
if line.startswith("data:"):
|
||||
data = line[5:].strip()
|
||||
if not endpoint_url["url"] and data.startswith("/message"):
|
||||
endpoint_url["url"] = BASE + data
|
||||
elif endpoint_url["url"]:
|
||||
try:
|
||||
payload = json.loads(data)
|
||||
if payload.get("id") == msg_id:
|
||||
result["value"] = payload
|
||||
result["done"] = True
|
||||
return
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
t = threading.Thread(target=read_sse, daemon=True)
|
||||
t.start()
|
||||
|
||||
# Wait for endpoint
|
||||
for _ in range(50):
|
||||
if endpoint_url["url"]:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if not endpoint_url["url"]:
|
||||
print(json.dumps({"error": "no endpoint received"}))
|
||||
sys.exit(1)
|
||||
|
||||
# Send initialize
|
||||
init_payload = {
|
||||
"jsonrpc": "2.0", "id": 0, "method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "relay-cli", "version": "0.1.0"}
|
||||
}
|
||||
}
|
||||
requests.post(endpoint_url["url"], json=init_payload, timeout=5)
|
||||
|
||||
# Send tools/call
|
||||
call_payload = {
|
||||
"jsonrpc": "2.0", "id": msg_id, "method": "tools/call",
|
||||
"params": {"name": tool_name, "arguments": args}
|
||||
}
|
||||
requests.post(endpoint_url["url"], json=call_payload, timeout=5)
|
||||
|
||||
# Wait for result
|
||||
for _ in range(100):
|
||||
if result["done"]:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
if result["done"]:
|
||||
content = result["value"].get("result", {}).get("content", [])
|
||||
for item in content:
|
||||
if item.get("type") == "text":
|
||||
print(item["text"])
|
||||
else:
|
||||
print(json.dumps({"error": "timeout waiting for response"}))
|
||||
sys.exit(1)
|
||||
25
tools/relay/call.ts
Normal file
25
tools/relay/call.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* CLI shim: call a relay MCP tool from bash.
|
||||
* Usage:
|
||||
* npx tsx call.ts read_messages '{"for":"pm"}'
|
||||
* npx tsx call.ts post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
|
||||
* npx tsx call.ts list_pending '{"for":"pm"}'
|
||||
*/
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
|
||||
const [, , toolName, argsJson] = process.argv;
|
||||
if (!toolName) {
|
||||
console.error("Usage: call.ts <tool_name> <args_json>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const args = argsJson ? JSON.parse(argsJson) : {};
|
||||
const url = new URL("http://localhost:7331/sse");
|
||||
const transport = new SSEClientTransport(url);
|
||||
const client = new Client({ name: "relay-cli", version: "0.1.0" }, { capabilities: {} });
|
||||
|
||||
await client.connect(transport);
|
||||
const result = await client.callTool({ name: toolName, arguments: args });
|
||||
console.log(JSON.stringify(result));
|
||||
await client.close();
|
||||
@@ -51,7 +51,8 @@ describe("RelayQueue", () => {
|
||||
assert.ok(isRole("pm"));
|
||||
assert.ok(isRole("dev-a"));
|
||||
assert.ok(isRole("dev-b"));
|
||||
assert.ok(!isRole("dev-c"));
|
||||
assert.ok(isRole("dev-c"));
|
||||
assert.ok(!isRole("dev-d"));
|
||||
assert.ok(!isRole(""));
|
||||
assert.ok(!isRole("PM"));
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export type Role = "pm" | "dev-a" | "dev-b";
|
||||
export type Role = "pm" | "dev-a" | "dev-b" | "dev-c";
|
||||
export type MessageKind = "status" | "question" | "directive" | "free";
|
||||
|
||||
export interface RelayMessage {
|
||||
@@ -12,7 +12,7 @@ export interface RelayMessage {
|
||||
ts: string;
|
||||
}
|
||||
|
||||
const KNOWN_ROLES = new Set<string>(["pm", "dev-a", "dev-b"]);
|
||||
const KNOWN_ROLES = new Set<string>(["pm", "dev-a", "dev-b", "dev-c"]);
|
||||
|
||||
export function isRole(s: string): s is Role {
|
||||
return KNOWN_ROLES.has(s);
|
||||
@@ -23,6 +23,7 @@ export class RelayQueue {
|
||||
["pm", []],
|
||||
["dev-a", []],
|
||||
["dev-b", []],
|
||||
["dev-c", []],
|
||||
]);
|
||||
|
||||
post(from: Role, to: Role, kind: MessageKind, body: string): RelayMessage {
|
||||
|
||||
@@ -10,11 +10,6 @@ import { RelayQueue, isRole } from "./queue.ts";
|
||||
const PORT = 7331;
|
||||
const queue = new RelayQueue();
|
||||
|
||||
const mcpServer = new Server(
|
||||
{ name: "relay", version: "0.1.0" },
|
||||
{ capabilities: { tools: {} } }
|
||||
);
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "post_message",
|
||||
@@ -25,12 +20,12 @@ const TOOLS = [
|
||||
properties: {
|
||||
from: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
enum: ["pm", "dev-a", "dev-b", "dev-c"],
|
||||
description: "Your role name",
|
||||
},
|
||||
to: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
enum: ["pm", "dev-a", "dev-b", "dev-c"],
|
||||
description: "Recipient role name",
|
||||
},
|
||||
kind: {
|
||||
@@ -55,7 +50,7 @@ const TOOLS = [
|
||||
properties: {
|
||||
for: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
enum: ["pm", "dev-a", "dev-b", "dev-c"],
|
||||
description: "Your role name",
|
||||
},
|
||||
},
|
||||
@@ -71,7 +66,7 @@ const TOOLS = [
|
||||
properties: {
|
||||
for: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
enum: ["pm", "dev-a", "dev-b", "dev-c"],
|
||||
description: "Your role name",
|
||||
},
|
||||
},
|
||||
@@ -80,41 +75,36 @@ const TOOLS = [
|
||||
},
|
||||
];
|
||||
|
||||
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
||||
|
||||
mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
const a = args as Record<string, string>;
|
||||
|
||||
function handleToolCall(name: string, args: Record<string, string>) {
|
||||
if (name === "post_message") {
|
||||
if (!isRole(a.from)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.from}"` }], isError: true };
|
||||
if (!isRole(args.from)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${args.from}"` }], isError: true };
|
||||
}
|
||||
if (!isRole(a.to)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.to}"` }], isError: true };
|
||||
if (!isRole(args.to)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${args.to}"` }], isError: true };
|
||||
}
|
||||
const kind = a.kind as "status" | "question" | "directive" | "free";
|
||||
const msg = queue.post(a.from, a.to, kind, a.body);
|
||||
const kind = args.kind as "status" | "question" | "directive" | "free";
|
||||
const msg = queue.post(args.from, args.to, kind, args.body);
|
||||
const ts = new Date(msg.ts).toTimeString().slice(0, 8);
|
||||
const preview = a.body.slice(0, 60).replace(/\n/g, " ");
|
||||
const ellipsis = a.body.length > 60 ? "..." : "";
|
||||
process.stdout.write(`[${ts}] ${a.from} → ${a.to} [${kind}] "${preview}${ellipsis}"\n`);
|
||||
const preview = args.body.slice(0, 60).replace(/\n/g, " ");
|
||||
const ellipsis = args.body.length > 60 ? "..." : "";
|
||||
process.stdout.write(`[${ts}] ${args.from} → ${args.to} [${kind}] "${preview}${ellipsis}"\n`);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify({ id: msg.id }) }] };
|
||||
}
|
||||
|
||||
if (name === "read_messages") {
|
||||
if (!isRole(a.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true };
|
||||
if (!isRole(args.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${args.for}"` }], isError: true };
|
||||
}
|
||||
const messages = queue.read(a.for);
|
||||
const messages = queue.read(args.for);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify(messages) }] };
|
||||
}
|
||||
|
||||
if (name === "list_pending") {
|
||||
if (!isRole(a.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true };
|
||||
if (!isRole(args.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${args.for}"` }], isError: true };
|
||||
}
|
||||
const result = queue.pending(a.for);
|
||||
const result = queue.pending(args.for);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
|
||||
}
|
||||
|
||||
@@ -122,7 +112,20 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
content: [{ type: "text" as const, text: `Error: unknown tool "${name}"` }],
|
||||
isError: true,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function makeServer() {
|
||||
const srv = new Server(
|
||||
{ name: "relay", version: "0.1.0" },
|
||||
{ capabilities: { tools: {} } }
|
||||
);
|
||||
srv.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
||||
srv.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
return handleToolCall(name, args as Record<string, string>);
|
||||
});
|
||||
return srv;
|
||||
}
|
||||
|
||||
const transports = new Map<string, SSEServerTransport>();
|
||||
|
||||
@@ -132,7 +135,8 @@ const httpServer = http.createServer(async (req, res) => {
|
||||
const transport = new SSEServerTransport("/message", res);
|
||||
transports.set(transport.sessionId, transport);
|
||||
transport.onclose = () => transports.delete(transport.sessionId);
|
||||
await mcpServer.connect(transport);
|
||||
// Each connection gets its own Server instance so multiple clients can coexist.
|
||||
await makeServer().connect(transport);
|
||||
} else if (req.method === "POST" && req.url?.startsWith("/message")) {
|
||||
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
@@ -31,6 +31,7 @@ COORD_DIR="$REPO_ROOT/docs/superpowers/coordination"
|
||||
PM_PROMPT="$(ls -t "$COORD_DIR"/*-pm-prompt.md 2>/dev/null | head -1 || echo "(none found — run multi-agent-kickoff skill first)")"
|
||||
DEV_A_PROMPT="$(ls -t "$COORD_DIR"/*-dev-a-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
DEV_B_PROMPT="$(ls -t "$COORD_DIR"/*-dev-b-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
DEV_C_PROMPT="$(ls -t "$COORD_DIR"/*-dev-c-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
|
||||
print_manual_instructions() {
|
||||
echo ""
|
||||
@@ -38,12 +39,13 @@ print_manual_instructions() {
|
||||
echo "║ RELAY SERVER — MULTI-AGENT LIFT LAUNCHER ║"
|
||||
echo "╚══════════════════════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
echo "Open 3 new terminals. In each, start Claude Code and paste"
|
||||
echo "Open 4 new terminals. In each, start Claude Code and paste"
|
||||
echo "the content BELOW the '---' line from the corresponding file."
|
||||
echo ""
|
||||
echo " Terminal 1 (PM): cat '$PM_PROMPT'"
|
||||
echo " Terminal 2 (Dev A): cat '$DEV_A_PROMPT'"
|
||||
echo " Terminal 3 (Dev B): cat '$DEV_B_PROMPT'"
|
||||
echo " Terminal 4 (Dev C): cat '$DEV_C_PROMPT'"
|
||||
echo ""
|
||||
echo "This terminal becomes the relay log. Keep it open."
|
||||
echo ""
|
||||
@@ -57,32 +59,37 @@ launch_tmux() {
|
||||
tmux new-window -t "$SESSION:" -n "pm" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-a" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-b" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-c" "cd '$REPO_ROOT' && claude"
|
||||
echo ""
|
||||
echo "[relay] Opened tmux session '$SESSION' with 4 windows: relay, pm, dev-a, dev-b."
|
||||
echo "[relay] Opened tmux session '$SESSION' with 5 windows: relay, pm, dev-a, dev-b, dev-c."
|
||||
echo "[relay] Paste the kickoff prompt into each Claude window."
|
||||
echo " Prompts:"
|
||||
echo " PM: $PM_PROMPT"
|
||||
echo " Dev A: $DEV_A_PROMPT"
|
||||
echo " Dev B: $DEV_B_PROMPT"
|
||||
echo " Dev C: $DEV_C_PROMPT"
|
||||
echo ""
|
||||
tmux attach-session -t "$SESSION"
|
||||
}
|
||||
|
||||
launch_kitty() {
|
||||
kitty @ launch --new-tab --tab-title "relay" -- \
|
||||
kitty @ launch --type=tab --tab-title "relay" -- \
|
||||
bash -c "cd '$SCRIPT_DIR' && npx tsx server.ts"
|
||||
kitty @ launch --new-window --window-title "PM" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --new-window --window-title "Dev-A" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --new-window --window-title "Dev-B" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --type=tab --tab-title "PM" --hold -- \
|
||||
bash -l -i -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --type=tab --tab-title "Dev-A" --hold -- \
|
||||
bash -l -i -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --type=tab --tab-title "Dev-B" --hold -- \
|
||||
bash -l -i -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --type=tab --tab-title "Dev-C" --hold -- \
|
||||
bash -l -i -c "cd '$REPO_ROOT' && claude"
|
||||
echo ""
|
||||
echo "[relay] Opened kitty tab 'relay' + 3 windows (PM, Dev-A, Dev-B)."
|
||||
echo "[relay] Opened kitty tab 'relay' + 4 windows (PM, Dev-A, Dev-B, Dev-C)."
|
||||
echo " Paste the kickoff prompts into each Claude window."
|
||||
echo " PM: $PM_PROMPT"
|
||||
echo " Dev A: $DEV_A_PROMPT"
|
||||
echo " Dev B: $DEV_B_PROMPT"
|
||||
echo " Dev C: $DEV_C_PROMPT"
|
||||
}
|
||||
|
||||
case "$MODE" in
|
||||
|
||||
Reference in New Issue
Block a user