shepherd-core 6.6.0

The harness-agnostic shepherd engine: domain types, configuration schema, and run state. Knows nothing about any CLI, harness, or process.
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
//! Product-byte custody, separate from the evidence that attests those bytes.
//!
//! The native CLI measures filesystem/Git facts while holding the run lock.
//! This allocating, host-independent contract owns the monotonic stage machine.

use alloc::{format, string::String, vec::Vec};

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error("invalid candidate custody: {0}")]
pub struct CandidateError(pub String);

type Result<T = ()> = core::result::Result<T, CandidateError>;

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct FileReference {
    pub path: String,
    pub sha256: String,
    pub bytes: u64,
}

impl FileReference {
    pub fn validate(&self) -> Result {
        if self.path.is_empty()
            || self.path.contains('\0')
            || !exact_hex(&self.sha256, 64)
            || self.bytes == 0
        {
            return Err(CandidateError(
                "artifact lacks a path, byte count, or exact SHA-256".into(),
            ));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProductSource {
    pub root: String,
    pub commit: String,
    pub tree: String,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProductFile {
    pub path: String,
    pub mode: String,
    pub sha256: String,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct CompilerDigests {
    pub claude: String,
    pub codex: String,
    pub pi: String,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProductArtifacts {
    pub native_cli: FileReference,
    pub component_wasm: FileReference,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProductManifest {
    pub schema: String,
    pub run: String,
    pub source: ProductSource,
    pub files: Vec<ProductFile>,
    pub compiler: CompilerDigests,
    pub artifacts: ProductArtifacts,
}

impl ProductManifest {
    pub fn validate(&self) -> Result {
        if self.schema != "shepherd.product-manifest/1"
            || crate::dispatch::RunId::new(&self.run).is_err()
            || self.source.root.is_empty()
            || !exact_hex(&self.source.commit, 40)
            || !exact_hex(&self.source.tree, 40)
            || self.files.is_empty()
            || self.files.len() > 65_536
            || [
                &self.compiler.claude,
                &self.compiler.codex,
                &self.compiler.pi,
            ]
            .iter()
            .any(|digest| !exact_hex(digest, 64))
        {
            return Err(CandidateError(
                "manifest schema, run, source, compiler or inventory is invalid".into(),
            ));
        }
        let mut previous = None;
        for file in &self.files {
            if !canonical_relative(&file.path)
                || excluded_product_path(&file.path)
                || previous.is_some_and(|path: &str| path >= file.path.as_str())
                || !exact_hex(&file.sha256, 64)
                || !matches!(file.mode.as_str(), "100644" | "100755" | "120000")
                || (file.mode == "120000" && product_symlink_target(&file.path).is_none())
            {
                return Err(CandidateError(format!(
                    "product inventory is not canonical at {}",
                    file.path
                )));
            }
            previous = Some(file.path.as_str());
        }
        self.artifacts.native_cli.validate()?;
        self.artifacts.component_wasm.validate()?;
        Ok(())
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    PartialEq,
    serde::Deserialize,
    serde::Serialize,
    strum::AsRefStr,
    strum::Display,
    strum::EnumCount,
    strum::EnumIs,
    strum::EnumString,
    strum::IntoStaticStr,
    strum::VariantNames,
)]
#[serde(rename_all = "kebab-case")]
#[strum(ascii_case_insensitive, serialize_all = "snake_case")]
pub enum CandidateState {
    Frozen,
    SourceVerified,
    Packing,
    Packages,
    Attested,
    Revoked,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct CandidateRecord {
    pub schema: String,
    pub candidate_id: String,
    pub run: String,
    pub run_incarnation: String,
    pub state: CandidateState,
    pub source_commit: String,
    pub source_tree: String,
    pub product_manifest_sha256: String,
    pub product_manifest: ProductManifest,
    pub packages_manifest: Option<FileReference>,
    pub lifecycle_manifest: Option<FileReference>,
    pub revocation_reason: Option<String>,
}

impl CandidateRecord {
    pub fn freeze(
        candidate_id: String,
        run_incarnation: String,
        manifest: ProductManifest,
        manifest_sha256: String,
    ) -> Result<Self> {
        let record = Self {
            schema: "shepherd.candidate-record/1".into(),
            candidate_id,
            run: manifest.run.clone(),
            run_incarnation,
            state: CandidateState::Frozen,
            source_commit: manifest.source.commit.clone(),
            source_tree: manifest.source.tree.clone(),
            product_manifest_sha256: manifest_sha256,
            product_manifest: manifest,
            packages_manifest: None,
            lifecycle_manifest: None,
            revocation_reason: None,
        };
        record.validate()?;
        Ok(record)
    }

    pub fn validate(&self) -> Result {
        self.product_manifest.validate()?;
        if self.schema != "shepherd.candidate-record/1"
            || !exact_hex(&self.candidate_id, 64)
            || self.run_incarnation.is_empty()
            || self.run != self.product_manifest.run
            || self.source_commit != self.product_manifest.source.commit
            || self.source_tree != self.product_manifest.source.tree
            || !exact_hex(&self.product_manifest_sha256, 64)
            || (self.state == CandidateState::Revoked) != self.revocation_reason.is_some()
            || self
                .revocation_reason
                .as_ref()
                .is_some_and(|reason| reason.trim().is_empty())
            || (self.lifecycle_manifest.is_some() && self.packages_manifest.is_none())
        {
            return Err(CandidateError(
                "record identity or revocation state is invalid".into(),
            ));
        }
        let stage_shape = match self.state {
            CandidateState::Frozen | CandidateState::SourceVerified | CandidateState::Packing => {
                self.packages_manifest.is_none() && self.lifecycle_manifest.is_none()
            }
            CandidateState::Packages => {
                self.packages_manifest.is_some() && self.lifecycle_manifest.is_none()
            }
            CandidateState::Attested => {
                self.packages_manifest.is_some() && self.lifecycle_manifest.is_some()
            }
            CandidateState::Revoked => true,
        };
        if !stage_shape {
            return Err(CandidateError(
                "record stage and attestations disagree".into(),
            ));
        }
        for artifact in [&self.packages_manifest, &self.lifecycle_manifest]
            .into_iter()
            .flatten()
        {
            artifact.validate()?;
        }
        Ok(())
    }

    /// The caller must freshly measure all product facts before advancing.
    pub fn verify_source(&mut self) -> Result {
        self.validate()?;
        if self.state == CandidateState::Revoked {
            return Err(CandidateError("candidate is revoked".into()));
        }
        if self.state == CandidateState::Frozen {
            self.state = CandidateState::SourceVerified;
        }
        Ok(())
    }

    /// Reservation is consumed even if packing later fails. Retry needs revoke/refreeze.
    pub fn reserve_pack(&mut self) -> Result {
        self.require(CandidateState::SourceVerified)?;
        self.state = CandidateState::Packing;
        Ok(())
    }

    pub fn attest_packages(&mut self, manifest: FileReference) -> Result {
        self.require(CandidateState::Packing)?;
        manifest.validate()?;
        self.packages_manifest = Some(manifest);
        self.state = CandidateState::Packages;
        Ok(())
    }

    pub fn attest_lifecycle(&mut self, manifest: FileReference) -> Result {
        self.require(CandidateState::Packages)?;
        manifest.validate()?;
        self.lifecycle_manifest = Some(manifest);
        self.state = CandidateState::Attested;
        Ok(())
    }

    pub fn revoke(&mut self, reason: String) -> Result {
        self.validate()?;
        if self.state == CandidateState::Revoked || reason.trim().is_empty() || reason.len() > 4096
        {
            return Err(CandidateError(
                "revocation requires a live candidate and bounded non-empty reason".into(),
            ));
        }
        self.state = CandidateState::Revoked;
        self.revocation_reason = Some(reason);
        Ok(())
    }

    fn require(&self, expected: CandidateState) -> Result {
        self.validate()?;
        if self.state != expected {
            return Err(CandidateError(format!(
                "operation requires {expected:?}, found {:?}",
                self.state
            )));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct CandidateCustody {
    pub schema: String,
    pub current: CandidateRecord,
    pub history: Vec<CandidateRecord>,
}

impl CandidateCustody {
    pub fn new(current: CandidateRecord) -> Result<Self> {
        let custody = Self {
            schema: "shepherd.candidate-custody/1".into(),
            current,
            history: Vec::new(),
        };
        custody.validate()?;
        Ok(custody)
    }

    pub fn validate(&self) -> Result {
        self.current.validate()?;
        if self.schema != "shepherd.candidate-custody/1" || self.history.len() > 64 {
            return Err(CandidateError(
                "custody schema or history size is invalid".into(),
            ));
        }
        let mut identities = alloc::collections::BTreeSet::new();
        identities.insert(&self.current.candidate_id);
        for prior in &self.history {
            prior.validate()?;
            if prior.state != CandidateState::Revoked
                || prior.run != self.current.run
                || prior.run_incarnation != self.current.run_incarnation
                || !identities.insert(&prior.candidate_id)
            {
                return Err(CandidateError(
                    "candidate history is not unique revoked lineage".into(),
                ));
            }
        }
        Ok(())
    }

    pub fn refreeze(&mut self, next: CandidateRecord) -> Result {
        self.validate()?;
        next.validate()?;
        if self.current.state != CandidateState::Revoked
            || self.history.len() >= 64
            || next.state != CandidateState::Frozen
            || next.run != self.current.run
            || next.run_incarnation != self.current.run_incarnation
            || next.candidate_id == self.current.candidate_id
            || self
                .history
                .iter()
                .any(|prior| prior.candidate_id == next.candidate_id)
        {
            return Err(CandidateError(
                "refreeze requires a new identity after explicit revocation".into(),
            ));
        }
        self.history
            .push(core::mem::replace(&mut self.current, next));
        Ok(())
    }
}

#[must_use]
pub fn exact_hex(value: &str, length: usize) -> bool {
    value.len() == length
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

#[must_use]
pub fn canonical_relative(path: &str) -> bool {
    !path.is_empty()
        && !path.contains(['\\', '\0', ':'])
        && path.split('/').all(|part| !matches!(part, "" | "." | ".."))
}

/// Only these repository-owned links are product inputs. Their link bytes and
/// resolved in-root target inventory are additionally checked by the native host.
#[must_use]
pub fn product_symlink_target(path: &str) -> Option<&'static str> {
    match path {
        "CLAUDE.md" => Some("AGENTS.md"),
        "plugins/shepherd/agents" => Some("../../agents"),
        "plugins/shepherd/hooks/hooks.json" => Some("../../../hooks/hooks.json"),
        "plugins/shepherd/hooks/scripts" => Some("../../../hooks/scripts"),
        "plugins/shepherd/skills" => Some("../../skills"),
        _ => None,
    }
}

/// Evidence may advance the frozen source only within this exact run's paths.
#[must_use]
pub fn evidence_only_path(run: &str, path: &str) -> bool {
    if !canonical_relative(path) {
        return false;
    }
    let parts: Vec<_> = path.split('/').collect();
    if parts.len() < 4 || parts[..2] != [".shepherd", "runs"] || parts[2] != run {
        return false;
    }
    // `attestation.json` sits directly in the run directory, beside `close.md`
    // and `handoff.md`, which were already flat. An `evidence/` subdirectory
    // for a single file bought nothing: the run directory IS the evidence
    // scope, and the run id in the path is what makes a foreign attestation
    // detectable. The subdirectory form stays recognized for runs that already
    // use it.
    matches!(
        &parts[3..],
        ["close.md" | "handoff.md" | "attestation.json"]
    ) || (parts[3] == "evidence" && parts.len() >= 5)
        || matches!(&parts[3..], ["lanes", _, "handoff.md"])
        || (parts.len() >= 7 && parts[3] == "lanes" && parts[5] == "evidence")
}

/// Narrow non-product state. Seeds, plans, reports and authored run designs
/// remain product inputs; a broad `.shepherd/runs/**` exclusion is forbidden.
#[must_use]
pub fn excluded_product_path(path: &str) -> bool {
    let parts: Vec<_> = path.split('/').collect();
    if matches!(
        parts.first(),
        Some(&".git" | &"target" | &"targets" | &"node_modules" | &".superpowers")
    ) || parts.contains(&"node_modules")
        || path.starts_with(".shepherd/tmp/")
        || matches!(
            path,
            ".shepherd/project.json"
                | ".shepherd/shepherd.lock"
                | ".shepherd/shepherd.db"
                | ".shepherd/shepherd.db-wal"
                | ".shepherd/shepherd.db-shm"
        )
    {
        return true;
    }
    // `.artifacts/` holds GENERATED, non-plugin-bound output that has no
    // natural home the way `target/` and `node_modules/` do -- rendered docs
    // for Pages, the attestation ledger, incidental binaries. It exists to keep
    // that out of the repository root, and none of it is product source: a
    // candidate's frozen hash must not move because docs were rendered or an
    // attestation was recorded against it.
    if parts.first() == Some(&".artifacts") {
        return true;
    }
    if parts.len() >= 4 && parts[..2] == [".shepherd", "runs"] {
        return evidence_only_path(parts[2], path)
            || matches!(
                &parts[3..],
                ["run.json" | "run.lock" | "orientation-pre.json" | "orientation-post.json"]
            )
            || parts[3] == "dispatch";
    }
    false
}