ckm 0.2.0

CKM (Codebase Knowledge Manifest) — pure Rust core library. The SSoT for all language wrappers.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! CKM type definitions — Rust implementation of INTERFACE.md v2.0.0.
//!
//! Every type here has a 1:1 correspondence with the Single Source of Truth interface definition.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// Freeform extension data. Producers can attach arbitrary key-value pairs
/// to any CKM entity. The SDK passes these through without validation.
pub type Extensions = HashMap<String, serde_json::Value>;

// ────────────────────────────────────────────────────────────────────────────
// Section 2: Input Types (from ckm.json v2)
// ────────────────────────────────────────────────────────────────────────────

/// The set of portable primitive types, mapped to JSON Schema primitives.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CanonicalType {
    /// JSON string type.
    String,
    /// JSON boolean type.
    Boolean,
    /// JSON number type (floating point).
    Number,
    /// JSON integer type.
    Integer,
    /// JSON array type.
    Array,
    /// JSON object type.
    Object,
    /// JSON null type.
    Null,
    /// Any type (untyped).
    Any,
}

impl CanonicalType {
    /// Parses a string into a CanonicalType. Defaults to Object for unknown types.
    pub fn parse(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "string" => Self::String,
            "boolean" | "bool" => Self::Boolean,
            "number" | "float" | "f64" => Self::Number,
            "integer" | "int" | "i64" => Self::Integer,
            "array" => Self::Array,
            "object" => Self::Object,
            "null" | "void" | "undefined" => Self::Null,
            "any" | "unknown" => Self::Any,
            _ => Self::Object,
        }
    }
}

impl std::fmt::Display for CanonicalType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            CanonicalType::String => "string",
            CanonicalType::Boolean => "boolean",
            CanonicalType::Number => "number",
            CanonicalType::Integer => "integer",
            CanonicalType::Array => "array",
            CanonicalType::Object => "object",
            CanonicalType::Null => "null",
            CanonicalType::Any => "any",
        };
        write!(f, "{}", s)
    }
}

/// A portable type reference with canonical mapping.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmTypeRef {
    /// Language-agnostic canonical type.
    pub canonical: CanonicalType,

    /// Source language type annotation (e.g., `CalVerFormat`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub original: Option<String>,

    /// Known enum values for string types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#enum: Option<Vec<String>>,
}

/// A property within a concept.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmProperty {
    /// Property name.
    pub name: String,

    /// Type reference (canonical + original).
    pub r#type: CkmTypeRef,

    /// Description from source documentation.
    pub description: String,

    /// Whether the property is required.
    pub required: bool,

    /// Default value. Null means no default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
}

/// A domain concept extracted from source code.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmConcept {
    /// Unique identifier (e.g., "concept-calver-config").
    pub id: String,

    /// Type name (e.g., `CalVerConfig`).
    pub name: String,

    /// Topic slug (e.g., "calver") — used for topic derivation.
    pub slug: String,

    /// One-line description.
    pub what: String,

    /// Semantic tags (e.g., ["config"]).
    pub tags: Vec<String>,

    /// Properties of the type, if applicable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<Vec<CkmProperty>>,

    /// Validation rules extracted from remarks or constraint tags.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rules: Option<Vec<String>>,

    /// Related concept names from @see tags or type references.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_to: Option<Vec<String>>,

    /// Producer-defined extension data. CKM passes this through without validation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Extensions>,
}

/// A function parameter within an operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmInput {
    /// Parameter name.
    pub name: String,

    /// Type reference.
    pub r#type: CkmTypeRef,

    /// Whether the parameter is required.
    pub required: bool,

    /// Description from source documentation.
    pub description: String,
}

/// A return value from an operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmOutput {
    /// Type reference.
    pub r#type: CkmTypeRef,

    /// Description of the return value.
    pub description: String,
}

/// A user-facing operation extracted from source code.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmOperation {
    /// Unique identifier (e.g., "op-validate").
    pub id: String,

    /// Function name (e.g., "validate").
    pub name: String,

    /// One-line description.
    pub what: String,

    /// Semantic tags for topic linkage.
    pub tags: Vec<String>,

    /// Preconditions that must be met before invoking this operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preconditions: Option<Vec<String>>,

    /// Function parameters.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inputs: Option<Vec<CkmInput>>,

    /// Return value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outputs: Option<CkmOutput>,

    /// Exit codes and their meanings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_codes: Option<std::collections::HashMap<String, String>>,

    /// Checks or validations performed by this operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checks_performed: Option<Vec<String>>,

    /// Producer-defined extension data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Extensions>,
}

/// A rule enforced by the tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmConstraint {
    /// Unique identifier (e.g., "constraint-future-date").
    pub id: String,

    /// Human-readable rule description.
    pub rule: String,

    /// Function or module that enforces the constraint.
    pub enforced_by: String,

    /// Severity level.
    pub severity: Severity,

    /// Config key that controls this constraint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_key: Option<String>,

    /// Default value for the config key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Whether this constraint has security implications.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub security: Option<bool>,

    /// Producer-defined extension data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Extensions>,
}

/// Severity levels for constraints.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Validation error — must be fixed.
    Error,
    /// Validation warning — should be addressed.
    Warning,
    /// Informational notice.
    Info,
}

/// A single step within a workflow.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmWorkflowStep {
    /// Discriminant: CLI command or manual action.
    pub action: StepAction,

    /// The command or instruction.
    pub value: String,

    /// Optional explanatory note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,

    /// Expected outcome of this step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect: Option<String>,
}

/// Discriminant for workflow step types.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StepAction {
    /// A CLI command to execute.
    Command,
    /// A manual action for the user to perform.
    Manual,
}

/// A multi-step workflow for achieving a common goal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmWorkflow {
    /// Unique identifier.
    pub id: String,

    /// What the workflow achieves.
    pub goal: String,

    /// Semantic tags.
    pub tags: Vec<String>,

    /// Ordered steps (minimum 1).
    pub steps: Vec<CkmWorkflowStep>,

    /// Producer-defined extension data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Extensions>,
}

/// A configuration schema entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmConfigEntry {
    /// Dotted key path (e.g., "calver.format").
    pub key: String,

    /// Type reference.
    pub r#type: CkmTypeRef,

    /// Description.
    pub description: String,

    /// Default value. Null means no default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Whether the config entry is required.
    pub required: bool,

    /// Downstream effect or behavior this config entry controls.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effect: Option<String>,

    /// Producer-defined extension data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Extensions>,
}

/// A producer-declared topic grouping for the manifest.
///
/// When present in the manifest, these override engine-derived topics.
/// This gives generators full control over topic structure.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmDeclaredTopic {
    /// Topic slug (e.g., "getting-started").
    pub name: String,

    /// One-line summary.
    pub summary: String,

    /// IDs of concepts belonging to this topic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub concept_ids: Vec<String>,

    /// IDs of operations belonging to this topic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub operation_ids: Vec<String>,

    /// IDs of constraints belonging to this topic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraint_ids: Vec<String>,

    /// Config key prefixes belonging to this topic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub config_keys: Vec<String>,
}

/// Provenance metadata about the manifest source.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmMeta {
    /// Project name (e.g., "my-tool").
    pub project: String,

    /// Source language (e.g., "typescript", "python", "rust").
    pub language: String,

    /// Tool that generated the manifest (e.g., "forge-ts@0.21.1").
    pub generator: String,

    /// ISO 8601 timestamp of generation.
    pub generated: String,

    /// Optional URL to source repository.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_url: Option<String>,
}

/// The top-level CKM manifest object (v2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmManifest {
    /// Schema URL (e.g., `https://ckm.dev/schemas/v2.json`).
    #[serde(rename = "$schema")]
    pub schema: String,

    /// Schema version (e.g., "2.0.0").
    pub version: String,

    /// Project metadata and provenance.
    pub meta: CkmMeta,

    /// Domain concepts (interfaces, types).
    pub concepts: Vec<CkmConcept>,

    /// User-facing operations (functions).
    pub operations: Vec<CkmOperation>,

    /// Enforced rules.
    pub constraints: Vec<CkmConstraint>,

    /// Multi-step workflows.
    pub workflows: Vec<CkmWorkflow>,

    /// Configuration schema entries.
    pub config_schema: Vec<CkmConfigEntry>,

    /// Producer-declared topics. When present, these override engine-derived topics.
    /// This gives generators full control over topic grouping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topics: Option<Vec<CkmDeclaredTopic>>,

    /// Producer-defined extension data at the manifest level.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Extensions>,
}

// ────────────────────────────────────────────────────────────────────────────
// Section 3: Derived Types (computed by the engine)
// ────────────────────────────────────────────────────────────────────────────

/// An auto-derived topic grouping related concepts, operations, config, and constraints.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmTopic {
    /// Slug used as CLI argument (e.g., "calver").
    pub name: String,

    /// One-line description (from the primary concept).
    pub summary: String,

    /// Related concepts.
    pub concepts: Vec<CkmConcept>,

    /// Related operations.
    pub operations: Vec<CkmOperation>,

    /// Related config entries.
    pub config_schema: Vec<CkmConfigEntry>,

    /// Related constraints.
    pub constraints: Vec<CkmConstraint>,
}

/// A summary entry for the topic index.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmTopicIndexEntry {
    /// Topic slug.
    pub name: String,

    /// One-line description.
    pub summary: String,

    /// Count of related concepts.
    pub concepts: usize,

    /// Count of related operations.
    pub operations: usize,

    /// Count of related config entries.
    pub config_fields: usize,

    /// Count of related constraints.
    pub constraints: usize,
}

/// Aggregate manifest counts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmManifestCounts {
    /// Total concepts in manifest.
    pub concepts: usize,

    /// Total operations.
    pub operations: usize,

    /// Total constraints.
    pub constraints: usize,

    /// Total workflows.
    pub workflows: usize,

    /// Total config entries.
    pub config_schema: usize,
}

/// The full topic index returned by `topic_json()` with no argument.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmTopicIndex {
    /// All topic summaries.
    pub topics: Vec<CkmTopicIndexEntry>,

    /// Aggregate manifest counts.
    pub ckm: CkmManifestCounts,
}

/// Manifest statistics returned by `inspect()`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmInspectResult {
    /// Manifest metadata.
    pub meta: CkmMeta,

    /// Counts of each manifest section.
    pub counts: CkmInspectCounts,

    /// List of derived topic slugs.
    pub topic_names: Vec<String>,
}

/// Counts for the inspect result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmInspectCounts {
    /// Number of concepts.
    pub concepts: usize,
    /// Number of operations.
    pub operations: usize,
    /// Number of constraints.
    pub constraints: usize,
    /// Number of workflows.
    pub workflows: usize,
    /// Number of config keys.
    pub config_keys: usize,
    /// Number of derived topics.
    pub topics: usize,
}

/// A single validation error with a JSON pointer path.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmValidationError {
    /// JSON pointer path (e.g., "/concepts/0/slug").
    pub path: String,

    /// Human-readable error message.
    pub message: String,
}

/// Result of manifest validation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmValidationResult {
    /// Whether the manifest is valid.
    pub valid: bool,

    /// Validation errors (empty if valid).
    pub errors: Vec<CkmValidationError>,
}

/// Error returned when a topic is not found.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CkmErrorResult {
    /// Error message (e.g., "Unknown topic: foo").
    pub error: String,

    /// Available topic names for suggestion.
    pub topics: Vec<String>,
}

/// The result of `topic_json()` — either a topic index, a single topic, or an error.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TopicJsonResult {
    /// Full topic index (when no topic name is given).
    Index(CkmTopicIndex),

    /// Single topic detail (when topic name matches).
    Topic(CkmTopic),

    /// Error result (when topic name does not match).
    Error(CkmErrorResult),
}