@oh-my-pi/pi-coding-agent 8.0.20 → 8.1.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.
Files changed (166) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/package.json +14 -11
  3. package/scripts/generate-wasm-b64.ts +24 -0
  4. package/src/capability/context-file.ts +1 -1
  5. package/src/capability/extension-module.ts +1 -1
  6. package/src/capability/extension.ts +1 -1
  7. package/src/capability/hook.ts +1 -1
  8. package/src/capability/instruction.ts +1 -1
  9. package/src/capability/mcp.ts +1 -1
  10. package/src/capability/prompt.ts +1 -1
  11. package/src/capability/rule.ts +1 -1
  12. package/src/capability/settings.ts +1 -1
  13. package/src/capability/skill.ts +1 -1
  14. package/src/capability/slash-command.ts +1 -1
  15. package/src/capability/ssh.ts +1 -1
  16. package/src/capability/system-prompt.ts +1 -1
  17. package/src/capability/tool.ts +1 -1
  18. package/src/cli/args.ts +1 -1
  19. package/src/cli/plugin-cli.ts +1 -5
  20. package/src/commit/agentic/agent.ts +309 -0
  21. package/src/commit/agentic/fallback.ts +96 -0
  22. package/src/commit/agentic/index.ts +359 -0
  23. package/src/commit/agentic/prompts/analyze-file.md +22 -0
  24. package/src/commit/agentic/prompts/session-user.md +26 -0
  25. package/src/commit/agentic/prompts/split-confirm.md +1 -0
  26. package/src/commit/agentic/prompts/system.md +40 -0
  27. package/src/commit/agentic/state.ts +74 -0
  28. package/src/commit/agentic/tools/analyze-file.ts +131 -0
  29. package/src/commit/agentic/tools/git-file-diff.ts +194 -0
  30. package/src/commit/agentic/tools/git-hunk.ts +50 -0
  31. package/src/commit/agentic/tools/git-overview.ts +84 -0
  32. package/src/commit/agentic/tools/index.ts +56 -0
  33. package/src/commit/agentic/tools/propose-changelog.ts +128 -0
  34. package/src/commit/agentic/tools/propose-commit.ts +154 -0
  35. package/src/commit/agentic/tools/recent-commits.ts +81 -0
  36. package/src/commit/agentic/tools/split-commit.ts +284 -0
  37. package/src/commit/agentic/topo-sort.ts +44 -0
  38. package/src/commit/agentic/trivial.ts +51 -0
  39. package/src/commit/agentic/validation.ts +200 -0
  40. package/src/commit/analysis/conventional.ts +169 -0
  41. package/src/commit/analysis/index.ts +4 -0
  42. package/src/commit/analysis/scope.ts +242 -0
  43. package/src/commit/analysis/summary.ts +114 -0
  44. package/src/commit/analysis/validation.ts +66 -0
  45. package/src/commit/changelog/detect.ts +36 -0
  46. package/src/commit/changelog/generate.ts +112 -0
  47. package/src/commit/changelog/index.ts +233 -0
  48. package/src/commit/changelog/parse.ts +44 -0
  49. package/src/commit/cli.ts +93 -0
  50. package/src/commit/git/diff.ts +148 -0
  51. package/src/commit/git/errors.ts +11 -0
  52. package/src/commit/git/index.ts +217 -0
  53. package/src/commit/git/operations.ts +53 -0
  54. package/src/commit/index.ts +5 -0
  55. package/src/commit/map-reduce/.map-phase.ts.kate-swp +0 -0
  56. package/src/commit/map-reduce/index.ts +63 -0
  57. package/src/commit/map-reduce/map-phase.ts +193 -0
  58. package/src/commit/map-reduce/reduce-phase.ts +147 -0
  59. package/src/commit/map-reduce/utils.ts +9 -0
  60. package/src/commit/message.ts +11 -0
  61. package/src/commit/model-selection.ts +84 -0
  62. package/src/commit/pipeline.ts +242 -0
  63. package/src/commit/prompts/analysis-system.md +155 -0
  64. package/src/commit/prompts/analysis-user.md +41 -0
  65. package/src/commit/prompts/changelog-system.md +56 -0
  66. package/src/commit/prompts/changelog-user.md +19 -0
  67. package/src/commit/prompts/file-observer-system.md +26 -0
  68. package/src/commit/prompts/file-observer-user.md +9 -0
  69. package/src/commit/prompts/reduce-system.md +60 -0
  70. package/src/commit/prompts/reduce-user.md +17 -0
  71. package/src/commit/prompts/summary-retry.md +4 -0
  72. package/src/commit/prompts/summary-system.md +52 -0
  73. package/src/commit/prompts/summary-user.md +13 -0
  74. package/src/commit/prompts/types-description.md +2 -0
  75. package/src/commit/types.ts +109 -0
  76. package/src/commit/utils/exclusions.ts +42 -0
  77. package/src/config/file-lock.ts +111 -0
  78. package/src/config/model-registry.ts +16 -7
  79. package/src/config/settings-manager.ts +115 -40
  80. package/src/config.ts +5 -5
  81. package/src/discovery/agents-md.ts +1 -1
  82. package/src/discovery/builtin.ts +1 -1
  83. package/src/discovery/claude.ts +1 -1
  84. package/src/discovery/cline.ts +1 -1
  85. package/src/discovery/codex.ts +1 -1
  86. package/src/discovery/cursor.ts +1 -1
  87. package/src/discovery/gemini.ts +1 -1
  88. package/src/discovery/github.ts +1 -1
  89. package/src/discovery/index.ts +11 -11
  90. package/src/discovery/mcp-json.ts +1 -1
  91. package/src/discovery/ssh.ts +1 -1
  92. package/src/discovery/vscode.ts +1 -1
  93. package/src/discovery/windsurf.ts +1 -1
  94. package/src/extensibility/custom-commands/loader.ts +1 -1
  95. package/src/extensibility/custom-commands/types.ts +1 -1
  96. package/src/extensibility/custom-tools/loader.ts +1 -1
  97. package/src/extensibility/custom-tools/types.ts +1 -1
  98. package/src/extensibility/extensions/loader.ts +1 -1
  99. package/src/extensibility/extensions/types.ts +1 -1
  100. package/src/extensibility/hooks/loader.ts +1 -1
  101. package/src/extensibility/hooks/types.ts +3 -3
  102. package/src/index.ts +10 -10
  103. package/src/ipy/executor.ts +97 -1
  104. package/src/lsp/index.ts +1 -1
  105. package/src/lsp/render.ts +90 -46
  106. package/src/main.ts +16 -3
  107. package/src/mcp/loader.ts +3 -3
  108. package/src/migrations.ts +3 -3
  109. package/src/modes/components/assistant-message.ts +29 -1
  110. package/src/modes/components/tool-execution.ts +5 -3
  111. package/src/modes/components/tree-selector.ts +1 -1
  112. package/src/modes/controllers/extension-ui-controller.ts +1 -1
  113. package/src/modes/controllers/selector-controller.ts +1 -1
  114. package/src/modes/interactive-mode.ts +5 -3
  115. package/src/modes/rpc/rpc-client.ts +1 -1
  116. package/src/modes/rpc/rpc-mode.ts +1 -4
  117. package/src/modes/rpc/rpc-types.ts +1 -1
  118. package/src/modes/theme/mermaid-cache.ts +89 -0
  119. package/src/modes/theme/theme.ts +2 -0
  120. package/src/modes/types.ts +2 -2
  121. package/src/patch/index.ts +3 -9
  122. package/src/patch/shared.ts +33 -5
  123. package/src/prompts/tools/task.md +2 -0
  124. package/src/sdk.ts +60 -22
  125. package/src/session/agent-session.ts +3 -3
  126. package/src/session/agent-storage.ts +32 -28
  127. package/src/session/artifacts.ts +24 -1
  128. package/src/session/auth-storage.ts +25 -10
  129. package/src/session/storage-migration.ts +12 -53
  130. package/src/system-prompt.ts +2 -2
  131. package/src/task/.executor.ts.kate-swp +0 -0
  132. package/src/task/executor.ts +1 -1
  133. package/src/task/index.ts +10 -1
  134. package/src/task/output-manager.ts +94 -0
  135. package/src/task/render.ts +7 -12
  136. package/src/task/worker.ts +1 -1
  137. package/src/tools/ask.ts +35 -13
  138. package/src/tools/bash.ts +80 -87
  139. package/src/tools/calculator.ts +42 -40
  140. package/src/tools/complete.ts +1 -1
  141. package/src/tools/fetch.ts +67 -104
  142. package/src/tools/find.ts +83 -86
  143. package/src/tools/grep.ts +80 -96
  144. package/src/tools/index.ts +10 -7
  145. package/src/tools/ls.ts +39 -65
  146. package/src/tools/notebook.ts +48 -64
  147. package/src/tools/output-utils.ts +1 -1
  148. package/src/tools/python.ts +71 -183
  149. package/src/tools/read.ts +74 -15
  150. package/src/tools/render-utils.ts +1 -15
  151. package/src/tools/ssh.ts +43 -24
  152. package/src/tools/todo-write.ts +27 -15
  153. package/src/tools/write.ts +93 -64
  154. package/src/tui/code-cell.ts +115 -0
  155. package/src/tui/file-list.ts +48 -0
  156. package/src/tui/index.ts +11 -0
  157. package/src/tui/output-block.ts +73 -0
  158. package/src/tui/status-line.ts +40 -0
  159. package/src/tui/tree-list.ts +56 -0
  160. package/src/tui/types.ts +17 -0
  161. package/src/tui/utils.ts +49 -0
  162. package/src/vendor/photon/photon_rs_bg.wasm.b64.js +1 -0
  163. package/src/web/search/auth.ts +1 -1
  164. package/src/web/search/index.ts +1 -1
  165. package/src/web/search/render.ts +119 -163
  166. package/tsconfig.json +0 -42
@@ -0,0 +1,148 @@
1
+ import type { DiffHunk, FileDiff, FileHunks, NumstatEntry } from "@oh-my-pi/pi-coding-agent/commit/types";
2
+
3
+ export function parseNumstat(output: string): NumstatEntry[] {
4
+ const entries: NumstatEntry[] = [];
5
+ for (const line of output.split("\n")) {
6
+ if (!line.trim()) continue;
7
+ const parts = line.split("\t");
8
+ if (parts.length < 3) continue;
9
+ const [addedRaw, deletedRaw, pathRaw] = parts;
10
+ const additions = Number.parseInt(addedRaw, 10);
11
+ const deletions = Number.parseInt(deletedRaw, 10);
12
+ const path = extractPathFromRename(pathRaw);
13
+ entries.push({
14
+ path,
15
+ additions: Number.isNaN(additions) ? 0 : additions,
16
+ deletions: Number.isNaN(deletions) ? 0 : deletions,
17
+ });
18
+ }
19
+ return entries;
20
+ }
21
+
22
+ export function parseFileDiffs(diff: string): FileDiff[] {
23
+ const sections: FileDiff[] = [];
24
+ const parts = diff.split("\ndiff --git ");
25
+ for (let index = 0; index < parts.length; index += 1) {
26
+ const part = index === 0 ? parts[index] : `diff --git ${parts[index]}`;
27
+ if (!part.trim()) continue;
28
+ const lines = part.split("\n");
29
+ const header = lines[0] ?? "";
30
+ const match = header.match(/diff --git a\/(.+?) b\/(.+)$/);
31
+ if (!match) continue;
32
+ const filename = match[2];
33
+ const content = part;
34
+ const isBinary = lines.some((line) => line.startsWith("Binary files "));
35
+ let additions = 0;
36
+ let deletions = 0;
37
+ for (const line of lines) {
38
+ if (line.startsWith("+++") || line.startsWith("---")) continue;
39
+ if (line.startsWith("+")) additions += 1;
40
+ else if (line.startsWith("-")) deletions += 1;
41
+ }
42
+ sections.push({
43
+ filename,
44
+ content,
45
+ additions,
46
+ deletions,
47
+ isBinary,
48
+ });
49
+ }
50
+ return sections;
51
+ }
52
+
53
+ export function parseDiffHunks(diff: string): FileHunks[] {
54
+ const files = parseFileDiffs(diff);
55
+ return files.map((file) => parseFileHunks(file));
56
+ }
57
+
58
+ export function parseFileHunks(fileDiff: FileDiff): FileHunks {
59
+ if (fileDiff.isBinary) {
60
+ return { filename: fileDiff.filename, isBinary: true, hunks: [] };
61
+ }
62
+
63
+ const lines = fileDiff.content.split("\n");
64
+ const hunks: DiffHunk[] = [];
65
+ let current: DiffHunk | null = null;
66
+ let buffer: string[] = [];
67
+ let index = 0;
68
+
69
+ for (const line of lines) {
70
+ if (line.startsWith("@@")) {
71
+ if (current) {
72
+ current.content = buffer.join("\n");
73
+ hunks.push(current);
74
+ }
75
+ const headerData = parseHunkHeader(line);
76
+ current = {
77
+ index,
78
+ header: line,
79
+ oldStart: headerData.oldStart,
80
+ oldLines: headerData.oldLines,
81
+ newStart: headerData.newStart,
82
+ newLines: headerData.newLines,
83
+ content: "",
84
+ };
85
+ buffer = [line];
86
+ index += 1;
87
+ continue;
88
+ }
89
+ if (current) {
90
+ buffer.push(line);
91
+ }
92
+ }
93
+
94
+ if (current) {
95
+ current.content = buffer.join("\n");
96
+ hunks.push(current);
97
+ }
98
+
99
+ return {
100
+ filename: fileDiff.filename,
101
+ isBinary: fileDiff.isBinary,
102
+ hunks,
103
+ };
104
+ }
105
+
106
+ function extractPathFromRename(pathPart: string): string {
107
+ const braceStart = pathPart.indexOf("{");
108
+ if (braceStart !== -1) {
109
+ const arrowPos = pathPart.indexOf(" => ", braceStart);
110
+ if (arrowPos !== -1) {
111
+ const braceEnd = pathPart.indexOf("}", arrowPos);
112
+ if (braceEnd !== -1) {
113
+ const prefix = pathPart.slice(0, braceStart);
114
+ const newName = pathPart.slice(arrowPos + 4, braceEnd).trim();
115
+ return `${prefix}${newName}`;
116
+ }
117
+ }
118
+ }
119
+
120
+ if (pathPart.includes(" => ")) {
121
+ const parts = pathPart.split(" => ");
122
+ return parts[1]?.trim() ?? pathPart.trim();
123
+ }
124
+
125
+ return pathPart.trim();
126
+ }
127
+
128
+ function parseHunkHeader(line: string): {
129
+ oldStart: number;
130
+ oldLines: number;
131
+ newStart: number;
132
+ newLines: number;
133
+ } {
134
+ const match = line.match(/@@\s-([0-9]+)(?:,([0-9]+))?\s\+([0-9]+)(?:,([0-9]+))?\s@@/);
135
+ if (!match) {
136
+ return { oldStart: 0, oldLines: 0, newStart: 0, newLines: 0 };
137
+ }
138
+ const oldStart = Number.parseInt(match[1] ?? "0", 10);
139
+ const oldLines = Number.parseInt(match[2] ?? "1", 10);
140
+ const newStart = Number.parseInt(match[3] ?? "0", 10);
141
+ const newLines = Number.parseInt(match[4] ?? "1", 10);
142
+ return {
143
+ oldStart: Number.isNaN(oldStart) ? 0 : oldStart,
144
+ oldLines: Number.isNaN(oldLines) ? 0 : oldLines,
145
+ newStart: Number.isNaN(newStart) ? 0 : newStart,
146
+ newLines: Number.isNaN(newLines) ? 0 : newLines,
147
+ };
148
+ }
@@ -0,0 +1,11 @@
1
+ export class GitError extends Error {
2
+ readonly command: string;
3
+ readonly stderr: string;
4
+
5
+ constructor(command: string, stderr: string) {
6
+ super(`${command} failed: ${stderr || "unknown error"}`);
7
+ this.command = command;
8
+ this.stderr = stderr;
9
+ this.name = "GitError";
10
+ }
11
+ }
@@ -0,0 +1,217 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ parseDiffHunks,
7
+ parseFileDiffs,
8
+ parseFileHunks,
9
+ parseNumstat,
10
+ } from "@oh-my-pi/pi-coding-agent/commit/git/diff";
11
+ import { GitError } from "@oh-my-pi/pi-coding-agent/commit/git/errors";
12
+ import { commit, push, resetStaging, runGitCommand, stageFiles } from "@oh-my-pi/pi-coding-agent/commit/git/operations";
13
+ import type { FileDiff, FileHunks, NumstatEntry } from "@oh-my-pi/pi-coding-agent/commit/types";
14
+ import { logger } from "@oh-my-pi/pi-utils";
15
+
16
+ export type HunkSelection = {
17
+ path: string;
18
+ hunks: { type: "all" } | { type: "indices"; indices: number[] } | { type: "lines"; start: number; end: number };
19
+ };
20
+
21
+ export class ControlledGit {
22
+ constructor(private readonly cwd: string) {}
23
+
24
+ async getDiff(staged: boolean): Promise<string> {
25
+ const args = staged ? ["diff", "--cached"] : ["diff"];
26
+ const result = await runGitCommand(this.cwd, args);
27
+ this.ensureSuccess(result, "git diff");
28
+ return result.stdout;
29
+ }
30
+
31
+ async getDiffForFiles(files: string[], staged = true): Promise<string> {
32
+ const args = staged ? ["diff", "--cached", "--", ...files] : ["diff", "--", ...files];
33
+ const result = await runGitCommand(this.cwd, args);
34
+ this.ensureSuccess(result, "git diff (files)");
35
+ return result.stdout;
36
+ }
37
+
38
+ async getChangedFiles(staged: boolean): Promise<string[]> {
39
+ const args = staged ? ["diff", "--cached", "--name-only"] : ["diff", "--name-only"];
40
+ const result = await runGitCommand(this.cwd, args);
41
+ this.ensureSuccess(result, "git diff --name-only");
42
+ return result.stdout
43
+ .split("\n")
44
+ .map((line) => line.trim())
45
+ .filter(Boolean);
46
+ }
47
+
48
+ async getStat(staged: boolean): Promise<string> {
49
+ const args = staged ? ["diff", "--cached", "--stat"] : ["diff", "--stat"];
50
+ const result = await runGitCommand(this.cwd, args);
51
+ this.ensureSuccess(result, "git diff --stat");
52
+ return result.stdout;
53
+ }
54
+
55
+ async getStatForFiles(files: string[], staged = true): Promise<string> {
56
+ const args = staged ? ["diff", "--cached", "--stat", "--", ...files] : ["diff", "--stat", "--", ...files];
57
+ const result = await runGitCommand(this.cwd, args);
58
+ this.ensureSuccess(result, "git diff --stat (files)");
59
+ return result.stdout;
60
+ }
61
+
62
+ async getNumstat(staged: boolean): Promise<NumstatEntry[]> {
63
+ const args = staged ? ["diff", "--cached", "--numstat"] : ["diff", "--numstat"];
64
+ const result = await runGitCommand(this.cwd, args);
65
+ this.ensureSuccess(result, "git diff --numstat");
66
+ return parseNumstat(result.stdout);
67
+ }
68
+
69
+ async getRecentCommits(count: number): Promise<string[]> {
70
+ const result = await runGitCommand(this.cwd, ["log", `-n${count}`, "--pretty=format:%s"]);
71
+ this.ensureSuccess(result, "git log");
72
+ return result.stdout
73
+ .split("\n")
74
+ .map((line) => line.trim())
75
+ .filter(Boolean);
76
+ }
77
+
78
+ async getStagedFiles(): Promise<string[]> {
79
+ const result = await runGitCommand(this.cwd, ["diff", "--cached", "--name-only"]);
80
+ this.ensureSuccess(result, "git diff --cached --name-only");
81
+ return result.stdout
82
+ .split("\n")
83
+ .map((line) => line.trim())
84
+ .filter(Boolean);
85
+ }
86
+
87
+ async getUntrackedFiles(): Promise<string[]> {
88
+ const result = await runGitCommand(this.cwd, ["ls-files", "--others", "--exclude-standard"]);
89
+ this.ensureSuccess(result, "git ls-files --others --exclude-standard");
90
+ return result.stdout
91
+ .split("\n")
92
+ .map((line) => line.trim())
93
+ .filter(Boolean);
94
+ }
95
+
96
+ async stageAll(): Promise<void> {
97
+ const result = await stageFiles(this.cwd, []);
98
+ this.ensureSuccess(result, "git add -A");
99
+ }
100
+
101
+ async stageFiles(files: string[]): Promise<void> {
102
+ const result = await stageFiles(this.cwd, files);
103
+ this.ensureSuccess(result, "git add");
104
+ }
105
+
106
+ async stageHunks(selections: HunkSelection[]): Promise<void> {
107
+ if (selections.length === 0) return;
108
+ const diff = await this.getDiff(false);
109
+ const fileDiffs = parseFileDiffs(diff);
110
+ const fileDiffMap = new Map(fileDiffs.map((entry) => [entry.filename, entry]));
111
+ const patchParts: string[] = [];
112
+ for (const selection of selections) {
113
+ const fileDiff = fileDiffMap.get(selection.path);
114
+ if (!fileDiff) {
115
+ throw new GitError("git apply --cached", `No diff found for ${selection.path}`);
116
+ }
117
+ if (fileDiff.isBinary) {
118
+ if (selection.hunks.type !== "all") {
119
+ throw new GitError("git apply --cached", `Cannot select hunks for binary file ${selection.path}`);
120
+ }
121
+ patchParts.push(fileDiff.content);
122
+ continue;
123
+ }
124
+
125
+ if (selection.hunks.type === "all") {
126
+ patchParts.push(fileDiff.content);
127
+ continue;
128
+ }
129
+
130
+ const fileHunks = parseFileHunks(fileDiff);
131
+ const selectedHunks = selectHunks(fileHunks, selection.hunks);
132
+ if (selectedHunks.length === 0) {
133
+ throw new GitError("git apply --cached", `No hunks selected for ${selection.path}`);
134
+ }
135
+ const header = extractFileHeader(fileDiff.content);
136
+ const filePatch = [header, ...selectedHunks.map((hunk) => hunk.content)].join("\n");
137
+ patchParts.push(filePatch);
138
+ }
139
+
140
+ const patch = joinPatch(patchParts);
141
+ if (!patch.trim()) return;
142
+ const tempPath = join(tmpdir(), `omp-hunks-${randomUUID()}.patch`);
143
+ try {
144
+ await Bun.write(tempPath, patch);
145
+ const result = await runGitCommand(this.cwd, ["apply", "--cached", "--binary", tempPath]);
146
+ this.ensureSuccess(result, "git apply --cached");
147
+ } finally {
148
+ await rm(tempPath, { force: true });
149
+ }
150
+ }
151
+
152
+ async resetStaging(files: string[] = []): Promise<void> {
153
+ const result = await resetStaging(this.cwd, files);
154
+ this.ensureSuccess(result, "git reset");
155
+ }
156
+
157
+ async commit(message: string): Promise<void> {
158
+ const result = await commit(this.cwd, message);
159
+ this.ensureSuccess(result, "git commit");
160
+ }
161
+
162
+ async push(): Promise<void> {
163
+ const result = await push(this.cwd);
164
+ this.ensureSuccess(result, "git push");
165
+ }
166
+
167
+ parseDiffFiles(diff: string): FileDiff[] {
168
+ return parseFileDiffs(diff);
169
+ }
170
+
171
+ parseDiffHunks(diff: string): FileHunks[] {
172
+ return parseDiffHunks(diff);
173
+ }
174
+
175
+ async getHunks(files: string[], staged = true): Promise<FileHunks[]> {
176
+ const diff = await this.getDiffForFiles(files, staged);
177
+ return this.parseDiffHunks(diff);
178
+ }
179
+
180
+ private ensureSuccess(result: { exitCode: number; stderr: string }, label: string): void {
181
+ if (result.exitCode !== 0) {
182
+ logger.error("commit git command failed", { label, stderr: result.stderr });
183
+ throw new GitError(label, result.stderr);
184
+ }
185
+ }
186
+ }
187
+
188
+ function extractFileHeader(diff: string): string {
189
+ const lines = diff.split("\n");
190
+ const headerLines: string[] = [];
191
+ for (const line of lines) {
192
+ if (line.startsWith("@@")) break;
193
+ headerLines.push(line);
194
+ }
195
+ return headerLines.join("\n");
196
+ }
197
+
198
+ function joinPatch(parts: string[]): string {
199
+ return parts
200
+ .map((part) => (part.endsWith("\n") ? part : `${part}\n`))
201
+ .join("\n")
202
+ .trimEnd()
203
+ .concat("\n");
204
+ }
205
+
206
+ function selectHunks(file: FileHunks, selector: HunkSelection["hunks"]): FileHunks["hunks"] {
207
+ if (selector.type === "indices") {
208
+ const wanted = new Set(selector.indices.map((value) => Math.max(1, Math.floor(value))));
209
+ return file.hunks.filter((hunk) => wanted.has(hunk.index + 1));
210
+ }
211
+ if (selector.type === "lines") {
212
+ const start = Math.floor(selector.start);
213
+ const end = Math.floor(selector.end);
214
+ return file.hunks.filter((hunk) => hunk.newStart <= end && hunk.newStart + hunk.newLines - 1 >= start);
215
+ }
216
+ return file.hunks;
217
+ }
@@ -0,0 +1,53 @@
1
+ import { $ } from "bun";
2
+
3
+ interface GitResult {
4
+ exitCode: number;
5
+ stdout: string;
6
+ stderr: string;
7
+ }
8
+
9
+ export async function runGitCommand(cwd: string, args: string[]): Promise<GitResult> {
10
+ const result = await $`git ${args}`.cwd(cwd).quiet().nothrow();
11
+ const stdout = result.text();
12
+ const stderr = result.stderr?.toString() ?? "";
13
+ return {
14
+ exitCode: result.exitCode ?? 0,
15
+ stdout,
16
+ stderr,
17
+ };
18
+ }
19
+
20
+ export async function stageFiles(cwd: string, files: string[]): Promise<GitResult> {
21
+ const args = files.length === 0 ? ["add", "-A"] : ["add", "--", ...files];
22
+ return runGitCommand(cwd, args);
23
+ }
24
+
25
+ export async function resetStaging(cwd: string, files: string[]): Promise<GitResult> {
26
+ const args = files.length === 0 ? ["reset"] : ["reset", "--", ...files];
27
+ return runGitCommand(cwd, args);
28
+ }
29
+
30
+ export async function push(cwd: string): Promise<GitResult> {
31
+ return runGitCommand(cwd, ["push"]);
32
+ }
33
+
34
+ export async function commit(cwd: string, message: string): Promise<GitResult> {
35
+ const child = Bun.spawn(["git", "commit", "-F", "-"], {
36
+ cwd,
37
+ stdin: Buffer.from(message),
38
+ stdout: "pipe",
39
+ stderr: "pipe",
40
+ });
41
+
42
+ const [stdout, stderr, exitCode] = await Promise.all([
43
+ new Response(child.stdout).text(),
44
+ new Response(child.stderr).text(),
45
+ child.exited,
46
+ ]);
47
+
48
+ return {
49
+ exitCode: exitCode ?? 0,
50
+ stdout: stdout.trim(),
51
+ stderr: stderr.trim(),
52
+ };
53
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Entry points for the omp commit command.
3
+ */
4
+
5
+ export { runCommitCommand } from "@oh-my-pi/pi-coding-agent/commit/pipeline";
File without changes
@@ -0,0 +1,63 @@
1
+ import type { Api, Model } from "@oh-my-pi/pi-ai";
2
+ import { parseFileDiffs } from "@oh-my-pi/pi-coding-agent/commit/git/diff";
3
+ import { runMapPhase } from "@oh-my-pi/pi-coding-agent/commit/map-reduce/map-phase";
4
+ import { runReducePhase } from "@oh-my-pi/pi-coding-agent/commit/map-reduce/reduce-phase";
5
+ import { estimateTokens } from "@oh-my-pi/pi-coding-agent/commit/map-reduce/utils";
6
+ import type { ConventionalAnalysis } from "@oh-my-pi/pi-coding-agent/commit/types";
7
+ import { isExcludedFile } from "@oh-my-pi/pi-coding-agent/commit/utils/exclusions";
8
+
9
+ const MIN_FILES_FOR_MAP_REDUCE = 4;
10
+ const MAX_FILE_TOKENS = 50_000;
11
+
12
+ export interface MapReduceSettings {
13
+ enabled?: boolean;
14
+ minFiles?: number;
15
+ maxFileTokens?: number;
16
+ maxConcurrency?: number;
17
+ timeoutMs?: number;
18
+ }
19
+
20
+ export interface MapReduceInput {
21
+ model: Model<Api>;
22
+ apiKey: string;
23
+ smolModel: Model<Api>;
24
+ smolApiKey: string;
25
+ diff: string;
26
+ stat: string;
27
+ scopeCandidates: string;
28
+ typesDescription?: string;
29
+ settings?: MapReduceSettings;
30
+ }
31
+
32
+ export function shouldUseMapReduce(diff: string, settings?: MapReduceSettings): boolean {
33
+ if (process.env.OMP_COMMIT_MAP_REDUCE?.toLowerCase() === "false") return false;
34
+ if (settings?.enabled === false) return false;
35
+ const minFiles = settings?.minFiles ?? MIN_FILES_FOR_MAP_REDUCE;
36
+ const maxFileTokens = settings?.maxFileTokens ?? MAX_FILE_TOKENS;
37
+ const files = parseFileDiffs(diff).filter((file) => !isExcludedFile(file.filename));
38
+ const fileCount = files.length;
39
+ if (fileCount >= minFiles) return true;
40
+ return files.some((file) => estimateTokens(file.content) > maxFileTokens);
41
+ }
42
+
43
+ /**
44
+ * Run map-reduce analysis for large diffs using smol + primary models.
45
+ */
46
+
47
+ export async function runMapReduceAnalysis(input: MapReduceInput): Promise<ConventionalAnalysis> {
48
+ const fileDiffs = parseFileDiffs(input.diff).filter((file) => !isExcludedFile(file.filename));
49
+ const observations = await runMapPhase({
50
+ model: input.smolModel,
51
+ apiKey: input.smolApiKey,
52
+ files: fileDiffs,
53
+ config: input.settings,
54
+ });
55
+ return runReducePhase({
56
+ model: input.model,
57
+ apiKey: input.apiKey,
58
+ observations,
59
+ stat: input.stat,
60
+ scopeCandidates: input.scopeCandidates,
61
+ typesDescription: input.typesDescription,
62
+ });
63
+ }
@@ -0,0 +1,193 @@
1
+ import type { Api, AssistantMessage, Model } from "@oh-my-pi/pi-ai";
2
+ import { completeSimple } from "@oh-my-pi/pi-ai";
3
+ import { truncateToTokenLimit } from "@oh-my-pi/pi-coding-agent/commit/map-reduce/utils";
4
+ import fileObserverSystemPrompt from "@oh-my-pi/pi-coding-agent/commit/prompts/file-observer-system.md" with {
5
+ type: "text",
6
+ };
7
+ import fileObserverUserPrompt from "@oh-my-pi/pi-coding-agent/commit/prompts/file-observer-user.md" with {
8
+ type: "text",
9
+ };
10
+ import type { FileDiff, FileObservation } from "@oh-my-pi/pi-coding-agent/commit/types";
11
+ import { isExcludedFile } from "@oh-my-pi/pi-coding-agent/commit/utils/exclusions";
12
+ import { renderPromptTemplate } from "@oh-my-pi/pi-coding-agent/config/prompt-templates";
13
+
14
+ const MAX_FILE_TOKENS = 50_000;
15
+ const MAX_CONTEXT_FILES = 20;
16
+ const MAX_CONCURRENCY = 5;
17
+ const MAP_PHASE_TIMEOUT_MS = 120_000;
18
+ const MAX_RETRIES = 3;
19
+ const RETRY_BACKOFF_MS = 1000;
20
+
21
+ export interface MapPhaseInput {
22
+ model: Model<Api>;
23
+ apiKey: string;
24
+ files: FileDiff[];
25
+ config?: {
26
+ maxFileTokens?: number;
27
+ maxConcurrency?: number;
28
+ timeoutMs?: number;
29
+ maxRetries?: number;
30
+ retryBackoffMs?: number;
31
+ };
32
+ }
33
+
34
+ export async function runMapPhase({ model, apiKey, files, config }: MapPhaseInput): Promise<FileObservation[]> {
35
+ const filtered = files.filter((file) => !isExcludedFile(file.filename));
36
+ const systemPrompt = renderPromptTemplate(fileObserverSystemPrompt);
37
+ const maxFileTokens = config?.maxFileTokens ?? MAX_FILE_TOKENS;
38
+ const maxConcurrency = config?.maxConcurrency ?? MAX_CONCURRENCY;
39
+ const timeoutMs = config?.timeoutMs ?? MAP_PHASE_TIMEOUT_MS;
40
+ const maxRetries = config?.maxRetries ?? MAX_RETRIES;
41
+ const retryBackoffMs = config?.retryBackoffMs ?? RETRY_BACKOFF_MS;
42
+ return runWithConcurrency(filtered, maxConcurrency, async (file) => {
43
+ if (file.isBinary) {
44
+ return {
45
+ file: file.filename,
46
+ observations: ["Binary file changed."],
47
+ additions: file.additions,
48
+ deletions: file.deletions,
49
+ };
50
+ }
51
+
52
+ const contextHeader = generateContextHeader(filtered, file.filename);
53
+ const truncated = truncateToTokenLimit(file.content, maxFileTokens);
54
+ const prompt = renderPromptTemplate(fileObserverUserPrompt, {
55
+ filename: file.filename,
56
+ diff: truncated,
57
+ context_header: contextHeader,
58
+ });
59
+
60
+ const response = await withRetry(
61
+ async () => {
62
+ const controller = new AbortController();
63
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
64
+ try {
65
+ return await completeSimple(
66
+ model,
67
+ {
68
+ systemPrompt: systemPrompt,
69
+ messages: [{ role: "user", content: prompt, timestamp: Date.now() }],
70
+ },
71
+ { apiKey, maxTokens: 400, signal: controller.signal },
72
+ );
73
+ } finally {
74
+ clearTimeout(timeout);
75
+ }
76
+ },
77
+ maxRetries,
78
+ retryBackoffMs,
79
+ );
80
+
81
+ const observations = parseObservations(response);
82
+ return {
83
+ file: file.filename,
84
+ observations,
85
+ additions: file.additions,
86
+ deletions: file.deletions,
87
+ };
88
+ });
89
+ }
90
+
91
+ function parseObservations(message: AssistantMessage): string[] {
92
+ const text = message.content
93
+ .filter((content) => content.type === "text")
94
+ .map((content) => content.text)
95
+ .join("")
96
+ .trim();
97
+
98
+ if (!text) return [];
99
+
100
+ const lines = text
101
+ .split("\n")
102
+ .map((line) => line.trim())
103
+ .filter(Boolean)
104
+ .map((line) => line.replace(/^[-*]\s+/, ""))
105
+ .filter(Boolean);
106
+
107
+ return lines.slice(0, 5);
108
+ }
109
+
110
+ function generateContextHeader(files: FileDiff[], currentFile: string): string {
111
+ if (files.length > 100) {
112
+ return `(Large commit with ${files.length} total files)`;
113
+ }
114
+
115
+ const otherFiles = files.filter((file) => file.filename !== currentFile);
116
+ if (otherFiles.length === 0) return "";
117
+
118
+ const sorted = [...otherFiles].sort((a, b) => b.additions + b.deletions - (a.additions + a.deletions));
119
+ const toShow = sorted.length > MAX_CONTEXT_FILES ? sorted.slice(0, MAX_CONTEXT_FILES) : sorted;
120
+
121
+ const lines = ["OTHER FILES IN THIS CHANGE:"];
122
+ for (const file of toShow) {
123
+ const lineCount = file.additions + file.deletions;
124
+ const description = inferFileDescription(file);
125
+ lines.push(`- ${file.filename} (${lineCount} lines): ${description}`);
126
+ }
127
+
128
+ if (toShow.length < sorted.length) {
129
+ lines.push(`... and ${sorted.length - toShow.length} more files`);
130
+ }
131
+
132
+ return lines.join("\n");
133
+ }
134
+
135
+ function inferFileDescription(file: FileDiff): string {
136
+ const filenameLower = file.filename.toLowerCase();
137
+ if (filenameLower.includes("test")) return "test file";
138
+ if (filenameLower.endsWith(".md")) return "documentation";
139
+ if (
140
+ filenameLower.includes("config") ||
141
+ filenameLower.endsWith(".toml") ||
142
+ filenameLower.endsWith(".yaml") ||
143
+ filenameLower.endsWith(".yml")
144
+ ) {
145
+ return "configuration";
146
+ }
147
+ if (filenameLower.includes("error")) return "error definitions";
148
+ if (filenameLower.includes("type")) return "type definitions";
149
+ if (filenameLower.endsWith("mod.rs") || filenameLower.endsWith("lib.rs")) return "module exports";
150
+ if (filenameLower.endsWith("main.rs") || filenameLower.endsWith("main.go") || filenameLower.endsWith("main.py")) {
151
+ return "entry point";
152
+ }
153
+
154
+ const content = file.content;
155
+ if (content.includes("interface ") || content.includes("type ")) return "type definitions";
156
+ if (content.includes("class ") || content.includes("function ") || content.includes("fn ")) return "implementation";
157
+ if (content.includes("async ") || content.includes("await")) return "async code";
158
+ return "source code";
159
+ }
160
+
161
+ async function runWithConcurrency<T, R>(
162
+ items: T[],
163
+ limit: number,
164
+ worker: (item: T, index: number) => Promise<R>,
165
+ ): Promise<R[]> {
166
+ const results = new Array<R>(items.length);
167
+ let nextIndex = 0;
168
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
169
+ while (true) {
170
+ const current = nextIndex;
171
+ nextIndex += 1;
172
+ if (current >= items.length) return;
173
+ results[current] = await worker(items[current] as T, current);
174
+ }
175
+ });
176
+ await Promise.all(runners);
177
+ return results;
178
+ }
179
+
180
+ async function withRetry<T>(fn: () => Promise<T>, attempts: number, backoffMs: number): Promise<T> {
181
+ let lastError: unknown;
182
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
183
+ try {
184
+ return await fn();
185
+ } catch (error) {
186
+ lastError = error;
187
+ if (attempt < attempts - 1) {
188
+ await Bun.sleep(backoffMs * (attempt + 1));
189
+ }
190
+ }
191
+ }
192
+ throw lastError;
193
+ }