Skip to main content

optimization_runner/mcp/
tools.rs

1//! The tools of `optimization-mcp` and the `optimization-run` calls behind
2//! them.
3use super::{Ctx, Launch, Server, guide, inputs, tasks};
4use optimization_job_api::{
5    Input, JobSpec, MAX_INPUT_BYTES, checked_input, process::bounded_command_until, storage::digest,
6};
7use serde::Deserialize;
8use serde_json::{Value, json, value::RawValue};
9use std::{
10    collections::BTreeMap,
11    fs,
12    io::ErrorKind,
13    path::{Component, Path, PathBuf},
14    process::{Command, Stdio},
15    thread,
16    time::{Duration, Instant, SystemTime},
17};
18
19/// Job states after which nothing changes.
20pub const TERMINAL: [&str; 5] = [
21    "completed",
22    "failed",
23    "cancelled",
24    "timed_out",
25    "interrupted",
26];
27/// Deadlines of runner calls: reads, and calls that run worker validation.
28const QUICK: Duration = Duration::from_secs(30);
29const SLOW: Duration = Duration::from_secs(120);
30/// Output cap of one runner call.
31const OUTPUT_CAP: usize = 64 * 1024 * 1024;
32/// Tasks listed by a result summary, and the size of `full` results.
33const SUMMARY_TASKS: usize = 100;
34const FULL_CAP: usize = 1024 * 1024;
35const MAX_WAIT_SECONDS: f64 = 600.0;
36/// Deadline of commands that change a job; they are never aborted.
37const MUTATING: Duration = Duration::from_secs(600);
38/// Largest result manifest read (one in-memory copy per request).
39const MANIFEST_CAP: u64 = 256 * 1024 * 1024;
40
41pub struct ToolError {
42    pub code: String,
43    pub message: String,
44    pub retryable: bool,
45}
46
47impl ToolError {
48    pub fn value(&self) -> Value {
49        json!({"error":{"code":self.code,"message":self.message,"retryable":self.retryable}})
50    }
51}
52
53pub enum Fail {
54    Tool(ToolError),
55    /// The request was cancelled or the server is shutting down.
56    Cancelled,
57}
58
59pub enum Outcome {
60    Done(Value),
61    Failed(ToolError),
62    /// A `CreateTaskResult` (Tasks extension).
63    Task(Value),
64    Cancelled,
65}
66
67pub(super) fn fail(code: &str, message: impl Into<String>) -> Fail {
68    Fail::Tool(ToolError {
69        code: code.into(),
70        message: message.into(),
71        retryable: false,
72    })
73}
74
75/// A `CallToolResult`: the value as structured content and, for clients that
76/// read only text, as its JSON.
77pub fn tool_result(value: Value, is_error: bool) -> Value {
78    json!({
79        "content": [{"type":"text","text":value.to_string()}],
80        "structuredContent": value,
81        "isError": is_error,
82    })
83}
84
85pub fn terminal(state: &Value) -> bool {
86    state.as_str().is_some_and(|s| TERMINAL.contains(&s))
87}
88
89/// Sleeps up to `duration`, returning early once the request is stopped.
90pub fn pause(server: &Server, ctx: &Ctx, duration: Duration) {
91    let start = Instant::now();
92    while start.elapsed() < duration && !ctx.stopped(server) {
93        thread::sleep(Duration::from_millis(50).min(duration));
94    }
95}
96
97fn random_hex() -> String {
98    use std::io::Read;
99    let mut bytes = [0u8; 16];
100    if fs::File::open("/dev/urandom")
101        .and_then(|mut f| f.read_exact(&mut bytes))
102        .is_err()
103    {
104        // Unpredictable enough for file names; task IDs need urandom.
105        let nanos = SystemTime::now()
106            .duration_since(SystemTime::UNIX_EPOCH)
107            .map(|d| d.as_nanos())
108            .unwrap_or_default();
109        return digest(format!("{nanos}-{}", std::process::id()).as_bytes())[..32].to_owned();
110    }
111    bytes.iter().map(|b| format!("{b:02x}")).collect()
112}
113
114pub fn task_token() -> std::io::Result<String> {
115    use std::io::Read;
116    let mut bytes = [0u8; 16];
117    fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
118    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
119}
120
121fn object(properties: Value, required: &[&str]) -> Value {
122    json!({"type":"object","properties":properties,"required":required,"additionalProperties":false})
123}
124
125pub(super) fn job_id_property() -> Value {
126    json!({"type":"string","pattern":"^[0-9a-f]{32}$","description":"Job ID, as returned by submit_job or list_jobs."})
127}
128
129/// The job envelope schema, embedded in the tools that take a job.
130fn envelope_schema() -> Value {
131    // A copy inside the crate, so the published package builds on its own;
132    // a test keeps it identical to docs/job-api/schemas.
133    let mut schema: Value = serde_json::from_str(include_str!(
134        "../../schemas/optimization.job-0.1.schema.json"
135    ))
136    .expect("the job schema is valid JSON");
137    let object = schema.as_object_mut().expect("the job schema is an object");
138    object.remove("$schema");
139    object.remove("$id");
140    object.insert(
141        "description".into(),
142        json!("An optimization.job/0.1 envelope (fcmaes.job/0.1 legacy specifications are accepted too). The payload follows the worker profile named by payload_schema; describe_worker lists them."),
143    );
144    schema
145}
146
147fn job_properties() -> Value {
148    json!({
149        "job": envelope_schema(),
150        "spec_path": {"type":"string","description":"Path of a job file on this machine, instead of job. Its relative input files are read from the file's directory."},
151        "input_dir": {"type":"string","description":"Directory the relative input files of job are read from; by default the server's input directory. Each file must match its SHA-256."},
152    })
153}
154
155/// Tool name, title, annotations, description and input schema.
156pub fn definitions(modern: bool) -> Vec<Value> {
157    let read = json!({"readOnlyHint":true,"openWorldHint":false});
158    let job_id = job_id_property();
159    let tools = [
160        (
161            "get_guide",
162            "Read the guide for agents",
163            read.clone(),
164            "The guide for agents (ai-context.md of optimization-jobs): which solver and profile fit a problem (LP or MIP, smooth NLP, black box, several objectives, diverse solutions, expensive simulations), library or job, installation, the job API and this server. Call it first when no solver or profile has been chosen yet. With section, only the first section whose heading contains that text (case-insensitive), with its subsections; an unknown section lists the headings.",
165            object(
166                json!({"section":{"type":"string","minLength":1,"description":"Text that a heading contains; without it, the whole guide."}}),
167                &[],
168            ),
169        ),
170        (
171            "describe_node",
172            "Describe the node",
173            read.clone(),
174            "The node's CPU capacity (slots), how jobs are launched, the CPUs and memory the host gives its jobs (host: affinity, cgroup quota and limit, physical cores, NUMA nodes) with warnings such as a capacity above the usable CPUs, and its registered workers with their profiles and builds. Start here once a solver is chosen.",
175            object(json!({}), &[]),
176        ),
177        (
178            "describe_worker",
179            "Describe a worker",
180            read.clone(),
181            "Everything a registered worker declares: its profiles (payload_schema values), problems, optimizers or backends and their options, claims, cancellation and resource rules. Read it before writing a payload.",
182            object(
183                json!({"worker":{"type":"string","description":"ID of a registered worker, from describe_node."}}),
184                &["worker"],
185            ),
186        ),
187        (
188            "put_input",
189            "Store an input file",
190            json!({"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}),
191            "Stores data that a job reads as an input file, such as a new LP model, in this node's content-addressed input store, and returns file, sha256, bytes and input_dir. A job then lists {\"name\": NAME, \"file\": file, \"sha256\": sha256} in inputs and is passed to validate_job and submit_job with input_dir; inputs stored this way share input_dir, so one job can use several. Pass exactly one of content (text, stored as its UTF-8 bytes; a JSON input as its serialized text), content_base64 (bytes) or from_artifact (a file of an existing job, to use it together with other stored inputs). Storing the same content again returns the same file. At most 64 MiB per input; the store holds data, never code.",
192            object(
193                json!({
194                    "content": {"type":"string","description":"Text, stored as its UTF-8 bytes; a JSON input as the text a JSON serializer wrote."},
195                    "content_base64": {"type":"string","contentEncoding":"base64","description":"Bytes in base64 (RFC 4648)."},
196                    "from_artifact": {
197                        "type":"object",
198                        "description":"An artifact of an existing job, copied into the store as get_artifact reads it whole.",
199                        "properties":{"job_id":job_id,"name":{"type":"string","description":"Artifact name from artifact_index of get_job or the result."}},
200                        "required":["job_id","name"],
201                        "additionalProperties":false,
202                    },
203                }),
204                &[],
205            ),
206        ),
207        (
208            "validate_job",
209            "Validate a job",
210            read.clone(),
211            "Checks a job without starting it: the envelope, the input files and the worker's own validation of the payload. Returns the resolved job with its task_count, or an invalid_job error explaining the problem. Pass exactly one of job or spec_path.",
212            object(job_properties(), &[]),
213        ),
214        (
215            "submit_job",
216            "Submit a job",
217            json!({"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}),
218            "Starts a job and returns its handle (job_id, state, directory) once the job exists durably. Submission is idempotent: the same request_key with the same content returns the existing job; other content under a used key fails with request_key_conflict. A job that needs more CPU slots than are free waits; one that needs more than the node has fails with capacity_exceeded. The job runs detached from this server and survives its restart. Clients with the MCP Tasks extension get a task that completes with the job's result. Pass exactly one of job or spec_path.",
219            object(job_properties(), &[]),
220        ),
221        (
222            "get_job",
223            "Get a job's state",
224            read.clone(),
225            "The job's state (submitted, starting, waiting, running, completed, failed, cancelled, timed_out or interrupted), its progress (completed and requested tasks, known work) and its directory. observed_state reports a launcher lost or an attempt interrupted by a reboot; repair_job finalizes those.",
226            object(json!({"job_id":job_id}), &["job_id"]),
227        ),
228        (
229            "wait_job",
230            "Wait for a job",
231            read.clone(),
232            "Waits until the job ends, is observed interrupted, or timeout_seconds pass, and returns get_job's answer. Call again to keep waiting. Reports progress (completed tasks) when the client asks for it.",
233            object(
234                json!({"job_id":job_id,"timeout_seconds":{"type":"number","exclusiveMinimum":0,"maximum":MAX_WAIT_SECONDS,"default":30,"description":"At most 600."}}),
235                &["job_id"],
236            ),
237        ),
238        (
239            "get_result",
240            "Get a job's result",
241            read.clone(),
242            "The result of an ended job. By default a summary: status, accounting, counts of claims and terminations, and per task its claim, termination, feasibility, objective and evidence (the first 100 tasks; no points). tasks returns the complete records (points, details) of the given task IDs; full returns the whole result manifest if it is under 1 MiB. A job that has not ended returns not_finished.",
243            object(
244                json!({
245                    "job_id": job_id,
246                    "tasks": {"type":"array","items":{"type":"integer","minimum":0},"maxItems":100,"description":"Task IDs whose complete records to return."},
247                    "full": {"type":"boolean","default":false,"description":"Return the whole result manifest."},
248                }),
249                &["job_id"],
250            ),
251        ),
252        (
253            "get_events",
254            "Get a job's events",
255            read.clone(),
256            "The job's lifecycle journal (admission, start, cancellation, deadline, finish), newest last.",
257            object(
258                json!({"job_id":job_id,"limit":{"type":"integer","minimum":1,"maximum":1000,"default":50,"description":"Return the last limit events."}}),
259                &["job_id"],
260            ),
261        ),
262        (
263            "get_artifact",
264            "Read a job artifact",
265            read.clone(),
266            "A file of a job, also while it runs: results (the result journal) or an artifact its worker declared, such as an evaluation log or a warm-start snapshot. get_job lists them with format and size (artifact_index); the result adds their SHA-256. Without offset and limit, the whole content up to 1 MiB; with them, a page of the checked records of a records artifact, continued from next_offset while it is below available.",
267            object(
268                json!({
269                    "job_id":job_id,
270                    "name":{"type":"string","description":"Artifact name from artifact_index of get_job or the result."},
271                    "offset":{"type":"integer","minimum":0,"description":"First record of the page; records artifacts only."},
272                    "limit":{"type":"integer","minimum":1,"maximum":10000,"description":"Records of the page (default 100); records artifacts only."},
273                }),
274                &["job_id", "name"],
275            ),
276        ),
277        (
278            "list_jobs",
279            "List jobs",
280            read,
281            "The jobs on this node, newest first: ID, state, progress and timestamps.",
282            object(
283                json!({
284                    "active_only": {"type":"boolean","default":false,"description":"Only jobs that have not ended."},
285                    "limit": {"type":"integer","minimum":1,"maximum":1000,"default":50},
286                }),
287                &[],
288            ),
289        ),
290        (
291            "cancel_job",
292            "Cancel a job",
293            json!({"readOnlyHint":false,"destructiveHint":true,"idempotentHint":true,"openWorldHint":false}),
294            "Stops a job gracefully: running tasks finish their current unit of work (a retry, a generation, a solve) and every completed task stays in the result; the job ends cancelled. A job that has already ended returns already_terminal.",
295            object(json!({"job_id":job_id}), &["job_id"]),
296        ),
297        (
298            "kill_job",
299            "Kill a job",
300            json!({"readOnlyHint":false,"destructiveHint":true,"idempotentHint":true,"openWorldHint":false}),
301            "Stops a job immediately: the worker is killed after one second and the work in progress is lost; committed task results stay. Prefer cancel_job.",
302            object(json!({"job_id":job_id}), &["job_id"]),
303        ),
304        (
305            "repair_job",
306            "Repair an interrupted job",
307            json!({"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}),
308            "Finalizes a job whose launcher was lost or that a reboot interrupted (get_job shows observed_state), keeping every committed task result and the exact accounting where it is known. Refuses (attempt_active, liveness_unknown) while a process may still own the job.",
309            object(json!({"job_id":job_id}), &["job_id"]),
310        ),
311    ];
312    tools
313        .into_iter()
314        .map(|(name, title, annotations, description, schema)| {
315            let mut annotations = annotations;
316            annotations["title"] = json!(title);
317            let mut tool = json!({"name":name,"title":title,"description":description,"inputSchema":schema,"annotations":annotations});
318            if modern && let Some(schema) = output_schema(name) {
319                tool["outputSchema"] = schema;
320            }
321            tool
322        })
323        .collect()
324}
325
326/// Success and coded tool errors both occupy structuredContent.
327pub(super) fn output_schema(name: &str) -> Option<Value> {
328    let sha256 = json!({"type":"string","pattern":"^[0-9a-f]{64}$"});
329    let success = match name {
330        // Both success shapes stay open, so the runner can add fields.
331        "put_input" | "upload_input" => json!({
332            "type": "object",
333            "required": ["file", "sha256", "bytes", "input_dir"],
334            "properties": {
335                "file": sha256,
336                "sha256": sha256,
337                "bytes": {"type":"integer","minimum":0,"maximum":MAX_INPUT_BYTES},
338                "input_dir": {"type":"string","minLength":1},
339            },
340        }),
341        // Older optimization jobs use completed_retries instead of
342        // completed_tasks. Job state, ID and directory are common to both.
343        "get_job" | "wait_job" => json!({
344            "type": "object",
345            "required": ["job_id", "state", "directory"],
346            "properties": {
347                "job_id": job_id_property(),
348                "state": {"enum":["submitted","starting","waiting","running","completed",
349                                   "failed","cancelled","timed_out","interrupted"]},
350                "directory": {"type":"string","minLength":1},
351                "observed_state": {"type":["string","null"]},
352                "completed_tasks": {"type":"integer","minimum":0},
353                "requested_tasks": {"type":"integer","minimum":0},
354                "artifact_index": {"type":"object"},
355            },
356        }),
357        _ => return None,
358    };
359    let error = object(
360        json!({"error":{
361            "type":"object",
362            "properties":{"code":{"type":"string"},"message":{"type":"string"},"retryable":{"type":"boolean"}},
363            "required":["code","message","retryable"],
364        }}),
365        &["error"],
366    );
367    Some(json!({"type":"object","anyOf":[success,error]}))
368}
369
370pub fn exists(name: &str) -> bool {
371    definitions(false).iter().any(|t| t["name"] == name)
372}
373
374pub fn call(server: &Server, name: &str, args: &Value, ctx: &Ctx) -> Outcome {
375    let result = match name {
376        "get_guide" => guide::get(args),
377        "describe_node" => describe_node(server, ctx),
378        "describe_worker" => string(args, "worker")
379            .and_then(|worker| server.cli(&["problems", "describe", "--", &worker], QUICK, ctx)),
380        "validate_job" => server.validation_permit(ctx).and_then(|_permit| {
381            let staged = stage(server, args)?;
382            server.cli(
383                &["validate", &format!("--spec={}", path(&staged.spec))],
384                SLOW,
385                ctx,
386            )
387        }),
388        "put_input" => inputs::put(server, args, ctx),
389        "submit_job" => return submit_job(server, args, ctx),
390        "get_job" => job_id(args).and_then(|id| server.get(&id, ctx)),
391        "wait_job" => wait_job(server, args, ctx),
392        "get_result" => get_result(server, args, ctx),
393        "get_events" => get_events(server, args, ctx),
394        "get_artifact" => get_artifact(server, args, ctx),
395        "list_jobs" => list_jobs(server, args, ctx),
396        "cancel_job" => job_id(args).and_then(|id| cancel(server, &id, false)),
397        "kill_job" => job_id(args).and_then(|id| cancel(server, &id, true)),
398        "repair_job" => job_id(args).and_then(|id| repair(server, &id)),
399        _ => Err(fail("invalid_arguments", format!("unknown tool {name}"))),
400    };
401    match result {
402        Ok(value) => Outcome::Done(value),
403        Err(Fail::Tool(error)) => Outcome::Failed(error),
404        Err(Fail::Cancelled) => Outcome::Cancelled,
405    }
406}
407
408fn path(p: &Path) -> String {
409    p.to_string_lossy().into_owned()
410}
411
412pub(super) fn string(args: &Value, key: &str) -> Result<String, Fail> {
413    args[key]
414        .as_str()
415        .filter(|s| !s.is_empty())
416        .map(str::to_owned)
417        .ok_or_else(|| {
418            fail(
419                "invalid_arguments",
420                format!("{key} must be a non-empty string"),
421            )
422        })
423}
424
425pub(super) fn job_id(args: &Value) -> Result<String, Fail> {
426    let id = string(args, "job_id")?;
427    if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
428        return Err(fail(
429            "invalid_arguments",
430            format!("job_id {id:?} is not a 32-digit hexadecimal job ID"),
431        ));
432    }
433    Ok(id)
434}
435
436fn limit(args: &Value, default: usize) -> Result<usize, Fail> {
437    match &args["limit"] {
438        Value::Null => Ok(default),
439        v => v
440            .as_u64()
441            .filter(|n| (1..=1000).contains(n))
442            .map(|n| n as usize)
443            .ok_or_else(|| {
444                fail(
445                    "invalid_arguments",
446                    "limit must be an integer from 1 to 1000",
447                )
448            }),
449    }
450}
451
452/// Reads the runner's coded error, the last JSON line of its stderr.
453fn runner_error(stderr: &[u8]) -> ToolError {
454    let text = String::from_utf8_lossy(stderr);
455    for line in text.lines().rev() {
456        if let Ok(v) = serde_json::from_str::<Value>(line)
457            && let Some(code) = v["error"]["code"].as_str()
458        {
459            return ToolError {
460                code: code.into(),
461                message: v["error"]["message"].as_str().unwrap_or_default().into(),
462                retryable: v["error"]["retryable"].as_bool().unwrap_or(false),
463            };
464        }
465    }
466    ToolError {
467        code: "runner_error".into(),
468        message: format!("optimization-run failed: {}", text.trim()),
469        retryable: false,
470    }
471}
472
473impl Server {
474    /// Runs `optimization-run --root ROOT ARGS` and returns its JSON output,
475    /// or its coded error. A read stops early when the request is cancelled.
476    pub fn cli(&self, args: &[&str], timeout: Duration, ctx: &Ctx) -> Result<Value, Fail> {
477        self.invoke(args, timeout, Some(&|| ctx.stopped(self)))
478    }
479
480    /// [`Server::cli`] for commands that change a job: once started they run
481    /// to their end, even when the request is cancelled (whose response is
482    /// then dropped), because killing the runner halfway could leave a job
483    /// half created or half stopped.
484    pub fn cli_mutating(&self, args: &[&str]) -> Result<Value, Fail> {
485        self.invoke(args, MUTATING, None)
486    }
487
488    fn invoke(
489        &self,
490        args: &[&str],
491        timeout: Duration,
492        abort: Option<&dyn Fn() -> bool>,
493    ) -> Result<Value, Fail> {
494        let mut argv = vec![path(&self.runner), "--root".into(), path(&self.root)];
495        argv.extend(args.iter().map(|a| a.to_string()));
496        let never = || false;
497        match bounded_command_until(&argv, vec![], timeout, OUTPUT_CAP, abort.unwrap_or(&never)) {
498            Ok((status, out, _)) if status.success() => serde_json::from_slice(&out)
499                .map_err(|e| fail("runner_error", format!("unreadable runner output: {e}"))),
500            Ok((_, _, err)) => Err(Fail::Tool(runner_error(&err))),
501            Err(e) if e.kind() == ErrorKind::Interrupted => Err(Fail::Cancelled),
502            Err(e) if e.kind() == ErrorKind::TimedOut => Err(Fail::Tool(ToolError {
503                code: "mcp_timeout".into(),
504                message: format!(
505                    "optimization-run {} did not answer within {} s",
506                    args.first().copied().unwrap_or_default(),
507                    timeout.as_secs()
508                ),
509                retryable: true,
510            })),
511            Err(e) => Err(fail(
512                "runner_error",
513                format!("cannot run {}: {e}", self.runner.display()),
514            )),
515        }
516    }
517
518    /// `jobs get`, with the job ID also under `job_id`.
519    pub fn get(&self, id: &str, ctx: &Ctx) -> Result<Value, Fail> {
520        let mut job = self.cli(&["jobs", "get", "--", id], QUICK, ctx)?;
521        job["job_id"] = json!(id);
522        Ok(job)
523    }
524}
525
526fn describe_node(server: &Server, ctx: &Ctx) -> Result<Value, Fail> {
527    let doctor = server.cli(&["node", "doctor"], QUICK, ctx)?;
528    let registry = server.cli(&["workers", "list"], QUICK, ctx)?;
529    let workers: Vec<Value> = registry
530        .as_object()
531        .map(|workers| {
532            workers
533                .iter()
534                .map(|(id, w)| {
535                    let d = &w["description"];
536                    json!({"worker":id,"protocol":d["protocol"],"profiles":d["profiles"],"engine":d["engine"],"build":d["build"]})
537                })
538                .collect()
539        })
540        .unwrap_or_default();
541    let mut node = json!({
542        "root": path(&server.root),
543        "capacity": doctor["capacity"],
544        "launch": server.launch.name(),
545        "systemd_user_manager": doctor["systemd_user_manager"],
546        "host": doctor["host"],
547        "warnings": doctor["warnings"],
548        "capabilities": doctor["capabilities"],
549        "workers": workers,
550    });
551    if doctor["capacity"].is_null() {
552        node["note"] = json!(format!(
553            "the node is not initialized; its owner runs: optimization-run --root {} node init --capacity N",
554            server.root.display()
555        ));
556    } else if node["workers"].as_array().is_some_and(Vec::is_empty) {
557        node["note"] = json!(format!(
558            "no worker is registered; its owner runs: optimization-run --root {} workers add --id ID --executable PATH",
559            server.root.display()
560        ));
561    }
562    Ok(node)
563}
564
565/// A job ready for `--spec`: the file, its content and, for inline jobs, the
566/// staging directory holding it and its input files (removed on drop).
567struct Staged {
568    spec: PathBuf,
569    job: Value,
570    request_key: String,
571    dir: Option<tempfile::TempDir>,
572}
573
574fn staging(root: &Path) -> PathBuf {
575    root.join("mcp").join("staging")
576}
577
578fn launch_logs(root: &Path) -> PathBuf {
579    root.join("mcp").join("launch")
580}
581
582fn older_than_a_day(entry: &fs::DirEntry) -> bool {
583    entry
584        .metadata()
585        .and_then(|m| m.modified())
586        .ok()
587        .and_then(|t| t.elapsed().ok())
588        .is_some_and(|age| age > Duration::from_secs(86_400))
589}
590
591/// Removes what servers that were killed left behind: staging directories
592/// and empty launcher logs older than a day.
593pub fn clean_staging(root: &Path) {
594    for entry in fs::read_dir(staging(root)).into_iter().flatten().flatten() {
595        if older_than_a_day(&entry) {
596            let _ = fs::remove_dir_all(entry.path());
597        }
598    }
599    for entry in fs::read_dir(launch_logs(root))
600        .into_iter()
601        .flatten()
602        .flatten()
603    {
604        if older_than_a_day(&entry) && entry.metadata().is_ok_and(|m| m.len() == 0) {
605            let _ = fs::remove_file(entry.path());
606        }
607    }
608}
609
610fn stage(server: &Server, args: &Value) -> Result<Staged, Fail> {
611    let staged = match (&args["job"], &args["spec_path"]) {
612        (Value::Object(_), Value::Null) => stage_inline(server, args)?,
613        (Value::Null, Value::String(file)) => {
614            let spec = fs::canonicalize(file)
615                .map_err(|e| fail("invalid_arguments", format!("spec_path {file}: {e}")))?;
616            let job = read_json_file(&spec, MAX_INPUT_BYTES)
617                .map_err(|e| fail("invalid_arguments", format!("spec_path {file}: {e}")))?;
618            Staged {
619                request_key: String::new(),
620                spec,
621                job,
622                dir: None,
623            }
624        }
625        _ => {
626            return Err(fail(
627                "invalid_arguments",
628                "pass exactly one of job (an object) or spec_path (a string)",
629            ));
630        }
631    };
632    if staged.job["schema_version"] == crate::command::SCHEMA {
633        return Err(fail(
634            "unsupported_job_kind",
635            "command jobs are CLI-only: the node owner runs them with optimization-run",
636        ));
637    }
638    let request_key = staged.job["request_key"]
639        .as_str()
640        .filter(|k| !k.is_empty())
641        .ok_or_else(|| {
642            fail(
643                "invalid_job",
644                "the job needs a non-empty string request_key",
645            )
646        })?
647        .to_owned();
648    Ok(Staged {
649        request_key,
650        ..staged
651    })
652}
653
654/// Parses a regular file of at most `cap` bytes as JSON.
655fn read_json_file(path: &Path, cap: u64) -> Result<Value, String> {
656    serde_json::from_slice(&read_file(path, cap)?).map_err(|e| e.to_string())
657}
658
659/// The bytes of a regular file of at most `cap` bytes.
660pub(super) fn read_file(path: &Path, cap: u64) -> Result<Vec<u8>, String> {
661    use std::io::Read;
662    let metadata = fs::metadata(path).map_err(|e| e.to_string())?;
663    if !metadata.is_file() {
664        return Err("not a regular file".into());
665    }
666    if metadata.len() > cap {
667        return Err(format!("{} bytes, over the cap of {cap}", metadata.len()));
668    }
669    let mut bytes = Vec::new();
670    fs::File::open(path)
671        .and_then(|f| f.take(cap + 1).read_to_end(&mut bytes))
672        .map_err(|e| e.to_string())?;
673    if bytes.len() as u64 > cap {
674        return Err(format!("over the cap of {cap} bytes"));
675    }
676    Ok(bytes)
677}
678
679/// Writes an inline job to a staging directory with copies of its input
680/// files, each checked against its SHA-256 first.
681fn stage_inline(server: &Server, args: &Value) -> Result<Staged, Fail> {
682    let job = args["job"].clone();
683    let base = match &args["input_dir"] {
684        Value::Null => server.input_dir.clone(),
685        Value::String(dir) => fs::canonicalize(dir)
686            .map_err(|e| fail("invalid_arguments", format!("input_dir {dir}: {e}")))?,
687        _ => return Err(fail("invalid_arguments", "input_dir must be a string")),
688    };
689    let parent = staging(&server.root);
690    fs::create_dir_all(&parent)
691        .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
692    let dir = tempfile::Builder::new()
693        .prefix("job-")
694        .tempdir_in(&parent)
695        .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
696    // Inputs are copied only for an envelope that is valid apart from them
697    // (at most 16 inputs of at most 64 MiB each); the runner reports what is
698    // wrong with any other.
699    let envelope_valid = serde_json::from_value::<JobSpec>(job.clone())
700        .ok()
701        .is_some_and(|spec| spec.validate().is_ok());
702    if let Some(inputs) = job["inputs"].as_array().filter(|_| envelope_valid) {
703        for value in inputs {
704            // Malformed declarations are left to the runner's own message.
705            let Ok(input) = serde_json::from_value::<Input>(value.clone()) else {
706                continue;
707            };
708            let relative = Path::new(&input.file);
709            if relative
710                .components()
711                .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
712            {
713                continue;
714            }
715            let bytes = checked_input(&base, &input).map_err(|e| {
716                fail(
717                    "invalid_job",
718                    format!(
719                        "input {} ({}): {e}",
720                        input.name,
721                        base.join(relative).display()
722                    ),
723                )
724            })?;
725            let target = dir.path().join(relative);
726            if let Some(parent) = target.parent() {
727                fs::create_dir_all(parent)
728                    .map_err(|e| fail("runner_error", format!("{}: {e}", parent.display())))?;
729            }
730            fs::write(&target, bytes)
731                .map_err(|e| fail("runner_error", format!("{}: {e}", target.display())))?;
732        }
733    }
734    // A name no input file uses.
735    let spec = loop {
736        let spec = dir
737            .path()
738            .join(format!(".mcp-job-{}.json", &random_hex()[..12]));
739        if !spec.exists() {
740            break spec;
741        }
742    };
743    fs::write(&spec, job.to_string())
744        .map_err(|e| fail("runner_error", format!("{}: {e}", spec.display())))?;
745    Ok(Staged {
746        spec,
747        job,
748        request_key: String::new(),
749        dir: Some(dir),
750    })
751}
752
753fn submit_job(server: &Server, args: &Value, ctx: &Ctx) -> Outcome {
754    // The place is held until the job exists, which is after its validation.
755    let permit = match server.validation_permit(ctx) {
756        Ok(permit) => permit,
757        Err(Fail::Tool(error)) => return Outcome::Failed(error),
758        Err(Fail::Cancelled) => return Outcome::Cancelled,
759    };
760    let submitted = stage(server, args).and_then(|staged| match server.launch {
761        Launch::Systemd => {
762            let job =
763                server.cli_mutating(&["submit", &format!("--spec={}", path(&staged.spec))])?;
764            let id = job["id"].as_str().unwrap_or_default().to_owned();
765            server.get(&id, ctx)
766        }
767        Launch::Process => launch_process(server, staged),
768    });
769    drop(permit);
770    let job = match submitted {
771        Ok(job) => job,
772        Err(Fail::Tool(error)) => return Outcome::Failed(error),
773        Err(Fail::Cancelled) => return Outcome::Cancelled,
774    };
775    if !ctx.tasks {
776        return Outcome::Done(job);
777    }
778    let job_id = job["job_id"].as_str().unwrap_or_default();
779    match tasks::create(server, job_id, &job, ctx) {
780        Ok(task) => Outcome::Task(task),
781        // The job exists; without a task the client still gets its handle.
782        Err(_) => Outcome::Done(job),
783    }
784}
785
786/// A context that is never cancelled, for submissions: once the launcher is
787/// started, its job is followed until it exists, whatever the request does.
788fn uninterrupted() -> Ctx {
789    Ctx {
790        modern: false,
791        tasks: false,
792        cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
793        progress: None,
794        id: Value::Null,
795    }
796}
797
798/// Starts `optimization-run run` in a session of its own, so the job
799/// outlives this server, and returns once the job exists. A job that did not
800/// exist before is confirmed when `jobs get` finds it with this submission's
801/// content; for an existing job, the launcher's own answer decides, so the
802/// runner's identity rule (content and worker) applies unchanged. Once
803/// started, a submission is not abandoned: a cancelled request only loses
804/// its response, and the staging directory stays until the runner has read
805/// it.
806fn launch_process(server: &Server, staged: Staged) -> Result<Value, Fail> {
807    let quiet = uninterrupted();
808    let id = digest(staged.request_key.as_bytes())[..32].to_owned();
809    let existed = server.get(&id, &quiet).is_ok();
810    let logs = launch_logs(&server.root);
811    fs::create_dir_all(&logs)
812        .map_err(|e| fail("runner_error", format!("{}: {e}", logs.display())))?;
813    let log = logs.join(format!("{id}-{}.log", &random_hex()[..8]));
814    let stderr = fs::File::create(&log)
815        .map_err(|e| fail("runner_error", format!("{}: {e}", log.display())))?;
816    let mut command = Command::new(&server.runner);
817    command
818        .arg("--root")
819        .arg(&server.root)
820        .arg("run")
821        .arg(format!("--spec={}", path(&staged.spec)))
822        .stdin(Stdio::null())
823        .stdout(Stdio::null())
824        .stderr(stderr);
825    #[cfg(unix)]
826    {
827        use std::os::unix::process::CommandExt;
828        // SAFETY: setsid is async-signal-safe and touches no memory of the
829        // parent process.
830        unsafe {
831            command.pre_exec(|| {
832                libc::setsid();
833                Ok(())
834            });
835        }
836    }
837    let mut child = command.spawn().map_err(|e| {
838        fail(
839            "runner_error",
840            format!("cannot start {}: {e}", server.runner.display()),
841        )
842    })?;
843    let Staged { job, dir, .. } = staged;
844    // The launcher is reaped whatever happens next. Its log is kept only if
845    // it fails after this request has returned.
846    let reap =
847        move |mut child: std::process::Child, log: PathBuf, dir: Option<tempfile::TempDir>| {
848            thread::spawn(move || {
849                let succeeded = child.wait().is_ok_and(|s| s.success());
850                drop(dir);
851                if succeeded {
852                    let _ = fs::remove_file(log);
853                }
854            });
855        };
856    let start = Instant::now();
857    loop {
858        match child.try_wait() {
859            Ok(Some(status)) => {
860                let text = fs::read(&log).unwrap_or_default();
861                let _ = fs::remove_file(&log);
862                if !status.success() {
863                    return Err(Fail::Tool(runner_error(&text)));
864                }
865                // An existing identical job, or one that already finished.
866                return server.get(&id, &quiet);
867            }
868            Ok(None) => {}
869            Err(e) => {
870                reap(child, log, dir);
871                return Err(fail("runner_error", format!("launcher: {e}")));
872            }
873        }
874        if !existed
875            && let Ok(job_now) = server.get(&id, &quiet)
876            && job_now["directory"]
877                .as_str()
878                .and_then(|d| fs::read(Path::new(d).join("submitted.json")).ok())
879                .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
880                .is_some_and(|submitted| submitted == job)
881        {
882            // The runner registers a job only after it has read the
883            // specification and its inputs: the staging copy is done with.
884            reap(child, log, None);
885            drop(dir);
886            return Ok(job_now);
887        }
888        if start.elapsed() > SLOW {
889            reap(child, log, dir);
890            return Err(Fail::Tool(ToolError {
891                code: "mcp_timeout".into(),
892                message: format!(
893                    "the job was not confirmed within {} s; its launcher keeps running, so check get_job {id} before submitting again",
894                    SLOW.as_secs()
895                ),
896                retryable: true,
897            }));
898        }
899        thread::sleep(Duration::from_millis(100));
900    }
901}
902
903fn wait_job(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
904    let id = job_id(args)?;
905    let timeout = match &args["timeout_seconds"] {
906        Value::Null => 30.0,
907        v => v
908            .as_f64()
909            .filter(|t| t.is_finite() && *t > 0.0 && *t <= MAX_WAIT_SECONDS)
910            .ok_or_else(|| {
911                fail(
912                    "invalid_arguments",
913                    format!("timeout_seconds must be in (0, {MAX_WAIT_SECONDS}]"),
914                )
915            })?,
916    };
917    let start = Instant::now();
918    let mut reported: Option<u64> = None;
919    loop {
920        let job = server.get(&id, ctx)?;
921        if let Some(done) = job["completed_tasks"].as_u64()
922            && reported.is_none_or(|r| done > r)
923        {
924            let state = job["state"].as_str().unwrap_or_default();
925            server.progress(ctx, done, job["requested_tasks"].as_u64(), state);
926            reported = Some(done);
927        }
928        if terminal(&job["state"])
929            || !job["observed_state"].is_null()
930            || start.elapsed().as_secs_f64() >= timeout
931        {
932            return Ok(job);
933        }
934        pause(server, ctx, Duration::from_millis(500));
935        if ctx.stopped(server) {
936            return Err(Fail::Cancelled);
937        }
938    }
939}
940
941/// The result manifest of an ended job, as bytes: the summary parses only
942/// the fields it shows, so an archive or a front of a few hundred MiB costs
943/// little more than its size in memory.
944pub fn read_manifest(job: &Value) -> Result<Vec<u8>, ToolError> {
945    if job["kind"] == "command" {
946        return Err(ToolError {code:"unsupported_job_kind".into(), message:"command results are available through optimization-run result; binary outputs through jobs collect".into(), retryable:false});
947    }
948    let id = job["job_id"].as_str().unwrap_or_default();
949    if !terminal(&job["state"]) {
950        let mut message = format!(
951            "job {id} is {}; wait_job until it ends",
952            job["state"].as_str().unwrap_or("unknown")
953        );
954        if let Some(observed) = job["observed_state"].as_str() {
955            message = format!("job {id} was observed {observed}; repair_job finalizes it");
956        }
957        return Err(ToolError {
958            code: "not_finished".into(),
959            message,
960            retryable: false,
961        });
962    }
963    let file = Path::new(job["directory"].as_str().unwrap_or_default()).join("run.json");
964    // Read directly: a large manifest needs neither the runner's pretty
965    // printing nor its output pipe.
966    read_file(&file, MANIFEST_CAP).map_err(|e| {
967        let code = if e.contains("over the cap") {
968            "result_too_large"
969        } else {
970            "runner_error"
971        };
972        ToolError {
973            code: code.into(),
974            message: format!("{}: {e}", file.display()),
975            retryable: false,
976        }
977    })
978}
979
980/// The fields of a manifest that a summary shows; task records stay raw.
981#[derive(Deserialize)]
982struct ManifestView<'a> {
983    #[serde(default)]
984    status: Value,
985    #[serde(default)]
986    schema_version: Value,
987    #[serde(default)]
988    worker: Value,
989    #[serde(default)]
990    payload_schema: Value,
991    #[serde(default)]
992    completed_tasks: Value,
993    #[serde(default)]
994    requested_tasks: Value,
995    #[serde(default)]
996    elapsed_seconds: Value,
997    #[serde(default)]
998    work: Value,
999    #[serde(default)]
1000    artifacts: Value,
1001    #[serde(default)]
1002    runner: RunnerView,
1003    #[serde(borrow, default)]
1004    results: Vec<&'a RawValue>,
1005}
1006
1007#[derive(Default, Deserialize)]
1008struct RunnerView {
1009    #[serde(default)]
1010    accounting_complete: Value,
1011    #[serde(default)]
1012    artifact_index: Value,
1013}
1014
1015#[derive(Default, Deserialize)]
1016struct RecordView {
1017    #[serde(default)]
1018    task_id: Value,
1019    #[serde(default)]
1020    outcome: OutcomeView,
1021}
1022
1023#[derive(Default, Deserialize)]
1024struct OutcomeView {
1025    #[serde(default)]
1026    claim: Value,
1027    #[serde(default)]
1028    termination: Value,
1029    #[serde(default)]
1030    feasible: Value,
1031    #[serde(default)]
1032    objective: Value,
1033    #[serde(default)]
1034    evidence: EvidenceView,
1035    #[serde(default)]
1036    objective_bounds: Value,
1037    #[serde(default)]
1038    imprecise: Value,
1039}
1040
1041#[derive(Default, Deserialize)]
1042struct EvidenceView {
1043    #[serde(default)]
1044    level: Value,
1045    #[serde(default)]
1046    refuted: Value,
1047}
1048
1049fn view(bytes: &[u8]) -> Result<ManifestView<'_>, ToolError> {
1050    serde_json::from_slice(bytes).map_err(|e| ToolError {
1051        code: "runner_error".into(),
1052        message: format!("unreadable result manifest: {e}"),
1053        retryable: false,
1054    })
1055}
1056
1057/// The compact view of a result: accounting and one line per task, without
1058/// points or details.
1059pub fn summary(job: &Value, bytes: &[u8]) -> Result<Value, ToolError> {
1060    let manifest = view(bytes)?;
1061    let mut claims = BTreeMap::<String, u64>::new();
1062    let mut terminations = BTreeMap::<String, u64>::new();
1063    let mut tasks = vec![];
1064    for raw in &manifest.results {
1065        let r: RecordView = serde_json::from_str(raw.get()).unwrap_or_default();
1066        let o = &r.outcome;
1067        *claims
1068            .entry(o.claim.as_str().unwrap_or("unknown").into())
1069            .or_default() += 1;
1070        *terminations
1071            .entry(o.termination.as_str().unwrap_or("unknown").into())
1072            .or_default() += 1;
1073        if tasks.len() < SUMMARY_TASKS {
1074            let mut task = json!({
1075                "task_id": r.task_id,
1076                "claim": o.claim,
1077                "termination": o.termination,
1078                "feasible": o.feasible,
1079                "objective": o.objective,
1080                "evidence": o.evidence.level,
1081            });
1082            for (key, value) in [
1083                ("objective_bounds", &o.objective_bounds),
1084                ("imprecise", &o.imprecise),
1085                ("refuted", &o.evidence.refuted),
1086            ] {
1087                if !value.is_null() {
1088                    task[key] = value.clone();
1089                }
1090            }
1091            tasks.push(task);
1092        }
1093    }
1094    let mut summary = json!({
1095        "job_id": job["job_id"],
1096        "state": job["state"],
1097        "status": manifest.status,
1098        "schema_version": manifest.schema_version,
1099        "worker": manifest.worker,
1100        "payload_schema": manifest.payload_schema,
1101        "completed_tasks": manifest.completed_tasks,
1102        "requested_tasks": manifest.requested_tasks,
1103        "elapsed_seconds": manifest.elapsed_seconds,
1104        "work": manifest.work,
1105        "accounting_complete": manifest.runner.accounting_complete,
1106        "claims": claims,
1107        "terminations": terminations,
1108        "tasks": tasks,
1109        "tasks_omitted": manifest.results.len().saturating_sub(SUMMARY_TASKS),
1110        "artifacts": manifest.artifacts,
1111        "directory": job["directory"],
1112    });
1113    if !manifest.runner.artifact_index.is_null() {
1114        summary["artifact_index"] = manifest.runner.artifact_index;
1115    }
1116    Ok(summary)
1117}
1118
1119fn record_id(raw: &RawValue) -> Option<u64> {
1120    #[derive(Deserialize)]
1121    struct Id {
1122        task_id: Option<u64>,
1123    }
1124    serde_json::from_str::<Id>(raw.get()).ok()?.task_id
1125}
1126
1127pub(super) fn result_record(bytes: &[u8], task: u64) -> Result<(Value, &RawValue), Fail> {
1128    let manifest = view(bytes).map_err(Fail::Tool)?;
1129    let record = manifest
1130        .results
1131        .into_iter()
1132        .find(|r| record_id(r) == Some(task))
1133        .ok_or_else(|| {
1134            fail(
1135                "invalid_arguments",
1136                "the result has no committed record for this task_id",
1137            )
1138        })?;
1139    Ok((manifest.payload_schema, record))
1140}
1141
1142fn get_result(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1143    let id = job_id(args)?;
1144    let job = server.get(&id, ctx)?;
1145    let bytes = read_manifest(&job).map_err(Fail::Tool)?;
1146    let too_large = |size: usize| {
1147        fail(
1148            "result_too_large",
1149            format!(
1150                "the result manifest has {size} bytes, over the 1 MiB inline cap; pass tasks, or read {}/run.json",
1151                job["directory"].as_str().unwrap_or_default()
1152            ),
1153        )
1154    };
1155    if args["full"].as_bool() == Some(true) {
1156        // Pretty printing at most quadruples a manifest.
1157        if bytes.len() > 4 * FULL_CAP {
1158            return Err(too_large(bytes.len()));
1159        }
1160        let manifest: Value = serde_json::from_slice(&bytes)
1161            .map_err(|e| fail("runner_error", format!("unreadable result manifest: {e}")))?;
1162        let size = manifest.to_string().len();
1163        if size > FULL_CAP {
1164            return Err(too_large(size));
1165        }
1166        return Ok(manifest);
1167    }
1168    match &args["tasks"] {
1169        Value::Null => summary(&job, &bytes).map_err(Fail::Tool),
1170        Value::Array(ids) => {
1171            let wanted: Vec<u64> = ids.iter().filter_map(Value::as_u64).collect();
1172            if wanted.len() != ids.len() || wanted.len() > 100 {
1173                return Err(fail(
1174                    "invalid_arguments",
1175                    "tasks must be at most 100 non-negative integer task IDs",
1176                ));
1177            }
1178            let manifest = view(&bytes).map_err(Fail::Tool)?;
1179            let mut records = vec![];
1180            for raw in &manifest.results {
1181                let selected = record_id(raw).is_some_and(|id| wanted.contains(&id));
1182                if selected && let Ok(record) = serde_json::from_str::<Value>(raw.get()) {
1183                    records.push(record);
1184                }
1185            }
1186            Ok(json!({"job_id":id,"state":job["state"],"tasks":records}))
1187        }
1188        _ => Err(fail("invalid_arguments", "tasks must be an array")),
1189    }
1190}
1191
1192fn get_artifact(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1193    let id = job_id(args)?;
1194    let name = string(args, "name")?;
1195    let mut argv = vec!["jobs".to_string(), "artifact".into()];
1196    for (key, low, high) in [("offset", 0, u32::MAX as u64), ("limit", 1, 10_000)] {
1197        match &args[key] {
1198            Value::Null => {}
1199            v => {
1200                let n = v
1201                    .as_u64()
1202                    .filter(|n| (low..=high).contains(n))
1203                    .ok_or_else(|| {
1204                        fail(
1205                            "invalid_arguments",
1206                            format!("{key} must be an integer from {low} to {high}"),
1207                        )
1208                    })?;
1209                argv.push(format!("--{key}={n}"));
1210            }
1211        }
1212    }
1213    argv.extend(["--".into(), id, name]);
1214    let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
1215    server.cli(&argv, QUICK, ctx)
1216}
1217
1218fn get_events(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1219    let id = job_id(args)?;
1220    let limit = limit(args, 50)?;
1221    let events = server.cli(&["jobs", "events", "--", &id], QUICK, ctx)?;
1222    let events = events.as_array().cloned().unwrap_or_default();
1223    let skip = events.len().saturating_sub(limit);
1224    Ok(json!({"job_id":id,"total":events.len(),"events":events[skip..]}))
1225}
1226
1227fn list_jobs(server: &Server, args: &Value, ctx: &Ctx) -> Result<Value, Fail> {
1228    let limit = limit(args, 50)?;
1229    let active_only = args["active_only"].as_bool() == Some(true);
1230    let jobs = server.cli(&["jobs", "list"], SLOW, ctx)?;
1231    let mut jobs: Vec<Value> = jobs
1232        .as_array()
1233        .cloned()
1234        .unwrap_or_default()
1235        .into_iter()
1236        .filter(|j| !active_only || !terminal(&j["state"]))
1237        .map(|j| {
1238            let mut job = json!({"job_id":j["id"],"state":j["state"]});
1239            for key in [
1240                "observed_state",
1241                "error",
1242                "completed_tasks",
1243                "requested_tasks",
1244                "submitted_at",
1245                "finished_at",
1246                "cancel_requested",
1247            ] {
1248                if !j[key].is_null() {
1249                    job[key] = j[key].clone();
1250                }
1251            }
1252            job
1253        })
1254        .collect();
1255    jobs.sort_by(|a, b| {
1256        let t = |j: &Value| j["submitted_at"].as_f64().unwrap_or(0.0);
1257        t(b).total_cmp(&t(a))
1258    });
1259    let total = jobs.len();
1260    jobs.truncate(limit);
1261    Ok(json!({"total":total,"jobs":jobs}))
1262}
1263
1264pub fn cancel(server: &Server, id: &str, now: bool) -> Result<Value, Fail> {
1265    let mut args = vec!["jobs", "cancel"];
1266    if now {
1267        args.push("--now");
1268    }
1269    args.extend(["--", id]);
1270    let mut job = server.cli_mutating(&args)?;
1271    job["job_id"] = json!(id);
1272    Ok(job)
1273}
1274
1275pub fn repair(server: &Server, id: &str) -> Result<Value, Fail> {
1276    let mut job = server.cli_mutating(&["jobs", "repair", "--", id])?;
1277    job["job_id"] = json!(id);
1278    Ok(job)
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283    #[test]
1284    fn command_results_are_never_summarized_as_optimization() {
1285        let error = super::read_manifest(
1286            &serde_json::json!({"kind":"command","state":"completed","directory":"/missing"}),
1287        )
1288        .unwrap_err();
1289        assert_eq!(error.code, "unsupported_job_kind");
1290    }
1291
1292    /// The crate's copy of the job schema must equal the published one in
1293    /// docs/job-api/schemas (absent outside the repository, as in a package).
1294    #[test]
1295    fn embedded_job_schema_matches_the_published_one() {
1296        let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
1297        let published =
1298            manifest.join("../../docs/job-api/schemas/optimization.job-0.1.schema.json");
1299        if let Ok(published) = std::fs::read_to_string(published) {
1300            assert_eq!(
1301                published,
1302                include_str!("../../schemas/optimization.job-0.1.schema.json"),
1303                "copy docs/job-api/schemas/optimization.job-0.1.schema.json to crates/optimization-runner/schemas/"
1304            );
1305        }
1306    }
1307}