-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathindex.ts
More file actions
524 lines (448 loc) · 16.2 KB
/
index.ts
File metadata and controls
524 lines (448 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/**
* Plannotator CLI for Claude Code
*
* Supports four modes:
*
* 1. Plan Review (default, no args):
* - Spawned by ExitPlanMode hook
* - Reads hook event from stdin, extracts plan content
* - Serves UI, returns approve/deny decision to stdout
*
* 2. Code Review (`plannotator review`):
* - Triggered by /review slash command
* - Runs git diff, opens review UI
* - Outputs feedback to stdout (captured by slash command)
*
* 3. Annotate (`plannotator annotate <file.md>`):
* - Triggered by /plannotator-annotate slash command
* - Opens any markdown file in the annotation UI
* - Outputs structured feedback to stdout
*
* 4. Sessions (`plannotator sessions`):
* - Lists active Plannotator server sessions
* - `--open [N]` reopens a session in the browser
* - `--clean` removes stale session files
*
* Global flags:
* --browser <name> - Override which browser to open (e.g. "Google Chrome")
*
* Environment variables:
* PLANNOTATOR_REMOTE - Set to "1" or "true" for remote mode (preferred)
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
*/
import {
startPlannotatorServer,
handleServerReady,
} from "@plannotator/server";
import {
startReviewServer,
handleReviewServerReady,
} from "@plannotator/server/review";
import {
startAnnotateServer,
handleAnnotateServerReady,
} from "@plannotator/server/annotate";
import { getGitContext, runGitDiff } from "@plannotator/server/git";
import { parsePRUrl, checkAuth, fetchPR, getCliName, getCliInstallUrl, getMRLabel, getMRNumberLabel, getDisplayRepo } from "@plannotator/server/pr";
import { writeRemoteShareLink } from "@plannotator/server/share-url";
import { resolveMarkdownFile } from "@plannotator/server/resolve-file";
import { registerSession, unregisterSession, listSessions } from "@plannotator/server/sessions";
import { openBrowser } from "@plannotator/server/browser";
import { detectProjectName } from "@plannotator/server/project";
import { planDenyFeedback } from "@plannotator/shared/feedback-templates";
import { findSessionLogsForCwd, getLastRenderedMessage, type RenderedMessage } from "./session-log";
import { findCodexRolloutByThreadId, getLastCodexMessage } from "./codex-session";
import path from "path";
// Embed the built HTML at compile time
// @ts-ignore - Bun import attribute for text
import planHtml from "../dist/index.html" with { type: "text" };
const planHtmlContent = planHtml as unknown as string;
// @ts-ignore - Bun import attribute for text
import reviewHtml from "../dist/review.html" with { type: "text" };
const reviewHtmlContent = reviewHtml as unknown as string;
// Check for subcommand
const args = process.argv.slice(2);
// Global flag: --browser <name>
const browserIdx = args.indexOf("--browser");
if (browserIdx !== -1 && args[browserIdx + 1]) {
process.env.PLANNOTATOR_BROWSER = args[browserIdx + 1];
args.splice(browserIdx, 2);
}
// Ensure session cleanup on exit
process.on("exit", () => unregisterSession());
// Check if URL sharing is enabled (default: true)
const sharingEnabled = process.env.PLANNOTATOR_SHARE !== "disabled";
// Custom share portal URL for self-hosting
const shareBaseUrl = process.env.PLANNOTATOR_SHARE_URL || undefined;
// Paste service URL for short URL sharing
const pasteApiUrl = process.env.PLANNOTATOR_PASTE_URL || undefined;
if (args[0] === "sessions") {
// ============================================
// SESSION DISCOVERY MODE
// ============================================
if (args.includes("--clean")) {
// Force cleanup: list sessions (which auto-removes stale entries)
const sessions = listSessions();
console.error(`Cleaned up stale sessions. ${sessions.length} active session(s) remain.`);
process.exit(0);
}
const sessions = listSessions();
if (sessions.length === 0) {
console.error("No active Plannotator sessions.");
process.exit(0);
}
const openIdx = args.indexOf("--open");
if (openIdx !== -1) {
// Open a session in the browser
const nArg = args[openIdx + 1];
const n = nArg ? parseInt(nArg, 10) : 1;
const session = sessions[n - 1];
if (!session) {
console.error(`Session #${n} not found. ${sessions.length} active session(s).`);
process.exit(1);
}
await openBrowser(session.url);
console.error(`Opened ${session.mode} session in browser: ${session.url}`);
process.exit(0);
}
// List sessions as a table
console.error("Active Plannotator sessions:\n");
for (let i = 0; i < sessions.length; i++) {
const s = sessions[i];
const age = Math.round((Date.now() - new Date(s.startedAt).getTime()) / 60000);
const ageStr = age < 60 ? `${age}m` : `${Math.floor(age / 60)}h ${age % 60}m`;
console.error(` #${i + 1} ${s.mode.padEnd(9)} ${s.project.padEnd(20)} ${s.url.padEnd(28)} ${ageStr} ago`);
}
console.error(`\nReopen with: plannotator sessions --open [N]`);
process.exit(0);
} else if (args[0] === "review") {
// ============================================
// CODE REVIEW MODE
// ============================================
const urlArg = args[1];
const isPRMode = urlArg?.startsWith("http://") || urlArg?.startsWith("https://");
let rawPatch: string;
let gitRef: string;
let diffError: string | undefined;
let gitContext: Awaited<ReturnType<typeof getGitContext>> | undefined;
let prMetadata: Awaited<ReturnType<typeof fetchPR>>["metadata"] | undefined;
if (isPRMode) {
// --- PR Review Mode ---
const prRef = parsePRUrl(urlArg);
if (!prRef) {
console.error(`Invalid PR/MR URL: ${urlArg}`);
console.error("Supported formats:");
console.error(" GitHub: https://github.com/owner/repo/pull/123");
console.error(" GitLab: https://gitlab.com/group/project/-/merge_requests/42");
process.exit(1);
}
const cliName = getCliName(prRef);
const cliUrl = getCliInstallUrl(prRef);
try {
await checkAuth(prRef);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes("not found") || msg.includes("ENOENT")) {
console.error(`${cliName === "gh" ? "GitHub" : "GitLab"} CLI (${cliName}) is not installed.`);
console.error(`Install it from ${cliUrl}`);
} else {
console.error(msg);
}
process.exit(1);
}
console.error(`Fetching ${getMRLabel(prRef)} ${getMRNumberLabel(prRef)} from ${getDisplayRepo(prRef)}...`);
try {
const pr = await fetchPR(prRef);
rawPatch = pr.rawPatch;
gitRef = `${getMRLabel(prRef)} ${getMRNumberLabel(prRef)}`;
prMetadata = pr.metadata;
} catch (err) {
console.error(err instanceof Error ? err.message : "Failed to fetch PR");
process.exit(1);
}
} else {
// --- Local Review Mode ---
gitContext = await getGitContext();
const diffResult = await runGitDiff("uncommitted", gitContext.defaultBranch);
rawPatch = diffResult.patch;
gitRef = diffResult.label;
diffError = diffResult.error;
}
const reviewProject = (await detectProjectName()) ?? "_unknown";
// Start review server (even if empty - user can switch diff types in local mode)
const server = await startReviewServer({
rawPatch,
gitRef,
error: diffError,
origin: "claude-code",
diffType: isPRMode ? undefined : "uncommitted",
gitContext,
prMetadata,
sharingEnabled,
shareBaseUrl,
htmlContent: reviewHtmlContent,
onReady: async (url, isRemote, port) => {
handleReviewServerReady(url, isRemote, port);
if (isRemote && sharingEnabled && rawPatch) {
await writeRemoteShareLink(rawPatch, shareBaseUrl, "review changes", "diff only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "review",
project: reviewProject,
startedAt: new Date().toISOString(),
label: isPRMode ? `${getMRLabel(prMetadata!).toLowerCase()}-review-${getDisplayRepo(prMetadata!)}${getMRNumberLabel(prMetadata!)}` : `review-${reviewProject}`,
});
// Wait for user feedback
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output feedback (captured by slash command)
if (result.approved) {
console.log("Code review completed — no changes requested.");
} else {
console.log(result.feedback);
if (!isPRMode) {
console.log("\nThe reviewer has identified issues above. You must address all of them.");
}
}
process.exit(0);
} else if (args[0] === "annotate") {
// ============================================
// ANNOTATE MODE
// ============================================
let filePath = args[1];
if (!filePath) {
console.error("Usage: plannotator annotate <file.md>");
process.exit(1);
}
// Strip @ prefix if present (Claude Code file reference syntax)
if (filePath.startsWith("@")) {
filePath = filePath.slice(1);
}
// Use PLANNOTATOR_CWD if set (original working directory before script cd'd)
const projectRoot = process.env.PLANNOTATOR_CWD || process.cwd();
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Project root: ${projectRoot}`);
console.error(`[DEBUG] File path arg: ${filePath}`);
}
// Smart file resolution: exact path, case-insensitive relative, or bare filename search
const resolved = await resolveMarkdownFile(filePath, projectRoot);
if (resolved.kind === "ambiguous") {
console.error(`Ambiguous filename "${resolved.input}" — found ${resolved.matches.length} matches:`);
for (const match of resolved.matches) {
console.error(` ${match}`);
}
process.exit(1);
}
if (resolved.kind === "not_found") {
console.error(`File not found: ${resolved.input}`);
process.exit(1);
}
const absolutePath = resolved.path;
console.error(`Resolved: ${absolutePath}`);
const markdown = await Bun.file(absolutePath).text();
const annotateProject = (await detectProjectName()) ?? "_unknown";
// Start the annotate server (reuses plan editor HTML)
const server = await startAnnotateServer({
markdown,
filePath: absolutePath,
origin: "claude-code",
sharingEnabled,
shareBaseUrl,
htmlContent: planHtmlContent,
onReady: async (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(markdown, shareBaseUrl, "annotate", "document only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "annotate",
project: annotateProject,
startedAt: new Date().toISOString(),
label: `annotate-${path.basename(absolutePath)}`,
});
// Wait for user feedback
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output feedback (captured by slash command)
console.log(result.feedback || "No feedback provided.");
process.exit(0);
} else if (args[0] === "annotate-last" || args[0] === "last") {
// ============================================
// ANNOTATE LAST MESSAGE MODE
// ============================================
const projectRoot = process.env.PLANNOTATOR_CWD || process.cwd();
const codexThreadId = process.env.CODEX_THREAD_ID;
const isCodex = !!codexThreadId;
let lastMessage: RenderedMessage | null = null;
if (codexThreadId) {
// Codex path: find rollout by thread ID
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Codex detected, thread ID: ${codexThreadId}`);
}
const rolloutPath = findCodexRolloutByThreadId(codexThreadId);
if (rolloutPath) {
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Rollout: ${rolloutPath}`);
}
const msg = getLastCodexMessage(rolloutPath);
if (msg) {
lastMessage = { messageId: codexThreadId, text: msg.text, lineNumbers: [] };
}
}
} else {
// Claude Code path: find session logs by CWD
const candidates = findSessionLogsForCwd(projectRoot);
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Project root: ${projectRoot}`);
console.error(`[DEBUG] Candidates: ${candidates.join(", ")}`);
}
for (const logPath of candidates) {
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Trying: ${logPath}`);
}
lastMessage = getLastRenderedMessage(logPath);
if (lastMessage) break;
}
}
if (!lastMessage) {
console.error("No rendered assistant message found in session logs.");
process.exit(1);
}
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Found message ${lastMessage.messageId} (${lastMessage.text.length} chars)`);
}
const annotateProject = (await detectProjectName()) ?? "_unknown";
const server = await startAnnotateServer({
markdown: lastMessage.text,
filePath: "last-message",
origin: isCodex ? "codex" : "claude-code",
mode: "annotate-last",
sharingEnabled,
shareBaseUrl,
htmlContent: planHtmlContent,
onReady: async (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(lastMessage.text, shareBaseUrl, "annotate", "message only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "annotate",
project: annotateProject,
startedAt: new Date().toISOString(),
label: `annotate-last`,
});
const result = await server.waitForDecision();
await Bun.sleep(1500);
server.stop();
console.log(result.feedback || "No feedback provided.");
process.exit(0);
} else {
// ============================================
// PLAN REVIEW MODE (default)
// ============================================
// Read hook event from stdin
const eventJson = await Bun.stdin.text();
let planContent = "";
let permissionMode = "default";
try {
const event = JSON.parse(eventJson);
planContent = event.tool_input?.plan || "";
permissionMode = event.permission_mode || "default";
} catch {
console.error("Failed to parse hook event from stdin");
process.exit(1);
}
if (!planContent) {
console.error("No plan content in hook event");
process.exit(1);
}
const planProject = (await detectProjectName()) ?? "_unknown";
// Start the plan review server
const server = await startPlannotatorServer({
plan: planContent,
origin: "claude-code",
permissionMode,
sharingEnabled,
shareBaseUrl,
pasteApiUrl,
htmlContent: planHtmlContent,
onReady: async (url, isRemote, port) => {
handleServerReady(url, isRemote, port);
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(planContent, shareBaseUrl, "review the plan", "plan only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "plan",
project: planProject,
startedAt: new Date().toISOString(),
label: `plan-${planProject}`,
});
// Wait for user decision (blocks until approve/deny)
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output JSON for PermissionRequest hook decision control
if (result.approved) {
// Build updatedPermissions to preserve the current permission mode
const updatedPermissions = [];
if (result.permissionMode) {
updatedPermissions.push({
type: "setMode",
mode: result.permissionMode,
destination: "session",
});
}
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "allow",
...(updatedPermissions.length > 0 && { updatedPermissions }),
},
},
})
);
} else {
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "deny",
message: planDenyFeedback(result.feedback || "", "ExitPlanMode"),
},
},
})
);
}
process.exit(0);
}