-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
617 lines (526 loc) · 20.8 KB
/
cli.ts
File metadata and controls
617 lines (526 loc) · 20.8 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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
#!/usr/bin/env node
/**
* @since 0.1.0
*
* CLI for exporting Claude Code sessions to GitHub Gists.
*
* Usage:
* claude-session-gists list # List available sessions
* claude-session-gists export # Export most recent session
* claude-session-gists export --project foo # Export session from project
* claude-session-gists create # Create GitHub Gist from session
* claude-session-gists create --commit # Create gist and output for git commit
*/
import { readFileSync } from "node:fs"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
import { Command, Options } from "@effect/cli"
import { NodeContext, NodeRuntime } from "@effect/platform-node"
import * as PlatformCommand from "@effect/platform/Command"
import * as CommandExecutor from "@effect/platform/CommandExecutor"
import { Console, Effect, Layer, Option } from "effect"
import * as FileSystem from "@effect/platform/FileSystem"
import * as Path from "@effect/platform/Path"
import {
SessionService,
makeSessionService,
Formatter,
FormatterLive,
GistService,
GistServiceLive,
type OutputFormat,
type Session
} from "../index.js"
// ============================================================================
// Package Version
// ============================================================================
const __dirname = dirname(fileURLToPath(import.meta.url))
const packageJson = JSON.parse(
readFileSync(join(__dirname, "../../package.json"), "utf-8")
) as { version: string }
const VERSION = packageJson.version
// ============================================================================
// Shared Options
// ============================================================================
const projectOption = Options.text("project").pipe(
Options.withAlias("p"),
Options.withDescription("Filter by project name (partial match)"),
Options.optional
)
const allProjectsOption = Options.boolean("all").pipe(
Options.withAlias("a"),
Options.withDescription("Show sessions from all projects (not just current directory)"),
Options.withDefault(false)
)
const formatOption = Options.choice("format", ["markdown", "json", "html"]).pipe(
Options.withAlias("f"),
Options.withDescription("Output format"),
Options.withDefault("markdown" as const)
)
const outputOption = Options.file("output").pipe(
Options.withAlias("o"),
Options.withDescription("Output file path"),
Options.optional
)
const publicOption = Options.boolean("public").pipe(
Options.withDescription("Create a public gist (default: secret)"),
Options.withDefault(false)
)
const includeToolsOption = Options.boolean("tools").pipe(
Options.withAlias("t"),
Options.withDescription("Include tool usage details"),
Options.withDefault(true)
)
const commitOption = Options.boolean("commit").pipe(
Options.withAlias("c"),
Options.withDescription("Output gist URL in format suitable for git commit trailers"),
Options.withDefault(false)
)
const sinceOption = Options.text("since").pipe(
Options.withAlias("s"),
Options.withDescription("Only include messages since timestamp (ISO format) or 'last-commit'"),
Options.optional
)
// ============================================================================
// Helpers
// ============================================================================
/**
* Get the timestamp of the last git commit
*/
const getLastCommitTimestamp: Effect.Effect<
Option.Option<Date>,
never,
CommandExecutor.CommandExecutor
> = Effect.gen(function* () {
const command = PlatformCommand.make("git", "log", "-1", "--format=%cI")
const result = yield* PlatformCommand.string(command).pipe(
Effect.map(output => {
const trimmed = output.trim()
if (!trimmed) return Option.none()
const date = new Date(trimmed)
return isNaN(date.getTime()) ? Option.none() : Option.some(date)
}),
Effect.catchAll(() => Effect.succeed(Option.none()))
)
return result
})
/**
* Parse the --since option into a Date
*/
const parseSinceOption = (
since: Option.Option<string>
): Effect.Effect<Option.Option<Date>, never, CommandExecutor.CommandExecutor> =>
Option.match(since, {
onNone: () => Effect.succeed(Option.none()),
onSome: (value) => {
if (value === "last-commit") {
return getLastCommitTimestamp
}
const date = new Date(value)
if (isNaN(date.getTime())) {
return Effect.succeed(Option.none())
}
return Effect.succeed(Option.some(date))
}
})
/**
* Filter session messages to only those after a given timestamp
*/
const filterSessionSince = (session: Session, since: Option.Option<Date>): Session =>
Option.match(since, {
onNone: () => session,
onSome: (sinceDate) => ({
...session,
messages: session.messages.filter(msg =>
Option.match(msg.timestamp, {
onNone: () => true, // Include messages without timestamps
onSome: (ts) => ts.getTime() > sinceDate.getTime()
})
)
})
})
// ============================================================================
// List Command
// ============================================================================
const listCommand = Command.make(
"list",
{ project: projectOption, all: allProjectsOption },
({ project, all }) =>
Effect.gen(function* () {
// Construct session service with appropriate scopeToCwd setting
// --all disables scoping to CWD, --project also disables it (explicit filter)
const scopeToCwd = !all && Option.isNone(project)
const sessionLayer = makeSessionService({
projectFilter: project,
scopeToCwd
})
yield* Effect.gen(function* () {
const sessionService = yield* SessionService
yield* Console.log("\n📁 Claude Code Sessions\n")
yield* Console.log("─".repeat(80))
const sessions = yield* sessionService.discover
if (sessions.length === 0) {
if (scopeToCwd) {
yield* Console.log("No sessions found for current directory.")
yield* Console.log("\nUse --all to list sessions from all projects.")
} else {
yield* Console.log("No sessions found.")
yield* Console.log("\nMake sure you have used Claude Code at least once.")
}
return
}
yield* Console.log(
`${"#".padEnd(4)} ${"Project".padEnd(40)} ${"Modified".padEnd(20)} ${"Msgs".padEnd(6)}`
)
yield* Console.log("─".repeat(80))
for (let i = 0; i < sessions.length; i++) {
const s = sessions[i]!
const modified = s.lastModified.toISOString().substring(0, 16).replace("T", " ")
const projectDisplay = s.projectName.length > 38
? s.projectName.substring(0, 35) + "..."
: s.projectName
yield* Console.log(
`${String(i + 1).padEnd(4)} ${projectDisplay.padEnd(40)} ${modified.padEnd(20)} ${String(s.messageCount).padEnd(6)}`
)
}
yield* Console.log("")
yield* Console.log(`Total: ${sessions.length} session(s)`)
if (scopeToCwd) {
yield* Console.log(`(Showing sessions for current directory. Use --all to see all projects.)`)
}
}).pipe(Effect.provide(sessionLayer))
})
)
// ============================================================================
// Export Command
// ============================================================================
const exportCommand = Command.make(
"export",
{
project: projectOption,
format: formatOption,
output: outputOption,
includeTools: includeToolsOption,
since: sinceOption
},
({ project, format, output, includeTools, since }) =>
Effect.gen(function* () {
// Construct session service scoped to current project (unless --project specified)
const sessionLayer = makeSessionService({
projectFilter: project,
scopeToCwd: Option.isNone(project)
})
yield* Effect.gen(function* () {
const sessionService = yield* SessionService
const formatter = yield* Formatter
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
yield* Console.log("🔍 Loading session...")
const fullSession = yield* sessionService.loadMostRecent
// Filter by --since if provided
const sinceDate = yield* parseSinceOption(since)
const session = filterSessionSince(fullSession, sinceDate)
yield* Console.log(`📝 Formatting as ${format}...`)
if (Option.isSome(sinceDate)) {
yield* Console.log(` Filtering to ${session.messages.length} messages since ${sinceDate.value.toISOString()}`)
}
const formatted = yield* formatter.format(session, format as OutputFormat, {
includeToolUse: includeTools
})
// Output to file or stdout
const outputPath = Option.match(output, {
onNone: () => Option.none<string>(),
onSome: (p) => Option.some(p)
})
if (Option.isSome(outputPath)) {
const outPath = Option.getOrThrow(outputPath)
yield* fs.writeFileString(outPath, formatted)
yield* Console.log(`✅ Exported to: ${outPath}`)
} else {
// Generate default filename
const filename = formatter.generateFilename(session.metadata, format as OutputFormat)
const defaultPath = path.join(process.cwd(), filename)
yield* fs.writeFileString(defaultPath, formatted)
yield* Console.log(`✅ Exported to: ${defaultPath}`)
}
yield* Console.log(` Project: ${session.metadata.projectName}`)
yield* Console.log(` Messages: ${session.messages.length}`)
}).pipe(Effect.provide(sessionLayer))
})
)
// ============================================================================
// Create Command
// ============================================================================
const createCommand = Command.make(
"create",
{
project: projectOption,
format: formatOption,
public: publicOption,
includeTools: includeToolsOption,
commit: commitOption,
since: sinceOption
},
({ project, format, public: isPublic, includeTools, commit, since }) =>
Effect.gen(function* () {
// Construct session service scoped to current project (unless --project specified)
const sessionLayer = makeSessionService({
projectFilter: project,
scopeToCwd: Option.isNone(project)
})
yield* Effect.gen(function* () {
const sessionService = yield* SessionService
const formatter = yield* Formatter
const gistService = yield* GistService
// Check authentication
const authMethod = yield* gistService.getAuthMethod
if (authMethod === "none") {
yield* Console.error("❌ No GitHub authentication found.")
yield* Console.error(" Run 'gh auth login' or set GITHUB_TOKEN environment variable.")
return yield* Effect.fail(new Error("No authentication"))
}
if (!commit) {
yield* Console.log(`🔐 Using ${authMethod} authentication`)
yield* Console.log("🔍 Loading session...")
}
const fullSession = yield* sessionService.loadMostRecent
// Filter by --since if provided
const sinceDate = yield* parseSinceOption(since)
const session = filterSessionSince(fullSession, sinceDate)
if (!commit) {
yield* Console.log(`📝 Formatting as ${format}...`)
if (Option.isSome(sinceDate)) {
yield* Console.log(` Filtering to ${session.messages.length} messages since ${sinceDate.value.toISOString()}`)
}
}
const formatted = yield* formatter.format(session, format as OutputFormat, {
includeToolUse: includeTools
})
const filename = formatter.generateFilename(session.metadata, format as OutputFormat)
if (!commit) {
yield* Console.log("🚀 Creating gist...")
}
const result = yield* gistService.create({
description: `Claude Code session: ${session.metadata.projectName} (${session.metadata.lastModified.toISOString().substring(0, 10)})`,
files: [{ filename, content: formatted }],
public: isPublic
})
if (commit) {
// Output just the URL in a format suitable for git commit trailers
yield* Console.log(`Claude-Session: ${result.htmlUrl}`)
} else {
yield* Console.log("")
yield* Console.log("✅ Gist created successfully!")
yield* Console.log("")
yield* Console.log(` 🔗 URL: ${result.htmlUrl}`)
yield* Console.log(` 📋 ID: ${result.id}`)
yield* Console.log(` 🔒 Visibility: ${isPublic ? "public" : "secret"}`)
yield* Console.log(` 📄 File: ${filename}`)
yield* Console.log("")
yield* Console.log("💡 To add to your commit message, use:")
yield* Console.log(` git commit -m "Your message" -m "Claude-Session: ${result.htmlUrl}"`)
}
}).pipe(Effect.provide(sessionLayer))
})
)
// ============================================================================
// Hook Command (for Claude Code Stop hook integration)
// ============================================================================
const hookCommand = Command.make(
"hook",
{
format: formatOption,
public: publicOption
},
({ format, public: isPublic }) =>
Effect.gen(function* () {
// Construct session service scoped to current project
const sessionLayer = makeSessionService({ scopeToCwd: true })
yield* Effect.gen(function* () {
// Read hook payload from stdin
// The Stop hook provides session info via stdin
const sessionService = yield* SessionService
const formatter = yield* Formatter
const gistService = yield* GistService
// For hooks, we use the most recent session for the current project
const session = yield* sessionService.loadMostRecent
const formatted = yield* formatter.format(session, format as OutputFormat, {
includeToolUse: true
})
const filename = formatter.generateFilename(session.metadata, format as OutputFormat)
const result = yield* gistService.create({
description: `Claude Code session: ${session.metadata.projectName} (auto-archived)`,
files: [{ filename, content: formatted }],
public: isPublic
})
// Output JSON for hook consumption
yield* Console.log(JSON.stringify({
success: true,
gistUrl: result.htmlUrl,
gistId: result.id,
project: session.metadata.projectName,
messageCount: session.messages.length
}))
}).pipe(Effect.provide(sessionLayer))
}).pipe(
Effect.catchAll((error) =>
Console.log(JSON.stringify({
success: false,
error: String(error)
}))
)
)
)
// ============================================================================
// Link Commit Command (for post-commit hook)
// ============================================================================
const gistUrlOption = Options.text("gist").pipe(
Options.withAlias("g"),
Options.withDescription("Gist URL or ID to update")
)
const repoOption = Options.text("repo").pipe(
Options.withAlias("r"),
Options.withDescription("GitHub repository (owner/repo) for commit links"),
Options.optional
)
/**
* Get commit info from git
*/
const getCommitInfo = Effect.gen(function* () {
const shaCommand = PlatformCommand.make("git", "rev-parse", "HEAD")
const sha = yield* PlatformCommand.string(shaCommand).pipe(
Effect.map(s => s.trim()),
Effect.catchAll(() => Effect.succeed(""))
)
const messageCommand = PlatformCommand.make("git", "log", "-1", "--format=%B")
const message = yield* PlatformCommand.string(messageCommand).pipe(
Effect.map(s => s.trim()),
Effect.catchAll(() => Effect.succeed(""))
)
const branchCommand = PlatformCommand.make("git", "rev-parse", "--abbrev-ref", "HEAD")
const branch = yield* PlatformCommand.string(branchCommand).pipe(
Effect.map(s => s.trim()),
Effect.catchAll(() => Effect.succeed(""))
)
// Try to get remote URL for repo info
const remoteCommand = PlatformCommand.make("git", "remote", "get-url", "origin")
const remoteUrl = yield* PlatformCommand.string(remoteCommand).pipe(
Effect.map(s => s.trim()),
Effect.catchAll(() => Effect.succeed(""))
)
// Parse repo from remote URL (handles both https and ssh formats)
let repo = ""
const httpsMatch = remoteUrl.match(/github\.com\/([^/]+\/[^/.]+)/)
const sshMatch = remoteUrl.match(/github\.com:([^/]+\/[^/.]+)/)
if (httpsMatch) repo = httpsMatch[1]!
else if (sshMatch) repo = sshMatch[1]!
return { sha, message, branch, repo }
})
/**
* Create commit info block to prepend to gist
*/
const createCommitInfoBlock = (
sha: string,
message: string,
branch: string,
repo: string
): string => {
const shortSha = sha.substring(0, 7)
const commitUrl = repo ? `https://github.com/${repo}/commit/${sha}` : ""
const commitLink = commitUrl ? `[${shortSha}](${commitUrl})` : shortSha
// Extract just the first line of commit message
const firstLine = message.split("\n")[0] || message
return `> **Commit:** ${commitLink}
> **Branch:** ${branch}
> **Message:** ${firstLine}
---
`
}
const linkCommitCommand = Command.make(
"link-commit",
{
gist: gistUrlOption,
repo: repoOption
},
({ gist, repo }) =>
Effect.gen(function* () {
const gistService = yield* GistService
// Extract gist ID from URL or use as-is
const gistId = gist.includes("/") ? gist.split("/").pop()! : gist
// Get commit info
const commitInfo = yield* getCommitInfo
const effectiveRepo = Option.getOrElse(repo, () => commitInfo.repo)
if (!commitInfo.sha) {
yield* Console.error("No commit found")
return
}
// Get the filename from the gist
const filesCommand = PlatformCommand.make("gh", "gist", "view", gistId, "--files")
const filename = yield* PlatformCommand.string(filesCommand).pipe(
Effect.map(s => s.trim().split("\n")[0] || "session.md"),
Effect.catchAll(() => Effect.succeed("session.md"))
)
// Fetch current gist content via gh CLI
const viewCommand = PlatformCommand.make("gh", "gist", "view", gistId, "-f", filename)
const currentContent = yield* PlatformCommand.string(viewCommand).pipe(
Effect.catchAll(() => Effect.succeed(""))
)
// Create commit info block and prepend
const commitBlock = createCommitInfoBlock(
commitInfo.sha,
commitInfo.message,
commitInfo.branch,
effectiveRepo
)
// Find the metadata table end (first --- after the table)
// The content looks like: # Title\n\n| ... |\n\n---\n\n## First message
const metadataEndMatch = currentContent.match(/\n---\n\n/)
let updatedContent: string
if (metadataEndMatch && metadataEndMatch.index !== undefined) {
const insertPos = metadataEndMatch.index + metadataEndMatch[0].length
updatedContent = currentContent.slice(0, insertPos) + commitBlock + currentContent.slice(insertPos)
} else {
// Fallback: prepend to content
updatedContent = commitBlock + currentContent
}
// Update the gist
yield* gistService.update({
gistId,
files: [{ filename, content: updatedContent }]
})
yield* Console.log(`Linked commit ${commitInfo.sha.substring(0, 7)} to gist ${gistId}`)
}).pipe(
Effect.catchAll((error) =>
Console.error(`Failed to link commit: ${error}`)
)
)
)
// ============================================================================
// Main Command
// ============================================================================
const mainCommand = Command.make("claude-session-gists").pipe(
Command.withDescription("Export Claude Code sessions to GitHub Gists for decision provenance"),
Command.withSubcommands([listCommand, exportCommand, createCommand, hookCommand, linkCommitCommand])
)
// ============================================================================
// CLI Setup
// ============================================================================
const cli = Command.run(mainCommand, {
name: "claude-session-gists",
version: VERSION
})
// ============================================================================
// Layer Composition
// ============================================================================
const MainLayer = Layer.mergeAll(
FormatterLive,
GistServiceLive
)
// ============================================================================
// Run
// ============================================================================
cli(process.argv).pipe(
Effect.provide(MainLayer),
Effect.provide(NodeContext.layer),
NodeRuntime.runMain
)