@nicknisi/sessions 0.0.0-bootstrap → 1.35.0-darwin-arm64

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.
package/bin/sessions ADDED
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: package/bin/sessions
3
+ size: 90117762 bytes
4
+ sha256: ac0868f83d055e6df34886c359f2ded0b851cae506236291b3119d11af4398cc
package/package.json CHANGED
@@ -1,19 +1,17 @@
1
1
  {
2
2
  "name": "@nicknisi/sessions",
3
- "version": "0.0.0-bootstrap",
4
- "description": "Find, resume, recall, and wrap AI coding sessions (Claude Code, Codex, Pi, OpenCode)",
3
+ "version": "1.35.0-darwin-arm64",
4
+ "description": "Prebuilt darwin-arm64 binary for @nicknisi/sessions",
5
5
  "license": "MIT",
6
- "type": "module",
7
- "bin": {
8
- "sessions": "bin/sessions.mjs"
9
- },
6
+ "os": [
7
+ "darwin"
8
+ ],
9
+ "cpu": [
10
+ "arm64"
11
+ ],
10
12
  "files": [
11
- "bin/sessions.mjs",
12
- "README.md"
13
+ "bin/sessions"
13
14
  ],
14
- "engines": {
15
- "node": ">=18"
16
- },
17
15
  "repository": {
18
16
  "type": "git",
19
17
  "url": "git+https://github.com/nicknisi/sessions.git"
package/README.md DELETED
@@ -1,585 +0,0 @@
1
- <h1 align="center">sessions</h1>
2
-
3
- <p align="center">
4
- Search and memory across your AI coding sessions.<br/>
5
- One index over <strong>Claude Code</strong>, <strong>Codex</strong>, <strong>Pi</strong>, and <strong>OpenCode</strong> — fuzzy-find and resume past sessions from the CLI, give agents recall over prior work via MCP, and see where your tokens go.
6
- </p>
7
-
8
- <p align="center">
9
- <a href="https://github.com/nicknisi/sessions/actions/workflows/ci.yml"><img src="https://github.com/nicknisi/sessions/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
10
- <a href="https://github.com/nicknisi/sessions/releases/latest"><img src="https://img.shields.io/github/v/release/nicknisi/sessions" alt="Latest Release" /></a>
11
- </p>
12
-
13
- ## Why
14
-
15
- Every AI coding session leaves a transcript behind. Claude Code buries them in `~/.claude/projects/`, Codex and Pi have their own layouts, OpenCode keeps everything in a SQLite database — and everything in them (what you tried, what you decided, what broke) is effectively write-only.
16
-
17
- `sessions` builds a full-text search index over all of it and makes that history useful in three ways:
18
-
19
- - **Search & resume (CLI)** — fuzzy-find any past session across all four tools, ranked by relevance, and jump back in.
20
- - **Agent memory (MCP)** — agents search your history, pull a repo-scoped context primer when you return to a codebase, and answer "what did I do last week?" via bundled skills.
21
- - **Usage reports** — a token/cost dashboard across tools, models, and projects.
22
-
23
- ## Install
24
-
25
- ### Homebrew
26
-
27
- ```sh
28
- brew install nicknisi/formulae/sessions
29
- ```
30
-
31
- Or, equivalently:
32
-
33
- ```sh
34
- brew tap nicknisi/formulae
35
- brew install sessions
36
- ```
37
-
38
- ### From source
39
-
40
- ```sh
41
- git clone https://github.com/nicknisi/sessions && cd sessions
42
- bun install && bun run build
43
- ```
44
-
45
- The compiled binary is at `dist/sessions`. Requires [Bun](https://bun.sh) when building from source. The Homebrew install is a standalone binary — no runtime needed.
46
-
47
- ### Dependencies
48
-
49
- - **fzf** (optional but recommended) — used for fuzzy selection. If fzf is not installed, a built-in numbered list selector is used as a fallback. Install with `brew install fzf`.
50
- - **Ollama** (optional) — enables semantic recall (see below). If Ollama is not running, search stays purely lexical. Install from [ollama.com](https://ollama.com).
51
-
52
- ### Semantic recall
53
-
54
- Search is lexical by default (full-text ranking over titles, paths, commands, and messages). When an embedding endpoint is available, `sessions` adds an **optional** semantic lane that fuses with — never replaces — the lexical results, so a paraphrase like "flaky tests" can surface a session about "intermittent CI failures".
55
-
56
- - **Providers**: the lane defaults to [Ollama](https://ollama.com) on `http://localhost:11434` (override with `SESSIONS_OLLAMA_URL`) using `nomic-embed-text` (override with `SESSIONS_OLLAMA_MODEL`; `ollama pull nomic-embed-text` to install it). Set `SESSIONS_EMBED_PROVIDER` to opt into a remote endpoint instead: `openai` for any OpenAI-compatible `/embeddings` API (default `https://api.openai.com/v1`, model `text-embedding-3-small`) or `tei` for [Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference) (default `http://localhost:8080`, model read from its `/info`). `SESSIONS_EMBED_URL`, `SESSIONS_EMBED_MODEL` (openai only) and `SESSIONS_EMBED_API_KEY` (sent as `Authorization: Bearer`) configure the remote providers; the key is required only for the real OpenAI endpoint, where `OPENAI_API_KEY` is used as a fallback.
57
- - **Absence is first-class**: no endpoint, an unreachable server, the model not pulled, an unknown `SESSIONS_EMBED_PROVIDER`, or a malformed URL all degrade to identical lexical behavior. Nothing is contacted unless a provider is detected or named — there is no flag.
58
- - **Threshold**: `SESSIONS_EMBED_THRESHOLD` (a number in `(0, 1)`) overrides the cosine floor below which a nearest-vector match is ignored; the default is `0.45`. Cosine values are model-specific. With `intfloat/multilingual-e5-small`, unrelated sessions already score about `0.77`–`0.88`, so `0.45` filters nothing. On two small mixed Korean/English corpora I measured, the true paraphrase hit ranked first every time but beat the best unrelated session by only `0.02`–`0.08`, and the bands overlapped across the two corpora, so no single floor separated them (`0.84` missed a true hit on both). Treat it as a per-corpus value to measure for your own model, not a recommended setting.
59
- - **Privacy**: the default Ollama lane contacts only `localhost`; nothing leaves your machine, and no model is bundled in the binary. A remote provider sends the embedded session text (title, first prompt, files touched, and the first few user messages, capped at 2000 characters per session) and your query text to the configured endpoint — and only when you set `SESSIONS_EMBED_PROVIDER` yourself.
60
-
61
- ## Quick Setup
62
-
63
- After installing, run:
64
-
65
- ```sh
66
- sessions setup
67
- ```
68
-
69
- This automatically:
70
-
71
- 1. Copies the plugin and skills to `~/.local/share/sessions/plugin/`
72
- 2. Detects which AI tools you have installed (Claude Code, Cursor, Codex)
73
- 3. Adds the MCP server config to each tool
74
- 4. Registers the plugin so skills are discoverable
75
-
76
- ```
77
- ❯ sessions setup
78
-
79
- sessions setup
80
-
81
- ✓ Plugin installed to ~/.local/share/sessions/plugin/
82
- ✓ MCP server added to Claude Code
83
- ✓ Plugin registered with Claude Code
84
- ✓ MCP server added to Cursor
85
- ✓ Plugin registered with Cursor
86
-
87
- Skills available:
88
- /context Context primer for the current repo
89
- /weekly-summary Summarize your past week's AI sessions
90
- /standup Yesterday + today activity for standups
91
- /recall What did I do on a specific project?
92
- /session-metrics Usage dashboard with tool breakdown
93
- /session-reflect Reflect on prompting, corrections, and delegation
94
- /memory Triage durable facts mined from past sessions
95
-
96
- Run `sessions setup` again after upgrading to update skills.
97
- ```
98
-
99
- After upgrading sessions (e.g., `brew upgrade sessions`), run `sessions setup` again to update the skills to the latest version.
100
-
101
- To remove the plugin, the MCP config, and the SessionStart hook: `sessions uninstall`. It removes only what the installer created — durable data in `~/.local/share/sessions` (the memory store and the transcript archive) is left alone.
102
-
103
- ## CLI: search & resume
104
-
105
- ```sh
106
- sessions # Browse all sessions with fzf
107
- sessions <query> # Full-text search across session content
108
- sessions --here # Scope to current git repo only
109
- sessions --tool claude # Filter to Claude Code sessions only
110
- sessions --errored # Only sessions that hit an error
111
- sessions --file src/auth.ts # Only sessions that touched this file
112
- sessions context # Print a context primer for the current repo
113
- sessions why <target> # Why does this code exist? Correlate it to past sessions
114
- sessions continue [<session>] # Pick a session back up in any agent, against today's code
115
- sessions digest <session> # Print one session's arc as compact markdown
116
- sessions report # Usage report (HTML dashboard, opens in browser)
117
- sessions memory mine # Mine past sessions for durable facts (JSON on stdout)
118
- sessions memory mine --since-last # ...only transcripts changed since the last mine
119
- sessions memory report # Recurrence report: violations, repeats, fuzzy paraphrase pairs
120
- sessions memory pending # Count + preview the candidates awaiting triage
121
- sessions memory approve <id> # Keep a mined candidate as a durable memory
122
- sessions memory approve <id> --always-on # ...and exempt it from topic filtering
123
- sessions memory approve <id> --no-always-on # ...or explicitly revoke that exemption
124
- sessions memory approve <id> --scope group:authkit # ...and scope it to a project group
125
- sessions memory approve <id> --scope repo:. # ...or bind it to this repo (imports arrive unbound)
126
- sessions memory reject <id> # Dismiss a candidate; it stops being emitted
127
- sessions memory snooze <id> # Hide a candidate without rejecting it
128
- sessions memory merge <id> <id>... # Fold paraphrases into the first id
129
- sessions memory export # Write approved memories as a portable bundle (JSON)
130
- sessions memory import <p> # Merge another author's bundle in as candidates
131
- sessions memory import --from pi-hermes # ...or import another agent's memory store
132
- sessions vault status # Durable transcript archive: counts, bytes, vault-only sessions
133
- sessions vault inspect <target> # One archived session by original path or session id
134
- ```
135
-
136
- ### Options
137
-
138
- | Flag / Command | Description |
139
- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
140
- | `context` | Print a markdown context primer for the current repo (see [Context primer](#context-primer)) |
141
- | `digest <session>` | Print one session's arc as compact markdown (~8k chars): each genuine user turn with its exchange's final assistant reply. Accepts a JSONL file path or a session id |
142
- | `continue [<session>]` | Pick a past session back up in any agent with a brief of its arc, whether its work landed, and what changed since in the files it touched (see [Continue](#continue-pick-up-where-a-session-left-off)). `--in <tool>` picks the agent; `--print` prints the brief |
143
- | `why <target>` | Explain why code exists by correlating a file, `path:line`, commit-ish, or free-text topic to the AI sessions behind it (see [Why](#why-explain-code)). Read-only on git and the index |
144
- | `report` | Generate a usage report (see [Usage reports](#usage-reports)) |
145
- | `memory mine` | Mine past sessions for durable facts worth remembering and print the candidate batch as JSON. `--repo <path>` scopes to one repo container (default: the current repo); `--all` mines every repo; `--since-last` mines only transcripts whose mtime or size changed since the previous mine, so a repeat run over an unchanged corpus emits an empty batch |
146
- | `memory report` | Read-only recurrence report over the memory store: VIOLATIONS (approved memories still being re-corrected after their `lastSeen` date), REPEATS (corrections spanning sessions and dates that were never triaged), and FUZZY (middling-similarity paraphrase pairs to confirm in `/memory`). `--repo <path>` / `--all` scope the report like `mine`; `--since YYYY-MM-DD` filters cluster evidence; `--json` emits the machine-readable batch; `--no-snapshot` skips appending to the trend history. Each run appends a dated snapshot to `~/.local/share/sessions/memory-recurrence-snapshots.jsonl`, and the TREND section shows deltas between runs |
147
- | `memory pending` | Print the untriaged backlog as JSON: the true candidate count plus the first five texts. Reads the store only — it never mines, which is what makes it cheap enough for `/weekly-summary` to call |
148
- | `memory <action>` | Record a triage decision by the `id` from the mine's batch: `approve <id>`, `reject <id>` (never emitted again), or `snooze <id>` (hidden until the snooze expires **and** a later `merge` adds a phrasing that was not there before). `approve` also takes `--always-on` (budgeted — see [Topic filtering and standing constraints](#topic-filtering-and-standing-constraints)), `--no-always-on` to explicitly revoke it, `--scope group:<name>` — see [Project groups](#project-groups) — and `--scope repo:<path>`, which binds a memory to one repo (the path is resolved to its repo container, so any worktree or subdirectory of it works) |
149
- | `memory export` | Write approved memories as a portable JSON bundle on stdout; `--out <path>` writes a file. Approved records only, with session paths and repo paths stripped — no local paths leave the machine |
150
- | `memory import <path>` | Merge a bundle from another author in as candidates to triage. Never lands as approved and never overwrites your own approve/reject decisions. A `repo`-scoped memory arrives with no repo key — export strips local paths — so bind it to one of your repos when you approve it: `--scope repo:.`. Import says how many need it |
151
- | `memory import --from <source>` | Import the durable facts another agent on this machine has stored, as candidates to triage: `pi-hermes` (its structured store, or MEMORY.md/USER.md/failures.md), `claude` (global and repo CLAUDE.md/AGENTS.md plus the per-project memory store), or `all`. `--repo <path>` sets the repo context (default: cwd). Long consolidated entries split at their own sentence boundaries to fit the memory band; entries already in the store count as known, not duplicates. `codex` stores hold command permissions, not facts, so it imports nothing. See [Other agents' memory stores](#other-agents-memory-stores) |
152
- | `vault status` | Report on the durable transcript archive: per-tool counts, total bytes, and how many archived sessions are vault-only (their source file is gone). See [Transcript vault](#transcript-vault) |
153
- | `vault inspect <target>` | Show one archived session by its original file path or session id: the manifest entry plus whether the session is live, archived, or both |
154
- | `setup` | Install plugin and configure MCP for detected tools (`--hooks` opts into auto-injection) |
155
- | `uninstall` | Remove plugin, MCP config, and the SessionStart hook from all tools. Durable data in `~/.local/share/sessions` (the memory store and the transcript archive) is preserved |
156
- | `cleanup` | Full reset: uninstall plugin + clear search index. The transcript archive is untouched — a cleared index rebuilds from the vault |
157
- | `--here` | Scope to the current git repo (default: all projects) |
158
- | `--tool <name>` | Filter by tool: `claude`, `codex`, `pi`, or `opencode` |
159
- | `--errored` | Only show sessions that hit an error |
160
- | `--fork` | Copy a command that forks the picked session (new session, same history) instead of resuming it |
161
- | `--file <path>` | Only sessions that touched or read this path (substring match; repeatable — every path must match). Newest first when no query is given |
162
- | `--mcp` | Start as an MCP server (stdio transport) |
163
- | `--clear-cache` | Remove the search index (rebuilds on next use) |
164
- | `--no-color` | Disable colored output |
165
- | `-h`, `--help` | Show help |
166
-
167
- ### Browsing
168
-
169
- With no arguments, `sessions` scans all session directories, extracts the first user prompt from each conversation, and pipes the results into fzf for fuzzy selection:
170
-
171
- ```
172
- ● my-project claude today Refactor the auth middleware to use JWT
173
- ● my-project pi 2d Help me debug the flaky integration test
174
- ● api-server codex 1w Add rate limiting to the /api/v2 endpoints
175
- ○ old-project claude 2025-03 Set up the initial project structure
176
- ```
177
-
178
- - **●** (green) — the project directory still exists
179
- - **○** (red) — the project directory has been deleted
180
-
181
- ### Searching
182
-
183
- Pass a query to run a full-text search across all sessions:
184
-
185
- ```sh
186
- sessions "rate limit"
187
- ```
188
-
189
- The CLI uses the same search index as the MCP server: results are ranked by relevance (BM25) rather than recency, matching uses porter stemming (`refactor` matches `refactoring`), and multi-word queries match sessions containing _any_ of the terms with the closest matches first. Search covers both your messages and the assistant's replies; system-injected content (`<system-reminder>`, etc.) is stripped from your messages so you only match what you actually typed. Search is message-granular: each matching session is shown with the best-matching message's snippet and its `msg#N` index, then piped into fzf.
190
-
191
- Korean, Japanese and Chinese text is searchable too. The main index splits on spaces and punctuation, which leaves an unspaced run of Han, Kana or Hangul as one token (searching `검색` would miss `검색을`, and `検索` would miss `全文検索機能`). So text that contains CJK is also indexed as overlapping two-character sequences in a side index, and a query is matched against both. This adds hits and drops none, and a corpus without CJK text is indexed and searched exactly as before. A one-character query matches words that begin or end with it. There is no word segmentation, so a short word can also match inside an unrelated longer one that contains the same two characters, and ranking across the two indexes is approximate. On a synthetic corpus where half the sessions mixed Korean, Japanese and Chinese with English, the index file grew from 10,428 KB to 18,160 KB; on an English-only corpus it went from 9,216 KB to 9,256 KB.
192
-
193
- ### After selection
194
-
195
- When you pick a session, `sessions` displays the resume command and copies it to your clipboard:
196
-
197
- ```
198
- my-project (claude)
199
- Refactor the auth middleware to use JWT
200
-
201
- cd /Users/you/Developer/my-project && claude --resume abc123
202
- (copied to clipboard)
203
- ```
204
-
205
- Each tool resumes directly: `claude --resume <id>`, `codex resume <uuid>`, `pi --session <file>`, `opencode --session <id>`. Pass `--fork` to copy a command that forks the session instead (a new session with the same history, leaving the original untouched): `claude --resume <id> --fork-session`, `codex fork <uuid>`, `pi --fork <file>`, `opencode --session <id> --fork`. To carry a session into a _different_ agent, use [`sessions continue`](#continue-pick-up-where-a-session-left-off).
206
-
207
- ## Continue: pick up where a session left off
208
-
209
- Resuming a session replays its transcript as if the code froze when it ended. Come back a week later and the agent trusts file contents that have since changed. `sessions continue` starts a **new** session instead, in any agent, whose first prompt is a bounded brief (~3k tokens):
210
-
211
- - **What happened**: the session's digest, with each exchange's message index for drilling in.
212
- - **Whether its work landed**: commits touching its files authored during the session or within two hours of it, or a warning that none did.
213
- - **What changed since**: for every file it edited, the commits that touched it afterwards, uncommitted edits in the checkout now, and deletions. Files it only read are flagged when they have moved too.
214
- - **Standing memory** for the repo, and an instruction to re-read moved files and report status before changing anything.
215
-
216
- ```sh
217
- sessions continue # the newest session in this repo
218
- sessions continue <session> # a transcript path, session id, or bare Pi/Codex uuid
219
- sessions continue <session> --in codex # carry a Claude Code session into Codex (or claude, pi, opencode)
220
- sessions continue <session> --print # print the brief instead of launching
221
- ```
222
-
223
- It launches in the session's directory when that still exists, otherwise the current one, and prints the brief instead of launching when stdin or stdout isn't a terminal. Git is read-only here too: `log`, `diff`, and `ls-files`. Agents get the same brief from the MCP tool `get_handoff_brief`, so "continue the session where we fixed the parser" works from inside any agent.
224
-
225
- ## Why: explain code
226
-
227
- `sessions why <target>` answers "why does this code exist" by correlating a git commit to the AI coding sessions that produced it. It is **read-only** on both sides: git is consulted with `log`/`blame`/`show` only, and nothing is ever written to any repository — no hooks, no trailers, no branches.
228
-
229
- ```sh
230
- sessions why src/cache.ts # commits that last touched a file, and their sessions
231
- sessions why src/cache.ts:142 # the commit that last changed one line (git blame)
232
- sessions why HEAD~2 # one commit and the sessions that produced it
233
- sessions why "jwt auth refactor" # sessions in this repo matching a topic (no git)
234
- sessions why src/cache.ts --json # emit the structured evidence as JSON
235
- ```
236
-
237
- **Forms.** The target is a file path (optionally `path:line`), a commit-ish (sha, tag, `HEAD~n`), or free text. A path resolves to the commit that last touched it (or, with a line, the commit that last changed that line via `git blame`); a commit-ish resolves directly; free text searches this repo's sessions with no git at all.
238
-
239
- **Confidence.** Each correlated session is tagged `files+time` (it edited the committed files inside its time window) or `time-only` (same repo and window, no file overlap). Results carry the commit (subject, author time, files, trailers), per-session excerpts, an overlapping-files list, and a ready-to-run resume command. An empty result is a result, not an error.
240
-
241
- The same correlation is exposed to agents as the read-only MCP tool `why_did_this_change` and the `/why` skill.
242
-
243
- ## Agent memory
244
-
245
- `sessions` includes an [MCP](https://modelcontextprotocol.io/) server that gives AI agents searchable access to your past conversations — across every tool, not just the one they're running in. `sessions setup` configures it automatically; for manual setup, add to your MCP configuration (e.g., `~/.claude/.mcp.json`):
246
-
247
- ```json
248
- {
249
- "mcpServers": {
250
- "sessions": {
251
- "command": "sessions",
252
- "args": ["--mcp"]
253
- }
254
- }
255
- }
256
- ```
257
-
258
- ### MCP tools
259
-
260
- The MCP server exposes thirteen tools. `search_sessions` and `grep_sessions` leave out the calling agent's own live session when they can identify it (Claude Code's session id, or the lone session of the caller's agent that started alongside the server):
261
-
262
- | Tool | Description |
263
- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
264
- | `search_sessions` | Ranked, top-k search across sessions by keyword; each result includes snippets, files/commands, an errored flag, a resume command, and `messageHits` — the specific matching messages (index, role, snippet). `files` and `commands` are capped at 10 and 5, with `fileCount`/`commandCount` reporting the true totals. A `files` filter answers "which sessions touched this file?" (newest first) |
265
- | `grep_sessions` | Exhaustive literal-or-regex match over every indexed message — for "every time I said X", counts, or exact patterns where ranked search would miss some. Returns `totalHits`/`totalSessions` and hit snippets; each hit's `msgIndex` feeds `get_session_messages` directly |
266
- | `get_session_messages` | Retrieve messages from a specific session, paginated by offset and limit — pass a `messageHits[].index` from search (or a `grep_sessions` hit's `msgIndex`, or an `exchanges[].index` from the digest) as the offset. `include_tools` annotates each turn with the assistant's tool calls |
267
- | `get_session_digest` | The arc of one session in a single bounded call (~2k tokens): every genuine user turn paired with its exchange's final assistant reply. Long sessions elide middle exchanges, never the ends |
268
- | `get_handoff_brief` | Everything needed to continue a past session against today's code in one bounded call: its digest, whether its work landed, what changed since in the files it touched, and the repo's memory, as markdown plus structured `drift`. The MCP face of [`sessions continue`](#continue-pick-up-where-a-session-left-off) |
269
- | `get_activity_digest` | Compact digest of sessions in a date range, grouped by day and project — for weekly summaries |
270
- | `get_session_metrics` | Usage metrics for a date range: tool/project breakdown, daily activity, active hours |
271
- | `get_context_primer` | Repo-scoped primer (recent sessions in detail + older headlines) for re-injecting prior work |
272
- | `why_did_this_change` | Correlate a file, `path:line`, commit-ish, or free-text topic to the AI sessions behind it. Returns the resolved commit (subject, author time, files, trailers) and the sessions that produced it, each tagged `files+time` or `time-only`, with excerpts and a resume command. Read-only on git and the index — never writes to any repository |
273
- | `get_memory` | Approved standing instructions and durable facts for this repo, its project groups, and cross-repo workflow rules — a bounded set of short sentences to read before starting a task. An optional `topic` narrows the result to what is relevant to the task at hand; memory approved with `--always-on` are returned regardless and come first |
274
- | `get_memory_sources` | Inventory every memory store the agents on this machine keep — pi-hermes-memory, Claude Code's global/per-project memory and CLAUDE.md/AGENTS.md files, Codex's rules and goals — with entry counts, durable-fact counts, and last-updated dates. Pure discovery for "what does each agent know?" |
275
- | `review_agent_memories` | Read the CONTENTS of those stores with provenance: source agent and store, scope, a durable flag (importable fact vs audit-only material), and a `similarTo` flag when an entry substantially overlaps a memory sessions already holds. Secret/injection text is withheld with a count. Filter by `agent`, narrow by `topic`; capped at 50 entries with `total`/`truncated` reporting the rest |
276
- | `get_memory_recurrence` | Read-only recurrence report over the memory store: VIOLATIONS (approved memories re-corrected after their `lastSeen` date), REPEATS (corrections spanning multiple sessions and dates that were never triaged), and FUZZY (middling-similarity paraphrase pairs for human confirmation). Each finding carries session links. `repo` defaults to the current repo; `all` crosses repos |
277
-
278
- Together these support the recall flow the bundled skills teach: `search_sessions` (ranked) or `grep_sessions` (exhaustive) localizes the hit to a message, the digest gives a session's whole arc in one call, and targeted message reads expand only the exchanges that matter — no paging full transcripts.
279
-
280
- The `get_activity_digest` tool supports a `detail` parameter: `"compact"` (default) returns topics and file paths only, `"highlights"` adds first and last user messages for substantive sessions (best for summaries), and `"full"` includes all user messages per session.
281
-
282
- ### Skills
283
-
284
- The plugin bundles skills that compose the MCP tools (and, for `/memory`, the CLI) into repeatable workflows:
285
-
286
- | Skill | Trigger | What it does |
287
- | ------------------ | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
288
- | `/context` | "what was I doing here", "catch me up" | Repo-scoped primer: prior decisions, dead ends, the open thread |
289
- | `/recall` | "what did I do on [project]" | Searches by topic or file, digests the best candidates, expands only the matched exchanges |
290
- | `/standup` | "standup", "what did I do yesterday" | Yesterday + today in compact format, terse bullets for Slack |
291
- | `/weekly-summary` | "summarize my week", "weekly recap" | Fetches full digest for the past 7 days, writes structured report, then nudges toward any new memory candidates |
292
- | `/session-metrics` | "session stats", "which tool do I use most" | Tool/project breakdown, daily activity, active hours heatmap |
293
- | `/session-reflect` | "reflect on my workflow", "why do I keep correcting the agent" | Cited interaction patterns and workflow experiments, with no automatic memory or instruction changes |
294
- | `/memory` | "triage memory", "review memory" | Runs the mine, clusters paraphrases, merges them, and walks approve / reject / snooze |
295
-
296
- Skills work with Claude Code, Cursor, Codex, and any agent that supports the skills.sh format.
297
-
298
- ### Project groups
299
-
300
- A memory's scope is normally derived: a fact seen in one repo container is `repo`-scoped, one seen across unrelated containers is `workflow`-scoped. A **project group** is the tier in between — a fact true of several related repos, but not of everything.
301
-
302
- Group membership cannot be derived from your session history, so it comes from a config file at `~/.local/share/sessions/groups.json` (or `$SESSIONS_DATA_DIR/groups.json`). Nothing writes it for you; create it yourself:
303
-
304
- ```json
305
- {
306
- "groups": {
307
- "authkit": ["~/Developer/authkit-*"],
308
- "workos-cli": ["~/Developer/cli/*"]
309
- }
310
- }
311
- ```
312
-
313
- Each group maps a name to a list of path globs matched against the resolved repo container. `~` expands to your home directory, and a subdirectory of a match counts as a member — working in `~/Developer/authkit-session/packages/core` puts you in `authkit`.
314
-
315
- Then assign a group at triage time:
316
-
317
- ```bash
318
- sessions memory approve <id> --scope group:authkit
319
- ```
320
-
321
- The file is never read from inside a repo, and it is never required. If it is missing, malformed, or does not mention a memory's group, retrieval quietly degrades to repo-plus-workflow rather than failing — but that also means a group memory with no matching config is silently never returned, so check the file if a group memory is not showing up.
322
-
323
- ### Topic filtering and standing constraints
324
-
325
- `get_memory` takes an optional `topic`. When present, the returned set is narrowed to memory whose text overlaps the topic, so an agent about to work on authentication does not spend context on your build conventions. Omitting `topic` returns everything, exactly as before.
326
-
327
- Some facts must never be filtered out — "canary is the mainline branch" has to reach the agent whether or not the task description mentions branching. Approve those with `--always-on`:
328
-
329
- ```bash
330
- sessions memory approve <id> --always-on
331
- ```
332
-
333
- An always-on memory is returned for every topic and sorts first, so an agent that truncates drops the conditional tail rather than the invariants. It still respects state and scope: rejected, snoozed, and out-of-scope memories are never returned. Approving again without the flag does not clear it — omission is not a decision; clearing takes an explicit `--no-always-on`.
334
-
335
- The set is budgeted: at most 20 always-on memories totalling 2,000 characters. The cap is what keeps the flag's promise credible — standing constraints only cut through if there are few enough of them to always be read — so a grant past it is refused with instructions to free a slot (`--no-always-on`). A store already over budget (hand-edited, or written before the cap existed) is still served in full, and `get_memory` says so: truncating a standing constraint would be exactly the silent suppression the flag exists to prevent.
336
-
337
- ### Content scanning
338
-
339
- Memory text is scanned at every boundary it can cross. Secret material (API keys, tokens, private-key blocks), prompt-injection phrasing ("ignore previous instructions…"), and invisible Unicode characters never enter the store or reach an agent: the mine drops the turn, `import` withholds the record and says so on stderr, `approve` refuses with the finding named, and `get_memory` withholds any pre-existing approved row while reporting its id — so you can `reject` it or re-approve a clean rephrasing with `--as`. The withheld text itself is never served, not even in the warning.
340
-
341
- Facts _about_ secret handling are deliberately not flagged — "set `DATABASE_URL` through doppler, never in `.env`" and "never pipe `$GITHUB_TOKEN` through curl" are exactly the memories worth keeping. The scanner matches secret material and hijack phrasing, not secret vocabulary: a prohibition legitimately names the thing it prohibits.
342
-
343
- ### Other agents' memory stores
344
-
345
- Sessions are only half of what an agent remembers. Each harness also keeps its own store beside the conversation, and if you hop between agents those stores scatter: pi-hermes-memory writes a categorized SQLite store plus `MEMORY.md`/`USER.md`/`failures.md`; Claude Code injects a global `~/.claude/CLAUDE.md`, per-repo `CLAUDE.md`/`AGENTS.md` files, and a per-project `memory/` directory; Codex records command-permission rules. Three surfaces make them visible and portable, all read-only against the source stores:
346
-
347
- - **`get_memory_sources`** (MCP) inventories every store it can see for the current repo: what it is, how many entries it holds, how many of those are durable facts, and when it was last updated. This is the "what does each agent know about me?" answer.
348
- - **`review_agent_memories`** (MCP) reads their contents with provenance. Every entry carries its source agent and store, a sessions-style scope, and a `durable` flag — `true` for standing facts (importable), `false` for audit-only material like Codex's allow/deny rules or Claude's agent research notes. Entries that substantially overlap a memory sessions already stores are flagged in `similarTo`, so redundancy and near-conflicts between agents are visible. The content scanner gates this surface too: flagged text is withheld with a count, never served. These entries are untriaged source material, not binding instructions — `get_memory` remains the binding surface.
349
- - **`sessions memory import --from <pi-hermes|claude|all>`** (CLI) lands another store's durable facts in your own store as candidates, through the same gates as a bundle import: the text band, the content scan, and candidate-until-approved. Long consolidated entries (pi-hermes averages ~1,100 characters per row) split at their own enumeration and sentence boundaries to fit the 240-character band; fragments that can't be reshaped are counted, never silently dropped. Entries already in the store are reported as known, and a pi-hermes fact recorded against a bare project name arrives unbound — bind it with `approve <id> --scope repo:.` like any import.
350
-
351
- The workflow this enables: switch agents for a project, run `get_memory_sources` to see what the old harness learned, `review_agent_memories` to audit it, and `memory import --from` to carry the facts worth keeping — then triage with `/memory` as usual. Codex keeps permission decisions rather than facts, so `--from codex` reports that and imports nothing.
352
-
353
- ### Context primer
354
-
355
- When you return to a codebase, the primer answers "where did I leave off?" — recent sessions in detail, older ones as headlines, including the branch you were on and the last exchange of each session. It's available three ways:
356
-
357
- - **On demand from an agent** — the `/context` skill or the `get_context_primer` MCP tool
358
- - **On demand from the shell** — `sessions context` prints it as markdown (`--full` widens detail; `--limit`/`--days`/`--tool` filter; `--worktree` narrows to the current worktree; `--out <path>` writes to a file)
359
- - **Automatically at session start** — opt-in, below
360
-
361
- #### Auto-injecting context at session start (opt-in)
362
-
363
- You can have a small primer injected automatically at the start of every Claude Code session via a [SessionStart hook](https://docs.claude.com/en/docs/claude-code/hooks):
364
-
365
- ```bash
366
- sessions setup --hooks # enable auto-injection (Claude Code)
367
- ```
368
-
369
- Run without `--hooks` and `setup` will ask interactively (when on a TTY); it is **off by default** because it costs a small number of tokens on every session. The hook runs `sessions context --hook` — a tiny primer (the 3 most recent sessions for the current repo). In a fresh repo with no history, or outside a git repo, it injects nothing and never blocks session start.
370
-
371
- To turn it off, run `sessions uninstall` (which also removes the plugin and MCP config). The hook lives in `~/.claude/settings.json` under `hooks.SessionStart`; enabling and disabling preserve any other hooks you have configured.
372
-
373
- > Codex and Cursor are not yet supported — their session-start hook contracts are still being confirmed. The hook also requires `sessions` to be on your `PATH` at session start.
374
-
375
- ## Usage reports
376
-
377
- `sessions report` reads your local Claude Code, Codex, Pi, and OpenCode logs and produces a token/cost usage report. By default it renders a self-contained HTML dashboard and opens it in your browser; JSON is available for piping and `--format text` prints a summary straight to the terminal.
378
-
379
- ```sh
380
- sessions report # HTML dashboard, opens in your browser
381
- sessions report --format text --today # quick terminal summary
382
- sessions report --out ./report.html # save the dashboard instead of opening it
383
- sessions report --format json --stdout # print JSON to stdout (for piping)
384
- sessions report --days 30 --tool claude # last 30 days, Claude Code only
385
- sessions report --this-month # current month to date
386
- sessions report --month 2026-05 # a specific calendar month
387
- sessions report --here # current project only
388
- ```
389
-
390
- Parsed transcripts are cached against their mtime and size, so only what changed is re-read; a bounded period additionally skips files last written before the window. Pass `--no-cache` to force a full read.
391
-
392
- The selected period is shown prominently at the top of both outputs (and in the JSON `period`).
393
-
394
- ### Report options
395
-
396
- | Flag | Description |
397
- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
398
- | `--format json\|html\|both\|text` | What to emit. Default `html`. `text` prints to stdout and writes no file. |
399
- | `--out <path>` | Save output instead of opening in the browser. For `both`, a directory → `usage-report.json` + `report.html`; for a single format, a file path. |
400
- | `--here` | Restrict to the current project. |
401
- | `--from YYYY-MM-DD` / `--to YYYY-MM-DD` | Inclusive local-date range. Default: all time. |
402
- | `--days N` | Last `N` days (instead of `--from`/`--to`). |
403
- | `--today` / `--this-week` / `--this-month` / `--last-month` / `--this-year` | Convenience presets that resolve to a date range. |
404
- | `--month YYYY-MM` | A specific calendar month. |
405
- | `--tool claude\|codex\|pi\|opencode` | Restrict to one tool. Default: all four. |
406
- | `--tz <IANA>` | Timezone for day/hour bucketing. Default: `$TIMEZONE`, else `America/Chicago`. |
407
- | `--stdout` | Print the JSON to stdout and skip the JSON file (HTML is still written if requested). |
408
- | `--offline` | Skip the pricing refresh; use cached/embedded pricing data. |
409
- | `--refresh-pricing` | Force a pricing refresh even if the cache is fresh. |
410
- | `--no-cache` | Bypass the incremental parse cache and re-read every transcript. |
411
-
412
- ### What's in the report
413
-
414
- Both outputs are built from the same data:
415
-
416
- - **Summary** — total cost, tokens, sessions, messages, active days, current/longest streak, peak hour, and most-used model.
417
- - **Pace** — spend per active day, a straight-line projection to the end of the period, and the equally long window immediately before it. Only for a bounded period; an all-time report has nothing to pace against.
418
- - **Cache** — hit rate, read and write volume, and what the prompt cache saved against uncached input rates.
419
- - **Breakdowns** — by tool, provider, model, and project.
420
- - **Weekly trend and model mix** — cost per week, and cost per week stacked by model, so a shift between models is visible while it happens.
421
- - **Subagents** — spend by dispatched agent type with the cost of a single dispatch of each, plus the costliest individual dispatches. Roughly half of a heavy Task user's tokens land here; they are counted in every total above, and this says who spent them.
422
- - **Sessions** — the distribution of session spend (median, p90, max across every session), and the most expensive ones named with their title or opening prompt, pulled read-only from the search index when one exists.
423
- - **Daily series** — per-day tokens/cost/sessions/messages with an hourly histogram.
424
- - **Insights** — a weekly trend plus hour-of-day and weekday activity profiles.
425
-
426
- In the HTML, every stat, section heading, and table column explains itself on hover — what is counted, what is excluded, and what the cost is an estimate of.
427
-
428
- The JSON is a sessions-owned `UsageReport` (`{ "generator": "sessions", "version": 1, ... }`). The HTML is fully self-contained (inline SVG charts, no external assets) and adapts to light/dark.
429
-
430
- Cost is estimated from [LiteLLM](https://github.com/BerriAI/litellm) pricing data, fetched at most once per day and cached locally, with an embedded snapshot as the offline fallback — a failed fetch never blocks the report. Pi sessions use the cost recorded in their own logs; OpenCode sessions use their recorded cost when present (Anthropic) and fall back to estimated pricing otherwise (OpenAI). A model with no published price is billed at the newest rate in its own family and flagged as an estimate in the report; one in no known family is counted at `$0`, loudly. Token totals exclude cache reads (replayed context, mostly free reuse).
431
-
432
- ## Wrapped
433
-
434
- `sessions wrapped` turns your year of AI coding into a scroll-through story and opens it in your browser: hidden `<thinking>` confessions behind your back, your beg-to-thank ratio and Irish goodbye rate, 15-minute rebounds between rival agents, caveman one-word commands vs wall-of-text manifestos, tokens, estimated API-rate spend, streaks, rhythm, and your coding personality. On every slide (and in the final master Share Studio), export full-graphic **Braun Swiss × Hardware** PNG cards (**Spec Sheet**, **4-Key Pad**, **Caught On Tape**, **Movie Poster**, **Job Title**, and **Toxic Friend**) in **Bone**, **Slate Dark**, or **Signal Invert** finishes across **4:5 Feed** (`1080×1350`, default), **16:9 X**, **1.91:1 LinkedIn**, or **9:16 Story**, with Zine censor bars hiding private repos by default and 1-click cycling through your real verbatim quotes and bespoke AI awards. **Stealth Mode** is ON by default for exported PNGs and captions (hiding private repo and file names behind NDA redaction bars with a 1-click reveal toggle). Every image carries `npx @nicknisi/sessions wrapped` so anyone who sees it can run their own.
435
-
436
- No install needed (macOS, Linux, and Windows):
437
-
438
- ```sh
439
- npx @nicknisi/sessions wrapped
440
- npx @nicknisi/sessions wrapped --year 2025
441
- ```
442
-
443
- No Node.js? Use the checksum-verified shell fallback (macOS / Linux):
444
-
445
- ```sh
446
- curl -fsSL https://sessions.engineering/wrapped | sh
447
- curl -fsSL https://sessions.engineering/wrapped | sh -s -- --year 2025 # pass options after --
448
- ```
449
-
450
- With `sessions` installed:
451
-
452
- ```sh
453
- sessions wrapped # this year, fast AI verdict on by default (<=25s, fails open)
454
- sessions wrapped --no-roast # deterministic slides without an AI roast
455
- sessions wrapped --offline # purely offline (skips AI roast and pricing refresh)
456
- sessions wrapped --no-stealth # include real repo/file names on share cards and roast digest
457
- sessions wrapped --reel # open on the condensed highlight reel instead of every slide
458
- sessions wrapped --year 2025 # a past calendar year
459
- sessions wrapped --stdout # the underlying JSON, for piping
460
- sessions wrapped --extras roast.json # inject your own extra slides
461
- ```
462
-
463
- Before the browser opens, a screenshot-sized summary card prints in the terminal right away (~3s on a warm cache). The page opens with the full story deck ready to tap, click, scroll, or arrow through like stories (pass `--reel` if you want the condensed highlight cut).
464
-
465
- The fun slides are **dynamically selected**: every candidate stat is scored for how notable it is in _your_ data, and only the top ones render — a daylight coder never sees a 3 AM slide. All stats are computed locally from your event logs and search index; on interactive runs the optional AI roast sends only a redacted stats-only digest to an agent CLI you already have installed (`--no-roast` or `--offline` skips it completely). Because AI tools prune old transcripts, the page discloses when its data starts if that's later than January 1. Token and cost math match `sessions report` exactly.
466
-
467
- ### Fast AI verdict (default on, fails open)
468
-
469
- By default on interactive runs, `sessions wrapped` hands a compact, **stats-only** digest (with private repo and file names redacted unless `--no-stealth` is set, and never raw transcript prose) to an agent CLI you already have installed (`claude`, then `codex`, then `pi` — override with `--roast-with <tool>`). It runs with stripped, ephemeral, low-latency flags (no tools, no MCP, no persisted session, low effort / fast model) under a **25-second hard timeout** while your terminal summary card is already on screen. Every model-written line is stamped `"improvised by <tool> from your stats"`, and one click swaps back to the deterministic tagline. It fails open cleanly when no CLI is installed, offline (`--offline`), or opted out (`--no-roast`).
470
-
471
- `--extras <path>` is the manual version: a JSON array of up to six slides (`[{"headline": "...", "title"?, "subline"?, "footnote"?}]`) injected into the story.
472
-
473
- ## How it works
474
-
475
- ### Session discovery
476
-
477
- `sessions` reads JSONL session files (and OpenCode's SQLite database) from these locations:
478
-
479
- | Tool | Location |
480
- | ----------- | ------------------------------------- |
481
- | Claude Code | `~/.claude/projects/<project>/` |
482
- | Pi | `~/.pi/agent/sessions/` |
483
- | Codex | `~/.codex/sessions/` |
484
- | OpenCode | `~/.local/share/opencode/opencode.db` |
485
-
486
- Each session file is parsed to extract:
487
-
488
- - **Working directory** — read from the session metadata to determine which project the session belongs to
489
- - **First user prompt** — the initial message you sent, cleaned of system-injected tags
490
- - **Custom title** — if the session was renamed in Claude Code, that title is used instead
491
- - **Message count** — total user + assistant messages in the session
492
- - **Timestamps** — first and last timestamps for session duration and date-range queries
493
- - **Subagent content** — for Claude Code, user messages from subagent sidecar files are folded into the search index
494
-
495
- ### Extra session folders
496
-
497
- Tools that run Pi with their own session directory can be indexed too. Set `SESSIONS_PI_EXTRA_DIRS` to a `:`-separated list of folders (like `PATH`); a leading `~` is your home directory and `*` (or `?`) matches within a path segment. For example, to include Riker's coding workers:
498
-
499
- ```sh
500
- export SESSIONS_PI_EXTRA_DIRS='~/.riker/jobs/*/session'
501
- ```
502
-
503
- Each folder may hold transcripts directly or in Pi's one-subfolder-per-project layout; only `*.jsonl` files are read. Folders that don't exist and globs that match nothing are skipped. The default is none. Sessions found this way are ordinary Pi sessions: search, grep, digests, primers, `why`, and usage reports all include them, and a session's Pi name (`pi --name`) is its title.
504
-
505
- ### Search index
506
-
507
- Both the CLI and the MCP server share a SQLite + FTS5 index at `~/.cache/sessions/index.db`. Messages are indexed individually, so a hit localizes to the exact message that matched — not just the session. The index is built automatically on first use (under a minute for a few thousand sessions) and updated incrementally on subsequent runs by checking file modification times — only new or changed sessions are re-indexed.
508
-
509
- Long-lived MCP servers coalesce concurrent refreshes and reuse a freshness check for five seconds, so a burst of related tool calls does not walk the full session tree repeatedly. Set `SESSIONS_REFRESH_INTERVAL_MS=0` on the MCP process to require a source scan before every call.
510
-
511
- To clear the index and force a full rebuild:
512
-
513
- ```sh
514
- sessions --clear-cache
515
- ```
516
-
517
- ### Transcript vault
518
-
519
- The search index is a disposable cache: it prunes rows when source transcripts vanish, and any schema change drops every table and rebuilds from whatever files still exist. Vendors garbage-collect transcripts on a rolling schedule (Claude Code deletes them after 30 days by default), so left to the index alone, history is lost.
520
-
521
- The **vault** is the durable copy. On every index refresh, each parseable transcript is archived to `~/.local/share/sessions/archive/` (raw bytes, one file per session, latest snapshot per file). This directory is the same durable-data convention that `sessions uninstall` already leaves alone, and it is **on by default** — the point is that archiving happens before anyone remembers to enable it. Set `SESSIONS_ARCHIVE_DIR` to relocate it, or `SESSIONS_ARCHIVE=0` to skip it for a run (the curl one-liner does this, so a one-off wrapped leaves no copy behind).
522
-
523
- The vault is also a **discovery source**: a session whose source file is gone is re-indexed from its vault copy under its original path, so search, resume commands, and message reads keep working. OpenCode is the one exception to raw-bytes archiving — its sessions are SQLite rows with no files, so a normalized JSONL export (the same shape the parser reads) is archived instead.
524
-
525
- Inspect the archive:
526
-
527
- ```sh
528
- sessions vault status # per-tool counts, total bytes, vault-only sessions
529
- sessions vault inspect <target> # one session by original path or session id
530
- ```
531
-
532
- `status` reports how many archived sessions are vault-only (their source file is already gone). `inspect` takes either the original file path or the session id and prints the manifest entry plus whether the session is live, archived, or both.
533
-
534
- To rebuild the search index from scratch (the vault is untouched, so archived history survives):
535
-
536
- ```sh
537
- sessions --clear-cache
538
- ```
539
-
540
- ### Scoping with `--here`
541
-
542
- When `--here` is passed, `sessions` resolves the current git repo root and only shows sessions whose working directory falls under that root. This works with bare repo worktrees — if a `.git` file points to a `.bare` directory, the parent is used as the repo root.
543
-
544
- Sessions that ran in a linked git worktree count toward the repo it belongs to, wherever the worktree lives. The main checkout is recorded when the session is indexed, so `--here`, project filters, the context primer, and `why` keep finding those sessions after the worktree is removed, and `search_sessions` results carry a `repo` field naming the main checkout. A sibling that only shares a name prefix (`app-v2` next to `app`) stays separate.
545
-
546
- ## Development
547
-
548
- ```sh
549
- bun install # Install dependencies
550
- bun run dev # Run directly without compiling
551
- bun run build # Compile to dist/sessions
552
- bun run typecheck # Type-check with tsc
553
- bun run lint # Lint with oxlint
554
- bun run format # Format with oxfmt
555
- bun run format:check # Check formatting without writing
556
- bun run eval # Search ranking eval against the golden fixture
557
- ```
558
-
559
- Search ranking is gated by a frozen golden eval fixture (`src/eval/`): recall@5, MRR, and negative-abstention thresholds run in CI, and the ranking constants in `cache.ts` move only against that fixture. See [docs/EVAL.md](docs/EVAL.md) for the discipline and how to log a real miss as a new golden.
560
-
561
- ### Cross-compilation
562
-
563
- The release workflow compiles binaries for four platforms:
564
-
565
- | Target | Artifact |
566
- | ------------------------- | ------------------------ |
567
- | macOS ARM (Apple Silicon) | `sessions-darwin-arm64` |
568
- | macOS x86_64 (Intel) | `sessions-darwin-x86_64` |
569
- | Linux x86_64 | `sessions-linux-x86_64` |
570
- | Linux ARM64 (aarch64) | `sessions-linux-arm64` |
571
-
572
- Binaries are compiled with `bun build --compile --minify` and distributed as `.tar.gz` archives attached to GitHub Releases.
573
-
574
- ### Release process
575
-
576
- Releases are automated with [release-please](https://github.com/googleapis/release-please):
577
-
578
- 1. Push commits to `main` using [conventional commit](https://www.conventionalcommits.org/) messages
579
- 2. Release-please opens a version-bump PR with an auto-generated changelog
580
- 3. Merge the PR to trigger the release pipeline
581
- 4. Binaries are built, attached to the GitHub Release, and the Homebrew formula is auto-updated
582
-
583
- ## License
584
-
585
- MIT
package/bin/sessions.mjs DELETED
@@ -1,123 +0,0 @@
1
- #!/usr/bin/env node
2
- // Thin zero-postinstall launcher for `@nicknisi/sessions` (modeled on
3
- // `@openai/codex` and `ccusage`). Resolves the matching platform binary from
4
- // optionalDependencies and execs it with inherited stdio.
5
-
6
- import { spawn } from 'node:child_process';
7
- import { chmodSync, existsSync, realpathSync, statSync } from 'node:fs';
8
- import { createRequire } from 'node:module';
9
- import path from 'node:path';
10
- import process from 'node:process';
11
- import { fileURLToPath } from 'node:url';
12
-
13
- const require = createRequire(import.meta.url);
14
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
-
16
- export const PLATFORM_PACKAGES = {
17
- 'darwin-arm64': { pkg: '@nicknisi/sessions-darwin-arm64', bin: 'bin/sessions' },
18
- 'darwin-x64': { pkg: '@nicknisi/sessions-darwin-x64', bin: 'bin/sessions' },
19
- 'linux-arm64': { pkg: '@nicknisi/sessions-linux-arm64', bin: 'bin/sessions' },
20
- 'linux-x64': { pkg: '@nicknisi/sessions-linux-x64', bin: 'bin/sessions' },
21
- 'win32-x64': { pkg: '@nicknisi/sessions-win32-x64', bin: 'bin/sessions.exe' },
22
- };
23
-
24
- const FALLBACK_HINT =
25
- 'Run without Node: curl -fsSL https://sessions.engineering/wrapped | sh\n' +
26
- 'Or install via Homebrew: brew install nicknisi/formulae/sessions';
27
-
28
- /**
29
- * Resolve the platform binary path or return an actionable error message.
30
- * Pure & injectable for unit tests.
31
- */
32
- export function resolveNativeBinary({
33
- platform = process.platform,
34
- arch = process.arch,
35
- resolvePath = (id) => require.resolve(id),
36
- fileExists = existsSync,
37
- } = {}) {
38
- const key = `${platform}-${arch}`;
39
- const spec = PLATFORM_PACKAGES[key];
40
- if (!spec) {
41
- return {
42
- error: `sessions: no prebuilt binary for ${key}.\n${FALLBACK_HINT}\n`,
43
- };
44
- }
45
- try {
46
- const pkgJson = resolvePath(`${spec.pkg}/package.json`);
47
- const binaryPath = path.join(path.dirname(pkgJson), spec.bin);
48
- if (fileExists(binaryPath)) return { binaryPath };
49
- return {
50
- error: `sessions: package ${spec.pkg} is installed, but ${spec.bin} is missing. Reinstall @nicknisi/sessions.\n${FALLBACK_HINT}\n`,
51
- };
52
- } catch {
53
- return {
54
- error:
55
- `sessions: missing optional native package "${spec.pkg}" for ${key}.\n` +
56
- `This happens when npm --omit=optional or a minimum-release-age policy skips platform binaries.\n` +
57
- `Retry without --omit=optional, or:\n${FALLBACK_HINT}\n`,
58
- };
59
- }
60
- }
61
-
62
- function ensureExecutable(binaryPath, platform = process.platform) {
63
- if (platform === 'win32') return;
64
- try {
65
- const mode = statSync(binaryPath).mode;
66
- if ((mode & 0o111) === 0) chmodSync(binaryPath, mode | 0o755);
67
- } catch {
68
- // Best-effort; spawn will report EACCES if truly non-executable.
69
- }
70
- }
71
-
72
- export function isOneOffNpxRun(dir = __dirname, argv = process.argv.slice(2)) {
73
- return argv[0] === 'wrapped' && (dir.includes('_npx') || dir.includes('bunx') || dir.includes('dlx'));
74
- }
75
-
76
- function main() {
77
- const resolved = resolveNativeBinary();
78
- if ('error' in resolved) {
79
- process.stderr.write(resolved.error);
80
- process.exit(1);
81
- }
82
-
83
- ensureExecutable(resolved.binaryPath);
84
-
85
- const args = process.argv.slice(2);
86
- const env = { ...process.env };
87
- // Mirror site/public/wrapped: one-off `npx @nicknisi/sessions wrapped` runs
88
- // skip duplicating transcripts into the archive unless the user opted in.
89
- if (env.SESSIONS_ARCHIVE === undefined && isOneOffNpxRun(__dirname, args)) {
90
- env.SESSIONS_ARCHIVE = '0';
91
- }
92
-
93
- const child = spawn(resolved.binaryPath, args, { stdio: 'inherit', env });
94
- const forward = (sig) => {
95
- if (!child.killed) child.kill(sig);
96
- };
97
- process.on('SIGINT', forward);
98
- process.on('SIGTERM', forward);
99
- child.on('error', (err) => {
100
- process.stderr.write(`sessions: failed to launch binary (${err.message})\n${FALLBACK_HINT}\n`);
101
- process.exit(1);
102
- });
103
- child.on('exit', (code, signal) => {
104
- if (signal) process.kill(process.pid, signal);
105
- process.exit(code ?? 1);
106
- });
107
- }
108
-
109
- // Resolve symlinks so `npx`/`bunx`/`pnpm dlx` invocations through
110
- // `node_modules/.bin/sessions` still detect direct execution.
111
- export function isDirectRun(argv1 = process.argv[1], metaUrl = import.meta.url) {
112
- if (!argv1) return false;
113
- const selfPath = fileURLToPath(metaUrl);
114
- try {
115
- return realpathSync(argv1) === realpathSync(selfPath);
116
- } catch {
117
- return path.resolve(argv1) === path.resolve(selfPath);
118
- }
119
- }
120
-
121
- if (isDirectRun()) {
122
- main();
123
- }