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 required root fields of an opted-in GTD page in Agent mode.
260    GtdTaskPage,
261    /// Preserve the root agenda continuation and empty event array in Agent mode.
262    /// Event rows retain the ordinary metadata transform.
263    AgendaContinuation,
264    /// Keep the root sessions array on an empty session list in Agent mode.
265    SessionList,
266    /// Compact direct recall rows in Agent presentation while retaining the
267    /// full canonical response for chains and Verbose/Human presentation.
268    RecallCompact,
269}
270
271impl HandlerDef {
272    /// Resolve the presentation policy for this handler.
273    ///
274    /// Returns [`VerbPresentationPolicy::AlwaysVerbose`] for verbs whose
275    /// semantics demand full output (full UUIDs, complete timestamps) regardless
276    /// of the caller's requested presentation mode.
277    ///
278    /// Stream writers retain exact receipt timestamps while keeping other
279    /// Agent transforms. Unlisted verbs use `Standard`.
280    pub fn presentation_policy(&self) -> VerbPresentationPolicy {
281        match self.name {
282            "get"
283            | "link"
284            | "query"
285            | "traverse"
286            | "neighbors"
287            | "brain.feedback"
288            | "brain.auto_feedback"
289            | "memory.feedback"
290            | "comm.delivered"
291            | "comm.transport_status"
292            | "git.digest"
293            | "git.ingest_cursor"
294            | "schema" => VerbPresentationPolicy::AlwaysVerbose,
295            "stream.append" => VerbPresentationPolicy::StreamAppendReceipt,
296            "stream.batch" => VerbPresentationPolicy::StreamBatchReceipts,
297            "gtd.tasks" | "gtd.next" => VerbPresentationPolicy::GtdTaskPage,
298            "schedule.agenda" => VerbPresentationPolicy::AgendaContinuation,
299            "session.list" => VerbPresentationPolicy::SessionList,
300            "memory.recall" => VerbPresentationPolicy::RecallCompact,
301            _ => VerbPresentationPolicy::Standard,
302        }
303    }
304}
305
306/// Backward-compatible type alias.  Existing code that names `VerbDef` still
307/// compiles; new code should use `HandlerDef` directly.
308#[deprecated(since = "0.2.0", note = "Use HandlerDef instead")]
309pub type VerbDef = HandlerDef;
310
311/// Match spec for one end of an [`EdgeEndpointRule`].
312///
313/// Identifies a substrate + kind pair that the rule applies to. Note that
314/// `kind` strings refer to the pack-declared note kinds / entity kinds — not
315/// the closed [`EdgeRelation`] set, which is universal.
316#[derive(Clone, Copy, Debug, PartialEq, Eq)]
317pub enum EndpointKind {
318    /// A note whose `kind` field equals the given string (e.g. `"task"`).
319    NoteOfKind(&'static str),
320    /// An entity whose `kind` field equals the given string (e.g. `"concept"`).
321    EntityOfKind(&'static str),
322    /// An entity whose base `kind` AND `entity_type` subtype both match the
323    /// given strings (e.g. `kind: "concept", entity_type: "theorem"`). Both
324    /// fields must match — enforcing the `(EntityKind, entity_type)` registry
325    /// invariant required by ADR-001:102. Required for granular entity subtypes
326    /// (formal-math theorem/definition, AMR gene/drug/pathogen): `EntityOfKind`
327    /// only sees the base kind (`"concept"`), so an `EntityOfKind("theorem")`
328    /// rule is silently inert. Additive — tightens nothing in the closed relation
329    /// set.
330    EntityOfType {
331        /// Base entity kind that must match (e.g. `"concept"`).
332        kind: &'static str,
333        /// Canonical `entity_type` subtype that must match (e.g. `"theorem"`).
334        entity_type: &'static str,
335    },
336}
337
338/// A pack-declared endpoint rule for a specific edge relation.
339///
340/// Rules are **additive**: they extend the set of allowed
341/// `(source, relation, target)` triples beyond the base contract.
342/// Packs cannot tighten the base rules — only broaden them. The closed
343/// [`EdgeRelation`] taxonomy itself is not extended; only the endpoint
344/// contract per relation is.
345///
346/// Example — GTD pack allows `depends_on` between task notes:
347///
348/// ```ignore
349/// EdgeEndpointRule {
350///     relation: EdgeRelation::DependsOn,
351///     source: EndpointKind::NoteOfKind("task"),
352///     target: EndpointKind::NoteOfKind("task"),
353/// }
354/// ```
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub struct EdgeEndpointRule {
357    pub relation: EdgeRelation,
358    pub source: EndpointKind,
359    pub target: EndpointKind,
360}
361
362/// Lifecycle specification for a note kind.
363///
364/// Declares which field holds the kind's domain state, the initial value,
365/// terminal values, and allowed transitions.  The runtime uses this to
366/// validate lifecycle operations at the verb boundary without hard-coding
367/// kind-specific logic in the shared CRUD path.
368///
369/// Phase 1 (current): packs declare the spec; the runtime records it for
370/// documentation and future enforcement.
371/// Phase 2 (future): the runtime uses `field` to route lifecycle writes
372/// to a first-class column rather than `properties`.
373#[derive(Clone, Debug, PartialEq, Eq)]
374pub struct NoteLifecycleSpec {
375    /// The field name that holds the kind's lifecycle state.
376    ///
377    /// Use `"kind_status"` for pack-owned lifecycle fields to avoid the
378    /// semantic collision with `Note.status` (NoteStatus).
379    pub field: &'static str,
380    /// The value assigned when a note of this kind is first created.
381    pub initial: &'static str,
382    /// Values from which no further transitions are possible.
383    pub terminal: &'static [&'static str],
384    /// Allowed `(from, to)` transitions. `"*"` as `from` matches any state.
385    pub transitions: &'static [(&'static str, &'static str)],
386}
387
388/// Kind-level schema specification for a note kind.
389///
390/// Each pack-registered note kind may declare a `NoteKindSpec` to describe
391/// its lifecycle semantics.  The runtime collects these at boot time via
392/// [`Pack::NOTE_KIND_SPECS`] for documentation, introspection, and future
393/// enforcement.
394#[derive(Clone, Debug, PartialEq, Eq)]
395pub struct NoteKindSpec {
396    /// The note kind string this spec governs (e.g. `"task"`).
397    pub kind: &'static str,
398    /// Alternate names this kind accepts on the wire.
399    pub aliases: &'static [&'static str],
400    /// Lifecycle state machine for this kind.
401    pub lifecycle: NoteLifecycleSpec,
402}
403
404/// Declared ownership policy for one note property.
405///
406/// This metadata does not itself enforce writes or grant authority.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum PropertyPolicy {
409    /// The substrate or owning pack derives this property from trusted runtime context.
410    Derived,
411    /// Only the owning pack's specialized writer establishes this property.
412    OwnerOnly,
413}
414
415/// Property policy for a note kind declared by the same pack.
416#[derive(Clone, Copy, Debug, PartialEq, Eq)]
417pub struct NotePropertyPolicySpec {
418    /// The owned note kind.
419    pub kind: &'static str,
420    /// The exact property key, without normalization.
421    pub key: &'static str,
422    /// The property's declared ownership policy.
423    pub policy: PropertyPolicy,
424}
425
426/// Which registered embedding spaces a note kind writes by default.
427#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
428pub enum NoteEmbeddingPolicy {
429    #[default]
430    AllModels,
431    DefaultModel,
432}
433
434/// Pack-owned embedding policy for one declared note kind.
435#[derive(Clone, Copy, Debug, PartialEq, Eq)]
436pub struct NoteEmbeddingPolicySpec {
437    pub kind: &'static str,
438    pub policy: NoteEmbeddingPolicy,
439}
440
441/// SQLite storage type for a nullable pack-auxiliary column addition.
442#[derive(Clone, Copy, Debug, PartialEq, Eq)]
443pub enum PackColumnAffinity {
444    /// A nullable `TEXT` column with no default or primary key.
445    Text,
446    /// A nullable `INTEGER` column with no default or primary key.
447    Integer,
448}
449
450/// An idempotent nullable-column addition to a pack-owned auxiliary table.
451///
452/// Identifiers must use ASCII letters, digits, or underscores and cannot start
453/// with a digit. Existing columns must match the declared type and have no
454/// default, primary key, generated expression, or `NOT NULL` constraint. A
455/// compatible partial upgrade completes without changing existing column values.
456/// The pack's full create-table DDL must also include every declared column.
457#[derive(Clone, Copy, Debug, PartialEq, Eq)]
458pub struct PackColumnAddition {
459    /// Pack-owned auxiliary table in the backend's main schema.
460    pub table: &'static str,
461    /// Column to add when absent from an existing table.
462    pub column: &'static str,
463    /// Exact declared SQLite type required for this column.
464    pub affinity: PackColumnAffinity,
465}
466
467/// A declared rebuild of pack-owned auxiliary tables whose `CHECK` constraints change
468/// (ADR-028 Amendment A7).
469///
470/// `CREATE TABLE IF NOT EXISTS` keeps the checks a table was created with, so a pack that widens
471/// one declares the rebuild here. The backend applies it in the transaction that applies the
472/// pack's schema plan, after the plan's statements:
473///
474/// - when the stored `CREATE TABLE` of `table` contains `marker`, the table already has the new
475///   shape: its columns must equal `columns`, or the plan is refused and nothing is rebuilt again;
476/// - otherwise `script` runs, every table in `rebuilds` must hold exactly the rows it held before,
477///   the plan's statements run again to recreate the triggers and indexes the script dropped, and
478///   the stored `CREATE TABLE` of `table` must then contain `marker`.
479///
480/// Any failure rolls the whole transaction back: the store keeps its old shape and the pack does
481/// not load. Read-only backends run no replacement. Identifiers use ASCII letters, digits, or
482/// underscores and cannot start with a digit.
483#[derive(Clone, Copy, Debug, PartialEq, Eq)]
484pub struct PackTableReplacement {
485    /// The table whose stored `CREATE TABLE` carries `marker`. The pack's schema plan creates it.
486    pub table: &'static str,
487    /// Text found in the stored `CREATE TABLE` of `table` only once it has the new shape.
488    pub marker: &'static str,
489    /// The column names of `table` in the new shape, in order.
490    pub columns: &'static [&'static str],
491    /// Every table the script drops and recreates, `table` among them. Each keeps its rows.
492    pub rebuilds: &'static [&'static str],
493    /// SQL that rebuilds the tables in `rebuilds`: create each new table under another name,
494    /// copy its rows, drop the old table and rename the new one. A dropped table's triggers and
495    /// indexes go with it; the plan's statements recreate them.
496    pub script: &'static str,
497}
498
499/// DDL statements the pack needs applied to the auxiliary schema.
500///
501/// Pack-auxiliary tables use idempotent `CREATE TABLE IF NOT EXISTS`; they are
502/// not part of the core versioned migration chain.  The runtime applies these
503/// statements once at pack registration time (or startup) against the active
504/// storage backend.
505#[derive(Clone, Debug, PartialEq, Eq)]
506pub struct PackSchemaPlan {
507    /// The pack this schema plan belongs to (used for error reporting).
508    pub pack: &'static str,
509    /// Idempotent SQL statements to apply.
510    pub statements: &'static [&'static str],
511}
512
513/// A composable module that contributes vocabulary, verbs, and edge endpoint
514/// rules to the khive runtime.
515///
516/// Packs declare what entity kinds, note kinds, and verbs they introduce, and
517/// optionally extend the per-relation endpoint contract via [`EDGE_RULES`].
518/// The runtime merges vocabularies from all loaded packs and rejects
519/// unregistered kinds at the service boundary.
520///
521/// The closed [`EdgeRelation`] enum is not extensible — only its
522/// per-relation endpoint contract is extensible by packs.
523///
524/// [`EDGE_RULES`]: Pack::EDGE_RULES
525pub trait Pack {
526    /// Short identifier for this pack (e.g. "kg", "tasks").
527    const NAME: &'static str;
528
529    /// Note kinds this pack contributes to the runtime vocabulary.
530    const NOTE_KINDS: &'static [&'static str];
531
532    /// Entity kinds this pack contributes to the runtime vocabulary.
533    const ENTITY_KINDS: &'static [&'static str];
534
535    /// Brain profile consumer kinds this pack requests.
536    ///
537    /// A pack that resolves a brain profile for a consumer (for example,
538    /// `"recall"`) declares that wire-level kind here. The runtime composes
539    /// declarations from all loaded packs so `brain.bind` can reject bindings
540    /// that no registered consumer will ever request. Multiple packs may
541    /// declare the same consumer kind; composition deduplicates them.
542    ///
543    /// The `"*"` binding wildcard is registry-owned and must not be declared
544    /// by a pack.
545    const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &[];
546
547    /// Handlers this pack registers.
548    ///
549    /// The runtime routes verb calls to the pack that declares them.
550    /// Only entries with `visibility: Visibility::Verb` are surfaced on the
551    /// MCP wire; `Visibility::Subhandler` entries are internal.
552    const HANDLERS: &'static [HandlerDef];
553
554    /// Additional edge endpoint rules this pack contributes.
555    ///
556    /// Defaults to empty — packs that introduce no new endpoint pairs (or
557    /// only rely on the base endpoint contract) can ignore this.
558    const EDGE_RULES: &'static [EdgeEndpointRule] = &[];
559
560    /// Entity-type subtypes this pack contributes to the `(EntityKind,
561    /// entity_type)` registry (the `entity_type` axis is distinct from and
562    /// finer-grained than the closed [`EntityKind`]
563    /// taxonomy — see `khive-types::entity_type::EntityTypeRegistry`).
564    ///
565    /// Defaults to empty, mirroring [`EDGE_RULES`]'s additive contract:
566    /// packs that introduce no new subtypes can ignore this. Entries here
567    /// are composed with `EntityTypeRegistry::builtin()` at runtime boot
568    /// (`VerbRegistry::all_entity_types`); packs must declare only new
569    /// `(kind, type_name)` pairs — they may not tighten or shadow a builtin
570    /// or another pack's declared subtype.
571    ///
572    /// [`EDGE_RULES`]: Pack::EDGE_RULES
573    const ENTITY_TYPES: &'static [EntityTypeDef] = &[];
574
575    /// Other pack names whose vocabulary this pack references.
576    ///
577    /// The runtime checks that every name in `REQUIRES` appears in the
578    /// loaded pack set before any pack is registered. Defaults to empty
579    /// so existing packs compile without changes.
580    const REQUIRES: &'static [&'static str] = &[];
581
582    /// Public verbs of this pack that keep the caller's default read set when called with
583    /// an explicit `namespace` (ADR-007, declared verbs). Such a call writes the named
584    /// namespace and reads the default set plus that namespace. Every name is one of this
585    /// pack's own `Visibility::Verb` handlers, listed once; registration refuses any other
586    /// list. Defaults to empty, so an explicit namespace reads that namespace alone.
587    const DEFAULT_READ_VERBS: &'static [&'static str] = &[];
588
589    /// Lifecycle and schema specs for note kinds this pack owns.
590    ///
591    /// Packs that introduce note kinds with explicit lifecycle semantics
592    /// (e.g. GTD's `task` kind) declare the spec here.  The runtime collects
593    /// these at boot time for introspection and future enforcement.  Defaults
594    /// to empty so existing packs compile without changes.
595    const NOTE_KIND_SPECS: &'static [NoteKindSpec] = &[];
596
597    /// Property policies for note kinds owned by this pack.
598    ///
599    /// Mirror this slice through `PackRuntime::note_property_policies`. The
600    /// registry validates and snapshots it at boot; declarations alone do not
601    /// change write enforcement. Unlisted keys carry no declared restriction.
602    const NOTE_PROPERTY_POLICIES: &'static [NotePropertyPolicySpec] = &[];
603
604    /// Write-time embedding policy for note kinds declared in `NOTE_KINDS`.
605    /// Unlisted kinds retain the all-model default.
606    const NOTE_EMBEDDING_POLICIES: &'static [NoteEmbeddingPolicySpec] = &[];
607
608    /// Pack-auxiliary schema plan.
609    ///
610    /// Packs that need their own auxiliary tables (e.g. GTD's
611    /// `gtd_lifecycle_audit`) declare idempotent DDL statements here.
612    /// The runtime applies them once at registration time.  Defaults to
613    /// `None` so packs with no auxiliary schema cost nothing.
614    const SCHEMA_PLAN: Option<PackSchemaPlan> = None;
615
616    /// Nullable-column upgrades for this pack's auxiliary tables.
617    ///
618    /// The backend validates and adds missing columns on existing tables before
619    /// applying [`Self::SCHEMA_PLAN`], then validates the final schema. The
620    /// entire plan is transactional. Absent tables are created only by the
621    /// pack's full DDL, so unloaded packs do not acquire auxiliary tables.
622    const SCHEMA_COLUMN_ADDITIONS: &'static [PackColumnAddition] = &[];
623
624    /// Declared rebuilds of this pack's auxiliary tables (ADR-028 Amendment A7).
625    ///
626    /// Each runs in the transaction that applies [`Self::SCHEMA_PLAN`], and only on a store whose
627    /// table lacks the replacement's marker. Defaults to empty.
628    const SCHEMA_TABLE_REPLACEMENTS: &'static [PackTableReplacement] = &[];
629
630    /// Validation rule IDs contributed by this pack.
631    ///
632    /// Rule IDs are namespaced by pack name: `<pack-name>/<rule-id>`.
633    /// The runtime merges rule IDs from all packs; the actual rule
634    /// implementations live in `khive-runtime::validation::ValidationRule`
635    /// (not in `khive-types`, which stays `no_std`). This const serves as
636    /// the declarative catalog of rule identifiers so the validation
637    /// infrastructure can enumerate what rules a pack claims without
638    /// loading the runtime.
639    ///
640    /// Defaults to empty — packs with no domain-specific validation rules
641    /// can leave this unset.
642    const VALIDATION_RULES: &'static [&'static str] = &[];
643}
644
645/// ADR-099 D3 — the v1 atomic-admissible verb set for `--atomic` bulk apply.
646///
647/// This is an EXPLICIT per-verb allowlist, never derived from [`VerbCategory`]
648/// or any other classification ("never a pack-level category", ADR-099 D3).
649/// Every verb here has a prepare/apply seam whose in-transaction phase reduces
650/// to synchronous DML — the atomic-unit suspend-free invariant
651/// (`SqlAccess::atomic_unit` in `khive-storage`). Extending this list is a
652/// design decision (ADR-099 amendment), not a code-review-only change; the
653/// `atomic_admissible_list_matches_adr` test below pins this exact set so an
654/// edit here forces the editor to touch that test and its ADR citation.
655pub const ATOMIC_ADMISSIBLE_VERBS: &[&str] = &[
656    "update",
657    "delete",
658    "link",
659    "merge",
660    "gtd.transition",
661    "gtd.complete",
662    "propose",
663    "review",
664    "withdraw",
665];
666
667/// Verbs rejected under `--atomic` because their write still computes an
668/// embedding synchronously and no prepare/apply seam hoists that embedding
669/// out of the transaction yet (ADR-099 D3, "v1 rejected — embedding-bearing").
670const ATOMIC_EMBEDDING_BEARING_VERBS: &[&str] = &[
671    "create",
672    "memory.remember",
673    "gtd.assign",
674    "comm.send",
675    "comm.reply",
676    "comm.ingest",
677];
678
679/// Verbs on [`ATOMIC_ADMISSIBLE_VERBS`] (ADR-099 D3 conceptually admissible)
680/// that have no *full-parity* prepare/apply seam yet, so they are rejected up
681/// front (checked BEFORE the general admissible-list check) rather than
682/// admitted with a silent gap. See
683/// crates/khive-types/docs/api/pack.md#adr-099-d3-atomic-admissibility-rejection-classes
684/// for why each verb is deferred and the ADR-099 B3 ordering rationale.
685pub const ATOMIC_KNOWN_UNIMPLEMENTED_VERBS: &[&str] = &["propose", "review", "withdraw", "merge"];
686
687/// Read verbs rejected under `--atomic` — they produce no write plan to apply
688/// (ADR-099 D3, "v1 rejected — reads").
689const ATOMIC_READ_VERBS: &[&str] = &[
690    "search",
691    "recall",
692    "query",
693    "traverse",
694    "list",
695    "get",
696    "neighbors",
697    "context",
698    "stats",
699    "verbs",
700];
701
702/// Conservative default maximum op count for one `--atomic` unit (ADR-099
703/// migration step 7 / B3). Override per invocation with
704/// `kkernel exec --atomic --atomic-max-ops N`. See
705/// crates/khive-types/docs/api/pack.md#atomic_max_ops_default--2000--rationale
706/// for why 2000 specifically was chosen and when to revisit it.
707pub const ATOMIC_MAX_OPS_DEFAULT: usize = 2000;
708
709/// Why a verb was rejected from an `--atomic` op list (ADR-099 D3, migration
710/// step 2). Distinguishes the two named rejection classes from a generic
711/// "not yet admitted" fallback so callers can produce an actionable message.
712#[derive(Clone, Copy, Debug, PartialEq, Eq)]
713pub enum AtomicRejectionReason {
714    /// The verb still computes an embedding synchronously in its write path.
715    EmbeddingBearing,
716    /// The verb is a read — it has no write plan to apply.
717    Read,
718    /// Neither on the v1 admissible list nor a known rejected category (e.g.
719    /// a verb added after this list was written). Rejected by default —
720    /// admissibility is opt-in, never inferred.
721    Unlisted,
722    /// On [`ATOMIC_ADMISSIBLE_VERBS`] per ADR-099 D3 (conceptually admissible,
723    /// intended to gain a seam) but has no prepare/apply implementation in
724    /// this slice yet ([`ATOMIC_KNOWN_UNIMPLEMENTED_VERBS`]). Rejected at the
725    /// same pre-runtime static-guard stage as every other rejection reason —
726    /// never silently no-opped, never deferred until after a runtime/write
727    /// attempt.
728    KnownUnimplemented,
729}
730
731/// Static admissibility classification for `verb_name` under ADR-099
732/// `--atomic` bulk apply.
733///
734/// Returns `None` when the verb is admissible; `Some(reason)` names why it is
735/// rejected. Default-deny: a verb name absent from every list here is
736/// [`AtomicRejectionReason::Unlisted`], never silently admitted.
737///
738/// `ATOMIC_KNOWN_UNIMPLEMENTED_VERBS` is checked BEFORE the general
739/// admissible-list membership check (ADR-099 B3): those
740/// verbs are members of `ATOMIC_ADMISSIBLE_VERBS`, so checking membership
741/// first would admit them (`None`) and defer their rejection to prepare time,
742/// after a runtime has already been constructed.
743pub fn atomic_admissibility(verb_name: &str) -> Option<AtomicRejectionReason> {
744    if ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(&verb_name) {
745        return Some(AtomicRejectionReason::KnownUnimplemented);
746    }
747    if ATOMIC_ADMISSIBLE_VERBS.contains(&verb_name) {
748        return None;
749    }
750    if ATOMIC_EMBEDDING_BEARING_VERBS.contains(&verb_name) {
751        return Some(AtomicRejectionReason::EmbeddingBearing);
752    }
753    if ATOMIC_READ_VERBS.contains(&verb_name) {
754        return Some(AtomicRejectionReason::Read);
755    }
756    Some(AtomicRejectionReason::Unlisted)
757}
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762
763    struct TestPack;
764
765    impl Pack for TestPack {
766        const NAME: &'static str = "test";
767        const NOTE_KINDS: &'static [&'static str] = &["memo"];
768        const ENTITY_KINDS: &'static [&'static str] = &["widget"];
769        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
770            name: "do_thing",
771            description: "does a thing",
772            visibility: Visibility::Verb,
773            category: VerbCategory::Commissive,
774            params: &[],
775        }];
776    }
777
778    #[test]
779    fn pack_trait_compiles() {
780        assert_eq!(TestPack::NAME, "test");
781        assert_eq!(TestPack::NOTE_KINDS, &["memo"]);
782        assert_eq!(TestPack::ENTITY_KINDS, &["widget"]);
783        assert_eq!(TestPack::HANDLERS.len(), 1);
784        assert_eq!(TestPack::HANDLERS[0].name, "do_thing");
785        assert_eq!(TestPack::HANDLERS[0].visibility, Visibility::Verb);
786        assert_eq!(TestPack::HANDLERS[0].category, VerbCategory::Commissive);
787    }
788
789    #[test]
790    fn verb_category_variants_exist() {
791        // Just ensuring the enum variants are accessible — no runtime assertion
792        // needed beyond confirming they exist at compile time.
793        let _ = VerbCategory::Assertive;
794        let _ = VerbCategory::Directive;
795        let _ = VerbCategory::Commissive;
796        let _ = VerbCategory::Declaration;
797    }
798
799    #[test]
800    fn pack_validation_rules_default_empty() {
801        assert!(TestPack::VALIDATION_RULES.is_empty());
802    }
803
804    #[test]
805    fn pack_entity_types_default_empty() {
806        assert!(TestPack::ENTITY_TYPES.is_empty());
807    }
808
809    // `link` must be AlwaysVerbose so edge IDs are not shortened.
810    #[test]
811    fn link_handler_is_always_verbose() {
812        let link_def = HandlerDef {
813            name: "link",
814            description: "Create a typed directed edge",
815            visibility: Visibility::Verb,
816            category: VerbCategory::Commissive,
817            params: &[],
818        };
819        assert_eq!(
820            link_def.presentation_policy(),
821            VerbPresentationPolicy::AlwaysVerbose,
822            "link must be AlwaysVerbose"
823        );
824    }
825
826    // AlwaysVerbose set regression: protect every identifier-bearing contract.
827    #[test]
828    fn always_verbose_set_contains_expected_verbs() {
829        let always_verbose = [
830            "get",
831            "link",
832            "query",
833            "traverse",
834            "neighbors",
835            "brain.feedback",
836            "brain.auto_feedback",
837            "memory.feedback",
838            "comm.delivered",
839            "comm.transport_status",
840            "git.digest",
841            "git.ingest_cursor",
842            "schema",
843        ];
844        for name in always_verbose {
845            let h = HandlerDef {
846                name,
847                description: "",
848                visibility: Visibility::Verb,
849                category: VerbCategory::Assertive,
850                params: &[],
851            };
852            assert_eq!(
853                h.presentation_policy(),
854                VerbPresentationPolicy::AlwaysVerbose,
855                "{name:?} must be AlwaysVerbose"
856            );
857        }
858    }
859
860    #[test]
861    fn stream_receipt_policies_are_closed_to_the_registered_writers() {
862        for (name, policy) in [
863            ("stream.append", VerbPresentationPolicy::StreamAppendReceipt),
864            ("stream.batch", VerbPresentationPolicy::StreamBatchReceipts),
865            ("stream.read", VerbPresentationPolicy::Standard),
866            ("stream.batch.other", VerbPresentationPolicy::Standard),
867            ("list", VerbPresentationPolicy::Standard),
868        ] {
869            let handler = HandlerDef {
870                name,
871                description: "",
872                visibility: Visibility::Verb,
873                category: VerbCategory::Commissive,
874                params: &[],
875            };
876            assert_eq!(handler.presentation_policy(), policy, "{name}");
877        }
878    }
879
880    #[test]
881    fn recall_compact_policy_is_exactly_the_registered_memory_verb() {
882        for name in [
883            "memory.recall",
884            "recall",
885            "memory.recall.other",
886            "memory.recallx",
887            "MEMORY.RECALL",
888        ] {
889            let handler = HandlerDef {
890                name,
891                description: "",
892                visibility: Visibility::Verb,
893                category: VerbCategory::Assertive,
894                params: &[],
895            };
896            assert_eq!(
897                handler.presentation_policy(),
898                if name == "memory.recall" {
899                    VerbPresentationPolicy::RecallCompact
900                } else {
901                    VerbPresentationPolicy::Standard
902                },
903                "{name}",
904            );
905        }
906    }
907
908    // Standard policy for all other verbs.
909    #[test]
910    fn non_verbose_verbs_are_standard_policy() {
911        let standard = [
912            "create", "list", "update", "delete", "search", "recall", "remember",
913        ];
914        for name in standard {
915            let h = HandlerDef {
916                name,
917                description: "",
918                visibility: Visibility::Verb,
919                category: VerbCategory::Commissive,
920                params: &[],
921            };
922            assert_eq!(
923                h.presentation_policy(),
924                VerbPresentationPolicy::Standard,
925                "{name:?} must be Standard (not AlwaysVerbose)"
926            );
927        }
928    }
929
930    // ── ADR-099 D3 atomic admissibility ────────────────────────────────────
931
932    // Drift-pin: a hardcoded copy of the ADR-099 D3 v1 admissible list. If
933    // someone edits `ATOMIC_ADMISSIBLE_VERBS`, this test fails until they also
934    // update this literal — forcing a look at ADR-099 D3 ("Decision: admit
935    // only verbs that expose a prepare/apply seam...") before the set changes.
936    #[test]
937    fn atomic_admissible_list_matches_adr099_d3() {
938        let adr_099_d3_v1_admissible_set: &[&str] = &[
939            "update",
940            "delete",
941            "link",
942            "merge",
943            "gtd.transition",
944            "gtd.complete",
945            "propose",
946            "review",
947            "withdraw",
948        ];
949        assert_eq!(
950            ATOMIC_ADMISSIBLE_VERBS, adr_099_d3_v1_admissible_set,
951            "ATOMIC_ADMISSIBLE_VERBS drifted from ADR-099 D3's explicit v1 list"
952        );
953    }
954
955    #[test]
956    fn atomic_admissible_verbs_are_admitted() {
957        for verb in ATOMIC_ADMISSIBLE_VERBS {
958            // Governance verbs are on ATOMIC_ADMISSIBLE_VERBS per ADR-099 D3
959            // (conceptually admissible) but are checked separately below:
960            // they are rejected at this same static layer for a distinct
961            // reason (KnownUnimplemented), not admitted (None).
962            if ATOMIC_KNOWN_UNIMPLEMENTED_VERBS.contains(verb) {
963                continue;
964            }
965            assert_eq!(
966                atomic_admissibility(verb),
967                None,
968                "{verb:?} is on the v1 admissible list and must be admitted"
969            );
970        }
971    }
972
973    #[test]
974    fn atomic_known_unimplemented_verbs_rejected_before_runtime() {
975        // ADR-099 B3: propose/review/withdraw
976        // remain on ATOMIC_ADMISSIBLE_VERBS (ADR-099 D3 intends them to gain a
977        // seam) but must be rejected at this SAME static pre-runtime guard —
978        // not admitted here and only failed later inside
979        // `atomic_prepare::prepare_op` after a runtime was already built.
980        for verb in ATOMIC_KNOWN_UNIMPLEMENTED_VERBS {
981            assert!(
982                ATOMIC_ADMISSIBLE_VERBS.contains(verb),
983                "{verb:?} must remain on ATOMIC_ADMISSIBLE_VERBS per ADR-099 D3"
984            );
985            assert_eq!(
986                atomic_admissibility(verb),
987                Some(AtomicRejectionReason::KnownUnimplemented),
988                "{verb:?} must be rejected as known-unimplemented, not admitted"
989            );
990        }
991    }
992
993    #[test]
994    fn atomic_embedding_bearing_verbs_rejected_named() {
995        for verb in [
996            "create",
997            "memory.remember",
998            "gtd.assign",
999            "comm.send",
1000            "comm.reply",
1001        ] {
1002            assert_eq!(
1003                atomic_admissibility(verb),
1004                Some(AtomicRejectionReason::EmbeddingBearing),
1005                "{verb:?} must be rejected as embedding-bearing (ADR-099 acceptance criteria)"
1006            );
1007        }
1008    }
1009
1010    #[test]
1011    fn atomic_read_verbs_rejected() {
1012        for verb in [
1013            "search",
1014            "recall",
1015            "query",
1016            "traverse",
1017            "list",
1018            "get",
1019            "neighbors",
1020            "context",
1021        ] {
1022            assert_eq!(
1023                atomic_admissibility(verb),
1024                Some(AtomicRejectionReason::Read),
1025                "{verb:?} must be rejected as a read verb"
1026            );
1027        }
1028    }
1029
1030    #[test]
1031    fn atomic_unknown_verb_defaults_to_unlisted_rejection() {
1032        assert_eq!(
1033            atomic_admissibility("some_future_verb_nobody_classified_yet"),
1034            Some(AtomicRejectionReason::Unlisted),
1035            "an unrecognized verb must default-deny, never silently admit"
1036        );
1037    }
1038}