@leftoff/cli 0.8.7 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leftoff",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "Leftoff (formerly Checkpoints): WTF was I working on? Tracks every Claude Code session on this machine, writes a 3-line checkpoint when one goes quiet, and adds /cp (checkpoint now), /cp-name and a /leftoff pane. Talks to the local Leftoff daemon on 127.0.0.1:7429 and falls back to writing markdown in ~/checkpoints.",
5
5
  "author": {
6
6
  "name": "Joel"
package/mod/hooks/core.js CHANGED
@@ -298,7 +298,8 @@ const CP_ORDER = ['id', 'session_id', 'session_title', 'created_at', 'trigger',
298
298
  export function resumeCommand(session) {
299
299
  const id = session.id || session.sessionId
300
300
  const cwd = resumeDir(session)
301
- return (cwd ? 'cd ' + shArg(cwd) + ' && ' : '') + (isCodex(session) ? codexInvocation(id) : claudeInvocation(session, ['--resume', id]))
301
+ const wt = resumeWorktreeName(session)
302
+ return (cwd ? 'cd ' + shArg(cwd) + ' && ' : '') + (isCodex(session) ? codexInvocation(id) : claudeInvocation(session, [...(wt ? ['--worktree', wt] : []), '--resume', id]))
302
303
  }
303
304
 
304
305
  // 0.8.0: a Codex session (its rollout under ~/.codex/sessions) resumes with `codex resume <id>`.
@@ -308,9 +309,24 @@ export function codexInvocation(id) { return 'codex resume ' + shArg(id) }
308
309
  // 0.7.1: where to run `claude --resume`: the session's folder, or, inside a git
309
310
  // worktree, that worktree's own top folder (Claude Code declines to re-enter a
310
311
  // `git worktree add` worktree from one of its subfolders; code.claude.com/docs/en/worktrees).
312
+ //
313
+ // 0.8.8: a worktree Claude Code made (<repo>/.claude/worktrees/<name>, from
314
+ // `claude --worktree` or EnterWorktree) is resumed the way Claude Code itself
315
+ // prints on exit: from the main checkout, `claude --worktree <name> --resume <id>`.
316
+ // On exit Claude Code moves the session back to where it was launched and
317
+ // clears its worktree binding, so --worktree is what puts it back in there.
318
+ // Not when the worktree is gone (folderGone): --worktree would make a new one.
319
+ export function resumeWorktreeName(session) {
320
+ const wt = session && session.repo && session.repo.worktree
321
+ const root = session && session.repo && session.repo.root
322
+ if (!wt || !root || typeof wt !== 'string' || session.folderGone || isCodex(session)) return null
323
+ const c = claudeWorktreeOf(wt)
324
+ return c && trimSlash(c.root) === trimSlash(root) && trimSlash(c.path) === trimSlash(wt) ? c.name : null
325
+ }
311
326
  export function resumeDir(session) {
312
327
  const cwd = session && session.cwd
313
328
  const wt = session && session.repo && session.repo.worktree
329
+ if (resumeWorktreeName(session)) return session.repo.root
314
330
  if (cwd && wt && typeof wt === 'string' && (cwd === wt || String(cwd).startsWith(wt.replace(/\/+$/, '') + '/'))) return wt
315
331
  return cwd || null
316
332
  }
@@ -821,9 +837,14 @@ export function applyEvent(s, ev) {
821
837
  // replayed older events (a Codex rollout read again) don't.
822
838
  if (s.parked && ms(at) > ms(s.parked.at) && unparks(s, ev, d)) delete s.parked
823
839
  switch (ev.type) {
824
- case 'session.parked':
840
+ case 'session.parked': {
841
+ const prevLock = s.parked && s.parked.worktreeLock // parked again: the lock it already holds stays on record
825
842
  s.parked = { at, note: d.note ? clip(String(d.note).replace(/\s+/g, ' ').trim(), 300) || null : null, checkpoint: d.checkpoint ? String(d.checkpoint) : null, by: d.by ? String(d.by) : null }
843
+ // 0.8.8: the worktree /cp-park (or Park) locked, so it can be unlocked later
844
+ if (d.worktreeLock && typeof d.worktreeLock === 'object' && typeof d.worktreeLock.path === 'string' && typeof d.worktreeLock.reason === 'string') s.parked.worktreeLock = { path: d.worktreeLock.path, root: typeof d.worktreeLock.root === 'string' ? d.worktreeLock.root : null, reason: d.worktreeLock.reason }
845
+ else if (prevLock) s.parked.worktreeLock = prevLock
826
846
  break
847
+ }
827
848
  case 'session.unparked':
828
849
  delete s.parked
829
850
  break
@@ -912,6 +933,137 @@ export function parseParkArgs(args) {
912
933
  return { note: note ? clip(note, 300) : null }
913
934
  }
914
935
 
936
+ // ------------------------------------------------------------ parked worktrees (0.8.8)
937
+ // Claude Code removes a session's worktree when the session exits and the
938
+ // worktree has no changes (code.claude.com/docs/en/worktrees, "Clean up
939
+ // worktrees"), and /cp-park exits. So in a linked git worktree, park first
940
+ // locks it (`git worktree lock --reason …`). Claude Code's exit cleanup keeps a
941
+ // worktree locked with a reason it didn't write, and its stale-lock sweep only
942
+ // releases its own "claude agent|session … (pid N)" locks, so the reason must
943
+ // never start with "claude ". Resume, Done with it, or the session coming back
944
+ // unlocks it. Only a lock with this exact session's reason is ever unlocked.
945
+ // run(argv) -> { code | exitCode, stdout, stderr }: $.process.run in the mod,
946
+ // execFile in the daemon, a fake in tests. Nothing here deletes anything.
947
+ export const PARK_LOCK_PREFIX = 'leftoff: parked session '
948
+ export function parkLockReason(sessionId) {
949
+ return PARK_LOCK_PREFIX + String(sessionId || '') + ' (resume it, or press Done with it on the board, to unlock)'
950
+ }
951
+ // a lock reason -> the session id Leftoff parked, or null for any other lock
952
+ export function parkLockSession(reason) {
953
+ const m = /^leftoff: parked session ([A-Za-z0-9-]{4,80})(?: |$)/.exec(String(reason == null ? '' : reason))
954
+ return m ? m[1] : null
955
+ }
956
+
957
+ // `git worktree list --porcelain` -> [{ path, branch, bare, detached, locked: null | reason ('' when none given) }]
958
+ export function parseWorktreeList(text) {
959
+ const out = []
960
+ let cur = null
961
+ for (const raw of String(text || '').split('\n')) {
962
+ const line = raw.replace(/\r$/, '')
963
+ if (line.startsWith('worktree ')) { cur = { path: line.slice(9), branch: null, bare: false, detached: false, locked: null }; out.push(cur); continue }
964
+ if (!cur) continue
965
+ if (line.startsWith('branch ')) cur.branch = line.slice(7).replace(/^refs\/heads\//, '')
966
+ else if (line === 'bare') cur.bare = true
967
+ else if (line === 'detached') cur.detached = true
968
+ else if (line === 'locked') cur.locked = ''
969
+ else if (line.startsWith('locked ')) cur.locked = line.slice(7)
970
+ }
971
+ return out
972
+ }
973
+
974
+ const runCode = (r) => (r == null ? null : r.code != null ? r.code : r.exitCode != null ? r.exitCode : null)
975
+ const trimSlash = (p) => String(p || '').replace(/\/+$/, '') || '/'
976
+ const firstLine = (s) => String(s || '').trim().split('\n')[0].slice(0, 200)
977
+ // a path inside Claude Code's own worktrees folder: <repo>/.claude/worktrees/<name>[/…]
978
+ export function claudeWorktreeOf(dir) {
979
+ const m = /^(.*)\/\.claude\/worktrees\/([^/]+)(?:\/.*)?$/.exec(trimSlash(dir))
980
+ return m ? { root: m[1] || '/', name: m[2], path: m[1] + '/.claude/worktrees/' + m[2] } : null
981
+ }
982
+
983
+ // Is dir in a linked git worktree? -> { kind: 'worktree', top, root, gitDir, commonDir }
984
+ // | { kind: 'none' } (not in git, or the main checkout) | { kind: 'unknown', why }
985
+ export async function worktreeAt(run, dir) {
986
+ if (!dir) return { kind: 'unknown', why: 'no folder on record' }
987
+ let r
988
+ try { r = await run(['git', '-C', dir, 'rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir', '--show-toplevel']) } catch (e) { return { kind: 'unknown', why: 'git didn’t run (' + firstLine(e && e.message) + ')' } }
989
+ if (runCode(r) !== 0) {
990
+ if (/not a git repository/i.test(String(r && r.stderr))) return claudeWorktreeOf(dir) ? { kind: 'unknown', why: 'git doesn’t see a repository there' } : { kind: 'none' }
991
+ return { kind: 'unknown', why: 'git: ' + (firstLine(r && r.stderr) || 'exit ' + runCode(r)) }
992
+ }
993
+ const [gitDir, commonDir, top] = String(r.stdout || '').trim().split('\n').map((x) => trimSlash(x.trim()))
994
+ if (!gitDir || !commonDir || !top) return { kind: 'unknown', why: 'git gave no answer' }
995
+ if (gitDir === commonDir) return { kind: 'none' } // the main checkout (or a submodule, its own repo)
996
+ return { kind: 'worktree', top, gitDir, commonDir, root: /\/\.git$/.test(commonDir) ? commonDir.slice(0, -5) || '/' : commonDir }
997
+ }
998
+
999
+ function findEntry(list, path, reason) {
1000
+ const p = trimSlash(path)
1001
+ return list.find((e) => trimSlash(e.path) === p) || (reason ? list.find((e) => e.locked === reason) : null) || null
1002
+ }
1003
+
1004
+ // /cp-park (and Park on the board): lock the worktree dir is in, then read it
1005
+ // back. -> { worktree: null } (not a worktree: nothing to protect)
1006
+ // | { worktree, root, locked: true, reason } (locked and checked)
1007
+ // | { worktree, root?, locked: false, why } (not protected: don't exit for them)
1008
+ export async function lockForPark(run, dir, sessionId) {
1009
+ const w = await worktreeAt(run, dir)
1010
+ if (w.kind === 'none') return { worktree: null }
1011
+ if (w.kind === 'unknown') { const g = claudeWorktreeOf(dir); return { worktree: g ? g.path : null, locked: false, why: w.why, unsure: true } }
1012
+ const reason = parkLockReason(sessionId)
1013
+ let lockErr = ''
1014
+ try { const r = await run(['git', '-C', w.top, 'worktree', 'lock', '--reason', reason, w.top]); if (runCode(r) !== 0) lockErr = firstLine(r && r.stderr) || 'exit ' + runCode(r) } catch (e) { lockErr = firstLine(e && e.message) }
1015
+ let list = null
1016
+ try { const l = await run(['git', '-C', w.top, 'worktree', 'list', '--porcelain']); if (runCode(l) === 0) list = parseWorktreeList(l.stdout) } catch {}
1017
+ const base = { worktree: w.top, root: w.root }
1018
+ if (!list) return { ...base, locked: false, why: 'couldn’t read the lock back' + (lockErr ? ' (' + lockErr + ')' : '') }
1019
+ const e = findEntry(list, w.top, reason)
1020
+ if (e && e.locked === reason) return { ...base, locked: true, reason }
1021
+ if (e && e.locked != null) return { ...base, locked: false, why: 'it’s already locked' + (e.locked ? ' (“' + clip(e.locked, 80) + '”)' : ''), foreign: true }
1022
+ return { ...base, locked: false, why: lockErr || 'the lock didn’t take' }
1023
+ }
1024
+
1025
+ // Is the lock still there, with our reason? (checked again right before /exit)
1026
+ export async function parkLockHeld(run, path, reason) {
1027
+ try {
1028
+ const l = await run(['git', '-C', path, 'worktree', 'list', '--porcelain'])
1029
+ if (runCode(l) !== 0) return false
1030
+ const e = findEntry(parseWorktreeList(l.stdout), path, reason)
1031
+ return !!(e && e.locked === reason)
1032
+ } catch { return false }
1033
+ }
1034
+
1035
+ // Unlock what Leftoff locked for this session: every worktree of the repo at
1036
+ // dir whose lock reason is this session's park reason. Any other lock (yours,
1037
+ // Claude Code's) is left alone. -> { unlocked: [path], failed: [{ path, why }], error? }
1038
+ export async function unlockParkLocks(run, dir, sessionId) {
1039
+ const out = { unlocked: [], failed: [] }
1040
+ if (!dir || !sessionId) return out
1041
+ let list
1042
+ try {
1043
+ const l = await run(['git', '-C', dir, 'worktree', 'list', '--porcelain'])
1044
+ if (runCode(l) !== 0) return { ...out, error: firstLine(l && l.stderr) || 'git worktree list failed' }
1045
+ list = parseWorktreeList(l.stdout)
1046
+ } catch (e) { return { ...out, error: firstLine(e && e.message) } }
1047
+ for (const e of list) {
1048
+ if (e.locked == null || parkLockSession(e.locked) !== String(sessionId)) continue
1049
+ try {
1050
+ const r = await run(['git', '-C', dir, 'worktree', 'unlock', e.path])
1051
+ if (runCode(r) === 0) out.unlocked.push(e.path)
1052
+ else out.failed.push({ path: e.path, why: firstLine(r && r.stderr) || 'exit ' + runCode(r) })
1053
+ } catch (err) { out.failed.push({ path: e.path, why: firstLine(err && err.message) }) }
1054
+ }
1055
+ return out
1056
+ }
1057
+
1058
+ // What /cp-park says about the worktree. res: lockForPark's answer.
1059
+ export function parkWorktreeText(res) {
1060
+ if (!res || !res.worktree && !res.unsure) return ''
1061
+ if (!res.worktree && !res.locked) return ' Leftoff couldn’t tell whether this is a worktree session (' + (res.why || 'no answer') + '), so it didn’t close it. If it is one, lock it first (`git worktree lock <worktree>`) or choose Keep if Claude Code asks: on /exit, Claude Code removes a worktree that has no changes.'
1062
+ if (res.locked) return ' This is a worktree session, so Leftoff locked the worktree first: Claude Code will say it kept it (“could not be removed”). Resume or Done with it unlocks it.'
1063
+ const where = res.worktree ? ' ' + shArg(res.worktree) : ''
1064
+ return ' This is a worktree session and Leftoff couldn’t lock it (' + (res.why || 'no answer') + '), so it didn’t close the session: on /exit, Claude Code removes a worktree that has no changes. To keep it, run `git worktree lock' + (where || ' <worktree>') + '` first, or choose Keep if Claude Code asks.'
1065
+ }
1066
+
915
1067
  // The question Claude ended its turn on, if it ended on one: the last paragraph
916
1068
  // of the answer when its last sentence ends with "?" (markdown and closing
917
1069
  // quotes ignored). Code blocks don't count. -> string or null
@@ -19,7 +19,7 @@ import {
19
19
  shortId, formatTabTitle, parseTabTitle, detectTerminal, parseProcLine, trailingQuestion,
20
20
  parseCheckpointArgs, SUMMARY_LENGTHS, parseBulletList, parseCatchupArgs,
21
21
  listHintFrom, extractChecklists, parseTodoArgs, parseDoneArgs, detectBackend, parseParkArgs,
22
- boardLinkLines, isNonInteractive,
22
+ boardLinkLines, isNonInteractive, lockForPark, parkLockHeld, unlockParkLocks, parkWorktreeText,
23
23
  } from './core.js'
24
24
 
25
25
  const PANE_ID = 'checkpoints'
@@ -28,7 +28,7 @@ const END_TIMEOUT_MS = 1000
28
28
  const MODEL_TIMEOUT_MS = 20000
29
29
 
30
30
  // Module state. $.state is not used: the pane redraws with $.ui.invalidate.
31
- const MOD_VERSION = '0.8.7' // keep in step with .claude-plugin/plugin.json
31
+ const MOD_VERSION = '0.8.8' // keep in step with .claude-plugin/plugin.json
32
32
 
33
33
  const st = {
34
34
  internal: false,
@@ -278,17 +278,45 @@ async function boardLinks($) {
278
278
  // only runs once Claude is done with the turn). If that's refused, it says to
279
279
  // type /exit. Nothing is ever killed.
280
280
  const PARK_FALLBACK = 'Parked. Type /exit when you\'re ready, and it\'ll stay on your board.'
281
+ const PARK_LOCK_LOST = 'Parked, but not closed: the worktree lock Leftoff took is gone, and on /exit Claude Code removes a worktree that has no changes. Lock it again (git worktree lock), or choose Keep if Claude Code asks.'
282
+ // 0.8.8: argv -> { exitCode, stdout, stderr } for the worktree helpers in core.js
283
+ async function gitFor($, argv) { return $.process.run(argv, { timeoutMs: 5000 }) }
281
284
  async function parkCommand($, args) {
282
285
  if (st.internal || !st.sessionId) return { text: 'Leftoff: not in a tracked session.' }
283
286
  const a = parseParkArgs(args)
287
+ // 0.8.8: in a git worktree, lock it first: Claude Code's exit removes a worktree
288
+ // with no changes, and parking means coming back. No lock, no automatic /exit.
289
+ let cwd = null
290
+ try { cwd = await $.session.cwd() } catch {}
291
+ cwd = cwd || (st.record && st.record.cwd) || null
292
+ const run = (argv) => gitFor($, argv)
293
+ const wt = cwd ? await lockForPark(run, cwd, st.sessionId).catch((e) => ({ worktree: null, locked: false, unsure: true, why: String(e && e.message) })) : { worktree: null, locked: false, unsure: true, why: 'no folder on record' }
284
294
  const cp = await makeCheckpoint($, 'park', a.note, null, { next: a.note })
285
- if (!cp) return { text: 'Leftoff: a checkpoint is already being made. Try /cp-park again in a moment.' }
286
- await sendOrSpool($, 'session.parked', { note: a.note, checkpoint: cp.id || null, by: 'command' })
287
- // After this command returns, not inside it: the built-in /exit.
295
+ if (!cp) {
296
+ if (wt.locked) await unlockParkLocks(run, wt.root || wt.worktree, st.sessionId).catch(() => null) // not parked after all
297
+ return { text: 'Leftoff: a checkpoint is already being made. Try /cp-park again in a moment.' }
298
+ }
299
+ const worktreeLock = wt.locked ? { path: wt.worktree, root: wt.root || null, reason: wt.reason } : null
300
+ await sendOrSpool($, 'session.parked', { note: a.note, checkpoint: cp.id || null, by: 'command', ...(worktreeLock ? { worktreeLock } : {}) })
301
+ const head = 'Parked' + (a.note ? ': ' + clip(a.note, 120) : '') + '.'
302
+ if (wt.worktree || wt.unsure) {
303
+ if (!wt.locked) return { text: head + parkWorktreeText(wt) }
304
+ }
305
+ // After this command returns, not inside it: the built-in /exit (in a worktree, only while our lock still holds).
288
306
  $.clock.after(400, async () => {
307
+ if (worktreeLock && !(await parkLockHeld(run, worktreeLock.path, worktreeLock.reason))) { try { $.ui.toast(PARK_LOCK_LOST, { timeoutMs: 12000 }) } catch {} return }
289
308
  try { await $.command.run({ command: 'exit' }) } catch { try { $.ui.toast(PARK_FALLBACK, { timeoutMs: 8000 }) } catch {} }
290
309
  })
291
- return { text: 'Parked' + (a.note ? ': ' + clip(a.note, 120) : '') + '. Closing this session; it stays on your board under Parked.' }
310
+ return { text: head + ' Closing this session; it stays on your board under Parked.' + parkWorktreeText(wt) }
311
+ }
312
+
313
+ // 0.8.8: this session is back (claude --resume, or --worktree <name> --resume):
314
+ // unlock any worktree Leftoff locked when it was parked. Only its own lock.
315
+ async function unlockOwnParkLocks($, cwd) {
316
+ if (st.internal || !st.sessionId || !cwd) return
317
+ try {
318
+ await unlockParkLocks((argv) => gitFor($, argv), cwd, st.sessionId)
319
+ } catch {}
292
320
  }
293
321
 
294
322
  // ------------------------------------------------------------ lists (v0.5.1)
@@ -901,6 +929,7 @@ export function register(on, options) {
901
929
  st.backend = await readBackend($, model)
902
930
  st.hello = { cwd, repo, model, backend: st.backend, surface, proc: st.proc ? { ...st.proc, source: 'mod' } : null, term: st.term }
903
931
  await sendOrSpool($, 'session.opened', st.hello)
932
+ if (repo) await unlockOwnParkLocks($, cwd) // 0.8.8
904
933
  if (st.heartbeat) st.heartbeat.cancel()
905
934
  st.heartbeat = $.clock.every(60000, () => { heartbeat($).catch(() => {}); startReplyLoop($) })
906
935
  st.ready = true
@@ -923,6 +952,7 @@ export function register(on, options) {
923
952
  st.lastCheckpoint = null
924
953
  st.titleSoon = false
925
954
  st.daemonTitle = null
955
+ if (e.source === 'resume' && e.cwd) await unlockOwnParkLocks($, e.cwd) // 0.8.8: /resume of a parked worktree session
926
956
  }
927
957
  if (!st.sessionId) st.sessionId = e.session_id
928
958
  await sendOrSpool($, 'session.started', {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leftoff/cli",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "Leftoff: WTF was I working on? Tracks every Claude Code session, writes a 3-line checkpoint when one goes quiet, and gives you a daily digest and a board, on your Mac and (optionally) your phone.",
5
5
  "keywords": [
6
6
  "claude",
package/ui/app.js CHANGED
@@ -3339,7 +3339,7 @@ document.addEventListener('click', async (ev) => {
3339
3339
  if (action === 'resume-open') { const ok = await resumeOpen(btn, btn.dataset.id || id); if (ok && btn.closest('.parked-card')) await render(); return ok }
3340
3340
  if (action === 'unpark') {
3341
3341
  btn.disabled = true
3342
- try { const r = await api('POST', '/v1/sessions/' + encodeURIComponent(btn.dataset.id || id) + '/park', { done: true }); toast(r.session && r.session.status === 'ended' ? 'Done with it · moved to Closed' : 'No longer parked') } catch (e) { toast(e.message, 5000); btn.disabled = false; return }
3342
+ try { const r = await api('POST', '/v1/sessions/' + encodeURIComponent(btn.dataset.id || id) + '/park', { done: true }); toast((r.session && r.session.status === 'ended' ? 'Done with it · moved to Closed' : 'No longer parked') + (r.worktreeUnlocked ? ' · its worktree is unlocked (still there)' : '')) } catch (e) { toast(e.message, 5000); btn.disabled = false; return }
3343
3343
  return render()
3344
3344
  }
3345
3345
  if (action === 'closed-more') { closedUi.limit += CLOSED_PAGE; btn.disabled = true; try { await closedFetch(state.boardFilter || { repos: [] }, state.boardSpace); closedRepaint() } catch (e) { toast(e.message, 5000) } return }