fraiseql-cli 2.16.0

CLI tools for FraiseQL v2 - Schema compilation and development utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! `fraiseql functions invoke` — a local test harness for function authors.
//!
//! Runs a compiled function in a **real V8 isolate** against a fixture payload with
//! **mocked host ops**, printing the guest's result and every host-op call it made.
//! This is the author's inner loop: fixture → run → observe, without a live server,
//! database, or network.
//!
//! The module loads exactly as the server does — one `FunctionModule` read from the
//! compiled schema's `module_dir`, dispatched through a `FunctionObserver` with the
//! Deno runtime registered (mirroring
//! `fraiseql-server::subsystems::loader::build_functions_subsystem`). The host is a
//! recording mock (`RecordingHost`): each op is logged, HTTP/query responses come
//! from `--mock-http` / `--mock-query` (a matched entry → canned response; a miss
//! against a configured mock fails loud), and other ops return benign defaults so a
//! smoke-run surfaces which ops a function calls before its mocks are written.
//!
//! **One isolate per process** (the V8 constraint documented in
//! `docs/architecture/functions.md`): a single `invoke` call is inherently safe;
//! only harness *tests* that run two invocations must fork per test (nextest).

use std::{
    path::Path,
    sync::{Arc, Mutex},
};

use anyhow::{Context, Result, anyhow, bail};
use fraiseql_functions::{
    EventPayload, FunctionDefinition, FunctionModule, FunctionObserver, FunctionsConfig, LogLevel,
    ResourceLimits, RuntimeType,
    host::{HostContext, HttpResponse, dyn_context::DynHostContext},
    runtime::deno::{DenoConfig, DenoRuntime},
    triggers::{
        mutation::{EventKind, TriggerPredicate},
        registry::ParsedTrigger,
    },
};
use serde::Deserialize;

/// Exit codes, scriptable in an adopter's CI (`functions.md`).
///
/// A harness/config error (module missing, bad fixture) surfaces as the default
/// `anyhow` error path (exit 1); these are the *outcome* codes.
pub mod exit {
    /// The guest ran and returned.
    pub const OK: i32 = 0;
    /// The `when` predicate did not match — nothing would fire; the guest was not run.
    pub const PREDICATE_NO_MATCH: i32 = 3;
    /// The guest ran but errored (threw, or the runtime rejected it).
    pub const GUEST_ERROR: i32 = 4;
}

/// Run `fraiseql functions invoke`.
///
/// # Errors
///
/// Returns a config/harness error (exit 1) if the schema or fixture cannot be read,
/// the function is unknown, its module file is missing, or the trigger kind is not
/// yet supported by the harness. A successful load returns `Ok(code)` with the
/// outcome [`exit`] code — the caller maps it to the process exit.
#[allow(clippy::too_many_arguments)] // Reason: a CLI command's flags; a struct would just relocate them.
pub async fn invoke(
    name: &str,
    payload_path: &Path,
    schema_path: &Path,
    mock_http_path: Option<&Path>,
    mock_query_path: Option<&Path>,
    idempotency_token: Option<String>,
    explain: bool,
    json: bool,
) -> Result<i32> {
    // ── Load the compiled schema's functions section + the named definition. ──
    let functions = load_functions_section(schema_path)?;
    let definition = functions
        .definitions
        .iter()
        .find(|def| def.name == name)
        .ok_or_else(|| anyhow!("no function named {name:?} in {}", schema_path.display()))?;

    let trigger = ParsedTrigger::parse(&definition.trigger)
        .map_err(|error| anyhow!("function {name:?} has an unparseable trigger: {error}"))?;

    // ── Synthesize the dispatch payload from the fixture, per trigger kind. ───
    let fixture: serde_json::Value = read_json(payload_path).context("reading --payload")?;
    let synth = synthesize_payload(name, &trigger, &fixture)?;

    // ── Predicates (#597): evaluate before running anything (--explain). ─────
    if let Some(outcome) = evaluate_predicates(&definition.when, &synth, explain, json) {
        if !outcome {
            // A false predicate is the dispatcher's zero-cost skip: no isolate spins.
            return Ok(exit::PREDICATE_NO_MATCH);
        }
    }

    // ── Load the module exactly like the server, register the Deno runtime. ──
    let module = load_module(&functions.module_dir, definition)?;
    if module.runtime != RuntimeType::Deno {
        bail!(
            "the invoke harness runs TypeScript/JavaScript (Deno) functions; {name:?} is {:?}",
            module.runtime
        );
    }
    let mut observer = FunctionObserver::new();
    observer.register_runtime(RuntimeType::Deno, DenoRuntime::new(&DenoConfig::default())?);

    // ── Build the recording mock host from the fixtures. ─────────────────────
    let mocks = HostMocks::load(mock_http_path, mock_query_path)?;
    let host = Arc::new(RecordingHost::new(synth.payload.clone(), mocks, idempotency_token));
    let dyn_host: Arc<dyn DynHostContext> = host.clone();

    // ── Run in a real isolate. ───────────────────────────────────────────────
    let result = observer
        .invoke_with_context(&module, synth.payload, dyn_host, ResourceLimits::default())
        .await;

    let calls = host.calls();
    match result {
        Ok(function_result) => {
            print_success(name, &function_result, &calls, json);
            // A before:mutation guest's return value *is* a decision, so the harness
            // reports the decision the server would reach rather than leaving the
            // author to read the convention out of the raw JSON.
            if let ParsedTrigger::BeforeMutation { mutation_name } = &trigger {
                print_before_mutation_decision(mutation_name, &function_result, &fixture, json);
            }
            Ok(exit::OK)
        },
        Err(error) => {
            print_guest_error(name, &error, &calls, json);
            Ok(exit::GUEST_ERROR)
        },
    }
}

/// Read + deserialize a JSON file with a clear error.
fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    serde_json::from_str(&text).with_context(|| format!("parsing JSON in {}", path.display()))
}

/// Parse the compiled schema and extract its `functions` section.
fn load_functions_section(schema_path: &Path) -> Result<FunctionsConfig> {
    let schema: serde_json::Value = read_json(schema_path).context("reading --schema")?;
    let functions = schema
        .get("functions")
        .filter(|value| !value.is_null())
        .ok_or_else(|| anyhow!("{} has no \"functions\" section", schema_path.display()))?;
    serde_json::from_value(functions.clone())
        .with_context(|| format!("parsing the functions section of {}", schema_path.display()))
}

/// Load the `FunctionModule` from `module_dir`, mirroring the server's loader
/// (`build_functions_subsystem` → `load_one_module`): try each supported extension,
/// first existing file wins, fail loud otherwise.
fn load_module(module_dir: &Path, definition: &FunctionDefinition) -> Result<FunctionModule> {
    // One definition of where a function's code lives, shared with the server's
    // loader and the compiler's compile-time check (#1325).
    let Some(path) = definition.resolve_module_path(module_dir) else {
        bail!(
            "no module file for {:?} at {}",
            definition.name,
            definition.module_path_pattern(module_dir)
        );
    };
    match definition.runtime {
        RuntimeType::Deno => {
            let source = std::fs::read_to_string(&path)
                .with_context(|| format!("reading module {}", path.display()))?;
            Ok(FunctionModule::from_source(definition.name.clone(), source, RuntimeType::Deno))
        },
        RuntimeType::Wasm => {
            let bytes = std::fs::read(&path)
                .with_context(|| format!("reading module {}", path.display()))?;
            Ok(FunctionModule::from_bytecode(definition.name.clone(), bytes.into()))
        },
        other => bail!("unsupported function runtime {other:?}"),
    }
}

/// A synthesized dispatch payload plus the row images the predicates evaluate on.
struct Synthesized {
    payload: EventPayload,
    /// The pre/post images (after:mutation/after:capture) for `--explain`; `None`
    /// for kinds that carry no row images.
    old:     Option<serde_json::Value>,
    new:     Option<serde_json::Value>,
}

/// Build the dispatch payload from a fixture, validated against the trigger kind.
///
/// - **after:mutation / after:capture** — the fixture is `{ "event_kind": "insert|update|delete",
///   "old": {…}|null, "new": {…}|null }` (or a bare object, treated as an insert's `new`).
///   Synthesized via the same `{event_kind, old, new}` payload the dispatcher builds.
/// - **before:mutation** (#1328) — the fixture *is* the mutation's resolved arguments, the object
///   the engine hands the chain: `{ "input": { … } }` for the usual single-input mutation, or
///   whatever the mutation's argument shape is. There are no row images: the write has not
///   happened.
/// - other kinds are not yet supported by the harness (see the follow-up note).
///
/// Each payload is built the way its **dispatcher** builds it, and they do not
/// agree: `AfterMutationTrigger::build_payload` puts the *function* name in
/// `trigger_type`, while `BeforeMutationChain::execute` puts the *mutation* name
/// and sets `entity` to it. Deriving one from the other would hand the guest a
/// payload no server produces.
fn synthesize_payload(
    name: &str,
    trigger: &ParsedTrigger,
    fixture: &serde_json::Value,
) -> Result<Synthesized> {
    match trigger {
        ParsedTrigger::BeforeMutation { mutation_name } => {
            if !fixture.is_object() {
                bail!(
                    "a before:mutation fixture is the mutation's arguments object — e.g. \
                     {{\"input\": {{…}}}} — not {}",
                    fixture_kind(fixture)
                );
            }
            Ok(Synthesized {
                payload: EventPayload {
                    trigger_type: format!("before:mutation:{mutation_name}"),
                    entity:       mutation_name.clone(),
                    event_kind:   "before".to_string(),
                    data:         fixture.clone(),
                    timestamp:    chrono::Utc::now(),
                },
                old:     None,
                new:     None,
            })
        },
        ParsedTrigger::AfterMutation { entity_type, .. }
        | ParsedTrigger::AfterCapture { entity_type, .. } => {
            let (kind_prefix, entity) = match trigger {
                ParsedTrigger::AfterCapture { .. } => ("after:capture", entity_type),
                _ => ("after:mutation", entity_type),
            };
            let (event_kind, old, new) = mutation_images(fixture)?;
            let data = serde_json::json!({
                "event_kind": event_kind.as_str(),
                "old": old,
                "new": new,
            });
            Ok(Synthesized {
                payload: EventPayload {
                    trigger_type: format!("{kind_prefix}:{name}"),
                    entity: entity.clone(),
                    event_kind: event_kind.to_string(),
                    data,
                    timestamp: chrono::Utc::now(),
                },
                old,
                new,
            })
        },
        ParsedTrigger::RequestQuery => {
            if !fixture.is_object() {
                bail!(
                    "a request:query fixture is the query field's arguments object — e.g. \
                     {{\"sku\": \"ABC-1\"}} — not {}",
                    fixture_kind(fixture)
                );
            }
            // Built by the same routine the server calls, not by a second copy of
            // the shape. The field name a real invocation carries comes from the
            // query that named the function, and the harness has no schema to find
            // it in — so it stands in the function's own name and says so, rather
            // than inventing a plausible field a guest might then key on.
            Ok(Synthesized {
                payload: fraiseql_functions::host::request_query::request_query_payload(
                    name,
                    fixture.clone(),
                ),
                old:     None,
                new:     None,
            })
        },
        other => bail!(
            "the invoke harness does not yet synthesize a payload for {other:?} — supported \
             kinds: after:mutation, after:capture, before:mutation, request:query. (cron / \
             after:ingest are a tracked follow-up.)"
        ),
    }
}

/// The JSON kind of a fixture, for a diagnostic that says what was found.
fn fixture_kind(fixture: &serde_json::Value) -> &'static str {
    match fixture {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "a boolean",
        serde_json::Value::Number(_) => "a number",
        serde_json::Value::String(_) => "a string",
        serde_json::Value::Array(_) => "an array",
        serde_json::Value::Object(_) => "an object",
    }
}

/// Extract `(event_kind, old, new)` from an after:mutation fixture.
///
/// A bare object (no `event_kind`/`old`/`new` keys) is treated as an insert's `new`
/// image — the common quick-fixture shape.
fn mutation_images(
    fixture: &serde_json::Value,
) -> Result<(EventKind, Option<serde_json::Value>, Option<serde_json::Value>)> {
    let obj = fixture
        .as_object()
        .ok_or_else(|| anyhow!("an after:mutation fixture must be a JSON object"))?;

    let has_shape =
        obj.contains_key("event_kind") || obj.contains_key("old") || obj.contains_key("new");
    if !has_shape {
        // Bare object → an insert carrying it as the new image.
        return Ok((EventKind::Insert, None, Some(fixture.clone())));
    }

    let event_kind = match obj.get("event_kind").and_then(serde_json::Value::as_str) {
        Some("insert") => EventKind::Insert,
        Some("update") => EventKind::Update,
        Some("delete") => EventKind::Delete,
        None => EventKind::Update,
        Some(other) => bail!("unknown event_kind {other:?} (insert | update | delete)"),
    };
    let take = |key: &str| obj.get(key).filter(|v| !v.is_null()).cloned();
    Ok((event_kind, take("old"), take("new")))
}

/// Evaluate the function's `when` predicates for `--explain`, printing a per-predicate
/// verdict. Returns `Some(held)` for a kind that carries row images, `None` when there
/// are no predicates to evaluate (always fires).
fn evaluate_predicates(
    predicates: &[TriggerPredicate],
    synth: &Synthesized,
    explain: bool,
    json: bool,
) -> Option<bool> {
    if predicates.is_empty() {
        if explain && !json {
            println!("predicates: none declared — the function fires on every matching event.");
        }
        return None;
    }

    let mut all_hold = true;
    let mut lines = Vec::new();
    for predicate in predicates {
        let held = predicate.matches(synth.old.as_ref(), synth.new.as_ref());
        all_hold &= held;
        lines.push((predicate, held));
    }

    if explain {
        if json {
            let report: Vec<_> = lines
                .iter()
                .map(|(p, held)| serde_json::json!({ "field": p.field, "holds": held }))
                .collect();
            println!(
                "{}",
                serde_json::json!({ "predicates_hold": all_hold, "predicates": report })
            );
        } else {
            println!("predicates ({}):", if all_hold { "MATCH" } else { "NO MATCH" });
            for (predicate, held) in &lines {
                let op = predicate
                    .eq
                    .as_ref()
                    .map(|v| format!("eq {v}"))
                    .or_else(|| predicate.changed_to.as_ref().map(|v| format!("changed_to {v}")))
                    .unwrap_or_default();
                println!("  [{}] {} {}", if *held { "✓" } else { "✗" }, predicate.field, op);
            }
        }
    }
    Some(all_hold)
}

// ── Mock host ────────────────────────────────────────────────────────────────

/// A recorded host-op call, for the output.
#[derive(Debug, Clone, serde::Serialize)]
struct HostOpCall {
    op:      String,
    /// A short, human-readable summary of the call arguments.
    summary: String,
}

/// Canned HTTP/query responses loaded from `--mock-http` / `--mock-query`.
#[derive(Default)]
struct HostMocks {
    http:  Option<Vec<HttpMock>>,
    query: Option<Vec<QueryMock>>,
}

#[derive(Debug, Deserialize)]
struct HttpMock {
    /// Match when the request URL contains this substring.
    url_contains: String,
    /// Optional method filter (case-insensitive).
    #[serde(default)]
    method:       Option<String>,
    #[serde(default = "default_status")]
    status:       u16,
    #[serde(default)]
    body:         serde_json::Value,
}

const fn default_status() -> u16 {
    200
}

#[derive(Debug, Deserialize)]
struct QueryMock {
    /// Match when the GraphQL/SQL text contains this substring; omit to match any.
    #[serde(default)]
    query_contains: Option<String>,
    /// The canned response value returned to the guest.
    response:       serde_json::Value,
}

impl HostMocks {
    fn load(http_path: Option<&Path>, query_path: Option<&Path>) -> Result<Self> {
        let http = http_path.map(read_json::<Vec<HttpMock>>).transpose().context("--mock-http")?;
        let query = query_path
            .map(read_json::<Vec<QueryMock>>)
            .transpose()
            .context("--mock-query")?;
        Ok(Self { http, query })
    }
}

/// A `HostContext` that records every op call and answers HTTP/query from the mocks.
struct RecordingHost {
    event:             EventPayload,
    mocks:             HostMocks,
    idempotency_token: Option<String>,
    calls:             Mutex<Vec<HostOpCall>>,
    logs:              Mutex<Vec<String>>,
}

impl RecordingHost {
    fn new(event: EventPayload, mocks: HostMocks, idempotency_token: Option<String>) -> Self {
        Self {
            event,
            mocks,
            idempotency_token,
            calls: Mutex::new(Vec::new()),
            logs: Mutex::new(Vec::new()),
        }
    }

    fn record(&self, op: &str, summary: String) {
        self.calls.lock().expect("calls mutex poisoned").push(HostOpCall {
            op: op.to_string(),
            summary,
        });
    }

    fn calls(&self) -> Vec<HostOpCall> {
        self.calls.lock().expect("calls mutex poisoned").clone()
    }
}

// Reason: `HostContext` is async because the live implementation performs I/O; a
// recording host used to dry-run a function still presents the awaited signature.
#[allow(unknown_lints, clippy::unused_async_trait_impl)]
impl HostContext for RecordingHost {
    async fn query(
        &self,
        graphql: &str,
        variables: serde_json::Value,
    ) -> fraiseql_error::Result<serde_json::Value> {
        self.record("query", summarize(graphql));
        match self.mocks.query.as_ref() {
            Some(mocks) => mocks
                .iter()
                .find(|m| m.query_contains.as_ref().is_none_or(|c| graphql.contains(c.as_str())))
                .map(|m| m.response.clone())
                .ok_or_else(|| {
                    fraiseql_error::FraiseQLError::validation(format!(
                        "--mock-query has no entry matching query {:?} (vars {variables})",
                        summarize(graphql)
                    ))
                }),
            // No mock configured → benign default so the call is visible in the output.
            None => Ok(serde_json::json!({ "data": null })),
        }
    }

    async fn sql_query(
        &self,
        sql: &str,
        _params: &[serde_json::Value],
    ) -> fraiseql_error::Result<Vec<serde_json::Value>> {
        self.record("sql_query", summarize(sql));
        Ok(Vec::new())
    }

    async fn http_request(
        &self,
        method: &str,
        url: &str,
        _headers: &[(String, String)],
        _body: Option<&[u8]>,
    ) -> fraiseql_error::Result<HttpResponse> {
        self.record("http_request", format!("{method} {url}"));
        match self.mocks.http.as_ref() {
            Some(mocks) => mocks
                .iter()
                .find(|m| {
                    url.contains(&m.url_contains)
                        && m.method.as_ref().is_none_or(|wm| wm.eq_ignore_ascii_case(method))
                })
                .map(|m| HttpResponse {
                    status:  m.status,
                    headers: Vec::new(),
                    body:    m.body.to_string().into_bytes(),
                })
                .ok_or_else(|| {
                    fraiseql_error::FraiseQLError::validation(format!(
                        "--mock-http has no entry matching {method} {url}"
                    ))
                }),
            None => Ok(HttpResponse {
                status:  200,
                headers: Vec::new(),
                body:    b"{}".to_vec(),
            }),
        }
    }

    async fn storage_get(&self, bucket: &str, key: &str) -> fraiseql_error::Result<Vec<u8>> {
        self.record("storage_get", format!("{bucket}/{key}"));
        Ok(Vec::new())
    }

    async fn storage_put(
        &self,
        bucket: &str,
        key: &str,
        _body: &[u8],
        _content_type: &str,
    ) -> fraiseql_error::Result<()> {
        self.record("storage_put", format!("{bucket}/{key}"));
        Ok(())
    }

    async fn send_email(
        &self,
        request: &fraiseql_functions::outbound::SendEmailRequest,
    ) -> fraiseql_error::Result<fraiseql_functions::outbound::SendEmailResponse> {
        self.record("send_email", format!("to {}", request.to));
        Ok(fraiseql_functions::outbound::SendEmailResponse {
            accepted:   true,
            message_id: Some("mock-send-id".to_string()),
        })
    }

    fn auth_context(&self) -> fraiseql_error::Result<serde_json::Value> {
        self.record("auth_context", String::new());
        Ok(serde_json::json!({}))
    }

    fn env_var(&self, name: &str) -> fraiseql_error::Result<Option<String>> {
        self.record("env_var", name.to_string());
        Ok(None)
    }

    fn event_payload(&self) -> &EventPayload {
        &self.event
    }

    fn log(&self, level: LogLevel, message: &str) {
        self.logs
            .lock()
            .expect("logs mutex poisoned")
            .push(format!("[{level:?}] {message}"));
    }

    fn idempotency_token(&self) -> Option<String> {
        self.idempotency_token.clone()
    }
}

/// Truncate a query/SQL string to a single readable summary line.
///
/// Truncation is by **character**, not byte. `&one_line[..80]` panicked with "byte index 80
/// is not a char boundary" whenever the 80th byte fell inside a multi-byte sequence — and the
/// input is entirely author-controlled: this summarizes the GraphQL text passed to
/// `HostContext::query` and the SQL passed to `sql_query` by the guest under test. A literal
/// like `city: { eq: "Zürich" }` or an accented identifier is ordinary, and the panic landed
/// *after* the isolate had run, so the guest's result and the host-op log were lost and the
/// process aborted instead of returning an exit code the adopter's CI could branch on. The
/// `unwrap_used`/`expect_used` ratchets do not cover string indexing, so nothing in the gate
/// caught it (#868 item 3).
const MAX_SUMMARY_CHARS: usize = 80;

fn summarize(text: &str) -> String {
    let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
    match one_line.char_indices().nth(MAX_SUMMARY_CHARS) {
        Some((byte_offset, _)) => format!("{}…", &one_line[..byte_offset]),
        None => one_line,
    }
}

// ── Output ─────────────────────────────────────────────────────────────────

fn print_success(
    name: &str,
    result: &fraiseql_functions::FunctionResult,
    calls: &[HostOpCall],
    json: bool,
) {
    if json {
        println!(
            "{}",
            serde_json::json!({
                "function": name,
                "ok": true,
                "result": result.value,
                "duration_ms": result.duration.as_millis(),
                "logs": result.logs.iter().map(|l| l.message.clone()).collect::<Vec<_>>(),
                "host_ops": calls,
            })
        );
        return;
    }
    println!("✓ {name} ran in {} ms", result.duration.as_millis());
    if let Some(value) = &result.value {
        println!("result: {value}");
    }
    print_logs_and_ops(&result.logs, calls);
}

/// Report what the `before:mutation` chain would decide from this guest's return
/// value (#1328).
///
/// The verdict comes from [`interpret_guest_decision`] — the same function
/// `BeforeMutationChain::execute` decides with — so the harness cannot tell an
/// author one thing while the server does another.
fn print_before_mutation_decision(
    mutation: &str,
    result: &fraiseql_functions::FunctionResult,
    fixture: &serde_json::Value,
    json: bool,
) {
    let decision =
        fraiseql_functions::interpret_guest_decision(result.value.as_ref(), fixture.clone());
    let (verdict, detail) = match &decision {
        fraiseql_functions::BeforeMutationResult::Abort(reason) => {
            ("abort", serde_json::Value::String(reason.clone()))
        },
        fraiseql_functions::BeforeMutationResult::Proceed(arguments) => {
            ("proceed", arguments.clone())
        },
        // Reason: `BeforeMutationResult` is `#[non_exhaustive]`, so this arm is
        // required from outside its crate. The harness reports what it cannot
        // interpret rather than guessing a verdict — the server's own gate refuses
        // the write on an unrecognised decision.
        unknown => ("unrecognised", serde_json::json!(format!("{unknown:?}"))),
    };
    if json {
        println!(
            "{}",
            serde_json::json!({
                "mutation": mutation,
                "decision": verdict,
                "arguments_or_reason": detail,
                "rewritten": verdict == "proceed" && &detail != fixture,
            })
        );
        return;
    }
    match verdict {
        "abort" => println!("decision: ABORT `{mutation}` — {detail}"),
        _ if &detail == fixture => println!("decision: PROCEED `{mutation}` (arguments unchanged)"),
        _ => println!("decision: PROCEED `{mutation}` with rewritten arguments: {detail}"),
    }
}

fn print_guest_error(
    name: &str,
    error: &fraiseql_error::FraiseQLError,
    calls: &[HostOpCall],
    json: bool,
) {
    if json {
        println!(
            "{}",
            serde_json::json!({ "function": name, "ok": false, "error": error.to_string(), "host_ops": calls })
        );
        return;
    }
    eprintln!("✗ {name} errored: {error}");
    print_logs_and_ops(&[], calls);
}

fn print_logs_and_ops(logs: &[fraiseql_functions::LogEntry], calls: &[HostOpCall]) {
    if !logs.is_empty() {
        println!("logs:");
        for entry in logs {
            println!("  [{:?}] {}", entry.level, entry.message);
        }
    }
    if calls.is_empty() {
        println!("host ops: (none)");
    } else {
        println!("host ops ({}):", calls.len());
        for call in calls {
            println!("  {} {}", call.op, call.summary);
        }
    }
}