taskfast_cli/cmd/settle.rs
1// SPDX-License-Identifier: MIT
2//! `taskfast settle` — poster signs an EIP-712 `DistributionApproval` and
3//! POSTs it to `/tasks/{id}/settle` to release escrowed funds.
4//!
5//! Pairs with server bead am-iyp6. The signing surface is identical to the
6//! one pinned in `taskfast_chains::tempo::sign_distribution`. The domain
7//! (`chain_id`, `verifying_contract`) prefers the task's per-task
8//! `settlement_domain` (venue-scoped — a Tempo Zone escrow for a zone-bound
9//! task; gh#865, ADR 0011 §5) and falls back to the global
10//! `GET /agents/me/readiness` domain when the task carries none, so the same
11//! binary signs correctly on L1 testnet/mainnet and in a zone without
12//! client-side chain config.
13//!
14//! Flow: parse UUID → `get_task` (pull `escrow_id` + `settlement_deadline` +
15//! `settlement_domain`) → readiness only if no per-task domain → sign →
16//! `POST /tasks/{id}/settle`. Dry-run skips the final POST but still signs
17//! so the envelope carries a real signature the caller can audit.
18//!
19//! Error mapping delegates to the shared `map_api_error` (401|403→Auth,
20//! 409|422→Validation); signing/keystore failures surface as `Wallet`
21//! (exit 5) via `SigningError`/`KeystoreError` → `CmdError`.
22
23use std::path::PathBuf;
24use std::str::FromStr;
25
26use alloy_primitives::{Address, B256, U256};
27use clap::Parser;
28use serde_json::json;
29use uuid::Uuid;
30
31use super::{CmdError, CmdResult, Ctx};
32use crate::envelope::Envelope;
33
34use taskfast_agent::bootstrap;
35use taskfast_chains::tempo::{sign_distribution, DistributionDomain};
36use taskfast_client::api::types::SettleTaskBody;
37use taskfast_client::map_api_error;
38
39#[derive(Debug, Parser)]
40pub struct Args {
41 /// Task UUID to settle. Task must have `escrow_id` + `settlement_deadline`
42 /// populated (i.e. escrow was created) and be in `:complete` or
43 /// `:disbursement_pending` on the server.
44 pub task_id: String,
45
46 /// Override the deadline signed into the approval. Defaults to the task's
47 /// `settlement_deadline` returned by `GET /tasks/{id}`. Unix seconds.
48 #[arg(long)]
49 pub deadline_unix: Option<u64>,
50
51 /// Keystore reference. Accepts a bare path (`/.../wallet.json`) or the
52 /// `file:/path` form written by `taskfast init` to `TEMPO_KEY_SOURCE`.
53 /// Mirrors `taskfast post`'s flag so a single keystore serves both verbs.
54 #[arg(long, env = "TEMPO_KEY_SOURCE")]
55 pub keystore: Option<String>,
56
57 /// Path to a file holding the keystore password (mode-0400 recommended).
58 /// `TASKFAST_WALLET_PASSWORD` env wins over this when both are set so CI
59 /// workflows can keep using the env-var form.
60 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
61 pub wallet_password_file: Option<PathBuf>,
62
63 /// Poster's wallet address (0x-prefixed). When present, we fail early if
64 /// the keystore decrypts to a different address — otherwise the server
65 /// would 422 after the round-trip. Purely a UX preflight.
66 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
67 pub wallet_address: Option<String>,
68
69 /// Acknowledge oversized budgets. Required when the task's budget
70 /// exceeds `confirm_above_budget` in the config. Mirrors the same
71 /// gate on `taskfast post`; both fail closed before any keystore
72 /// prompt or signing.
73 #[arg(long)]
74 pub yes: bool,
75}
76
77pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
78 // 1. Validate UUID upfront — bad input must not cost a round-trip.
79 let task_id = Uuid::parse_str(&args.task_id)
80 .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
81
82 let client = ctx.client()?;
83
84 // 2. Fetch task detail — we need escrow_id + settlement_deadline.
85 let task = match client.inner().get_task(&task_id).await {
86 Ok(v) => v.into_inner(),
87 Err(e) => return Err(map_api_error(e).await.into()),
88 };
89
90 // Fail-closed budget gate before keystore prompt or signing — a
91 // fat-finger settle on a huge task should die immediately.
92 ctx.enforce_budget_gate(task.budget_max.as_deref(), args.yes, "settle this task")?;
93
94 let escrow_id_hex: String = match task.escrow_id.as_ref().map(|e| e.to_string()) {
95 Some(e) => e,
96 None => {
97 // gh#143: dev auto-disburse settles without waiting for the
98 // poster's explicit `settle`, clearing the escrow data. When the
99 // task already reached (or is passing through) the settle target,
100 // report success with a note instead of the "no escrow_id" usage
101 // error — the goal the caller wanted is met. Missing escrow in
102 // any other state is a genuine not-ready error.
103 if let Some(note) = task.status.as_deref().and_then(settlement_note) {
104 return Ok(Envelope::success(
105 ctx.environment,
106 ctx.dry_run,
107 json!({
108 "task_id": task_id.to_string(),
109 "status": task.status,
110 "note": note,
111 }),
112 ));
113 }
114 return Err(CmdError::Usage(
115 "task has no escrow_id; settle requires an initialized escrow \
116 (task must be in :complete or :disbursement_pending)"
117 .into(),
118 ));
119 }
120 };
121
122 // 3. Resolve deadline: explicit override wins; otherwise require the
123 // server-stored value. Either can be absent but not both.
124 let deadline_unix: u64 = match args.deadline_unix {
125 Some(n) => n,
126 None => {
127 let dt = task.settlement_deadline.ok_or_else(|| {
128 CmdError::Usage(
129 "task has no settlement_deadline; either wait for escrow \
130 creation or pass --deadline-unix explicitly"
131 .into(),
132 )
133 })?;
134 // `timestamp()` is i64; clamp to u64 for the uint256. A negative
135 // server-side deadline is nonsensical; treat as decode.
136 u64::try_from(dt.timestamp()).map_err(|_| {
137 CmdError::Decode(format!(
138 "task settlement_deadline is before epoch: {}",
139 dt.to_rfc3339()
140 ))
141 })?
142 }
143 };
144
145 // 4. EIP-712 domain. Prefer the task's per-task `settlement_domain` — the
146 // venue-scoped domain (a Tempo Zone escrow + chain_id for a zone-bound
147 // task) that this task's escrow actually verifies against. Fall back to
148 // the global `GET /agents/me/readiness` domain only when the task carries
149 // none — a default-venue task, whose venue IS the readiness L1 domain, so
150 // the two are identical. Signing a zone task against the L1 domain would
151 // verify against the wrong escrow and the server would reject it (gh#865,
152 // ADR 0011 §5; mirrors the `escrow sign` fix in gh#111).
153 let (raw_chain_id, verifying_contract_str): (i64, String) =
154 match task.settlement_domain.as_ref() {
155 Some(d) => (d.chain_id, d.verifying_contract.to_string()),
156 None => {
157 let readiness = bootstrap::get_readiness(&client)
158 .await
159 .map_err(CmdError::from)?;
160 let d = readiness.settlement_domain;
161 (d.chain_id, d.verifying_contract.to_string())
162 }
163 };
164 let verifying_contract: Address = verifying_contract_str.parse().map_err(|e| {
165 CmdError::Decode(format!(
166 "settlement domain has invalid verifying_contract `{verifying_contract_str}`: {e}"
167 ))
168 })?;
169 let chain_id: u64 = u64::try_from(raw_chain_id).map_err(|_| {
170 CmdError::Decode(format!(
171 "settlement domain has negative chain_id: {raw_chain_id}"
172 ))
173 })?;
174 let domain = DistributionDomain::new(chain_id, verifying_contract);
175
176 // 5. Parse escrow_id. The server's schema already regex-validates the
177 // shape; we re-parse locally to produce a `B256` for signing. A parse
178 // failure here would be a server contract violation.
179 let escrow_id: B256 = B256::from_str(&escrow_id_hex).map_err(|e| {
180 CmdError::Decode(format!(
181 "server returned invalid escrow_id `{escrow_id_hex}`: {e}"
182 ))
183 })?;
184 let deadline = U256::from(deadline_unix);
185
186 // 6. Load keystore. Bead spec calls for the signature to appear in the
187 // dry-run envelope, so we sign even in dry-run and never short-circuit
188 // before keystore resolution.
189 let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
190 ctx.keystore_path
191 .as_deref()
192 .and_then(|p| p.to_str().map(str::to_string))
193 });
194 let signer = super::wallet_args::load_signer(
195 keystore_ref.as_deref(),
196 args.wallet_password_file.as_deref(),
197 "settlement approval",
198 )?;
199
200 // 7. Optional preflight: keystore must match --wallet-address if given.
201 // Without this, a mismatch surfaces as a server 422 after the full
202 // round-trip (including the get_task + readiness calls above).
203 let wallet_address_for_check = args
204 .wallet_address
205 .as_deref()
206 .or(ctx.wallet_address.as_deref());
207 if let Some(expected) = wallet_address_for_check {
208 let expected_addr: Address = expected.parse().map_err(|e| {
209 CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
210 })?;
211 if signer.address() != expected_addr {
212 return Err(CmdError::Usage(format!(
213 "keystore address {:#x} does not match --wallet-address {}",
214 signer.address(),
215 expected
216 )));
217 }
218 }
219
220 // 8. Sign the DistributionApproval. `sign_distribution` returns the
221 // 132-char 0x-prefixed `r||s||v` shape the server's verifier expects.
222 let signature_hex = sign_distribution(&signer, &domain, escrow_id, deadline)?;
223
224 // 9. Dry-run fork — envelope carries the real signature so callers can
225 // audit it (e.g., `cast wallet verify` or the Elixir verifier fixture)
226 // before committing the live POST.
227 if ctx.dry_run {
228 return Ok(Envelope::success(
229 ctx.environment,
230 ctx.dry_run,
231 json!({
232 "action": "would_settle",
233 "task_id": task_id.to_string(),
234 "escrow_id": escrow_id_hex,
235 "deadline": deadline_unix,
236 "domain": {
237 "chain_id": chain_id,
238 "verifying_contract": verifying_contract_str,
239 },
240 "signature": signature_hex,
241 }),
242 ));
243 }
244
245 // 10. Live POST. `signature` is a plain string in the current spec; the
246 // `0x`-prefixed 65-byte EIP-712 shape is validated server-side. A
247 // malformed value here would mean `sign_distribution` regressed
248 // (crypto-layer bug), not a network/server issue.
249 let body = SettleTaskBody {
250 signature: signature_hex,
251 };
252 let resp = match client.inner().settle_task(&task_id, &body).await {
253 Ok(v) => v.into_inner(),
254 Err(e) => {
255 let err = map_api_error(e).await;
256 // gh#143: auto-disburse can win the race between our preflight
257 // GET and this signed POST — a 409 `task_not_eligible` /
258 // `escrow_not_ready` then describes a task that already settled.
259 // Re-check the status and report success with a note. Genuine
260 // rejections (deadline_expired, signer_mismatch, …) and a
261 // re-check that finds no advancement stay errors.
262 if matches!(&err, taskfast_client::Error::Validation { code, .. }
263 if matches!(code.as_str(), "task_not_eligible" | "escrow_not_ready"))
264 {
265 if let Ok(advanced) = client.inner().get_task(&task_id).await {
266 let advanced = advanced.into_inner();
267 if let Some(note) = advanced.status.as_deref().and_then(settlement_note) {
268 return Ok(Envelope::success(
269 ctx.environment,
270 ctx.dry_run,
271 json!({
272 "task_id": task_id.to_string(),
273 "status": advanced.status,
274 "note": note,
275 }),
276 ));
277 }
278 }
279 }
280 return Err(err.into());
281 }
282 };
283
284 Ok(Envelope::success(
285 ctx.environment,
286 ctx.dry_run,
287 json!({
288 "task_id": resp.task_id,
289 "status": resp.status,
290 }),
291 ))
292}
293
294/// gh#143 note for a task whose settlement already happened (or is in
295/// flight) without this poster's explicit settle — the dev auto-disburse
296/// race. Every other status returns `None`: a settle problem there is a
297/// genuine failure, not an idempotent replay.
298fn settlement_note(status: &str) -> Option<&'static str> {
299 match status {
300 "settled" => Some("already settled"),
301 "disbursement_pending" => Some("settlement underway"),
302 _ => None,
303 }
304}