Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Handoff?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/indigoai-us-handoff)
---
name: handoff
description: Preserve session state for a follow-up agent with handoff files and commits.
model: sonnet
effort: low
allowed-tools: Read, Write, Edit, Grep, Glob, Bash(git:*), Bash(bash:*), Bash(jq:*), Bash(date:*), Bash(mkdir:*), Bash(cat:*), Bash(rm:*), Bash(.claude/skills/_shared/journal.sh:*), Bash(bash .claude/skills/_shared/journal.sh:*), Bash(hq core handoff open-steps:*), Bash(hq core handoff run:*), Bash(bash core/scripts/handoff-run.sh:*), Bash(hq core handoff archive-decision:*), Bash, AskUserQuestion, Task, Agent, Skill
---
# Fresh Session Continuity
Write a thread file + `handoff.json` with minimal foreground token cost. Keep shell-only cleanup in a detached post-script, and run model-based follow-ups (`/learn`, `/document-release`) through the current runtime's visible delegation capability, with a synchronous Skill fallback after the handoff is durable.
**Why the split:** handoff used to chain 4+ heavy sub-skills (/learn → INDEX regen → document-release → qmd) in the foreground, which re-ingested ~200KB of INDEX.md and large policy bodies — enough to trigger mid-handoff autocompact and corrupt the thread write. Detached shell cleanup keeps logs tiny; visible runtime delegation keeps model work isolated without hidden `claude -p` auth failures. If the session dies after `handoff.json` is written, next session self-heals via `/startwork`.
**User's message (optional):** $ARGUMENTS
## Process
### 1. Write the session changeset (personal/core knowledge commits use it)
Write the exact relative paths intentionally changed by this session into a unique JSON changeset file. Do not scan repository status to expand this list. Step 3 passes this file to `hq core handoff run`, which first commits only these session-scoped personal/core knowledge changes, then finalizes with the same file.
Write every temp path in this skill out literally in each Bash call. The credential guard cannot resolve shell variables (`"$CHANGESET_TMP"`), command substitution (`$(mktemp ...)`), or globs in path operands, so it blocks those commands and forces a rewrite. Pick the changeset path once as `workspace/threads/.handoff-tmp/.handoff-changeset-{slug}-{stamp}.json`, where `{stamp}` is the output of `date -u +%Y%m%dT%H%M%SZ` (the stamp keeps concurrent sessions with the same slug apart), and keep it as `{changeset_file}`. Run `mkdir -p workspace/threads/.handoff-tmp`, write the JSON array to `{changeset_file}` with the `Write` tool, then check that it is a JSON array (nothing is committed in this step):
```bash
jq -e 'type == "array"' "workspace/threads/.handoff-tmp/.handoff-changeset-{slug}-{stamp}.json" >/dev/null
```
A non-zero exit means the file is not a JSON array: rewrite it before Step 3.
The file holds a JSON array such as `["core/knowledge/public/<repo>/<file-you-changed>"]`.
Include only files this session intentionally changed. List files, not folders: an entry with a trailing slash, an absolute path, or a `..` segment fails the whole changeset, and the knowledge commit prints the offending entries and stops the handoff before finalize. The knowledge commit in Step 3 commits only listed files inside personal/core knowledge repositories and the bound company's knowledge repository, and leaves unrelated staged or dirty files untouched. It reads the bound company from `HQ_ACTIVE_COMPANY`, or, when that is empty because the company was bound mid-session, from the session lock's primary company only (`company_slug`; the other members of a multi-company lock are never used). The lock is read only when the session id comes from the environment, and that id is passed to `hq-session.sh` explicitly; `workspace/sessions/.current` is never used, because it can name another live session. The company must be a real `companies/<slug>` directory with an exact-case entry in `companies/manifest.yaml` (this applies to `HQ_ACTIVE_COMPANY` too), otherwise it is treated as unbound. The helper never touches another company's knowledge. A bound company's knowledge that is a plain synced directory (the usual case) syncs through its vault and is not committed. With no bound company its output (`knowledge_commit.result` in the Step 3 JSON) is `SKIPPED-COMPANY-KNOWLEDGE: <reason>` (no bound company, no session id in the environment, session lock unreadable, or company not registered); keep that line for the Step 6 report. This step behaves the same under Claude, Codex, and Grok.
### 2. Collect learnings (do NOT invoke /learn)
Reflect on the session and build a JSON array of operational learnings — mistakes that cost time, unexpected behaviors, patterns that worked, user corrections. If nothing novel, use `[]`.
Format:
```json
[
{"type": "rule", "content": "NEVER: ...", "scope": "global", "source": "session-learning"},
{"type": "rule", "content": "ALWAYS: ...", "scope": "company:{co}", "source": "session-learning"}
]
```
Choose one concrete learnings file path, such as `/tmp/handoff-learnings-{short-slug}.json`, write the array there, and retain the same serialized array as `{learnings_json}`. Reuse the exact path in Steps 3 and 4.5. Empty array is fine. **Do not call `/learn` here — Step 4.5 dispatches it after the learning array is durable.**
#### 2b. Collect environment deficiencies (from memory only)
Second collection in this step. Answer the checklist below **from session memory only**. Do **not** read logs, transcripts, session JSONL, tool-result files, or any other record of the session in this step; if you do not remember a problem, it does not go in.
For each of the seven levers, ask whether the environment (not the task) slowed or misled you this session:
| lever | question |
|---|---|
| `navigation` | Did finding the right file, script, or doc take repeated searches or wrong turns? |
| `automated-checks` | Was a test, lint, hook, or CI check missing, flaky, slow, or misleading? |
| `coding-standards` | Was a convention unclear, contradictory, or undocumented? |
| `steering-bloat` | Did injected policies, reminders, or context crowd out what mattered or get truncated? |
| `tool-economy` | Did a tool or command cost far more calls, output, or retries than the job needed? |
| `no-ops` | Did a command, hook, or step run and do nothing useful? |
| `information-access` | Was needed information, access, or a credential unavailable or hard to reach? |
Write one item per real problem into a `deficiencies[]` array:
```json
[
{"lever": "navigation", "kind": "repo", "severity": "medium",
"summary": "one line", "evidence": "what concretely happened this session",
"proposed_fix": "the change or exact command that would prevent it"}
]
```
- `kind`: `hq-core` (HQ scaffold, scripts, skills, policies), `local-setup` (this machine or account), or `repo` (the target code repo).
- `severity`: `high` | `medium` | `low`.
- `evidence` is required. Drop any item without a concrete evidence string before storing; the finalizer also drops items whose evidence is empty.
- Write the array to a temp file under `workspace/threads/.handoff-tmp/` as a literal path such as `workspace/threads/.handoff-tmp/deficiencies-{slug}-{stamp}.json` (same `{stamp}` as Step 1), written with the `Write` tool, and keep the path as `{deficiencies_file}`. `[]` is fine. Remove the file after Step 3.
### 2.2 Capture signal and entity candidates (opt-in companies only)
If the bound company has `signals_capture` or `ontology_capture` on
(`core/scripts/knowledge-prefs.sh get {co} <field>`), follow
`.claude/skills/_shared/session-close-capture.md`: from the summary you are
about to pass to `hq core handoff run`, write up to 15 candidates — decisions,
commitments, risks, open questions, action items, and the people / projects /
companies they name — with `core/scripts/ontology-candidate.sh`, source ref
`handoff:{thread_id}`. Both switches off: skip silently. Fail-soft.
### 2.5 Close active session journal (if any)
Spec: `core/knowledge/public/hq-core/journal-spec.md`. If a journal was opened earlier in this session by `/brainstorm`, `/deep-plan`, or `/prd`, close it now so its frontmatter records `status: closed` + a one-line summary.
```bash
bash .claude/skills/_shared/journal.sh close "{project_dir}" "{one-line synthesis of session, ≤120 chars}"
```
Pass the resolved project directory that owns this session's journal. The helper is fail-soft (no-op if no owned active journal pointer exists). The summary should mirror what you write into `--summary` for `hq core handoff run`. Helper clears only this session's pointer on success.
### 3. Run `hq core handoff run` (synchronous, one tool call)
Call it through `bash core/scripts/handoff-run.sh`, which takes the same arguments. The wrapper runs `hq core handoff run` with every argument first and passes its output and exit code through. hq-cli 5.345.231 rejects `--company` and `--deficiencies-json` with `Unknown arg` before any thread is written, and dropping them is not an option there: its finalize would derive the owner company from the touched paths and store no deficiencies. When the CLI exits without writing a thread, the wrapper finishes the same steps with the `core/scripts` helpers, which accept both flags, and adds `cli_fallback` (the CLI's exit code and first error line) to the JSON. Report `cli_fallback` in Step 6 when it is present.
`hq core handoff run` runs the mechanical part of the handoff in one process, in this order, and stops at the first step that fails:
1. the scoped personal/core knowledge commit for the Step 1 changeset;
2. finalize (all arguments other than the four below pass through to it unchanged);
3. the detached post (Step 4);
4. auto-file of hq-core deficiencies (see "Auto-file hq-core deficiencies");
5. the builder route check (see "Builder route").
Its own options: `--files-touched-json-file <path>` (required; used by both the knowledge commit and finalize), `--learnings-file <path>` (passed to the post), and `--no-post`, `--no-autofile`, `--no-builder-route` to skip a step. Archiving is not part of it (Step 7).
Finalize handles everything that must be durable before session end:
- Receives the same explicit session changeset used by the knowledge commit helper (Step 1)
- Writes thread file + `handoff.json` + `workspace/threads/{thread}.changeset.json`
- Regenerates thread INDEX + recent.md + orchestrator INDEX via dedicated bash scripts (`rebuild-threads-index.sh`, `rebuild-orchestrator-index.sh`) — zero Claude context
- Commits HQ via explicit paths: thread/index files plus the validated `--files-touched-json` paths (never `git add -A`)
- Classifies noisy HQ root status via `hq core hq-status-summary` so baseline local files do not become accidental handoff scope
- Schedules ownership-aware qmd reindex via `qmd-reindex-bg.sh` (shared with post): agent boxes hard-skip (`skipped-agent`, zero qmd mutation — managed timer/post-sync own freshness); laptops use one non-blocking single-flight cleanup→update→embed
Pass `--company "{co}"` only for the explicitly resolved owner of this handoff. Omit it for HQ/global work. Never derive ownership from touched paths or distribute a complete thread to multiple companies.
Reuse the `{changeset_file}` prepared in Step 1 and pass its literal path — never inline the changeset into `--files-touched-json`. On Windows Git Bash the OS caps a command line at ~32KB (~8KB under cmd.exe), and a large changeset rides argv through several hops (status-summary, jq) and aborts the handoff. The file form keeps it off argv. This mirrors the learnings temp-file pattern from Step 2. Keep it under `workspace/threads/.handoff-tmp/` (gitignored, exists on Git Bash — do **not** use `/tmp`, which some Windows setups lack; do **not** use a slug-only deterministic path under `workspace/threads/` — concurrent sessions collide and unignored temps flip `git.dirty`). Clean it up whether the finalizer succeeds or fails, and propagate a non-zero finalize exit status:
```bash
rc=0
bash core/scripts/handoff-run.sh \
--learnings-file "{learnings_file path from Step 2}" \
--company "{co}" \
--title "Handoff: {one-line title}" \
--summary "{one-paragraph summary of what changed}" \
--message "{user's handoff message, or echo of the summary}" \
--next-steps-json '[{"...json array of next steps..."}]' \
--files-touched-json-file "workspace/threads/.handoff-tmp/.handoff-changeset-{slug}-{stamp}.json" \
--learnings-json-file "{learnings_file path from Step 2}" \
--deficiencies-json "{deficiencies_file from Step 2b}" \
--tags-json '["handoff","{co}","{topic}"]' \
--slug "{short-hyphenated-slug}" || rc=$?
rm -f "workspace/threads/.handoff-tmp/.handoff-changeset-{slug}-{stamp}.json" # clean up on both success and failure; keep the Step 2 learnings file for Step 4.5
[ "$rc" -eq 0 ] || { echo "hq core handoff run failed (rc=$rc)" >&2; exit "$rc"; }
```
After finalization succeeds, update this predecessor session's title with
`set_session_title` to show that the handoff is ready. Follow
`core/policies/hq-session-title-grammar.md`: use the `📤` handed-off status
glyph with the existing company, product, and work subject; do not replace the
subject with a generic "handoff" label. Do this only after the thread is
durable. Before calling the tool, run `bash core/scripts/hq-session.sh current`
to get the current session id, sanitize it as
`${session_id//[^A-Za-z0-9._-]/_}`, and check whether
`.claude/state/session-title-${session_key}.manual` exists. If it exists, skip
the title update so a manual rename is preserved. If the optional title tool is unavailable, skip the update without blocking handoff completion.
Every next step is stored with an `id` (`<thread_id>#<n>`) and `status: open`.
Before writing the new thread's next steps, close the ones this session actually
finished so they stop being copied forward:
```bash
hq core handoff open-steps list # what is still open across recent handoffs
hq core handoff open-steps close <step-id> --note "<what closed it>"
```
Finalize also copies the next-step command to the user's clipboard (fail-soft; pbcopy/wl-copy/xclip). Default is `/resumework {thread_id}`. If a different command is the right continuation, pass it explicitly via `--next-command "{command}"`.
The inline `--files-touched-json '[...]'` flag still works for small changesets and older callers, but the file form above is the default because it is the only one that survives a large untracked tree on Windows.
`--files-touched-json-file` (or the inline `--files-touched-json`) is the session changeset boundary. Pass precise paths for files/directories intentionally changed this session. It may be an array of strings or objects:
```json
[
"core/scripts/handoff-finalize.sh",
{"path":"docs/architecture.md","reason":"updated diagram for new flow"},
{"path":"old/file.md","deleted":true,"reason":"removed obsolete file"}
]
```
Do not compensate for noisy root `git status` by passing broad parent directories unless the whole directory is intentionally in scope.
The command emits a single JSON line to stdout: the finalize payload plus `knowledge_commit`, `post`, `autofile`, `builder_route` and `builder_brief`:
```json
{"thread_id":"T-...","thread_path":"workspace/threads/T-...json",
"changeset_path":"workspace/threads/T-...changeset.json",
"handoff_path":"workspace/threads/handoff.json","hq_committed":true,
"hq_commit_status":"committed","hq_commit_error":"",
"committed_paths":["..."],"stage_failures":[],"skipped_paths":[],
"baseline_noise_count":123,
"indexes_regen":true,"qmd_pid":"12345","git_bg_errors":"",
"next_command":"/resumework T-...","clipboard_copied":true,
"knowledge_commit":{"code":0,"result":"..."},
"post":{"launched":true,"skipped":false,"error":null},
"autofile":"skipped: no hq-core deficiencies",
"builder_route":"route: public (no staging checkout)","builder_brief":null}
```
When the knowledge commit fails, the command exits with its code, prints its message on stderr and nothing on stdout, and finalize does not run: tell the user the handoff did not complete and surface the message. A missing `--files-touched-json-file` exits 2.
`qmd_pid` may be a worker PID on laptops, or the tokens `skipped-agent` / `skipped` (or empty when HOME is unset / helper missing). Busy and dedupe are quiet inside the worker after a PID was already printed; they must never be reported as a successful agent reindex.
**Capture `thread_path` from the result** — you need it for Steps 4.5 and 7. Keep `changeset_path`, `committed_paths`, `skipped_paths`, and `baseline_noise_count` for the final report.
`hq_commit_status` says why `hq_committed` is what it is: `committed`, `nothing-to-commit`, `failed` (git refused the commit), or `stage-failed` (`git add` rejected paths — the shape a held `.git/index.lock` takes, where no commit is even attempted). Both failure states exit **4** after printing the payload, with git's message in `hq_commit_error` and the unstageable paths in `stage_failures`; the post, auto-file and builder route steps do not run. Treat exit 4 as a hard stop — the thread files exist on disk but are uncommitted, so tell the user the handoff did not complete, surface the git error, and do not proceed to Step 4.
### 4. Detached post (started by Step 3; mechanical cleanup only)
`hq core handoff run` starts the post detached right after finalize succeeds, with the thread path and the `--learnings-file` path. Do not start it again. `post.launched` is `true` when it started; `post.error` holds the reason when it did not (report it in Step 6; the handoff itself is already durable).
The post runs detached and:
1. Archives threads older than 60 days into `workspace/threads/archive/YYYY-MM/` (gated once per 24h)
2. Regenerates INDEX files again (captures any archive moves)
3. Records eligible learn/doc-release work as pending until the handoff reports dispatch proof
4. Schedules the same ownership-aware helper as finalize (`qmd-reindex-bg.sh`). On agent boxes both paths return `skipped-agent` and never start qmd or the managed indexer. On laptops, if a finalize-spawned worker already holds the single-flight lock (or just finished within the helper dedupe window), this is a quiet no-op — not a second independent writer
Logs land at `/tmp/handoff-post.log` and `/tmp/qmd-handoff.log`. If the session dies while the post-script runs, the script keeps going — `handoff.json` is already valid.
### 4.5 Dispatch runtime-appropriate model follow-ups
Only begin this step after `hq core handoff run` succeeds: `{learnings_json}` is now stored in `{thread_path}` and is recoverable even if every execution route fails. Do **not** call `claude -p` or `codex exec`, and do **not** run model work from the post.
Run applicable follow-ups sequentially in this order: `/learn` first, then `/document-release`; wait for each result before starting the next. Before dispatch, tell the user a rough expected duration for the applicable work by estimating each follow-up and adding the estimates. Label it as an estimate, not a promise.
Before dispatching document-release, resolve its availability once for this session with `bash core/scripts/skill-installed.sh document-release "${HQ_ACTIVE_COMPANY:-}"`. Use the bound active company from `HQ_ACTIVE_COMPANY`; do not derive the skill scope from `.metadata.company`, which may describe a touched tenant. When no company is bound, the check searches root and package skills only. Only when document-release is installed may a document-release follow-up use a dispatch route or appear in the recovery warning. If the check reports that it is absent, do not invoke it and record `document-release: skipped (skill not installed)` in the follow-up outcomes.
For each applicable follow-up, use the first capability available in this order:
1. **Codex:** when `spawn_agent` (and `wait_agent`) is available, call `spawn_agent` and wait for its result. This is visible delegation.
2. **Claude Code:** otherwise, when the visible `Task` or `Agent` mechanism is available, launch the follow-up through that mechanism and wait for its result.
3. **Last fallback:** otherwise, or when the visible dispatch returns an error or no completion proof, invoke the corresponding `Skill` tool **synchronously** in this parent after finalization.
Treat a follow-up as applied only when its agent/task/Skill result confirms completion. A launched ID alone is not proof. Keep it as durably pending when all available routes fail or no route exists.
**Company-scoped work stays in the parent.** A delegated child has no company binding, so the scope hook blocks it from every path under `companies/<co>/`. Run `/learn` for any item scoped `company:<co>`, and `/document-release` whenever the thread's `files_touched` has an entry under `companies/`, synchronously through the `Skill` tool in this bound parent instead of delegating. A child that reports it was blocked by the scope hook did not complete the work: treat that follow-up as unconfirmed and rerun it in the parent. Delegated children also run on the app's default subagent model, so open the files a child reports changing before you report them as applied.
Use this prompt for each learnings follow-up when `{learnings_json}` contains any array item:
```
Use the learn skill to process this JSON learnings array: {learnings_json}. Apply each item exactly as written, preserving scope and user corrections. Do not read INDEX.md. Commit only the files you change, if the repository rules require it. Return a concise summary of applied learnings, skipped items, and changed files.
```
Use this prompt for each document-release follow-up when `{thread_path}` has any `files_touched` entry under `companies/` or `repos/` and the installed-skill check passed:
```
Use the document-release skill for the handoff thread at {thread_path}. Update release/docs indexes only where warranted by the touched files. Do not read unrelated company knowledge. Commit only the files you change, if the repository rules require it. Return a concise summary of changes, skipped work, and changed files.
```
For synchronous fallback, invoke `Skill` with `/learn {learnings_json}` or `/document-release {thread_path}` as applicable. Do not call `claude -p`.
#### Auto-file hq-core deficiencies
Step 3 already ran auto-file once (skip it there with `--no-autofile`). Keep the `autofile` field of the Step 3 JSON as `{autofile_result}`. A non-zero auto-file exit stops `hq core handoff run` with that code after printing the JSON; report `{autofile_result}` and continue with the follow-ups. Auto-file files at most one `hq feedback bug` report per handoff and only on public installs:
- Builder machines never file. A builder machine has `repos/private/hq-core-staging` and a successful `git push --dry-run` there (same test as the builder route below); a staging folder that cannot push files like a public install.
- Only `kind: "hq-core"` deficiencies go in. The body has one section per item (lever, severity, summary, evidence, proposed fix) plus the thread's `system_info` block. The title is the highest-severity summary.
- Zero hq-core items: nothing is filed.
- Dedupe: a hash of lever and summary per item is recorded in `workspace/handoff-autofile/filed.json`. Items filed in the last 7 days are omitted; if all are omitted, nothing is filed.
- `HQ_HANDOFF_AUTOFILE=0` disables filing. Items still stay in the thread and the report.
- The body is scanned with `core/scripts/lib/secret-patterns.sh` before submit. A match aborts the submit.
Results: `filed: <id>`, `skipped: <reason>`, `aborted: <reason>`, or `failed: <reason>`. Do not retry a failed or aborted submit.
#### Builder route: draft hq-core fixes as a staging PR
Step 3 already ran the builder route check once, after finalize succeeded (skip it there with `--no-builder-route`). Act on it after the follow-ups. The `builder_route` field of the Step 3 JSON is `route: builder` or `route: public (<reason>)`. The builder test passes only when `repos/private/hq-core-staging` is a git repo and `git push --dry-run` to its origin succeeds. On the public route, the auto-file step above already covered hq-core items; set `{builder_pr_result}` to `none (<reason>)` and stop here. `HQ_HANDOFF_BUILDER_ROUTE=0` forces the public route.
On the builder route the `builder_brief` field is `brief: <path>` or `brief: none (<reason>)`. With no brief, set `{builder_pr_result}` to `none (<reason>)`. With a brief, dispatch one visible fix agent through the same routes as the follow-ups above: Codex `spawn_agent` then `wait_agent`, else Claude `Task`/`Agent`. Never use `claude -p` or a hidden background process. If neither visible route exists, do not run the fixes in this parent; set `{builder_pr_result}` to `none (no visible agent dispatch available)`.
Give the agent this prompt, with the brief path filled in:
> Read {brief_path} and follow it exactly. Work only in repos/private/hq-core-staging. Create the named branch off origin/main, apply the listed hq-core fixes grouped by lever, run the tests for every touched area plus the repo leak scan, and open one PR with bash core/scripts/hq-pr-create.sh -R indigoai-us/hq-core-staging. Add the manual-copy label and push one more commit when .claude/skills or .claude/commands are touched. List each applied deficiency with its evidence and the thread id in the PR body, and put skipped items (no evidence, outside hq-core, failing tests) under 'Not applied'. Never merge, never use gh pr merge or --admin, never push to main. End with 'pr: <url>' or 'pr: none (<reason>)'.
Wait for the result. Keep its final `pr:` line value as `{builder_pr_result}`. A launched agent id without a `pr:` line is `none (fix agent returned no result)`.
### 5. Detect active pipelines (cheap, keep in foreground)
```bash
# `find` (not a bare glob) so this no-ops cleanly when the dir/files are
# absent — zsh aborts a bare unmatched glob with "no matches found".
find workspace/orchestrator/_pipeline -mindepth 2 -maxdepth 2 \
-name pipeline-state.json 2>/dev/null | while read -r sf; do
# Not `status`: it is a read-only special parameter in zsh.
pipeline_status=$(jq -r '.status // ""' "$sf" 2>/dev/null)
if [ "$pipeline_status" = "in_progress" ] || [ "$pipeline_status" = "paused" ]; then
pipeline_id=$(jq -r '.pipeline_id' "$sf")
company=$(jq -r '.company' "$sf")
done_count=$(jq -r '.summary.done // 0' "$sf")
total=$(jq -r '.summary.total // 0' "$sf")
echo "Active pipeline: ${pipeline_id} (${company}) — ${done_count}/${total} done"
fi
done
```
If any active pipelines surface, mention them in the report and suggest `/run-pipeline --resume {pipeline_id}`.
### 6. Report
Chat report follows the active output style (`core/policies/hq-audience-mode.md`). Files this skill writes stay full prose. The templates below are chat-only.
**Default (`HQ`, and any style that is not `hq-operator`):** one or two short plain sentences. Do not print Scope, Dedup, Action, file paths, thread IDs, or PIDs. Do not paste the operator template.
When trusted command-report details context is present, lead with a short plain-language summary. Put useful, non-sensitive diagnostics in a collapsed `Technical details` section. Without that context, keep the summary-only format.
When trusted context is absent (for example, a routed natural-language or programmatic invocation), check the flag at report time with `HQ_CLI_BIN="$(command -v hq 2>/dev/null || true)" node .claude/hooks/command-report-details-flag.cjs`. Use expanded details only when it prints `true`; otherwise keep the summary-only format. This gate never overrides `hq-operator` style.
- Clipboard copied: `All saved. To pick up later, open a new chat and paste what's on your clipboard.`
- Clipboard not copied: `All saved. To pick up later, open a new chat and run {next_command}.`
- Active pipelines: add one plain sentence that some work is still running and a new chat can pick it up.
- Deficiencies with `kind: "local-setup"`: list them under a `Your setup` heading, one line each with the plain summary and, when `proposed_fix` is a command, the exact command to run.
- Deficiencies with `kind: "repo"`: route each to `/learn` with repo scope (`"scope": "repo:{repo}"`) through the same Step 4.5 follow-up as learnings; do not list them in chat.
- Deficiencies with `kind: "hq-core"`: add one plain line with `{autofile_result}` from Step 4.5, showing the filed feedback id or the reason nothing was filed (for example `Reported 2 HQ problems to the HQ team (feedback fb_123).` or `HQ problems noted, not reported: auto-filing is off.`). When there are zero hq-core items, still add one plain line that nothing was filed (for example `No HQ problems to report.`). On the builder route, add one more plain line with `{builder_pr_result}`: the PR link (for example `Drafted fixes for review: <url>`) or the reason no PR was opened.
- Step 1 printed `SKIPPED-COMPANY-KNOWLEDGE:` (the knowledge commit of the Step 1 changeset, reported in `knowledge_commit.result` of the Step 3 JSON): add one plain sentence that no company was bound, so company knowledge was not saved by this handoff.
- `git_bg_errors` non-empty: add one plain sentence that one knowledge folder did not save, and they can ask you to retry. No raw git dump.
If any eligible follow-up is still uncompleted after the synchronous Skill fallback, put this warning first (Auto-Clarity — the person must run a command). In the default style, lead with one plain sentence that something still needs finishing, then the recovery commands. Include the document-release recovery entry and its `Run exactly:` line only when the same installed-skill check above passed. If the skill is absent, record `document-release: skipped (skill not installed)` and omit the document-release recovery entry and command:
```
WARN: Follow-up recovery required
- Learnings: {learning_count} item(s) are durably pending in thread {thread_id} at {thread_path}.
Run exactly: /learn {learnings_json}
- Documentation: release follow-up is pending for thread {thread_id} at {thread_path}.
Run exactly: /document-release {thread_path}
```
**Operator (`/output-style hq-operator`):**
```
Handoff ready.
Thread: {thread_id}
Summary: {conversation_summary}
Git: {branch} @ {commit}
Changeset: {changeset_path}
Committed paths: {committed_paths count}
Skipped paths: {skipped_paths count, if any}
Baseline noise: {baseline_noise_count} unrelated/baseline status entries
Background work dispatched:
- handoff post ({post.launched}) → /tmp/handoff-post.log
- /learn → {Codex spawn_agent | Claude Task/Agent | synchronous Skill | durably pending}
- /document-release → {Codex spawn_agent | Claude Task/Agent | synchronous Skill | durably pending | document-release: skipped (skill not installed)}
- qmd helper (`skipped-agent` | `skipped` | worker pid) → /tmp/qmd-handoff.log
- builder fix PR → {builder_pr_result}
To continue in a fresh session:
1. Start a new session
2. Run: {next_command} — already copied to your clipboard, just paste
(resumes THIS handoff exactly; or /startwork to resume the latest
handoff / pick a new target)
If `clipboard_copied` was false, drop the "already copied" phrasing and just show the command.
If `git_bg_errors` was non-empty, append:
⚠ Personal/core knowledge repo git errors: {git_bg_errors}
```
If recovery is still needed in operator mode, put the same `WARN: Follow-up recovery required` block at the top (before `Handoff ready.`), substituting actual values and including only applicable commands.
### 7. Archive this session (optional, desktop app only)
Run this last, after the Step 6 report is written in full. Archiving ends the conversation at once, so nothing may come after it. When `/handoff-all` asked for an `HQ-RESUME:` line, write that line before this step.
Skip the step silently when `hq core handoff run` failed, or when the `archive_session` tool (`mcp__ccd_session_mgmt__archive_session`) is not available, as in the terminal CLI, Codex, and Grok. Otherwise decide once.
Never paste the user's message into a shell command. Create an empty file with `mktemp workspace/threads/.handoff-tmp/archive-args.XXXXXX`, write the user's handoff message (the optional message at the top of this skill) into it with the `Write` tool, exactly as typed, and pass the path as `--args-file`. An empty message is an empty file. Then run:
```bash
hq core handoff archive-decision --root "$PWD" --cwd "$PWD" \
--thread "{thread_path from Step 3}" --args-file "{args file}"
rm -f "{args file}"
```
Add `--repo-dir "{dir}"` for each other repo checkout this session committed or pushed in, so its branch is checked for open PRs. Add `--recovery-pending` when the Step 6 report includes the `WARN: Follow-up recovery required` block. Add `--background-running` when any background task, background Bash command, or subagent started in this session is still running.
The command reads `--archive` / `--no-archive` from the message, then `HQ_HANDOFF_ARCHIVE`, then `auto_archive` in `personal/settings/handoff.yaml` and `core/settings/handoff.yaml` (default off). `--archive` counts only as a leading flag, so "don't --archive" never archives. A wanted archive is refused when recovery is pending; when the thread file, its changeset, or the `handoff.json` pointer is missing; when the session's linked worktree has uncommitted changes, since archiving deletes that worktree; when a checked branch has an open PR; when the session has background work (`--background-running`, an active hq lane with this session as senior, or a running hq monitor aimed at it); or when the session has an ask waiting on the owner in `workspace/reports/conduct/`. A check that cannot run refuses with "could not verify".
- `archive: yes` → add one plain sentence to the end of the report saying the session is being archived and can be reopened from the Archived list. Then call `archive_session` with `session_id: "self"` and `reason: "Handoff complete"`. If the tool returns an error (the session is pinned, still working, or the user declined), say in one plain sentence that the session stayed open.
- `archive: no (off…)` → do nothing and say nothing.
- Any other `archive: no (<reason>)` → add one plain sentence saying the session was left open and why.
## Thread vs Checkpoint
Threads (current format) carry richer context: git state, worker state, learnings, searchability. Legacy checkpoints in `workspace/checkpoints/` still work but aren't written by this skill.
## Why Fresh Sessions
Fresh context = no accumulated noise, clean slate for complex tasks, follows Ralph methodology (fresh agent per task). Use handoff when a session has been running a while, you're switching task types, or you want cleaner separation between work chunks.
## Rules
- **Use visible dispatch first, then synchronous Skill only as a last fallback** — `spawn_agent` is preferred in Codex; `Task`/`Agent` is preferred in Claude Code. The parent may invoke `Skill` only after finalization and only when visible dispatch is unavailable or unconfirmed.
- **Never call `claude -p` from handoff** — unconfirmed follow-up work remains durable in the handoff thread and must emit the Step 6 recovery warning, never silently skip.
- **Do not Read INDEX.md files** — they're regenerated by bash scripts that pipe metadata through `jq -s`. Reading them into Claude's context defeats the whole point.
- **Always use `hq core handoff run` for knowledge commit + thread + commit + INDEX regen + post** — don't narrate individual steps, don't inline jq commands.
- **Changeset owns scope** — when HQ root status is noisy, scope comes from `--files-touched-json` and the generated changeset, not from whole-repo `git status`.
- **Context diet** — this skill should emit <15K tokens of tool output on a typical session. If you find yourself Reading more than 3 files, stop and rethink.
- **Session handoffs execute directly** — skip any planning-mode detour.
- **Commit flow:** personal/core knowledge repos commit only the explicit session changeset (the knowledge commit inside `hq core handoff run`, from the Step 1 file), company knowledge syncs through its vault, and finalize commits the HQ changes using explicit paths. Never `git add -A` from this skill.
## See also
- `/resumework {thread_id}` — resume THIS thread exactly in a fresh session (takes the thread id this skill prints)
- `/startwork` — the follow-up agent resumes the latest handoff, or picks a new company/project/repo
- `/checkpoint` — a lighter mid-session save
- `/delegate` — hand the project to ANOTHER person or fleet agent (ownership transfer + verified access + pickup DM), rather than to your own next session