SLOPSHOPPER

session-bookmark

Compaction bookmark: git state, last prompts, session notes and /compact instructions kept in session state and appended to the compacted conversation

commandprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-bookmark
› fix the failing auth test and add an audit log call ⏺ 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 › /session-bookmark ⎿ session-bookmark: No compaction bookmark in this session's state. A resumed session's transcript may still carry one. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

session-bookmark

A compaction bookmark kept in session state instead of a file. It stands in for file-based PreCompact and SessionStart compact|resume hooks that write a bookmark file and read it back after compaction.

Nothing in it is specific to one repository: it reads git state, the conversation and the project's notes file (.claude/harness.json for state_dir). Notes need the harness plugin's add-bookmark skill; the rest depends on no other plugin.

What it does

  • On a manual, auto or plugin compaction of the main conversation, it records the branch, git log --oneline -5, git status --porcelain (first 40 entries, then a count of the rest), the last three prompts, the stored session notes and the /compact instructions into $.state['session-bookmark'].bookmark. $.state outlives compactions and mod reloads.
  • The same bookmark is appended to the compacted conversation as its last message, opening with POST-COMPACT BOOKMARK (session-bookmark). The model reads it on the next request, so a mid-turn auto-compaction is covered too, and a resumed transcript already holds it.
  • Notes added with the harness:add-bookmark skill print in a ## Session Notes section, after the last user messages and before the /compact instructions. They are read at each compaction from <state_dir>/session-bookmark/notes.json under the git top level of the session cwd, else of CLAUDE_PROJECT_DIR; when neither is a repository, the first of the cwd and CLAUDE_PROJECT_DIR that holds a notes file is read. state_dir coming from .claude/harness.json (default .claude/state/harness). The newest 20 notes are kept, each cut at 300 characters. An absent, malformed or other-version file means no notes section; a note stays until /harness:add-bookmark --clear.
  • Git is read from the session cwd when it is a repository (a worktree the session moved into), else from CLAUDE_PROJECT_DIR. Git runs beside the summarizer (GIT_OPTIONAL_LOCKS=0, 5 s timeout per command); when core reuses a precomputed summary, the git calls and the notes read are the compaction's only wait. A repository with no commits yet still reports its branch and status. When neither folder is a repository, or git is missing, the git fields are null and the prompts are still recorded.
  • Precompute and subagent compactions pass through untouched. A skipped compaction records nothing.

Command

NameDoes
/session-bookmarkPrints the bookmark held in this session's state, or says none is held. $.state is promised to survive a reload, not a resume, so a resumed session can answer none while its transcript still carries a bookmark message.

State

$.state['session-bookmark'] (contract: types/index.d.ts):

KeyTypeMeaning
bookmark`Bookmark \null`Latest compaction bookmark: time, trigger, root, branch, log, status, last prompts, notes, instructions.

Known limitations

  • $.state is per session: the bookmark reaches a new process only as the message already in the compacted transcript. Only the latest bookmark is kept; the old history.log has no equivalent.
  • The bookmark has no session-id line, and its time is UTC ISO 8601 rather than local time with an offset.
  • A previous compaction's summary is a user message, so it can appear among the "last user messages" when fewer than three prompts followed it.
  • The notes file is per project folder, not per session: two sessions in one repository share their notes, and a note nobody clears reaches the next session's bookmark. A linked worktree reads its own file.
  • A session without this mod loaded gets no bookmark at all. Where the mod is enabled in project settings, a folder whose workspace trust was never accepted, including a claude -p run there, ignores those settings and compacts with no bookmark.
  • A project that also keeps file-based bookmark hooks in its settings gets two bookmarks per compaction; remove those hooks when enabling this mod.
  • A CLAUDE_CODE_PLUGIN_DIRS entry points at one checkout and replaces the marketplace copy, so with it set, which mod code loads follows that checkout's branch, not the session worktree's.
  • claude plugin test runs in a Linux sandbox; Windows paths are passed to git as given.

Checks

claude plugin validate <mod folder>
claude plugin test <mod folder>
tsc -p <mod folder>   # once the engine has generated .claude-plugin/types/ by loading the mod

Loading

Install from the operator-straps marketplace:

claude plugin marketplace add t968rs/operator-straps
claude plugin install session-bookmark@operator-straps

For development, a CLAUDE_CODE_PLUGIN_DIRS entry in the env block of the user-level ~/.claude/settings.json (or claude --plugin-dir <folder> for one session) loads the folder with hot reload and replaces the marketplace copy of the same-named mod, so it never runs twice. The variable is one string, ;-separated on Windows: append to its existing value rather than replacing it. The project's settings are not read for this variable.

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "C:\\path\\to\\operator-straps\\plugins\\session-bookmark;C:\\path\\to\\operator-straps\\plugins\\pr-review-watch;C:\\path\\to\\operator-straps\\plugins\\git-status"
  }
}
Source 4 files
hooks/register.ts 8 lines
1import type { Register } from 'claude-code'
2
3import { registerBookmark } from './bookmark'
4
5export const register: Register = on => {
6  registerBookmark(on)
7}
8
hooks/bookmark.ts 245 lines
1import type {
2  EngineInterface,
3  Register,
4  SessionCompactInput,
5  SessionCompactResult,
6  SessionMessage,
7} from 'claude-code'
8import { atom, read, update } from 'claude-code'
9
10import type { Bookmark } from '../types'
11import { notesFileOf, parseNotes, stateDirOf } from './notes'
12
13/**
14 * Compaction bookmark kept in `$.state` instead of a bookmark file.
15 *
16 * Stands in for file-based `PreCompact` and `SessionStart` compact|resume bookmark hooks. The bookmark
17 * is written to `$.state`, which outlives compaction and
18 * module reloads, and is appended to the compacted conversation as its last message, so the model reads it
19 * on the very next request, mid-turn auto-compactions included, and a resumed transcript carries it.
20 * Every failure path degrades to the compaction as core answered it; the hook never throws past `next`.
21 */
22
23type Dollar = EngineInterface
24
25const bookmarkState = atom({ plugin: 'session-bookmark', key: 'bookmark' } as const, null)
26
27/** Opening line of every bookmark message; also how a later compaction recognises one. */
28export const BOOKMARK_HEADER = 'POST-COMPACT BOOKMARK (session-bookmark)'
29/** Longest stored prompt or instruction text, in characters. */
30export const MAX_MESSAGE_CHARS = 2000
31/** Most porcelain status entries kept; the rest are counted, not listed. */
32export const MAX_STATUS_LINES = 40
33/** The `/session-bookmark` reply when this session's state holds no bookmark. */
34export const NO_BOOKMARK_TEXT =
35  "No compaction bookmark in this session's state. A resumed session's transcript may still carry one."
36const MESSAGE_COUNT = 3
37const GIT_TIMEOUT_MS = 5000
38const COMMAND = 'session-bookmark'
39/** Triggers that install a compaction (precompute installs nothing). */
40const INSTALLING = { trigger: ['manual', 'auto', 'plugin'] } as const
41
42const RESUME_HINT =
43  'The content below is the authoritative resume point. Read the LAST user message recorded here and ' +
44  'continue from there, not from tool-result replays rehydrated above it. Run `git status` and ' +
45  '`git log -3` before acting: commits may have landed during compaction.'
46
47// ---------------------------------------------------------------------------
48// Pure
49
50/**
51 * Whether a message counts as a prompt: a user message with text, no tool results, not a bookmark. A
52 * previous compaction's summary is a user message too, so it counts.
53 */
54const isPrompt = (m: SessionMessage): boolean =>
55  m.role === 'user' &&
56  (m.toolResults ?? []).length === 0 &&
57  m.text.trim() !== '' &&
58  !m.text.startsWith(BOOKMARK_HEADER)
59
60/** The last `n` prompts (an earlier summary included), newest last. */
61export const lastUserTexts = (messages: readonly SessionMessage[], n = MESSAGE_COUNT): string[] =>
62  messages.filter(isPrompt).slice(-n).map(m => m.text.trim())
63
64/** Cuts text past MAX_MESSAGE_CHARS, keeping the start. */
65const truncate = (text: string): string =>
66  text.length <= MAX_MESSAGE_CHARS ? text : `${text.slice(0, MAX_MESSAGE_CHARS)}\n...(truncated)`
67
68/** Keeps the first MAX_STATUS_LINES porcelain entries and counts the rest. */
69const capStatus = (status: string): string => {
70  const lines = status.split('\n')
71  if (lines.length <= MAX_STATUS_LINES) return status
72  const rest = lines.length - MAX_STATUS_LINES
73  return [...lines.slice(0, MAX_STATUS_LINES), `... (${rest} more entries)`].join('\n')
74}
75
76/** A fenced block; four backticks so a prompt holding a triple fence stays inside. */
77const fence = (body: string): string[] => ['````', body, '````', '']
78
79/** The prompt section's lines. */
80const messageLines = (messages: readonly string[]): string[] => {
81  if (messages.length === 0) return ['(no user messages recovered)', '']
82  return messages.flatMap((m, i) => [`### Message ${i + 1}`, '', ...fence(truncate(m))])
83}
84
85/** The session notes' lines: one numbered line per note. */
86const noteLines = (notes: readonly string[]): string[] => [
87  '## Session Notes',
88  '',
89  ...notes.map((n, i) => `${i + 1}. ${n}`),
90  '',
91]
92
93/** The bookmark as the message the model reads after the compaction. */
94export const formatBookmark = (b: Bookmark): string => {
95  const lines = [
96    `${BOOKMARK_HEADER}. ${RESUME_HINT}`,
97    '',
98    `- Saved: ${new Date(b.savedAt).toISOString()}`,
99    `- Trigger: ${b.trigger}`,
100    `- Branch: ${b.branch === null ? '(unknown)' : `\`${b.branch}\``}`,
101    `- Root: ${b.root === null ? '(unknown)' : `\`${b.root}\``}`,
102    '',
103    '## Recent Commits',
104    '',
105    ...fence(b.log ?? '(git unavailable)'),
106    '## Working Tree (git status --porcelain)',
107    '',
108    ...fence(b.status === null ? '(git unavailable)' : b.status || '(clean)'),
109    '## Last User Messages (verbatim, newest last)',
110    '',
111    ...messageLines(b.lastMessages),
112  ]
113  const notes = b.notes ?? []
114  if (notes.length > 0) lines.push(...noteLines(notes))
115  if (b.instructions !== null) lines.push('## Compaction Instructions', '', ...fence(truncate(b.instructions)))
116  return lines.join('\n').trimEnd()
117}
118
119// ---------------------------------------------------------------------------
120// Host access (kept in this file: `$` is not passed across an import)
121
122/**
123 * Folders to read git from, in order: the session cwd (a worktree the session moved into), then
124 * CLAUDE_PROJECT_DIR; blanks and repeats dropped. Never throws.
125 */
126const rootCandidates = async ($: Dollar): Promise<string[]> => {
127  const cwd = await $.session.cwd().catch(() => undefined)
128  const env = await $.env.get('CLAUDE_PROJECT_DIR').catch(() => undefined)
129  const named = [cwd, env].filter((p): p is string => p !== undefined && p.trim() !== '')
130  return [...new Set(named)]
131}
132
133/** Stdout of one git command, trailing whitespace cut; null on any failure. */
134const gitText = async ($: Dollar, root: string, args: string[]): Promise<string | null> => {
135  const ran = await $.process
136    .run(['git', '-C', root, ...args], { timeoutMs: GIT_TIMEOUT_MS, env: { GIT_OPTIONAL_LOCKS: '0' } })
137    .catch(() => undefined)
138  // trimEnd: a porcelain line's leading space is its index column (" M a.py")
139  return ran === undefined || ran.exitCode !== 0 ? null : ran.stdout.trimEnd()
140}
141
142type GitFields = Pick<Bookmark, 'root' | 'branch' | 'log' | 'status'>
143
144const NO_GIT: GitFields = { root: null, branch: null, log: null, status: null }
145
146/** What git answered, and the repository's top level (where the project's notes live); null without a repository. */
147type GitCapture = { git: GitFields; top: string | null }
148
149/** The checked-out branch; in a repository with no commits, HEAD's symbolic name. Null when neither answers. */
150const gitBranch = async ($: Dollar, root: string): Promise<string | null> =>
151  (await gitText($, root, ['rev-parse', '--abbrev-ref', 'HEAD'])) ??
152  (await gitText($, root, ['symbolic-ref', '--short', 'HEAD']))
153
154/**
155 * Branch, recent commits and capped porcelain status from the first candidate that is a repository; all
156 * null when none is. Never throws.
157 */
158const captureGit = async ($: Dollar): Promise<GitCapture> => {
159  for (const root of await rootCandidates($)) {
160    const top = await gitText($, root, ['rev-parse', '--show-toplevel'])
161    if (top === null) continue
162    const [branch, log, status] = await Promise.all([
163      gitBranch($, root),
164      gitText($, root, ['log', '--oneline', '-5']),
165      gitText($, root, ['status', '--porcelain']),
166    ])
167    return { git: { root, branch, log, status: status === null ? null : capStatus(status) }, top }
168  }
169  return { git: NO_GIT, top: null }
170}
171
172/** The notes of the first root that holds a notes file: `<state_dir>/session-bookmark/notes.json`. Never throws. */
173const captureNotes = async ($: Dollar, top: string | null): Promise<string[]> => {
174  try {
175    for (const root of top === null ? await rootCandidates($) : [top]) {
176      const config = await $.fs.read(`${root.replace(/\\/g, '/')}/.claude/harness.json`).catch(() => undefined)
177      const text = await $.fs.read(notesFileOf(root, stateDirOf(config))).catch(() => undefined)
178      if (typeof text === 'string') return parseNotes(text)
179    }
180  } catch {
181    // a notes failure leaves the bookmark without notes
182  }
183  return []
184}
185
186type Capture = { git: GitFields; notes: string[] }
187
188/** Git state and session notes, read before the compaction answers. Never throws. */
189const capture = async ($: Dollar): Promise<Capture> => {
190  const { git, top } = await captureGit($)
191  return { git, notes: await captureNotes($, top) }
192}
193
194/** Builds and stores the bookmark, and returns the result with the bookmark message appended. */
195const bookmarkResult = async (
196  $: Dollar,
197  e: SessionCompactInput,
198  trigger: Bookmark['trigger'],
199  { git, notes }: Capture,
200  result: SessionCompactResult & { skip?: undefined },
201): Promise<SessionCompactResult> => {
202  const b: Bookmark = {
203    savedAt: await $.clock.now(),
204    trigger,
205    ...git,
206    lastMessages: lastUserTexts(e.messages),
207    notes,
208    instructions: e.instructions?.trim() || null,
209  }
210  await update($, bookmarkState, () => b).catch(() => undefined)
211  const message: SessionMessage = { role: 'user', text: formatBookmark(b), toolUses: [] }
212  return { ...result, messages: [...result.messages, message] }
213}
214
215// ---------------------------------------------------------------------------
216// Registration
217
218/** Registers the compaction bookmark and the `/session-bookmark` command. */
219export const registerBookmark = (on: Parameters<Register>[0]): void => {
220  on('session.compact', INSTALLING, async ($, e, next) => {
221    if (e.agentId !== undefined) return next(e)
222    // git and the notes overlap the summarizer; when core reuses a precomputed summary, git's own timeouts are the wait
223    const captured = capture($)
224    const result = await next(e)
225    if (result.skip !== undefined) return result
226    try {
227      return await bookmarkResult($, e, e.trigger, await captured, result)
228    } catch {
229      return result
230    }
231  })
232
233  on('session.start', async ($, e, next) => {
234    await $.command
235      .register({ name: COMMAND, description: 'Show the compaction bookmark saved in this session' })
236      .catch(() => undefined)
237    return next(e)
238  })
239
240  on('command.run', { command: COMMAND }, async $ => {
241    const b = await read($, bookmarkState)
242    return { text: b === null ? NO_BOOKMARK_TEXT : formatBookmark(b) }
243  }).catch(() => ({ text: 'session-bookmark: bookmark state unavailable.' }))
244}
245
hooks/notes.ts 65 lines
1/**
2 * The session notes the `harness:add-bookmark` skill stores and the bookmark prints.
3 *
4 * The skill's script (`plugins/harness/skills/add-bookmark/commands/add_note.py`) writes
5 * `<state_dir>/session-bookmark/notes.json` under the project root: `{ "version": 1, "notes": [{ "added",
6 * "text" }] }`. An installed mod sits in its own plugin cache folder and cannot read the harness plugin, so the
7 * names and limits are copied here; `tests/mods/test_session_bookmark_notes_contract.py` pins them. Pure: no `$`.
8 */
9
10export const DEFAULT_STATE_DIR = '.claude/state/harness'
11export const NOTES_PATH = 'session-bookmark/notes.json'
12export const NOTES_SCHEMA_VERSION = 1
13/** The most notes printed; the script refuses a note past this many. */
14export const MAX_NOTES = 20
15/** The longest note printed, in characters; the script refuses a longer one. */
16export const MAX_NOTE_CHARS = 300
17
18type Json = Readonly<Record<string, unknown>>
19
20const isObject = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
21
22const parse = (text: string): unknown => {
23  try {
24    return JSON.parse(text)
25  } catch {
26    return undefined
27  }
28}
29
30/** Forward slashes, no surrounding blanks, no trailing slash. */
31const cleanPath = (p: string): string => p.trim().replace(/\\/g, '/').replace(/\/+$/, '')
32
33/** `state_dir` from a `harness.json` text; the default when the text is absent, malformed or holds none. */
34export const stateDirOf = (configText: string | undefined): string => {
35  const data = configText === undefined ? undefined : parse(configText)
36  const named = isObject(data) && typeof data.state_dir === 'string' ? cleanPath(data.state_dir) : ''
37  return named === '' ? DEFAULT_STATE_DIR : named
38}
39
40/** Whether a path is absolute: POSIX, drive or UNC. */
41const isAbsolute = (path: string): boolean => /^([A-Za-z]:)?[\\/]/.test(path)
42
43/** The notes file under `root`; an absolute `stateDir` is kept as it is. */
44export const notesFileOf = (root: string, stateDir: string): string => {
45  const base = isAbsolute(stateDir) ? stateDir : `${cleanPath(root)}/${stateDir}`
46  return `${base}/${NOTES_PATH}`
47}
48
49/** A note's text cut to the limit and trimmed; blank and non-text entries read as null. */
50const noteText = (entry: unknown): string | null => {
51  const text = isObject(entry) && typeof entry.text === 'string' ? entry.text.trim() : ''
52  return text === '' ? null : text.slice(0, MAX_NOTE_CHARS)
53}
54
55/**
56 * The notes in a file's text, oldest first, at most `MAX_NOTES` (the newest when more are stored). Malformed
57 * JSON, another version or a missing `notes` array hold none.
58 */
59export const parseNotes = (text: string): string[] => {
60  const data = parse(text)
61  if (!isObject(data) || data.version !== NOTES_SCHEMA_VERSION || !Array.isArray(data.notes)) return []
62  const kept = data.notes.map(noteText).filter((t): t is string => t !== null)
63  return kept.slice(-MAX_NOTES)
64}
65
types/index.d.ts 30 lines
1/** Session state captured as the main conversation compacts; stands in for a bookmark file. */
2export type Bookmark = {
3  /** Epoch ms when the compaction finished. */
4  savedAt: number
5  trigger: 'manual' | 'auto' | 'plugin'
6  /** The folder git answered from (session cwd, else CLAUDE_PROJECT_DIR); null when neither is a repo. */
7  root: string | null
8  /** `git rev-parse --abbrev-ref HEAD`, else `git symbolic-ref --short HEAD` (no commits yet); null when git was unavailable. */
9  branch: string | null
10  /** `git log --oneline -5`; null when git was unavailable or the repository has no commits. */
11  log: string | null
12  /** `git status --porcelain`, capped at MAX_STATUS_LINES entries plus a count line; null when git was unavailable, '' when clean. */
13  status: string | null
14  /** The last user prompts before the compaction, newest last; a previous compaction's summary can be one. */
15  lastMessages: string[]
16  /** Session notes added with the `harness:add-bookmark` skill, oldest first; [] when none are stored. */
17  notes: string[]
18  /** The compaction's instructions (the text after `/compact`); null when none. */
19  instructions: string | null
20}
21
22declare module 'claude-code' {
23  interface PluginState {
24    'session-bookmark': {
25      /** The latest compaction bookmark of this session; null before the first. */
26      bookmark: Bookmark | null
27    }
28  }
29}
30