shipslip 0.14.0

Deploy Laravel apps over SSH with a preview, a deploy lock, and a receipt.
Documentation
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
//! Anchor selection: an active lock wins, then a verified run, then checkout
//! history, then 24h. Missing and failed reads remain distinct in the headline.

use super::{WindowTime, DEFAULT_WINDOW};

mod types;
pub use types::{
    Anchor, AnchorFallback, CheckoutFallbackReason, MarkerFallbackReason, RunCheck,
    RunFallbackReason,
};

use crate::marker::{decode, Marker};
use std::collections::HashMap;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct Probe {
    pub marker: Option<Result<Marker, MarkerFallbackReason>>,
    pub head: Option<Result<String, String>>,
    pub reflog: Option<Result<String, String>>,
    pub active: Option<(String, Option<usize>)>,
    pub times: HashMap<String, WindowTime>,
    pub splits: HashMap<String, (u64, String)>,
}

pub(super) struct Choice {
    pub anchor: Anchor,
    pub time: WindowTime,
    pub marker: Option<Marker>,
    pub warnings: Vec<String>,
    pub fallbacks: Vec<AnchorFallback>,
}

impl Choice {
    pub(super) fn new(
        anchor: Anchor,
        time: WindowTime,
        marker: Option<Marker>,
        fallbacks: Vec<AnchorFallback>,
    ) -> Self {
        Self {
            warnings: fallbacks
                .iter()
                .filter_map(AnchorFallback::warning)
                .collect(),
            anchor,
            time,
            marker,
            fallbacks,
        }
    }
}

pub(super) fn reflog_fields(tip: &str) -> Option<(&str, u64)> {
    let mut fields = tip.split_whitespace();
    let sha = fields.next()?;
    if !crate::script::is_full_sha(sha) {
        return None;
    }
    let time = fields
        .next()?
        .strip_prefix("HEAD@{")?
        .strip_suffix('}')?
        .parse()
        .ok()?;
    Some((sha, time))
}

impl Probe {
    pub fn line(&mut self, line: &str, fallback: &WindowTime) -> bool {
        let fields: Vec<_> = line.split(' ').collect();
        match fields.as_slice() {
            ["@marker", "missing"] => {}
            ["@marker", "ok", text] => {
                self.marker = Some(
                    decode(text)
                        .and_then(|text| Marker::parse(&text))
                        .ok_or(MarkerFallbackReason::Corrupt),
                )
            }
            ["@marker", "error", error] => {
                self.marker = Some(Err(MarkerFallbackReason::Unreadable {
                    message: decode(error)
                        .unwrap_or_else(|| "could not read last-run marker".into())
                        .into(),
                }))
            }
            ["@git-head", "ok", sha] => {
                self.head = Some(if crate::script::is_full_sha(sha) {
                    Ok(sha.to_string())
                } else {
                    Err("invalid HEAD".into())
                })
            }
            ["@git-head", "error", error] => {
                self.head = Some(Err(decode(error).unwrap_or_else(|| "git failed".into())))
            }
            ["@reflog", "missing"] => {}
            ["@reflog", "ok", tip] => {
                self.reflog = Some(
                    decode(tip)
                        .filter(|tip| reflog_fields(tip).is_some())
                        .ok_or_else(|| "invalid reflog output".into()),
                )
            }
            ["@reflog", "error", error] => {
                self.reflog = Some(Err(decode(error).unwrap_or_else(|| "reflog failed".into())))
            }
            ["@active", run, step] => self.active = decode(run).map(|run| (run, step.parse().ok())),
            ["@anchor-time", key, epoch, date, clock, offset] => {
                if let Ok(start) = epoch.parse() {
                    self.times.insert(
                        key.to_string(),
                        WindowTime {
                            now: fallback.now,
                            start,
                            start_local: format!("{date} {clock}"),
                            start_date: date.to_string(),
                            offset_start: offset.to_string(),
                            offset_now: fallback.offset_now.clone(),
                        },
                    );
                }
            }
            ["@split", path, size, sum] => {
                if let (Some(path), Ok(size)) = (decode(path), size.parse()) {
                    self.splits.insert(path, (size, sum.to_string()));
                }
            }
            _ => return false,
        }
        true
    }

    pub fn choose(&self, fallback: WindowTime) -> Choice {
        let mut fallbacks = Vec::new();
        if let Some(Ok(marker)) = &self.marker {
            if let Some(time) = self
                .times
                .get("marker")
                .filter(|time| time.start <= fallback.now && time.start == marker.started_at)
            {
                if let Some((_, step)) = self
                    .active
                    .as_ref()
                    .filter(|(run, _)| run == &marker.run_id)
                {
                    return Choice::new(
                        Anchor::RunInProgress {
                            run_id: marker.run_id.clone().into(),
                            step: *step,
                        },
                        time.clone(),
                        Some(marker.clone()),
                        fallbacks,
                    );
                }
                let git_error = self
                    .head
                    .as_ref()
                    .and_then(|head| head.as_ref().err())
                    .or_else(|| self.reflog.as_ref().and_then(|tip| tip.as_ref().err()));
                if let Some(error) = git_error {
                    return Choice::new(
                        run_anchor(
                            marker,
                            RunCheck::Unverified {
                                reason: error.clone().into(),
                            },
                        ),
                        time.clone(),
                        Some(marker.clone()),
                        fallbacks,
                    );
                }
                let head = self.head.as_ref().and_then(|head| head.as_ref().ok());
                let tip = self.reflog.as_ref().and_then(|tip| tip.as_ref().ok());
                let valid = head == Some(&marker.target_sha)
                    && match &marker.reflog_tip {
                        Some(stored) => tip == Some(stored),
                        None => tip
                            .and_then(|tip| reflog_fields(tip))
                            .is_some_and(|(sha, _)| sha == marker.target_sha),
                    };
                if valid {
                    return Choice::new(
                        run_anchor(marker, RunCheck::Verified),
                        time.clone(),
                        Some(marker.clone()),
                        fallbacks,
                    );
                }
                let reason = if tip.is_none() {
                    RunFallbackReason::ReflogMissing
                } else if head != Some(&marker.target_sha)
                    && marker
                        .reflog_tip
                        .as_deref()
                        .and_then(reflog_fields)
                        .is_none_or(|(sha, _)| sha != marker.target_sha)
                {
                    RunFallbackReason::TargetNotReached {
                        target_commit: marker.target_sha.clone().into(),
                    }
                } else {
                    RunFallbackReason::CheckoutChanged
                };
                let fallback = AnchorFallback::Run {
                    run_id: marker.run_id.clone().into(),
                    reason,
                };
                fallbacks.push(fallback);
            } else {
                let fallback = AnchorFallback::Run {
                    run_id: marker.run_id.clone().into(),
                    reason: RunFallbackReason::InvalidStartTime,
                };
                fallbacks.push(fallback);
            }
        } else if let Some(Err(error)) = &self.marker {
            let fallback = AnchorFallback::LastRunMarker {
                reason: error.clone(),
            };
            fallbacks.push(fallback);
        } else {
            fallbacks.push(AnchorFallback::LastRunMarker {
                reason: MarkerFallbackReason::Missing,
            });
        }
        if let Some(Ok(tip)) = &self.reflog {
            if let (Some((sha, epoch)), Some(time)) = (reflog_fields(tip), self.times.get("reflog"))
            {
                if epoch == time.start && epoch <= fallback.now {
                    return Choice::new(
                        Anchor::CheckoutChange { commit: sha.into() },
                        time.clone(),
                        None,
                        fallbacks,
                    );
                }
            }
        }
        let reason = match (&self.reflog, &self.head) {
            (Some(Err(error)), _) => CheckoutFallbackReason::ReflogReadFailed {
                message: error.clone().into(),
            },
            (_, Some(Err(error))) => CheckoutFallbackReason::HeadReadFailed {
                message: error.clone().into(),
            },
            (Some(Ok(tip)), _) => CheckoutFallbackReason::InvalidStartTime {
                commit: reflog_fields(tip)
                    .expect("probe validates reflog fields")
                    .0
                    .into(),
            },
            (None, _) => CheckoutFallbackReason::ReflogMissing,
        };
        fallbacks.push(AnchorFallback::CheckoutChange { reason });
        Choice::new(
            Anchor::Default {
                seconds: DEFAULT_WINDOW,
            },
            fallback,
            None,
            fallbacks,
        )
    }
}

fn run_anchor(marker: &Marker, check: RunCheck) -> Anchor {
    Anchor::Run {
        run_id: marker.run_id.clone().into(),
        plan: marker.plan.clone().into(),
        target_commit: marker.target_sha.clone().into(),
        check,
        server_marker_outcome: marker.outcome.clone().map(Into::into),
        reflog_recorded: marker.reflog_tip.is_some(),
    }
}

/// Does not write even temporary files. Marker reads and Git diagnostics are
/// bounded and base64-framed. Cursor checksums are computed only inside emit's
/// already-approved file descriptor in the surrounding probe.
pub(super) const SCRIPT: &str = r#"
gitdir=$(git rev-parse --absolute-git-dir 2>/dev/null) || gitdir=''
if [ -z "$gitdir" ]; then
  if [ -d .git ]; then gitdir=.git; else gitdir=$(git rev-parse --resolve-git-dir .git 2>/dev/null) || gitdir=''; fi
fi
anchor_time() {
  [[ "$2" =~ ^[0-9]{1,12}$ ]] || return 0
  local converted
  converted=$(TZ="$tz" date -d "@$2" '+%F %T %z' 2>/dev/null) || return 0
  echo "@anchor-time $1 $2 $converted"
}
declare -A marker_offsets marker_inodes marker_sums
if [ -n "$gitdir" ] && [ -e "$gitdir/shipslip.last-run" ]; then
  if marker_text=$(head -c 262145 -- "$gitdir/shipslip.last-run" 2>/dev/null); then
    echo "@marker ok $(printf '%s' "$marker_text" | base64 -w0)"
    while IFS=' ' read -r kind a b c d; do
      case "$kind" in
        @started) anchor_time marker "$a" ;;
        @file)
          if [[ "$a" =~ ^[0-9]+$ && "$b" =~ ^[0-9]+$ && "$c" =~ ^[0-9a-f]{64}$ ]]; then
            [[ "$d" =~ ^[A-Za-z0-9+/=]+$ ]] || continue
            marker_offsets["$d"]=$b; marker_inodes["$d"]=$a; marker_sums["$d"]=$c
          fi ;;
      esac
    done <<< "$marker_text"
  else echo "@marker error $(printf '%s' 'could not read last-run marker' | base64 -w0)"; fi
else echo '@marker missing'; fi
if head=$(git rev-parse HEAD 2>&1); then echo "@git-head ok $head"; else echo "@git-head error $(printf '%s' "${head%%$'\n'*}" | base64 -w0)"; fi
if tip=$(git reflog -1 --date=unix --format='%H %gD %gs' 2>&1); then
  if [ -n "$tip" ]; then
    echo "@reflog ok $(printf '%s' "$tip" | base64 -w0)"
    at=${tip#*HEAD@\{}; at=${at%%\}*}; anchor_time reflog "$at"
  else echo '@reflog missing'; fi
else echo "@reflog error $(printf '%s' "${tip%%$'\n'*}" | base64 -w0)"; fi
if [ -n "$gitdir" ] && [ -d "$gitdir/shipslip.lock" ]; then
  if active=$(cat "$gitdir/shipslip.lock/run_id" 2>/dev/null); then
    step='-'
    if [[ "$active" =~ ^[a-zA-Z0-9_-]+$ ]]; then
      if [ -d "$HOME/.shipslip/runs/$active/maintenance-down" ] && [ ! -e "$HOME/.shipslip/runs/$active/maintenance-down/exit" ]; then step=0; fi
      for d in "$HOME"/.shipslip/runs/"$active"/step-*; do
        if [ -d "$d" ] && [ ! -e "$d/exit" ]; then step=${d##*step-}; fi
      done
    fi
    echo "@active $(printf '%s' "$active" | base64 -w0) $step"
  fi
fi
"#;

#[cfg(test)]
mod tests {
    use super::*;
    fn time() -> WindowTime {
        WindowTime {
            now: 1000,
            start: 900,
            start_local: "2026-10-02 00:00:00".into(),
            start_date: "2026-10-02".into(),
            offset_start: "+0000".into(),
            offset_now: "+0000".into(),
        }
    }
    fn probe() -> Probe {
        let sha = "a".repeat(40);
        let tip = format!("{sha} HEAD@{{900}} merge: fast-forward");
        Probe {
            marker: Some(Ok(Marker {
                run_id: "r-one".into(),
                plan: "deploy".into(),
                target_sha: sha.clone(),
                started_at: 900,
                finished_at: Some(950),
                outcome: Some("succeeded".into()),
                reflog_tip: Some(tip.clone()),
                files: Vec::new(),
            })),
            head: Some(Ok(sha)),
            reflog: Some(Ok(tip)),
            times: HashMap::from([("marker".into(), time()), ("reflog".into(), time())]),
            ..Probe::default()
        }
    }
    #[test]
    fn active_lock_wins_even_before_the_target_commit_is_checked_out() {
        let mut probe = probe();
        probe.head = Some(Ok("b".repeat(40)));
        probe.active = Some(("r-one".into(), Some(2)));
        let choice = probe.choose(time());
        assert_eq!(
            choice.anchor,
            Anchor::RunInProgress {
                run_id: "r-one".into(),
                step: Some(2)
            }
        );
        assert!(choice.marker.is_some());
    }
    #[test]
    fn verifies_tip_and_labels_git_errors_and_missing_tips() {
        let mut probe = probe();
        assert!(matches!(
            probe.choose(time()).anchor,
            Anchor::Run {
                check: RunCheck::Verified,
                reflog_recorded: true,
                ..
            }
        ));
        probe.reflog = Some(Ok(format!(
            "{} HEAD@{{900}} checkout: moved back",
            "a".repeat(40)
        )));
        let choice = probe.choose(time());
        assert!(matches!(choice.anchor, Anchor::CheckoutChange { .. }));
        assert!(choice.warnings[0].contains("checkout changed after run"));
        probe.head = Some(Err("dubious ownership".into()));
        assert!(matches!(
            probe.choose(time()).anchor,
            Anchor::Run { check: RunCheck::Unverified { reason }, .. }
                if reason.raw() == "dubious ownership"
        ));
        probe.head = Some(Ok("a".repeat(40)));
        probe.marker.as_mut().unwrap().as_mut().unwrap().reflog_tip = None;
        assert!(matches!(
            probe.choose(time()).anchor,
            Anchor::Run {
                reflog_recorded: false,
                ..
            }
        ));
    }
    #[test]
    fn corrupt_markers_and_failed_reflogs_are_not_silently_missing() {
        let mut probe = probe();
        probe.marker = Some(Err("corrupt".into()));
        assert!(probe.choose(time()).warnings[0].contains("corrupt"));
        probe.reflog = Some(Err("git refused".into()));
        let choice = probe.choose(time());
        assert!(matches!(choice.anchor, Anchor::Default { .. }));
        assert!(choice
            .warnings
            .iter()
            .any(|warning| warning.contains("reflog failed (git refused)")));
    }
}