shared-context-engineering 0.3.3

Shared Context Engineering CLI
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
518
519
520
521
//! Pure repository identity canonicalization and hashing.
//!
//! Turns an explicit configured identity or a Git remote URL into a
//! scheme-neutral canonical identity, then derives a stable repository ID as
//! `sha256("sce-repository-id-v1\0" + canonical_identity)` hex.
//!
//! This root module performs no I/O: it never opens databases, reads Git
//! config, or touches the filesystem. Runtime precedence resolution and Git
//! remote lookup live in [`resolve`]. Errors intentionally never echo the
//! raw input so credential-bearing remote URLs cannot leak through
//! diagnostics.

pub mod resolve;

use sha2::{Digest, Sha256};

/// Domain-separation prefix hashed before the canonical identity.
pub const REPOSITORY_ID_HASH_DOMAIN: &[u8] = b"sce-repository-id-v1\0";

/// A resolved repository identity: the safe canonical form plus its hash.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepositoryIdentity {
    /// Credential-free canonical identity, safe to display and store.
    pub canonical_identity: String,
    /// Lowercase hex SHA-256 of the domain prefix plus canonical identity.
    pub repository_id: String,
}

impl RepositoryIdentity {
    /// Human-readable on-disk directory segment (`<slug>-<short>`) for this
    /// identity. Convenience wrapper over [`repository_dir_segment`]; the
    /// authoritative identity is still [`RepositoryIdentity::repository_id`].
    pub fn dir_segment(&self) -> String {
        repository_dir_segment(&self.canonical_identity)
    }
}

/// Canonicalization failure. Variants carry no input fragments so
/// credential-bearing URLs never leak into error output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepositoryIdentityError {
    /// Explicit identity was empty after trimming whitespace.
    EmptyExplicitIdentity,
    /// Remote URL was empty after trimming whitespace.
    EmptyRemoteUrl,
    /// Remote URL scheme is not a supported Git transport.
    UnsupportedRemoteUrl,
    /// Remote URL has no usable host component.
    MissingHost,
    /// Remote URL has no usable repository path component.
    MissingPath,
    /// Remote URL port component is not a valid number.
    InvalidPort,
}

impl std::fmt::Display for RepositoryIdentityError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let message = match self {
            Self::EmptyExplicitIdentity => "explicit repository identity is empty",
            Self::EmptyRemoteUrl => "remote URL is empty",
            Self::UnsupportedRemoteUrl => {
                "remote URL is not a supported Git transport (ssh, scp-style ssh, http, https, git)"
            }
            Self::MissingHost => "remote URL has no host",
            Self::MissingPath => "remote URL has no repository path",
            Self::InvalidPort => "remote URL has an invalid port",
        };
        f.write_str(message)
    }
}

impl std::error::Error for RepositoryIdentityError {}

/// Builds a repository identity from an explicitly configured identity
/// string (`agent_trace.repository_id`). Canonicalization is trimming only:
/// explicit identities are operator-chosen opaque values, not URLs.
pub fn repository_identity_from_explicit(
    raw: &str,
) -> Result<RepositoryIdentity, RepositoryIdentityError> {
    let canonical = raw.trim();
    if canonical.is_empty() {
        return Err(RepositoryIdentityError::EmptyExplicitIdentity);
    }
    Ok(identity_from_canonical(canonical.to_string()))
}

/// Builds a repository identity from a Git remote URL. Equivalent SSH,
/// SCP-style, and HTTPS URLs canonicalize to the same identity.
pub fn repository_identity_from_remote_url(
    raw: &str,
) -> Result<RepositoryIdentity, RepositoryIdentityError> {
    let canonical = canonicalize_remote_url(raw)?;
    Ok(identity_from_canonical(canonical))
}

/// Derives the repository ID hex digest for a canonical identity.
pub fn derive_repository_id(canonical_identity: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(REPOSITORY_ID_HASH_DOMAIN);
    hasher.update(canonical_identity.as_bytes());
    hex_encode(&hasher.finalize())
}

/// Length in hex chars of the disambiguating short hash in a directory segment.
const DIR_SEGMENT_SHORT_HASH_LEN: usize = 4;

/// Derives the human-readable on-disk directory segment for a canonical
/// identity as `<slug>-<short>`, where `slug` is the lowercased canonical
/// identity with every run of non-alphanumeric characters collapsed to a
/// single `-` and leading/trailing `-` trimmed, and `short` is the first four
/// hex chars of `SHA256(canonical_identity)` computed with **no** domain
/// prefix. The short hash is deliberately distinct from [`derive_repository_id`],
/// which keeps its `sce-repository-id-v1\0` domain separation. This is a pure
/// display/layout helper: the authoritative identity remains the repository ID.
pub fn repository_dir_segment(canonical_identity: &str) -> String {
    let slug = slugify(canonical_identity);
    let short = derive_short_hash(canonical_identity);
    if slug.is_empty() {
        short
    } else {
        format!("{slug}-{short}")
    }
}

/// Lowercases and collapses every run of non-alphanumeric characters to a
/// single `-`, trimming leading and trailing `-`.
fn slugify(input: &str) -> String {
    let mut slug = String::with_capacity(input.len());
    let mut pending_dash = false;
    for ch in input.chars() {
        if ch.is_ascii_alphanumeric() {
            if pending_dash && !slug.is_empty() {
                slug.push('-');
            }
            pending_dash = false;
            slug.push(ch.to_ascii_lowercase());
        } else {
            pending_dash = true;
        }
    }
    slug
}

/// First [`DIR_SEGMENT_SHORT_HASH_LEN`] hex chars of the un-prefixed
/// `SHA256(canonical_identity)`.
fn derive_short_hash(canonical_identity: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(canonical_identity.as_bytes());
    let full = hex_encode(&hasher.finalize());
    full[..DIR_SEGMENT_SHORT_HASH_LEN].to_string()
}

/// Canonicalizes a Git remote URL to the scheme-neutral form
/// `host[:port]/path` with credentials stripped, hostname lowercased,
/// default ports removed, and query/fragment/trailing-slash/trailing-`.git`
/// cleaned up. The returned string never contains credentials.
pub fn canonicalize_remote_url(raw: &str) -> Result<String, RepositoryIdentityError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(RepositoryIdentityError::EmptyRemoteUrl);
    }

    if let Some((scheme, rest)) = trimmed.split_once("://") {
        canonicalize_scheme_url(scheme, rest)
    } else {
        canonicalize_scp_style(trimmed)
    }
}

fn identity_from_canonical(canonical_identity: String) -> RepositoryIdentity {
    let repository_id = derive_repository_id(&canonical_identity);
    RepositoryIdentity {
        canonical_identity,
        repository_id,
    }
}

fn canonicalize_scheme_url(scheme: &str, rest: &str) -> Result<String, RepositoryIdentityError> {
    let scheme = scheme.to_ascii_lowercase();
    let default_port = match scheme.as_str() {
        "ssh" | "git+ssh" | "ssh+git" => Some(22),
        "http" => Some(80),
        "https" => Some(443),
        "git" => Some(9418),
        _ => return Err(RepositoryIdentityError::UnsupportedRemoteUrl),
    };

    let (authority, path) = match rest.split_once('/') {
        Some((authority, path)) => (authority, path),
        None => (rest, ""),
    };

    let host_port = strip_userinfo(authority);
    let (host, port) = split_host_port(host_port)?;
    if host.is_empty() {
        return Err(RepositoryIdentityError::MissingHost);
    }

    let path = clean_path(path)?;
    Ok(render_canonical(&host, port, default_port, &path))
}

fn canonicalize_scp_style(input: &str) -> Result<String, RepositoryIdentityError> {
    // SCP-style form: [user@]host:path — the colon must come before any '/'.
    let host_port_end = input.find(':');
    let first_slash = input.find('/');
    let colon = match (host_port_end, first_slash) {
        (Some(colon), Some(slash)) if colon < slash => colon,
        (Some(colon), None) => colon,
        _ => return Err(RepositoryIdentityError::UnsupportedRemoteUrl),
    };

    let authority = &input[..colon];
    let path = &input[colon + 1..];

    let host = strip_userinfo(authority).to_ascii_lowercase();
    if host.is_empty() {
        return Err(RepositoryIdentityError::MissingHost);
    }
    // SCP-style implies SSH on the default port; no port component exists.
    let path = clean_path(path)?;
    Ok(format!("{host}/{path}"))
}

fn strip_userinfo(authority: &str) -> &str {
    match authority.rfind('@') {
        Some(at) => &authority[at + 1..],
        None => authority,
    }
}

fn split_host_port(host_port: &str) -> Result<(String, Option<u16>), RepositoryIdentityError> {
    // IPv6 literals are bracketed: [::1]:2222
    if let Some(rest) = host_port.strip_prefix('[') {
        let Some(close) = rest.find(']') else {
            return Err(RepositoryIdentityError::MissingHost);
        };
        let host = rest[..close].to_ascii_lowercase();
        let after = &rest[close + 1..];
        if after.is_empty() {
            return Ok((format!("[{host}]"), None));
        }
        let Some(port) = after.strip_prefix(':') else {
            return Err(RepositoryIdentityError::InvalidPort);
        };
        let port = parse_port(port)?;
        return Ok((format!("[{host}]"), Some(port)));
    }

    match host_port.rsplit_once(':') {
        Some((host, port)) => Ok((host.to_ascii_lowercase(), Some(parse_port(port)?))),
        None => Ok((host_port.to_ascii_lowercase(), None)),
    }
}

fn parse_port(port: &str) -> Result<u16, RepositoryIdentityError> {
    port.parse::<u16>()
        .map_err(|_| RepositoryIdentityError::InvalidPort)
}

fn clean_path(path: &str) -> Result<String, RepositoryIdentityError> {
    let path = path.split(['?', '#']).next().unwrap_or("");
    let path = path.trim_matches('/');
    let path = path.strip_suffix(".git").unwrap_or(path);
    let path = path.trim_matches('/');
    if path.is_empty() {
        return Err(RepositoryIdentityError::MissingPath);
    }
    Ok(path.to_string())
}

fn render_canonical(
    host: &str,
    port: Option<u16>,
    default_port: Option<u16>,
    path: &str,
) -> String {
    match port {
        Some(port) if Some(port) != default_port => format!("{host}:{port}/{path}"),
        _ => format!("{host}/{path}"),
    }
}

fn hex_encode(bytes: &[u8]) -> String {
    use std::fmt::Write;

    let mut hex = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        let _ = write!(hex, "{b:02x}");
    }
    hex
}

#[cfg(test)]
mod tests {
    use super::*;

    fn canonical(raw: &str) -> String {
        canonicalize_remote_url(raw).expect("expected canonicalization to succeed")
    }

    #[test]
    fn equivalent_github_urls_share_canonical_identity_and_id() {
        let forms = [
            "git@github.com:CroCoder/shared-context-engineering.git",
            "ssh://git@github.com/CroCoder/shared-context-engineering.git",
            "ssh://git@github.com:22/CroCoder/shared-context-engineering.git",
            "https://github.com/CroCoder/shared-context-engineering.git",
            "https://github.com:443/CroCoder/shared-context-engineering",
            "https://GitHub.com/CroCoder/shared-context-engineering.git/",
            "https://token@github.com/CroCoder/shared-context-engineering.git?ref=main#readme",
        ];

        let expected = "github.com/CroCoder/shared-context-engineering";
        let expected_id = derive_repository_id(expected);
        for form in forms {
            let identity = repository_identity_from_remote_url(form)
                .expect("expected identity resolution to succeed");
            assert_eq!(identity.canonical_identity, expected, "input: {form}");
            assert_eq!(identity.repository_id, expected_id, "input: {form}");
        }
    }

    #[test]
    fn repository_id_uses_domain_separated_sha256() {
        let identity = repository_identity_from_explicit("acme/widgets")
            .expect("expected explicit identity to resolve");
        let mut hasher = Sha256::new();
        hasher.update(b"sce-repository-id-v1\0");
        hasher.update(b"acme/widgets");
        let expected = hex_encode(&hasher.finalize());
        assert_eq!(identity.repository_id, expected);
        assert_eq!(identity.repository_id.len(), 64);
    }

    #[test]
    fn distinct_identities_hash_differently() {
        let a = repository_identity_from_remote_url("git@github.com:acme/widgets.git")
            .expect("expected identity resolution to succeed");
        let b = repository_identity_from_remote_url("git@github.com:acme/gadgets.git")
            .expect("expected identity resolution to succeed");
        let c = repository_identity_from_remote_url("git@gitlab.com:acme/widgets.git")
            .expect("expected identity resolution to succeed");
        assert_ne!(a.repository_id, b.repository_id);
        assert_ne!(a.repository_id, c.repository_id);
        assert_ne!(b.repository_id, c.repository_id);
    }

    #[test]
    fn credentials_are_stripped_and_never_leak() {
        let secret_forms = [
            "https://alice:s3cr3t@github.com/acme/widgets.git",
            "ssh://alice:s3cr3t@github.com:22/acme/widgets.git",
            "alice@github.com:acme/widgets.git",
        ];
        for form in secret_forms {
            let identity = repository_identity_from_remote_url(form)
                .expect("expected identity resolution to succeed");
            assert_eq!(identity.canonical_identity, "github.com/acme/widgets");
            assert!(!identity.canonical_identity.contains("alice"));
            assert!(!identity.canonical_identity.contains("s3cr3t"));
            assert!(!identity.repository_id.contains("s3cr3t"));
        }
    }

    #[test]
    fn errors_do_not_echo_input() {
        let cases = [
            ("", RepositoryIdentityError::EmptyRemoteUrl),
            (
                "file:///alice:s3cr3t/repo.git",
                RepositoryIdentityError::UnsupportedRemoteUrl,
            ),
            (
                "/local/path/to/s3cr3t-repo",
                RepositoryIdentityError::UnsupportedRemoteUrl,
            ),
            (
                "https://alice:s3cr3t@github.com",
                RepositoryIdentityError::MissingPath,
            ),
            (
                "https://alice:s3cr3t@/acme/widgets.git",
                RepositoryIdentityError::MissingHost,
            ),
            (
                "https://github.com:port/acme/widgets.git",
                RepositoryIdentityError::InvalidPort,
            ),
        ];
        for (input, expected) in cases {
            let error =
                canonicalize_remote_url(input).expect_err("expected canonicalization error");
            assert_eq!(error, expected, "input: {input}");
            let rendered = error.to_string();
            assert!(
                !rendered.contains("s3cr3t"),
                "error leaked input: {rendered}"
            );
        }
    }

    #[test]
    fn non_default_ports_are_preserved() {
        assert_eq!(
            canonical("ssh://git@github.com:2222/acme/widgets.git"),
            "github.com:2222/acme/widgets"
        );
        assert_eq!(
            canonical("https://github.com:8443/acme/widgets.git"),
            "github.com:8443/acme/widgets"
        );
        assert_eq!(
            canonical("git://github.com:9418/acme/widgets.git"),
            "github.com/acme/widgets"
        );
        assert_eq!(
            canonical("http://github.com:80/acme/widgets.git"),
            "github.com/acme/widgets"
        );
    }

    #[test]
    fn hostnames_are_lowercased_but_paths_preserved() {
        assert_eq!(
            canonical("Git@GitHub.COM:Acme/Widgets.git"),
            "github.com/Acme/Widgets"
        );
    }

    #[test]
    fn query_fragment_and_trailing_cleanup() {
        assert_eq!(
            canonical("https://github.com/acme/widgets.git?depth=1"),
            "github.com/acme/widgets"
        );
        assert_eq!(
            canonical("https://github.com/acme/widgets#fragment"),
            "github.com/acme/widgets"
        );
        assert_eq!(
            canonical("https://github.com/acme/widgets///"),
            "github.com/acme/widgets"
        );
        assert_eq!(
            canonical("https://github.com/acme/widgets.git/"),
            "github.com/acme/widgets"
        );
    }

    #[test]
    fn scp_style_requires_colon_before_slash() {
        assert_eq!(
            canonicalize_remote_url("github.com/acme/widgets:tag"),
            Err(RepositoryIdentityError::UnsupportedRemoteUrl)
        );
        assert_eq!(
            canonical("git@github.com:acme/widgets"),
            "github.com/acme/widgets"
        );
    }

    #[test]
    fn ipv6_hosts_are_supported() {
        assert_eq!(
            canonical("ssh://git@[2001:DB8::1]:2222/acme/widgets.git"),
            "[2001:db8::1]:2222/acme/widgets"
        );
        assert_eq!(
            canonical("ssh://git@[2001:db8::1]/acme/widgets.git"),
            "[2001:db8::1]/acme/widgets"
        );
    }

    #[test]
    fn explicit_identity_is_trimmed_and_used_verbatim() {
        let identity = repository_identity_from_explicit("  my-monorepo  ")
            .expect("expected explicit identity to resolve");
        assert_eq!(identity.canonical_identity, "my-monorepo");
        assert_eq!(
            repository_identity_from_explicit("   "),
            Err(RepositoryIdentityError::EmptyExplicitIdentity)
        );
    }

    fn un_prefixed_sha256_prefix(input: &str, len: usize) -> String {
        let mut hasher = Sha256::new();
        hasher.update(input.as_bytes());
        hex_encode(&hasher.finalize())[..len].to_string()
    }

    #[test]
    fn dir_segment_matches_slug_and_un_prefixed_short_hash() {
        // Slug: lowercased, non-alphanumeric runs (`.`,`/`) collapsed to `-`,
        // trimmed. Short: first 4 hex of the un-prefixed SHA-256, deliberately
        // distinct from the domain-prefixed repository ID.
        let canonical = "github.com/crocoder-dev/shared-context-engineering";
        let short = un_prefixed_sha256_prefix(canonical, 4);
        assert_eq!(
            repository_dir_segment(canonical),
            format!("github-com-crocoder-dev-shared-context-engineering-{short}")
        );
        assert_ne!(short, derive_repository_id(canonical)[..4]);
    }

    #[test]
    fn missing_path_variants_error() {
        assert_eq!(
            canonicalize_remote_url("https://github.com/"),
            Err(RepositoryIdentityError::MissingPath)
        );
        assert_eq!(
            canonicalize_remote_url("git@github.com:"),
            Err(RepositoryIdentityError::MissingPath)
        );
        assert_eq!(
            canonicalize_remote_url("https://github.com/.git"),
            Err(RepositoryIdentityError::MissingPath)
        );
    }
}