1use std::path::{Path, PathBuf};
22
23use anyhow::{Context, Result, anyhow, ensure};
24use jiff::Timestamp;
25use serde::{Deserialize, Serialize};
26
27use crate::{
28 git,
29 land_sync_recovery::{GhPrObserver, PrObserver},
30 queue::{OperatorResume, Queue, Task},
31 run::{LandApproval, Liveness, MergeRepair, MergeRepairPhase, RunState, RunStatus},
32};
33
34pub use crate::land_sync_recovery_control::BeforeWrite;
35
36fn before_write<T>(result: Result<T>) -> Result<T> {
37 result.map_err(|error| {
38 if error.is::<BeforeWrite>() {
39 error
40 } else {
41 anyhow::Error::new(BeforeWrite(error))
42 }
43 })
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Request {
49 pub run: String,
51 pub head: String,
54 pub actor: String,
56 pub request: String,
58}
59
60#[derive(Debug, Clone)]
62pub struct Outcome {
63 pub task: Task,
65 pub repeated: bool,
67 pub reconciled: bool,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Revision {
74 pub request: String,
76 pub rev: u64,
78 pub instruction: String,
80 pub previous_instruction: String,
82 pub previous_task_instruction: Option<String>,
84 pub previous_rev: Option<u64>,
86 pub head: String,
88 pub repair: String,
90 pub invalidated_approval: Option<LandApproval>,
92 pub at: Timestamp,
94}
95
96impl RunState {
97 pub fn approval_revoked_by_revision(&self, question: &str) -> bool {
100 self.instruction_revisions.iter().any(|r| {
101 r.invalidated_approval
102 .as_ref()
103 .is_some_and(|a| a.question == question)
104 })
105 }
106
107 pub(crate) fn unfinished_instruction_revision(&self) -> Option<&Revision> {
110 self.instruction_revisions.last().filter(|revision| {
111 !self.merge_repairs.iter().any(|repair| {
112 repair.question == revision.repair && repair.phase == MergeRepairPhase::Complete
113 })
114 })
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "snake_case")]
120enum Phase {
121 Prepared,
122 Authorized,
123 Applied,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127struct Binding {
128 task: serde_json::Value,
129 instruction: String,
130 rev: u64,
131 head: String,
132 pr: String,
133 repair: String,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
137struct Receipt {
138 request: Request,
139 phase: Phase,
140 binding: Binding,
141 queued: Task,
142 created_at: Timestamp,
143 #[serde(default)]
144 applied_at: Option<Timestamp>,
145}
146
147fn save_receipt(path: &Path, receipt: &Receipt) -> Result<()> {
148 let tmp = path.with_extension("tmp");
149 std::fs::write(&tmp, serde_json::to_vec_pretty(receipt)?)?;
150 std::fs::rename(tmp, path)?;
151 Ok(())
152}
153
154pub fn receipt_path(home: &Path, actor: &str, request: &str) -> PathBuf {
156 home.join("instruction-revision-controls")
157 .join(actor)
158 .join(format!("{request}.json"))
159}
160
161pub fn adopt_into_run(
167 state: &mut RunState,
168 key: &str,
169 repair: &str,
170 instruction: &str,
171 rev: u64,
172 head: &str,
173 pr: &str,
174) {
175 let at = Timestamp::now();
176 state.instruction_revisions.push(Revision {
177 request: key.to_owned(),
178 rev,
179 instruction: instruction.to_owned(),
180 previous_instruction: std::mem::replace(&mut state.instruction, instruction.to_owned()),
181 previous_task_instruction: state.task_instruction.replace(instruction.to_owned()),
182 previous_rev: state.task_instruction_rev.replace(rev),
183 head: head.to_owned(),
184 repair: repair.to_owned(),
185 invalidated_approval: state.land_approval.take(),
186 at,
187 });
188 if let Some(e2e) = state.head_e2e.take() {
189 state
190 .verification_history
191 .push(crate::run::VerificationEvidence {
192 superseded_by: None,
193 archived_at: Some(at),
194 fixes_spent: Some(state.gate_fixes.len()),
195 gate_head: None,
196 gate_ran: false,
197 gate: Vec::new(),
198 e2e: Some(e2e),
199 });
200 }
201 state.merge_repairs.push(MergeRepair {
202 question: repair.to_owned(),
203 head: head.to_owned(),
204 pr: pr.to_owned(),
205 reviews: state.reviews.clone(),
206 gate: state.gate.clone(),
207 gate_head: state.gate_head.clone(),
208 gate_fixes: state.gate_fixes.clone(),
209 pre_gate: state.pre_gate.clone(),
210 phase: MergeRepairPhase::Requested,
211 failure: None,
212 });
213 state.gate_ran = false;
214 state.gate_head = None;
215 state.land_armed_head = None;
216 state.land_reruns = None;
217 state.parked = false;
218 state.status = RunStatus::Landing;
219 state.event(
220 "instruction-revision",
221 format!(
222 "owner adopted task instruction generation {rev} into this run and PR; bounded repair and a fresh review, E2E, gate and head-bound approval are required"
223 ),
224 );
225}
226
227pub async fn adopt(queue: &Queue, home: &Path, request: Request) -> Result<Outcome> {
229 adopt_with(queue, home, request, &GhPrObserver).await
230}
231
232#[allow(clippy::too_many_lines)]
234pub async fn adopt_with<O: PrObserver>(
235 queue: &Queue,
236 home: &Path,
237 mut request: Request,
238 observer: &O,
239) -> Result<Outcome> {
240 before_write((|| -> Result<()> {
241 ensure!(
242 crate::run::is_run_id(&request.run),
243 "instruction adoption needs a full run id"
244 );
245 ensure!(
246 crate::ask::valid_asset_name(&request.actor)
247 && crate::ask::valid_asset_name(&request.request),
248 "actor and request must be safe filenames of at most 64 bytes"
249 );
250 ensure!(
251 request.head.len() == 40 && request.head.bytes().all(|c| c.is_ascii_hexdigit()),
252 "instruction adoption needs a full 40-character HEAD SHA"
253 );
254 Ok(())
255 })())?;
256 request.head = request.head.to_ascii_lowercase();
257
258 let dir = home
259 .join("instruction-revision-controls")
260 .join(&request.actor);
261 before_write(std::fs::create_dir_all(&dir).map_err(Into::into))?;
262 let lock = before_write(
263 std::fs::OpenOptions::new()
264 .write(true)
265 .create(true)
266 .truncate(false)
267 .open(dir.join(format!("{}.lock", request.request)))
268 .map_err(Into::into),
269 )?;
270 before_write(crate::pr_head::try_lock_file(&lock).map_err(Into::into))?;
271
272 let path = receipt_path(home, &request.actor, &request.request);
273 let key = format!("{}/{}", request.actor, request.request);
274 let repair = format!("instruction-{}-{}", request.actor, request.request);
275
276 let prior: Option<Receipt> = if path.exists() {
277 let bytes = std::fs::read(&path).with_context(|| {
278 format!(
279 "uncertain instruction revision receipt: could not read {}; inspect before retrying",
280 path.display()
281 )
282 })?;
283 Some(serde_json::from_slice(&bytes).with_context(|| {
284 format!(
285 "uncertain instruction revision receipt: corrupt JSON in {}; inspect before retrying",
286 path.display()
287 )
288 })?)
289 } else {
290 None
291 };
292
293 if let Some(prior) = &prior {
294 if prior.request != request {
295 return Err(anyhow::Error::new(BeforeWrite(anyhow!(
296 "request ID already binds a different operation"
297 ))));
298 }
299 let task = queue.get(&prior.queued.id).with_context(|| {
300 format!(
301 "uncertain instruction revision receipt: owning task {} unreadable",
302 prior.queued.id
303 )
304 })?;
305 if prior.phase == Phase::Applied {
306 return Ok(Outcome {
307 task,
308 repeated: true,
309 reconciled: false,
310 });
311 }
312 if task.instruction_revision_requests.contains(&key) {
313 let mut completed = prior.clone();
314 completed.phase = Phase::Applied;
315 completed.applied_at = Some(Timestamp::now());
316 save_receipt(&path, &completed)?;
317 return Ok(Outcome {
318 task,
319 repeated: true,
320 reconciled: true,
321 });
322 }
323 }
324
325 let fresh = prior.is_none();
326 let wrap = |err: anyhow::Error| -> anyhow::Error {
327 if fresh {
328 anyhow::Error::new(BeforeWrite(err))
329 } else {
330 err
331 }
332 };
333
334 crate::task_reassign::ensure_current(queue, &request.run).map_err(&wrap)?;
335 let mut owners = queue
336 .list()
337 .into_iter()
338 .filter(|t| t.execution_runs().last() == Some(&request.run));
339 let listed = owners
340 .next()
341 .context("run has no eligible latest task owner")
342 .map_err(&wrap)?;
343 if owners.next().is_some() {
344 return Err(wrap(anyhow!("run has ambiguous task ownership")));
345 }
346 if let Some(prior) = &prior
347 && prior.queued.id != listed.id
348 {
349 return Err(anyhow!(
350 "uncertain instruction revision receipt: receipt targets task {} but current owner is {}",
351 prior.queued.id,
352 listed.id
353 ));
354 }
355 let _claim = queue
356 .claim_for_instruction_revision(&listed.id)
357 .context("task is claimed by a running daemon or another control")
358 .map_err(&wrap)?;
359 let task = queue.get(&listed.id).map_err(&wrap)?;
360
361 let _owner = crate::pr_head::owner_lock(home, &request.run).map_err(&wrap)?;
362 let mut state = RunState::load_under(&request.run, home).map_err(&wrap)?;
363 crate::pr_head::ensure_owner(&state).map_err(&wrap)?;
364 let adopted = state.instruction_revisions.iter().any(|r| r.request == key);
365 if state.instruction_revisions.last().is_some_and(|revision| {
366 revision.request != key
367 && !task
368 .instruction_revision_requests
369 .contains(&revision.request)
370 }) {
371 return Err(wrap(anyhow!(
372 "another instruction adoption is interrupted; replay its owner request first"
373 )));
374 }
375 match (&prior, adopted) {
376 (None, true) => {
377 return Err(anyhow!(
378 "uncertain instruction revision state: run already adopted request `{key}` without a receipt; inspect before retrying"
379 ));
380 }
381 (Some(p), false) if p.phase == Phase::Authorized => {
382 return Err(anyhow!(
383 "uncertain instruction revision receipt: receipt recorded adoption but the run has none for `{key}`; inspect before retrying"
384 ));
385 }
386 _ => {}
387 }
388 if !adopted {
389 verify(home, &request, &task, &state, observer, &wrap).await?;
390 } else {
391 crate::land_sync_recovery_control::check_latest_execution_run(&task, &state)?;
393 crate::land_sync_recovery_control::check_task_not_running_or_done(&task)?;
394 let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
395 ensure!(
396 state.liveness_under(home, claimed) == Liveness::Dead,
397 "run is live or its ownership is unknown"
398 );
399 }
400 let _maintenance = crate::driver::maintenance(home, &state.id).map_err(&wrap)?;
401
402 let pr = state
403 .pr
404 .as_ref()
405 .map(|p| p.url.clone())
406 .context("run has no recorded pull request")
407 .map_err(&wrap)?;
408 let binding = Binding {
409 task: serde_json::to_value(&task)
410 .map_err(anyhow::Error::from)
411 .map_err(&wrap)?,
412 instruction: task.instruction.clone(),
413 rev: task.instruction_rev,
414 head: request.head.clone(),
415 pr,
416 repair: repair.clone(),
417 };
418
419 let reconciled = prior.is_some();
420 let mut receipt = if let Some(prior) = prior {
421 ensure!(
422 prior.binding == binding || adopted && prior.binding.same_operation(&binding),
423 "interrupted instruction revision is stale: task, instruction, HEAD or PR changed"
424 );
425 prior
426 } else {
427 let mut queued = task.clone();
428 if !crate::repair_budget::queue_resumption(queue, &mut queued, &state.id).map_err(&wrap)? {
429 queued.release_operator("instruction-revision", None);
430 }
431 queued.resume_override = Some(OperatorResume {
432 question_id: String::new(),
433 at: Timestamp::now(),
434 conductor_rehold: None,
435 forced: true,
436 pinned_run: Some(state.id.clone()),
437 });
438 queued.instruction_revision_requests.push(key.clone());
439 let prepared = Receipt {
440 request: request.clone(),
441 phase: Phase::Prepared,
442 binding,
443 queued,
444 created_at: Timestamp::now(),
445 applied_at: None,
446 };
447 save_receipt(&path, &prepared)?;
448 prepared
449 };
450
451 if !adopted {
452 adopt_into_run(
453 &mut state,
454 &key,
455 &repair,
456 &receipt.binding.instruction,
457 receipt.binding.rev,
458 &receipt.binding.head,
459 &receipt.binding.pr,
460 );
461 state.save_under(home)?;
462 }
463 revoke_open_approval(&state, &key)?;
464 if receipt.phase == Phase::Prepared {
465 receipt.phase = Phase::Authorized;
466 save_receipt(&path, &receipt)?;
467 }
468
469 queue.commit_instruction_revision(&mut receipt.queued, &receipt.binding.task)?;
470 receipt.phase = Phase::Applied;
471 receipt.applied_at = Some(Timestamp::now());
472 save_receipt(&path, &receipt)?;
473
474 Ok(Outcome {
475 task: queue.get(&task.id)?,
476 repeated: false,
477 reconciled,
478 })
479}
480
481impl Binding {
482 fn same_operation(&self, other: &Self) -> bool {
485 self.instruction == other.instruction
486 && self.rev == other.rev
487 && self.head == other.head
488 && self.pr == other.pr
489 && self.repair == other.repair
490 }
491}
492
493fn revoke_open_approval(state: &RunState, key: &str) -> Result<()> {
497 let Some(revision) = state
498 .instruction_revisions
499 .iter()
500 .find(|r| r.request == key)
501 else {
502 return Ok(());
503 };
504 let Some(approval) = &revision.invalidated_approval else {
505 return Ok(());
506 };
507 let store = crate::ask::Questions::open();
508 if let Ok(mut question) = store.get_for_effects(&approval.question)
509 && question.status == crate::ask::QuestionStatus::Open
510 {
511 question.abandon("the task instruction was revised; this approval no longer applies");
512 store.put(&mut question)?;
513 }
514 Ok(())
515}
516
517async fn verify<O: PrObserver>(
519 home: &Path,
520 request: &Request,
521 task: &Task,
522 state: &RunState,
523 observer: &O,
524 wrap: &impl Fn(anyhow::Error) -> anyhow::Error,
525) -> Result<()> {
526 (|| -> Result<()> {
527 crate::land_sync_recovery_control::check_task_ownership(task, state, false)?;
528 ensure!(
529 state
530 .origin
531 .as_ref()
532 .and_then(|o| o.task.as_deref())
533 .is_none_or(|owner| owner == task.id),
534 "run belongs to another task"
535 );
536 ensure!(
537 task.instruction_rev > state.task_instruction_rev.unwrap_or(0)
538 && !task.instruction.trim().is_empty(),
539 "task has no newer instruction generation than the retained run"
540 );
541 let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
542 ensure!(
543 state.liveness_under(home, claimed) == Liveness::Dead,
544 "run is live or its ownership is unknown"
545 );
546 ensure!(
547 state.status.resumable()
548 && state.released_to.is_none()
549 && state.retired_to.is_none()
550 && state.pr_taken_over_by.is_none()
551 && state.merge_decision.is_none(),
552 "run ownership is final or holds an owner stop decision"
553 );
554 ensure!(
555 state.merge_repairs.iter().all(|r| matches!(
556 r.phase,
557 MergeRepairPhase::Complete | MergeRepairPhase::Failed
558 )),
559 "a repair is already in flight on this run"
560 );
561 ensure!(
562 state.merge_repairs.len() < state.config.graph.land_rounds
563 && state.config.graph.review_rounds > 0,
564 "repair generation budget exhausted or review disabled; no instruction revision was adopted"
565 );
566 Ok(())
567 })()
568 .map_err(wrap)?;
569
570 let winner = state
571 .winner()
572 .cloned()
573 .context("run has no retained winner")
574 .map_err(wrap)?;
575 if !git::is_clean(&winner.worktree).await.map_err(wrap)? {
576 return Err(wrap(anyhow!("retained worktree has uncommitted changes")));
577 }
578 let scratch = home.join("runs").join(&state.id).join("rebase");
579 if git::checked_rebase_in_progress(&scratch)
580 .await
581 .map_err(wrap)?
582 {
583 return Err(wrap(anyhow!(
584 "landing rebase is already in progress in scratch worktree"
585 )));
586 }
587 let local = git::rev_parse(&winner.worktree, "HEAD")
588 .await
589 .map_err(wrap)?;
590 let branch = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
591 .await
592 .map_err(wrap)?;
593 if local != branch {
594 return Err(wrap(anyhow!(
595 "retained worktree does not match the winner branch"
596 )));
597 }
598 if !local.eq_ignore_ascii_case(&request.head) {
599 return Err(wrap(anyhow!(
600 "retained HEAD changed since the owner request (expected {}, actual {local})",
601 request.head
602 )));
603 }
604 let pushed = state
605 .pr_pushed_head
606 .as_deref()
607 .context("run has no recorded published PR head")
608 .map_err(wrap)?;
609 if !pushed.eq_ignore_ascii_case(&local) {
610 return Err(wrap(anyhow!(
611 "retained HEAD ({local}) does not match recorded published PR head ({pushed})"
612 )));
613 }
614 let record = state
615 .pr
616 .as_ref()
617 .context("run has no recorded pull request")
618 .map_err(wrap)?;
619 if record.state != "open" {
620 return Err(wrap(anyhow!("recorded pull request is not open")));
621 }
622 let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
623 let remote = git::remote_head(&state.repo, &state.config.merge.remote, &public)
624 .await
625 .map_err(wrap)?;
626 if !remote
627 .as_deref()
628 .is_some_and(|r| r.eq_ignore_ascii_case(&local))
629 {
630 return Err(wrap(anyhow!(
631 "public branch `{public}` ({}) does not match retained HEAD ({local})",
632 remote.as_deref().unwrap_or("missing")
633 )));
634 }
635 let observed = observer
636 .observe_pr(&state.repo, &record.url)
637 .await
638 .map_err(wrap)?;
639 (|| -> Result<()> {
640 ensure!(observed.open, "pull request is no longer open");
641 ensure!(
642 observed.url == record.url && observed.number == record.number,
643 "observed pull request does not match the run's recorded pull request"
644 );
645 ensure!(
646 observed.head.eq_ignore_ascii_case(&local),
647 "published PR head ({}) does not match retained HEAD ({local})",
648 observed.head
649 );
650 if let Some(base) = observed.base_branch.as_deref().filter(|b| !b.is_empty()) {
651 ensure!(
652 base == state.base_branch,
653 "pull request base branch changed (expected {}, observed {base})",
654 state.base_branch
655 );
656 }
657 Ok(())
658 })()
659 .map_err(wrap)
660}
661
662#[cfg(test)]
663mod tests {
664 use super::*;
665 use crate::run::GateRepairE2e;
666
667 #[test]
668 fn adoption_revokes_approval_and_verification_but_keeps_history() {
669 let mut state = RunState::new(
670 PathBuf::from("."),
671 "main".into(),
672 "abc".into(),
673 "use teravars 0.7.0".into(),
674 crate::config::Config::default(),
675 );
676 state.task_instruction = Some("use teravars 0.7.0".into());
677 state.land_approval = Some(LandApproval {
678 question: "q-old".into(),
679 head: "h".into(),
680 });
681 state.land_armed_head = Some("h".into());
682 state.gate_ran = true;
683 state.gate_head = Some("h".into());
684 state.head_e2e = Some(GateRepairE2e::new("h".into(), true, Vec::new()));
685
686 adopt_into_run(
687 &mut state,
688 "cli/r",
689 "instruction-cli-r",
690 "use teravars 0.8.0",
691 3,
692 "h",
693 "https://github.com/o/r/pull/1",
694 );
695
696 assert!(state.land_approval.is_none() && state.land_armed_head.is_none());
697 assert!(!state.gate_ran && state.gate_head.is_none() && state.head_e2e.is_none());
698 assert_eq!(state.verification_history.len(), 1);
699 assert!(state.approval_revoked_by_revision("q-old"));
700 assert!(!state.approval_revoked_by_revision("q-new"));
701 assert_eq!(state.instruction, "use teravars 0.8.0");
703 assert_eq!(
704 state.task_instruction.as_deref(),
705 Some("use teravars 0.8.0")
706 );
707 assert_eq!(state.task_instruction_rev, Some(3));
708 let revision = &state.instruction_revisions[0];
709 assert_eq!(revision.previous_instruction, "use teravars 0.7.0");
710 assert_eq!(state.merge_repairs.len(), 1);
711 assert_eq!(state.merge_repairs[0].phase, MergeRepairPhase::Requested);
712 assert_eq!(state.merge_repairs[0].gate_head.as_deref(), Some("h"));
713 }
714}