Skip to main content

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