codekin 0.3.7 → 0.4.1
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 +2 -1
- package/dist/assets/index-BAdQqYEY.js +182 -0
- package/dist/assets/index-CeZYNLWt.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +8 -2
- package/server/dist/approval-manager.d.ts +44 -8
- package/server/dist/approval-manager.js +262 -23
- package/server/dist/approval-manager.js.map +1 -1
- package/server/dist/claude-process.d.ts +16 -0
- package/server/dist/claude-process.js +42 -10
- package/server/dist/claude-process.js.map +1 -1
- package/server/dist/commit-event-handler.d.ts +41 -0
- package/server/dist/commit-event-handler.js +99 -0
- package/server/dist/commit-event-handler.js.map +1 -0
- package/server/dist/commit-event-hooks.d.ts +35 -0
- package/server/dist/commit-event-hooks.js +177 -0
- package/server/dist/commit-event-hooks.js.map +1 -0
- package/server/dist/crypto-utils.js +10 -5
- package/server/dist/crypto-utils.js.map +1 -1
- package/server/dist/diff-parser.d.ts +23 -0
- package/server/dist/diff-parser.js +242 -0
- package/server/dist/diff-parser.js.map +1 -0
- package/server/dist/session-manager.d.ts +27 -8
- package/server/dist/session-manager.js +375 -35
- package/server/dist/session-manager.js.map +1 -1
- package/server/dist/session-routes.js +109 -4
- package/server/dist/session-routes.js.map +1 -1
- package/server/dist/stepflow-handler.js +17 -3
- package/server/dist/stepflow-handler.js.map +1 -1
- package/server/dist/tsconfig.tsbuildinfo +1 -1
- package/server/dist/types.d.ts +62 -1
- package/server/dist/upload-routes.d.ts +1 -1
- package/server/dist/upload-routes.js +46 -16
- package/server/dist/upload-routes.js.map +1 -1
- package/server/dist/webhook-workspace.js +5 -2
- package/server/dist/webhook-workspace.js.map +1 -1
- package/server/dist/workflow-loader.d.ts +6 -0
- package/server/dist/workflow-loader.js +11 -0
- package/server/dist/workflow-loader.js.map +1 -1
- package/server/dist/workflow-routes.d.ts +5 -1
- package/server/dist/workflow-routes.js +48 -7
- package/server/dist/workflow-routes.js.map +1 -1
- package/server/dist/ws-message-handler.js +20 -0
- package/server/dist/ws-message-handler.js.map +1 -1
- package/server/dist/ws-server.js +19 -3
- package/server/dist/ws-server.js.map +1 -1
- package/server/workflows/commit-review.md +22 -0
- package/server/workflows/docs-audit.weekly.md +97 -0
- package/dist/assets/index-Dc76fIdG.js +0 -174
- package/dist/assets/index-DoL2Uppj.css +0 -1
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
* - SessionPersistence: disk I/O for session state
|
|
17
17
|
*/
|
|
18
18
|
import { randomUUID } from 'crypto';
|
|
19
|
+
import { execFile } from 'child_process';
|
|
20
|
+
import { promises as fs } from 'fs';
|
|
21
|
+
import path from 'path';
|
|
22
|
+
import { promisify } from 'util';
|
|
19
23
|
import { ClaudeProcess } from './claude-process.js';
|
|
20
24
|
import { SessionArchive } from './session-archive.js';
|
|
21
25
|
import { cleanupWorkspace } from './webhook-workspace.js';
|
|
@@ -24,6 +28,79 @@ import { ApprovalManager } from './approval-manager.js';
|
|
|
24
28
|
import { SessionNaming } from './session-naming.js';
|
|
25
29
|
import { SessionPersistence } from './session-persistence.js';
|
|
26
30
|
import { deriveSessionToken } from './crypto-utils.js';
|
|
31
|
+
import { parseDiff, createUntrackedFileDiff } from './diff-parser.js';
|
|
32
|
+
const execFileAsync = promisify(execFile);
|
|
33
|
+
/** Max stdout for git commands (2 MB). */
|
|
34
|
+
const GIT_MAX_BUFFER = 2 * 1024 * 1024;
|
|
35
|
+
/** Timeout for git commands (10 seconds). */
|
|
36
|
+
const GIT_TIMEOUT_MS = 10_000;
|
|
37
|
+
/** Max paths per git command to stay under ARG_MAX (~128 KB on Linux). */
|
|
38
|
+
const GIT_PATH_CHUNK_SIZE = 200;
|
|
39
|
+
/** Run a git command as a fixed argv array (no shell interpolation). */
|
|
40
|
+
async function execGit(args, cwd) {
|
|
41
|
+
const { stdout } = await execFileAsync('git', args, {
|
|
42
|
+
cwd,
|
|
43
|
+
maxBuffer: GIT_MAX_BUFFER,
|
|
44
|
+
timeout: GIT_TIMEOUT_MS,
|
|
45
|
+
});
|
|
46
|
+
return stdout;
|
|
47
|
+
}
|
|
48
|
+
/** Run a git command with paths chunked to avoid E2BIG. Concatenates stdout. */
|
|
49
|
+
async function execGitChunked(baseArgs, paths, cwd) {
|
|
50
|
+
let result = '';
|
|
51
|
+
for (let i = 0; i < paths.length; i += GIT_PATH_CHUNK_SIZE) {
|
|
52
|
+
const chunk = paths.slice(i, i + GIT_PATH_CHUNK_SIZE);
|
|
53
|
+
result += await execGit([...baseArgs, '--', ...chunk], cwd);
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
/** Get file statuses from `git status --porcelain` for given paths (or all). */
|
|
58
|
+
async function getFileStatuses(cwd, paths) {
|
|
59
|
+
const args = ['status', '--porcelain', '-z'];
|
|
60
|
+
if (paths)
|
|
61
|
+
args.push('--', ...paths);
|
|
62
|
+
const raw = await execGit(args, cwd);
|
|
63
|
+
const result = {};
|
|
64
|
+
// git status --porcelain=v1 -z format: XY NUL path NUL
|
|
65
|
+
// XY is a two-character status code: X = index status, Y = worktree status.
|
|
66
|
+
// Examples: " M" = unstaged modification, "A " = staged addition, "??" = untracked.
|
|
67
|
+
// For renames/copies: XY NUL oldpath NUL newpath NUL
|
|
68
|
+
const parts = raw.split('\0');
|
|
69
|
+
let i = 0;
|
|
70
|
+
while (i < parts.length) {
|
|
71
|
+
const entry = parts[i];
|
|
72
|
+
if (entry.length < 3) {
|
|
73
|
+
i++;
|
|
74
|
+
continue;
|
|
75
|
+
} // skip empty trailing entries
|
|
76
|
+
const x = entry[0]; // index status
|
|
77
|
+
const y = entry[1]; // worktree status
|
|
78
|
+
const filePath = entry.slice(3);
|
|
79
|
+
if (x === 'R' || x === 'C') {
|
|
80
|
+
// Rename/copy: next NUL-separated part is the new path
|
|
81
|
+
const newPath = parts[i + 1] ?? filePath;
|
|
82
|
+
result[newPath] = 'renamed';
|
|
83
|
+
i += 2;
|
|
84
|
+
}
|
|
85
|
+
else if (x === 'D' || y === 'D') {
|
|
86
|
+
result[filePath] = 'deleted';
|
|
87
|
+
i++;
|
|
88
|
+
}
|
|
89
|
+
else if (x === '?' && y === '?') {
|
|
90
|
+
result[filePath] = 'added';
|
|
91
|
+
i++;
|
|
92
|
+
}
|
|
93
|
+
else if (x === 'A') {
|
|
94
|
+
result[filePath] = 'added';
|
|
95
|
+
i++;
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
result[filePath] = 'modified';
|
|
99
|
+
i++;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return result;
|
|
103
|
+
}
|
|
27
104
|
/** Max messages retained in a session's output history buffer. */
|
|
28
105
|
const MAX_HISTORY = 2000;
|
|
29
106
|
/** Max auto-restart attempts before requiring manual intervention. */
|
|
@@ -50,22 +127,25 @@ const API_RETRY_PATTERNS = [
|
|
|
50
127
|
/503/,
|
|
51
128
|
];
|
|
52
129
|
export class SessionManager {
|
|
130
|
+
/** All active (non-archived) sessions, keyed by session UUID. */
|
|
53
131
|
sessions = new Map();
|
|
54
|
-
/**
|
|
132
|
+
/** Reverse lookup: WebSocket → session ID for O(1) client-to-session resolution. */
|
|
133
|
+
clientSessionMap = new Map();
|
|
134
|
+
/** SQLite archive for closed sessions (persists conversation summaries across restarts). */
|
|
55
135
|
archive;
|
|
56
136
|
/** Exposed so ws-server can pass its port to child Claude processes. */
|
|
57
137
|
_serverPort = PORT;
|
|
58
138
|
/** Exposed so ws-server can pass the auth token to child Claude processes. */
|
|
59
139
|
_authToken = '';
|
|
60
|
-
/** Callback to broadcast a message to ALL connected WebSocket clients (set by ws-server). */
|
|
140
|
+
/** Callback to broadcast a message to ALL connected WebSocket clients (set by ws-server on startup). */
|
|
61
141
|
_globalBroadcast = null;
|
|
62
|
-
/** Registered listeners notified when a session's Claude process exits. */
|
|
142
|
+
/** Registered listeners notified when a session's Claude process exits (used by webhook-handler for chained workflows). */
|
|
63
143
|
_exitListeners = [];
|
|
64
|
-
/** Delegated approval logic. */
|
|
144
|
+
/** Delegated approval logic (auto-approve patterns, deny-lists, pattern management). */
|
|
65
145
|
approvalManager;
|
|
66
|
-
/** Delegated naming logic. */
|
|
146
|
+
/** Delegated auto-naming logic (generates session names from first user message via Claude API). */
|
|
67
147
|
sessionNaming;
|
|
68
|
-
/** Delegated persistence logic. */
|
|
148
|
+
/** Delegated persistence logic (saves/restores session metadata to disk across server restarts). */
|
|
69
149
|
sessionPersistence;
|
|
70
150
|
constructor() {
|
|
71
151
|
this.archive = new SessionArchive();
|
|
@@ -94,6 +174,10 @@ export class SessionManager {
|
|
|
94
174
|
getApprovals(workingDir) {
|
|
95
175
|
return this.approvalManager.getApprovals(workingDir);
|
|
96
176
|
}
|
|
177
|
+
/** Return approvals effective globally via cross-repo inference. */
|
|
178
|
+
getGlobalApprovals() {
|
|
179
|
+
return this.approvalManager.getGlobalApprovals();
|
|
180
|
+
}
|
|
97
181
|
/** Remove an auto-approval rule for a repo (workingDir) and persist to disk. */
|
|
98
182
|
removeApproval(workingDir, opts, skipPersist = false) {
|
|
99
183
|
return this.approvalManager.removeApproval(workingDir, opts, skipPersist);
|
|
@@ -157,6 +241,7 @@ export class SessionManager {
|
|
|
157
241
|
isProcessing: false,
|
|
158
242
|
pendingControlRequests: new Map(),
|
|
159
243
|
pendingToolApprovals: new Map(),
|
|
244
|
+
_leaveGraceTimer: null,
|
|
160
245
|
};
|
|
161
246
|
this.sessions.set(id, session);
|
|
162
247
|
this.persistToDisk();
|
|
@@ -201,7 +286,13 @@ export class SessionManager {
|
|
|
201
286
|
const session = this.sessions.get(sessionId);
|
|
202
287
|
if (!session)
|
|
203
288
|
return undefined;
|
|
289
|
+
// Cancel pending auto-deny from leave grace period
|
|
290
|
+
if (session._leaveGraceTimer) {
|
|
291
|
+
clearTimeout(session._leaveGraceTimer);
|
|
292
|
+
session._leaveGraceTimer = null;
|
|
293
|
+
}
|
|
204
294
|
session.clients.add(ws);
|
|
295
|
+
this.clientSessionMap.set(ws, sessionId);
|
|
205
296
|
// Re-broadcast pending tool approval prompts (PreToolUse hook path)
|
|
206
297
|
for (const pending of session.pendingToolApprovals.values()) {
|
|
207
298
|
if (pending.promptMsg) {
|
|
@@ -218,28 +309,38 @@ export class SessionManager {
|
|
|
218
309
|
}
|
|
219
310
|
return session;
|
|
220
311
|
}
|
|
221
|
-
/** Remove a WebSocket client from a session. Auto-denies pending prompts if last client leaves. */
|
|
312
|
+
/** Remove a WebSocket client from a session. Auto-denies pending prompts if last client leaves (after grace period). */
|
|
222
313
|
leave(sessionId, ws) {
|
|
223
314
|
const session = this.sessions.get(sessionId);
|
|
224
315
|
if (session) {
|
|
225
316
|
session.clients.delete(ws);
|
|
226
|
-
|
|
317
|
+
this.clientSessionMap.delete(ws);
|
|
318
|
+
// If no clients remain, wait a grace period before auto-denying.
|
|
319
|
+
// This prevents false denials when the user is just refreshing the page.
|
|
227
320
|
if (session.clients.size === 0) {
|
|
228
|
-
if (session.
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
session.
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
321
|
+
if (session._leaveGraceTimer)
|
|
322
|
+
clearTimeout(session._leaveGraceTimer);
|
|
323
|
+
session._leaveGraceTimer = setTimeout(() => {
|
|
324
|
+
session._leaveGraceTimer = null;
|
|
325
|
+
// Re-check: if still no clients after grace period, auto-deny
|
|
326
|
+
if (session.clients.size === 0) {
|
|
327
|
+
if (session.pendingControlRequests.size > 0) {
|
|
328
|
+
console.log(`[session] last client left, auto-denying ${session.pendingControlRequests.size} pending control requests`);
|
|
329
|
+
for (const [requestId] of session.pendingControlRequests) {
|
|
330
|
+
session.claudeProcess?.sendControlResponse(requestId, 'deny');
|
|
331
|
+
}
|
|
332
|
+
session.pendingControlRequests.clear();
|
|
333
|
+
}
|
|
334
|
+
if (session.pendingToolApprovals.size > 0) {
|
|
335
|
+
console.log(`[session] last client left, auto-denying ${session.pendingToolApprovals.size} pending tool approval(s)`);
|
|
336
|
+
for (const [reqId, pending] of session.pendingToolApprovals) {
|
|
337
|
+
pending.resolve({ allow: false, always: false });
|
|
338
|
+
this.broadcast(session, { type: 'prompt_dismiss', requestId: reqId });
|
|
339
|
+
}
|
|
340
|
+
session.pendingToolApprovals.clear();
|
|
341
|
+
}
|
|
240
342
|
}
|
|
241
|
-
|
|
242
|
-
}
|
|
343
|
+
}, 3000);
|
|
243
344
|
}
|
|
244
345
|
}
|
|
245
346
|
}
|
|
@@ -255,6 +356,8 @@ export class SessionManager {
|
|
|
255
356
|
clearTimeout(session._apiRetryTimer);
|
|
256
357
|
if (session._namingTimer)
|
|
257
358
|
clearTimeout(session._namingTimer);
|
|
359
|
+
if (session._leaveGraceTimer)
|
|
360
|
+
clearTimeout(session._leaveGraceTimer);
|
|
258
361
|
// Kill claude process if running
|
|
259
362
|
if (session.claudeProcess) {
|
|
260
363
|
session.claudeProcess.stop();
|
|
@@ -670,10 +773,40 @@ export class SessionManager {
|
|
|
670
773
|
if (!session)
|
|
671
774
|
return;
|
|
672
775
|
// Check for pending tool approval from PreToolUse hook
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
776
|
+
if (!requestId) {
|
|
777
|
+
const totalPending = session.pendingToolApprovals.size + session.pendingControlRequests.size;
|
|
778
|
+
if (totalPending === 1) {
|
|
779
|
+
// Exactly one pending prompt — safe to infer the target
|
|
780
|
+
const soleApproval = session.pendingToolApprovals.size === 1
|
|
781
|
+
? session.pendingToolApprovals.values().next().value
|
|
782
|
+
: undefined;
|
|
783
|
+
if (soleApproval) {
|
|
784
|
+
console.warn(`[prompt_response] no requestId, routing to sole pending tool approval: ${soleApproval.toolName}`);
|
|
785
|
+
this.resolveToolApproval(session, soleApproval, value);
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
const soleControl = session.pendingControlRequests.size === 1
|
|
789
|
+
? session.pendingControlRequests.values().next().value
|
|
790
|
+
: undefined;
|
|
791
|
+
if (soleControl) {
|
|
792
|
+
console.warn(`[prompt_response] no requestId, routing to sole pending control request: ${soleControl.toolName}`);
|
|
793
|
+
requestId = soleControl.requestId;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
else if (totalPending > 1) {
|
|
797
|
+
console.warn(`[prompt_response] no requestId with ${totalPending} pending prompts — rejecting to prevent misrouted response`);
|
|
798
|
+
this.broadcast(session, {
|
|
799
|
+
type: 'system_message',
|
|
800
|
+
subtype: 'error',
|
|
801
|
+
text: 'Prompt response could not be routed: multiple prompts pending. Please refresh and try again.',
|
|
802
|
+
});
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
else {
|
|
806
|
+
console.warn(`[prompt_response] no requestId, no pending prompts — forwarding as user message`);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
const approval = requestId ? session.pendingToolApprovals.get(requestId) : undefined;
|
|
677
810
|
if (approval) {
|
|
678
811
|
this.resolveToolApproval(session, approval, value);
|
|
679
812
|
return;
|
|
@@ -681,9 +814,7 @@ export class SessionManager {
|
|
|
681
814
|
if (!session.claudeProcess?.isAlive())
|
|
682
815
|
return;
|
|
683
816
|
// Find matching pending control request
|
|
684
|
-
const pending = requestId
|
|
685
|
-
? session.pendingControlRequests.get(requestId)
|
|
686
|
-
: session.pendingControlRequests.values().next().value; // fallback: oldest
|
|
817
|
+
const pending = requestId ? session.pendingControlRequests.get(requestId) : undefined;
|
|
687
818
|
if (pending) {
|
|
688
819
|
session.pendingControlRequests.delete(pending.requestId);
|
|
689
820
|
// Dismiss prompt on all other clients viewing this session
|
|
@@ -1028,19 +1159,228 @@ export class SessionManager {
|
|
|
1028
1159
|
}
|
|
1029
1160
|
}
|
|
1030
1161
|
}
|
|
1031
|
-
// Find which session a WebSocket is connected to
|
|
1162
|
+
// Find which session a WebSocket is connected to (O(1) via reverse map)
|
|
1032
1163
|
findSessionForClient(ws) {
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
}
|
|
1164
|
+
const sessionId = this.clientSessionMap.get(ws);
|
|
1165
|
+
if (sessionId)
|
|
1166
|
+
return this.sessions.get(sessionId);
|
|
1037
1167
|
return undefined;
|
|
1038
1168
|
}
|
|
1039
|
-
// Remove a client from all sessions
|
|
1169
|
+
// Remove a client from all sessions (iterates for safety since a ws
|
|
1170
|
+
// could theoretically appear in multiple session client sets)
|
|
1040
1171
|
removeClient(ws) {
|
|
1041
1172
|
for (const session of this.sessions.values()) {
|
|
1042
1173
|
session.clients.delete(ws);
|
|
1043
1174
|
}
|
|
1175
|
+
this.clientSessionMap.delete(ws);
|
|
1176
|
+
}
|
|
1177
|
+
// ---------------------------------------------------------------------------
|
|
1178
|
+
// Diff viewer
|
|
1179
|
+
// ---------------------------------------------------------------------------
|
|
1180
|
+
/**
|
|
1181
|
+
* Run git diff in a session's workingDir and return structured results.
|
|
1182
|
+
* Includes untracked file discovery for 'unstaged' and 'all' scopes.
|
|
1183
|
+
*/
|
|
1184
|
+
async getDiff(sessionId, scope = 'all') {
|
|
1185
|
+
const session = this.sessions.get(sessionId);
|
|
1186
|
+
if (!session)
|
|
1187
|
+
return { type: 'diff_error', message: 'Session not found' };
|
|
1188
|
+
const cwd = session.workingDir;
|
|
1189
|
+
try {
|
|
1190
|
+
// Get branch name
|
|
1191
|
+
let branch;
|
|
1192
|
+
try {
|
|
1193
|
+
const branchResult = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
|
|
1194
|
+
branch = branchResult.trim();
|
|
1195
|
+
if (branch === 'HEAD') {
|
|
1196
|
+
const shaResult = await execGit(['rev-parse', '--short', 'HEAD'], cwd);
|
|
1197
|
+
branch = `detached at ${shaResult.trim()}`;
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
catch {
|
|
1201
|
+
branch = 'unknown';
|
|
1202
|
+
}
|
|
1203
|
+
// Build diff command based on scope
|
|
1204
|
+
const diffArgs = ['diff', '--find-renames', '--no-color', '--unified=3'];
|
|
1205
|
+
if (scope === 'staged') {
|
|
1206
|
+
diffArgs.push('--cached');
|
|
1207
|
+
}
|
|
1208
|
+
else if (scope === 'all') {
|
|
1209
|
+
diffArgs.push('HEAD');
|
|
1210
|
+
}
|
|
1211
|
+
// 'unstaged' uses bare `git diff` (working tree vs index)
|
|
1212
|
+
let rawDiff;
|
|
1213
|
+
try {
|
|
1214
|
+
rawDiff = await execGit(diffArgs, cwd);
|
|
1215
|
+
}
|
|
1216
|
+
catch {
|
|
1217
|
+
// git diff HEAD fails if no commits yet — fall back to staged + unstaged
|
|
1218
|
+
if (scope === 'all') {
|
|
1219
|
+
const [staged, unstaged] = await Promise.all([
|
|
1220
|
+
execGit(['diff', '--cached', '--find-renames', '--no-color', '--unified=3'], cwd).catch(() => ''),
|
|
1221
|
+
execGit(['diff', '--find-renames', '--no-color', '--unified=3'], cwd).catch(() => ''),
|
|
1222
|
+
]);
|
|
1223
|
+
rawDiff = staged + unstaged;
|
|
1224
|
+
}
|
|
1225
|
+
else {
|
|
1226
|
+
rawDiff = '';
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
const { files, truncated, truncationReason } = parseDiff(rawDiff);
|
|
1230
|
+
// Discover untracked files for 'unstaged' and 'all' scopes
|
|
1231
|
+
if (scope !== 'staged') {
|
|
1232
|
+
try {
|
|
1233
|
+
const untrackedRaw = await execGit(['ls-files', '--others', '--exclude-standard'], cwd);
|
|
1234
|
+
const untrackedPaths = untrackedRaw.trim().split('\n').filter(Boolean);
|
|
1235
|
+
for (const relPath of untrackedPaths) {
|
|
1236
|
+
try {
|
|
1237
|
+
const fullPath = path.join(cwd, relPath);
|
|
1238
|
+
// Check if binary by attempting to read as utf-8
|
|
1239
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
1240
|
+
files.push(createUntrackedFileDiff(relPath, content));
|
|
1241
|
+
}
|
|
1242
|
+
catch {
|
|
1243
|
+
// Binary or unreadable — add as binary
|
|
1244
|
+
files.push({
|
|
1245
|
+
path: relPath,
|
|
1246
|
+
status: 'added',
|
|
1247
|
+
isBinary: true,
|
|
1248
|
+
additions: 0,
|
|
1249
|
+
deletions: 0,
|
|
1250
|
+
hunks: [],
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
catch {
|
|
1256
|
+
// ls-files failed — skip untracked
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
const summary = {
|
|
1260
|
+
filesChanged: files.length,
|
|
1261
|
+
insertions: files.reduce((sum, f) => sum + f.additions, 0),
|
|
1262
|
+
deletions: files.reduce((sum, f) => sum + f.deletions, 0),
|
|
1263
|
+
truncated,
|
|
1264
|
+
truncationReason,
|
|
1265
|
+
};
|
|
1266
|
+
return { type: 'diff_result', files, summary, branch, scope };
|
|
1267
|
+
}
|
|
1268
|
+
catch (err) {
|
|
1269
|
+
const message = err instanceof Error ? err.message : 'Failed to get diff';
|
|
1270
|
+
return { type: 'diff_error', message };
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* Discard changes in a session's workingDir per the given scope and paths.
|
|
1275
|
+
* Returns a fresh diff_result after discarding.
|
|
1276
|
+
*/
|
|
1277
|
+
async discardChanges(sessionId, scope, paths, statuses) {
|
|
1278
|
+
const session = this.sessions.get(sessionId);
|
|
1279
|
+
if (!session)
|
|
1280
|
+
return { type: 'diff_error', message: 'Session not found' };
|
|
1281
|
+
const cwd = session.workingDir;
|
|
1282
|
+
try {
|
|
1283
|
+
// Validate paths — enforce separator boundary to prevent /repoX matching /repo
|
|
1284
|
+
if (paths) {
|
|
1285
|
+
const root = path.join(path.resolve(cwd), path.sep);
|
|
1286
|
+
for (const p of paths) {
|
|
1287
|
+
if (p.includes('..') || path.isAbsolute(p)) {
|
|
1288
|
+
return { type: 'diff_error', message: `Invalid path: ${p}` };
|
|
1289
|
+
}
|
|
1290
|
+
const resolved = path.resolve(cwd, p);
|
|
1291
|
+
if (resolved !== path.resolve(cwd) && !resolved.startsWith(root)) {
|
|
1292
|
+
return { type: 'diff_error', message: `Path escapes working directory: ${p}` };
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
// Determine file statuses if not provided
|
|
1297
|
+
let fileStatuses = statuses ?? {};
|
|
1298
|
+
if (!statuses && paths) {
|
|
1299
|
+
fileStatuses = await getFileStatuses(cwd, paths);
|
|
1300
|
+
}
|
|
1301
|
+
else if (!statuses && !paths) {
|
|
1302
|
+
fileStatuses = await getFileStatuses(cwd);
|
|
1303
|
+
}
|
|
1304
|
+
const targetPaths = paths ?? Object.keys(fileStatuses);
|
|
1305
|
+
// Separate files by status for different handling
|
|
1306
|
+
const trackedPaths = [];
|
|
1307
|
+
const untrackedPaths = [];
|
|
1308
|
+
const stagedNewPaths = [];
|
|
1309
|
+
for (const p of targetPaths) {
|
|
1310
|
+
const status = fileStatuses[p];
|
|
1311
|
+
if (status === 'added') {
|
|
1312
|
+
// Determine if untracked or staged-new by checking the index
|
|
1313
|
+
try {
|
|
1314
|
+
const indexEntry = (await execGit(['ls-files', '--stage', '--', p], cwd)).trim();
|
|
1315
|
+
if (indexEntry) {
|
|
1316
|
+
stagedNewPaths.push(p);
|
|
1317
|
+
}
|
|
1318
|
+
else {
|
|
1319
|
+
untrackedPaths.push(p);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
catch {
|
|
1323
|
+
untrackedPaths.push(p);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
else {
|
|
1327
|
+
trackedPaths.push(p);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
// Handle tracked files (modified, deleted, renamed) with git restore
|
|
1331
|
+
if (trackedPaths.length > 0) {
|
|
1332
|
+
const restoreArgs = ['restore'];
|
|
1333
|
+
if (scope === 'staged') {
|
|
1334
|
+
restoreArgs.push('--staged');
|
|
1335
|
+
}
|
|
1336
|
+
else if (scope === 'all') {
|
|
1337
|
+
restoreArgs.push('--staged', '--worktree');
|
|
1338
|
+
}
|
|
1339
|
+
else {
|
|
1340
|
+
restoreArgs.push('--worktree');
|
|
1341
|
+
}
|
|
1342
|
+
try {
|
|
1343
|
+
await execGitChunked(restoreArgs, trackedPaths, cwd);
|
|
1344
|
+
}
|
|
1345
|
+
catch (err) {
|
|
1346
|
+
// Fallback for Git < 2.23
|
|
1347
|
+
console.warn('[discard] git restore failed, trying fallback:', err);
|
|
1348
|
+
if (scope === 'staged' || scope === 'all') {
|
|
1349
|
+
await execGitChunked(['reset', 'HEAD'], trackedPaths, cwd);
|
|
1350
|
+
}
|
|
1351
|
+
if (scope === 'unstaged' || scope === 'all') {
|
|
1352
|
+
await execGitChunked(['checkout'], trackedPaths, cwd);
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
// Handle staged new files
|
|
1357
|
+
if (stagedNewPaths.length > 0) {
|
|
1358
|
+
if (scope === 'staged') {
|
|
1359
|
+
// Unstage only — leave on disk
|
|
1360
|
+
await execGitChunked(['rm', '--cached'], stagedNewPaths, cwd);
|
|
1361
|
+
}
|
|
1362
|
+
else if (scope === 'all') {
|
|
1363
|
+
// Remove from index and disk
|
|
1364
|
+
await execGitChunked(['rm', '--cached'], stagedNewPaths, cwd);
|
|
1365
|
+
for (const p of stagedNewPaths) {
|
|
1366
|
+
await fs.unlink(path.join(cwd, p)).catch(() => { });
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
// 'unstaged' scope: N/A for staged-new files
|
|
1370
|
+
}
|
|
1371
|
+
// Handle untracked files (delete from disk)
|
|
1372
|
+
if (untrackedPaths.length > 0 && scope !== 'staged') {
|
|
1373
|
+
for (const p of untrackedPaths) {
|
|
1374
|
+
await fs.unlink(path.join(cwd, p)).catch(() => { });
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
// Return fresh diff
|
|
1378
|
+
return await this.getDiff(sessionId, scope);
|
|
1379
|
+
}
|
|
1380
|
+
catch (err) {
|
|
1381
|
+
const message = err instanceof Error ? err.message : 'Failed to discard changes';
|
|
1382
|
+
return { type: 'diff_error', message };
|
|
1383
|
+
}
|
|
1044
1384
|
}
|
|
1045
1385
|
/** Graceful shutdown: complete in-progress tasks, persist state, kill all processes. */
|
|
1046
1386
|
shutdown() {
|