lady-lens 1.6.8 → 1.6.11

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/DOCUMENTATIE.md CHANGED
@@ -1,430 +1,428 @@
1
- # lady-lens documentation
2
-
3
- Full guide to architecture, API ports, MCP integration, npm package use and configuration through `config.json`. (The file name stays `DOCUMENTATIE.md` so existing links keep working.)
4
-
5
- ---
6
-
7
- ## 0. Installation and setup
8
-
9
- Requires Node.js 18 or newer; the Mendix MDL export needs 22.13 or newer (see Step 6 below: another Node for lens). Do these steps once, in order.
10
-
11
- **Step 1: install**
12
-
13
- ```bash
14
- npm install -g lady-lens # from npmjs.org
15
- lens v # prints the version: `lens` is now on your PATH
16
- ```
17
-
18
- From source instead (development, or a version that is not published yet): `npm install` and `npm run pack` in this folder build `dist\lady-lens-<version>.tgz`; install it with `npm install -g .\dist\lady-lens-<version>.tgz` (later: `lens update .\dist\lady-lens-<version>.tgz`). With `npm link`, `lens` runs straight from this folder.
19
-
20
- **Step 2: register a project and index it**
21
-
22
- ```bash
23
- lens add C:\git\my-project # registers the project and runs the first sync
24
- lens list # check that it is listed
25
- lens sync # later: incremental sync (--full = everything)
26
- ```
27
-
28
- **Step 3: connect your AI assistant (stdio, no daemon needed)**
29
-
30
- ```bash
31
- lens install # every agent found; or one: lens install vscode
32
- lens install --skill # also the Lady-lens workflow skill
33
- lens install --mendix # the Mendix skill; or for some agents: lens install skill-mendix vscode claude-code
34
- lens install --dry-run # shows what would change, writes nothing
35
- ```
36
-
37
- `lens install` adds a stdio entry to each agent's MCP configuration (VS Code: `%APPDATA%\Code\User\mcp.json`), keeps the other servers and saves the old file as `<file>.lady-lens.bak`. Restart the agent afterwards (VS Code: *MCP: List Servers* or reload the window).
38
-
39
- **Step 4 (alternative): one background daemon for all projects**
40
-
41
- ```bash
42
- lens mcp -d # MCP on http://127.0.0.1:4318/mcp, UI on http://127.0.0.1:4317
43
- lens status # is it running?
44
- lens ps # tracked PIDs per folder
45
- lens stop # stop it
46
- ```
47
-
48
- Example for VS Code (`mcp.json`):
49
-
50
- ```json
51
- { "servers": { "lady-lens": { "type": "http", "url": "http://127.0.0.1:4318/mcp?repo=C:/git/my-project" } } }
52
- ```
53
-
54
- See [section 5](#5-using-it-as-an-mcp-server) for several projects per daemon and other agents.
55
-
56
- **Step 5: update**
57
-
58
- ```bash
59
- lens update # the newest version from npm
60
- lens update 1.2.8 # a given version
61
- lens update C:\path\lady-lens-1.2.8.tgz # a package file: a machine without npm access, or a build from source
62
- ```
63
-
64
- In order, `lens update`:
65
-
66
- 1. stops every lens process: the daemon and the stdio servers your agents started. On Windows a running lens keeps the graph database module (`lbugjs.node`) open, and npm cannot replace it (`EBUSY`);
67
- 2. runs `npm install -g` with the package. When that still fails (an agent started lens again), it stops lens once more and retries once;
68
- 3. lets the new lens refresh what you installed (`lens install --refresh`): the MCP entry in every agent where lady-lens is registered (a `--repo` is kept), the installed `SKILL.md` files (main and Mendix skill), and `~/.lady-lens/lens-instructions.md` with the instruction files that point to it. Your own `CLAUDE.md`, `AGENTS.md` or `copilot-instructions.md` only holds a link line and does not change. Nothing you did not install is added;
69
- 4. starts the daemon again if it ran.
70
-
71
- Reconnect the MCP server in your agents afterwards (Claude Code: `/mcp`; VS Code: restart the server), so they start the new version.
72
-
73
- **Step 6: another Node for lens**
74
-
75
- The Mendix MDL export reads mxcli's catalog with `node:sqlite`, which needs Node 22.13 or newer. When your projects need an older Node on PATH (nvm), let only lens run on a newer one; PATH and nvm stay as they are:
76
-
77
- ```bash
78
- lens node "C:\Program Files\nodejs\node.exe" # lens, its daemon and the agent registrations now run on that Node
79
- lens node # which Node lens runs on
80
- lens node --clear # back to the Node on PATH
81
- ```
82
-
83
- The choice is kept in `~/.lady-lens/lens.json`. It holds at once, in every terminal and for agents started from the desktop; `setx LENS_NODE ...` only reaches terminals started later (in cmder not even those), so use `lens node`. `LENS_NODE` still overrides the file. `lens node` stops lens, re-registers the agents with the new Node and starts the daemon again if it ran. The package stays where npm installed it: Ladybug's native module works on every Node version. `lens sync --debug` writes the Node it ran on in the second line of its log.
84
-
85
- ---
86
-
87
- ## 1. Architecture overview and philosophy
88
-
89
- `lady-lens` is a fast, local code graph and semantic analysis engine built on [LadybugDB](https://www.npmjs.com/package/@ladybugdb/core). It indexes source code, documentation, decisions and dependencies into a directed graph. AI coding agents and developers can ask for exact facts about the codebase (definitions, import chains, callers, test reach, code health and architecture metrics) without spending expensive LLM tokens on context.
90
-
91
- The code base follows a strict **hexagonal architecture (ports and adapters)**:
92
- - **Core domain / model**: graphs, nodes (files, functions, documents, decisions) and edges (`IMPORTS`, `CALLS`, `TESTS`, `READS`, `CO_CHANGES`).
93
- - **Storage port (`GraphStorePort`)**: interchangeable storage adapters (in memory for fast tests, LadybugDB for persistent indexing).
94
- - **Sync and extraction port**: incremental parsing and AST extraction for JavaScript/TypeScript, C# and other registered languages; Mendix `.mpr` models are handled through `mxcli` as an external graph contributor.
95
- - **Git port (`core/git`)**: the only place that starts git; see [Branches and commits](#branches-and-commits).
96
- - **Query and view ports**: `functionView`, `folderView`, `codeHealth`, `rankGraphNodes`, `impact`.
97
- - **Primary adapters**: reachable through the **npm package**, the **MCP server (Model Context Protocol)** and the **CLI (`lens`)**.
98
-
99
- ---
100
-
101
- ## 2. API ports: access through MCP and the npm package
102
-
103
- Every feature of `lady-lens` is a **first-class API port**, available programmatically through the npm package (`lady-lens`) and interactively through the Model Context Protocol (MCP).
104
-
105
- The library sync API is `createGraphSync().sync({ mode: 'incremental' })`; use `mode: 'full'` for a complete re-index.
106
-
107
- ### Overview of all ports
108
-
109
- | Port / domain | MCP tool | npm export (`lady-lens`) | Description |
110
- | :--- | :--- | :--- | :--- |
111
- | **Function analysis** | `functionView` | `functionView(graph, symbol, { readFile, maxSites })` / `functionViewTool(args)` | Definition, line numbers, docstring/purpose, all calling files (`callers`), linked tests and referenced backlog stories of a function; `resolved` and `unresolved` call counts (a `note` "niet bewezen leeg" when none is bound but the name appears); for a class `children` (methods) and `inheritors` (subclasses). |
112
- | **Folder and module analysis** | `folderView` | `folderView(graph, folder)` / `folderViewTool(args)` | Structure of a folder: parts, internal data flow, who calls the folder from outside and possible deviations (cycles, untested files). |
113
- | **Code health and metrics** | `health` | `codeHealth(graph, opts)` / `healthTool(args)` | NDepend-style statistics: test reach (including index.js barrels), cyclic dependencies, boundary violations, hotspots (churn x lines), coupling (Ca, Ce, instability), zone of pain, and AST design smells with actionable pattern advice (`dispatch-chain`, `fallback-heavy`, `deep-nesting`, `loop-branching`, `long-condition`, `flag-parameter`, `repeated-literal`, `global-mutable-state`, `direct-io`, `god-module`). A measured line coverage (`coverage-summary.json`, written by `vitest --coverage` with the `json-summary` reporter) beats the import guess: a file covered through another one is tested, and its exports are not guessed by name. Barrels (`index.js`) are never flagged for untested exports, fan-in/out, zone of pain or god-module; tool config files (`*.config.*`) are scripts. On request `hubs` (most neighbours) and `bridges` (betweenness), each with `total` and `truncated` (`hubsAndBridges(graph, opts)`). |
114
- | **Symbol location** | `definedIn` | `definedIn(graph, symbol)` / `definedInTool(args)` | Where an identifier is defined or exported: file path and exact start/end lines. |
115
- | **Imports** | `imports` | `importsOf(graph, file)` / `imports(args)` | Which files and modules a given file imports directly. |
116
- | **Dependents** | `importedBy` | `importersOf(graph, file)` / `importedBy(args)` | Which files import the given file (fan-in analysis). |
117
- | **Exports** | `exports` | `exportsOf(graph, file)` / `exportsTool(args)` | Complete sorted list of exported functions, variables and types of a file. |
118
- | **File check** | `exists` | `fileLookup(graph, file)` / `fileExists(args)` | Checks whether a file is in the project graph; suggests matches for typos or moved folders. |
119
- | **Graph search** | `graph_query` | `graph_query(args)` / `rankGraphNodes(graph, query)` | Semantic and keyword search through the graph by relevance score, IDF weighting and relations. |
120
- | **Interactive search** | `searchView` | `searchView(args)` | Advanced search with regex, case sensitivity, file type filter (code, doc, test) and path globs. |
121
- | **Text and regex** | `grep` | `grep(args)` | Fast regex search through code, honouring `.gitignore` and project exclusions. |
122
- | **Config search** | `config_grep` | `grep(args)` + config filter | Searches only project and configuration files, such as `.csproj` and reference-manager XML. |
123
- | **Config references** | `config_references` | `grep(args)` + config filter | Finds which config files mention a package, project or Siemens functional block. |
124
- | **Config update** | `config_update` | `fs` + `createGraphSync().touch()` | Replaces one config file, optionally checks a SHA-256 and refreshes the graph facts. |
125
- | **Path matching** | `glob` | `glob(args)` | Finds repository paths by glob pattern (e.g. `core/**/*.js`). |
126
- | **AST chunk reader** | `read_chunk` | `read_chunk(args)` | Reads one AST chunk (class/function) or a range of lines. Large files return a compact summary. |
127
- | **Decisions and discussions** | `discussion_save`, `discussion_query`, etc. | `saveDiscussion`, `loadDiscussions`, `queryDiscussions` | Manages architecture decisions and discussions, with frontmatter links to code nodes. |
128
- | **Multi-repo management** | `repo_list`, `repo_add`, `repo_remove` | `registerRepo`, `unregisterRepo`, `listRegisteredRepos` | Manages several projects in the central Ladybug database registry. |
129
- | **Graph sync** | `repo_sync` | `createGraphSync(options).sync()` | Scans the project incrementally (by size and mtime) or fully (`mode: 'full'`). Records the branch and commit and reports `commitsSince`. With `branch: '<name>'` another branch is indexed into the scope `branch:<name>` without checking it out. |
130
- | **Branch difference** | `branch_diff` | `branchDiff({ from, to, root })` | What `to` changes since its merge-base with `from`: files (added, removed, modified, renamed) and functions (added, removed, modified, renamed) and changed import and call relations. |
131
- | **Mendix model difference** | `mendix_diff` | `mendixDiff({ from, to, root })` | The Mendix model changes `to` brings since its merge-base with `from`, read from git without a checkout or mxcli, for a single-file `.mpr` (MPR v1, documents compared by `ContentsHash`) and for `mprcontents/` (MPR v2, the `.mxunit` files git reports). Returns `commits` (sha, date, author, subject), `files`, and `documents`: per document `module`, `folders`, `name`, `qualifiedName`, `type` and `change`; for a modified one `elements` (added, deleted, modified; `type`, `name`, `detail` such as `NanoflowCallAction: Module.Flow`, and `properties` as `{ path, before, after }` with paths like `Action > ParameterMappings`; a pointer shows as `{ element }`); for a microflow or nanoflow `flow.before` / `flow.after` with `nodes` (`summary`, `status`) and `edges` (`from`, `to`, `cases`, `status`). Needs Node 22.13+ (`lens node`). |
132
- | **Diff impact** | `diff_impact` | `diffImpact(args)` / `changedFunctions({ from, to, git, readFile })` | The functions a diff changes (the work not committed yet, or `from`..`to`) with callers, tests, bound/unbound call counts, complexity and test gaps; riskiest first, with `total` and `truncated`. |
133
- | **Search over projects** | `cross_repo_search` | `crossRepoSearch(args)` | `searchView` over every registered project or `repos: [...]`, project after project; unregistered names in `unknown`. |
134
- | **Tool metadata** | (all tools) | `RESEARCH_TOOL_SCHEMAS`, `buildMcpToolSchemas()` | Every schema has `readOnly` (MCP `annotations.readOnlyHint`); the discussion tools carry `usedBy: ['/discuss', '/research']` so a host such as Kura gives them only to those consumers. |
135
- | **Branch impact** | `branch_impact` | `branchImpact({ change, against, root })` | What a change on one branch (e.g. a bugfix on `release`) means for another: functions still used there (file and line), overlap, shared files and text merge conflicts. |
136
- | **Commit inspection** | `commit_show` | `commitShow({ commit, root })` | What one commit changed (files and functions against its first parent); for a merge commit, what the merge brought in. |
137
- | **Function history** | `function_history` | `functionHistory({ name, file, ref, max, root })` | Commits that added, modified or removed one function; without `name` every commit that touched the file. Name based: a renamed function starts a new history. |
138
-
139
- ### Branches and commits
140
-
141
- The graph knows which branch and commit it was built on:
142
-
143
- - After every sync a `Branch` node points to its `Commit` (`HEAD_AT`). `repo_sync` reports how many commits came in since the previous sync on that branch. A commit that changed no file is recorded too.
144
- - A saved discussion gets `CREATED_AT` (commit) and `ON_BRANCH` (branch). If you switch to a branch where the source file does not exist, the discussion stays; `discussion_query` shows the source as "not on this branch" and on which branch the file does exist. Switching back and syncing restores the link by itself.
145
- - `repo_sync({ branch: 'feature-x' })` reads that branch with `git ls-tree` and `git cat-file --batch` into its own scope `branch:feature-x`. The working copy, `HEAD` and the project scope stay unchanged. A second call only reads what changed since the stored commit. This scope has no Mendix contributions and no co-change signal.
146
- - `branch_diff`, `branch_impact`, `commit_show` and `function_history` read git directly and check nothing out. Functions are compared by name and content (hash of the body); a function whose name changed but whose body is alike (same file, or a renamed file) shows as `renamed` with `oldName`, and `branch_diff` also lists added and removed import and call relations (`relations`). `branch_impact` finds callers with `git grep` (at most 20 references per function; for a renamed function it searches the old name) and uses `git merge-tree --write-tree` (git 2.38 or newer) for conflicts.
147
- - All git calls go through `core/git` (`createGit({ root, run })`); a test checks that git is started nowhere else. `createFakeGit(state)` is an in-memory git for tests; `test/gitPort.contract.test.js` runs the same scenario on both and compares the answers.
148
-
149
- ---
150
-
151
- ## 3. Configuration through `config.json`
152
-
153
- All `lady-lens` settings can be set in one central **`config.json`** file in the root of the project.
154
-
155
- ### Automatic detection
156
- `lady-lens` looks for configuration files in this order:
157
- 1. A file given with `--config <path>` or the environment variable `LENS_SETTINGS_PATH`.
158
- 2. `config.json` (recommended default)
159
- 3. `lens.config.json`
160
- 4. `.lady-lens.json`
161
- 5. `.lady-lens.yaml`
162
-
163
- ### Complete example of `config.json`
164
-
165
- ```json
166
- {
167
- "project": {
168
- "graph_roots": ["."],
169
- "exclude_dirs": [
170
- ".git",
171
- ".memory",
172
- "node_modules",
173
- "outputs",
174
- "coverage",
175
- "dist",
176
- "build",
177
- "target",
178
- ".vs",
179
- ".idea"
180
- ],
181
- "graph_extensions": [
182
- ".js",
183
- ".mjs",
184
- ".ts",
185
- ".jsx",
186
- ".tsx",
187
- ".cs",
188
- ".csproj",
189
- ".sln",
190
- ".sql",
191
- ".ps1",
192
- ".md",
193
- ".yaml",
194
- ".yml",
195
- ".json"
196
- ]
197
- },
198
- "graph": {
199
- "ast": {
200
- "enabled": false
201
- },
202
- "documentation": {
203
- "enabled": true
204
- },
205
- "links": {
206
- "enabled": true
207
- },
208
- "freshness": {
209
- "default_max_age_days": 30
210
- }
211
- },
212
- "mcp": {
213
- "port": 4318,
214
- "uiPort": 4317
215
- },
216
- "database": ".memory/graph/project.lbdb",
217
- "env": {
218
- "TOOL_RESULT_CHARS": "6000",
219
- "READ_CHUNK_MAX_CHARS": "12000",
220
- "READ_CHUNK_MAX_LINES": "400",
221
- "GREP_MAX_MATCHES": "50",
222
- "DEBUG_LEVEL": "2",
223
- "DEBUG_LOG_FILE": ""
224
- }
225
- }
226
- ```
227
-
228
- ### Configuration sections
229
-
230
- 1. **`project`**:
231
- - `graph_roots`: folders to index (default `["."]`).
232
- - `exclude_dirs`: folders ignored during sync, glob and grep.
233
- - `graph_extensions`: file extensions included in the code graph.
234
- 2. **`graph`**:
235
- - `ast.enabled`: also store the full JavaScript syntax tree of every file (default `false`). Symbols, calls and functions are extracted either way; the stored tree is about 9× the size of the source and can fill the graph database's buffer on large vendored bundles.
236
- - `documentation.enabled`: index markdown documents and link frontmatter.
237
- - `links.enabled`: link import and call relations automatically.
238
- - `freshness.default_max_age_days`: maximum age before automatic re-indexing.
239
- 3. **`mcp`**:
240
- - `port`: HTTP/SSE port of the MCP server (default `4318`).
241
- - `uiPort`: web UI dashboard port (default `4317`).
242
- 4. **`database`**:
243
- - Path to the LadybugDB database file. If not set, lens uses `~/.lady-lens/repos/<id>/graph.lbdb`.
244
- 5. **`env`**:
245
- - Sets lens environment variables directly (such as `TOOL_RESULT_CHARS`, `DEBUG_LEVEL`).
246
-
247
- ---
248
-
249
- ## 4. Using it as an npm package
250
-
251
- Install the package as a dependency from npm (or a `.tgz` built with `npm run pack`, see [section 0](#0-installation-and-setup)):
252
-
253
- ```bash
254
- npm install lady-lens
255
- npm install ..\lady-lens\dist\lady-lens-<version>.tgz # a build from source
256
- ```
257
-
258
- ### Direct imports (main entry)
259
-
260
- Every port is available from the root export:
261
-
262
- ```javascript
263
- import {
264
- createGraphSync,
265
- functionViewTool,
266
- folderViewTool,
267
- healthTool,
268
- definedInTool,
269
- graph_query,
270
- grep,
271
- glob,
272
- read_chunk,
273
- RESEARCH_TOOLS,
274
- loadProjectSettingsSync
275
- } from 'lady-lens';
276
-
277
- // 1. Read the settings (reads config.json automatically)
278
- const settings = loadProjectSettingsSync();
279
-
280
- // 2. Incremental sync of the repository
281
- const syncResult = await createGraphSync().sync({ mode: 'incremental' });
282
- console.log(`Graph synced: ${syncResult.nodes} nodes`);
283
-
284
- // 3. Ask for a function view
285
- const fnDetails = await functionViewTool({ symbol: 'createGraphSync' });
286
- console.log('Callers of createGraphSync:', fnDetails.callers);
287
-
288
- // 4. Inspect code health
289
- const health = await healthTool({ limit: 5 });
290
- console.log('Top hotspots:', health.hotspots);
291
-
292
- // 5. Semantic graph query
293
- const queryResult = await graph_query({ query: 'database storage' });
294
- console.log('Nodes found:', queryResult.nodes);
295
- ```
296
-
297
- ### Modular subpath imports
298
-
299
- Specialised scenarios can use subpath imports:
300
-
301
- ```javascript
302
- import { createGraph, createGraphRepository } from 'lady-lens/graph';
303
- import { RESEARCH_TOOLS, grep, glob } from 'lady-lens/search';
304
- import { createLadyLensMcpServer, createMcpHttpServer } from 'lady-lens/mcp';
305
- import { listRegisteredRepos, registerRepo } from 'lady-lens/repository';
306
- import { createProfiler, globalProfiler } from 'lady-lens/observability';
307
- ```
308
-
309
- ---
310
-
311
- ## 5. Using it as an MCP server
312
-
313
- Start the background service with the CLI:
314
-
315
- ```bash
316
- lens mcp -d
317
- ```
318
-
319
- This starts:
320
- - The **Streamable HTTP MCP server** on `http://127.0.0.1:4318/mcp`
321
- - The legacy **SSE MCP server** on `http://127.0.0.1:4318/sse`
322
- - The **UI dashboard** on `http://127.0.0.1:4317`
323
-
324
- ### AI assistant configuration
325
-
326
- Add the server to your MCP configuration file (for example in Antigravity, Claude Desktop, Cursor or VS Code):
327
-
328
- #### Streamable HTTP mode (recommended)
329
- ```json
330
- {
331
- "mcpServers": {
332
- "lady-lens": {
333
- "url": "http://127.0.0.1:4318/mcp"
334
- }
335
- }
336
- }
337
- ```
338
-
339
- Use `/sse` only for older clients that do not support Streamable HTTP.
340
-
341
- ### Configuration files through MCP
342
-
343
- No extra setting in `config.json` is needed. The agent uses these tools:
344
-
345
- ```json
346
- {
347
- "name": "config_references",
348
- "arguments": { "reference": "INVENTORY_OP" }
349
- }
350
- ```
351
-
352
- This returns, among other things, `referenceManager.xml`, the line number and the matching text. Use `config_references` for this, not `imports` or `importedBy`.
353
-
354
- Read the file before changing it. Then pass the complete new content to `config_update`. Use the SHA-256 of the content you read as `expectedHash`; a stale update is refused.
355
-
356
- ```json
357
- {
358
- "name": "config_update",
359
- "arguments": {
360
- "path": "App/App.csproj",
361
- "content": "<Project>...</Project>",
362
- "expectedHash": "<sha256>"
363
- }
364
- }
365
- ```
366
-
367
- Supported: `.csproj`, `.sln`, `.props`, `.targets`, `.xml`, `.ini`, `.yaml`, `.yml`, `.toml` and `package.json`. After an update an incremental graph sync runs.
368
-
369
- ### Agent instruction
370
-
371
- Use this text in the agent chat:
372
-
373
- > Use Lady Lens MCP. First pick the right repo with `repo` or register it with `lens add`. Use `config_references` for questions like: who references `INVENTORY_OP`? Do not use `imports` or `importedBy`. Then read the config files found. Use `config_update` with the complete new content and `expectedHash`. Do not write directly outside `config_update`.
374
-
375
- #### One daemon, several projects
376
- One daemon serves every registered project (`lens add <folder>`). Pick the project per client in the URL:
377
-
378
- ```json
379
- { "mcpServers": { "lady-lens": { "url": "http://127.0.0.1:4318/mcp?repo=C:/git/my-project" } } }
380
- ```
381
-
382
- - `repo` is a registered folder or id; the `X-Lens-Repo` header works too.
383
- - An unregistered repo is refused (HTTP 403): run `lens add <folder>` first.
384
- - Without `repo` the folder where `lens mcp -d` was started applies; a tool call can override that with its `repo` argument.
385
- - Tool calls run one after another, so simultaneous requests for different projects do not affect each other.
386
- - The UI dashboard that starts with `lens mcp -d` works the same way: `http://127.0.0.1:4317/?repo=<folder or id>` shows that project (not registered: HTTP 403); with more than one registered project a dropdown appears.
387
-
388
- #### Direct stdio mode
389
- ```json
390
- {
391
- "mcpServers": {
392
- "lady-lens": {
393
- "command": "node",
394
- "args": ["C:/git/lady-lens/bin/lens.mjs", "mcp", "--stdio"]
395
- }
396
- }
397
- }
398
- ```
399
-
400
- ---
401
-
402
- ## 6. CLI command reference
403
-
404
- The command line interface `lens` gives direct access to every feature:
405
-
406
- | Command | Description |
407
- | :--- | :--- |
408
- | `lens sync [--repo <dir>] [--full] [--debug]` | Sync the graph for the current project or a target folder. `--debug` writes every step (scan, parse, mxcli calls, graph write) with its time, size, memory and any error stack to `~/.lady-lens/logs/sync-<time>.log`. |
409
- | `lens ask <tool> '<json>'` | Call one of the research tools directly (e.g. `lens ask functionView '{"symbol":"createProfiler"}'`). |
410
- | `lens mcp [-d]` | Start the MCP server (optionally in the background with `-d`). |
411
- | `lens stop [pid]` | End the background daemon and release ports and locks, or only the given PID. |
412
- | `lens ps` | Show the tracked daemon PIDs per folder. |
413
- | `lens status` | Show whether the background daemon is running. |
414
- | `lens ui [--port 4317]` | Start the interactive graph visualisation in the browser. The **Stacktrace** tab ties a pasted Node, .NET, Python or Java trace to project files and functions (`POST /api/trace`, `traceView` in `core/search/stackTrace.js`). The four tabs share one place in the URL (Back/Forward, crumbs, copyable link). Under the code: health issues, the function at the line with callers, calls, call tree, tests and documents, the file's imports, and its history (`GET /api/at`, `/api/flow`, `/api/history`; `callFlow`, `toMermaid`, `codeHistory` in `core/search`). Graph Network: the flow diagram of the function with Mermaid export. |
415
- | `lens list` | Overview of all registered repositories and their database paths. |
416
- | `lens add <dir>` | Register a new project and run the first sync right away. |
417
- | `lens remove <id\|dir>` | Remove a repository from the registry. |
418
- | `lens tools` | Show all available tools with their schemas and parameters. |
419
- | `lens bench [--repo <dir>] [--runs N] [--baseline] [--no-processes] [--json]` | Time the sync (with its phases) and every question on a repository, in a temporary database: the registry and the repository's own database stay as they are. Saves the run in `~/.lady-lens/bench/<repo id>/` (numbers and environment, no paths or code) and compares it with the baseline there; `lens bench compare` compares the newest run again. See README, Performance. |
420
- | `lens install [agent...]` | Install the MCP stdio configuration in detected agents. |
421
- | `lens install --skill` | Install the Lady-lens workflow skill, write `~/.lady-lens/lens-instructions.md`, and add one marked line pointing to it in `~/.claude/CLAUDE.md`, `~/.copilot/copilot-instructions.md`, `~/.codex/AGENTS.md` and `~/.vibe/AGENTS.md`; own rules files for VS Code and Antigravity. |
422
- | `lens uninstall [agent...]` | Remove the MCP entry from the agents. |
423
- | `lens uninstall --skill` | Remove the skill, the marked line and the two rules files. |
424
- | `lens install --mendix` | Install the `lady-lens-mendix` skill in the detected Claude, Copilot and Agents skill directories: search Mendix pages, widgets and flows in `.mxcli/mdl` (written from mxcli's catalog by a background export that `lens sync` starts after a model change; it never holds up the sync or MCP calls: `LENS_MDL_EXPORT=background|inline|off`, state in `.mxcli/lens-mdl.json`), change them with `mxcli`. Every other mxcli call stops after `LENS_MXCLI_TIMEOUT_MS` (default 120000); when mxcli gives nothing, the previous Mendix model is kept. `lens uninstall --mendix` removes it. |
425
- | `lens update [<version or file.tgz>]` | Update lady-lens: stop every lens process (on Windows they keep the graph database module open and npm cannot replace it), `npm install -g` the newest version (or the given version or local tgz), then let the new lens re-register itself where it was registered and copy again the skills and policies that are installed (`lens install --refresh`), and start the daemon again if it ran. Reconnect your agents afterwards. `lens install skill`, `lens install skill-mendix` and agent names (`vscode`, `claude-code`) work as well as `--skill` / `--mendix`. |
426
- | `lens node [<path to node.exe> or --clear]` | Run lens on another Node than the one on PATH, e.g. Node 22.13+ for the Mendix MDL export while nvm keeps Node 18 for your projects. The choice is kept in `~/.lady-lens/lens.json`, so it holds at once, in every terminal and for agents started from the desktop (unlike `setx`, which only reaches terminals started later). It stops lens, re-registers the agents with that Node (`lens install --refresh`) and starts the daemon again if it ran. `lens node` shows the choice, `--clear` undoes it. `LENS_NODE` overrides the file. |
427
- odejs
428
- ode.exe"`, open a new terminal, then `lens stop` and `lens install --refresh`. |
429
- | `lens v` / `lens version` | Show the installed package version. |
430
- | `.\scripts\update-lens.ps1 [-Pack] [-Source <source>]` | Older script for a build from source; `lens update <file.tgz>` does the same and also refreshes the agents and skills. |
1
+ # lady-lens documentation
2
+
3
+ Full guide to architecture, API ports, MCP integration, npm package use and configuration through `config.json`. (The file name stays `DOCUMENTATIE.md` so existing links keep working.)
4
+
5
+ ---
6
+
7
+ ## 0. Installation and setup
8
+
9
+ Requires Node.js 18 or newer; the Mendix MDL export needs 22.13 or newer (see Step 6 below: another Node for lens). Do these steps once, in order.
10
+
11
+ **Step 1: install**
12
+
13
+ ```bash
14
+ npm install -g lady-lens # from npmjs.org
15
+ lens v # prints the version: `lens` is now on your PATH
16
+ ```
17
+
18
+ From source instead (development, or a version that is not published yet): `npm install` and `npm run pack` in this folder build `dist\lady-lens-<version>.tgz`; install it with `npm install -g .\dist\lady-lens-<version>.tgz` (later: `lens update .\dist\lady-lens-<version>.tgz`). With `npm link`, `lens` runs straight from this folder.
19
+
20
+ **Step 2: register a project and index it**
21
+
22
+ ```bash
23
+ lens add C:\git\my-project # registers the project and runs the first sync
24
+ lens list # check that it is listed
25
+ lens sync # later: incremental sync (--full = everything)
26
+ ```
27
+
28
+ **Step 3: connect your AI assistant (stdio, no daemon needed)**
29
+
30
+ ```bash
31
+ lens install # every agent found; or one: lens install vscode
32
+ lens install --skill # also the Lady-lens workflow skill
33
+ lens install --mendix # the Mendix skill; or for some agents: lens install skill-mendix vscode claude-code
34
+ lens install --dry-run # shows what would change, writes nothing
35
+ ```
36
+
37
+ `lens install` adds a stdio entry to each agent's MCP configuration (VS Code: `%APPDATA%\Code\User\mcp.json`), keeps the other servers and saves the old file as `<file>.lady-lens.bak`. Restart the agent afterwards (VS Code: *MCP: List Servers* or reload the window).
38
+
39
+ **Step 4 (alternative): one background daemon for all projects**
40
+
41
+ ```bash
42
+ lens mcp -d # MCP on http://127.0.0.1:4318/mcp, UI on http://127.0.0.1:4317
43
+ lens status # is it running?
44
+ lens ps # tracked PIDs per folder
45
+ lens stop # stop it
46
+ ```
47
+
48
+ Example for VS Code (`mcp.json`):
49
+
50
+ ```json
51
+ { "servers": { "lady-lens": { "type": "http", "url": "http://127.0.0.1:4318/mcp?repo=C:/git/my-project" } } }
52
+ ```
53
+
54
+ See [section 5](#5-using-it-as-an-mcp-server) for several projects per daemon and other agents.
55
+
56
+ **Step 5: update**
57
+
58
+ ```bash
59
+ lens update # the newest version from npm
60
+ lens update 1.2.8 # a given version
61
+ lens update C:\path\lady-lens-1.2.8.tgz # a package file: a machine without npm access, or a build from source
62
+ ```
63
+
64
+ In order, `lens update`:
65
+
66
+ 1. stops every lens process: the daemon and the stdio servers your agents started. On Windows a running lens keeps the graph database module (`lbugjs.node`) open, and npm cannot replace it (`EBUSY`);
67
+ 2. runs `npm install -g` with the package. When that still fails (an agent started lens again), it stops lens once more and retries once;
68
+ 3. lets the new lens refresh what you installed (`lens install --refresh`): the MCP entry in every agent where lady-lens is registered (a `--repo` is kept), the installed `SKILL.md` files (main and Mendix skill), and `~/.lady-lens/lens-instructions.md` with the instruction files that point to it. Your own `CLAUDE.md`, `AGENTS.md` or `copilot-instructions.md` only holds a link line and does not change. Nothing you did not install is added;
69
+ 4. starts the daemon again if it ran.
70
+
71
+ Reconnect the MCP server in your agents afterwards (Claude Code: `/mcp`; VS Code: restart the server), so they start the new version.
72
+
73
+ **Step 6: another Node for lens**
74
+
75
+ The Mendix MDL export reads mxcli's catalog with `node:sqlite`, which needs Node 22.13 or newer. When your projects need an older Node on PATH (nvm), let only lens run on a newer one; PATH and nvm stay as they are:
76
+
77
+ ```bash
78
+ lens node "C:\Program Files\nodejs\node.exe" # lens, its daemon and the agent registrations now run on that Node
79
+ lens node # which Node lens runs on
80
+ lens node --clear # back to the Node on PATH
81
+ ```
82
+
83
+ The choice is kept in `~/.lady-lens/lens.json`. It holds at once, in every terminal and for agents started from the desktop; `setx LENS_NODE ...` only reaches terminals started later (in cmder not even those), so use `lens node`. `LENS_NODE` still overrides the file. `lens node` stops lens, re-registers the agents with the new Node and starts the daemon again if it ran. The package stays where npm installed it: Ladybug's native module works on every Node version. `lens sync --debug` writes the Node it ran on in the second line of its log.
84
+
85
+ ---
86
+
87
+ ## 1. Architecture overview and philosophy
88
+
89
+ `lady-lens` is a fast, local code graph and semantic analysis engine built on [LadybugDB](https://www.npmjs.com/package/@ladybugdb/core). It indexes source code, documentation, decisions and dependencies into a directed graph. AI coding agents and developers can ask for exact facts about the codebase (definitions, import chains, callers, test reach, code health and architecture metrics) without spending expensive LLM tokens on context.
90
+
91
+ The code base follows a strict **hexagonal architecture (ports and adapters)**:
92
+ - **Core domain / model**: graphs, nodes (files, functions, documents, decisions) and edges (`IMPORTS`, `CALLS`, `TESTS`, `READS`, `CO_CHANGES`).
93
+ - **Storage port (`GraphStorePort`)**: interchangeable storage adapters (in memory for fast tests, LadybugDB for persistent indexing).
94
+ - **Sync and extraction port**: incremental parsing and AST extraction for JavaScript/TypeScript, C# and other registered languages; Mendix `.mpr` models are handled through `mxcli` as an external graph contributor.
95
+ - **Git port (`core/git`)**: the only place that starts git; see [Branches and commits](#branches-and-commits).
96
+ - **Query and view ports**: `functionView`, `folderView`, `codeHealth`, `rankGraphNodes`, `impact`.
97
+ - **Primary adapters**: reachable through the **npm package**, the **MCP server (Model Context Protocol)** and the **CLI (`lens`)**.
98
+
99
+ ---
100
+
101
+ ## 2. API ports: access through MCP and the npm package
102
+
103
+ Every feature of `lady-lens` is a **first-class API port**, available programmatically through the npm package (`lady-lens`) and interactively through the Model Context Protocol (MCP).
104
+
105
+ The library sync API is `createGraphSync().sync({ mode: 'incremental' })`; use `mode: 'full'` for a complete re-index.
106
+
107
+ ### Overview of all ports
108
+
109
+ | Port / domain | MCP tool | npm export (`lady-lens`) | Description |
110
+ | :--- | :--- | :--- | :--- |
111
+ | **Function analysis** | `functionView` | `functionView(graph, symbol, { readFile, maxSites })` / `functionViewTool(args)` | Definition, line numbers, docstring/purpose, all calling files (`callers`), linked tests and referenced backlog stories of a function; `resolved` and `unresolved` call counts (a `note` "niet bewezen leeg" when none is bound but the name appears); for a class `children` (methods) and `inheritors` (subclasses). |
112
+ | **Folder and module analysis** | `folderView` | `folderView(graph, folder)` / `folderViewTool(args)` | Structure of a folder: parts, internal data flow, who calls the folder from outside and possible deviations (cycles, untested files). |
113
+ | **Code health and metrics** | `health` | `codeHealth(graph, opts)` / `healthTool(args)` | NDepend-style statistics: test reach (including index.js barrels), cyclic dependencies, boundary violations, hotspots (churn x lines), coupling (Ca, Ce, instability), zone of pain, and AST design smells with actionable pattern advice (`dispatch-chain`, `fallback-heavy`, `deep-nesting`, `loop-branching`, `long-condition`, `flag-parameter`, `repeated-literal`, `global-mutable-state`, `direct-io`, `god-module`). A measured line coverage (`coverage-summary.json`, written by `vitest --coverage` with the `json-summary` reporter) beats the import guess: a file covered through another one is tested, and its exports are not guessed by name. Barrels (`index.js`) are never flagged for untested exports, fan-in/out, zone of pain or god-module; tool config files (`*.config.*`) are scripts. On request `hubs` (most neighbours) and `bridges` (betweenness), each with `total` and `truncated` (`hubsAndBridges(graph, opts)`). |
114
+ | **Symbol location** | `definedIn` | `definedIn(graph, symbol)` / `definedInTool(args)` | Where an identifier is defined or exported: file path and exact start/end lines. |
115
+ | **Imports** | `imports` | `importsOf(graph, file)` / `imports(args)` | Which files and modules a given file imports directly. |
116
+ | **Dependents** | `importedBy` | `importersOf(graph, file)` / `importedBy(args)` | Which files import the given file (fan-in analysis). |
117
+ | **Exports** | `exports` | `exportsOf(graph, file)` / `exportsTool(args)` | Complete sorted list of exported functions, variables and types of a file. |
118
+ | **File check** | `exists` | `fileLookup(graph, file)` / `fileExists(args)` | Checks whether a file is in the project graph; suggests matches for typos or moved folders. |
119
+ | **Graph search** | `graph_query` | `graph_query(args)` / `rankGraphNodes(graph, query)` | Semantic and keyword search through the graph by relevance score, IDF weighting and relations. |
120
+ | **Interactive search** | `searchView` | `searchView(args)` | Advanced search with regex, case sensitivity, file type filter (code, doc, test) and path globs. |
121
+ | **Text and regex** | `grep` | `grep(args)` | Fast regex search through code, honouring `.gitignore` and project exclusions. |
122
+ | **Config search** | `config_grep` | `grep(args)` + config filter | Searches only project and configuration files, such as `.csproj` and reference-manager XML. |
123
+ | **Config references** | `config_references` | `grep(args)` + config filter | Finds which config files mention a package, project or Siemens functional block. |
124
+ | **Config update** | `config_update` | `fs` + `createGraphSync().touch()` | Replaces one config file, optionally checks a SHA-256 and refreshes the graph facts. |
125
+ | **Path matching** | `glob` | `glob(args)` | Finds repository paths by glob pattern (e.g. `core/**/*.js`). |
126
+ | **AST chunk reader** | `read_chunk` | `read_chunk(args)` | Reads one AST chunk (class/function) or a range of lines. Large files return a compact summary. |
127
+ | **Decisions and discussions** | `discussion_save`, `discussion_query`, etc. | `saveDiscussion`, `loadDiscussions`, `queryDiscussions` | Manages architecture decisions and discussions, with frontmatter links to code nodes. |
128
+ | **Multi-repo management** | `repo_list`, `repo_add`, `repo_remove` | `registerRepo`, `unregisterRepo`, `listRegisteredRepos` | Manages several projects in the central Ladybug database registry. |
129
+ | **Graph sync** | `repo_sync` | `createGraphSync(options).sync()` | Scans the project incrementally (by size and mtime) or fully (`mode: 'full'`). Records the branch and commit and reports `commitsSince`. With `branch: '<name>'` another branch is indexed into the scope `branch:<name>` without checking it out. |
130
+ | **Branch difference** | `branch_diff` | `branchDiff({ from, to, root })` | What `to` changes since its merge-base with `from`: files (added, removed, modified, renamed) and functions (added, removed, modified, renamed) and changed import and call relations. |
131
+ | **Mendix model difference** | `mendix_diff` | `mendixDiff({ from, to, root })` | The Mendix model changes `to` brings since its merge-base with `from`, read from git without a checkout or mxcli, for a single-file `.mpr` (MPR v1, documents compared by `ContentsHash`) and for `mprcontents/` (MPR v2, the `.mxunit` files git reports). Returns `commits` (sha, date, author, subject), `files`, and `documents`: per document `module`, `folders`, `name`, `qualifiedName`, `type` and `change`; for a modified one `elements` (added, deleted, modified; `type`, `name`, `detail` such as `NanoflowCallAction: Module.Flow`, and `properties` as `{ path, before, after }` with paths like `Action > ParameterMappings`; a pointer shows as `{ element }`); for a microflow or nanoflow `flow.before` / `flow.after` with `nodes` (`summary`, `status`) and `edges` (`from`, `to`, `cases`, `status`). Needs Node 22.13+ (`lens node`). |
132
+ | **Diff impact** | `diff_impact` | `diffImpact(args)` / `changedFunctions({ from, to, git, readFile })` | The functions a diff changes (the work not committed yet, or `from`..`to`) with callers, tests, bound/unbound call counts, complexity and test gaps; riskiest first, with `total` and `truncated`. |
133
+ | **Search over projects** | `cross_repo_search` | `crossRepoSearch(args)` | `searchView` over every registered project or `repos: [...]`, project after project; unregistered names in `unknown`. |
134
+ | **Tool metadata** | (all tools) | `RESEARCH_TOOL_SCHEMAS`, `buildMcpToolSchemas()` | Every schema has `readOnly` (MCP `annotations.readOnlyHint`); the discussion tools carry `usedBy: ['/discuss', '/research']` so a host such as Kura gives them only to those consumers. |
135
+ | **Branch impact** | `branch_impact` | `branchImpact({ change, against, root })` | What a change on one branch (e.g. a bugfix on `release`) means for another: functions still used there (file and line), overlap, shared files and text merge conflicts. |
136
+ | **Commit inspection** | `commit_show` | `commitShow({ commit, root })` | What one commit changed (files and functions against its first parent); for a merge commit, what the merge brought in. |
137
+ | **Function history** | `function_history` | `functionHistory({ name, file, ref, max, root })` | Commits that added, modified or removed one function; without `name` every commit that touched the file. Name based: a renamed function starts a new history. |
138
+
139
+ ### Branches and commits
140
+
141
+ The graph knows which branch and commit it was built on:
142
+
143
+ - After every sync a `Branch` node points to its `Commit` (`HEAD_AT`). `repo_sync` reports how many commits came in since the previous sync on that branch. A commit that changed no file is recorded too.
144
+ - A saved discussion gets `CREATED_AT` (commit) and `ON_BRANCH` (branch). If you switch to a branch where the source file does not exist, the discussion stays; `discussion_query` shows the source as "not on this branch" and on which branch the file does exist. Switching back and syncing restores the link by itself.
145
+ - `repo_sync({ branch: 'feature-x' })` reads that branch with `git ls-tree` and `git cat-file --batch` into its own scope `branch:feature-x`. The working copy, `HEAD` and the project scope stay unchanged. A second call only reads what changed since the stored commit. This scope has no Mendix contributions and no co-change signal.
146
+ - `branch_diff`, `branch_impact`, `commit_show` and `function_history` read git directly and check nothing out. Functions are compared by name and content (hash of the body); a function whose name changed but whose body is alike (same file, or a renamed file) shows as `renamed` with `oldName`, and `branch_diff` also lists added and removed import and call relations (`relations`). `branch_impact` finds callers with `git grep` (at most 20 references per function; for a renamed function it searches the old name) and uses `git merge-tree --write-tree` (git 2.38 or newer) for conflicts.
147
+ - All git calls go through `core/git` (`createGit({ root, run })`); a test checks that git is started nowhere else. `createFakeGit(state)` is an in-memory git for tests; `test/gitPort.contract.test.js` runs the same scenario on both and compares the answers.
148
+
149
+ ---
150
+
151
+ ## 3. Configuration through `config.json`
152
+
153
+ All `lady-lens` settings can be set in one central **`config.json`** file in the root of the project.
154
+
155
+ ### Automatic detection
156
+ `lady-lens` looks for configuration files in this order:
157
+ 1. A file given with `--config <path>` or the environment variable `LENS_SETTINGS_PATH`.
158
+ 2. `config.json` (recommended default)
159
+ 3. `lens.config.json`
160
+ 4. `.lady-lens.json`
161
+ 5. `.lady-lens.yaml`
162
+
163
+ ### Complete example of `config.json`
164
+
165
+ ```json
166
+ {
167
+ "project": {
168
+ "graph_roots": ["."],
169
+ "exclude_dirs": [
170
+ ".git",
171
+ ".memory",
172
+ "node_modules",
173
+ "outputs",
174
+ "coverage",
175
+ "dist",
176
+ "build",
177
+ "target",
178
+ ".vs",
179
+ ".idea"
180
+ ],
181
+ "graph_extensions": [
182
+ ".js",
183
+ ".mjs",
184
+ ".ts",
185
+ ".jsx",
186
+ ".tsx",
187
+ ".cs",
188
+ ".csproj",
189
+ ".sln",
190
+ ".sql",
191
+ ".ps1",
192
+ ".md",
193
+ ".yaml",
194
+ ".yml",
195
+ ".json"
196
+ ]
197
+ },
198
+ "graph": {
199
+ "ast": {
200
+ "enabled": false
201
+ },
202
+ "documentation": {
203
+ "enabled": true
204
+ },
205
+ "links": {
206
+ "enabled": true
207
+ },
208
+ "freshness": {
209
+ "default_max_age_days": 30
210
+ }
211
+ },
212
+ "mcp": {
213
+ "port": 4318,
214
+ "uiPort": 4317
215
+ },
216
+ "database": ".memory/graph/project.lbdb",
217
+ "env": {
218
+ "TOOL_RESULT_CHARS": "6000",
219
+ "READ_CHUNK_MAX_CHARS": "12000",
220
+ "READ_CHUNK_MAX_LINES": "400",
221
+ "GREP_MAX_MATCHES": "50",
222
+ "DEBUG_LEVEL": "2",
223
+ "DEBUG_LOG_FILE": ""
224
+ }
225
+ }
226
+ ```
227
+
228
+ ### Configuration sections
229
+
230
+ 1. **`project`**:
231
+ - `graph_roots`: folders to index (default `["."]`).
232
+ - `exclude_dirs`: folders ignored during sync, glob and grep.
233
+ - `graph_extensions`: file extensions included in the code graph.
234
+ 2. **`graph`**:
235
+ - `ast.enabled`: also store the full JavaScript syntax tree of every file (default `false`). Symbols, calls and functions are extracted either way; the stored tree is about 9× the size of the source and can fill the graph database's buffer on large vendored bundles.
236
+ - `documentation.enabled`: index markdown documents and link frontmatter.
237
+ - `links.enabled`: link import and call relations automatically.
238
+ - `freshness.default_max_age_days`: maximum age before automatic re-indexing.
239
+ 3. **`mcp`**:
240
+ - `port`: HTTP/SSE port of the MCP server (default `4318`).
241
+ - `uiPort`: web UI dashboard port (default `4317`).
242
+ 4. **`database`**:
243
+ - Path to the LadybugDB database file. If not set, lens uses `~/.lady-lens/repos/<id>/graph.lbdb`.
244
+ 5. **`env`**:
245
+ - Sets lens environment variables directly (such as `TOOL_RESULT_CHARS`, `DEBUG_LEVEL`).
246
+
247
+ ---
248
+
249
+ ## 4. Using it as an npm package
250
+
251
+ Install the package as a dependency from npm (or a `.tgz` built with `npm run pack`, see [section 0](#0-installation-and-setup)):
252
+
253
+ ```bash
254
+ npm install lady-lens
255
+ npm install ..\lady-lens\dist\lady-lens-<version>.tgz # a build from source
256
+ ```
257
+
258
+ ### Direct imports (main entry)
259
+
260
+ Every port is available from the root export:
261
+
262
+ ```javascript
263
+ import {
264
+ createGraphSync,
265
+ functionViewTool,
266
+ folderViewTool,
267
+ healthTool,
268
+ definedInTool,
269
+ graph_query,
270
+ grep,
271
+ glob,
272
+ read_chunk,
273
+ RESEARCH_TOOLS,
274
+ loadProjectSettingsSync
275
+ } from 'lady-lens';
276
+
277
+ // 1. Read the settings (reads config.json automatically)
278
+ const settings = loadProjectSettingsSync();
279
+
280
+ // 2. Incremental sync of the repository
281
+ const syncResult = await createGraphSync().sync({ mode: 'incremental' });
282
+ console.log(`Graph synced: ${syncResult.nodes} nodes`);
283
+
284
+ // 3. Ask for a function view
285
+ const fnDetails = await functionViewTool({ symbol: 'createGraphSync' });
286
+ console.log('Callers of createGraphSync:', fnDetails.callers);
287
+
288
+ // 4. Inspect code health
289
+ const health = await healthTool({ limit: 5 });
290
+ console.log('Top hotspots:', health.hotspots);
291
+
292
+ // 5. Semantic graph query
293
+ const queryResult = await graph_query({ query: 'database storage' });
294
+ console.log('Nodes found:', queryResult.nodes);
295
+ ```
296
+
297
+ ### Modular subpath imports
298
+
299
+ Specialised scenarios can use subpath imports:
300
+
301
+ ```javascript
302
+ import { createGraph, createGraphRepository } from 'lady-lens/graph';
303
+ import { RESEARCH_TOOLS, grep, glob } from 'lady-lens/search';
304
+ import { createLadyLensMcpServer, createMcpHttpServer } from 'lady-lens/mcp';
305
+ import { listRegisteredRepos, registerRepo } from 'lady-lens/repository';
306
+ import { createProfiler, globalProfiler } from 'lady-lens/observability';
307
+ ```
308
+
309
+ ---
310
+
311
+ ## 5. Using it as an MCP server
312
+
313
+ Start the background service with the CLI:
314
+
315
+ ```bash
316
+ lens mcp -d
317
+ ```
318
+
319
+ This starts:
320
+ - The **Streamable HTTP MCP server** on `http://127.0.0.1:4318/mcp`
321
+ - The legacy **SSE MCP server** on `http://127.0.0.1:4318/sse`
322
+ - The **UI dashboard** on `http://127.0.0.1:4317`
323
+
324
+ ### AI assistant configuration
325
+
326
+ Add the server to your MCP configuration file (for example in Antigravity, Claude Desktop, Cursor or VS Code):
327
+
328
+ #### Streamable HTTP mode (recommended)
329
+ ```json
330
+ {
331
+ "mcpServers": {
332
+ "lady-lens": {
333
+ "url": "http://127.0.0.1:4318/mcp"
334
+ }
335
+ }
336
+ }
337
+ ```
338
+
339
+ Use `/sse` only for older clients that do not support Streamable HTTP.
340
+
341
+ ### Configuration files through MCP
342
+
343
+ No extra setting in `config.json` is needed. The agent uses these tools:
344
+
345
+ ```json
346
+ {
347
+ "name": "config_references",
348
+ "arguments": { "reference": "INVENTORY_OP" }
349
+ }
350
+ ```
351
+
352
+ This returns, among other things, `referenceManager.xml`, the line number and the matching text. Use `config_references` for this, not `imports` or `importedBy`.
353
+
354
+ Read the file before changing it. Then pass the complete new content to `config_update`. Use the SHA-256 of the content you read as `expectedHash`; a stale update is refused.
355
+
356
+ ```json
357
+ {
358
+ "name": "config_update",
359
+ "arguments": {
360
+ "path": "App/App.csproj",
361
+ "content": "<Project>...</Project>",
362
+ "expectedHash": "<sha256>"
363
+ }
364
+ }
365
+ ```
366
+
367
+ Supported: `.csproj`, `.sln`, `.props`, `.targets`, `.xml`, `.ini`, `.yaml`, `.yml`, `.toml` and `package.json`. After an update an incremental graph sync runs.
368
+
369
+ ### Agent instruction
370
+
371
+ Use this text in the agent chat:
372
+
373
+ > Use Lady Lens MCP. First pick the right repo with `repo` or register it with `lens add`. Use `config_references` for questions like: who references `INVENTORY_OP`? Do not use `imports` or `importedBy`. Then read the config files found. Use `config_update` with the complete new content and `expectedHash`. Do not write directly outside `config_update`.
374
+
375
+ #### One daemon, several projects
376
+ One daemon serves every registered project (`lens add <folder>`). Pick the project per client in the URL:
377
+
378
+ ```json
379
+ { "mcpServers": { "lady-lens": { "url": "http://127.0.0.1:4318/mcp?repo=C:/git/my-project" } } }
380
+ ```
381
+
382
+ - `repo` is a registered folder or id; the `X-Lens-Repo` header works too.
383
+ - An unregistered repo is refused (HTTP 403): run `lens add <folder>` first.
384
+ - Without `repo` the folder where `lens mcp -d` was started applies; a tool call can override that with its `repo` argument.
385
+ - Tool calls run one after another, so simultaneous requests for different projects do not affect each other.
386
+ - The UI dashboard that starts with `lens mcp -d` works the same way: `http://127.0.0.1:4317/?repo=<folder or id>` shows that project (not registered: HTTP 403); with more than one registered project a dropdown appears.
387
+
388
+ #### Direct stdio mode
389
+ ```json
390
+ {
391
+ "mcpServers": {
392
+ "lady-lens": {
393
+ "command": "node",
394
+ "args": ["C:/git/lady-lens/bin/lens.mjs", "mcp", "--stdio"]
395
+ }
396
+ }
397
+ }
398
+ ```
399
+
400
+ ---
401
+
402
+ ## 6. CLI command reference
403
+
404
+ The command line interface `lens` gives direct access to every feature:
405
+
406
+ | Command | Description |
407
+ | :--- | :--- |
408
+ | `lens sync [--repo <dir>] [--full] [--debug]` | Sync the graph for the current project or a target folder. `--debug` writes every step (scan, parse, mxcli calls, graph write) with its time, size, memory and any error stack to `~/.lady-lens/logs/sync-<time>.log`. |
409
+ | `lens ask <tool> '<json>'` | Call one of the research tools directly (e.g. `lens ask functionView '{"symbol":"createProfiler"}'`). |
410
+ | `lens mcp [-d]` | Start the MCP server (optionally in the background with `-d`). |
411
+ | `lens stop [pid]` | End the background daemon and release ports and locks, or only the given PID. |
412
+ | `lens ps` | Show the tracked daemon PIDs per folder. |
413
+ | `lens status` | Show whether the background daemon is running. |
414
+ | `lens ui [--port 4317]` | Start the interactive graph visualisation in the browser. The **Stacktrace** tab ties a pasted Node, .NET, Python or Java trace to project files and functions (`POST /api/trace`, `traceView` in `core/search/stackTrace.js`). The four tabs share one place in the URL (Back/Forward, crumbs, copyable link). Under the code: health issues, the function at the line with callers, calls, call tree, tests and documents, the file's imports, and its history (`GET /api/at`, `/api/flow`, `/api/history`; `callFlow`, `toMermaid`, `codeHistory` in `core/search`). Graph Network: the flow diagram of the function with Mermaid export. |
415
+ | `lens list` | Overview of all registered repositories and their database paths. |
416
+ | `lens add <dir>` | Register a new project and run the first sync right away. |
417
+ | `lens remove <id\|dir>` | Remove a repository from the registry. |
418
+ | `lens tools` | Show all available tools with their schemas and parameters. |
419
+ | `lens bench [--repo <dir>] [--runs N] [--baseline] [--no-processes] [--json]` | Time the sync (with its phases) and every question on a repository, in a temporary database: the registry and the repository's own database stay as they are. Saves the run in `~/.lady-lens/bench/<repo id>/` (numbers and environment, no paths or code) and compares it with the baseline there; `lens bench compare` compares the newest run again. See README, Performance. |
420
+ | `lens install [agent...]` | Install the MCP stdio configuration in detected agents. |
421
+ | `lens install --skill` | Install the Lady-lens workflow skill, write `~/.lady-lens/lens-instructions.md`, and add one marked line pointing to it in `~/.claude/CLAUDE.md`, `~/.copilot/copilot-instructions.md`, `~/.codex/AGENTS.md` and `~/.vibe/AGENTS.md`; own rules files for VS Code and Antigravity. |
422
+ | `lens uninstall [agent...]` | Remove the MCP entry from the agents. |
423
+ | `lens uninstall --skill` | Remove the skill, the marked line and the two rules files. |
424
+ | `lens install --mendix` | Install the `lady-lens-mendix` skill in the detected Claude, Copilot and Agents skill directories: search Mendix pages, widgets and flows in `.mxcli/mdl` (written from mxcli's catalog by a background export that `lens sync` starts after a model change; it never holds up the sync or MCP calls: `LENS_MDL_EXPORT=background|inline|off`, state in `.mxcli/lens-mdl.json`), change them with `mxcli`. Every other mxcli call stops after `LENS_MXCLI_TIMEOUT_MS` (default 120000); when mxcli gives nothing, the previous Mendix model is kept. `lens uninstall --mendix` removes it. |
425
+ | `lens update [<version or file.tgz>]` | Update lady-lens: stop every lens process (on Windows they keep the graph database module open and npm cannot replace it), `npm install -g` the newest version (or the given version or local tgz), then let the new lens re-register itself where it was registered and copy again the skills and policies that are installed (`lens install --refresh`), and start the daemon again if it ran. Reconnect your agents afterwards. `lens install skill`, `lens install skill-mendix` and agent names (`vscode`, `claude-code`) work as well as `--skill` / `--mendix`. |
426
+ | `lens node [<path to node.exe> or --clear]` | Run lens on another Node than the one on PATH, e.g. Node 22.13+ for the Mendix MDL export while nvm keeps Node 18 for your projects. The choice is kept in `~/.lady-lens/lens.json`, so it holds at once, in every terminal and for agents started from the desktop (unlike `setx`, which only reaches terminals started later). It stops lens, re-registers the agents with that Node (`lens install --refresh`) and starts the daemon again if it ran. `lens node` shows the choice, `--clear` undoes it. `LENS_NODE` overrides the file. |
427
+ | `lens v` / `lens version` | Show the installed package version. |
428
+ | `.\scripts\update-lens.ps1 [-Pack] [-Source <source>]` | Older script for a build from source; `lens update <file.tgz>` does the same and also refreshes the agents and skills. |