use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail, ensure};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::chat_control::{Filing, build_task};
use crate::queue::{Queue, Task};
use crate::talk::{Sender, Talk, Talks, Who};
const SCHEMA: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Phase {
Prepared,
Applied,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct OwnerOccurrence {
talk: String,
turn: usize,
accepted_at: Timestamp,
owner_input_sha256: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
external_request: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct AttachmentBinding {
name: String,
path: PathBuf,
sha256: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RequestBinding {
title: String,
instruction: String,
canonical_repo: PathBuf,
source: crate::queue::Source,
#[serde(default, skip_serializing_if = "Option::is_none")]
issue: Option<crate::queue::IssueRef>,
sources: crate::refs::Sources,
#[serde(default, skip_serializing_if = "Option::is_none")]
hold: Option<String>,
priority: i32,
solo: bool,
urgent: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
implementers: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
build_cache: Option<crate::config::BuildCache>,
attachments: Vec<AttachmentBinding>,
force: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Receipt {
schema: u32,
request: String,
occurrence: OwnerOccurrence,
binding: RequestBinding,
task_id: String,
phase: Phase,
created_at: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
applied_at: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
filed_task: Option<Task>,
}
fn sha256_hex(bytes: &[u8]) -> String {
let mut encoded = String::with_capacity(64);
for byte in Sha256::digest(bytes) {
write!(encoded, "{byte:02x}").expect("write to String");
}
encoded
}
pub(crate) fn receipt_path(home: &Path, talk_id: &str, request: &str) -> PathBuf {
home.join("immediate-filing-controls")
.join(talk_id)
.join(format!("{request}.json"))
}
fn save_receipt(path: &Path, receipt: &Receipt) -> Result<()> {
let tmp = path.with_extension(format!("tmp.{}", crate::rng::entropy()));
std::fs::write(&tmp, serde_json::to_vec_pretty(receipt)?)
.with_context(|| format!("write immediate filing receipt {}", tmp.display()))?;
std::fs::rename(&tmp, path)
.with_context(|| format!("replace immediate filing receipt {}", path.display()))?;
Ok(())
}
fn verify_owner_occurrence(talks: &Talks, talk: &Talk) -> Result<OwnerOccurrence> {
let turn_index = match crate::chat_goal::current_source() {
crate::chat_goal::Source::Input { turn } => turn,
crate::chat_goal::Source::External => {
bail!("external messages cannot authorize immediate task filing");
}
crate::chat_goal::Source::Automatic => {
bail!("automatic turns cannot authorize immediate task filing");
}
crate::chat_goal::Source::Goal { .. } => {
bail!("automatic goal turns cannot authorize immediate task filing");
}
crate::chat_goal::Source::Standing(_) => {
bail!("standing recovery turns cannot authorize immediate task filing");
}
};
let input = talk
.turns
.get(turn_index)
.context("owner input turn is absent")?;
ensure!(
input.who == Who::Operator,
"immediate task filing requires an explicit owner turn"
);
ensure!(
!talk.turns[turn_index + 1..]
.iter()
.any(|later| later.who == Who::Operator),
"owner input turn has been superseded by a newer turn"
);
ensure!(
input.sender != Some(Sender::External)
&& !input
.messages
.iter()
.any(|message| message.sender == Some(Sender::External)),
"external messages cannot authorize immediate task filing"
);
ensure!(
!input.messages.is_empty(),
"legacy or ambiguous chat turns cannot authorize immediate task filing"
);
ensure!(
input
.messages
.iter()
.all(|message| message.sender.is_some()),
"undated or ambiguous draft messages cannot authorize immediate task filing"
);
let operator_messages: Vec<&crate::talk::Message> = input
.messages
.iter()
.filter(|message| message.sender == Some(Sender::Operator))
.collect();
ensure!(
!operator_messages.is_empty(),
"turn contains no explicit owner message"
);
ensure!(
operator_messages
.iter()
.any(|message| !message.body.trim().is_empty() || !message.attachments.is_empty()),
"owner turn contains no actual request"
);
let accepted_at = crate::talk::owner_send_boundary(&input.messages)
.context("owner input turn is missing an explicit acceptance boundary")?;
let external_request = crate::talk::external::verify_owner_turn(talks, talk, turn_index)?;
let canonical_messages: Vec<_> = operator_messages
.iter()
.map(|message| {
serde_json::json!({
"accepted_at": message.accepted_at,
"body": message.body,
"attachments": message.attachments.iter().map(|a| &a.id).collect::<Vec<_>>(),
"reply": message.reply,
})
})
.collect();
let owner_input_sha256 = sha256_hex(&serde_json::to_vec(&canonical_messages)?);
Ok(OwnerOccurrence {
talk: talk.id.clone(),
turn: turn_index,
accepted_at,
owner_input_sha256,
external_request,
})
}
fn normalize_binding(talk_id: &str, filing: &Filing, force: bool) -> Result<RequestBinding> {
ensure!(
matches!(
&filing.source,
crate::queue::Source::Agent { run, node }
if run == talk_id && node == crate::queue::CHAT_NODE
),
"immediate filing must retain this conversation's provenance"
);
ensure!(
!filing.title.trim().is_empty() && !filing.instruction.trim().is_empty(),
"immediate filing requires a non-empty title and instruction"
);
ensure!(
filing.repo.is_absolute(),
"immediate filing repository must be an absolute path"
);
ensure!(
filing.repo.is_dir(),
"immediate filing repository does not exist: {}",
filing.repo.display()
);
let canonical_repo = std::fs::canonicalize(&filing.repo).with_context(|| {
format!(
"canonicalize immediate filing repository {}",
filing.repo.display()
)
})?;
let mut attachments = Vec::with_capacity(filing.attach.len());
for path in &filing.attach {
ensure!(
path.is_absolute(),
"immediate filing attachment must be an absolute path: {}",
path.display()
);
let name = path
.file_name()
.and_then(|n| n.to_str())
.with_context(|| format!("`{}` has no usable file name", path.display()))?;
ensure!(
crate::ask::valid_asset_name(name),
"attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ with no `..`"
);
ensure!(
path.is_file(),
"attachment `{}` is not a file",
path.display()
);
let canonical = std::fs::canonicalize(path)
.with_context(|| format!("canonicalize attachment {}", path.display()))?;
let bytes = std::fs::read(&canonical)
.with_context(|| format!("read attachment {}", canonical.display()))?;
attachments.push(AttachmentBinding {
name: name.to_owned(),
path: canonical,
sha256: sha256_hex(&bytes),
});
}
Ok(RequestBinding {
title: filing.title.clone(),
instruction: filing.instruction.clone(),
canonical_repo,
source: filing.source.clone(),
issue: filing.issue.clone(),
sources: filing.sources.clone(),
hold: filing.hold.clone(),
priority: filing.priority,
solo: filing.solo,
urgent: filing.urgent,
implementers: filing.implementers,
build_cache: filing.build_cache,
attachments,
force,
})
}
fn verify_copied_attachments(queue: &Queue, task: &Task, binding: &RequestBinding) -> Result<()> {
ensure!(
task.attachments.len() == binding.attachments.len(),
"immediate filing attachment count changed"
);
for (path, expected) in queue
.attachment_paths(task)
.iter()
.zip(&binding.attachments)
{
let bytes = std::fs::read(path)
.with_context(|| format!("read copied attachment {}", path.display()))?;
ensure!(
sha256_hex(&bytes) == expected.sha256,
"immediate filing attachment `{}` changed after request binding",
expected.name
);
}
Ok(())
}
fn stored_matches_binding(stored: &Task, expected_id: &str, binding: &RequestBinding) -> bool {
let repo_matches = std::fs::canonicalize(&stored.repo)
.ok()
.is_some_and(|canonical| canonical == binding.canonical_repo)
|| crate::git::same_checkout(&stored.repo, &binding.canonical_repo).unwrap_or(false);
stored.id == expected_id
&& stored.source == binding.source
&& stored.title == binding.title
&& stored.instruction == binding.instruction
&& repo_matches
}
fn load_and_verify_stored(queue: &Queue, task_id: &str, binding: &RequestBinding) -> Result<Task> {
let stored = queue.get(task_id).with_context(|| {
format!("uncertain immediate filing receipt: reserved task {task_id} is unreadable")
})?;
ensure!(
stored_matches_binding(&stored, task_id, binding),
"uncertain immediate filing receipt: reserved task {task_id} does not match this request"
);
Ok(stored)
}
pub(crate) async fn file(
queue: &Queue,
home: &Path,
talks: &Talks,
talk_id: &str,
request: &str,
filing: Filing,
force: bool,
) -> Result<Task> {
ensure!(
crate::ask::valid_asset_name(talk_id) && crate::ask::valid_asset_name(request),
"immediate filing talk and request IDs must be safe filenames of at most 64 bytes"
);
let talk = crate::chat_control::authorize(talks, talk_id, crate::queue::CHAT_NODE)?;
let occurrence = verify_owner_occurrence(talks, &talk)?;
let binding = normalize_binding(talk_id, &filing, force)?;
let dir = home.join("immediate-filing-controls").join(talk_id);
std::fs::create_dir_all(&dir)?;
let lock_file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(dir.join(format!("{request}.lock")))?;
let _lock = crate::pr_head::OwnerLock::acquire(lock_file)
.context("immediate filing request is already in progress")?;
let path = receipt_path(home, talk_id, request);
let prior = if path.try_exists()? {
let bytes = std::fs::read(&path).with_context(|| {
format!(
"uncertain immediate filing receipt: could not read {}; inspect before retrying",
path.display()
)
})?;
let receipt: Receipt = serde_json::from_slice(&bytes).with_context(|| {
format!(
"uncertain immediate filing receipt: corrupt JSON in {}; inspect before retrying",
path.display()
)
})?;
ensure!(
receipt.schema == SCHEMA && receipt.request == request,
"uncertain immediate filing receipt: unexpected schema or request identity in {}",
path.display()
);
Some(receipt)
} else {
None
};
if let Some(mut prior) = prior {
ensure!(
prior.occurrence == occurrence,
"request ID `{request}` already binds a different owner authorization boundary"
);
ensure!(
prior.binding == binding,
"request ID `{request}` already binds a different immediate task filing"
);
match prior.phase {
Phase::Applied => {
if queue.path_of(&prior.task_id).try_exists()? {
return queue.get(&prior.task_id).with_context(|| {
format!(
"uncertain immediate filing receipt: filed task {} is unreadable",
prior.task_id
)
});
}
return prior.filed_task.context(
"uncertain immediate filing receipt: applied task snapshot is missing",
);
}
Phase::Prepared => {
if queue.path_of(&prior.task_id).try_exists()? {
let stored = load_and_verify_stored(queue, &prior.task_id, &binding)?;
prior.phase = Phase::Applied;
prior.applied_at = Some(Timestamp::now());
prior.filed_task = Some(stored.clone());
save_receipt(&path, &prior)?;
return Ok(stored);
}
let attach = filing.attach.clone();
let mut task = build_task(filing, true);
task.id = prior.task_id.clone();
let created = queue.file_with_exact_id(&mut task, &attach, true, |task| {
verify_copied_attachments(queue, task, &binding)
})?;
let final_task = if created {
task
} else {
load_and_verify_stored(queue, &prior.task_id, &binding)?
};
prior.phase = Phase::Applied;
prior.applied_at = Some(Timestamp::now());
prior.filed_task = Some(final_task.clone());
save_receipt(&path, &prior)?;
return Ok(final_task);
}
}
}
if !force {
let hits = crate::dupes::check(
queue,
&home.join("runs"),
&filing.repo,
&filing.instruction,
None,
None,
);
let cfg = crate::config::Config::discover(&filing.repo, None)
.ok()
.map(|(cfg, _)| cfg);
let screened = crate::dupes::screen_with_config(
hits,
&filing.instruction,
None,
&filing.repo,
cfg.as_ref(),
)
.await
.map_err(|duplicate| {
anyhow::anyhow!(
"{}",
duplicate.render(
"Nothing was filed. If it is not a duplicate, ask the owner before repeating with --force."
)
)
})?;
if let crate::dupes::Screened::Unjudged(why) = screened {
tracing::warn!(%why, "duplicate-work judgement unavailable for immediate chat filing; filing anyway");
}
}
let task_id = queue.reserve_unused_id()?;
let mut receipt = Receipt {
schema: SCHEMA,
request: request.to_owned(),
occurrence,
binding,
task_id: task_id.clone(),
phase: Phase::Prepared,
created_at: Timestamp::now(),
applied_at: None,
filed_task: None,
};
save_receipt(&path, &receipt)?;
let attach = filing.attach.clone();
let mut task = build_task(filing, true);
task.id = task_id.clone();
let created = queue.file_with_exact_id(&mut task, &attach, false, |task| {
verify_copied_attachments(queue, task, &receipt.binding)
})?;
ensure!(
created,
"uncertain immediate filing: reserved task id {task_id} appeared concurrently"
);
receipt.phase = Phase::Applied;
receipt.applied_at = Some(Timestamp::now());
receipt.filed_task = Some(task.clone());
save_receipt(&path, &receipt)?;
Ok(task)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chat_control::{Operation, execute_authenticated};
use crate::chat_goal::Source as TurnSource;
use crate::config::{AgentKind, AgentSpec, BuildCache, Config};
use crate::queue::{IssueRef, Source as TaskSource, TaskStatus};
use crate::talk::{self, Message, Turn};
struct Fixture {
tmp: tempfile::TempDir,
queue: Queue,
talks: Talks,
repo_a: PathBuf,
repo_b: PathBuf,
talk: Talk,
}
impl Fixture {
fn new() -> Self {
let tmp = tempfile::tempdir().unwrap();
let repo_a = tmp.path().join("repo-a");
let repo_b = tmp.path().join("repo-b");
std::fs::create_dir_all(&repo_a).unwrap();
std::fs::create_dir_all(&repo_b).unwrap();
let mut cfg = Config::default();
cfg.agents.push(AgentSpec {
id: "fixture".into(),
kind: AgentKind::Command,
model: None,
command: vec!["true".into()],
extra_args: vec![],
env: Default::default(),
prompt_delivery: None,
max_turn_secs: None,
});
let queue = Queue::at(tmp.path().join("queue"));
let talks = Talks::at(tmp.path().join("talks"));
let talk = talk::begin(&talks, &cfg, repo_a.clone(), Some("fixture")).unwrap();
Self {
tmp,
queue,
talks,
repo_a,
repo_b,
talk,
}
}
fn home(&self) -> &Path {
self.tmp.path()
}
fn record_owner(&mut self, text: &str) -> usize {
talk::record(&mut self.talk, &self.talks, text, Vec::new()).unwrap();
self.talk.turns.len() - 1
}
fn filing(&self, repo: &Path, title: &str, instruction: &str) -> Filing {
Filing {
title: title.into(),
instruction: instruction.into(),
repo: repo.to_path_buf(),
source: TaskSource::Agent {
run: self.talk.id.clone(),
node: crate::queue::CHAT_NODE.into(),
},
issue: None,
sources: Default::default(),
hold: None,
priority: 0,
solo: true,
urgent: false,
implementers: None,
build_cache: None,
attach: Vec::new(),
}
}
}
#[tokio::test]
async fn owner_chat_turn_files_immediate_task_across_repos_and_preserves_fields() {
let mut fx = Fixture::new();
let turn = fx.record_owner("Please file shun issue #339 as immediate");
let shot = fx.home().join("shot.png");
std::fs::write(&shot, b"png-bytes").unwrap();
let mut filing = fx.filing(&fx.repo_b, "shun #339", "Fix shun issue #339");
filing.issue = Some(IssueRef {
number: 339,
repo: "example/shun".into(),
});
filing.hold = Some("waiting on owner check".into());
filing.priority = 7;
filing.urgent = true;
filing.implementers = Some(2);
filing.build_cache = Some(BuildCache::Isolated);
filing.attach = vec![shot];
let response = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-shun-339".into(),
filing: Box::new(filing),
force: false,
},
)
.await
.unwrap();
let filed: Task = serde_json::from_str(&response).unwrap();
assert!(filed.immediate);
assert!(filed.urgent);
assert!(filed.solo);
assert_eq!(filed.priority, 7);
assert_eq!(filed.status, TaskStatus::Held);
assert_eq!(filed.hold_reason.as_deref(), Some("waiting on owner check"));
assert_eq!(filed.repo, fx.repo_b);
assert_eq!(filed.issue.as_ref().map(|i| i.number), Some(339));
assert_eq!(filed.attachments, ["shot.png"]);
assert_eq!(filed.overrides.as_ref().and_then(|o| o.candidates), Some(2));
assert_eq!(
filed.overrides.as_ref().and_then(|o| o.build_cache),
Some(BuildCache::Isolated)
);
let stored = fx.queue.get(&filed.id).unwrap();
assert!(stored.immediate);
assert!(fx.queue.attachment_paths(&stored)[0].is_file());
let receipt: Receipt = serde_json::from_slice(
&std::fs::read(receipt_path(fx.home(), &fx.talk.id, "req-shun-339")).unwrap(),
)
.unwrap();
assert_eq!(receipt.phase, Phase::Applied);
assert_eq!(receipt.task_id, filed.id);
assert_eq!(
receipt.binding.canonical_repo,
std::fs::canonicalize(&fx.repo_b).unwrap()
);
assert_eq!(receipt.occurrence.turn, turn);
}
#[tokio::test]
async fn drained_owner_turn_and_cli_owner_binding_admit_while_unbound_cli_fails() {
let mut fx = Fixture::new();
talk::queue_magi(&mut fx.talk, &fx.talks, "Automatic notice").unwrap();
talk::queue(&mut fx.talk, &fx.talks, "File this immediate", Vec::new()).unwrap();
let (_, drained_turn) = talk::drain_indexed(&mut fx.talk, &fx.talks)
.unwrap()
.unwrap();
let response = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: drained_turn },
Operation::AddImmediate {
request: "req-drained".into(),
filing: Box::new(fx.filing(&fx.repo_a, "drained", "Drained immediate")),
force: false,
},
)
.await
.unwrap();
let filed: Task = serde_json::from_str(&response).unwrap();
assert!(filed.immediate);
let cli_turn = fx.record_owner("CLI owner request");
fx.talks
.mutate(&fx.talk.id, |t| {
t.external_requests.push(talk::external::Request {
request: "owner-req-1".into(),
sender: String::new(),
text: "CLI owner request".into(),
input_turn: cli_turn,
reply_turn: None,
status: "started".into(),
worker: None,
error: None,
});
Ok(())
})
.unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: cli_turn },
Operation::AddImmediate {
request: "req-unbound-cli".into(),
filing: Box::new(fx.filing(&fx.repo_a, "unbound", "Should fail")),
force: false,
},
)
.await
.unwrap_err();
assert!(
err.to_string().contains("no matching owner binding")
|| err.to_string().contains("external"),
"{err:#}"
);
let binding_dir = fx.talks.root().join("owner-requests");
std::fs::create_dir_all(&binding_dir).unwrap();
let binding_file = binding_dir.join(sha256_hex(b"owner-req-1"));
std::fs::write(
binding_file,
serde_json::json!({
"talk": fx.talk.id,
"text_sha256": sha256_hex(b"CLI owner request"),
})
.to_string(),
)
.unwrap();
let ok = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: cli_turn },
Operation::AddImmediate {
request: "req-bound-cli".into(),
filing: Box::new(fx.filing(&fx.repo_a, "bound", "Bound immediate")),
force: false,
},
)
.await
.unwrap();
let bound_task: Task = serde_json::from_str(&ok).unwrap();
assert!(bound_task.immediate);
let receipt: Receipt = serde_json::from_slice(
&std::fs::read(receipt_path(fx.home(), &fx.talk.id, "req-bound-cli")).unwrap(),
)
.unwrap();
assert_eq!(
receipt.occurrence.external_request.as_deref(),
Some("owner-req-1")
);
}
#[tokio::test]
async fn non_owner_sources_legacy_turns_superseded_turns_and_ordinary_add_behave_safely() {
let mut fx = Fixture::new();
let owner_turn = fx.record_owner("Owner request");
let ordinary: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: owner_turn },
Operation::Add {
filing: Box::new(fx.filing(&fx.repo_a, "ordinary", "Ordinary work")),
},
)
.await
.unwrap(),
)
.unwrap();
assert!(!ordinary.immediate);
for source in [TurnSource::Automatic, TurnSource::External] {
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
source,
Operation::AddImmediate {
request: "req-denied".into(),
filing: Box::new(fx.filing(&fx.repo_a, "denied", "Denied work")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("immediate"), "{err:#}");
}
let goal_id = "goal-imm";
fx.talks
.mutate(&fx.talk.id, |t| {
t.goals.push(serde_json::from_value(serde_json::json!({
"id": goal_id,
"rev": 1,
"purpose": "watch",
"scope": "repo",
"condition": { "description": "done", "kind": "tasks_done" },
"state": "runnable",
"step": "continue",
"source_turn": owner_turn,
"owner_input": "Owner request",
"tasks": [ordinary.id],
"runs": [],
"watches": [],
"evidence": "",
"wake": 1,
"handled": 0,
"started": 1,
"wakes": 1,
"fingerprint": "fp"
}))?);
Ok(())
})
.unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Goal {
id: goal_id.into(),
generation: 1,
},
Operation::AddImmediate {
request: "req-goal".into(),
filing: Box::new(fx.filing(&fx.repo_a, "goal", "Goal immediate")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("goal"), "{err:#}");
let mut held = Task::new(
"held".into(),
"held work".into(),
fx.repo_a.clone(),
TaskSource::Agent {
run: fx.talk.id.clone(),
node: crate::queue::CHAT_NODE.into(),
},
);
held.hold_machine(Some("ci failed".into()));
fx.queue.put(&mut held).unwrap();
let report_turn: Turn = serde_json::from_value(serde_json::json!({
"sender": "magi",
"who": "operator",
"body": "report",
"at": Timestamp::now(),
"messages": [{
"sender": "magi",
"body": "report",
"attachments": [],
"recovery_event": crate::chat_control::standing::Event::task(&held)
}]
}))
.unwrap();
let standing_source = crate::chat_control::standing::capture(
true,
fx.home(),
&fx.talks.get(&fx.talk.id).unwrap(),
Some(&report_turn),
TurnSource::Automatic,
);
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
standing_source.clone(),
Operation::Standing {
task: held.id.clone(),
evidence: "verified".into(),
command: Box::new(Operation::AddImmediate {
request: "req-standing".into(),
filing: Box::new(fx.filing(&fx.repo_a, "standing", "Standing immediate")),
force: false,
}),
},
)
.await
.unwrap_err();
assert!(
err.to_string()
.contains("outside the standing recovery allowlist"),
"{err:#}"
);
assert!(
execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
standing_source,
Operation::AddImmediate {
request: "req-standing-raw".into(),
filing: Box::new(fx.filing(&fx.repo_a, "standing", "Standing raw")),
force: false,
},
)
.await
.is_err()
);
let legacy_idx = fx
.talks
.mutate(&fx.talk.id, |t| {
let idx = t.turns.len();
t.turns.push(Turn {
sender: None,
who: Who::Operator,
body: "legacy owner".into(),
at: Timestamp::now(),
attachments: Vec::new(),
usage: None,
breaks: None,
messages: Vec::new(),
posted_by: None,
});
Ok(idx)
})
.unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: legacy_idx },
Operation::AddImmediate {
request: "req-legacy".into(),
filing: Box::new(fx.filing(&fx.repo_a, "legacy", "Legacy immediate")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("legacy or ambiguous"), "{err:#}");
let undated_idx = fx
.talks
.mutate(&fx.talk.id, |t| {
let idx = t.turns.len();
t.turns.push(Turn {
sender: Some(Sender::Operator),
who: Who::Operator,
body: "undated".into(),
at: Timestamp::now(),
attachments: Vec::new(),
usage: None,
breaks: None,
messages: vec![Message {
display: None,
recovery_event: None,
sender: Some(Sender::Operator),
accepted_at: None,
body: "undated".into(),
attachments: Vec::new(),
reply: None,
}],
posted_by: None,
});
Ok(idx)
})
.unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: undated_idx },
Operation::AddImmediate {
request: "req-undated".into(),
filing: Box::new(fx.filing(&fx.repo_a, "undated", "Undated immediate")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("acceptance boundary"), "{err:#}");
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: owner_turn },
Operation::AddImmediate {
request: "req-stale-turn".into(),
filing: Box::new(fx.filing(&fx.repo_a, "stale", "Stale turn immediate")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("superseded"), "{err:#}");
assert_eq!(fx.queue.list().iter().filter(|t| t.immediate).count(), 0);
}
#[tokio::test]
async fn idempotent_replay_binding_mismatches_and_prepared_crash_recovery() {
let mut fx = Fixture::new();
let turn = fx.record_owner("File shun #339 immediate with screenshot");
let shot = fx.home().join("shot.png");
std::fs::write(&shot, b"initial-png").unwrap();
let make_filing = |repo: &Path, instruction: &str| {
let mut f = fx.filing(repo, "shun #339", instruction);
f.attach = vec![shot.clone()];
f
};
let first: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-1".into(),
filing: Box::new(make_filing(&fx.repo_b, "Fix shun #339")),
force: false,
},
)
.await
.unwrap(),
)
.unwrap();
assert!(first.immediate);
let second: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-1".into(),
filing: Box::new(make_filing(&fx.repo_b, "Fix shun #339")),
force: false,
},
)
.await
.unwrap(),
)
.unwrap();
assert_eq!(second.id, first.id);
assert_eq!(fx.queue.list().len(), 1);
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-1".into(),
filing: Box::new(make_filing(&fx.repo_a, "Fix shun #339")),
force: false,
},
)
.await
.unwrap_err();
assert!(
err.to_string().contains("different immediate task filing"),
"{err:#}"
);
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-1".into(),
filing: Box::new(make_filing(&fx.repo_b, "Different instruction")),
force: false,
},
)
.await
.unwrap_err();
assert!(
err.to_string().contains("different immediate task filing"),
"{err:#}"
);
std::fs::write(&shot, b"tampered-png").unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-1".into(),
filing: Box::new(make_filing(&fx.repo_b, "Fix shun #339")),
force: false,
},
)
.await
.unwrap_err();
assert!(
err.to_string().contains("different immediate task filing"),
"{err:#}"
);
std::fs::write(&shot, b"initial-png").unwrap();
let path = receipt_path(fx.home(), &fx.talk.id, "req-recover-pre");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let occurrence = verify_owner_occurrence_for_test(&fx.talks, &fx.talk.id, turn).await;
let recover_filing = make_filing(&fx.repo_b, "Recover before queue write");
let binding = normalize_binding(&fx.talk.id, &recover_filing, false).unwrap();
let reserved_id = fx.queue.reserve_unused_id().unwrap();
let partial_dir = fx.queue.attachments_dir(&reserved_id);
std::fs::create_dir_all(&partial_dir).unwrap();
std::fs::write(partial_dir.join("shot.png"), b"half").unwrap();
let prepared = Receipt {
schema: SCHEMA,
request: "req-recover-pre".into(),
occurrence: occurrence.clone(),
binding: binding.clone(),
task_id: reserved_id.clone(),
phase: Phase::Prepared,
created_at: Timestamp::now(),
applied_at: None,
filed_task: None,
};
save_receipt(&path, &prepared).unwrap();
std::fs::remove_dir_all(&partial_dir).unwrap();
let collision = reserved_id.clone();
let alternate = "other-filing".to_owned();
let competing = Queue::at(fx.queue.root().to_owned()).with_id_source({
let ids = std::sync::Mutex::new([collision, alternate.clone()].into_iter());
move || ids.lock().unwrap().next().unwrap()
});
let mut other = build_task(fx.filing(&fx.repo_b, "other", "Other filing"), false);
other.id = reserved_id.clone();
assert!(!competing.create_new(&mut other).unwrap());
competing.put(&mut other).unwrap();
assert_eq!(other.id, alternate);
std::fs::create_dir_all(&partial_dir).unwrap();
std::fs::write(partial_dir.join("shot.png"), b"half").unwrap();
let recovered: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-recover-pre".into(),
filing: Box::new(recover_filing),
force: false,
},
)
.await
.unwrap(),
)
.unwrap();
assert_eq!(recovered.id, reserved_id);
assert!(recovered.immediate);
assert_eq!(
std::fs::read(&fx.queue.attachment_paths(&recovered)[0]).unwrap(),
b"initial-png"
);
let after: Receipt = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(after.phase, Phase::Applied);
let path_post = receipt_path(fx.home(), &fx.talk.id, "req-recover-post");
let post_filing = fx.filing(&fx.repo_b, "shun #340", "Recover after queue write");
let post_binding = normalize_binding(&fx.talk.id, &post_filing, false).unwrap();
let post_id = fx.queue.reserve_unused_id().unwrap();
let mut already = build_task(
fx.filing(&fx.repo_b, "shun #340", "Recover after queue write"),
true,
);
already.id = post_id.clone();
assert!(
fx.queue
.file_with_exact_id(&mut already, &[], false, |task| {
verify_copied_attachments(&fx.queue, task, &post_binding)
})
.unwrap()
);
save_receipt(
&path_post,
&Receipt {
schema: SCHEMA,
request: "req-recover-post".into(),
occurrence,
binding: post_binding,
task_id: post_id.clone(),
phase: Phase::Prepared,
created_at: Timestamp::now(),
applied_at: None,
filed_task: None,
},
)
.unwrap();
let reconciled: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-recover-post".into(),
filing: Box::new(post_filing),
force: false,
},
)
.await
.unwrap(),
)
.unwrap();
assert_eq!(reconciled.id, post_id);
assert_eq!(fx.queue.list().len(), 4);
let after_post: Receipt =
serde_json::from_slice(&std::fs::read(&path_post).unwrap()).unwrap();
assert_eq!(after_post.phase, Phase::Applied);
let corrupt_path = receipt_path(fx.home(), &fx.talk.id, "req-corrupt");
std::fs::write(&corrupt_path, b"{not valid json").unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-corrupt".into(),
filing: Box::new(fx.filing(&fx.repo_b, "corrupt", "Should fail")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("corrupt JSON"), "{err:#}");
assert_eq!(fx.queue.list().len(), 4);
let mut interrupted = after_post;
interrupted.phase = Phase::Prepared;
interrupted.applied_at = None;
interrupted.filed_task = None;
save_receipt(&path_post, &interrupted).unwrap();
fx.queue
.remove(
&post_id,
false,
&crate::ask::Questions::at(fx.home().join("questions")),
)
.unwrap();
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-recover-post".into(),
filing: Box::new(fx.filing(&fx.repo_b, "shun #340", "Recover after queue write")),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("was deleted"), "{err:#}");
assert!(!fx.queue.path_of(&post_id).exists());
assert_eq!(fx.queue.list().len(), 3);
let replay_filing = make_filing(&fx.repo_b, "Fix shun #339");
let next_turn = fx.record_owner("Another owner turn");
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn: next_turn },
Operation::AddImmediate {
request: "req-1".into(),
filing: Box::new(replay_filing),
force: false,
},
)
.await
.unwrap_err();
assert!(
err.to_string()
.contains("different owner authorization boundary"),
"{err:#}"
);
}
#[test]
fn changed_attachment_after_binding_cannot_be_published() {
let fx = Fixture::new();
let path = fx.home().join("shot.png");
std::fs::write(&path, b"original").unwrap();
let mut filing = fx.filing(&fx.repo_b, "task", "File with attachment");
filing.attach.push(path.clone());
let binding = normalize_binding(&fx.talk.id, &filing, false).unwrap();
let sources = filing.attach.clone();
let mut task = build_task(filing, true);
task.id = fx.queue.reserve_unused_id().unwrap();
std::fs::write(&path, b"changed during duplicate screening").unwrap();
let error = fx
.queue
.file_with_exact_id(&mut task, &sources, false, |task| {
verify_copied_attachments(&fx.queue, task, &binding)
})
.unwrap_err();
assert!(error.to_string().contains("changed after request binding"));
assert!(!fx.queue.path_of(&task.id).exists());
assert!(!fx.queue.attachments_dir(&task.id).exists());
std::fs::write(&path, b"original").unwrap();
assert!(
fx.queue
.file_with_exact_id(&mut task, &sources, true, |task| {
verify_copied_attachments(&fx.queue, task, &binding)
})
.unwrap()
);
assert_eq!(
std::fs::read(&fx.queue.attachment_paths(&task)[0]).unwrap(),
b"original"
);
}
async fn verify_owner_occurrence_for_test(
talks: &Talks,
talk_id: &str,
turn: usize,
) -> OwnerOccurrence {
let talk = talks.get(talk_id).unwrap();
crate::chat_goal::with_source(TurnSource::Input { turn }, async {
verify_owner_occurrence(talks, &talk).unwrap()
})
.await
}
#[tokio::test]
async fn duplicate_screening_runs_after_receipt_lookup_and_writes_no_receipt_on_refusal() {
let mut fx = Fixture::new();
let judge_script = fx.repo_b.join("dupes-judge.sh");
std::fs::write(
&judge_script,
"#!/bin/sh\nprintf '{\"duplicate\":true,\"reason\":\"already owned by live task\"}\\n'\n",
)
.unwrap();
let cfg = Config {
agents: vec![AgentSpec {
id: "judge".into(),
kind: AgentKind::Command,
model: None,
command: vec![
"sh".into(),
judge_script.to_string_lossy().replace('\\', "/"),
],
extra_args: vec![],
env: Default::default(),
prompt_delivery: None,
max_turn_secs: Some(30),
}],
roles: crate::config::Roles {
dupes_judge: Some(crate::config::AgentChoice::One("judge".into())),
..Default::default()
},
..Config::default()
};
std::fs::write(fx.repo_b.join("magi.toml"), toml::to_string(&cfg).unwrap()).unwrap();
let turn = fx.record_owner("File branch magi/ab12/A as immediate");
let first: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-dup-1".into(),
filing: Box::new(fx.filing(
&fx.repo_b,
"branch work",
"Review and fix branch magi/ab12/A",
)),
force: false,
},
)
.await
.unwrap(),
)
.unwrap();
let mut owned = fx.queue.get(&first.id).unwrap();
owned.review_branch = Some("magi/ab12/A".into());
fx.queue.put(&mut owned).unwrap();
let replayed: Task = serde_json::from_str(
&execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-dup-1".into(),
filing: Box::new(fx.filing(
&fx.repo_b,
"branch work",
"Review and fix branch magi/ab12/A",
)),
force: false,
},
)
.await
.unwrap(),
)
.unwrap();
assert_eq!(replayed.id, first.id);
let err = execute_authenticated(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
TurnSource::Input { turn },
Operation::AddImmediate {
request: "req-dup-2".into(),
filing: Box::new(fx.filing(
&fx.repo_b,
"branch work",
"Review and fix branch magi/ab12/A",
)),
force: false,
},
)
.await
.unwrap_err();
assert!(err.to_string().contains("Nothing was filed"), "{err:#}");
assert!(!receipt_path(fx.home(), &fx.talk.id, "req-dup-2").exists());
}
#[tokio::test]
async fn dispatch_refuses_add_immediate_without_authenticated_bridge() {
let mut fx = Fixture::new();
let turn = fx.record_owner("File immediate");
let _ = turn;
let err = crate::chat_control::dispatch(
&fx.queue,
fx.home(),
&fx.talks,
&fx.talk.id,
Operation::AddImmediate {
request: "req-no-bridge".into(),
filing: Box::new(fx.filing(&fx.repo_a, "no bridge", "Must fail locally")),
force: false,
},
)
.await
.unwrap_err();
assert!(
err.to_string()
.contains("requires the authenticated chat control channel"),
"{err:#}"
);
assert!(fx.queue.list().is_empty());
}
}