ki-manager 2.2.0__tar.gz → 2.3.0.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. ki_manager-2.3.0.dev1/CHANGELOG.md +116 -0
  2. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/PKG-INFO +26 -1
  3. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/README.md +25 -0
  4. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/pyproject.toml +1 -1
  5. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/__init__.py +1 -1
  6. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/cli.py +19 -3
  7. ki_manager-2.3.0.dev1/src/ki_manager/scripts/add_ki_to_config.py +80 -0
  8. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/generate_dir_index.py +1 -1
  9. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/ki_graph_visualize.py +43 -10
  10. ki_manager-2.3.0.dev1/src/ki_manager/scripts/ki_search.py +305 -0
  11. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/ki_utils.py +266 -53
  12. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/knowledge_engine.py +8 -3
  13. ki_manager-2.3.0.dev1/src/ki_manager/scripts/sync_agents_md.py +160 -0
  14. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/server.py +753 -105
  15. ki_manager-2.3.0.dev1/src/ki_manager/tools/facade.py +385 -0
  16. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/tools/scaffold.py +24 -42
  17. ki_manager-2.3.0.dev1/src/ki_manager/workflows/create-adr.md +76 -0
  18. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/workflows/expand-knowledge.md +65 -25
  19. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/workflows/scaffold-knowledge.md +90 -30
  20. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/workflows/sync-knowledge.md +48 -13
  21. ki_manager-2.2.0/CHANGELOG.md +0 -74
  22. ki_manager-2.2.0/src/ki_manager/scripts/add_ki_to_config.py +0 -57
  23. ki_manager-2.2.0/src/ki_manager/workflows/create-adr.md +0 -64
  24. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/.gitignore +0 -0
  25. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/LICENSE +0 -0
  26. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/analyze_module.py +0 -0
  27. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/audit_coverage.py +0 -0
  28. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/finalize_ki_scaffolds.py +0 -0
  29. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/find_unmapped_files.py +0 -0
  30. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/generate_ki_scaffolds.py +0 -0
  31. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/scripts/ki_dependency_analyzer.py +0 -0
  32. {ki_manager-2.2.0 → ki_manager-2.3.0.dev1}/src/ki_manager/tools/__init__.py +0 -0
@@ -0,0 +1,116 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `ki-manager` project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ <!-- Note: This changelog is intended for end-users and AI agents. It must always be maintained in English and focus on user-facing features, behavior changes, and bug fixes rather than internal implementation details. -->
9
+
10
+ ## [Unreleased]
11
+
12
+ ## [2.3.0.dev1] — 2026-10-05
13
+
14
+ ### Added
15
+ - `--tool-mode full|compact` CLI option and `KI_TOOL_MODE` environment variable: compact facade mode reducing `tools/list` from 33 schemas to 6 essential tools (`ki_instructions`, `ki_search`, `ki_read`, `ki_tools`, `ki_call`, `ki_mutate`), drastically reducing context token usage for MCP clients.
16
+ - `ki_search` MCP tool & search engine: BM25 ranking across Knowledge Items and ADRs without external embedding dependencies, featuring bilingual RU/EN stemming, weighted fields (Title x5, Headers x3, Path x2, Body x1), and contextual snippets.
17
+ - `ki_read` MCP tool: token-efficient reader for KI and ADR markdown files with section filtering and character limit truncation.
18
+ - `ki_tools` MCP tool: grouped catalog of all available tools and on-demand JSON schema inspector.
19
+ - `ki_call` and `ki_mutate` facade dispatchers: safe routing with schema validation and enforcement of `readOnlyHint` (read-only queries in `ki_call`, mutations in `ki_mutate`).
20
+ - Dynamic instructions & template directives: workflows and server rules dynamically adapt tool call examples and `allowed-tools` frontmatter to active `--tool-mode` (`full` vs `compact`) via HTML comment directives (`<!-- if-compact -->`), maintaining a single source of truth without content divergence.
21
+ - Dedicated Agent Skill `ki-manager-workflows`: guide in `.agent/skills/ki-manager-workflows/` for authoring and maintaining dual-mode workflow instructions.
22
+ - CLI `install-skills` mode option: `ki-manager install-skills` supports `--tool-mode full|compact` to render installed skill markdown for the intended client environment.
23
+ - `add_ki_to_config` MCP tool and CLI helper: safely register or update Knowledge Items in `doc_config.json` with sandbox checks and atomic file updates.
24
+ - `edit_doc_config` MCP tool: granular and safe modifications (`set`, `append`, `delete`) to service sections (`tracked_modules`, `artifacts`, `coverage_settings`) of `doc_config.json`.
25
+ - `sync_agents_md` MCP tool and script: synchronize Knowledge Items and ADR tables in `AGENTS.md` using the single source of truth from `doc_config.json` and `decisions/`.
26
+ - Per-project configurable agent instructions sync: `sync_agents_md` can be disabled via `"sync_agents_md": false` in `ki_config.json` to prevent context pollution in large projects.
27
+ - `create_adr` MCP tool: create new Architecture Decision Records (ADR) with auto-incremented sequential ID prefix (`XXX`), standardized metadata, registration in `doc_config.json`, and automatic `AGENTS.md` sync.
28
+ - Structured ADR table parser and enhanced `ki://adr-list.md` virtual resource displaying ID, Title, Status, Date, and File links.
29
+ - Automatic IDE MCP tool schema generation (`<tool>.json`) for Antigravity, Cursor, and Windsurf on startup.
30
+ - Comprehensive positive and negative test suite for configuration tools, ADR creation, synchronization rules, and sandbox enforcement.
31
+ - Flexible configuration discovery: `ki_config.json` can now reside in project root, `.config/`, `config/`, `.ki-base/`, or `.know/`.
32
+ - Fileless project registration: `ki_register_project` now supports registering projects directly via `workspace` and `inline_config` in `~/.ki_base/registry.json` without requiring configuration files on disk.
33
+ - First-class custom knowledge root support: `paths.knowledge_root` is dynamically resolved and respected across all tools, engines, and scripts without chicken-and-egg discovery issues.
34
+ - Configurable scaffolding: `ki_init_project` now accepts `knowledge_root` and `config_location` (`root` or `knowledge_dir`) parameters.
35
+ - Dynamic workflow paths: workflow instructions dynamically substitute `{{KI_DIR}}` with the active project's knowledge folder name.
36
+ - Unit and negative test coverage for flexible discovery, custom roots, and registry validation errors.
37
+
38
+ ### Changed
39
+ - `scaffold.migrate_project` now preserves existing `AGENTS.md` files instead of forcibly deleting them.
40
+ - Neutralized MCP tool descriptions and server prompt schemas, replacing hardcoded `.ki-base/` with dynamic references.
41
+
42
+
43
+ ### Fixed
44
+ - Fixed an issue where `write_know_file` could permanently delete the contents of a file (leaving 0 bytes) if an encoding error occurred during saving.
45
+ - Fixed server crashes and communication failures on Windows when handling text with emojis or special Unicode characters.
46
+ - Fixed `edit_know_file` frequently failing to find and replace text blocks on Windows due to invisible line-ending mismatches (CRLF vs LF).
47
+ - Fixed the `update_last_verified` tool being completely unusable due to a "missing script" error.
48
+ - Fixed `git_checkpoint` failing to create backups when the project contained `.gitignore`'d files.
49
+ - Fixed incorrect schema definitions that prevented AI agents from successfully calling parameterless tools.
50
+ - Fixed outdated workflow instructions that were causing AI agents to fail by using the deprecated `ki_call` syntax.
51
+
52
+ ## [2.2.0] — 2026-09-24
53
+
54
+ ### Added
55
+ - `ki_graph_visualize` MCP tool: on-the-fly Mermaid architecture diagrams visualizing dependencies and file clusters across Knowledge Items.
56
+ - Cross-platform CI matrix workflow testing both Ubuntu and Windows environments on Python 3.10, 3.11, and 3.12.
57
+ - End-to-end MCP integration test suite validating real JSON-RPC stdio subprocess communication, handshake, and tool execution.
58
+ - Automated pre-flight release verification gate ensuring zero broken packages before release tagging.
59
+
60
+ ### Fixed
61
+ - Proper exit codes and help formatting for `ki-manager-skills` CLI flags (`--help`, `-h`, `--version`).
62
+
63
+ ## [2.1.4] — 2026-09-22
64
+
65
+ ### Added
66
+ - Unified file and directory exclusion engine supporting glob patterns (`*`, `?`) across configuration files (`config.json`, `doc_config.json`, `ki_config.json`).
67
+ - Official project changelog following the Keep a Changelog standard.
68
+
69
+ ### Changed
70
+ - Knowledge audit tools (`audit_coverage`, `find_unmapped_files`, `generate_dir_index`, `analyze_dependencies`) now consistently respect all configured exclusion rules.
71
+
72
+ ### Fixed
73
+ - UTF-8 encoding crashes when running MCP tool scripts in Windows environments.
74
+
75
+ ## [2.1.3] — 2026-08-12
76
+
77
+ ### Added
78
+ - `ki_finalize_scaffolds` MCP tool for bulk finalizing generated Knowledge Item drafts.
79
+ - Bundled `scaffold-knowledge` workflow for AI coding assistants.
80
+ - Installation hint for `ki-manager-skills install-skills` displayed during server startup.
81
+
82
+ ### Changed
83
+ - Synchronized Smithery catalog manifest with updated schemas for all 25 MCP tools.
84
+
85
+ ## [2.1.2] — 2026-08-11
86
+
87
+ ### Fixed
88
+ - Test suite verification during automated package build and release.
89
+
90
+ ## [2.1.1] — 2026-08-11
91
+
92
+ ### Fixed
93
+ - Workspace path resolution compliance with the updated MCP protocol specification.
94
+
95
+ ## [2.1.0] — 2026-08-11
96
+
97
+ ### Added
98
+ - Support for `server/discover` handshake and workspace folder detection under MCP 2026-07-28 protocol.
99
+ - `ki-manager-skills` CLI command to easily install bundled workflows into IDE skill directories.
100
+ - Automated release workflow for publishing packages to PyPI and Smithery Registry.
101
+
102
+ ## [2.0.0] — 2026-07-24
103
+
104
+ ### Added
105
+ - Initial 2.0 release of the `ki-manager` MCP server for project knowledge base management.
106
+
107
+ [Unreleased]: https://github.com/Laeryid/KI-base/compare/v2.3.0.dev1...HEAD
108
+ [2.3.0.dev1]: https://github.com/Laeryid/KI-base/compare/v2.2.1...v2.3.0.dev1
109
+ [2.2.1]: https://github.com/Laeryid/KI-base/compare/v2.2.0...v2.2.1
110
+ [2.2.0]: https://github.com/Laeryid/KI-base/compare/v2.1.4...v2.2.0
111
+ [2.1.4]: https://github.com/Laeryid/KI-base/compare/v2.1.3...v2.1.4
112
+ [2.1.3]: https://github.com/Laeryid/KI-base/compare/v2.1.2...v2.1.3
113
+ [2.1.2]: https://github.com/Laeryid/KI-base/compare/v2.1.1...v2.1.2
114
+ [2.1.1]: https://github.com/Laeryid/KI-base/compare/v2.1.0...v2.1.1
115
+ [2.1.0]: https://github.com/Laeryid/KI-base/compare/v2.0.37...v2.1.0
116
+ [2.0.0]: https://github.com/Laeryid/KI-base/releases/tag/v2.0.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ki-manager
3
- Version: 2.2.0
3
+ Version: 2.3.0.dev1
4
4
  Summary: Knowledge Item (KI) management MCP server for AI-assisted development
5
5
  Project-URL: Homepage, https://github.com/Laeryid/KI-base
6
6
  Project-URL: Repository, https://github.com/Laeryid/KI-base
@@ -43,6 +43,10 @@ Classifier: Topic :: Software Development :: Documentation
43
43
  Requires-Python: >=3.8
44
44
  Description-Content-Type: text/markdown
45
45
 
46
+ <p align="center">
47
+ <img src="https://raw.githubusercontent.com/Laeryid/KI-base/main/ki_manager_logo.png" width="150" alt="ki-manager Logo">
48
+ </p>
49
+
46
50
  # ki-manager — Knowledge Item MCP Server
47
51
 
48
52
  > AI-powered knowledge management for software projects.
@@ -122,6 +126,23 @@ On Windows:
122
126
  }
123
127
  ```
124
128
 
129
+ ### Compact Mode (Token Saver)
130
+
131
+ By default, `ki-manager` runs in `full` mode and exposes all tools directly. For AI clients that inject tool definitions into the context window, you can enable compact facade mode to expose only 6 essential tools (`ki_instructions`, `ki_search`, `ki_read`, `ki_tools`, `ki_call`, `ki_mutate`):
132
+
133
+ ```json
134
+ {
135
+ "mcpServers": {
136
+ "ki-manager": {
137
+ "command": "ki-manager",
138
+ "args": ["--tool-mode", "compact"]
139
+ }
140
+ }
141
+ }
142
+ ```
143
+
144
+ Alternatively, set the environment variable `KI_TOOL_MODE=compact`.
145
+
125
146
  ---
126
147
 
127
148
  ## Quickstart
@@ -164,6 +185,10 @@ Use the available tools or slash commands:
164
185
  | `ki_scaffold` | Create stub KI files for uncovered modules |
165
186
  | `ki_scaffold_status` | Show pending vs enriched scaffold KIs |
166
187
  | `ki_finalize_scaffolds` | Strip scaffold markers, update doc_config summaries |
188
+ | `add_ki_to_config` | Register or update Knowledge Item in `doc_config.json` |
189
+ | `edit_doc_config` | Safely modify `doc_config.json` (`tracked_modules`, `artifacts`, `coverage_settings`) |
190
+ | `sync_agents_md` | Sync Knowledge Items and ADR tables in `AGENTS.md` (can be disabled via `sync_agents_md: false` in `ki_config.json`) |
191
+ | `create_adr` | Create structured ADR with sequential ID, template, and auto-registration |
167
192
  | `analyze_all_dependencies` | Update "Related KIs" links across all KIs |
168
193
  | `git_checkpoint` | Save knowledge snapshot to git |
169
194
  | `/scaffold-knowledge` | Bootstrap KI stubs → AI enrichment → finalize |
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/Laeryid/KI-base/main/ki_manager_logo.png" width="150" alt="ki-manager Logo">
3
+ </p>
4
+
1
5
  # ki-manager — Knowledge Item MCP Server
2
6
 
3
7
  > AI-powered knowledge management for software projects.
@@ -77,6 +81,23 @@ On Windows:
77
81
  }
78
82
  ```
79
83
 
84
+ ### Compact Mode (Token Saver)
85
+
86
+ By default, `ki-manager` runs in `full` mode and exposes all tools directly. For AI clients that inject tool definitions into the context window, you can enable compact facade mode to expose only 6 essential tools (`ki_instructions`, `ki_search`, `ki_read`, `ki_tools`, `ki_call`, `ki_mutate`):
87
+
88
+ ```json
89
+ {
90
+ "mcpServers": {
91
+ "ki-manager": {
92
+ "command": "ki-manager",
93
+ "args": ["--tool-mode", "compact"]
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ Alternatively, set the environment variable `KI_TOOL_MODE=compact`.
100
+
80
101
  ---
81
102
 
82
103
  ## Quickstart
@@ -119,6 +140,10 @@ Use the available tools or slash commands:
119
140
  | `ki_scaffold` | Create stub KI files for uncovered modules |
120
141
  | `ki_scaffold_status` | Show pending vs enriched scaffold KIs |
121
142
  | `ki_finalize_scaffolds` | Strip scaffold markers, update doc_config summaries |
143
+ | `add_ki_to_config` | Register or update Knowledge Item in `doc_config.json` |
144
+ | `edit_doc_config` | Safely modify `doc_config.json` (`tracked_modules`, `artifacts`, `coverage_settings`) |
145
+ | `sync_agents_md` | Sync Knowledge Items and ADR tables in `AGENTS.md` (can be disabled via `sync_agents_md: false` in `ki_config.json`) |
146
+ | `create_adr` | Create structured ADR with sequential ID, template, and auto-registration |
122
147
  | `analyze_all_dependencies` | Update "Related KIs" links across all KIs |
123
148
  | `git_checkpoint` | Save knowledge snapshot to git |
124
149
  | `/scaffold-knowledge` | Bootstrap KI stubs → AI enrichment → finalize |
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "ki-manager"
7
- version = "2.2.0"
7
+ version = "2.3.0.dev1"
8
8
  description = "Knowledge Item (KI) management MCP server for AI-assisted development"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -1,3 +1,3 @@
1
1
 
2
2
  """ki-manager — Knowledge Item MCP server for AI-assisted development."""
3
- __version__ = "2.2.0"
3
+ __version__ = "2.3.0.dev1"
@@ -11,6 +11,7 @@ Usage:
11
11
  """
12
12
 
13
13
  import sys
14
+ import os
14
15
  import argparse
15
16
  from pathlib import Path
16
17
 
@@ -61,6 +62,13 @@ def install_skills(argv=None):
61
62
  default=None,
62
63
  help="Target skills directory (default: current working directory)",
63
64
  )
65
+ parser.add_argument(
66
+ "--tool-mode",
67
+ type=str,
68
+ choices=["full", "compact"],
69
+ default=None,
70
+ help="Format for skill instructions (default: full, or KI_TOOL_MODE env var)",
71
+ )
64
72
  args = parser.parse_args(argv)
65
73
 
66
74
  target = Path(args.path).resolve() if args.path else Path.cwd()
@@ -77,9 +85,17 @@ def install_skills(argv=None):
77
85
  installed = []
78
86
  skipped = []
79
87
 
88
+ # Import facade renderer
89
+ sys.path.insert(0, str(_PACKAGE_DIR / "tools"))
90
+ from facade import render_instruction
91
+ target_mode = (args.tool_mode or os.environ.get("KI_TOOL_MODE", "full")).lower()
92
+ if target_mode not in ("full", "compact"):
93
+ target_mode = "full"
94
+
80
95
  for wf_file in workflow_files:
81
- content = wf_file.read_text(encoding="utf-8")
82
- meta, _ = _parse_frontmatter(content)
96
+ raw_content = wf_file.read_text(encoding="utf-8")
97
+ rendered_content = render_instruction(raw_content, tool_mode=target_mode)
98
+ meta, _ = _parse_frontmatter(rendered_content)
83
99
 
84
100
  skill_name = meta.get("name") or f"ki-manager-{wf_file.stem}"
85
101
  skill_dir = target / skill_name
@@ -90,7 +106,7 @@ def install_skills(argv=None):
90
106
  continue
91
107
 
92
108
  skill_dir.mkdir(parents=True, exist_ok=True)
93
- skill_md.write_text(content, encoding="utf-8")
109
+ skill_md.write_text(rendered_content, encoding="utf-8")
94
110
  installed.append(skill_name)
95
111
 
96
112
  print(f"Installed: {len(installed)} skill(s)")
@@ -0,0 +1,80 @@
1
+ """
2
+ add_ki_to_config.py
3
+
4
+ CLI helper and module function to register or update a Knowledge Item in doc_config.json.
5
+ """
6
+
7
+ import sys
8
+ import os
9
+ import json
10
+ import argparse
11
+ from typing import List, Optional
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+ import ki_utils
15
+
16
+
17
+ def add_ki(
18
+ ki_name: str,
19
+ description: str,
20
+ covers: Optional[List[str]] = None,
21
+ depends_on: Optional[List[str]] = None,
22
+ summary: Optional[str] = None
23
+ ) -> str:
24
+ """
25
+ Registers or updates a Knowledge Item in doc_config.json.
26
+ """
27
+ if not ki_name:
28
+ raise ValueError("ki_name is required.")
29
+
30
+ covers = covers if covers is not None else []
31
+ depends_on = depends_on if depends_on is not None else []
32
+
33
+ config = ki_utils.get_doc_config()
34
+ if not config and not ki_utils.get_doc_config_path():
35
+ raise PermissionError("No active workspace detected or doc_config.json not found.")
36
+
37
+ if "knowledge_items" not in config:
38
+ config["knowledge_items"] = {}
39
+
40
+ existing = config["knowledge_items"].get(ki_name, {})
41
+ entry = {
42
+ "description": description if description else existing.get("description", ""),
43
+ "covers": covers,
44
+ "depends_on": depends_on,
45
+ }
46
+
47
+ if summary:
48
+ entry["summary"] = summary
49
+ elif "summary" in existing:
50
+ entry["summary"] = existing["summary"]
51
+ elif description:
52
+ entry["summary"] = description
53
+
54
+ config["knowledge_items"][ki_name] = entry
55
+ ki_utils.save_doc_config(config)
56
+ return f"Knowledge Item '{ki_name}' successfully registered in doc_config.json"
57
+
58
+
59
+ def main():
60
+ parser = argparse.ArgumentParser(description="Add or update a Knowledge Item in doc_config.json")
61
+ parser.add_argument("ki_name", type=str, help="Knowledge Item filename")
62
+ parser.add_argument("description", type=str, help="KI description")
63
+ parser.add_argument("--covers", type=str, default="[]", help="JSON array of covered modules")
64
+ parser.add_argument("--depends-on", type=str, default="[]", help="JSON array of dependencies")
65
+ parser.add_argument("--summary", type=str, default=None, help="Optional summary text")
66
+
67
+ args = parser.parse_args()
68
+ try:
69
+ covers = json.loads(args.covers)
70
+ depends_on = json.loads(args.depends_on)
71
+ except json.JSONDecodeError as e:
72
+ print(f"Error decoding JSON arguments: {e}")
73
+ sys.exit(1)
74
+
75
+ result = add_ki(args.ki_name, args.description, covers, depends_on, args.summary)
76
+ print(result)
77
+
78
+
79
+ if __name__ == "__main__":
80
+ main()
@@ -94,7 +94,7 @@ def build_tree(root: str, knowledge_root_name: str,
94
94
  def generate_dir_index(output_path: str, max_depth: int = 3) -> None:
95
95
  project_root = get_project_root()
96
96
  knowledge_root = get_knowledge_root()
97
- knowledge_root_name = os.path.basename(knowledge_root) if knowledge_root else ".know"
97
+ knowledge_root_name = os.path.basename(knowledge_root) if knowledge_root else ".ki-base"
98
98
  now = datetime.now(timezone.utc).strftime("%Y-%m-%d")
99
99
  project_name = os.path.basename(os.path.abspath(project_root))
100
100
  total_files = count_files_in_dir(project_root)
@@ -14,6 +14,7 @@ import os
14
14
  import sys
15
15
  import re
16
16
  import argparse
17
+ import textwrap
17
18
  from pathlib import Path
18
19
  from typing import Dict, List, Optional, Set, Tuple, Any
19
20
 
@@ -45,16 +46,31 @@ def clean_label(text: str) -> str:
45
46
  return text.replace('"', "'").replace("\n", " ").strip()
46
47
 
47
48
 
49
+ def wrap_label(text: str, width: int = 35) -> str:
50
+ """Wraps long labels with <br/> for compact Mermaid node rendering."""
51
+ cleaned = clean_label(text)
52
+ if len(cleaned) <= width:
53
+ return cleaned
54
+ parts = textwrap.wrap(cleaned, width=width)
55
+ return "<br/>".join(parts)
56
+
57
+
48
58
  def build_mermaid_graph(
49
59
  mode: str = "semantic",
50
60
  ki_filter: Optional[str] = None,
51
- direction: str = "TD",
61
+ direction: Optional[str] = None,
52
62
  max_unmapped: int = 15,
63
+ max_files_per_ki: int = 10,
53
64
  ) -> str:
54
65
  """
55
66
  Generates Mermaid graph markdown based on doc_config.json and dependency analysis.
56
67
  """
57
- direction = direction.upper() if direction.upper() in ("TD", "LR", "TB", "RL", "BT") else "TD"
68
+ # Adaptive direction: LR (horizontal) for focused single-KI subgraphs, TD (top-down) for global overviews
69
+ if not direction:
70
+ direction = "LR" if ki_filter else "TD"
71
+ else:
72
+ direction = direction.upper() if direction.upper() in ("TD", "LR", "TB", "RL", "BT") else "TD"
73
+
58
74
  doc_config = ki_utils.get_doc_config()
59
75
  knowledge_items: Dict[str, Any] = doc_config.get("knowledge_items", {}) if doc_config else {}
60
76
 
@@ -113,7 +129,7 @@ def build_mermaid_graph(
113
129
  files_count = len(info.get("depends_on", []))
114
130
  ki_id = sanitize_id(ki_name, prefix="ki")
115
131
  display_title = info.get("summary") or os.path.splitext(ki_name)[0]
116
- lines.append(f' {ki_id}["{clean_label(display_title)}<br/>({files_count} files)"]')
132
+ lines.append(f' {ki_id}["{wrap_label(display_title, width=32)}<br/>({files_count} files)"]')
117
133
 
118
134
  for src, dst in sorted(edges):
119
135
  if src in visible_kis and dst in visible_kis:
@@ -127,12 +143,29 @@ def build_mermaid_graph(
127
143
  subgraph_id = sanitize_id(ki_name, prefix="sg")
128
144
  display_title = info.get("summary") or os.path.splitext(ki_name)[0]
129
145
 
130
- lines.append(f' subgraph {subgraph_id} ["{clean_label(display_title)}"]')
146
+ lines.append(f' subgraph {subgraph_id} ["{wrap_label(display_title, width=40)}"]')
131
147
  if depends_on:
132
- for file_path in sorted(depends_on):
133
- fid = sanitize_id(f"{ki_name}_{file_path}", prefix="f")
134
- basename = os.path.basename(file_path)
135
- lines.append(f' {fid}["{clean_label(basename)}"]')
148
+ # If global semantic mode (no filter), limit files per KI to prevent visual spaghetti
149
+ files_to_render = depends_on
150
+ overflow_count = 0
151
+ if not ki_filter and len(depends_on) > max_files_per_ki:
152
+ files_to_render = depends_on[:max_files_per_ki]
153
+ overflow_count = len(depends_on) - max_files_per_ki
154
+
155
+ for file_path in sorted(files_to_render):
156
+ is_dir = file_path.endswith(("/", "\\"))
157
+ clean_path = file_path.rstrip("/\\")
158
+ if not is_dir and analyzer and (analyzer.project_root / clean_path).is_dir():
159
+ is_dir = True
160
+
161
+ fid = sanitize_id(f"{ki_name}_{clean_path}", prefix="f")
162
+ basename = os.path.basename(clean_path) or clean_path
163
+ icon = "📁 " if is_dir else ""
164
+ lines.append(f' {fid}["{icon}{clean_label(basename)}"]')
165
+
166
+ if overflow_count > 0:
167
+ more_id = sanitize_id(f"more_{ki_name}", prefix="f")
168
+ lines.append(f' {more_id}["... and {overflow_count} more files"]')
136
169
  else:
137
170
  placeholder_id = sanitize_id(f"empty_{ki_name}", prefix="node")
138
171
  lines.append(f' {placeholder_id}["(no tracked files)"]')
@@ -188,8 +221,8 @@ def main():
188
221
  parser.add_argument(
189
222
  "--direction",
190
223
  choices=["TD", "LR", "TB", "RL", "BT"],
191
- default="TD",
192
- help="Mermaid flowchart direction (default: TD)",
224
+ default=None,
225
+ help="Mermaid flowchart direction (default: LR for focused --ki, TD for global)",
193
226
  )
194
227
  args = parser.parse_args()
195
228