Skip to content
Kward Search API index

Module: Kward::ConfigFiles

Defined in:
lib/kward/config_files.rb

Overview

Resolves Kward configuration, cache, memory, prompt, skill, and plugin paths, and reads/writes the JSON config file used by the CLI and RPC server.

This module is the configuration boundary, not a runtime settings cache. Most methods read the filesystem each time so CLI commands and RPC reloads can observe edits made outside the process. Callers that need caching should own invalidation explicitly, as Client#reload_config does for provider state.

Keep path decisions here. Higher-level code should ask ConfigFiles for config, prompt, skill, plugin, cache, memory, and session locations instead of reconstructing ~/.kward paths independently.

Defined Under Namespace

Classes: ConfigError, PromptTemplate, Skill

Constant Summary collapse

MAX_SKILL_FILE_BYTES =
100_000
MAX_PROMPT_FILE_BYTES =
32 * 1024
DEFAULT_OVERLAY_SETTINGS =
{ "alignment" => "center", "width" => "maximum" }.freeze
PROJECT_BROWSER_ICON_THEMES =
%w[off nerd-font].freeze
DEFAULT_PERSONAS =
{
  "characters" => [
    {
      "key" => "kward",
      "label" => "Kward",
      "instruction" => "Your name is Kward, the grim Andruid - robotic keeper of the Forest of Code, protecting the nature of good engineering principles. Speak like an old druid, be suspicious of everyone, but with good intent."
    }
  ],
  "default" => "kward"
}.freeze
OVERLAY_ALIGNMENTS =
%w[left center right].freeze
OVERLAY_WIDTHS =
%w[capped maximum].freeze

Class Method Summary collapse

Class Method Details

.active_persona_label(workspace_root:, model: nil, config: read_config) ⇒ Object

Returns the label of the persona selected by default/workspace/model rules.



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/kward/config_files.rb', line 730

def active_persona_label(workspace_root:, model: nil, config: read_config)
  personas = config["personas"]
  return nil unless personas.is_a?(Hash)

  labels = crew_character_labels(personas)
  active_label = persona_label_for_key(personas["default"], labels) unless personas["default"].nil?

  workspaces = personas["workspaces"]
  if workspaces.is_a?(Hash)
    root = canonical_workspace_root(workspace_root)
    workspaces.each do |path, key|
      next unless canonical_workspace_root(path) == root

      active_label = persona_label_for_key(key, labels)
      break
    end
  end

  models = personas["models"]
  if models.is_a?(Hash) && !model.to_s.empty? && models.key?(model.to_s)
    active_label = persona_label_for_key(models[model.to_s], labels)
  end

  active_label
end

.add_persona_entry(entries, layer, value, name: nil) ⇒ Object



849
850
851
852
853
854
# File 'lib/kward/config_files.rb', line 849

def add_persona_entry(entries, layer, value, name: nil)
  text = presence(value)
  return unless text

  entries << { layer: layer.to_s, name: name.to_s, prompt: text }
end

.agents_prompt(config: read_config) ⇒ String?

Reads global principle instructions from the config directory.

PRINCIPLES.md is preferred. AGENTS.md remains a backwards-compatible alias for existing installations.

Returns:

  • (String, nil)

    prompt text, or nil when absent/too large



644
645
646
647
648
649
650
651
# File 'lib/kward/config_files.rb', line 644

def agents_prompt(config: read_config)
  return nil unless include_config_principles?(config)

  path = config_principles_path
  return read_prompt_file(path, "Kward principles file") if File.exist?(path)

  read_prompt_file(config_agents_path, "Kward AGENTS.md alias")
end

.cache_dirString

Returns directory containing reusable local caches.

Returns:

  • (String)

    directory containing reusable local caches



106
107
108
# File 'lib/kward/config_files.rb', line 106

def cache_dir
  File.join(config_dir, "cache")
end

.canonical_workspace_root(path) ⇒ Object



844
845
846
847
# File 'lib/kward/config_files.rb', line 844

def canonical_workspace_root(path)
  expanded = File.expand_path(path.to_s.empty? ? Dir.pwd : path.to_s)
  File.directory?(expanded) ? File.realpath(expanded) : expanded
end

.character_entries(raw) ⇒ Object



896
897
898
899
900
901
902
903
904
905
# File 'lib/kward/config_files.rb', line 896

def character_entries(raw)
  case raw
  when Hash
    raw.map { |key, definition| [key, definition] }
  when Array
    raw.filter_map { |entry| character_entry(entry) }
  else
    []
  end
end

.character_entry(entry) ⇒ Object



907
908
909
910
911
912
913
914
915
916
# File 'lib/kward/config_files.rb', line 907

def character_entry(entry)
  return nil unless entry.is_a?(Hash)

  if entry.length == 1 && entry.keys.first.is_a?(String)
    [entry.keys.first, entry.values.first]
  else
    key = entry["key"] || entry[:key] || entry["id"] || entry[:id] || entry["name"] || entry[:name]
    key.to_s.empty? ? nil : [key, entry]
  end
end

.code_search_cache_dirObject



203
204
205
# File 'lib/kward/config_files.rb', line 203

def code_search_cache_dir
  File.join(cache_dir, "code_search")
end

.composer_busy_help?(config = read_config) ⇒ Boolean

Returns whether the composer should show busy-state keyboard help.

Returns:

  • (Boolean)


432
433
434
435
# File 'lib/kward/config_files.rb', line 432

def composer_busy_help?(config = read_config)
  composer = config["composer"].is_a?(Hash) ? config["composer"] : {}
  composer["busy_help"] != false
end

.composer_tab_keybindings(config = read_config) ⇒ Object

Returns the configured tab keybinding family, or auto when unset/invalid.



438
439
440
441
442
# File 'lib/kward/config_files.rb', line 438

def composer_tab_keybindings(config = read_config)
  composer = config["composer"].is_a?(Hash) ? config["composer"] : {}
  value = composer["tab_keybindings"].to_s.downcase
  %w[auto ctrl alt].include?(value) ? value : "auto"
end

.config_agents_pathObject



703
704
705
# File 'lib/kward/config_files.rb', line 703

def config_agents_path
  File.join(config_dir, "AGENTS.md")
end

.config_dirString

Directory that contains Kward's user config and adjacent prompt/skill data. Defaults to ~/.kward, or the directory of KWARD_CONFIG_PATH.

Returns:

  • (String)

    expanded config directory path



93
94
95
96
97
98
# File 'lib/kward/config_files.rb', line 93

def config_dir
  config_path = ENV["KWARD_CONFIG_PATH"]
  return File.expand_path(File.dirname(config_path)) if config_path && !config_path.empty?

  File.expand_path("~/.kward")
end

.config_pathString

Returns expanded JSON config file path.

Returns:

  • (String)

    expanded JSON config file path



101
102
103
# File 'lib/kward/config_files.rb', line 101

def config_path
  File.expand_path(ENV["KWARD_CONFIG_PATH"] || File.join(config_dir, "config.json"))
end

.config_principles_pathObject



699
700
701
# File 'lib/kward/config_files.rb', line 699

def config_principles_path
  File.join(config_dir, "PRINCIPLES.md")
end

.config_value(config, *keys) ⇒ Object

Returns the first present non-empty string value among several config keys.



401
402
403
404
405
406
407
# File 'lib/kward/config_files.rb', line 401

def config_value(config, *keys)
  keys.each do |key|
    text = presence(config[key])
    return text if text
  end
  nil
end

.crew_character_labels(personas) ⇒ Object



862
863
864
865
866
# File 'lib/kward/config_files.rb', line 862

def crew_character_labels(personas)
  named_character_values(personas) do |_key, definition|
    extract_character_label(definition)
  end
end

.crew_characters(personas) ⇒ Object



856
857
858
859
860
# File 'lib/kward/config_files.rb', line 856

def crew_characters(personas)
  named_character_values(personas) do |_key, definition|
    extract_character_instruction(definition)
  end
end

.default_configHash

Returns a fresh default config suitable for first-run persistence.

Returns:

  • (Hash)

    deep-mutable config defaults



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
# File 'lib/kward/config_files.rb', line 131

def default_config
  {
    "personas" => JSON.parse(JSON.generate(DEFAULT_PERSONAS)),
    "memory" => {
      "enabled" => false,
      "auto_summary" => false
    },
    "composer" => {
      "busy_help" => true,
      "tab_keybindings" => "auto"
    },
    "editor" => {
      "mode" => "modern",
      "agent" => {},
      "runners" => {},
      "auto_indent" => true,
      "auto_close_pairs" => true,
      "soft_wrap" => true,
      "bar_cursor" => true,
      "line_numbers" => "absolute",
      "diff_view" => "auto"
    },
    "overlay" => DEFAULT_OVERLAY_SETTINGS.dup,
    "project_browser" => {
      "icons" => "off"
    },
    "web_search" => {
      "enabled" => true,
      "provider" => "auto",
      "allow_model_providers" => false
    },
    "updates" => {
      "check" => true
    },
    "sessions" => {
      "auto_resume" => false
    },
    "skills" => {
      "trust_project" => false
    },
    "enforce_workspace_agents_file" => false,
    "system_prompt" => {
      "include_principles" => true
    },
    "mcpServers" => {},
    "transports" => {},
    "tools" => {
      "workspace_guardrails" => true
    },
    "permissions" => {
      "enabled" => false,
      "mode" => "ask"
    },
    "sandbox" => {
      "mode" => "off",
      "network" => "deny",
      "writable_roots" => [],
      "protect_git_metadata" => true
    }
  }
end

.delete_config_key(key, path = config_path) ⇒ Object

Removes a top-level config key when it exists.



392
393
394
395
396
397
398
# File 'lib/kward/config_files.rb', line 392

def delete_config_key(key, path = config_path)
  config = read_config(path)
  existed = config.key?(key.to_s)
  config.delete(key.to_s)
  write_config(config, path) if existed
  existed
end

.diff_view(config = read_config) ⇒ Object

Returns the integrated diff viewer display mode.



547
548
549
550
# File 'lib/kward/config_files.rb', line 547

def diff_view(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  DiffViewMode.normalize(editor["diff_view"])
end

.editor_agent_model(config = read_config) ⇒ Object

Returns the optional model override for editor-agent turns.



469
470
471
# File 'lib/kward/config_files.rb', line 469

def editor_agent_model(config = read_config)
  editor_agent_setting(config, "model")
end

.editor_agent_provider(config = read_config) ⇒ Object

Returns the optional provider override for editor-agent turns.



461
462
463
464
465
466
# File 'lib/kward/config_files.rb', line 461

def editor_agent_provider(config = read_config)
  value = ENV["KWARD_EDITOR_PROVIDER"].to_s.strip
  return value unless value.empty?

  editor_agent_setting(config, "provider")
end

.editor_agent_reasoning_effort(config = read_config) ⇒ Object

Returns the optional reasoning-effort override for editor-agent turns.



474
475
476
# File 'lib/kward/config_files.rb', line 474

def editor_agent_reasoning_effort(config = read_config)
  editor_agent_setting(config, "reasoning_effort")
end

.editor_agent_setting(config, key) ⇒ Object



502
503
504
505
506
507
# File 'lib/kward/config_files.rb', line 502

def editor_agent_setting(config, key)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  agent = editor["agent"].is_a?(Hash) ? editor["agent"] : {}
  value = agent[key].to_s.strip
  value.empty? ? nil : value
end

.editor_auto_close_pairs?(config = read_config) ⇒ Boolean

Returns whether the built-in TUI editor should auto-close typed pairs.

Returns:

  • (Boolean)


523
524
525
526
# File 'lib/kward/config_files.rb', line 523

def editor_auto_close_pairs?(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  editor["auto_close_pairs"] != false
end

.editor_auto_indent?(config = read_config) ⇒ Boolean

Returns whether the built-in TUI editor should auto-indent new lines.

Returns:

  • (Boolean)


517
518
519
520
# File 'lib/kward/config_files.rb', line 517

def editor_auto_indent?(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  editor["auto_indent"] != false
end

.editor_bar_cursor?(config = read_config) ⇒ Boolean

Returns whether editable built-in TUI editor buffers should use a bar cursor.

Returns:

  • (Boolean)


535
536
537
538
# File 'lib/kward/config_files.rb', line 535

def editor_bar_cursor?(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  editor["bar_cursor"] != false
end

.editor_line_numbers(config = read_config) ⇒ Object

Returns the built-in TUI editor line-number display mode.



541
542
543
544
# File 'lib/kward/config_files.rb', line 541

def editor_line_numbers(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  EditorMode.normalize_line_numbers(editor["line_numbers"])
end

.editor_mode(config = read_config) ⇒ Object

Returns the built-in TUI editor keymap mode.



445
446
447
448
# File 'lib/kward/config_files.rb', line 445

def editor_mode(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  EditorMode.normalize(editor["mode"])
end

.editor_runners(config = read_config) ⇒ Object

Returns configured editor runner definitions, or an empty map.

Runner defaults are resolved by the editor runner at execution time so the generated config remains portable across machines.



454
455
456
457
458
# File 'lib/kward/config_files.rb', line 454

def editor_runners(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  runners = editor["runners"]
  runners.is_a?(Hash) ? runners : {}
end

.editor_soft_wrap?(config = read_config) ⇒ Boolean

Returns whether the built-in TUI editor should soft-wrap long lines.

Returns:

  • (Boolean)


529
530
531
532
# File 'lib/kward/config_files.rb', line 529

def editor_soft_wrap?(config = read_config)
  editor = config["editor"].is_a?(Hash) ? config["editor"] : {}
  editor["soft_wrap"] != false
end

.emit_warning(message, warning_sink: nil) ⇒ Object



1022
1023
1024
1025
# File 'lib/kward/config_files.rb', line 1022

def emit_warning(message, warning_sink: nil)
  sink = warning_sink || @warning_sink
  sink ? sink.call(message) : warn(message)
end

.enforce_workspace_agents_file?(config = read_config) ⇒ Boolean

Returns whether workspace AGENTS.md contents should be injected directly instead of a compact read-when-relevant instruction.

Returns:

  • (Boolean)


589
590
591
# File 'lib/kward/config_files.rb', line 589

def enforce_workspace_agents_file?(config = read_config)
  config["enforce_workspace_agents_file"] == true
end

.ensure_default_config!(path = config_path) ⇒ Object

Performs ensure default config for configuration file and path handling.



194
195
196
197
198
199
200
201
# File 'lib/kward/config_files.rb', line 194

def ensure_default_config!(path = config_path)
  path = File.expand_path(path)
  return false if skip_config? && path == config_path
  return false if File.exist?(path)

  write_config(default_config, path)
  true
end

.extract_character_instruction(definition) ⇒ Object



924
925
926
927
928
929
930
931
932
933
# File 'lib/kward/config_files.rb', line 924

def extract_character_instruction(definition)
  return nil if definition.nil?

  if definition.is_a?(Hash)
    value = definition["instruction"] || definition[:instruction]
    return presence(value)
  end

  presence(definition)
end

.extract_character_label(definition) ⇒ Object



918
919
920
921
922
# File 'lib/kward/config_files.rb', line 918

def extract_character_label(definition)
  return nil unless definition.is_a?(Hash)

  presence(definition["label"] || definition[:label])
end

.include_config_principles?(config = read_config) ⇒ Boolean

Returns whether config-directory principles are included in normal system prompt assembly. Replacement prompt files bypass all assembled sections.

Returns:

  • (Boolean)


655
656
657
658
659
660
# File 'lib/kward/config_files.rb', line 655

def include_config_principles?(config = read_config)
  settings = config["system_prompt"]
  return true unless settings.is_a?(Hash)

  settings["include_principles"] != false
end

.inside_directory?(path, base) ⇒ Boolean

Returns:

  • (Boolean)


1027
1028
1029
# File 'lib/kward/config_files.rb', line 1027

def inside_directory?(path, base)
  PathGuard.inside?(path, base)
end

.kwshrc_pathString

Returns embedded-shell rc config path.

Returns:

  • (String)

    embedded-shell rc config path



111
112
113
# File 'lib/kward/config_files.rb', line 111

def kwshrc_path
  File.join(config_dir, "kwshrc")
end

.kwshrc_pathsArray<String>

Returns embedded-shell rc config paths in load order.

Returns:

  • (Array<String>)

    embedded-shell rc config paths in load order



116
117
118
# File 'lib/kward/config_files.rb', line 116

def kwshrc_paths
  [kwshrc_path, File.expand_path("~/.kwshrc")].uniq
end

.lifecycle_hooks_config(workspace_root = Dir.pwd) ⇒ Object



283
284
285
286
287
288
289
# File 'lib/kward/config_files.rb', line 283

def lifecycle_hooks_config(workspace_root = Dir.pwd)
  config = read_config
  workspace_config = read_trusted_workspace_hooks_config(workspace_root)
  return config if workspace_config.empty?

  merge_hooks_config(config, workspace_config)
end

.mcp_servers(config = read_config) ⇒ Object

Returns configured MCP stdio servers, or an empty config when absent.



609
610
611
612
# File 'lib/kward/config_files.rb', line 609

def mcp_servers(config = read_config)
  value = config["mcpServers"] || config.dig("mcp", "servers")
  value.is_a?(Hash) ? value : {}
end

.memory_core_pathObject



238
239
240
# File 'lib/kward/config_files.rb', line 238

def memory_core_path
  File.join(memory_dir, "core.json")
end

.memory_dirString

Returns directory containing structured memory files.

Returns:

  • (String)

    directory containing structured memory files



234
235
236
# File 'lib/kward/config_files.rb', line 234

def memory_dir
  File.join(config_dir, "memory")
end

.memory_events_pathObject



246
247
248
# File 'lib/kward/config_files.rb', line 246

def memory_events_path
  File.join(memory_dir, "events.jsonl")
end

.memory_soft_pathObject



242
243
244
# File 'lib/kward/config_files.rb', line 242

def memory_soft_path
  File.join(memory_dir, "soft.jsonl")
end

.merge_hook_maps(left, right) ⇒ Object



339
340
341
342
343
344
345
346
347
# File 'lib/kward/config_files.rb', line 339

def merge_hook_maps(left, right)
  left = left.is_a?(Hash) ? left : {}
  right = right.is_a?(Hash) ? right : {}
  merged = JSON.parse(JSON.generate(left))
  right.each do |event, entries|
    merged[event.to_s] = Array(merged[event.to_s]) + Array(entries)
  end
  merged
end

.merge_hooks_config(config, workspace_config) ⇒ Object



333
334
335
336
337
# File 'lib/kward/config_files.rb', line 333

def merge_hooks_config(config, workspace_config)
  merged = JSON.parse(JSON.generate(config || {}))
  merged["hooks"] = merge_hook_maps(merged["hooks"], workspace_config["hooks"] || workspace_config[:hooks])
  merged
end

.model_catalog_cache_path(provider_id) ⇒ Object

Raises:

  • (ArgumentError)


211
212
213
214
215
216
# File 'lib/kward/config_files.rb', line 211

def model_catalog_cache_path(provider_id)
  provider = provider_id.to_s.gsub(/[^a-z0-9_-]/i, "_")
  raise ArgumentError, "Provider id must be a non-empty string" if provider.empty?

  File.join(cache_dir, "models", "#{provider}.json")
end

.named_character_values(personas) ⇒ Object



887
888
889
890
891
892
893
894
# File 'lib/kward/config_files.rb', line 887

def named_character_values(personas)
  character_entries(personas["characters"] || personas["crew"]).each_with_object({}) do |(key, definition), mapping|
    value = yield(key, definition)
    next if value.to_s.empty?

    mapping[key.to_s] = value
  end
end

.openrouter_models_cache_pathObject



207
208
209
# File 'lib/kward/config_files.rb', line 207

def openrouter_models_cache_path
  File.join(cache_dir, "openrouter_models.json")
end

.overlay_settings(config = read_config) ⇒ Hash

Returns validated overlay settings with defaults for missing or invalid values.

Parameters:

  • config (Hash) (defaults to: read_config)

    parsed config object

Returns:

  • (Hash)

    overlay settings with alignment and width



414
415
416
417
418
419
420
421
422
# File 'lib/kward/config_files.rb', line 414

def overlay_settings(config = read_config)
  overlay = config["overlay"].is_a?(Hash) ? config["overlay"] : {}
  settings = DEFAULT_OVERLAY_SETTINGS.dup
  alignment = overlay["alignment"].to_s
  width = overlay["width"].to_s
  settings["alignment"] = alignment if OVERLAY_ALIGNMENTS.include?(alignment)
  settings["width"] = width if OVERLAY_WIDTHS.include?(width)
  settings
end

.permission_policy(config = read_config) ⇒ Object

Builds the opt-in model-tool permission policy from persisted configuration.



559
560
561
# File 'lib/kward/config_files.rb', line 559

def permission_policy(config = read_config)
  Permissions::Policy.from_config(config)
end

.persona_entries(workspace_root:, model: nil, reasoning_effort: nil, now: Time.now, config: read_config, include_reasoning: true) ⇒ Object



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/kward/config_files.rb', line 756

def persona_entries(workspace_root:, model: nil, reasoning_effort: nil, now: Time.now, config: read_config, include_reasoning: true)
  personas = config["personas"]
  return [] unless personas.is_a?(Hash)

  characters = crew_characters(personas)
  entries = []
  active_persona = { layer: "default", value: personas["default"], name: nil }

  workspaces = personas["workspaces"]
  if workspaces.is_a?(Hash)
    root = canonical_workspace_root(workspace_root)
    workspaces.each do |path, key|
      if canonical_workspace_root(path) == root
        active_persona = { layer: "workspace", value: key, name: path }
        break
      end
    end
  end

  models = personas["models"]
  if models.is_a?(Hash) && !model.to_s.empty? && models.key?(model.to_s)
    active_persona = { layer: "model", value: models[model.to_s], name: model.to_s }
  end

  add_persona_entry(
    entries,
    active_persona.fetch(:layer),
    resolved_persona_text(active_persona.fetch(:value), characters: characters),
    name: active_persona[:name]
  )

  modifiers = personas["persona_modifiers"]
  if modifiers.is_a?(Hash)
    if include_reasoning
      reasoning = modifiers["reasoning"]
      add_persona_entry(entries, "reasoning", reasoning[reasoning_effort.to_s]) if reasoning.is_a?(Hash) && !reasoning_effort.to_s.empty?
    end

    time_of_day = modifiers["time_of_day"]
    bucket = time_of_day_bucket(now)
    add_persona_entry(entries, "time_of_day", time_of_day[bucket], name: bucket) if time_of_day.is_a?(Hash)

    weekday = modifiers["weekday"]
    day = weekday_name(now)
    add_persona_entry(entries, "weekday", weekday[day], name: day) if weekday.is_a?(Hash)

    add_persona_entry(entries, "suffix", modifiers["suffix"])
  end

  entries
end

.persona_label_for_key(value, labels) ⇒ Object



880
881
882
883
884
885
# File 'lib/kward/config_files.rb', line 880

def persona_label_for_key(value, labels)
  key = value.to_s.strip
  return nil if key.empty?

  presence(labels[key])
end

.persona_prompt(workspace_root, model: nil, reasoning_effort: nil, now: Time.now, config: read_config) ⇒ String?

Builds persona prompt text from default, workspace, model, reasoning, time-of-day, weekday, and suffix config entries.

Persona resolution is intentionally data-driven so users can edit config without plugin code. Keep new persona selectors additive and deterministic; prompt construction depends on stable ordering.

Parameters:

  • workspace_root (String)

    active workspace root

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

    active model name

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

    active reasoning effort

  • now (Time) (defaults to: Time.now)

    local time used for time-based modifiers

  • config (Hash) (defaults to: read_config)

    parsed config object

Returns:

  • (String, nil)

    persona prompt text when entries match



720
721
722
723
724
725
726
727
# File 'lib/kward/config_files.rb', line 720

def persona_prompt(workspace_root, model: nil, reasoning_effort: nil, now: Time.now, config: read_config)
  text = persona_entries(workspace_root: workspace_root, model: model, reasoning_effort: reasoning_effort, now: now, config: config).map do |entry|
    entry[:prompt]
  end.join("\n\n")
  return nil if text.empty?

  text
end

.plugin_dirString

Returns trusted user plugin directory.

Returns:

  • (String)

    trusted user plugin directory



960
961
962
# File 'lib/kward/config_files.rb', line 960

def plugin_dir
  File.expand_path("~/.kward/plugins")
end

.plugin_paths(warning_sink: nil) ⇒ Array<String>

Finds trusted plugin files and package entrypoints.

Plugins are intentionally loaded only from ~/.kward/plugins, not from a workspace or custom KWARD_CONFIG_PATH directory.

Returns:

  • (Array<String>)

    sorted plugin file paths



970
971
972
973
974
975
976
977
978
979
980
# File 'lib/kward/config_files.rb', line 970

def plugin_paths(warning_sink: nil)
  plugins_root = plugin_dir
  return [] unless Dir.exist?(plugins_root)

  paths = Dir.glob(File.join(plugins_root, "*.rb"))
  paths.concat(Dir.glob(File.join(plugins_root, "*", "plugin.rb")))
  paths.sort
rescue StandardError => e
  emit_warning("Warning: skipping Kward plugins in #{plugins_root}: #{e.message}", warning_sink: warning_sink)
  []
end

.presence(value) ⇒ Object



1031
1032
1033
1034
# File 'lib/kward/config_files.rb', line 1031

def presence(value)
  text = value.to_s
  text.empty? ? nil : text
end

.project_browser_icon_theme(config = read_config) ⇒ Object

Returns the project browser icon theme, or off when unset or invalid.



425
426
427
428
429
# File 'lib/kward/config_files.rb', line 425

def project_browser_icon_theme(config = read_config)
  browser = config["project_browser"].is_a?(Hash) ? config["project_browser"] : {}
  theme = browser["icons"].to_s
  PROJECT_BROWSER_ICON_THEMES.include?(theme) ? theme : "off"
end

.project_browser_state_pathObject



222
223
224
# File 'lib/kward/config_files.rb', line 222

def project_browser_state_path
  File.join(cache_dir, "project_browser_state.json")
end

.project_skill_candidates(workspace_root: Dir.pwd, warning_sink: nil) ⇒ Object



955
956
957
# File 'lib/kward/config_files.rb', line 955

def project_skill_candidates(workspace_root: Dir.pwd, warning_sink: nil)
  skills_registry(workspace_root: workspace_root, warning_sink: warning_sink).project_skill_candidates
end

.project_skills_trusted?(config = read_config) ⇒ Boolean

Returns whether project-level Agent Skills should be loaded from the workspace.

Returns:

  • (Boolean)


576
577
578
579
# File 'lib/kward/config_files.rb', line 576

def project_skills_trusted?(config = read_config)
  skills = config["skills"].is_a?(Hash) ? config["skills"] : {}
  skills["trust_project"] == true
end

.prompt_history_path(cwd, config_dir: self.config_dir, kind: "prompt") ⇒ Object



226
227
228
229
230
231
# File 'lib/kward/config_files.rb', line 226

def prompt_history_path(cwd, config_dir: self.config_dir, kind: "prompt")
  key = Digest::SHA256.hexdigest(canonical_workspace_root(cwd))[0, 24]
  return File.join(config_dir, "history", "#{key}.jsonl") if kind.to_s == "prompt"

  File.join(config_dir, "history", kind.to_s, "#{key}.jsonl")
end

.prompt_source_signature(path) ⇒ Object



820
821
822
823
824
825
826
827
# File 'lib/kward/config_files.rb', line 820

def prompt_source_signature(path)
  return "#{path}:missing" unless File.exist?(path)

  stat = File.stat(path)
  "#{path}:#{stat.size}:#{stat.mtime.to_f}"
rescue StandardError
  "#{path}:unavailable"
end

.prompt_template_registryObject



1013
1014
1015
1016
1017
1018
1019
1020
# File 'lib/kward/config_files.rb', line 1013

def prompt_template_registry
  Prompts::Templates.new(
    config_dir: config_dir,
    template_class: PromptTemplate,
    markdown_parser: ->(path) { Frontmatter.markdown_parts(path) },
    warning_sink: @warning_sink
  )
end

.prompt_templates(reserved_commands: []) ⇒ Array<PromptTemplate>

Lists prompt templates exposed as slash commands.

Parameters:

  • reserved_commands (Array<String>) (defaults to: [])

    command names unavailable to templates

Returns:



986
987
988
# File 'lib/kward/config_files.rb', line 986

def prompt_templates(reserved_commands: [])
  prompt_template_registry.prompt_templates(reserved_commands: reserved_commands)
end

.read_config(path = config_path) ⇒ Hash

Reads the JSON config file.

Missing files are treated as an empty config. Invalid JSON raises a user-facing error that includes the file path. This method does not merge defaults; callers should apply feature-specific defaults at the point where behavior is decided.

Parameters:

  • path (String) (defaults to: config_path)

    config file path

Returns:

  • (Hash)

    parsed config object



259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/kward/config_files.rb', line 259

def read_config(path = config_path)
  path = File.expand_path(path)
  return {} if skip_config? && path == config_path
  return {} unless File.exist?(path)

  config = JSON.parse(File.read(path))
  return config if config.is_a?(Hash)

  raise ConfigError.new(path: path, format: "JSON", detail: "top-level value must be an object")
rescue JSON::ParserError => e
  raise ConfigError.new(path: path, format: "JSON", detail: e.message)
end

.read_kwsh_configObject



349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/kward/config_files.rb', line 349

def read_kwsh_config
  config = {
    shell: Kwsh::DEFAULT_SHELL,
    timeout_seconds: Kwsh::DEFAULT_TIMEOUT_SECONDS,
    max_output_bytes: Kwsh::DEFAULT_MAX_OUTPUT_BYTES,
    history_limit: Kwsh::DEFAULT_HISTORY_LIMIT,
    env: {},
    aliases: {}
  }
  rc_config = read_kwshrc_config
  config[:env].merge!(rc_config[:env])
  config[:aliases].merge!(rc_config[:aliases])
  config
end

.read_kwshrc_config(paths = kwshrc_paths, env: ENV.to_h) ⇒ Object



364
365
366
367
368
# File 'lib/kward/config_files.rb', line 364

def read_kwshrc_config(paths = kwshrc_paths, env: ENV.to_h)
  Kwshrc.read(paths, env: env)
rescue Kwshrc::ParseError => e
  raise "Invalid kwshrc config: #{e.message}"
end

.read_prompt_file(path, label) ⇒ Object



829
830
831
832
833
834
835
836
837
838
839
840
841
842
# File 'lib/kward/config_files.rb', line 829

def read_prompt_file(path, label)
  return nil unless File.exist?(path)

  size = File.size(path)
  if size > MAX_PROMPT_FILE_BYTES
    emit_warning "Warning: skipping #{label} #{path}: file too large (#{size} bytes; limit is #{MAX_PROMPT_FILE_BYTES} bytes)"
    return nil
  end

  File.read(path)
rescue StandardError => e
  emit_warning "Warning: skipping #{label} #{path}: #{e.message}"
  nil
end

.read_skill_file(name, relative_path = nil, workspace_root: Dir.pwd) ⇒ String

Reads a skill file by skill name and optional relative path.

Parameters:

  • name (String)

    configured skill name

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

    path inside the skill directory

Returns:

  • (String)

    file contents or an error string



995
996
997
# File 'lib/kward/config_files.rb', line 995

def read_skill_file(name, relative_path = nil, workspace_root: Dir.pwd)
  skills_registry(workspace_root: workspace_root).read_skill_file(name, relative_path)
end

.read_trusted_workspace_hooksObject



326
327
328
329
330
331
# File 'lib/kward/config_files.rb', line 326

def read_trusted_workspace_hooks
  config = read_config(trusted_workspace_hooks_path)
  config.is_a?(Hash) ? config : {}
rescue ConfigError
  {}
end

.read_trusted_workspace_hooks_config(workspace_root = Dir.pwd) ⇒ Object



291
292
293
294
295
296
# File 'lib/kward/config_files.rb', line 291

def read_trusted_workspace_hooks_config(workspace_root = Dir.pwd)
  path = workspace_hooks_path(workspace_root)
  return {} unless workspace_hooks_trusted?(workspace_root)

  read_config(path)
end

.replacement_system_prompt?(config = read_config) ⇒ Boolean

Returns:

  • (Boolean)


683
684
685
# File 'lib/kward/config_files.rb', line 683

def replacement_system_prompt?(config = read_config)
  !system_prompt_file_path(config).nil?
end

.resolved_persona_text(value, characters: {}) ⇒ Object



868
869
870
871
872
873
874
875
876
877
878
# File 'lib/kward/config_files.rb', line 868

def resolved_persona_text(value, characters: {})
  return nil if value.nil?

  key = value.to_s.strip
  return nil if key.empty?

  text = characters[key.to_s]
  return text unless text.to_s.empty?

  value
end

.sandbox_policy(workspace_root, config = read_config) ⇒ Object

Builds the user-controlled command sandbox policy for a workspace.



564
565
566
567
568
569
570
571
572
573
# File 'lib/kward/config_files.rb', line 564

def sandbox_policy(workspace_root, config = read_config)
  sandbox = config["sandbox"].is_a?(Hash) ? config["sandbox"] : {}
  Sandbox::Policy.new(
    mode: sandbox.fetch("mode", "off"),
    network: sandbox.fetch("network", "deny"),
    workspace_root: workspace_root,
    writable_roots: sandbox.fetch("writable_roots", []),
    protect_git_metadata: sandbox.fetch("protect_git_metadata", true)
  )
end

.session_auto_resume_enabled?(config = read_config) ⇒ Boolean

Returns whether new frontends should resume the last active session automatically.

Returns:

  • (Boolean)


582
583
584
585
# File 'lib/kward/config_files.rb', line 582

def session_auto_resume_enabled?(config = read_config)
  sessions = config["sessions"].is_a?(Hash) ? config["sessions"] : {}
  sessions["auto_resume"] == true
end

.shell_agent_model(config = read_config) ⇒ Object

Returns the shell-agent model override, preferring the environment.



487
488
489
490
491
492
# File 'lib/kward/config_files.rb', line 487

def shell_agent_model(config = read_config)
  value = ENV["KWSH_MODE"].to_s.strip
  return value unless value.empty?

  shell_agent_setting(config, "model")
end

.shell_agent_provider(config = read_config) ⇒ Object

Returns the shell-agent provider override, preferring the environment.



479
480
481
482
483
484
# File 'lib/kward/config_files.rb', line 479

def shell_agent_provider(config = read_config)
  value = ENV["KWSH_PROVIDER"].to_s.strip
  return value unless value.empty?

  shell_agent_setting(config, "provider")
end

.shell_agent_reasoning_effort(config = read_config) ⇒ Object

Returns the shell-agent reasoning-effort override, preferring the environment.



495
496
497
498
499
500
# File 'lib/kward/config_files.rb', line 495

def shell_agent_reasoning_effort(config = read_config)
  value = ENV["KWSH_REASONING"].to_s.strip
  return value unless value.empty?

  shell_agent_setting(config, "reasoning_effort")
end

.shell_agent_setting(config, key) ⇒ Object



509
510
511
512
513
514
# File 'lib/kward/config_files.rb', line 509

def shell_agent_setting(config, key)
  shell = config["shell"].is_a?(Hash) ? config["shell"] : {}
  agent = shell["agent"].is_a?(Hash) ? shell["agent"] : {}
  value = agent[key].to_s.strip
  value.empty? ? nil : value
end

.skills(workspace_root: Dir.pwd, warning_sink: nil, project_skill_paths: nil) ⇒ Array<Skill>

Lists configured skills discovered under the config directory.

Returns:

  • (Array<Skill>)

    skill metadata available to the model



951
952
953
# File 'lib/kward/config_files.rb', line 951

def skills(workspace_root: Dir.pwd, warning_sink: nil, project_skill_paths: nil)
  skills_registry(workspace_root: workspace_root, warning_sink: warning_sink, project_skill_paths: project_skill_paths).skills
end

.skills_registry(workspace_root: Dir.pwd, warning_sink: nil, project_skill_paths: nil) ⇒ Object



999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
# File 'lib/kward/config_files.rb', line 999

def skills_registry(workspace_root: Dir.pwd, warning_sink: nil, project_skill_paths: nil)
  Skills::Registry.new(
    config_dir: config_dir,
    workspace_root: workspace_root,
    project_skills_trusted: project_skills_trusted?,
    skill_class: Skill,
    max_file_bytes: MAX_SKILL_FILE_BYTES,
    markdown_parser: ->(path) { Frontmatter.markdown_parts(path, lenient: true) },
    inside_directory: method(:inside_directory?),
    warning_sink: warning_sink || @warning_sink,
    project_skill_paths: project_skill_paths
  )
end

.skip_config=(value) ⇒ Object



73
74
75
# File 'lib/kward/config_files.rb', line 73

def skip_config=(value)
  @skip_config = value
end

.skip_config?Boolean

Returns:

  • (Boolean)


85
86
87
# File 'lib/kward/config_files.rb', line 85

def skip_config?
  @skip_config == true
end

.system_prompt_file(config = read_config) ⇒ Object

Returns the replacement system prompt text when configured. A configured but unavailable file intentionally yields nil: callers must not fall back to Kward's larger assembled prompt in replacement mode.



676
677
678
679
680
681
# File 'lib/kward/config_files.rb', line 676

def system_prompt_file(config = read_config)
  path = system_prompt_file_path(config)
  return nil unless path

  read_prompt_file(path, "custom system prompt file")
end

.system_prompt_file_path(config = read_config) ⇒ Object

Returns the configured replacement system prompt path, or nil when normal prompt assembly should be used. Relative paths are anchored to the config directory so configuration remains portable with KWARD_CONFIG_PATH.



665
666
667
668
669
670
671
# File 'lib/kward/config_files.rb', line 665

def system_prompt_file_path(config = read_config)
  settings = config["system_prompt"]
  value = settings.is_a?(Hash) ? settings["file"].to_s.strip : ""
  return nil if value.empty?

  File.expand_path(value, config_dir)
end

.system_prompt_sources_fingerprintObject

Returns a lightweight fingerprint for config-owned prompt sources. It is used by active conversations to pick up prompt edits without a restart.



689
690
691
692
693
694
695
696
697
# File 'lib/kward/config_files.rb', line 689

def system_prompt_sources_fingerprint
  config = read_config
  paths = [config_path, system_prompt_file_path(config)]
  if include_config_principles?(config)
    paths << (File.exist?(config_principles_path) ? config_principles_path : config_agents_path)
  end

  paths.compact.map { |path| prompt_source_signature(path) }.join("\0")
end

.time_of_day_bucket(now) ⇒ Object



935
936
937
938
939
940
941
942
# File 'lib/kward/config_files.rb', line 935

def time_of_day_bucket(now)
  hour = now.hour
  return "morning" if hour >= 5 && hour < 11
  return "before_lunch" if hour == 11
  return "late_evening" if hour >= 21 || hour < 5

  nil
end

.transport_config(transport_id, config = read_config) ⇒ Object

Returns the private configuration namespace for one transport.



600
601
602
603
604
605
606
# File 'lib/kward/config_files.rb', line 600

def transport_config(transport_id, config = read_config)
  transports = config["transports"]
  return {} unless transports.is_a?(Hash)

  values = transports[transport_id.to_s]
  values.is_a?(Hash) ? DeepCopy.dup(values) : {}
end

.trust_workspace_hooks!(workspace_root = Dir.pwd) ⇒ Object



306
307
308
309
310
311
312
313
# File 'lib/kward/config_files.rb', line 306

def trust_workspace_hooks!(workspace_root = Dir.pwd)
  path = workspace_hooks_path(workspace_root)
  raise "No workspace hook config found: #{path}" unless File.file?(path)

  trusted = read_trusted_workspace_hooks
  trusted[File.expand_path(path)] = workspace_hooks_digest(workspace_root)
  PrivateFile.write_json(trusted_workspace_hooks_path, trusted)
end

.trusted_workspace_hooks_pathObject



124
125
126
# File 'lib/kward/config_files.rb', line 124

def trusted_workspace_hooks_path
  File.join(config_dir, "trusted_workspace_hooks.json")
end

.untrust_workspace_hooks!(workspace_root = Dir.pwd) ⇒ Object



315
316
317
318
319
320
# File 'lib/kward/config_files.rb', line 315

def untrust_workspace_hooks!(workspace_root = Dir.pwd)
  path = File.expand_path(workspace_hooks_path(workspace_root))
  trusted = read_trusted_workspace_hooks
  trusted.delete(path)
  PrivateFile.write_json(trusted_workspace_hooks_path, trusted)
end

.update_check_cache_pathObject



218
219
220
# File 'lib/kward/config_files.rb', line 218

def update_check_cache_path
  File.join(cache_dir, "update_check.json")
end

.update_config(values, path = config_path) ⇒ Object

Merges top-level config values and writes the updated config privately.



371
372
373
374
375
376
377
378
# File 'lib/kward/config_files.rb', line 371

def update_config(values, path = config_path)
  raise "Config values must be an object" unless values.is_a?(Hash)

  config = read_config(path)
  values.each { |key, value| config[key.to_s] = value }
  write_config(config, path)
  config
end

.update_nested_config(section, values, path = config_path) ⇒ Object

Merges values into a one-level nested config section and writes privately.



381
382
383
384
385
386
387
388
389
# File 'lib/kward/config_files.rb', line 381

def update_nested_config(section, values, path = config_path)
  raise "Config values must be an object" unless values.is_a?(Hash)

  config = read_config(path)
  current = config[section.to_s].is_a?(Hash) ? config[section.to_s].dup : {}
  config[section.to_s] = current.merge(values.transform_keys(&:to_s))
  write_config(config, path)
  config
end

.update_overlay_settings(values) ⇒ Object

Validates and persists terminal overlay settings.



615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'lib/kward/config_files.rb', line 615

def update_overlay_settings(values)
  raise "Overlay settings must be an object" unless values.is_a?(Hash)

  config = read_config
  overlay = overlay_settings(config)
  values.each do |key, value|
    key = key.to_s
    value = value.to_s
    case key
    when "alignment"
      raise "Overlay alignment must be left, center, or right" unless OVERLAY_ALIGNMENTS.include?(value)
    when "width"
      raise "Overlay width must be capped or maximum" unless OVERLAY_WIDTHS.include?(value)
    else
      raise "Unknown overlay setting: #{key}"
    end
    overlay[key] = value
  end
  config["overlay"] = overlay
  write_config(config)
  overlay_settings(config)
end

.warning_sinkObject



81
82
83
# File 'lib/kward/config_files.rb', line 81

def warning_sink
  @warning_sink
end

.warning_sink=(sink) ⇒ Object



77
78
79
# File 'lib/kward/config_files.rb', line 77

def warning_sink=(sink)
  @warning_sink = sink
end

.web_search_config(config = read_config) ⇒ Object

Returns the nested web-search config object, or an empty config when absent.



594
595
596
597
# File 'lib/kward/config_files.rb', line 594

def web_search_config(config = read_config)
  value = config["web_search"]
  value.is_a?(Hash) ? value : {}
end

.weekday_name(now) ⇒ Object



944
945
946
# File 'lib/kward/config_files.rb', line 944

def weekday_name(now)
  %w[sunday monday tuesday wednesday thursday friday saturday][now.wday]
end

.workspace_agents_file?(workspace_root) ⇒ Boolean

Returns:

  • (Boolean)


812
813
814
# File 'lib/kward/config_files.rb', line 812

def workspace_agents_file?(workspace_root)
  File.exist?(workspace_agents_path(workspace_root))
end

.workspace_agents_path(workspace_root) ⇒ Object



808
809
810
# File 'lib/kward/config_files.rb', line 808

def workspace_agents_path(workspace_root)
  File.join(canonical_workspace_root(workspace_root), "AGENTS.md")
end

.workspace_agents_prompt(workspace_root) ⇒ Object



816
817
818
# File 'lib/kward/config_files.rb', line 816

def workspace_agents_prompt(workspace_root)
  read_prompt_file(workspace_agents_path(workspace_root), "workspace AGENTS.md")
end

.workspace_guardrails_enabled?(config = read_config) ⇒ Boolean

Returns whether file tools must stay inside the active workspace root.

Returns:

  • (Boolean)


553
554
555
556
# File 'lib/kward/config_files.rb', line 553

def workspace_guardrails_enabled?(config = read_config)
  tools = config["tools"].is_a?(Hash) ? config["tools"] : {}
  tools["workspace_guardrails"] != false
end

.workspace_hooks_digest(workspace_root = Dir.pwd) ⇒ Object



322
323
324
# File 'lib/kward/config_files.rb', line 322

def workspace_hooks_digest(workspace_root = Dir.pwd)
  Digest::SHA256.file(workspace_hooks_path(workspace_root)).hexdigest
end

.workspace_hooks_path(root = Dir.pwd) ⇒ Object



120
121
122
# File 'lib/kward/config_files.rb', line 120

def workspace_hooks_path(root = Dir.pwd)
  File.join(File.expand_path(root), ".kward", "hooks.json")
end

.workspace_hooks_trusted?(workspace_root = Dir.pwd) ⇒ Boolean

Returns:

  • (Boolean)


298
299
300
301
302
303
304
# File 'lib/kward/config_files.rb', line 298

def workspace_hooks_trusted?(workspace_root = Dir.pwd)
  path = workspace_hooks_path(workspace_root)
  return false unless File.file?(path)

  trusted = read_trusted_workspace_hooks
  trusted[File.expand_path(path)] == workspace_hooks_digest(workspace_root)
end

.write_config(config, path = config_path) ⇒ Object

Writes config JSON using private file permissions.

Parameters:

  • config (Hash)

    config object to persist

  • path (String) (defaults to: config_path)

    config file path



276
277
278
279
280
281
# File 'lib/kward/config_files.rb', line 276

def write_config(config, path = config_path)
  path = File.expand_path(path)
  raise "Cannot write Kward config while --skip-config is active: #{path}" if skip_config? && path == config_path

  PrivateFile.write_json(path, config)
end