hank 0.4.0

In-memory, multi-tenant code-analysis engine — the structural signal for the Bobbin × Quipu stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! The `hank` command-line interface.
//!
//! `analyze`, `refs`, `status`, `serve` (MCP), the Phase-2 call-graph commands
//! `callers`/`impact` and `dataflow`, `export` (referential structure as Turtle,
//! §5.10/FR-34), the `watch` file-watcher (debounced, tiered re-extraction,
//! §5.5/FR-17), and the `hook` adapter (edit-reactive harness integration,
//! §5.9/FR-30) and `verify` (the FR-23/FR-24 edit-buffer verdict) are live.
//! `promote` (Phase-4 Quipu promotion, FR-19/20/21) is live behind the `quipu`
//! feature and prints a phase notice in a build without it (`docs/hank-spec.md`).

use std::io;
use std::path::{Path, PathBuf};

use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use colored::Colorize;
use tracing_subscriber::EnvFilter;

use crate::cli_cmds;
use crate::config::HankConfig;
use crate::extract::extract_symbols;

// Command bodies live in child modules to keep this file under the size
// limit (hank #83); they are `impl Cli` blocks reaching `self` as before.
#[path = "cli_analyze.rs"]
mod cli_analyze;
#[path = "cli_promote.rs"]
mod cli_promote;
#[path = "cli_serve.rs"]
mod cli_serve;
#[path = "cli_status.rs"]
mod cli_status;

/// Hank — live, per-tenant code structure for the Bobbin × Quipu stack.
#[derive(Debug, Parser)]
#[command(name = "hank", version, about, long_about = None)]
pub struct Cli {
    /// The subcommand to run.
    #[command(subcommand)]
    command: Commands,

    /// Emit machine-readable JSON.
    #[arg(long, global = true)]
    json: bool,

    /// Suppress non-essential output.
    #[arg(long, global = true)]
    quiet: bool,

    /// Show detailed progress.
    #[arg(long, global = true)]
    verbose: bool,

    /// Tenant/session id (defaults to single-tenant).
    #[arg(long, global = true, env = "BOBBIN_ROLE")]
    tenant: Option<String>,

    /// Path to a config file (overrides discovery).
    #[arg(long, global = true)]
    config: Option<PathBuf>,
}

/// The available subcommands.
#[derive(Debug, Subcommand)]
enum Commands {
    /// Run the MCP server (stdio by default; `--http` for streamable-HTTP).
    Serve {
        /// Serve over streamable-HTTP instead of stdio.
        #[arg(long)]
        http: bool,
    },
    /// Run the resident-graph daemon: build the base graph once and hold it,
    /// serving a local liveness surface (Phase 3, FR-31). Query endpoints and the
    /// hook/MCP thin-client cutover land in later stages.
    Daemon {
        /// Port for the daemon's local HTTP surface (defaults to `serve.mcp_http_port`).
        #[arg(long)]
        port: Option<u16>,
    },
    /// Build the base graph for a path and print a summary.
    Analyze {
        /// Directory or file to analyze (defaults to the current directory).
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Analyze the tree at a git ref (a baseline commit) instead of the
        /// working tree — the FR-13 base. Repo-relative; degrades to empty
        /// outside a repo or for an unresolved ref.
        #[arg(long)]
        at: Option<String>,
    },
    /// What does a CHANGE do — which entities does it add, remove or modify?
    ///
    /// The FR-13 baseline pointed at a change-time question instead of a tree
    /// one. `--base` is the ref to diff FROM (defaults to the configured
    /// `base_ref`); omit `--to` to judge the WORKING TREE, which is the shape a
    /// proposed, uncommitted change has.
    Changed {
        /// Ref to diff from (defaults to the configured `base_ref`).
        #[arg(long)]
        base: Option<String>,
        /// Ref to diff to. Omit to diff against the working tree.
        #[arg(long)]
        to: Option<String>,
    },
    /// Find the definition sites of a symbol by name.
    Refs {
        /// Symbol name to locate. With --at this slot is the search PATH
        /// instead: a name is redundant once a position names the symbol.
        symbol: Option<String>,
        /// Directory to search (defaults to the current directory).
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Resolve the symbol at a POSITION instead of by name: `FILE:LINE`,
        /// relative to the search path. Disambiguates common names — `build`,
        /// `new` — by pointing at the one you mean. The tree-sitter tier
        /// resolves to the innermost symbol enclosing that LINE; column
        /// precision needs the LSP tier (FR-2), so a column is refused rather
        /// than silently ignored.
        #[arg(long, value_name = "FILE:LINE")]
        at: Option<String>,
    },
    /// Direct callers and callees of a symbol.
    Callers {
        /// Symbol name.
        symbol: String,
        /// Directory to build the call graph over (defaults to current dir).
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Blast radius: symbols transitively affected by changing a symbol.
    Impact {
        /// Seed symbol.
        symbol: String,
        /// Directory to build the call graph over (defaults to current dir).
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Maximum hops to follow.
        #[arg(long, default_value_t = 5)]
        hops: u32,
        /// Reconcile against a co-change file set (FR-11): a JSON array of
        /// paths, or a newline-separated list. Supplied by Bobbin.
        #[arg(long)]
        cochange: Option<PathBuf>,
    },
    /// Detected communities: densely-connected clusters of symbols (FR-9).
    Communities {
        /// Directory to build the call graph over (defaults to current dir).
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Count same-file symbol-name collisions — names whose definitions share
    /// one unqualified symbol IRI and merge into a single node on promotion.
    /// The sizing input for the scope-qualified IRI migration; only the
    /// extractor can see the same-kind variant, so this lives here and not in
    /// a graph query.
    Census {
        /// Directory to scan (defaults to the current directory).
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Export the referential structure (modules, symbols, edges) as Turtle,
    /// or promote it into Quipu with `--to` (FR-34; the promotion spelling of
    /// `promote`, spec §15).
    Export {
        /// Directory to export (defaults to current dir).
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Repository name to attribute entities to. Defaults to the `origin`
        /// remote's repo name, else the dir name (print-only); a promotion via
        /// `--to` refuses the dir-name guess and wants `--repo` or an origin.
        #[arg(long)]
        repo: Option<String>,
        /// Output format.
        #[arg(long, default_value = "turtle")]
        format: ExportFormat,
        /// Promote into the Quipu at this base URL instead of printing Turtle.
        /// SHACL-validates before writing, exactly like `hank promote`.
        #[arg(long)]
        to: Option<String>,
    },
    /// Intra-procedural data dependence within a function.
    Dataflow {
        /// Function to analyze.
        function: String,
        /// Directory to build the dataflow over (defaults to current dir).
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Trace flow for a specific variable (omit to list all edges).
        #[arg(long)]
        var: Option<String>,
        /// Trace what the variable flows into, rather than what it depends on.
        #[arg(long)]
        forward: bool,
        /// Maximum hops to follow.
        #[arg(long, default_value_t = 5)]
        hops: u32,
    },
    /// Verdict on a proposed edit buffer (FR-23/FR-24).
    Verify {
        /// The file being edited.
        #[arg(long)]
        file: PathBuf,
        /// The edited buffer to check.
        #[arg(long)]
        buffer: PathBuf,
    },
    /// Promote a commit's structural facts into Quipu (Phase 4).
    Promote {
        /// Commit-ish to promote.
        #[arg(long, default_value = "HEAD")]
        commit: String,
        /// Quipu base URL to promote into (e.g. `http://localhost:8080`). Required
        /// for a real promotion; without it, promotion is unwired and refuses.
        #[arg(long)]
        to: Option<String>,
        /// Repository name to attribute promoted entities to. Defaults to the
        /// `origin` remote's repo name; with no origin, promotion refuses rather
        /// than deriving identity from the directory name (a worktree's dir name
        /// mints wrong IRIs and fragments the graph).
        #[arg(long)]
        repo: Option<String>,
        /// Directory to promote (defaults to current dir).
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Watch a tree and re-extract changed files, debounced and tiered (FR-17).
    Watch {
        /// Directory to watch (defaults to the current directory).
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Show base commit, tiers, and configuration.
    Status,
    /// Agent-harness hook adapter (reads the hook payload on stdin).
    Hook {
        /// Which hook event to handle.
        event: HookEvent,
    },
    /// Generate shell completions.
    Completions {
        /// Target shell.
        shell: clap_complete::Shell,
    },
    /// Show the ed25519 public key of hank's verdict-signing identity, to
    /// register in quipu as this verifier's `aegis:publicKey` (quipu feature).
    #[cfg(feature = "quipu")]
    Verifier {
        /// Path to the PKCS#8 signing key (created 0600 if absent).
        #[arg(long, default_value = "hank-signing.pk8")]
        key_path: PathBuf,
    },
}

/// Supported agent-harness hook events.
#[derive(Debug, Clone, Copy, ValueEnum)]
enum HookEvent {
    /// Claude Code `PostToolUse` on Edit/Write: advise on cross-file blast radius.
    PostEdit,
    /// Claude Code `PreToolUse` on Edit/Write: deny an edit that exceeds the
    /// tenant's capability scope. Opt-in, and always fails open.
    PreEdit,
    /// Claude Code `PreToolUse` on Bash: RECORD the action (verb, target,
    /// `target_class`) for the trace. Never denies, never prints, always exits 0.
    PreBash,
}

/// Output formats for `hank export`.
#[derive(Debug, Clone, Copy, ValueEnum)]
enum ExportFormat {
    /// RDF Turtle in the `bobbin:` code ontology.
    Turtle,
}

/// The metric name for a DELIBERATELY-invoked command, or None for the two
/// invocations that are not "use": the hook (the guard spools its own line)
/// and shell completions. Exhaustive on purpose — a new command must decide
/// its own answer here or fail to compile, so the leverage metric can never
/// silently under-count a surface that grew.
fn deliberate_use_name(cmd: &Commands) -> Option<&'static str> {
    Some(match cmd {
        Commands::Hook { .. } | Commands::Completions { .. } => return None,
        Commands::Serve { .. } => "serve",
        Commands::Daemon { .. } => "daemon",
        Commands::Analyze { .. } => "analyze",
        Commands::Refs { .. } => "refs",
        Commands::Watch { .. } => "watch",
        Commands::Status => "status",
        Commands::Callers { .. } => "callers",
        Commands::Communities { .. } => "communities",
        Commands::Impact { .. } => "impact",
        Commands::Dataflow { .. } => "dataflow",
        Commands::Verify { .. } => "verify",
        Commands::Changed { .. } => "changed",
        Commands::Census { .. } => "census",
        Commands::Export { .. } => "export",
        Commands::Promote { .. } => "promote",
        #[cfg(feature = "quipu")]
        Commands::Verifier { .. } => "verifier",
    })
}

impl Cli {
    /// Whether `--verbose` was passed. Consulted by `main` to raise the default
    /// tracing verbosity (see [`init_tracing`]).
    #[must_use]
    pub fn verbose(&self) -> bool {
        self.verbose
    }

    /// Load configuration honouring the global `--config` override.
    ///
    /// Every command that reads config goes through here, so `--config` is
    /// honoured uniformly rather than silently ignored on all but a chosen few
    /// (aegis-ll3p).
    fn load_config(&self, root: &Path) -> anyhow::Result<HankConfig> {
        HankConfig::resolve(self.config.as_deref(), root).map_err(Into::into)
    }

    /// Run the parsed command.
    pub async fn run(self) -> anyhow::Result<()> {
        // DELIBERATE-USE metric (aegis-0nng): the leverage signal aegis-m9ln's
        // workflow half exists to move — is anyone running analyze/impact/refs
        // BEFORE a change, or does hank only ever fire as the passive guard?
        // The hook is excluded (the guard spools its own richer line) and so is
        // shell completion (not a use). Fail-silent by the spool's contract.
        if let Some(cmd) = deliberate_use_name(&self.command) {
            crate::metrics::emit("command", &[("cmd", cmd.into())]);
        }
        match &self.command {
            Commands::Analyze { path, at } => self.analyze(path, at.as_deref()),
            Commands::Refs { symbol, path, at } => {
                self.refs(symbol.as_deref(), path, at.as_deref())
            }
            Commands::Watch { path } => self.watch(path).await,
            Commands::Status => self.status(),
            Commands::Hook { event } => match event {
                HookEvent::PostEdit => crate::hook::run_post_edit(self.tenant.as_deref()),
                HookEvent::PreBash => crate::hook::run_pre_bash(),
                HookEvent::PreEdit => {
                    crate::hook::run_pre_edit(self.tenant.as_deref(), self.config.as_deref())
                }
            },
            Commands::Completions { shell } => {
                let mut cmd = Cli::command();
                clap_complete::generate(*shell, &mut cmd, "hank", &mut io::stdout());
                Ok(())
            }
            #[cfg(feature = "quipu")]
            Commands::Verifier { key_path } => {
                let keypair = crate::verdict::load_or_generate(key_path)?;
                println!("verifier: {}", crate::verdict::VERIFIER);
                println!("public_key: {}", crate::verdict::public_key_hex(&keypair));
                Ok(())
            }
            Commands::Serve { http } => self.serve(*http).await,
            Commands::Daemon { port } => self.daemon(*port).await,
            Commands::Callers { symbol, path } => {
                cli_cmds::callers(self.json, self.quiet, symbol, path)
            }
            Commands::Communities { path } => cli_cmds::communities(self.json, self.quiet, path),
            Commands::Census { path } => cli_cmds::census(self.json, self.quiet, path),
            Commands::Impact {
                symbol,
                path,
                hops,
                cochange,
            } => cli_cmds::impact(
                self.json,
                self.quiet,
                symbol,
                path,
                *hops,
                cochange.as_deref(),
            ),
            Commands::Export {
                path,
                repo,
                format,
                to,
            } => {
                let ExportFormat::Turtle = format;
                match to {
                    // `export --to quipu` IS promotion (spec §15's other spelling),
                    // so it routes through the one promotion path — validate then
                    // write — rather than a second implementation that could drift
                    // from `promote`. It is a write, so honour the guard first.
                    Some(_) => {
                        self.load_config(path)?.write_guard("promotion")?;
                        self.promote(path, "HEAD", to.as_deref(), repo.as_deref())
                    }
                    None => cli_cmds::export(path, repo.as_deref()),
                }
            }
            Commands::Dataflow {
                function,
                path,
                var,
                forward,
                hops,
            } => cli_cmds::dataflow(
                self.json,
                self.quiet,
                function,
                path,
                var.as_deref(),
                *forward,
                *hops,
            ),
            Commands::Changed { base, to } => self.changed(base.as_deref(), to.as_deref()),
            Commands::Verify { file, buffer } => {
                cli_cmds::verify(self.json, self.quiet, file, buffer)
            }
            Commands::Promote {
                commit,
                to,
                repo,
                path,
            } => {
                // THE WRITE GUARD, made real (aegis-ltjo). Promotion is the write
                // hank performs, so `serve.read_only` must refuse it — BEFORE any
                // work, so the guard holds regardless of feature.
                self.load_config(path)?.write_guard("promotion")?;
                self.promote(path, commit, to.as_deref(), repo.as_deref())
            }
        }
    }

    /// Print a notice for a command whose engine has not yet landed.
    // Used only by the feature-stub arms (serve/daemon without `mcp`, promote
    // without `quipu`); a build with both features enabled reaches none, so it is
    // legitimately dead there.
    #[allow(dead_code)]
    fn planned(&self, name: &str, phase: u8, detail: &str) {
        if !self.quiet {
            eprintln!(
                "{} `{name}` is planned for Phase {phase}: {detail}. See docs/hank-spec.md.",
                "note:".yellow().bold()
            );
        }
    }
}

///
/// `RUST_LOG` wins when set — the conventional Rust escape hatch, and it can
/// target specific modules, which a boolean flag cannot. Absent it, `--verbose`
/// raises the default from `info` to `debug`. So precedence is
/// `RUST_LOG` > `--verbose` > the `info` default.
pub fn init_tracing(verbose: bool) {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new(default_log_level(verbose)));
    let _ = tracing_subscriber::fmt()
        .with_writer(io::stderr)
        .with_env_filter(filter)
        .try_init();
}

/// The default tracing level when `RUST_LOG` is unset.
fn default_log_level(verbose: bool) -> &'static str {
    if verbose {
        "debug"
    } else {
        "info"
    }
}

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

    #[test]
    fn verbose_raises_the_default_log_level() {
        assert_eq!(default_log_level(false), "info");
        assert_eq!(default_log_level(true), "debug");
    }
}