khive-pack-knowledge 0.12.0

Knowledge verb pack — lore corpus (atoms/domains), TF-IDF retrieval, concept registration
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
//! Param/option types for the knowledge pack verbs.

use serde::{Deserialize, Deserializer};
use serde_json::Value;
use uuid::Uuid;

pub use khive_brain_core::SectionType;

// ── Section record (what the SQL stores) ─────────────────────────────────────

#[derive(Debug, Clone)]
pub(crate) struct Section {
    pub id: uuid::Uuid,
    pub atom_id: String,
    pub namespace: String,
    /// The stored `section_type` text: a current [`SectionType`] value, or a retired
    /// name (see `retired`) kept unchanged on rows written before the retirement.
    pub section_type: String,
    /// True when `section_type` is one of [`SectionType::RETIRED_NAMES`].
    pub retired: bool,
    pub heading: String,
    pub content: String,
    pub content_hash: String,
    pub status: String,
    pub tokens: i64,
    pub sort_order: i64,
    pub created_at: i64,
    pub updated_at: i64,
}

// ── atom record (what the SQL stores) ────────────────────────────────────────

#[derive(Debug, Clone)]
pub(crate) struct Atom {
    pub id: Uuid,
    pub namespace: String,
    pub slug: String,
    pub name: String,
    /// The atom's content text (also serves as its description). Backed by the
    /// `content` column in `knowledge_atoms`.
    pub content: String,
    /// JSON array string e.g. `["rag","retrieval"]`
    pub tags: String,
    /// JSON object string
    pub properties: Option<String>,
    pub status: Option<String>,
    pub source_uri: Option<String>,
    pub source_type: Option<String>,
    pub finalized: bool,
    pub created_at: i64,
    pub updated_at: i64,
    // REASON: deleted_at is stored in SQL and read when reconstructing full atom history;
    // not yet surfaced to callers but required for soft-delete query correctness.
    #[allow(dead_code)]
    pub deleted_at: Option<i64>,
}

impl Atom {
    /// Comma-separated display of tags (used in FTS scoring text).
    pub fn tags_display(&self) -> String {
        let v: Vec<String> = serde_json::from_str(&self.tags).unwrap_or_default();
        v.join(" ")
    }
}

// ── domain record ─────────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub(crate) struct Domain {
    pub id: Uuid,
    pub namespace: String,
    pub slug: String,
    pub name: String,
    pub description: Option<String>,
    pub tags: String,
    /// JSON array of member atom slugs
    pub members: String,
    pub created_at: i64,
    pub updated_at: i64,
    // REASON: deleted_at is stored in SQL and read when reconstructing full domain history;
    // not yet surfaced to callers but required for soft-delete query correctness.
    #[allow(dead_code)]
    pub deleted_at: Option<i64>,
}

// ── upsert_atoms ─────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct AtomInput {
    pub slug: String,
    pub name: String,
    /// The atom's content text (>= 20 words).
    #[serde(default)]
    pub content: Option<String>,
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    #[serde(default)]
    pub properties: Option<Value>,
    /// Patch semantics: omitted preserves an existing flag, `null` resets it
    /// to false, and a boolean sets it explicitly.
    #[serde(default, deserialize_with = "tri_state")]
    pub finalized: Option<Option<bool>>,
    /// Patch semantics: omitted preserves an existing URI, `null` clears it,
    /// and a string replaces it.
    #[serde(default, deserialize_with = "tri_state")]
    pub source_uri: Option<Option<String>>,
    /// Patch semantics: omitted preserves an existing type, `null` clears it,
    /// and a string replaces it.
    #[serde(default, deserialize_with = "tri_state")]
    pub source_type: Option<Option<String>>,
}

/// Preserve the distinction Serde's ordinary `Option<T>` collapses: an absent
/// key uses the field default (`None`), while a present null/value becomes
/// `Some(None)` / `Some(Some(value))`.
fn tri_state<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
where
    T: Deserialize<'de>,
    D: Deserializer<'de>,
{
    Ok(Some(Option::deserialize(deserializer)?))
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct UpsertAtomsParams {
    pub atoms: Vec<AtomWrite>,
    #[serde(default)]
    pub dry_run: bool,
    #[serde(default)]
    // REASON: chunk_size is accepted from callers as a hint for client-side pagination;
    // server-side chunking is not yet implemented but the field must be deserialized
    // so callers that send it don't receive unexpected errors.
    pub chunk_size: Option<usize>,
}

#[derive(Debug)]
pub(crate) enum AtomWrite {
    Upsert(AtomInput),
    PropertiesOnly(AtomPropertiesInput),
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct AtomPropertiesInput {
    pub id: Uuid,
    #[serde(deserialize_with = "Value::deserialize")]
    pub properties: Value,
}

impl<'de> Deserialize<'de> for AtomWrite {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        if value.get("id").is_some() {
            serde_json::from_value(value)
                .map(Self::PropertiesOnly)
                .map_err(serde::de::Error::custom)
        } else {
            serde_json::from_value(value)
                .map(Self::Upsert)
                .map_err(serde::de::Error::custom)
        }
    }
}

// ── upsert_domains ─────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct DomainInput {
    pub slug: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    #[serde(default)]
    pub members: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct UpsertDomainsParams {
    pub domains: Vec<DomainInput>,
}

// ── get ───────────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GetParams {
    /// Full UUID, exact namespace-scoped slug, or unique 8+ hexadecimal UUID prefix.
    pub id: String,
    /// When `true`, include the atom's sections in the response under a `sections` key.
    /// Defaults to `false`; domains ignore this flag (they have no sections).
    #[serde(default)]
    pub include_sections: Option<bool>,
}

// ── list ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct ListParams {
    #[serde(rename = "type", alias = "kind", default)]
    pub kind: Option<String>,
    #[serde(default)]
    pub limit: Option<usize>,
    #[serde(default)]
    pub offset: Option<usize>,
    /// Keyset cursor for a stable full-store walk. An empty string starts
    /// cursor mode; subsequent requests pass the prior page's `next_after`
    /// full UUID.
    #[serde(default)]
    pub after: Option<String>,
    /// Exact response projection. Storage reads select only these columns plus
    /// hidden pagination keys, so key-only walks do not hydrate atom content.
    #[serde(default)]
    pub fields: Option<Vec<String>>,
    #[serde(default)]
    pub status: Option<Value>,
    #[serde(default)]
    pub exclude_status: Option<String>,
}

// ── stats ────────────────────────────────────────────────────────────────────

/// `knowledge.stats` takes no filter arguments; the empty struct exists purely
/// so unknown/typo'd params (e.g. a caller expecting a `domain` filter that
/// doesn't exist) are rejected instead of silently ignored.
#[derive(Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct StatsParams {}

// ── delete_atoms ──────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct DeleteAtomsParams {
    pub ids: Vec<String>,
    #[serde(default)]
    // REASON: cascade is accepted from callers for API forward-compatibility; cascading
    // delete behavior is not yet implemented (atoms are soft-deleted without affecting sections).
    pub cascade: Option<bool>,
}

// ── index ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct IndexParams {
    #[serde(default)]
    pub ids: Option<Vec<String>>,
    #[serde(default)]
    pub batch_size: Option<usize>,
    #[serde(default)]
    pub insert_only: Option<bool>,
    #[serde(default)]
    pub rebuild_ann: Option<bool>,
}

// ── fold ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct FoldParams {
    pub candidates: Vec<FoldCandidate>,
    pub budget: usize,
    #[serde(default)]
    pub min_score: Option<f32>,
    #[serde(default)]
    pub category_weights: Option<std::collections::BTreeMap<String, f32>>,
    #[serde(default)]
    pub diversity_bias: Option<f32>,
    #[serde(default)]
    pub epistemic_weight: Option<f32>,
}

#[derive(Debug, Clone, Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct FoldCandidate {
    pub id: String,
    pub score: f32,
    pub size: usize,
    /// Display name, e.g. from `knowledge.suggest`'s `{id, name, score, size}`
    /// output — accepted (and echoed back on `selected` items) so `suggest`'s
    /// results feed `fold`'s `candidates` unmodified (issue #105); not used by
    /// the selection algorithm itself.
    #[serde(default)]
    pub name: Option<String>,
    /// Optional live member count accepted from unmodified suggest results.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub members: Option<usize>,
    #[serde(default)]
    pub content: Option<Value>,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default)]
    pub information_gain: Option<f32>,
}

// ── search ────────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SearchParams {
    pub query: String,
    #[serde(rename = "type", alias = "kind", default)]
    pub kind: Option<String>,
    #[serde(default)]
    pub status: Option<Value>,
    #[serde(default)]
    pub exclude_status: Option<String>,
    /// When false (default), draft atoms are excluded from results.
    /// Pass true to include draft atoms alongside reviewed ones.
    /// Has no effect when an explicit `status` filter is provided.
    #[serde(default)]
    pub include_drafts: Option<bool>,
    #[serde(default)]
    pub role: Option<String>,
    #[serde(default)]
    pub limit: Option<usize>,
    #[serde(default)]
    pub min_score: Option<f64>,
    #[serde(default)]
    pub weights: Option<SearchWeights>,
    #[serde(default)]
    pub decompose: Option<bool>,
    #[serde(default)]
    pub decompose_threshold: Option<usize>,
    #[serde(default)]
    pub intersection_bonus: Option<f64>,
    #[serde(default)]
    pub rerank: Option<bool>,
    #[serde(default)]
    pub rerank_alpha: Option<f64>,
}

/// Tunable TF-IDF weight parameters.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SearchWeights {
    pub w_exact_name: Option<f64>,
    pub w_name: Option<f64>,
    pub w_tags: Option<f64>,
    pub w_content: Option<f64>,
    pub expand_discount: Option<f64>,
    pub coverage_alpha: Option<f64>,
    pub w_bigram: Option<f64>,
}

// ── suggest ───────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SuggestParams {
    pub query: String,
    #[serde(default)]
    pub role: Option<String>,
    #[serde(default)]
    pub limit: Option<usize>,
}

// ── compose ───────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ComposeParams {
    /// Exact read namespace. Registry dispatch pre-applies this to the token;
    /// direct handlers validate a matching authorized token and narrow any
    /// broader visibility before reading.
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default)]
    pub domain_ids: Option<Vec<String>>,
    #[serde(default)]
    pub atom_ids: Option<Vec<String>>,
    pub query: String,
    #[serde(default)]
    pub auto_limit: Option<usize>,
    #[serde(default)]
    pub max_tokens: Option<usize>,
    #[serde(default)]
    pub explain: Option<bool>,
    /// Blend knowledge-graph `concept`/`document` entities into the candidate
    /// pool (ADR-051 Amendment 1). Defaults to `true`. Has no effect on
    /// `atom_ids`-only calls, which never blend (the caller pinned exact
    /// atoms and gets exactly those back).
    #[serde(default)]
    pub blend_kg: Option<bool>,
}

// ── edit ─────────────────────────────────────────────────────────────────────

/// One section update within a `knowledge.edit` call.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SectionUpdate {
    /// Section type (must be a valid `SectionType` canonical name).
    pub section_type: String,
    /// New content for this section.  Required.
    pub content: String,
    /// Optional override for the markdown heading text.
    #[serde(default)]
    pub heading: Option<String>,
    /// Sort position within the atom (lower = earlier). Defaults to type ordinal.
    #[serde(default)]
    pub sort_order: Option<i64>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct EditParams {
    /// Atom UUID or slug to edit sections for.
    pub id: String,
    /// Sections to upsert.  Must not be empty.
    pub sections: Vec<SectionUpdate>,
}

// ── challenge / adjudicate ────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ChallengeParams {
    /// Atom UUID or slug.
    pub atom_id: String,
    /// Section type to challenge.
    pub section_type: String,
    /// Disambiguator when an atom has multiple same-type sections
    /// (`content_hash` from `knowledge.edit`). Required if more than one
    /// eligible section of `section_type` exists.
    #[serde(default)]
    pub content_hash: Option<String>,
    /// Optional challenge reason.
    #[serde(default)]
    pub reason: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct AdjudicateParams {
    /// Atom UUID or slug.
    pub atom_id: String,
    /// Section type to adjudicate.
    pub section_type: String,
    /// Disambiguator when an atom has multiple same-type disputed sections
    /// (`content_hash` from `knowledge.edit`). Required if more than one
    /// disputed section of `section_type` exists.
    #[serde(default)]
    pub content_hash: Option<String>,
    /// Resolution: "accept" (keep disputed, mark reviewed) or "reject" (revert to reviewed).
    pub resolution: String,
}

// ── import ────────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ImportParams {
    /// Filesystem path to a markdown file or directory.
    pub path: String,
    /// Markdown format hint.  Only `"atlas_md"` is supported in v1.
    #[serde(default)]
    pub format: Option<String>,
    /// Chunk strategy: `"section"` (atom plus parsed section rows, default) or
    /// `"atom"` (whole markdown in one atom with no section rows).
    #[serde(default)]
    pub chunk_strategy: Option<String>,
}