@omfalos/mokosh 0.4.3 → 0.5.0

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.
package/README.md CHANGED
@@ -1,89 +1,61 @@
1
1
  # Mokosh 🌊
2
2
 
3
- > Available on npm as [`@omfalos/mokosh`](https://www.npmjs.com/package/@omfalos/mokosh).
4
-
5
- Mokosh is a lightweight, AST-powered dependency graph generator for modern web and script projects. It extracts import maps from JavaScript, TypeScript, Python, Go, CSS, SCSS, Less, Stylus, CoffeeScript, LiveScript, Lua, and Gherkin files to help AI models and developers understand code relationships efficiently.
6
-
7
- Designed for performance and RAG (Retrieval-Augmented Generation) workflows, Mokosh enables you to visualize your project structure, traverse dependencies, and even propose test tags based on code changes.
3
+ Mokosh is an AST-powered dependency-graph analysis tool for polyglot codebases. It parses source
4
+ files, builds a directed import graph, and exposes it through a CLI and an MCP server — so both
5
+ humans and AI assistants can query dependencies, blast radius, complexity, duplication, coverage,
6
+ and doc-drift from one graph instead of grepping around.
8
7
 
9
8
  ## Why Mokosh?
10
9
 
11
- - **Runs entirely on your machine.** No accounts, no servers, no data sent anywhere. Your source code stays local at all times.
10
+ - **Runs entirely on your machine.** No accounts, no servers, no data sent anywhere.
12
11
  - **Works offline.** The graph is built from your filesystem — no network required during analysis.
13
- - **Integrates in minutes via MCP.** Drop it into any AI assistant that supports the Model Context Protocol and start querying your codebase immediately.
14
- - **Spans 10+ languages in one graph.** TypeScript, Python, Go, CSS, SCSS, Lua, Gherkin, and more — all in a single traversable dependency graph.
15
- - **AI-ready output.** Slim query mode, token-efficient responses, and structured tags are designed to fit naturally into LLM context windows.
16
- - **No vendor lock-in.** Open tool, open format. Run it in CI, in a local script, or as an MCP server — your choice.
17
-
18
- ## Features
19
-
20
- - **Multi-Language Support**: Robust extraction from:
21
- - **JavaScript/TypeScript**: static `import`, dynamic `import()`, `require()`, and re-exports.
22
- - **Python**: all import forms (`import X`, `from X import Y`, relative `.`/`..` imports, star imports) via `@lezer/python` AST. Test files (`test_*.py`, `*_test.py`) and test frameworks (`pytest`, `unittest`) auto-detected.
23
- - **Go**: top-level declarations and `// @tag` markers via `@lezer/go` AST. Module-local imports are resolved to internal files via `go.mod` (including `replace` directives); everything else is treated as external. See [ADR-007](./docs/adr-007-go-resolution.md).
24
- - **CSS/SCSS/Less/Stylus**: tracks `@import` relationships.
25
- - **CoffeeScript/LiveScript/Lua/Gherkin**: AST-based parsing for dependencies and tags.
26
- - **Graph Traversal**: Programmatically explore dependencies from any entry point with depth control.
27
- - **Visual Diagrams**: Export your dependency graph to Mermaid.js format.
28
- - **Lock File Integration**: Automatically extract dependency versions and tags from `package-lock.json`, `yarn.lock`, and `pnpm-lock.yaml`.
29
- - **Unused File Detection**: Identify files in your project that are not imported by any entry point.
30
- - **Cycle Detection**: Check for circular dependencies and use as a CI gate (`--check-cycles` exits non-zero if cycles are found).
31
- - **Caching**: Serialize and deserialize the graph to save computation time.
32
- - **Filtering & Token Saving**: Use `--query` to filter nodes and dependencies, significantly reducing the size of the output for AI models.
33
- - **Test Tag Proposal**: Automatically identify affected Playwright/Cucumber test tags based on `git diff`.
34
- - **Feature Hub Detection**: Identify architectural hub files (files with high out-degree — orchestrators and aggregators that import many internal modules) and surface them as `feature:<name>` tags. Prevents tag explosion when a widely-used utility changes.
35
- - **Enriched Exports**: Named exports carry their JSDoc description, type signature, and lifecycle flags (`deprecated`, `internal`, `public`, `alpha`, `beta`) giving AI models precise symbol-level context.
36
- - **Call Edges**: Beyond imports, Mokosh traces cross-file function/method calls and stores them as `callEdges` on each node.
37
- - **Tested-By Index**: Every logic/barrel file records which test files import it (`testedBy`), enabling instant "what tests cover this module?" queries.
38
- - **Git Stats**: Optionally enrich each node with `commitCount90d` and `lastAuthor` (enabled via `gitStats: true` in config), enabling sorting by commit activity.
39
-
40
- ## Token Saving with Queries
41
-
42
- When working with large codebases, providing the entire dependency graph to an AI model can exceed context limits or waste tokens. Use the `--query` flag to filter the output to only what's relevant:
43
-
44
- - **Filter by language**: `--query "type:typescript"`
45
- - **Filter by category**: `--query "category:ui"`
46
- - **Filter by tag**: `--query "tag:core"`
47
- - **Filter by documentation**: `--query "hasDocstring:false"` — find files missing a JSDoc description
48
- - **Combine filters**: `--query "category:logic,tag:api"`
49
-
50
- Example of a focused query:
51
- ```bash
52
- npx @omfalos/mokosh --query "type:typescript,category:logic" src/index.ts
53
- ```
54
-
55
- ## Supported Languages & Tags
56
-
57
- Mokosh automatically detects file types and uses the appropriate parser. You can also group files using `@tag <name>` in comments:
58
-
59
- | Language | Extension | Tag Example |
12
+ - **Spans 15+ languages in one graph.** TypeScript, JavaScript, Python, Go, CSS/SCSS/Less/Stylus,
13
+ CoffeeScript, LiveScript, Lua, Gherkin, and Markdown/MDX — all in a single traversable graph.
14
+ - **AI-ready output.** Slim query mode, token-efficient responses, and structured tags are
15
+ designed to fit naturally into LLM context windows.
16
+ - **Integrates in minutes via MCP.** Drop it into any AI assistant that supports the Model
17
+ Context Protocol and start querying your codebase immediately.
18
+ - **No vendor lock-in.** Open tool, open format. Run it in CI, in a local script, or as an MCP
19
+ server your choice.
20
+
21
+ ## What it can tell you
22
+
23
+ - **Dependency graph traversal** — dependencies, dependents, and full blast-radius (`get_affected`)
24
+ from any file, with call-edge precision (not just imports) for TS/JS/Go/Python.
25
+ - **Cycle detection**, usable as a CI gate.
26
+ - **Unused-file detection** files unreachable from any entry point.
27
+ - **Duplicate-code detection** cross-language, suffix-array based, structural for CSS.
28
+ - **Complexity & risk hotspots** McCabe cyclomatic + cognitive complexity per function, and a
29
+ combined complexity × low-coverage × churn signal (`find_risk_hotspots`).
30
+ - **Doc-drift detection** flags markdown docs whose referenced files changed more recently than
31
+ the doc itself.
32
+ - **Test-tag proposal** infers affected test tags/files from `git diff`, and can write `@tag`
33
+ annotations back into test files (`apply_tags`).
34
+ - **Type graph, API surface, module responsibility, feature-hub detection**higher-level views
35
+ built on top of the same graph.
36
+ - **Monorepo support** auto-detects Turborepo/Nx/pnpm/Yarn/npm workspaces and gives you
37
+ per-package graphs plus cross-package blast radius.
38
+
39
+ Every capability above is available identically from the CLI and the MCP server — see
40
+ [docs/mcp.md](./docs/mcp.md) for the full MCP tool reference and [docs/usage.md](./docs/usage.md)
41
+ for the full CLI reference.
42
+
43
+ ## Supported languages
44
+
45
+ | Language | Extensions | `@tag` marker |
60
46
  | --- | --- | --- |
61
- | JavaScript | `.js`, `.jsx` | `// @tag core` |
62
- | TypeScript | `.ts`, `.tsx` | `// @tag models` |
47
+ | TypeScript / JavaScript | `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs` | `// @tag core` |
63
48
  | Python | `.py` | `# @tag auth` |
64
49
  | Go | `.go` | `// @tag service` |
65
- | CSS/SCSS/Less | `.css`, `.scss`, `.less` | N/A |
50
+ | CSS / SCSS / Sass / Less | `.css`, `.scss`, `.sass`, `.less` | N/A |
66
51
  | Stylus | `.styl` | N/A |
67
52
  | CoffeeScript | `.coffee` | `# @tag script` |
68
53
  | LiveScript | `.ls` | `# @tag app` |
69
54
  | Lua | `.lua` | `-- @tag config` |
70
- | Gherkin | `.feature` | `@smoke` |
71
-
72
- ## Installation
55
+ | Gherkin / Cucumber | `.feature` | `@smoke` |
56
+ | Markdown / MDX | `.md`, `.mdx` | N/A (used for doc-drift linking) |
73
57
 
74
- Install from npm:
75
-
76
- ```bash
77
- npm install @omfalos/mokosh
78
- ```
79
-
80
- Or run it without installing via `npx`:
81
-
82
- ```bash
83
- npx @omfalos/mokosh src/index.ts
84
- ```
85
-
86
- To work on Mokosh itself, clone and build locally:
58
+ ## Install & build
87
59
 
88
60
  ```bash
89
61
  git clone https://github.com/Omfalos/mokosh.git
@@ -92,151 +64,93 @@ npm install
92
64
  npm run build
93
65
  ```
94
66
 
95
- ## Quick Start
67
+ Mokosh is also published as [`@omfalos/mokosh`](https://www.npmjs.com/package/@omfalos/mokosh) —
68
+ `npm install @omfalos/mokosh`, or run it without installing via `npx @omfalos/mokosh <entry-point>`.
69
+
70
+ ## Quick start
96
71
 
97
- ### AI Assistant Setup
72
+ ### AI assistant setup (recommended first step)
98
73
 
99
- Scaffold a Claude Code skill and slash command that teach your AI assistant how to drive Mokosh — via MCP if it's configured, falling back to the CLI otherwise:
74
+ Scaffold a Claude Code skill and slash command that teach your AI assistant how to drive Mokosh —
75
+ via MCP if it's configured, falling back to the CLI otherwise:
100
76
 
101
77
  ```bash
102
- npx @omfalos/mokosh --init-skill
78
+ mokosh --init-skill
103
79
  ```
104
80
 
105
- This writes `.claude/skills/mokosh/SKILL.md` (auto-invoked) and `.claude/commands/mokosh.md` (explicit `/mokosh`) into your project. Existing files are left untouched — pass `--force` to overwrite.
81
+ This writes `.claude/skills/mokosh/SKILL.md` (auto-invoked) and `.claude/commands/mokosh.md`
82
+ (explicit `/mokosh`) into your project. Existing files are left untouched — pass `--force` to
83
+ overwrite.
106
84
 
107
- ### CLI Usage
85
+ ### MCP server
108
86
 
109
- Generate a dependency graph as JSON:
110
- ```bash
111
- npx @omfalos/mokosh src/index.ts
112
- ```
87
+ Point your MCP client at `dist/mcp.js` (see `.mcp.json` in this repo for a working example).
88
+ Call `analyze` once to build and cache the graph, then call any other tool — `get_dependencies`,
89
+ `get_affected`, `find_unused`, `find_duplicates`, `find_risk_hotspots`, `query`, and 15+ more.
90
+ Full tool-by-tool reference: [docs/mcp.md](./docs/mcp.md).
113
91
 
114
- Generate a Mermaid diagram:
115
- ```bash
116
- npx @omfalos/mokosh --mermaid src/index.ts > graph.mmd
117
- ```
92
+ ### CLI
118
93
 
119
- Propose test tags for changed files:
120
94
  ```bash
121
- npx @omfalos/mokosh --propose-tags src/index.ts
122
- ```
95
+ # Dependency graph as JSON
96
+ mokosh src/index.ts
123
97
 
124
- Detect feature hub files (high out-degree orchestrators):
125
- ```bash
126
- npx @omfalos/mokosh --detect-features src/index.ts
127
- ```
98
+ # Mermaid diagram
99
+ mokosh --mermaid src/index.ts > graph.mmd
128
100
 
129
- Find unused files:
130
- ```bash
131
- npx @omfalos/mokosh --find-unused src/index.ts
132
- ```
133
-
134
- Use caching to speed up subsequent runs:
135
- ```bash
136
- npx @omfalos/mokosh --cache mokosh-cache/graph.json src/index.ts
137
- ```
101
+ # Filter the graph to save tokens
102
+ mokosh --query "category:logic,hasDocstring:false" src/index.ts
138
103
 
139
- > **Note:** Add `mokosh-cache/` to your `.gitignore` to avoid committing the cache directory.
104
+ # Blast radius / affected tests / unused files / cycles
105
+ mokosh --affected --file src/auth/session.ts src/index.ts
106
+ mokosh --affected-tests src/index.ts
107
+ mokosh --find-unused src/index.ts
108
+ mokosh --check-cycles src/index.ts
140
109
 
141
- Filter graph by category and tag:
142
- ```bash
143
- npx @omfalos/mokosh --query "category:logic,tag:auth" src/index.ts
110
+ # Watch mode re-runs on file changes
111
+ mokosh --watch --query "category:logic" src/index.ts
144
112
  ```
145
113
 
146
- ### Options
147
-
148
- - `--cache [file]`: Path to cache file. If no file is provided, it defaults to `mokosh-cache/graph.json` in the project root.
149
- - `--config <file>`: Path to a `mokosh.config.js` / `mokosh.config.json` file (overrides auto-discovery).
150
- - `--root <dir>`: Set the project root directory (default: current directory).
151
- - `--mermaid`: Output a Mermaid chart (`graph TD`) instead of JSON.
152
- - `--propose-tags`: Use `git diff` to identify changed files and propose relevant test tags by traversing the dependency graph.
153
- - `--plain`: Output tags as plain text (one per line) instead of JSON. Use with `--propose-tags`.
154
- - `--affected-tests`: Like `--propose-tags` but outputs test file paths instead of tags — pipe directly into a test runner: `vitest $(mokosh --affected-tests)`.
155
- - `--detect-features`: Output files with high out-degree (feature hubs — orchestrators/aggregators that import many internal modules), sorted by out-degree descending.
156
- - `--feature-threshold <N>`: Minimum internal imports (out-degree) for a file to be a feature hub (default: `5`). Applies to `--detect-features`, `--propose-tags`, and `--affected-tests`.
157
- - `--find-unused`: Scan the project for files that are not reachable from the specified entry points.
158
- - `--exclude-tests`: Exclude test files from `--find-unused` output.
159
- - `--check-cycles`: Check for circular dependencies; exits non-zero if any are found (CI gate).
160
- - `--find-uncovered`: List non-test files whose line coverage is below the configured threshold (requires `coverageReportPath` in `mokosh.config.*`). Use `--feature-threshold` to override the default 80 % threshold.
161
- - `--callers`: List files whose exported functions call into a given file. Requires `--file <path>`. More precise than `--find-unused` because it uses call edges rather than import edges.
162
- - `--file <path>`: Target file for `--callers`.
163
- - `--find-symbol`: Find every file that exports a symbol by exact name. Requires `--function <name>`. Precision varies by language: call-edge callers for TS/JS/Go/Python (coverage differs per language, see [ADR-011](./docs/adr-011-go-python-call-edges.md)), whole-file dependents otherwise.
164
- - `--query <query>`: Filter the output graph using a query string. Supported keys: `path`, `type`, `category`, `tag`, `external`, `importsFile`, `importedBy`, `minImports`, `maxImports`, `minSize`, `maxSize`, `hasDocstring`, `sort`, `limit`. Example: `category:logic,hasDocstring:false`.
165
- - `--query-help`: Print the full query filter reference and examples.
166
- - `--silent`: Suppress progress output on stderr.
167
- - `--init-skill`: Scaffold the bundled Claude Code skill/command (`.claude/skills/mokosh/SKILL.md`, `.claude/commands/mokosh.md`) into the current project.
168
- - `--init-config`: Scaffold a commented starter `mokosh.config.js` into the project root.
169
- - `--force`: Overwrite existing files. Use with `--init-skill` / `--init-config`.
170
- - `--help`: Show usage information.
114
+ Run `mokosh --help` for the full flag reference, `mokosh --query-help` for the query DSL, or see
115
+ [docs/usage.md](./docs/usage.md) for a guided walkthrough of every command.
171
116
 
172
117
  ### Programmatic API
173
118
 
174
119
  ```typescript
175
- import { createImportMap } from 'mokosh';
176
-
177
- const rootDir = process.cwd();
178
- const entryPoints = ['src/main.ts'];
120
+ import { createImportMap } from "@omfalos/mokosh";
179
121
 
180
- const graph = createImportMap(rootDir, entryPoints);
122
+ const graph = createImportMap(process.cwd(), ["src/index.ts"]);
181
123
 
182
- // Traverse the graph
183
- graph.traverse('src/main.ts', (node, depth) => {
184
- console.log(`${' '.repeat(depth)} ${node.path}`);
124
+ graph.traverse("src/index.ts", (node, depth) => {
125
+ console.log(`${" ".repeat(depth)} ${node.path}`);
185
126
  });
186
127
 
187
- // Export to Mermaid
188
128
  console.log(graph.toMermaid());
189
129
  ```
190
130
 
191
131
  ## Configuration
192
132
 
193
- Mokosh auto-discovers `mokosh.config.json` / `.js` / `.cjs` in the project root — no flag needed, for both the CLI and the MCP server. Scaffold a commented starter file with:
133
+ Mokosh auto-discovers `mokosh.config.json` / `.js` / `.cjs` in the project root for both the CLI
134
+ and the MCP server — scaffold a commented starter with `mokosh --init-config`.
194
135
 
195
- ```bash
196
- npx @omfalos/mokosh --init-config
197
- ```
136
+ > The MCP server only loads `mokosh.config.json` (JS execution is disabled there for safety). If
137
+ > you want the MCP server to pick up your config, use a `.json` file rather than `.js`/`.cjs`.
198
138
 
199
- > **Note:** The MCP server only loads `mokosh.config.json` (JS execution is disabled there for safety). If you want the MCP server to pick up your config, use a `.json` file rather than `.js`/`.cjs`.
200
-
201
- **`mokosh.config.json`:**
202
- ```json
203
- {
204
- "cachePath": "custom-cache/graph.json",
205
- "entryPoints": ["src/index.ts"],
206
- "ignoreDirs": ["vendor", "generated"],
207
- "extensions": [".graphql"],
208
- "configMatchers": [".myconfig."],
209
- "testPatterns": [".unit.", ".integration."],
210
- "testLibraries": ["@my-org/test-utils"],
211
- "barrelThreshold": 0.7
212
- }
213
- ```
214
-
215
- `ignoreDirs` and `extensions` are **additive** — they extend the built-in defaults rather than replacing them.
216
-
217
- ### Config fields
139
+ Commonly-used fields see [docs/usage.md](./docs/usage.md#configuration-file) for the complete
140
+ list, factory-function configs, and programmatic config-loading:
218
141
 
219
142
  | Field | Type | Description |
220
143
  | --- | --- | --- |
221
- | `cachePath` | `string` | Override default `mokosh-cache/graph.json` |
222
- | `entryPoints` | `string[]` | Default entry points when none passed on CLI |
223
- | `ignoreDirs` | `string[]` | Extra dirs to skip (merged with built-in defaults) |
224
- | `extensions` | `string[]` | Extra file extensions to scan (merged with built-in defaults) |
225
- | `configMatchers` | `string[]` | Extra basename substrings that classify a file as `"config"` |
226
- | `testPatterns` | `string[]` | Extra basename substrings that classify a file as `"test"` |
227
- | `testLibraries` | `string[]` | Extra import names that classify a file as `"test"` |
228
- | `barrelThreshold` | `number` | Export-ratio threshold for `"barrel"` detection (default `0.8`) |
229
- | `gitStats` | `boolean` | When `true`, enriches each cache-missed node with `commitCount90d` and `lastAuthor` via two batched `git log` calls per build. Off by default. |
230
- | `coverageReportPath` | `string` | Path (relative to project root) to an Istanbul `coverage-summary.json`. When set, each node gets a `coveragePct` field. |
231
- | `coverageThreshold` | `number` | Line-coverage % below which `--find-uncovered` / `find_uncovered` flags a file. Default: `80`. |
232
- | `tagApplier` | `{ framework?, frameworkOverrides? }` | Configures `--apply-tags` output format. `framework` is the fallback test framework (`vitest` \| `playwright` \| `cypress` \| `jest`) used when a file's own imports don't reveal one; `frameworkOverrides` maps path-glob patterns to a framework, checked before the top-level fallback. See [ADR-008](./docs/adr-008-tag-applier-strategies.md). |
233
-
234
- See the [Usage Guide](./docs/usage.md#configuration-file) for `mokosh.config.js` (factory functions, side effects) and programmatic config-loading examples.
144
+ | `entryPoints` | `string[]` | Default entry points when none passed on the CLI |
145
+ | `ignoreDirs` / `extensions` | `string[]` | Extra dirs/extensions, merged with the built-in defaults |
146
+ | `pathAliases` | `Record<string, string[]>` | Explicit import-alias map (tsconfig `paths` shape); takes precedence over `tsconfig.json` |
147
+ | `gitStats` | `boolean` | Enables `commitCount90d` / `lastAuthor` enrichment (off by default) |
148
+ | `coverageReportPath` / `coverageThreshold` | `string` / `number` | Istanbul coverage summary + threshold for `find_uncovered` / `find_risk_hotspots` |
149
+ | `tagApplier` | `{ framework?, frameworkOverrides? }` | Test-tag output format for `apply_tags` see [ADR-008](./docs/adr-008-tag-applier-strategies.md) |
150
+ | `parallelParsing` | `boolean \| { minFiles?, maxThreads? }` | Worker-pool parsing threshold see [ADR-010](./docs/adr-010-parallel-parsing.md) |
235
151
 
236
152
  ## Documentation
237
153
 
238
- For detailed information on each process, check the following guides:
239
-
240
154
  ### Guides
241
155
  - [Architecture Overview](./docs/architecture.md)
242
156
  - [Usage Guide](./docs/usage.md)
@@ -260,3 +174,9 @@ For detailed information on each process, check the following guides:
260
174
  - [ADR-009: AST Library for Markdown Parsing](./docs/adr-009-markdown-parsing.md)
261
175
  - [ADR-010: Worker-Pool Parallel Parsing](./docs/adr-010-parallel-parsing.md)
262
176
  - [ADR-011: Extending Complexity and Call Edges to Go and Python](./docs/adr-011-go-python-call-edges.md)
177
+ - [ADR-012: Duplicate Detection](./docs/adr-012-duplicate-detection.md)
178
+ - [ADR-013: Duplicate Detection Noise Reduction](./docs/adr-013-duplicate-detection-noise-reduction.md)
179
+ - [ADR-014: Duplicate Detection at Scale](./docs/adr-014-duplicate-detection-scale.md)
180
+ - [ADR-015: Suffix-Array Duplicate Detection](./docs/adr-015-suffix-array-duplicate-detection.md)
181
+ - [ADR-016: Branch/PR Comparison](./docs/adr-016-branch-comparison.md)
182
+ - [ADR-017: JVM Language Support (Java, Kotlin, Scala, Groovy)](./docs/adr-017-jvm-languages.md)