# session (Unified Skill)

## Core Instructions (SKILL.md)

#### Core Instructions (content/distilled/session/SKILL.md)

# Session Lifecycle Router

Route a session-lifecycle task to the right mode, then read that mode's instructions before acting. Do not improvise a lifecycle ritual from memory — each mode encodes a specific, tested procedure.

## Modes

| Task signal | Mode | Read |
|---|---|---|
| "wrap up", "close session", end-of-session summary + commit + push + context clear | close | `references/close/SKILL.md` |
| switch context now, will return later; stash work + release claims | park | `references/park/SKILL.md` |
| fast snapshot, no ceremony; resume later via `/renew` | next | `references/next/SKILL.md` |
| resume work on a project/area; load journal, whisper, beads context; claim work | renew | `references/renew/SKILL.md` |
| generate a context/handoff document for session continuity | create-handoff | `references/create-handoff/SKILL.md` |
| continue from a previous session's handoff document | resume-handoff | `references/resume-handoff/SKILL.md` |

## Selection rules

- Full ceremony with journal routing and push → **close**. Quick stash without ceremony → **next**. Context switch mid-session → **park**.
- The user asks *how to continue later* → **create-handoff**; the user asks *to continue* from an existing handoff → **resume-handoff**.
- "renew" always means resuming; "close" always means ending. When unsure whether the user wants to stop or stash, ask one clarifying question.

## Procedure

1. Identify the mode from the table above.
2. Read the referenced file (resolve paths against this skill's directory).
3. Follow that file's instructions exactly — they handle non-interactive shell quirks, `$JOURNAL_PATH` resolution, and beads/git state.

---

#### Reference: references/close/SKILL.md

**Tools:** Read, Write, Edit, Glob, Bash

# Close Session

End the current session: log what was done, update tasks, route durable knowledge to `~/.whisper/`, commit and push, clear context.

Uses `$JOURNAL_PATH` for the daily log journal, and `~/.whisper/` for accumulated operational knowledge. Agent shells run non-interactive and never source `.bashrc`, so the environment may be missing these exports — resolve both values per step 1 (env → shell config → convention → legacy fallback).

## Steps

1. Pull the journal repo:
   ```bash
   # Non-interactive shells never source .bashrc, so $JOURNAL_PATH etc. are
   # usually unset here. Source the config in a throwaway shell — bash itself
   # handles comments, quotes, and nested vars ($JORNAL) — then fall back.
   shellval() { bash -c 'source ~/.bashrc >/dev/null 2>&1; printf "%s\n" "${'"'$1'"'}"' 2>/dev/null; }
   JOURNAL="${JOURNAL_PATH:-$(shellval JOURNAL_PATH)}"
   [ -n "$JOURNAL" ] || JOURNAL="$(shellval JORNAL)"
   [ -n "$JOURNAL" ] || JOURNAL="$HOME/para/areas/jornal"   # JORNAL convention
   [ -d "$JOURNAL/.git" ] || JOURNAL="$HOME/dev/status"     # legacy clone; flag this fallback in the reply
   LOG_SUBDIR="${JOURNAL_LOG_SUBDIR:-$(shellval JOURNAL_LOG_SUBDIR)}"
   [ -n "$LOG_SUBDIR" ] || LOG_SUBDIR="areas/log"
   cd "$JOURNAL" && git pull
   ```

2. Get today's date and time (`date +%Y-%m-%d`, `date +%H:%M`).
   Derive the log path: `$JOURNAL/$LOG_SUBDIR/YYYY/YYYY-MM/YYYY-MM-DD.md`

3. If the log file does not exist, create it with the daily log template.

4. Review the full conversation history and write a concise session summary covering:
   - What was worked on (key topics, files, repos)
   - Decisions made
   - Tasks completed or created
   - Any unresolved items or next steps

5. Append the summary to the `## Log` section of today's daily log:
   ```
   ### Session:HH:MM (<context>)
   - bullet point summary entries
   - **Next:** what to pick up next time (if applicable)
   ```

6. Update project/area files if tasks were completed or created:
   - Mark completed tasks `[x]`
   - Add new tasks as `[ ]`
   - Add/update `[~]` waiting items
   - Update `## Notes` with decisions

7. If any tasks or follow-ups came up that aren't in a project/area, add them to `inbox.md`.

8. **Route durable knowledge to `~/.whisper/`.** Scan the session for anything worth keeping and route by scope (skip this step entirely if nothing durable was learned):
   - **Branch-specific finding** → `bd note <beads-epic>` or `~/.whisper/repos/<repo>/branches/<slug>/notes.md`
   - **Repo-wide infra fact** → `~/.whisper/repos/<repo>/env.md`
   - **Universal agent behavior rule** → `bd remember` or `~/.whisper/rules.md`
   - **Worktree setup fact** → `~/.whisper/repos/<repo>/worktrees/<name>/env.md`
   - **No secrets anywhere:** never write tokens, keys, or PII
   - **Extend, don't duplicate:** append to existing notes rather than creating new ones

9. Commit and push. Stage only the files this session touched, explicitly by name:
   ```bash
   cd "$JOURNAL" && git add <log-file> [<files>] && git commit -m "log: YYYY-MM-DD session notes" && git push
   ```

10. As the very last step, run `/clear` to reset the conversation context.

## Rules

- Do NOT ask the user any questions. Summarize automatically from conversation context.
- Keep the summary concise — bullet points, not paragraphs.
- If today's log already has content, append to it; never overwrite existing entries.
- Always pull before reading and push after committing.

---

#### Reference: references/create-handoff/references/handoff-template.md

```markdown
---
date: [ISO timestamp with timezone]
git_commit: [short hash]
branch: [branch name]
directory: [working directory]
issue: [issue-123 if applicable]
status: handoff
---

# Handoff: [brief description]

## Context

[1-2 paragraph overview]

## Current Status

### Completed
- [x] [Task with file references]

### In Progress
- [ ] [Task with current state]

### Planned
- [ ] [Next task]

## Critical Files

1. `path/to/file.ext:123` - [Why it matters]
2. `path/to/file.ext:456` - [Why it matters]

## Recent Changes

- `path/to/file.ext:123` - [What changed]

## Key Learnings

1. [Learning]
   - Evidence: [file reference or reasoning]

## Open Questions

- [ ] [Unresolved question]

## Next Steps

1. [Priority action]

## Artifacts

New files:
- `path/to/new-file.ext`

Modified files:
- `path/to/modified-file.ext`

## Related Links

- [Relevant documentation, plan, or discussion]

## Additional Context

[Anything another session needs immediately]
```

---

#### Reference: references/create-handoff/references/naming.md

## Handoff Naming

Create files at `handoffs/YYYY-MM-DD_HH-MM-SS_description.md`

Examples:
- `handoffs/2026-01-12_14-30-00_issue-123_add-oauth.md`
- `handoffs/2026-01-12_14-30-00_refactor-auth-system.md`

---

#### Reference: references/create-handoff/SKILL.md

# Create Handoff Document

Create a concise handoff document for another agent session.

## Procedure

1. Gather current repository metadata.
2. Choose a handoff filename using `references/naming.md`.
3. Write the document using `references/handoff-template.md`.
4. Tell the user where the handoff was written and how to resume from it.

## Rules

- Be specific and include file references where they matter.
- Capture decisions, learnings, and next steps, not just a task list.
- Reference artifacts instead of copying large code blocks.

---

#### Reference: references/next/SKILL.md

**Tools:** Read, Write, Edit, Bash

# Next

Snapshot the current session to `~/.whisper/` and move on. Fast — no project file updates, no inbox triage, no ticket operations. Pure stash.

## Steps

1. Get timestamp: `date +%Y-%m-%d` and `date +%H:%M`.

2. Detect repo and branch:
   ```bash
   repo_url=$(git remote get-url origin 2>/dev/null | sed 's|https://||;s|git@||;s|\.git$||')
   branch=$(git rev-parse --abbrev-ref HEAD)
   branch_slug=$(echo "$branch" | sed 's|/|--|g')
   notes_path=~/.whisper/repos/"${repo_url}"/branches/"${branch_slug}"/notes.md
   ```

3. If `~/.whisper/` doesn't exist or the branch slot doesn't exist, run `/w check` first (which will offer to init). If the user declines, skip and warn.

4. Scan the last portion of the conversation and write a 2–5 bullet snapshot:
   - What was worked on (files, topics)
   - Key decisions or changes made
   - **Next:** the most logical continuation point

5. Append the snapshot to `notes.md`:
   ```
   ### YYYY-MM-DD HH:MM — snap
   - what was worked on
   - decisions made
   - **Next:** continuation point
   ```

6. No commit, no push, no ticket operations. Just write the file.

## Output

```
✓ Snapped to ~/.whisper/repos/<repo>/branches/<slug>/notes.md

Use `/renew` later to pick this back up.
```

## Rules

- Do NOT ask questions — summarize automatically from conversation context.
- Keep it brief — 2–5 bullets, not paragraphs.
- Do NOT commit or push anything.
- Do NOT update project files, inbox, or tickets.
- Do NOT run `/clear`.

---

#### Reference: references/park/SKILL.md

**Tools:** Read, Write, Edit, Bash

# Park

Snapshot the current session's work on a project/area before switching context. This is NOT end-of-day — just a context switch.

Uses `$JOURNAL_PATH` (defaults to `~/dev/status`) for the daily log journal, and `~/.whisper/` for accumulated operational knowledge. The log subdirectory defaults to `log/`; set `$JOURNAL_LOG_SUBDIR` to override (e.g. `areas/log` for the JORNAL layout).

## Steps

1. Get today's date and current time (`date +%Y-%m-%d`, `date +%H:%M`).
   ```bash
   JOURNAL="${JOURNAL_PATH:-$HOME/dev/status}"
   LOG_SUBDIR="${JOURNAL_LOG_SUBDIR:-log}"
   ```

2. Read today's log: `$JOURNAL/$LOG_SUBDIR/YYYY/YYYY-MM/YYYY-MM-DD.md`
   If it doesn't exist, create it with the daily log template.

3. Review the conversation history to determine:
   - What project/area was being worked on
   - What was accomplished in this session
   - What the logical next step is
   - Any new tasks, decisions, or blockers discovered

4. Append a session entry to today's log under `## Log`:
   ```
   ### Session:HH:MM (<project/area context>)
   - what was done
   - decisions made
   - **Next:** what to do when resuming
   ```

5. Update the relevant project/area file if needed:
   - Mark completed tasks `[x]`
   - Add new tasks discovered during the session
   - Add/update `[~]` waiting items with context
   - Update `## Notes` with any decisions

6. If there are uncommitted changes in the project's git worktree, note them in the log entry.

7. **Release any in-progress ticket claim if leaving mid-work.**
   Check whether a ticket was claimed for this session:
   ```bash
   BRANCH=$(git branch --show-current 2>/dev/null)
   bd list --status in_progress --label branch:$BRANCH 2>/dev/null
   ```
   For each in-progress ticket that is NOT complete:
   - **If meaningful work was committed:** keep the claim and append a progress note:
     ```bash
     bd note <id> "Session parked $(date +%H:%M). Done: <brief>. Safe to resume from: <last commit>."
     ```
   - **If nothing was committed:** release the claim so another agent can pick it up:
     ```bash
     bd update <id> --assignee "" --status open
     ```

8. **Record snapshot to `~/.whisper/`.** If `~/.whisper/` exists and a beads-epic is linked, append a note to the epic:
   ```bash
   repo_url=$(git remote get-url origin 2>/dev/null | sed 's|https://||;s|git@||;s|\.git$||')
   branch_slug=$(git rev-parse --abbrev-ref HEAD | sed 's|/|--|g')
   context_path=~/.whisper/repos/"${repo_url}"/branches/"${branch_slug}"/context.md
   beads_epic=$(grep '^beads-epic:' "$context_path" 2>/dev/null | sed 's/^beads-epic: *//')
   if [ -n "$beads_epic" ]; then
     bd note "$beads_epic" "Parked $(date +%H:%M). Done: <what was accomplished>. Next: <the logical continuation>."
   fi
   ```

9. Do NOT commit/push the journal repo yet — that happens at `/close`. Just write the files.

## Output format

```
---
**Parked: <project/area name>**

**Session summary**
- what was accomplished

**Next step** *(for when you /renew)*
- the logical continuation

**Updated**
- files modified in status repo (log, project file, etc.)

*Ready to switch context. Use `/renew <slug>` to pick up something else.*
```

## Rules

- Do NOT ask questions — summarize automatically from conversation context.
- Keep it brief — this is a quick snapshot, not a full report.
- Do NOT commit or push the journal repo.
- Do NOT run `/clear` — the user may continue working in this session.

---

#### Reference: references/renew/SKILL.md

**Tools:** Read, Write, Edit, Glob, Bash, Grep

# Renew

Load focused context for a specific project or area to continue work.

Uses `$JOURNAL_PATH` (defaults to `~/dev/status`) for the daily log journal, and `~/.whisper/` for accumulated operational knowledge. The log subdirectory defaults to `log/`; set `$JOURNAL_LOG_SUBDIR` to override (e.g. `areas/log` for the JORNAL layout).

## Steps

1. Pull the journal repo:
   ```bash
   JOURNAL="${JOURNAL_PATH:-$HOME/dev/status}"
   LOG_SUBDIR="${JOURNAL_LOG_SUBDIR:-log}"
   cd "$JOURNAL" && git pull
   ```

2. Identify the target.

   **If a `<slug>` is provided:** The user says `/renew <slug>`.

   **If no slug is provided:** Infer from the current workspace context:
   - Get the repo name: `basename $(git rev-parse --show-toplevel 2>/dev/null)`
   - Get the branch name: `git branch --show-current 2>/dev/null`
   - Extract a candidate slug from the branch (strip prefix like `ak/`, `feature/`, etc.)
   - Use both the repo name and branch-derived slug as candidates

   **Match candidates** against:
   - `$JOURNAL/projects/*.md` — check filenames and grep for repo/branch references
   - `$JOURNAL/areas/*.md` — same
   - Try exact match, then partial/substring match
   - If multiple matches found, list them and ask the user to pick
   - If no match found, list available projects/areas and ask

3. Read the matched project or area file.

4. Read today's log (`$JOURNAL/$LOG_SUBDIR/YYYY/YYYY-MM/YYYY-MM-DD.md`).
   If it doesn't exist, create it with the daily log template.
   Scan for any earlier session entries related to this project/area today.

5. Search recent logs for context (last 3 days):
   ```bash
   grep -rl "<slug>" "$JOURNAL"/"$LOG_SUBDIR"/YYYY/YYYY-MM/ 2>/dev/null | tail -3
   ```
   Read any matches to understand recent session history.

6. Search inbox for related items:
   ```bash
   grep -i "<slug>" "$JOURNAL"/inbox.md
   ```

7. **Check `~/.whisper/` for accumulated knowledge.**
   If `~/.whisper/` exists, load context:
   ```bash
   repo_url=$(git remote get-url origin 2>/dev/null | sed 's|https://||;s|git@||;s|\.git$||')
   branch_slug=$(git rev-parse --abbrev-ref HEAD | sed 's|/|--|g')
   whisper_dir=~/.whisper/repos/"${repo_url}"/branches/"${branch_slug}"
   ```
   - Read `context.md` if it exists (extract beads-epic, status)
   - Read `plan.md` if it has real content
   - Read `notes.md` if it has real content
   - Read `env.md` at repo level for infra facts
   - If beads is available, fetch open issues:
     ```bash
     bd list --label branch:<branch> 2>/dev/null
     bd list --status in_progress --label branch:<branch> 2>/dev/null
     ```
     Surface any `in_progress` tickets prominently. The **Suggested next step** must only reference tickets NOT currently `in_progress`.

8. If the project/area has a worktree or repo path noted in its file, gather git context:
   - `cd <worktree-path> && git branch --show-current`
   - `git log --oneline -5`
   - `git status --short`
   - `git log --oneline origin/main..HEAD`

## Output format

```
---
**Resuming: Project/Area Name**

**Status**: brief one-line summary of where things stand

**Last session** *(from most recent log entry)*
- what was done last time

**Open tasks**
- [ ] task list from the project/area file

**Waiting**
- [~] any blocked items and who/what they're waiting on

**Related inbox items** *(if any)*
- items that mention this project

**Whisper context** *(if ~/.whisper/ exists)*
- Plan: summary of current plan
- Notes: key findings
- Beads issues: <n> open, <n> in_progress

**⚠ Active in flight** *(omit if none)*
- ◐ `<id>` — <title> [started: <date>]
- *(If your intended ticket is listed here, see **Claiming work** below.)*

**Workspace**
- Worktree: path, branch, status
- Commits ahead of main, uncommitted changes, etc.

**Suggested next step**
- what makes sense to do next — only suggest tickets NOT currently in_progress
```

Then ask: *"Ready to continue, or want to adjust the plan?"*

---

## Claiming work

Before writing any code, claim the ticket atomically and check for file conflicts.

### Steps

1. **Claim atomically:**
   ```bash
   bd update <ticket-id> --claim
   ```

2. **Check for file-level conflicts** with other in-progress tickets:
   ```bash
   bd list --status in_progress --label branch:<branch> --json 2>/dev/null \
     | python3 -c "
   import json, sys
   issues = json.loads(sys.stdin.read() or '[]')
   for i in issues:
       files = (i.get('metadata') or {}).get('files', [])
       for f in files:
           print(i['id'] + '\t' + f)
   "
   ```
   Cross-reference against the claimed ticket's own `metadata.files`.
   If overlap found, surface a warning:
   ```
   ⚠ File conflict detected:
     services/api.py is also claimed by ticket-abc (in_progress)

   Options:
     A) Gate this ticket until the blocker closes
     B) Coordinate merge order
     C) Proceed — accept the conflict (reconcile at merge time)
   ```

3. **If backing off** (chose option A):
   ```bash
   bd update <ticket-id> --assignee "" --status open
   bd gate create <ticket-id> --type bead --await-id <blocking-id>
   ```

### Metadata coverage warning

File conflict detection only works when both tickets have `metadata.files` populated (set by `create-issues` or `/w link` at ticket creation time). Tickets created before this convention was adopted have no metadata. For those tickets, **"no conflict found" means unknown, not safe**.

---

#### Reference: references/resume-handoff/references/analysis-template.md

```text
I've analyzed the handoff from [date]. Here's the current situation:

## Original Context
[Summary of what was being worked on]

## Task Status Review

Completed:
- [x] [Task] - VERIFIED: [Current status]

In Progress:
- [ ] [Task] - STATUS: [Current state]

Planned:
- [ ] [Next task]

## Changes Since Handoff

Commits since handoff:
- [Commit summary]

Impact:
[How the current state affects the original plan]

## Key Learnings Still Applicable

1. [Learning] - [Why it still applies or not]

## Questions Needing Resolution

- [ ] [Question]

## Recommended Next Action

Priority 1: [Action]
- Reason: [Why]
- Files: [What to read or change]
- Approach: [How to proceed]
```

---

#### Reference: references/resume-handoff/references/locating.md

## Locating a Handoff

Examples:

```bash
# List recent handoffs
ls -lt handoffs/ | head -10

# Find handoffs for a specific issue
ls handoffs/*issue-123* | sort -r | head -1
rg -n "issue: issue-123" handoffs/*.md
```

---

#### Reference: references/resume-handoff/SKILL.md

# Resume from Handoff

Resume work from a handoff document through analysis and verification.

## Procedure

1. Locate the handoff file.
2. Read it completely.
3. Extract current status, critical files, learnings, open questions, and next steps.
4. Verify how the repository changed since the handoff.
5. Read the referenced critical files.
6. Present the current situation using `references/analysis-template.md`.
7. Wait for confirmation before starting new work.

## Rules

- Always verify the handoff against the current codebase.
- Treat stale handoffs as possibly inaccurate.
- Preserve the original priorities unless the current repository invalidates them.
