@getchomp/mcp 0.0.0-stage → 0.2.43
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/LICENSE +21 -0
- 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 +39 -3
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/mcp/src/plugins/enrich-nodes/index.ts
|
|
3
|
+
*
|
|
4
|
+
* Self-contained `enrich-nodes` plugin module (`L1_SEMANTIC`).
|
|
5
|
+
* Auto-discovered from `packages/mcp/src/plugins/` with zero external plumbing:
|
|
6
|
+
* - State & settings folder: `.chomp/plugins/enrich-nodes/` (`settings.json`)
|
|
7
|
+
* - Declarative Settings UI (`settingsSchema`)
|
|
8
|
+
* - Inspector & HUD Presentation (`PluginPresentation` v1, including honest `Un-enriched` state)
|
|
9
|
+
* - Active View Spotlight (`ctx.setActiveView` + per-domain `summary.views`)
|
|
10
|
+
* - Owned MCP tool (`chomp_enrich_nodes`)
|
|
11
|
+
* - Owned CLI summary formatter (`formatCliSummary`)
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { dirname, resolve } from "node:path";
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
import { ENRICH_NODES_PLUGIN_NAME, SEMANTIC_OVERLAY_LAYER, SEMANTIC_PRODUCER_SOURCE, SEMANTIC_SIDECAR_FILE_REL, buildEnrichmentQueue, buildEnrichmentStatus, enrichNodesPlugin, mergeNodesIntoSemanticSidecar, readSemanticSidecar, } from "../../enrichNodesPlugin.js";
|
|
17
|
+
import { formatEnrichNodesSummary } from "../../intelligence.js";
|
|
18
|
+
import { defineChompPlugin } from "../../pluginRunner.js";
|
|
19
|
+
export const enrichNodesPluginModule = defineChompPlugin({
|
|
20
|
+
...enrichNodesPlugin,
|
|
21
|
+
defaultEnabled: true,
|
|
22
|
+
scanRepoFiles: false,
|
|
23
|
+
settingsSchema: [
|
|
24
|
+
{
|
|
25
|
+
key: "flagStaleDrift",
|
|
26
|
+
label: "Flag stale summaries",
|
|
27
|
+
description: "Warn when code changes after a summary was generated.",
|
|
28
|
+
kind: "boolean",
|
|
29
|
+
defaultValue: true,
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
key: "hideHudWhenEnriched",
|
|
33
|
+
label: "Hide HUD row when complete",
|
|
34
|
+
description: "Hide Summaries in the HUD when all nodes are summarized.",
|
|
35
|
+
kind: "boolean",
|
|
36
|
+
defaultValue: false,
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
key: "persistSidecar",
|
|
40
|
+
label: "Sync semantic sidecar",
|
|
41
|
+
description: "Save semantic labels to .chomp/plugins/enrich-nodes/semantic.json so enrichments survive database rebuilds.",
|
|
42
|
+
kind: "boolean",
|
|
43
|
+
defaultValue: true,
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
key: "includeExportedTypes",
|
|
47
|
+
label: "Include exported types",
|
|
48
|
+
description: "Count TypeScript interfaces and type aliases in enrichment coverage and priority queue targets.",
|
|
49
|
+
kind: "boolean",
|
|
50
|
+
defaultValue: true,
|
|
51
|
+
},
|
|
52
|
+
],
|
|
53
|
+
formatCliSummary: (res, ansi) => {
|
|
54
|
+
const s = res.summary ?? {};
|
|
55
|
+
if (typeof s.totalContracts !== "number")
|
|
56
|
+
return [];
|
|
57
|
+
const pct = s.coveragePct === null || s.coveragePct === undefined ? "N/A" : `${s.coveragePct}%`;
|
|
58
|
+
return [
|
|
59
|
+
`${ansi.dim("Summaries:")} ${ansi.bold(pct)} summarized (${s.enrichedContracts ?? 0}/${s.totalContracts} nodes) · ${(s.staleContracts ?? 0) === 0
|
|
60
|
+
? ansi.green("0 stale")
|
|
61
|
+
: ansi.yellow(`${s.staleContracts} stale`)}`,
|
|
62
|
+
];
|
|
63
|
+
},
|
|
64
|
+
mcpTools: [
|
|
65
|
+
{
|
|
66
|
+
name: "chomp_enrich_nodes",
|
|
67
|
+
description: "SUMMARIES PLUGIN: Supports prioritized work-queue inspection (`action: 'queue'` with inline JSDoc & code context + existing domain taxonomy), coverage reporting (`action: 'status'`), sidecar persistence (`action: 'export' | 'import'`), Summaries presentation refresh (`action: 'refresh'`), AND batch node summaries/overlays + `.chomp/rules.json` classification rules (`action: 'upsert'`, default when `nodes`/`overlays`/`rules`/`defaults` are passed; supports `defer_refresh: true` during bulk runs).",
|
|
68
|
+
inputSchema: {
|
|
69
|
+
action: z
|
|
70
|
+
.enum(["upsert", "queue", "status", "refresh", "export", "import"])
|
|
71
|
+
.optional()
|
|
72
|
+
.describe("Operation: 'queue' (prioritized unenriched/stale nodes with code context & domain taxonomy), 'status' (coverage & domain summary), 'upsert' (write nodes/overlays/rules), 'refresh' (recompute enrich-nodes presentation), 'export' (sync DB semantic overlays to semantic.json), or 'import' (hydrate from semantic.json)."),
|
|
73
|
+
packageName: z
|
|
74
|
+
.string()
|
|
75
|
+
.optional()
|
|
76
|
+
.describe("Optional package filter for 'queue' or 'status' (e.g., 'core', '@chomp/web')"),
|
|
77
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
|
|
78
|
+
status: z
|
|
79
|
+
.enum(["needs_enrichment", "unenriched", "stale", "all"])
|
|
80
|
+
.optional()
|
|
81
|
+
.describe("Target filter for action 'queue' (default: 'needs_enrichment')"),
|
|
82
|
+
includeTypes: z
|
|
83
|
+
.boolean()
|
|
84
|
+
.optional()
|
|
85
|
+
.describe("Whether to include EXPORTED_TYPE nodes in 'queue' (defaults to plugin setting includeExportedTypes)"),
|
|
86
|
+
include_types: z.boolean().optional().describe("Alias for includeTypes (snake_case)"),
|
|
87
|
+
limit: z
|
|
88
|
+
.number()
|
|
89
|
+
.optional()
|
|
90
|
+
.describe("Maximum queue items per page for action 'queue' (default: 40, max: 100)"),
|
|
91
|
+
cursor: z
|
|
92
|
+
.number()
|
|
93
|
+
.optional()
|
|
94
|
+
.describe("Zero-based pagination offset for action 'queue' (default: 0)"),
|
|
95
|
+
includeContext: z
|
|
96
|
+
.boolean()
|
|
97
|
+
.optional()
|
|
98
|
+
.describe("Include adjacent JSDoc summary and source code slice in action 'queue' (default: true)"),
|
|
99
|
+
include_context: z.boolean().optional().describe("Alias for includeContext (snake_case)"),
|
|
100
|
+
contextLines: z
|
|
101
|
+
.number()
|
|
102
|
+
.optional()
|
|
103
|
+
.describe("Number of source lines after node start line to include in 'queue' (default: 18, max: 60)"),
|
|
104
|
+
context_lines: z.number().optional().describe("Alias for contextLines (snake_case)"),
|
|
105
|
+
deferRefresh: z
|
|
106
|
+
.boolean()
|
|
107
|
+
.optional()
|
|
108
|
+
.describe("When true on 'upsert', skips recomputing package presentation overlays until a final 'refresh' call (faster & race-free for parallel/batched runs)"),
|
|
109
|
+
defer_refresh: z.boolean().optional().describe("Alias for deferRefresh (snake_case)"),
|
|
110
|
+
overwrite: z
|
|
111
|
+
.boolean()
|
|
112
|
+
.optional()
|
|
113
|
+
.describe("When true on action 'import', overwrites existing DB semantic overlays from semantic.json (default: false)"),
|
|
114
|
+
nodes: z
|
|
115
|
+
.array(z.object({
|
|
116
|
+
nodeId: z.string(),
|
|
117
|
+
domain: z.string().optional(),
|
|
118
|
+
humanLabel: z.string().optional(),
|
|
119
|
+
summary: z.string().optional(),
|
|
120
|
+
rationale: z.string().optional(),
|
|
121
|
+
action: z
|
|
122
|
+
.enum(["middleware_badge", "component_badge", "micro_node", "station_node"])
|
|
123
|
+
.optional()
|
|
124
|
+
.describe("Optional classification rule action for this node (`middleware_badge` = ◆ diamond badge, `component_badge` = ❖ 4-diamond badge, `micro_node` = ● internal helper, `station_node` = show as full node)"),
|
|
125
|
+
badgeLabel: z
|
|
126
|
+
.string()
|
|
127
|
+
.optional()
|
|
128
|
+
.describe("Optional badge label when action is `middleware_badge` or `component_badge` (e.g. 'auth', 'protected', 'rate-limited')"),
|
|
129
|
+
badgeMode: z
|
|
130
|
+
.enum(["fold_into_callers", "badge_on_node"])
|
|
131
|
+
.optional()
|
|
132
|
+
.describe("`fold_into_callers` folds leaf guards/components into callers; `badge_on_node` attaches the badge directly onto the matched node"),
|
|
133
|
+
}))
|
|
134
|
+
.optional()
|
|
135
|
+
.describe("Array of nodes to enrich or classify"),
|
|
136
|
+
overlays: z
|
|
137
|
+
.array(z.object({
|
|
138
|
+
entityId: z.string().describe("Target node or edge ID"),
|
|
139
|
+
layer: z
|
|
140
|
+
.string()
|
|
141
|
+
.default("L1_SEMANTIC")
|
|
142
|
+
.describe("Overlay layer: L1_PORTS, L1_SEMANTIC, L1_DESIGN_SYSTEM, L2_RUNTIME, L3_INFRA, or PLUGIN:<name>"),
|
|
143
|
+
source: z
|
|
144
|
+
.string()
|
|
145
|
+
.default("agent")
|
|
146
|
+
.describe("Overlay producer/plugin identifier (e.g. 'chomp_enrich_nodes', 'datadog', 'design-system', 'openapi')"),
|
|
147
|
+
environment: z
|
|
148
|
+
.string()
|
|
149
|
+
.default("default")
|
|
150
|
+
.describe("Target environment (e.g. 'default', 'production', 'staging', 'local')"),
|
|
151
|
+
payload: z
|
|
152
|
+
.record(z.any())
|
|
153
|
+
.describe("Structured JSON overlay payload (e.g. { p95Ms, errorRate, rps }, { inputTypes, outputType }, { title, kv, metrics, tags })"),
|
|
154
|
+
bodyHash: z
|
|
155
|
+
.string()
|
|
156
|
+
.nullable()
|
|
157
|
+
.optional()
|
|
158
|
+
.describe("Optional AST bodyHash at time of analysis for staleness tracking"),
|
|
159
|
+
derivation: z
|
|
160
|
+
.enum(["EXTRACTED", "INFERRED", "AI_HYPOTHESIS"])
|
|
161
|
+
.optional()
|
|
162
|
+
.describe("Epistemic provenance: EXTRACTED, INFERRED, or AI_HYPOTHESIS"),
|
|
163
|
+
inputs: z
|
|
164
|
+
.array(z.object({
|
|
165
|
+
path: z.string(),
|
|
166
|
+
hash: z.string(),
|
|
167
|
+
}))
|
|
168
|
+
.optional()
|
|
169
|
+
.describe("Optional list of external non-AST input files ({ path, hash }) that this overlay depends on"),
|
|
170
|
+
evidence: z
|
|
171
|
+
.array(z.object({
|
|
172
|
+
filePath: z.string(),
|
|
173
|
+
lineNumber: z.number().optional(),
|
|
174
|
+
snippet: z.string().optional(),
|
|
175
|
+
evidenceRole: z.string().optional(),
|
|
176
|
+
}))
|
|
177
|
+
.optional()
|
|
178
|
+
.describe("Optional source file and line evidence references"),
|
|
179
|
+
runId: z.string().optional().describe("Optional run/commit identifier for prune-on-recommit"),
|
|
180
|
+
pruneStaleBySource: z
|
|
181
|
+
.boolean()
|
|
182
|
+
.optional()
|
|
183
|
+
.describe("When true, prunes obsolete rows from prior runs for this (layer, source, environment)"),
|
|
184
|
+
merge: z
|
|
185
|
+
.boolean()
|
|
186
|
+
.optional()
|
|
187
|
+
.describe("When true (default), merges payload into existing overlay for the same key"),
|
|
188
|
+
}))
|
|
189
|
+
.optional()
|
|
190
|
+
.describe("Extensible multi-layer and plugin overlays to upsert into `entity_overlays`"),
|
|
191
|
+
runId: z
|
|
192
|
+
.string()
|
|
193
|
+
.optional()
|
|
194
|
+
.describe("Optional batch run identifier applied to all overlays in this call for prune-on-recommit"),
|
|
195
|
+
pruneStaleBySource: z
|
|
196
|
+
.boolean()
|
|
197
|
+
.optional()
|
|
198
|
+
.describe("When true (default when runId is provided), prunes obsolete overlay rows from prior runs for each affected (layer, source, environment)"),
|
|
199
|
+
rules: z
|
|
200
|
+
.array(z.object({
|
|
201
|
+
id: z.string().optional(),
|
|
202
|
+
name: z.string(),
|
|
203
|
+
description: z.string().optional(),
|
|
204
|
+
enabled: z.boolean().optional(),
|
|
205
|
+
match: z.object({
|
|
206
|
+
nodeId: z.string().optional(),
|
|
207
|
+
namePattern: z.string().optional(),
|
|
208
|
+
entityType: z.string().optional(),
|
|
209
|
+
patternId: z.string().optional(),
|
|
210
|
+
packageLabel: z.string().optional(),
|
|
211
|
+
filePathPattern: z.string().optional(),
|
|
212
|
+
overlayLayer: z.string().optional(),
|
|
213
|
+
overlaySource: z.string().optional(),
|
|
214
|
+
overlayField: z.string().optional(),
|
|
215
|
+
overlayValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
|
|
216
|
+
}),
|
|
217
|
+
action: z.enum(["middleware_badge", "component_badge", "micro_node", "station_node"]),
|
|
218
|
+
badgeLabel: z.string().optional(),
|
|
219
|
+
badgeMode: z.enum(["fold_into_callers", "badge_on_node"]).optional(),
|
|
220
|
+
}))
|
|
221
|
+
.optional()
|
|
222
|
+
.describe("Custom classification & folding rules to add or update in `.chomp/rules.json`"),
|
|
223
|
+
defaults: z
|
|
224
|
+
.object({
|
|
225
|
+
foldMiddleware: z.boolean().optional(),
|
|
226
|
+
foldComponents: z.boolean().optional(),
|
|
227
|
+
foldMicroNodes: z.boolean().optional(),
|
|
228
|
+
})
|
|
229
|
+
.optional()
|
|
230
|
+
.describe("Optional toggle overrides for the 3 built-in classification rules"),
|
|
231
|
+
create_view: z
|
|
232
|
+
.boolean()
|
|
233
|
+
.optional()
|
|
234
|
+
.describe("When true, updates .chomp/current_view.json to highlight the enriched nodes in the UI. Leave false (default) during coding tasks; pass true only when answering user questions or walkthrough requests."),
|
|
235
|
+
createView: z.boolean().optional().describe("Alias for create_view (camelCase)"),
|
|
236
|
+
},
|
|
237
|
+
handler: async (args, ctx) => {
|
|
238
|
+
const hasWriteArgs = Boolean(args.nodes && args.nodes.length > 0) ||
|
|
239
|
+
Boolean(args.overlays && args.overlays.length > 0) ||
|
|
240
|
+
Boolean(args.rules && args.rules.length > 0) ||
|
|
241
|
+
Boolean(args.defaults);
|
|
242
|
+
const action = args.action ?? (hasWriteArgs ? "upsert" : "refresh");
|
|
243
|
+
const pkgName = args.packageName ?? args.package_name;
|
|
244
|
+
const requireDbAndGraph = async () => {
|
|
245
|
+
if (!existsSync(ctx.dbPath)) {
|
|
246
|
+
throw new Error(`Chomp database not found at ${ctx.dbPath}.`);
|
|
247
|
+
}
|
|
248
|
+
const rawGraph = await ctx.loadRawGraph();
|
|
249
|
+
if (!rawGraph) {
|
|
250
|
+
throw new Error(`Graph data for repository '${ctx.repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
251
|
+
}
|
|
252
|
+
return rawGraph;
|
|
253
|
+
};
|
|
254
|
+
if (action === "status") {
|
|
255
|
+
const rawGraph = await requireDbAndGraph();
|
|
256
|
+
const existingOverlays = await ctx.withStorage((s) => s.getEntityOverlays(ctx.repoId, { layers: [SEMANTIC_OVERLAY_LAYER] }));
|
|
257
|
+
return buildEnrichmentStatus({
|
|
258
|
+
graph: rawGraph,
|
|
259
|
+
existingOverlays,
|
|
260
|
+
repoPath: ctx.repoPath,
|
|
261
|
+
settings: ctx.settings,
|
|
262
|
+
packageName: pkgName,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
if (action === "queue") {
|
|
266
|
+
const rawGraph = await requireDbAndGraph();
|
|
267
|
+
const existingOverlays = await ctx.withStorage((s) => s.getEntityOverlays(ctx.repoId, { layers: [SEMANTIC_OVERLAY_LAYER] }));
|
|
268
|
+
return buildEnrichmentQueue({
|
|
269
|
+
graph: rawGraph,
|
|
270
|
+
existingOverlays,
|
|
271
|
+
repoPath: ctx.repoPath,
|
|
272
|
+
settings: ctx.settings,
|
|
273
|
+
packageName: pkgName,
|
|
274
|
+
status: args.status,
|
|
275
|
+
includeTypes: args.includeTypes ?? args.include_types,
|
|
276
|
+
limit: args.limit,
|
|
277
|
+
cursor: args.cursor,
|
|
278
|
+
includeContext: args.includeContext ?? args.include_context,
|
|
279
|
+
contextLines: args.contextLines ?? args.context_lines,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
if (action === "export") {
|
|
283
|
+
await requireDbAndGraph();
|
|
284
|
+
const existingOverlays = await ctx.withStorage((s) => s.getEntityOverlays(ctx.repoId, { layers: [SEMANTIC_OVERLAY_LAYER] }));
|
|
285
|
+
const dbUpdates = [];
|
|
286
|
+
for (const ov of existingOverlays) {
|
|
287
|
+
if (ov.source === ENRICH_NODES_PLUGIN_NAME)
|
|
288
|
+
continue;
|
|
289
|
+
const p = ov.payload ?? {};
|
|
290
|
+
const domain = typeof p.domain === "string" && p.domain.trim() ? p.domain.trim() : undefined;
|
|
291
|
+
const humanLabel = typeof p.humanLabel === "string" && p.humanLabel.trim()
|
|
292
|
+
? p.humanLabel.trim()
|
|
293
|
+
: undefined;
|
|
294
|
+
const summary = typeof p.summary === "string" && p.summary.trim() ? p.summary.trim() : undefined;
|
|
295
|
+
const rationale = typeof p.rationale === "string" && p.rationale.trim()
|
|
296
|
+
? p.rationale.trim()
|
|
297
|
+
: undefined;
|
|
298
|
+
if (!domain && !humanLabel && !summary && !rationale)
|
|
299
|
+
continue;
|
|
300
|
+
dbUpdates.push({
|
|
301
|
+
nodeId: ov.entityId,
|
|
302
|
+
...(domain ? { domain } : {}),
|
|
303
|
+
...(humanLabel ? { humanLabel } : {}),
|
|
304
|
+
...(summary ? { summary } : {}),
|
|
305
|
+
...(rationale ? { rationale } : {}),
|
|
306
|
+
bodyHash: ov.bodyHash ?? null,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
const synced = mergeNodesIntoSemanticSidecar(ctx.repoPath, dbUpdates, existingOverlays);
|
|
310
|
+
return {
|
|
311
|
+
action: "export",
|
|
312
|
+
path: synced.path,
|
|
313
|
+
exportedCount: dbUpdates.length,
|
|
314
|
+
totalSidecarNodes: synced.totalNodes,
|
|
315
|
+
domains: synced.domains,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
if (action === "import") {
|
|
319
|
+
const rawGraph = await requireDbAndGraph();
|
|
320
|
+
const sidecar = readSemanticSidecar(ctx.repoPath);
|
|
321
|
+
if (!sidecar) {
|
|
322
|
+
return {
|
|
323
|
+
action: "import",
|
|
324
|
+
path: SEMANTIC_SIDECAR_FILE_REL,
|
|
325
|
+
sidecarExists: false,
|
|
326
|
+
importedCount: 0,
|
|
327
|
+
skippedExistingCount: 0,
|
|
328
|
+
unknownNodeIds: [],
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
const nodeById = new Map(rawGraph.nodes.map((n) => [n.id, n]));
|
|
332
|
+
const existingOverlays = await ctx.withStorage((s) => s.getEntityOverlays(ctx.repoId, { layers: [SEMANTIC_OVERLAY_LAYER] }));
|
|
333
|
+
const existingSemanticIds = new Set();
|
|
334
|
+
for (const ov of existingOverlays) {
|
|
335
|
+
if (ov.source === ENRICH_NODES_PLUGIN_NAME)
|
|
336
|
+
continue;
|
|
337
|
+
const p = ov.payload ?? {};
|
|
338
|
+
if (p.domain || p.humanLabel || p.summary || p.rationale) {
|
|
339
|
+
existingSemanticIds.add(ov.entityId);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const batch = [];
|
|
343
|
+
const unknownNodeIds = [];
|
|
344
|
+
let skippedExistingCount = 0;
|
|
345
|
+
for (const [nodeId, entry] of Object.entries(sidecar.nodes)) {
|
|
346
|
+
const node = nodeById.get(nodeId);
|
|
347
|
+
if (!node) {
|
|
348
|
+
unknownNodeIds.push(nodeId);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (!args.overwrite && existingSemanticIds.has(nodeId)) {
|
|
352
|
+
skippedExistingCount++;
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
const currentBodyHash = typeof node.metadata?.bodyHash === "string" ? node.metadata.bodyHash : null;
|
|
356
|
+
batch.push({
|
|
357
|
+
repositoryId: ctx.repoId,
|
|
358
|
+
entityId: nodeId,
|
|
359
|
+
layer: SEMANTIC_OVERLAY_LAYER,
|
|
360
|
+
source: SEMANTIC_PRODUCER_SOURCE,
|
|
361
|
+
environment: "default",
|
|
362
|
+
derivation: "AI_HYPOTHESIS",
|
|
363
|
+
...(entry.bodyHash !== undefined
|
|
364
|
+
? { bodyHash: entry.bodyHash }
|
|
365
|
+
: currentBodyHash
|
|
366
|
+
? { bodyHash: currentBodyHash }
|
|
367
|
+
: {}),
|
|
368
|
+
payload: {
|
|
369
|
+
...(entry.domain ? { domain: entry.domain } : {}),
|
|
370
|
+
...(entry.humanLabel ? { humanLabel: entry.humanLabel } : {}),
|
|
371
|
+
...(entry.summary ? { summary: entry.summary } : {}),
|
|
372
|
+
...(entry.rationale ? { rationale: entry.rationale } : {}),
|
|
373
|
+
},
|
|
374
|
+
merge: true,
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
let refreshSummary = {};
|
|
378
|
+
await ctx.withStorage(async (storage) => {
|
|
379
|
+
if (batch.length > 0) {
|
|
380
|
+
await storage.upsertEntityOverlays(batch, { repositoryId: ctx.repoId });
|
|
381
|
+
}
|
|
382
|
+
const runRes = await ctx.runSelf({ storage, graph: rawGraph, persist: true });
|
|
383
|
+
refreshSummary = runRes.summary ?? {};
|
|
384
|
+
});
|
|
385
|
+
ctx.invalidateCache();
|
|
386
|
+
return {
|
|
387
|
+
action: "import",
|
|
388
|
+
path: SEMANTIC_SIDECAR_FILE_REL,
|
|
389
|
+
sidecarExists: true,
|
|
390
|
+
importedCount: batch.length,
|
|
391
|
+
skippedExistingCount,
|
|
392
|
+
unknownNodeIds,
|
|
393
|
+
remainingUnenriched: refreshSummary.unenrichedContracts ?? null,
|
|
394
|
+
remainingStale: refreshSummary.staleContracts ?? null,
|
|
395
|
+
coveragePct: refreshSummary.coveragePct ?? null,
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
if (action === "refresh") {
|
|
399
|
+
const rawGraph = existsSync(ctx.dbPath) ? await ctx.loadRawGraph() : null;
|
|
400
|
+
let refreshSummary = {};
|
|
401
|
+
if (existsSync(ctx.dbPath)) {
|
|
402
|
+
await ctx.withStorage(async (storage) => {
|
|
403
|
+
const runRes = await ctx.runSelf({
|
|
404
|
+
storage,
|
|
405
|
+
...(rawGraph ? { graph: rawGraph } : {}),
|
|
406
|
+
persist: true,
|
|
407
|
+
});
|
|
408
|
+
refreshSummary = runRes.summary ?? {};
|
|
409
|
+
});
|
|
410
|
+
ctx.invalidateCache();
|
|
411
|
+
}
|
|
412
|
+
return {
|
|
413
|
+
action: "refresh",
|
|
414
|
+
summary: formatEnrichNodesSummary({}, 0),
|
|
415
|
+
...refreshSummary,
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
// action === "upsert"
|
|
419
|
+
const layerCounts = {};
|
|
420
|
+
let rulesAddedOrUpdated = 0;
|
|
421
|
+
const unknownNodeIds = [];
|
|
422
|
+
const newDomains = [];
|
|
423
|
+
const deferRefresh = Boolean(args.deferRefresh ?? args.defer_refresh);
|
|
424
|
+
let sidecarSynced = false;
|
|
425
|
+
let refreshSummary = null;
|
|
426
|
+
const validNodesForRules = [];
|
|
427
|
+
if ((args.nodes && args.nodes.length > 0) || (args.overlays && args.overlays.length > 0)) {
|
|
428
|
+
const rawGraph = await requireDbAndGraph();
|
|
429
|
+
const nodeById = new Map((rawGraph.nodes ?? []).map((n) => [n.id, n]));
|
|
430
|
+
const knownEntityIds = new Set([
|
|
431
|
+
...(rawGraph.nodes ?? []).map((n) => n.id),
|
|
432
|
+
...(rawGraph.edges ?? []).map((e) => e.id),
|
|
433
|
+
]);
|
|
434
|
+
const needsSidecar = ctx.settings.persistSidecar !== false && (args.nodes?.length ?? 0) > 0;
|
|
435
|
+
const batchOverlays = [];
|
|
436
|
+
const sidecarUpdates = [];
|
|
437
|
+
const submittedDomains = [];
|
|
438
|
+
for (const node of args.nodes ?? []) {
|
|
439
|
+
const targetNode = nodeById.get(node.nodeId);
|
|
440
|
+
if (!targetNode) {
|
|
441
|
+
if (!unknownNodeIds.includes(node.nodeId)) {
|
|
442
|
+
unknownNodeIds.push(node.nodeId);
|
|
443
|
+
}
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
validNodesForRules.push(node);
|
|
447
|
+
if (node.domain || node.humanLabel || node.summary || node.rationale) {
|
|
448
|
+
const trimmedDomain = node.domain?.trim();
|
|
449
|
+
if (trimmedDomain) {
|
|
450
|
+
submittedDomains.push(trimmedDomain);
|
|
451
|
+
}
|
|
452
|
+
const currentBodyHash = typeof targetNode.metadata?.bodyHash === "string"
|
|
453
|
+
? targetNode.metadata.bodyHash
|
|
454
|
+
: null;
|
|
455
|
+
batchOverlays.push({
|
|
456
|
+
repositoryId: ctx.repoId,
|
|
457
|
+
entityId: node.nodeId,
|
|
458
|
+
layer: SEMANTIC_OVERLAY_LAYER,
|
|
459
|
+
source: SEMANTIC_PRODUCER_SOURCE,
|
|
460
|
+
environment: "default",
|
|
461
|
+
derivation: "AI_HYPOTHESIS",
|
|
462
|
+
...(currentBodyHash ? { bodyHash: currentBodyHash } : {}),
|
|
463
|
+
payload: {
|
|
464
|
+
...(trimmedDomain ? { domain: trimmedDomain } : {}),
|
|
465
|
+
...(node.humanLabel?.trim() ? { humanLabel: node.humanLabel.trim() } : {}),
|
|
466
|
+
...(node.summary?.trim() ? { summary: node.summary.trim() } : {}),
|
|
467
|
+
...(node.rationale?.trim() ? { rationale: node.rationale.trim() } : {}),
|
|
468
|
+
},
|
|
469
|
+
merge: true,
|
|
470
|
+
});
|
|
471
|
+
sidecarUpdates.push({
|
|
472
|
+
nodeId: node.nodeId,
|
|
473
|
+
...(trimmedDomain ? { domain: trimmedDomain } : {}),
|
|
474
|
+
...(node.humanLabel?.trim() ? { humanLabel: node.humanLabel.trim() } : {}),
|
|
475
|
+
...(node.summary?.trim() ? { summary: node.summary.trim() } : {}),
|
|
476
|
+
...(node.rationale?.trim() ? { rationale: node.rationale.trim() } : {}),
|
|
477
|
+
bodyHash: currentBodyHash,
|
|
478
|
+
});
|
|
479
|
+
layerCounts[SEMANTIC_OVERLAY_LAYER] =
|
|
480
|
+
(layerCounts[SEMANTIC_OVERLAY_LAYER] ?? 0) + 1;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
for (const ov of args.overlays ?? []) {
|
|
484
|
+
if (!knownEntityIds.has(ov.entityId)) {
|
|
485
|
+
if (!unknownNodeIds.includes(ov.entityId)) {
|
|
486
|
+
unknownNodeIds.push(ov.entityId);
|
|
487
|
+
}
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
const layerName = (ov.layer || SEMANTIC_OVERLAY_LAYER).trim();
|
|
491
|
+
batchOverlays.push({
|
|
492
|
+
repositoryId: ctx.repoId,
|
|
493
|
+
entityId: ov.entityId,
|
|
494
|
+
layer: layerName,
|
|
495
|
+
source: ov.source || "agent",
|
|
496
|
+
environment: ov.environment || "default",
|
|
497
|
+
payload: ov.payload || {},
|
|
498
|
+
...(ov.bodyHash !== undefined ? { bodyHash: ov.bodyHash } : {}),
|
|
499
|
+
...(ov.derivation ? { derivation: ov.derivation } : {}),
|
|
500
|
+
...(ov.inputs ? { inputs: ov.inputs } : {}),
|
|
501
|
+
...(ov.evidence ? { evidence: ov.evidence } : {}),
|
|
502
|
+
...(ov.runId ?? args.runId ? { runId: ov.runId ?? args.runId } : {}),
|
|
503
|
+
...(ov.pruneStaleBySource !== undefined
|
|
504
|
+
? { pruneStaleBySource: ov.pruneStaleBySource }
|
|
505
|
+
: {}),
|
|
506
|
+
merge: ov.merge ?? true,
|
|
507
|
+
});
|
|
508
|
+
layerCounts[layerName] = (layerCounts[layerName] ?? 0) + 1;
|
|
509
|
+
}
|
|
510
|
+
if (batchOverlays.length > 0) {
|
|
511
|
+
let existingSemanticOverlays = [];
|
|
512
|
+
refreshSummary = await ctx.withStorage(async (storage) => {
|
|
513
|
+
if (submittedDomains.length > 0 || needsSidecar) {
|
|
514
|
+
existingSemanticOverlays = await storage.getEntityOverlays(ctx.repoId, {
|
|
515
|
+
layers: [SEMANTIC_OVERLAY_LAYER],
|
|
516
|
+
});
|
|
517
|
+
const existingDomainSet = new Set();
|
|
518
|
+
for (const ov of existingSemanticOverlays) {
|
|
519
|
+
if (ov.source === ENRICH_NODES_PLUGIN_NAME)
|
|
520
|
+
continue;
|
|
521
|
+
const d = ov.payload?.domain;
|
|
522
|
+
if (typeof d === "string" && d.trim()) {
|
|
523
|
+
existingDomainSet.add(d.trim());
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (existingDomainSet.size > 0) {
|
|
527
|
+
const seenNew = new Set();
|
|
528
|
+
for (const d of submittedDomains) {
|
|
529
|
+
if (!existingDomainSet.has(d) && !seenNew.has(d)) {
|
|
530
|
+
seenNew.add(d);
|
|
531
|
+
newDomains.push(d);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
await storage.upsertEntityOverlays(batchOverlays, {
|
|
537
|
+
repositoryId: ctx.repoId,
|
|
538
|
+
...(args.runId ? { runId: args.runId } : {}),
|
|
539
|
+
...(args.pruneStaleBySource !== undefined
|
|
540
|
+
? { pruneStaleBySource: args.pruneStaleBySource }
|
|
541
|
+
: {}),
|
|
542
|
+
});
|
|
543
|
+
if (!deferRefresh && layerCounts[SEMANTIC_OVERLAY_LAYER]) {
|
|
544
|
+
const runRes = await ctx.runSelf({
|
|
545
|
+
storage,
|
|
546
|
+
graph: rawGraph,
|
|
547
|
+
persist: true,
|
|
548
|
+
});
|
|
549
|
+
return runRes.summary ?? {};
|
|
550
|
+
}
|
|
551
|
+
return null;
|
|
552
|
+
});
|
|
553
|
+
if (needsSidecar && sidecarUpdates.length > 0) {
|
|
554
|
+
mergeNodesIntoSemanticSidecar(ctx.repoPath, sidecarUpdates, existingSemanticOverlays);
|
|
555
|
+
sidecarSynced = true;
|
|
556
|
+
}
|
|
557
|
+
ctx.invalidateCache();
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
const nodeRules = validNodesForRules
|
|
561
|
+
.filter((n) => Boolean(n.action || n.badgeLabel))
|
|
562
|
+
.map((n) => ({
|
|
563
|
+
id: `agent-node-${n.nodeId}`,
|
|
564
|
+
name: n.humanLabel
|
|
565
|
+
? `${n.humanLabel} (${n.action ?? "middleware_badge"})`
|
|
566
|
+
: `Node ${n.nodeId} (${n.badgeLabel || n.action || "middleware_badge"})`,
|
|
567
|
+
description: n.summary || `Agent rule for node ${n.nodeId}`,
|
|
568
|
+
enabled: true,
|
|
569
|
+
match: { nodeId: n.nodeId },
|
|
570
|
+
action: n.action ?? "middleware_badge",
|
|
571
|
+
...(n.badgeLabel ? { badgeLabel: n.badgeLabel } : {}),
|
|
572
|
+
badgeMode: n.badgeMode ??
|
|
573
|
+
(n.badgeLabel ? "badge_on_node" : "fold_into_callers"),
|
|
574
|
+
}));
|
|
575
|
+
const allIncomingRules = [...nodeRules, ...(args.rules ?? [])];
|
|
576
|
+
if (allIncomingRules.length > 0 || args.defaults) {
|
|
577
|
+
const rulesPath = resolve(ctx.repoPath, ".chomp", "rules.json");
|
|
578
|
+
let currentConfig = {
|
|
579
|
+
version: 1,
|
|
580
|
+
defaults: {
|
|
581
|
+
foldMiddleware: true,
|
|
582
|
+
foldComponents: true,
|
|
583
|
+
foldMicroNodes: true,
|
|
584
|
+
},
|
|
585
|
+
customRules: [],
|
|
586
|
+
};
|
|
587
|
+
if (existsSync(rulesPath)) {
|
|
588
|
+
try {
|
|
589
|
+
currentConfig = JSON.parse(readFileSync(rulesPath, "utf8"));
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
// Keep default structure if file was malformed
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
if (!currentConfig.defaults || typeof currentConfig.defaults !== "object") {
|
|
596
|
+
currentConfig.defaults = {
|
|
597
|
+
foldMiddleware: true,
|
|
598
|
+
foldComponents: true,
|
|
599
|
+
foldMicroNodes: true,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
if (args.defaults) {
|
|
603
|
+
if (typeof args.defaults.foldMiddleware === "boolean") {
|
|
604
|
+
currentConfig.defaults.foldMiddleware = args.defaults.foldMiddleware;
|
|
605
|
+
}
|
|
606
|
+
if (typeof args.defaults.foldComponents === "boolean") {
|
|
607
|
+
currentConfig.defaults.foldComponents = args.defaults.foldComponents;
|
|
608
|
+
}
|
|
609
|
+
if (typeof args.defaults.foldMicroNodes === "boolean") {
|
|
610
|
+
currentConfig.defaults.foldMicroNodes = args.defaults.foldMicroNodes;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
if (!Array.isArray(currentConfig.customRules)) {
|
|
614
|
+
currentConfig.customRules = [];
|
|
615
|
+
}
|
|
616
|
+
const nowIso = new Date().toISOString();
|
|
617
|
+
for (const r of allIncomingRules) {
|
|
618
|
+
const ruleId = r.id ||
|
|
619
|
+
`agent-rule-${r.name
|
|
620
|
+
.toLowerCase()
|
|
621
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
622
|
+
.replace(/^-|-$/g, "")
|
|
623
|
+
.slice(0, 32)}-${Date.now().toString(36).slice(-4)}`;
|
|
624
|
+
const newEntry = {
|
|
625
|
+
id: ruleId,
|
|
626
|
+
name: r.name,
|
|
627
|
+
...(r.description ? { description: r.description } : {}),
|
|
628
|
+
enabled: r.enabled ?? true,
|
|
629
|
+
match: r.match,
|
|
630
|
+
action: r.action,
|
|
631
|
+
...(r.badgeLabel ? { badgeLabel: r.badgeLabel } : {}),
|
|
632
|
+
badgeMode: r.badgeMode ?? "fold_into_callers",
|
|
633
|
+
createdBy: "agent",
|
|
634
|
+
createdAt: nowIso,
|
|
635
|
+
};
|
|
636
|
+
const existingIdx = currentConfig.customRules.findIndex((existing) => existing.id === ruleId);
|
|
637
|
+
if (existingIdx >= 0) {
|
|
638
|
+
currentConfig.customRules[existingIdx] = newEntry;
|
|
639
|
+
}
|
|
640
|
+
else {
|
|
641
|
+
currentConfig.customRules.push(newEntry);
|
|
642
|
+
}
|
|
643
|
+
rulesAddedOrUpdated++;
|
|
644
|
+
}
|
|
645
|
+
mkdirSync(dirname(rulesPath), { recursive: true });
|
|
646
|
+
writeFileSync(rulesPath, JSON.stringify(currentConfig, null, 2), "utf8");
|
|
647
|
+
}
|
|
648
|
+
if (args.create_view ?? args.createView) {
|
|
649
|
+
const unknownSet = new Set(unknownNodeIds);
|
|
650
|
+
const highlightIds = Array.from(new Set([
|
|
651
|
+
...validNodesForRules.map((n) => n.nodeId),
|
|
652
|
+
...(args.overlays ?? [])
|
|
653
|
+
.map((o) => o.entityId)
|
|
654
|
+
.filter((id) => !unknownSet.has(id)),
|
|
655
|
+
])).slice(0, 40);
|
|
656
|
+
if (highlightIds.length > 0) {
|
|
657
|
+
const projected = await ctx.loadProjectedGraph();
|
|
658
|
+
const annotations = {};
|
|
659
|
+
for (const n of validNodesForRules) {
|
|
660
|
+
if (n.summary || n.humanLabel || n.domain) {
|
|
661
|
+
annotations[n.nodeId] = [n.domain, n.humanLabel, n.summary]
|
|
662
|
+
.filter(Boolean)
|
|
663
|
+
.join(" — ");
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
ctx.setActiveView({
|
|
667
|
+
title: "Updated node summaries",
|
|
668
|
+
description: `Summarized ${highlightIds.length} node(s)`,
|
|
669
|
+
highlightNodeIds: highlightIds,
|
|
670
|
+
...(Object.keys(annotations).length > 0 ? { nodeAnnotations: annotations } : {}),
|
|
671
|
+
...(projected ? { graph: projected } : {}),
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return {
|
|
676
|
+
action: "upsert",
|
|
677
|
+
summary: formatEnrichNodesSummary(layerCounts, rulesAddedOrUpdated),
|
|
678
|
+
writtenByLayer: layerCounts,
|
|
679
|
+
rulesAddedOrUpdated,
|
|
680
|
+
unknownNodeIds,
|
|
681
|
+
newDomains,
|
|
682
|
+
deferredRefresh: deferRefresh && Boolean(layerCounts[SEMANTIC_OVERLAY_LAYER]),
|
|
683
|
+
sidecarSynced,
|
|
684
|
+
...(refreshSummary
|
|
685
|
+
? {
|
|
686
|
+
remainingUnenriched: refreshSummary.unenrichedContracts ?? null,
|
|
687
|
+
remainingStale: refreshSummary.staleContracts ?? null,
|
|
688
|
+
coveragePct: refreshSummary.coveragePct ?? null,
|
|
689
|
+
}
|
|
690
|
+
: {}),
|
|
691
|
+
};
|
|
692
|
+
},
|
|
693
|
+
},
|
|
694
|
+
],
|
|
695
|
+
});
|
|
696
|
+
export default enrichNodesPluginModule;
|
|
697
|
+
export { ENRICH_NODES_PLUGIN_NAME };
|