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
457
458
459
460
461
462
463
464
465
466
467
468
//! Single-use Native attestations for on-demand Shepherd skill loading.

#[cfg(feature = "alloc")]
use alloc::{
    format,
    string::{String, ToString},
};

use crate::Harness;

use super::{
    AgentId, DispatchError, DispatchResult, ProfileLease, ProfileLeaseState, ProjectId, Role,
    RootSessionBinding, RunId, SessionId, constant_time_digest_eq,
};

pub const SKILL_USE_CHALLENGE_SCHEMA: &str = "shepherd.skill-use-challenge/1";
pub const LOADED_SKILL_SCHEMA: &str = "shepherd.loaded-skill/1";

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    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 SkillUseStage {
    DuringWork,
    Completion,
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    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 SkillUseState {
    Pending,
    Attested,
    Expired,
}

/// Exact Native root authority, including an inactive profile's last state.
/// Retaining that state prevents entering and exiting a profile from reviving
/// a challenge issued before the profile transition.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct SkillUseRootAuthority {
    pub binding: RootSessionBinding,
    pub profile_lease: Option<ProfileLease>,
}

impl SkillUseRootAuthority {
    pub fn validate(&self) -> DispatchResult<()> {
        self.binding
            .validate()
            .map_err(|error| DispatchError::InvalidSkillUse(error.to_string()))?;
        if self.binding.role != Role::Shepherd
            || !matches!(
                self.binding.harness,
                Harness::ClaudeCode | Harness::Codex | Harness::Pi
            )
        {
            return Err(DispatchError::InvalidSkillUse(
                "root skill use requires an actual Shepherd root binding".into(),
            ));
        }
        if let Some(lease) = &self.profile_lease {
            lease.validate()?;
            if lease.project_id != self.binding.project_id
                || lease.run != self.binding.run
                || lease.root_session_id != self.binding.session_id
                || lease.harness != self.binding.harness
                || self.binding.project_filesystem_id.as_deref()
                    != Some(lease.project_filesystem_id.as_str())
                || lease.state == ProfileLeaseState::Entered
            {
                return Err(DispatchError::InvalidSkillUse(
                    "root skill use has an unactivated or foreign profile lease".into(),
                ));
            }
        }
        Ok(())
    }

    #[must_use]
    pub fn role(&self) -> Role {
        if self
            .profile_lease
            .as_ref()
            .is_some_and(|lease| lease.state == ProfileLeaseState::Active)
        {
            Role::Planter
        } else {
            Role::Shepherd
        }
    }

    pub fn validate_live(&self, now: i64) -> DispatchResult<()> {
        self.validate()?;
        if now < self.binding.bound_at || now >= self.binding.expires_at {
            return Err(DispatchError::InvalidSkillUse(
                "root skill-use authority is not live".into(),
            ));
        }
        if self
            .profile_lease
            .as_ref()
            .is_some_and(|lease| now < lease.entered_at)
        {
            return Err(DispatchError::InvalidSkillUse(
                "root skill-use authority predates its retained profile lease".into(),
            ));
        }
        if let Some(lease) = &self.profile_lease
            && lease.state == ProfileLeaseState::Active
        {
            lease.validate_for_root(&self.binding, now)?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SkillUsePrepare {
    pub project_id: ProjectId,
    pub run: RunId,
    pub dispatch_id: Option<AgentId>,
    pub root_authority: Option<SkillUseRootAuthority>,
    pub session_id: SessionId,
    pub target: Harness,
    pub role: Role,
    pub startup_skill: String,
    pub skill: String,
    pub stage: SkillUseStage,
    pub installed_carrier_path: String,
    pub candidate_sha256: [u8; 32],
    pub carrier_sha256: [u8; 32],
    pub compiler_tree_sha256: [u8; 32],
    pub skill_bundle_sha256: [u8; 32],
    pub nonce_sha256: [u8; 32],
    pub prepared_at: i64,
    pub expires_at: i64,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct SkillUseChallenge {
    pub schema: String,
    pub project_id: ProjectId,
    pub run: RunId,
    pub dispatch_id: Option<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_authority: Option<SkillUseRootAuthority>,
    pub session_id: SessionId,
    pub target: Harness,
    pub role: Role,
    pub startup_skill: String,
    pub skill: String,
    pub stage: SkillUseStage,
    pub installed_carrier_path: String,
    #[serde(with = "super::pending::digest_serde")]
    pub candidate_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub carrier_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub compiler_tree_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub skill_bundle_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub nonce_sha256: [u8; 32],
    pub prepared_at: i64,
    pub expires_at: i64,
    pub state: SkillUseState,
    pub attested_at: Option<i64>,
}

impl SkillUseChallenge {
    pub fn prepare(input: SkillUsePrepare) -> DispatchResult<Self> {
        if !allowed_skill_use(input.role, &input.startup_skill, &input.skill, input.stage) {
            return Err(DispatchError::InvalidSkillUse(format!(
                "role `{}` with startup `{}` cannot load `{}` at {:?}",
                input.role, input.startup_skill, input.skill, input.stage
            )));
        }
        if input.prepared_at < 0
            || input.expires_at <= input.prepared_at
            || !valid_installed_path(&input.installed_carrier_path)
            || input.candidate_sha256 == [0; 32]
            || input.carrier_sha256 == [0; 32]
            || input.compiler_tree_sha256 == [0; 32]
            || input.skill_bundle_sha256 == [0; 32]
            || input.nonce_sha256 == [0; 32]
        {
            return Err(DispatchError::InvalidSkillUse(
                "skill-use identity, digest, path, or lease is invalid".into(),
            ));
        }
        let value = Self {
            schema: SKILL_USE_CHALLENGE_SCHEMA.into(),
            project_id: input.project_id,
            run: input.run,
            dispatch_id: input.dispatch_id,
            root_authority: input.root_authority,
            session_id: input.session_id,
            target: input.target,
            role: input.role,
            startup_skill: input.startup_skill,
            skill: input.skill,
            stage: input.stage,
            installed_carrier_path: input.installed_carrier_path,
            candidate_sha256: input.candidate_sha256,
            carrier_sha256: input.carrier_sha256,
            compiler_tree_sha256: input.compiler_tree_sha256,
            skill_bundle_sha256: input.skill_bundle_sha256,
            nonce_sha256: input.nonce_sha256,
            prepared_at: input.prepared_at,
            expires_at: input.expires_at,
            state: SkillUseState::Pending,
            attested_at: None,
        };
        value.validate()?;
        Ok(value)
    }

    pub fn validate(&self) -> DispatchResult<()> {
        if self.schema != SKILL_USE_CHALLENGE_SCHEMA
            || !allowed_skill_use(self.role, &self.startup_skill, &self.skill, self.stage)
            || self.prepared_at < 0
            || self.expires_at <= self.prepared_at
            || !valid_installed_path(&self.installed_carrier_path)
            || self.candidate_sha256 == [0; 32]
            || self.carrier_sha256 == [0; 32]
            || self.compiler_tree_sha256 == [0; 32]
            || self.skill_bundle_sha256 == [0; 32]
            || self.nonce_sha256 == [0; 32]
            || match self.state {
                SkillUseState::Pending | SkillUseState::Expired => self.attested_at.is_some(),
                SkillUseState::Attested => self
                    .attested_at
                    .is_none_or(|value| value < self.prepared_at || value >= self.expires_at),
            }
        {
            return Err(DispatchError::InvalidSkillUse(
                "persisted skill-use challenge is inconsistent".into(),
            ));
        }
        match (&self.dispatch_id, &self.root_authority) {
            (Some(_), None) if !matches!(self.role, Role::Shepherd | Role::Planter) => {}
            (None, Some(authority)) => {
                authority.validate_live(self.prepared_at)?;
                if self.project_id != authority.binding.project_id
                    || self.run != authority.binding.run
                    || self.session_id != authority.binding.session_id
                    || self.target != authority.binding.harness
                    || self.role != authority.role()
                    || self.expires_at > authority.binding.expires_at
                    || authority.profile_lease.as_ref().is_some_and(|lease| {
                        lease.state == ProfileLeaseState::Active
                            && (self.expires_at > lease.expires_at
                                || !constant_time_digest_eq(
                                    &self.candidate_sha256,
                                    &lease.expected_attachment.candidate_sha256,
                                ))
                    })
                {
                    return Err(DispatchError::InvalidSkillUse(
                        "root challenge differs from its exact root/profile authority".into(),
                    ));
                }
            }
            _ => {
                return Err(DispatchError::InvalidSkillUse(
                    "skill use requires exactly one child or Native root authority".into(),
                ));
            }
        }
        Ok(())
    }

    pub fn attest(&mut self, attestation: &LoadedSkillAttestation, now: i64) -> DispatchResult<()> {
        self.validate()?;
        if self.state != SkillUseState::Pending {
            return Err(DispatchError::SkillUseReplay);
        }
        if now >= self.expires_at {
            self.state = SkillUseState::Expired;
            return Err(DispatchError::SkillUseExpired {
                expires_at: self.expires_at,
            });
        }
        attestation.validate_against(self, now)?;
        self.state = SkillUseState::Attested;
        self.attested_at = Some(now);
        self.validate()
    }

    /// Persist the terminal state of an unused challenge after its deadline.
    /// The adapter calls this before returning an expiry error so the durable
    /// record cannot remain pending and later be mistaken for live authority.
    pub fn expire(&mut self, now: i64) -> DispatchResult<()> {
        self.validate()?;
        if self.state != SkillUseState::Pending {
            return Err(DispatchError::SkillUseReplay);
        }
        if now < self.expires_at {
            return Err(DispatchError::InvalidSkillUse(
                "skill-use challenge has not reached its expiry".into(),
            ));
        }
        self.state = SkillUseState::Expired;
        self.validate()
    }
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct LoadedSkillAttestation {
    pub schema: String,
    pub project_id: ProjectId,
    pub run: RunId,
    pub dispatch_id: Option<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_authority: Option<SkillUseRootAuthority>,
    pub session_id: SessionId,
    pub target: Harness,
    pub role: Role,
    pub startup_skill: String,
    pub skill: String,
    pub stage: SkillUseStage,
    pub installed_carrier_path: String,
    #[serde(with = "super::pending::digest_serde")]
    pub candidate_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub carrier_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub compiler_tree_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub skill_bundle_sha256: [u8; 32],
    #[serde(with = "super::pending::digest_serde")]
    pub nonce_sha256: [u8; 32],
    pub loaded_at: i64,
}

impl LoadedSkillAttestation {
    #[must_use]
    pub fn from_challenge(challenge: &SkillUseChallenge, loaded_at: i64) -> Self {
        Self {
            schema: LOADED_SKILL_SCHEMA.into(),
            project_id: challenge.project_id.clone(),
            run: challenge.run.clone(),
            dispatch_id: challenge.dispatch_id.clone(),
            root_authority: challenge.root_authority.clone(),
            session_id: challenge.session_id.clone(),
            target: challenge.target,
            role: challenge.role,
            startup_skill: challenge.startup_skill.clone(),
            skill: challenge.skill.clone(),
            stage: challenge.stage,
            installed_carrier_path: challenge.installed_carrier_path.clone(),
            candidate_sha256: challenge.candidate_sha256,
            carrier_sha256: challenge.carrier_sha256,
            compiler_tree_sha256: challenge.compiler_tree_sha256,
            skill_bundle_sha256: challenge.skill_bundle_sha256,
            nonce_sha256: challenge.nonce_sha256,
            loaded_at,
        }
    }

    pub fn validate_against(&self, challenge: &SkillUseChallenge, now: i64) -> DispatchResult<()> {
        challenge.validate()?;
        if self.schema != LOADED_SKILL_SCHEMA
            || self.loaded_at != now
            || self.loaded_at < challenge.prepared_at
            || self.loaded_at >= challenge.expires_at
            || self.project_id != challenge.project_id
            || self.run != challenge.run
            || self.dispatch_id != challenge.dispatch_id
            || self.root_authority != challenge.root_authority
            || self.session_id != challenge.session_id
            || self.target != challenge.target
            || self.role != challenge.role
            || self.startup_skill != challenge.startup_skill
            || self.skill != challenge.skill
            || self.stage != challenge.stage
            || self.installed_carrier_path != challenge.installed_carrier_path
            || !constant_time_digest_eq(&self.candidate_sha256, &challenge.candidate_sha256)
            || !constant_time_digest_eq(&self.carrier_sha256, &challenge.carrier_sha256)
            || !constant_time_digest_eq(&self.compiler_tree_sha256, &challenge.compiler_tree_sha256)
            || !constant_time_digest_eq(&self.skill_bundle_sha256, &challenge.skill_bundle_sha256)
            || !constant_time_digest_eq(&self.nonce_sha256, &challenge.nonce_sha256)
        {
            return Err(DispatchError::AttachmentMismatch(
                "loaded skill does not match the Native single-use challenge".into(),
            ));
        }
        Ok(())
    }
}

#[must_use]
pub fn allowed_skill_use(
    role: Role,
    startup_skill: &str,
    skill: &str,
    stage: SkillUseStage,
) -> bool {
    if skill == "debugging" {
        return role == Role::Coder
            && startup_skill == "implementing"
            && stage == SkillUseStage::DuringWork;
    }
    if skill != "verification" || stage != SkillUseStage::Completion {
        return false;
    }
    matches!(
        (role, startup_skill),
        (Role::Shepherd, "shepherd")
            | (Role::Planter, "planting")
            | (Role::Engineer, "planning")
            | (Role::Conductor, "lane-execution")
            | (Role::Coder, "implementing")
            | (Role::Worker, "artifact-work")
            | (Role::Auditor | Role::Critic, "reviewing")
            | (Role::Discovery, "researching")
    )
}

fn valid_installed_path(value: &str) -> bool {
    let bytes = value.as_bytes();
    !value.is_empty()
        && value.len() <= 4_096
        && !value.contains(['\0', '\n', '\r'])
        && (value.starts_with('/')
            || (bytes.len() >= 3
                && bytes[0].is_ascii_alphabetic()
                && bytes[1] == b':'
                && matches!(bytes[2], b'/' | b'\\')))
}