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