gobby-wiki 0.8.0

Gobby wiki CLI shell
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
use std::fmt;
use std::path::{Path, PathBuf};

use gobby_core::ai_context::AiContext;
use gobby_core::config::AiRouting;

use crate::{exports, synthesis};

/// Parsed gwiki command passed in from the binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    Init {
        scope: ScopeSelection,
    },
    Setup {
        scope: ScopeSelection,
        options: SetupOptions,
    },
    Index {
        scope: ScopeSelection,
    },
    Collect {
        scope: ScopeSelection,
    },
    IngestFile {
        path: PathBuf,
        scope: ScopeSelection,
        options: IngestFileOptions,
    },
    IngestUrl {
        urls: Vec<String>,
        scope: ScopeSelection,
    },
    SyncSessions {
        scope: ScopeSelection,
        options: SyncSessionsOptions,
    },
    Refresh {
        scope: ScopeSelection,
        source_ids: Vec<String>,
        dry_run: bool,
    },
    Sources {
        scope: ScopeSelection,
    },
    RemoveSource {
        id: String,
        scope: ScopeSelection,
        dry_run: bool,
        keep_asset: bool,
    },
    Purge {
        scope: ScopeSelection,
        yes: bool,
    },
    Search {
        query: String,
        scope: ScopeSelection,
        limit: usize,
        include_semantic: bool,
        token_budget: Option<usize>,
    },
    Ask {
        query: String,
        scope: ScopeSelection,
        llm: bool,
        ai: AiRouting,
        require_ai: bool,
        token_budget: Option<usize>,
    },
    Read {
        target: ReadTarget,
        scope: ScopeSelection,
    },
    Backlinks {
        page: String,
        scope: ScopeSelection,
    },
    LinkSuggest {
        scope: ScopeSelection,
        limit: usize,
    },
    Benchmark {
        scope: ScopeSelection,
        options: BenchmarkOptions,
    },
    Compile {
        topic: Option<String>,
        outline: Vec<String>,
        source: Vec<String>,
        target_kind: synthesis::ArticleKind,
        target_page: Option<PathBuf>,
        write_intent: bool,
        ai: AiRouting,
        scope: ScopeSelection,
    },
    Export {
        scope: ScopeSelection,
        command: exports::ExportCommand,
    },
    Graph {
        scope: ScopeSelection,
    },
    GraphContext {
        scope: ScopeSelection,
    },
    ReviewReport {
        scope: ScopeSelection,
        options: ReviewReportOptions,
    },
    Audit {
        scope: ScopeSelection,
    },
    Lint {
        scope: ScopeSelection,
    },
    Normalize {
        scope: ScopeSelection,
        check: bool,
    },
    Health {
        scope: ScopeSelection,
    },
    Librarian {
        scope: ScopeSelection,
        ai: AiRouting,
    },
    Upkeep {
        scope: ScopeSelection,
        options: UpkeepOptions,
        ai: AiRouting,
    },
    Recap {
        scope: ScopeSelection,
        options: RecapOptions,
        ai: AiRouting,
    },
    Status {
        scope: ScopeSelection,
    },
    Trust {
        scope: ScopeSelection,
    },
    CitationQuality {
        scope: ScopeSelection,
    },
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RunOptions {
    pub quiet: bool,
}

/// Budgets and toggles for the `upkeep` conductor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UpkeepOptions {
    pub max_pages: usize,
    pub min_mentions: usize,
    pub max_sources_per_page: usize,
    pub dry_run: bool,
}

impl UpkeepOptions {
    pub const DEFAULT_MAX_PAGES: usize = crate::upkeep::DEFAULT_MAX_PAGES;
    pub const DEFAULT_MIN_MENTIONS: usize = crate::upkeep::DEFAULT_MIN_MENTIONS;
    pub const DEFAULT_MAX_SOURCES_PER_PAGE: usize = crate::upkeep::DEFAULT_MAX_SOURCES_PER_PAGE;
}

impl Default for UpkeepOptions {
    fn default() -> Self {
        Self {
            max_pages: Self::DEFAULT_MAX_PAGES,
            min_mentions: Self::DEFAULT_MIN_MENTIONS,
            max_sources_per_page: Self::DEFAULT_MAX_SOURCES_PER_PAGE,
            dry_run: false,
        }
    }
}

/// Options for the `recap` daily session page.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RecapOptions {
    /// Target day as `YYYY-MM-DD` (UTC attribution); `None` means today.
    pub date: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadTarget {
    Path(PathBuf),
    Title(String),
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SetupOptions {
    pub standalone: bool,
    pub database_url: Option<String>,
    pub no_services: bool,
    pub falkordb_host: Option<String>,
    pub falkordb_port: Option<u16>,
    pub falkordb_password: Option<String>,
    pub qdrant_url: Option<String>,
    pub embedding_provider: Option<String>,
    pub embedding_api_base: Option<String>,
    pub embedding_model: Option<String>,
    pub embedding_query_prefix: Option<String>,
    pub embedding_vector_dim: Option<usize>,
    pub embedding_api_key: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BenchmarkOptions {
    pub retrieval_candidates: usize,
}

impl BenchmarkOptions {
    pub const DEFAULT_RETRIEVAL_CANDIDATES: usize =
        crate::benchmark::DEFAULT_RETRIEVAL_PRECISION_CANDIDATES;
}

impl Default for BenchmarkOptions {
    fn default() -> Self {
        Self {
            retrieval_candidates: Self::DEFAULT_RETRIEVAL_CANDIDATES,
        }
    }
}

/// AI and media policy options for `ingest-file`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IngestFileOptions {
    pub no_ai: bool,
    pub translate: bool,
    pub target_lang: Option<String>,
    pub video_frame_interval_seconds: Option<u32>,
    pub transcription_routing: Option<AiRouting>,
    pub vision_routing: Option<AiRouting>,
    pub text_routing: Option<AiRouting>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncSessionsOptions {
    pub archive_dir: Option<PathBuf>,
    pub wiki_dir: Option<PathBuf>,
    pub limit: Option<usize>,
    pub raw: bool,
    /// Generate a daemon-equivalent summary for raw archives that have no daemon
    /// synthesis, instead of the structural skeleton. Degrades to skeleton when
    /// AI is unavailable.
    pub summarize: bool,
    /// Enrich daemon-synthesized session pages with connection links before write.
    pub enrich: bool,
}

impl Default for SyncSessionsOptions {
    fn default() -> Self {
        Self {
            archive_dir: None,
            wiki_dir: None,
            limit: None,
            raw: false,
            summarize: false,
            enrich: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewReportOptions {
    pub files: Vec<String>,
    pub symbols: Vec<String>,
    pub diff_path: Option<PathBuf>,
    pub output: String,
}

impl IngestFileOptions {
    pub fn apply_to_ai_context(&self, context: &mut AiContext) {
        if !self.no_ai {
            if let Some(routing) = self.transcription_routing {
                if self.translate {
                    context.bindings.audio_translate.routing = routing;
                } else {
                    context.bindings.audio_transcribe.routing = routing;
                }
            }
            if let Some(routing) = self.vision_routing {
                context.bindings.vision_extract.routing = routing;
            }
            if let Some(routing) = self.text_routing {
                context.bindings.text_generate.routing = routing;
            }
            if self.translate
                && let Some(target_lang) = &self.target_lang
            {
                context.bindings.audio_translate.target_lang = Some(target_lang.clone());
            }
            return;
        }

        context.bindings.embed.routing = AiRouting::Off;
        context.bindings.audio_transcribe.routing = AiRouting::Off;
        context.bindings.audio_translate.routing = AiRouting::Off;
        context.bindings.vision_extract.routing = AiRouting::Off;
        context.bindings.text_generate.routing = AiRouting::Off;
    }
}

/// Shared scope flags accepted by shell commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScopeSelection {
    Detect,
    ProjectRoot(PathBuf),
    Topic(String),
}

impl ScopeSelection {
    pub fn detect() -> Self {
        Self::Detect
    }

    pub fn project(root: impl Into<PathBuf>) -> Self {
        Self::ProjectRoot(root.into())
    }

    pub fn topic(topic: impl Into<String>) -> Self {
        Self::Topic(topic.into())
    }

    pub fn identity(&self) -> ScopeIdentity {
        match self {
            Self::Detect => ScopeIdentity::global(),
            Self::ProjectRoot(root) => ScopeIdentity::project(root.display().to_string()),
            Self::Topic(topic) => ScopeIdentity::topic(topic.clone()),
        }
    }

    pub fn is_project(&self) -> bool {
        matches!(self, Self::ProjectRoot(_))
    }

    pub fn project_root(&self) -> Option<&Path> {
        match self {
            Self::ProjectRoot(root) => Some(root.as_path()),
            Self::Detect | Self::Topic(_) => None,
        }
    }

    pub fn topic_name(&self) -> Option<&str> {
        match self {
            Self::Topic(topic) => Some(topic.as_str()),
            Self::Detect | Self::ProjectRoot(_) => None,
        }
    }
}

impl Default for ScopeSelection {
    fn default() -> Self {
        Self::detect()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ScopeKind {
    Global,
    Project,
    Topic,
}

impl ScopeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Global => "global",
            Self::Project => "project",
            Self::Topic => "topic",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScopeIdentity {
    pub kind: ScopeKind,
    pub id: String,
}

impl ScopeIdentity {
    pub fn global() -> Self {
        Self {
            kind: ScopeKind::Global,
            id: "default".to_string(),
        }
    }

    pub fn project(id: impl Into<String>) -> Self {
        Self {
            kind: ScopeKind::Project,
            id: id.into(),
        }
    }

    pub fn topic(id: impl Into<String>) -> Self {
        Self {
            kind: ScopeKind::Topic,
            id: id.into(),
        }
    }
}

impl fmt::Display for ScopeIdentity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.kind.as_str(), self.id)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CommandOutcome {
    pub status_messages: Vec<String>,
    pub result: CommandResult,
    pub exit_code: u8,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CommandResult {
    pub payload: serde_json::Value,
    pub text: String,
}

#[cfg(test)]
mod tests {
    use super::{IngestFileOptions, ScopeSelection};
    use gobby_core::ai_context::AiContext;
    use gobby_core::config::{AiRouting, EnvOnlySource};

    #[test]
    fn scope_selection_constructors_express_allowed_states() {
        let detect = ScopeSelection::detect();
        assert!(!detect.is_project());
        assert_eq!(detect.topic_name(), None);
        assert_eq!(ScopeSelection::default(), detect);
        assert_eq!(detect.identity(), crate::ScopeIdentity::global());

        let project = ScopeSelection::project("/repo");
        assert!(project.is_project());
        assert_eq!(project.topic_name(), None);
        assert_eq!(project.project_root(), Some(std::path::Path::new("/repo")));
        assert_eq!(project.identity(), crate::ScopeIdentity::project("/repo"));

        let topic = ScopeSelection::topic("ops");
        assert!(!topic.is_project());
        assert_eq!(topic.topic_name(), Some("ops"));
    }

    #[test]
    fn target_lang_requires_translate_flag() {
        let mut source = EnvOnlySource;
        let mut context = AiContext::resolve(None, &mut source);

        IngestFileOptions {
            target_lang: Some("fr".to_string()),
            ..IngestFileOptions::default()
        }
        .apply_to_ai_context(&mut context);
        assert!(context.bindings.audio_translate.target_lang.is_none());

        IngestFileOptions {
            translate: true,
            target_lang: Some("fr".to_string()),
            ..IngestFileOptions::default()
        }
        .apply_to_ai_context(&mut context);
        assert_eq!(
            context.bindings.audio_translate.target_lang.as_deref(),
            Some("fr")
        );
    }

    #[test]
    fn transcription_routing_applies_to_active_audio_capability() {
        let mut source = EnvOnlySource;
        let mut context = AiContext::resolve(None, &mut source);
        let original_translate_route = context.bindings.audio_translate.routing;

        IngestFileOptions {
            transcription_routing: Some(AiRouting::Direct),
            ..IngestFileOptions::default()
        }
        .apply_to_ai_context(&mut context);
        assert_eq!(context.bindings.audio_transcribe.routing, AiRouting::Direct);
        assert_eq!(
            context.bindings.audio_translate.routing,
            original_translate_route
        );

        let mut source = EnvOnlySource;
        let mut context = AiContext::resolve(None, &mut source);
        let original_transcribe_route = context.bindings.audio_transcribe.routing;
        IngestFileOptions {
            translate: true,
            transcription_routing: Some(AiRouting::Direct),
            ..IngestFileOptions::default()
        }
        .apply_to_ai_context(&mut context);
        assert_eq!(
            context.bindings.audio_transcribe.routing,
            original_transcribe_route
        );
        assert_eq!(context.bindings.audio_translate.routing, AiRouting::Direct);
    }

    #[test]
    fn crate_has_no_gcode_dependency() {
        let manifest = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"))
            .expect("manifest is readable");
        let manifest: toml::Value = toml::from_str(&manifest).expect("manifest is valid TOML");
        let dependencies = manifest
            .get("dependencies")
            .and_then(toml::Value::as_table)
            .expect("manifest has dependencies table");

        assert!(
            dependencies.contains_key("gobby-core"),
            "gobby-wiki must depend on gobby-core"
        );
        assert!(
            !dependencies.contains_key("gobby-code"),
            "gobby-wiki must not depend on gobby-code"
        );
    }
}