@stupify/cli 0.0.2 → 0.0.4
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 +55 -0
- package/dist/analysis.d.ts +16 -0
- package/dist/analysis.js +133 -0
- package/dist/cache.d.ts +2 -0
- package/dist/cache.js +59 -0
- package/dist/checks.d.ts +4 -0
- package/dist/checks.js +218 -0
- package/dist/command.d.ts +2 -0
- package/dist/command.js +147 -0
- package/dist/constants.d.ts +4 -0
- package/dist/constants.js +53 -0
- package/dist/counter-scout.d.ts +14 -0
- package/dist/counter-scout.js +159 -0
- package/dist/diff.d.ts +1 -0
- package/dist/diff.js +10 -0
- package/dist/doctor.d.ts +4 -0
- package/dist/doctor.js +131 -0
- package/dist/git.d.ts +11 -0
- package/dist/git.js +253 -0
- package/dist/hooks.d.ts +3 -0
- package/dist/hooks.js +117 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/model.d.ts +10 -0
- package/dist/model.js +297 -0
- package/dist/prompts.d.ts +8 -0
- package/dist/prompts.js +87 -0
- package/dist/render.d.ts +3 -0
- package/dist/render.js +93 -0
- package/dist/repomix-provider.d.ts +12 -0
- package/dist/repomix-provider.js +196 -0
- package/dist/search-bench.d.ts +1 -0
- package/dist/search-bench.js +675 -0
- package/dist/search-profile.d.ts +6 -0
- package/dist/search-profile.js +73 -0
- package/dist/sem-provider.d.ts +2 -0
- package/dist/sem-provider.js +247 -0
- package/dist/stupify.d.ts +4 -0
- package/dist/stupify.js +237 -0
- package/dist/trace.d.ts +29 -0
- package/dist/trace.js +64 -0
- package/dist/types.d.ts +320 -0
- package/dist/types.js +6 -0
- package/package.json +42 -5
- package/src/analysis.ts +188 -0
- package/src/cache.ts +65 -0
- package/src/checks.ts +221 -0
- package/src/command.ts +173 -0
- package/src/constants.ts +56 -0
- package/src/counter-scout.ts +175 -0
- package/src/diff.ts +9 -0
- package/src/doctor.ts +140 -0
- package/src/git.ts +262 -0
- package/src/hooks.ts +134 -0
- package/src/index.ts +1 -0
- package/src/model.ts +373 -0
- package/src/prompts.ts +98 -0
- package/src/render.ts +96 -0
- package/src/repomix-provider.ts +219 -0
- package/src/search-bench.ts +783 -0
- package/src/search-profile.ts +89 -0
- package/src/sem-provider.ts +282 -0
- package/src/stupify.ts +285 -0
- package/src/trace.ts +103 -0
- package/src/types.ts +340 -0
- package/bin/stupify.mjs +0 -3
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { defaultChecks, searchChecks } from "./checks.ts";
|
|
4
|
+
import type {
|
|
5
|
+
RepomixSearchConfig,
|
|
6
|
+
SearchProfile,
|
|
7
|
+
SearchProfilePattern,
|
|
8
|
+
StupifyCheck,
|
|
9
|
+
} from "./types.ts";
|
|
10
|
+
|
|
11
|
+
export async function loadSearchProfile(profilePath: string | null): Promise<SearchProfile | null> {
|
|
12
|
+
if (!profilePath) return null;
|
|
13
|
+
const fullPath = path.resolve(profilePath);
|
|
14
|
+
const value = JSON.parse(await readFile(fullPath, "utf8")) as SearchProfile;
|
|
15
|
+
if (!value || typeof value !== "object" || typeof value.id !== "string" || value.id.length === 0) {
|
|
16
|
+
throw new Error(`Invalid search profile: ${profilePath}`);
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function effectiveSearchChecks(
|
|
22
|
+
explicitCheckIds: readonly string[] | null,
|
|
23
|
+
profile: SearchProfile | null,
|
|
24
|
+
): readonly StupifyCheck[] {
|
|
25
|
+
const checks = explicitCheckIds
|
|
26
|
+
? searchChecks(explicitCheckIds)
|
|
27
|
+
: profilePatternIds(profile).length > 0
|
|
28
|
+
? checksById(profilePatternIds(profile))
|
|
29
|
+
: searchChecks(null);
|
|
30
|
+
|
|
31
|
+
if (!profile?.patterns) return checks;
|
|
32
|
+
return checks.map((check) => applyPatternOverride(check, profile.patterns?.[check.id]));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function effectiveMaxCandidates(defaultValue: number, profile: SearchProfile | null): number {
|
|
36
|
+
return positiveInteger(profile?.maxCandidates) ?? defaultValue;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function effectiveMaxSearchInputTokens(defaultValue: number, profile: SearchProfile | null): number {
|
|
40
|
+
return positiveInteger(profile?.maxSearchInputTokens) ?? defaultValue;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function effectiveRepomixConfig(
|
|
44
|
+
defaultValue: RepomixSearchConfig,
|
|
45
|
+
profile: SearchProfile | null,
|
|
46
|
+
): RepomixSearchConfig {
|
|
47
|
+
const override = profile?.repomix;
|
|
48
|
+
if (!override) return defaultValue;
|
|
49
|
+
return {
|
|
50
|
+
compress: override.compress ?? defaultValue.compress,
|
|
51
|
+
showLineNumbers: override.showLineNumbers ?? defaultValue.showLineNumbers,
|
|
52
|
+
removeEmptyLines: override.removeEmptyLines ?? defaultValue.removeEmptyLines,
|
|
53
|
+
maxFileSizeBytes: positiveInteger(override.maxFileBytes) ?? defaultValue.maxFileSizeBytes,
|
|
54
|
+
maxTotalSizeBytes: positiveInteger(override.maxTotalBytes) ?? defaultValue.maxTotalSizeBytes,
|
|
55
|
+
ignorePatterns: override.ignorePatterns ?? defaultValue.ignorePatterns,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function profilePatternIds(profile: SearchProfile | null): readonly string[] {
|
|
60
|
+
if (!profile?.patterns) return [];
|
|
61
|
+
return Object.entries(profile.patterns)
|
|
62
|
+
.filter(([, pattern]) => pattern.enabled === true)
|
|
63
|
+
.map(([id]) => id);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function checksById(ids: readonly string[]): readonly StupifyCheck[] {
|
|
67
|
+
const byId = new Map<string, StupifyCheck>(defaultChecks.map((check) => [check.id, check]));
|
|
68
|
+
return ids.map((id) => {
|
|
69
|
+
const check = byId.get(id);
|
|
70
|
+
if (!check) throw new Error(`Unknown check in search profile: ${id}`);
|
|
71
|
+
return check;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function applyPatternOverride(check: StupifyCheck, override: SearchProfilePattern | undefined): StupifyCheck {
|
|
76
|
+
if (!override) return check;
|
|
77
|
+
return {
|
|
78
|
+
...check,
|
|
79
|
+
searchPrompt: override.searchPrompt ?? check.searchPrompt,
|
|
80
|
+
searchExamples: {
|
|
81
|
+
match: override.matchExamples ?? check.searchExamples?.match ?? check.examples?.match ?? [],
|
|
82
|
+
nonMatch: override.nonMatchExamples ?? check.searchExamples?.nonMatch ?? check.examples?.noMatch ?? [],
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function positiveInteger(value: unknown): number | null {
|
|
88
|
+
return Number.isInteger(value) && Number(value) > 0 ? Number(value) : null;
|
|
89
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { mkdtemp, realpath, rm } from "node:fs/promises";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { cachedJson, fingerprint } from "./cache.ts";
|
|
8
|
+
import { readDiffFromStdin } from "./diff.ts";
|
|
9
|
+
import {
|
|
10
|
+
sourceRangeForCommit,
|
|
11
|
+
sourceRangeForRecentCommits,
|
|
12
|
+
sourceRangeSince,
|
|
13
|
+
stagedDiff,
|
|
14
|
+
} from "./git.ts";
|
|
15
|
+
import type {
|
|
16
|
+
SearchCommand,
|
|
17
|
+
SemChange,
|
|
18
|
+
SemChangeSet,
|
|
19
|
+
SemChangeSummary,
|
|
20
|
+
SourceRange,
|
|
21
|
+
} from "./types.ts";
|
|
22
|
+
import { sourceId } from "./types.ts";
|
|
23
|
+
|
|
24
|
+
const execFileAsync = promisify(execFile);
|
|
25
|
+
|
|
26
|
+
export async function semChangeSetForCommand(
|
|
27
|
+
command: SearchCommand,
|
|
28
|
+
): Promise<SemChangeSet> {
|
|
29
|
+
if (command.kind === "stdin") return semChangeSetFromPatch(await readDiffFromStdin(), command.debugSem);
|
|
30
|
+
if (command.kind === "staged") {
|
|
31
|
+
const diff = await stagedDiff();
|
|
32
|
+
if (!diff.text.trim()) return emptyChangeSet("staged", diff.stats);
|
|
33
|
+
return semChangeSetFromPatch(diff.text, command.debugSem, "staged");
|
|
34
|
+
}
|
|
35
|
+
if (command.kind === "commit") {
|
|
36
|
+
const range = await sourceRangeForCommit(command.commit);
|
|
37
|
+
const raw = await cachedSemDiff(
|
|
38
|
+
["diff", "--commit", command.commit, "--format", "json"],
|
|
39
|
+
range,
|
|
40
|
+
command.debugSem,
|
|
41
|
+
);
|
|
42
|
+
return withContextWorkspace(normalizeSemDiff(raw, range), command.debugSem);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const range = await semRangeForCommand(command);
|
|
46
|
+
const raw = await cachedSemDiff(
|
|
47
|
+
["diff", "--from", range.base, "--to", range.target, "--format", "json"],
|
|
48
|
+
range,
|
|
49
|
+
command.debugSem,
|
|
50
|
+
);
|
|
51
|
+
return withContextWorkspace(normalizeSemDiff(raw, range), command.debugSem);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function emptyChangeSet(label: string, stats: SourceRange["stats"]): SemChangeSet {
|
|
55
|
+
return {
|
|
56
|
+
id: sourceId(label),
|
|
57
|
+
label,
|
|
58
|
+
base: label,
|
|
59
|
+
target: label,
|
|
60
|
+
contextCwd: process.cwd(),
|
|
61
|
+
cleanup: async () => undefined,
|
|
62
|
+
changes: [],
|
|
63
|
+
summary: {
|
|
64
|
+
added: stats.additions,
|
|
65
|
+
deleted: stats.deletions,
|
|
66
|
+
modified: 0,
|
|
67
|
+
moved: 0,
|
|
68
|
+
renamed: 0,
|
|
69
|
+
fileCount: stats.filesChanged,
|
|
70
|
+
total: 0,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function semRangeForCommand(command: SearchCommand): Promise<SourceRange> {
|
|
76
|
+
if (command.kind === "since") return sourceRangeSince(command.since);
|
|
77
|
+
if (command.kind === "commit") return sourceRangeForCommit(command.commit);
|
|
78
|
+
if (command.kind === "commits") return sourceRangeForRecentCommits(command.count);
|
|
79
|
+
throw new Error("sem cannot resolve stdin as a git range.");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function semChangeSetFromPatch(patch: string, debugSem: boolean, label = "stdin"): Promise<SemChangeSet> {
|
|
83
|
+
if (!patch.trim()) throw new Error("No diff received on stdin.");
|
|
84
|
+
const raw = await cachedJson(
|
|
85
|
+
"sem-diff",
|
|
86
|
+
fingerprint({
|
|
87
|
+
version: 1,
|
|
88
|
+
cwd: process.cwd(),
|
|
89
|
+
command: ["diff", "--patch", "--format", "json"],
|
|
90
|
+
patchHash: fingerprint(patch),
|
|
91
|
+
}),
|
|
92
|
+
() => runSemWithInput(["diff", "--patch", "--format", "json"], patch, debugSem),
|
|
93
|
+
);
|
|
94
|
+
return {
|
|
95
|
+
...normalizeSemDiff(raw, {
|
|
96
|
+
id: sourceId(label),
|
|
97
|
+
label,
|
|
98
|
+
base: label,
|
|
99
|
+
target: label,
|
|
100
|
+
stats: { filesChanged: 0, additions: 0, deletions: 0 },
|
|
101
|
+
}),
|
|
102
|
+
contextCwd: process.cwd(),
|
|
103
|
+
cleanup: async () => undefined,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function cachedSemDiff(
|
|
108
|
+
args: readonly string[],
|
|
109
|
+
range: SourceRange,
|
|
110
|
+
debugSem: boolean,
|
|
111
|
+
): Promise<unknown> {
|
|
112
|
+
return cachedJson(
|
|
113
|
+
"sem-diff",
|
|
114
|
+
fingerprint({
|
|
115
|
+
version: 1,
|
|
116
|
+
cwd: process.cwd(),
|
|
117
|
+
args,
|
|
118
|
+
base: range.base,
|
|
119
|
+
target: range.target,
|
|
120
|
+
}),
|
|
121
|
+
() => runSem(args, debugSem),
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function withContextWorkspace(changeSet: SemChangeSet, debugSem: boolean): Promise<SemChangeSet> {
|
|
126
|
+
const tempDir = await realpath(await mkdtemp(path.join(tmpdir(), "stupify-sem-context-")));
|
|
127
|
+
let worktreeAdded = false;
|
|
128
|
+
try {
|
|
129
|
+
await git(["worktree", "add", "--detach", tempDir, changeSet.target], debugSem);
|
|
130
|
+
worktreeAdded = true;
|
|
131
|
+
return {
|
|
132
|
+
...changeSet,
|
|
133
|
+
contextCwd: tempDir,
|
|
134
|
+
cleanup: async () => cleanupWorktree(tempDir, worktreeAdded, debugSem),
|
|
135
|
+
};
|
|
136
|
+
} catch (error) {
|
|
137
|
+
await cleanupWorktree(tempDir, worktreeAdded, debugSem);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function runSem(args: readonly string[], debugSem: boolean, cwd = process.cwd()): Promise<unknown> {
|
|
143
|
+
if (debugSem) console.error(`sem ${args.join(" ")}`);
|
|
144
|
+
const { command, commandArgs } = resolveSemCommand(args);
|
|
145
|
+
try {
|
|
146
|
+
const { stdout, stderr } = await execFileAsync(command, commandArgs, {
|
|
147
|
+
cwd,
|
|
148
|
+
maxBuffer: 128 * 1024 * 1024,
|
|
149
|
+
});
|
|
150
|
+
if (debugSem && stderr.trim()) console.error(stderr.trim());
|
|
151
|
+
return JSON.parse(stdout);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
154
|
+
throw new Error(`sem failed. Install @ataraxy-labs/sem and ensure its binary is downloaded.\n${message}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function runSemWithInput(args: readonly string[], stdin: string, debugSem: boolean): Promise<unknown> {
|
|
159
|
+
if (debugSem) console.error(`sem ${args.join(" ")}`);
|
|
160
|
+
const { command, commandArgs } = resolveSemCommand(args);
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
const child = spawn(command, commandArgs, { stdio: ["pipe", "pipe", "pipe"] });
|
|
163
|
+
const stdout: Buffer[] = [];
|
|
164
|
+
const stderr: Buffer[] = [];
|
|
165
|
+
child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
|
|
166
|
+
child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
|
|
167
|
+
child.on("error", (error) => reject(error));
|
|
168
|
+
child.on("close", (code) => {
|
|
169
|
+
const stderrText = Buffer.concat(stderr).toString("utf8");
|
|
170
|
+
if (debugSem && stderrText.trim()) console.error(stderrText.trim());
|
|
171
|
+
if (code !== 0) {
|
|
172
|
+
reject(new Error(`sem failed with exit code ${code}${stderrText ? `: ${stderrText.trim()}` : ""}`));
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
resolve(JSON.parse(Buffer.concat(stdout).toString("utf8")));
|
|
177
|
+
} catch (error) {
|
|
178
|
+
reject(error);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
child.stdin.end(stdin);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function git(args: readonly string[], debugSem: boolean): Promise<void> {
|
|
186
|
+
if (debugSem) console.error(`git ${args.join(" ")}`);
|
|
187
|
+
await execFileAsync("git", [...args], { maxBuffer: 128 * 1024 * 1024 });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function cleanupWorktree(tempDir: string, worktreeAdded: boolean, debugSem: boolean): Promise<void> {
|
|
191
|
+
if (!worktreeAdded) {
|
|
192
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
await git(["worktree", "remove", "--force", tempDir], debugSem);
|
|
197
|
+
} catch {
|
|
198
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
199
|
+
await git(["worktree", "prune"], debugSem).catch(() => undefined);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function resolveSemCommand(args: readonly string[]): Readonly<{ command: string; commandArgs: readonly string[] }> {
|
|
204
|
+
const packageBin = semPackageBin();
|
|
205
|
+
if (packageBin) return { command: process.execPath, commandArgs: [packageBin, ...args] };
|
|
206
|
+
return { command: "sem", commandArgs: args };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function semPackageBin(): string | null {
|
|
210
|
+
try {
|
|
211
|
+
const require = createRequire(import.meta.url);
|
|
212
|
+
return require.resolve("@ataraxy-labs/sem/bin/sem.js");
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function normalizeSemDiff(value: unknown, range: SourceRange): SemChangeSet {
|
|
219
|
+
if (!value || typeof value !== "object") throw new Error("sem returned invalid diff JSON.");
|
|
220
|
+
const record = value as Record<string, unknown>;
|
|
221
|
+
const changes = Array.isArray(record.changes) ? record.changes.flatMap(normalizeSemChange) : [];
|
|
222
|
+
const summary = normalizeSemSummary(record.summary, changes);
|
|
223
|
+
return {
|
|
224
|
+
id: range.id,
|
|
225
|
+
label: range.label,
|
|
226
|
+
base: range.base,
|
|
227
|
+
target: range.target,
|
|
228
|
+
contextCwd: process.cwd(),
|
|
229
|
+
cleanup: async () => undefined,
|
|
230
|
+
changes,
|
|
231
|
+
summary,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function normalizeSemChange(value: unknown): readonly SemChange[] {
|
|
236
|
+
if (!value || typeof value !== "object") return [];
|
|
237
|
+
const record = value as Record<string, unknown>;
|
|
238
|
+
const entityId = stringValue(record.entityId);
|
|
239
|
+
const entityName = stringValue(record.entityName);
|
|
240
|
+
const entityType = stringValue(record.entityType);
|
|
241
|
+
const filePath = stringValue(record.filePath);
|
|
242
|
+
const changeType = stringValue(record.changeType);
|
|
243
|
+
if (!entityId || !entityName || !entityType || !filePath || !changeType) return [];
|
|
244
|
+
return [{
|
|
245
|
+
entityId,
|
|
246
|
+
entityName,
|
|
247
|
+
entityType,
|
|
248
|
+
filePath,
|
|
249
|
+
changeType,
|
|
250
|
+
beforeContent: nullableString(record.beforeContent),
|
|
251
|
+
afterContent: nullableString(record.afterContent),
|
|
252
|
+
}];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function normalizeSemSummary(value: unknown, changes: readonly SemChange[]): SemChangeSummary {
|
|
256
|
+
const record = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
257
|
+
return {
|
|
258
|
+
added: numberValue(record.added) ?? countByChange(changes, "added"),
|
|
259
|
+
deleted: numberValue(record.deleted) ?? countByChange(changes, "deleted"),
|
|
260
|
+
modified: numberValue(record.modified) ?? countByChange(changes, "modified"),
|
|
261
|
+
moved: numberValue(record.moved) ?? countByChange(changes, "moved"),
|
|
262
|
+
renamed: numberValue(record.renamed) ?? countByChange(changes, "renamed"),
|
|
263
|
+
fileCount: numberValue(record.fileCount) ?? new Set(changes.map((change) => change.filePath)).size,
|
|
264
|
+
total: numberValue(record.total) ?? changes.length,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function countByChange(changes: readonly SemChange[], changeType: string): number {
|
|
269
|
+
return changes.filter((change) => change.changeType === changeType).length;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function stringValue(value: unknown): string {
|
|
273
|
+
return typeof value === "string" ? value : "";
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function nullableString(value: unknown): string | null {
|
|
277
|
+
return typeof value === "string" ? value : null;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function numberValue(value: unknown): number | null {
|
|
281
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
282
|
+
}
|
package/src/stupify.ts
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { countPromptTokens, runSearch, searchRequest } from "./analysis.ts";
|
|
5
|
+
import { searchChecks } from "./checks.ts";
|
|
6
|
+
import { parseCommand } from "./command.ts";
|
|
7
|
+
import { counterScoutTargets } from "./counter-scout.ts";
|
|
8
|
+
import { runDoctor } from "./doctor.ts";
|
|
9
|
+
import { runHookCommand } from "./hooks.ts";
|
|
10
|
+
import { firstRunModelBootstrap, loadLocalModel } from "./model.ts";
|
|
11
|
+
import { entityContextsFromChanges, emptyContextPack, repomixContextPack, repomixSearchConfig } from "./repomix-provider.ts";
|
|
12
|
+
import { helpText, renderSearchRun } from "./render.ts";
|
|
13
|
+
import {
|
|
14
|
+
effectiveMaxCandidates,
|
|
15
|
+
effectiveMaxSearchInputTokens,
|
|
16
|
+
effectiveRepomixConfig,
|
|
17
|
+
effectiveSearchChecks,
|
|
18
|
+
loadSearchProfile,
|
|
19
|
+
} from "./search-profile.ts";
|
|
20
|
+
import { semChangeSetForCommand } from "./sem-provider.ts";
|
|
21
|
+
import { createTracer } from "./trace.ts";
|
|
22
|
+
import type { SearchCommand, SearchProfile, SearchRunJson, SemContext, SemContextPack, StupifyCheck } from "./types.ts";
|
|
23
|
+
|
|
24
|
+
export async function main(argv = process.argv.slice(2)): Promise<number> {
|
|
25
|
+
const startedAt = Date.now();
|
|
26
|
+
try {
|
|
27
|
+
const command = parseCommand(argv);
|
|
28
|
+
if (command.kind === "help") {
|
|
29
|
+
console.log(helpText());
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
if (command.kind === "hook") {
|
|
33
|
+
console.log(await runHookCommand(command.action));
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
if (command.kind === "doctor") {
|
|
37
|
+
const result = await runDoctor();
|
|
38
|
+
console.log(result.text);
|
|
39
|
+
return result.exitCode;
|
|
40
|
+
}
|
|
41
|
+
if (command.kind === "bench-search") {
|
|
42
|
+
const { runSearchBench } = await import("./search-bench.ts");
|
|
43
|
+
console.log(await runSearchBench(command.configPath));
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const run = await runSearchCommand(command, startedAt);
|
|
48
|
+
console.log(renderSearchRun(run, command));
|
|
49
|
+
return 0;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
52
|
+
return 1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function runSearchCommand(command: SearchCommand, startedAt: number): Promise<SearchRunJson> {
|
|
57
|
+
const t = createTracer({
|
|
58
|
+
writeLine: () => undefined,
|
|
59
|
+
onEvent: (event) => {
|
|
60
|
+
const parts = [`trace ${event.name}`, `${event.ms}ms`];
|
|
61
|
+
if (event.count !== undefined) parts.push(`count=${event.count}`);
|
|
62
|
+
if (event.detail) parts.push(event.detail);
|
|
63
|
+
console.error(parts.join(" "));
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const profile = await loadSearchProfile(command.searchProfilePath);
|
|
68
|
+
const checks = profile ? effectiveSearchChecks(command.checkIds, profile) : searchChecks(command.checkIds);
|
|
69
|
+
const patternIds = checks.map((check) => check.id);
|
|
70
|
+
const maxCandidates = effectiveMaxCandidates(command.maxCandidates, profile);
|
|
71
|
+
const maxSearchInputTokens = effectiveMaxSearchInputTokens(command.maxSearchInputTokens, profile);
|
|
72
|
+
const { value: changeSet } = await t.trace(
|
|
73
|
+
"entity.diff",
|
|
74
|
+
() => semChangeSetForCommand(command),
|
|
75
|
+
{
|
|
76
|
+
count: (v) => v.summary.total,
|
|
77
|
+
detail: (v) => `${v.summary.fileCount} files`,
|
|
78
|
+
},
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
printRunPlan(command, changeSet.summary.fileCount, changeSet.summary.total, patternIds);
|
|
83
|
+
const candidates = counterScoutTargets(changeSet, checks, maxCandidates);
|
|
84
|
+
const contexts = entityContextsFromChanges(candidates, changeSet.changes);
|
|
85
|
+
const targetsByPattern = countTargetsByPattern(contexts);
|
|
86
|
+
const targetsPreview = previewTargets(contexts);
|
|
87
|
+
if (contexts.length === 0) {
|
|
88
|
+
return {
|
|
89
|
+
schemaVersion: "search.v1",
|
|
90
|
+
mode: "search",
|
|
91
|
+
source: command.source,
|
|
92
|
+
model: { id: command.model },
|
|
93
|
+
patterns: patternIds,
|
|
94
|
+
stats: {
|
|
95
|
+
elapsedMs: Date.now() - startedAt,
|
|
96
|
+
modelCalls: 0,
|
|
97
|
+
skipped: true,
|
|
98
|
+
skipReason: "no_candidates",
|
|
99
|
+
filesChanged: changeSet.summary.fileCount,
|
|
100
|
+
entitiesScanned: changeSet.summary.total,
|
|
101
|
+
candidates: 0,
|
|
102
|
+
searchTargets: 0,
|
|
103
|
+
repomixFiles: 0,
|
|
104
|
+
repomixTokens: 0,
|
|
105
|
+
profileId: profile?.id,
|
|
106
|
+
targetsByPattern,
|
|
107
|
+
targetsPreview,
|
|
108
|
+
},
|
|
109
|
+
matches: [],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const baseRepomixConfig = effectiveRepomixConfig(repomixSearchConfig(), profile);
|
|
114
|
+
const initialPack = profile?.context === "sem"
|
|
115
|
+
? emptyContextPack()
|
|
116
|
+
: await t.trace(
|
|
117
|
+
"context.pack",
|
|
118
|
+
() => repomixContextPack(changeSet.contextCwd, contexts, changeSet.changes, baseRepomixConfig),
|
|
119
|
+
{
|
|
120
|
+
count: (v) => v.filePaths.length,
|
|
121
|
+
detail: (v) => `${v.totalTokens} tokens`,
|
|
122
|
+
},
|
|
123
|
+
).then((result) => result.value);
|
|
124
|
+
const packedFiles = new Set(initialPack.filePaths);
|
|
125
|
+
const searchContexts = profile?.context === "sem"
|
|
126
|
+
? contexts
|
|
127
|
+
: contexts.filter((context) => context.filePath && packedFiles.has(context.filePath));
|
|
128
|
+
if (searchContexts.length === 0) {
|
|
129
|
+
return {
|
|
130
|
+
schemaVersion: "search.v1",
|
|
131
|
+
mode: "search",
|
|
132
|
+
source: command.source,
|
|
133
|
+
model: { id: command.model },
|
|
134
|
+
patterns: patternIds,
|
|
135
|
+
stats: {
|
|
136
|
+
elapsedMs: Date.now() - startedAt,
|
|
137
|
+
modelCalls: 0,
|
|
138
|
+
skipped: true,
|
|
139
|
+
skipReason: "no_candidates",
|
|
140
|
+
filesChanged: changeSet.summary.fileCount,
|
|
141
|
+
entitiesScanned: changeSet.summary.total,
|
|
142
|
+
candidates: contexts.length,
|
|
143
|
+
searchTargets: 0,
|
|
144
|
+
repomixFiles: initialPack.filePaths.length,
|
|
145
|
+
repomixTokens: initialPack.totalTokens,
|
|
146
|
+
repomixConfig: initialPack.config,
|
|
147
|
+
profileId: profile?.id,
|
|
148
|
+
targetsByPattern,
|
|
149
|
+
targetsPreview,
|
|
150
|
+
},
|
|
151
|
+
matches: [],
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const pack = profile?.context === "sem" || searchContexts.length === contexts.length
|
|
155
|
+
? initialPack
|
|
156
|
+
: await repomixContextPack(changeSet.contextCwd, searchContexts, changeSet.changes, baseRepomixConfig);
|
|
157
|
+
|
|
158
|
+
const modelPath = await firstRunModelBootstrap(command.model);
|
|
159
|
+
const model = await loadLocalModel(modelPath, command.model, "scout");
|
|
160
|
+
const request = buildSearchRequest(
|
|
161
|
+
changeSet,
|
|
162
|
+
searchContexts,
|
|
163
|
+
pack,
|
|
164
|
+
checks,
|
|
165
|
+
profile,
|
|
166
|
+
command.includeCounterReasonInPrompt,
|
|
167
|
+
);
|
|
168
|
+
const inputTokens = await countPromptTokens(model, request.prompt);
|
|
169
|
+
if (inputTokens > maxSearchInputTokens) {
|
|
170
|
+
return {
|
|
171
|
+
schemaVersion: "search.v1",
|
|
172
|
+
mode: "search",
|
|
173
|
+
source: command.source,
|
|
174
|
+
model: { id: command.model },
|
|
175
|
+
patterns: patternIds,
|
|
176
|
+
stats: {
|
|
177
|
+
elapsedMs: Date.now() - startedAt,
|
|
178
|
+
modelCalls: 0,
|
|
179
|
+
inputTokens,
|
|
180
|
+
inputTokenCap: maxSearchInputTokens,
|
|
181
|
+
skipped: true,
|
|
182
|
+
skipReason: "input_too_large",
|
|
183
|
+
filesChanged: changeSet.summary.fileCount,
|
|
184
|
+
entitiesScanned: changeSet.summary.total,
|
|
185
|
+
candidates: contexts.length,
|
|
186
|
+
searchTargets: searchContexts.length,
|
|
187
|
+
repomixFiles: pack.filePaths.length,
|
|
188
|
+
repomixTokens: pack.totalTokens,
|
|
189
|
+
repomixConfig: pack.config,
|
|
190
|
+
profileId: profile?.id,
|
|
191
|
+
targetsByPattern: countTargetsByPattern(searchContexts),
|
|
192
|
+
targetsPreview: previewTargets(searchContexts),
|
|
193
|
+
},
|
|
194
|
+
matches: [],
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const { value: matches } = await t.trace(
|
|
199
|
+
"search.model",
|
|
200
|
+
() => runSearch(model, request),
|
|
201
|
+
{ count: (v) => v.length },
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
schemaVersion: "search.v1",
|
|
206
|
+
mode: "search",
|
|
207
|
+
source: command.source,
|
|
208
|
+
model: { id: command.model },
|
|
209
|
+
patterns: patternIds,
|
|
210
|
+
stats: {
|
|
211
|
+
elapsedMs: Date.now() - startedAt,
|
|
212
|
+
modelCalls: 1,
|
|
213
|
+
inputTokens,
|
|
214
|
+
inputTokenCap: maxSearchInputTokens,
|
|
215
|
+
filesChanged: changeSet.summary.fileCount,
|
|
216
|
+
entitiesScanned: changeSet.summary.total,
|
|
217
|
+
candidates: contexts.length,
|
|
218
|
+
searchTargets: searchContexts.length,
|
|
219
|
+
repomixFiles: pack.filePaths.length,
|
|
220
|
+
repomixTokens: pack.totalTokens,
|
|
221
|
+
repomixConfig: pack.config,
|
|
222
|
+
profileId: profile?.id,
|
|
223
|
+
targetsByPattern: countTargetsByPattern(searchContexts),
|
|
224
|
+
targetsPreview: previewTargets(searchContexts),
|
|
225
|
+
},
|
|
226
|
+
matches,
|
|
227
|
+
};
|
|
228
|
+
} finally {
|
|
229
|
+
await changeSet.cleanup();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function buildSearchRequest(
|
|
234
|
+
changeSet: Parameters<typeof searchRequest>[0]["changeSet"],
|
|
235
|
+
contexts: Parameters<typeof searchRequest>[0]["contexts"],
|
|
236
|
+
pack: SemContextPack,
|
|
237
|
+
patterns: readonly StupifyCheck[],
|
|
238
|
+
profile: SearchProfile | null,
|
|
239
|
+
includeCounterReasonInPrompt: boolean,
|
|
240
|
+
) {
|
|
241
|
+
return searchRequest({
|
|
242
|
+
changeSet,
|
|
243
|
+
contexts,
|
|
244
|
+
pack,
|
|
245
|
+
patterns,
|
|
246
|
+
includeCounterReasonInPrompt: profile?.includeCounterReasonInPrompt ?? includeCounterReasonInPrompt,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function printRunPlan(
|
|
251
|
+
command: SearchCommand,
|
|
252
|
+
filesChanged: number,
|
|
253
|
+
entitiesScanned: number,
|
|
254
|
+
patternIds: readonly string[],
|
|
255
|
+
): void {
|
|
256
|
+
if (command.json) return;
|
|
257
|
+
console.error("🧙 stupify 🪄");
|
|
258
|
+
console.error(`Mode: search (${command.source})`);
|
|
259
|
+
console.error(`Sem: ${filesChanged} files, ${entitiesScanned} changed entities`);
|
|
260
|
+
console.error(`Patterns: ${patternIds.join(", ")}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function countTargetsByPattern(contexts: readonly SemContext[]): Record<string, number> {
|
|
264
|
+
const counts: Record<string, number> = {};
|
|
265
|
+
for (const context of contexts) counts[context.checkId] = (counts[context.checkId] ?? 0) + 1;
|
|
266
|
+
return counts;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function previewTargets(contexts: readonly SemContext[]) {
|
|
270
|
+
return contexts.map((context) => ({
|
|
271
|
+
targetId: context.targetId,
|
|
272
|
+
patternId: context.checkId,
|
|
273
|
+
entityKind: context.entityKind || undefined,
|
|
274
|
+
sourceKind: context.filePath ? pathKind(context.filePath) : undefined,
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function pathKind(filePath: string): string {
|
|
279
|
+
const ext = filePath.split(".").pop();
|
|
280
|
+
return ext && ext !== filePath ? ext : "unknown";
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
284
|
+
process.exitCode = await main();
|
|
285
|
+
}
|