lady-lens 1.6.11 → 1.6.15
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 +5 -2
- package/README.md +5 -2
- package/bin/lens.mjs +18 -19
- package/core/git/fakeGit.js +3 -1
- package/core/git/hooks.js +106 -0
- package/core/git/index.js +3 -0
- package/core/graph/query/classShape.js +20 -0
- package/core/graph/query/functionView.js +198 -200
- package/core/graph/query/index.js +1 -0
- package/core/graph/query/parameterSeams.js +198 -0
- package/core/graph/query/questionIntent.js +6 -6
- package/core/mcp/handlers/repoList.js +2 -2
- package/core/mcp/httpServer.js +17 -0
- package/core/mcp/index.js +1 -0
- package/core/mcp/mendixSchemas.js +7 -3
- package/core/mcp/syncQueue.js +35 -0
- package/core/mendix/diffUnits.js +115 -0
- package/core/mendix/elementDiff.js +195 -92
- package/core/mendix/flows.js +12 -2
- package/core/mendix/index.js +2 -1
- package/core/mendix/mendixDiff.js +171 -107
- package/core/mendix/modelReader.js +138 -90
- package/core/repository/groups.js +162 -0
- package/core/repository/index.js +7 -0
- package/core/repository/registry.js +1 -1
- package/core/search/schemas.js +1 -1
- package/package.json +1 -1
- package/skills/lady-lens/SKILL.md +2 -2
package/DOCUMENTATIE.md
CHANGED
|
@@ -30,6 +30,7 @@ lens sync # later: incremental sync (--full = everything
|
|
|
30
30
|
```bash
|
|
31
31
|
lens install # every agent found; or one: lens install vscode
|
|
32
32
|
lens install --skill # also the Lady-lens workflow skill
|
|
33
|
+
lens install --hooks # non-blocking Git post-commit hooks for background sync
|
|
33
34
|
lens install --mendix # the Mendix skill; or for some agents: lens install skill-mendix vscode claude-code
|
|
34
35
|
lens install --dry-run # shows what would change, writes nothing
|
|
35
36
|
```
|
|
@@ -108,7 +109,7 @@ The library sync API is `createGraphSync().sync({ mode: 'incremental' })`; use `
|
|
|
108
109
|
|
|
109
110
|
| Port / domain | MCP tool | npm export (`lady-lens`) | Description |
|
|
110
111
|
| :--- | :--- | :--- | :--- |
|
|
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
|
+
| **Function analysis** | `functionView` | `functionView(graph, symbol, { readFile, maxSites })` / `functionViewTool(args)` | Definition, line numbers, docstring/purpose, parameter seams (`parameterSeams`: methods and properties called on parameters), 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
113
|
| **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
114
|
| **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
115
|
| **Symbol location** | `definedIn` | `definedIn(graph, symbol)` / `definedInTool(args)` | Where an identifier is defined or exported: file path and exact start/end lines. |
|
|
@@ -128,7 +129,7 @@ The library sync API is `createGraphSync().sync({ mode: 'incremental' })`; use `
|
|
|
128
129
|
| **Multi-repo management** | `repo_list`, `repo_add`, `repo_remove` | `registerRepo`, `unregisterRepo`, `listRegisteredRepos` | Manages several projects in the central Ladybug database registry. |
|
|
129
130
|
| **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
131
|
| **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
|
|
132
|
+
| **Mendix model difference** | `mendix_diff` | `mendixDiff({ from, to, root, detail, ignore, documents, modules })` | The Mendix model changes `to` brings since its merge-base with `from`, read from git or disk worktree without a checkout or mxcli, for single-file `.mpr` (MPR v1) and `mprcontents/` (MPR v2). Supports cross-folder resolution for multi-clone repos (`repo_list` groups), `to: 'working-tree'`, compact element diffing (`detail: 'changes' | 'summary' | 'full'`), noise reduction (`ignore: ['translations', 'layout']`), and added/deleted document elements. Returns `schemaVersion: 1`, `resolved`, `commits`, `widgets`, `files`, `documents` and `ignored`. Needs Node 22.13+ (`lens node`). |
|
|
132
133
|
| **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
134
|
| **Search over projects** | `cross_repo_search` | `crossRepoSearch(args)` | `searchView` over every registered project or `repos: [...]`, project after project; unregistered names in `unknown`. |
|
|
134
135
|
| **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. |
|
|
@@ -419,8 +420,10 @@ The command line interface `lens` gives direct access to every feature:
|
|
|
419
420
|
| `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
421
|
| `lens install [agent...]` | Install the MCP stdio configuration in detected agents. |
|
|
421
422
|
| `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. |
|
|
423
|
+
| `lens install --hooks` | Install non-blocking Git hooks (`post-commit`, `post-checkout`, `post-merge`, `post-rewrite`) in `.git/hooks` for bundled background daemon sync (`POST /sync?repo=...`). `LENS_HOOKS=0` disables. |
|
|
422
424
|
| `lens uninstall [agent...]` | Remove the MCP entry from the agents. |
|
|
423
425
|
| `lens uninstall --skill` | Remove the skill, the marked line and the two rules files. |
|
|
426
|
+
| `lens uninstall --hooks` | Remove lady-lens hook blocks from `.git/hooks`, leaving other hook content intact. |
|
|
424
427
|
| `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
428
|
| `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
429
|
| `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. |
|
package/README.md
CHANGED
|
@@ -33,6 +33,7 @@ lens list # check that it is there
|
|
|
33
33
|
```
|
|
34
34
|
lens install # MCP entry (stdio) in every agent found; or name one: lens install vscode
|
|
35
35
|
lens install --skill # the Lady-lens workflow skill for those agents
|
|
36
|
+
lens install --hooks # non-blocking Git post-commit hooks for background sync
|
|
36
37
|
lens install --mendix # the Mendix skill (search .mpr content via .mxcli/mdl, change it with mxcli)
|
|
37
38
|
lens install skill-mendix vscode claude-code # the same, only for those agents
|
|
38
39
|
```
|
|
@@ -111,7 +112,7 @@ Every tool that returns a list takes `limit`: how many items its main list holds
|
|
|
111
112
|
| Tool | Answers |
|
|
112
113
|
|---|---|
|
|
113
114
|
| `definedIn` | where a function or name is defined, with lines |
|
|
114
|
-
| `functionView` | what a function does: definition and lines, purpose, callers, tests (with test names), stories; bound (`resolved`) and unbound (`unresolved`) calls, with "niet bewezen leeg" when nothing is bound but the name appears; for a class its methods (`children`) and subclasses (`inheritors`); `maxSites` for more than 5 lines per file |
|
|
115
|
+
| `functionView` | what a function does: definition and lines, purpose, parameter seams (`parameterSeams`: methods and properties accessed on parameters), callers, tests (with test names), stories; bound (`resolved`) and unbound (`unresolved`) calls, with "niet bewezen leeg" when nothing is bound but the name appears; for a class its methods (`children`) and subclasses (`inheritors`); `maxSites` for more than 5 lines per file |
|
|
115
116
|
| `diff_impact` | what my change touches: the functions the work not committed yet (or a range `from`..`to`) changes, with callers, tests, complexity and test gaps, riskiest first |
|
|
116
117
|
| `importedBy` / `imports` | who imports a file / what it imports |
|
|
117
118
|
| `exports` | what a file exports |
|
|
@@ -124,7 +125,7 @@ Every tool that returns a list takes `limit`: how many items its main list holds
|
|
|
124
125
|
| `config_update` | safely replace one config file and refresh its graph facts; supports `expectedHash` |
|
|
125
126
|
| `repo_sync` | index the repository; records the branch and commit and reports `commitsSince`; `branch: "<name>"` indexes another branch into its own scope `branch:<name>` without checking it out |
|
|
126
127
|
| `branch_diff` | what branch `to` changes since its merge-base with `from`: files and functions added, removed, modified, renamed, plus changed import and call relations |
|
|
127
|
-
| `mendix_diff` | Mendix model changes of a branch, read from git (no checkout, no mxcli;
|
|
128
|
+
| `mendix_diff` | Mendix model changes of a branch, read from git or disk worktree (no checkout, no mxcli; MPR v1 and mprcontents/ v2): commits, changed documents with module, folder, name and type, elements with property diffs (compact with `detail: "changes"`, ignore noise with `ignore: ["translations"]`), flow graphs with statuses and clean node summaries. Resolves cross-folder clones in the same repo group, supports `to: "working-tree"`. Data for a client (extension / review tool); needs Node 22.13+ (`lens node`) |
|
|
128
129
|
| `branch_impact` | what a change on one branch (e.g. a bugfix on `release`) means for another: functions still used there, overlap, shared files, text merge conflicts |
|
|
129
130
|
| `commit_show` | what one commit changed (files and functions against its first parent) |
|
|
130
131
|
| `function_history` | the commits that added, modified or removed one function; without `name` every commit that touched the file |
|
|
@@ -167,6 +168,8 @@ This adds a stdio entry (absolute `node` path, no daemon, no port) to each agent
|
|
|
167
168
|
|
|
168
169
|
`lens install --skill` installs `skills/lady-lens/SKILL.md` in detected Claude, Copilot, or Agents skill directories, and makes lady-lens the default for code search (a skill only loads when a task matches it). The rules live in one file, `~/.lady-lens/lens-instructions.md` (from `skills/lady-lens/lens-instructions.md`). Files you own get only one marked line: in `CLAUDE.md` an `@` import of that file, elsewhere the core rule itself plus a link to it: `~/.claude/CLAUDE.md` (an `@` import), `~/.copilot/copilot-instructions.md`, `~/.codex/AGENTS.md` and `~/.vibe/AGENTS.md` (Mistral Vibe). VS Code (`User/prompts/lady-lens.instructions.md`) and Antigravity (`~/.gemini/config/rules/lady-lens.md`) get a rules file of their own. `lens uninstall --skill` removes the skill, that one line and those two files; nothing else in your files changes.
|
|
169
170
|
|
|
171
|
+
`lens install --hooks` sets up non-blocking Git hooks (`post-commit`, `post-checkout`, `post-merge`, `post-rewrite`) in `.git/hooks` that trigger a bundled background sync on the daemon (`POST /sync?repo=...`). Hooks run after events, never block commits, preserve pre-existing hook scripts, and can be disabled with `LENS_HOOKS=0`. `lens uninstall --hooks` cleanly removes the lady-lens block.
|
|
172
|
+
|
|
170
173
|
Start the background service:
|
|
171
174
|
```bash
|
|
172
175
|
lens mcp -d # starts Streamable HTTP MCP on http://127.0.0.1:4318/mcp and UI on http://127.0.0.1:4317
|
package/bin/lens.mjs
CHANGED
|
@@ -27,8 +27,7 @@ const id = idOfRepo(repo);
|
|
|
27
27
|
const dbFlag = flag('--db');
|
|
28
28
|
const cfg = [flag('--config'), process.env.LENS_SETTINGS_PATH, 'config.json', 'lens.config.json', '.lady-lens.json', '.lady-lens.yaml']
|
|
29
29
|
.map(p => p && (path.isAbsolute(p) ? p : path.join(repo, p))).find(p => p && fs.existsSync(p));
|
|
30
|
-
const
|
|
31
|
-
const fileConfig = cfg ? readJsonFile(cfg) : {};
|
|
30
|
+
const fileConfig = cfg ? (() => { try { return JSON.parse(fs.readFileSync(cfg, 'utf8')); } catch { return {}; } })() : {};
|
|
32
31
|
if (fileConfig.env) Object.entries(fileConfig.env).forEach(([k, v]) => { if (!process.env[`LENS_${k}`] && !process.env[k]) process.env[`LENS_${k}`] = String(v); });
|
|
33
32
|
|
|
34
33
|
const readRegistry = () => { try { return JSON.parse(fs.readFileSync(REGISTRY, 'utf8')); } catch { return { repos: {} }; } };
|
|
@@ -37,11 +36,7 @@ const existingEntry = registryData.repos[id];
|
|
|
37
36
|
|
|
38
37
|
const explicitDb = dbFlag && (registryData.repos[dbFlag]?.database || (dbFlag.endsWith('.lbdb') ? path.resolve(dbFlag) : path.join(HOME, 'repos', dbFlag, 'graph.lbdb')));
|
|
39
38
|
const configDb = fileConfig.database || fileConfig.db;
|
|
40
|
-
const targetDb = process.env.LENS_GRAPH_DB
|
|
41
|
-
|| explicitDb
|
|
42
|
-
|| (configDb ? path.resolve(repo, configDb) : null)
|
|
43
|
-
|| existingEntry?.database
|
|
44
|
-
|| path.join(HOME, 'repos', id, 'graph.lbdb');
|
|
39
|
+
const targetDb = process.env.LENS_GRAPH_DB || explicitDb || (configDb ? path.resolve(repo, configDb) : null) || existingEntry?.database || path.join(HOME, 'repos', id, 'graph.lbdb');
|
|
45
40
|
process.env.LENS_REPO_ROOT = repo;
|
|
46
41
|
configureLensRoot(repo); // core is imported above, before LENS_REPO_ROOT is set: without this the scan root was not `repo`
|
|
47
42
|
process.env.LENS_GRAPH_DB = targetDb;
|
|
@@ -60,7 +55,16 @@ if (command === 'list') {
|
|
|
60
55
|
for (const entry of Object.values(readRegistry().repos)) console.log(`${entry.id} ${entry.path} ${entry.nodes ?? '?'} nodes last sync ${entry.lastSync ?? 'never'}`);
|
|
61
56
|
process.exit(0);
|
|
62
57
|
}
|
|
63
|
-
if (command === 'install' || command === 'uninstall') {
|
|
58
|
+
if (command === 'install' || command === 'uninstall') {
|
|
59
|
+
if (has('--hooks') || rest.includes('hooks')) {
|
|
60
|
+
const { hookInstallCommand } = await import('../core/git/index.js');
|
|
61
|
+
const out = hookInstallCommand({ action: command, repo: repoExplicit ? repo : process.cwd(), dryRun: has('--dry-run') });
|
|
62
|
+
console.log(out.text); process.exit(out.ok ? 0 : 1);
|
|
63
|
+
}
|
|
64
|
+
const { agentInstallCommand } = await import('../core/mcp/index.js');
|
|
65
|
+
const out = agentInstallCommand({ action: command, ids: rest.filter(a => !a.startsWith('-')), lensPath: fileURLToPath(import.meta.url), repo: repoExplicit ? repo : null, dryRun: has('--dry-run'), skill: has('--skill'), mendix: has('--mendix'), refresh: has('--refresh') });
|
|
66
|
+
console.log(out.text); process.exit(out.ok ? 0 : 1);
|
|
67
|
+
}
|
|
64
68
|
if (command === 'update' || command === 'node') { const update = await import('../core/update/index.js'); const daemonFile = path.join(HOME, 'daemon.json'); const out = command === 'node' ? update.lensNodeCommand(rest[0], { home: os.homedir(), daemonFile }) : update.runLensUpdate({ arg: rest.find(a => !a.startsWith('-')), lensPath: fileURLToPath(import.meta.url), daemonFile }); console.log(out.text); process.exit(out.ok ? 0 : 1); }
|
|
65
69
|
// the MDL export of a Mendix project, started by a sync in the background (core/graph/sync/mendixExport.js)
|
|
66
70
|
if (command === 'mendix-export') { await (await import('../core/graph/index.js')).runMdlExport(rest[0]); process.exit(0); }
|
|
@@ -79,15 +83,13 @@ const [{ RESEARCH_TOOLS, RESEARCH_TOOL_SCHEMAS, DASHBOARD_TOOLS }, { buildMcpToo
|
|
|
79
83
|
if (command === 'add') {
|
|
80
84
|
const { repoAdd, activateRepoContext } = await import('../core/mcp/index.js');
|
|
81
85
|
const { registered, sync } = await repoAdd({ path: rest[0] || process.cwd(), ...(dbFlag && { database: targetDb }) }, { activate: activateRepoContext });
|
|
82
|
-
console.log(`Registered ${registered.id} ${registered.path} (${sync.nodes} nodes) -> database: ${registered.database}`);
|
|
83
|
-
process.exit(0);
|
|
86
|
+
console.log(`Registered ${registered.id} ${registered.path} (${sync.nodes} nodes) -> database: ${registered.database}`); process.exit(0);
|
|
84
87
|
}
|
|
85
88
|
if (command === 'remove') {
|
|
86
|
-
|
|
87
|
-
if (!target) { console.error('usage: lens remove <id|dir>'); process.exit(1); }
|
|
89
|
+
if (!rest[0]) { console.error('usage: lens remove <id|dir>'); process.exit(1); }
|
|
88
90
|
const { repoRemove } = await import('../core/mcp/index.js');
|
|
89
|
-
const { removed, repo: entry } = repoRemove({ repo:
|
|
90
|
-
console.log(removed ? `Removed ${entry.id} ${entry.path}` : `Repository not found: ${
|
|
91
|
+
const { removed, repo: entry } = repoRemove({ repo: rest[0] });
|
|
92
|
+
console.log(removed ? `Removed ${entry.id} ${entry.path}` : `Repository not found: ${rest[0]}`);
|
|
91
93
|
process.exit(0);
|
|
92
94
|
}
|
|
93
95
|
|
|
@@ -138,7 +140,7 @@ if (command === 'mcp' && !args.includes('--stdio')) {
|
|
|
138
140
|
console.log(`lady-lens services listening:\n MCP Link: http://127.0.0.1:${actualPort}/mcp\n Legacy SSE: http://127.0.0.1:${actualPort}/sse\n MCP Status: http://127.0.0.1:${actualPort}/\n UI Dashboard: http://127.0.0.1:${uiPort}/\n Repo: ${repo}`);
|
|
139
141
|
if (!isChild) console.log(` (Ctrl+C or 'lens stop' to stop)`);
|
|
140
142
|
}
|
|
141
|
-
const logSyncFailure = (err,
|
|
143
|
+
const logSyncFailure = (err, log) => log && fs.appendFileSync(log, `lens sync failed: ${err.stack}\n`);
|
|
142
144
|
function handleSyncError(err, debugLog) {
|
|
143
145
|
logSyncFailure(err, debugLog);
|
|
144
146
|
console.error(`lens sync fout: ${err.message}${debugLog ? `\n(debug log: ${debugLog})` : ''}`);
|
|
@@ -194,7 +196,4 @@ if (command === 'tools') {
|
|
|
194
196
|
process.exit(0);
|
|
195
197
|
}
|
|
196
198
|
|
|
197
|
-
if (!['mcp', 'ui'].includes(command)) {
|
|
198
|
-
console.log('usage: lens <mcp|ui|sync|status|stop|list|add|remove|ask|tools|bench|install|uninstall|update|node|v|version> [options]');
|
|
199
|
-
process.exit(command ? 1 : 0);
|
|
200
|
-
}
|
|
199
|
+
if (!['mcp', 'ui'].includes(command)) { console.log('usage: lens <mcp|ui|sync|status|stop|list|add|remove|ask|tools|bench|install|uninstall|update|node|v|version> [options]'); process.exit(command ? 1 : 0); }
|
package/core/git/fakeGit.js
CHANGED
|
@@ -11,7 +11,7 @@ import crypto from 'crypto';
|
|
|
11
11
|
export const fakeSha = name => crypto.createHash('sha1').update(name).digest('hex');
|
|
12
12
|
|
|
13
13
|
const NO_REPOSITORY = {
|
|
14
|
-
currentBranch: () => null, resolveCommit: () => null, mergeBase: () => null, readBlob: () => null, readBlobBytes: () => null, logRange: () => [], commitList: () => [], countRange: () => null,
|
|
14
|
+
currentBranch: () => null, rootCommit: () => null, originUrl: () => null, resolveCommit: () => null, mergeBase: () => null, readBlob: () => null, readBlobBytes: () => null, logRange: () => [], commitList: () => [], countRange: () => null,
|
|
15
15
|
headInfo: () => null, commitInfo: () => null, fileLog: () => [], commitFiles: () => [], listBranches: () => [], listTree: () => null,
|
|
16
16
|
readBlobs: (ref, paths) => new Map(paths.map(file => [file, null])), existsAt: () => false, prefix: () => null, changedSince: () => null,
|
|
17
17
|
grepRef: () => [], grepRefs: (ref, names) => new Map(names.map(name => [name, []])), lastCommitFor: () => null, conflicts: () => null, worktreeChanges: () => [], ignoredPaths: () => null, commitsWithFiles: () => [],
|
|
@@ -82,6 +82,8 @@ export function createFakeGit(state = null) {
|
|
|
82
82
|
|
|
83
83
|
const git = {
|
|
84
84
|
currentBranch: () => state.head ?? null,
|
|
85
|
+
rootCommit: () => (state?.commits?.length ? fakeSha(state.commits[0].name) : null),
|
|
86
|
+
originUrl: () => null,
|
|
85
87
|
resolveCommit: ref => resolve(ref),
|
|
86
88
|
mergeBase: (a, b) => {
|
|
87
89
|
const [x, y] = [resolve(a), resolve(b)];
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Non-blocking Git hooks installer and manager (backlog/snelheid-en-hooks.md AC5, AC6, AC7).
|
|
3
|
+
* Hooks run after events (post-commit, post-checkout, post-merge, post-rewrite),
|
|
4
|
+
* never block commits, and trigger a bundled background sync on the daemon.
|
|
5
|
+
* @module core/git/hooks
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'fs';
|
|
8
|
+
import path from 'path';
|
|
9
|
+
|
|
10
|
+
export const HOOK_NAMES = Object.freeze([
|
|
11
|
+
'post-commit',
|
|
12
|
+
'post-checkout',
|
|
13
|
+
'post-merge',
|
|
14
|
+
'post-rewrite'
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
export const HOOK_START = '# lady-lens hook: start';
|
|
18
|
+
export const HOOK_END = '# lady-lens hook: end';
|
|
19
|
+
|
|
20
|
+
export const HOOK_SCRIPT = `${HOOK_START}
|
|
21
|
+
if [ "\${LENS_HOOKS:-1}" != "0" ]; then
|
|
22
|
+
(curl -s -m 1 -X POST "http://127.0.0.1:4318/sync?repo=$(pwd)" >/dev/null 2>&1 || nohup lens sync >/dev/null 2>&1 &) >/dev/null 2>&1 &
|
|
23
|
+
fi
|
|
24
|
+
${HOOK_END}`;
|
|
25
|
+
|
|
26
|
+
function gitHooksDir(repo) {
|
|
27
|
+
const gitDir = path.join(repo, '.git');
|
|
28
|
+
if (!fs.existsSync(gitDir)) return null;
|
|
29
|
+
const stat = fs.statSync(gitDir);
|
|
30
|
+
if (stat.isFile()) {
|
|
31
|
+
const content = fs.readFileSync(gitDir, 'utf8');
|
|
32
|
+
const match = /^gitdir:\s*(.+)$/m.exec(content);
|
|
33
|
+
if (match) return path.resolve(repo, match[1].trim(), 'hooks');
|
|
34
|
+
}
|
|
35
|
+
return path.join(gitDir, 'hooks');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function updateHookContent(existing, hookScript) {
|
|
39
|
+
if (!existing.includes(HOOK_START)) {
|
|
40
|
+
const prefix = existing.endsWith('\n') ? existing : `${existing}\n`;
|
|
41
|
+
return `${prefix}\n${hookScript}\n`;
|
|
42
|
+
}
|
|
43
|
+
const before = existing.slice(0, existing.indexOf(HOOK_START));
|
|
44
|
+
const after = existing.slice(existing.indexOf(HOOK_END) + HOOK_END.length);
|
|
45
|
+
return `${before}${hookScript}${after}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function removeHookContent(existing) {
|
|
49
|
+
const before = existing.slice(0, existing.indexOf(HOOK_START));
|
|
50
|
+
const after = existing.slice(existing.indexOf(HOOK_END) + HOOK_END.length);
|
|
51
|
+
return `${before}${after}`.replace(/^\s*\n+/, '').trimEnd() + '\n';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function installSingleHook(dir, name, dryRun) {
|
|
55
|
+
const filePath = path.join(dir, name);
|
|
56
|
+
const exists = fs.existsSync(filePath);
|
|
57
|
+
const current = exists ? fs.readFileSync(filePath, 'utf8') : '#!/bin/sh\n';
|
|
58
|
+
const next = updateHookContent(current, HOOK_SCRIPT);
|
|
59
|
+
if (current === next) return { name, status: 'unchanged' };
|
|
60
|
+
if (!dryRun) fs.writeFileSync(filePath, next, { mode: 0o755 });
|
|
61
|
+
return { name, status: exists ? 'updated' : 'installed' };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function ensureHooksDir(dir, dryRun) {
|
|
65
|
+
if (!dryRun) fs.mkdirSync(dir, { recursive: true });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function installHooks(options = {}) {
|
|
69
|
+
const repo = options.repo || process.cwd();
|
|
70
|
+
const dir = gitHooksDir(repo);
|
|
71
|
+
if (!dir) return { ok: false, text: `No .git repository found in ${repo}` };
|
|
72
|
+
ensureHooksDir(dir, Boolean(options.dryRun));
|
|
73
|
+
const results = HOOK_NAMES.map(name => installSingleHook(dir, name, Boolean(options.dryRun)));
|
|
74
|
+
return { ok: true, results, text: results.map(r => `${r.status.padEnd(10)} ${r.name}`).join('\n') };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function writeUninstalledHook(filePath, content) {
|
|
78
|
+
const isBare = content.trim() === '' || content.trim() === '#!/bin/sh';
|
|
79
|
+
if (isBare) {
|
|
80
|
+
fs.rmSync(filePath, { force: true });
|
|
81
|
+
} else {
|
|
82
|
+
fs.writeFileSync(filePath, content, { mode: 0o755 });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function uninstallSingleHook(dir, name, dryRun) {
|
|
87
|
+
const filePath = path.join(dir, name);
|
|
88
|
+
if (!fs.existsSync(filePath)) return { name, status: 'absent' };
|
|
89
|
+
const current = fs.readFileSync(filePath, 'utf8');
|
|
90
|
+
if (!current.includes(HOOK_START)) return { name, status: 'unchanged' };
|
|
91
|
+
const next = removeHookContent(current);
|
|
92
|
+
if (!dryRun) writeUninstalledHook(filePath, next);
|
|
93
|
+
return { name, status: 'removed' };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function uninstallHooks(options = {}) {
|
|
97
|
+
const repo = options.repo || process.cwd();
|
|
98
|
+
const dir = gitHooksDir(repo);
|
|
99
|
+
if (!dir) return { ok: false, text: `No .git repository found in ${repo}` };
|
|
100
|
+
const results = HOOK_NAMES.map(name => uninstallSingleHook(dir, name, Boolean(options.dryRun)));
|
|
101
|
+
return { ok: true, results, text: results.map(r => `${r.status.padEnd(10)} ${r.name}`).join('\n') };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function hookInstallCommand(options = {}) {
|
|
105
|
+
return options.action === 'uninstall' ? uninstallHooks(options) : installHooks(options);
|
|
106
|
+
}
|
package/core/git/index.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { execFileSync } from 'child_process';
|
|
7
7
|
export { createFakeGit, fakeSha } from './fakeGit.js';
|
|
8
|
+
export { HOOK_NAMES, HOOK_START, HOOK_END, HOOK_SCRIPT, installHooks, uninstallHooks, hookInstallCommand } from './hooks.js';
|
|
8
9
|
|
|
9
10
|
// windowsHide: in the detached daemon (no console) every git call without it opened a console and took ~1 s, not ~75 ms
|
|
10
11
|
// stderr piped, not ignored: the error then carries git's reason (`error.stderr`), such as "dubious ownership"
|
|
@@ -81,6 +82,8 @@ export function createGit({ root, run = defaultRun } = {}) {
|
|
|
81
82
|
}
|
|
82
83
|
return {
|
|
83
84
|
currentBranch: () => tryGit('rev-parse', '--abbrev-ref', 'HEAD')?.trim() || null,
|
|
85
|
+
rootCommit: () => tryGit('rev-list', '--max-parents=0', 'HEAD')?.trim().split(/\s+/)[0] || null,
|
|
86
|
+
originUrl: () => tryGit('config', '--get', 'remote.origin.url')?.trim() || null,
|
|
84
87
|
// null for an unknown ref; a folder git refuses is no unknown ref, so that throws (GIT_UNSAFE_REPOSITORY)
|
|
85
88
|
resolveCommit: ref => {
|
|
86
89
|
try { return git('rev-parse', '--verify', '--quiet', `${ref}^{commit}`).trim() || null; } catch (error) {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* classShape: Extracts inner functions (children) and extending classes (inheritors) for a class symbol.
|
|
3
|
+
*/
|
|
4
|
+
const fileFunctions = (file) => (Array.isArray(file?.functions) ? file.functions : []);
|
|
5
|
+
|
|
6
|
+
function isChildFunction(fn, symbol, startLine, endLine) {
|
|
7
|
+
if (fn.name === symbol) return false;
|
|
8
|
+
const loc = fn.loc || [fn.startLine, fn.endLine];
|
|
9
|
+
return loc[0] > startLine && loc[1] <= endLine;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function classShape(definitions, symbol, paths, factsOf) {
|
|
13
|
+
const isClass = definitions.some(({ path }) => factsOf(path)?.text && new RegExp(String.raw`\bclass\s+${symbol.replace(/[$]/g, '\\$')}\b`).test(factsOf(path).text));
|
|
14
|
+
if (!isClass) return {};
|
|
15
|
+
const children = definitions.filter(l => Number.isInteger(l.startLine)).flatMap(({ path, startLine, endLine }) =>
|
|
16
|
+
fileFunctions(factsOf(path)).filter(fn => isChildFunction(fn, symbol, startLine, endLine)).map(fn => ({ name: fn.name, path, line: (fn.loc || [fn.startLine])[0] })));
|
|
17
|
+
const extendsX = new RegExp(String.raw`\bclass\s+([\w$]+)[^{\n]*?(?:extends|:|\()\s*(?:[\w$]+\.)*` + symbol.replace(/[$]/g, '\\$') + String.raw`(?![\w$])`, 'g');
|
|
18
|
+
const inheritors = paths.flatMap(path => [...(factsOf(path)?.text ?? '').matchAll(extendsX)].filter(m => m[1] !== symbol).map(m => ({ name: m[1], path, line: factsOf(path).text.slice(0, m.index).split('\n').length })));
|
|
19
|
+
return { ...(children.length ? { children } : {}), ...(inheritors.length ? { inheritors } : {}) };
|
|
20
|
+
}
|