Class: KairosMcp::KnowledgeProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/kairos_mcp/knowledge_provider.rb

Overview

KnowledgeProvider: Manages L1 (knowledge layer) skills in Anthropic format

L1 characteristics:

  • Project-specific universal knowledge
  • Hash-only blockchain recording
  • Lightweight modification constraints
  • Folder-based archiving (.archived/ directory)

Storage:

  • Content (*.md files): Always stored in files for human readability
  • Metadata: Stored in files (default) or SQLite (when sqlite backend enabled)
  • Blockchain: Uses the configured storage backend

Constant Summary collapse

ARCHIVED_DIR =
'.archived'
ARCHIVE_META_FILE =
'.archive_meta.yml'
BACKUP_DIR_PATTERN =

Backup directories created by upgrade flow (.bak.<timestamp>). Loader must skip these — they may contain old/broken frontmatter.

/(?:^|\.)bak(?:\.|$)/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(knowledge_dir = nil, vector_search_enabled: true, storage_backend: nil, user_context: nil, include_skillset_knowledge: true) ⇒ KnowledgeProvider

Initialize the KnowledgeProvider

Parameters:

  • knowledge_dir (String) (defaults to: nil)

    Path to knowledge directory

  • vector_search_enabled (Boolean) (defaults to: true)

    Enable vector search

  • storage_backend (Storage::Backend, nil) (defaults to: nil)

    Storage backend to use

  • include_skillset_knowledge (Boolean) (defaults to: true)

    Register knowledge dirs declared by enabled SkillSets. Default true; pass false to build a provider scoped strictly to the main knowledge dir.



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/kairos_mcp/knowledge_provider.rb', line 47

def initialize(knowledge_dir = nil, vector_search_enabled: true, storage_backend: nil,
               user_context: nil, include_skillset_knowledge: true)
  knowledge_dir ||= KairosMcp.knowledge_dir(user_context: user_context)
  @knowledge_dir = knowledge_dir
  @user_context = user_context
  @vector_search_enabled = vector_search_enabled
  @storage_backend = storage_backend
  @vector_search = nil
  @index_built = false
  @external_dirs = []
  FileUtils.mkdir_p(@knowledge_dir)
  register_skillset_knowledge_dirs if include_skillset_knowledge
end

Instance Attribute Details

#knowledge_dirObject (readonly)

Main knowledge directory (constitutively-recorded L1). Exposed so callers can distinguish main-dir knowledge from read-only external SkillSet knowledge, e.g. to scope INV-A correspondence checks to recorded artifacts.



31
32
33
# File 'lib/kairos_mcp/knowledge_provider.rb', line 31

def knowledge_dir
  @knowledge_dir
end

Instance Method Details

#add_external_dir(dir, source:, layer: :L1, index: true, only: nil) ⇒ Object

Register an external knowledge directory (e.g. from a SkillSet) Knowledge is read-only from external dirs; no merge into the main dir.

Idempotent by directory: registering the same dir twice (e.g. once from the SkillSet manifest at construction, once from a SkillSet that also registers itself) keeps the first registration rather than duplicating list entries.

Parameters:

  • dir (String)

    Absolute path to the container directory holding entry subdirectories (e.g. <skillset>/knowledge), not an entry directory itself

  • source (String)

    Identifier for the source (e.g. "skillset:mmp")

  • layer (Symbol) (defaults to: :L1)

    Layer governance (:L0, :L1, :L2)

  • index (Boolean) (defaults to: true)

    Whether to include in vector search index

  • only (Array<String>, nil) (defaults to: nil)

    Entry names to expose. nil exposes every subdirectory. Passing the declared set keeps undeclared knowledge shipped inside a SkillSet from becoming visible as L1 by proximity alone.



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/kairos_mcp/knowledge_provider.rb', line 76

def add_external_dir(dir, source:, layer: :L1, index: true, only: nil)
  return unless File.directory?(dir)

  absolute = File.expand_path(dir)
  return if @external_dirs.any? { |ext| ext[:dir] == absolute }

  @external_dirs << {
    dir: absolute, source: source, layer: layer, index: index,
    only: only && Array(only).map { |n| File.basename(n.to_s) }
  }
  @index_built = false if index # Invalidate index when new indexed dir added
end

#archive(name, reason:, superseded_by: nil) ⇒ Hash

Archive a knowledge skill (move to .archived/ directory)

Parameters:

  • name (String)

    Skill name

  • reason (String)

    Reason for archiving

  • superseded_by (String, nil) (defaults to: nil)

    Name of the knowledge that supersedes this one

Returns:

  • (Hash)

    Result with success status



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 409

def archive(name, reason:, superseded_by: nil)
  skill = get(name)
  unless skill
    return { success: false, error: "Knowledge '#{name}' not found" }
  end
  return not_owned(name) unless owned?(skill)

  # Check if already archived
  if archived?(name)
    return { success: false, error: "Knowledge '#{name}' is already archived" }
  end

  # Create archive directory
  archived_dir = File.join(@knowledge_dir, ARCHIVED_DIR)
  FileUtils.mkdir_p(archived_dir)

  # The archive root is itself a path this method did not choose. If
  # `.archived` is a symlink out of the store, asking containment against it
  # asks about the wrong root — the predicate answers truthfully about a
  # directory nobody meant, and the move carries L1 knowledge outside.
  # Every path below is therefore bounded by @knowledge_dir.
  return archive_root_escaped unless PathContainment.contained?(@knowledge_dir, archived_dir)

  # Calculate hash before moving
  content = File.read(skill.md_file_path)
  content_hash = Digest::SHA256.hexdigest(content)

  dest_path = File.join(archived_dir, name)
  meta_path = File.join(dest_path, ARCHIVE_META_FILE)

  # Both the move destination AND the metadata file are checked. The
  # metadata write is a separate target from base_path, so ownership of the
  # entry says nothing about it: a symlink named .archive_meta.yml inside an
  # entry this provider legitimately owns would otherwise carry an
  # attacker-supplied reason to any file this process can write.
  unless PathContainment.contained?(@knowledge_dir, dest_path) &&
         PathContainment.contained?(@knowledge_dir, meta_path)
    return { success: false, error: "Invalid knowledge name '#{name}': archive destination resolves outside the knowledge directory" }
  end

  FileUtils.mv(skill.base_path, dest_path)

  # Re-checked after the move: the entry that just arrived may itself carry
  # a .archive_meta.yml symlink, which only becomes a path under dest_path
  # once it is there.
  unless PathContainment.contained?(dest_path, meta_path)
    FileUtils.rm_f(meta_path)
  end

  # Create archive metadata file
  meta = {
    'archived_at' => Time.now.iso8601,
    'archived_reason' => reason,
    'superseded_by' => superseded_by,
    'original_path' => skill.base_path,
    'content_hash' => content_hash
  }
  File.write(meta_path, meta.to_yaml)

  # Record to blockchain
  record_hash_reference(
    name: name,
    action: 'archive',
    prev_hash: content_hash,
    next_hash: nil,
    reason: reason
  )

  # Remove from vector search index
  remove_from_vector_index(name)

  # Track pending change for state commit (archive = demotion)
  track_pending_change(layer: 'L1', action: 'archive', skill_id: name, reason: reason)

  { success: true, archived: name, path: dest_path, hash: content_hash }
rescue StandardError => e
  { success: false, error: "Archive failed: #{e.message}" }
end

#archive_root_escapedObject



683
684
685
686
# File 'lib/kairos_mcp/knowledge_provider.rb', line 683

def archive_root_escaped
  { success: false,
    error: "The archive directory (#{ARCHIVED_DIR}) resolves outside the knowledge directory; refusing to move anything through it" }
end

#archived?(name) ⇒ Boolean

Check if a knowledge skill is archived

Parameters:

  • name (String)

    Skill name

Returns:

  • (Boolean)

    True if archived



624
625
626
627
628
629
630
# File 'lib/kairos_mcp/knowledge_provider.rb', line 624

def archived?(name)
  return false unless PathContainment.safe_segment?(name)

  archived_root = File.join(@knowledge_dir, ARCHIVED_DIR)
  archived_path = File.join(archived_root, name)
  File.directory?(archived_path) && PathContainment.contained?(archived_root, archived_path)
end

#create(name, content, reason: nil, create_subdirs: false) ⇒ Hash

Create a new knowledge skill

Parameters:

  • name (String)

    Skill name

  • content (String)

    Full content including YAML frontmatter

  • reason (String) (defaults to: nil)

    Reason for creation

  • create_subdirs (Boolean) (defaults to: false)

    Whether to create scripts/assets/references

Returns:

  • (Hash)

    Result with success status and skill info



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 171

def create(name, content, reason: nil, create_subdirs: false)
  # Checked BEFORE the join: File.join raises TypeError on a non-String, so
  # a malformed argument would escape as an exception instead of the
  # structured refusal every other caller of this method expects.
  unless PathContainment.safe_segment?(name)
    return { success: false, error: "Invalid knowledge name #{name.inspect}: not a single path segment" }
  end

  if reserved_name?(name)
    return { success: false, error: "Invalid knowledge name '#{name}': reserved by the knowledge store" }
  end

  skill_dir = File.join(@knowledge_dir, name)
  unless PathContainment.contained?(@knowledge_dir, skill_dir)
    return { success: false, error: "Invalid knowledge name '#{name}': resolves outside the knowledge directory" }
  end

  if File.exist?(skill_dir)
    return { success: false, error: "Knowledge '#{name}' already exists" }
  end

  skill = AnthropicSkillParser.create(@knowledge_dir, name, content, create_subdirs: create_subdirs)
  
  # Record hash reference to blockchain
  content_hash = Digest::SHA256.hexdigest(content)
  record_hash_reference(
    name: name,
    action: 'create',
    prev_hash: nil,
    next_hash: content_hash,
    reason: reason || "Create knowledge: #{name}"
  )

  # Update vector search index
  update_vector_index(name, content, skill)

  # Track pending change for state commit
  track_pending_change(layer: 'L1', action: 'create', skill_id: name, reason: reason)

  { success: true, skill: skill.to_h, hash: content_hash, next_hash: content_hash }
end

#delete(name, reason: nil) ⇒ Hash

Delete a knowledge skill

Parameters:

  • name (String)

    Skill name

  • reason (String) (defaults to: nil)

    Reason for deletion

Returns:

  • (Hash)

    Result with success status



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 261

def delete(name, reason: nil)
  skill = get(name)
  unless skill
    return { success: false, error: "Knowledge '#{name}' not found" }
  end
  return not_owned(name) unless owned?(skill)

  # Calculate hash before deletion
  prev_content = File.read(skill.md_file_path)
  prev_hash = Digest::SHA256.hexdigest(prev_content)

  # Delete the directory
  FileUtils.rm_rf(skill.base_path)

  # Record hash reference to blockchain
  record_hash_reference(
    name: name,
    action: 'delete',
    prev_hash: prev_hash,
    next_hash: nil,
    reason: reason || "Delete knowledge: #{name}"
  )

  # Remove from vector search index
  remove_from_vector_index(name)

  # Track pending change for state commit
  track_pending_change(layer: 'L1', action: 'delete', skill_id: name, reason: reason)

  { success: true, deleted: name, prev_hash: prev_hash }
end

#get(name) ⇒ AnthropicSkillParser::SkillEntry?

Get a specific knowledge skill by name Searches main knowledge dir first, then external SkillSet dirs

Parameters:

  • name (String)

    Skill name

Returns:



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/kairos_mcp/knowledge_provider.rb', line 142

def get(name)
  return nil unless PathContainment.safe_segment?(name)
  return nil if reserved_name?(name)

  skill_dir = File.join(@knowledge_dir, name)
  if PathContainment.contained?(@knowledge_dir, skill_dir) && File.directory?(skill_dir)
    return AnthropicSkillParser.parse(skill_dir)
  end

  # Search external directories
  @external_dirs.each do |ext|
    next if ext[:only] && !ext[:only].include?(name)

    ext_skill_dir = File.join(ext[:dir], name)
    next unless PathContainment.contained?(ext[:dir], ext_skill_dir)

    return AnthropicSkillParser.parse(ext_skill_dir) if File.directory?(ext_skill_dir)
  end

  nil
end

#get_archived(name) ⇒ Hash?

Get a specific archived knowledge skill

Parameters:

  • name (String)

    Skill name

Returns:

  • (Hash, nil)

    Archived skill info or nil



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/kairos_mcp/knowledge_provider.rb', line 598

def get_archived(name)
  return nil unless PathContainment.safe_segment?(name)

  archived_root = File.join(@knowledge_dir, ARCHIVED_DIR)
  archived_path = File.join(archived_root, name)
  return nil unless File.directory?(archived_path) && PathContainment.contained?(archived_root, archived_path)

  skill = AnthropicSkillParser.parse(archived_path)
  return nil unless skill

  meta_file = File.join(archived_path, ARCHIVE_META_FILE)
  meta = File.exist?(meta_file) ? YAML.safe_load(File.read(meta_file)) : {}

  {
    skill: skill.to_h,
    archived_at: meta['archived_at'],
    archived_reason: meta['archived_reason'],
    superseded_by: meta['superseded_by'],
    content_hash: meta['content_hash']
  }
end

#listArray<Hash>

List all knowledge skills (including those from external SkillSet dirs)

Returns:

  • (Array<Hash>)

    List of knowledge skill summaries



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 98

def list
  results = skill_dirs.map do |dir|
    skill = AnthropicSkillParser.parse(dir)
    next unless skill

    {
      name: skill.name,
      description: skill.description,
      version: skill.version,
      tags: skill.tags,
      has_scripts: skill.has_scripts?,
      has_assets: skill.has_assets?,
      has_references: skill.has_references?
    }
  end.compact

  # Include knowledge from external directories (SkillSets)
  @external_dirs.each do |ext|
    external_skill_dirs(ext[:dir], only: ext[:only]).each do |dir|
      skill = AnthropicSkillParser.parse(dir)
      next unless skill

      results << {
        name: skill.name,
        description: skill.description,
        version: skill.version,
        tags: skill.tags,
        has_scripts: skill.has_scripts?,
        has_assets: skill.has_assets?,
        has_references: skill.has_references?,
        source: ext[:source],
        layer: ext[:layer]
      }
    end
  end

  results
end

#list_archivedArray<Hash>

List all archived knowledge skills

Returns:

  • (Array<Hash>)

    List of archived knowledge summaries



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/kairos_mcp/knowledge_provider.rb', line 571

def list_archived
  archived_dir = File.join(@knowledge_dir, ARCHIVED_DIR)
  return [] unless File.directory?(archived_dir)
  return [] unless PathContainment.contained?(@knowledge_dir, archived_dir)

  Dir[File.join(archived_dir, '*')].select do |f|
    File.directory?(f) && PathContainment.contained?(@knowledge_dir, f)
  end.map do |dir|
    skill = AnthropicSkillParser.parse(dir)
    meta_file = File.join(dir, ARCHIVE_META_FILE)
    meta = File.exist?(meta_file) ? YAML.safe_load(File.read(meta_file)) : {}

    {
      name: skill&.name || File.basename(dir),
      description: skill&.description,
      archived_at: meta['archived_at'],
      archived_reason: meta['archived_reason'],
      superseded_by: meta['superseded_by'],
      content_hash: meta['content_hash']
    }
  end
end

#list_assets(name) ⇒ Array<Hash>

List assets in a knowledge skill

Parameters:

  • name (String)

    Skill name

Returns:

  • (Array<Hash>)

    List of asset info



308
309
310
311
312
313
# File 'lib/kairos_mcp/knowledge_provider.rb', line 308

def list_assets(name)
  skill = get(name)
  return [] unless skill

  AnthropicSkillParser.list_assets(skill)
end

#list_references(name) ⇒ Array<Hash>

List references in a knowledge skill

Parameters:

  • name (String)

    Skill name

Returns:

  • (Array<Hash>)

    List of reference info



319
320
321
322
323
324
# File 'lib/kairos_mcp/knowledge_provider.rb', line 319

def list_references(name)
  skill = get(name)
  return [] unless skill

  AnthropicSkillParser.list_references(skill)
end

#list_scripts(name) ⇒ Array<Hash>

List scripts in a knowledge skill

Parameters:

  • name (String)

    Skill name

Returns:

  • (Array<Hash>)

    List of script info



297
298
299
300
301
302
# File 'lib/kairos_mcp/knowledge_provider.rb', line 297

def list_scripts(name)
  skill = get(name)
  return [] unless skill

  AnthropicSkillParser.list_scripts(skill)
end

#not_owned(name) ⇒ Object

The refusal names the diagnosis and the remedy. owned? is source- agnostic — add_external_dir accepts any directory and any source label — so the message says where the entry is, not what kind of thing owns it.



677
678
679
680
681
# File 'lib/kairos_mcp/knowledge_provider.rb', line 677

def not_owned(name)
  { success: false,
    error: "Knowledge '#{name}' lives outside this store and is read-only here. " \
           "To keep a local version, create it under this instance's knowledge directory instead of updating it in place." }
end

#owned?(skill) ⇒ Boolean

True if this provider owns the entry, i.e. it lives inside the store this provider writes to.

Public because a caller that has to choose between updating and creating needs the answer: resolvability is not write authority, and deciding by get alone sends an update at an entry this provider will refuse.

get deliberately searches external SkillSet directories after the main store — that is how shipped knowledge is read (see the note on add_external_dir: external knowledge is read-only). The mutators used to inherit that reach and acted on whatever get had resolved, so an ordinary name with no ".." and no symlink in it rewrote, moved or removed files belonging to an installed SkillSet. Read authority and write authority are different scopes; this is where they part.

Returns:

  • (Boolean)


667
668
669
670
671
672
# File 'lib/kairos_mcp/knowledge_provider.rb', line 667

def owned?(skill)
  base = skill.respond_to?(:base_path) ? skill.base_path : nil
  return false unless base

  PathContainment.contained?(@knowledge_dir, base)
end

#rebuild_indexBoolean

Rebuild the vector search index (includes indexed external dirs)

Returns:

  • (Boolean)

    Success status



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 357

def rebuild_index
  documents = skill_dirs.filter_map do |dir|
    skill = AnthropicSkillParser.parse(dir)
    next unless skill

    content = File.read(skill.md_file_path) rescue ''
    {
      id: skill.name,
      text: build_searchable_text(skill, content),
      metadata: {
        description: skill.description,
        tags: skill.tags,
        version: skill.version
      }
    }
  end

  # Include external dirs that have indexing enabled
  @external_dirs.select { |ext| ext[:index] }.each do |ext|
    external_skill_dirs(ext[:dir], only: ext[:only]).each do |dir|
      skill = AnthropicSkillParser.parse(dir)
      next unless skill

      content = File.read(skill.md_file_path) rescue ''
      documents << {
        id: "#{ext[:source]}:#{skill.name}",
        text: build_searchable_text(skill, content),
        metadata: {
          description: skill.description,
          tags: skill.tags,
          version: skill.version,
          source: ext[:source]
        }
      }
    end
  end

  result = vector_search.rebuild(documents)
  @index_built = result
  result
end

#reserved_name?(name) ⇒ Boolean

Names the store keeps for itself.

.archived is where archived entries live; accepted as an ordinary entry name it can be claimed on a fresh store before the archive directory first exists, and a later delete of that "entry" removes the whole archive while being recorded as the deletion of one entry.

BACKUP_DIR_PATTERN is the store's other self-reservation: skill_dirs and external_skill_dirs filter those names out of every enumeration, so an entry created under one is recorded on the chain and retrievable by name while being invisible to knowledge_list and to audit.

Any directory name this store manages for itself belongs here. If another is introduced, add it — the filters that hide it and this predicate have to name the same set.

Returns:

  • (Boolean)


647
648
649
650
651
# File 'lib/kairos_mcp/knowledge_provider.rb', line 647

def reserved_name?(name)
  return false unless name.is_a?(String)

  name == ARCHIVED_DIR || backup_dir?(name)
end

#search(query, max_results = 5, semantic: nil) ⇒ Array<Hash>

Search knowledge skills by query

Parameters:

  • query (String)

    Search query

  • max_results (Integer) (defaults to: 5)

    Maximum number of results

  • semantic (Boolean) (defaults to: nil)

    Force semantic search if available

Returns:

  • (Array<Hash>)

    Matching skills



332
333
334
335
336
337
338
339
340
# File 'lib/kairos_mcp/knowledge_provider.rb', line 332

def search(query, max_results = 5, semantic: nil)
  use_semantic = semantic.nil? ? @vector_search_enabled : semantic
  
  if use_semantic && vector_search.semantic?
    semantic_search(query, max_results)
  else
    regex_search(query, max_results)
  end
end

#storage_typeSymbol

Get the storage backend type

Returns:

  • (Symbol)

    :file or :sqlite



91
92
93
# File 'lib/kairos_mcp/knowledge_provider.rb', line 91

def storage_type
  storage_backend.backend_type
end

#unarchive(name, reason:) ⇒ Hash

Unarchive a knowledge skill (restore from .archived/ directory)

Parameters:

  • name (String)

    Skill name

  • reason (String)

    Reason for unarchiving

Returns:

  • (Hash)

    Result with success status



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 493

def unarchive(name, reason:)
  unless PathContainment.safe_segment?(name)
    return { success: false, error: "Invalid knowledge name '#{name}': not a single path segment" }
  end

  if reserved_name?(name)
    return { success: false, error: "Invalid knowledge name '#{name}': reserved by the knowledge store" }
  end

  archived_root = File.join(@knowledge_dir, ARCHIVED_DIR)
  archived_path = File.join(archived_root, name)
  active_path = File.join(@knowledge_dir, name)
  archived_meta = File.join(archived_path, ARCHIVE_META_FILE)
  active_meta = File.join(active_path, ARCHIVE_META_FILE)

  # The archive root is a path this method did not choose. If `.archived` is
  # a symlink out of the store, containment asked against it would answer
  # about the wrong root and this move would bring an arbitrary outside
  # directory in as L1 knowledge. Every path below is bounded by
  # @knowledge_dir, not by the archive root.
  return archive_root_escaped unless PathContainment.contained?(@knowledge_dir, archived_root)

  unless File.directory?(archived_path) && PathContainment.contained?(@knowledge_dir, archived_path)
    return { success: false, error: "Archived knowledge '#{name}' not found" }
  end

  # Every path this method reads, moves or deletes — not just the two ends.
  unless PathContainment.contained?(@knowledge_dir, active_path) &&
         PathContainment.contained?(archived_path, archived_meta) &&
         PathContainment.contained?(@knowledge_dir, active_meta)
    return { success: false, error: "Invalid knowledge name '#{name}': resolves outside the knowledge directory" }
  end

  # Check if active knowledge with same name exists
  if File.directory?(active_path)
    return { success: false, error: "Active knowledge '#{name}' already exists. Rename or delete it first." }
  end

  # Read archive metadata
  meta_file = archived_meta
  meta = File.exist?(meta_file) ? YAML.safe_load(File.read(meta_file)) : {}

  # Move back to active
  FileUtils.mv(archived_path, active_path)

  # Remove archive metadata file. Re-checked after the move for the same
  # reason as in #archive: the entry may carry a symlink by that name, and
  # rm_f would follow it.
  FileUtils.rm_f(active_meta) if PathContainment.contained?(active_path, active_meta)

  # Parse the restored skill
  skill = AnthropicSkillParser.parse(active_path)
  content = File.read(skill.md_file_path)
  content_hash = Digest::SHA256.hexdigest(content)

  # Record to blockchain
  record_hash_reference(
    name: name,
    action: 'unarchive',
    prev_hash: meta['content_hash'],
    next_hash: content_hash,
    reason: reason
  )

  # Update vector search index
  update_vector_index(name, content, skill)

  # Track pending change for state commit
  track_pending_change(layer: 'L1', action: 'unarchive', skill_id: name, reason: reason)

  { success: true, unarchived: name, path: active_path, hash: content_hash }
rescue StandardError => e
  { success: false, error: "Unarchive failed: #{e.message}" }
end

#update(name, new_content, reason: nil) ⇒ Hash

Update an existing knowledge skill

Parameters:

  • name (String)

    Skill name

  • new_content (String)

    New content including YAML frontmatter

  • reason (String) (defaults to: nil)

    Reason for update

Returns:

  • (Hash)

    Result with success status



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
# File 'lib/kairos_mcp/knowledge_provider.rb', line 219

def update(name, new_content, reason: nil)
  skill = get(name)
  unless skill
    return { success: false, error: "Knowledge '#{name}' not found" }
  end
  return not_owned(name) unless owned?(skill)

  # Calculate hashes
  prev_content = File.read(skill.md_file_path)
  prev_hash = Digest::SHA256.hexdigest(prev_content)
  next_hash = Digest::SHA256.hexdigest(new_content)

  if prev_hash == next_hash
    return { success: false, error: "No changes detected" }
  end

  # Update the file
  updated_skill = AnthropicSkillParser.update(skill.base_path, new_content)

  # Record hash reference to blockchain
  record_hash_reference(
    name: name,
    action: 'update',
    prev_hash: prev_hash,
    next_hash: next_hash,
    reason: reason || "Update knowledge: #{name}"
  )

  # Update vector search index
  update_vector_index(name, new_content, updated_skill)

  # Track pending change for state commit
  track_pending_change(layer: 'L1', action: 'update', skill_id: name, reason: reason)

  { success: true, skill: updated_skill.to_h, prev_hash: prev_hash, next_hash: next_hash }
end

#vector_search_statusHash

Get vector search status

Returns:

  • (Hash)

    Status information



345
346
347
348
349
350
351
352
# File 'lib/kairos_mcp/knowledge_provider.rb', line 345

def vector_search_status
  {
    enabled: @vector_search_enabled,
    semantic_available: VectorSearch.available?,
    index_built: @index_built,
    document_count: vector_search.count
  }
end