hallouminate-daemon 0.6.1

Daemon layer for hallouminate.
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
//! IPC types shared between the daemon server and its CLI/MCP clients.
//!
//! Wire format is JSON-lines over a Unix domain socket: one request,
//! one response, then the connection closes. Keeps server-side dispatch
//! trivially correct around per-corpus locks and the global write-lane
//! semaphore without needing an in-band correlation id.
//!
//! # Wire compatibility (v1)
//!
//! The daemon and every client (CLI, MCP) ship from the *same* `hallouminate`
//! binary. The response payloads in this module embed domain types
//! ([`IndexReport`], [`GroundResponse`], [`FileEntry`]) wholesale and carry
//! **no protocol version envelope** and no `#[serde(deny_unknown_fields)]`
//! — a single binary owns both sides of the socket, so a field added to a
//! domain type lands on both sides in the same release. **Cross-version IPC
//! (a client from one release talking to a daemon from another) is not a
//! supported configuration in v1.** If a future contributor wants to ship a
//! standalone client (e.g. a third-party Python client, an out-of-process
//! agent) they must first add an explicit `version: u32` to the request /
//! response envelopes and a negotiation handshake; do not assume the
//! current shape is forward-compatible by accident.

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::report::IndexReport;
use hallouminate_domain::corpus::{FileEntry, TreeNode};
use hallouminate_domain::ground::GroundResponse;

pub use hallouminate_domain::corpus::{LineRange, Position};

/// Top-level request envelope. Carries a `cwd: PathBuf` plus a
/// [`DaemonRequestPayload`] discriminating one of the request variants.
///
/// `cwd` is the client's working directory at request time — the daemon
/// walks it on every request to discover the active repo-layer config
/// (`.hallouminate/config.toml`) and merge it with the boot baseline. See
/// `.cheese/specs/repo-config-discovery.md`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DaemonRequest {
    pub cwd: PathBuf,
    pub payload: DaemonRequestPayload,
}

/// The discriminated request body. One variant per CLI/MCP operation the
/// daemon owns. Stateless operations (`Ping`, `ListCorpora`, `ListFiles`,
/// `ReadMarkdown`, `Ground`) skip the write lane; mutating operations
/// (`Index`, `AddMarkdown`, `DeleteMarkdown`) take the corpus lock and the
/// write-lane permit in that order.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum DaemonRequestPayload {
    /// Liveness check; the server responds with `Pong`.
    Ping,
    /// `ground` semantic search.
    Ground(GroundRequest),
    /// `index` corpus rebuild.
    Index(IndexRequest),
    /// List configured corpora (explicit + repository-derived).
    ListCorpora,
    /// List files visible in a corpus.
    ListFiles(ListFilesRequest),
    /// List files visible in a corpus, grouped into a directory tree.
    ListTree(ListTreeRequest),
    /// Write a markdown file to a corpus root and refresh its index rows.
    AddMarkdown(AddMarkdownRequest),
    /// Read verbatim markdown content from a corpus root.
    ReadMarkdown(ReadMarkdownRequest),
    /// Unlink a markdown file from a corpus root and prune its index rows.
    DeleteMarkdown(DeleteMarkdownRequest),
    /// Find every page in a corpus that links to a given page via a
    /// `[[wikilink]]`.
    Backlinks(BacklinksRequest),
    /// Read-only index health summary for a corpus: file counts, chunk count,
    /// newest index timestamp, and unindexed-file count.
    CorpusStats { corpus: Option<String> },
    /// Daemon self-status: per-task heartbeat state, maintenance debt
    /// level, deferral count, watcher counters, and the last ladder trip.
    /// Stubbed to a default/empty [`StatusReport`] until curd 9 wires the
    /// real daemon-internal sources (status.rs).
    Status,
    /// Ask the daemon to shut down gracefully: cancel the accept loop, drop
    /// the flock guard, and remove the socket file. The server acks with
    /// `"stopping"` before tearing down.
    Shutdown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroundRequest {
    pub query: String,
    pub corpus: Option<String>,
    pub top_files: Option<usize>,
    pub chunks_per_file: Option<usize>,
    pub limit: Option<usize>,
    pub snippet_chars: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexRequest {
    pub corpus: Option<String>,
    pub paths_from: Option<PathBuf>,
    /// Fail the whole run if any selected corpus root is missing, instead of
    /// the default skip-with-warning. Defaults to `false` so older clients
    /// that omit the field keep the lenient behavior.
    #[serde(default)]
    pub strict: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListFilesRequest {
    pub corpus: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListTreeRequest {
    pub corpus: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AddMarkdownRequest {
    pub corpus: String,
    pub path: String,
    pub content: String,
    #[serde(default)]
    pub overwrite: bool,

    // ── edit-mode selectors (at most one may be Some/set; see decision D1) ──
    /// Section-splice mode: splice `content` under this heading's section.
    #[serde(default)]
    pub under_heading: Option<String>,
    /// Splice position within the section. Only meaningful with `under_heading`.
    #[serde(default)]
    pub position: Position,
    /// Line-range-replace mode: replace lines `[start, end]` (1-based, inclusive).
    #[serde(default)]
    pub replace_lines: Option<LineRange>,
    /// Text-match-replace mode: replace the unique literal occurrence of this
    /// substring.
    #[serde(default)]
    pub replace_match: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadMarkdownRequest {
    pub corpus: Option<String>,
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteMarkdownRequest {
    pub corpus: String,
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacklinksRequest {
    pub corpus: Option<String>,
    pub path: String,
}

/// Daemon response envelope. `Ok` carries an opaque JSON payload — each
/// request variant documents its own response shape. `Err` distinguishes
/// invalid-input failures (the MCP transport maps these to JSON-RPC -32602)
/// from internal faults (-32603).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum DaemonResponse {
    Ok { result: serde_json::Value },
    Err { kind: ErrorKind, message: String },
}

impl DaemonResponse {
    /// Wrap a serializable payload in an `Ok` response.
    ///
    /// On serialization failure the result is an [`Internal`](ErrorKind::Internal)
    /// error rather than a silent `Ok { result: Null }`: a `null` payload
    /// reads as an empty success across the CLI/MCP transport, so swallowing
    /// the error would mask the fault. The `Err` variant is a valid `Self`,
    /// so the signature is unchanged.
    pub fn ok<T: Serialize>(value: &T) -> Self {
        match serde_json::to_value(value) {
            Ok(result) => DaemonResponse::Ok { result },
            Err(e) => DaemonResponse::internal(format!("serialize response: {e}")),
        }
    }

    pub fn invalid_params(msg: impl Into<String>) -> Self {
        DaemonResponse::Err {
            kind: ErrorKind::InvalidParams,
            message: msg.into(),
        }
    }

    pub fn internal(msg: impl Into<String>) -> Self {
        DaemonResponse::Err {
            kind: ErrorKind::Internal,
            message: msg.into(),
        }
    }

    pub fn retryable(msg: impl Into<String>) -> Self {
        DaemonResponse::Err {
            kind: ErrorKind::Retryable,
            message: msg.into(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorKind {
    InvalidParams,
    Internal,
    /// The daemon refused or timed out without completing the operation from
    /// the caller's perspective (e.g. `DebtLevel::Hard`'s bounded wait
    /// expired, or a client-side RPC deadline fired) -- retry with backoff.
    /// A client-side timeout may leave the original attempt still running
    /// server-side, so retries must tolerate the first attempt having landed.
    Retryable,
}

// ── Response payload structs ───────────────────────────────────────────
//
// One per request variant. CLI / MCP clients deserialize the daemon's
// `Ok` payload into these typed shapes via `DaemonClient::call::<T>()`;
// dispatch.rs constructs them and serializes through `DaemonResponse::ok`.

/// `ListCorpora` payload entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CorpusEntry {
    pub name: String,
    pub paths: Vec<String>,
}

/// `Ground` payload. Carries both the rendered outline (matches the MCP
/// `ground` text content) and the full structured response so different
/// transports can pick the shape they need without paying for a second
/// search.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroundResult {
    pub outline: String,
    pub response: GroundResponse,
}

/// `AddMarkdown` payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddMarkdownResult {
    pub corpus: String,
    pub path: String,
    pub absolute_path: String,
    pub indexed: IndexReport,
    /// Non-blocking lint advisories for the written content (broken links,
    /// empty mermaid blocks, heading-level jumps). Omitted when empty so the
    /// common clean-write case carries no extra payload.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

/// `ReadMarkdown` payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadMarkdownResult {
    pub corpus: String,
    pub path: String,
    pub absolute_path: String,
    pub content: String,
    pub bytes: u64,
}

/// `DeleteMarkdown` payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteMarkdownResult {
    pub corpus: String,
    pub path: String,
    pub absolute_path: String,
    pub file_ref: String,
}

/// `Backlinks` payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacklinksResult {
    pub corpus: String,
    pub path: String,
    /// Corpus-relative paths of every page whose content links to `path` via
    /// a `[[wikilink]]`.
    pub backlinks: Vec<String>,
    /// Files that could not be read during the scan (permission change,
    /// deletion, transient I/O error). Non-empty means the scan is
    /// incomplete — the caller cannot treat an empty `backlinks` as "no
    /// backlinks" when warnings are present. Omitted when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

/// `CorpusStats` payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorpusStatsResult {
    pub corpus: String,
    pub indexed_files: u64,
    pub total_chunks: u64,
    pub last_indexed_ms: Option<i64>,
    pub unindexed_files: u64,
}

/// `Ping` reply payload (Curd C — cross-version daemon skew). Carries the
/// daemon binary's `CARGO_PKG_VERSION` so the MCP `serve` bootstrap can detect
/// version skew — a new client adopting a daemon spawned from an older release
/// — and self-heal by restarting the stale daemon. `flock` enforces one
/// daemon, not one version, so without this a fresh MCP server would silently
/// drive a mismatched daemon.
///
/// # Wire compatibility
///
/// A daemon from a release *before* this field existed answers `Ping` with the
/// bare string `"pong"`, which carries no `version`. Clients must treat a
/// missing or unparseable version as a mismatch (→ restart), never as a hard
/// error — see `bootstrap::ensure_daemon_running`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PongResult {
    pub version: String,
}

/// `ListFiles` payload alias — daemon emits an array of [`FileEntry`].
pub type ListFilesResult = Vec<FileEntry>;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListTreeResult {
    pub corpus: String,
    pub root: TreeNode,
}

/// `ListCorpora` payload alias — daemon emits an array of [`CorpusEntry`].
pub type ListCorporaResult = Vec<CorpusEntry>;

/// `Status` payload. Wire-side mirror of daemon-internal status types
/// (`heartbeat::{TaskName, TaskStatus}`, `debt::DebtLevel`,
/// `state::WatcherCounters`, `ladder::LadderTrip`/`LadderAction`) -- ipc.rs
/// does not depend on sibling daemon modules today (see module doc), so the
/// wire shape is mirrored here rather than referencing those types directly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusReport {
    pub per_task: Vec<TaskStatus>,
    pub debt: DebtLevel,
    pub defer_count: u32,
    pub watcher: WatcherCounters,
    pub trips: TripState,
}

/// One of the five long-lived daemon loops a watchdog can monitor. Mirrors
/// `heartbeat::TaskName`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskName {
    Maintenance,
    CatchUp,
    WatcherPump,
    IdleExit,
    Signal,
}

/// A task's heartbeat health. Mirrors `heartbeat::TaskStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskState {
    Alive,
    Stalled,
}

/// Per-task status entry within [`StatusReport::per_task`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskStatus {
    pub task: TaskName,
    pub state: TaskState,
}

/// Graduated maintenance debt level. Mirrors `debt::DebtLevel`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DebtLevel {
    Ok,
    Soft,
    Hard,
}

/// Watcher event/reindex counters. Mirrors `state::WatcherCounters`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WatcherCounters {
    pub events: u64,
    pub reindexes: u64,
    pub noop_reindexes: u64,
}

/// An escalating ladder action. Mirrors `ladder::LadderAction`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LadderAction {
    ForceMaintenance,
    RestartTask(TaskName),
    WatchdogTrip,
}

/// The daemon's last recorded ladder trip, if any. Mirrors
/// `state::LadderTrip` as an `Option`-shaped enum for a clean wire
/// representation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum TripState {
    None,
    Tripped { action: LadderAction, at_secs: u64 },
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A payload whose `Serialize` impl always fails, standing in for any
    /// domain type that errors mid-serialization (e.g. a map with non-string
    /// keys nested deep in a response).
    struct FailsToSerialize;

    impl Serialize for FailsToSerialize {
        fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom("boom"))
        }
    }

    #[test]
    fn ok_maps_serialize_failure_to_internal_error_not_null_success() {
        // WHY: a serialization failure that degrades to `Ok { result: Null }`
        // reads as an empty success on the CLI/MCP transport, hiding the
        // fault from the caller. It must surface as an Internal error.
        let resp = DaemonResponse::ok(&FailsToSerialize);
        match resp {
            DaemonResponse::Err { kind, message } => {
                assert_eq!(kind, ErrorKind::Internal);
                assert!(
                    message.starts_with("serialize response:"),
                    "message should name the serialize failure, got: {message:?}"
                );
            }
            DaemonResponse::Ok { result } => {
                panic!("serialize failure must not produce Ok, got result: {result:?}");
            }
        }
    }

    #[test]
    fn ok_wraps_serializable_payload_verbatim() {
        // WHY: the failure path must not regress the happy path — a value
        // that serializes cleanly still lands in `Ok { result }`.
        let resp = DaemonResponse::ok(&"pong");
        match resp {
            DaemonResponse::Ok { result } => {
                assert_eq!(result, serde_json::Value::String("pong".to_string()));
            }
            DaemonResponse::Err { kind, message } => {
                panic!("clean payload must serialize, got {kind:?}: {message}");
            }
        }
    }

    #[test]
    fn serialize_failure_response_is_err_envelope_on_the_wire() {
        // WHY: the defect is transport-level — a client deserializing the
        // response must see an error, not the old `{"status":"ok",
        // "result":null}` it would misread as empty success. Pin the wire
        // shape a remote client actually decodes, so a regression to the
        // null-success envelope is caught here.
        let wire = serde_json::to_value(DaemonResponse::ok(&FailsToSerialize))
            .expect("the Err envelope itself serializes cleanly");
        assert_eq!(wire["status"], "err");
        assert_eq!(wire["kind"], "internal");
        assert!(
            wire.get("result").is_none(),
            "an error envelope must not carry a `result` field, got: {wire}"
        );
        assert!(
            wire["message"]
                .as_str()
                .is_some_and(|m| m.starts_with("serialize response:")),
            "error message must name the serialize failure, got: {wire}"
        );
    }
}