cat:collect-results
Gather results from completed subagent including commits, metrics, and state updates
What this skill does
# Collect Results
## Purpose
Extract work products from a completed subagent's worktree, including commit history, code changes,
token metrics, and status information. Prepares the subagent's work for integration back into the
parent task branch.
## When to Use
- Subagent has signaled completion
- Subagent has hit context limits and partial results are needed
- Monitoring indicates subagent is stalled or needs intervention
- Before merging subagent branch to task branch
## Workflow
**Progress Output (MANDATORY):**
Display collection progress using visible feedback symbols:
**On collection start:**
```
◆ Collecting results: {subagent-id}...
```
**On successful collection:**
```
✓ Subagent complete: {N}K tokens · {N} commits
→ Files changed: {N}
→ Status: {success|partial|failed}
```
**On collection with issues:**
```
⚠ Subagent complete with concerns: {N}K tokens · {N} commits
→ Compaction events: {N}
→ Discovered issues: {N}
```
These symbols match the phase-based progress format used in `/cat:work`.
Steps: Verify completion, Extract commits, Parse metrics, Extract issues, Report to user, Update STATE.md
### 1. Verify Subagent Completion
Check for completion marker file (fast path, no session parsing):
```bash
WORKTREE=".worktrees/${TASK}-sub-${UUID}"
COMPLETION_FILE="${WORKTREE}/.completion.json"
# Check for completion marker (preferred - lightweight)
if [ -f "$COMPLETION_FILE" ]; then
echo "Subagent completed"
cat "$COMPLETION_FILE" # Contains status, tokensUsed, compactionEvents, summary
else
echo "Subagent not yet complete or marker not written"
fi
```
**Why completion marker?** Reading `.completion.json` (~200 bytes) is far cheaper than parsing
the session JSONL file (potentially megabytes of conversation history).
### 2. Extract Commit History
```bash
cd "${WORKTREE}"
# Get commits made by subagent (since branch creation)
git log --oneline origin/HEAD..HEAD
# Get detailed commit info
git log --format="%H %s" origin/HEAD..HEAD > /tmp/subagent-commits.txt
```
### 3. Parse Token Metrics
**CRITICAL: Token totals must span ALL compaction events.**
Session files contain entries BEFORE and AFTER any compaction. The jq command below parses ALL
assistant entries regardless of when compaction occurred, providing cumulative totals.
**Preferred: Read from completion marker** (already computed by subagent):
```bash
COMPLETION_FILE="${WORKTREE}/.completion.json"
if [ -f "$COMPLETION_FILE" ]; then
TOTAL_TOKENS=$(jq -r '.tokensUsed // 0' "$COMPLETION_FILE")
INPUT_TOKENS=$(jq -r '.inputTokens // 0' "$COMPLETION_FILE")
OUTPUT_TOKENS=$(jq -r '.outputTokens // 0' "$COMPLETION_FILE")
COMPACTIONS=$(jq -r '.compactionEvents // 0' "$COMPLETION_FILE")
STATUS=$(jq -r '.status // "unknown"' "$COMPLETION_FILE")
fi
```
**Fallback: Use token-report skill** for accurate context-based metrics:
If `.completion.json` is missing or has no token data, invoke `/cat:token-report` which extracts
`totalTokens` from Task tool completions in the session file. This metric represents actual context
processed (matching CLI "Done" display) rather than cumulative API response tokens.
```bash
SESSION_ID=$(cat "${WORKTREE}/.session_id" 2>/dev/null)
if [ -n "$SESSION_ID" ] && [ ! -f "$COMPLETION_FILE" ]; then
echo "NOTE: .completion.json missing. Token metrics available via /cat:token-report"
# The token-report skill extracts totalTokens from toolUseResult in session JSONL
fi
```
**Why totalTokens from toolUseResult?** The session file stores Task tool completion results with
`totalTokens` which represents the full context the subagent processed. This matches the CLI
"Done (X tool uses · XK tokens · Xm Xs)" display and is the correct metric for monitoring.
### 4. Extract Discovered Issues
If curiosity was medium or high, the subagent may have noted issues in `.completion.json`:
```bash
COMPLETION_FILE="${WORKTREE}/.completion.json"
ISSUES=$(jq -r '.discoveredIssues // []' "$COMPLETION_FILE")
ISSUE_COUNT=$(echo "$ISSUES" | jq 'length')
if [ "$ISSUE_COUNT" -gt 0 ]; then
echo "Discovered issues: $ISSUE_COUNT"
echo "$ISSUES" | jq -r '.[] | "- [\(.severity)] \(.file):\(.line) - \(.description)"'
fi
```
**Issue format in .completion.json:**
```json
{
"discoveredIssues": [
{
"file": "src/parser/Lexer.java",
"line": 142,
"type": "code-quality",
"severity": "medium",
"description": "Duplicate token validation logic could be extracted",
"benefitCost": 2.5
}
]
}
```
**Important:** The main agent handles these issues based on the `patience` setting (see
work.md handle_discovered_issues step). This skill only extracts them.
### 5. Read Subagent Work Products
```bash
cd "${WORKTREE}"
# List modified files
git diff --name-only origin/HEAD..HEAD
# Get full diff for review
git diff origin/HEAD..HEAD > /tmp/subagent-changes.diff
```
### 6. Extract Subagent Status
If subagent maintained a STATE.md or status file:
```bash
# Read subagent's final state
cat "${WORKTREE}/.claude/cat/tasks/${TASK}/STATE.md"
# Or check for completion report
cat "${WORKTREE}/COMPLETION_REPORT.md" 2>/dev/null
```
### 7. MANDATORY: Report Token Metrics to User
**CRITICAL (M096): Verify token values before reporting - never estimate or guess.**
Before presenting metrics, verify you have ACTUAL measured values:
```bash
# Verify .completion.json exists and contains numeric values
if [ -f "$COMPLETION_FILE" ]; then
TOTAL=$(jq -r '.tokensUsed // 0' "$COMPLETION_FILE")
if [ "$TOTAL" -gt 0 ]; then
echo "Token metrics verified from .completion.json"
else
echo "WARNING: No token data in .completion.json - parsing session file"
# Fall back to session file parsing (see step 3)
fi
fi
# Sanity check: implementation subagents typically use 30K-150K tokens
# If value seems unreasonably low (< 10K for implementation), verify source
```
**Anti-pattern (M096):** Presenting token metrics without actually reading them from `.completion.json`
or session file. Claiming "subagent used X tokens" without verification is a measurement bug.
**Before updating state, present token metrics to user.**
**CRITICAL: Output directly WITHOUT code blocks (M125).** Markdown `**bold**` renders correctly
when output as plain text, but shows as literal asterisks inside triple-backtick code blocks.
Output format (do NOT wrap in ```):
## Subagent Execution Report
**Subagent:** a1b2c3d4
**Task:** 1.2-implement-parser
**Status:** success
**Token Usage:**
- Total tokens: 65,000 (32.5% of 200K context)
- Input tokens: 45,000
- Output tokens: 20,000
- Compaction events: 0
- Execution quality: Good ✓
**Work Summary:**
- Commits: 5
- Files changed: 12
- Lines: +450 / -120
**Discovered Issues:** 2 (will be handled by main agent based on patience setting)
**Why mandatory:** Users cannot observe subagent execution. This report is the only visibility
into what happened during subagent execution and whether quality may have degraded.
**If compaction events > 0, add warning:**
```
⚠️ CONTEXT COMPACTION DETECTED
The subagent experienced context pressure and may have produced lower quality output.
Consider invoking /cat:decompose-task for similar tasks in the future.
```
### 8. Update Parent STATE.md
Record collection results in parent's tracking:
```yaml
subagents:
- id: a1b2c3d4
task: 1.2-implement-parser
status: collected # Changed from 'running'
collected_at: 2026-01-10T15:00:00Z
results:
commits: 5
files_changed: 12
lines_added: 450
lines_removed: 120
metrics:
total_tokens: 65000
input_tokens: 45000
output_tokens: 20000
compaction_events: 0
ready_for_merge: true
reported_to_user: true # MANDATORY - metrics must be shown to user
```
### 9. Prepare for Merge
```bash
# Ensure subagent branch is up to date
cd "${WORKTREE}"
git status
# Note any uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
echo "WARNING: Uncommitted changes inRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.