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
//! CKM engine — auto-generates topic index from a ckm.json manifest.
//!
//! Implements SPEC.md algorithms for topic derivation, JSON output, and
//! terminal formatting. Handles both v1 and v2 manifests transparently.

use serde_json::Value;

use crate::format::{format_topic_content, format_topic_index};
use crate::migrate::{derive_slug, detect_version, migrate_v1_to_v2};
use crate::types::{
    CkmConcept, CkmErrorResult, CkmInspectCounts, CkmInspectResult, CkmManifest, CkmManifestCounts,
    CkmTopic, CkmTopicIndex, CkmTopicIndexEntry, TopicJsonResult,
};

/// The core CKM engine.
///
/// Consumes a manifest (v1 or v2), derives topics at construction time,
/// and exposes methods for progressive disclosure at four levels.
#[derive(Debug, Clone)]
pub struct CkmEngine {
    manifest: CkmManifest,
    derived_topics: Vec<CkmTopic>,
}

impl CkmEngine {
    /// Creates a new CKM engine from a parsed JSON value.
    ///
    /// If the input is a v1 manifest, it is automatically migrated to v2.
    /// Topics are derived at construction time.
    pub fn new(data: Value) -> Self {
        let version = detect_version(&data);
        let manifest = if version == 1 {
            migrate_v1_to_v2(&data)
        } else {
            serde_json::from_value(data).unwrap_or_else(|_| CkmManifest {
                schema: String::new(),
                version: "2.0.0".to_string(),
                meta: crate::types::CkmMeta {
                    project: "unknown".to_string(),
                    language: "unknown".to_string(),
                    generator: "unknown".to_string(),
                    generated: String::new(),
                    source_url: None,
                },
                concepts: Vec::new(),
                operations: Vec::new(),
                constraints: Vec::new(),
                workflows: Vec::new(),
                config_schema: Vec::new(),
                topics: None,
                extensions: None,
            })
        };

        // Use producer-declared topics if present, otherwise derive from manifest
        let derived_topics = if let Some(ref declared) = manifest.topics {
            resolve_declared_topics(declared, &manifest)
        } else {
            derive_topics(&manifest)
        };

        CkmEngine {
            manifest,
            derived_topics,
        }
    }

    /// All auto-derived topics, computed at construction time.
    pub fn topics(&self) -> &[CkmTopic] {
        &self.derived_topics
    }

    /// Returns formatted topic index for terminal display (Level 0).
    ///
    /// Output stays within 300 token budget.
    pub fn topic_index(&self, tool_name: &str) -> String {
        format_topic_index(&self.derived_topics, tool_name)
    }

    /// Returns human-readable content for a specific topic (Level 1).
    ///
    /// Returns `None` if the topic is not found.
    /// Output stays within 800 token budget.
    pub fn topic_content(&self, topic_name: &str) -> Option<String> {
        format_topic_content(&self.derived_topics, topic_name)
    }

    /// Returns structured JSON data for a topic or the full index.
    ///
    /// - If `topic_name` is `None`: returns `TopicJsonResult::Index` (Level 2)
    /// - If `topic_name` matches a topic: returns `TopicJsonResult::Topic` (Level 1J)
    /// - If `topic_name` does not match: returns `TopicJsonResult::Error`
    pub fn topic_json(&self, topic_name: Option<&str>) -> TopicJsonResult {
        match topic_name {
            None => TopicJsonResult::Index(self.build_topic_index_json()),
            Some(name) => self.build_topic_json(name),
        }
    }

    /// Returns the raw manifest (v2, possibly migrated from v1).
    pub fn manifest(&self) -> &CkmManifest {
        &self.manifest
    }

    /// Returns manifest statistics: metadata, counts, and topic names.
    pub fn inspect(&self) -> CkmInspectResult {
        CkmInspectResult {
            meta: self.manifest.meta.clone(),
            counts: CkmInspectCounts {
                concepts: self.manifest.concepts.len(),
                operations: self.manifest.operations.len(),
                constraints: self.manifest.constraints.len(),
                workflows: self.manifest.workflows.len(),
                config_keys: self.manifest.config_schema.len(),
                topics: self.derived_topics.len(),
            },
            topic_names: self.derived_topics.iter().map(|t| t.name.clone()).collect(),
        }
    }

    fn build_topic_index_json(&self) -> CkmTopicIndex {
        CkmTopicIndex {
            topics: self
                .derived_topics
                .iter()
                .map(|t| CkmTopicIndexEntry {
                    name: t.name.clone(),
                    summary: t.summary.clone(),
                    concepts: t.concepts.len(),
                    operations: t.operations.len(),
                    config_fields: t.config_schema.len(),
                    constraints: t.constraints.len(),
                })
                .collect(),
            ckm: CkmManifestCounts {
                concepts: self.manifest.concepts.len(),
                operations: self.manifest.operations.len(),
                constraints: self.manifest.constraints.len(),
                workflows: self.manifest.workflows.len(),
                config_schema: self.manifest.config_schema.len(),
            },
        }
    }

    fn build_topic_json(&self, topic_name: &str) -> TopicJsonResult {
        match self.derived_topics.iter().find(|t| t.name == topic_name) {
            Some(topic) => TopicJsonResult::Topic(topic.clone()),
            None => TopicJsonResult::Error(CkmErrorResult {
                error: format!("Unknown topic: {}", topic_name),
                topics: self.derived_topics.iter().map(|t| t.name.clone()).collect(),
            }),
        }
    }
}

// ─── Producer-Declared Topics ───────────────────────────────────────────

/// Resolves producer-declared topics by looking up IDs in the manifest.
/// This gives generators full control over topic grouping.
fn resolve_declared_topics(
    declared: &[crate::types::CkmDeclaredTopic],
    manifest: &CkmManifest,
) -> Vec<CkmTopic> {
    declared
        .iter()
        .map(|dt| {
            let concepts: Vec<_> = manifest
                .concepts
                .iter()
                .filter(|c| dt.concept_ids.contains(&c.id))
                .cloned()
                .collect();

            let operations: Vec<_> = manifest
                .operations
                .iter()
                .filter(|o| dt.operation_ids.contains(&o.id))
                .cloned()
                .collect();

            let constraints: Vec<_> = manifest
                .constraints
                .iter()
                .filter(|c| dt.constraint_ids.contains(&c.id))
                .cloned()
                .collect();

            let config_schema: Vec<_> = manifest
                .config_schema
                .iter()
                .filter(|e| dt.config_keys.iter().any(|k| e.key.starts_with(k)))
                .cloned()
                .collect();

            CkmTopic {
                name: dt.name.clone(),
                summary: dt.summary.clone(),
                concepts,
                operations,
                config_schema,
                constraints,
            }
        })
        .collect()
}

// ─── Topic Derivation (SPEC.md Section 3 — revised) ────────────────────
//
// Every concept with a non-empty slug becomes a topic.
// Operations/constraints/config are matched by tag overlap or keyword.
// Unmatched operations get their own topics so nothing is invisible.

fn derive_topics(manifest: &CkmManifest) -> Vec<CkmTopic> {
    let mut topics: Vec<CkmTopic> = Vec::new();
    let mut claimed_op_ids: Vec<String> = Vec::new();
    let mut claimed_constraint_ids: Vec<String> = Vec::new();

    // Phase 1: Every concept with a slug becomes a topic
    for concept in &manifest.concepts {
        let slug = &concept.slug;
        if slug.is_empty() {
            continue;
        }

        // Skip if we already have a topic with this slug (dedup)
        if topics.iter().any(|t| t.name == *slug) {
            // Merge this concept into the existing topic
            if let Some(existing) = topics.iter_mut().find(|t| t.name == *slug) {
                existing.concepts.push(concept.clone());
            }
            continue;
        }

        // Collect related concepts (same slug or name contains slug)
        let mut related_concepts: Vec<CkmConcept> = vec![concept.clone()];
        for other in &manifest.concepts {
            if other.id == concept.id {
                continue;
            }
            if other.slug == *slug {
                related_concepts.push(other.clone());
            } else {
                let other_slug = derive_slug(&other.name);
                if other.name.to_lowercase().contains(slug) || slug.contains(&other_slug) {
                    related_concepts.push(other.clone());
                }
            }
        }
        let concept_names: Vec<String> = related_concepts.iter().map(|c| c.name.clone()).collect();

        // Match operations by tag overlap or keyword
        let matched_operations: Vec<_> = manifest
            .operations
            .iter()
            .filter(|op| {
                if op.tags.iter().any(|t| t.to_lowercase() == slug.to_lowercase()) {
                    return true;
                }
                matches_by_keyword(&op.name, &op.what, slug, &concept_names)
            })
            .cloned()
            .collect();
        for op in &matched_operations {
            claimed_op_ids.push(op.id.clone());
        }

        // Match config entries by key prefix
        let matched_config: Vec<_> = manifest
            .config_schema
            .iter()
            .filter(|entry| {
                let key_prefix = entry.key.split('.').next().unwrap_or("");
                key_prefix == slug
            })
            .cloned()
            .collect();

        // Match constraints by enforcedBy referencing concepts or matched operations
        let matched_constraints: Vec<_> = manifest
            .constraints
            .iter()
            .filter(|c| {
                if concept_names.iter().any(|name| c.enforced_by.contains(name.as_str())) {
                    return true;
                }
                matched_operations.iter().any(|op| c.enforced_by.contains(op.name.as_str()))
            })
            .cloned()
            .collect();
        for c in &matched_constraints {
            claimed_constraint_ids.push(c.id.clone());
        }

        topics.push(CkmTopic {
            name: slug.clone(),
            summary: concept.what.clone(),
            concepts: related_concepts,
            operations: matched_operations,
            config_schema: matched_config,
            constraints: matched_constraints,
        });
    }

    // Phase 2: Unclaimed operations get their own topics
    for op in &manifest.operations {
        if claimed_op_ids.contains(&op.id) {
            continue;
        }
        let slug = derive_slug(&op.name);
        if slug.is_empty() {
            continue;
        }
        // If a topic with this slug already exists, add the operation to it
        if let Some(existing) = topics.iter_mut().find(|t| t.name == slug) {
            existing.operations.push(op.clone());
            claimed_op_ids.push(op.id.clone());
            continue;
        }
        // Create a new topic for this operation
        topics.push(CkmTopic {
            name: slug.clone(),
            summary: op.what.clone(),
            concepts: Vec::new(),
            operations: vec![op.clone()],
            config_schema: Vec::new(),
            constraints: Vec::new(),
        });
        claimed_op_ids.push(op.id.clone());
    }

    // Phase 3: Unclaimed constraints get added to matching topics or their own
    for constraint in &manifest.constraints {
        if claimed_constraint_ids.contains(&constraint.id) {
            continue;
        }
        // Try to find a topic whose operations match enforcedBy
        let mut matched = false;
        for topic in &mut topics {
            if topic.operations.iter().any(|op| constraint.enforced_by.contains(op.name.as_str())) {
                topic.constraints.push(constraint.clone());
                matched = true;
                break;
            }
        }
        if !matched {
            // Add to first topic or create an "other" topic
            if let Some(first) = topics.first_mut() {
                first.constraints.push(constraint.clone());
            }
        }
    }

    topics
}

/// Checks if a name+description matches a slug or concept names by keyword.
fn matches_by_keyword(name: &str, what: &str, slug: &str, concept_names: &[String]) -> bool {
    let haystack = format!("{} {}", name, what).to_lowercase();
    if haystack.contains(slug) {
        return true;
    }
    concept_names
        .iter()
        .any(|n| haystack.contains(&n.to_lowercase()))
}

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

    fn minimal_v2() -> Value {
        serde_json::json!({
            "$schema": "https://ckm.dev/schemas/v2.json",
            "version": "2.0.0",
            "meta": {
                "project": "test",
                "language": "typescript",
                "generator": "hand-authored",
                "generated": "2026-01-01T00:00:00.000Z"
            },
            "concepts": [
                {
                    "id": "concept-calver-config",
                    "name": "CalVerConfig",
                    "slug": "calver",
                    "what": "Configures CalVer validation rules.",
                    "tags": ["config"],
                    "properties": [
                        {
                            "name": "format",
                            "type": { "canonical": "string", "original": "CalVerFormat" },
                            "description": "Calendar format.",
                            "required": true,
                            "default": "YYYY.MM.DD"
                        }
                    ]
                }
            ],
            "operations": [
                {
                    "id": "op-validate",
                    "name": "validate",
                    "what": "Validates a calver version string.",
                    "tags": ["calver"],
                    "inputs": [
                        {
                            "name": "version",
                            "type": { "canonical": "string" },
                            "required": true,
                            "description": "The version string."
                        }
                    ]
                }
            ],
            "constraints": [
                {
                    "id": "constraint-no-future",
                    "rule": "No future dates.",
                    "enforcedBy": "validate",
                    "severity": "error"
                }
            ],
            "workflows": [],
            "configSchema": [
                {
                    "key": "calver.format",
                    "type": { "canonical": "string", "original": "CalVerFormat" },
                    "description": "Calendar format.",
                    "default": "YYYY.MM.DD",
                    "required": true
                }
            ]
        })
    }

    #[test]
    fn test_engine_new() {
        let engine = CkmEngine::new(minimal_v2());
        assert_eq!(engine.topics().len(), 1);
        assert_eq!(engine.topics()[0].name, "calver");
    }

    #[test]
    fn test_engine_topic_index() {
        let engine = CkmEngine::new(minimal_v2());
        let output = engine.topic_index("my-tool");
        assert!(output.contains("my-tool CKM"));
        assert!(output.contains("calver"));
    }

    #[test]
    fn test_engine_topic_content() {
        let engine = CkmEngine::new(minimal_v2());
        let output = engine.topic_content("calver").unwrap();
        assert!(output.contains("CalVerConfig"));
        assert!(engine.topic_content("nonexistent").is_none());
    }

    #[test]
    fn test_engine_topic_json_index() {
        let engine = CkmEngine::new(minimal_v2());
        match engine.topic_json(None) {
            TopicJsonResult::Index(idx) => {
                assert_eq!(idx.topics.len(), 1);
                assert_eq!(idx.topics[0].name, "calver");
            }
            _ => panic!("Expected TopicJsonResult::Index"),
        }
    }

    #[test]
    fn test_engine_topic_json_single() {
        let engine = CkmEngine::new(minimal_v2());
        match engine.topic_json(Some("calver")) {
            TopicJsonResult::Topic(t) => {
                assert_eq!(t.name, "calver");
            }
            _ => panic!("Expected TopicJsonResult::Topic"),
        }
    }

    #[test]
    fn test_engine_topic_json_error() {
        let engine = CkmEngine::new(minimal_v2());
        match engine.topic_json(Some("nonexistent")) {
            TopicJsonResult::Error(e) => {
                assert!(e.error.contains("Unknown topic"));
                assert!(e.topics.contains(&"calver".to_string()));
            }
            _ => panic!("Expected TopicJsonResult::Error"),
        }
    }

    #[test]
    fn test_engine_manifest() {
        let engine = CkmEngine::new(minimal_v2());
        assert_eq!(engine.manifest().meta.project, "test");
    }

    #[test]
    fn test_engine_inspect() {
        let engine = CkmEngine::new(minimal_v2());
        let result = engine.inspect();
        assert_eq!(result.meta.project, "test");
        assert_eq!(result.counts.concepts, 1);
        assert_eq!(result.counts.operations, 1);
        assert_eq!(result.counts.topics, 1);
        assert_eq!(result.topic_names, vec!["calver"]);
    }

    #[test]
    fn test_engine_v1_auto_migration() {
        let v1 = serde_json::json!({
            "project": "legacy",
            "generated": "2025-01-01T00:00:00.000Z",
            "concepts": [
                {
                    "id": "concept-CalVerConfig",
                    "name": "CalVerConfig",
                    "what": "Configures CalVer.",
                    "properties": [
                        {
                            "name": "format",
                            "type": "CalVerFormat",
                            "description": "The format."
                        }
                    ]
                }
            ],
            "operations": [],
            "constraints": [],
            "workflows": [],
            "configSchema": []
        });
        let engine = CkmEngine::new(v1);
        assert_eq!(engine.manifest().version, "2.0.0");
        assert_eq!(engine.manifest().meta.project, "legacy");
        assert_eq!(engine.topics().len(), 1);
        assert_eq!(engine.topics()[0].name, "calver");
    }

    #[test]
    fn test_engine_empty_manifest() {
        let data = serde_json::json!({
            "$schema": "https://ckm.dev/schemas/v2.json",
            "version": "2.0.0",
            "meta": {
                "project": "empty",
                "language": "rust",
                "generator": "hand-authored",
                "generated": "2026-01-01T00:00:00.000Z"
            },
            "concepts": [],
            "operations": [],
            "constraints": [],
            "workflows": [],
            "configSchema": []
        });
        let engine = CkmEngine::new(data);
        assert!(engine.topics().is_empty());
        assert_eq!(engine.inspect().counts.topics, 0);
    }
}