@getchomp/mcp 0.0.0-stage → 0.2.42
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 +15 -2
- package/dist/conventionsReference.d.ts +84 -0
- package/dist/conventionsReference.js +313 -0
- package/dist/designSystem/astScanner.d.ts +153 -0
- package/dist/designSystem/astScanner.js +2014 -0
- package/dist/designSystem/baseline.d.ts +65 -0
- package/dist/designSystem/baseline.js +136 -0
- package/dist/designSystem/color.d.ts +35 -0
- package/dist/designSystem/color.js +265 -0
- package/dist/designSystem/config.d.ts +183 -0
- package/dist/designSystem/config.js +469 -0
- package/dist/designSystem/contrast.d.ts +55 -0
- package/dist/designSystem/contrast.js +377 -0
- package/dist/designSystem/cssParser.d.ts +63 -0
- package/dist/designSystem/cssParser.js +469 -0
- package/dist/designSystem/merges.d.ts +57 -0
- package/dist/designSystem/merges.js +94 -0
- package/dist/designSystem/preprocessors.d.ts +46 -0
- package/dist/designSystem/preprocessors.js +1108 -0
- package/dist/designSystem/presentation.d.ts +45 -0
- package/dist/designSystem/presentation.js +796 -0
- package/dist/designSystem/styleVectors.d.ts +27 -0
- package/dist/designSystem/styleVectors.js +484 -0
- package/dist/designSystem/tokens.d.ts +39 -0
- package/dist/designSystem/tokens.js +409 -0
- package/dist/designSystem/topology.d.ts +64 -0
- package/dist/designSystem/topology.js +254 -0
- package/dist/designSystem/types.d.ts +857 -0
- package/dist/designSystem/types.js +113 -0
- package/dist/designSystem/typography.d.ts +25 -0
- package/dist/designSystem/typography.js +244 -0
- package/dist/designSystem/uiShapes.d.ts +74 -0
- package/dist/designSystem/uiShapes.js +285 -0
- package/dist/designSystem/valueClusters.d.ts +76 -0
- package/dist/designSystem/valueClusters.js +281 -0
- package/dist/designSystemPlugin.d.ts +321 -0
- package/dist/designSystemPlugin.js +4730 -0
- package/dist/enrichNodesPlugin.d.ts +160 -0
- package/dist/enrichNodesPlugin.js +957 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1298 -0
- package/dist/intelligence.d.ts +502 -0
- package/dist/intelligence.js +3058 -0
- package/dist/pluginRunner.d.ts +364 -0
- package/dist/pluginRunner.js +1096 -0
- package/dist/plugins/design-system/index.d.ts +14 -0
- package/dist/plugins/design-system/index.js +241 -0
- package/dist/plugins/enrich-nodes/index.d.ts +388 -0
- package/dist/plugins/enrich-nodes/index.js +697 -0
- package/dist/plugins/index.d.ts +15 -0
- package/dist/plugins/index.js +20 -0
- package/dist/plugins/local-shims/index.d.ts +121 -0
- package/dist/plugins/local-shims/index.js +237 -0
- package/dist/shimsPlugin.d.ts +134 -0
- package/dist/shimsPlugin.js +1392 -0
- package/package.json +38 -3
|
@@ -0,0 +1,1096 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/mcp/src/pluginRunner.ts
|
|
3
|
+
*
|
|
4
|
+
* Modular Chomp Plugin Runtime, Folder Discovery, Settings, Active Views & Projection Engine
|
|
5
|
+
* Enforces [PAT-DB-03], [PAT-DB-05], [PAT-MCP-03], [PAT-VIS-28], and [PAT-VIS-36].
|
|
6
|
+
*
|
|
7
|
+
* Architecture ("One Folder, Zero Plumbing Edits"):
|
|
8
|
+
* - Built-in plugins live in self-contained folders under `packages/mcp/src/plugins/<name>/index.ts`
|
|
9
|
+
* and are auto-discovered at startup (`discoverPluginsInDir`).
|
|
10
|
+
* - Repository-local plugin state & user settings live under `.chomp/plugins/<plugin.name>/`
|
|
11
|
+
* (e.g. `.chomp/plugins/local-shims/shims.json`, `.chomp/plugins/<name>/settings.json`).
|
|
12
|
+
* - Every plugin automatically receives:
|
|
13
|
+
* 1. Scoped `.chomp/plugins/<name>/` file I/O + SHA-256 `inputs` staleness hashes (`ctx.pluginDir`,
|
|
14
|
+
* `ctx.readPluginFile`, `ctx.writePluginFile`, `ctx.hashPluginFile`).
|
|
15
|
+
* 2. Declarative `settingsSchema` resolved into `ctx.settings` and rendered automatically in the
|
|
16
|
+
* Explorer Settings drawer (`GET/PUT /api/plugins/:name/settings`).
|
|
17
|
+
* 3. Active View array controls via both declarative Spotlight lenses (`summary.views[].highlightNodeIds`)
|
|
18
|
+
* and imperative `ctx.setActiveView({ highlightNodeIds, ... })` writing `.chomp/current_view.json`.
|
|
19
|
+
* 4. Generic `PluginPresentation` v1 sections rendered in the HUD, Package Inspector, and Node Inspector.
|
|
20
|
+
* 5. Optional `projectGraph`, `mcpTools`, and `formatCliSummary` hooks wired automatically across
|
|
21
|
+
* CLI, Explorer UI, and MCP server with zero edits outside the plugin's own folder.
|
|
22
|
+
*/
|
|
23
|
+
import { execSync } from "node:child_process";
|
|
24
|
+
import { createHash } from "node:crypto";
|
|
25
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { basename, dirname, relative, resolve } from "node:path";
|
|
27
|
+
import { pathToFileURL } from "node:url";
|
|
28
|
+
import { CORE_EXTRACTOR_VERSION, PLUGIN_PRESENTATION_PAYLOAD_KEY, analyzeTarget, isValidEnvVarName, resolvePluginSettings, sanitizePluginPresentation, } from "@getchomp/core";
|
|
29
|
+
import { createSQLiteStorage, } from "@getchomp/db";
|
|
30
|
+
import { buildActiveViewUrl, resolveViewTargetAltitude, } from "./intelligence.js";
|
|
31
|
+
export const PLUGINS_STATE_DIR_REL = ".chomp/plugins";
|
|
32
|
+
/** Identity helper providing full TypeScript inference when authoring a self-contained plugin folder. */
|
|
33
|
+
export function defineChompPlugin(plugin) {
|
|
34
|
+
return plugin;
|
|
35
|
+
}
|
|
36
|
+
const IGNORED_DIRS = new Set([
|
|
37
|
+
".git",
|
|
38
|
+
".chomp",
|
|
39
|
+
"node_modules",
|
|
40
|
+
"dist",
|
|
41
|
+
"build",
|
|
42
|
+
"out",
|
|
43
|
+
".next",
|
|
44
|
+
".nuxt",
|
|
45
|
+
".output",
|
|
46
|
+
".svelte-kit",
|
|
47
|
+
".astro",
|
|
48
|
+
".turbo",
|
|
49
|
+
"storybook-static",
|
|
50
|
+
"coverage",
|
|
51
|
+
"vendor",
|
|
52
|
+
"migrations",
|
|
53
|
+
"upgrades",
|
|
54
|
+
]);
|
|
55
|
+
const pluginRegistry = new Map();
|
|
56
|
+
const pluginPersistQueues = new Map();
|
|
57
|
+
async function serializePluginPersist(key, fn) {
|
|
58
|
+
const prev = pluginPersistQueues.get(key) ?? Promise.resolve();
|
|
59
|
+
let release;
|
|
60
|
+
const next = new Promise((res) => {
|
|
61
|
+
release = res;
|
|
62
|
+
});
|
|
63
|
+
const chained = prev.catch(() => undefined).then(() => next);
|
|
64
|
+
pluginPersistQueues.set(key, chained);
|
|
65
|
+
try {
|
|
66
|
+
await prev.catch(() => undefined);
|
|
67
|
+
return await fn();
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
release();
|
|
71
|
+
if (pluginPersistQueues.get(key) === chained) {
|
|
72
|
+
pluginPersistQueues.delete(key);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Resolves a plugin by name or merges bare plugin instances with their registered
|
|
78
|
+
* module metadata (`settingsSchema`, `scanRepoFiles`, `defaultEnabled`, etc.) so direct
|
|
79
|
+
* callers like `manageLocalShims` or `auditDesignSystem` always honor persisted settings.
|
|
80
|
+
*/
|
|
81
|
+
export function resolveEffectivePlugin(pluginOrName) {
|
|
82
|
+
if (typeof pluginOrName === "string") {
|
|
83
|
+
return getChompPlugin(pluginOrName);
|
|
84
|
+
}
|
|
85
|
+
const registered = getChompPlugin(pluginOrName.name);
|
|
86
|
+
if (!registered || registered === pluginOrName) {
|
|
87
|
+
return pluginOrName;
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
...registered,
|
|
91
|
+
...pluginOrName,
|
|
92
|
+
displayName: pluginOrName.displayName ?? registered.displayName,
|
|
93
|
+
order: pluginOrName.order ?? registered.order,
|
|
94
|
+
defaultEnabled: pluginOrName.defaultEnabled ?? registered.defaultEnabled,
|
|
95
|
+
legacySources: pluginOrName.legacySources ?? registered.legacySources,
|
|
96
|
+
inspectorScopes: pluginOrName.inspectorScopes ?? registered.inspectorScopes,
|
|
97
|
+
settingsSchema: pluginOrName.settingsSchema ?? registered.settingsSchema,
|
|
98
|
+
scanRepoFiles: pluginOrName.scanRepoFiles ?? registered.scanRepoFiles,
|
|
99
|
+
mcpTools: pluginOrName.mcpTools ?? registered.mcpTools,
|
|
100
|
+
formatCliSummary: pluginOrName.formatCliSummary ?? registered.formatCliSummary,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** Max serialized size of one overlay's presentation; lowest-priority sections are dropped beyond it. */
|
|
104
|
+
export const MAX_PRESENTATION_BYTES = 120_000;
|
|
105
|
+
function toPosixPath(p) {
|
|
106
|
+
return p.replace(/\\/g, "/");
|
|
107
|
+
}
|
|
108
|
+
function isObj(v) {
|
|
109
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
110
|
+
}
|
|
111
|
+
function sanitizePluginDirSegment(pluginName) {
|
|
112
|
+
return pluginName.trim().toLowerCase().replace(/^plugin:/i, "").replace(/[^a-z0-9._-]/g, "-");
|
|
113
|
+
}
|
|
114
|
+
export function getPluginStateDirRel(pluginName) {
|
|
115
|
+
return `${PLUGINS_STATE_DIR_REL}/${sanitizePluginDirSegment(pluginName)}`;
|
|
116
|
+
}
|
|
117
|
+
export function getPluginStateDir(repoPath, pluginName) {
|
|
118
|
+
return resolve(repoPath, ".chomp", "plugins", sanitizePluginDirSegment(pluginName));
|
|
119
|
+
}
|
|
120
|
+
export function getPluginSettingsPath(repoPath, pluginName) {
|
|
121
|
+
return resolve(getPluginStateDir(repoPath, pluginName), "settings.json");
|
|
122
|
+
}
|
|
123
|
+
export const PLUGIN_LAST_RUN_FILENAME = "last-run.json";
|
|
124
|
+
export function getPluginLastRunPath(repoPath, pluginName) {
|
|
125
|
+
return resolve(getPluginStateDir(repoPath, pluginName), PLUGIN_LAST_RUN_FILENAME);
|
|
126
|
+
}
|
|
127
|
+
export function readPluginLastRun(repoPath, pluginName) {
|
|
128
|
+
if (!repoPath)
|
|
129
|
+
return null;
|
|
130
|
+
const filePath = getPluginLastRunPath(repoPath, pluginName);
|
|
131
|
+
if (!existsSync(filePath))
|
|
132
|
+
return null;
|
|
133
|
+
try {
|
|
134
|
+
const parsed = JSON.parse(readFileSync(filePath, "utf8"));
|
|
135
|
+
if (!isObj(parsed))
|
|
136
|
+
return null;
|
|
137
|
+
const status = parsed.status === "error" ? "error" : parsed.status === "ok" ? "ok" : null;
|
|
138
|
+
if (!status)
|
|
139
|
+
return null;
|
|
140
|
+
if (typeof parsed.startedAt !== "string" || typeof parsed.finishedAt !== "string")
|
|
141
|
+
return null;
|
|
142
|
+
return {
|
|
143
|
+
pluginName: typeof parsed.pluginName === "string" ? parsed.pluginName : pluginName,
|
|
144
|
+
pluginVersion: typeof parsed.pluginVersion === "string" ? parsed.pluginVersion : "0.0.0",
|
|
145
|
+
layer: typeof parsed.layer === "string" ? parsed.layer : "",
|
|
146
|
+
status,
|
|
147
|
+
...(typeof parsed.runId === "string" ? { runId: parsed.runId } : {}),
|
|
148
|
+
startedAt: parsed.startedAt,
|
|
149
|
+
finishedAt: parsed.finishedAt,
|
|
150
|
+
durationMs: typeof parsed.durationMs === "number" && Number.isFinite(parsed.durationMs) ? parsed.durationMs : 0,
|
|
151
|
+
...(typeof parsed.acceptedFileCount === "number" ? { acceptedFileCount: parsed.acceptedFileCount } : {}),
|
|
152
|
+
...(typeof parsed.overlayCount === "number" ? { overlayCount: parsed.overlayCount } : {}),
|
|
153
|
+
presentationWarnings: Array.isArray(parsed.presentationWarnings)
|
|
154
|
+
? parsed.presentationWarnings.filter((w) => typeof w === "string")
|
|
155
|
+
: [],
|
|
156
|
+
...(typeof parsed.error === "string" && parsed.error ? { error: parsed.error } : {}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
export function writePluginLastRun(repoPath, record) {
|
|
164
|
+
try {
|
|
165
|
+
const filePath = getPluginLastRunPath(repoPath, record.pluginName);
|
|
166
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
167
|
+
writeFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`, "utf8");
|
|
168
|
+
return filePath;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export function loadPluginSettings(repoPath, pluginOrName) {
|
|
175
|
+
const plugin = resolveEffectivePlugin(pluginOrName);
|
|
176
|
+
if (!plugin)
|
|
177
|
+
return {};
|
|
178
|
+
let raw = {};
|
|
179
|
+
if (repoPath) {
|
|
180
|
+
const settingsPath = getPluginSettingsPath(repoPath, plugin.name);
|
|
181
|
+
if (existsSync(settingsPath)) {
|
|
182
|
+
try {
|
|
183
|
+
raw = JSON.parse(readFileSync(settingsPath, "utf8"));
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
raw = {};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return resolvePluginSettings(plugin.settingsSchema, raw);
|
|
191
|
+
}
|
|
192
|
+
export function savePluginSettings(repoPath, pluginOrName, patch) {
|
|
193
|
+
const plugin = resolveEffectivePlugin(pluginOrName);
|
|
194
|
+
if (!plugin) {
|
|
195
|
+
throw new Error(`Unknown Chomp plugin '${String(pluginOrName)}'.`);
|
|
196
|
+
}
|
|
197
|
+
const settingsPath = getPluginSettingsPath(repoPath, plugin.name);
|
|
198
|
+
let currentRaw = {};
|
|
199
|
+
if (existsSync(settingsPath)) {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = JSON.parse(readFileSync(settingsPath, "utf8"));
|
|
202
|
+
if (isObj(parsed))
|
|
203
|
+
currentRaw = parsed;
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
currentRaw = {};
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const merged = { ...currentRaw, ...(isObj(patch) ? patch : {}) };
|
|
210
|
+
const resolved = resolvePluginSettings(plugin.settingsSchema, merged);
|
|
211
|
+
mkdirSync(dirname(settingsPath), { recursive: true });
|
|
212
|
+
writeFileSync(settingsPath, `${JSON.stringify(resolved, null, 2)}\n`, "utf8");
|
|
213
|
+
return resolved;
|
|
214
|
+
}
|
|
215
|
+
export function getPluginMcpToolSummaries(plugin) {
|
|
216
|
+
return (plugin.mcpTools ?? []).map((t) => ({
|
|
217
|
+
name: t.name,
|
|
218
|
+
description: t.description,
|
|
219
|
+
}));
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Resolves a secret from `env` (`process.env` by default) via a `kind: "env"` setting key
|
|
223
|
+
* or direct environment-variable identifier — never reading raw secrets from `settings.json`.
|
|
224
|
+
*/
|
|
225
|
+
export function resolvePluginSecret(plugin, settings, settingKeyOrEnvName, env = process.env) {
|
|
226
|
+
const field = plugin.settingsSchema?.find((f) => f.key === settingKeyOrEnvName);
|
|
227
|
+
const envVarName = field && field.kind === "env"
|
|
228
|
+
? String(settings[field.key] ?? field.defaultValue ?? "").trim()
|
|
229
|
+
: settingKeyOrEnvName.trim();
|
|
230
|
+
if (!envVarName || !isValidEnvVarName(envVarName))
|
|
231
|
+
return undefined;
|
|
232
|
+
const raw = env[envVarName];
|
|
233
|
+
return typeof raw === "string" && raw.trim() ? raw.trim() : undefined;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Computes boolean presence status (`true` = set in `env`, `false` = unset) for each `kind: "env"`
|
|
237
|
+
* field in `plugin.settingsSchema`. Safe to expose to the UI because secret values are never included.
|
|
238
|
+
*/
|
|
239
|
+
export function getPluginEnvStatus(plugin, settings, env = process.env) {
|
|
240
|
+
const envFields = (plugin.settingsSchema ?? []).filter((f) => f.kind === "env");
|
|
241
|
+
if (envFields.length === 0)
|
|
242
|
+
return undefined;
|
|
243
|
+
const status = {};
|
|
244
|
+
for (const field of envFields) {
|
|
245
|
+
status[field.key] = Boolean(resolvePluginSecret(plugin, settings, field.key, env));
|
|
246
|
+
}
|
|
247
|
+
return status;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Resolves the current Git branch name for a repository or worktree (handling `.git` pointer files).
|
|
251
|
+
*/
|
|
252
|
+
export function resolveRepoGitBranch(repoPath, fallbackBranch) {
|
|
253
|
+
try {
|
|
254
|
+
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
|
|
255
|
+
cwd: repoPath,
|
|
256
|
+
encoding: "utf8",
|
|
257
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
258
|
+
}).trim();
|
|
259
|
+
if (branch && branch !== "HEAD") {
|
|
260
|
+
return branch;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
// Fallback to reading .git/HEAD directly below
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
const dotGitPath = resolve(repoPath, ".git");
|
|
268
|
+
if (existsSync(dotGitPath)) {
|
|
269
|
+
let gitDir = dotGitPath;
|
|
270
|
+
const stat = statSync(dotGitPath);
|
|
271
|
+
if (stat.isFile()) {
|
|
272
|
+
const ptr = readFileSync(dotGitPath, "utf8").trim();
|
|
273
|
+
const m = ptr.match(/^gitdir:\s*(.+)$/i);
|
|
274
|
+
if (m) {
|
|
275
|
+
gitDir = resolve(repoPath, m[1].trim());
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const headPath = resolve(gitDir, "HEAD");
|
|
279
|
+
if (existsSync(headPath)) {
|
|
280
|
+
const headContent = readFileSync(headPath, "utf8").trim();
|
|
281
|
+
if (headContent.startsWith("ref: refs/heads/")) {
|
|
282
|
+
return headContent.replace("ref: refs/heads/", "").trim();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// Ignore and fall back
|
|
289
|
+
}
|
|
290
|
+
return fallbackBranch;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Resolves the canonical repository name for `inputPath`, unwrapping Git worktree
|
|
294
|
+
* `.git` pointer files (`gitdir:` + `commondir`) back to the parent repository root.
|
|
295
|
+
*/
|
|
296
|
+
export function resolveRepoName(inputPath) {
|
|
297
|
+
const abs = resolve(inputPath);
|
|
298
|
+
let dir = abs;
|
|
299
|
+
try {
|
|
300
|
+
if (existsSync(abs) && !statSync(abs).isDirectory()) {
|
|
301
|
+
dir = dirname(abs);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
// Path may not exist yet; fall back to basename(abs)
|
|
306
|
+
}
|
|
307
|
+
const posixDir = dir.replace(/\\/g, "/");
|
|
308
|
+
const fixtureMatch = /\/fixtures\/(?:cloned-repos|test-repos)\/([^/]+)(?:\/|$)/.exec(posixDir);
|
|
309
|
+
if (fixtureMatch) {
|
|
310
|
+
const matchEnd = posixDir.indexOf(fixtureMatch[0]) + fixtureMatch[0].replace(/\/$/, "").length;
|
|
311
|
+
const fixtureRoot = dir.slice(0, matchEnd);
|
|
312
|
+
if (!existsSync(resolve(fixtureRoot, ".git"))) {
|
|
313
|
+
return fixtureMatch[1];
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (existsSync(resolve(dir, ".chomp")) && !existsSync(resolve(dir, ".git"))) {
|
|
317
|
+
return basename(dir);
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
let cur = dir;
|
|
321
|
+
let gitEntryPath;
|
|
322
|
+
let gitOwnerDir;
|
|
323
|
+
for (let i = 0; i < 8; i++) {
|
|
324
|
+
const candidate = resolve(cur, ".git");
|
|
325
|
+
if (existsSync(candidate)) {
|
|
326
|
+
gitEntryPath = candidate;
|
|
327
|
+
gitOwnerDir = cur;
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
const parent = dirname(cur);
|
|
331
|
+
if (parent === cur)
|
|
332
|
+
break;
|
|
333
|
+
cur = parent;
|
|
334
|
+
}
|
|
335
|
+
if (gitEntryPath && gitOwnerDir) {
|
|
336
|
+
const stat = statSync(gitEntryPath);
|
|
337
|
+
if (stat.isFile()) {
|
|
338
|
+
const ptr = readFileSync(gitEntryPath, "utf8").trim();
|
|
339
|
+
const match = /^gitdir:\s*(.+)$/i.exec(ptr);
|
|
340
|
+
if (match) {
|
|
341
|
+
const gitDir = resolve(gitOwnerDir, match[1].trim());
|
|
342
|
+
const commonDirFile = resolve(gitDir, "commondir");
|
|
343
|
+
if (existsSync(commonDirFile)) {
|
|
344
|
+
const relCommon = readFileSync(commonDirFile, "utf8").trim();
|
|
345
|
+
if (relCommon) {
|
|
346
|
+
const commonDir = resolve(gitDir, relCommon);
|
|
347
|
+
if (basename(commonDir) === ".git") {
|
|
348
|
+
return basename(dirname(commonDir));
|
|
349
|
+
}
|
|
350
|
+
const cleanBare = basename(commonDir).replace(/\.git$/i, "");
|
|
351
|
+
if (cleanBare)
|
|
352
|
+
return cleanBare;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const normalizedGitDir = gitDir.replace(/\\/g, "/");
|
|
356
|
+
const wtMatch = /^(.*)\/\.git\/worktrees\/[^/]+\/?$/.exec(normalizedGitDir);
|
|
357
|
+
if (wtMatch && wtMatch[1]) {
|
|
358
|
+
return basename(wtMatch[1]);
|
|
359
|
+
}
|
|
360
|
+
return basename(gitOwnerDir);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (stat.isDirectory()) {
|
|
364
|
+
if (gitOwnerDir !== dir &&
|
|
365
|
+
existsSync(resolve(dir, "package.json")) &&
|
|
366
|
+
!dir.startsWith(resolve(gitOwnerDir, "packages") + "/") &&
|
|
367
|
+
!dir.startsWith(resolve(gitOwnerDir, "apps") + "/")) {
|
|
368
|
+
return basename(dir);
|
|
369
|
+
}
|
|
370
|
+
if (!posixDir.includes("/.chomp/")) {
|
|
371
|
+
return basename(gitOwnerDir);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
// Fall back to basename(dir)
|
|
378
|
+
}
|
|
379
|
+
return basename(dir);
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Resolves the base URL of the local Chomp Visualizer server (`chomp ui`) for Active View deep-links.
|
|
383
|
+
*/
|
|
384
|
+
export function resolveActiveUiBaseUrl(repoPath) {
|
|
385
|
+
if (process.env.CHOMP_UI_URL && process.env.CHOMP_UI_URL.trim()) {
|
|
386
|
+
return process.env.CHOMP_UI_URL.trim().replace(/\/+$/, "");
|
|
387
|
+
}
|
|
388
|
+
try {
|
|
389
|
+
const serverMetaPath = resolve(repoPath, ".chomp", "ui_server.json");
|
|
390
|
+
if (existsSync(serverMetaPath)) {
|
|
391
|
+
const parsed = JSON.parse(readFileSync(serverMetaPath, "utf8"));
|
|
392
|
+
if (typeof parsed?.url === "string" && parsed.url.trim()) {
|
|
393
|
+
return parsed.url.trim().replace(/\/+$/, "");
|
|
394
|
+
}
|
|
395
|
+
if (typeof parsed?.port === "number" && Number.isFinite(parsed.port)) {
|
|
396
|
+
return `http://localhost:${parsed.port}`;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
// Fall back to default port
|
|
402
|
+
}
|
|
403
|
+
if (process.env.CHOMP_UI_PORT && process.env.CHOMP_UI_PORT.trim()) {
|
|
404
|
+
return `http://localhost:${process.env.CHOMP_UI_PORT.trim()}`;
|
|
405
|
+
}
|
|
406
|
+
return "http://localhost:5555";
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Writes `.chomp/current_view.json` on behalf of a plugin (`[PAT-MCP-03]`, `[PAT-VIS-28]`),
|
|
410
|
+
* resolving topological altitude and deep-link URL automatically.
|
|
411
|
+
*/
|
|
412
|
+
export function writePluginActiveView(options, spec) {
|
|
413
|
+
const highlightIds = Array.from(new Set((spec.highlightNodeIds ?? []).filter((id) => typeof id === "string" && id.trim().length > 0)));
|
|
414
|
+
if (highlightIds.length === 0)
|
|
415
|
+
return null;
|
|
416
|
+
const repoPath = resolve(options.repoPath);
|
|
417
|
+
const repoName = options.repoName ?? resolveRepoName(repoPath);
|
|
418
|
+
const repoId = options.repoId ?? repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
419
|
+
const branchName = resolveRepoGitBranch(repoPath, spec.graph?.branchName);
|
|
420
|
+
let viewLevel = spec.viewLevel ?? (spec.packageName ? "package" : "system");
|
|
421
|
+
let packageName = spec.packageName;
|
|
422
|
+
if (spec.graph) {
|
|
423
|
+
const altitude = resolveViewTargetAltitude(spec.graph, highlightIds, spec.viewLevel ?? (spec.packageName ? "package" : undefined), spec.packageName);
|
|
424
|
+
viewLevel = altitude.viewLevel;
|
|
425
|
+
packageName = altitude.packageName;
|
|
426
|
+
}
|
|
427
|
+
const viewUrl = buildActiveViewUrl({
|
|
428
|
+
baseUrl: resolveActiveUiBaseUrl(repoPath),
|
|
429
|
+
viewLevel,
|
|
430
|
+
packageName,
|
|
431
|
+
});
|
|
432
|
+
const viewPath = resolve(repoPath, ".chomp", "current_view.json");
|
|
433
|
+
mkdirSync(dirname(viewPath), { recursive: true });
|
|
434
|
+
writeFileSync(viewPath, `${JSON.stringify({
|
|
435
|
+
repoId,
|
|
436
|
+
repoName,
|
|
437
|
+
...(branchName ? { branchName } : {}),
|
|
438
|
+
createdAt: new Date().toISOString(),
|
|
439
|
+
viewLevel,
|
|
440
|
+
...(packageName ? { packageName } : {}),
|
|
441
|
+
viewUrl,
|
|
442
|
+
title: spec.title,
|
|
443
|
+
description: spec.description,
|
|
444
|
+
highlightNodeIds: highlightIds,
|
|
445
|
+
...(spec.nodeAnnotations && Object.keys(spec.nodeAnnotations).length > 0
|
|
446
|
+
? { nodeAnnotations: spec.nodeAnnotations }
|
|
447
|
+
: {}),
|
|
448
|
+
layer: options.layer,
|
|
449
|
+
source: options.pluginName,
|
|
450
|
+
...(spec.pills && spec.pills.length > 0 ? { pills: spec.pills } : {}),
|
|
451
|
+
...(spec.metrics && Object.keys(spec.metrics).length > 0 ? { metrics: spec.metrics } : {}),
|
|
452
|
+
}, null, 2)}\n`, "utf8");
|
|
453
|
+
return viewUrl;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Enforces the Plugin Presentation Contract on every overlay a plugin produced: the presentation is
|
|
457
|
+
* sanitized (bounded, unknown blocks dropped) and size-capped. A presentation that is not usable is
|
|
458
|
+
* removed so the UI falls back to the generic payload view instead of failing.
|
|
459
|
+
*/
|
|
460
|
+
export function enforcePresentationContract(overlays, pluginName) {
|
|
461
|
+
const warnings = [];
|
|
462
|
+
const out = overlays.map((ov) => {
|
|
463
|
+
const raw = ov.payload?.[PLUGIN_PRESENTATION_PAYLOAD_KEY];
|
|
464
|
+
if (raw === undefined)
|
|
465
|
+
return ov;
|
|
466
|
+
const { presentation, warnings: w } = sanitizePluginPresentation(raw);
|
|
467
|
+
for (const msg of w)
|
|
468
|
+
warnings.push(`${pluginName}:${ov.entityId}: ${msg}`);
|
|
469
|
+
const { [PLUGIN_PRESENTATION_PAYLOAD_KEY]: _drop, ...rest } = ov.payload ?? {};
|
|
470
|
+
if (!presentation)
|
|
471
|
+
return { ...ov, payload: rest };
|
|
472
|
+
let bounded = presentation;
|
|
473
|
+
while (JSON.stringify(bounded).length > MAX_PRESENTATION_BYTES &&
|
|
474
|
+
bounded.sections.length > 1) {
|
|
475
|
+
const dropIdx = bounded.sections.reduce((worst, sec, i, arr) => ((sec.priority ?? 100) >= (arr[worst].priority ?? 100) ? i : worst), 0);
|
|
476
|
+
warnings.push(`${pluginName}:${ov.entityId}: presentation exceeded ${MAX_PRESENTATION_BYTES} bytes; dropped section "${bounded.sections[dropIdx].id}"`);
|
|
477
|
+
bounded = {
|
|
478
|
+
...bounded,
|
|
479
|
+
sections: bounded.sections.filter((_, i) => i !== dropIdx),
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
return { ...ov, payload: { ...rest, [PLUGIN_PRESENTATION_PAYLOAD_KEY]: bounded } };
|
|
483
|
+
});
|
|
484
|
+
return { overlays: out, warnings };
|
|
485
|
+
}
|
|
486
|
+
export function registerChompPlugin(plugin) {
|
|
487
|
+
pluginRegistry.set(plugin.name.trim().toLowerCase(), plugin);
|
|
488
|
+
}
|
|
489
|
+
export function unregisterChompPlugin(name) {
|
|
490
|
+
const key = name.trim().toLowerCase().replace(/^plugin:/i, "");
|
|
491
|
+
return pluginRegistry.delete(key);
|
|
492
|
+
}
|
|
493
|
+
export function getChompPlugin(name) {
|
|
494
|
+
const key = name.trim().toLowerCase().replace(/^plugin:/i, "");
|
|
495
|
+
return pluginRegistry.get(key);
|
|
496
|
+
}
|
|
497
|
+
export function listChompPlugins() {
|
|
498
|
+
return [...pluginRegistry.values()].sort((a, b) => (a.order ?? 100) - (b.order ?? 100) ||
|
|
499
|
+
(a.displayName ?? a.name).localeCompare(b.displayName ?? b.name));
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Returns default `overlayLayers` visibility map combining core layers and all registered plugins.
|
|
503
|
+
*/
|
|
504
|
+
export function getRegisteredPluginDefaultLayers() {
|
|
505
|
+
const out = {};
|
|
506
|
+
for (const plugin of pluginRegistry.values()) {
|
|
507
|
+
out[plugin.layer] = plugin.defaultEnabled ?? true;
|
|
508
|
+
}
|
|
509
|
+
return out;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Checks whether a plugin overlay alters structural layout (`structureFp`) via registered `isStructuralOverlay` hooks.
|
|
513
|
+
*/
|
|
514
|
+
export function isRegisteredStructuralPluginOverlay(overlay) {
|
|
515
|
+
for (const plugin of pluginRegistry.values()) {
|
|
516
|
+
if (!plugin.isStructuralOverlay)
|
|
517
|
+
continue;
|
|
518
|
+
if (plugin.layer === overlay.layer || plugin.name === overlay.source) {
|
|
519
|
+
if (plugin.isStructuralOverlay(overlay))
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return false;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Reads `.chomp/rules.json#overlayLayers` from `repoPath` when not explicitly supplied.
|
|
527
|
+
*/
|
|
528
|
+
export function readRepoOverlayLayerToggles(repoPath) {
|
|
529
|
+
if (!repoPath)
|
|
530
|
+
return {};
|
|
531
|
+
try {
|
|
532
|
+
const rulesPath = resolve(repoPath, ".chomp", "rules.json");
|
|
533
|
+
if (!existsSync(rulesPath))
|
|
534
|
+
return {};
|
|
535
|
+
const parsed = JSON.parse(readFileSync(rulesPath, "utf8"));
|
|
536
|
+
if (isObj(parsed?.overlayLayers)) {
|
|
537
|
+
const out = {};
|
|
538
|
+
for (const [k, v] of Object.entries(parsed.overlayLayers)) {
|
|
539
|
+
if (typeof v === "boolean")
|
|
540
|
+
out[k] = v;
|
|
541
|
+
}
|
|
542
|
+
return out;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
// Ignore malformed rules.json
|
|
547
|
+
}
|
|
548
|
+
return {};
|
|
549
|
+
}
|
|
550
|
+
export function isPluginLayerEnabled(plugin, overlayLayers) {
|
|
551
|
+
const defaultEnabled = plugin.defaultEnabled ?? true;
|
|
552
|
+
if (!overlayLayers)
|
|
553
|
+
return defaultEnabled;
|
|
554
|
+
if (plugin.layer in overlayLayers) {
|
|
555
|
+
return overlayLayers[plugin.layer] !== false;
|
|
556
|
+
}
|
|
557
|
+
return defaultEnabled;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Runs every enabled registered plugin's `projectGraph` hook in deterministic registration order.
|
|
561
|
+
* Eliminates plugin-specific projection branches from `ui.ts`, `health.ts`, and `mcp/src/index.ts`.
|
|
562
|
+
*/
|
|
563
|
+
export function applyActivePluginProjections(graph, options) {
|
|
564
|
+
const repoPath = options?.repoPath ? resolve(options.repoPath) : undefined;
|
|
565
|
+
const overlayLayers = options?.overlayLayers ?? readRepoOverlayLayerToggles(repoPath);
|
|
566
|
+
const overlays = options?.overlays ?? [];
|
|
567
|
+
const readRepoFile = (relPath) => {
|
|
568
|
+
const norm = toPosixPath(relPath).replace(/^\/+/, "");
|
|
569
|
+
if (options?.readRepoFileOverride) {
|
|
570
|
+
return options.readRepoFileOverride(norm);
|
|
571
|
+
}
|
|
572
|
+
if (!repoPath)
|
|
573
|
+
return null;
|
|
574
|
+
const abs = resolve(repoPath, norm);
|
|
575
|
+
if (!existsSync(abs))
|
|
576
|
+
return null;
|
|
577
|
+
try {
|
|
578
|
+
return readFileSync(abs, "utf8");
|
|
579
|
+
}
|
|
580
|
+
catch {
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
let current = graph;
|
|
585
|
+
for (const plugin of pluginRegistry.values()) {
|
|
586
|
+
if (!plugin.projectGraph)
|
|
587
|
+
continue;
|
|
588
|
+
if (!isPluginLayerEnabled(plugin, overlayLayers))
|
|
589
|
+
continue;
|
|
590
|
+
const settings = loadPluginSettings(repoPath, plugin);
|
|
591
|
+
const pluginDirRel = getPluginStateDirRel(plugin.name);
|
|
592
|
+
const readPluginFile = (relPath) => {
|
|
593
|
+
const clean = toPosixPath(relPath).replace(/^\/+/, "");
|
|
594
|
+
return readRepoFile(`${pluginDirRel}/${clean}`);
|
|
595
|
+
};
|
|
596
|
+
const scopedOverlays = overlays.filter((o) => o.layer === plugin.layer || (o.source && o.source === plugin.name));
|
|
597
|
+
current = plugin.projectGraph({
|
|
598
|
+
graph: current,
|
|
599
|
+
overlays: scopedOverlays,
|
|
600
|
+
repoPath,
|
|
601
|
+
settings,
|
|
602
|
+
readRepoFile,
|
|
603
|
+
readPluginFile,
|
|
604
|
+
resolveSecret: (key) => resolvePluginSecret(plugin, settings, key),
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
return current;
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Auto-discovers and registers self-contained plugin folders inside `pluginsRootDir`.
|
|
611
|
+
* Each subdirectory `<pluginsRootDir>/<folder>/` is checked for `index.js`, `index.mjs`, or `index.ts`.
|
|
612
|
+
*/
|
|
613
|
+
export async function discoverPluginsInDir(pluginsRootDir) {
|
|
614
|
+
if (!existsSync(pluginsRootDir))
|
|
615
|
+
return [];
|
|
616
|
+
let entries;
|
|
617
|
+
try {
|
|
618
|
+
entries = readdirSync(pluginsRootDir, { withFileTypes: true });
|
|
619
|
+
}
|
|
620
|
+
catch {
|
|
621
|
+
return [];
|
|
622
|
+
}
|
|
623
|
+
const discovered = [];
|
|
624
|
+
const subdirs = entries
|
|
625
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith(".") && !e.name.startsWith("_"))
|
|
626
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
627
|
+
for (const dir of subdirs) {
|
|
628
|
+
const folderPath = resolve(pluginsRootDir, dir.name);
|
|
629
|
+
const candidates = ["index.js", "index.mjs", "index.ts", "plugin.mjs", "plugin.js"];
|
|
630
|
+
const entryName = candidates.find((c) => existsSync(resolve(folderPath, c)));
|
|
631
|
+
if (!entryName)
|
|
632
|
+
continue;
|
|
633
|
+
const entryPath = resolve(folderPath, entryName);
|
|
634
|
+
const mod = await import(pathToFileURL(entryPath).href);
|
|
635
|
+
const candidate = mod?.default ?? mod?.plugin;
|
|
636
|
+
if (isObj(candidate) &&
|
|
637
|
+
typeof candidate.name === "string" &&
|
|
638
|
+
typeof candidate.layer === "string" &&
|
|
639
|
+
typeof candidate.accepts === "function" &&
|
|
640
|
+
typeof candidate.extract === "function") {
|
|
641
|
+
const typed = candidate;
|
|
642
|
+
registerChompPlugin(typed);
|
|
643
|
+
discovered.push(typed);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return discovered;
|
|
647
|
+
}
|
|
648
|
+
function matchesExcludedWorkspace(relPosixPath, excludeWorkspaces) {
|
|
649
|
+
if (!excludeWorkspaces || excludeWorkspaces.length === 0)
|
|
650
|
+
return false;
|
|
651
|
+
for (const rawPattern of excludeWorkspaces) {
|
|
652
|
+
const clean = toPosixPath(rawPattern.trim()).replace(/\/+\*?$/, "");
|
|
653
|
+
if (!clean)
|
|
654
|
+
continue;
|
|
655
|
+
if (relPosixPath === clean || relPosixPath.startsWith(`${clean}/`)) {
|
|
656
|
+
return true;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Walks `repoPath` deterministically (plus `.chomp/plugins/**`) and returns sorted repo-relative POSIX file paths.
|
|
663
|
+
*/
|
|
664
|
+
export function collectPluginRepoFiles(repoPath, excludeWorkspaces) {
|
|
665
|
+
const absRoot = resolve(repoPath);
|
|
666
|
+
if (!existsSync(absRoot))
|
|
667
|
+
return [];
|
|
668
|
+
const stat = statSync(absRoot);
|
|
669
|
+
if (!stat.isDirectory()) {
|
|
670
|
+
return [basename(absRoot)];
|
|
671
|
+
}
|
|
672
|
+
const isInsideFixtures = toPosixPath(absRoot).includes("/fixtures/test-repos/") ||
|
|
673
|
+
toPosixPath(absRoot).includes("/fixtures/cloned-repos/");
|
|
674
|
+
const results = [];
|
|
675
|
+
const walk = (dir, allowDotChompPlugins = false) => {
|
|
676
|
+
let entries;
|
|
677
|
+
try {
|
|
678
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
for (const entry of entries) {
|
|
684
|
+
if (!allowDotChompPlugins) {
|
|
685
|
+
if (IGNORED_DIRS.has(entry.name))
|
|
686
|
+
continue;
|
|
687
|
+
if (entry.name.startsWith(".") && entry.name !== ".storybook")
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
else if (entry.name.startsWith(".")) {
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const fullPath = resolve(dir, entry.name);
|
|
694
|
+
const relPath = toPosixPath(relative(absRoot, fullPath));
|
|
695
|
+
if (!relPath)
|
|
696
|
+
continue;
|
|
697
|
+
if (!allowDotChompPlugins) {
|
|
698
|
+
if (!isInsideFixtures &&
|
|
699
|
+
(relPath === "fixtures" || relPath.startsWith("fixtures/"))) {
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
if (matchesExcludedWorkspace(relPath, excludeWorkspaces)) {
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (entry.isDirectory()) {
|
|
707
|
+
walk(fullPath, allowDotChompPlugins);
|
|
708
|
+
}
|
|
709
|
+
else if (entry.isFile()) {
|
|
710
|
+
if (entry.name.endsWith(".min.js") || entry.name.endsWith(".min.css")) {
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
if (allowDotChompPlugins && entry.name === PLUGIN_LAST_RUN_FILENAME) {
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
results.push(relPath);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
walk(absRoot, false);
|
|
721
|
+
// Automatically include all per-plugin state & manifest files under `.chomp/plugins/**`
|
|
722
|
+
const pluginsStateDir = resolve(absRoot, ".chomp", "plugins");
|
|
723
|
+
if (existsSync(pluginsStateDir)) {
|
|
724
|
+
walk(pluginsStateDir, true);
|
|
725
|
+
}
|
|
726
|
+
// Backward-compatible legacy `.chomp/shims.json` support if present
|
|
727
|
+
if (existsSync(resolve(absRoot, ".chomp", "shims.json"))) {
|
|
728
|
+
results.push(".chomp/shims.json");
|
|
729
|
+
}
|
|
730
|
+
results.sort((a, b) => a.localeCompare(b));
|
|
731
|
+
return results;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Lightweight file collector used when `plugin.scanRepoFiles === false`:
|
|
735
|
+
* inspects ONLY `.chomp/plugins/**`, legacy `.chomp/shims.json`, and root `chomp.config.json`
|
|
736
|
+
* without walking the repository source tree.
|
|
737
|
+
*/
|
|
738
|
+
export function collectPluginStateFiles(repoPath) {
|
|
739
|
+
const absRoot = resolve(repoPath);
|
|
740
|
+
if (!existsSync(absRoot))
|
|
741
|
+
return [];
|
|
742
|
+
const stat = statSync(absRoot);
|
|
743
|
+
if (!stat.isDirectory())
|
|
744
|
+
return [basename(absRoot)];
|
|
745
|
+
const results = [];
|
|
746
|
+
const walkPluginsDir = (dir) => {
|
|
747
|
+
let entries;
|
|
748
|
+
try {
|
|
749
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
750
|
+
}
|
|
751
|
+
catch {
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
for (const entry of entries) {
|
|
755
|
+
if (entry.name.startsWith("."))
|
|
756
|
+
continue;
|
|
757
|
+
const fullPath = resolve(dir, entry.name);
|
|
758
|
+
const relPath = toPosixPath(relative(absRoot, fullPath));
|
|
759
|
+
if (!relPath)
|
|
760
|
+
continue;
|
|
761
|
+
if (entry.isDirectory()) {
|
|
762
|
+
walkPluginsDir(fullPath);
|
|
763
|
+
}
|
|
764
|
+
else if (entry.isFile()) {
|
|
765
|
+
if (entry.name === PLUGIN_LAST_RUN_FILENAME)
|
|
766
|
+
continue;
|
|
767
|
+
results.push(relPath);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
const pluginsStateDir = resolve(absRoot, ".chomp", "plugins");
|
|
772
|
+
if (existsSync(pluginsStateDir)) {
|
|
773
|
+
walkPluginsDir(pluginsStateDir);
|
|
774
|
+
}
|
|
775
|
+
if (existsSync(resolve(absRoot, ".chomp", "shims.json"))) {
|
|
776
|
+
results.push(".chomp/shims.json");
|
|
777
|
+
}
|
|
778
|
+
if (existsSync(resolve(absRoot, "chomp.config.json"))) {
|
|
779
|
+
results.push("chomp.config.json");
|
|
780
|
+
}
|
|
781
|
+
results.sort((a, b) => a.localeCompare(b));
|
|
782
|
+
return results;
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Computes a deterministic 16-character SHA-256 fingerprint for an input file (`[PAT-DB-05]`).
|
|
786
|
+
* Matches the exact 16-hex slice used by `graphRepository.ts` (`upsertEntityOverlaySync` / `getEntityOverlaysSync`).
|
|
787
|
+
*/
|
|
788
|
+
export function computeFileOverlayHash(repoPath, relOrAbsPath) {
|
|
789
|
+
const absRoot = resolve(repoPath);
|
|
790
|
+
const absFile = resolve(absRoot, relOrAbsPath);
|
|
791
|
+
if (!existsSync(absFile))
|
|
792
|
+
return null;
|
|
793
|
+
try {
|
|
794
|
+
const buf = readFileSync(absFile);
|
|
795
|
+
const hash = createHash("sha256").update(buf).digest("hex").slice(0, 16);
|
|
796
|
+
const relPath = toPosixPath(relative(absRoot, absFile));
|
|
797
|
+
return {
|
|
798
|
+
path: relPath && !relPath.startsWith("..") ? relPath : toPosixPath(relOrAbsPath),
|
|
799
|
+
hash,
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
catch {
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
export function buildOverlayEvidence(filePath, lineNumber, snippet, evidenceRole) {
|
|
807
|
+
return {
|
|
808
|
+
filePath: toPosixPath(filePath.trim()),
|
|
809
|
+
...(typeof lineNumber === "number" && Number.isFinite(lineNumber)
|
|
810
|
+
? { lineNumber }
|
|
811
|
+
: {}),
|
|
812
|
+
...(typeof snippet === "string" && snippet.trim()
|
|
813
|
+
? { snippet: snippet.trim().slice(0, 240) }
|
|
814
|
+
: {}),
|
|
815
|
+
...(typeof evidenceRole === "string" && evidenceRole.trim()
|
|
816
|
+
? { evidenceRole: evidenceRole.trim() }
|
|
817
|
+
: {}),
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Executes a single `ChompPlugin` against a repository and optionally persists
|
|
822
|
+
* its deterministic `EXTRACTED` overlays into `entity_overlays` with `runId` prune-on-recommit (`[PAT-DB-05]`).
|
|
823
|
+
*/
|
|
824
|
+
export async function runChompPlugin(pluginOrName, options) {
|
|
825
|
+
const t0 = Date.now();
|
|
826
|
+
const plugin = resolveEffectivePlugin(pluginOrName);
|
|
827
|
+
if (!plugin) {
|
|
828
|
+
throw new Error(`Unknown Chomp plugin '${String(pluginOrName)}'. Registered plugins: ${listChompPlugins()
|
|
829
|
+
.map((p) => p.name)
|
|
830
|
+
.join(", ") || "none"}`);
|
|
831
|
+
}
|
|
832
|
+
const startedAt = new Date(t0).toISOString();
|
|
833
|
+
const stat = statSync(options.repoPath);
|
|
834
|
+
const isDir = stat.isDirectory();
|
|
835
|
+
const repoPath = isDir ? resolve(options.repoPath) : dirname(resolve(options.repoPath));
|
|
836
|
+
const repoName = options.repoName ?? resolveRepoName(repoPath);
|
|
837
|
+
const repoId = options.repoId ?? repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
838
|
+
const environment = (options.environment || "default").trim();
|
|
839
|
+
const persist = options.persist ?? true;
|
|
840
|
+
const dbPath = resolve(options.dbPath ?? resolve(repoPath, ".chomp", "graph.db"));
|
|
841
|
+
const shouldPersistRunRecord = options.persistRunRecord ??
|
|
842
|
+
(persist && (!options.storage || existsSync(dirname(dbPath))));
|
|
843
|
+
const executeRun = async () => {
|
|
844
|
+
let ownStorage = null;
|
|
845
|
+
const storage = options.storage ??
|
|
846
|
+
(persist || ((!options.graph || !options.existingOverlays) && existsSync(dbPath))
|
|
847
|
+
? (ownStorage = createSQLiteStorage(dbPath))
|
|
848
|
+
: undefined);
|
|
849
|
+
try {
|
|
850
|
+
let resolvedRepoId = repoId;
|
|
851
|
+
let graph = options.graph;
|
|
852
|
+
if (!graph && storage) {
|
|
853
|
+
graph = (await storage.getRepresentationGraph(resolvedRepoId)) ?? undefined;
|
|
854
|
+
if (!graph) {
|
|
855
|
+
const repos = await storage.listRepositories();
|
|
856
|
+
if (repos[0]) {
|
|
857
|
+
resolvedRepoId = repos[0].id;
|
|
858
|
+
graph = (await storage.getRepresentationGraph(resolvedRepoId)) ?? undefined;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
if (!graph) {
|
|
863
|
+
graph = analyzeTarget(repoPath, CORE_EXTRACTOR_VERSION, undefined, options.excludeWorkspaces);
|
|
864
|
+
}
|
|
865
|
+
const existingOverlays = options.existingOverlays ??
|
|
866
|
+
(storage ? await storage.getEntityOverlays(resolvedRepoId) : []);
|
|
867
|
+
const runId = options.runId?.trim() ||
|
|
868
|
+
`${plugin.name}@${plugin.version}:${graph.commitSha || "nogit"}:${Date.now().toString(36)}`;
|
|
869
|
+
const allFiles = plugin.scanRepoFiles === false
|
|
870
|
+
? collectPluginStateFiles(repoPath)
|
|
871
|
+
: collectPluginRepoFiles(repoPath, options.excludeWorkspaces);
|
|
872
|
+
const acceptedFiles = allFiles.filter((f) => plugin.accepts(f));
|
|
873
|
+
const fileCache = new Map();
|
|
874
|
+
const hashCache = new Map();
|
|
875
|
+
const readFile = (relOrAbs) => {
|
|
876
|
+
const key = toPosixPath(relOrAbs);
|
|
877
|
+
if (fileCache.has(key))
|
|
878
|
+
return fileCache.get(key) ?? null;
|
|
879
|
+
const abs = resolve(repoPath, relOrAbs);
|
|
880
|
+
if (!existsSync(abs)) {
|
|
881
|
+
fileCache.set(key, null);
|
|
882
|
+
return null;
|
|
883
|
+
}
|
|
884
|
+
try {
|
|
885
|
+
const content = readFileSync(abs, "utf8");
|
|
886
|
+
fileCache.set(key, content);
|
|
887
|
+
return content;
|
|
888
|
+
}
|
|
889
|
+
catch {
|
|
890
|
+
fileCache.set(key, null);
|
|
891
|
+
return null;
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
const hashFile = (relOrAbs) => {
|
|
895
|
+
const key = toPosixPath(relOrAbs);
|
|
896
|
+
if (hashCache.has(key))
|
|
897
|
+
return hashCache.get(key) ?? null;
|
|
898
|
+
const dep = computeFileOverlayHash(repoPath, relOrAbs);
|
|
899
|
+
hashCache.set(key, dep);
|
|
900
|
+
return dep;
|
|
901
|
+
};
|
|
902
|
+
const pluginDir = getPluginStateDir(repoPath, plugin.name);
|
|
903
|
+
const pluginDirRel = getPluginStateDirRel(plugin.name);
|
|
904
|
+
const settings = options.settingsOverride
|
|
905
|
+
? resolvePluginSettings(plugin.settingsSchema, {
|
|
906
|
+
...loadPluginSettings(repoPath, plugin),
|
|
907
|
+
...options.settingsOverride,
|
|
908
|
+
})
|
|
909
|
+
: loadPluginSettings(repoPath, plugin);
|
|
910
|
+
const readPluginFile = (relPath) => {
|
|
911
|
+
const clean = toPosixPath(relPath).replace(/^\/+/, "");
|
|
912
|
+
return readFile(`${pluginDirRel}/${clean}`);
|
|
913
|
+
};
|
|
914
|
+
const writePluginFile = (relPath, content) => {
|
|
915
|
+
const clean = toPosixPath(relPath).replace(/^\/+/, "");
|
|
916
|
+
const absTarget = resolve(pluginDir, clean);
|
|
917
|
+
mkdirSync(dirname(absTarget), { recursive: true });
|
|
918
|
+
writeFileSync(absTarget, content, "utf8");
|
|
919
|
+
const relKey = `${pluginDirRel}/${clean}`;
|
|
920
|
+
fileCache.set(relKey, content);
|
|
921
|
+
hashCache.delete(relKey);
|
|
922
|
+
return absTarget;
|
|
923
|
+
};
|
|
924
|
+
const hashPluginFile = (relPath) => {
|
|
925
|
+
const clean = toPosixPath(relPath).replace(/^\/+/, "");
|
|
926
|
+
return hashFile(`${pluginDirRel}/${clean}`);
|
|
927
|
+
};
|
|
928
|
+
const setActiveView = (spec) => writePluginActiveView({
|
|
929
|
+
repoPath,
|
|
930
|
+
repoId: resolvedRepoId,
|
|
931
|
+
repoName,
|
|
932
|
+
pluginName: plugin.name,
|
|
933
|
+
layer: plugin.layer,
|
|
934
|
+
}, { graph, ...spec });
|
|
935
|
+
const ctx = {
|
|
936
|
+
repoId: resolvedRepoId,
|
|
937
|
+
repoName,
|
|
938
|
+
repoPath,
|
|
939
|
+
graph,
|
|
940
|
+
existingOverlays,
|
|
941
|
+
files: acceptedFiles,
|
|
942
|
+
environment,
|
|
943
|
+
runId,
|
|
944
|
+
pluginDir,
|
|
945
|
+
pluginDirRel,
|
|
946
|
+
settings,
|
|
947
|
+
readFile,
|
|
948
|
+
readPluginFile,
|
|
949
|
+
writePluginFile,
|
|
950
|
+
hashFile,
|
|
951
|
+
hashPluginFile,
|
|
952
|
+
evidence: buildOverlayEvidence,
|
|
953
|
+
resolveSecret: (key) => resolvePluginSecret(plugin, settings, key),
|
|
954
|
+
setActiveView,
|
|
955
|
+
};
|
|
956
|
+
const rawResult = await plugin.extract(ctx);
|
|
957
|
+
const rawOverlays = Array.isArray(rawResult)
|
|
958
|
+
? rawResult
|
|
959
|
+
: (rawResult.overlays ?? []);
|
|
960
|
+
const summary = Array.isArray(rawResult) ? {} : (rawResult.summary ?? {});
|
|
961
|
+
const enforced = enforcePresentationContract(rawOverlays, plugin.name);
|
|
962
|
+
const knownEntityIds = new Set([
|
|
963
|
+
...graph.nodes.map((n) => n.id),
|
|
964
|
+
...graph.edges.map((e) => e.id),
|
|
965
|
+
]);
|
|
966
|
+
if (knownEntityIds.size > 0) {
|
|
967
|
+
for (const ov of enforced.overlays) {
|
|
968
|
+
if (!knownEntityIds.has(ov.entityId)) {
|
|
969
|
+
enforced.warnings.push(`${plugin.name}:${ov.entityId}: overlay targets unknown entityId not present in graph`);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
const normalizedOverlays = enforced.overlays.map((ov) => ({
|
|
974
|
+
...ov,
|
|
975
|
+
repositoryId: ov.repositoryId ?? resolvedRepoId,
|
|
976
|
+
layer: ov.layer || plugin.layer,
|
|
977
|
+
source: ov.source || plugin.name,
|
|
978
|
+
environment: ov.environment || environment,
|
|
979
|
+
derivation: ov.derivation ?? "EXTRACTED",
|
|
980
|
+
runId,
|
|
981
|
+
pruneStaleBySource: ov.pruneStaleBySource ?? true,
|
|
982
|
+
merge: ov.merge ?? false,
|
|
983
|
+
}));
|
|
984
|
+
if (persist && storage) {
|
|
985
|
+
if (normalizedOverlays.length > 0) {
|
|
986
|
+
await storage.upsertEntityOverlays(normalizedOverlays, {
|
|
987
|
+
repositoryId: resolvedRepoId,
|
|
988
|
+
layer: plugin.layer,
|
|
989
|
+
source: plugin.name,
|
|
990
|
+
environment,
|
|
991
|
+
runId,
|
|
992
|
+
pruneStaleBySource: true,
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
else {
|
|
996
|
+
await storage.pruneEntityOverlays({
|
|
997
|
+
repositoryId: resolvedRepoId,
|
|
998
|
+
layer: plugin.layer,
|
|
999
|
+
source: plugin.name,
|
|
1000
|
+
environment,
|
|
1001
|
+
activeRunId: runId,
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
for (const legacySource of plugin.legacySources ?? []) {
|
|
1005
|
+
await storage.pruneEntityOverlays({
|
|
1006
|
+
repositoryId: resolvedRepoId,
|
|
1007
|
+
layer: plugin.layer,
|
|
1008
|
+
source: legacySource,
|
|
1009
|
+
environment,
|
|
1010
|
+
activeRunId: runId,
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
const durationMs = Date.now() - t0;
|
|
1015
|
+
if (shouldPersistRunRecord) {
|
|
1016
|
+
writePluginLastRun(repoPath, {
|
|
1017
|
+
pluginName: plugin.name,
|
|
1018
|
+
pluginVersion: plugin.version,
|
|
1019
|
+
layer: plugin.layer,
|
|
1020
|
+
status: "ok",
|
|
1021
|
+
runId,
|
|
1022
|
+
startedAt,
|
|
1023
|
+
finishedAt: new Date().toISOString(),
|
|
1024
|
+
durationMs,
|
|
1025
|
+
acceptedFileCount: acceptedFiles.length,
|
|
1026
|
+
overlayCount: normalizedOverlays.length,
|
|
1027
|
+
presentationWarnings: enforced.warnings,
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
return {
|
|
1031
|
+
pluginName: plugin.name,
|
|
1032
|
+
pluginVersion: plugin.version,
|
|
1033
|
+
layer: plugin.layer,
|
|
1034
|
+
runId,
|
|
1035
|
+
acceptedFileCount: acceptedFiles.length,
|
|
1036
|
+
overlayCount: normalizedOverlays.length,
|
|
1037
|
+
overlays: normalizedOverlays,
|
|
1038
|
+
summary,
|
|
1039
|
+
durationMs,
|
|
1040
|
+
presentationWarnings: enforced.warnings,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
catch (err) {
|
|
1044
|
+
if (shouldPersistRunRecord) {
|
|
1045
|
+
writePluginLastRun(repoPath, {
|
|
1046
|
+
pluginName: plugin.name,
|
|
1047
|
+
pluginVersion: plugin.version,
|
|
1048
|
+
layer: plugin.layer,
|
|
1049
|
+
status: "error",
|
|
1050
|
+
startedAt,
|
|
1051
|
+
finishedAt: new Date().toISOString(),
|
|
1052
|
+
durationMs: Date.now() - t0,
|
|
1053
|
+
presentationWarnings: [],
|
|
1054
|
+
error: String(err?.message ?? err).slice(0, 1000),
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
throw err;
|
|
1058
|
+
}
|
|
1059
|
+
finally {
|
|
1060
|
+
if (ownStorage) {
|
|
1061
|
+
await ownStorage.close();
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
1065
|
+
if (persist) {
|
|
1066
|
+
const queueKey = `${dbPath}::${plugin.name}::${environment}`;
|
|
1067
|
+
return serializePluginPersist(queueKey, executeRun);
|
|
1068
|
+
}
|
|
1069
|
+
return executeRun();
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Runs all registered Chomp plugins (plus any repo-local `.chomp/plugins/<custom>/plugin.mjs` drop-ins)
|
|
1073
|
+
* sequentially against `options.repoPath`.
|
|
1074
|
+
*/
|
|
1075
|
+
export async function runAllChompPlugins(options) {
|
|
1076
|
+
const repoLocalPluginsDir = resolve(options.repoPath, ".chomp", "plugins");
|
|
1077
|
+
if (existsSync(repoLocalPluginsDir)) {
|
|
1078
|
+
await discoverPluginsInDir(repoLocalPluginsDir);
|
|
1079
|
+
}
|
|
1080
|
+
const plugins = listChompPlugins();
|
|
1081
|
+
const results = [];
|
|
1082
|
+
for (const plugin of plugins) {
|
|
1083
|
+
try {
|
|
1084
|
+
const res = await runChompPlugin(plugin, options);
|
|
1085
|
+
results.push(res);
|
|
1086
|
+
}
|
|
1087
|
+
catch (err) {
|
|
1088
|
+
const errorObj = err instanceof Error ? err : new Error(String(err));
|
|
1089
|
+
options.onPluginError?.(plugin, errorObj);
|
|
1090
|
+
if (!options.continueOnError) {
|
|
1091
|
+
throw errorObj;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
return results;
|
|
1096
|
+
}
|