khive_types/pack.rs
1//! Pack trait — the declarative composition unit for khive.
2//!
3//! A pack declares vocabulary (note kinds, entity kinds), verbs, and edge
4//! endpoint rules. This is purely static metadata — no I/O, no async.
5//! Runtime dispatch lives in `khive-runtime` (`PackRuntime` trait +
6//! `VerbRegistry`).
7//!
8//! This trait lives in khive-types (no_std, zero deps) so downstream crates
9//! can reference pack metadata without pulling in the full runtime.
10
11use crate::edge::EdgeRelation;
12
13/// Visibility tier for a handler.
14///
15/// `Verb` entries appear on the MCP wire and are invokable by agents.
16/// `Subhandler` entries are internal — callable by the operator via CLI
17/// but not surfaced as top-level MCP verbs.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum Visibility {
20 /// Externally invokable via MCP `request` tool.
21 Verb,
22 /// Internal — operator-only via `kkernel exec '<pack>.<handler>(...)'`.
23 Subhandler,
24}
25
26/// Illocutionary force classification for a verb handler.
27///
28/// Follows Searle's five speech-act categories (1976). Every `Visibility::Verb`
29/// handler in the MCP surface MUST carry a category. `Subhandler` entries may
30/// use the category of their parent verb or `Assertive` as a sensible default.
31///
32/// The category is a documentation / introspection tag. It is NOT used for
33/// permission checking, transport routing, or return-shape selection.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum VerbCategory {
36 /// Speaker represents a state of affairs — retrieves and presents facts.
37 /// Examples: `get`, `list`, `search`, `recall`.
38 Assertive,
39 /// Speaker attempts to get the hearer to do something.
40 /// Examples: `assign`, `transition`.
41 Directive,
42 /// Speaker commits to a persistent change.
43 /// Examples: `create`, `remember`, `link`, `send`.
44 Commissive,
45 /// Speaker changes institutional status by fiat.
46 /// Examples: `update`, `delete`, `merge`, `complete`.
47 Declaration,
48 // `Expressive` is intentionally absent — no verb currently uses it.
49}
50
51/// Parameter type for `help=true` schema envelopes.
52///
53/// Declares the name, type hint, required flag, and one-line description for
54/// a single verb parameter. Stored as a `&'static` slice on [`HandlerDef`] so
55/// the registry can return it without any allocation at call time.
56///
57/// The `param_type` field is a free-form string (e.g. `"string"`, `"uuid"`,
58/// `"bool"`, `"integer"`, `"string | null"`) — it is documentation-only and
59/// not used for validation.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub struct ParamDef {
62 /// Parameter name as used in the DSL (e.g. `"id"`, `"kind"`, `"query"`).
63 pub name: &'static str,
64 /// Free-form type hint for documentation (e.g. `"string"`, `"uuid"`, `"bool"`).
65 pub param_type: &'static str,
66 /// Whether the caller must supply this parameter.
67 pub required: bool,
68 /// One-line human-readable description.
69 pub description: &'static str,
70}
71
72/// Handler metadata for discovery and documentation.
73///
74/// Replaces the previous `VerbDef`. Every entry carries a `visibility` tag
75/// so the registry can separate the MCP-exposed surface from internal handlers,
76/// and a `category` that classifies the illocutionary force of the verb
77/// per the speech-act taxonomy.
78///
79/// The `params` slice is used by `VerbRegistry::describe_verb` to build the
80/// `help=true` schema envelope. Packs that predate this field leave it empty
81/// (`&[]`) which is backward-compatible — callers receive a schema envelope
82/// with zero params rather than an error.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct HandlerDef {
85 pub name: &'static str,
86 pub description: &'static str,
87 pub visibility: Visibility,
88 /// Illocutionary force classification. Use `Assertive` for `Subhandler`
89 /// entries that have no external callers.
90 pub category: VerbCategory,
91 /// Parameter schema for `help=true` introspection (issue #287).
92 ///
93 /// Empty (`&[]`) is the correct default for handlers that predate this
94 /// field or have no fixed parameter schema (e.g. free-form query verbs).
95 pub params: &'static [ParamDef],
96}
97
98/// Presentation override for a verb handler.
99///
100/// Most verbs use the default `Standard` policy which allows the caller's
101/// requested `PresentationMode` to apply. A small set declare `AlwaysVerbose`
102/// because Agent-mode trimming (UUID shortening, empty-field dropping) would
103/// corrupt their response for downstream chaining — e.g. `get` returns UUIDs
104/// that callers pipe into `link`; shortening them here breaks the chain.
105///
106/// The policy is carried as a `const` in [`HandlerDef`] so the registry can
107/// consult it before applying the presentation transform.
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
109pub enum VerbPresentationPolicy {
110 /// Apply the caller's requested `PresentationMode` unchanged.
111 #[default]
112 Standard,
113 /// Always use `Verbose` output regardless of the caller's mode.
114 ///
115 /// Declared verbs: `get`, `link`, `query`, `traverse`, `neighbors`,
116 /// `brain.feedback`.
117 ///
118 /// `link` is included because the returned edge ID is the only handle for
119 /// follow-up `neighbors`/`traverse` calls; short-form IDs risk prefix
120 /// collision at scale (~65K edges can share an 8-char prefix).
121 ///
122 /// `brain.feedback` is included because callers chain `target_id` from the
123 /// response back into subsequent feedback or profile queries; an 8-char
124 /// prefix is ambiguous and defeats the acknowledged-ID contract (#545).
125 AlwaysVerbose,
126}
127
128impl HandlerDef {
129 /// Resolve the presentation policy for this handler.
130 ///
131 /// Returns [`VerbPresentationPolicy::AlwaysVerbose`] for verbs whose
132 /// semantics demand full output (full UUIDs, complete timestamps) regardless
133 /// of the caller's requested presentation mode.
134 ///
135 /// New verbs that need this override must be added here; omission from the
136 /// list means `Standard` applies.
137 pub fn presentation_policy(&self) -> VerbPresentationPolicy {
138 // AlwaysVerbose verbs bypass agent-mode transforms entirely.
139 //
140 // `link` is AlwaysVerbose because the edge ID returned is the only handle
141 // for follow-up `neighbors`/`traverse` calls. At scale, two edges can share
142 // the same 8-char prefix (birthday collision ~65K edges), so shortening the
143 // edge ID in agent mode breaks downstream chaining.
144 match self.name {
145 "get" | "link" | "query" | "traverse" | "neighbors" | "brain.feedback" => {
146 VerbPresentationPolicy::AlwaysVerbose
147 }
148 _ => VerbPresentationPolicy::Standard,
149 }
150 }
151}
152
153/// Backward-compatible type alias. Existing code that names `VerbDef` still
154/// compiles; new code should use `HandlerDef` directly.
155#[deprecated(since = "0.2.0", note = "Use HandlerDef instead")]
156pub type VerbDef = HandlerDef;
157
158/// Match spec for one end of an [`EdgeEndpointRule`].
159///
160/// Identifies a substrate + kind pair that the rule applies to. Note that
161/// `kind` strings refer to the pack-declared note kinds / entity kinds — not
162/// the closed [`EdgeRelation`] set, which is universal.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub enum EndpointKind {
165 /// A note whose `kind` field equals the given string (e.g. `"task"`).
166 NoteOfKind(&'static str),
167 /// An entity whose `kind` field equals the given string (e.g. `"concept"`).
168 EntityOfKind(&'static str),
169 /// An entity whose base `kind` AND `entity_type` subtype both match the
170 /// given strings (e.g. `kind: "concept", entity_type: "theorem"`). Both
171 /// fields must match — enforcing the `(EntityKind, entity_type)` registry
172 /// invariant required by ADR-001:102. Required for granular entity subtypes
173 /// (formal-math theorem/definition, AMR gene/drug/pathogen): `EntityOfKind`
174 /// only sees the base kind (`"concept"`), so an `EntityOfKind("theorem")`
175 /// rule is silently inert. Additive — tightens nothing in the closed relation
176 /// set.
177 EntityOfType {
178 /// Base entity kind that must match (e.g. `"concept"`).
179 kind: &'static str,
180 /// Canonical `entity_type` subtype that must match (e.g. `"theorem"`).
181 entity_type: &'static str,
182 },
183}
184
185/// A pack-declared endpoint rule for a specific edge relation.
186///
187/// Rules are **additive**: they extend the set of allowed
188/// `(source, relation, target)` triples beyond the base contract.
189/// Packs cannot tighten the base rules — only broaden them. The closed
190/// [`EdgeRelation`] taxonomy itself is not extended; only the endpoint
191/// contract per relation is.
192///
193/// Example — GTD pack allows `depends_on` between task notes:
194///
195/// ```ignore
196/// EdgeEndpointRule {
197/// relation: EdgeRelation::DependsOn,
198/// source: EndpointKind::NoteOfKind("task"),
199/// target: EndpointKind::NoteOfKind("task"),
200/// }
201/// ```
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub struct EdgeEndpointRule {
204 pub relation: EdgeRelation,
205 pub source: EndpointKind,
206 pub target: EndpointKind,
207}
208
209/// Lifecycle specification for a note kind.
210///
211/// Declares which field holds the kind's domain state, the initial value,
212/// terminal values, and allowed transitions. The runtime uses this to
213/// validate lifecycle operations at the verb boundary without hard-coding
214/// kind-specific logic in the shared CRUD path.
215///
216/// Phase 1 (current): packs declare the spec; the runtime records it for
217/// documentation and future enforcement.
218/// Phase 2 (future): the runtime uses `field` to route lifecycle writes
219/// to a first-class column rather than `properties`.
220#[derive(Clone, Debug, PartialEq, Eq)]
221pub struct NoteLifecycleSpec {
222 /// The field name that holds the kind's lifecycle state.
223 ///
224 /// Use `"kind_status"` for pack-owned lifecycle fields to avoid the
225 /// semantic collision with `Note.status` (NoteStatus).
226 pub field: &'static str,
227 /// The value assigned when a note of this kind is first created.
228 pub initial: &'static str,
229 /// Values from which no further transitions are possible.
230 pub terminal: &'static [&'static str],
231 /// Allowed `(from, to)` transitions. `"*"` as `from` matches any state.
232 pub transitions: &'static [(&'static str, &'static str)],
233}
234
235/// Kind-level schema specification for a note kind.
236///
237/// Each pack-registered note kind may declare a `NoteKindSpec` to describe
238/// its lifecycle semantics. The runtime collects these at boot time via
239/// [`Pack::NOTE_KIND_SPECS`] for documentation, introspection, and future
240/// enforcement.
241#[derive(Clone, Debug, PartialEq, Eq)]
242pub struct NoteKindSpec {
243 /// The note kind string this spec governs (e.g. `"task"`).
244 pub kind: &'static str,
245 /// Alternate names this kind accepts on the wire.
246 pub aliases: &'static [&'static str],
247 /// Lifecycle state machine for this kind.
248 pub lifecycle: NoteLifecycleSpec,
249}
250
251/// DDL statements the pack needs applied to the auxiliary schema.
252///
253/// Pack-auxiliary tables use idempotent `CREATE TABLE IF NOT EXISTS`; they are
254/// not part of the core versioned migration chain. The runtime applies these
255/// statements once at pack registration time (or startup) against the active
256/// storage backend.
257#[derive(Clone, Debug, PartialEq, Eq)]
258pub struct PackSchemaPlan {
259 /// The pack this schema plan belongs to (used for error reporting).
260 pub pack: &'static str,
261 /// Idempotent SQL statements to apply.
262 pub statements: &'static [&'static str],
263}
264
265/// A composable module that contributes vocabulary, verbs, and edge endpoint
266/// rules to the khive runtime.
267///
268/// Packs declare what entity kinds, note kinds, and verbs they introduce, and
269/// optionally extend the per-relation endpoint contract via [`EDGE_RULES`].
270/// The runtime merges vocabularies from all loaded packs and rejects
271/// unregistered kinds at the service boundary.
272///
273/// The closed [`EdgeRelation`] enum is not extensible — only its
274/// per-relation endpoint contract is extensible by packs.
275///
276/// [`EDGE_RULES`]: Pack::EDGE_RULES
277pub trait Pack {
278 /// Short identifier for this pack (e.g. "kg", "tasks").
279 const NAME: &'static str;
280
281 /// Note kinds this pack contributes to the runtime vocabulary.
282 const NOTE_KINDS: &'static [&'static str];
283
284 /// Entity kinds this pack contributes to the runtime vocabulary.
285 const ENTITY_KINDS: &'static [&'static str];
286
287 /// Handlers this pack registers.
288 ///
289 /// The runtime routes verb calls to the pack that declares them.
290 /// Only entries with `visibility: Visibility::Verb` are surfaced on the
291 /// MCP wire; `Visibility::Subhandler` entries are internal.
292 const HANDLERS: &'static [HandlerDef];
293
294 /// Additional edge endpoint rules this pack contributes.
295 ///
296 /// Defaults to empty — packs that introduce no new endpoint pairs (or
297 /// only rely on the base endpoint contract) can ignore this.
298 const EDGE_RULES: &'static [EdgeEndpointRule] = &[];
299
300 /// Other pack names whose vocabulary this pack references.
301 ///
302 /// The runtime checks that every name in `REQUIRES` appears in the
303 /// loaded pack set before any pack is registered. Defaults to empty
304 /// so existing packs compile without changes.
305 const REQUIRES: &'static [&'static str] = &[];
306
307 /// Lifecycle and schema specs for note kinds this pack owns.
308 ///
309 /// Packs that introduce note kinds with explicit lifecycle semantics
310 /// (e.g. GTD's `task` kind) declare the spec here. The runtime collects
311 /// these at boot time for introspection and future enforcement. Defaults
312 /// to empty so existing packs compile without changes.
313 const NOTE_KIND_SPECS: &'static [NoteKindSpec] = &[];
314
315 /// Pack-auxiliary schema plan.
316 ///
317 /// Packs that need their own auxiliary tables (e.g. GTD's
318 /// `gtd_lifecycle_audit`) declare idempotent DDL statements here.
319 /// The runtime applies them once at registration time. Defaults to
320 /// `None` so packs with no auxiliary schema cost nothing.
321 const SCHEMA_PLAN: Option<PackSchemaPlan> = None;
322
323 /// Validation rule IDs contributed by this pack.
324 ///
325 /// Rule IDs are namespaced by pack name: `<pack-name>/<rule-id>`.
326 /// The runtime merges rule IDs from all packs; the actual rule
327 /// implementations live in `khive-runtime::validation::ValidationRule`
328 /// (not in `khive-types`, which stays `no_std`). This const serves as
329 /// the declarative catalog of rule identifiers so the validation
330 /// infrastructure can enumerate what rules a pack claims without
331 /// loading the runtime.
332 ///
333 /// Defaults to empty — packs with no domain-specific validation rules
334 /// can leave this unset.
335 const VALIDATION_RULES: &'static [&'static str] = &[];
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 struct TestPack;
343
344 impl Pack for TestPack {
345 const NAME: &'static str = "test";
346 const NOTE_KINDS: &'static [&'static str] = &["memo"];
347 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
348 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
349 name: "do_thing",
350 description: "does a thing",
351 visibility: Visibility::Verb,
352 category: VerbCategory::Commissive,
353 params: &[],
354 }];
355 }
356
357 #[test]
358 fn pack_trait_compiles() {
359 assert_eq!(TestPack::NAME, "test");
360 assert_eq!(TestPack::NOTE_KINDS, &["memo"]);
361 assert_eq!(TestPack::ENTITY_KINDS, &["widget"]);
362 assert_eq!(TestPack::HANDLERS.len(), 1);
363 assert_eq!(TestPack::HANDLERS[0].name, "do_thing");
364 assert_eq!(TestPack::HANDLERS[0].visibility, Visibility::Verb);
365 assert_eq!(TestPack::HANDLERS[0].category, VerbCategory::Commissive);
366 }
367
368 #[test]
369 fn verb_category_variants_exist() {
370 // Just ensuring the enum variants are accessible — no runtime assertion
371 // needed beyond confirming they exist at compile time.
372 let _ = VerbCategory::Assertive;
373 let _ = VerbCategory::Directive;
374 let _ = VerbCategory::Commissive;
375 let _ = VerbCategory::Declaration;
376 }
377
378 #[test]
379 fn pack_validation_rules_default_empty() {
380 assert!(TestPack::VALIDATION_RULES.is_empty());
381 }
382
383 // `link` must be AlwaysVerbose so edge IDs are not shortened.
384 #[test]
385 fn link_handler_is_always_verbose() {
386 let link_def = HandlerDef {
387 name: "link",
388 description: "Create a typed directed edge",
389 visibility: Visibility::Verb,
390 category: VerbCategory::Commissive,
391 params: &[],
392 };
393 assert_eq!(
394 link_def.presentation_policy(),
395 VerbPresentationPolicy::AlwaysVerbose,
396 "link must be AlwaysVerbose"
397 );
398 }
399
400 // AlwaysVerbose set regression: ensure get/query/traverse/neighbors/brain.feedback remain.
401 #[test]
402 fn always_verbose_set_contains_expected_verbs() {
403 let always_verbose = [
404 "get",
405 "link",
406 "query",
407 "traverse",
408 "neighbors",
409 "brain.feedback",
410 ];
411 for name in always_verbose {
412 let h = HandlerDef {
413 name,
414 description: "",
415 visibility: Visibility::Verb,
416 category: VerbCategory::Assertive,
417 params: &[],
418 };
419 assert_eq!(
420 h.presentation_policy(),
421 VerbPresentationPolicy::AlwaysVerbose,
422 "{name:?} must be AlwaysVerbose"
423 );
424 }
425 }
426
427 // Standard policy for all other verbs.
428 #[test]
429 fn non_verbose_verbs_are_standard_policy() {
430 let standard = [
431 "create", "list", "update", "delete", "search", "recall", "remember",
432 ];
433 for name in standard {
434 let h = HandlerDef {
435 name,
436 description: "",
437 visibility: Visibility::Verb,
438 category: VerbCategory::Commissive,
439 params: &[],
440 };
441 assert_eq!(
442 h.presentation_policy(),
443 VerbPresentationPolicy::Standard,
444 "{name:?} must be Standard (not AlwaysVerbose)"
445 );
446 }
447 }
448}