Skip to main content

sqry_daemon_protocol/
protocol.rs

1//! Wire types for the sqryd daemon IPC.
2//!
3//! Every type in this module serialises as UTF-8 JSON through serde.
4//! The wire format is versioned via the `envelope_version` field on
5//! [`DaemonHelloResponse`] / [`ShimRegisterAck`]; clients negotiate
6//! compatibility during the handshake before issuing any JSON-RPC
7//! request or entering the shim byte-pump.
8//!
9//! # JSON-RPC 2.0 conformance
10//!
11//! - Requests and responses carry the mandatory `"jsonrpc": "2.0"` tag
12//!   enforced by [`JsonRpcVersion`]'s manual serde impls.
13//! - Response ids follow the spec exactly: a response to a request
14//!   with a missing/invalid id MUST carry `id: null`; `Option<JsonRpcId>`
15//!   on [`JsonRpcResponse::id`] is NOT marked `skip_serializing_if`, so
16//!   `None` serialises as JSON `null` instead of being omitted.
17//! - Batches are implemented in the sqry-daemon router; this module
18//!   only provides the single-request envelope types.
19//!
20//! # `shim/register`
21//!
22//! [`ShimRegister`] / [`ShimProtocol`] / [`ShimRegisterAck`] are the
23//! Phase 8c shim handshake wire types. The router in sqry-daemon
24//! discriminates on the very first frame:
25//!
26//! - If the frame object has both `protocol` + `pid` keys (shim-shaped),
27//!   the router enters the shim path and deserialises as [`ShimRegister`]
28//!   with `deny_unknown_fields`. On deserialisation failure (e.g. extra
29//!   keys from the hello shape, or an unknown `protocol` variant) the
30//!   server writes [`ShimRegisterAck`]`{ accepted: false, reason: Some(..) }`
31//!   and closes. **Not** a JSON-RPC `-32600` — the shim client expects a
32//!   [`ShimRegisterAck`] as the first response, so the wire-form stays
33//!   coherent.
34//! - Otherwise the router falls through to the [`DaemonHello`] path
35//!   (JSON-RPC). A frame with neither shape is rejected with
36//!   `-32600 Invalid Request` and `id: null`.
37
38use std::marker::PhantomData;
39
40use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
41
42use crate::revision::{RevisionQueryMetadata, RevisionQueryTarget};
43
44// ---------------------------------------------------------------------------
45// WorkspaceId — protocol-side wire wrapper for sqry-core's WorkspaceId.
46// ---------------------------------------------------------------------------
47
48/// 32-byte stable identity for a logical workspace, byte-identical to
49/// `sqry_core::workspace::WorkspaceId`.
50///
51/// Defined here in the leaf protocol crate so the daemon wire types
52/// (`DaemonHello.logical_workspace`, `daemon/load.logical_workspace`,
53/// `daemon/workspaceStatus.workspace_id`) can carry the identity without
54/// the protocol crate taking a `sqry-core` dependency. The `sqry-daemon`
55/// binary owns the `From`/`Into` bridge against the canonical
56/// `sqry_core::workspace::WorkspaceId` type — both use the same 32-byte
57/// representation, so the bridge is a zero-cost newtype unwrap.
58///
59/// `STEP_6` (workspace-aware-cross-repo DAG) introduced this type. Older
60/// daemon clients that send `DaemonHello` without `logical_workspace`
61/// continue to work because the field is `#[serde(default)]` — they
62/// reproduce today's per-source-root semantics, with `workspace_id =
63/// None` on the matching [`crate::WorkspaceState`] entries.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
65pub struct WorkspaceId([u8; 32]);
66
67impl WorkspaceId {
68    /// Construct from raw 32 bytes. Callers in `sqry-daemon` use this
69    /// to bridge from `sqry_core::workspace::WorkspaceId::as_bytes()`.
70    #[must_use]
71    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
72        Self(bytes)
73    }
74
75    /// Borrow the 32-byte digest. Callers cross the bridge by feeding
76    /// these bytes back into `sqry_core::workspace::WorkspaceId`.
77    #[must_use]
78    pub const fn as_bytes(&self) -> &[u8; 32] {
79        &self.0
80    }
81
82    /// First 16 hex characters. Suitable for log lines / short
83    /// identifiers; **not** sufficient for cross-process identity.
84    #[must_use]
85    pub fn as_short_hex(&self) -> String {
86        let full = self.as_full_hex();
87        full[..16].to_string()
88    }
89
90    /// Full 64-character hex digest. Use this for any identity
91    /// comparison.
92    #[must_use]
93    pub fn as_full_hex(&self) -> String {
94        use std::fmt::Write as _;
95        let mut s = String::with_capacity(64);
96        for byte in &self.0 {
97            // `write!` to a `String` is infallible.
98            let _ = write!(s, "{byte:02x}");
99        }
100        s
101    }
102}
103
104impl std::fmt::Display for WorkspaceId {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.write_str(&self.as_short_hex())
107    }
108}
109
110// ---------------------------------------------------------------------------
111// LogicalWorkspaceWire — daemon-IPC wire form of sqry-core's LogicalWorkspace.
112// ---------------------------------------------------------------------------
113
114/// Wire-form summary of a `LogicalWorkspace`, attached to
115/// [`DaemonHello`] / `daemon/load` payloads. Carries the workspace
116/// identity plus the canonical source-root paths the client wants the
117/// daemon to bind under a single grouping `workspace_id`.
118///
119/// `member_folders` and `exclusions` are explicitly **not** carried on
120/// this wire shape — they are MCP / redaction-side concerns (Step 7 of
121/// the workspace-aware-cross-repo plan), not daemon admission concerns.
122/// The daemon only needs `workspace_id` + the source-root list to build
123/// one [`crate::WorkspaceState`]-keyed entry per source root.
124#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
125#[serde(deny_unknown_fields)]
126pub struct LogicalWorkspaceWire {
127    /// 32-byte BLAKE3-256 identity of the logical workspace.
128    pub workspace_id: WorkspaceId,
129    /// Canonical absolute source-root paths. The daemon constructs one
130    /// `WorkspaceKey { workspace_id: Some(this id), source_root: <p>, .. }`
131    /// per entry, all sharing the same `workspace_id` for grouping.
132    pub source_roots: Vec<std::path::PathBuf>,
133    /// `STEP_11_4` — per-source-root bindings. Each entry's `path` MUST
134    /// appear in [`Self::source_roots`]; the binding's
135    /// `config_fingerprint` overrides the workspace-level default for
136    /// that root only. Empty in the common case so the wire stays
137    /// pre-STEP_11_4-compatible.
138    #[serde(default, skip_serializing_if = "Vec::is_empty")]
139    pub source_root_bindings: Vec<SourceRootBinding>,
140    /// `STEP_11_4` — workspace-level config fingerprint applied to any
141    /// source root that does not carry its own
142    /// [`SourceRootBinding::config_fingerprint`] override. `0` is the
143    /// "fingerprint not set" sentinel.
144    #[serde(default, skip_serializing_if = "is_zero_u64")]
145    pub workspace_config_fingerprint: u64,
146}
147
148#[allow(
149    clippy::trivially_copy_pass_by_ref,
150    reason = "serde skip_serializing_if callbacks are invoked with a reference to the field"
151)]
152fn is_zero_u64(value: &u64) -> bool {
153    *value == 0
154}
155
156/// `STEP_11_4` — per-source-root binding inside a [`LogicalWorkspaceWire`].
157///
158/// `path` MUST appear in the parent [`LogicalWorkspaceWire::source_roots`]
159/// vector; the daemon matches bindings to source roots by canonical path
160/// equality. A binding whose `path` is not in `source_roots` is silently
161/// ignored.
162#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
163#[serde(deny_unknown_fields)]
164pub struct SourceRootBinding {
165    /// Canonical absolute path of the source root this binding applies to.
166    pub path: std::path::PathBuf,
167    /// Per-source-root override of the config fingerprint. `0` means
168    /// "use the workspace-level fingerprint"; non-zero overrides for
169    /// this source root only.
170    #[serde(default, skip_serializing_if = "is_zero_u64")]
171    pub config_fingerprint: u64,
172    /// Optional pre-resolved classpath directory for this source root.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub classpath_dir: Option<std::path::PathBuf>,
175}
176
177// ---------------------------------------------------------------------------
178// WorkspaceIndexStatus — daemon/workspaceStatus result payload.
179// ---------------------------------------------------------------------------
180
181/// Aggregate status of a single source root inside a logical workspace.
182/// Mirrors the per-source-root subset of `WorkspaceStatus` so cross-repo
183/// MCP / LSP queries can render a per-source-root state without paying
184/// the cost of the full `daemon/status` snapshot.
185///
186/// `STEP_11_4` (workspace-aware-cross-repo, 2026-04-26) — adds the
187/// `classpath_present` flag so consumers of `daemon/workspaceStatus`
188/// know which source roots have JVM classpath analysis available
189/// (`<source_root>/.sqry/classpath/` exists) without having to make a
190/// separate filesystem probe. The flag is per-source-root, never
191/// aggregated, so a workspace mixing JVM and non-JVM source roots
192/// reports accurate per-root granularity.
193#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
194pub struct WorkspaceSourceRootStatus {
195    /// Canonical absolute path to the source root.
196    pub source_root: std::path::PathBuf,
197    /// Per-source-root lifecycle state. `Evicted` is a valid (and
198    /// useful — partial eviction is observable here) value for a
199    /// source root that has been LRU'd out while sibling source roots
200    /// remain `Loaded`.
201    pub state: WorkspaceState,
202    /// Live graph size for this source root, in bytes.
203    pub current_bytes: u64,
204    /// `STEP_11_4` — `true` when the daemon observed
205    /// `<source_root>/.sqry/classpath/` as a directory at status time.
206    /// `false` when the directory is absent or the probe failed (the
207    /// daemon never blocks status on a classpath probe; failures
208    /// surface through the LSP-side `WorkspaceIndexStatus.warnings`
209    /// channel instead).
210    ///
211    /// `#[serde(default)]` so v1 IPC payloads (which never carried the
212    /// flag) round-trip into `false`. `skip_serializing_if = ...` is
213    /// deliberately NOT applied — the flag must be serialised even
214    /// when `false` so consumers can distinguish "JVM-aware daemon
215    /// reporting no classpath" from "older daemon that does not yet
216    /// surface the flag".
217    #[serde(default)]
218    pub classpath_present: bool,
219}
220
221/// Aggregate status of a logical workspace, returned by
222/// `daemon/workspaceStatus { workspace_id }`.
223///
224/// The daemon walks every `WorkspaceKey` whose `workspace_id` matches
225/// the request and aggregates them into this view. A workspace is
226/// "partially evicted" when at least one source root reports
227/// [`WorkspaceState::Evicted`] but at least one other reports any
228/// non-Evicted state — see [`Self::partially_evicted`].
229///
230/// `STEP_12` (workspace-aware-cross-repo, 2026-04-26) introduced the
231/// hex-string telemetry fields `workspace_id_short` (16 hex chars,
232/// display) and `workspace_id_full` (64 hex chars, machine identity).
233/// Scripts consuming this payload should key on `workspace_id_full` —
234/// the 32-byte `workspace_id` is the canonical bytewise identity but
235/// the hex string is what humans / shell tooling read. The two hex
236/// fields are derived from `workspace_id`; they are NOT independent
237/// inputs — they exist purely for ergonomic JSON consumption.
238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
239pub struct WorkspaceIndexStatus {
240    /// Identity the request matched against.
241    pub workspace_id: WorkspaceId,
242    /// `STEP_12` — short (16 hex) form of `workspace_id`, suitable for
243    /// CLI columns and human-scale log lines. Display only.
244    pub workspace_id_short: String,
245    /// `STEP_12` — full (64 hex) form of `workspace_id`. Machine
246    /// identity. Cross-process script consumers MUST key on this
247    /// rather than the short form to avoid the (remote, non-zero)
248    /// possibility of short-hex collisions across hundreds of
249    /// thousands of distinct workspaces.
250    pub workspace_id_full: String,
251    /// Per-source-root status rows, sorted by `source_root` for
252    /// deterministic CLI / test output.
253    pub source_roots: Vec<WorkspaceSourceRootStatus>,
254}
255
256impl WorkspaceIndexStatus {
257    /// Whether at least one source root is in [`WorkspaceState::Evicted`]
258    /// while at least one other is not. `false` for fully-loaded or
259    /// fully-evicted aggregates.
260    #[must_use]
261    pub fn partially_evicted(&self) -> bool {
262        let any_evicted = self
263            .source_roots
264            .iter()
265            .any(|r| matches!(r.state, WorkspaceState::Evicted));
266        let any_alive = self
267            .source_roots
268            .iter()
269            .any(|r| !matches!(r.state, WorkspaceState::Evicted));
270        any_evicted && any_alive
271    }
272}
273
274// ---------------------------------------------------------------------------
275// Wire envelope version.
276// ---------------------------------------------------------------------------
277
278/// Version of the daemon wire envelope ([`DaemonHelloResponse::envelope_version`],
279/// [`ShimRegisterAck::envelope_version`]).
280///
281/// Bumped when the [`ResponseEnvelope`] schema changes in an incompatible way.
282/// Kept at `1` per the Amendment-2 2026-04-09 freeze.
283///
284/// This constant lives in the leaf wire-type crate (`sqry-daemon-protocol`) so
285/// every consumer of the wire format — the daemon itself, the daemon client
286/// (`sqry-daemon-client`), and the shim-mode callers inside `sqry-lsp` /
287/// `sqry-mcp` — validates against exactly one source of truth. Clients MUST
288/// reject a response whose `envelope_version` differs from this constant
289/// rather than proceed on a mismatched wire format.
290pub const ENVELOPE_VERSION: u32 = 1;
291
292// ---------------------------------------------------------------------------
293// WorkspaceState — moved here from sqry-daemon/src/workspace/state.rs
294// ---------------------------------------------------------------------------
295
296/// Six-state workspace lifecycle per plan Task 6 Step 1 and Amendment 2 §G.5 /
297/// §G.7.
298///
299/// The `#[repr(u8)]` is load-bearing: `sqry-daemon`'s `LoadedWorkspace::state`
300/// is an `AtomicU8`, and the conversions [`Self::from_u8`] / [`Self::as_u8`]
301/// serialise the state machine without allocation. Values are deliberately
302/// contiguous from 0 so adding a variant stays backwards-compatible with
303/// persisted telemetry.
304///
305/// This type lives in the leaf wire-type crate so [`ResponseMeta`] can
306/// carry a canonical `workspace_state` string on every successful tool
307/// response without the leaf crate taking a dep on `sqry-daemon` itself.
308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
309#[repr(u8)]
310pub enum WorkspaceState {
311    /// Workspace entry exists but no graph has been loaded yet.
312    Unloaded = 0,
313
314    /// Initial load is in progress — a single blocking read from disk or
315    /// a full rebuild with no prior snapshot.
316    Loading = 1,
317
318    /// Graph is loaded, idle, and ready to serve queries.
319    Loaded = 2,
320
321    /// A rebuild (incremental or full) is actively running on the
322    /// dispatcher's background task. Queries keep serving the prior
323    /// `ArcSwap<CodeGraph>` snapshot until `publish_and_retain` swaps
324    /// the new graph in.
325    Rebuilding = 3,
326
327    /// Workspace was LRU-evicted or explicitly unloaded. The entry is
328    /// REMOVED from the manager map — the next query must re-load via
329    /// `get_or_load`. This discriminant exists for the short window
330    /// between `execute_eviction` storing the state and
331    /// `workspaces.remove(key)` completing (both under
332    /// `workspaces.write()`); external observers routed through
333    /// `WorkspaceManager::classify_for_serve` see the map-missing arm
334    /// first and get `DaemonError::WorkspaceEvicted` regardless.
335    Evicted = 4,
336
337    /// The most recent rebuild failed. Queries are served from the last
338    /// good snapshot with `meta.stale = true`; if the
339    /// `stale_serve_max_age_hours` cap is exceeded, queries receive the
340    /// JSON-RPC `-32002 workspace_stale_expired` error instead.
341    Failed = 5,
342}
343
344impl WorkspaceState {
345    /// Round-trip the state to its discriminant.
346    #[must_use]
347    pub const fn as_u8(self) -> u8 {
348        self as u8
349    }
350
351    /// Parse a discriminant back to a state. Returns `None` on any value
352    /// outside the current enum range — callers should treat this as a
353    /// telemetry corruption rather than silently map to `Unloaded`.
354    #[must_use]
355    pub const fn from_u8(value: u8) -> Option<Self> {
356        match value {
357            0 => Some(Self::Unloaded),
358            1 => Some(Self::Loading),
359            2 => Some(Self::Loaded),
360            3 => Some(Self::Rebuilding),
361            4 => Some(Self::Evicted),
362            5 => Some(Self::Failed),
363            _ => None,
364        }
365    }
366
367    /// Canonical display string. Used by `daemon/status` output and
368    /// tracing spans.
369    #[must_use]
370    pub const fn as_str(self) -> &'static str {
371        match self {
372            Self::Unloaded => "unloaded",
373            Self::Loading => "loading",
374            Self::Loaded => "loaded",
375            Self::Rebuilding => "rebuilding",
376            Self::Evicted => "evicted",
377            Self::Failed => "failed",
378        }
379    }
380
381    /// Whether the workspace can still serve queries in this state.
382    ///
383    /// `true` for [`Self::Loaded`], [`Self::Rebuilding`] (old snapshot
384    /// still served), and [`Self::Failed`] (stale-serve subject to the
385    /// age cap). `false` for [`Self::Unloaded`], [`Self::Loading`],
386    /// and [`Self::Evicted`].
387    #[must_use]
388    pub const fn is_serving(self) -> bool {
389        matches!(self, Self::Loaded | Self::Rebuilding | Self::Failed)
390    }
391}
392
393impl std::fmt::Display for WorkspaceState {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        f.write_str(self.as_str())
396    }
397}
398
399// ---------------------------------------------------------------------------
400// Handshake types.
401// ---------------------------------------------------------------------------
402
403/// Pre-handshake header sent as the very first frame by a CLI client.
404/// The server responds with [`DaemonHelloResponse`] before the
405/// JSON-RPC request loop begins.
406#[derive(Debug, Clone, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct DaemonHello {
409    /// Free-form client identifier (`env!("CARGO_PKG_VERSION")` plus
410    /// user-agent suffix). Informational only.
411    pub client_version: String,
412
413    /// Wire protocol version. Phase 8a accepts exactly `1`.
414    pub protocol_version: u32,
415
416    /// Optional logical-workspace binding hint (`STEP_6` of the
417    /// workspace-aware-cross-repo plan). When present, every
418    /// subsequent `daemon/load` on this connection that does not
419    /// itself supply `logical_workspace` inherits this binding —
420    /// keeping today's anonymous behaviour for clients that do not
421    /// set the hint.
422    ///
423    /// `#[serde(default)]` so older clients (and the standalone
424    /// `sqry-mcp` / `sqry-lsp` shims that have not yet learned about
425    /// logical workspaces) keep working with `None`. The daemon
426    /// router synthesises one `WorkspaceKey` per source root with
427    /// `workspace_id = Some(this id)`.
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    pub logical_workspace: Option<LogicalWorkspaceWire>,
430}
431
432/// Server's reply to [`DaemonHello`]. If `compatible` is `false` the
433/// server closes the connection immediately after the frame is sent.
434#[derive(Debug, Clone, Serialize, Deserialize)]
435#[serde(deny_unknown_fields)]
436pub struct DaemonHelloResponse {
437    pub compatible: bool,
438    pub daemon_version: String,
439    pub envelope_version: u32,
440}
441
442// ---------------------------------------------------------------------------
443// Shim handshake (Phase 8c wire types).
444// ---------------------------------------------------------------------------
445
446/// Which client protocol the shim will pump bytes for. Phase 8c surface.
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
448#[serde(rename_all = "lowercase")]
449pub enum ShimProtocol {
450    Lsp,
451    Mcp,
452}
453
454/// Shim registration header sent as the first frame by a
455/// `sqry lsp --daemon` or `sqry mcp --daemon` process. The router in
456/// sqry-daemon shape-discriminates between [`DaemonHello`] and this
457/// type using `#[serde(deny_unknown_fields)]`.
458#[derive(Debug, Clone, Serialize, Deserialize)]
459#[serde(deny_unknown_fields)]
460pub struct ShimRegister {
461    pub protocol: ShimProtocol,
462    pub pid: u32,
463}
464
465/// Server's reply to [`ShimRegister`]. If `accepted` is `false` the
466/// server closes the connection after sending the ack and the shim
467/// client surfaces `reason` to its parent process. When `accepted` is
468/// `true`, `reason` is omitted from the wire form (skip-if-none).
469#[derive(Debug, Clone, Serialize, Deserialize)]
470#[serde(deny_unknown_fields)]
471pub struct ShimRegisterAck {
472    pub accepted: bool,
473    pub daemon_version: String,
474    /// Rejection reason. Omitted from the wire when accepted=true.
475    #[serde(skip_serializing_if = "Option::is_none")]
476    pub reason: Option<String>,
477    pub envelope_version: u32,
478}
479
480// ---------------------------------------------------------------------------
481// ResponseEnvelope.
482// ---------------------------------------------------------------------------
483
484/// Uniform successful-response wrapper. Every successful method
485/// response is serialised as `ResponseEnvelope<T>` at the JSON-RPC
486/// `result` field — clients can rely on the [`ResponseMeta`] shape
487/// being present on every successful reply regardless of method.
488#[derive(Debug, Clone, Serialize, Deserialize)]
489pub struct ResponseEnvelope<T> {
490    pub result: T,
491    pub meta: ResponseMeta,
492}
493
494/// Metadata attached to every successful response. For Phase 8a
495/// management methods the staleness fields are always absent
496/// (`stale = false`, no `last_good_at`, no `last_error`,
497/// `workspace_state = None`). Phase 8b populates them from the
498/// server-side `ServeVerdict` for tool-method responses.
499#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500pub struct ResponseMeta {
501    pub stale: bool,
502
503    #[serde(skip_serializing_if = "Option::is_none")]
504    pub last_good_at: Option<String>,
505
506    #[serde(skip_serializing_if = "Option::is_none")]
507    pub last_error: Option<String>,
508
509    /// Canonical workspace state string (serde form of
510    /// [`WorkspaceState`]). `None` for methods not tied to a workspace.
511    #[serde(skip_serializing_if = "Option::is_none")]
512    pub workspace_state: Option<WorkspaceState>,
513
514    pub daemon_version: String,
515}
516
517impl ResponseMeta {
518    /// Construct the [`ResponseMeta`] used by daemon management methods
519    /// (`daemon/status`, `daemon/unload`, `daemon/stop` — the ones not
520    /// bound to a specific workspace).
521    #[must_use]
522    pub fn management(daemon_version: &str) -> Self {
523        Self {
524            stale: false,
525            last_good_at: None,
526            last_error: None,
527            workspace_state: None,
528            daemon_version: daemon_version.to_owned(),
529        }
530    }
531
532    /// Construct the [`ResponseMeta`] for a successful `daemon/load`.
533    /// Phase 8b adds `fresh_from` / `stale_from` constructors for
534    /// MCP tool-method responses that route through `classify_for_serve`.
535    #[must_use]
536    pub fn loaded(daemon_version: &str) -> Self {
537        Self {
538            stale: false,
539            last_good_at: None,
540            last_error: None,
541            workspace_state: Some(WorkspaceState::Loaded),
542            daemon_version: daemon_version.to_owned(),
543        }
544    }
545
546    /// Construct [`ResponseMeta`] for a tool-method response served from a
547    /// Fresh workspace verdict (`WorkspaceState::Loaded` or `Rebuilding`).
548    ///
549    /// Phase 8b Task 7 — populated by the `tool_dispatch` helper when
550    /// the daemon's `WorkspaceManager::classify_for_serve` returns
551    /// `ServeVerdict::Fresh`. `stale` is `false` and both `last_good_at`
552    /// and `last_error` are absent from the wire form (they are skipped
553    /// by `serde(skip_serializing_if = "Option::is_none")`).
554    #[must_use]
555    pub fn fresh_from(state: WorkspaceState, daemon_version: &str) -> Self {
556        Self {
557            stale: false,
558            last_good_at: None,
559            last_error: None,
560            workspace_state: Some(state),
561            daemon_version: daemon_version.to_owned(),
562        }
563    }
564
565    /// Construct [`ResponseMeta`] for a tool-method response served from a
566    /// Stale verdict. `last_good_at` is rendered as RFC3339 UTC-Zulu via
567    /// `chrono::DateTime::<Utc>::from(SystemTime) -> to_rfc3339_opts(Secs, true)`.
568    ///
569    /// `workspace_state` is fixed at [`WorkspaceState::Failed`] because
570    /// `WorkspaceManager::classify_for_serve` only emits a Stale verdict
571    /// when the observed state is `Failed`. Keeping this constructor
572    /// intentionally rigid (no caller-supplied state) prevents the wire
573    /// form from claiming `stale = true` with a `workspace_state` the
574    /// classifier could never have produced.
575    #[must_use]
576    pub fn stale_from(
577        last_good_at: std::time::SystemTime,
578        last_error: Option<String>,
579        daemon_version: &str,
580    ) -> Self {
581        use chrono::{DateTime, SecondsFormat, Utc};
582        let rfc3339 =
583            DateTime::<Utc>::from(last_good_at).to_rfc3339_opts(SecondsFormat::Secs, true);
584        Self {
585            stale: true,
586            last_good_at: Some(rfc3339),
587            last_error,
588            workspace_state: Some(WorkspaceState::Failed),
589            daemon_version: daemon_version.to_owned(),
590        }
591    }
592}
593
594// ---------------------------------------------------------------------------
595// daemon/load result wire type.
596// ---------------------------------------------------------------------------
597
598/// `daemon/load` success result payload.
599///
600/// Serialised under the `result` field of [`ResponseEnvelope`]. Living
601/// in the leaf protocol crate lets both the daemon (writer) and
602/// [`sqry-daemon-client`][] (reader) share a single typed definition —
603/// clients can `serde_json::from_value::<ResponseEnvelope<LoadResult>>`
604/// and get compile-time schema checking instead of stringly-typed
605/// `serde_json::Value::get` lookups.
606///
607/// [`sqry-daemon-client`]: ../../sqry-daemon-client/index.html
608#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
609#[serde(deny_unknown_fields)]
610pub struct LoadResult {
611    /// The canonicalised workspace root path that the daemon loaded.
612    pub root: std::path::PathBuf,
613
614    /// Resident graph memory footprint for the loaded workspace, in
615    /// bytes. Matches `LoadedWorkspace::heap_bytes()` at the moment of
616    /// the response.
617    pub current_bytes: u64,
618
619    /// The canonical workspace lifecycle state after the load
620    /// completes. Always [`WorkspaceState::Loaded`] on the successful
621    /// `daemon/load` path — the field is typed so clients do not have
622    /// to re-parse the string.
623    pub state: WorkspaceState,
624}
625
626/// Status of a `daemon/rebuild` invocation (cluster-G §2.4).
627///
628/// Distinguishes the four outcomes the dispatcher can produce so a
629/// `--timeout 0` (fire-and-forget) caller can distinguish "started in
630/// the background" from "actually completed in this call". Pre-§2.4
631/// callers received only the `Completed` shape and a missing field
632/// here is interpreted as `Completed` for backward compatibility.
633#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
634#[serde(rename_all = "snake_case")]
635pub enum RebuildStatus {
636    /// The rebuild ran to completion in this call. `duration_ms`,
637    /// `nodes`, `edges`, `files_indexed`, and `was_full` are all
638    /// populated.
639    #[default]
640    Completed,
641    /// `--timeout 0` (fire-and-forget): the runner-role was acquired
642    /// and the rebuild is running in the background. The stat fields
643    /// are absent. The caller should poll `daemon/status` to observe
644    /// completion.
645    Started,
646    /// Another runner is active; this request was coalesced into the
647    /// pending lane. The stat fields reflect the runner's *previous*
648    /// publish if known, or are absent.
649    Coalesced,
650    /// Reservation failed before the pipeline started (e.g.
651    /// `MemoryBudgetExceeded`, `WorkspaceOversize`). The stat fields
652    /// are absent.
653    Rejected,
654}
655
656/// `daemon/rebuild` success result payload (`schema_version` 2 — see
657/// cluster-G §2.4).
658///
659/// Serialised under the `result` field of [`ResponseEnvelope`]. The
660/// stat fields are `Option`-typed because `--timeout 0` callers
661/// receive them populated only when `status == Completed`.
662#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
663pub struct RebuildResult {
664    /// The canonicalised workspace root path that was rebuilt.
665    pub root: std::path::PathBuf,
666    /// Outcome of the dispatch. New in cluster-G §2.4. Older clients
667    /// that pre-date the schema bump are tolerated by the
668    /// `#[serde(default)]` here — they read the field as `Completed`
669    /// and continue to work because pre-§2.4 daemons only ever
670    /// produced the completed shape.
671    #[serde(default)]
672    pub status: RebuildStatus,
673    /// Wall-clock time the rebuild took, in milliseconds. Populated
674    /// only when `status == Completed`.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub duration_ms: Option<u64>,
677    /// Node count of the freshly published graph. Populated only
678    /// when `status == Completed`.
679    #[serde(default, skip_serializing_if = "Option::is_none")]
680    pub nodes: Option<u64>,
681    /// Edge count of the freshly published graph. Populated only
682    /// when `status == Completed`.
683    #[serde(default, skip_serializing_if = "Option::is_none")]
684    pub edges: Option<u64>,
685    /// Number of source files indexed in the freshly published
686    /// graph. Populated only when `status == Completed`.
687    #[serde(default, skip_serializing_if = "Option::is_none")]
688    pub files_indexed: Option<u64>,
689    /// `true` when the rebuild was a full (non-incremental) rebuild.
690    /// Populated only when `status == Completed`.
691    #[serde(default, skip_serializing_if = "Option::is_none")]
692    pub was_full: Option<bool>,
693}
694
695/// `daemon/cancel_rebuild` success result payload.
696///
697/// Serialised under the `result` field of [`ResponseEnvelope`].
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
699pub struct CancelRebuildResult {
700    /// The canonicalised workspace root path whose rebuild was signalled for
701    /// cancellation.
702    pub root: std::path::PathBuf,
703    /// `true` when a rebuild was actually in flight at the moment the
704    /// cancellation signal was dispatched.
705    pub cancelled: bool,
706}
707
708// ---------------------------------------------------------------------------
709// `daemon/search` / `daemon/query` wire types.
710//
711// Mirror the relevant arguments of `commands::search::run_search` so the
712// CLI shim at `sqry-cli/src/commands/search.rs` can attempt the daemon
713// path before falling through to in-process load. Field shape follows the
714// established protocol-crate convention: leaf-only (no upstream sqry deps,
715// no tower-lsp types), flat fields rather than nested LSP `Location`
716// wrappers — the CLI converts to `DisplaySymbol` for output formatting,
717// keeping parity at the formatter layer rather than the wire layer.
718// ---------------------------------------------------------------------------
719
720/// `daemon/search` request payload.
721///
722/// Submitted as the `params` field of a [`JsonRpcRequest`] with
723/// `method == "daemon/search"`. Wire-compatible with `--exact`, regex, and
724/// fuzzy search modes; the daemon handler dispatches to the same
725/// `find_by_exact_name` / regex / fuzzy logic the in-process CLI uses
726/// (verifiable by the `DAEMON_SEARCH_TESTS` parity assertions).
727///
728/// Errors: a request whose `search_path` does not resolve to a
729/// daemon-loaded workspace returns `WorkspaceEvicted` (-32004) or
730/// `WorkspaceNotLoaded`; an incompatible plugin selection returns
731/// `WorkspaceIncompatibleGraph` (-32005). The CLI shim treats either as
732/// a soft failure and falls through to the in-process path.
733#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
734#[serde(deny_unknown_fields)]
735pub struct SearchRequest {
736    /// Wire envelope version. Defaults to [`ENVELOPE_VERSION`] for
737    /// forward-compatible serde when the field is absent.
738    #[serde(default = "default_envelope_version")]
739    pub envelope_version: u32,
740    /// Pattern to search for. Interpreted per `mode`.
741    pub pattern: String,
742    /// Workspace root the search should resolve against. The daemon
743    /// normalises and looks this up via `WorkspaceManager`.
744    pub search_path: String,
745    /// Search interpretation mode. Maps to the CLI's `--exact` / `--fuzzy`
746    /// flags; everything else falls into [`SearchMode::Regex`].
747    pub mode: SearchMode,
748    /// Optional kind filter (e.g. `"function"`, `"class"`). Matches
749    /// the in-process `Cli::kind` semantics.
750    #[serde(default, skip_serializing_if = "Option::is_none")]
751    pub kind: Option<String>,
752    /// Optional language filter (e.g. `"rust"`, `"python"`).
753    #[serde(default, skip_serializing_if = "Option::is_none")]
754    pub lang: Option<String>,
755    /// Maximum result count. `None` lets the daemon apply its default
756    /// (mirrors `Cli::limit`).
757    #[serde(default, skip_serializing_if = "Option::is_none")]
758    pub limit: Option<u32>,
759    /// Mirror of the CLI's `--include-generated` flag (default in-process:
760    /// `false` — macro-generated symbols are dropped). When `false` the
761    /// daemon applies the same `filter_nodes_by_macro_boundary` contract
762    /// as `sqry-cli/src/commands/search.rs::run_regular_search` so the
763    /// daemon route does not surface macro-generated symbols the
764    /// in-process path would have dropped.
765    ///
766    /// Serde default is `true` for backward compatibility — a request
767    /// body that omits the field gets the same "no filter" behaviour
768    /// the tier-2 daemon handler shipped with originally (the
769    /// `DAEMON_SEARCH_HANDLER` unit's approved tests rely on that
770    /// default and continue to pass without modification).
771    #[serde(default = "default_include_generated")]
772    pub include_generated: bool,
773    /// Optional explicit revision target. When absent, daemon search keeps
774    /// the legacy behavior and queries only the live workspace identified by
775    /// `search_path`.
776    #[serde(default, skip_serializing_if = "Option::is_none")]
777    pub revision: Option<RevisionQueryTarget>,
778}
779
780fn default_envelope_version() -> u32 {
781    ENVELOPE_VERSION
782}
783
784fn default_include_generated() -> bool {
785    // True keeps the pre-`include_generated` wire-shape behaviour: the
786    // daemon returns every candidate, including macro-generated ones.
787    // Callers that need parity with the CLI's default exact search must
788    // set this to `false` so the daemon drops `macro_generated == Some(true)`
789    // nodes before serialising the result set.
790    true
791}
792
793/// Search interpretation mode for [`SearchRequest::mode`].
794#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
795#[serde(rename_all = "lowercase")]
796pub enum SearchMode {
797    /// Regex pattern over interned symbol names. Default behaviour for
798    /// `sqry search <pat>` and `sqry <pat>`.
799    Regex,
800    /// Literal byte-exact symbol-name match (`--exact` / planner
801    /// `name:<literal>` contract).
802    Exact,
803    /// Trigram fuzzy match (`--fuzzy`).
804    Fuzzy,
805}
806
807/// One search hit. Flat shape (no LSP `Location` wrapper) so the protocol
808/// crate stays leaf-only; the CLI shim converts to `DisplaySymbol` for
809/// output formatting.
810///
811/// Line/column semantics match `DisplaySymbol`:
812///   - `start_line` / `end_line` are 1-based
813///   - `start_column` / `end_column` are 0-based byte offsets
814#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
815#[serde(deny_unknown_fields)]
816pub struct SearchItem {
817    pub name: String,
818    pub qualified_name: String,
819    pub kind: String,
820    pub language: String,
821    pub file_path: String,
822    pub start_line: u32,
823    pub start_column: u32,
824    pub end_line: u32,
825    pub end_column: u32,
826    /// Fuzzy match score. Absent for regex / exact hits.
827    #[serde(default, skip_serializing_if = "Option::is_none")]
828    pub score: Option<f32>,
829}
830
831/// `daemon/search` success result payload.
832///
833/// Serialised under the `result` field of [`ResponseEnvelope`]. The CLI
834/// shim reads `total` + `truncated` separately so it can emit the same
835/// "Showing N of M matches" banner the in-process path does.
836#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
837#[serde(deny_unknown_fields)]
838pub struct SearchResult {
839    /// The hits returned for this query, post-limit.
840    pub items: Vec<SearchItem>,
841    /// Pre-truncation match count. When `truncated == false` this equals
842    /// `items.len()`; when `truncated == true` it is at least `limit + 1`
843    /// (lower-bound sentinel, matching the LSP `list_unused_symbols` /
844    /// `list_circular_dependencies` convention).
845    pub total: u64,
846    /// True when the result was capped by `SearchRequest::limit`.
847    pub truncated: bool,
848    /// Reserved for future cursor-based pagination. Tier-2 always returns
849    /// `None`; clients should not assume any specific format.
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub cursor: Option<String>,
852    /// Revision metadata for revision-aware searches. Absent for legacy
853    /// live-workspace searches.
854    #[serde(default, skip_serializing_if = "Option::is_none")]
855    pub revision: Option<RevisionQueryMetadata>,
856}
857
858/// `daemon/query` request payload.
859///
860/// The request mirrors the structural `sqry query` CLI surface and can target
861/// either the loaded live workspace (`revision == None`) or an explicit
862/// resident revision handle / selector. Explicit revision responses carry
863/// provenance; omitted selectors preserve live-workspace behavior.
864#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
865#[serde(deny_unknown_fields)]
866pub struct QueryRequest {
867    /// Wire envelope version.
868    #[serde(default = "default_envelope_version")]
869    pub envelope_version: u32,
870    /// Structural query expression.
871    pub query: String,
872    /// Workspace or repository root used to resolve the graph.
873    pub search_path: String,
874    /// Optional result cap. `None` means the daemon default.
875    #[serde(default, skip_serializing_if = "Option::is_none")]
876    pub limit: Option<u32>,
877    /// Optional explicit revision target. Absent means live workspace only.
878    #[serde(default, skip_serializing_if = "Option::is_none")]
879    pub revision: Option<RevisionQueryTarget>,
880}
881
882/// `daemon/query` success result payload.
883#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
884#[serde(deny_unknown_fields)]
885pub struct QueryResult {
886    /// Query matches converted to the common symbol wire shape.
887    pub items: Vec<SearchItem>,
888    /// Pre-truncation match count.
889    pub total: u64,
890    /// True when `items` was capped by [`QueryRequest::limit`].
891    pub truncated: bool,
892    /// Revision metadata for explicit revision queries.
893    #[serde(default, skip_serializing_if = "Option::is_none")]
894    pub revision: Option<RevisionQueryMetadata>,
895}
896
897// ---------------------------------------------------------------------------
898// JSON-RPC 2.0 envelope types.
899// ---------------------------------------------------------------------------
900
901/// JSON-RPC `"2.0"` version tag. Manual serde impls enforce exact
902/// string match on the wire so malformed requests never leak into the
903/// method dispatcher.
904#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
905pub struct JsonRpcVersion;
906
907impl Serialize for JsonRpcVersion {
908    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
909        s.serialize_str("2.0")
910    }
911}
912
913impl<'de> Deserialize<'de> for JsonRpcVersion {
914    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
915        struct Vis(PhantomData<JsonRpcVersion>);
916        impl de::Visitor<'_> for Vis {
917            type Value = JsonRpcVersion;
918            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
919                f.write_str("the string \"2.0\"")
920            }
921            fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
922                if v == "2.0" {
923                    Ok(JsonRpcVersion)
924                } else {
925                    Err(E::invalid_value(de::Unexpected::Str(v), &"\"2.0\""))
926                }
927            }
928        }
929        d.deserialize_str(Vis(PhantomData))
930    }
931}
932
933/// JSON-RPC id: `null`, integer (signed or unsigned), or string.
934/// `I64` covers `i64::MIN..=i64::MAX`; `U64` covers
935/// `i64::MAX + 1..=u64::MAX`. Serde's untagged deserialize tries
936/// variants in order so `0..=i64::MAX` lands in `I64` and
937/// `i64::MAX + 1..=u64::MAX` in `U64`.
938#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
939#[serde(untagged)]
940pub enum JsonRpcId {
941    /// Signed integer id.
942    I64(i64),
943    /// Unsigned integer id above `i64::MAX`.
944    U64(u64),
945    /// String id.
946    Str(String),
947}
948
949/// JSON-RPC 2.0 request.
950#[derive(Debug, Clone, Serialize, Deserialize)]
951pub struct JsonRpcRequest {
952    pub jsonrpc: JsonRpcVersion,
953
954    /// `None` ≙ notification (no response expected).
955    #[serde(default, skip_serializing_if = "Option::is_none")]
956    pub id: Option<JsonRpcId>,
957
958    pub method: String,
959
960    #[serde(default)]
961    pub params: serde_json::Value,
962}
963
964/// JSON-RPC 2.0 response. `id` is [`Option<JsonRpcId>`] with **no**
965/// `skip_serializing_if` — the `None` case serialises as JSON `null`,
966/// which is exactly what the spec demands for parse-error and
967/// invalid-request responses.
968#[derive(Debug, Clone, Serialize, Deserialize)]
969pub struct JsonRpcResponse {
970    pub jsonrpc: JsonRpcVersion,
971
972    /// `null` on the wire when the server could not determine the
973    /// originating request id (parse error, invalid request shape,
974    /// batch element with un-parseable id).
975    pub id: Option<JsonRpcId>,
976
977    #[serde(flatten)]
978    pub payload: JsonRpcPayload,
979}
980
981/// Tagged success-or-error payload. Serde `untagged` so the wire form
982/// is `{... "result": ...}` or `{... "error": ...}`, never both.
983#[derive(Debug, Clone, Serialize, Deserialize)]
984#[serde(untagged)]
985pub enum JsonRpcPayload {
986    Success { result: serde_json::Value },
987    Error { error: JsonRpcError },
988}
989
990/// JSON-RPC 2.0 error payload.
991#[derive(Debug, Clone, Serialize, Deserialize)]
992pub struct JsonRpcError {
993    pub code: i32,
994    pub message: String,
995    #[serde(skip_serializing_if = "Option::is_none")]
996    pub data: Option<serde_json::Value>,
997}
998
999impl JsonRpcResponse {
1000    /// Construct a successful response.
1001    #[must_use]
1002    pub fn success(id: Option<JsonRpcId>, result: serde_json::Value) -> Self {
1003        Self {
1004            jsonrpc: JsonRpcVersion,
1005            id,
1006            payload: JsonRpcPayload::Success { result },
1007        }
1008    }
1009
1010    /// Construct an error response.
1011    #[must_use]
1012    pub fn error(
1013        id: Option<JsonRpcId>,
1014        code: i32,
1015        message: impl Into<String>,
1016        data: Option<serde_json::Value>,
1017    ) -> Self {
1018        Self {
1019            jsonrpc: JsonRpcVersion,
1020            id,
1021            payload: JsonRpcPayload::Error {
1022                error: JsonRpcError {
1023                    code,
1024                    message: message.into(),
1025                    data,
1026                },
1027            },
1028        }
1029    }
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035
1036    #[test]
1037    fn jsonrpc_version_roundtrip() {
1038        let wire = serde_json::to_string(&JsonRpcVersion).unwrap();
1039        assert_eq!(wire, r#""2.0""#);
1040        let back: JsonRpcVersion = serde_json::from_str(&wire).unwrap();
1041        assert_eq!(back, JsonRpcVersion);
1042    }
1043
1044    #[test]
1045    fn jsonrpc_version_rejects_wrong_string() {
1046        let err = serde_json::from_str::<JsonRpcVersion>(r#""1.0""#)
1047            .expect_err("must reject non-\"2.0\"");
1048        assert!(err.to_string().contains("\"2.0\""));
1049    }
1050
1051    #[test]
1052    fn jsonrpc_id_untagged_roundtrip() {
1053        let cases: &[(&str, JsonRpcId)] = &[
1054            ("0", JsonRpcId::I64(0)),
1055            ("-7", JsonRpcId::I64(-7)),
1056            (&i64::MAX.to_string(), JsonRpcId::I64(i64::MAX)),
1057            ("\"abc\"", JsonRpcId::Str("abc".into())),
1058        ];
1059        for (wire, expected) in cases {
1060            let parsed: JsonRpcId = serde_json::from_str(wire).expect(wire);
1061            assert_eq!(&parsed, expected, "round-trip failed for {wire}");
1062        }
1063        // i64::MAX + 1 routes to U64.
1064        let u: JsonRpcId = serde_json::from_str("9223372036854775808").unwrap();
1065        assert_eq!(u, JsonRpcId::U64(9_223_372_036_854_775_808));
1066    }
1067
1068    #[test]
1069    fn response_id_none_serializes_as_json_null() {
1070        let resp = JsonRpcResponse::error(None, -32700, "Parse error", None);
1071        let wire = serde_json::to_string(&resp).unwrap();
1072        assert!(
1073            wire.contains(r#""id":null"#),
1074            "expected id:null in wire form, got: {wire}"
1075        );
1076    }
1077
1078    #[test]
1079    fn response_id_some_serializes_as_value() {
1080        let resp = JsonRpcResponse::success(Some(JsonRpcId::I64(7)), serde_json::json!({}));
1081        let wire = serde_json::to_string(&resp).unwrap();
1082        assert!(wire.contains(r#""id":7"#));
1083    }
1084
1085    #[test]
1086    fn response_meta_management_has_none_workspace_state() {
1087        let meta = ResponseMeta::management("8.0.6");
1088        let wire = serde_json::to_string(&meta).unwrap();
1089        assert!(!wire.contains("workspace_state"), "wire: {wire}");
1090        assert!(wire.contains(r#""stale":false"#));
1091        assert!(wire.contains(r#""daemon_version":"8.0.6""#));
1092    }
1093
1094    #[test]
1095    fn response_meta_loaded_has_loaded_workspace_state() {
1096        let meta = ResponseMeta::loaded("8.0.6");
1097        let wire = serde_json::to_string(&meta).unwrap();
1098        assert!(
1099            wire.contains(r#""workspace_state":"Loaded""#),
1100            "wire: {wire}"
1101        );
1102    }
1103
1104    #[test]
1105    fn response_meta_fresh_from_emits_state() {
1106        let meta = ResponseMeta::fresh_from(WorkspaceState::Loaded, "8.0.6");
1107        let wire = serde_json::to_string(&meta).unwrap();
1108        assert!(
1109            wire.contains(r#""workspace_state":"Loaded""#),
1110            "wire: {wire}"
1111        );
1112        assert!(wire.contains(r#""stale":false"#), "wire: {wire}");
1113        // `last_good_at` / `last_error` are omitted for a Fresh verdict.
1114        assert!(!wire.contains("last_good_at"), "wire: {wire}");
1115        assert!(!wire.contains("last_error"), "wire: {wire}");
1116
1117        // Rebuilding is also a valid Fresh variant per `classify_for_serve`.
1118        let meta_rebuild = ResponseMeta::fresh_from(WorkspaceState::Rebuilding, "8.0.6");
1119        let wire_rebuild = serde_json::to_string(&meta_rebuild).unwrap();
1120        assert!(
1121            wire_rebuild.contains(r#""workspace_state":"Rebuilding""#),
1122            "wire: {wire_rebuild}"
1123        );
1124    }
1125
1126    #[test]
1127    fn response_meta_stale_from_rfc3339_and_workspace_state() {
1128        let anchor =
1129            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_760_000_000);
1130        let meta = ResponseMeta::stale_from(anchor, Some("boom".to_owned()), "8.0.6");
1131        let wire = serde_json::to_string(&meta).unwrap();
1132        assert!(wire.contains(r#""stale":true"#), "wire: {wire}");
1133        assert!(
1134            wire.contains(r#""workspace_state":"Failed""#),
1135            "wire: {wire}"
1136        );
1137        assert!(wire.contains(r#""last_error":"boom""#), "wire: {wire}");
1138        // RFC3339 UTC-Zulu — the rendered timestamp must terminate with `Z"`.
1139        let last_good_marker = r#""last_good_at":""#;
1140        let start = wire
1141            .find(last_good_marker)
1142            .unwrap_or_else(|| panic!("missing last_good_at in wire: {wire}"))
1143            + last_good_marker.len();
1144        let rest = &wire[start..];
1145        let end = rest
1146            .find('"')
1147            .expect("last_good_at must be a closed string");
1148        let rfc = &rest[..end];
1149        assert!(rfc.ends_with('Z'), "expected UTC-Zulu, got: {rfc}");
1150        assert!(
1151            rfc.contains('T'),
1152            "RFC3339 must carry a 'T' separator: {rfc}"
1153        );
1154    }
1155
1156    // ------------------------------------------------------------------
1157    // ShimRegisterAck tests (Phase 8c U1 new surface).
1158    // ------------------------------------------------------------------
1159
1160    #[test]
1161    fn shim_register_ack_accepted_omits_reason_on_wire() {
1162        let ack = ShimRegisterAck {
1163            accepted: true,
1164            daemon_version: "8.0.6".to_owned(),
1165            reason: None,
1166            envelope_version: 1,
1167        };
1168        let wire = serde_json::to_string(&ack).unwrap();
1169        assert!(!wire.contains("reason"), "wire: {wire}");
1170        assert!(wire.contains(r#""accepted":true"#), "wire: {wire}");
1171        assert!(wire.contains(r#""daemon_version":"8.0.6""#), "wire: {wire}");
1172        assert!(wire.contains(r#""envelope_version":1"#), "wire: {wire}");
1173    }
1174
1175    #[test]
1176    fn shim_register_ack_rejected_includes_reason() {
1177        let ack = ShimRegisterAck {
1178            accepted: false,
1179            daemon_version: "8.0.6".to_owned(),
1180            reason: Some("cap".to_owned()),
1181            envelope_version: 1,
1182        };
1183        let wire = serde_json::to_string(&ack).unwrap();
1184        assert!(wire.contains(r#""reason":"cap""#), "wire: {wire}");
1185        assert!(wire.contains(r#""accepted":false"#), "wire: {wire}");
1186    }
1187
1188    // ------------------------------------------------------------------
1189    // deny_unknown_fields verification (iter-1 M1 fix).
1190    // ------------------------------------------------------------------
1191
1192    #[test]
1193    fn daemon_hello_rejects_unknown_fields() {
1194        let wire = r#"{"client_version":"x","protocol_version":1,"extra":true}"#;
1195        let err = serde_json::from_str::<DaemonHello>(wire)
1196            .expect_err("DaemonHello must reject unknown fields");
1197        // serde's `deny_unknown_fields` error message contains
1198        // "unknown field" — enough to assert without pinning exact phrasing.
1199        let msg = err.to_string();
1200        assert!(
1201            msg.contains("unknown field"),
1202            "expected 'unknown field' in error, got: {msg}"
1203        );
1204    }
1205
1206    #[test]
1207    fn shim_register_rejects_unknown_fields() {
1208        let wire = r#"{"protocol":"lsp","pid":1,"extra":true}"#;
1209        let err = serde_json::from_str::<ShimRegister>(wire)
1210            .expect_err("ShimRegister must reject unknown fields");
1211        let msg = err.to_string();
1212        assert!(
1213            msg.contains("unknown field"),
1214            "expected 'unknown field' in error, got: {msg}"
1215        );
1216    }
1217
1218    // ── daemon/search (verivus-oss/sqry#238 Tier 2) ─────────────────
1219
1220    #[test]
1221    fn search_request_roundtrip_minimal() {
1222        let req = SearchRequest {
1223            envelope_version: ENVELOPE_VERSION,
1224            pattern: "foo".into(),
1225            search_path: "/tmp/ws".into(),
1226            mode: SearchMode::Exact,
1227            kind: None,
1228            lang: None,
1229            limit: None,
1230            include_generated: true,
1231            revision: None,
1232        };
1233        let wire = serde_json::to_string(&req).expect("serialize");
1234        let back: SearchRequest = serde_json::from_str(&wire).expect("deserialize");
1235        assert_eq!(back, req);
1236    }
1237
1238    #[test]
1239    fn search_request_roundtrip_with_all_filters() {
1240        let req = SearchRequest {
1241            envelope_version: ENVELOPE_VERSION,
1242            pattern: "test_.*".into(),
1243            search_path: "/srv/repo".into(),
1244            mode: SearchMode::Regex,
1245            kind: Some("function".into()),
1246            lang: Some("rust".into()),
1247            limit: Some(50),
1248            include_generated: false,
1249            revision: None,
1250        };
1251        let wire = serde_json::to_string(&req).expect("serialize");
1252        let back: SearchRequest = serde_json::from_str(&wire).expect("deserialize");
1253        assert_eq!(back, req);
1254    }
1255
1256    #[test]
1257    fn search_request_mode_lowercase_on_wire() {
1258        let req = SearchRequest {
1259            envelope_version: ENVELOPE_VERSION,
1260            pattern: "f".into(),
1261            search_path: ".".into(),
1262            mode: SearchMode::Fuzzy,
1263            kind: None,
1264            lang: None,
1265            limit: None,
1266            include_generated: true,
1267            revision: None,
1268        };
1269        let wire = serde_json::to_string(&req).expect("serialize");
1270        // The `#[serde(rename_all = "lowercase")]` attribute on SearchMode
1271        // must surface the variant as `"fuzzy"`, not `"Fuzzy"`.
1272        assert!(
1273            wire.contains(r#""mode":"fuzzy""#),
1274            "expected mode=fuzzy lowercase; got: {wire}"
1275        );
1276    }
1277
1278    #[test]
1279    fn search_request_rejects_unknown_field() {
1280        let wire =
1281            r#"{"envelope_version":1,"pattern":"f","search_path":"/","mode":"exact","bogus":true}"#;
1282        let err = serde_json::from_str::<SearchRequest>(wire)
1283            .expect_err("SearchRequest must reject unknown fields");
1284        assert!(
1285            err.to_string().contains("unknown field"),
1286            "expected unknown-field error, got: {err}"
1287        );
1288    }
1289
1290    #[test]
1291    fn search_request_include_generated_defaults_when_absent() {
1292        // Forward-compat: a request body that predates the
1293        // `include_generated` wire field deserialises to the legacy
1294        // "no filter" behaviour (`true`), preserving the
1295        // `DAEMON_SEARCH_HANDLER` unit's approved tests after the
1296        // Codex round-1 CLI shim review fix.
1297        let wire = r#"{"pattern":"f","search_path":"/","mode":"exact"}"#;
1298        let req: SearchRequest =
1299            serde_json::from_str(wire).expect("deserialize w/o include_generated");
1300        assert!(req.include_generated);
1301        assert_eq!(req.revision, None);
1302    }
1303
1304    #[test]
1305    fn search_request_include_generated_round_trips_when_false() {
1306        let wire = r#"{"pattern":"f","search_path":"/","mode":"exact","include_generated":false}"#;
1307        let req: SearchRequest =
1308            serde_json::from_str(wire).expect("deserialize include_generated=false");
1309        assert!(!req.include_generated);
1310        // Re-serialise and confirm the field is preserved.
1311        let back = serde_json::to_string(&req).expect("serialize");
1312        assert!(
1313            back.contains(r#""include_generated":false"#),
1314            "include_generated=false must survive a round-trip: {back}"
1315        );
1316    }
1317
1318    #[test]
1319    fn search_request_envelope_version_defaults_when_absent() {
1320        // Forward-compat: older clients can omit `envelope_version` and
1321        // the daemon defaults it to ENVELOPE_VERSION.
1322        let wire = r#"{"pattern":"f","search_path":"/","mode":"exact"}"#;
1323        let req: SearchRequest =
1324            serde_json::from_str(wire).expect("deserialize w/o envelope_version");
1325        assert_eq!(req.envelope_version, ENVELOPE_VERSION);
1326    }
1327
1328    #[test]
1329    fn search_result_roundtrip_empty() {
1330        let result = SearchResult {
1331            items: vec![],
1332            total: 0,
1333            truncated: false,
1334            cursor: None,
1335            revision: None,
1336        };
1337        let wire = serde_json::to_string(&result).expect("serialize");
1338        assert!(
1339            !wire.contains("\"revision\""),
1340            "legacy live-workspace search result must omit revision metadata: {wire}"
1341        );
1342        let back: SearchResult = serde_json::from_str(&wire).expect("deserialize");
1343        assert_eq!(back, result);
1344    }
1345
1346    #[test]
1347    fn search_request_revision_target_round_trips_when_present() {
1348        let req = SearchRequest {
1349            envelope_version: ENVELOPE_VERSION,
1350            pattern: "foo".into(),
1351            search_path: "/tmp/ws".into(),
1352            mode: SearchMode::Exact,
1353            kind: None,
1354            lang: None,
1355            limit: None,
1356            include_generated: true,
1357            revision: Some(crate::revision::RevisionQueryTarget::RevisionId {
1358                revision_id: crate::revision::RevisionId("rev-1".to_owned()),
1359            }),
1360        };
1361        let wire = serde_json::to_string(&req).expect("serialize");
1362        assert!(wire.contains(r#""revision""#));
1363        let back: SearchRequest = serde_json::from_str(&wire).expect("deserialize");
1364        assert_eq!(back, req);
1365    }
1366
1367    #[test]
1368    fn search_result_roundtrip_single_hit() {
1369        let result = SearchResult {
1370            items: vec![SearchItem {
1371                name: "start_kernel".into(),
1372                qualified_name: "kernel::start_kernel".into(),
1373                kind: "function".into(),
1374                language: "c".into(),
1375                file_path: "/linux/init/main.c".into(),
1376                start_line: 985,
1377                start_column: 0,
1378                end_line: 1100,
1379                end_column: 1,
1380                score: None,
1381            }],
1382            total: 1,
1383            truncated: false,
1384            cursor: None,
1385            revision: None,
1386        };
1387        let wire = serde_json::to_string(&result).expect("serialize");
1388        let back: SearchResult = serde_json::from_str(&wire).expect("deserialize");
1389        assert_eq!(back, result);
1390    }
1391
1392    #[test]
1393    fn search_result_roundtrip_truncated_with_score() {
1394        let result = SearchResult {
1395            items: (0..3)
1396                .map(|i| SearchItem {
1397                    name: format!("hit_{i}"),
1398                    qualified_name: format!("crate::hit_{i}"),
1399                    kind: "function".into(),
1400                    language: "rust".into(),
1401                    file_path: "/repo/src/lib.rs".into(),
1402                    start_line: 10 + i,
1403                    start_column: 0,
1404                    end_line: 12 + i,
1405                    end_column: 1,
1406                    score: Some(0.5_f32 + (i as f32) * 0.1),
1407                })
1408                .collect(),
1409            total: 101,
1410            truncated: true,
1411            cursor: None,
1412            revision: None,
1413        };
1414        let wire = serde_json::to_string(&result).expect("serialize");
1415        let back: SearchResult = serde_json::from_str(&wire).expect("deserialize");
1416        assert_eq!(back, result);
1417    }
1418
1419    #[test]
1420    fn search_item_rejects_unknown_field() {
1421        let wire = r#"{"name":"f","qualified_name":"f","kind":"function","language":"rust","file_path":"/","start_line":1,"start_column":0,"end_line":1,"end_column":0,"bogus":1}"#;
1422        let err = serde_json::from_str::<SearchItem>(wire)
1423            .expect_err("SearchItem must reject unknown fields");
1424        assert!(err.to_string().contains("unknown field"));
1425    }
1426
1427    #[test]
1428    fn search_result_rejects_unknown_field() {
1429        let wire = r#"{"items":[],"total":0,"truncated":false,"bogus":1}"#;
1430        let err = serde_json::from_str::<SearchResult>(wire)
1431            .expect_err("SearchResult must reject unknown fields");
1432        assert!(err.to_string().contains("unknown field"));
1433    }
1434
1435    #[test]
1436    fn search_result_score_omitted_when_none() {
1437        // `skip_serializing_if = "Option::is_none"` on `score` keeps the
1438        // wire compact for regex/exact hits where no score is meaningful.
1439        let item = SearchItem {
1440            name: "f".into(),
1441            qualified_name: "f".into(),
1442            kind: "function".into(),
1443            language: "rust".into(),
1444            file_path: "/".into(),
1445            start_line: 1,
1446            start_column: 0,
1447            end_line: 1,
1448            end_column: 0,
1449            score: None,
1450        };
1451        let wire = serde_json::to_string(&item).expect("serialize");
1452        assert!(
1453            !wire.contains("\"score\""),
1454            "score must be omitted when None; got: {wire}"
1455        );
1456    }
1457
1458    #[test]
1459    fn search_result_envelope_wraps_payload() {
1460        // SearchResult is intended to ride inside ResponseEnvelope<T>, just
1461        // like LoadResult / RebuildResult. Verify the wrap.
1462        let envelope = ResponseEnvelope {
1463            result: SearchResult {
1464                items: vec![],
1465                total: 0,
1466                truncated: false,
1467                cursor: None,
1468                revision: None,
1469            },
1470            meta: ResponseMeta::management("test"),
1471        };
1472        let wire = serde_json::to_string(&envelope).expect("serialize");
1473        let back: ResponseEnvelope<SearchResult> =
1474            serde_json::from_str(&wire).expect("deserialize");
1475        assert_eq!(back.result, envelope.result);
1476    }
1477}