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/// Declared ownership policy for one note property.
389///
390/// This metadata does not itself enforce writes or grant authority.
391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
392pub enum PropertyPolicy {
393 /// The substrate or owning pack derives this property from trusted runtime context.
394 Derived,
395 /// Only the owning pack's specialized writer establishes this property.
396 OwnerOnly,
397}
398
399/// Property policy for a note kind declared by the same pack.
400#[derive(Clone, Copy, Debug, PartialEq, Eq)]
401pub struct NotePropertyPolicySpec {
402 /// The owned note kind.
403 pub kind: &'static str,
404 /// The exact property key, without normalization.
405 pub key: &'static str,
406 /// The property's declared ownership policy.
407 pub policy: PropertyPolicy,
408}
409
410/// Which registered embedding spaces a note kind writes by default.
411#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
412pub enum NoteEmbeddingPolicy {
413 #[default]
414 AllModels,
415 DefaultModel,
416}
417
418/// Pack-owned embedding policy for one declared note kind.
419#[derive(Clone, Copy, Debug, PartialEq, Eq)]
420pub struct NoteEmbeddingPolicySpec {
421 pub kind: &'static str,
422 pub policy: NoteEmbeddingPolicy,
423}
424
425/// SQLite storage type for a nullable pack-auxiliary column addition.
426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
427pub enum PackColumnAffinity {
428 /// A nullable `TEXT` column with no default or primary key.
429 Text,
430 /// A nullable `INTEGER` column with no default or primary key.
431 Integer,
432}
433
434/// An idempotent nullable-column addition to a pack-owned auxiliary table.
435///
436/// Identifiers must use ASCII letters, digits, or underscores and cannot start
437/// with a digit. Existing columns must match the declared type and have no
438/// default, primary key, generated expression, or `NOT NULL` constraint. A
439/// compatible partial upgrade completes without changing existing column values.
440/// The pack's full create-table DDL must also include every declared column.
441#[derive(Clone, Copy, Debug, PartialEq, Eq)]
442pub struct PackColumnAddition {
443 /// Pack-owned auxiliary table in the backend's main schema.
444 pub table: &'static str,
445 /// Column to add when absent from an existing table.
446 pub column: &'static str,
447 /// Exact declared SQLite type required for this column.
448 pub affinity: PackColumnAffinity,
449}
450
451/// DDL statements the pack needs applied to the auxiliary schema.
452///
453/// Pack-auxiliary tables use idempotent `CREATE TABLE IF NOT EXISTS`; they are
454/// not part of the core versioned migration chain. The runtime applies these
455/// statements once at pack registration time (or startup) against the active
456/// storage backend.
457#[derive(Clone, Debug, PartialEq, Eq)]
458pub struct PackSchemaPlan {
459 /// The pack this schema plan belongs to (used for error reporting).
460 pub pack: &'static str,
461 /// Idempotent SQL statements to apply.
462 pub statements: &'static [&'static str],
463}
464
465/// A composable module that contributes vocabulary, verbs, and edge endpoint
466/// rules to the khive runtime.
467///
468/// Packs declare what entity kinds, note kinds, and verbs they introduce, and
469/// optionally extend the per-relation endpoint contract via [`EDGE_RULES`].
470/// The runtime merges vocabularies from all loaded packs and rejects
471/// unregistered kinds at the service boundary.
472///
473/// The closed [`EdgeRelation`] enum is not extensible — only its
474/// per-relation endpoint contract is extensible by packs.
475///
476/// [`EDGE_RULES`]: Pack::EDGE_RULES
477pub trait Pack {
478 /// Short identifier for this pack (e.g. "kg", "tasks").
479 const NAME: &'static str;
480
481 /// Note kinds this pack contributes to the runtime vocabulary.
482 const NOTE_KINDS: &'static [&'static str];
483
484 /// Entity kinds this pack contributes to the runtime vocabulary.
485 const ENTITY_KINDS: &'static [&'static str];
486
487 /// Brain profile consumer kinds this pack requests.
488 ///
489 /// A pack that resolves a brain profile for a consumer (for example,
490 /// `"recall"`) declares that wire-level kind here. The runtime composes
491 /// declarations from all loaded packs so `brain.bind` can reject bindings
492 /// that no registered consumer will ever request. Multiple packs may
493 /// declare the same consumer kind; composition deduplicates them.
494 ///
495 /// The `"*"` binding wildcard is registry-owned and must not be declared
496 /// by a pack.
497 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &[];
498
499 /// Handlers this pack registers.
500 ///
501 /// The runtime routes verb calls to the pack that declares them.
502 /// Only entries with `visibility: Visibility::Verb` are surfaced on the
503 /// MCP wire; `Visibility::Subhandler` entries are internal.
504 const HANDLERS: &'static [HandlerDef];
505
506 /// Additional edge endpoint rules this pack contributes.
507 ///
508 /// Defaults to empty — packs that introduce no new endpoint pairs (or
509 /// only rely on the base endpoint contract) can ignore this.
510 const EDGE_RULES: &'static [EdgeEndpointRule] = &[];
511
512 /// Entity-type subtypes this pack contributes to the `(EntityKind,
513 /// entity_type)` registry (the `entity_type` axis is distinct from and
514 /// finer-grained than the closed [`EntityKind`](crate::entity::EntityKind)
515 /// taxonomy — see `khive-types::entity_type::EntityTypeRegistry`).
516 ///
517 /// Defaults to empty, mirroring [`EDGE_RULES`]'s additive contract:
518 /// packs that introduce no new subtypes can ignore this. Entries here
519 /// are composed with `EntityTypeRegistry::builtin()` at runtime boot
520 /// (`VerbRegistry::all_entity_types`); packs must declare only new
521 /// `(kind, type_name)` pairs — they may not tighten or shadow a builtin
522 /// or another pack's declared subtype.
523 ///
524 /// [`EDGE_RULES`]: Pack::EDGE_RULES
525 const ENTITY_TYPES: &'static [EntityTypeDef] = &[];
526
527 /// Other pack names whose vocabulary this pack references.
528 ///
529 /// The runtime checks that every name in `REQUIRES` appears in the
530 /// loaded pack set before any pack is registered. Defaults to empty
531 /// so existing packs compile without changes.
532 const REQUIRES: &'static [&'static str] = &[];
533
534 /// Lifecycle and schema specs for note kinds this pack owns.
535 ///
536 /// Packs that introduce note kinds with explicit lifecycle semantics
537 /// (e.g. GTD's `task` kind) declare the spec here. The runtime collects
538 /// these at boot time for introspection and future enforcement. Defaults
539 /// to empty so existing packs compile without changes.
540 const NOTE_KIND_SPECS: &'static [NoteKindSpec] = &[];
541
542 /// Property policies for note kinds owned by this pack.
543 ///
544 /// Mirror this slice through `PackRuntime::note_property_policies`. The
545 /// registry validates and snapshots it at boot; declarations alone do not
546 /// change write enforcement. Unlisted keys carry no declared restriction.
547 const NOTE_PROPERTY_POLICIES: &'static [NotePropertyPolicySpec] = &[];
548
549 /// Write-time embedding policy for note kinds declared in `NOTE_KINDS`.
550 /// Unlisted kinds retain the all-model default.
551 const NOTE_EMBEDDING_POLICIES: &'static [NoteEmbeddingPolicySpec] = &[];
552
553 /// Pack-auxiliary schema plan.
554 ///
555 /// Packs that need their own auxiliary tables (e.g. GTD's
556 /// `gtd_lifecycle_audit`) declare idempotent DDL statements here.
557 /// The runtime applies them once at registration time. Defaults to
558 /// `None` so packs with no auxiliary schema cost nothing.
559 const SCHEMA_PLAN: Option<PackSchemaPlan> = None;
560
561 /// Nullable-column upgrades for this pack's auxiliary tables.
562 ///
563 /// The backend validates and adds missing columns on existing tables before
564 /// applying [`Self::SCHEMA_PLAN`], then validates the final schema. The
565 /// entire plan is transactional. Absent tables are created only by the
566 /// pack's full DDL, so unloaded packs do not acquire auxiliary tables.
567 const SCHEMA_COLUMN_ADDITIONS: &'static [PackColumnAddition] = &[];
568
569 /// Validation rule IDs contributed by this pack.
570 ///
571 /// Rule IDs are namespaced by pack name: `<pack-name>/<rule-id>`.
572 /// The runtime merges rule IDs from all packs; the actual rule
573 /// implementations live in `khive-runtime::validation::ValidationRule`
574 /// (not in `khive-types`, which stays `no_std`). This const serves as
575 /// the declarative catalog of rule identifiers so the validation
576 /// infrastructure can enumerate what rules a pack claims without
577 /// loading the runtime.
578 ///
579 /// Defaults to empty — packs with no domain-specific validation rules
580 /// can leave this unset.
581 const VALIDATION_RULES: &'static [&'static str] = &[];
582}
583
584/// ADR-099 D3 — the v1 atomic-admissible verb set for `--atomic` bulk apply.
585///
586/// This is an EXPLICIT per-verb allowlist, never derived from [`VerbCategory`]
587/// or any other classification ("never a pack-level category", ADR-099 D3).
588/// Every verb here has a prepare/apply seam whose in-transaction phase reduces
589/// to synchronous DML — the atomic-unit suspend-free invariant
590/// (`SqlAccess::atomic_unit` in `khive-storage`). Extending this list is a
591/// design decision (ADR-099 amendment), not a code-review-only change; the
592/// `atomic_admissible_list_matches_adr` test below pins this exact set so an
593/// edit here forces the editor to touch that test and its ADR citation.
594pub const ATOMIC_ADMISSIBLE_VERBS: &[&str] = &[
595 "update",
596 "delete",
597 "link",
598 "merge",
599 "gtd.transition",
600 "gtd.complete",
601 "propose",
602 "review",
603 "withdraw",
604];
605
606/// Verbs rejected under `--atomic` because their write still computes an
607/// embedding synchronously and no prepare/apply seam hoists that embedding
608/// out of the transaction yet (ADR-099 D3, "v1 rejected — embedding-bearing").
609const ATOMIC_EMBEDDING_BEARING_VERBS: &[&str] = &[
610 "create",
611 "memory.remember",
612 "gtd.assign",
613 "comm.send",
614 "comm.reply",
615 "comm.ingest",
616];
617
618/// Verbs on [`ATOMIC_ADMISSIBLE_VERBS`] (ADR-099 D3 conceptually admissible)
619/// that have no *full-parity* prepare/apply seam yet, so they are rejected up
620/// front (checked BEFORE the general admissible-list check) rather than
621/// admitted with a silent gap. See
622/// crates/khive-types/docs/api/pack.md#adr-099-d3-atomic-admissibility-rejection-classes
623/// for why each verb is deferred and the ADR-099 B3 ordering rationale.
624pub const ATOMIC_KNOWN_UNIMPLEMENTED_VERBS: &[&str] = &["propose", "review", "withdraw", "merge"];
625
626/// Read verbs rejected under `--atomic` — they produce no write plan to apply
627/// (ADR-099 D3, "v1 rejected — reads").
628const ATOMIC_READ_VERBS: &[&str] = &[
629 "search",
630 "recall",
631 "query",
632 "traverse",
633 "list",
634 "get",
635 "neighbors",
636 "context",
637 "stats",
638 "verbs",
639];
640
641/// Conservative default maximum op count for one `--atomic` unit (ADR-099
642/// migration step 7 / B3). Override per invocation with
643/// `kkernel exec --atomic --atomic-max-ops N`. See
644/// crates/khive-types/docs/api/pack.md#atomic_max_ops_default--2000--rationale
645/// for why 2000 specifically was chosen and when to revisit it.
646pub const ATOMIC_MAX_OPS_DEFAULT: usize = 2000;
647
648/// Why a verb was rejected from an `--atomic` op list (ADR-099 D3, migration
649/// step 2). Distinguishes the two named rejection classes from a generic
650/// "not yet admitted" fallback so callers can produce an actionable message.
651#[derive(Clone, Copy, Debug, PartialEq, Eq)]
652pub enum AtomicRejectionReason {
653 /// The verb still computes an embedding synchronously in its write path.
654 EmbeddingBearing,
655 /// The verb is a read — it has no write plan to apply.
656 Read,
657 /// Neither on the v1 admissible list nor a known rejected category (e.g.
658 /// a verb added after this list was written). Rejected by default —
659 /// admissibility is opt-in, never inferred.
660 Unlisted,
661 /// On [`ATOMIC_ADMISSIBLE_VERBS`] per ADR-099 D3 (conceptually admissible,
662 /// intended to gain a seam) but has no prepare/apply implementation in
663 /// this slice yet ([`ATOMIC_KNOWN_UNIMPLEMENTED_VERBS`]). Rejected at the
664 /// same pre-runtime static-guard stage as every other rejection reason —
665 /// never silently no-opped, never deferred until after a runtime/write
666 /// attempt.
667 KnownUnimplemented,
668}
669
670/// Static admissibility classification for `verb_name` under ADR-099
671/// `--atomic` bulk apply.
672///
673/// Returns `None` when the verb is admissible; `Some(reason)` names why it is
674/// rejected. Default-deny: a verb name absent from every list here is
675/// [`AtomicRejectionReason::Unlisted`], never silently admitted.
676///
677/// `ATOMIC_KNOWN_UNIMPLEMENTED_VERBS` is checked BEFORE the general
678/// admissible-list membership check (ADR-099 B3): those
679/// verbs are members of `ATOMIC_ADMISSIBLE_VERBS`, so checking membership
680/// first would admit them (`None`) and defer their rejection to prepare time,
681/// after a runtime has already been constructed.
682pub fn atomic_admissibility(verb_name: &str) -> Option<AtomicRejectionReason> {
683 if ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(&verb_name) {
684 return Some(AtomicRejectionReason::KnownUnimplemented);
685 }
686 if ATOMIC_ADMISSIBLE_VERBS.contains(&verb_name) {
687 return None;
688 }
689 if ATOMIC_EMBEDDING_BEARING_VERBS.contains(&verb_name) {
690 return Some(AtomicRejectionReason::EmbeddingBearing);
691 }
692 if ATOMIC_READ_VERBS.contains(&verb_name) {
693 return Some(AtomicRejectionReason::Read);
694 }
695 Some(AtomicRejectionReason::Unlisted)
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701
702 struct TestPack;
703
704 impl Pack for TestPack {
705 const NAME: &'static str = "test";
706 const NOTE_KINDS: &'static [&'static str] = &["memo"];
707 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
708 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
709 name: "do_thing",
710 description: "does a thing",
711 visibility: Visibility::Verb,
712 category: VerbCategory::Commissive,
713 params: &[],
714 }];
715 }
716
717 #[test]
718 fn pack_trait_compiles() {
719 assert_eq!(TestPack::NAME, "test");
720 assert_eq!(TestPack::NOTE_KINDS, &["memo"]);
721 assert_eq!(TestPack::ENTITY_KINDS, &["widget"]);
722 assert_eq!(TestPack::HANDLERS.len(), 1);
723 assert_eq!(TestPack::HANDLERS[0].name, "do_thing");
724 assert_eq!(TestPack::HANDLERS[0].visibility, Visibility::Verb);
725 assert_eq!(TestPack::HANDLERS[0].category, VerbCategory::Commissive);
726 }
727
728 #[test]
729 fn verb_category_variants_exist() {
730 // Just ensuring the enum variants are accessible — no runtime assertion
731 // needed beyond confirming they exist at compile time.
732 let _ = VerbCategory::Assertive;
733 let _ = VerbCategory::Directive;
734 let _ = VerbCategory::Commissive;
735 let _ = VerbCategory::Declaration;
736 }
737
738 #[test]
739 fn pack_validation_rules_default_empty() {
740 assert!(TestPack::VALIDATION_RULES.is_empty());
741 }
742
743 #[test]
744 fn pack_entity_types_default_empty() {
745 assert!(TestPack::ENTITY_TYPES.is_empty());
746 }
747
748 // `link` must be AlwaysVerbose so edge IDs are not shortened.
749 #[test]
750 fn link_handler_is_always_verbose() {
751 let link_def = HandlerDef {
752 name: "link",
753 description: "Create a typed directed edge",
754 visibility: Visibility::Verb,
755 category: VerbCategory::Commissive,
756 params: &[],
757 };
758 assert_eq!(
759 link_def.presentation_policy(),
760 VerbPresentationPolicy::AlwaysVerbose,
761 "link must be AlwaysVerbose"
762 );
763 }
764
765 // AlwaysVerbose set regression: protect every identifier-bearing contract.
766 #[test]
767 fn always_verbose_set_contains_expected_verbs() {
768 let always_verbose = [
769 "get",
770 "link",
771 "query",
772 "traverse",
773 "neighbors",
774 "brain.feedback",
775 "brain.auto_feedback",
776 "memory.feedback",
777 "comm.delivered",
778 "comm.transport_status",
779 "git.digest",
780 "git.ingest_cursor",
781 ];
782 for name in always_verbose {
783 let h = HandlerDef {
784 name,
785 description: "",
786 visibility: Visibility::Verb,
787 category: VerbCategory::Assertive,
788 params: &[],
789 };
790 assert_eq!(
791 h.presentation_policy(),
792 VerbPresentationPolicy::AlwaysVerbose,
793 "{name:?} must be AlwaysVerbose"
794 );
795 }
796 }
797
798 #[test]
799 fn stream_receipt_policies_are_closed_to_the_registered_writers() {
800 for (name, policy) in [
801 ("stream.append", VerbPresentationPolicy::StreamAppendReceipt),
802 ("stream.batch", VerbPresentationPolicy::StreamBatchReceipts),
803 ("stream.read", VerbPresentationPolicy::Standard),
804 ("stream.batch.other", VerbPresentationPolicy::Standard),
805 ("list", VerbPresentationPolicy::Standard),
806 ] {
807 let handler = HandlerDef {
808 name,
809 description: "",
810 visibility: Visibility::Verb,
811 category: VerbCategory::Commissive,
812 params: &[],
813 };
814 assert_eq!(handler.presentation_policy(), policy, "{name}");
815 }
816 }
817
818 // Standard policy for all other verbs.
819 #[test]
820 fn non_verbose_verbs_are_standard_policy() {
821 let standard = [
822 "create", "list", "update", "delete", "search", "recall", "remember",
823 ];
824 for name in standard {
825 let h = HandlerDef {
826 name,
827 description: "",
828 visibility: Visibility::Verb,
829 category: VerbCategory::Commissive,
830 params: &[],
831 };
832 assert_eq!(
833 h.presentation_policy(),
834 VerbPresentationPolicy::Standard,
835 "{name:?} must be Standard (not AlwaysVerbose)"
836 );
837 }
838 }
839
840 // ── ADR-099 D3 atomic admissibility ────────────────────────────────────
841
842 // Drift-pin: a hardcoded copy of the ADR-099 D3 v1 admissible list. If
843 // someone edits `ATOMIC_ADMISSIBLE_VERBS`, this test fails until they also
844 // update this literal — forcing a look at ADR-099 D3 ("Decision: admit
845 // only verbs that expose a prepare/apply seam...") before the set changes.
846 #[test]
847 fn atomic_admissible_list_matches_adr099_d3() {
848 let adr_099_d3_v1_admissible_set: &[&str] = &[
849 "update",
850 "delete",
851 "link",
852 "merge",
853 "gtd.transition",
854 "gtd.complete",
855 "propose",
856 "review",
857 "withdraw",
858 ];
859 assert_eq!(
860 ATOMIC_ADMISSIBLE_VERBS, adr_099_d3_v1_admissible_set,
861 "ATOMIC_ADMISSIBLE_VERBS drifted from ADR-099 D3's explicit v1 list"
862 );
863 }
864
865 #[test]
866 fn atomic_admissible_verbs_are_admitted() {
867 for verb in ATOMIC_ADMISSIBLE_VERBS {
868 // Governance verbs are on ATOMIC_ADMISSIBLE_VERBS per ADR-099 D3
869 // (conceptually admissible) but are checked separately below:
870 // they are rejected at this same static layer for a distinct
871 // reason (KnownUnimplemented), not admitted (None).
872 if ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(verb) {
873 continue;
874 }
875 assert_eq!(
876 atomic_admissibility(verb),
877 None,
878 "{verb:?} is on the v1 admissible list and must be admitted"
879 );
880 }
881 }
882
883 #[test]
884 fn atomic_known_unimplemented_verbs_rejected_before_runtime() {
885 // ADR-099 B3: propose/review/withdraw
886 // remain on ATOMIC_ADMISSIBLE_VERBS (ADR-099 D3 intends them to gain a
887 // seam) but must be rejected at this SAME static pre-runtime guard —
888 // not admitted here and only failed later inside
889 // `atomic_prepare::prepare_op` after a runtime was already built.
890 for verb in ATOMIC_KNOWN_UNIMPLEMENTED_VERBS {
891 assert!(
892 ATOMIC_ADMISSIBLE_VERBS.contains(verb),
893 "{verb:?} must remain on ATOMIC_ADMISSIBLE_VERBS per ADR-099 D3"
894 );
895 assert_eq!(
896 atomic_admissibility(verb),
897 Some(AtomicRejectionReason::KnownUnimplemented),
898 "{verb:?} must be rejected as known-unimplemented, not admitted"
899 );
900 }
901 }
902
903 #[test]
904 fn atomic_embedding_bearing_verbs_rejected_named() {
905 for verb in [
906 "create",
907 "memory.remember",
908 "gtd.assign",
909 "comm.send",
910 "comm.reply",
911 ] {
912 assert_eq!(
913 atomic_admissibility(verb),
914 Some(AtomicRejectionReason::EmbeddingBearing),
915 "{verb:?} must be rejected as embedding-bearing (ADR-099 acceptance criteria)"
916 );
917 }
918 }
919
920 #[test]
921 fn atomic_read_verbs_rejected() {
922 for verb in [
923 "search",
924 "recall",
925 "query",
926 "traverse",
927 "list",
928 "get",
929 "neighbors",
930 "context",
931 ] {
932 assert_eq!(
933 atomic_admissibility(verb),
934 Some(AtomicRejectionReason::Read),
935 "{verb:?} must be rejected as a read verb"
936 );
937 }
938 }
939
940 #[test]
941 fn atomic_unknown_verb_defaults_to_unlisted_rejection() {
942 assert_eq!(
943 atomic_admissibility("some_future_verb_nobody_classified_yet"),
944 Some(AtomicRejectionReason::Unlisted),
945 "an unrecognized verb must default-deny, never silently admit"
946 );
947 }
948}