ceulen 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +100 -1
- package/extensions/index.ts +5 -1
- package/extensions/lib/env.test.ts +147 -0
- package/extensions/lib/env.ts +180 -0
- package/extensions/lib/order.test.ts +74 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +23 -4
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/lib/config.ts +8 -3
- package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
- package/extensions/modules/advisor/index.ts +6 -3
- package/extensions/modules/advisor/test/module.test.ts +31 -0
- package/extensions/modules/classifier/index.ts +55 -1
- package/extensions/modules/classifier/test/classifier.test.ts +62 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/jfind/index.ts +115 -0
- package/extensions/modules/jfind/lib/cascade.ts +377 -0
- package/extensions/modules/jfind/lib/format.ts +12 -0
- package/extensions/modules/jfind/lib/judge.ts +74 -0
- package/extensions/modules/jfind/lib/lexical.ts +232 -0
- package/extensions/modules/jfind/lib/questions.ts +178 -0
- package/extensions/modules/jfind/lib/tree.ts +374 -0
- package/extensions/modules/jfind/test/cascade.test.ts +305 -0
- package/extensions/modules/notify/index.ts +33 -0
- package/extensions/modules/notify/lib/notify.ts +99 -0
- package/extensions/modules/notify/test/notify.test.ts +95 -0
- package/extensions/modules/plan/lib/plan-tools.ts +13 -0
- package/extensions/modules/repair/configPanel.ts +7 -1
- package/extensions/modules/repair/index.ts +158 -3
- package/extensions/modules/repair/lib/auto-generated.ts +89 -0
- package/extensions/modules/repair/lib/read-archive.ts +101 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
- package/extensions/modules/repair/lib/settings.ts +4 -1
- package/extensions/modules/repair/test/freshness.test.ts +41 -1
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +2 -1
- package/extensions/modules/router/configPanel.ts +4 -4
- package/extensions/modules/router/index.ts +1 -1
- package/extensions/modules/router/lib/config.ts +9 -4
- package/extensions/modules/router/lib/systemone.ts +17 -4
- package/extensions/modules/router/test/unit.test.ts +46 -1
- package/extensions/modules/rules/index.ts +13 -3
- package/extensions/modules/rules/lib/rules.ts +24 -12
- package/extensions/modules/rules/test/lib.test.ts +20 -0
- package/extensions/modules/rules/test/module.test.ts +21 -0
- package/extensions/modules/sg/index.ts +129 -0
- package/extensions/modules/sg/lib/ops.ts +144 -0
- package/extensions/modules/sg/lib/sg-cli.ts +104 -0
- package/extensions/modules/sg/test/sg.test.ts +128 -0
- package/extensions/modules/shells/index.ts +210 -0
- package/extensions/modules/shells/lib/sessions.ts +344 -0
- package/extensions/modules/shells/test/sessions.test.ts +275 -0
- package/extensions/modules/subagent/index.ts +11 -5
- package/extensions/modules/subagent/lib/herdr.ts +5 -0
- package/extensions/modules/subagent/lib/routing.ts +31 -8
- package/extensions/modules/subagent/lib/runner.ts +8 -2
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +181 -0
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/extension.test.ts +2 -1
- package/extensions/modules/web/test/settings.test.ts +6 -0
- package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
- package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
- package/package.json +3 -3
|
@@ -142,15 +142,21 @@ export function defaultUserRulesDir(): string {
|
|
|
142
142
|
}
|
|
143
143
|
|
|
144
144
|
/** `<dir>/.pi/RULES.md` from cwd up to the filesystem root, then the user file. */
|
|
145
|
-
export function discoverRuleFiles(cwd: string, userDir = defaultUserRulesDir()): string[] {
|
|
145
|
+
export function discoverRuleFiles(cwd: string, userDir = defaultUserRulesDir(), trusted = true): string[] {
|
|
146
146
|
const files: string[] = [];
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
147
|
+
// Untrusted project: repo-controlled RULES.md (and its @imports) must never
|
|
148
|
+
// reach the system prompt — the same gate as pi's AGENTS.md context files
|
|
149
|
+
// and every other project-file consumer here (subagent agents, settings
|
|
150
|
+
// overlays). Only the user-level file applies.
|
|
151
|
+
if (trusted) {
|
|
152
|
+
let dir = path.resolve(cwd);
|
|
153
|
+
for (;;) {
|
|
154
|
+
const candidate = path.join(dir, PROJECT_DIR, RULES_FILE);
|
|
155
|
+
if (existsSync(candidate)) files.push(candidate);
|
|
156
|
+
const parent = path.dirname(dir);
|
|
157
|
+
if (parent === dir) break;
|
|
158
|
+
dir = parent;
|
|
159
|
+
}
|
|
154
160
|
}
|
|
155
161
|
const user = path.join(userDir, RULES_FILE);
|
|
156
162
|
if (existsSync(user)) files.push(user);
|
|
@@ -193,6 +199,13 @@ function expandImports(text: string, baseDir: string, state: ImportState, depth:
|
|
|
193
199
|
if (state.seen.has(resolved)) return whole;
|
|
194
200
|
|
|
195
201
|
let content: string;
|
|
202
|
+
// Track the target even when the read FAILS: a previously-missing
|
|
203
|
+
// import being CREATED must invalidate the cache — signature() emits
|
|
204
|
+
// `<file>:missing` for absent entries, so the existence flip changes
|
|
205
|
+
// the signature and the next load re-reads (live finding, reviewer
|
|
206
|
+
// 2026-10-06 — creating the file a missing-marker points at is the
|
|
207
|
+
// most likely user fix, and it silently kept serving the marker).
|
|
208
|
+
state.read.add(resolved);
|
|
196
209
|
try {
|
|
197
210
|
content = readFileSync(resolved, "utf8");
|
|
198
211
|
} catch {
|
|
@@ -202,7 +215,6 @@ function expandImports(text: string, baseDir: string, state: ImportState, depth:
|
|
|
202
215
|
return `${lead}[import depth limit reached: @${cleaned}]`;
|
|
203
216
|
}
|
|
204
217
|
state.seen.add(resolved);
|
|
205
|
-
state.read.add(resolved);
|
|
206
218
|
const nested = expandImports(content.trim(), path.dirname(resolved), state, depth + 1);
|
|
207
219
|
return `${lead}${nested}`;
|
|
208
220
|
});
|
|
@@ -282,9 +294,9 @@ export function clearRuleCache(): void {
|
|
|
282
294
|
cache = null;
|
|
283
295
|
}
|
|
284
296
|
|
|
285
|
-
export function loadRules(cwd = process.cwd(), userDir = defaultUserRulesDir()): RuleModel {
|
|
286
|
-
const key = `${path.resolve(cwd)}\u0000${userDir}`;
|
|
287
|
-
const files = discoverRuleFiles(cwd, userDir);
|
|
297
|
+
export function loadRules(cwd = process.cwd(), userDir = defaultUserRulesDir(), trusted = true): RuleModel {
|
|
298
|
+
const key = `${path.resolve(cwd)}\u0000${userDir}\u0000${trusted ? "t" : "u"}`;
|
|
299
|
+
const files = discoverRuleFiles(cwd, userDir, trusted);
|
|
288
300
|
// Track RULES.md files AND previously imported files, so editing an imported
|
|
289
301
|
// doc invalidates the cache too.
|
|
290
302
|
const tracked = new Set([...files, ...(cache?.tracked ?? [])]);
|
|
@@ -254,6 +254,26 @@ describe("mtime cache", () => {
|
|
|
254
254
|
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("BODY-V2"));
|
|
255
255
|
});
|
|
256
256
|
|
|
257
|
+
it("creating a previously-missing @import target invalidates the cache (no /rules reload)", () => {
|
|
258
|
+
// Live finding (reviewer 2026-10-06): only successfully-read files were
|
|
259
|
+
// tracked, so creating the file a [missing import] marker points at
|
|
260
|
+
// changed no tracked mtime — the marker kept serving until RULES.md
|
|
261
|
+
// itself was edited. Missing targets are now tracked (existence flip
|
|
262
|
+
// changes the signature).
|
|
263
|
+
const { cwd, userDir } = workspace();
|
|
264
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\n@later.md\n");
|
|
265
|
+
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("[missing import: @later.md]"));
|
|
266
|
+
|
|
267
|
+
const target = path.join(cwd, ".pi/later.md");
|
|
268
|
+
writeFileSync(target, "ARRIVED\n", "utf8");
|
|
269
|
+
const future = new Date(Date.now() + 5000);
|
|
270
|
+
utimesSync(target, future, future);
|
|
271
|
+
|
|
272
|
+
const body = loadRules(cwd, userDir).rules[0].body;
|
|
273
|
+
assert.ok(body.includes("ARRIVED"), `imported content served without cache drop; got: ${body}`);
|
|
274
|
+
assert.ok(!body.includes("[missing import"));
|
|
275
|
+
});
|
|
276
|
+
|
|
257
277
|
it("returns the cached model unchanged when nothing on disk moved", () => {
|
|
258
278
|
const { cwd, userDir } = workspace();
|
|
259
279
|
write(path.join(cwd, ".pi/RULES.md"), "## a\nstable\n");
|
|
@@ -219,4 +219,25 @@ describe("rules module — /rules command", () => {
|
|
|
219
219
|
await commands.get("rules").handler("bogus", context(workspace(), notes));
|
|
220
220
|
assert.equal(notes[0].level, "error");
|
|
221
221
|
});
|
|
222
|
+
|
|
223
|
+
it("UNTRUSTED project: repo RULES.md never reaches the prompt; user file still applies", async () => {
|
|
224
|
+
// Live-found defect (reviewer 2026-10-06): the composer had no trust gate —
|
|
225
|
+
// an untrusted checkout's RULES.md (and its @imports) landed in every
|
|
226
|
+
// request's system prompt. Same gate as pi's AGENTS.md context files.
|
|
227
|
+
const cwd = workspace({ ".pi/RULES.md": "## project-rule\nPROJECT-SECRET-MARKER\n" });
|
|
228
|
+
const { events } = harness();
|
|
229
|
+
const untrusted = { ...context(cwd), isProjectTrusted: () => false };
|
|
230
|
+
const result = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, untrusted);
|
|
231
|
+
assert.equal(result, undefined, "no project rules for an untrusted checkout");
|
|
232
|
+
|
|
233
|
+
// rule_get honors the same gate (no on-demand exfiltration of bodies).
|
|
234
|
+
const { tools } = harness();
|
|
235
|
+
const got = await tools.get("rule_get")!.execute("t1", { name: "project-rule" }, undefined, undefined, untrusted);
|
|
236
|
+
assert.match(JSON.stringify(got), /not found/i, "untrusted: rule body not served");
|
|
237
|
+
|
|
238
|
+
// Trusted sees them again (and the cache key carries the flag).
|
|
239
|
+
const trustedResult = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, context(cwd));
|
|
240
|
+
assert.ok(trustedResult?.systemPrompt.includes("PROJECT-SECRET-MARKER"));
|
|
241
|
+
});
|
|
222
242
|
});
|
|
243
|
+
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// sg module — structural search & rewrite via the ast-grep CLI (gh-module
|
|
2
|
+
// fail-open pattern): `ast_grep` search + `ast_edit` multi-op rewrites with a
|
|
3
|
+
// dry-run default. Missing binary → the module registers nothing and the
|
|
4
|
+
// /config Enable row stays reachable.
|
|
5
|
+
|
|
6
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
9
|
+
import { realSg, sgAvailable, type SgRunner } from "./lib/sg-cli.js";
|
|
10
|
+
import { buildRunArgs, formatMatches, mergeMatches, parseSearch } from "./lib/ops.js";
|
|
11
|
+
|
|
12
|
+
const LANGUAGE_PARAM = Type.Optional(
|
|
13
|
+
Type.String({ description: 'Tree-sitter language id when the files\' extension is ambiguous — "ts", "tsx", "py", "rust", "go", "java"… (optional; inferred from the extension).' }),
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
async function runSearch(rg: SgRunner, cwd: string, opts: { pattern: string; language?: string; globs?: string[]; paths?: string[] }, signal?: AbortSignal) {
|
|
17
|
+
return parseSearch(await rg.run(cwd, buildRunArgs({ ...opts, json: true }), signal), opts.pattern);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export default function sgModule(pi: ExtensionAPI): void {
|
|
21
|
+
// No sg/ast-grep binary → no tools; /config's Enable row still renders
|
|
22
|
+
// (install + /reload activates).
|
|
23
|
+
if (!sgAvailable()) return;
|
|
24
|
+
|
|
25
|
+
const disabled = readDisabledTools();
|
|
26
|
+
|
|
27
|
+
pi.registerTool({
|
|
28
|
+
name: "ast_grep",
|
|
29
|
+
label: "AST Grep",
|
|
30
|
+
defaultActive: !disabled.has("ast_grep"),
|
|
31
|
+
description:
|
|
32
|
+
"Structural code search via the ast-grep CLI: match AST patterns with meta-variables ($VAR = one node, $$$ALL = many) instead of regex — `$FUNC($$$ARGS)` finds every call. " +
|
|
33
|
+
"Patterns are snippets of real code in the target language. Use for syntax-aware searches regex mangles (calls, imports, JSX). Returns path:line:col + matched text.",
|
|
34
|
+
promptSnippet: "Structural AST code search (ast-grep patterns)",
|
|
35
|
+
promptGuidelines: [
|
|
36
|
+
"Write the pattern as real code with $NAME holes; it must parse in the target language.",
|
|
37
|
+
"Prefer this over regex grep when the shape of the code matters (calls, assignments, JSX tags).",
|
|
38
|
+
"A pattern that fails to parse returns a hint — simplify the pattern or set `language`.",
|
|
39
|
+
],
|
|
40
|
+
parameters: Type.Object({
|
|
41
|
+
pattern: Type.String({ description: "ast-grep pattern (real code with $VAR / $$$ALL meta-variables)." }),
|
|
42
|
+
patterns: Type.Optional(Type.Array(Type.String(), { description: "Extra OR patterns — each is searched and results are merged+deduped." })),
|
|
43
|
+
language: LANGUAGE_PARAM,
|
|
44
|
+
globs: Type.Optional(Type.Array(Type.String(), { description: 'Glob filter, e.g. ["*.ts", "!*.test.ts"].' })),
|
|
45
|
+
paths: Type.Optional(Type.Array(Type.String(), { description: 'Files/directories to search (default ["."]).' })),
|
|
46
|
+
}),
|
|
47
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
48
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
49
|
+
const p = params as { pattern: string; patterns?: string[]; language?: string; globs?: string[]; paths?: string[] };
|
|
50
|
+
const all = [p.pattern, ...(p.patterns ?? [])];
|
|
51
|
+
try {
|
|
52
|
+
const runs = await Promise.all(
|
|
53
|
+
all.map((pattern) => runSearch(realSg, cwd, { pattern, language: p.language, globs: p.globs, paths: p.paths }, signal)),
|
|
54
|
+
);
|
|
55
|
+
const merged = mergeMatches(runs);
|
|
56
|
+
const patternError = merged.patternError;
|
|
57
|
+
if (patternError) {
|
|
58
|
+
return { content: [{ type: "text", text: patternError }], isError: true as const, details: { pattern: p.pattern } };
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
content: [{ type: "text", text: formatMatches(merged.matches, all.join(" | ")) }],
|
|
62
|
+
details: { matches: merged.matches.length },
|
|
63
|
+
};
|
|
64
|
+
} catch (err) {
|
|
65
|
+
return { content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }], isError: true as const, details: { pattern: p.pattern } };
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
pi.registerTool({
|
|
71
|
+
name: "ast_edit",
|
|
72
|
+
label: "AST Edit",
|
|
73
|
+
defaultActive: !disabled.has("ast_edit"),
|
|
74
|
+
description:
|
|
75
|
+
"Structural code rewrite via the ast-grep CLI: one pattern → rewrite pair applied across files (the rewrite reuses $VAR / $$$ALL meta-variables). " +
|
|
76
|
+
"DRY-RUN BY DEFAULT: returns the per-file diff without touching disk. Pass write:true to apply (files are rewritten in place; NOT atomic across files). " +
|
|
77
|
+
"After applying, the match count is re-checked and reported so silent misses (a rewrite that generates new matches) are visible.",
|
|
78
|
+
promptSnippet: "Structural AST rewrite (ast-grep), dry-run by default",
|
|
79
|
+
promptGuidelines: [
|
|
80
|
+
"Always inspect the dry-run diff before write:true — rewrites apply to every match in scope.",
|
|
81
|
+
"The rewrite is a code template reusing the pattern's meta-variables ($VAR stays, text around it changes).",
|
|
82
|
+
"Scope rewrites with paths/globs; use for mechanical multi-file refactors, not one-line edits (edit wins there).",
|
|
83
|
+
],
|
|
84
|
+
parameters: Type.Object({
|
|
85
|
+
pattern: Type.String({ description: "ast-grep pattern (real code with $VAR / $$$ALL meta-variables)." }),
|
|
86
|
+
rewrite: Type.String({ description: "Rewrite template reusing the pattern's meta-variables." }),
|
|
87
|
+
language: LANGUAGE_PARAM,
|
|
88
|
+
globs: Type.Optional(Type.Array(Type.String(), { description: 'Glob filter, e.g. ["src/**"].' })),
|
|
89
|
+
paths: Type.Optional(Type.Array(Type.String(), { description: 'Files/directories to rewrite (default ["."]).' })),
|
|
90
|
+
write: Type.Optional(Type.Boolean({ default: false, description: "false (default) = dry-run diff only; true = rewrite the files on disk." })),
|
|
91
|
+
}),
|
|
92
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
93
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
94
|
+
const p = params as { pattern: string; rewrite: string; language?: string; globs?: string[]; paths?: string[]; write?: boolean };
|
|
95
|
+
try {
|
|
96
|
+
const before = await runSearch(realSg, cwd, { pattern: p.pattern, language: p.language, globs: p.globs, paths: p.paths }, signal);
|
|
97
|
+
if (before.patternError) {
|
|
98
|
+
return { content: [{ type: "text", text: before.patternError }], isError: true as const, details: { pattern: p.pattern } };
|
|
99
|
+
}
|
|
100
|
+
if (before.noMatches) {
|
|
101
|
+
return { content: [{ type: "text", text: `no matches for ${p.pattern} — nothing to rewrite` }], details: { matches: 0 } };
|
|
102
|
+
}
|
|
103
|
+
if (p.write !== true) {
|
|
104
|
+
const preview = await realSg.run(cwd, buildRunArgs({ pattern: p.pattern, rewrite: p.rewrite, language: p.language, globs: p.globs, paths: p.paths }), signal);
|
|
105
|
+
const files = [...new Set(before.matches.map((m) => m.file))];
|
|
106
|
+
let text = `DRY-RUN — ${before.matches.length} match(es) across ${files.length} file(s) would change:\n${files.map((f) => ` ${f}`).join("\n")}\n\n${preview.stdout.trim()}`;
|
|
107
|
+
if (text.length > 16_000) text = `${text.slice(0, 16_000)}\n[… preview truncated — narrow paths/globs …]`;
|
|
108
|
+
return { content: [{ type: "text", text }], details: { matches: before.matches.length, files } };
|
|
109
|
+
}
|
|
110
|
+
const apply = await realSg.run(cwd, buildRunArgs({ pattern: p.pattern, rewrite: p.rewrite, language: p.language, globs: p.globs, paths: p.paths, update: true }), signal);
|
|
111
|
+
if (apply.exitCode !== 0) {
|
|
112
|
+
throw new Error(`sg -U rewrite failed (exit ${apply.exitCode}): ${apply.stderr.slice(0, 300) || apply.stdout.slice(0, 300)}`);
|
|
113
|
+
}
|
|
114
|
+
// Staleness check: a rewrite that produces fresh matches means the
|
|
115
|
+
// rule isn't idempotent — surface it instead of silently looping
|
|
116
|
+
// later callers into re-applying.
|
|
117
|
+
const after = await runSearch(realSg, cwd, { pattern: p.pattern, language: p.language, globs: p.globs, paths: p.paths }, signal);
|
|
118
|
+
const files = [...new Set(before.matches.map((m) => m.file))];
|
|
119
|
+
let text = `rewrote ${before.matches.length} match(es) across ${files.length} file(s):\n${files.map((f) => ` ${f}`).join("\n")}`;
|
|
120
|
+
if (!after.noMatches) {
|
|
121
|
+
text += `\nnote: ${after.matches.length} match(es) REMAIN post-rewrite — the rewrite generates new matches for its own pattern; re-running would loop.`;
|
|
122
|
+
}
|
|
123
|
+
return { content: [{ type: "text", text }], details: { matches: before.matches.length, files, remaining: after.matches.length } };
|
|
124
|
+
} catch (err) {
|
|
125
|
+
return { content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }], isError: true as const, details: { pattern: p.pattern } };
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// sg ops — pure arg-building / parsing / formatting over the sg CLI facts
|
|
2
|
+
// (verified against ast-grep 0.45.3):
|
|
3
|
+
// run -p PAT [-l LANG] [--globs G]… [PATHS…] --json=compact
|
|
4
|
+
// → one JSON array of matches; exit 1 + "[]" = NO MATCHES (not an error);
|
|
5
|
+
// stderr carrying "ERROR node" = the pattern failed to parse; exit 9 =
|
|
6
|
+
// bad args (bad glob). range.start.line/column are 0-BASED.
|
|
7
|
+
// run -p PAT -r REW … (no -U) → per-file diff preview (dry-run).
|
|
8
|
+
// run -p PAT -r REW … -U → writes files, prints NOTHING on success.
|
|
9
|
+
|
|
10
|
+
export interface SgMatch {
|
|
11
|
+
file: string;
|
|
12
|
+
/** 1-based (converted from sg's 0-based range). */
|
|
13
|
+
line: number;
|
|
14
|
+
column: number;
|
|
15
|
+
text: string;
|
|
16
|
+
/** Dedup key from sg's byte offsets. */
|
|
17
|
+
byteStart: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ParsedSg {
|
|
21
|
+
matches: SgMatch[];
|
|
22
|
+
noMatches: boolean;
|
|
23
|
+
patternError?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface RawSgMatch {
|
|
27
|
+
text?: string;
|
|
28
|
+
file?: string;
|
|
29
|
+
range?: { start?: { line?: number; column?: number }; end?: { line?: number; column?: number } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Build `run` args for a search (or rewrite preview when rewrite given). */
|
|
33
|
+
export function buildRunArgs(opts: {
|
|
34
|
+
pattern: string;
|
|
35
|
+
rewrite?: string;
|
|
36
|
+
language?: string;
|
|
37
|
+
globs?: string[];
|
|
38
|
+
paths?: string[];
|
|
39
|
+
update?: boolean;
|
|
40
|
+
json?: boolean;
|
|
41
|
+
}): string[] {
|
|
42
|
+
const args = ["run", "-p", opts.pattern];
|
|
43
|
+
if (opts.rewrite !== undefined) args.push("-r", opts.rewrite);
|
|
44
|
+
if (opts.language) args.push("-l", opts.language);
|
|
45
|
+
for (const g of opts.globs ?? []) args.push("--globs", g);
|
|
46
|
+
if (opts.update) args.push("-U");
|
|
47
|
+
if (opts.json) args.push("--json=compact");
|
|
48
|
+
args.push(...(opts.paths && opts.paths.length > 0 ? opts.paths : ["."]));
|
|
49
|
+
return args;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Parse a `--json=compact` search result. Exit 1 with an empty array is a
|
|
53
|
+
* NO-MATCH, not an error; a pattern-parse failure ("ERROR node" stderr on
|
|
54
|
+
* older sg, exit 8 + "Cannot parse query" on ast-grep 0.4x) is a
|
|
55
|
+
* patternError — the tools render it as a hint, not a tool crash. */
|
|
56
|
+
export function parseSearch(result: { exitCode: number; stdout: string; stderr: string }, pattern: string): ParsedSg {
|
|
57
|
+
if (
|
|
58
|
+
result.stderr.includes("ERROR node") ||
|
|
59
|
+
(result.exitCode !== 0 && /Cannot parse query|Multiple AST nodes are detected/.test(result.stderr))
|
|
60
|
+
) {
|
|
61
|
+
return { matches: [], noMatches: true, patternError: `pattern failed to parse: ${pattern}${firstLine(result.stderr)}` };
|
|
62
|
+
}
|
|
63
|
+
let raw: unknown;
|
|
64
|
+
try {
|
|
65
|
+
raw = JSON.parse(result.stdout);
|
|
66
|
+
} catch {
|
|
67
|
+
throw new Error(`sg returned non-JSON output (exit ${result.exitCode}): ${result.stdout.slice(0, 200) || result.stderr.slice(0, 200)}`);
|
|
68
|
+
}
|
|
69
|
+
if (!Array.isArray(raw)) {
|
|
70
|
+
throw new Error(`sg returned unexpected output (exit ${result.exitCode}): ${result.stdout.slice(0, 200)}`);
|
|
71
|
+
}
|
|
72
|
+
const matches = (raw as RawSgMatch[])
|
|
73
|
+
.filter((m) => typeof m.file === "string")
|
|
74
|
+
.map((m) => ({
|
|
75
|
+
file: m.file!,
|
|
76
|
+
// sg's range is 0-based — surface 1-based editor coordinates.
|
|
77
|
+
line: (m.range?.start?.line ?? 0) + 1,
|
|
78
|
+
column: (m.range?.start?.column ?? 0) + 1,
|
|
79
|
+
text: m.text ?? "",
|
|
80
|
+
byteStart: byteStartOf(m),
|
|
81
|
+
}));
|
|
82
|
+
return { matches, noMatches: matches.length === 0 };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function byteStartOf(m: RawSgMatch): number {
|
|
86
|
+
const bo = (m as { range?: { byteOffset?: { start?: number } } }).range?.byteOffset?.start;
|
|
87
|
+
if (typeof bo === "number") return bo;
|
|
88
|
+
// Older sg without byteOffset: fall back to a file+position key (deduped
|
|
89
|
+
// per-run anyway — cross-run dedupe just keeps both, harmless).
|
|
90
|
+
return -1;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function firstLine(stderr: string): string {
|
|
94
|
+
const line = stderr.split("\n").find((l) => l.trim().length > 0);
|
|
95
|
+
return line ? ` (${line.trim().slice(0, 160)})` : "";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Merge sequential-run results, deduping by file + byte offset. */
|
|
99
|
+
export function mergeMatches(runs: ParsedSg[]): ParsedSg {
|
|
100
|
+
const patternError = runs.find((r) => r.patternError)?.patternError;
|
|
101
|
+
const seen = new Set<string>();
|
|
102
|
+
const matches: SgMatch[] = [];
|
|
103
|
+
for (const run of runs) {
|
|
104
|
+
for (const m of run.matches) {
|
|
105
|
+
const key = `${m.file}:${m.byteStart}`;
|
|
106
|
+
if (m.byteStart >= 0 && seen.has(key)) continue;
|
|
107
|
+
seen.add(key);
|
|
108
|
+
matches.push(m);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { matches, noMatches: matches.length === 0 && !patternError, patternError };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Render matches: `path:line:col text`. */
|
|
115
|
+
export function formatMatches(matches: SgMatch[], pattern: string, maxMatches = 200): string {
|
|
116
|
+
if (matches.length === 0) return `no matches for ${pattern}`;
|
|
117
|
+
const shown = matches.slice(0, maxMatches);
|
|
118
|
+
const lines = shown.map((m) => {
|
|
119
|
+
const text = m.text.length > 200 ? `${m.text.slice(0, 197)}…` : m.text;
|
|
120
|
+
return `${m.file}:${m.line}:${m.column} ${text.replaceAll("\n", "\\n")}`;
|
|
121
|
+
});
|
|
122
|
+
if (matches.length > shown.length) {
|
|
123
|
+
lines.push(`… ${matches.length - shown.length} more (showing ${shown.length} of ${matches.length})`);
|
|
124
|
+
}
|
|
125
|
+
return lines.join("\n");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Split a dry-run diff preview into per-file sections (`path\n@@ …`). */
|
|
129
|
+
export function parseDiffOutput(stdout: string): Array<{ file: string; diff: string }> {
|
|
130
|
+
const out: Array<{ file: string; diff: string }> = [];
|
|
131
|
+
const lines = stdout.split("\n");
|
|
132
|
+
let current: { file: string; lines: string[] } | undefined;
|
|
133
|
+
for (const line of lines) {
|
|
134
|
+
// File headers are bare relative paths (no @@, no gutter glyphs).
|
|
135
|
+
if (line.length > 0 && !line.startsWith("@@") && !/^\s*[0-9]+\s*[│|]/.test(line) && !/^[│\-+ ]/.test(line) && line === line.trim() && !line.includes("│")) {
|
|
136
|
+
if (current) out.push({ file: current.file, diff: current.lines.join("\n") });
|
|
137
|
+
current = { file: line, lines: [] };
|
|
138
|
+
} else if (current) {
|
|
139
|
+
current.lines.push(line);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (current) out.push({ file: current.file, diff: current.lines.join("\n") });
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// The `sg`/`ast-grep` CLI runner — the single seam every op goes through
|
|
2
|
+
// (gh-module pattern: injected fake in tests). Zero deps.
|
|
3
|
+
//
|
|
4
|
+
// Env contract: NO_COLOR/CLICOLOR/CLICOLOR_FORCE pinned OFF — the user's
|
|
5
|
+
// CLICOLOR_FORCE=1 otherwise colorizes piped JSON and breaks parsing (the
|
|
6
|
+
// live gh bug, same fix).
|
|
7
|
+
|
|
8
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
9
|
+
|
|
10
|
+
/** Deadline for one sg invocation. */
|
|
11
|
+
export const SG_TIMEOUT_MS = 30_000;
|
|
12
|
+
/** Captured-output cap per stream. */
|
|
13
|
+
export const SG_OUTPUT_LIMIT_BYTES = 2 * 1024 * 1024;
|
|
14
|
+
const TRUNCATION_MARKER = "\n[sg output truncated after 2 MiB]\n";
|
|
15
|
+
|
|
16
|
+
/** sg / ast-grep with color forced OFF. */
|
|
17
|
+
export function sgEnv(): NodeJS.ProcessEnv {
|
|
18
|
+
return {
|
|
19
|
+
...process.env,
|
|
20
|
+
NO_COLOR: "1",
|
|
21
|
+
CLICOLOR: "0",
|
|
22
|
+
CLICOLOR_FORCE: "0",
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SgCommandResult {
|
|
27
|
+
exitCode: number;
|
|
28
|
+
stdout: string;
|
|
29
|
+
stderr: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The seam every op goes through — swapped for a fake in tests. */
|
|
33
|
+
export interface SgRunner {
|
|
34
|
+
/** Run sg; does NOT throw on non-zero exit. */
|
|
35
|
+
run(cwd: string, args: string[], signal?: AbortSignal): Promise<SgCommandResult>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let availableCache: string | null | undefined;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolve the sg binary: `ast-grep` first (the maintained name; `sg` prints a
|
|
42
|
+
* deprecation warning to stderr on every call), falling back to `sg`. Cached.
|
|
43
|
+
* Null when neither is installed (module registration is fail-open on this).
|
|
44
|
+
*/
|
|
45
|
+
export function sgBinary(): string | null {
|
|
46
|
+
if (availableCache !== undefined) return availableCache;
|
|
47
|
+
availableCache = null;
|
|
48
|
+
for (const bin of ["ast-grep", "sg"]) {
|
|
49
|
+
try {
|
|
50
|
+
const probe = spawnSync(bin, ["--version"], { stdio: "ignore", timeout: 10_000 });
|
|
51
|
+
if (!probe.error && probe.status === 0) {
|
|
52
|
+
availableCache = bin;
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
// try the next candidate
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return availableCache;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Test hook: forget the probed binary (module state outlives a test). */
|
|
63
|
+
export function resetSgBinaryCache(): void {
|
|
64
|
+
availableCache = undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** True when an sg CLI is installed (cached after the first probe). */
|
|
68
|
+
export function sgAvailable(): boolean {
|
|
69
|
+
return sgBinary() !== null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const realSg: SgRunner = {
|
|
73
|
+
run(cwd, args, signal) {
|
|
74
|
+
const bin = sgBinary();
|
|
75
|
+
if (!bin) {
|
|
76
|
+
return Promise.reject(new Error("ast-grep CLI is not installed — install with `brew install ast-grep` or `npm i -g @ast-grep/cli`."));
|
|
77
|
+
}
|
|
78
|
+
return new Promise<SgCommandResult>((resolveP, rejectP) => {
|
|
79
|
+
const timeout = AbortSignal.timeout(SG_TIMEOUT_MS);
|
|
80
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
81
|
+
const child = spawn(bin, args, { cwd, env: sgEnv(), stdio: ["ignore", "pipe", "pipe"], signal: combined });
|
|
82
|
+
const out: Buffer[] = [];
|
|
83
|
+
const err: Buffer[] = [];
|
|
84
|
+
let outTotal = 0;
|
|
85
|
+
let errTotal = 0;
|
|
86
|
+
child.stdout!.on("data", (chunk: Buffer) => {
|
|
87
|
+
outTotal += chunk.length;
|
|
88
|
+
if (outTotal <= SG_OUTPUT_LIMIT_BYTES) out.push(chunk);
|
|
89
|
+
});
|
|
90
|
+
child.stderr!.on("data", (chunk: Buffer) => {
|
|
91
|
+
errTotal += chunk.length;
|
|
92
|
+
if (errTotal <= SG_OUTPUT_LIMIT_BYTES) err.push(chunk);
|
|
93
|
+
});
|
|
94
|
+
child.on("error", rejectP);
|
|
95
|
+
child.on("close", (code) => {
|
|
96
|
+
let stdout = Buffer.concat(out).toString("utf8");
|
|
97
|
+
if (outTotal > SG_OUTPUT_LIMIT_BYTES) stdout += TRUNCATION_MARKER;
|
|
98
|
+
let stderr = Buffer.concat(err).toString("utf8");
|
|
99
|
+
if (errTotal > SG_OUTPUT_LIMIT_BYTES) stderr += TRUNCATION_MARKER;
|
|
100
|
+
resolveP({ exitCode: code ?? -1, stdout, stderr });
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
},
|
|
104
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// sg module unit tests — fake SgRunner (scripted arg-matching, gh.test.ts
|
|
2
|
+
// pattern). No real sg spawns; the binary is not assumed present.
|
|
3
|
+
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { describe, it } from "node:test";
|
|
6
|
+
import { sgBinary, type SgRunner } from "../lib/sg-cli.js";
|
|
7
|
+
import {
|
|
8
|
+
buildRunArgs,
|
|
9
|
+
formatMatches,
|
|
10
|
+
mergeMatches,
|
|
11
|
+
parseDiffOutput,
|
|
12
|
+
parseSearch,
|
|
13
|
+
type SgMatch,
|
|
14
|
+
} from "../lib/ops.js";
|
|
15
|
+
|
|
16
|
+
function sgMatch(over: Partial<SgMatch>): SgMatch {
|
|
17
|
+
return { file: "a.ts", line: 2, column: 3, text: "return 1;", byteStart: 26, ...over };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const SEARCH_JSON = JSON.stringify([
|
|
21
|
+
{ text: "return 1;", range: { byteOffset: { start: 26, end: 35 }, start: { line: 1, column: 2 }, end: { line: 1, column: 11 } }, file: "a.ts", lines: " return 1;" },
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
describe("buildRunArgs", () => {
|
|
25
|
+
it("search: pattern + json + default path", () => {
|
|
26
|
+
assert.deepEqual(buildRunArgs({ pattern: "return 1", json: true }), ["run", "-p", "return 1", "--json=compact", "."]);
|
|
27
|
+
});
|
|
28
|
+
it("language, globs, paths", () => {
|
|
29
|
+
const args = buildRunArgs({ pattern: "P", language: "ts", globs: ["*.ts"], paths: ["src", "lib"], json: true });
|
|
30
|
+
assert.deepEqual(args, ["run", "-p", "P", "-l", "ts", "--globs", "*.ts", "--json=compact", "src", "lib"]);
|
|
31
|
+
});
|
|
32
|
+
it("rewrite dry-run has NO -U; apply adds it", () => {
|
|
33
|
+
const dry = buildRunArgs({ pattern: "P", rewrite: "R", json: true });
|
|
34
|
+
assert.equal(dry.includes("-U"), false);
|
|
35
|
+
assert.ok(dry.includes("-r"));
|
|
36
|
+
const apply = buildRunArgs({ pattern: "P", rewrite: "R", update: true });
|
|
37
|
+
assert.equal(apply.includes("-U"), true);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe("parseSearch", () => {
|
|
42
|
+
it("converts 0-based range to 1-based display", () => {
|
|
43
|
+
const r = parseSearch({ exitCode: 0, stdout: SEARCH_JSON, stderr: "" }, "return 1");
|
|
44
|
+
assert.equal(r.matches[0]!.line, 2);
|
|
45
|
+
assert.equal(r.matches[0]!.column, 3);
|
|
46
|
+
assert.equal(r.noMatches, false);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("exit 1 + empty array = no matches, NOT an error", () => {
|
|
50
|
+
const r = parseSearch({ exitCode: 1, stdout: "[]", stderr: "" }, "zzz");
|
|
51
|
+
assert.equal(r.noMatches, true);
|
|
52
|
+
assert.deepEqual(r.matches, []);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("ERROR node stderr → pattern error with remediation text", () => {
|
|
56
|
+
const r = parseSearch({ exitCode: 0, stdout: "[]", stderr: "Warning: Pattern contains an ERROR node and may cause unexpected results." }, "((((");
|
|
57
|
+
assert.match(r.patternError!, /pattern failed to parse/);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("non-JSON stdout throws (bad args surface loudly)", () => {
|
|
61
|
+
assert.throws(() => parseSearch({ exitCode: 9, stdout: "error: unexpected argument", stderr: "" }, "x"), /non-JSON/);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("matches without byteOffset still parse (dedupe key -1)", () => {
|
|
65
|
+
const legacy = JSON.stringify([{ text: "x", file: "f.ts", range: { start: { line: 0, column: 0 } } }]);
|
|
66
|
+
const r = parseSearch({ exitCode: 0, stdout: legacy, stderr: "" }, "x");
|
|
67
|
+
assert.equal(r.matches[0]!.byteStart, -1);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe("mergeMatches", () => {
|
|
72
|
+
it("dedupes by file + byteStart across sequential runs", () => {
|
|
73
|
+
const a = { matches: [sgMatch({ byteStart: 5 }), sgMatch({ file: "b.ts", byteStart: 7 })], noMatches: false };
|
|
74
|
+
const b = { matches: [sgMatch({ byteStart: 5 }), sgMatch({ byteStart: 9 })], noMatches: false };
|
|
75
|
+
const merged = mergeMatches([a, b]);
|
|
76
|
+
assert.equal(merged.matches.length, 3);
|
|
77
|
+
});
|
|
78
|
+
it("keeps -1-keyed legacy matches (no false dedupe)", () => {
|
|
79
|
+
const a = { matches: [sgMatch({ byteStart: -1, line: 1 })], noMatches: false };
|
|
80
|
+
const b = { matches: [sgMatch({ byteStart: -1, line: 5 })], noMatches: false };
|
|
81
|
+
assert.equal(mergeMatches([a, b]).matches.length, 2);
|
|
82
|
+
});
|
|
83
|
+
it("surfaces a pattern error from any run", () => {
|
|
84
|
+
const merged = mergeMatches([{ matches: [], noMatches: true }, { matches: [], noMatches: true, patternError: "bad" }]);
|
|
85
|
+
assert.equal(merged.patternError, "bad");
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe("formatMatches", () => {
|
|
90
|
+
it("path:line:col + text, capped with a footer", () => {
|
|
91
|
+
const matches = Array.from({ length: 250 }, (_, i) => sgMatch({ file: `f${i}.ts`, line: i + 1, column: 1, byteStart: i }));
|
|
92
|
+
const out = formatMatches(matches, "pat");
|
|
93
|
+
const lines = out.split("\n");
|
|
94
|
+
assert.match(lines[0]!, /^f0\.ts:1:1 return 1;$/);
|
|
95
|
+
assert.match(lines.at(-1)!, /showing 200 of 250/);
|
|
96
|
+
});
|
|
97
|
+
it("empty → friendly no-match line", () => {
|
|
98
|
+
assert.equal(formatMatches([], "pat"), "no matches for pat");
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
describe("parseDiffOutput", () => {
|
|
103
|
+
it("splits per-file sections on bare-path headers", () => {
|
|
104
|
+
const stdout = [
|
|
105
|
+
"a.ts",
|
|
106
|
+
"@@ -0,3 +0,3 @@",
|
|
107
|
+
"1 1│ export function foo() {",
|
|
108
|
+
" │- return 1;",
|
|
109
|
+
" 2│+ return 2",
|
|
110
|
+
"sub/c.ts",
|
|
111
|
+
"@@ -0,3 +0,3 @@",
|
|
112
|
+
"2 │- return 1;",
|
|
113
|
+
].join("\n");
|
|
114
|
+
const sections = parseDiffOutput(stdout);
|
|
115
|
+
assert.deepEqual(sections.map((s) => s.file), ["a.ts", "sub/c.ts"]);
|
|
116
|
+
assert.match(sections[0]!.diff, /return 2/);
|
|
117
|
+
assert.match(sections[1]!.diff, /return 1;/);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe("binary probe", () => {
|
|
122
|
+
it("sgBinary returns a name or null without throwing", () => {
|
|
123
|
+
// Cached after first call; on this dev machine ast-grep IS installed,
|
|
124
|
+
// but the test only asserts the shape (CI has no binary).
|
|
125
|
+
const bin = sgBinary();
|
|
126
|
+
assert.ok(bin === null || bin === "ast-grep" || bin === "sg");
|
|
127
|
+
});
|
|
128
|
+
});
|