shared-context-engineering 0.3.1

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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Minimal agent-trace domain model and hunk classification contract.
//!
//! This module defines the domain types for producing a minimal agent-trace
//! JSON payload from patch data. The classification logic computes the
//! intersection of a constructed patch and a post-commit patch
//! (`intersection_patch = intersect_patches(constructed_patch, post_commit_patch)`),
//! then compares `intersection_patch` against `post_commit_patch` hunk by hunk,
//! anchored to `post_commit_patch` as the canonical source of truth.
//!
//! Classification rules:
//! - **exact** line-by-line match between `intersection_patch` and `post_commit_patch` hunk => `ai`
//! - same hunk slot in `post_commit_patch` but not exact line-by-line match => `mixed`
//! - hunk present in `post_commit_patch` but missing from `intersection_patch` => `unknown`

use std::{collections::BTreeSet, error::Error, fmt, io::Cursor, path::Path, sync::OnceLock};

use anyhow::{Context, Result};
use chrono::{DateTime, FixedOffset};
use jsonschema::{validator_for, Validator};
use murmur3::murmur3_32;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::{NoContext, Timestamp, Uuid};

use super::patch::{
    intersect_patches, parse_patch, FileChangeKind, ParsedPatch, PatchFileChange, PatchHunk,
    TouchedLineKind,
};
use super::version::PACKAGE_VERSION;

pub const AGENT_TRACE_VERSION: &str = "0.1.0";
pub(crate) const SCE_WEB_BASE_URL: &str = "https://sce.crocoder.dev";

const RANGE_CONTENT_HASH_PREFIX: &str = "murmur3:";
const RANGE_CONTENT_HASH_INPUT_VERSION: &[u8] = b"sce-agent-trace-range-content-hash-v1\0";
const TOUCHED_LINE_ADDED_TAG: &[u8] = b"added\0";
const TOUCHED_LINE_REMOVED_TAG: &[u8] = b"removed\0";

pub(crate) fn agent_trace_conversation_url(agent_trace_id: &str) -> String {
    format!("{SCE_WEB_BASE_URL}/conversations/{agent_trace_id}")
}

pub(crate) fn agent_trace_persisted_url(agent_trace_id: &str) -> String {
    format!("{}/trace/{agent_trace_id}", sce_web_host())
}

pub(crate) fn agent_trace_session_url(session_id: &str) -> String {
    format!("{SCE_WEB_BASE_URL}/sessions/{session_id}")
}

fn sce_web_host() -> &'static str {
    SCE_WEB_BASE_URL
        .strip_prefix("https://")
        .unwrap_or(SCE_WEB_BASE_URL)
}

fn default_agent_trace_version() -> String {
    AGENT_TRACE_VERSION.to_owned()
}

fn default_agent_trace_metadata() -> AgentTraceMetadata {
    AgentTraceMetadata {
        sce: AgentTraceSceMetadata {
            version: PACKAGE_VERSION.to_owned(),
        },
    }
}

fn generate_agent_trace_id(commit_time: DateTime<FixedOffset>) -> Result<String> {
    let seconds = u64::try_from(commit_time.timestamp()).with_context(|| {
        format!(
            "Invalid commit timestamp '{}': unix seconds must be non-negative.",
            commit_time.to_rfc3339()
        )
    })?;
    let timestamp = Timestamp::from_unix(NoContext, seconds, commit_time.timestamp_subsec_nanos());

    Ok(Uuid::new_v7(timestamp).to_string())
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AgentTraceMetadataInput<'a> {
    pub commit_timestamp: &'a str,
    pub commit_revision: &'a str,
    pub vcs_type: Option<AgentTraceVcsType>,
    pub tool_name: Option<&'a str>,
    pub tool_version: Option<&'a str>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentTraceVcsType {
    Git,
    Jj,
    Hg,
    Svn,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct AgentTraceVcs {
    #[serde(rename = "type")]
    pub r#type: AgentTraceVcsType,
    pub revision: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct AgentTraceTool {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct AgentTraceMetadata {
    pub sce: AgentTraceSceMetadata,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct AgentTraceSceMetadata {
    pub version: String,
}

fn parse_commit_timestamp(commit_timestamp: &str) -> Result<DateTime<FixedOffset>> {
    DateTime::parse_from_rfc3339(commit_timestamp).with_context(|| {
        format!("Invalid commit timestamp '{commit_timestamp}': expected RFC 3339 date-time.")
    })
}

#[allow(dead_code)]
const AGENT_TRACE_SCHEMA_PATH: &str = "config/schema/agent-trace.schema.json";
#[allow(dead_code)]
pub(crate) const AGENT_TRACE_SCHEMA_JSON: &str =
    include_str!("../../assets/generated/config/schema/agent-trace.schema.json");

#[allow(dead_code)]
static AGENT_TRACE_SCHEMA_VALIDATOR: OnceLock<Validator> = OnceLock::new();

#[derive(Debug, Eq, PartialEq)]
#[allow(dead_code)]
pub(crate) enum AgentTraceValidationError {
    FileRead { path: String, message: String },
    InvalidJson { message: String },
    SchemaValidation { errors: Vec<String> },
}

impl fmt::Display for AgentTraceValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FileRead { path, message } => {
                write!(f, "Agent Trace JSON file could not be read at '{path}': {message}")
            }
            Self::InvalidJson { message } => {
                write!(f, "Agent Trace JSON must be valid JSON: {message}")
            }
            Self::SchemaValidation { errors } => write!(
                f,
                "Agent Trace JSON failed schema validation against embedded schema '{AGENT_TRACE_SCHEMA_PATH}': {}",
                errors.join(" | ")
            ),
        }
    }
}

impl Error for AgentTraceValidationError {}

#[allow(dead_code)]
fn agent_trace_schema_validator() -> &'static Validator {
    AGENT_TRACE_SCHEMA_VALIDATOR.get_or_init(|| {
        let schema: Value = serde_json::from_str(AGENT_TRACE_SCHEMA_JSON)
            .expect("agent trace schema JSON should parse");
        validator_for(&schema).expect("agent trace schema JSON should compile")
    })
}

#[allow(dead_code)]
pub(crate) fn validate_agent_trace_value(value: &Value) -> Result<(), AgentTraceValidationError> {
    let mut errors = agent_trace_schema_validator()
        .iter_errors(value)
        .map(|error| error.to_string())
        .collect::<Vec<_>>();

    if errors.is_empty() {
        return Ok(());
    }

    errors.sort();

    Err(AgentTraceValidationError::SchemaValidation { errors })
}

#[allow(dead_code)]
pub(crate) fn validate_agent_trace_json(raw: &str) -> Result<(), AgentTraceValidationError> {
    let value: Value =
        serde_json::from_str(raw).map_err(|error| AgentTraceValidationError::InvalidJson {
            message: error.to_string(),
        })?;

    validate_agent_trace_value(&value)
}

#[allow(dead_code)]
pub(crate) fn validate_agent_trace_file(path: &Path) -> Result<(), AgentTraceValidationError> {
    let raw =
        std::fs::read_to_string(path).map_err(|error| AgentTraceValidationError::FileRead {
            path: path.display().to_string(),
            message: error.to_string(),
        })?;

    validate_agent_trace_json(&raw)
}
/// Classification of a single hunk's origin relative to the AI candidate patch.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HunkContributor {
    /// All touched lines in the `post_commit_patch` hunk are present identically
    /// in `intersection_patch`.
    Ai,
    /// The `post_commit_patch` hunk has a corresponding slot in `intersection_patch`
    /// but the content differs.
    Mixed,
    /// The `post_commit_patch` hunk has no corresponding slot in `intersection_patch`
    /// (missing from AI candidate).
    Unknown,
}

/// A single conversation entry derived from one `post_commit_patch` hunk.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct Conversation {
    /// Absolute lookup URL for the generated top-level agent trace.
    pub url: String,
    /// Classification of this hunk's origin.
    pub contributor: Contributor,
    /// Line ranges in the new file, derived from the `post_commit_patch` hunk metadata.
    pub ranges: Vec<LineRange>,
    /// Optional related resources for this conversation entry.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub related: Option<Vec<ConversationRelated>>,
}

/// A related resource for a conversation entry.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(dead_code)]
pub struct ConversationRelated {
    /// Free-form related resource type.
    #[serde(rename = "type")]
    pub kind: String,
    /// Related resource URL.
    pub url: String,
}

/// Nested contributor object for a conversation entry.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct Contributor {
    /// Classification of this hunk's origin.
    #[serde(rename = "type")]
    pub kind: HunkContributor,
    /// Model provenance for this contributor; omitted when unknown.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_id: Option<String>,
}

/// A single line range in the new file.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct LineRange {
    pub start_line: u64,
    pub end_line: u64,
    pub content_hash: String,
}

/// A file-level entry in the minimal agent-trace payload.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct TraceFile {
    /// Post-change file path (from `post_commit_patch`).
    pub path: String,
    /// One conversation per `post_commit_patch` hunk, in `post_commit_patch` hunk order.
    pub conversations: Vec<Conversation>,
}

/// Top-level minimal agent-trace payload.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct AgentTrace {
    /// Agent-trace payload version.
    #[serde(default = "default_agent_trace_version")]
    pub version: String,
    /// Trace record identifier (`UUIDv7` generated from commit-time metadata).
    #[serde(default)]
    pub id: String,
    /// RFC 3339 timestamp string sourced from caller-provided commit metadata.
    #[serde(default)]
    pub timestamp: String,
    /// Version control metadata sourced from caller-provided commit metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vcs: Option<AgentTraceVcs>,
    /// Optional tool metadata sourced from caller-provided metadata input.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool: Option<AgentTraceTool>,
    /// Implementation-specific metadata for SCE-generated traces.
    #[serde(default = "default_agent_trace_metadata")]
    pub metadata: AgentTraceMetadata,
    /// File-level trace entries, one per file present in `post_commit_patch`.
    pub files: Vec<TraceFile>,
}

/// Classify a single `post_commit_patch` hunk against the corresponding
/// `intersection_patch` hunk (if any).
///
/// Two hunks correspond when they share the same `old_start` value within the
/// same file. This is the slot-matching rule that aligns `intersection_patch`
/// hunks to `post_commit_patch` hunks for comparison.
///
/// Returns:
/// - `HunkContributor::Ai` when the `intersection_patch` hunk exists and its
///   touched lines match the `post_commit_patch` hunk's touched lines exactly
///   (same count, same kind, same `line_number`, same content, in the same order).
/// - `HunkContributor::Mixed` when the `intersection_patch` hunk exists but its
///   touched lines differ from the `post_commit_patch` hunk's touched lines.
/// - `HunkContributor::Unknown` when no `intersection_patch` hunk with the same
///   `old_start` exists for this `post_commit_patch` hunk.
pub fn classify_hunk(
    post_commit_hunk: &PatchHunk,
    intersection_hunks: &[PatchHunk],
) -> HunkContributor {
    let Some(intersection_hunk) = intersection_hunks
        .iter()
        .find(|h| h.old_start == post_commit_hunk.old_start)
    else {
        return HunkContributor::Unknown;
    };

    if hunks_match_exactly(post_commit_hunk, intersection_hunk) {
        HunkContributor::Ai
    } else {
        HunkContributor::Mixed
    }
}

#[allow(dead_code)]
pub(crate) fn patches_have_overlap(
    candidate_patch: &ParsedPatch,
    target_patch: &ParsedPatch,
) -> bool {
    let intersection_patch = intersect_patches(candidate_patch, target_patch);

    patch_has_touched_lines(&intersection_patch)
}

pub(crate) fn patch_has_touched_lines(patch: &ParsedPatch) -> bool {
    patch
        .files
        .iter()
        .any(|file| file.hunks.iter().any(|hunk| !hunk.lines.is_empty()))
}

/// Check whether two hunks have identical touched lines in the same order.
fn hunks_match_exactly(left: &PatchHunk, right: &PatchHunk) -> bool {
    if left.lines.len() != right.lines.len() {
        return false;
    }
    left.lines.iter().zip(right.lines.iter()).all(|(ll, rl)| {
        ll.kind == rl.kind && ll.line_number == rl.line_number && ll.content == rl.content
    })
}

#[allow(dead_code)]
pub(crate) fn range_content_hash(hunk: &PatchHunk) -> String {
    let mut input = Vec::new();
    input.extend_from_slice(RANGE_CONTENT_HASH_INPUT_VERSION);

    for line in &hunk.lines {
        let kind_tag = match line.kind {
            TouchedLineKind::Added => TOUCHED_LINE_ADDED_TAG,
            TouchedLineKind::Removed => TOUCHED_LINE_REMOVED_TAG,
        };
        let content = line.content.as_bytes();

        input.extend_from_slice(kind_tag);
        input.extend_from_slice(&(content.len() as u64).to_be_bytes());
        input.extend_from_slice(content);
        input.push(0);
    }

    let hash = murmur3_32(&mut Cursor::new(input), 0)
        .expect("murmur3 hashing from in-memory cursor should not fail");
    format!("{RANGE_CONTENT_HASH_PREFIX}{hash:08x}")
}

fn line_range_from_hunk(file: &PatchFileChange, hunk: &PatchHunk) -> LineRange {
    let (start_line, line_count) = match file.kind {
        FileChangeKind::Deleted if hunk.new_count == 0 => (hunk.old_start, hunk.old_count),
        _ => (hunk.new_start, hunk.new_count),
    };
    let end_line = start_line.saturating_add(line_count.saturating_sub(1));

    LineRange {
        start_line,
        end_line,
        content_hash: range_content_hash(hunk),
    }
}

fn trace_path(file: &PatchFileChange) -> &str {
    if file.new_path.is_empty() {
        &file.old_path
    } else {
        &file.new_path
    }
}

fn parse_embedded_deleted_patch(file: &PatchFileChange) -> Option<ParsedPatch> {
    if file.kind != FileChangeKind::Deleted
        || !Path::new(&file.old_path)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("patch"))
    {
        return None;
    }

    let embedded_patch = file
        .hunks
        .iter()
        .flat_map(|hunk| hunk.lines.iter())
        .filter(|line| line.kind == TouchedLineKind::Removed)
        .map(|line| line.content.as_str())
        .collect::<Vec<_>>()
        .join("\n");

    let parsed_patch = parse_patch(&embedded_patch, None).ok()?;
    (!parsed_patch.files.is_empty()).then_some(parsed_patch)
}

fn build_trace_file(
    post_commit_file: &PatchFileChange,
    intersection_patch: &ParsedPatch,
    conversation_url: &str,
) -> Option<TraceFile> {
    if post_commit_file.hunks.is_empty() {
        return None;
    }

    let intersection_file = intersection_patch
        .files
        .iter()
        .find(|ifile| ifile.new_path == post_commit_file.new_path);

    let conversations = post_commit_file
        .hunks
        .iter()
        .map(|post_commit_hunk| {
            let (contributor_kind, contributor_model_id, matched_intersection_hunk) =
                match intersection_file {
                    Some(ifile) => {
                        let contributor_kind = classify_hunk(post_commit_hunk, &ifile.hunks);
                        let matched_intersection_hunk = ifile
                            .hunks
                            .iter()
                            .find(|h| h.old_start == post_commit_hunk.old_start);
                        let contributor_model_id = match contributor_kind {
                            HunkContributor::Ai | HunkContributor::Mixed => {
                                matched_intersection_hunk.and_then(|hunk| hunk.model_id.clone())
                            }
                            HunkContributor::Unknown => None,
                        };
                        (
                            contributor_kind,
                            contributor_model_id,
                            matched_intersection_hunk,
                        )
                    }
                    None => (HunkContributor::Unknown, None, None),
                };
            let related_session_ids = matched_intersection_hunk
                .into_iter()
                .flat_map(|hunk| hunk.lines.iter())
                .filter_map(|line| line.session_id.as_deref())
                .filter(|session_id| !session_id.is_empty())
                .collect::<BTreeSet<_>>();
            let related = (!related_session_ids.is_empty()).then(|| {
                related_session_ids
                    .into_iter()
                    .map(|session_id| ConversationRelated {
                        kind: String::from("session"),
                        url: agent_trace_session_url(session_id),
                    })
                    .collect()
            });

            Conversation {
                url: conversation_url.to_owned(),
                contributor: Contributor {
                    kind: contributor_kind,
                    model_id: contributor_model_id,
                },
                ranges: vec![line_range_from_hunk(post_commit_file, post_commit_hunk)],
                related,
            }
        })
        .collect();

    Some(TraceFile {
        path: trace_path(post_commit_file).to_string(),
        conversations,
    })
}

/// Build the minimal agent-trace payload from two patches.
///
/// Computes `intersection_patch = intersect_patches(constructed_patch, post_commit_patch)`,
/// then iterates over `post_commit_patch`'s files and hunks to classify each hunk
/// against `intersection_patch`. Deleted `.patch` files whose removed contents are
/// themselves valid patch text are expanded into trace entries for the embedded
/// patch's files. Metadata-only entries with no hunks are omitted. The output
/// preserves the surrounding `post_commit_patch` file ordering and per-file hunk
/// ordering.
///
/// Files in `post_commit_patch` that have no corresponding file in
/// `intersection_patch` still appear in the output with all hunks classified
/// as `Unknown`.
#[allow(dead_code)]
pub fn build_agent_trace(
    constructed_patch: &ParsedPatch,
    post_commit_patch: &ParsedPatch,
    metadata: AgentTraceMetadataInput<'_>,
) -> Result<AgentTrace> {
    let commit_time = parse_commit_timestamp(metadata.commit_timestamp)?;
    let id = generate_agent_trace_id(commit_time)?;
    let conversation_url = agent_trace_conversation_url(&id);
    let timestamp = metadata.commit_timestamp.to_owned();
    let intersection_patch = intersect_patches(constructed_patch, post_commit_patch);

    let mut files = Vec::new();

    for post_commit_file in &post_commit_patch.files {
        if let Some(embedded_patch) = parse_embedded_deleted_patch(post_commit_file) {
            let embedded_intersection = intersect_patches(constructed_patch, &embedded_patch);
            files.extend(embedded_patch.files.iter().filter_map(|embedded_file| {
                build_trace_file(embedded_file, &embedded_intersection, &conversation_url)
            }));
            continue;
        }

        if let Some(trace_file) =
            build_trace_file(post_commit_file, &intersection_patch, &conversation_url)
        {
            files.push(trace_file);
        }
    }

    let tool = if !intersection_patch.files.is_empty()
        && (metadata.tool_name.is_some() || metadata.tool_version.is_some())
    {
        Some(AgentTraceTool {
            name: metadata.tool_name.map(ToOwned::to_owned),
            version: metadata.tool_version.map(ToOwned::to_owned),
        })
    } else {
        None
    };

    Ok(AgentTrace {
        version: default_agent_trace_version(),
        id,
        timestamp,
        vcs: metadata.vcs_type.map(|vcs_type| AgentTraceVcs {
            r#type: vcs_type,
            revision: metadata.commit_revision.to_owned(),
        }),
        tool,
        metadata: default_agent_trace_metadata(),
        files,
    })
}

#[cfg(test)]
mod tests;