hank 0.4.0

In-memory, multi-tenant code-analysis engine — the structural signal for the Bobbin × Quipu stack
Documentation
//! The typed fact model Hank serves.
//!
//! Every served fact carries a [`Tier`] (how it was derived) — the confidence
//! tag FR-3 requires so a consumer never mistakes a tree-sitter approximation
//! for an LSP-precise fact.
//!
//! [`Freshness`] (how current a fact is) is FR-3's OTHER half, and it is **not
//! yet served**. Freshness state (fresh/stale/recomputing) is a property of the
//! Phase-3 resident graph + file-watcher (FR-16/17); the current serve path
//! rebuilds the graph on demand per request from the working copy, where there
//! is no cached fact that could be stale. So [`Freshness`] and [`Fact`] (the
//! subject–edge–object carrier that pairs a value with both tags) are defined
//! here as the Phase-3 carrier but have no caller on the served path yet.
//!
//! This docstring previously asserted that every served fact carried a freshness
//! tag. It did not — freshness was served nowhere (aegis-8yrn). Correcting the
//! claim, rather than stamping a hardcoded `fresh` that would imply a tracking
//! system that does not exist, is the FR-3 honesty rule applied to the spec
//! itself: a fact that cannot state its own freshness says so, it does not
//! default to looking current.

use serde::{Deserialize, Serialize};

/// Provenance/precision of a fact — which extractor produced it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tier {
    /// Fast, build-free, approximate (tree-sitter).
    TreeSitter,
    /// Precise defs/refs/types where a build resolves (LSP).
    Lsp,
    /// Control/data dependence from the code property graph.
    Cpg,
}

/// How current a served fact is relative to the tenant's working copy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Freshness {
    /// Reflects the latest observed edit.
    Fresh,
    /// Known to be behind a pending edit.
    Stale,
    /// A recompute is in flight.
    Recomputing,
}

impl Tier {
    /// The lowercase string form used on the wire and in the ontology.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Tier::TreeSitter => "treesitter",
            Tier::Lsp => "lsp",
            Tier::Cpg => "cpg",
        }
    }

    /// The tiers this build can ACTUALLY serve — the single source of truth for
    /// `hank status` / `hank_status` (aegis-qe5z).
    ///
    /// It reports a tier only when that tier has a registered extractor. Today
    /// that is tree-sitter ALONE: the LSP tier (FR-2) and the CPG tier (FR-7) are
    /// unimplemented, so they are NOT advertised. `status` used to push `lsp`/`cpg`
    /// on `cfg!(feature = "lsp"/"cpg")`, but those were EMPTY Cargo features that
    /// gated no code — so `--features lsp` produced a binary that advertised a
    /// precision tier while every fact it served was still `TreeSitter`. That is
    /// the exact "present an approximation as precise" failure FR-3 and AGENTS.md
    /// forbid, one level up at the feature flag (sibling of aegis-8yrn).
    ///
    /// When a tier gains a real implementation, add it HERE, gated on that
    /// implementation (a `Vec` push behind the module that provides it) — never on
    /// a bare feature flag, which can be enabled without the code existing.
    #[must_use]
    pub fn served() -> Vec<String> {
        vec![Tier::TreeSitter.as_str().to_string()]
    }
}

/// The kind of a named code symbol. Values mirror the enumeration in Quipu's
/// `shapes/code-entities.ttl` (`bobbin:symbolKind`) so promoted facts validate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SymbolKind {
    /// A free function.
    Function,
    /// A method associated with a type.
    Method,
    /// A class.
    Class,
    /// An interface / trait.
    Interface,
    /// An enum.
    Enum,
    /// A struct.
    Struct,
    /// A variable binding.
    Variable,
    /// A constant.
    Constant,
    /// A module.
    Module,
    /// A property.
    Property,
    /// A field.
    Field,
    /// A constructor.
    Constructor,
    /// A type alias.
    TypeAlias,
}

impl SymbolKind {
    /// The lowercase string form used on the wire and in the ontology
    /// (`bobbin:symbolKind`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            SymbolKind::Function => "function",
            SymbolKind::Method => "method",
            SymbolKind::Class => "class",
            SymbolKind::Interface => "interface",
            SymbolKind::Enum => "enum",
            SymbolKind::Struct => "struct",
            SymbolKind::Variable => "variable",
            SymbolKind::Constant => "constant",
            SymbolKind::Module => "module",
            SymbolKind::Property => "property",
            SymbolKind::Field => "field",
            SymbolKind::Constructor => "constructor",
            SymbolKind::TypeAlias => "type_alias",
        }
    }
}

/// A structural edge between two symbols or modules. These become predicates in
/// the `bobbin:` code ontology on promotion (see `docs/hank-spec.md` §9.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
    /// Caller invokes callee.
    Calls,
    /// A use site of a definition.
    References,
    /// A symbol is defined in a module.
    DefinedIn,
    /// A module depends on another module.
    Imports,
    /// A data-dependence edge (CPG).
    DataDependsOn,
    /// A control-dependence edge (CPG).
    ControlDependsOn,
}

/// A named symbol extracted from a source file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Symbol {
    /// The symbol's name.
    pub name: String,
    /// The chain of named enclosing scopes (module, impl, trait, class,
    /// function — per language), outermost first; empty for a top-level symbol.
    /// This is what makes the promoted IRI unique when one file defines two
    /// same-named symbols in different scopes (aegis-1q14: 42 of 43 measured
    /// collisions silently merged into one node before this existed).
    #[serde(default)]
    pub scope: Vec<String>,
    /// What kind of symbol it is.
    pub kind: SymbolKind,
    /// 1-based line where the symbol begins.
    pub start_line: usize,
    /// 1-based line where the symbol ends.
    pub end_line: usize,
    /// How this symbol was derived.
    pub tier: Tier,
}

/// A single structural fact: `subject —edge→ object`, tagged with provenance.
///
/// The Phase-3 freshness carrier (see the module docs): it pairs a value with
/// both a [`Tier`] and a [`Freshness`], but nothing on the served path constructs
/// one yet — freshness lands with the resident graph + watcher (FR-16/17).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fact {
    /// The subject identifier.
    pub subject: String,
    /// The relationship.
    pub edge: EdgeKind,
    /// The object identifier.
    pub object: String,
    /// How this fact was derived.
    pub tier: Tier,
    /// How current the fact is.
    pub freshness: Freshness,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn served_tiers_are_only_implemented_ones() {
        // aegis-qe5z: status must advertise a tier only when it is real. Today
        // the extractor assigns TreeSitter alone, so that is all `served()` may
        // claim — never `lsp`/`cpg`, which have no implementation. A push of an
        // unimplemented tier here (or a re-introduced empty feature) fails this.
        assert_eq!(Tier::served(), vec!["treesitter".to_string()]);
        assert!(!Tier::served().contains(&"lsp".to_string()));
        assert!(!Tier::served().contains(&"cpg".to_string()));
    }
}