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.as_second()).map_err(|_| {
137 CmdError::Decode(format!("task settlement_deadline is before epoch: {dt}"))
138 })?
139 }
140 };
141
142 // 4. EIP-712 domain. Prefer the task's per-task `settlement_domain` — the
143 // venue-scoped domain (a Tempo Zone escrow + chain_id for a zone-bound
144 // task) that this task's escrow actually verifies against. Fall back to
145 // the global `GET /agents/me/readiness` domain only when the task carries
146 // none — a default-venue task, whose venue IS the readiness L1 domain, so
147 // the two are identical. Signing a zone task against the L1 domain would
148 // verify against the wrong escrow and the server would reject it (gh#865,
149 // ADR 0011 §5; mirrors the `escrow sign` fix in gh#111).
150 let (raw_chain_id, verifying_contract_str): (i64, String) =
151 match task.settlement_domain.as_ref() {
152 Some(d) => (d.chain_id, d.verifying_contract.to_string()),
153 None => {
154 let readiness = bootstrap::get_readiness(&client)
155 .await
156 .map_err(CmdError::from)?;
157 let d = readiness.settlement_domain;
158 (d.chain_id, d.verifying_contract.to_string())
159 }
160 };
161 let verifying_contract: Address = verifying_contract_str.parse().map_err(|e| {
162 CmdError::Decode(format!(
163 "settlement domain has invalid verifying_contract `{verifying_contract_str}`: {e}"
164 ))
165 })?;
166 let chain_id: u64 = u64::try_from(raw_chain_id).map_err(|_| {
167 CmdError::Decode(format!(
168 "settlement domain has negative chain_id: {raw_chain_id}"
169 ))
170 })?;
171 let domain = DistributionDomain::new(chain_id, verifying_contract);
172
173 // 5. Parse escrow_id. The server's schema already regex-validates the
174 // shape; we re-parse locally to produce a `B256` for signing. A parse
175 // failure here would be a server contract violation.
176 let escrow_id: B256 = B256::from_str(&escrow_id_hex).map_err(|e| {
177 CmdError::Decode(format!(
178 "server returned invalid escrow_id `{escrow_id_hex}`: {e}"
179 ))
180 })?;
181 let deadline = U256::from(deadline_unix);
182
183 // 6. Load keystore and validate --wallet-address preflight.
184 // Bead spec calls for the signature to appear in the dry-run envelope,
185 // so we sign even in dry-run and never short-circuit before keystore resolution.
186 let keystore_path = super::wallet_args::resolve_keystore_path(
187 args.keystore.as_deref(),
188 ctx.keystore_path.as_deref(),
189 );
190 let signer = super::wallet_args::load_signer_and_validate(
191 keystore_path.as_deref(),
192 args.wallet_password_file.as_deref(),
193 args.wallet_address
194 .as_deref()
195 .or(ctx.wallet_address.as_deref()),
196 "settlement approval",
197 )?;
198
199 // 8. Sign the DistributionApproval. `sign_distribution` returns the
200 // 132-char 0x-prefixed `r||s||v` shape the server's verifier expects.
201 let signature_hex = sign_distribution(&signer, &domain, escrow_id, deadline)?;
202
203 // 9. Dry-run fork — envelope carries the real signature so callers can
204 // audit it (e.g., `cast wallet verify` or the Elixir verifier fixture)
205 // before committing the live POST.
206 if ctx.dry_run {
207 return Ok(Envelope::success(
208 ctx.environment,
209 ctx.dry_run,
210 json!({
211 "action": "would_settle",
212 "task_id": task_id.to_string(),
213 "escrow_id": escrow_id_hex,
214 "deadline": deadline_unix,
215 "domain": {
216 "chain_id": chain_id,
217 "verifying_contract": verifying_contract_str,
218 },
219 "signature": signature_hex,
220 }),
221 ));
222 }
223
224 // 10. Live POST. `signature` is a plain string in the current spec; the
225 // `0x`-prefixed 65-byte EIP-712 shape is validated server-side. A
226 // malformed value here would mean `sign_distribution` regressed
227 // (crypto-layer bug), not a network/server issue.
228 let body = SettleTaskBody {
229 signature: signature_hex,
230 };
231 let resp = match client.inner().settle_task(&task_id, &body).await {
232 Ok(v) => v.into_inner(),
233 Err(e) => {
234 let err = map_api_error(e).await;
235 // gh#143: auto-disburse can win the race between our preflight
236 // GET and this signed POST — a 409 `task_not_eligible` /
237 // `escrow_not_ready` then describes a task that already settled.
238 // Re-check the status and report success with a note. Genuine
239 // rejections (deadline_expired, signer_mismatch, …) and a
240 // re-check that finds no advancement stay errors.
241 if matches!(&err, taskfast_client::Error::Validation { code, .. }
242 if matches!(code.as_str(), "task_not_eligible" | "escrow_not_ready"))
243 {
244 if let Ok(advanced) = client.inner().get_task(&task_id).await {
245 let advanced = advanced.into_inner();
246 if let Some(note) = advanced.status.as_deref().and_then(settlement_note) {
247 return Ok(Envelope::success(
248 ctx.environment,
249 ctx.dry_run,
250 json!({
251 "task_id": task_id.to_string(),
252 "status": advanced.status,
253 "note": note,
254 }),
255 ));
256 }
257 }
258 }
259 return Err(err.into());
260 }
261 };
262
263 Ok(Envelope::success(
264 ctx.environment,
265 ctx.dry_run,
266 json!({
267 "task_id": resp.task_id,
268 "status": resp.status,
269 }),
270 ))
271}
272
273/// gh#143 note for a task whose settlement already happened (or is in
274/// flight) without this poster's explicit settle — the dev auto-disburse
275/// race. Every other status returns `None`: a settle problem there is a
276/// genuine failure, not an idempotent replay.
277fn settlement_note(status: &str) -> Option<&'static str> {
278 match status {
279 "settled" => Some("already settled"),
280 "disbursement_pending" => Some("settlement underway"),
281 _ => None,
282 }
283}