kkernel 0.9.0

khive kernel — stdio MCP server binary and admin CLI (sync, pack introspection, db ops)
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
//! CLI argument types and output types for `kkernel kg` subcommands.

use std::path::PathBuf;

use clap::Subcommand;
use khive_changeset::Envelope;
use serde::Serialize;

// ── Subcommand tree ────────────────────────────────────────────────────────────

/// Subcommands for `kkernel kg` — KG validation/review, sync, import/export, and hooks.
#[derive(Subcommand, Debug)]
pub enum KgCommand {
    /// Validate the KG in `.khive/kg/` against structural and rule-pass checks.
    Validate(ValidateArgs),

    /// Initialize `.khive/kg/` and write `.khive/khive.toml` with defaults.
    Init(InitArgs),

    /// Fetch a remote KG archive into `.khive/kg/remotes/<remote>/`.
    ///
    /// `sync` is a visible alias so `kkernel kg sync --repin <remote>`
    /// reaches the same implementation.
    #[command(visible_alias = "sync")]
    Fetch(FetchArgs),

    /// Export a namespace-scoped KG archive from a SQLite DB.
    Export(ExportArgs),

    /// Import a KG archive or flat adapter records into a SQLite DB.
    Import(ImportArgs),

    /// Compare DB state against `.khive/kg/{entities,edges}.ndjson`.
    Status(StatusArgs),

    /// Manage the pre-commit hook for KG validation.
    #[command(subcommand)]
    Hook(HookCommand),

    /// Validate and commit a staged tier-2 change-set (ADR-102 Amendment to ADR-020).
    Commit(CommitArgs),

    /// Review a staged change-set without applying or committing it (ADR-145).
    Review(ReviewArgs),
}

/// CLI arguments for `kkernel kg validate`.
#[derive(clap::Parser, Debug)]
pub struct ValidateArgs {
    /// Repository root containing `.khive/kg/`.
    #[arg(long, default_value = ".")]
    pub repo: PathBuf,

    /// Apply fixable rules and report what changed.
    #[arg(long)]
    pub fix: bool,

    /// Treat warnings as errors; exit 1 when warnings > 0.
    #[arg(long)]
    pub strict: bool,

    /// Output format.
    #[arg(long, default_value = "text")]
    pub format: OutputFormat,

    /// Show all violations (default: cap at 2 then `+ N more`).
    #[arg(long)]
    pub verbose: bool,

    /// Print summary line only.
    #[arg(long)]
    pub quiet: bool,

    /// Override the default `.khive/kg/rules.toml` path.
    #[arg(long)]
    pub rules: Option<PathBuf>,

    /// Run built-in structural checks only; skip `rules.yaml`.
    #[arg(long)]
    pub no_rules: bool,
}

/// Supported output formats for validation reports.
#[derive(clap::ValueEnum, Debug, Clone, Copy)]
pub enum OutputFormat {
    Text,
    Json,
    Github,
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputFormat::Text => write!(f, "text"),
            OutputFormat::Json => write!(f, "json"),
            OutputFormat::Github => write!(f, "github"),
        }
    }
}

/// CLI arguments for `kkernel kg init`.
#[derive(clap::Parser, Debug)]
pub struct InitArgs {
    /// Repository root to initialize.
    #[arg(long, default_value = ".")]
    pub repo: PathBuf,

    /// Also generate `.github/workflows/kg-validate.yml`.
    #[arg(long)]
    pub ci: bool,

    /// Install the pre-commit hook without reinitializing.
    #[arg(long)]
    pub add_hooks: bool,
}

/// CLI arguments for `kkernel kg fetch` (alias: `sync`).
#[derive(clap::Parser, Debug)]
pub struct FetchArgs {
    /// Remote name, used for cache path `.khive/kg/remotes/<remote>`.
    pub remote: String,

    /// Repository root that owns `.khive/`.
    #[arg(long, default_value = ".")]
    pub repo: PathBuf,

    /// Git remote URL.
    #[arg(long)]
    pub url: String,

    /// Git ref to fetch.
    #[arg(long = "ref", default_value = "main")]
    pub git_ref: String,

    /// Namespace to assign to fetched records.
    #[arg(long, default_value = "local")]
    pub namespace: String,

    /// Optional content hash pin: sha256:<64 lowercase hex chars>.
    #[arg(long)]
    pub pin: Option<String>,

    /// Accept the fetched content hash and return it for schema.yaml repinning.
    #[arg(long)]
    pub repin: bool,
}

/// CLI arguments for `kkernel kg export`.
#[derive(clap::Parser, Debug)]
pub struct ExportArgs {
    /// Output archive JSON path.
    pub output: PathBuf,

    /// SQLite database path. Required so this command never defaults to ~/.khive.
    #[arg(long)]
    pub db: PathBuf,

    /// Namespace to export.
    #[arg(long, default_value = "local")]
    pub namespace: String,
}

/// CLI arguments for `kkernel kg import`.
#[derive(clap::Parser, Debug)]
pub struct ImportArgs {
    /// Source archive or adapter input file.
    pub source: PathBuf,

    /// SQLite database path. Required so this command never defaults to ~/.khive.
    #[arg(long)]
    pub db: PathBuf,

    /// Namespace for imported records.
    #[arg(long, default_value = "local")]
    pub namespace: String,

    /// Import format. Default is the `KgArchive` JSON envelope.
    #[arg(long, value_enum, default_value_t = ImportFormat::Archive)]
    pub format: ImportFormat,

    /// Print adapter warnings to stderr.
    #[arg(long)]
    pub verbose: bool,
}

/// Supported input formats for `kkernel kg import`.
#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportFormat {
    Archive,
    Json,
    Ndjson,
}

/// CLI arguments for `kkernel kg status`.
#[derive(clap::Parser, Debug)]
pub struct StatusArgs {
    /// Repository root containing `.khive/kg/{entities,edges}.ndjson`.
    #[arg(long, default_value = ".")]
    pub repo: PathBuf,

    /// SQLite database path. Required so this command never defaults to ~/.khive.
    #[arg(long)]
    pub db: PathBuf,

    /// Namespace to compare.
    #[arg(long, default_value = "local")]
    pub namespace: String,
}

/// CLI arguments for `kkernel kg commit`.
///
/// Restores the `kg commit` primitive [ADR-020](../../../docs/adr/ADR-020-git-native-kg-implementation.md)
/// §5 specified but never shipped, scoped per
/// [ADR-102](../../../docs/adr/ADR-102-tiered-validate-and-merge.md)'s Amendment
/// to ADR-020: the tier-2 commit step for an already-reviewed staged
/// change-set, against this ADR's own local-only change-set/snapshot
/// repository (D6) — not the project-repository-embedded `.khive/kg/` layout
/// `validate`/`init`/`export`/`import`/`status` operate on.
#[derive(clap::Parser, Debug)]
pub struct CommitArgs {
    /// Path to the staged change-set NDJSON-delta file (ADR-101 D2).
    pub changeset: PathBuf,

    /// Path to the rules file (TOML) the change-set is validated against
    /// before it may be committed. Required — the rules file is load-bearing
    /// configuration for this primitive, not an optional convenience.
    #[arg(long)]
    pub rules: PathBuf,

    /// Target git repository holding staged change-sets and committed
    /// snapshots. Must have no configured git remote (ADR-102 D6) — this
    /// repository is local-only by binding constraint.
    #[arg(long, default_value = ".")]
    pub repo: PathBuf,

    /// Commit message body: a human-readable description of the batch
    /// (ADR-101 D4).
    #[arg(short = 'm', long = "message")]
    pub message: String,

    /// Output format for the pre-commit validation report.
    #[arg(long, default_value = "text")]
    pub format: OutputFormat,
}

/// CLI arguments for `kkernel kg review`.
///
/// This is the read-only, npm-routed review slice from ADR-145 D8. It parses
/// the strict ADR-101 change-set, runs the same partial-view rule pass as
/// `kg commit`, and evaluates the ADR-102 tier/reviewer floor. It deliberately
/// accepts no repository, database, apply, commit, or publish arguments.
#[derive(clap::Parser, Debug)]
pub struct ReviewArgs {
    /// Path to the staged ADR-101 NDJSON-delta change-set.
    pub changeset: PathBuf,

    /// Explicit TOML rules file used by the commit-time partial-view rule pass.
    #[arg(long)]
    pub rules: PathBuf,

    /// Opaque reviewer model-family token used by the ADR-102 Tier-2 gate.
    #[arg(long)]
    pub reviewer_model_family: Option<String>,

    /// Output format for the versioned review report.
    #[arg(long, default_value = "text")]
    pub format: OutputFormat,
}

/// Result of a successful `kkernel kg commit` run.
#[derive(Debug, Serialize)]
pub struct CommitReport {
    /// SHA of the git commit that landed the change-set.
    pub commit_sha: String,
    /// Path (relative to `repo`) of the committed change-set file.
    pub changeset_path: String,
    /// Number of operations in the committed change-set.
    pub ops: usize,
    /// `Envelope::producer` — carried as the `Change-Set-Producer` trailer.
    pub producer: String,
    /// Value carried as the `Change-Set-Producer-Batch` trailer (see
    /// `kg::commit` module docs for how it is derived from the envelope).
    pub producer_batch: String,
}

/// Stable read-only report emitted by `kkernel kg review` (ADR-145 D4/D8).
#[derive(Debug, Serialize)]
pub struct ReviewReport {
    pub schema_version: &'static str,
    pub review_kind: &'static str,
    pub capability: ReviewCapability,
    pub change_set: ReviewChangeSet,
    pub tier_summary: ReviewTierSummary,
    pub validation: ReviewValidationSummary,
    pub findings: Vec<ReviewFinding>,
    pub review_gate: ReviewGate,
}

/// Provenance envelope and ordered operation summaries for the reviewed batch.
#[derive(Debug, Serialize)]
pub struct ReviewChangeSet {
    pub envelope: Envelope,
    pub operations: Vec<ReviewOperation>,
}

/// One ADR-101 operation in source order with its ADR-102 floor classification.
#[derive(Debug, Serialize)]
pub struct ReviewOperation {
    pub index: usize,
    pub id: String,
    pub op: String,
    pub target: String,
    pub tier: String,
    pub summary: String,
    pub reason: String,
    pub tier_reasons: Vec<String>,
    pub entity_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<serde_json::Value>,
}

/// Aggregate tier counts for the ordered operation list.
#[derive(Debug, Serialize)]
pub struct ReviewTierSummary {
    pub operations: usize,
    pub tier_1: usize,
    pub tier_2: usize,
    pub highest_tier: String,
    pub requires_independent_review: bool,
    pub policy: &'static str,
}

/// A deterministic, flattened validation finding.
#[derive(Debug, Serialize)]
pub struct ReviewFinding {
    pub rule_id: String,
    pub severity: String,
    pub message: String,
    pub subject_id: Option<String>,
    pub subject_name: Option<String>,
    pub subject_kind: Option<String>,
    pub fixable: bool,
}

/// Aggregate state for the reused commit-time partial-view rule pass.
#[derive(Debug, Serialize)]
pub struct ReviewValidationSummary {
    pub scope: &'static str,
    pub rules_evaluated: usize,
    pub failed_rules: usize,
    pub errors: usize,
    pub warnings: usize,
    pub info: usize,
    pub passed: bool,
}

/// ADR-102 independent-review routing result.
#[derive(Debug, Serialize)]
pub struct ReviewGate {
    pub required: bool,
    pub producer_model_family: String,
    pub reviewer_model_family: Option<String>,
    pub eligible: bool,
    pub approval_ready: bool,
    pub status: String,
    pub reason: String,
    pub persisted: bool,
}

/// Explicit capability declaration for the initial local review slice.
#[derive(Debug, Serialize)]
pub struct ReviewCapability {
    pub source: &'static str,
    pub mutability: &'static str,
    pub no_writes: bool,
    pub git_reads: bool,
    pub khive_reads: bool,
    pub github_writes: bool,
    pub wasm: bool,
    pub persistence: bool,
    pub unavailable_actions: [&'static str; 5],
}

/// Subcommands for `kkernel kg hook` — install, remove, and check the pre-commit hook.
#[derive(Subcommand, Debug)]
pub enum HookCommand {
    /// Create `.git/hooks/pre-commit` symlink pointing to the tracked hook.
    Install {
        #[arg(long, default_value = ".")]
        repo: PathBuf,
    },
    /// Remove the `.git/hooks/pre-commit` symlink.
    Uninstall {
        #[arg(long, default_value = ".")]
        repo: PathBuf,
    },
    /// Show whether the hook symlink exists and points to a valid target.
    Status {
        #[arg(long, default_value = ".")]
        repo: PathBuf,
    },
}

// ── Output types ───────────────────────────────────────────────────────────────

/// Hash-based comparison result between the DB state and on-disk NDJSON files.
#[derive(Debug, Serialize)]
pub struct KgStatusReport {
    pub db_hash: String,
    pub ndjson_hash: String,
    pub clean: bool,
}

/// Aggregate result of a `kkernel kg validate` run.
#[derive(Debug, Serialize)]
pub struct ValidationReport {
    pub rules: Vec<RuleResult>,
    pub summary: ValidationSummary,
}

/// Result for a single validation rule in a `kkernel kg validate` run.
#[derive(Debug, Serialize)]
pub struct RuleResult {
    pub id: String,
    pub severity: &'static str,
    pub passed: bool,
    pub violations: Vec<Violation>,
}

/// A single rule violation with location metadata and a fixability flag.
#[derive(Debug, Serialize)]
pub struct Violation {
    pub entity_id: Option<String>,
    pub entity_name: Option<String>,
    pub entity_kind: Option<String>,
    pub rule_id: String,
    pub severity: &'static str,
    pub message: String,
    pub fixable: bool,
}

/// Aggregate counts from a `kkernel kg validate` run.
#[derive(Debug, Serialize)]
pub struct ValidationSummary {
    pub errors: usize,
    pub warnings: usize,
    pub info: usize,
    pub entities: usize,
    pub edges: usize,
    pub empty: bool,
    pub passed: bool,
}

/// Status of the pre-commit hook symlink for KG validation.
#[derive(Debug, Serialize)]
pub struct HookStatus {
    pub symlink_exists: bool,
    pub symlink_target: Option<String>,
    pub target_valid: bool,
}