1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Server-global **workspace registry** — the persistent index of every
//! workspace the `nornir` server tracks.
//!
//! This is the index the self-sync poll loop updates, `nornir workspace ls`
//! reads, and (next phase) the `Workspaces.*` gRPC service / viz picker query.
//! It is distinct from a *warehouse* (one per workspace, under `builds/`) and
//! from a [`crate::workspace::WorkspaceDescriptor`] (the per-workspace
//! `nornir-workspace.toml` that lists members) — the registry just *indexes*
//! those, keyed by workspace name.
//!
//! **Storage:** a single redb file at `<server.root>/registry.redb`. redb
//! stores **bytes**, not structs, so each row is `workspace_name (&str) →`
//! the [`Workspace`] record serialized with serde_json. The server is the sole
//! writer, matching the redb/iceberg single-writer discipline used for the
//! warehouse.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use redb::{Database, ReadableTable, TableDefinition};
use serde::{Deserialize, Serialize};
/// `name → serde_json(Workspace)`. Bytes in, bytes out.
const TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("workspaces");
/// How a workspace's source is provided.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
/// Server polls member git URLs and republishes (server-user `nornir`).
Monitored,
/// A thin client pushes its working-tree source in; server computes.
Pushed,
/// Sources live outside (fat-style external checkout); only `builds/` is
/// server-owned and `git/` stays empty.
External,
}
impl Mode {
pub fn as_str(&self) -> &'static str {
match self {
Mode::Monitored => "monitored",
Mode::Pushed => "pushed",
Mode::External => "external",
}
}
/// Parse a mode string; anything unrecognized ⇒ [`Mode::Pushed`].
pub fn parse(s: &str) -> Self {
match s {
"monitored" => Mode::Monitored,
"external" => Mode::External,
_ => Mode::Pushed,
}
}
}
/// Per-member sync state (meaningful in [`Mode::Monitored`]).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MemberState {
pub name: String,
/// Git URL fetched/polled (mirrors `RepoSpec.git`).
pub remote: String,
/// Tracked ref/branch; empty ⇒ `main`.
pub git_ref: String,
/// Last SHA seen via `git ls-remote`; empty ⇒ never polled.
pub last_seen_sha: String,
/// RFC3339 of the last successful fetch; empty ⇒ never.
pub last_synced: String,
/// `"ok"` | `"fetching"` | `"error: …"` | "".
pub sync_state: String,
/// Working-tree freshness of the server's clone (AUT6). The SHA above can
/// only see *committed* state; this digest sees uncommitted edits too. A
/// thin client compares its own local digest against this to flag staleness.
/// Equals [`crate::gitio::CLEAN_WORKTREE_DIGEST`] when the clone is clean;
/// empty ⇒ never computed. See [`crate::gitio::worktree_freshness`].
#[serde(default)]
pub worktree_digest: String,
/// `true` ⇒ the server's clone has uncommitted changes (tracked mods, staged,
/// or untracked). Mirrors `worktree_digest != CLEAN_WORKTREE_DIGEST`.
#[serde(default)]
pub worktree_dirty: bool,
}
/// One registry row: a workspace the server tracks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workspace {
pub name: String,
pub mode: Mode,
/// Seed: a local path or git URL to the workspace's `nornir-workspace.toml`.
pub descriptor: String,
/// Poll interval for monitored workspaces, e.g. `"60s"`; empty ⇒ default.
pub poll: String,
/// Iceberg snapshot id the warehouse currently publishes; empty ⇒ none yet.
pub current_snapshot: String,
pub members: Vec<MemberState>,
/// The descriptor's raw TOML **content**, stored IN the registry so the row is
/// the self-contained source of truth — the server re-reads `deep_scan`/members
/// from here, never a sibling `descriptors/*.toml` file. Empty for a git-URL
/// seed whose content isn't known until first fetch. `#[serde(default)]` so rows
/// written before this field round-trip cleanly.
#[serde(default)]
pub descriptor_content: String,
pub created_at: String,
pub updated_at: String,
}
impl Workspace {
/// Build a record, seeding members from a local `nornir-workspace.toml`
/// descriptor when it exists (each repo's `git` + `branch` →
/// `remote`/`git_ref`; `path`-only members get an empty remote). A git-URL
/// descriptor (not a local path) yields an empty member list until first
/// fetch. Pass `created_at` to preserve it across a re-register.
pub fn new(
name: String,
descriptor: String,
mode: Mode,
poll: String,
created_at: Option<String>,
) -> Self {
// Read the descriptor FILE when the seed is a local path, capturing its raw
// content into the row so the registry — not the file — is the source of
// truth thereafter (a git-URL seed leaves both empty until first fetch).
let mut members = Vec::new();
let mut content = String::new();
let dpath = std::path::Path::new(&descriptor);
if dpath.exists()
&& let Ok(text) = std::fs::read_to_string(dpath)
{
if let Ok(desc) = crate::workspace::WorkspaceDescriptor::from_content(&text) {
members = Self::members_from(&desc);
}
content = text;
}
Self::assemble(name, descriptor, content, mode, poll, members, created_at)
}
/// Build a record from descriptor **content** (thin-mode: the client shipped the
/// TOML). Members come from the content and the content itself is stored in the
/// row — nothing touches disk, so no `descriptors/*.toml` file is needed.
pub fn from_content(
name: String,
descriptor: String,
content: String,
mode: Mode,
poll: String,
created_at: Option<String>,
) -> Self {
let members = crate::workspace::WorkspaceDescriptor::from_content(&content)
.map(|d| Self::members_from(&d))
.unwrap_or_default();
Self::assemble(name, descriptor, content, mode, poll, members, created_at)
}
fn members_from(desc: &crate::workspace::WorkspaceDescriptor) -> Vec<MemberState> {
desc.repos
.iter()
.map(|(mname, spec)| MemberState {
name: mname.clone(),
remote: spec.git.clone().unwrap_or_default(),
git_ref: spec.branch.clone().unwrap_or_default(),
..Default::default()
})
.collect()
}
#[allow(clippy::too_many_arguments)]
fn assemble(
name: String,
descriptor: String,
descriptor_content: String,
mode: Mode,
poll: String,
members: Vec<MemberState>,
created_at: Option<String>,
) -> Self {
let now = chrono::Utc::now().to_rfc3339();
Workspace {
name,
mode,
descriptor,
poll,
current_snapshot: String::new(),
members,
descriptor_content,
created_at: created_at.unwrap_or_else(|| now.clone()),
updated_at: now,
}
}
}
/// The redb-backed registry. Open once; cheap to clone-free reuse.
pub struct Registry {
db: Database,
/// The server root the registry lives under (`<root>/registry.redb`). Each
/// workspace's on-disk build data sits beside it at `<root>/<name>/builds/`;
/// [`Registry::remove`] resolves that from here when purging.
root: PathBuf,
}
impl Registry {
/// Open (creating if absent) the registry at `<root>/registry.redb`.
pub fn open(root: &Path) -> Result<Self> {
std::fs::create_dir_all(root)
.with_context(|| format!("create registry root {}", root.display()))?;
let path = root.join("registry.redb");
let db = Database::create(&path)
.with_context(|| format!("open {}", path.display()))?;
// Materialize the table so first-time reads don't fail.
let w = db.begin_write()?;
{
let _ = w.open_table(TABLE)?;
}
w.commit()?;
Ok(Self { db, root: root.to_path_buf() })
}
/// The on-disk `builds/` dir for `name` (`<root>/<name>/builds`): the
/// per-workspace warehouse + `catalog.redb` + `jobs.redb`. Resolving it here (off
/// the registry root) keeps the layout in one place for the purge path.
pub fn builds_dir(&self, name: &str) -> PathBuf {
self.root.join(name).join("builds")
}
/// Insert or replace a workspace row.
pub fn upsert(&self, ws: &Workspace) -> Result<()> {
let bytes = serde_json::to_vec(ws).context("encode workspace record")?;
let w = self.db.begin_write()?;
{
let mut t = w.open_table(TABLE)?;
t.insert(ws.name.as_str(), bytes.as_slice())?;
}
w.commit()?;
Ok(())
}
/// Fetch one workspace by name.
pub fn get(&self, name: &str) -> Result<Option<Workspace>> {
let r = self.db.begin_read()?;
let t = r.open_table(TABLE)?;
match t.get(name)? {
Some(v) => Ok(Some(
serde_json::from_slice(v.value()).context("decode workspace record")?,
)),
None => Ok(None),
}
}
/// All workspaces, in key (name) order.
pub fn list(&self) -> Result<Vec<Workspace>> {
let r = self.db.begin_read()?;
let t = r.open_table(TABLE)?;
let mut out = Vec::new();
for row in t.iter()? {
let (_k, v) = row?;
out.push(serde_json::from_slice(v.value()).context("decode workspace record")?);
}
Ok(out)
}
/// Remove a workspace; returns whether the registry row existed.
///
/// This is the **shared core** both faces land on: the CLI `nornir workspace rm`
/// (locally, or via the `Workspaces.Remove` RPC) and the viz "🗑 Kill workspace"
/// confirm (always via the RPC) both call here, so the purge semantics are fixed
/// once, not per-face.
///
/// - `purge == false` (default, back-compat): drop ONLY the registry row. The
/// workspace's `builds/` warehouse stays on disk.
/// - `purge == true`: after dropping the row, also `remove_dir_all` the
/// workspace's [`builds_dir`](Self::builds_dir) (`<root>/<name>/builds/` —
/// warehouse + `catalog.redb` + `jobs.redb`), so the workspace is fully gone. A
/// missing builds dir is a no-op; the registry row is already removed by then.
pub fn remove(&self, name: &str, purge: bool) -> Result<bool> {
let w = self.db.begin_write()?;
let existed = {
let mut t = w.open_table(TABLE)?;
let removed = t.remove(name)?.is_some();
removed
};
w.commit()?;
if existed && purge {
let builds = self.builds_dir(name);
if builds.exists() {
std::fs::remove_dir_all(&builds)
.with_context(|| format!("purge builds dir {}", builds.display()))?;
}
}
Ok(existed)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rec(name: &str, mode: Mode) -> Workspace {
Workspace {
name: name.into(),
mode,
descriptor: "/tmp/ws/nornir-workspace.toml".into(),
poll: "60s".into(),
current_snapshot: String::new(),
members: vec![MemberState {
name: "holger".into(),
remote: "git@codeberg.org:nordisk/holger".into(),
git_ref: "main".into(),
..Default::default()
}],
descriptor_content: String::new(),
created_at: "2026-06-08T00:00:00Z".into(),
updated_at: "2026-06-08T00:00:00Z".into(),
}
}
#[test]
fn roundtrip_upsert_get_list_remove() {
let dir = std::env::temp_dir().join(format!("nornir-reg-{}", std::process::id()));
let reg = Registry::open(&dir).unwrap();
assert!(reg.get("a").unwrap().is_none());
reg.upsert(&rec("a", Mode::Monitored)).unwrap();
reg.upsert(&rec("b", Mode::Pushed)).unwrap();
let a = reg.get("a").unwrap().unwrap();
assert_eq!(a.mode, Mode::Monitored);
assert_eq!(a.members[0].remote, "git@codeberg.org:nordisk/holger");
let all = reg.list().unwrap();
assert_eq!(all.len(), 2);
assert_eq!(all[0].name, "a"); // key order
assert!(reg.remove("a", false).unwrap());
assert!(!reg.remove("a", false).unwrap());
assert_eq!(reg.list().unwrap().len(), 1);
std::fs::remove_dir_all(&dir).ok();
}
/// INJECT-ASSERT: the shared purge core. `remove(.., true)` deletes the
/// workspace's `<root>/<name>/builds/` dir; `remove(.., false)` leaves it (the
/// back-compat registry-only path). Resolution is off the registry root.
#[test]
fn remove_purge_deletes_builds_dir_non_purge_leaves_it() {
let dir = std::env::temp_dir().join(format!("nornir-purge-{}", std::process::id()));
std::fs::remove_dir_all(&dir).ok();
let reg = Registry::open(&dir).unwrap();
// Two workspaces, each with an on-disk builds/ tree holding warehouse files.
for ws in ["keep", "nuke"] {
reg.upsert(&rec(ws, Mode::Pushed)).unwrap();
let builds = reg.builds_dir(ws);
std::fs::create_dir_all(builds.join("warehouse")).unwrap();
std::fs::write(builds.join("catalog.redb"), b"x").unwrap();
std::fs::write(builds.join("jobs.redb"), b"y").unwrap();
assert!(builds.exists());
}
// Non-purge: row gone, builds/ stays.
assert!(reg.remove("keep", false).unwrap());
assert!(reg.get("keep").unwrap().is_none());
assert!(reg.builds_dir("keep").exists(), "non-purge must leave builds/");
// Purge: row gone AND builds/ removed.
assert!(reg.remove("nuke", true).unwrap());
assert!(reg.get("nuke").unwrap().is_none());
assert!(!reg.builds_dir("nuke").exists(), "purge must remove builds/");
// Purge of a missing builds dir is a no-op (row already gone ⇒ false).
assert!(!reg.remove("nuke", true).unwrap());
std::fs::remove_dir_all(&dir).ok();
}
}
/// One row of the `workspace ls` roster — the projection BOTH the fat (registry
/// [`Workspace`]) and thin (proto) faces map into, so they render identically
/// (CLI⟺UI parity, the Nornir-tab roster's data). AUT9.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct RosterRow {
pub name: String,
pub mode: String,
pub members: usize,
pub last_synced: String,
/// PO1 — the rolled-up POPULATE verdict for this workspace (latest clone/fetch
/// outcome per member → a workspace state). `"green"` (all members' latest ok),
/// `"red"` (≥1 member's latest is an error), `"stale"` (never populated — no
/// clone_events), or `""` when the populate roll-up wasn't requested
/// (`workspace ls` without `--status`). The roster's red/green badge.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub populate: String,
/// The first failing member (when `populate == "red"`), else empty.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub failing_member: String,
/// That member's latest error detail (when `populate == "red"`), else empty.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub last_error: String,
}
/// `workspace ls` as a uniform [`crate::cli_outcome::CommandOutcome`] — the CLI twin
/// of the Nornir-tab workspace roster. `rows` are already projected from the
/// canonical source (fat: `Registry::list`; thin: `Workspaces.List` RPC) — this only
/// shapes + renders. `ok ⟺ ≥1 workspace` (an empty registry is a valid resting state
/// for a user, but for the autopilot a seeded-then-empty roster is RED).
pub fn roster_outcome(rows: &[RosterRow]) -> crate::cli_outcome::CommandOutcome {
use crate::cli_outcome::CommandOutcome;
if rows.is_empty() {
return CommandOutcome::fail(
"workspace ls",
"no workspaces registered — `nornir workspace register …`",
);
}
// PO1: show the POPULATE column only when at least one row carries a verdict
// (i.e. `--status` was passed / the viz roster requested the roll-up).
let has_populate = rows.iter().any(|r| !r.populate.is_empty());
let mut human = if has_populate {
format!(
"{:<20} {:<10} {:>7} {:<22} {:<8} {}",
"NAME", "MODE", "MEMBERS", "LAST SYNCED", "POPULATE", "LAST ERROR"
)
} else {
format!("{:<20} {:<10} {:>7} {}", "NAME", "MODE", "MEMBERS", "LAST SYNCED")
};
for r in rows {
if has_populate {
let mark = match r.populate.as_str() {
"green" => "✓ ok",
"red" => "✗ failed",
"stale" => "· stale",
_ => "—",
};
let err = if r.failing_member.is_empty() {
String::new()
} else {
format!("{}: {}", r.failing_member, r.last_error)
};
human.push_str(&format!(
"\n{:<20} {:<10} {:>7} {:<22} {:<8} {}",
r.name, r.mode, r.members, r.last_synced, mark, err
));
} else {
human.push_str(&format!(
"\n{:<20} {:<10} {:>7} {}",
r.name, r.mode, r.members, r.last_synced
));
}
}
CommandOutcome::ok("workspace ls", serde_json::json!(rows), human)
}
#[cfg(test)]
mod roster_outcome_tests {
use super::*;
#[test]
fn empty_registry_roster_is_red() {
let o = roster_outcome(&[]);
assert_eq!(o.command, "workspace ls");
assert!(!o.is_sannr(), "an empty roster is RED for the autopilot");
}
#[test]
fn populated_roster_is_sannr_with_rows() {
let rows = vec![
RosterRow { name: "nordisk".into(), mode: "monitored".into(), members: 8, last_synced: "2026-06-23".into(), ..Default::default() },
RosterRow { name: "holger".into(), mode: "local".into(), members: 1, last_synced: "never".into(), ..Default::default() },
];
let o = roster_outcome(&rows);
assert!(o.is_sannr(), "a populated roster is a true (sannr) outcome");
let arr = o.data.as_array().unwrap();
assert_eq!(arr.len(), 2);
assert_eq!(arr[0]["name"], serde_json::json!("nordisk"));
assert_eq!(arr[0]["members"], serde_json::json!(8));
}
/// PO1 (inject-assert): a roster with a RED workspace (a failing member) and a
/// GREEN workspace renders the verdicts + names the failing member in the
/// human view, and carries them in the JSON data. The CLI twin of the
/// Nornir-tab roster's red/green badge.
#[test]
fn roster_with_populate_verdicts_shows_red_and_failing_member() {
let rows = vec![
RosterRow {
name: "nordisk".into(),
mode: "monitored".into(),
members: 8,
last_synced: "2026-06-23".into(),
populate: "red".into(),
failing_member: "korp".into(),
last_error: "Couldn't obtain Username".into(),
},
RosterRow {
name: "holger".into(),
mode: "monitored".into(),
members: 2,
last_synced: "2026-06-23".into(),
populate: "green".into(),
..Default::default()
},
];
let o = roster_outcome(&rows);
assert!(o.is_sannr());
// JSON carries the verdict + failing member for the failed workspace.
let arr = o.data.as_array().unwrap();
let nordisk = arr.iter().find(|r| r["name"] == "nordisk").unwrap();
assert_eq!(nordisk["populate"], "red");
assert_eq!(nordisk["failing_member"], "korp");
assert!(nordisk["last_error"].as_str().unwrap().contains("Couldn't obtain Username"));
let holger = arr.iter().find(|r| r["name"] == "holger").unwrap();
assert_eq!(holger["populate"], "green");
// A green workspace omits the failing-member/error keys (skip_serializing_if).
assert!(holger.get("failing_member").is_none());
// The human render shows the POPULATE column + names the failing member.
assert!(o.human.contains("POPULATE"), "populate column shown: {}", o.human);
assert!(o.human.contains("✗ failed"));
assert!(o.human.contains("korp: Couldn't obtain Username"));
}
}