@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.
Files changed (66) hide show
  1. package/README.md +55 -0
  2. package/dist/analysis.d.ts +16 -0
  3. package/dist/analysis.js +133 -0
  4. package/dist/cache.d.ts +2 -0
  5. package/dist/cache.js +59 -0
  6. package/dist/checks.d.ts +4 -0
  7. package/dist/checks.js +218 -0
  8. package/dist/command.d.ts +2 -0
  9. package/dist/command.js +147 -0
  10. package/dist/constants.d.ts +4 -0
  11. package/dist/constants.js +53 -0
  12. package/dist/counter-scout.d.ts +14 -0
  13. package/dist/counter-scout.js +159 -0
  14. package/dist/diff.d.ts +1 -0
  15. package/dist/diff.js +10 -0
  16. package/dist/doctor.d.ts +4 -0
  17. package/dist/doctor.js +131 -0
  18. package/dist/git.d.ts +11 -0
  19. package/dist/git.js +253 -0
  20. package/dist/hooks.d.ts +3 -0
  21. package/dist/hooks.js +117 -0
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.js +1 -0
  24. package/dist/model.d.ts +10 -0
  25. package/dist/model.js +297 -0
  26. package/dist/prompts.d.ts +8 -0
  27. package/dist/prompts.js +87 -0
  28. package/dist/render.d.ts +3 -0
  29. package/dist/render.js +93 -0
  30. package/dist/repomix-provider.d.ts +12 -0
  31. package/dist/repomix-provider.js +196 -0
  32. package/dist/search-bench.d.ts +1 -0
  33. package/dist/search-bench.js +675 -0
  34. package/dist/search-profile.d.ts +6 -0
  35. package/dist/search-profile.js +73 -0
  36. package/dist/sem-provider.d.ts +2 -0
  37. package/dist/sem-provider.js +247 -0
  38. package/dist/stupify.d.ts +4 -0
  39. package/dist/stupify.js +237 -0
  40. package/dist/trace.d.ts +29 -0
  41. package/dist/trace.js +64 -0
  42. package/dist/types.d.ts +320 -0
  43. package/dist/types.js +6 -0
  44. package/package.json +42 -5
  45. package/src/analysis.ts +188 -0
  46. package/src/cache.ts +65 -0
  47. package/src/checks.ts +221 -0
  48. package/src/command.ts +173 -0
  49. package/src/constants.ts +56 -0
  50. package/src/counter-scout.ts +175 -0
  51. package/src/diff.ts +9 -0
  52. package/src/doctor.ts +140 -0
  53. package/src/git.ts +262 -0
  54. package/src/hooks.ts +134 -0
  55. package/src/index.ts +1 -0
  56. package/src/model.ts +373 -0
  57. package/src/prompts.ts +98 -0
  58. package/src/render.ts +96 -0
  59. package/src/repomix-provider.ts +219 -0
  60. package/src/search-bench.ts +783 -0
  61. package/src/search-profile.ts +89 -0
  62. package/src/sem-provider.ts +282 -0
  63. package/src/stupify.ts +285 -0
  64. package/src/trace.ts +103 -0
  65. package/src/types.ts +340 -0
  66. package/bin/stupify.mjs +0 -3
@@ -0,0 +1,53 @@
1
+ export const VERSION = "0.0.4";
2
+ export const DEFAULT_MODEL_ID = "gemma-4-e2b";
3
+ export const MODEL_REGISTRY = {
4
+ "gemma-4-e2b": {
5
+ id: "gemma-4-e2b",
6
+ name: "Gemma 4 E2B Instruct Q4_K_M",
7
+ size: "about 3.1 GB",
8
+ file: "gemma-4-e2b-it-q4_k_m.gguf",
9
+ url: "https://huggingface.co/unsloth/gemma-4-E2B-it-GGUF/resolve/main/gemma-4-E2B-it-Q4_K_M.gguf?download=true",
10
+ },
11
+ "gemma-4-e4b": {
12
+ id: "gemma-4-e4b",
13
+ name: "Gemma 4 E4B Instruct Q4_K_M",
14
+ size: "about 5.0 GB",
15
+ file: "gemma-4-e4b-it-q4_k_m.gguf",
16
+ url: "https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF/resolve/main/gemma-4-E4B-it-Q4_K_M.gguf?download=true",
17
+ },
18
+ "gemma-4-26b-a4b": {
19
+ id: "gemma-4-26b-a4b",
20
+ name: "Gemma 4 26B A4B Instruct UD-IQ2_XXS",
21
+ size: "about 9.9 GB",
22
+ file: "gemma-4-26b-a4b-it-ud-iq2_xxs.gguf",
23
+ url: "https://huggingface.co/unsloth/gemma-4-26B-A4B-it-GGUF/resolve/main/gemma-4-26B-A4B-it-UD-IQ2_XXS.gguf?download=true",
24
+ },
25
+ "qwen3-4b-magicquant": {
26
+ id: "qwen3-4b-magicquant",
27
+ name: "Qwen3-4B-Instruct-2507 MagicQuant Q4_K_M",
28
+ size: "about 2.4 GB",
29
+ file: "qwen3-4b-instruct-2507-magicquant-q4_k_m.gguf",
30
+ url: "https://huggingface.co/magiccodingman/Qwen3-4B-Instruct-2507-Unsloth-MagicQuant-v2-GGUF/resolve/main/Model-MQ-Q4_K_M_1.gguf?download=true",
31
+ },
32
+ "qwen2.5-coder-1.5b": {
33
+ id: "qwen2.5-coder-1.5b",
34
+ name: "Qwen2.5-Coder-1.5B-Instruct Q4_K_M",
35
+ size: "about 1.1 GB",
36
+ file: "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf",
37
+ url: "https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/resolve/main/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf?download=true",
38
+ },
39
+ "qwen2.5-coder-7b": {
40
+ id: "qwen2.5-coder-7b",
41
+ name: "Qwen2.5-Coder-7B-Instruct Q4_K_M",
42
+ size: "about 4.7 GB",
43
+ file: "qwen2.5-coder-7b-instruct-q4_k_m.gguf",
44
+ url: "https://huggingface.co/Qwen/Qwen2.5-Coder-7B-Instruct-GGUF/resolve/main/qwen2.5-coder-7b-instruct-q4_k_m.gguf?download=true",
45
+ },
46
+ "qwen2.5-coder-32b": {
47
+ id: "qwen2.5-coder-32b",
48
+ name: "Qwen2.5-Coder-32B-Instruct Q4_K_M",
49
+ size: "about 19 GB",
50
+ file: "qwen2.5-coder-32b-instruct-q4_k_m.gguf",
51
+ url: "https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct-GGUF/resolve/main/qwen2.5-coder-32b-instruct-q4_k_m.gguf?download=true",
52
+ },
53
+ };
@@ -0,0 +1,14 @@
1
+ import type { CheckId, SemCandidate, SemChangeSet, StupifyCheck } from "./types.ts";
2
+ type Signal = Readonly<{
3
+ checkId: CheckId;
4
+ entityId: string;
5
+ reasonCode: string;
6
+ }>;
7
+ type SignalBucket = Readonly<{
8
+ checkId: CheckId;
9
+ total: number;
10
+ examples: readonly Signal[];
11
+ }>;
12
+ export declare function counterScoutTargets(changeSet: SemChangeSet, checks: readonly StupifyCheck[], maxTargets: number): readonly SemCandidate[];
13
+ export declare function runSignalCounters(changeSet: SemChangeSet, checks: readonly StupifyCheck[]): readonly SignalBucket[];
14
+ export {};
@@ -0,0 +1,159 @@
1
+ const MAX_COUNTER_EXAMPLES_PER_CHECK = 4;
2
+ export function counterScoutTargets(changeSet, checks, maxTargets) {
3
+ const buckets = runSignalCounters(changeSet, checks);
4
+ const targets = [];
5
+ let cursor = 0;
6
+ while (targets.length < maxTargets && buckets.some((bucket) => cursor < bucket.examples.length)) {
7
+ for (const bucket of buckets) {
8
+ const signal = bucket.examples[cursor];
9
+ if (!signal)
10
+ continue;
11
+ targets.push({
12
+ sourceId: changeSet.id,
13
+ targetId: `t${String(targets.length + 1).padStart(3, "0")}`,
14
+ entityId: signal.entityId,
15
+ checkId: signal.checkId,
16
+ reason: signal.reasonCode,
17
+ });
18
+ if (targets.length >= maxTargets)
19
+ break;
20
+ }
21
+ cursor += 1;
22
+ }
23
+ return targets;
24
+ }
25
+ export function runSignalCounters(changeSet, checks) {
26
+ return checks
27
+ .map((check) => {
28
+ const signals = changeSet.changes.flatMap((change) => {
29
+ const reasonCode = reasonForCheck(check.id, change);
30
+ return reasonCode ? [{ checkId: check.id, entityId: change.entityId, reasonCode }] : [];
31
+ });
32
+ return {
33
+ checkId: check.id,
34
+ total: signals.length,
35
+ examples: signals.slice(0, MAX_COUNTER_EXAMPLES_PER_CHECK),
36
+ };
37
+ })
38
+ .filter((bucket) => bucket.total > 0);
39
+ }
40
+ function reasonForCheck(checkId, change) {
41
+ if (!isSearchableSourceChange(change))
42
+ return null;
43
+ const haystack = `${change.entityName}\n${change.entityType}\n${change.filePath}\n${change.afterContent ?? ""}`.toLowerCase();
44
+ const changed = change.changeType === "added" || change.changeType === "modified";
45
+ if (!changed)
46
+ return null;
47
+ switch (checkId) {
48
+ case "duplicated_schema":
49
+ return isDuplicatedSchemaCandidate(change) ? "local_schemaish_copy" : null;
50
+ case "unnecessary_complexity":
51
+ return /\b(helper|wrapper|service|provider|manager|factory|adapter|resolver|coordinator)\b/i.test(change.entityName)
52
+ ? "new_abstraction_name"
53
+ : null;
54
+ case "fake_precision_windowing":
55
+ return /\b(token|budget|window|batch|ratio|estimate|counter|count|limit)\b/i.test(haystack)
56
+ ? "precision_accounting_terms"
57
+ : null;
58
+ case "coauthored_slop":
59
+ return /\b(coauhtoried|coauthored|co-authored|co-authored-by)\b/i.test(haystack)
60
+ ? "coauthor_text"
61
+ : null;
62
+ case "mega_file":
63
+ return change.entityType === "chunk" && /lines\s+\d+-\d+/i.test(change.entityName)
64
+ ? "large_changed_chunk"
65
+ : null;
66
+ case "over_commenting":
67
+ return overCommentingSignal(change)
68
+ ? "comment_lines_increased"
69
+ : null;
70
+ case "lint_bypass":
71
+ return lintBypassSignal(change.afterContent ?? "")
72
+ ? "lint_or_type_bypass_text"
73
+ : null;
74
+ case "inconsistent_patterns":
75
+ return /\b(manager|factory|provider|adapter|orchestrator|coordinator)\b/i.test(change.entityName)
76
+ ? "pattern_abstraction_name"
77
+ : null;
78
+ case "reinvented_utils":
79
+ return reinventedUtilitySignal(change)
80
+ ? "generic_utility_name"
81
+ : null;
82
+ case "operator_style_mismatch":
83
+ return /\b(manager|factory|provider|enterprise|orchestrator)\b/i.test(haystack)
84
+ ? "style_smell_terms"
85
+ : null;
86
+ default:
87
+ return null;
88
+ }
89
+ }
90
+ function isDuplicatedSchemaCandidate(change) {
91
+ if (!/^(interface|type)$/i.test(change.entityType))
92
+ return false;
93
+ if (/^(public|external|internal|payment|.+client$)/i.test(change.entityName))
94
+ return false;
95
+ return /\b(local|payload|schema)\b/i.test(words(change.entityName));
96
+ }
97
+ function overCommentingSignal(change) {
98
+ const before = commentLines(change.beforeContent);
99
+ const after = commentLines(change.afterContent);
100
+ if (after <= before + 3)
101
+ return false;
102
+ const comments = commentText(change.afterContent);
103
+ if (/\b(because|why|constraint|provider|external|api|quirk|edge case|timezone|utc|ledger|finance|reconciliation|rejects|mirrors|keep this)\b/i.test(comments)) {
104
+ return false;
105
+ }
106
+ return true;
107
+ }
108
+ function lintBypassSignal(value) {
109
+ return value.split(/\r?\n/).some((line) => {
110
+ const trimmed = line.trim();
111
+ const comment = /^(\/\/|\/\*|\*)/.test(trimmed);
112
+ if (comment && /@ts-ignore\s*$/i.test(trimmed))
113
+ return true;
114
+ if (comment && /@ts-expect-error\s*$/i.test(trimmed))
115
+ return true;
116
+ if (comment && /(eslint-disable|biome-ignore)/i.test(trimmed) && !/\s--\s*\S/.test(trimmed))
117
+ return true;
118
+ return /\bas unknown as\b|\bas any\b|:\s*any\b/i.test(trimmed);
119
+ });
120
+ }
121
+ function reinventedUtilitySignal(change) {
122
+ const name = change.entityName;
123
+ if (!/^(clamp|debounce|throttle|slug|slugify|group|sort|shuffle|memoize|pick|omit|uniq)/i.test(name))
124
+ return false;
125
+ const content = change.afterContent ?? "";
126
+ if (/currency|invoice|refund|subscription|tier|domain/i.test(`${name}\n${content}`))
127
+ return false;
128
+ return true;
129
+ }
130
+ function isSearchableSourceChange(change) {
131
+ const filePath = change.filePath.toLowerCase();
132
+ if (/(^|\/)(bun|package-lock|pnpm-lock|yarn)\.lock$/.test(filePath))
133
+ return false;
134
+ if (/(^|\/)(dist|build|coverage|generated|vendor|fixtures?|snapshots?)(\/|$)/.test(filePath))
135
+ return false;
136
+ if (/\.(md|mdx|txt|json|jsonc|ya?ml|toml|lock|csv|svg|png|jpe?g|gif|webp)$/i.test(filePath))
137
+ return false;
138
+ if (/\.(test|spec|fixture)\.[cm]?[jt]sx?$/i.test(filePath))
139
+ return false;
140
+ return /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/i.test(filePath);
141
+ }
142
+ function commentLines(value) {
143
+ if (!value)
144
+ return 0;
145
+ return value.split(/\r?\n/).filter((line) => /^\s*(\/\/|\/\*|\*|#)/.test(line)).length;
146
+ }
147
+ function commentText(value) {
148
+ if (!value)
149
+ return "";
150
+ return value
151
+ .split(/\r?\n/)
152
+ .filter((line) => /^\s*(\/\/|\/\*|\*|#)/.test(line))
153
+ .join("\n");
154
+ }
155
+ function words(value) {
156
+ return value
157
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
158
+ .replace(/[_-]+/g, " ");
159
+ }
package/dist/diff.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function readDiffFromStdin(): Promise<string>;
package/dist/diff.js ADDED
@@ -0,0 +1,10 @@
1
+ import { stdin as input } from "node:process";
2
+ export async function readDiffFromStdin() {
3
+ const chunks = [];
4
+ for await (const chunk of input)
5
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
6
+ const text = Buffer.concat(chunks).toString("utf8");
7
+ if (!text.trim())
8
+ throw new Error("No diff received on stdin.");
9
+ return text;
10
+ }
@@ -0,0 +1,4 @@
1
+ export declare function runDoctor(): Promise<Readonly<{
2
+ exitCode: number;
3
+ text: string;
4
+ }>>;
package/dist/doctor.js ADDED
@@ -0,0 +1,131 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ import { homedir, platform } from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { DEFAULT_MODEL_ID, MODEL_REGISTRY } from "./constants.js";
7
+ import { runHookCommand } from "./hooks.js";
8
+ const execFileAsync = promisify(execFile);
9
+ export async function runDoctor() {
10
+ const checks = await Promise.all([
11
+ gitCheck(),
12
+ hookCheck(),
13
+ semCheck(),
14
+ repomixCheck(),
15
+ llamaServerCheck(),
16
+ modelCacheCheck(),
17
+ ]);
18
+ const requiredMissing = checks.some((check) => check.required && check.status === "missing");
19
+ return {
20
+ exitCode: requiredMissing ? 1 : 0,
21
+ text: renderDoctor(checks),
22
+ };
23
+ }
24
+ async function gitCheck() {
25
+ try {
26
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel"], { maxBuffer: 1024 * 1024 });
27
+ return { label: "git repo", status: "ok", detail: stdout.trim(), required: true };
28
+ }
29
+ catch {
30
+ return { label: "git repo", status: "missing", detail: "not inside a git repository", required: true };
31
+ }
32
+ }
33
+ async function hookCheck() {
34
+ try {
35
+ const status = await runHookCommand("status");
36
+ return { label: "pre-commit hook", status: "info", detail: status.replace(/^Stupify hook:\s*/, "") };
37
+ }
38
+ catch (error) {
39
+ return { label: "pre-commit hook", status: "info", detail: errorMessage(error) };
40
+ }
41
+ }
42
+ async function semCheck() {
43
+ const packageBin = resolvePackage("@ataraxy-labs/sem/bin/sem.js");
44
+ if (packageBin)
45
+ return { label: "sem", status: "ok", detail: "@ataraxy-labs/sem package binary found", required: true };
46
+ if (await commandExists("sem"))
47
+ return { label: "sem", status: "ok", detail: "sem found on PATH", required: true };
48
+ return { label: "sem", status: "missing", detail: "install @ataraxy-labs/sem or put sem on PATH", required: true };
49
+ }
50
+ async function repomixCheck() {
51
+ if (resolvePackage("repomix"))
52
+ return { label: "Repomix", status: "ok", detail: "repomix package found", required: true };
53
+ return { label: "Repomix", status: "missing", detail: "repomix package is not installed", required: true };
54
+ }
55
+ async function llamaServerCheck() {
56
+ if (await commandExists("llama-server"))
57
+ return { label: "llama-server", status: "ok", detail: "llama-server found on PATH", required: true };
58
+ return { label: "llama-server", status: "missing", detail: "install llama.cpp, for example `brew install llama.cpp`", required: true };
59
+ }
60
+ async function modelCacheCheck() {
61
+ const model = MODEL_REGISTRY[DEFAULT_MODEL_ID];
62
+ const modelPath = path.join(cacheDir(), "models", model.file);
63
+ if (await fileExists(modelPath))
64
+ return { label: "default model", status: "ok", detail: `${model.name} cached` };
65
+ return {
66
+ label: "default model",
67
+ status: "info",
68
+ detail: `${model.name} not cached yet; first interactive search can download it locally`,
69
+ };
70
+ }
71
+ function renderDoctor(checks) {
72
+ const lines = [
73
+ "Stupify doctor",
74
+ "",
75
+ ...checks.map((check) => `${icon(check.status)} ${check.label}: ${check.detail}`),
76
+ "",
77
+ "Privacy: local-only. Stupify does not upload source, diffs, filenames, repo URLs, commit messages, author names, or private package names.",
78
+ ];
79
+ return lines.join("\n");
80
+ }
81
+ function icon(status) {
82
+ if (status === "ok")
83
+ return "OK";
84
+ if (status === "missing")
85
+ return "MISSING";
86
+ return "INFO";
87
+ }
88
+ function resolvePackage(specifier) {
89
+ try {
90
+ const require = createRequire(import.meta.url);
91
+ return require.resolve(specifier);
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ async function commandExists(command) {
98
+ try {
99
+ await execFileAsync("sh", ["-c", `command -v ${shellQuote(command)}`], { maxBuffer: 1024 * 1024 });
100
+ return true;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ async function fileExists(filePath) {
107
+ try {
108
+ const { stat } = await import("node:fs/promises");
109
+ return (await stat(filePath)).isFile();
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ function cacheDir() {
116
+ if (process.env.STUPIFY_CACHE_DIR)
117
+ return process.env.STUPIFY_CACHE_DIR;
118
+ if (process.env.XDG_CACHE_HOME)
119
+ return path.join(process.env.XDG_CACHE_HOME, "stupify");
120
+ if (platform() === "darwin")
121
+ return path.join(homedir(), "Library", "Caches", "stupify");
122
+ if (platform() === "win32" && process.env.LOCALAPPDATA)
123
+ return path.join(process.env.LOCALAPPDATA, "stupify", "Cache");
124
+ return path.join(homedir(), ".cache", "stupify");
125
+ }
126
+ function shellQuote(value) {
127
+ return `'${value.replace(/'/g, "'\\''")}'`;
128
+ }
129
+ function errorMessage(error) {
130
+ return error instanceof Error ? error.message : String(error);
131
+ }
package/dist/git.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { type NetDiff, type SourceRange, type StagedDiff } from "./types.ts";
2
+ export declare function netDiffSince(since: string): Promise<NetDiff>;
3
+ export declare function netDiffForCommit(commit: string): Promise<NetDiff>;
4
+ export declare function netDiffForRecentCommits(count: number): Promise<NetDiff>;
5
+ export declare function sourceRangeSince(since: string): Promise<SourceRange>;
6
+ export declare function sourceRangeForCommit(commit: string): Promise<SourceRange>;
7
+ export declare function sourceRangeForRecentCommits(count: number): Promise<SourceRange>;
8
+ export declare function netDiffFromStdin(text: string): Promise<NetDiff>;
9
+ export declare function stagedDiff(): Promise<StagedDiff>;
10
+ export declare function gitRoot(): Promise<string>;
11
+ export declare function gitPath(pathspec: string): Promise<string>;
package/dist/git.js ADDED
@@ -0,0 +1,253 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { sourceId } from "./types.js";
4
+ const execFileAsync = promisify(execFile);
5
+ export async function netDiffSince(since) {
6
+ const range = await sourceRangeSince(since);
7
+ return netDiff(range.base, range.target, range.label, range.id);
8
+ }
9
+ export async function netDiffForCommit(commit) {
10
+ const range = await sourceRangeForCommit(commit);
11
+ return netDiff(range.base, range.target, range.label, range.id);
12
+ }
13
+ export async function netDiffForRecentCommits(count) {
14
+ const range = await sourceRangeForRecentCommits(count);
15
+ return netDiff(range.base, range.target, range.label, range.id);
16
+ }
17
+ export async function sourceRangeSince(since) {
18
+ const [base, target] = await Promise.all([baseBefore(since), revParse("HEAD")]);
19
+ return sourceRange(base, target, `last ${since}`);
20
+ }
21
+ export async function sourceRangeForCommit(commit) {
22
+ const [base, target, shortTarget, message] = await Promise.all([
23
+ revParse(`${commit}^1`),
24
+ revParse(commit),
25
+ shortCommit(commit),
26
+ commitMessage(commit),
27
+ ]);
28
+ return sourceRange(base, target, firstLine(message) || shortTarget, sourceId(shortTarget));
29
+ }
30
+ export async function sourceRangeForRecentCommits(count) {
31
+ const commits = await recentCommits(count);
32
+ if (commits.length === 0)
33
+ throw new Error("No non-merge commits found.");
34
+ const oldest = commits[0];
35
+ const newest = commits[commits.length - 1];
36
+ const [base, target, shortBase, shortTarget] = await Promise.all([
37
+ revParse(`${oldest}^1`),
38
+ revParse(newest),
39
+ shortCommit(`${oldest}^1`),
40
+ shortCommit(newest),
41
+ ]);
42
+ return sourceRange(base, target, `${commits.length} recent commits`, sourceId(`range:${shortBase}..${shortTarget}`));
43
+ }
44
+ export async function netDiffFromStdin(text) {
45
+ if (!text.trim())
46
+ throw new Error("No diff received on stdin.");
47
+ return {
48
+ id: sourceId("stdin"),
49
+ label: "stdin",
50
+ base: "stdin",
51
+ target: "stdin",
52
+ text,
53
+ stats: statsFromDiff(text),
54
+ };
55
+ }
56
+ export async function stagedDiff() {
57
+ try {
58
+ const { stdout } = await execFileAsync("git", [
59
+ "diff",
60
+ "--cached",
61
+ "--no-ext-diff",
62
+ "--no-color",
63
+ "--unified=3",
64
+ "--",
65
+ ], { maxBuffer: 64 * 1024 * 1024 });
66
+ return { text: stdout, stats: statsFromDiff(stdout) };
67
+ }
68
+ catch {
69
+ throw new Error("Could not read staged changes. Run stupify inside a git repository.");
70
+ }
71
+ }
72
+ export async function gitRoot() {
73
+ try {
74
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel"]);
75
+ return stdout.trim();
76
+ }
77
+ catch {
78
+ throw new Error("Could not find a git repository.");
79
+ }
80
+ }
81
+ export async function gitPath(pathspec) {
82
+ try {
83
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--git-path", pathspec]);
84
+ return stdout.trim();
85
+ }
86
+ catch {
87
+ throw new Error(`Could not resolve git path: ${pathspec}`);
88
+ }
89
+ }
90
+ async function netDiff(base, target, label, id) {
91
+ const [text, stats, shortBase, shortTarget] = await Promise.all([
92
+ diff(base, target),
93
+ diffStats(base, target),
94
+ shortCommit(base),
95
+ shortCommit(target),
96
+ ]);
97
+ return {
98
+ id: id ?? sourceId(`net:${shortBase}..${shortTarget}`),
99
+ label,
100
+ base,
101
+ target,
102
+ text,
103
+ stats,
104
+ };
105
+ }
106
+ async function sourceRange(base, target, label, id) {
107
+ const [stats, shortBase, shortTarget] = await Promise.all([
108
+ diffStats(base, target),
109
+ shortCommit(base),
110
+ shortCommit(target),
111
+ ]);
112
+ return {
113
+ id: id ?? sourceId(`net:${shortBase}..${shortTarget}`),
114
+ label,
115
+ base,
116
+ target,
117
+ stats,
118
+ };
119
+ }
120
+ async function baseBefore(since) {
121
+ try {
122
+ const { stdout } = await execFileAsync("git", [
123
+ "log",
124
+ "--first-parent",
125
+ "--before",
126
+ since,
127
+ "-1",
128
+ "--format=%H",
129
+ ]);
130
+ const commit = stdout.trim();
131
+ if (commit)
132
+ return commit;
133
+ return rootCommit();
134
+ }
135
+ catch {
136
+ throw new Error(`Could not resolve base commit before ${since}.`);
137
+ }
138
+ }
139
+ async function rootCommit() {
140
+ try {
141
+ const { stdout } = await execFileAsync("git", ["rev-list", "--max-parents=0", "HEAD"]);
142
+ return stdout.trim().split(/\r?\n/, 1)[0] ?? "";
143
+ }
144
+ catch {
145
+ throw new Error("Could not resolve repository root commit.");
146
+ }
147
+ }
148
+ async function diff(base, target) {
149
+ try {
150
+ const { stdout } = await execFileAsync("git", [
151
+ "diff",
152
+ "--no-ext-diff",
153
+ "--no-color",
154
+ "--unified=8",
155
+ base,
156
+ target,
157
+ "--",
158
+ ], { maxBuffer: 128 * 1024 * 1024 });
159
+ if (!stdout.trim())
160
+ throw new Error("empty diff");
161
+ return stdout;
162
+ }
163
+ catch {
164
+ throw new Error(`No diff found for ${base}..${target}.`);
165
+ }
166
+ }
167
+ async function diffStats(base, target) {
168
+ try {
169
+ const { stdout } = await execFileAsync("git", ["diff", "--numstat", base, target, "--"], {
170
+ maxBuffer: 16 * 1024 * 1024,
171
+ });
172
+ return statsFromNumstat(stdout);
173
+ }
174
+ catch {
175
+ return { filesChanged: 0, additions: 0, deletions: 0 };
176
+ }
177
+ }
178
+ function statsFromDiff(diffText) {
179
+ const files = new Set();
180
+ let additions = 0;
181
+ let deletions = 0;
182
+ for (const line of diffText.split(/\r?\n/)) {
183
+ const fileMatch = /^diff --git a\/.+ b\/(.+)$/.exec(line);
184
+ if (fileMatch)
185
+ files.add(fileMatch[1]);
186
+ else if (line.startsWith("+") && !line.startsWith("+++"))
187
+ additions += 1;
188
+ else if (line.startsWith("-") && !line.startsWith("---"))
189
+ deletions += 1;
190
+ }
191
+ return { filesChanged: files.size, additions, deletions };
192
+ }
193
+ function statsFromNumstat(numstat) {
194
+ let filesChanged = 0;
195
+ let additions = 0;
196
+ let deletions = 0;
197
+ for (const line of numstat.split(/\r?\n/)) {
198
+ if (!line.trim())
199
+ continue;
200
+ const [added, deleted] = line.split(/\s+/, 3);
201
+ filesChanged += 1;
202
+ additions += Number(added) || 0;
203
+ deletions += Number(deleted) || 0;
204
+ }
205
+ return { filesChanged, additions, deletions };
206
+ }
207
+ async function recentCommits(count) {
208
+ try {
209
+ const { stdout } = await execFileAsync("git", [
210
+ "log",
211
+ "--first-parent",
212
+ "--no-merges",
213
+ "--format=%H",
214
+ `-${count}`,
215
+ ]);
216
+ return stdout.split(/\r?\n/).filter(Boolean).reverse();
217
+ }
218
+ catch {
219
+ throw new Error(`Could not read last ${count} commits.`);
220
+ }
221
+ }
222
+ async function revParse(rev) {
223
+ try {
224
+ const { stdout } = await execFileAsync("git", ["rev-parse", rev]);
225
+ return stdout.trim();
226
+ }
227
+ catch {
228
+ throw new Error(`Could not resolve ${rev}.`);
229
+ }
230
+ }
231
+ async function shortCommit(commit) {
232
+ try {
233
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--short", commit]);
234
+ return stdout.trim();
235
+ }
236
+ catch {
237
+ throw new Error(`Could not resolve commit ${commit}.`);
238
+ }
239
+ }
240
+ async function commitMessage(commit) {
241
+ try {
242
+ const { stdout } = await execFileAsync("git", ["show", "--no-patch", "--format=%B", commit], {
243
+ maxBuffer: 1024 * 1024,
244
+ });
245
+ return stdout;
246
+ }
247
+ catch {
248
+ throw new Error(`Could not read commit message for ${commit}.`);
249
+ }
250
+ }
251
+ function firstLine(value) {
252
+ return value.trim().split(/\r?\n/, 1)[0]?.trim() ?? "";
253
+ }
@@ -0,0 +1,3 @@
1
+ import type { HookAction } from "./types.ts";
2
+ export declare function runHookCommand(action: HookAction): Promise<string>;
3
+ export declare function hookSnippet(): string;