SLOPSHOPPER

session-outputs

Shows what the current session produced (PRs, branches, Jira, Notion, Slack and other links, edited files, scratchpad files) in a pane (/outputs)

panecommandtoastprocesstimer
v0.3.0no licenseupdated 2026-10-21binarythink/claude-marketplace/session-outputs
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-outputs
│ ┃ Session outputs ✕ › fix the failing auth test and add an audit log call │ ┃ [ Refresh ] 0 artifacts · updated 17:15:51 │ ┃ No artifacts in this session yet. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /outputs │ ⎿ session-outputs: Session outputs pane opened: 0 artifacts. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Session outputs
[ Refresh ] 0 artifacts · updated 17:15:51 No artifacts in this session yet.
README

claude-marketplace

Personal Claude Code mods.

ModCommandDescription
git-graph/git-graphToggles a side pane showing the working directory's git log as a graph
pii-guard—Checks each prompt for personal data before it is sent: blocks Korean unique identifiers, asks before sending phone numbers, emails, cards, accounts, addresses and attachments
session-outputs/outputsToggles a pane listing what the current session produced — PRs, branches, Jira/Notion/Confluence/Slack links, edited files, scratchpad files — grouped into what the session produced (output) and links you gave it (input)
todo-band/todo, /auto-todoToggles a pane showing the session scratchpad's TODO.jsonl (or TODO.md); its todo-plan skill has Claude keep the plan there with dependencies, and /auto-todo has Claude keep it up to date on every request
herdr-screenshot—Its herdr-screenshot skill saves a Herdr pane's screen as a PNG by rendering the pane's ANSI dump in headless Chrome

The panes stay closed until you run the command; running it again closes the pane.

todo-band: TODO.jsonl

The todo-plan skill has Claude write one JSON object per line to the session scratchpad:

{"id":"api","title":"Implement API","status":"doing","deps":["schema"]}
{"id":"deploy","title":"Deploy to dev1","status":"waiting","deps":["api"],"note":"user syncs ArgoCD"}

status is todo, doing (agent running it), waiting (waiting on the user to run or confirm something), done or cancelled. The pane orders items by deps, marks a todo whose deps are not all done as blocked, and flags broken lines, unknown deps and cycles. The full rules are in todo-band/skills/todo-plan/SKILL.md.

The hide done button in the pane's header (or h while the pane has focus) hides done and cancelled items (in TODO.md, - [x] lines) for the rest of the session; press show done (N) to bring them back. show keys (or k) prefixes each TODO.jsonl row with its id, e.g. ▶ [api] Implement API; hide keys turns it off.

/auto-todo [on|off]

Without auto-todo, TODO.jsonl exists only once Claude picks the todo-plan skill for a multi-step task, and later requests in the session go untracked. With /auto-todo on, every prompt you type carries a hidden instruction to keep TODO.jsonl current: work requests (edits, commands, investigation) are appended as items and their statuses updated; questions that need no work get none. If a turn edits files or runs commands but leaves TODO.jsonl untouched, the next prompt also carries a one-time reminder.

  • No argument toggles; the pane header shows auto ● (on) or auto ○ (off).
  • The setting lasts for the session only. To start every session on, set the plugin option autoTodoDefault to true in /config.
  • /auto-todo off stops the instruction and tells Claude once to stop updating the file on its own; the file and the pane stay.

pii-guard: 전송 전 개인정보 확인

프롬프트(붙여넣은 텍스트 포함)와 @경로로 참조한 파일을 전송 전에 검사한다.

처리유형
확인 없이 차단주민등록번호·외국인등록번호(구분자 있는 형식), 여권번호·운전면허번호(키워드 또는 구분자 형식)
"그래도 보낼까요?" 확인구분자 없는 13자리 주민번호 형식, 휴대전화, 이메일, 카드(Luhn), 계좌(키워드), 주소(시·도~번지), 이미지·문서 첨부
  • 대화상자와 차단 사유에는 유형과 건수만 표시하고 감지한 값은 표시하지 않는다.
  • 막힌 프롬프트는 엔진이 입력창에 되돌려 두므로 값을 지우고 다시 보낼 수 있다.
  • 물어볼 수 없는 경우(-p, SDK)나 검사 중 오류가 나면 보내지 않는다(fail-closed).
  • 모델이 도구로 읽는 파일·명령 출력은 검사하지 않는다. 첨부 이미지·문서는 내용 검사 없이 확인만 한다.

herdr-screenshot: pane 화면 PNG 저장

Herdr pane 안에서 "이 화면 캡처해줘" 처럼 요청하면 스킬이 scripts/cap.sh 를 실행한다.

cap.sh [--pane <id>] [--out <png|dir>] [--title <text>] [--lines N]
  • 기본은 현재 pane($HERDR_PANE_ID)의 보이는 화면. --lines N 이면 scrollback 포함
  • 측정 패스로 콘텐츠 크기를 잰 뒤 그 크기로 2배 해상도 스크린샷을 찍으므로 넓은 pane 도 잘리지 않는다
  • 필요: Google Chrome, 폰트 D2KodingLigature Nerd Font (한글 2칸 정렬용)

session-outputs: 세션 산출물 뷰어

/outputs 로 pane 을 열고 닫는다. 현재 진행 중인 세션의 transcript(~/.claude/projects/<slug>/<session id>.jsonl)와 scratchpad 를 읽어 수집 출처별로 두 그룹에 나눠 보여준다. 다른 세션의 산출물은 보이지 않는다.

그룹출처
outputassistant 의 글과 도구 입력(MCP 호출 포함)에 나온 URL, Write·Edit·NotebookEdit 와 Bash 명령으로 만들거나 고친 파일, git·gh 명령의 입출력, 세션 중 checkout 된 branch, 세션 scratchpad 의 파일
input사용자 메시지의 글에 나온 URL
  • 같은 항목이 두 그룹에서 나오면 처음 나온 쪽에만 보인다. 사용자가 준 참고 링크를 assistant 가 다시 언급해도 input 에 남는다
  • 그룹 안에서는 세션에 처음 나온 순서이고, 파일과 링크가 섞인다. scratchpad 파일은 output 의 맨 끝에 온다
  • 각 행은 type(PR · Branch · Jira · Confluence · Notion · Slack · GitHub · Web · File · Scratch), name, path 순이다. 파일의 name 은 파일 이름, path 는 worktree 기준 폴더(root 는 .)이고, 링크의 path 는 URL 이다. path 는 흐리게 보인다. 지금 없는 파일은 (deleted) 로 표시한다
  • git·gh 명령에서는 입력·출력 모두 GitHub 링크(PR · Branch · GitHub)만 남긴다. 출력은 gh pr create·gh issue create·gh release create·git push 의 것만 읽는다. gh pr view·gh api·git log 같은 조회 명령의 출력과 PR 본문(--body)의 Jira·Notion 링크는 참고 자료라 제외한다
  • Bash 명령은 실행하지 않고 글자만 읽어, 쓰기 대상 경로를 찾는다: redirect(>·>>·&>, heredoc 포함), sed -i·perl -i, cp·mv·install 의 대상, tee, touch, curl -o, dd of=, sh -c 안의 명령. 같은 명령 안의 변수 대입(f=~/x; cat >> "$f")과 cd 는 따라가고, 상대 경로는 그 명령을 보낸 때의 cwd 기준이다
  • 파일 이름에 $(date …) 처럼 실행해야 아는 값이 있으면(cp f "f.bak.$(date +%s)") 같은 폴더에서 이름이 맞고 명령을 보낸 뒤 고쳐진 파일 중 가장 먼저 고쳐진 것을 보인다. 찾지 못하면 보이지 않는다
  • cp a dir 처럼 대상이 폴더면 dir/a 를 보인다
  • 폴더 부분을 모르는 경로(정의하지 않은 $VAR, $(mktemp)), glob, /dev/* 는 제외한다. python script.py 처럼 프로그램 안에서 쓰는 파일은 찾지 못한다
  • branch 는 git checkout -b·git switch -c·git worktree add -b·git push -u 명령, git push 출력의 pull/new/<branch> URL 에서 찾는다
  • scratchpad 는 /tmp 아래라 재부팅 후에는 사라진다
  • r 로 다시 읽는다. 열려 있으면 10초마다 갱신한다
  • pane 에 포커스가 있을 때 j/k 로 한 item 씩 이동하고, c 는 선택한 item 의 이름, p 는 경로(파일은 절대 경로, 링크는 URL, URL 없는 branch 는 이름)를 클립보드에 복사한다
  • 4 MiB 가 넘는 transcript 는 tail -c 로 나눠 읽는다 ($.fs.read 상한)
  • 링크는 path 칸의 URL 을 클릭하면 열린다 (OSC 8 hyperlink). 파일은 OSC 8 을 못 그리는 터미널에서 file:// URL 이 덧붙지 않도록 링크를 걸지 않는다. p 로 절대 경로를 복사한다
  • attribution 링크(claude.ai/code/session_…, claude.com/claude-code), api.* 엔드포인트, Read·WebFetch 등 도구 결과 속 URL 은 잡음이라 제외한다

Install

In a Claude Code terminal session:

/plugin install git-graph --marketplace binarythink/claude-marketplace
/plugin install todo-band --marketplace binarythink/claude-marketplace
/plugin install pii-guard --marketplace binarythink/claude-marketplace
/plugin install herdr-screenshot --marketplace binarythink/claude-marketplace
/plugin install session-outputs --marketplace binarythink/claude-marketplace

Answer y to add the marketplace, then pick a scope.

Or from the shell:

claude plugin marketplace add binarythink/claude-marketplace
claude plugin install git-graph@binarythink
claude plugin install todo-band@binarythink
claude plugin install pii-guard@binarythink
claude plugin install herdr-screenshot@binarythink
claude plugin install session-outputs@binarythink

Update

Bump version in the mod's .claude-plugin/plugin.json when publishing a change, then:

claude plugin marketplace update binarythink
claude plugin update git-graph@binarythink

Develop

claude --plugin-dir ./git-graph   # loads the working copy, reloads on save
claude plugin validate .
claude plugin test ./git-graph
Source 4 files
hooks/register.tsx 388 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, UiPressArgument } from 'claude-code'
3
4import type { Artifact, ArtifactIndex, ArtifactKind, ArtifactSource } from '../types'
5import type { ParsedArtifact, ParsedTranscript } from './parse'
6import {
7  KIND_LABELS, clockTime, dirOf, displayPath, parseTranscript, parseWorktrees, slugOf, spanOf,
8} from './parse'
9
10const PANE = 'session-outputs'
11const TITLE = 'Session outputs'
12const POLL_MS = 10_000
13const TMP_ROOTS = ['/private/tmp', '/tmp']
14const SCRATCH_DEPTH = 2
15// $.fs.read 와 $.process.run 의 stdout 은 4 MiB 까지라, 그보다 큰 transcript 는 나눠 읽는다.
16const READ_LIMIT = 4 * 1024 * 1024
17// 명령을 보낸 시각(assistant 메시지 기록 시각)과 파일 mtime 사이의 시계 오차 여유
18const WRITTEN_SLACK_MS = 5_000
19
20const indexAtom = atom({ plugin: 'session-outputs', key: 'index' } as const, {} as ArtifactIndex)
21// j/k 로 고르는 item 의 순번. 화면에 그린 순서(출처별 묶음) 기준이다.
22const selectedAtom = atom({ plugin: 'session-outputs', key: 'selected' } as const, 0)
23
24// 그룹을 그리는 순서와 제목
25const GROUPS: { source: ArtifactSource; title: string }[] = [
26  { source: 'output', title: 'output' },
27  { source: 'input', title: 'input' },
28]
29
30const KIND_COLORS: Record<ArtifactKind, string> = {
31  pr: 'green',
32  branch: 'cyan',
33  jira: 'blue',
34  notion: 'white',
35  confluence: 'blue',
36  slack: 'magenta',
37  github: 'gray',
38  web: 'gray',
39  file: 'yellow',
40  scratch: 'yellow',
41}
42
43// transcript 는 수 MB 라 mtime·size 가 그대로면 다시 읽지 않는다. reload 하면 비워진다.
44let cached: { path: string; mtimeMs: number; size: number; parsed: ParsedTranscript } | undefined
45let isRefreshing = false
46
47const paneOf = async ($: EngineInterface) =>
48  (await $.ui.panes()).find(pane => pane.id === PANE)
49
50// 이 저장소의 worktree 들. 첫 줄이 main worktree 다. git 이 아니면 세션 root 하나.
51// 파일 경로를 줄이는 데 쓰고, transcript·scratchpad 폴더 이름(slug) 후보이기도 하다.
52async function worktreeRoots($: EngineInterface): Promise<string[]> {
53  const root = await $.session.root()
54  try {
55    const { exitCode, stdout } = await $.process.run(['git', 'worktree', 'list', '--porcelain'], { cwd: root, timeoutMs: 10_000 })
56    const roots = exitCode === 0 ? parseWorktrees(stdout) : []
57    if (roots.length > 0) return roots
58  } catch {}
59  return [root]
60}
61
62// <tmp>/claude-<uid> 폴더들. 세션 scratchpad 는 그 아래 <project slug>/<session id>/scratchpad 에 있다.
63async function tmpBases($: EngineInterface): Promise<string[]> {
64  const custom = await $.env.get('CLAUDE_CODE_TMPDIR')
65  // macOS 의 /tmp 는 /private/tmp 의 symlink 라 실제 경로로 한 번만 센다.
66  const bases = new Map<string, string>()
67  for (const root of custom ? [custom, ...TMP_ROOTS] : TMP_ROOTS) {
68    const entries = await $.fs.list(root).catch(() => [])
69    for (const one of entries) {
70      if (one.kind !== 'dir' || !one.name.startsWith('claude-')) continue
71      const base = `${root}/${one.name}`
72      const real = (await $.fs.stat(base, { resolve: true }).catch(() => undefined))?.realPath ?? base
73      if (!bases.has(real)) bases.set(real, base)
74    }
75  }
76  return [...bases.values()]
77}
78
79async function scratchFiles($: EngineInterface, dir: string, prefix = '', depth = 0): Promise<string[]> {
80  const entries = await $.fs.list(dir).catch(() => [])
81  const files: string[] = []
82  for (const one of entries.sort((a, b) => a.name.localeCompare(b.name))) {
83    if (one.kind === 'file') files.push(`${prefix}${one.name}`)
84    else if (one.kind === 'dir' && depth < SCRATCH_DEPTH) {
85      files.push(...await scratchFiles($, `${dir}/${one.name}`, `${prefix}${one.name}/`, depth + 1))
86    }
87  }
88  return files
89}
90
91// tail -c +<offset> 의 앞 4 MiB 에서 마지막 줄바꿈까지만 쓰고, 그 UTF-8 바이트 수만큼 offset 을 넘긴다.
92// 잘린 끝 줄(멀티바이트 글자가 잘렸을 수도 있다)은 다음 조각에서 처음부터 다시 읽힌다.
93async function readLarge($: EngineInterface, path: string): Promise<string> {
94  const encoder = new TextEncoder()
95  const chunks: string[] = []
96  let offset = 0
97  for (;;) {
98    const { exitCode, stdout, stderr, isStdoutTruncated } =
99      await $.process.run(['tail', '-c', `+${offset + 1}`, path], { timeoutMs: 30_000 })
100    if (exitCode !== 0) throw new Error(stderr.trim() || `tail exited with ${exitCode}`)
101    if (!isStdoutTruncated) {
102      chunks.push(stdout)
103      return chunks.join('')
104    }
105    const end = stdout.lastIndexOf('\n')
106    if (end < 0) throw new Error(`${path}: a line over 4 MiB`)
107    const whole = stdout.slice(0, end + 1)
108    chunks.push(whole)
109    offset += encoder.encode(whole).length
110  }
111}
112
113async function readTranscript($: EngineInterface, path: string, mtimeMs: number, size: number, home?: string) {
114  if (cached && cached.path === path && cached.mtimeMs === mtimeMs && cached.size === size) return cached.parsed
115  const text = size < READ_LIMIT ? await $.fs.read(path) : await readLarge($, path)
116  const parsed = parseTranscript(text, home)
117  cached = { path, mtimeMs, size, parsed }
118  return parsed
119}
120
121// Bash 가 쓴 파일 중 경로가 실행 결과에 달린 것의 지금 경로. 찾지 못하면 undefined 라 목록에서 뺀다.
122// - cp a dir: dir 이 폴더면 그 안의 a
123// - cp f "f.bak.$(date +%s)": 이름이 맞고 명령을 보낸 뒤 고쳐진 파일 중 가장 먼저 고쳐진 것
124async function settlePath($: EngineInterface, one: ParsedArtifact & { path: string }): Promise<string | undefined> {
125  if (one.intoDirName) {
126    const stat = await $.fs.stat(one.path).catch(() => undefined)
127    return stat?.kind === 'dir' ? `${one.path}/${one.intoDirName}` : one.path
128  }
129  if (!one.namePattern) return one.path
130  const dir = one.path.slice(0, one.path.lastIndexOf('/')) || '/'
131  const name = new RegExp(one.namePattern)
132  const after = (one.writtenAt ?? 0) - WRITTEN_SLACK_MS
133  const [first] = (await $.fs.list(dir).catch(() => []))
134    .filter(entry => entry.kind === 'file' && name.test(entry.name) && entry.mtimeMs >= after)
135    .sort((a, b) => a.mtimeMs - b.mtimeMs)
136  return first && `${dir === '/' ? '' : dir}/${first.name}`
137}
138
139// 현재 세션의 transcript 와 scratchpad 만 읽는다.
140// transcript 는 <config>/projects/<세션을 시작한 폴더의 slug>/<session id>.jsonl 이라, 시작 폴더 후보를 차례로 본다.
141async function buildIndex($: EngineInterface): Promise<ArtifactIndex> {
142  const home = await $.env.get('HOME')
143  const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home ? `${home}/.claude` : undefined)
144  if (!configDir) return { error: 'HOME is not set', loadedAt: Date.now() }
145
146  const [id, root, cwd, roots, bases] =
147    await Promise.all([$.session.id(), $.session.root(), $.session.cwd(), worktreeRoots($), tmpBases($)])
148  const slugs = [...new Set([root, cwd, ...roots].map(slugOf))]
149
150  let transcript: { path: string; mtimeMs: number; size: number } | undefined
151  for (const slug of slugs) {
152    const path = `${configDir}/projects/${slug}/${id}.jsonl`
153    const stat = await $.fs.stat(path).catch(() => undefined)
154    if (stat?.kind === 'file') {
155      transcript = { path, mtimeMs: stat.mtimeMs, size: stat.size }
156      break
157    }
158  }
159  // 새 세션은 첫 프롬프트를 보내기 전까지 transcript 가 없다. 오류가 아니라 아직 산출물이 없는 상태다.
160  if (!transcript) return { loadedAt: Date.now() }
161
162  const parsed = await readTranscript($, transcript.path, transcript.mtimeMs, transcript.size, home)
163  const artifacts: Artifact[] = []
164  const files = new Set<string>()
165  for (const { namePattern, writtenAt, intoDirName, ...one } of parsed.artifacts) {
166    if (one.kind !== 'file' || !one.path) {
167      artifacts.push(one)
168      continue
169    }
170    const path = await settlePath($, { ...one, path: one.path, namePattern, writtenAt, intoDirName })
171    // scratchpad 에 쓴 파일은 아래 Scratch 로 보인다.
172    if (!path || files.has(path) || path.includes(`/${id}/scratchpad/`)) continue
173    files.add(path)
174    const exists = await $.fs.exists(path).catch(() => false)
175    artifacts.push({
176      ...one,
177      label: path.split('/').pop() || path,
178      path,
179      displayPath: displayPath(path, roots, home),
180      href: exists ? `file://${path}` : undefined,
181      isGone: !exists,
182    })
183  }
184  scratch: for (const base of bases) {
185    for (const slug of slugs) {
186      const pad = `${base}/${slug}/${id}/scratchpad`
187      if (!(await $.fs.exists(pad).catch(() => false))) continue
188      for (const name of await scratchFiles($, pad)) {
189        const path = `${pad}/${name}`
190        artifacts.push({
191          kind: 'scratch',
192          label: name.split('/').pop() ?? name,
193          href: `file://${path}`,
194          path,
195          displayPath: displayPath(path, roots, home),
196          source: 'output',
197        })
198      }
199      break scratch
200    }
201  }
202
203  const prompt = parsed.firstPrompt
204  return {
205    session: {
206      id,
207      title: parsed.title ?? parsed.aiTitle ?? (prompt ? (prompt.length > 60 ? `${prompt.slice(0, 59)}…` : prompt) : '(untitled)'),
208      cwd: parsed.cwd,
209      startedAt: parsed.startedAt,
210      endedAt: parsed.endedAt ?? transcript.mtimeMs,
211      artifacts,
212    },
213    loadedAt: Date.now(),
214  }
215}
216
217async function refresh($: EngineInterface): Promise<ArtifactIndex | undefined> {
218  if (isRefreshing) return undefined
219  isRefreshing = true
220  try {
221    let index: ArtifactIndex
222    try {
223      index = await buildIndex($)
224    } catch (err) {
225      index = { ...(await read($, indexAtom)), error: String(err), loadedAt: Date.now() }
226    }
227    await update($, indexAtom, () => index)
228    return index
229  } finally {
230    isRefreshing = false
231  }
232}
233
234// 화면에 그리는 순서: 출처별로 묶고, 한 그룹 안에서는 세션에 처음 나온 순서(scratchpad 파일은 맨 끝).
235const orderOf = (artifacts: Artifact[]) =>
236  GROUPS.flatMap(group => artifacts.filter(one => one.source === group.source))
237
238// 행의 path 칸: 파일은 줄인 경로, 링크는 URL. URL 없는 branch 는 비운다.
239// 파일은 name 칸이 이미 파일 이름이라 폴더만 보인다.
240const locationOf = (one: Artifact) => (one.displayPath === undefined ? one.href : dirOf(one.displayPath))
241
242// p 가 복사하는 값: 파일은 절대 경로, 링크는 URL, URL 없는 branch 는 이름.
243const pathOf = (one: Artifact) => one.path ?? one.href ?? one.label
244
245const itemKey = (n: number) => `item-${n}`
246
247const summaryOf = (index: ArtifactIndex) => {
248  const count = index.session?.artifacts.length ?? 0
249  return `${count} artifact${count === 1 ? '' : 's'}`
250}
251
252export const register: Register = on => {
253  on('session.start', async ($, e, next) => {
254    await $.command.register({
255      name: 'outputs',
256      description: 'Toggle the pane showing what this session produced: PRs, branches, Jira/Notion/Slack links, files',
257    })
258    // reload 로 session.start 가 다시 불려도 pane 이 열려 있을 때만 읽는다.
259    if (await paneOf($).catch(() => undefined)) void refresh($).catch(() => undefined)
260    $.clock.every(POLL_MS, () => {
261      void (async () => {
262        if (await paneOf($)) await refresh($)
263      })().catch(() => undefined)
264    })
265
266    return next(e)
267  })
268
269  // /outputs 는 pane 을 열고 닫는 toggle 이다. 세션 시작 시 자동으로 열지 않는다.
270  // 다른 탭 뒤에 열려 있으면 닫지 않고 앞으로 가져온다.
271  on('command.run', { command: 'outputs' }, async $ => {
272    const pane = await paneOf($)
273    if (pane?.isShown) {
274      await $.ui.close({ id: PANE })
275      return { text: 'Session outputs pane closed.' }
276    }
277    if (pane) {
278      // 열린 id 를 다시 open 하면 제목만 바뀌고 탭은 그대로라, 닫았다 열어 맨 앞 탭으로 올린다.
279      await $.ui.close({ id: PANE })
280      await $.ui.open({ id: PANE, title: TITLE })
281      void refresh($).catch(() => undefined)
282      return { text: 'Session outputs pane brought to front.' }
283    }
284    const index = await refresh($) ?? await read($, indexAtom)
285    await $.ui.open({ id: PANE, title: TITLE })
286
287    return { text: index.error ? `Session outputs: ${index.error}` : `Session outputs pane opened: ${summaryOf(index)}.` }
288  })
289
290  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
291    const { Box, Text, Button, Link } = $.ui.resolve(e)
292    const index = await read($, indexAtom)
293    const session = index.session
294    const items = orderOf(session?.artifacts ?? [])
295    // 다시 읽어 item 이 줄었으면 마지막 item 에 머문다.
296    const selected = Math.min(await read($, selectedAtom), Math.max(0, items.length - 1))
297
298    // 키를 연달아 누르면 다시 그리기 전에 다음 press 가 오므로, 그린 시점의 selected 가 아니라 atom 의 지금 값을 쓴다.
299    const clamp = (n: number) => Math.min(items.length - 1, Math.max(0, n))
300    const move = (delta: number) => async () => {
301      if (items.length === 0) return
302      let next = 0
303      await update($, selectedAtom, current => (next = clamp(clamp(current) + delta)))
304      await $.ui.scroll({ to: { key: itemKey(next) }, in: PANE }).catch(() => undefined)
305    }
306    const copy = (what: 'name' | 'path') => async (press: UiPressArgument) => {
307      const item = items[clamp(await read($, selectedAtom))]
308      if (!item) return
309      const text = what === 'name' ? item.label : pathOf(item)
310      const { isCopied } = await $.ui.copy({ text, surface: press.surface })
311      await $.ui.toast(isCopied ? `Copied ${what}: ${text}` : `Could not copy the ${what}`)
312    }
313
314    const name = (one: Artifact) => one.isGone
315      ? <Text dimColor strikethrough>{`${one.label} (deleted)`}</Text>
316      : <Text>{one.label}</Text>
317    // path 칸은 흐리게 그린다. 링크는 URL 칸 자체를 Link 로 둔다. OSC 8 을 못 그리는 터미널은
318    // Link 글자 뒤에 URL 을 덧붙이므로, 글자 없이 href 만 주어야 URL 이 한 번만 보인다.
319    // 파일은 같은 이유로 Link 를 쓰지 않는다(폴더 뒤에 file:// URL 이 붙는다).
320    const location = (one: Artifact) => {
321      const text = locationOf(one)
322      if (!text) return null
323      return (
324        <Text dimColor>
325          {'  '}
326          {one.displayPath === undefined && one.href ? <Link href={one.href} /> : text}
327        </Text>
328      )
329    }
330
331    // 행은 type, name, path 순이다. type 칸은 이 pane 에 보이는 가장 긴 종류 이름에 맞춘다.
332    const typeWidth = Math.max(0, ...items.map(one => KIND_LABELS[one.kind].length))
333    let n = 0
334    const groups = GROUPS.flatMap(group => {
335      const rows = items.filter(one => one.source === group.source)
336      if (rows.length === 0) return []
337      return [(
338        <Box key={`g-${group.source}`} flexDirection="column" marginTop={1}>
339          <Text bold>{`▸ ${group.title} (${rows.length})`}</Text>
340          {rows.map(one => {
341            const at = n++
342            const isSelected = at === selected
343            return (
344              <Box key={itemKey(at)}>
345                <Text wrap="truncate-end">
346                  <Text color="cyan" bold>{isSelected ? '› ' : '  '}</Text>
347                  <Text color={KIND_COLORS[one.kind]}>{`${KIND_LABELS[one.kind].padEnd(typeWidth)}  `}</Text>
348                  {isSelected ? <Text inverse>{name(one)}</Text> : name(one)}
349                  {location(one)}
350                </Text>
351              </Box>
352            )
353          })}
354        </Box>
355      )]
356    })
357
358    const loaded = index.loadedAt ? ` · updated ${clockTime(index.loadedAt)}` : ''
359
360    return (
361      <Box flexDirection="column">
362        <Box flexDirection="row" gap={1}>
363          <Button key="refresh" label="Refresh" hotkey="r" onPress={() => void refresh($)} />
364          <Text dimColor wrap="truncate-end">{`${summaryOf(index)}${loaded}`}</Text>
365        </Box>
366        {items.length > 0 && (
367          <Box flexDirection="row" gap={2}>
368            <Button key="next" label="Next" hotkey="j" plain onPress={() => void move(1)()} />
369            <Button key="prev" label="Prev" hotkey="k" plain onPress={() => void move(-1)()} />
370            <Button key="copy-name" label="Copy name" hotkey="c" plain onPress={press => void copy('name')(press)} />
371            <Button key="copy-path" label="Copy path" hotkey="p" plain onPress={press => void copy('path')(press)} />
372          </Box>
373        )}
374        {session && (
375          <Text wrap="truncate-end">
376            <Text bold>{session.title}</Text>
377            <Text dimColor>{`  ${[spanOf(session.startedAt, session.endedAt), session.id.slice(0, 8)].filter(Boolean).join(' · ')}`}</Text>
378          </Text>
379        )}
380        {index.error && <Text color="red">{index.error}</Text>}
381        {!index.error && !index.loadedAt && <Text dimColor>Reading the session transcript…</Text>}
382        {index.loadedAt && !index.error && items.length === 0 && <Text dimColor>No artifacts in this session yet.</Text>}
383        {groups}
384      </Box>
385    )
386  })
387}
388
hooks/parse.ts 353 lines
1import type { Artifact, ArtifactKind, ArtifactSource } from '../types'
2import { writtenFiles } from './shell'
3
4// URL 하나를 분류한 결과. 어디서 나왔는지(source)는 수집하는 쪽이 붙인다.
5export type Link = Omit<Artifact, 'source'>
6
7export const KIND_LABELS: Record<ArtifactKind, string> = {
8  pr: 'PR',
9  branch: 'Branch',
10  jira: 'Jira',
11  notion: 'Notion',
12  confluence: 'Confluence',
13  slack: 'Slack',
14  github: 'GitHub',
15  web: 'Web',
16  file: 'File',
17  scratch: 'Scratch',
18}
19
20// 파일을 쓰는 도구. 입력의 경로가 산출물이고, 입력 본문의 URL 은 보지 않는다(README 의 설치 URL 같은 잡음).
21const FILE_TOOLS: Record<string, string> = {
22  Write: 'file_path',
23  Edit: 'file_path',
24  MultiEdit: 'file_path',
25  NotebookEdit: 'notebook_path',
26}
27
28// 괄호·따옴표·꺾쇠·백슬래시·비 ASCII 에서 끊는다. 마크다운 링크와 JSON 문자열 안의 URL 도 잡힌다.
29const URL_RE = /https?:\/\/[A-Za-z0-9\-._~:/?#@!$&*+,;=%]+/g
30const TRAILING_RE = /[.,;:!?*]+$/
31
32// 모든 커밋·PR 에 붙는 attribution 과 API 엔드포인트는 산출물이 아니다.
33// '…slack', '…atlassian' 처럼 글에서 잘린 host 도 버린다.
34const isNoise = (url: URL) =>
35  url.host.startsWith('api.')
36  || /\.(slack|atlassian|notion|github)$/.test(url.hostname)
37  || url.host === 'localhost'
38  || (url.host === 'claude.com' && url.pathname.startsWith('/claude-code'))
39  || (url.host === 'code.claude.com' && url.pathname.length <= 1)
40  || (url.host === 'claude.ai' && url.pathname.startsWith('/code/session_'))
41
42const PROTECTED_BRANCHES = new Set(['main', 'master', 'HEAD', 'develop'])
43
44export const isWorkBranch = (name: string | undefined): name is string =>
45  !!name && !name.startsWith('-') && !PROTECTED_BRANCHES.has(name)
46
47const decode = (part: string) => {
48  try {
49    return decodeURIComponent(part.replace(/\+/g, ' '))
50  } catch {
51    return part
52  }
53}
54
55// notion.so/<workspace>/<Title-Words>-<32 hex id> 에서 제목 부분만 남긴다.
56const notionTitle = (path: string) => {
57  const last = decode(path.split('/').filter(Boolean).pop() ?? '')
58  const title = last.replace(/-?[0-9a-f]{32}$/i, '').replace(/-/g, ' ').trim()
59  return title || 'Notion page'
60}
61
62export const extractUrls = (text: string): string[] =>
63  (text.match(URL_RE) ?? []).map(raw => raw.replace(TRAILING_RE, ''))
64
65// URL 하나를 산출물로 분류한다. 잡음이거나 URL 이 아니면 undefined.
66export function classifyUrl(raw: string): Link | undefined {
67  let url: URL
68  try {
69    url = new URL(raw)
70  } catch {
71    return undefined
72  }
73  if (!/\.[a-z]{2,}$/i.test(url.hostname) || raw.includes('$') || isNoise(url)) return undefined
74
75  const host = url.hostname.toLowerCase()
76  const parts = url.pathname.split('/').filter(Boolean)
77
78  if (host === 'github.com' && parts.length >= 2) {
79    const [owner, repo, section, ...rest] = parts
80    const base = `https://github.com/${owner}/${repo}`
81    if (section === 'pull' && rest[0] === 'new' && rest.length > 1) {
82      const branch = decode(rest.slice(1).join('/'))
83      return { kind: 'branch', label: branch, href: `${base}/tree/${rest.slice(1).join('/')}` }
84    }
85    if (section === 'pull' && /^\d+$/.test(rest[0] ?? '')) {
86      return { kind: 'pr', label: `${owner}/${repo}#${rest[0]}`, href: `${base}/pull/${rest[0]}` }
87    }
88    return { kind: 'github', label: parts.join('/'), href: `https://github.com/${parts.join('/')}` }
89  }
90
91  if (host.endsWith('.atlassian.net')) {
92    const key = url.pathname.match(/\/browse\/([A-Z][A-Z0-9_]+-\d+)/)?.[1]
93      ?? url.searchParams.get('selectedIssue') ?? undefined
94    if (key) return { kind: 'jira', label: key, href: `https://${host}/browse/${key}` }
95    if (parts[0] === 'wiki') {
96      const title = decode(parts[parts.length - 1] ?? '')
97      return { kind: 'confluence', label: /^\d+$/.test(title) ? `page ${title}` : title, href: raw }
98    }
99  }
100
101  if (host === 'notion.so' || host.endsWith('.notion.so') || host.endsWith('.notion.site') || host === 'app.notion.com') {
102    return { kind: 'notion', label: notionTitle(url.pathname), href: raw }
103  }
104
105  if (host.endsWith('.slack.com') && parts[0] === 'archives' && parts[1]) {
106    const ts = parts[2]?.match(/^p(\d{10})(\d*)$/)
107    const at = ts ? ` · ${shortTime(Number(ts[1]) * 1000)}` : ''
108    return { kind: 'slack', label: `${host.split('.')[0]} ${parts[1]}${at}`, href: raw }
109  }
110
111  return { kind: 'web', label: `${host}${url.pathname === '/' ? '' : url.pathname}`, href: raw }
112}
113
114// Bash 명령에서 새로 만들거나 push 한 branch 이름을 찾는다.
115const BRANCH_RES = [
116  /git\s+(?:-C\s+\S+\s+)?(?:checkout|switch)\s+(?:[^\n;&|]*?\s)?-[bBcC]\s+([^\s;&|]+)/g,
117  /git\s+(?:-C\s+\S+\s+)?worktree\s+add\s+[^\n;&|]*?-[bB]\s+([^\s;&|]+)/g,
118  /git\s+(?:-C\s+\S+\s+)?push\s+[^\n;&|]*?(?:-u|--set-upstream)\s+[^\s;&|-]\S*\s+([^\s;&|:]+)/g,
119]
120
121export function branchesFromCommand(command: string): string[] {
122  const found: string[] = []
123  for (const re of BRANCH_RES) {
124    for (const match of command.matchAll(re)) {
125      const name = match[1]?.replace(/^['"]|['"]$/g, '')
126      if (isWorkBranch(name)) found.push(name)
127    }
128  }
129  return found
130}
131
132// Bash 가 쓴 파일 중 경로가 실행 결과에 달린 것은 register 가 파일 시스템을 보고 path 를 확정한다.
133export type ParsedArtifact = Artifact & {
134  // 파일 이름에 실행해야 아는 값이 든 경우의 이름 정규식(cp f "f.bak.$(date +%s)")과 명령을 보낸 시각
135  namePattern?: string
136  writtenAt?: number
137  // cp·mv 의 대상이 폴더라면 그 안에 생기는 파일 이름
138  intoDirName?: string
139}
140
141export type ParsedTranscript = {
142  // 사용자가 붙인 제목(/rename). 없으면 aiTitle, 그것도 없으면 firstPrompt 를 쓴다.
143  title?: string
144  aiTitle?: string
145  firstPrompt?: string
146  startedAt?: number
147  endedAt?: number
148  cwd?: string
149  // 링크·branch·file 을 처음 수집된 순서대로. 같은 항목이 다시 나와도 처음 출처를 유지한다.
150  // file 의 path 는 절대 경로이고, displayPath·href·isGone 은 register 가 채운다.
151  artifacts: ParsedArtifact[]
152}
153
154type Block = {
155  type?: string
156  text?: string
157  id?: string
158  name?: string
159  input?: Record<string, unknown>
160  tool_use_id?: string
161  content?: unknown
162}
163
164const REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g
165// 붙여넣은 텍스트는 <pasted_content id="..."> 로 감싸여 저장된다. 태그만 걷고 내용은 남긴다.
166const PASTED_TAG_RE = /<\/?pasted_content\b[^>]*>/g
167
168const resultText = (content: unknown): string => {
169  if (typeof content === 'string') return content
170  if (!Array.isArray(content)) return ''
171  return content.map(one => (typeof one?.text === 'string' ? one.text : '')).join('\n')
172}
173
174// PR·branch URL 을 남기는 명령. 다른 Bash 명령(grep, cat, 스크립트)의 입출력에 든 URL 은 잡음이다.
175const GIT_COMMAND_RE = /(^|[\s;&|(])(gh|git)\s/
176// 출력에 새로 만든 것의 URL 을 찍는 git·gh 명령. gh pr view·gh api·git log 같은 조회 명령의 출력은
177// PR 본문·커밋 메시지에 든 참고 링크라 보지 않는다.
178const CREATING_COMMAND_RE =
179  /(^|[\s;&|(])(gh\s+(pr|issue|release)\s+create|git\s+(-C\s+\S+\s+)?push)(\s|$)/
180// git·gh 명령의 입출력에서는 GitHub 링크만 남긴다. PR 본문(--body)이나 출력에 든 Jira·Notion 링크는 참고 자료다.
181const GIT_KINDS = new Set<ArtifactKind>(['pr', 'branch', 'github'])
182
183// 세션 transcript(JSONL) 한 파일에서 제목·기간·링크·파일·branch 를 모은다.
184// 링크는 사용자·assistant 의 글, Bash 가 아닌 도구 입력, git·gh 명령의 입력과 산출물을 만드는 명령의 출력에서만 찾는다.
185// 다른 도구 결과(Read, WebFetch, MCP)는 잡음이 많아 보지 않는다.
186// 파일은 Write·Edit 의 경로와 Bash 명령이 쓰는 경로(redirect, sed -i, cp, mv, tee 등)다. ~ 는 home 으로 펼친다.
187// transcript 의 gitBranch 는 그때 checkout 된 branch 일 뿐이라, 다른 산출물이 있는 세션에서만 남긴다.
188export function parseTranscript(text: string, home?: string): ParsedTranscript {
189  const parsed: ParsedTranscript = { artifacts: [] }
190  // 링크는 href, branch 는 이름, file 은 경로로 같은 항목을 가린다.
191  const seen = new Map<string, ParsedArtifact>()
192  const creatingToolIds = new Set<string>()
193  const checkedOut: string[] = []
194
195  const add = (key: string, artifact: ParsedArtifact) => {
196    const known = seen.get(key)
197    if (known) {
198      // git push 로 URL 이 나중에 생긴 branch 는 처음 출처를 둔 채 URL 만 채운다.
199      known.href ??= artifact.href
200      return
201    }
202    seen.set(key, artifact)
203    parsed.artifacts.push(artifact)
204  }
205  const addUrls = (text: string, source: ArtifactSource, kinds?: Set<ArtifactKind>) => {
206    for (const raw of extractUrls(text)) {
207      const link = classifyUrl(raw)
208      if (!link || (kinds && !kinds.has(link.kind))) continue
209      if (link.kind === 'branch') addBranch(link.label, source, link.href)
210      else add(`link:${link.href ?? link.label}`, { ...link, source })
211    }
212  }
213  const addBranch = (name: string | undefined, source: ArtifactSource, href?: string) => {
214    if (isWorkBranch(name)) add(`branch:${name}`, { kind: 'branch', label: name, href, source })
215  }
216  const addFile = (path: unknown, extra?: Partial<ParsedArtifact>) => {
217    if (typeof path !== 'string' || path === '') return
218    // 이름을 아직 모르는 파일은 명령마다 다른 파일이다(같은 명령으로 두 번 백업).
219    const key = extra?.namePattern ? `file:${path}@${extra.writtenAt}` : `file:${path}`
220    add(key, { kind: 'file', label: path.split('/').pop() || path, path, source: 'output', ...extra })
221  }
222
223  for (const line of text.split('\n')) {
224    if (line.includes('"custom-title"') || line.includes('"ai-title"')) {
225      try {
226        const record = JSON.parse(line)
227        const custom = record.type === 'custom-title' ? record.customTitle : undefined
228        const ai = record.type === 'ai-title' ? record.aiTitle : undefined
229        if (typeof custom === 'string' && custom.trim()) parsed.title = custom.trim()
230        if (typeof ai === 'string' && ai.trim()) parsed.aiTitle = ai.trim()
231      } catch {}
232      continue
233    }
234    if (!line.includes('"type":"user"') && !line.includes('"type":"assistant"')) continue
235
236    let record: {
237      type?: string
238      isMeta?: boolean
239      timestamp?: string
240      cwd?: string
241      gitBranch?: string
242      message?: { content?: unknown }
243    }
244    try {
245      record = JSON.parse(line)
246    } catch {
247      continue
248    }
249    if (record.type !== 'user' && record.type !== 'assistant') continue
250
251    const at = record.timestamp ? Date.parse(record.timestamp) : NaN
252    if (!Number.isNaN(at)) {
253      parsed.startedAt ??= at
254      parsed.endedAt = at
255    }
256    if (record.cwd) parsed.cwd = record.cwd
257    if (isWorkBranch(record.gitBranch) && !checkedOut.includes(record.gitBranch)) checkedOut.push(record.gitBranch)
258    if (record.isMeta) continue
259
260    const content = record.message?.content
261    const blocks: Block[] = typeof content === 'string'
262      ? [{ type: 'text', text: content }]
263      : Array.isArray(content) ? content : []
264
265    for (const block of blocks) {
266      if (block.type === 'text' && typeof block.text === 'string') {
267        const body = block.text.replace(REMINDER_RE, '').replace(PASTED_TAG_RE, '').trim()
268        if (record.type === 'user' && parsed.firstPrompt === undefined && body && !body.startsWith('<')) {
269          parsed.firstPrompt = body.split('\n')[0]!.trim()
270        }
271        addUrls(body, record.type === 'user' ? 'input' : 'output')
272      } else if (block.type === 'tool_use' && block.name) {
273        const input = block.input ?? {}
274        const pathKey = FILE_TOOLS[block.name]
275        if (pathKey) {
276          addFile(input[pathKey])
277          continue
278        }
279        if (block.name === 'Bash') {
280          const command = typeof input.command === 'string' ? input.command : ''
281          for (const { path, ...extra } of writtenFiles(command, { cwd: record.cwd, home })) {
282            addFile(path, extra.namePattern ? { ...extra, writtenAt: Number.isNaN(at) ? undefined : at } : extra)
283          }
284          if (!GIT_COMMAND_RE.test(command)) continue
285          if (block.id && CREATING_COMMAND_RE.test(command)) creatingToolIds.add(block.id)
286          for (const name of branchesFromCommand(command)) addBranch(name, 'output')
287          addUrls(command, 'output', GIT_KINDS)
288          continue
289        }
290        addUrls(JSON.stringify(input), 'output')
291      } else if (block.type === 'tool_result' && creatingToolIds.has(block.tool_use_id ?? '')) {
292        addUrls(resultText(block.content), 'output', GIT_KINDS)
293      }
294    }
295  }
296
297  if (parsed.artifacts.length > 0) {
298    for (const name of checkedOut) addBranch(name, 'output')
299  }
300  return parsed
301}
302
303const pad2 = (n: number) => String(n).padStart(2, '0')
304
305// 10/15 01:02
306export const shortTime = (ms: number) => {
307  const d = new Date(ms)
308  return `${pad2(d.getMonth() + 1)}/${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
309}
310
311export const clockTime = (ms: number) => {
312  const d = new Date(ms)
313  return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
314}
315
316// 같은 날이면 끝 시각만, 다르면 둘 다.
317export const spanOf = (startedAt?: number, endedAt?: number) => {
318  if (startedAt === undefined) return ''
319  const start = shortTime(startedAt)
320  if (endedAt === undefined || endedAt - startedAt < 60_000) return start
321  const end = shortTime(endedAt)
322  return start.slice(0, 5) === end.slice(0, 5) ? `${start}–${end.slice(6)}` : `${start} – ${end}`
323}
324
325// Claude Code 는 프로젝트별 폴더 이름을 경로의 영숫자 아닌 글자를 '-' 로 바꿔 만든다.
326export const slugOf = (path: string) => path.replace(/[^a-zA-Z0-9]/g, '-')
327
328// git worktree list --porcelain 의 worktree 경로들
329export const parseWorktrees = (stdout: string): string[] =>
330  stdout.split('\n').filter(line => line.startsWith('worktree ')).map(line => line.slice('worktree '.length).trim())
331
332// displayPath 결과에서 파일 이름을 뺀 폴더 부분. worktree root 의 파일은 '.', 다른 worktree 의 root 는 'x:' 이다.
333export function dirOf(path: string): string {
334  const slash = path.lastIndexOf('/')
335  if (slash >= 0) return path.slice(0, slash) || '/'
336  const colon = path.indexOf(':')
337  return colon >= 0 ? path.slice(0, colon + 1) : '.'
338}
339
340// 경로를 가장 긴 worktree 기준 상대 경로로 줄인다. 다른 worktree 면 그 폴더 이름을 앞에 붙이되,
341// '<main 폴더>-' 로 시작하면 그 부분은 뺀다 (repo-feature → feature:).
342export function displayPath(path: string, roots: string[], home?: string): string {
343  const root = [...roots].sort((a, b) => b.length - a.length).find(one => path.startsWith(`${one}/`))
344  if (root) {
345    const relative = path.slice(root.length + 1)
346    if (root === roots[0]) return relative
347    const main = roots[0]?.split('/').pop() ?? ''
348    const name = root.split('/').pop() ?? root
349    return `${main && name.startsWith(`${main}-`) ? name.slice(main.length + 1) : name}:${relative}`
350  }
351  return home && path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path
352}
353
hooks/shell.ts 398 lines
1// Bash 명령 한 줄이 쓰는 파일 경로를 찾는다. 셸을 실행하지 않고 글자만 읽으므로, 같은 명령 안에서
2// 정한 변수(f=...; cat >> "$f")와 cd 는 따라가고, $(...)·`...` 처럼 실행해야 아는 값은 모르는 값으로 둔다.
3
4// 실행해야 아는 값($(date), 정의하지 않은 $VAR)이 들어간 자리
5const UNKNOWN = '\u0000'
6
7export type WrittenFile = {
8  // 절대 경로. namePattern 이 있으면 이 경로의 파일 이름 부분은 자리표시자다.
9  path: string
10  // 파일 이름에 실행해야 아는 값이 들어 있을 때 그 이름의 정규식(cp f "f.bak.$(date +%s)")
11  namePattern?: string
12  // cp·mv 의 대상이 폴더일 수도 있을 때, 폴더라면 그 안에 생기는 파일 이름
13  intoDirName?: string
14}
15
16type Part = { text: string; quote: '' | "'" | '"' } | { sub: true }
17type Word = Part[]
18type Token = { op: string } | { redirect: string } | { word: Word }
19
20const isWord = (token: Token | undefined): token is { word: Word } => !!token && 'word' in token
21
22const literalOf = (word: Word) => word.map(part => ('text' in part ? part.text : '')).join('')
23
24// i 의 '(' 와 짝인 ')' 다음 위치. 안의 따옴표는 건너뛴다.
25function closingParen(src: string, i: number): number {
26  let depth = 0
27  for (; i < src.length; i++) {
28    const c = src[i]
29    if (c === '\\') i++
30    else if (c === "'" || c === '"') {
31      const end = src.indexOf(c, i + 1)
32      i = end < 0 ? src.length : end
33    } else if (c === '(') depth++
34    else if (c === ')' && --depth === 0) return i + 1
35  }
36  return src.length
37}
38
39// 명령을 단어·연산자·redirect 로 나눈다. heredoc 본문은 버린다.
40function lex(src: string): Token[] {
41  const tokens: Token[] = []
42  const heredocs: { delimiter: string; isIndented: boolean }[] = []
43  let word: Word | undefined
44  let text = ''
45
46  const flushText = () => {
47    if (text) (word ??= []).push({ text, quote: '' })
48    text = ''
49  }
50  const endWord = () => {
51    flushText()
52    if (!word) return
53    const before = tokens[tokens.length - 1]
54    if (before && 'redirect' in before && before.redirect.startsWith('<<') && before.redirect !== '<<<') {
55      heredocs.push({ delimiter: literalOf(word), isIndented: before.redirect === '<<-' })
56    }
57    tokens.push({ word })
58    word = undefined
59  }
60  const op = (value: string) => {
61    endWord()
62    tokens.push({ op: value })
63  }
64
65  let i = 0
66  while (i < src.length) {
67    const c = src[i]!
68    const two = src.slice(i, i + 2)
69    if (c === '\n') {
70      op(';')
71      i++
72      // 줄바꿈 다음은 heredoc 본문이다. 구분자만 있는 줄까지 건너뛴다.
73      for (const doc of heredocs.splice(0)) {
74        while (i < src.length) {
75          const end = src.indexOf('\n', i)
76          const line = src.slice(i, end < 0 ? src.length : end)
77          i = end < 0 ? src.length : end + 1
78          if ((doc.isIndented ? line.replace(/^\t+/, '') : line) === doc.delimiter) break
79        }
80      }
81    } else if (c === ' ' || c === '\t') {
82      endWord()
83      i++
84    } else if (c === '#' && !word && !text) {
85      while (i < src.length && src[i] !== '\n') i++
86    } else if (c === ';' || c === '(' || c === ')') {
87      op(';')
88      i++
89    } else if (two === '&&' || two === '||' || two === '|&') {
90      op(two)
91      i += 2
92    } else if (two === '&>') {
93      endWord()
94      const value = src.slice(i, i + 3) === '&>>' ? '&>>' : '&>'
95      tokens.push({ redirect: value })
96      i += value.length
97    } else if (c === '&' || c === '|') {
98      op(c)
99      i++
100    } else if (c === '>' || c === '<') {
101      // 2>err.log 의 2 는 fd 번호라 단어가 아니다.
102      if (!word && /^\d+$/.test(text)) text = ''
103      endWord()
104      const value = src.slice(i).match(/^(>>|>\||>&|<<<|<<-|<<|<&|<>|>|<)/)![1]!
105      tokens.push({ redirect: value })
106      i += value.length
107    } else if (c === "'") {
108      flushText()
109      const end = src.indexOf("'", i + 1)
110      ;(word ??= []).push({ text: src.slice(i + 1, end < 0 ? src.length : end), quote: "'" })
111      i = end < 0 ? src.length : end + 1
112    } else if (c === '"') {
113      flushText()
114      word ??= []
115      let inner = ''
116      i++
117      while (i < src.length && src[i] !== '"') {
118        if (src[i] === '\\' && i + 1 < src.length) {
119          inner += /[$`"\\\n]/.test(src[i + 1]!) ? src[i + 1] : src.slice(i, i + 2)
120          i += 2
121        } else if (src.startsWith('$(', i) || src[i] === '`') {
122          if (inner) word.push({ text: inner, quote: '"' })
123          inner = ''
124          word.push({ sub: true })
125          i = src[i] === '`' ? src.indexOf('`', i + 1) + 1 || src.length : closingParen(src, i + 1)
126        } else {
127          inner += src[i++]
128        }
129      }
130      if (inner || word.length === 0) word.push({ text: inner, quote: '"' })
131      i++
132    } else if (c === '\\') {
133      flushText()
134      if (src[i + 1] !== '\n') (word ??= []).push({ text: src[i + 1] ?? '', quote: "'" })
135      i += 2
136    } else if (two === '$(' || c === '`') {
137      flushText()
138      ;(word ??= []).push({ sub: true })
139      i = c === '`' ? src.indexOf('`', i + 1) + 1 || src.length : closingParen(src, i + 1)
140    } else {
141      text += c
142      i++
143    }
144  }
145  endWord()
146  return tokens
147}
148
149type Scope = { cwd?: string; home?: string; vars: Map<string, string> }
150
151// 단어를 셸처럼 펼친다. 따옴표 없는 *?[ 가 있으면 glob 이라 경로로 쓰지 않는다.
152function expand(word: Word, scope: Scope): { value: string; isGlob: boolean } {
153  let value = ''
154  let isGlob = false
155  word.forEach((part, at) => {
156    if (!('text' in part)) {
157      value += UNKNOWN
158      return
159    }
160    if (part.quote === "'") {
161      value += part.text
162      return
163    }
164    let text = part.text
165    // ~ 는 단어 맨 앞과 대입의 = 바로 뒤(f=~/x)에서 펼친다.
166    if (part.quote === '' && at === 0 && scope.home) text = text.replace(/^((?:[A-Za-z_]\w*=)?)~(?=\/|$)/, `$1${scope.home}`)
167    if (part.quote === '' && /[*?[]/.test(text)) isGlob = true
168    value += text.replace(/\$(?:\{(\w+)\}|(\w+))/g, (_, braced: string, bare: string) => {
169      const name = braced ?? bare
170      return scope.vars.get(name) ?? (name === 'HOME' && scope.home ? scope.home : UNKNOWN)
171    })
172  })
173  return { value, isGlob }
174}
175
176// . 과 .. 을 걷어낸 절대 경로. 상대 경로인데 cwd 를 모르면 undefined.
177function absolute(path: string, cwd: string | undefined): string | undefined {
178  if (!path.startsWith('/') && !cwd) return undefined
179  const segments: string[] = []
180  for (const one of (path.startsWith('/') ? path : `${cwd}/${path}`).split('/')) {
181    if (one === '..') segments.pop()
182    else if (one && one !== '.') segments.push(one)
183  }
184  return `/${segments.join('/')}`
185}
186
187const escapeRe = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
188
189const baseName = (path: string) => path.replace(/\/+$/, '').split('/').pop() ?? ''
190
191// 펼친 값 하나를 쓴 파일로 만든다. 폴더 부분을 모르거나 glob·장치 파일이면 버린다.
192function fileOf(value: string, isGlob: boolean, scope: Scope): WrittenFile | undefined {
193  if (!value || value === '-' || isGlob) return undefined
194  const path = absolute(value, scope.cwd)
195  if (!path || path === '/' || path.startsWith('/dev/') || path.startsWith('/proc/')) return undefined
196  const name = baseName(path)
197  if (path.slice(0, path.length - name.length).includes(UNKNOWN)) return undefined
198  if (!name.includes(UNKNOWN)) return { path }
199  if (name.replaceAll(UNKNOWN, '') === '') return undefined
200  return {
201    path: path.replaceAll(UNKNOWN, '*'),
202    namePattern: `^${name.split(UNKNOWN).map(escapeRe).join('.+')}$`,
203  }
204}
205
206// 옵션을 걷어낸 인자. withValue 의 옵션은 다음 인자를 값으로 가져간다.
207function positionals(args: string[], withValue: string[] = []): { values: string[]; options: Map<string, string> } {
208  const values: string[] = []
209  const options = new Map<string, string>()
210  for (let i = 0; i < args.length; i++) {
211    const arg = args[i]!
212    if (arg === '--') {
213      values.push(...args.slice(i + 1))
214      break
215    }
216    if (arg.startsWith('-') && arg.length > 1) {
217      const [name, inline] = arg.startsWith('--') ? arg.split(/=(.*)/s) : [arg]
218      if (inline !== undefined) options.set(name!, inline)
219      else if (withValue.includes(arg)) options.set(arg, args[++i] ?? '')
220      else options.set(arg, '')
221      continue
222    }
223    values.push(arg)
224  }
225  return { values, options }
226}
227
228// sed -i, perl -i 가 고치는 파일. -e·-f 가 없으면 첫 인자가 script 다.
229function inPlaceTargets(name: 'sed' | 'perl', args: string[]): string[] {
230  let isInPlace = false
231  let hasScript = false
232  const values: string[] = []
233  for (let i = 0; i < args.length; i++) {
234    const arg = args[i]!
235    if (arg === '--') {
236      values.push(...args.slice(i + 1))
237      break
238    }
239    if (arg.startsWith('--')) {
240      if (arg.startsWith('--in-place')) isInPlace = true
241      if (/^--(expression|file)=/.test(arg)) hasScript = true
242      else if (arg === '--expression' || arg === '--file') {
243        hasScript = true
244        i++
245      }
246      continue
247    }
248    if (!arg.startsWith('-') || arg.length === 1) {
249      values.push(arg)
250      continue
251    }
252    const flags = arg.slice(1)
253    for (let j = 0; j < flags.length; j++) {
254      const flag = flags[j]!
255      const isLast = j === flags.length - 1
256      if (flag === 'i') {
257        isInPlace = true
258        // BSD sed 는 -i 다음 인자가 백업 확장자다(-i '' 또는 -i .bak).
259        if (name === 'sed' && isLast && /^(\.[^\s/]*)?$/.test(args[i + 1] ?? '-')) i++
260        break
261      }
262      if (flag === 'e' || flag === 'f' || (name === 'perl' && flag === 'E')) {
263        hasScript = true
264        if (isLast) i++
265        break
266      }
267      if (name === 'perl' && /[MmIlx0]/.test(flag)) break
268    }
269  }
270  if (!isInPlace) return []
271  return hasScript ? values : values.slice(1)
272}
273
274const SHELLS = new Set(['sh', 'bash', 'zsh'])
275const WRAPPERS = new Set(['sudo', 'command', 'nohup', 'time', 'exec', 'builtin'])
276const DECLARES = new Set(['export', 'local', 'declare', 'typeset', 'readonly'])
277const ASSIGN_RE = /^([A-Za-z_]\w*)=/s
278
279// 'f=x' 처럼 이름이 따옴표 밖에 있어야 대입이다. "f=x" 는 명령 이름이다.
280const isAssignment = ({ value, raw }: { value: string; raw: Word }) => {
281  const first = raw[0]
282  return ASSIGN_RE.test(value) && !!first && 'text' in first && first.quote === ''
283}
284
285// 단순 명령 하나(argv)가 쓰는 파일을 모으고, 변수 대입과 cd 는 scope 에 반영한다.
286function runSimple(words: { value: string; isGlob: boolean; raw: Word }[], scope: Scope, out: WrittenFile[]) {
287  let at = 0
288  // FOO=1 cmd 의 FOO 는 그 명령에만 쓰인다. 명령 없이 대입만 있으면 이후 명령에 남는다.
289  const assigns: [string, string][] = []
290  while (at < words.length && isAssignment(words[at]!)) {
291    const [, name] = words[at]!.value.match(ASSIGN_RE)!
292    assigns.push([name!, words[at]!.value.slice(name!.length + 1)])
293    at++
294  }
295  if (at === words.length) {
296    for (const [name, value] of assigns) scope.vars.set(name, value)
297    return
298  }
299  while (at < words.length && WRAPPERS.has(baseName(words[at]!.value))) at++
300  if (words[at]?.value === 'env') {
301    at++
302    while (at < words.length && (ASSIGN_RE.test(words[at]!.value) || words[at]!.value.startsWith('-'))) at++
303  }
304
305  const name = baseName(words[at]?.value ?? '')
306  const rest = words.slice(at + 1)
307  const args = rest.map(one => one.value)
308  const add = (value: string, extra?: Partial<WrittenFile>) => {
309    const word = rest.find(one => one.value === value)
310    const file = fileOf(value, word?.isGlob ?? false, scope)
311    if (file) out.push(file.namePattern ? file : { ...file, ...extra })
312  }
313
314  if (DECLARES.has(name)) {
315    for (const value of args) {
316      const match = value.match(ASSIGN_RE)
317      if (match) scope.vars.set(match[1]!, value.slice(match[1]!.length + 1))
318    }
319  } else if (name === 'cd' || name === 'pushd') {
320    const target = positionals(args).values[0]
321    if (target === '-') return
322    const next = target === undefined ? scope.home : target.includes(UNKNOWN) ? undefined : absolute(target, scope.cwd)
323    scope.cwd = next
324  } else if (name === 'sed' || name === 'gsed' || name === 'perl') {
325    for (const value of inPlaceTargets(name === 'perl' ? 'perl' : 'sed', args)) add(value)
326  } else if (name === 'cp' || name === 'mv' || name === 'install') {
327    const { values, options } = positionals(args, ['-t', '-m', '-o', '-g', '-S', '--target-directory', '--suffix', '--mode', '--owner', '--group'])
328    if (name === 'install' && options.has('-d')) return
329    const into = options.get('-t') ?? options.get('--target-directory')
330    const sources = into === undefined ? values.slice(0, -1) : values
331    const dir = into ?? values[values.length - 1]
332    if (dir === undefined || sources.length === 0) return
333    if (into === undefined && sources.length === 1 && !dir.endsWith('/')) {
334      const fromName = baseName(sources[0]!)
335      add(dir, fromName && !fromName.includes(UNKNOWN) ? { intoDirName: fromName } : undefined)
336      return
337    }
338    for (const source of sources) {
339      const fromName = baseName(source)
340      const file = fromName && !fromName.includes(UNKNOWN) && fileOf(`${dir.replace(/\/+$/, '')}/${fromName}`, false, scope)
341      if (file) out.push(file)
342    }
343  } else if (name === 'tee') {
344    for (const value of positionals(args).values) add(value)
345  } else if (name === 'touch') {
346    for (const value of positionals(args, ['-t', '-r', '-d']).values) add(value)
347  } else if (name === 'curl') {
348    args.forEach((arg, i) => {
349      if (arg === '--output' || /^-[A-Za-z]*o$/.test(arg)) add(args[i + 1] ?? '')
350      else if (arg.startsWith('--output=')) add(arg.slice('--output='.length))
351      else if (/^-o./.test(arg)) add(arg.slice(2))
352    })
353  } else if (name === 'dd') {
354    for (const arg of args) if (arg.startsWith('of=')) add(arg.slice(3))
355  } else if (SHELLS.has(name)) {
356    const script = args[args.indexOf('-c') + 1]
357    if (args.includes('-c') && script !== undefined && !script.includes(UNKNOWN)) {
358      out.push(...writtenFiles(script, { cwd: scope.cwd, home: scope.home, vars: new Map(scope.vars) }))
359    }
360  }
361}
362
363const WRITE_REDIRECTS = new Set(['>', '>>', '>|', '&>', '&>>', '<>'])
364
365// command 를 cwd 에서 실행했을 때 만들거나 고치는 파일들. 명령에 나온 순서대로, 겹쳐도 그대로 둔다.
366export function writtenFiles(
367  command: string,
368  { cwd, home, vars = new Map() }: { cwd?: string; home?: string; vars?: Map<string, string> },
369): WrittenFile[] {
370  const scope: Scope = { cwd, home, vars }
371  const out: WrittenFile[] = []
372  const tokens = lex(command)
373  let words: { value: string; isGlob: boolean; raw: Word }[] = []
374  for (let i = 0; i <= tokens.length; i++) {
375    const token = tokens[i]
376    if (!token || 'op' in token) {
377      runSimple(words, scope, out)
378      words = []
379      continue
380    }
381    if ('redirect' in token) {
382      const target = tokens[i + 1]
383      if (!isWord(target)) continue
384      i++
385      // >&2, >&- 는 fd 를 잇는 것이다.
386      const isFd = token.redirect === '>&' && /^(\d+|-)$/.test(literalOf(target.word))
387      if (!isFd && (WRITE_REDIRECTS.has(token.redirect) || token.redirect === '>&')) {
388        const { value, isGlob } = expand(target.word, scope)
389        const file = fileOf(value, isGlob, scope)
390        if (file) out.push(file)
391      }
392      continue
393    }
394    words.push({ ...expand(token.word, scope), raw: token.word })
395  }
396  return out
397}
398
types/index.d.ts 45 lines
1// file 은 Write/Edit 나 Bash 명령(redirect, sed -i, cp, mv, tee 등)으로 만들거나 고친 파일, scratch 는 세션 scratchpad 의 파일.
2export type ArtifactKind =
3  | 'pr' | 'branch' | 'jira' | 'notion' | 'confluence' | 'slack' | 'github' | 'web' | 'file' | 'scratch'
4
5// 처음 수집된 곳. input 은 사용자 메시지의 글, output 은 그 밖의 전부(assistant 의 글, 도구 입력,
6// git·gh 명령의 입출력, checkout 된 branch, scratchpad 파일). pane 은 이 값으로 그룹을 나눈다.
7export type ArtifactSource = 'input' | 'output'
8
9export type Artifact = {
10  kind: ArtifactKind
11  // 행의 name 칸. file·scratch 는 파일 이름(basename)이다.
12  label: string
13  href?: string
14  // file·scratch 의 절대 경로. p 로 복사하는 값이다.
15  path?: string
16  // file·scratch 의 worktree 기준 상대 경로 등. 행의 path 칸에는 이 경로의 폴더 부분이 보인다.
17  displayPath?: string
18  source: ArtifactSource
19  // file 이 지금은 지워졌으면 true. 링크는 확인하지 않는다.
20  isGone?: boolean
21}
22
23export type SessionArtifacts = {
24  id: string
25  title: string
26  // 세션이 작업한 worktree 경로(마지막 cwd)
27  cwd?: string
28  startedAt?: number
29  endedAt?: number
30  artifacts: Artifact[]
31}
32
33// 현재 세션의 산출물. 아직 읽지 않았으면 loadedAt 이 없다.
34export type ArtifactIndex = {
35  session?: SessionArtifacts
36  loadedAt?: number
37  error?: string
38}
39
40declare module 'claude-code' {
41  interface PluginState {
42    'session-outputs': { index: ArtifactIndex; selected: number }
43  }
44}
45