prikk 0.18.1

Prikk CLI initial scaffold.
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
//! `prikk branch` — list, create, and close local branch refs.
//!
//! Branch creation already exists: `commit --ref heads/topic` followed by `seal --ref heads/topic`
//! creates an unborn branch as a signed Root block at `update_seq = 1` (DC-13 Non-Default Ref
//! Genesis). `branch create --from` must publish the *same* ref-state shape DC-13's genesis
//! publishes — maintainer-signed, `RefKind::Branch`, `update_seq = 1`,
//! `previous_ref_state_id = None` for a name with no surviving log — so a branch is
//! indistinguishable afterward regardless of which path created it. The only permitted
//! difference is the target: DC-13 seals a block it just created; this points at a block that
//! already exists.
//!
//! **`branch close` (DC-61) is closure, not deletion.** Nothing is removed: the pointer, its
//! history, and every object stay. Closure publishes a final ref state carrying the `closed`
//! field (`RefStatePayload` tag 7, schema 2). DC-60 tried deletion (removing the pointer while
//! keeping the log); that produced "pointer absent, log present," a state the system does not
//! merely classify as corruption but has a *repair function* for
//! (`RefStore::recoverable_missing_ref` / `doctor`'s `reconstruct_missing_ref_from_log`), so
//! `doctor` would have offered to resurrect every deleted branch, and it also bricked
//! repository-wide commits at every record count
//! (`.git-exclude/reviewed/prikk-dc60-delete-divergence-ruling-v1.md`). Closure leaves the pointer
//! present, so `verify`, `publish`, `recoverable_missing_ref`, and `doctor` all take their ordinary
//! paths — no new state, no new arm, nothing to repair.
//!
//! **Reopening a closed branch is an ordinary CAS update** (publish a new ref state without the
//! `closed` field) and is permitted, but this increment does not add a `branch reopen` CLI verb —
//! the command surface DC-61 specifies is `close` and `list --all` only. The capability is
//! exercised directly against `RefStore::publish` in the test suite.
//!
//! No current-branch pointer/`switch`: see the module-level non-goal in the accepted RFC (DC-60).
//! Every command still resolves `--ref` exactly as before.

use std::path::PathBuf;

use prikk_error::PrikkError;
use prikk_object::{
    CanonicalEncode, ObjectEnvelope, ObjectId, ObjectType, RefKind, RefStatePayload,
    RefUpdatePayload,
};
use prikk_store::{
    DEFAULT_CHECKOUT_REF, FileObjectStore, MaintainerSigner, RefPublication, RefStore, Wal,
    maintainer_signature, require_active_ref_for_non_empty_wal, validate_local_branch_ref,
};

/// Envelope schema version for a `RefState` carrying no `closed` field (every ordinary
/// publication: create, seal-genesis, and reopening alike).
const REF_STATE_SCHEMA_OPEN: u32 = 1;
/// Envelope schema version for a `RefState` whose `closed` field is present (DC-61).
const REF_STATE_SCHEMA_CLOSED: u32 = 2;

/// Dispatch `prikk branch [list|create|close]`.
pub fn run_branch(root: PathBuf, args: Vec<String>) -> std::result::Result<(), String> {
    let mut iter = args.into_iter();
    let first = iter.next();
    match first.as_deref() {
        None | Some("list") => run_list(root, iter.collect()),
        Some("create") => run_create(root, iter.collect()),
        Some("close") => run_close(root, iter.collect()),
        // No explicit subcommand keyword: a leading flag (e.g. bare `prikk branch --all`) is an
        // argument to the implicit default, `list` — the same default `None` above already takes.
        Some(flag) if flag.starts_with('-') => {
            let mut rest = vec![flag.to_string()];
            rest.extend(iter);
            run_list(root, rest)
        }
        Some(other) => Err(format!(
            "unknown branch subcommand: {other} (expected list, create, or close)"
        )),
    }
}

fn run_list(root: PathBuf, args: Vec<String>) -> std::result::Result<(), String> {
    let mut show_all = false;
    for arg in args {
        match arg.as_str() {
            "--all" => show_all = true,
            other => return Err(format!("unknown branch list argument: {other}")),
        }
    }
    let layout = crate::open_repository(root)?;
    let ref_store = RefStore::new(layout.clone());
    let object_store = FileObjectStore::new(layout);
    let entries = ref_store
        .list_ref_pointers()
        .map_err(|err| err.to_string())?;
    let mut printed_any = false;
    for entry in entries {
        let envelope = object_store
            .read_typed(entry.ref_state_id, ObjectType::RefState)
            .map_err(|err| err.to_string())?
            .ok_or_else(|| {
                format!(
                    "ref {} RefState {} is missing",
                    entry.ref_name, entry.ref_state_id
                )
            })?;
        let payload =
            RefStatePayload::decode_canonical(&envelope.canonical_payload, envelope.schema_version)
                .map_err(|err| err.to_string())?;
        if payload.closed && !show_all {
            continue;
        }
        if payload.closed {
            println!("{} {} (closed)", entry.ref_name, entry.ref_state_id);
        } else {
            println!("{} {}", entry.ref_name, entry.ref_state_id);
        }
        printed_any = true;
    }
    if !printed_any {
        println!("no branches");
    }
    Ok(())
}

fn run_create(root: PathBuf, args: Vec<String>) -> std::result::Result<(), String> {
    let parsed = parse_create_args(args)?;
    let layout = crate::open_repository(root)?;
    layout
        .require_current_format()
        .map_err(|err| err.to_string())?;
    let canonical = validate_local_branch_ref(&parsed.name).map_err(|err| err.to_string())?;
    let ref_store = RefStore::new(layout.clone());
    let object_store = FileObjectStore::new(layout.clone());

    if ref_store
        .read_current_ref_state_id(&canonical)
        .map_err(|err| err.to_string())?
        .is_some()
    {
        return Err(format!("branch {canonical} already exists"));
    }

    // A ref log can survive an interrupted publication with no live pointer. Creating over it
    // would produce the "pointer absent, log present" state that DC-61 exists to resolve with a
    // ref-log tombstone; `publish` would refuse anyway, but fail closed here with a clear message
    // rather than a generic classification failure.
    if ref_store
        .recoverable_missing_ref(&canonical)
        .map_err(|err| err.to_string())?
        .is_some()
    {
        return Err(format!(
            "branch {canonical} has a surviving ref log with no live pointer; resuming it is not \
             yet supported (see DC-61), and creating over it would produce a corrupt state"
        ));
    }

    let from_ref = parsed
        .from
        .unwrap_or_else(|| DEFAULT_CHECKOUT_REF.to_string());
    let target_object_id = resolve_published_target(&ref_store, &object_store, &from_ref)?;

    let signer = crate::maintainer_signer_from_env()?;
    let ref_state_payload = RefStatePayload {
        ref_name: canonical.clone(),
        kind: RefKind::Branch,
        target_object_id,
        update_seq: 1,
        previous_ref_state_id: None,
        required_attestation_ids: Vec::new(),
        closed: false,
    };
    let ref_state_envelope = signed_envelope(
        ObjectType::RefState,
        REF_STATE_SCHEMA_OPEN,
        ref_state_payload
            .to_canonical_bytes()
            .map_err(|err| err.to_string())?,
        &signer,
    )?;
    let ref_state_id = ref_state_envelope.object_id();
    let ref_update_payload = RefUpdatePayload {
        ref_name: canonical.clone(),
        old_ref_state_id: None,
        new_ref_state_id: ref_state_id,
        new_target_object_id: target_object_id,
        update_seq: 1,
        created_at: 0,
        author_key_id: signer.key_id().to_string(),
    };
    let ref_update_envelope = signed_envelope(
        ObjectType::RefUpdate,
        1,
        ref_update_payload
            .to_canonical_bytes()
            .map_err(|err| err.to_string())?,
        &signer,
    )?;
    let publication = RefPublication {
        ref_name: canonical.clone(),
        expected_previous_ref_state_id: None,
        ref_state: ref_state_envelope,
        ref_update: ref_update_envelope,
    };
    let published_ref_state_id = ref_store
        .publish(&publication)
        .map_err(|err| err.to_string())?;

    println!("created branch {canonical}");
    println!("target block: {target_object_id}");
    println!("RefState: {published_ref_state_id}");
    println!("update_seq: 1");
    Ok(())
}

fn run_close(root: PathBuf, args: Vec<String>) -> std::result::Result<(), String> {
    let mut name = None;
    for arg in args {
        if name.is_some() {
            return Err(format!(
                "branch close accepts at most one name, got extra: {arg}"
            ));
        }
        name = Some(arg);
    }
    let Some(name) = name else {
        return Err("branch close requires <name>".to_string());
    };

    let layout = crate::open_repository(root)?;
    layout
        .require_current_format()
        .map_err(|err| err.to_string())?;
    let canonical = validate_local_branch_ref(&name).map_err(|err| err.to_string())?;
    let ref_store = RefStore::new(layout.clone());
    let object_store = FileObjectStore::new(layout.clone());

    let Some(current_ref_state_id) = ref_store
        .read_current_ref_state_id(&canonical)
        .map_err(|err| err.to_string())?
    else {
        return Err(format!("branch {canonical} does not exist"));
    };
    let current_envelope = object_store
        .read_typed(current_ref_state_id, ObjectType::RefState)
        .map_err(|err| err.to_string())?
        .ok_or_else(|| format!("branch {canonical} RefState {current_ref_state_id} is missing"))?;
    let current_payload = RefStatePayload::decode_canonical(
        &current_envelope.canonical_payload,
        current_envelope.schema_version,
    )
    .map_err(|err| err.to_string())?;
    if current_payload.closed {
        return Err(format!("branch {canonical} is already closed"));
    }

    let replay = Wal::for_layout(&layout)
        .replay()
        .map_err(|err| err.to_string())?;
    if !replay.records.is_empty() {
        match require_active_ref_for_non_empty_wal(&layout, &canonical) {
            Ok(_) => {
                return Err(format!(
                    "cannot close {canonical}: it owns a non-empty active WAL; seal it before closing"
                ));
            }
            // Owned by a different ref: this branch's own active WAL is not implicated, so closing
            // it may proceed.
            Err(PrikkError::LockConflict(_)) => {}
            // Missing or malformed active-ref metadata on a non-empty WAL is an integrity condition,
            // not evidence this branch is uninvolved — fail closed like every other publisher
            // (`node_authoring.rs` propagates the same error via `?`) rather than treat "unknown
            // owner" as "not this branch."
            Err(err) => return Err(err.to_string()),
        }
    }

    let next_seq = current_payload
        .update_seq
        .checked_add(1)
        .ok_or_else(|| "ref-state update sequence overflow".to_string())?;

    let signer = crate::maintainer_signer_from_env()?;
    let ref_state_payload = RefStatePayload {
        ref_name: canonical.clone(),
        kind: current_payload.kind,
        target_object_id: current_payload.target_object_id,
        update_seq: next_seq,
        previous_ref_state_id: Some(current_ref_state_id),
        required_attestation_ids: current_payload.required_attestation_ids.clone(),
        closed: true,
    };
    let ref_state_envelope = signed_envelope(
        ObjectType::RefState,
        REF_STATE_SCHEMA_CLOSED,
        ref_state_payload
            .to_canonical_bytes()
            .map_err(|err| err.to_string())?,
        &signer,
    )?;
    let ref_state_id = ref_state_envelope.object_id();
    let ref_update_payload = RefUpdatePayload {
        ref_name: canonical.clone(),
        old_ref_state_id: Some(current_ref_state_id),
        new_ref_state_id: ref_state_id,
        new_target_object_id: current_payload.target_object_id,
        update_seq: next_seq,
        created_at: 0,
        author_key_id: signer.key_id().to_string(),
    };
    let ref_update_envelope = signed_envelope(
        ObjectType::RefUpdate,
        1,
        ref_update_payload
            .to_canonical_bytes()
            .map_err(|err| err.to_string())?,
        &signer,
    )?;
    let publication = RefPublication {
        ref_name: canonical.clone(),
        expected_previous_ref_state_id: Some(current_ref_state_id),
        ref_state: ref_state_envelope,
        ref_update: ref_update_envelope,
    };
    let published_ref_state_id = ref_store
        .publish(&publication)
        .map_err(|err| err.to_string())?;

    println!("closed branch {canonical}");
    println!("RefState: {published_ref_state_id}");
    println!(
        "nothing was reclaimed; the pointer, its history, and every object remain, and the branch is recoverable"
    );
    Ok(())
}

/// Resolve `--from`'s target block, requiring it to be a currently published ref.
fn resolve_published_target(
    ref_store: &RefStore,
    object_store: &FileObjectStore,
    from_ref: &str,
) -> std::result::Result<ObjectId, String> {
    let from_ref_state_id = ref_store
        .read_current_ref_state_id(from_ref)
        .map_err(|err| err.to_string())?
        .ok_or_else(|| format!("--from ref {from_ref} does not resolve to a published ref"))?;
    let from_envelope = object_store
        .read_typed(from_ref_state_id, ObjectType::RefState)
        .map_err(|err| err.to_string())?
        .ok_or_else(|| format!("--from ref {from_ref} RefState {from_ref_state_id} is missing"))?;
    let from_payload = RefStatePayload::decode_canonical(
        &from_envelope.canonical_payload,
        from_envelope.schema_version,
    )
    .map_err(|err| err.to_string())?;
    if from_payload.ref_name != from_ref {
        return Err(format!(
            "--from RefState name mismatch: expected {from_ref}, got {}",
            from_payload.ref_name
        ));
    }
    if object_store
        .read_typed(from_payload.target_object_id, ObjectType::Block)
        .map_err(|err| err.to_string())?
        .is_none()
    {
        return Err(format!(
            "--from ref {from_ref} targets missing block {}",
            from_payload.target_object_id
        ));
    }
    Ok(from_payload.target_object_id)
}

fn signed_envelope(
    object_type: ObjectType,
    schema_version: u32,
    canonical_payload: Vec<u8>,
    signer: &impl MaintainerSigner,
) -> std::result::Result<ObjectEnvelope, String> {
    let mut envelope = ObjectEnvelope::unsigned(object_type, schema_version, canonical_payload);
    let object_id = envelope.object_id();
    envelope
        .add_signature(
            maintainer_signature(signer, object_type, object_id).map_err(|err| err.to_string())?,
        )
        .map_err(|err| err.to_string())?;
    Ok(envelope)
}

struct CreateArgs {
    name: String,
    from: Option<String>,
}

fn parse_create_args(args: Vec<String>) -> std::result::Result<CreateArgs, String> {
    let mut name = None;
    let mut from = None;
    let mut iter = args.into_iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--from" => {
                let Some(value) = iter.next() else {
                    return Err("branch create --from requires a value".to_string());
                };
                from = Some(value);
            }
            other if other.starts_with('-') => {
                return Err(format!("unknown branch create argument: {other}"));
            }
            _ => {
                if name.is_some() {
                    return Err("branch create accepts at most one name".to_string());
                }
                name = Some(arg);
            }
        }
    }
    let Some(name) = name else {
        return Err("branch create requires <name>".to_string());
    };
    Ok(CreateArgs { name, from })
}