khive_types/pack.rs
1//! Pack trait — the declarative composition unit for khive.
2//!
3//! A pack declares vocabulary (note kinds, entity kinds, brain consumer
4//! kinds), verbs, and edge endpoint rules. This is purely static metadata —
5//! no I/O, no async.
6//! Runtime dispatch lives in `khive-runtime` (`PackRuntime` trait +
7//! `VerbRegistry`).
8//!
9//! This trait lives in khive-types (no_std, zero deps) so downstream crates
10//! can reference pack metadata without pulling in the full runtime.
11
12use crate::edge::EdgeRelation;
13use crate::entity_type::EntityTypeDef;
14
15/// Argument names owned by the outer request envelope rather than verb handlers.
16///
17/// Handler metadata must not advertise these names because every request parser rejects them
18/// before pack dispatch. Keeping this list in the shared type crate lets both request parsing and
19/// registry construction enforce one exact contract.
20pub const RESERVED_ENVELOPE_ARGS: &[&str] = &["presentation", "presentation_per_op"];
21
22/// Tag marking a `tool` pack registry object.
23///
24/// The value is on-disk data on every row the tool registry has ever minted,
25/// so it is not free to change.
26pub const TOOL_REGISTRY_TAG: &str = "tool-registry";
27
28/// Tags whose presence makes an entity a pack's registry row.
29///
30/// Such a row is not ordinary metadata: its fields are policy inputs. The
31/// tool registry's `source` names the binary a granted tool name resolves to,
32/// and `side_effect` is read at run time and handed to the policy decision, so
33/// a caller who can patch the row can change what a granted name does without
34/// registering anything. The generic entity verbs therefore refuse to write a
35/// row carrying one of these tags, including a patch that would remove the tag
36/// itself, and the owning pack's verbs are the only writer.
37///
38/// This is a list rather than a field allow-list on purpose: a list of
39/// protected properties goes stale the first time a pack adds a
40/// capability-bearing property, which is exactly how `side_effect` was missed.
41pub const PACK_REGISTRY_TAGS: &[&str] = &[TOOL_REGISTRY_TAG];
42
43/// Canonical registry tag carried by a row, including legacy case variants.
44/// Storage name resolution folds tags to lowercase, so generic write guards
45/// must use the same comparison or a differently cased tag can bypass them.
46pub fn pack_registry_tag(tag: &str) -> Option<&'static str> {
47 PACK_REGISTRY_TAGS
48 .iter()
49 .copied()
50 .find(|registered| registered.eq_ignore_ascii_case(tag))
51}
52
53/// Visibility tier for a handler.
54///
55/// `Verb` entries appear on the MCP wire and are invokable by agents.
56/// `Subhandler` entries are internal — callable by the operator via CLI
57/// but not surfaced as top-level MCP verbs.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum Visibility {
60 /// Externally invokable via MCP `request` tool.
61 Verb,
62 /// Internal — operator-only via `kkernel exec '<pack>.<handler>(...)'`.
63 Subhandler,
64}
65
66/// Illocutionary force classification for a verb handler.
67///
68/// Follows Searle's five speech-act categories (1976). Every `Visibility::Verb`
69/// handler in the MCP surface MUST carry a category. `Subhandler` entries may
70/// use the category of their parent verb or `Assertive` as a sensible default.
71///
72/// The category is a documentation / introspection tag. It is NOT used for
73/// permission checking. It is one input — never the sole proof — to two
74/// narrow, sanctioned runtime decisions, both in `khive-runtime`'s
75/// `VerbRegistry`:
76/// - `admission_degrade_safe` treats `Assertive` as a necessary condition
77/// for letting a dispatch's own audit row degrade under transient
78/// admission pressure, combined with an explicit per-verb allowlist.
79/// - `is_retry_safe_after_frame_omission` treats `Assertive` as a necessary
80/// condition for telling a caller that a response lost to the MCP
81/// daemon's frame budget is safe to re-issue, combined with an explicit
82/// exclusion list.
83///
84/// Both combine the category with an audited list rather than trusting it
85/// alone, because several `Assertive` handlers schedule their own persisted
86/// or accounting-bearing side effect on every dispatch (`memory.recall`'s
87/// serve ledger, `search`'s `SearchExecuted` telemetry) that the speech-act
88/// classification cannot see.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum VerbCategory {
91 /// Speaker represents a state of affairs — retrieves and presents facts.
92 /// Examples: `get`, `list`, `search`, `recall`.
93 Assertive,
94 /// Speaker attempts to get the hearer to do something.
95 /// Examples: `assign`, `transition`.
96 Directive,
97 /// Speaker commits to a persistent change.
98 /// Examples: `create`, `remember`, `link`, `send`.
99 Commissive,
100 /// Speaker changes institutional status by fiat.
101 /// Examples: `update`, `delete`, `merge`, `complete`.
102 Declaration,
103 // `Expressive` is intentionally absent — no verb currently uses it.
104}
105
106/// How a `uuid` or `array of uuid` parameter resolves a caller-supplied
107/// identifier — full UUID and short hex-prefix acceptance, and whether
108/// either form is checked against a namespace. This is a property of the
109/// handler's own resolution code, declared explicitly per parameter so
110/// `VerbRegistry::describe_verb`'s rendered contract can never drift from
111/// what the handler actually does (see khive-runtime's `pack.rs`
112/// `IdResolutionMode` rendering table for the exact wording per variant).
113///
114/// Every variant here must correspond to a resolver function that actually
115/// exists in the codebase — this is not a place to guess. When a new `uuid`
116/// parameter is added, its handler must be read to determine which existing
117/// variant matches (or whether a new one is needed); the parameter name
118/// alone never determines the mode.
119#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
120pub enum IdResolutionMode {
121 /// Not a UUID-typed identifier parameter — no resolver contract applies.
122 #[default]
123 NotApplicable,
124 /// ADR-007 Rev 6 by-ID contract: a full UUID and a short hex prefix both
125 /// resolve with no namespace predicate at all. The Gate, not
126 /// storage-layer filtering, is the authorization seam. Used by `get`,
127 /// `update`, `delete`, `merge`, `link`'s endpoint parameters, GTD's
128 /// lifecycle `id` parameters, and brain's feedback `target_id`.
129 UnscopedById,
130 /// A full UUID resolves as given, with no namespace check performed by
131 /// the resolver. A short hex prefix is resolved by searching only the
132 /// caller's primary namespace. Used by graph-read anchors
133 /// (`neighbors`/`traverse`) and citation targets.
134 PrefixScopedToPrimary,
135 /// Both a full UUID and a short hex prefix are validated against the
136 /// caller's primary namespace: a record that exists but belongs to a
137 /// different namespace resolves as not found.
138 FullAndPrefixScopedToPrimary,
139 /// Only a full UUID is accepted — a short hex prefix is rejected
140 /// outright — and the UUID is validated against the caller's own
141 /// (primary) namespace.
142 FullUuidOnlyScopedToPrimary,
143 /// Only a full UUID is accepted — a short hex prefix is rejected
144 /// outright — and no namespace check is performed by the resolver
145 /// itself (any namespace scoping comes from the enclosing operation,
146 /// not from this parameter).
147 UnscopedFullUuidOnly,
148 /// `list.target_id`: edge lists resolve full UUIDs as given and prefixes
149 /// or entity names in the primary namespace; event lists accept only an
150 /// exact full subject UUID, with visibility applied to event rows.
151 EdgeOrEventTarget,
152}
153
154/// Parameter type for `help=true` schema envelopes.
155///
156/// Declares the name, type hint, required flag, and one-line description for
157/// a single verb parameter. Stored as a `&'static` slice on [`HandlerDef`] so
158/// the registry can return it without any allocation at call time.
159///
160/// The `param_type` field is drawn from a closed vocabulary (e.g. `"string"`,
161/// `"uuid"`, `"boolean"`, `"integer"`), asserted as an exact set by a
162/// registry-wide test. It does not validate the argument, but it is not
163/// documentation-only either: the runtime derives each verb's published JSON
164/// Schema from it, so an unmapped spelling withholds that verb's schema.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub struct ParamDef {
167 /// Parameter name as used in the DSL (e.g. `"id"`, `"kind"`, `"query"`).
168 pub name: &'static str,
169 /// Type hint from the closed vocabulary (e.g. `"string"`, `"uuid"`, `"boolean"`).
170 pub param_type: &'static str,
171 /// Whether the caller must supply this parameter.
172 pub required: bool,
173 /// One-line human-readable description.
174 pub description: &'static str,
175 /// Identifier-resolution mode for `param_type` `"uuid"` or `"array of
176 /// uuid"` parameters; [`IdResolutionMode::NotApplicable`] for every
177 /// other parameter type.
178 pub resolution_mode: IdResolutionMode,
179}
180
181/// Handler metadata for discovery and documentation.
182///
183/// Replaces the previous `VerbDef`. Every entry carries a `visibility` tag
184/// so the registry can separate the MCP-exposed surface from internal handlers,
185/// and a `category` that classifies the illocutionary force of the verb
186/// per the speech-act taxonomy.
187///
188/// The `params` slice is used by `VerbRegistry::describe_verb` to build the
189/// `help=true` schema envelope. Packs that predate this field leave it empty
190/// (`&[]`) which is backward-compatible — callers receive a schema envelope
191/// with zero params rather than an error.
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct HandlerDef {
194 pub name: &'static str,
195 pub description: &'static str,
196 pub visibility: Visibility,
197 /// Illocutionary force classification. Use `Assertive` for `Subhandler`
198 /// entries that have no external callers.
199 pub category: VerbCategory,
200 /// Parameter schema for `help=true` introspection.
201 ///
202 /// Empty (`&[]`) is the correct default for handlers that predate this
203 /// field or have no fixed parameter schema (e.g. free-form query verbs).
204 pub params: &'static [ParamDef],
205}
206
207/// Presentation override for a verb handler.
208///
209/// Most verbs use the default `Standard` policy which allows the caller's
210/// requested `PresentationMode` to apply. A small set declare `AlwaysVerbose`
211/// because Agent-mode trimming (UUID shortening, empty-field dropping) would
212/// corrupt their response for downstream chaining — e.g. `get` returns UUIDs
213/// that callers pipe into `link`; shortening them here breaks the chain.
214///
215/// The policy is carried as a `const` in [`HandlerDef`] so the registry can
216/// consult it before applying the presentation transform.
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
218pub enum VerbPresentationPolicy {
219 /// Apply the caller's requested `PresentationMode` unchanged.
220 #[default]
221 Standard,
222 /// Always use `Verbose` output regardless of the caller's mode.
223 ///
224 /// Declared verbs: `get`, `link`, `query`, `traverse`, `neighbors`,
225 /// `brain.feedback`, `brain.auto_feedback`, `memory.feedback`,
226 /// `comm.delivered`, `comm.transport_status`, `git.digest`, `git.ingest_cursor`.
227 ///
228 /// `link` is included because the returned edge ID is the only handle for
229 /// follow-up `neighbors`/`traverse` calls; short-form IDs risk prefix
230 /// collision at scale (~65K edges can share an 8-char prefix).
231 ///
232 /// `brain.feedback` is included because callers chain `target_id` from the
233 /// response back into subsequent feedback or profile queries; an 8-char
234 /// prefix is ambiguous and defeats the acknowledged-ID contract.
235 /// `memory.feedback` has the same exact-target contract and rejects prefix
236 /// resolution, so its acknowledged `target_id` must remain canonical.
237 /// `brain.auto_feedback` acknowledges the same canonical `target_id` and
238 /// feeds those strict paths, so it carries the same guarantee.
239 /// `comm.delivered` is included because its `id` is an exact correlation
240 /// key and the verb deliberately rejects prefix resolution (#1482).
241 /// `comm.transport_status` preserves the same exact outbound correlation key.
242 ///
243 /// `git.digest` is included because its successful response is also the
244 /// durable receipt payload. Presentation must not shorten `receipt_id` or
245 /// otherwise make the returned result differ from the stored result.
246 /// `git.ingest_cursor` preserves raw checkpoint strings, full project UUIDs,
247 /// and stored microsecond timestamps for persisted-position inspection.
248 AlwaysVerbose,
249 /// Preserve only the root append receipt's `created_at` string in Agent mode.
250 StreamAppendReceipt,
251 /// Preserve `created_at` and `updated_at` strings on immediate `results`
252 /// array members in Agent mode.
253 StreamBatchReceipts,
254 /// Preserve the root agenda continuation and empty event array in Agent mode.
255 /// Event rows retain the ordinary metadata transform.
256 AgendaContinuation,
257}
258
259impl HandlerDef {
260 /// Resolve the presentation policy for this handler.
261 ///
262 /// Returns [`VerbPresentationPolicy::AlwaysVerbose`] for verbs whose
263 /// semantics demand full output (full UUIDs, complete timestamps) regardless
264 /// of the caller's requested presentation mode.
265 ///
266 /// Stream writers retain exact receipt timestamps while keeping other
267 /// Agent transforms. Unlisted verbs use `Standard`.
268 pub fn presentation_policy(&self) -> VerbPresentationPolicy {
269 match self.name {
270 "get"
271 | "link"
272 | "query"
273 | "traverse"
274 | "neighbors"
275 | "brain.feedback"
276 | "brain.auto_feedback"
277 | "memory.feedback"
278 | "comm.delivered"
279 | "comm.transport_status"
280 | "git.digest"
281 | "git.ingest_cursor" => VerbPresentationPolicy::AlwaysVerbose,
282 "stream.append" => VerbPresentationPolicy::StreamAppendReceipt,
283 "stream.batch" => VerbPresentationPolicy::StreamBatchReceipts,
284 "schedule.agenda" => VerbPresentationPolicy::AgendaContinuation,
285 _ => VerbPresentationPolicy::Standard,
286 }
287 }
288}
289
290/// Backward-compatible type alias. Existing code that names `VerbDef` still
291/// compiles; new code should use `HandlerDef` directly.
292#[deprecated(since = "0.2.0", note = "Use HandlerDef instead")]
293pub type VerbDef = HandlerDef;
294
295/// Match spec for one end of an [`EdgeEndpointRule`].
296///
297/// Identifies a substrate + kind pair that the rule applies to. Note that
298/// `kind` strings refer to the pack-declared note kinds / entity kinds — not
299/// the closed [`EdgeRelation`] set, which is universal.
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
301pub enum EndpointKind {
302 /// A note whose `kind` field equals the given string (e.g. `"task"`).
303 NoteOfKind(&'static str),
304 /// An entity whose `kind` field equals the given string (e.g. `"concept"`).
305 EntityOfKind(&'static str),
306 /// An entity whose base `kind` AND `entity_type` subtype both match the
307 /// given strings (e.g. `kind: "concept", entity_type: "theorem"`). Both
308 /// fields must match — enforcing the `(EntityKind, entity_type)` registry
309 /// invariant required by ADR-001:102. Required for granular entity subtypes
310 /// (formal-math theorem/definition, AMR gene/drug/pathogen): `EntityOfKind`
311 /// only sees the base kind (`"concept"`), so an `EntityOfKind("theorem")`
312 /// rule is silently inert. Additive — tightens nothing in the closed relation
313 /// set.
314 EntityOfType {
315 /// Base entity kind that must match (e.g. `"concept"`).
316 kind: &'static str,
317 /// Canonical `entity_type` subtype that must match (e.g. `"theorem"`).
318 entity_type: &'static str,
319 },
320}
321
322/// A pack-declared endpoint rule for a specific edge relation.
323///
324/// Rules are **additive**: they extend the set of allowed
325/// `(source, relation, target)` triples beyond the base contract.
326/// Packs cannot tighten the base rules — only broaden them. The closed
327/// [`EdgeRelation`] taxonomy itself is not extended; only the endpoint
328/// contract per relation is.
329///
330/// Example — GTD pack allows `depends_on` between task notes:
331///
332/// ```ignore
333/// EdgeEndpointRule {
334/// relation: EdgeRelation::DependsOn,
335/// source: EndpointKind::NoteOfKind("task"),
336/// target: EndpointKind::NoteOfKind("task"),
337/// }
338/// ```
339#[derive(Clone, Copy, Debug, PartialEq, Eq)]
340pub struct EdgeEndpointRule {
341 pub relation: EdgeRelation,
342 pub source: EndpointKind,
343 pub target: EndpointKind,
344}
345
346/// Lifecycle specification for a note kind.
347///
348/// Declares which field holds the kind's domain state, the initial value,
349/// terminal values, and allowed transitions. The runtime uses this to
350/// validate lifecycle operations at the verb boundary without hard-coding
351/// kind-specific logic in the shared CRUD path.
352///
353/// Phase 1 (current): packs declare the spec; the runtime records it for
354/// documentation and future enforcement.
355/// Phase 2 (future): the runtime uses `field` to route lifecycle writes
356/// to a first-class column rather than `properties`.
357#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct NoteLifecycleSpec {
359 /// The field name that holds the kind's lifecycle state.
360 ///
361 /// Use `"kind_status"` for pack-owned lifecycle fields to avoid the
362 /// semantic collision with `Note.status` (NoteStatus).
363 pub field: &'static str,
364 /// The value assigned when a note of this kind is first created.
365 pub initial: &'static str,
366 /// Values from which no further transitions are possible.
367 pub terminal: &'static [&'static str],
368 /// Allowed `(from, to)` transitions. `"*"` as `from` matches any state.
369 pub transitions: &'static [(&'static str, &'static str)],
370}
371
372/// Kind-level schema specification for a note kind.
373///
374/// Each pack-registered note kind may declare a `NoteKindSpec` to describe
375/// its lifecycle semantics. The runtime collects these at boot time via
376/// [`Pack::NOTE_KIND_SPECS`] for documentation, introspection, and future
377/// enforcement.
378#[derive(Clone, Debug, PartialEq, Eq)]
379pub struct NoteKindSpec {
380 /// The note kind string this spec governs (e.g. `"task"`).
381 pub kind: &'static str,
382 /// Alternate names this kind accepts on the wire.
383 pub aliases: &'static [&'static str],
384 /// Lifecycle state machine for this kind.
385 pub lifecycle: NoteLifecycleSpec,
386}
387
388/// Which registered embedding spaces a note kind writes by default.
389#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
390pub enum NoteEmbeddingPolicy {
391 #[default]
392 AllModels,
393 DefaultModel,
394}
395
396/// Pack-owned embedding policy for one declared note kind.
397#[derive(Clone, Copy, Debug, PartialEq, Eq)]
398pub struct NoteEmbeddingPolicySpec {
399 pub kind: &'static str,
400 pub policy: NoteEmbeddingPolicy,
401}
402
403/// SQLite storage type for a nullable pack-auxiliary column addition.
404#[derive(Clone, Copy, Debug, PartialEq, Eq)]
405pub enum PackColumnAffinity {
406 /// A nullable `TEXT` column with no default or primary key.
407 Text,
408 /// A nullable `INTEGER` column with no default or primary key.
409 Integer,
410}
411
412/// An idempotent nullable-column addition to a pack-owned auxiliary table.
413///
414/// Identifiers must use ASCII letters, digits, or underscores and cannot start
415/// with a digit. Existing columns must match the declared type and have no
416/// default, primary key, generated expression, or `NOT NULL` constraint. A
417/// compatible partial upgrade completes without changing existing column values.
418/// The pack's full create-table DDL must also include every declared column.
419#[derive(Clone, Copy, Debug, PartialEq, Eq)]
420pub struct PackColumnAddition {
421 /// Pack-owned auxiliary table in the backend's main schema.
422 pub table: &'static str,
423 /// Column to add when absent from an existing table.
424 pub column: &'static str,
425 /// Exact declared SQLite type required for this column.
426 pub affinity: PackColumnAffinity,
427}
428
429/// DDL statements the pack needs applied to the auxiliary schema.
430///
431/// Pack-auxiliary tables use idempotent `CREATE TABLE IF NOT EXISTS`; they are
432/// not part of the core versioned migration chain. The runtime applies these
433/// statements once at pack registration time (or startup) against the active
434/// storage backend.
435#[derive(Clone, Debug, PartialEq, Eq)]
436pub struct PackSchemaPlan {
437 /// The pack this schema plan belongs to (used for error reporting).
438 pub pack: &'static str,
439 /// Idempotent SQL statements to apply.
440 pub statements: &'static [&'static str],
441}
442
443/// A composable module that contributes vocabulary, verbs, and edge endpoint
444/// rules to the khive runtime.
445///
446/// Packs declare what entity kinds, note kinds, and verbs they introduce, and
447/// optionally extend the per-relation endpoint contract via [`EDGE_RULES`].
448/// The runtime merges vocabularies from all loaded packs and rejects
449/// unregistered kinds at the service boundary.
450///
451/// The closed [`EdgeRelation`] enum is not extensible — only its
452/// per-relation endpoint contract is extensible by packs.
453///
454/// [`EDGE_RULES`]: Pack::EDGE_RULES
455pub trait Pack {
456 /// Short identifier for this pack (e.g. "kg", "tasks").
457 const NAME: &'static str;
458
459 /// Note kinds this pack contributes to the runtime vocabulary.
460 const NOTE_KINDS: &'static [&'static str];
461
462 /// Entity kinds this pack contributes to the runtime vocabulary.
463 const ENTITY_KINDS: &'static [&'static str];
464
465 /// Brain profile consumer kinds this pack requests.
466 ///
467 /// A pack that resolves a brain profile for a consumer (for example,
468 /// `"recall"`) declares that wire-level kind here. The runtime composes
469 /// declarations from all loaded packs so `brain.bind` can reject bindings
470 /// that no registered consumer will ever request. Multiple packs may
471 /// declare the same consumer kind; composition deduplicates them.
472 ///
473 /// The `"*"` binding wildcard is registry-owned and must not be declared
474 /// by a pack.
475 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &[];
476
477 /// Handlers this pack registers.
478 ///
479 /// The runtime routes verb calls to the pack that declares them.
480 /// Only entries with `visibility: Visibility::Verb` are surfaced on the
481 /// MCP wire; `Visibility::Subhandler` entries are internal.
482 const HANDLERS: &'static [HandlerDef];
483
484 /// Additional edge endpoint rules this pack contributes.
485 ///
486 /// Defaults to empty — packs that introduce no new endpoint pairs (or
487 /// only rely on the base endpoint contract) can ignore this.
488 const EDGE_RULES: &'static [EdgeEndpointRule] = &[];
489
490 /// Entity-type subtypes this pack contributes to the `(EntityKind,
491 /// entity_type)` registry (the `entity_type` axis is distinct from and
492 /// finer-grained than the closed [`EntityKind`](crate::entity::EntityKind)
493 /// taxonomy — see `khive-types::entity_type::EntityTypeRegistry`).
494 ///
495 /// Defaults to empty, mirroring [`EDGE_RULES`]'s additive contract:
496 /// packs that introduce no new subtypes can ignore this. Entries here
497 /// are composed with `EntityTypeRegistry::builtin()` at runtime boot
498 /// (`VerbRegistry::all_entity_types`); packs must declare only new
499 /// `(kind, type_name)` pairs — they may not tighten or shadow a builtin
500 /// or another pack's declared subtype.
501 ///
502 /// [`EDGE_RULES`]: Pack::EDGE_RULES
503 const ENTITY_TYPES: &'static [EntityTypeDef] = &[];
504
505 /// Other pack names whose vocabulary this pack references.
506 ///
507 /// The runtime checks that every name in `REQUIRES` appears in the
508 /// loaded pack set before any pack is registered. Defaults to empty
509 /// so existing packs compile without changes.
510 const REQUIRES: &'static [&'static str] = &[];
511
512 /// Lifecycle and schema specs for note kinds this pack owns.
513 ///
514 /// Packs that introduce note kinds with explicit lifecycle semantics
515 /// (e.g. GTD's `task` kind) declare the spec here. The runtime collects
516 /// these at boot time for introspection and future enforcement. Defaults
517 /// to empty so existing packs compile without changes.
518 const NOTE_KIND_SPECS: &'static [NoteKindSpec] = &[];
519
520 /// Write-time embedding policy for note kinds declared in `NOTE_KINDS`.
521 /// Unlisted kinds retain the all-model default.
522 const NOTE_EMBEDDING_POLICIES: &'static [NoteEmbeddingPolicySpec] = &[];
523
524 /// Pack-auxiliary schema plan.
525 ///
526 /// Packs that need their own auxiliary tables (e.g. GTD's
527 /// `gtd_lifecycle_audit`) declare idempotent DDL statements here.
528 /// The runtime applies them once at registration time. Defaults to
529 /// `None` so packs with no auxiliary schema cost nothing.
530 const SCHEMA_PLAN: Option<PackSchemaPlan> = None;
531
532 /// Nullable-column upgrades for this pack's auxiliary tables.
533 ///
534 /// The backend validates and adds missing columns on existing tables before
535 /// applying [`Self::SCHEMA_PLAN`], then validates the final schema. The
536 /// entire plan is transactional. Absent tables are created only by the
537 /// pack's full DDL, so unloaded packs do not acquire auxiliary tables.
538 const SCHEMA_COLUMN_ADDITIONS: &'static [PackColumnAddition] = &[];
539
540 /// Validation rule IDs contributed by this pack.
541 ///
542 /// Rule IDs are namespaced by pack name: `<pack-name>/<rule-id>`.
543 /// The runtime merges rule IDs from all packs; the actual rule
544 /// implementations live in `khive-runtime::validation::ValidationRule`
545 /// (not in `khive-types`, which stays `no_std`). This const serves as
546 /// the declarative catalog of rule identifiers so the validation
547 /// infrastructure can enumerate what rules a pack claims without
548 /// loading the runtime.
549 ///
550 /// Defaults to empty — packs with no domain-specific validation rules
551 /// can leave this unset.
552 const VALIDATION_RULES: &'static [&'static str] = &[];
553}
554
555/// ADR-099 D3 — the v1 atomic-admissible verb set for `--atomic` bulk apply.
556///
557/// This is an EXPLICIT per-verb allowlist, never derived from [`VerbCategory`]
558/// or any other classification ("never a pack-level category", ADR-099 D3).
559/// Every verb here has a prepare/apply seam whose in-transaction phase reduces
560/// to synchronous DML — the atomic-unit suspend-free invariant
561/// (`SqlAccess::atomic_unit` in `khive-storage`). Extending this list is a
562/// design decision (ADR-099 amendment), not a code-review-only change; the
563/// `atomic_admissible_list_matches_adr` test below pins this exact set so an
564/// edit here forces the editor to touch that test and its ADR citation.
565pub const ATOMIC_ADMISSIBLE_VERBS: &[&str] = &[
566 "update",
567 "delete",
568 "link",
569 "merge",
570 "gtd.transition",
571 "gtd.complete",
572 "propose",
573 "review",
574 "withdraw",
575];
576
577/// Verbs rejected under `--atomic` because their write still computes an
578/// embedding synchronously and no prepare/apply seam hoists that embedding
579/// out of the transaction yet (ADR-099 D3, "v1 rejected — embedding-bearing").
580const ATOMIC_EMBEDDING_BEARING_VERBS: &[&str] = &[
581 "create",
582 "memory.remember",
583 "gtd.assign",
584 "comm.send",
585 "comm.reply",
586 "comm.ingest",
587];
588
589/// Verbs on [`ATOMIC_ADMISSIBLE_VERBS`] (ADR-099 D3 conceptually admissible)
590/// that have no *full-parity* prepare/apply seam yet, so they are rejected up
591/// front (checked BEFORE the general admissible-list check) rather than
592/// admitted with a silent gap. See
593/// crates/khive-types/docs/api/pack.md#adr-099-d3-atomic-admissibility-rejection-classes
594/// for why each verb is deferred and the ADR-099 B3 ordering rationale.
595pub const ATOMIC_KNOWN_UNIMPLEMENTED_VERBS: &[&str] = &["propose", "review", "withdraw", "merge"];
596
597/// Read verbs rejected under `--atomic` — they produce no write plan to apply
598/// (ADR-099 D3, "v1 rejected — reads").
599const ATOMIC_READ_VERBS: &[&str] = &[
600 "search",
601 "recall",
602 "query",
603 "traverse",
604 "list",
605 "get",
606 "neighbors",
607 "context",
608 "stats",
609 "verbs",
610];
611
612/// Conservative default maximum op count for one `--atomic` unit (ADR-099
613/// migration step 7 / B3). Override per invocation with
614/// `kkernel exec --atomic --atomic-max-ops N`. See
615/// crates/khive-types/docs/api/pack.md#atomic_max_ops_default--2000--rationale
616/// for why 2000 specifically was chosen and when to revisit it.
617pub const ATOMIC_MAX_OPS_DEFAULT: usize = 2000;
618
619/// Why a verb was rejected from an `--atomic` op list (ADR-099 D3, migration
620/// step 2). Distinguishes the two named rejection classes from a generic
621/// "not yet admitted" fallback so callers can produce an actionable message.
622#[derive(Clone, Copy, Debug, PartialEq, Eq)]
623pub enum AtomicRejectionReason {
624 /// The verb still computes an embedding synchronously in its write path.
625 EmbeddingBearing,
626 /// The verb is a read — it has no write plan to apply.
627 Read,
628 /// Neither on the v1 admissible list nor a known rejected category (e.g.
629 /// a verb added after this list was written). Rejected by default —
630 /// admissibility is opt-in, never inferred.
631 Unlisted,
632 /// On [`ATOMIC_ADMISSIBLE_VERBS`] per ADR-099 D3 (conceptually admissible,
633 /// intended to gain a seam) but has no prepare/apply implementation in
634 /// this slice yet ([`ATOMIC_KNOWN_UNIMPLEMENTED_VERBS`]). Rejected at the
635 /// same pre-runtime static-guard stage as every other rejection reason —
636 /// never silently no-opped, never deferred until after a runtime/write
637 /// attempt.
638 KnownUnimplemented,
639}
640
641/// Static admissibility classification for `verb_name` under ADR-099
642/// `--atomic` bulk apply.
643///
644/// Returns `None` when the verb is admissible; `Some(reason)` names why it is
645/// rejected. Default-deny: a verb name absent from every list here is
646/// [`AtomicRejectionReason::Unlisted`], never silently admitted.
647///
648/// `ATOMIC_KNOWN_UNIMPLEMENTED_VERBS` is checked BEFORE the general
649/// admissible-list membership check (ADR-099 B3): those
650/// verbs are members of `ATOMIC_ADMISSIBLE_VERBS`, so checking membership
651/// first would admit them (`None`) and defer their rejection to prepare time,
652/// after a runtime has already been constructed.
653pub fn atomic_admissibility(verb_name: &str) -> Option<AtomicRejectionReason> {
654 if ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(&verb_name) {
655 return Some(AtomicRejectionReason::KnownUnimplemented);
656 }
657 if ATOMIC_ADMISSIBLE_VERBS.contains(&verb_name) {
658 return None;
659 }
660 if ATOMIC_EMBEDDING_BEARING_VERBS.contains(&verb_name) {
661 return Some(AtomicRejectionReason::EmbeddingBearing);
662 }
663 if ATOMIC_READ_VERBS.contains(&verb_name) {
664 return Some(AtomicRejectionReason::Read);
665 }
666 Some(AtomicRejectionReason::Unlisted)
667}
668
669#[cfg(test)]
670mod tests {
671 use super::*;
672
673 struct TestPack;
674
675 impl Pack for TestPack {
676 const NAME: &'static str = "test";
677 const NOTE_KINDS: &'static [&'static str] = &["memo"];
678 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
679 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
680 name: "do_thing",
681 description: "does a thing",
682 visibility: Visibility::Verb,
683 category: VerbCategory::Commissive,
684 params: &[],
685 }];
686 }
687
688 #[test]
689 fn pack_trait_compiles() {
690 assert_eq!(TestPack::NAME, "test");
691 assert_eq!(TestPack::NOTE_KINDS, &["memo"]);
692 assert_eq!(TestPack::ENTITY_KINDS, &["widget"]);
693 assert_eq!(TestPack::HANDLERS.len(), 1);
694 assert_eq!(TestPack::HANDLERS[0].name, "do_thing");
695 assert_eq!(TestPack::HANDLERS[0].visibility, Visibility::Verb);
696 assert_eq!(TestPack::HANDLERS[0].category, VerbCategory::Commissive);
697 }
698
699 #[test]
700 fn verb_category_variants_exist() {
701 // Just ensuring the enum variants are accessible — no runtime assertion
702 // needed beyond confirming they exist at compile time.
703 let _ = VerbCategory::Assertive;
704 let _ = VerbCategory::Directive;
705 let _ = VerbCategory::Commissive;
706 let _ = VerbCategory::Declaration;
707 }
708
709 #[test]
710 fn pack_validation_rules_default_empty() {
711 assert!(TestPack::VALIDATION_RULES.is_empty());
712 }
713
714 #[test]
715 fn pack_entity_types_default_empty() {
716 assert!(TestPack::ENTITY_TYPES.is_empty());
717 }
718
719 // `link` must be AlwaysVerbose so edge IDs are not shortened.
720 #[test]
721 fn link_handler_is_always_verbose() {
722 let link_def = HandlerDef {
723 name: "link",
724 description: "Create a typed directed edge",
725 visibility: Visibility::Verb,
726 category: VerbCategory::Commissive,
727 params: &[],
728 };
729 assert_eq!(
730 link_def.presentation_policy(),
731 VerbPresentationPolicy::AlwaysVerbose,
732 "link must be AlwaysVerbose"
733 );
734 }
735
736 // AlwaysVerbose set regression: protect every identifier-bearing contract.
737 #[test]
738 fn always_verbose_set_contains_expected_verbs() {
739 let always_verbose = [
740 "get",
741 "link",
742 "query",
743 "traverse",
744 "neighbors",
745 "brain.feedback",
746 "brain.auto_feedback",
747 "memory.feedback",
748 "comm.delivered",
749 "comm.transport_status",
750 "git.digest",
751 "git.ingest_cursor",
752 ];
753 for name in always_verbose {
754 let h = HandlerDef {
755 name,
756 description: "",
757 visibility: Visibility::Verb,
758 category: VerbCategory::Assertive,
759 params: &[],
760 };
761 assert_eq!(
762 h.presentation_policy(),
763 VerbPresentationPolicy::AlwaysVerbose,
764 "{name:?} must be AlwaysVerbose"
765 );
766 }
767 }
768
769 #[test]
770 fn stream_receipt_policies_are_closed_to_the_registered_writers() {
771 for (name, policy) in [
772 ("stream.append", VerbPresentationPolicy::StreamAppendReceipt),
773 ("stream.batch", VerbPresentationPolicy::StreamBatchReceipts),
774 ("stream.read", VerbPresentationPolicy::Standard),
775 ("stream.batch.other", VerbPresentationPolicy::Standard),
776 ("list", VerbPresentationPolicy::Standard),
777 ] {
778 let handler = HandlerDef {
779 name,
780 description: "",
781 visibility: Visibility::Verb,
782 category: VerbCategory::Commissive,
783 params: &[],
784 };
785 assert_eq!(handler.presentation_policy(), policy, "{name}");
786 }
787 }
788
789 // Standard policy for all other verbs.
790 #[test]
791 fn non_verbose_verbs_are_standard_policy() {
792 let standard = [
793 "create", "list", "update", "delete", "search", "recall", "remember",
794 ];
795 for name in standard {
796 let h = HandlerDef {
797 name,
798 description: "",
799 visibility: Visibility::Verb,
800 category: VerbCategory::Commissive,
801 params: &[],
802 };
803 assert_eq!(
804 h.presentation_policy(),
805 VerbPresentationPolicy::Standard,
806 "{name:?} must be Standard (not AlwaysVerbose)"
807 );
808 }
809 }
810
811 // ── ADR-099 D3 atomic admissibility ────────────────────────────────────
812
813 // Drift-pin: a hardcoded copy of the ADR-099 D3 v1 admissible list. If
814 // someone edits `ATOMIC_ADMISSIBLE_VERBS`, this test fails until they also
815 // update this literal — forcing a look at ADR-099 D3 ("Decision: admit
816 // only verbs that expose a prepare/apply seam...") before the set changes.
817 #[test]
818 fn atomic_admissible_list_matches_adr099_d3() {
819 let adr_099_d3_v1_admissible_set: &[&str] = &[
820 "update",
821 "delete",
822 "link",
823 "merge",
824 "gtd.transition",
825 "gtd.complete",
826 "propose",
827 "review",
828 "withdraw",
829 ];
830 assert_eq!(
831 ATOMIC_ADMISSIBLE_VERBS, adr_099_d3_v1_admissible_set,
832 "ATOMIC_ADMISSIBLE_VERBS drifted from ADR-099 D3's explicit v1 list"
833 );
834 }
835
836 #[test]
837 fn atomic_admissible_verbs_are_admitted() {
838 for verb in ATOMIC_ADMISSIBLE_VERBS {
839 // Governance verbs are on ATOMIC_ADMISSIBLE_VERBS per ADR-099 D3
840 // (conceptually admissible) but are checked separately below:
841 // they are rejected at this same static layer for a distinct
842 // reason (KnownUnimplemented), not admitted (None).
843 if ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(verb) {
844 continue;
845 }
846 assert_eq!(
847 atomic_admissibility(verb),
848 None,
849 "{verb:?} is on the v1 admissible list and must be admitted"
850 );
851 }
852 }
853
854 #[test]
855 fn atomic_known_unimplemented_verbs_rejected_before_runtime() {
856 // ADR-099 B3: propose/review/withdraw
857 // remain on ATOMIC_ADMISSIBLE_VERBS (ADR-099 D3 intends them to gain a
858 // seam) but must be rejected at this SAME static pre-runtime guard —
859 // not admitted here and only failed later inside
860 // `atomic_prepare::prepare_op` after a runtime was already built.
861 for verb in ATOMIC_KNOWN_UNIMPLEMENTED_VERBS {
862 assert!(
863 ATOMIC_ADMISSIBLE_VERBS.contains(verb),
864 "{verb:?} must remain on ATOMIC_ADMISSIBLE_VERBS per ADR-099 D3"
865 );
866 assert_eq!(
867 atomic_admissibility(verb),
868 Some(AtomicRejectionReason::KnownUnimplemented),
869 "{verb:?} must be rejected as known-unimplemented, not admitted"
870 );
871 }
872 }
873
874 #[test]
875 fn atomic_embedding_bearing_verbs_rejected_named() {
876 for verb in [
877 "create",
878 "memory.remember",
879 "gtd.assign",
880 "comm.send",
881 "comm.reply",
882 ] {
883 assert_eq!(
884 atomic_admissibility(verb),
885 Some(AtomicRejectionReason::EmbeddingBearing),
886 "{verb:?} must be rejected as embedding-bearing (ADR-099 acceptance criteria)"
887 );
888 }
889 }
890
891 #[test]
892 fn atomic_read_verbs_rejected() {
893 for verb in [
894 "search",
895 "recall",
896 "query",
897 "traverse",
898 "list",
899 "get",
900 "neighbors",
901 "context",
902 ] {
903 assert_eq!(
904 atomic_admissibility(verb),
905 Some(AtomicRejectionReason::Read),
906 "{verb:?} must be rejected as a read verb"
907 );
908 }
909 }
910
911 #[test]
912 fn atomic_unknown_verb_defaults_to_unlisted_rejection() {
913 assert_eq!(
914 atomic_admissibility("some_future_verb_nobody_classified_yet"),
915 Some(AtomicRejectionReason::Unlisted),
916 "an unrecognized verb must default-deny, never silently admit"
917 );
918 }
919}