⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v0.2.0

save-session

@jemshit⭐ 219 stars

Save the active coding session (session ID, model, working directory) to a per-harness markdown record under ~/.agents/memories/sessions/, and later find a saved session by project title and tell the user exactly how to resume it. USE THIS SKILL whenever the user wants to save, bookmark, or remember a session or session id ("save this session", "remember this session", "store my session id", "note down where we were"), or asks to get back into earlier work ("resume the X session", "find the session for X", "continue where we left off on X", "which session were we doing X in", "what's my session id for X", "how do I get back into X"). Applies to Pi, Claude Code, Codex, Antigravity CLI (agy), and OpenCode. Trigger even when the user names neither a session ID nor a harness — figuring those out is this skill's job.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐⭐ 219 on GitHubGitHub ↗

Popular

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

save-session

Stop losing track of your AI coding sessions.

You are deep in one coding-agent session, switch tools for another task, and a week later cannot remember which session had the useful context—or how to get back into it. Session ids are opaque, each harness resumes differently, and using the wrong directory can open another project's history.

save-session gives every supported coding agent the same simple workflow: bookmark the session you are in under a name you will remember, then find and resume it later with the exact command and working directory handed back to you.

save this session — project is "heap benchmark"     →  one bookmark written
show me my saved sessions                            →  saved work listed
resume the heap benchmark session                    →  exact command + working directory

Why install it?

  • One skill, five harnesses. Use the same requests in Pi, Claude Code, Codex, Antigravity CLI, and OpenCode.
  • It never guesses. If detection is uncertain, it asks before saving or presenting a session as the right one.
  • No ids or flags to memorize. Ask by project name and get the harness's native resume command.
  • Plain text on your machine. Bookmarks are small, human-readable Markdown files. The skill adds no server, account, or hosted database.

Install

For Agent Skills-compatible harnesses, including Codex and OpenCode:

npx skills add jemshit/save-session -g

Omit -g to install only for the current project.

For Claude Code as a plugin:

claude plugin marketplace add jemshit/save-session
claude plugin install save-session@save-session

For Pi:

pi install git:github.com/jemshit/save-session

How it works

Save detects the current session id, model, and working directory, then stores one bookmark under the project title you provide. If the same session already has another title, it asks whether to keep or replace it. If another session uses the same title, it safely adds - 2, - 3, and so on. Similar-looking titles are shown for confirmation instead of being merged automatically.

Find and resume searches by project title or lists the current harness's bookmarks, then returns the exact native resume command and the directory to run it from. Finding is read-only.

Records live in one Markdown file per harness under ~/.agents/memories/sessions/ because session ids do not translate across harnesses. Set AGENTS_MEMORIES_DIR to use another location.

# Sessions — Pi

## heap benchmark
- saved: 2026-10-16T23:40:00Z
- session_id: 11111111-2222-3333-4444-555555555555
- model: provider/model-name
- dir: <absolute path to the project>

Supported harnesses

HarnessSession detectionResume command
PiCurrent PI_SESSION_IDpi --session <id>
Claude CodeEnvironment hint validated against the project transcript when availableclaude --resume <id>
CodexLocal rollout matched to the current working directorycodex resume <id>
Antigravity CLIOlder conversation cache; newer installs currently require an explicit idagy --conversation <id>
OpenCodeopencode session list or the local session storeopencode --session <id>

License

MIT — see LICENSE.

// HOW IT'S BUILT

// FILES

9 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skills/save-session/SKILL.md18 KB3cece0c6192fupstream ↗
    ---
    name: save-session
    description: Save the active coding session (session ID, model, working directory) to a per-harness markdown record under ~/.agents/memories/sessions/, and later find a saved session by project title and tell the user exactly how to resume it. USE THIS SKILL whenever the user wants to save, bookmark, or remember a session or session id ("save this session", "remember this session", "store my session id", "note down where we were"), or asks to get back into earlier work ("resume the X session", "find the session for X", "continue where we left off on X", "which session were we doing X in", "what's my session id for X", "how do I get back into X"). Applies to Pi, Claude Code, Codex, Antigravity CLI (agy), and OpenCode. Trigger even when the user names neither a session ID nor a harness — figuring those out is this skill's job.
    license: MIT
    metadata:
      author: "Jemshit Iskanderov"
      version: "0.2.0"
    ---
    
    # save-session
    
    Two modes:
    
    1. **save** — record the current session under a project title so future-you can find it.
    2. **find & resume** — look up saved sessions by project title and hand the user the exact resume command.
    
    ## Where records live
    
    Destination resolution, in order:
    
    1. A destination the request explicitly names (useful for testing or project-local notes).
    2. The `AGENTS_MEMORIES_DIR` environment variable, if set.
    3. Default: `~/.agents/memories/sessions/` (create it if missing).
    
    Sessions are owned by the harness that created them — a Pi session id means nothing to
    Codex, and each harness stores and resumes sessions its own way. That is why records get
    **one file per harness**, so a lookup never mixes id spaces:
    
    ```
    ~/.agents/memories/sessions/
    ├── pi.md
    ├── claude-code.md
    ├── codex.md
    ├── antigravity.md
    └── opencode.md
    ```
    
    ## Record format
    
    Keep entries to exactly these four fields — this is a lookup index, not a journal. Notes,
    summaries, and reflections belong in the project itself.
    
    ```markdown
    # Sessions — Pi
    
    ## DataStructures heap benchmark
    - saved: 2026-10-16T23:40:00Z
    - session_id: 11111111-2222-3333-4444-555555555555
    - model: provider/model-name
    - dir: <absolute path to the project>
    ```
    
    - `saved` — current UTC timestamp, ISO-8601 (`YYYY-MM-DDTHH:MM:SSZ`). Use the
      `saved` value returned by `detect_session.py`; never supply a date from model knowledge.
    - `session_id` — exactly what the harness's resume command expects.
    - `model` — the model the session runs on (e.g. `provider/model`). If genuinely
      undetectable, omit the line rather than inventing one.
    - `dir` — absolute working directory; most harnesses can only resume from the right place.
    
    The file's top heading names the harness (`# Sessions — Pi`, `# Sessions — Claude Code`,
    `# Sessions — Codex`, `# Sessions — Antigravity`, `# Sessions — OpenCode`). Entries are
    appended oldest-first; file order is the timeline.
    
    ## Entry identity and title handling
    
    A record entry is identified by its **`session_id`**, not its title — the id is what a
    resume command consumes; the title is only the human-facing label. `save_session.py` enforces
    these rules without printing the ledger into the agent's context:
    
    - **Already recorded → update, don't append.** Refresh that entry's `saved` timestamp and
      correct `model`/`dir` if they changed. Keep the entry in place (file order is the
      timeline; `saved` shows freshness). Say plainly in your reply that you updated the
      existing entry rather than created a new one. The one exception: a *different title* —
      next bullet.
    - **Already recorded under a *different title* → ask first, never silently retitle.** Say:
      this session is already saved as "<existing title>" — and ask whether to **ignore**
      (keep the existing entry exactly as it is) or **replace** (retitle the entry to the new
      title and refresh its `model`, `dir`, and `saved` date). One entry per session id, always; the
      `- N` numbering is only for *different* session ids sharing a title.
    - **Not recorded → append.** The project title comes from the user and is required — ask
      for it if the request doesn't include one; keep the user's wording. If that title already
      exists in the same file **on a different session**, number the new one instead of
      overwriting: `My Project`, `My Project - 2`, `My Project - 3`, … (highest existing
      suffix + 1). Several live sessions on one project is normal; each gets its own entry so a
      later lookup can show all of them.
    - **Similar but non-identical title → ask first.** Case/whitespace-only differences and a
      single insertion, deletion, or substitution may be a typo. The script reports the nearby
      titles but never merges them. The user can choose an existing exact spelling or keep the
      requested spelling with `--accept-similar`.
    
    ## Harness reference
    
    First establish which harness you are running in (your own environment tells you; if in
    doubt, ask the user). Then use that harness's row only — foreign environment variables from
    another tool's installer are not evidence. The table doubles as the no-shell fallback;
    `scripts/detect_session.py` is the authority — when a harness changes its storage, update
    both together (three of the five are pure file reads, so the table stays useful).
    
    | Harness | Record file | Session ID | Model | Resume |
    |---|---|---|---|---|
    | Pi | `pi.md` | env `PI_SESSION_ID` | env `PI_PROVIDER` + `PI_MODEL` | `pi --session <id>` (TUI `/resume` opens the picker) |
    | Claude Code | `claude-code.md` | env `CLAUDE_CODE_SESSION_ID`, checked against `<config>/projects/<project>/<uuid>.jsonl` when available | latest assistant `message.model` in that transcript | `claude --resume <id>` (TUI: `/resume <id>`) |
    | Codex | `codex.md` | `$CODEX_HOME/sessions/**/rollout-*-<uuid>.jsonl` whose metadata records this working directory | latest `turn_context.payload.model` | `codex resume <id>` |
    | Antigravity CLI | `antigravity.md` | `~/.gemini/antigravity-cli/cache/last_conversations.json` (older installs); newer installs use `projects.json` + a private SQLite store, not yet readable here | `model` in `~/.gemini/antigravity-cli/settings.json` (the default, not per-session) | `agy --conversation <id>` (TUI: `/resume`) |
    | OpenCode | `opencode.md` | `opencode session list --format json` or DB `session_v2.id` | `session_v2.model` column | `opencode --session <id>` (TUI: `/sessions`) |
    
    Per-harness detection details:
    
    - **Pi** exposes everything: `PI_SESSION_ID`, `PI_MODEL`, `PI_PROVIDER`, `PI_SESSION_FILE`.
      Combine provider and model as `provider/model`. Exact-ID resume is `pi --session <id>`;
      `/resume` is a picker and does not take an id.
    - **Claude Code** exposes `CLAUDE_CODE_SESSION_ID` to tool subprocesses. Validate it against
      the matching transcript when possible because after `--continue` or an argument-free
      `--resume` it can still name the startup session. Transcripts live under
      `${CLAUDE_CONFIG_DIR:-~/.claude}/projects/<project>/<session-uuid>.jsonl`; the project
      directory can be overridden with `CLAUDE_CODE_PROJECT_DIR_NAME`. Match every candidate's
      `cwd` field exactly because different paths can produce the same slug. The current model is
      the latest assistant `message.model`, and the transcript schema is internal. Claude's local
      transcript retention defaults to a finite window and persistence can be disabled, so this
      ledger bookmarks an id; it does not preserve the underlying conversation.
    - **Codex** keeps one rollout file per session:
      `${CODEX_HOME:-~/.codex}/sessions/<YYYY>/<MM>/<DD>/rollout-<timestamp>-<session-uuid>.jsonl`.
      The first UUID in the filename is the resumable conversation id. Require an exact `cwd`
      match in the rollout metadata; if none matches, fail rather than returning another project's
      newest session. `session_meta` records the working directory and provider; the latest
      `turn_context` record carries the model.
    - **Antigravity CLI (agy)** keeps a workspace-keyed cache:
      `~/.gemini/antigravity-cli/cache/last_conversations.json` maps absolute path → current
      conversation id. Conversation history is scoped to the working directory, which is why
      `dir` matters here more than anywhere else. Newer releases replaced that file with a
      `projects.json` workspace→project mapping and moved conversation data into a private
      SQLite store; this skill cannot read that format yet, so when only `projects.json` is
      present it reports the gap by name rather than guessing at an unpublished schema — pass
      `--id`, or read it from the `/resume` picker, until this is updated against a live install.
    - **OpenCode** stores sessions in `opencode.db` (SQLite, table
      `session_v2` with `id`, `model` JSON, `directory`, `time_updated`, among many other columns)
      and exposes them via `opencode session list --format json`. Confirmed against OpenCode v2.
      The database's location is resolved in priority order: an explicit `OPENCODE_DB` wins
      outright; otherwise `opencode debug paths db` is the tool's own authoritative answer and
      wins outright too — a release channel (stable vs. a beta/nightly build) can relocate the
      data directory, and merging in a different database's rows could surface a stale session as
      current. `XDG_DATA_HOME`, or `~/.local/share/opencode/` by default on Linux, macOS, and
      Windows (`%USERPROFILE%\.local\share\opencode` there), is used only when neither can answer.
      Some OpenCode 1.x builds replaced this with a JSON-file store under
      `storage/{project,session,message}/` and dropped the `session list` command entirely; if
      detection unexpectedly reports no session despite one existing, check `opencode --version`
      and upgrade before assuming this skill is wrong.
    
    ## Detecting without a shell
    
    Prefer environment values and direct file reads — they work in headless or permission-restricted
    contexts. This matters more than it looks: some harnesses (Antigravity CLI in headless mode)
    **auto-deny a shell command and abort the whole run**, so reaching for a shell unnecessarily can
    kill the task before it starts.
    
    Order of attack:
    
    1. **Authoritative environment values first** — Pi exposes the current id directly. Claude's
       env id is useful but remains heuristic until its transcript validates it.
    2. **File reads first after that** — the session stores listed above are ordinary
       JSON/JSONL/SQLite files. Read the JSON ones directly for Claude Code, Codex, and
       Antigravity. OpenCode's documented JSON CLI is preferred over its private SQLite schema.
    3. **Shell only when it is the remaining path** (Pi env inspection or the OpenCode CLI/SQLite)
       — and only when you already know commands run in this context.
    4. **If a command is denied, do not retry it.** Fall back to file reads, or tell the user
       what you could not detect and ask for the id. A permission denial is information, not
       an obstacle to route around.
    
    `scripts/detect_session.py` (in this skill's directory) automates all of the above with
    fallbacks, but it is a fast path, not the procedure:
    
    ```bash
    python3 <skill-dir>/scripts/detect_session.py --harness <pi|claude-code|codex|antigravity|opencode>
    # → {"ok": true, "heuristic": false, "saved": ..., "records_dir": ..., ...}
    #                                                    (authoritative, currently Pi)
    # → {"ok": true, "heuristic": true, ...}           (working-directory/store heuristic — disclose it)
    # → {"ok": false, "reason": "..."} + exit code 1   (a missing id is never guessed)
    python3 <skill-dir>/scripts/detect_session.py --check   # verify record files; exits non-zero on duplicate ids or unreadable files
    ```
    
    (`python3` above; on Windows the interpreter is usually `python` or `py`. The scripts are
    plain standard-library Python and run on Linux, macOS, and Windows.)
    
    **Interpreter, everywhere in this file:** any `python3` below means `python` or `py -3` on
    Windows.
    
    If detection still fails, say so plainly and ask the user for the id (Pi: `/session`,
    Claude Code: `CLAUDE_CODE_SESSION_ID` from a tool subprocess or the `/resume` picker,
    Codex: `/status`, agy: the `/resume` picker, OpenCode: `/sessions`) — a
    missing `model` is fine to omit, but never fabricate a session id.
    
    ## Mode 1 — save
    
    1. Get the project title from the user (required), then run the bundled writer. Pass the harness
       you are running in, any id named by the request, and `--sessions-dir` when the request names a
       destination; environment auto-detection is only a fallback:
    
       ```bash
       python3 <skill-dir>/scripts/save_session.py --title "<project title>" --harness <harness> [--id <id>] [--sessions-dir <dir>]
       ```
    
       Do **not** read the record file or the script source during a normal save. The writer performs
       exact-id lookup, validation, numbering, locking, and atomic replacement internally and prints
       one compact JSON object. Exit `0` means completed, exit `1` means an error and no write, and
       exit `2` means `needs_confirmation` and no write.
    2. Interpret the result:
       - `created` / `updated` → report the returned title, id, and file.
       - `confirm_detected_session` → show the detected id and source; after the user confirms,
         rerun with that exact `--id`. A working-directory/store result can be stale when several
         sessions share a directory.
       - `session_has_different_title` → ask **ignore** or **replace**. On **ignore**, do not call
         the script again: report that the returned `existing_title` remains unchanged and nothing
         was written. On **replace**, rerun with `--replace-title`.
       - `similar_title` → show the returned nearby titles. Rerun with the chosen exact spelling,
         or with the requested spelling plus `--accept-similar` if the user wants it kept separate.
       - `record_locked` → confirm no save operation is still running; only then remove the exact
         lock file reported by the script and retry. Never remove another harness's lock.
       - any other error → report it; do not edit the Markdown as a workaround.
    3. Confirm in your reply: title, session id, file, and whether the script created, updated,
       replaced, or ignored the entry.
    
    A user-provided id still wins verbatim. A local `validated: false` can mean the session came
    from another machine; surface it, but do not substitute another id. Without a runnable Python
    interpreter, follow the same rules manually as a last resort and validate with
    `detect_session.py --check` when execution becomes available.
    
    `--ignore-existing` remains available for a programmatic caller that explicitly wants a locked,
    structured revalidation of the no-op. The normal agent flow does not use it.
    
    ## Mode 2 — find & resume
    
    1. Extract what the user wants: a **lookup by name** ("resume the X session"), or a **listing**
       ("what sessions do I have saved", "show me my sessions"). **No name at all** ("resume my
       session", "get me back in") → list the current harness's entries with `--list` and ask
       which one — never silently pick.
    2. Use the bundled script for either (it never modifies records):
    
       ```bash
       python3 <skill-dir>/scripts/find_session.py --list --json         # current harness (auto-detects; --harness/--all to override)
       python3 <skill-dir>/scripts/find_session.py --title "<project name>" [--pick latest] --json
       python3 <skill-dir>/scripts/find_session.py --session-id <id> --json
       # → {"matches": [{"file", "harness", "title", "session_id", "model", "dir", "saved", "resume"}]}
       # no matches: exit code 1 — say so plainly rather than guessing
       ```
    
       Without a shell, read the record files directly: match `##` headings
       case-insensitively (substring in either direction), or list every entry in the
       current harness's file, sorted by `saved`.
    
       `--list` needs to know which harness it is listing: it takes the environment hint
       (Pi's `PI_SESSION_ID`, Claude Code's session env, OpenCode's `OPENCODE`) or an explicit
       `--harness` / `--all`. When
       neither is available it stops and asks — **never guess which harness**, because session
       ids do not translate across harnesses and a wrong guess lists an unrelated history.
    3. Show the matches: title, harness file, `saved`, `session_id`, `model`, `dir`. When
       several entries match — same title, different session ids; several live sessions on
       one project are normal (`Finance cashflow` and `Finance cashflow - 2` must both be
       listed, each with its own id) — list **every one** sorted by `saved`, recommend the
       most recently saved, and let the user pick a different one when they know better
       (a saved timestamp can be stale if the session kept running after its last save).
    4. Pick one (the recommendation by default; the user chooses if ambiguous) and give the
       **exact resume command** for its harness with the id filled in.
    5. Because resuming is usually directory-scoped, also tell the user the `dir` to `cd` into
       first.
    
    Finding never modifies records. If the record files look emptier than expected (entries
    or whole files missing — it happens), say so instead of silently proceeding: quiet loss is
    the one failure the save flow cannot see by itself (`detect_session.py --check` lists what
    exists).
    
    ## Rules
    
    - **Resuming belongs to the user.** Mode 2's deliverable is the exact command line for
      the user to run in their harness — print it in a code block. Don't spawn interactive
      harness processes to "test" resumption; if a context genuinely supports scripted
      resumption, the user will ask for it.
    - Never overwrite, edit, or delete a *different session's* entry. The only writes are:
      appending a new session's entry, and updating a session's *own* entry (same `session_id`).
    - Ask only for what is missing — normally just the project title. Don't interrogate the
      user for values you can detect.
    - Session records are not a place for secrets: no tokens, keys, or credentials, ever.
    
    ## Reference
    
    - `references/decision-flow.md` — the same decision logic as Mermaid figures, one per mode,
      with every interaction point marked. It is derived from this file, so edit both together
      and run `python3 scripts/check_flow_doc.py`, which fails when a decision point is
      documented on only one side.
    
  • skills/save-session/scripts/check_flow_doc.py13 KB51884eafa60dupstream ↗
    #!/usr/bin/env python3
    """Check that references/decision-flow.md and SKILL.md still agree.
    
    Three kinds of check:
    
    1. Structural — each mermaid block declares a flowchart, has balanced quoting, and every
       node referenced on an edge is declared somewhere in that block. Catches the class of
       typo that makes GitHub render an error box instead of a diagram.
    
    2. Coverage — a declarative list of the skill's decision points, each paired with the
       phrase that must appear in SKILL.md and the phrase that must appear in the flow doc.
       If a rule is dropped from either side, the check fails. SKILL.md stays authoritative.
    
    3. Completeness — the part that stops this file from quietly going stale:
       - every numbered step under Mode 1 and Mode 2 in SKILL.md must be mapped to at least one
         decision point, so a newly added step fails the check until someone covers it;
       - every `## ` section in SKILL.md must be either represented by a figure or explicitly
         declared out of scope, so a newly added section cannot pass unnoticed.
    
    Markdown emphasis, backticks and line wrapping are normalized away before matching, so a
    pattern can be written the way a human reads it. This is a lint, not a proof: it verifies
    that each decision point is still *mentioned* on both sides, not that the wording is
    semantically equivalent.
    
    Usage:
        python3 scripts/check_flow_doc.py            # human report (python/py -3 on Windows)
        python3 scripts/check_flow_doc.py --json     # machine-readable
    Exit code 0 when every check passes, 1 otherwise.
    """
    import json
    import re
    import sys
    from pathlib import Path
    
    SKILL_DIR = Path(__file__).resolve().parent.parent
    SKILL_MD = SKILL_DIR / "SKILL.md"
    FLOW_MD = SKILL_DIR / "references" / "decision-flow.md"
    
    # (id, phrase required in SKILL.md, phrase required in references/decision-flow.md)
    DECISION_POINTS = [
        # detection strategy order (Figure 3)
        ("det-file-reads-first", "file reads first", "read the harness store directly"),
        ("det-no-retry-denied", "do not retry it", "do not retry it"),
        ("det-ask-fallback", "ask the user for the id", "ask - the user can read it"),
        # artifact shape
        ("entry-shape-heading", "# sessions —", "# sessions —"),
        ("entry-shape-four-fields", "exactly these four fields", "exactly the four fields"),
        ("entry-shape-create-file", "file's top heading names", "create the file with its top heading"),
        ("entry-shape-timeline", "file order is the timeline", "file order is the timeline"),
        # Mode 1 - save
        ("m1-user-id-wins", "wins verbatim", "provided id verbatim"),
        ("m1-heuristic-confirms", "confirm_detected_session", "confirm_detected_session"),
        ("m1-title-required", "project title from the user", "ask - project title"),
        ("m1-title-supplied-bypass", "if the request doesn't include one", "did the request already"),
        ("m1-update-same-title", "update, don't append", "updated in place"),
        ("m1-ask-ignore-replace", "ignore", "ignore or replace"),
        ("m1-replace-path", "--replace-title", "--replace-title"),
        ("m1-ignore-path", "do not call\n     the script again", "do not rerun the script"),
        ("m1-numbering", "highest existing suffix", "highest existing suffix"),
        ("m1-confirm-reply", "title, session id", "title, session id"),
        ("m1-script-writes", "do **not** read the record file", "do not read the ledger"),
        ("m1-similar-title", "similar_title", "similar_title"),
        ("m1-lock-error", "record_locked", "record_locked"),
        # Mode 2 - find and resume
        ("m2-by-title", "find_session.py --title", "find_session.py --title"),
        ("m2-listing", "--list", "--list"),
        ("m2-bare-resume", "no name at all", "no name at all"),
        ("m2-never-silent-pick", "never silently pick", "let the user choose"),
        ("m2-refuse-guess-harness", "never guess which harness", "never guess the harness"),
        ("m2-recommend-newest", "most recently saved", "mark the newest as recommended"),
        ("m2-deliver-command", "exact resume command", "print the exact resume command"),
        ("m2-cd-dir", "`dir` to `cd` into", "cd dir"),
        ("m2-never-writes", "never modifies records", "never modified"),
        ("m2-entry-loss-announced", "say so instead of silently proceeding", "say so instead of proceeding"),
        # shared invariants
        ("inv-one-file-per-harness", "one file per harness", "one record file per harness"),
        ("inv-entry-identity", "identified by its **`session_id`**", "identified by its `session_id`"),
        ("inv-never-fabricate", "never fabricate", "never fabricate"),
        ("inv-destination-order", "AGENTS_MEMORIES_DIR", "AGENTS_MEMORIES_DIR"),
        ("inv-no-secrets", "no tokens, keys, or credentials", "no secrets"),
        ("inv-ask-only-missing", "ask only for what is missing", "ask only for what is missing"),
        ("inv-resuming-belongs-to-user", "resuming belongs to the user", "resuming stays with the user"),
    ]
    
    MODE1_STEPS = {
        1: ["m1-title-required", "m1-script-writes", "m1-user-id-wins"],
        2: ["m1-heuristic-confirms", "m1-ask-ignore-replace", "m1-replace-path",
            "m1-ignore-path", "m1-similar-title", "m1-lock-error"],
        3: ["m1-confirm-reply"],
    }
    
    MODE2_STEPS = {
        1: ["m2-by-title", "m2-listing", "m2-bare-resume"],
        2: ["m2-listing", "m2-refuse-guess-harness", "det-file-reads-first"],
        3: ["m2-never-silent-pick", "m2-recommend-newest"],
        4: ["m2-never-silent-pick", "m2-deliver-command"],
        5: ["m2-cd-dir", "inv-resuming-belongs-to-user"],
    }
    
    # Every `## ` section in SKILL.md must be represented by a figure, or declared here.
    OUT_OF_SCOPE = {
        "where records live": "destination order and the file list live in the invariant table and the SKILL.md harness table",
        "record format": "artifact shape, documented in the Entry shape section of this file",
        "harness reference": "lookup table; resume commands are authoritative in find_session.py",
        "detecting without a shell": "strategy order is Figure 3",
        "reference": "documentation pointers, no decisions",
        "rules": "each rule is listed in the invariants table",
        "entry identity and title handling": "Figure 1 plus the invariant table",
        "mode 1 — save": "Figure 1",
        "mode 2 — find & resume": "Figure 2",
    }
    
    
    def normalize(text):
        """Drop markdown emphasis/backticks and collapse whitespace so phrases match by eye."""
        text = text.replace("**", " ").replace("`", " ").replace("*", " ")
        text = re.sub(r"^\s*[-#>]+\s*", " ", text, flags=re.M)
        return re.sub(r"\s+", " ", text).lower().strip()
    
    
    def strip_fences(text):
        """Remove fenced code blocks so headings/step numbers inside examples are ignored."""
        return re.sub(r"```.*?```", "", text, flags=re.S)
    
    
    def mermaid_blocks(text):
        return re.findall(r"```mermaid\n(.*?)```", text, flags=re.S)
    
    
    def check_structure(flow_text):
        """Structural problems that break rendering. Returns a list of error strings."""
        errors = []
        blocks = mermaid_blocks(flow_text)
        if not blocks:
            return ["no mermaid blocks found in the flow doc"]
        for i, block in enumerate(blocks, 1):
            lines = [ln.strip() for ln in block.splitlines() if ln.strip() and not ln.strip().startswith("%%")]
            if not lines:
                errors.append(f"figure {i}: empty block")
                continue
            if not re.match(r"^(flowchart|graph)\s+(TD|TB|LR|RL|BT)\b", lines[0]):
                errors.append(f"figure {i}: does not start with a flowchart declaration: {lines[0]!r}")
            declared, referenced = set(), set()
            for ln in lines[1:]:
                if ln.count('"') % 2:
                    errors.append(f"figure {i}: unbalanced quotes in {ln!r}")
                for node_id in re.findall(r"([A-Za-z_][A-Za-z0-9_]*)\s*(?:\[|\{|\(|>|\(\[)", ln):
                    declared.add(node_id)
                for node_id in re.findall(r"([A-Za-z_][A-Za-z0-9_]*)\s*-->", ln):
                    referenced.add(node_id)
                for node_id in re.findall(r"-->\s*\|[^|]*\|\s*([A-Za-z_][A-Za-z0-9_]*)", ln):
                    referenced.add(node_id)
                for node_id in re.findall(r"-->\s*([A-Za-z_][A-Za-z0-9_]*)", ln):
                    referenced.add(node_id)
            for node_id in sorted(referenced - declared):
                errors.append(f"figure {i}: node {node_id!r} used on an edge but never declared")
            for node_id in sorted(declared):
                if not re.search(rf"\b{re.escape(node_id)}\b", block):
                    errors.append(f"figure {i}: node {node_id!r} declared but never used")
        return errors
    
    
    def check_coverage(skill_text, flow_text):
        skill, flow = normalize(skill_text), normalize(flow_text)
        results = []
        for rule_id, skill_phrase, flow_phrase in DECISION_POINTS:
            results.append({
                "id": rule_id,
                "skill_phrase": skill_phrase,
                "skill_ok": normalize(skill_phrase) in skill,
                "flow_phrase": flow_phrase,
                "flow_ok": normalize(flow_phrase) in flow,
            })
        return results
    
    
    def numbered_steps(text, heading, next_heading):
        """Step numbers of the top-level numbered list inside a section."""
        start = text.find(heading)
        end = text.find(next_heading) if next_heading else -1
        section = text[start:end] if start != -1 and end != -1 else text[start:]
        return sorted({int(m.group(1)) for m in re.finditer(r"^(\d+)\.\s", section, flags=re.M)})
    
    
    def check_completeness(skill_text, known_rule_ids):
        """Every step and every section must be accounted for. Returns a list of errors."""
        errors = []
        bare = strip_fences(skill_text)
    
        for heading, next_heading, mapping, label in (
            ("## Mode 1 — save", "## Mode 2", MODE1_STEPS, "Mode 1"),
            ("## Mode 2 — find & resume", "## Rules", MODE2_STEPS, "Mode 2"),
        ):
            steps = numbered_steps(bare, heading, next_heading)
            if not steps:
                errors.append(f"{label}: no numbered steps found under {heading!r}")
            for step in steps:
                if step not in mapping:
                    errors.append(f"{label} step {step} is not mapped to a decision point in check_flow_doc.py")
                    continue
                for rule_id in mapping[step]:
                    if rule_id not in known_rule_ids:
                        errors.append(f"{label} step {step} maps to unknown decision point {rule_id!r}")
            for step in mapping:
                if step not in steps:
                    errors.append(f"{label} step {step} is mapped here but no longer exists in SKILL.md")
    
        for heading in re.findall(r"^##\s+(.+?)\s*$", bare, flags=re.M):
            if heading.strip().lower() not in OUT_OF_SCOPE:
                errors.append(
                    f"SKILL.md section {heading!r} is neither represented by a figure nor declared "
                    f"out of scope in check_flow_doc.py"
                )
        for heading in OUT_OF_SCOPE:
            if heading not in {h.strip().lower() for h in re.findall(r"^##\s+(.+?)\s*$", bare, flags=re.M)}:
                errors.append(f"declared section {heading!r} no longer exists in SKILL.md")
        return errors
    
    
    def main():
        for path in (SKILL_MD, FLOW_MD):
            if not path.exists():
                sys.exit(f"missing {path}")
        skill_text, flow_text = SKILL_MD.read_text(encoding="utf-8"), FLOW_MD.read_text(encoding="utf-8")
    
        structural = check_structure(flow_text)
        coverage = check_coverage(skill_text, flow_text)
        completeness = check_completeness(skill_text, {c[0] for c in DECISION_POINTS})
        failed = [c for c in coverage if not (c["skill_ok"] and c["flow_ok"])]
        ok = not structural and not failed and not completeness
    
        if "--json" in sys.argv:
            print(json.dumps({
                "ok": ok,
                "structural_errors": structural,
                "completeness_errors": completeness,
                "coverage": coverage,
            }, indent=2))
            sys.exit(0 if ok else 1)
    
        steps_mapped = sum(len(v) for v in MODE1_STEPS.values()) + sum(len(v) for v in MODE2_STEPS.values())
        print(f"{SKILL_MD.name} <-> {FLOW_MD.name}")
        print(f"  mermaid figures:  {len(mermaid_blocks(flow_text))}")
        print(f"  decision points:  {len(coverage)}")
        print(f"  mapped steps:     {len(MODE1_STEPS)} + {len(MODE2_STEPS)} (Mode 1 + Mode 2), {steps_mapped} mappings")
        print(f"  sections declared out of scope: {len(OUT_OF_SCOPE)}")
        if structural:
            print("\nSTRUCTURAL ERRORS")
            for e in structural:
                print(f"  - {e}")
        if failed:
            print("\nDRIFT (a decision point is documented on one side only)")
            for c in failed:
                missing = []
                if not c["skill_ok"]:
                    missing.append(f"SKILL.md is missing {c['skill_phrase']!r}")
                if not c["flow_ok"]:
                    missing.append(f"decision-flow.md is missing {c['flow_phrase']!r}")
                print(f"  - {c['id']}: " + "; ".join(missing))
        if completeness:
            print("\nCOMPLETENESS (a step or section is unaccounted for)")
            for e in completeness:
                print(f"  - {e}")
        print("\n" + ("OK - the flow doc matches SKILL.md" if ok else "FAIL - see above"))
        sys.exit(0 if ok else 1)
    
    
    if __name__ == "__main__":
        main()
    
  • skills/save-session/scripts/detect_session.py38 KBcc00395aafb2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skills/save-session/scripts/find_session.py10.0 KB9dcfcf4310c4upstream ↗
    #!/usr/bin/env python3
    """Find, list, and resume-match saved sessions.
    
    Usage:
        find_session.py --title "finance cashflow"               # find by title (all files)
        find_session.py --title "..." --harness pi               # ...within one harness's file
        find_session.py --title "..." --pick latest              # ...only the newest match of that title
        find_session.py --session-id <id>                        # exact id lookup
        find_session.py --list                                    # list this harness's saved entries
        find_session.py --list --harness <harness>               # list one harness's entries
        find_session.py --list --all                             # list every harness's entries
    
    `--list` auto-detects the *current* harness from environment hints for Pi,
    Claude Code, and OpenCode, and lists every saved entry in that harness's record
    file with its exact resume command. Without an env hint it refuses to guess and
    asks for --harness or --all. Passing --title too filters the listing. Reads only
    — record files are never modified here.
    
    Prints JSON: {"matches": [{"file", "harness", "title", "session_id",
    "model", "dir", "saved", "resume"}]} and a human summary. No matches: exit 1.
    """
    import argparse
    import json
    import os
    import re
    import sys
    from pathlib import Path
    
    SCRIPT_DIR = Path(__file__).resolve().parent
    if str(SCRIPT_DIR) not in sys.path:
        sys.path.insert(0, str(SCRIPT_DIR))
    
    import record_store as store
    
    HARNESS_BY_FILE = store.HARNESS_BY_FILE
    
    RESUME = {
        "pi": "pi --session {sid}",
        "claude-code": "claude --resume {sid}",
        "codex": "codex resume {sid}",
        "antigravity": "agy --conversation {sid}",
        "opencode": "opencode --session {sid}",
    }
    
    
    def sessions_dir():
        # expanduser: ``AGENTS_MEMORIES_DIR=~/.agents/...`` is natural to write and PowerShell
        # does not expand it, so without this the script silently looks in a literal ./~ dir.
        raw = os.environ.get("AGENTS_MEMORIES_DIR", str(Path.home() / ".agents/memories/sessions"))
        return Path(os.path.expanduser(raw))
    
    
    def auto_harness():
        """The current harness from env hints only — never a guess."""
        if os.environ.get("PI_SESSION_ID"):
            return "pi"
        if os.environ.get("CLAUDE_CODE_SESSION_ID") or os.environ.get("CLAUDECODE"):
            return "claude-code"
        if os.environ.get("OPENCODE"):
            return "opencode"
        return None
    
    
    def harness_of(path, text):
        # Case-insensitive filename lookup: on case-insensitive filesystems a record file can be
        # named Pi.md, and a miss here would silently produce an entry with no resume command.
        known = HARNESS_BY_FILE.get(path.name.lower())
        if known:
            return known
        lines = text.splitlines()
        m = re.match(r"^#\s+Sessions\s+—\s+(.+)$", (lines[0] if lines else "").lstrip(""), re.I)
        if m:
            return m.group(1).strip().lower().replace(" ", "-")
        return path.stem
    
    
    def entry_pairs(parsed):
        entries = []
        for entry in parsed:
            fields = dict(entry["fields"])
            if entry["duplicates"]:
                fields["_invalid"] = True
            entries.append((entry["title"], fields))
        return entries
    
    
    def parse_entries(text):
        """(entries, problems) where entries are (title, fields) pairs.
    
        A heading carrying two `session_id:` lines means two sessions share one entry, and keeping
        the last value silently loses the first id — so it is reported instead. This happened here:
        a malformed record merged two sessions and a session id vanished without a word.
        """
        parsed, problems = store.parse_record(text)
        entries = entry_pairs(parsed)
        return entries, problems
    
    
    def to_match(f, harness, title, fields):
        sid = fields.get("session_id")
        template = RESUME.get(harness)
        return {
            "file": f.name,
            "harness": harness,
            "title": title,
            "session_id": sid,
            "model": fields.get("model"),
            "dir": fields.get("dir"),
            "saved": fields.get("saved"),
            # None rather than an empty string when the harness or the id is unknown: an empty
            # resume command reads like a valid answer.
            "resume": template.format(sid=sid) if (template and sid and not fields.get("_invalid")) else None,
        }
    
    
    def main():
        try:
            # Piped stdout on Windows uses the locale codec (cp1252); a non-ASCII title would
            # raise there, and agents always capture output through a pipe.
            sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        except (AttributeError, OSError):
            pass
        ap = argparse.ArgumentParser(description="Find and list saved sessions")
        ap.add_argument("--title", default=None, help="project title to look up (filters --list too)")
        ap.add_argument("--session-id", default=None, help="exact session id to look up")
        ap.add_argument("--list", action="store_true", help="list saved entries")
        ap.add_argument("--harness", choices=sorted(set(HARNESS_BY_FILE.values())), default=None)
        ap.add_argument("--sessions-dir", default=None)
        ap.add_argument("--pick", choices=["latest", "all"], default="all",
                        help="latest: only the most recently saved match of a --title lookup")
        ap.add_argument("--all", action="store_true", help="with --list: every harness's file")
        ap.add_argument("--json", action="store_true",
                        help="print compact JSON only, without the human summary")
        args = ap.parse_args()
    
        if not args.title and args.session_id is None and not args.list:
            ap.error("nothing to do: pass --title <name>, --session-id <id>, or --list")
        if args.title is not None and not args.title.strip():
            ap.error("--title needs a non-empty value; a blank title would match every entry")
        if args.session_id is not None and not args.session_id.strip():
            ap.error("--session-id needs a non-empty value")
        if args.session_id is not None and (args.title is not None or args.list):
            ap.error("--session-id is mutually exclusive with --title and --list")
        if args.all and args.harness:
            ap.error("--all and --harness are mutually exclusive")
        if args.all and not args.list:
            ap.error("--all only makes sense with --list")
        if args.list and args.pick != "all":
            # Previously this was silently ignored, which reads as "the newest was used" when every
            # entry was in fact listed. A flag that does nothing must say so.
            ap.error("--pick applies to a --title lookup; --list shows every entry")
        if args.session_id is not None and args.pick != "all":
            ap.error("--pick applies to a --title lookup")
    
        base = Path(os.path.expanduser(args.sessions_dir)) if args.sessions_dir else sessions_dir()
    
        # --list: harness selection is current-harness by env hint, else explicit
        if args.list:
            if not args.harness and not args.all:
                detected = auto_harness()
                if detected is None:
                    sys.exit("cannot tell which harness you are in — pass --harness <name> or --all")
                args.harness = detected
    
        matches, problems = [], []
        if base.is_dir():
            try:
                files = sorted(base.glob("*.md"))
            except (OSError, RuntimeError) as exc:
                files = []
                problems.append(f"record directory unreadable ({type(exc).__name__}: {exc})")
            for f in files:
                try:
                    text = f.read_text(encoding="utf-8-sig")
                except (OSError, UnicodeError) as exc:
                    problems.append(f"{f.name}: unreadable ({type(exc).__name__}: {exc})")
                    continue
                harness = harness_of(f, text)
                expected = store.HARNESSES.get(harness, (None, None))[1]
                parsed, file_problems = store.validate_record(text, expected)
                entries = entry_pairs(parsed)
                problems += [f"{f.name}: {p}" for p in file_problems]
                if args.harness and harness != args.harness:
                    continue
                query = (args.title or "").strip().lower()
                for title, fields in entries:
                    if fields.get("_invalid"):
                        continue
                    if query:
                        lowered = title.lower()
                        if query not in lowered and lowered not in query:
                            continue
                    if args.session_id is not None and fields.get("session_id") != args.session_id:
                        continue
                    matches.append(to_match(f, harness, title, fields))
    
        matches.sort(key=lambda m: (m.get("saved") or "",))
        if matches and args.pick == "latest":
            matches = [matches[-1]]
        for m in matches:
            m["recommended"] = m is matches[-1]
    
        if args.list:
            scope = "list " + (args.harness or "all harnesses")
        elif args.session_id is not None:
            scope = f"find exact session id {args.session_id!r}"
        else:
            scope = f"find {args.title!r}"
        payload = {"sessions_dir": str(base), "scope": scope, "matches": matches}
        if problems:
            # Loud, not silent: a malformed record must not quietly lose a session id.
            payload["problems"] = problems
        print(json.dumps(payload, ensure_ascii=False,
                         separators=(",", ":") if args.json else None,
                         indent=None if args.json else 2))
        for problem in problems:
            print(f"warning: {problem}", file=sys.stderr)
        if not args.json:
            for m in matches:
                tag = "  <- most recent" if m["recommended"] and len(matches) > 1 else ""
                resume = m["resume"] or "(no session id recorded — cannot build a resume command)"
                print(f"- [{m['harness']}] {m['title']}  (saved {m['saved']})  ->  {resume}{tag}")
                if m["dir"]:
                    # State the value without pretending one shell's quoting/change-drive rules are
                    # portable to bash, PowerShell, and cmd.exe.
                    print(f'    working directory: {m["dir"]} (resume from this directory)')
        if problems:
            sys.exit(1)
        if not matches:
            print(f"no saved sessions for {scope} in {base}", file=sys.stderr)
            sys.exit(1)
    
    
    if __name__ == "__main__":
        main()
    
  • skills/save-session/scripts/record_store.py7.3 KBaf4113a22312upstream ↗
    #!/usr/bin/env python3
    """Shared parsing, validation, title handling, and atomic writes for session ledgers."""
    
    import os
    import re
    import stat
    import tempfile
    from contextlib import contextmanager
    from pathlib import Path
    
    
    HARNESSES = {
        "pi": ("pi.md", "# Sessions — Pi"),
        "claude-code": ("claude-code.md", "# Sessions — Claude Code"),
        "codex": ("codex.md", "# Sessions — Codex"),
        "antigravity": ("antigravity.md", "# Sessions — Antigravity"),
        "opencode": ("opencode.md", "# Sessions — OpenCode"),
    }
    HARNESS_BY_FILE = {filename: harness for harness, (filename, _) in HARNESSES.items()}
    RECORD_FIELDS = {"saved", "session_id", "model", "dir"}
    REQUIRED_RECORD_FIELDS = {"saved", "session_id", "dir"}
    SAVED_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")
    
    
    class RecordLocked(Exception):
        def __init__(self, path):
            self.path = Path(path)
            super().__init__(str(self.path))
    
    
    def record_path(base, harness):
        filename, _ = HARNESSES[harness]
        return Path(base) / filename
    
    
    def resolved_target(path):
        """Resolve file and directory symlinks so os.replace() updates the target, not a link."""
        return Path(path).resolve(strict=False)
    
    
    def parse_record(text, expected_heading=None):
        """Return (entries, problems). Entries preserve order and duplicate-field evidence."""
        lines = text.lstrip("").splitlines()
        entries, current, problems = [], None, []
        first = lines[0] if lines else ""
        if expected_heading is not None and first != expected_heading:
            problems.append(f"expected top heading {expected_heading!r}")
    
        for number, line in enumerate(lines[1:], 2):
            if not line:
                continue
            if line.startswith("## "):
                current = {"title": line[3:].strip(), "fields": {}, "duplicates": []}
                entries.append(current)
                continue
            if current is not None and line.startswith("- ") and ":" in line:
                key, value = (part.strip() for part in line[2:].split(":", 1))
                if key in current["fields"]:
                    current["duplicates"].append(key)
                    problems.append(
                        f"entry {current['title']!r} has duplicate field {key} — more than one {key}: line "
                        f"({current['fields'][key]!r} and {value!r}; entry is unusable)"
                    )
                current["fields"][key] = value
                continue
            problems.append(f"line {number}: unexpected content")
    
        return entries, problems
    
    
    def validate_record(text, expected_heading=None):
        """Parse a complete ledger and report every structural and field-level problem."""
        entries, problems = parse_record(text, expected_heading)
    
        ids = []
        for entry in entries:
            title, fields = entry["title"], entry["fields"]
            label = f"entry {title!r}"
            if not title:
                problems.append("entry has an empty title")
            unknown = sorted(set(fields) - RECORD_FIELDS)
            if unknown:
                problems.append(f"{label}: unknown field(s) {unknown}")
            missing = sorted(REQUIRED_RECORD_FIELDS - set(fields))
            if missing:
                problems.append(f"{label}: missing required field(s) {missing}")
            empty = sorted(key for key, value in fields.items() if key in RECORD_FIELDS and not value)
            if empty:
                problems.append(f"{label}: empty field(s) {empty}")
            saved = fields.get("saved")
            if saved and not SAVED_RE.fullmatch(saved):
                problems.append(f"{label}: saved must be UTC YYYY-MM-DDTHH:MM:SSZ")
            sid = fields.get("session_id")
            if sid:
                ids.append(sid)
    
        duplicates = sorted({sid for sid in ids if ids.count(sid) > 1})
        if duplicates:
            problems.append(f"duplicate session id(s) {duplicates} — one entry per session id is the rule")
        return entries, problems
    
    
    def render_record(heading, entries):
        lines = [heading]
        for entry in entries:
            fields = entry["fields"]
            lines.extend(["", f"## {entry['title']}", f"- saved: {fields['saved']}",
                          f"- session_id: {fields['session_id']}"])
            if fields.get("model"):
                lines.append(f"- model: {fields['model']}")
            lines.append(f"- dir: {fields['dir']}")
        return "\n".join(lines) + "\n"
    
    
    def validate_value(label, value):
        if not isinstance(value, str) or not value or value != value.strip():
            raise ValueError(f"{label} must be non-empty with no leading or trailing whitespace")
        if any(ord(ch) < 32 or ord(ch) == 127 for ch in value):
            raise ValueError(f"{label} must not contain control characters")
    
    
    def normalize_title(title):
        return " ".join(title.casefold().split())
    
    
    def within_one_edit(a, b):
        if a == b or abs(len(a) - len(b)) > 1:
            return False
        if len(a) == len(b):
            return sum(left != right for left, right in zip(a, b)) == 1
        short, long_ = (a, b) if len(a) < len(b) else (b, a)
        i = j = skipped = 0
        while i < len(short) and j < len(long_):
            if short[i] == long_[j]:
                i += 1
            else:
                skipped += 1
                if skipped > 1:
                    return False
            j += 1
        return True
    
    
    def similar_titles(requested, titles):
        wanted = normalize_title(requested)
        matches = []
        for title in titles:
            if title == requested:
                continue
            candidate = normalize_title(title)
            if candidate == wanted:
                reason = "case_or_whitespace"
            elif within_one_edit(candidate, wanted):
                reason = "one_edit"
            else:
                continue
            if not any(item["title"] == title for item in matches):
                matches.append({"title": title, "reason": reason})
        return matches
    
    
    def allocate_title(requested, titles):
        if requested not in titles:
            return requested
        suffix = re.compile(rf"^{re.escape(requested)} - ([0-9]+)$")
        highest = 1
        for title in titles:
            match = suffix.fullmatch(title)
            if match and int(match.group(1)) >= 2:
                highest = max(highest, int(match.group(1)))
        return f"{requested} - {highest + 1}"
    
    
    @contextmanager
    def record_lock(path):
        target = resolved_target(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        lock = target.with_name(target.name + ".lock")
        try:
            fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
        except FileExistsError as exc:
            raise RecordLocked(lock) from exc
        try:
            with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
                handle.write(f"pid={os.getpid()}\n")
            yield target
        finally:
            try:
                lock.unlink()
            except FileNotFoundError:
                pass
    
    
    def atomic_write(path, text):
        target = resolved_target(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        old_mode = stat.S_IMODE(target.stat().st_mode) if target.exists() else None
        fd, temporary = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)
        temporary = Path(temporary)
        try:
            with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
                handle.write(text)
                handle.flush()
                os.fsync(handle.fileno())
            if old_mode is not None:
                temporary.chmod(old_mode)
            os.replace(temporary, target)
        finally:
            try:
                temporary.unlink()
            except FileNotFoundError:
                pass
    
  • skills/save-session/scripts/save_session.py9.8 KBa9c0aba4aca0upstream ↗
    #!/usr/bin/env python3
    """Detect and safely create or update one saved-session ledger entry.
    
    Exit 0: completed. Exit 1: error, nothing written. Exit 2: confirmation required,
    nothing written. Operational results use one compact JSON object on stdout.
    """
    
    import argparse
    import json
    import os
    import sys
    from pathlib import Path
    
    SCRIPT_DIR = Path(__file__).resolve().parent
    if str(SCRIPT_DIR) not in sys.path:
        sys.path.insert(0, str(SCRIPT_DIR))
    
    import detect_session as detect
    import record_store as store
    
    
    def emit(payload, code=0):
        print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
        return code
    
    
    class JSONArgumentParser(argparse.ArgumentParser):
        def error(self, message):
            print(json.dumps({"ok": False, "status": "error", "reason": "invalid_argument",
                              "detail": message}, separators=(",", ":")))
            raise SystemExit(1)
    
    
    def auto_harness():
        if os.environ.get("PI_SESSION_ID"):
            return "pi"
        if os.environ.get("CLAUDE_CODE_SESSION_ID") or os.environ.get("CLAUDECODE"):
            return "claude-code"
        if os.environ.get("OPENCODE"):
            return "opencode"
        return None
    
    
    def detect_metadata(harness, session_id):
        if session_id is not None:
            result = detect.detect_by_id(harness, session_id)
        else:
            result = detect.HARNESSES[harness]()
        result.setdefault("heuristic", True)
        result.setdefault("model", None)
        result.setdefault("source", None)
        return result
    
    
    def result_payload(status, harness, title, session_id, path, **extra):
        payload = {"ok": status not in {"needs_confirmation", "error"}, "status": status,
                   "harness": harness, "title": title, "session_id": session_id,
                   "file": str(path)}
        payload.update(extra)
        return payload
    
    
    def main(argv=None):
        try:
            sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        except (AttributeError, OSError):
            pass
        parser = JSONArgumentParser(description="Safely save one coding-agent session")
        parser.add_argument("--harness", choices=sorted(store.HARNESSES))
        parser.add_argument("--id", dest="session_id")
        parser.add_argument("--title", required=True)
        parser.add_argument("--sessions-dir")
        choices = parser.add_mutually_exclusive_group()
        choices.add_argument("--ignore-existing", action="store_true",
                             help="revalidate a different-title conflict without changing it")
        choices.add_argument("--replace-title", action="store_true")
        parser.add_argument("--accept-similar", action="store_true")
        args = parser.parse_args(argv)
    
        harness = args.harness or auto_harness()
        if harness is None:
            return emit({"ok": False, "status": "error", "reason": "unknown_harness",
                         "detail": "cannot tell which harness this is; pass --harness"}, 1)
        try:
            store.validate_value("title", args.title)
            if args.session_id is not None:
                store.validate_value("session id", args.session_id)
        except ValueError as exc:
            return emit({"ok": False, "status": "error", "reason": "invalid_argument",
                         "detail": str(exc)}, 1)
    
        metadata = detect_metadata(harness, args.session_id)
        if not metadata.get("ok"):
            return emit({"ok": False, "status": "error", "reason": "detection_failed",
                         "detail": metadata.get("reason") or "session detection failed"}, 1)
        session_id = metadata.get("session_id")
        if args.session_id is None and metadata.get("heuristic"):
            return emit({"ok": False, "status": "needs_confirmation",
                         "reason": "confirm_detected_session", "harness": harness,
                         "session_id": session_id, "source": metadata.get("source"),
                         "title": args.title,
                         "choices": ["rerun with --id after confirmation"]}, 2)
        try:
            store.validate_value("detected session id", session_id)
            store.validate_value("working directory", os.getcwd())
            if metadata.get("model"):
                store.validate_value("detected model", metadata["model"])
        except ValueError as exc:
            return emit({"ok": False, "status": "error", "reason": "invalid_detected_metadata",
                         "detail": str(exc)}, 1)
    
        try:
            base = (Path(os.path.expanduser(args.sessions_dir)) if args.sessions_dir
                    else detect.sessions_dir())
        except (OSError, RuntimeError) as exc:
            return emit({"ok": False, "status": "error", "reason": "record_io_failed",
                         "detail": f"{type(exc).__name__}: {exc}"}, 1)
        path = store.record_path(base, harness)
        heading = store.HARNESSES[harness][1]
        try:
            with store.record_lock(path) as target:
                if target.exists():
                    text = target.read_text(encoding="utf-8-sig")
                    entries, problems = store.validate_record(text, heading)
                    if problems:
                        return emit(result_payload("error", harness, args.title, session_id, target,
                                                   reason="malformed_record", problems=problems), 1)
                else:
                    entries = []
    
                same_id = next((entry for entry in entries
                                if entry["fields"].get("session_id") == session_id), None)
                titles = [entry["title"] for entry in entries]
                saved, directory, model = detect.utc_timestamp(), os.getcwd(), metadata.get("model")
    
                if same_id is not None and same_id["title"] != args.title:
                    if args.ignore_existing:
                        return emit(result_payload("ignored", harness, same_id["title"], session_id,
                                                   target, requested_title=args.title), 0)
                    if not args.replace_title:
                        return emit(result_payload(
                            "needs_confirmation", harness, args.title, session_id, target,
                            reason="session_has_different_title", existing_title=same_id["title"],
                            choices=["ignore_existing", "replace_title"]), 2)
                    other_titles = [entry["title"] for entry in entries if entry is not same_id]
                    if args.title not in other_titles and not args.accept_similar:
                        similar = store.similar_titles(args.title, other_titles)
                        if similar:
                            return emit(result_payload(
                                "needs_confirmation", harness, args.title, session_id, target,
                                reason="similar_title", similar_titles=similar,
                                choices=["rerun --replace-title with an existing exact title",
                                         "rerun --replace-title --accept-similar"]), 2)
                    same_id["title"] = store.allocate_title(args.title, other_titles)
                    same_id["fields"].update({"saved": saved, "dir": directory})
                    if model:
                        same_id["fields"]["model"] = model
                    status = "replaced"
                elif same_id is not None:
                    if args.ignore_existing or args.replace_title:
                        return emit(result_payload("error", harness, args.title, session_id, target,
                                                   reason="choice_not_applicable"), 1)
                    same_id["fields"].update({"saved": saved, "dir": directory})
                    if model:
                        same_id["fields"]["model"] = model
                    status = "updated"
                else:
                    if args.ignore_existing or args.replace_title:
                        return emit(result_payload("error", harness, args.title, session_id, target,
                                                   reason="choice_not_applicable"), 1)
                    if args.title not in titles and not args.accept_similar:
                        similar = store.similar_titles(args.title, titles)
                        if similar:
                            return emit(result_payload(
                                "needs_confirmation", harness, args.title, session_id, target,
                                reason="similar_title", similar_titles=similar,
                                choices=["rerun with an existing exact title",
                                         "rerun with --accept-similar"]), 2)
                    final_title = store.allocate_title(args.title, titles)
                    fields = {"saved": saved, "session_id": session_id, "dir": directory}
                    if model:
                        fields["model"] = model
                    entries.append({"title": final_title, "fields": fields, "duplicates": []})
                    status = "created"
    
                new_text = store.render_record(heading, entries)
                _, problems = store.validate_record(new_text, heading)
                if problems:
                    return emit(result_payload("error", harness, args.title, session_id, target,
                                               reason="generated_invalid_record", problems=problems), 1)
                store.atomic_write(target, new_text)
                final = same_id["title"] if same_id is not None else entries[-1]["title"]
                extras = {"source": metadata.get("source")}
                if "validated" in metadata:
                    extras["validated"] = metadata["validated"]
                if metadata.get("note"):
                    extras["note"] = metadata["note"]
                return emit(result_payload(status, harness, final, session_id, target, **extras), 0)
        except store.RecordLocked as exc:
            return emit({"ok": False, "status": "error", "reason": "record_locked",
                         "lock_file": str(exc.path)}, 1)
        except (OSError, RuntimeError, UnicodeError) as exc:
            return emit({"ok": False, "status": "error", "reason": "record_io_failed",
                         "detail": f"{type(exc).__name__}: {exc}"}, 1)
    
    
    if __name__ == "__main__":
        sys.exit(main())
    
  • skills/save-session/references/decision-flow.md7.9 KB173f2ae1c725upstream ↗
    # Decision flow
    
    Visual companion to `SKILL.md` — **SKILL.md is authoritative**; this file is derived from
    it and must be updated together. Run `scripts/check_flow_doc.py` to catch drift: it verifies
    every decision point appears in both files, and that **every numbered step and every section**
    of SKILL.md is either covered by a figure or explicitly declared out of scope.
    
    Why the figures are split by **mode** rather than by operation: a flowchart answers "given
    this request, what happens next?", and one request enters exactly one mode. Per-operation
    diagrams would force the reader to hold state and re-enter at the right node — the exact
    place models slip. Logic used by only one mode (id resolution) lives inside that mode's
    figure.
    
    The one deliberate exception is **Figure 3, detection**: it is a subroutine entered from
    Mode 1 step 1, it has its own ordered fallbacks, and inlining it would make Figure 1
    unreadably wide. It is marked as a subroutine rather than pretended to be a mode.
    
    Hexagons (`ASK`) mark **interaction points** — every place the skill must stop and ask the
    user rather than decide. In prose these are easy to skim past; here they are unmissable.
    
    ## Figure 0 — routing
    
    ```mermaid
    flowchart TD
        REQ(["user request"]) --> WHICH{"what does the request ask for,<br/>read from the words not a keyword match"}
        WHICH -->|"save this session / remember it / bookmark it"| M1["Mode 1 - save"]
        WHICH -->|"resume X / find X / list my sessions / no name given"| M2["Mode 2 - find and resume"]
        M1 --> M1END["a record is created or updated"]
        M2 --> M2END["the user gets a command<br/>records are never modified"]
    ```
    
    ## Figure 1 — Mode 1, save
    
    ```mermaid
    flowchart TD
        S(["Mode 1 - save"]) --> HASTITLE{"did the request already<br/>supply a project title"}
        HASTITLE -->|"no"| TITLE{{"ASK - project title<br/>required, keep the user's wording<br/>ask only for what is missing"}}
        HASTITLE -->|"yes"| RUN
        TITLE --> RUN["run save_session.py<br/>pass a user-provided id verbatim<br/>do not read the ledger"]
        RUN --> SCRIPT["inside the writer: detect and validate<br/>lock, parse, apply exact rules,<br/>validate and atomically replace"]
        SCRIPT --> RESULT{"inside exact rules: create the file with its top heading;<br/>exact title collision uses highest existing suffix plus one<br/>JSON status and exit code"}
        RESULT -->|"created / updated in place / replaced<br/>exit 0"| DONE(["confirm - title, session id, file,<br/>and action taken"])
        RESULT -->|"confirm_detected_session<br/>exit 2"| ASKID{{"ASK - confirm or correct<br/>show the detected id and its evidence<br/>then rerun with --id"}}
        ASKID --> RUN
        RESULT -->|"session_has_different_title<br/>exit 2"| ANN{{"ASK - already saved as X<br/>ignore or replace"}}
        ANN -->|"ignore"| IGNORE["do not rerun the script<br/>report existing title unchanged<br/>and nothing written"]
        ANN -->|"replace"| REPLACE["rerun with --replace-title<br/>refresh saved, model and dir"]
        IGNORE --> DONE
        REPLACE --> RUN
        RESULT -->|"similar_title<br/>exit 2"| SIMILAR{{"ASK - use an existing exact spelling<br/>or keep separate"}}
        SIMILAR -->|"existing spelling"| RUN
        SIMILAR -->|"keep separate"| ACCEPT["rerun with --accept-similar"]
        ACCEPT --> RUN
        RESULT -->|"record_locked / other error<br/>exit 1"| ERROR(["report the error; no write<br/>never edit the ledger as a workaround"])
    ```
    
    ## Figure 2 — Mode 2, find and resume
    
    ```mermaid
    flowchart TD
        F(["Mode 2 - find and resume"]) --> SHAPE{"what shape is the request"}
        SHAPE -->|"names a project"| BYNAME["find_session.py --title NAME"]
        SHAPE -->|"wants everything listed"| LIST["find_session.py --list<br/>for the current harness"]
        SHAPE -->|"no name at all"| BARE["list the current harness first<br/>then ask which"]
        LIST --> HINT{"is the harness known<br/>from an env hint or an explicit flag"}
        BARE --> HINT
        HINT -->|"no"| ASKH{{"ASK - which harness, or use --all<br/>never guess the harness"}}
        HINT -->|"yes"| MATCH
        ASKH --> MATCH
        BYNAME --> MATCH{"how many entries matched"}
        MATCH -->|"none"| NONE(["say so plainly, and if the records<br/>look emptier than expected<br/>say so instead of proceeding<br/>never invent a session"])
        MATCH -->|"one"| PICK["take it"]
        MATCH -->|"several, same title or different ids"| ASKM{{"ASK - list every match sorted by saved,<br/>mark the newest as recommended,<br/>let the user choose"}}
        ASKM --> PICK
        PICK --> OUT(["print the exact resume command for that harness,<br/>plus the cd DIR to run it from<br/>resuming stays with the user - deliver the command"])
    ```
    
    ## Figure 3 — detection subroutine
    
    Entered from Mode 1 step 1. The order matters more than the mechanics: file reads work
    everywhere, a shell does not.
    
    ```mermaid
    flowchart TD
        D(["need this session's id, model and dir"]) --> ENV{"does this harness expose<br/>a usable session environment value"}
        ENV -->|"yes"| TRUST{"is that value authoritative<br/>Pi yes, Claude still needs confirmation"}
        TRUST -->|"yes"| OUT
        TRUST -->|"no"| VALIDATE["validate it against the harness store when available<br/>and preserve the heuristic flag"]
        VALIDATE --> VALIDOK{"did validation succeed"}
        VALIDOK -->|"yes"| OUT
        VALIDOK -->|"no"| ASKU
        ENV -->|"no"| READ["read the harness store directly<br/>JSON and JSONL need no shell"]
        READ --> GOT{"id found"}
        GOT -->|"yes"| OUT(["detect_session.py result<br/>ok, heuristic flag, source<br/>current UTC saved and records_dir"])
        GOT -->|"no"| SHELL{"is a shell the only remaining path<br/>pi env vars, opencode sqlite"}
        SHELL -->|"no"| ASKU{{"ASK - the user can read it<br/>/session, /status,<br/>/resume picker, /sessions"}}
        SHELL -->|"yes"| RUN["run the command once"]
        RUN --> DENIED{"was the command denied"}
        DENIED -->|"yes"| NORETRY["do not retry it<br/>fall back to file reads or ask"]
        DENIED -->|"no"| OUT
        NORETRY --> ASKU
        ASKU --> SAVED(["record the id the user gave"])
    ```
    
    ## Entry shape (artifact, not flow)
    
    Figures 1 and 2 read and write entries in this shape.
    
    ```markdown
    # Sessions — <Harness>
    
    ## <project title>
    - saved: 2026-10-16T23:40:00Z
    - session_id: <id in that harness's own format>
    - model: <provider/model>
    - dir: <absolute working directory>
    ```
    
    - Exactly the four fields: `saved` (UTC, ISO-8601), `session_id`, `model`, `dir`.
    - If the file does not exist, create the file with its top heading first.
    - Entries append oldest-first, so file order is the timeline; `saved` shows freshness.
    
    ## Invariants (not flow)
    
    These hold everywhere and have no branch, so putting them in a figure would imply they are
    optional somewhere. They live in `SKILL.md` under Rules and Entry identity.
    
    | Invariant | Why it matters |
    |---|---|
    | One record file per harness | Session ids do not translate across harnesses; mixing them corrupts lookups |
    | An entry is identified by its `session_id`, never its title | The id is what a resume command consumes; titles are only human labels |
    | A session id is never fabricated | A wrong id is worse than an admitted gap — ask the user instead |
    | Mode 2 never writes | Read paths must be safe to run anytime |
    | Entry loss is announced | If the records look emptier than expected, say so instead of proceeding — quiet loss is the one failure saving cannot see |
    | Resuming stays with the user | Deliver the command line; never spawn an interactive harness process to test it |
    | Ask only for what is missing | Normally just the project title; do not interrogate for values detection can produce |
    | Destination order: request-named → `AGENTS_MEMORIES_DIR` → `~/.agents/memories/sessions/` | An explicit destination must always win, or tests and project-local records break |
    | No secrets in records | These files are plain text and often committed |
    
    Harness → storage / model / resume mapping stays in the `SKILL.md` table, and the resume
    commands are authoritative in `scripts/find_session.py`; they are deliberately not copied
    here.
    
  • skills/save-session/agents/openai.yaml231 Bae7bc49dd4bdupstream ↗
    interface:
      display_name: "Save Session"
      short_description: "Save, list, and resume agent sessions"
      default_prompt: "Use $save-session to save this session under a project title, or to list and resume a previously saved one."
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/jemshit-save-session-skills-save-session.md

// REPO STATS

219 stars