heddle-cli 0.12.0

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
//! Hosted review-signature sync bridge.
//!
//! `heddle review sign` records a `ReviewSignatures` state-attachment LOCALLY.
//! weft#549 rejects a client-pushed attachment in the pack, so a signature only
//! reaches the hosted server through the caller-authenticated, PoP-signed
//! `StateReviewService::SignState` RPC (which binds the signing key to the
//! authenticated caller). This module replays our local signatures over that
//! RPC after a successful `heddle push`, mirroring [`crate::client::discussion_sync`]:
//!
//! * **Push (write path):** for the pushed state(s), forward each review
//!   signature WE authored to the hosted `SignState`. The signature bytes were
//!   computed over the deterministic [`objects::object::state_review::signing_payload`],
//!   byte-identical to the server's reconstruction, so the exact signature the
//!   local `review sign` wrote verifies unchanged server-side. weft relaxes the
//!   `signed_at` skew gate for this authenticated install path, so a signature
//!   minted long before the push still lands.
//! * **Pull (read path):** none needed — the server-minted `ReviewSignatures`
//!   attachment rides the pull pack like any server-owned attachment, so a clone
//!   / pull materializes it and the local `review show` reads it directly.
//!
//! ## Fail-closed self filter
//!
//! Only signatures whose actor is the local principal are forwarded. The actor
//! is resolved from [`Repository::get_principal`] (env → config → git) — the SAME
//! source `review sign` stamped the `actor` with — NOT `config().principal`
//! alone, which is empty in git-overlay / env-identity repos and would silently
//! drop our own signatures. When the principal is unresolvable we warn and skip
//! (we cannot tell which signatures are ours).
//!
//! ## Retry discipline
//!
//! The mirror (`.heddle/collaboration/hosted-review-mirror.json`) records both
//! `synced` and permanently-`rejected` `(state, signature)` pairs. A transient
//! failure (network / server unavailable / state not yet on the server) is left
//! for the next push to retry; a permanent rejection (bad signature, key not
//! owned by the caller) is recorded so it stops retrying and warning every push.

#![cfg(feature = "client")]

use std::{
    collections::{BTreeMap, HashSet},
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use api::heddle::api::v1alpha1::{
    PathSymbolRef, ReviewKind as ProtoReviewKind, ReviewScope as ProtoReviewScope, review_scope,
};
use objects::{
    fs_atomic::write_file_atomic,
    object::{
        ReviewKind, ReviewScope, ReviewSignature, ReviewSignaturesBlob, StateAttachmentBody,
        StateId,
    },
    store::ObjectStore,
};
use repo::{HistoryQuery, Repository, StateAttachmentKind};
use serde::{Deserialize, Serialize};
use wire::ProtocolError;

use crate::client::HostedClient;

/// How far back from HEAD to scan for locally-recorded review signatures.
const REVIEW_SCAN_LIMIT: usize = 50;

#[derive(Debug, Default, Serialize, Deserialize)]
struct HostedReviewMirror {
    #[serde(default)]
    repos: BTreeMap<String, RepoReviewMirror>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct RepoReviewMirror {
    /// `(state_id, signature-hex)` pairs successfully installed on the server.
    #[serde(default)]
    synced: Vec<String>,
    /// Pairs the server permanently rejected — do not retry (avoids warning
    /// every push over a signature that will never install).
    #[serde(default)]
    rejected: Vec<String>,
}

fn synced_key(state_id: &StateId, signature_hex: &str) -> String {
    format!("{}#{signature_hex}", state_id.to_string_full())
}

fn mirror_path(heddle_dir: &Path) -> PathBuf {
    heddle_dir
        .join("collaboration")
        .join("hosted-review-mirror.json")
}

fn load_mirror(heddle_dir: &Path) -> Result<HostedReviewMirror> {
    match fs::read(mirror_path(heddle_dir)) {
        Ok(bytes) => serde_json::from_slice(&bytes).context("decode hosted review mirror map"),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            Ok(HostedReviewMirror::default())
        }
        Err(error) => Err(error).context("read hosted review mirror map"),
    }
}

fn save_mirror(heddle_dir: &Path, mirror: &HostedReviewMirror) -> Result<()> {
    let path = mirror_path(heddle_dir);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).context("create collaboration dir")?;
    }
    let bytes = serde_json::to_vec_pretty(mirror).context("encode hosted review mirror map")?;
    write_file_atomic(&path, &bytes).context("write hosted review mirror map")?;
    Ok(())
}

fn kind_to_proto(kind: ReviewKind) -> ProtoReviewKind {
    match kind {
        ReviewKind::Read => ProtoReviewKind::Read,
        ReviewKind::AgentPreview => ProtoReviewKind::AgentPreview,
        ReviewKind::AgentCoReview => ProtoReviewKind::AgentCoReview,
    }
}

fn scope_to_proto(scope: &ReviewScope) -> ProtoReviewScope {
    let inner = match scope {
        ReviewScope::WholeChange => review_scope::Scope::WholeChange(review_scope::WholeChange {}),
        ReviewScope::Symbols(symbols) => review_scope::Scope::Symbols(review_scope::SymbolList {
            symbols: symbols
                .iter()
                .map(|anchor| PathSymbolRef {
                    file: anchor.file.clone(),
                    symbol: anchor.symbol.clone(),
                })
                .collect(),
        }),
    };
    ProtoReviewScope { scope: Some(inner) }
}

/// Whether a hosted rejection is permanent (won't succeed on retry) vs transient
/// (retry next push). A malformed/invalid signature or a key the caller does not
/// own will never install; a network error or a state not yet on the server may.
fn is_permanent(error: &ProtocolError) -> bool {
    matches!(
        error,
        ProtocolError::InvalidState(_) | ProtocolError::AuthorizationFailed(_)
    )
}

enum ForwardOutcome {
    Installed,
    Permanent(String),
    Transient(String),
}

/// Read the current `ReviewSignatures` blob for a state, if any.
fn read_signatures(repo: &Repository, state_id: &StateId) -> Result<Vec<ReviewSignature>> {
    let Some(attachment) =
        repo.latest_state_attachment(state_id, StateAttachmentKind::ReviewSignatures)?
    else {
        return Ok(Vec::new());
    };
    let StateAttachmentBody::ReviewSignatures(hash) = attachment.body else {
        return Ok(Vec::new());
    };
    let Some(blob) = repo.store().get_blob(&hash)? else {
        return Ok(Vec::new());
    };
    let decoded = ReviewSignaturesBlob::decode(blob.content())
        .map_err(|error| anyhow::anyhow!("decode review signatures blob: {error}"))?;
    Ok(decoded.signatures)
}

/// Replay local review signatures we authored to the hosted `StateReviewService`.
pub async fn push_review_signatures(
    repo: &Repository,
    client: &mut HostedClient,
    repo_path: &str,
) -> Result<usize> {
    let Some(head) = repo.head().context("resolve repository head")? else {
        return Ok(0);
    };

    // Resolve our identity from the SAME source `review sign` stamped the actor
    // with (env → config → git). Warn + skip if unresolvable — we cannot tell
    // which signatures are ours.
    let principal = match repo.get_principal() {
        Ok(principal) => principal,
        Err(error) => {
            eprintln!(
                "{} review sync skipped: could not resolve the local principal ({error}); \
                 set one with `heddle init --principal-name <name> --principal-email <email>`",
                crate::cli::style::warn_marker(),
            );
            return Ok(0);
        }
    };

    let states = repo
        .query_history(&HistoryQuery::new(Some(head)).with_limit(REVIEW_SCAN_LIMIT))
        .context("walk history for review signatures")?;

    let heddle_dir = repo.heddle_dir().to_path_buf();
    let mut mirror = load_mirror(&heddle_dir)?;
    let skip: HashSet<String> = mirror
        .repos
        .get(repo_path)
        .map(|repo_mirror| {
            repo_mirror
                .synced
                .iter()
                .chain(repo_mirror.rejected.iter())
                .cloned()
                .collect()
        })
        .unwrap_or_default();

    let mut synced = 0usize;
    for state in states {
        let signatures = match read_signatures(repo, &state.state_id) {
            Ok(signatures) => signatures,
            Err(error) => {
                eprintln!(
                    "{} hosted review {}: {error:#}",
                    crate::cli::style::warn_marker(),
                    state.state_id.short()
                );
                continue;
            }
        };
        for signature in signatures {
            if signature.actor.name != principal.name || signature.actor.email != principal.email {
                continue;
            }
            let key = synced_key(&state.state_id, &signature.signature);
            if skip.contains(&key) {
                continue;
            }
            match forward_signature(client, repo_path, &state.state_id, &signature).await {
                ForwardOutcome::Installed => {
                    mirror
                        .repos
                        .entry(repo_path.to_string())
                        .or_default()
                        .synced
                        .push(key);
                    save_mirror(&heddle_dir, &mirror)?;
                    synced += 1;
                }
                ForwardOutcome::Permanent(message) => {
                    // Record so we stop retrying + warning on every push.
                    mirror
                        .repos
                        .entry(repo_path.to_string())
                        .or_default()
                        .rejected
                        .push(key);
                    save_mirror(&heddle_dir, &mirror)?;
                    eprintln!(
                        "{} hosted review {}: permanently rejected, will not retry: {message}",
                        crate::cli::style::warn_marker(),
                        state.state_id.short()
                    );
                }
                ForwardOutcome::Transient(message) => {
                    eprintln!(
                        "{} hosted review {}: {message} (will retry on next push)",
                        crate::cli::style::warn_marker(),
                        state.state_id.short()
                    );
                }
            }
        }
    }
    Ok(synced)
}

async fn forward_signature(
    client: &mut HostedClient,
    repo_path: &str,
    state_id: &StateId,
    signature: &ReviewSignature,
) -> ForwardOutcome {
    // A malformed stored signature will never install → permanent.
    let public_key = match hex::decode(&signature.public_key) {
        Ok(bytes) => bytes,
        Err(error) => return ForwardOutcome::Permanent(format!("public_key is not hex: {error}")),
    };
    let signature_bytes = match hex::decode(&signature.signature) {
        Ok(bytes) => bytes,
        Err(error) => return ForwardOutcome::Permanent(format!("signature is not hex: {error}")),
    };
    match client
        .sign_state(
            repo_path,
            state_id,
            kind_to_proto(signature.kind),
            scope_to_proto(&signature.scope),
            signature.justification.as_deref().unwrap_or_default(),
            &signature.algorithm,
            public_key,
            signature_bytes,
            signature.signed_at,
            sign_op_id(repo_path, state_id, &signature.signature),
        )
        .await
    {
        // Idempotent success or an already-installed signature both mean "on the
        // server".
        Ok(_) | Err(ProtocolError::AlreadyExists(_)) => ForwardOutcome::Installed,
        Err(error) if is_permanent(&error) => ForwardOutcome::Permanent(error.to_string()),
        Err(error) => ForwardOutcome::Transient(error.to_string()),
    }
}

const OP_NAMESPACE: uuid::Uuid = uuid::Uuid::from_u128(0x6865_6464_6c65_7276_775f_7379_6e63_0001);

fn sign_op_id(repo_path: &str, state_id: &StateId, signature_hex: &str) -> String {
    uuid::Uuid::new_v5(
        &OP_NAMESPACE,
        format!(
            "sign:{repo_path}:{}:{signature_hex}",
            state_id.to_string_full()
        )
        .as_bytes(),
    )
    .to_string()
}

#[cfg(test)]
mod tests {
    use chrono::Utc;
    use objects::object::{Attribution, Blob, Principal, StateAttachment, SymbolAnchor};
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn whole_change_scope_maps_to_proto() {
        let proto = scope_to_proto(&ReviewScope::WholeChange);
        assert!(matches!(
            proto.scope,
            Some(review_scope::Scope::WholeChange(_))
        ));
    }

    #[test]
    fn symbol_scope_maps_to_proto() {
        let proto = scope_to_proto(&ReviewScope::Symbols(vec![SymbolAnchor::new(
            "a.rs", "foo",
        )]));
        match proto.scope {
            Some(review_scope::Scope::Symbols(list)) => {
                assert_eq!(list.symbols.len(), 1);
                assert_eq!(list.symbols[0].file, "a.rs");
                assert_eq!(list.symbols[0].symbol, "foo");
            }
            other => panic!("expected symbols scope, got {other:?}"),
        }
    }

    #[test]
    fn synced_key_is_state_scoped() {
        let a = StateId::from_bytes([1; 32]);
        let b = StateId::from_bytes([2; 32]);
        assert_ne!(synced_key(&a, "abad1dea"), synced_key(&b, "abad1dea"));
        assert_eq!(synced_key(&a, "abad1dea"), synced_key(&a, "abad1dea"));
    }

    #[test]
    fn kind_maps_to_proto() {
        assert_eq!(kind_to_proto(ReviewKind::Read), ProtoReviewKind::Read);
        assert_eq!(
            kind_to_proto(ReviewKind::AgentPreview),
            ProtoReviewKind::AgentPreview
        );
        assert_eq!(
            kind_to_proto(ReviewKind::AgentCoReview),
            ProtoReviewKind::AgentCoReview
        );
    }

    // A bad-signature / key-not-owned rejection is permanent (stops retrying);
    // a network / not-yet-pushed error is transient (retries next push).
    #[test]
    fn permanent_vs_transient_classification() {
        assert!(is_permanent(&ProtocolError::InvalidState("bad sig".into())));
        assert!(is_permanent(&ProtocolError::AuthorizationFailed(
            "key not owned".into()
        )));
        assert!(!is_permanent(&ProtocolError::ObjectNotFound(
            "state not on server yet".into()
        )));
        assert!(!is_permanent(&ProtocolError::Remote("unavailable".into())));
    }

    #[tokio::test]
    async fn push_installs_owned_signatures_and_persists_permanent_rejections() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init_default(temp.path()).unwrap();
        let principal = Principal::new("Reviewer", "reviewer@example.com");
        let mut config = repo.config().clone();
        config.set_principal(principal.name.clone(), principal.email.clone());
        config.save(&repo.heddle_dir().join("config.toml")).unwrap();
        let repo = Repository::open(temp.path()).unwrap();
        std::fs::write(temp.path().join("reviewed.txt"), "reviewed\n").unwrap();
        let state = repo
            .snapshot_with_attribution(
                Some("review target".to_string()),
                None,
                Attribution::human(principal.clone()),
            )
            .unwrap()
            .id();

        let signature = |actor: Principal, public_key: &str, signature: &str| ReviewSignature {
            actor,
            kind: ReviewKind::Read,
            scope: ReviewScope::WholeChange,
            justification: None,
            signed_at: 1_700_000_000,
            algorithm: "ed25519".to_string(),
            public_key: public_key.to_string(),
            signature: signature.to_string(),
        };
        let signatures = ReviewSignaturesBlob {
            format_version: 1,
            signatures: vec![
                signature(principal.clone(), "not-hex", "aa"),
                signature(principal.clone(), "aa", "bb"),
                signature(Principal::new("Other", "other@example.com"), "cc", "dd"),
            ],
        };
        let blob = Blob::new(signatures.encode().unwrap());
        repo.store().put_blob(&blob).unwrap();
        repo.put_state_attachment(&StateAttachment {
            state_id: state,
            body: StateAttachmentBody::ReviewSignatures(blob.hash()),
            attribution: Attribution::human(principal),
            created_at: Utc::now(),
            supersedes: None,
        })
        .unwrap();

        let (mut client, server) = crate::hosted_runtime::hosted::test_server::start().await;
        assert_eq!(
            push_review_signatures(&repo, &mut client, "acme/widgets")
                .await
                .unwrap(),
            1
        );
        assert_eq!(
            push_review_signatures(&repo, &mut client, "acme/widgets")
                .await
                .unwrap(),
            0
        );
        let mirror = load_mirror(repo.heddle_dir()).unwrap();
        let repo_mirror = &mirror.repos["acme/widgets"];
        assert_eq!(repo_mirror.synced.len(), 1);
        assert_eq!(repo_mirror.rejected.len(), 1);

        client.close().await;
        server.await.unwrap();
    }
}