wenlan-types 0.14.1

Shared wire-format types for Wenlan, the local-first personal agent memory system.
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// SPDX-License-Identifier: Apache-2.0
//! API request types for all HTTP endpoints.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ===== Memory CRUD =====

#[derive(Debug, Serialize, Deserialize)]
pub struct StoreMemoryRequest {
    pub content: String,
    #[serde(default)]
    pub memory_type: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
    #[serde(default)]
    pub source_agent: Option<String>,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub confidence: Option<f32>,
    #[serde(default)]
    pub supersedes: Option<String>,
    /// Entity name for resolution (e.g. "Alice", "PostgreSQL")
    #[serde(default)]
    pub entity: Option<String>,
    /// Direct entity ID (bypasses name resolution)
    #[serde(default)]
    pub entity_id: Option<String>,
    #[serde(default)]
    pub structured_fields: Option<serde_json::Value>,
    #[serde(default)]
    pub retrieval_cue: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SearchMemoryRequest {
    pub query: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
    #[serde(default)]
    pub memory_type: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
    #[serde(default)]
    pub source_agent: Option<String>,
    /// When `true` AND the daemon has a reranker wired (via
    /// `WENLAN_RERANKER_ENABLED=1`), results pass through a cross-encoder
    /// reranker after the embedding+FTS hybrid step. When `true` but no
    /// reranker is available, the daemon logs a warning and falls back to
    /// the plain hybrid ordering. Default `false` to preserve current
    /// behavior for callers that don't opt in.
    #[serde(default)]
    pub rerank: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ListMemoriesRequest {
    #[serde(default)]
    pub memory_type: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
    #[serde(default = "default_list_limit")]
    pub limit: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirmed: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConfirmRequest {
    #[serde(default = "default_confirmed")]
    pub confirmed: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ReclassifyMemoryRequest {
    pub memory_type: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ImportMemoriesRequest {
    pub source: String,
    pub content: String,
    #[serde(default)]
    pub label: Option<String>,
}

// ===== General search/context =====

#[derive(Debug, Serialize, Deserialize)]
pub struct SearchRequest {
    pub query: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
    pub source_filter: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
}

#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct ContextRequest {
    pub current_file: String,
    pub cursor_prefix: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ChatContextRequest {
    #[serde(default)]
    pub query: Option<String>,
    #[serde(default)]
    pub conversation_id: Option<String>,
    #[serde(default = "default_max_chunks")]
    pub max_chunks: usize,
    #[serde(default)]
    pub relevance_threshold: Option<f64>,
    /// Deprecated: goal-typed memories were folded into identity by migration 45
    /// (Phase 0). Daemon ignores this field — no goal-load path exists anymore.
    /// Field stays for wire backward compat; will be removed in 0.4.
    #[deprecated(
        since = "0.3.2",
        note = "Goal taxonomy folded into Identity by migration 45 (Phase 0). \
                Daemon ignores this field. Will be removed in 0.4."
    )]
    #[serde(default = "default_true")]
    pub include_goals: bool,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
}

// ===== Knowledge graph =====

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateEntityRequest {
    pub name: String,
    pub entity_type: String,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
    #[serde(default)]
    pub source_agent: Option<String>,
    #[serde(default)]
    pub confidence: Option<f32>,
}

#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateRelationRequest {
    pub from_entity: String,
    pub to_entity: String,
    pub relation_type: String,
    #[serde(default)]
    pub source_agent: Option<String>,
    #[serde(default)]
    pub confidence: Option<f64>,
    #[serde(default)]
    pub explanation: Option<String>,
    #[serde(default)]
    pub source_memory_id: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AddObservationRequest {
    pub entity_id: String,
    pub content: String,
    #[serde(default)]
    pub source_agent: Option<String>,
    #[serde(default)]
    pub confidence: Option<f32>,
}

#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct LinkEntityRequest {
    pub source_id: String,
    pub entity_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ListEntitiesRequest {
    #[serde(default)]
    pub entity_type: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SearchEntitiesRequest {
    pub query: String,
    #[serde(default = "default_entity_search_limit")]
    pub limit: usize,
}

// ===== Profile & Agents =====

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateProfileRequest {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub display_name: Option<String>,
    #[serde(default)]
    pub email: Option<String>,
    #[serde(default)]
    pub bio: Option<String>,
    #[serde(default)]
    pub avatar_path: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateAgentRequest {
    #[serde(default)]
    pub agent_type: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub trust_level: Option<String>,
    /// Empty string clears the field; None leaves it unchanged.
    #[serde(default)]
    pub display_name: Option<String>,
}

// ===== Spaces =====

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateSpaceRequest {
    pub name: String,
    pub description: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateSpaceRequest {
    pub new_name: Option<String>,
    pub description: Option<String>,
}

// ===== Concepts =====

#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateConceptRequest {
    pub title: String,
    pub content: String,
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub entity_id: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
    #[serde(default)]
    pub source_memory_ids: Vec<String>,
    #[serde(default)]
    pub creation_kind: Option<String>,
    /// Dedicated workspace axis (P3). When Some, persisted to `pages.workspace`.
    /// Distinct from `space` (category column used for page_type filtering).
    #[serde(default)]
    pub workspace: Option<String>,
}

/// First durable snapshot for a human-authored Page draft.
///
/// The client only sends this request once either `title` or `content` is
/// meaningful. Both fields default to empty so title-first and body-first
/// writing flows share one wire shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreatePageDraftRequest {
    /// Stable client-generated id used to make an ambiguous create retry safe.
    pub draft_id: String,
    pub title: String,
    pub content: String,
    pub space: Option<String>,
    space_provided: bool,
}

impl CreatePageDraftRequest {
    /// Build a request with an explicit `space` value.
    ///
    /// Passing `None` serializes as `"space": null`.
    pub fn new(draft_id: String, title: String, content: String, space: Option<String>) -> Self {
        Self {
            draft_id,
            title,
            content,
            space,
            space_provided: true,
        }
    }

    /// Build a request that omits `space`, allowing the server to inherit the
    /// `X-Wenlan-Space` request header.
    pub fn new_inheriting_header_space(draft_id: String, title: String, content: String) -> Self {
        Self {
            draft_id,
            title,
            content,
            space: None,
            space_provided: false,
        }
    }

    /// Whether the JSON body contained a `space` key.
    ///
    /// This distinguishes an omitted key (inherit the request header) from an
    /// explicit `null` (clear the header-provided Space).
    pub fn space_was_provided(&self) -> bool {
        self.space_provided
    }
}

impl Serialize for CreatePageDraftRequest {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        let field_count = if self.space_provided { 4 } else { 3 };
        let mut state = serializer.serialize_struct("CreatePageDraftRequest", field_count)?;
        state.serialize_field("draft_id", &self.draft_id)?;
        state.serialize_field("title", &self.title)?;
        state.serialize_field("content", &self.content)?;
        if self.space_provided {
            state.serialize_field("space", &self.space)?;
        }
        state.end()
    }
}

impl<'de> Deserialize<'de> for CreatePageDraftRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            draft_id: String,
            #[serde(default)]
            title: String,
            #[serde(default)]
            content: String,
            #[serde(default, deserialize_with = "double_option")]
            space: Option<Option<String>>,
        }

        let wire = Wire::deserialize(deserializer)?;
        let (space_provided, space) = match wire.space {
            Some(space) => (true, space),
            None => (false, None),
        };
        Ok(Self {
            draft_id: wire.draft_id,
            title: wire.title,
            content: wire.content,
            space,
            space_provided,
        })
    }
}

/// Complete replacement snapshot for an existing Page draft.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct UpdatePageDraftRequest {
    pub expected_version: i64,
    pub title: String,
    pub content: String,
    pub space: Option<String>,
}

impl<'de> Deserialize<'de> for UpdatePageDraftRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            expected_version: i64,
            title: String,
            content: String,
            #[serde(default, deserialize_with = "double_option")]
            space: Option<Option<String>>,
        }

        let wire = Wire::deserialize(deserializer)?;
        let space = wire
            .space
            .ok_or_else(|| serde::de::Error::missing_field("space"))?;
        Ok(Self {
            expected_version: wire.expected_version,
            title: wire.title,
            content: wire.content,
            space,
        })
    }
}

/// Optimistic-concurrency body shared by draft publish and discard.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PageDraftVersionRequest {
    pub expected_version: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum AcceptRefinementRequest {
    Accept {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        notes: Option<String>,
    },
    PickSpace {
        space: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        notes: Option<String>,
    },
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SearchPagesRequest {
    pub query: String,
    #[serde(default)]
    pub limit: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space: Option<String>,
}

// ===== Ingest =====

#[derive(Debug, Serialize, Deserialize)]
pub struct IngestTextRequest {
    pub source: String,
    pub source_id: String,
    pub title: String,
    pub content: String,
    pub url: Option<String>,
    pub metadata: Option<HashMap<String, String>>,
}

#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct IngestWebpageRequest {
    pub url: String,
    pub title: String,
    pub content: String,
    pub metadata: Option<HashMap<String, String>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct IngestMemoryRequest {
    pub source: String,
    pub source_id: String,
    pub title: String,
    pub content: String,
    pub url: Option<String>,
    pub tags: Option<Vec<String>>,
    pub metadata: Option<HashMap<String, String>>,
}

// ===== Sources =====

#[doc(hidden)]
#[derive(Debug, Serialize, Deserialize)]
pub struct AddSourceRequest {
    pub source_type: String,
    /// Filesystem path as a string. Kept as `String` (not `PathBuf`) because
    /// this is an HTTP wire format — the handler converts it to `PathBuf`.
    pub path: String,
}

// ===== Config =====

/// Distinguishes an omitted JSON field (outer None) from an explicit `null`
/// (Some(None)). Used for presence-sensitive wire fields.
fn double_option<'de, T, D>(de: D) -> Result<Option<Option<T>>, D::Error>
where
    T: serde::Deserialize<'de>,
    D: serde::Deserializer<'de>,
{
    serde::Deserialize::deserialize(de).map(Some)
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateConfigRequest {
    #[serde(default)]
    pub skip_apps: Option<Vec<String>>,
    #[serde(default)]
    pub skip_title_patterns: Option<Vec<String>>,
    #[serde(default)]
    pub private_browsing_detection: Option<bool>,
    #[serde(default)]
    pub setup_completed: Option<bool>,
    #[serde(default)]
    pub clipboard_enabled: Option<bool>,
    #[serde(default)]
    pub screen_capture_enabled: Option<bool>,
    #[serde(default)]
    pub remote_access_enabled: Option<bool>,
    /// Anthropic model used for fast/routine tasks (e.g. classification, tagging).
    #[serde(default)]
    pub routine_model: Option<String>,
    /// Anthropic model used for synthesis tasks (e.g. distillation, narrative).
    #[serde(default)]
    pub synthesis_model: Option<String>,
    /// Base URL for an OpenAI-compatible external LLM endpoint.
    #[serde(default)]
    pub external_llm_endpoint: Option<String>,
    /// Model identifier to use with the external LLM endpoint.
    #[serde(default)]
    pub external_llm_model: Option<String>,
    /// API key for the external endpoint. Tri-state: omitted = preserve stored
    /// key; `null` or `""` = clear; non-empty = replace. Never echoed back.
    #[serde(
        default,
        deserialize_with = "double_option",
        skip_serializing_if = "Option::is_none"
    )]
    pub external_llm_api_key: Option<Option<String>>,
    /// Per-job source pin for everyday work: `"anthropic"` | `"external"` |
    /// `"on_device"`. Omitted = preserve; `""` = clear; other values are
    /// validated by the config route.
    #[serde(default)]
    pub everyday_source: Option<String>,
    /// Per-job source pin for synthesis: `"anthropic"` | `"external"`
    /// (`"on_device"` only when the compile gate is set). Omitted = preserve;
    /// `""` = clear; validated by the config route.
    #[serde(default)]
    pub synthesis_source: Option<String>,
    /// Gates the proactive Page-Map suggestion phase in the scheduler. Omitted =
    /// preserve stored value; present = set. Never gates the explicit improve route.
    #[serde(default)]
    pub page_map_auto_suggest: Option<bool>,
}

// ===== Chunks / indexed files =====

#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteByTimeRangeRequest {
    pub start: i64,
    pub end: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BulkDeleteItem {
    pub source: String,
    pub source_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BulkDeleteRequest {
    pub items: Vec<BulkDeleteItem>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateChunkRequest {
    pub content: String,
}

// ===== Entity / Observation CRUD =====

#[derive(Debug, Serialize, Deserialize)]
pub struct ConfirmEntityRequest {
    #[serde(default = "default_confirmed")]
    pub confirmed: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AddEntityObservationRequest {
    pub content: String,
    #[serde(default)]
    pub source_agent: Option<String>,
    #[serde(default)]
    pub confidence: Option<f32>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateObservationRequest {
    pub content: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConfirmObservationRequest {
    #[serde(default = "default_confirmed")]
    pub confirmed: bool,
}

// ===== Spaces extended =====

#[derive(Debug, Serialize, Deserialize)]
pub struct ReorderSpaceRequest {
    pub name: String,
    pub new_order: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SetDocumentSpaceRequest {
    pub space_name: String,
}

// ===== Tags =====

#[derive(Debug, Serialize, Deserialize)]
pub struct SetDocumentTagsRequest {
    #[serde(default)]
    pub source: Option<String>,
    pub tags: Vec<String>,
}

// ===== Memory update =====

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateMemoryRequest {
    #[serde(default)]
    pub content: Option<String>,
    #[serde(default, alias = "domain")]
    pub space: Option<String>,
    #[serde(default)]
    pub confirmed: Option<bool>,
    #[serde(default)]
    pub memory_type: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SetStabilityRequest {
    pub stability: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CorrectMemoryRequest {
    pub correction_prompt: String,
}

// ===== Concepts update =====

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdatePageRequest {
    pub content: String,
    /// Source memory IDs to associate with this page version.
    /// Omitted or empty by HTTP callers that preserve existing sources;
    /// always populated by `post_write::update_page`.
    #[serde(default)]
    pub source_memory_ids: Vec<String>,
    /// Optimistic-concurrency guard for the M0 write gate. `Some(v)` lands the
    /// write only while the stored page is still at version `v`; a mismatch is
    /// refused instead of overwriting whatever landed in between.
    ///
    /// Omitted by legacy clients, in which case the server guards on the version
    /// it loaded to make the ownership decision — so the decision and the write
    /// always describe the same row.
    #[serde(default)]
    pub expected_version: Option<i64>,
    /// Retry identity. Sent together, `caller_id` and `operation_id` make the
    /// write replayable: the same pair with the same request replays the
    /// stored response instead of writing again, and the same pair with a
    /// different request is a conflict. This is what turns "the response was
    /// lost, the client retried" into a no-op rather than a second version.
    ///
    /// Either one alone is ignored — an operation id is only meaningful
    /// within the caller that minted it.
    #[serde(default)]
    pub caller_id: Option<String>,
    #[serde(default)]
    pub operation_id: Option<String>,
}

/// Body for `PUT /api/pages/{id}` — agent-side refresh of a stale page.
///
/// Distinct from `UpdatePageRequest` (manual content edit via POST) because:
///  - `source_memory_ids` is replaced, not preserved.
///  - `summary` is optionally updated.
///  - The handler clears `stale_reason` in the same transaction.
///
/// v1 deliberately excludes title / entity_id / space changes — slug rename
/// has its own concurrent-read failure mode and lands as a separate route.
#[derive(Debug, Serialize, Deserialize)]
pub struct RefreshPageRequest {
    pub content: String,
    pub source_memory_ids: Vec<String>,
    #[serde(default)]
    pub summary: Option<String>,
}

// ===== Concept Export =====

/// Request body for `POST /api/pages/export` (bulk export all pages to an Obsidian vault).
#[derive(Debug, Deserialize, Serialize)]
pub struct ExportPagesRequest {
    pub vault_path: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ExportPageRequest {
    pub vault_path: String,
}

// ===== LLM test =====

/// `POST /api/llm/test` — probe an OpenAI-compatible LLM endpoint with a 1-shot prompt.
/// Used by the app settings UI to validate a custom endpoint before saving.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestLlmRequest {
    pub endpoint: String,
    pub model: String,
    /// Optional override prompt. Defaults to "Say 'hello' and nothing else." server-side.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    /// Optional bearer key for this probe only — not persisted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestLlmResponse {
    pub response: String,
}

// ===== On-device model =====

/// Body for `POST /api/on-device-model/download`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnDeviceModelRequest {
    pub model_id: String,
}

// ===== Default value functions =====

fn default_limit() -> usize {
    10
}

fn default_list_limit() -> usize {
    100
}

fn default_confirmed() -> bool {
    true
}

fn default_max_chunks() -> usize {
    5
}

fn default_true() -> bool {
    true
}

fn default_entity_search_limit() -> usize {
    20
}

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

    #[test]
    fn search_pages_request_accepts_page_type() {
        let json = r#"{"query":"foo","limit":10,"page_type":"recap"}"#;
        let parsed: SearchPagesRequest = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.page_type.as_deref(), Some("recap"));
    }

    #[test]
    fn search_pages_request_page_type_optional() {
        let json = r#"{"query":"foo","limit":10}"#;
        let parsed: SearchPagesRequest = serde_json::from_str(json).unwrap();
        assert!(parsed.page_type.is_none());
    }

    #[test]
    fn search_pages_request_accepts_optional_space() {
        let json = r#"{"query":"foo","space":"work"}"#;
        let parsed: SearchPagesRequest = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.space.as_deref(), Some("work"));

        let omitted: SearchPagesRequest = serde_json::from_str(r#"{"query":"foo"}"#).unwrap();
        assert!(omitted.space.is_none());
    }
}

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

    #[test]
    fn confirmed_false_serializes_to_json() {
        let req = ListMemoriesRequest {
            memory_type: None,
            space: None,
            limit: 20,
            confirmed: Some(false),
        };
        let s = serde_json::to_string(&req).unwrap();
        assert!(s.contains("\"confirmed\":false"), "got: {s}");
    }

    #[test]
    fn confirmed_none_skips_serialization() {
        let req = ListMemoriesRequest {
            memory_type: None,
            space: None,
            limit: 20,
            confirmed: None,
        };
        let s = serde_json::to_string(&req).unwrap();
        assert!(!s.contains("confirmed"), "got: {s}");
    }
}

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

    #[test]
    fn set_document_tags_request_accepts_optional_source() {
        let req: SetDocumentTagsRequest =
            serde_json::from_str(r#"{"source":"manual","tags":["rust"]}"#).unwrap();

        assert_eq!(req.source.as_deref(), Some("manual"));
        assert_eq!(req.tags, vec!["rust"]);
    }

    #[test]
    fn set_document_tags_request_defaults_source_for_old_payloads() {
        let req: SetDocumentTagsRequest = serde_json::from_str(r#"{"tags":["rust"]}"#).unwrap();

        assert!(req.source.is_none());
        assert_eq!(req.tags, vec!["rust"]);
    }
}

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

    #[test]
    fn on_device_model_request_round_trips_model_id() {
        let req: OnDeviceModelRequest = serde_json::from_str(r#"{"model_id":"qwen3-4b"}"#).unwrap();

        assert_eq!(req.model_id, "qwen3-4b");
        assert_eq!(
            serde_json::to_string(&req).unwrap(),
            r#"{"model_id":"qwen3-4b"}"#
        );
    }
}

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

    #[test]
    fn update_config_request_external_key_tristate() {
        let r: UpdateConfigRequest = serde_json::from_str("{}").unwrap();
        assert_eq!(r.external_llm_api_key, None); // omitted
        let r: UpdateConfigRequest =
            serde_json::from_str(r#"{"external_llm_api_key":null}"#).unwrap();
        assert_eq!(r.external_llm_api_key, Some(None)); // explicit null
        let r: UpdateConfigRequest =
            serde_json::from_str(r#"{"external_llm_api_key":"sk-x"}"#).unwrap();
        assert_eq!(r.external_llm_api_key, Some(Some("sk-x".to_string())));
    }

    #[test]
    fn test_llm_request_api_key_optional() {
        let r: TestLlmRequest =
            serde_json::from_str(r#"{"endpoint":"http://x","model":"m"}"#).unwrap();
        assert!(r.api_key.is_none());
    }
}