
Session To Agent
- 1 installs
- 70 repo stars
- Updated July 26, 2026
- rysweet/amplihack
Converts a Claude Code or Copilot session transcript into a reusable goal-seeking agent by extracting goals and patterns and running amplihack new.
About
Reads a coding session transcript, extracts the primary goal, constraints, tools, and strategies, then generates a reusable goal-seeking agent with memory via the amplihack CLI. A developer uses it to productize a one-off session workflow into a re-runnable agent.
- Extracts goals, constraints, and patterns from session transcripts
- Generates agent prompt.md and runs amplihack new with memory enabled
Session To Agent by the numbers
- 1 all-time installs (skills.sh)
- Ranked #14,103 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/rysweet/amplihack --skill session-to-agentAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 70 |
| Last updated | July 26, 2026 |
| Repository | rysweet/amplihack ↗ |
What it does
Converts a Claude Code or Copilot session transcript into a reusable goal-seeking agent by extracting goals and patterns and running amplihack new.
Files
Session-to-Agent Skill
Convert an interactive coding session into a reusable goal-seeking agent with memory. The skill reads session transcripts, extracts goals and patterns, and generates a complete agent via amplihack new.
Quick Start
Step 1: Invoke the skill
User: /session-to-agentOr describe what you want:
User: Turn this session into a reusable agentStep 2: The skill extracts from the current session
It analyzes the session transcript to identify:
- Primary goal and sub-goals
- Constraints (technical, operational, time)
- Tools and commands used
- Patterns and strategies observed
- Domain knowledge gained during the session
Step 3: A goal-seeking agent is generated
The skill writes a prompt.md file and runs:
amplihack new --file prompt.md --sdk copilot --enable-memoryThe generated agent can be re-run autonomously to repeat or extend the session's workflow.
What It Extracts
| Category | Examples |
|---|---|
| Primary Goal | "Implement JWT authentication for the REST API" |
| Sub-Goals | Token generation, middleware, refresh flow, tests |
| Constraints | Must use RS256, tokens expire in 1h, no external IdP |
| Tools Used | pytest, ruff, git, curl, Bash, Read, Edit |
| Patterns | Outside-in TDD, error-first validation, retry logic |
| Domain Knowledge | JWT spec details, library quirks, API contract rules |
| Success Criteria | All tests pass, CI green, security review approved |
Customizing the Generated Agent
After generation, you can refine the agent by editing:
prompt.md-- the goal description and constraintsplan.yaml-- the execution phases and dependenciesskills.yaml-- the required skills and tool mappingsmetadata.json-- SDK, memory, and multi-agent settings
Re-run the generator after edits:
amplihack new --file prompt.md --sdk copilot --enable-memoryMemory Export (Optional)
When --enable-memory is used, the skill can optionally export the current session's Kuzu memory database as the agent's initial knowledge base. This seeds the new agent with facts, discoveries, and context from the session that created it.
# Export is offered interactively after agent generation
# Or specify explicitly:
amplihack new --file prompt.md --enable-memory --sdk copilotWhen to Use This Skill
- After completing a multi-step workflow you want to repeat
- When a session reveals a reusable process worth automating
- To hand off a workflow to a colleague as a runnable agent
- To create a CI/CD or SRE automation agent from manual steps
- When session knowledge should persist as an executable artifact
When NOT to Use This Skill
- For trivial single-command tasks (use a script instead)
- When the session was exploratory with no clear repeatable goal
- When the workflow is already captured as a recipe or agent
Supporting Files
| Need | File |
|---|---|
| Full extraction algorithm and templates | reference.md |
| Worked examples with real sessions | examples.md |
| Goal-seeking agent design guidance | goal-seeking-agent-pattern skill |
| Knowledge extraction from sessions | knowledge-extractor skill |
Session-to-Agent: Examples
Worked examples showing how sessions are converted into goal-seeking agents.
Example 1: Security Analyst Session to Security Audit Agent
Session Summary
A user spent 90 minutes manually auditing a Python web API for security issues. They checked dependencies, reviewed authentication middleware, tested for SQL injection, and verified CORS headers.
Extracted Context
{
"primary_goal": "Audit a Python web API for common security vulnerabilities",
"sub_goals": [
"Scan dependencies for known CVEs",
"Review authentication and authorization middleware",
"Test endpoints for SQL injection and XSS",
"Verify CORS, CSP, and security headers",
"Generate a severity-ranked findings report"
],
"constraints": [
"Must not modify production database",
"Only test against staging environment",
"Complete within 2 hours"
],
"tools_used": [
"pip-audit",
"bandit",
"curl",
"sqlmap (manual equivalent)",
"Grep for pattern scanning",
"Read for code review"
],
"patterns_observed": [
"Scan dependencies first (fastest, highest signal)",
"Static analysis before dynamic testing",
"Check authentication before authorization",
"Verify error responses do not leak stack traces"
],
"domain_knowledge": [
"FastAPI's Depends() system for middleware injection",
"SQLAlchemy parameterized queries prevent most SQL injection",
"CORS misconfiguration is the most common finding in internal APIs"
],
"success_criteria": [
"All OWASP Top 10 categories checked",
"Zero critical findings or all critical findings remediated",
"Report generated with severity levels and remediation steps"
],
"failure_modes": [
"pip-audit can miss vendored dependencies -- supplement with Snyk or OSV",
"Dynamic testing requires running server -- add health check first"
],
"estimated_complexity": "moderate",
"suggested_agent_name": "api-security-auditor"
}Generated prompt.md
# Goal: Audit a Python web API for common security vulnerabilities
## Objective
Audit a Python web API for common security vulnerabilities.
### Sub-Goals
- Scan dependencies for known CVEs
- Review authentication and authorization middleware
- Test endpoints for SQL injection and XSS
- Verify CORS, CSP, and security headers
- Generate a severity-ranked findings report
## Success Criteria
- All OWASP Top 10 categories checked
- Zero critical findings or all critical findings remediated
- Report generated with severity levels and remediation steps
## Constraints
- Must not modify production database
- Only test against staging environment
- Complete within 2 hours
## Domain Knowledge
- FastAPI's Depends() system for middleware injection
- SQLAlchemy parameterized queries prevent most SQL injection
- CORS misconfiguration is the most common finding in internal APIs
## Patterns and Strategies
- Scan dependencies first (fastest, highest signal)
- Static analysis before dynamic testing
- Check authentication before authorization
- Verify error responses do not leak stack traces
## Tools and Capabilities Required
- pip-audit
- bandit
- curl
- sqlmap (manual equivalent)
- Grep for pattern scanning
- Read for code review
## Failure Modes and Recovery
- pip-audit can miss vendored dependencies -- supplement with Snyk or OSV
- Dynamic testing requires running server -- add health check firstAgent Generation Command
amplihack new \
--file /tmp/session-agent-prompt.md \
--name api-security-auditor \
--sdk copilot \
--enable-memory \
--output ./goal_agents/api-security-auditorResult
A 4-phase agent:
1. Dependency Audit -- runs pip-audit and bandit 2. Code Review -- static analysis of auth, input validation, error handling 3. Dynamic Testing -- tests endpoints with crafted payloads 4. Reporting -- generates markdown report with findings and remediation
---
Example 2: Code Review Session to Code Review Agent
Session Summary
A user conducted a thorough code review of a PR with 15 changed files. They checked naming conventions, tested edge cases, verified error handling, and confirmed test coverage. The session took 45 minutes.
Extracted Context
{
"primary_goal": "Review a pull request for code quality, correctness, and test coverage",
"sub_goals": [
"Check naming conventions and code style",
"Verify error handling in all new functions",
"Identify missing edge case tests",
"Confirm type annotations are complete",
"Review for philosophy compliance (ruthless simplicity)"
],
"constraints": [
"Must not push changes to the PR branch",
"Review all changed files, not just a sample",
"Flag issues with severity levels (critical, warning, suggestion)"
],
"tools_used": [
"gh pr diff",
"Read for file inspection",
"Grep for pattern matching",
"ruff check --select ALL",
"mypy for type checking"
],
"patterns_observed": [
"Read the PR description first to understand intent",
"Diff-first review: scan all changes before deep-diving",
"Check test files alongside implementation files",
"Look for missing __all__ exports in module files",
"Verify docstrings match actual behavior"
],
"domain_knowledge": [
"Project uses ruff for linting with strict config",
"All public functions require type annotations per project policy",
"Test files must mirror src/ structure"
],
"success_criteria": [
"All critical issues identified and documented",
"Review comments posted to PR with severity tags",
"No false positives in critical category"
],
"failure_modes": [
"Large diffs can exceed context window -- chunk by file",
"Renamed files appear as delete+add -- check git rename detection"
],
"estimated_complexity": "moderate",
"suggested_agent_name": "pr-code-reviewer"
}Agent Generation Command
amplihack new \
--file /tmp/session-agent-prompt.md \
--name pr-code-reviewer \
--sdk copilot \
--enable-memoryResult
A 3-phase agent:
1. PR Context -- reads PR description, fetches diff, identifies changed files 2. Deep Review -- reviews each file for style, correctness, types, tests 3. Report -- generates review summary with categorized findings
---
Example 3: Data Analysis Session to Data Pipeline Agent
Session Summary
A user spent 2 hours building a data transformation pipeline: fetching data from three CSV sources, cleaning and merging them, running validation checks, and exporting the result to a PostgreSQL database. They iterated on data quality rules until the pipeline produced clean output.
Extracted Context
{
"primary_goal": "Build a data pipeline that ingests CSVs, cleans and merges data, validates quality, and loads into PostgreSQL",
"sub_goals": [
"Fetch and parse 3 CSV sources with different schemas",
"Normalize column names and types across sources",
"Merge records on shared key with deduplication",
"Apply quality rules (completeness, range checks, format validation)",
"Load validated records into PostgreSQL staging table",
"Generate quality report with pass/fail counts"
],
"constraints": [
"Must handle missing values gracefully (default or skip, never error)",
"Idempotent: safe to re-run without duplicating data",
"Must complete within 30 minutes for 500K total records"
],
"tools_used": [
"pandas for data manipulation",
"psycopg2 for PostgreSQL connection",
"Bash for file operations",
"Python scripts for transformation logic"
],
"patterns_observed": [
"Validate schema before processing (fail fast on wrong format)",
"Log rejected records to a separate file for manual review",
"Use UPSERT (INSERT ON CONFLICT UPDATE) for idempotency",
"Process sources in parallel since they are independent"
],
"domain_knowledge": [
"Source A uses ISO dates, Source B uses US format, Source C uses epoch",
"Customer ID field has leading zeros that must be preserved as strings",
"PostgreSQL COPY is 10x faster than INSERT for bulk loads"
],
"success_criteria": [
"All 3 sources successfully ingested",
"Quality checks pass with >95% completeness",
"Data loaded into PostgreSQL staging table",
"Quality report generated with metrics"
],
"failure_modes": [
"CSV encoding issues (Latin-1 vs UTF-8) -- detect and convert",
"PostgreSQL connection timeout -- retry with exponential backoff",
"Memory issues with large CSVs -- use chunked reading"
],
"estimated_complexity": "moderate",
"suggested_agent_name": "csv-to-postgres-pipeline"
}Agent Generation Command
amplihack new \
--file /tmp/session-agent-prompt.md \
--name csv-to-postgres-pipeline \
--sdk copilot \
--enable-memory \
--multi-agentResult
A 4-phase agent with multi-agent architecture:
1. Ingestion (parallel sub-agents) -- each source gets its own sub-agent 2. Transformation -- normalize schemas, merge, deduplicate 3. Validation -- apply quality rules, log rejections 4. Loading -- bulk load to PostgreSQL, generate quality report
The --multi-agent flag creates a coordinator agent that orchestrates three ingestion sub-agents in parallel, then sequences through transformation, validation, and loading.
---
Example 4: Debugging Session to Diagnostic Agent
Session Summary
A user spent 60 minutes debugging a flaky integration test. The test passed locally but failed in CI. The root cause was a race condition in async database cleanup between tests.
Extracted Context
{
"primary_goal": "Diagnose and fix flaky integration tests that pass locally but fail in CI",
"sub_goals": [
"Compare local and CI environments (Python version, OS, dependencies)",
"Identify test isolation issues (shared state between tests)",
"Check for race conditions in async test fixtures",
"Verify database cleanup between test cases",
"Confirm fix by running tests in CI-like conditions locally"
],
"constraints": [
"Must not change test behavior, only fix flakiness",
"Fix must work in both local and CI environments",
"Cannot add sleep-based waits (use proper synchronization)"
],
"tools_used": [
"pytest --tb=long -x for detailed failure output",
"pytest -p no:randomly to control test ordering",
"git bisect to find introducing commit",
"docker for CI environment reproduction"
],
"patterns_observed": [
"Run failing test in isolation first to check if it is test interaction",
"Check pytest fixtures for shared mutable state",
"Look for missing await in async teardown",
"Compare environment variables between local and CI"
],
"domain_knowledge": [
"pytest-asyncio event_loop fixture is session-scoped by default",
"PostgreSQL connections persist across tests unless explicitly closed",
"CI runs tests in parallel by default which exposes race conditions"
],
"success_criteria": [
"Test passes reliably in 10 consecutive CI runs",
"No new test failures introduced",
"Root cause documented in test docstring"
],
"failure_modes": [
"git bisect may point to unrelated commit if flakiness is probabilistic",
"Docker environment may not perfectly match CI -- check CI config"
],
"estimated_complexity": "moderate",
"suggested_agent_name": "flaky-test-diagnostician"
}Agent Generation Command
amplihack new \
--file /tmp/session-agent-prompt.md \
--name flaky-test-diagnostician \
--sdk copilot \
--enable-memoryResult
A 5-phase diagnostic agent:
1. Environment Comparison -- diff local vs CI config 2. Isolation Testing -- run failing test alone vs with neighbors 3. Root Cause Analysis -- check fixtures, shared state, async cleanup 4. Fix Application -- apply targeted fix based on diagnosis 5. Verification -- run test suite multiple times to confirm stability
---
Usage Pattern Summary
| Session Type | Agent Type | Key Flags |
|---|---|---|
| Security audit | Audit agent | --enable-memory |
| Code review | Review agent | --enable-memory |
| Data pipeline | Pipeline agent | --multi-agent |
| Debugging/diagnostics | Diagnostic agent | --enable-memory |
| Infrastructure setup | Automation agent | --multi-agent --enable-spawning |
| API development | API builder agent | --enable-memory |
Session-to-Agent: Reference
Complete technical reference for the session-to-agent skill. Covers the extraction algorithm, prompt template, memory export, CLI integration, and configuration options.
1. Extraction Algorithm
The skill follows a five-stage pipeline to convert a session transcript into a goal-seeking agent.
Stage 1: Locate Session Transcript
Session transcripts are stored as JSONL files under the Claude projects directory. The skill finds the current or most recent session file.
from pathlib import Path
import json
def find_session_transcript(project_dir: str | None = None) -> Path | None:
"""Find the most recent session JSONL file for this project.
Claude Code stores session transcripts as JSONL files in:
~/.claude/projects/<project-slug>/<session-id>.jsonl
The project slug is derived from the working directory path with
slashes replaced by dashes.
"""
if project_dir is None:
# Derive from cwd
cwd = Path.cwd().resolve()
slug = str(cwd).replace("/", "-").lstrip("-")
project_dir = Path.home() / ".claude" / "projects" / slug
project_path = Path(project_dir)
if not project_path.exists():
return None
jsonl_files = sorted(
project_path.glob("*.jsonl"),
key=lambda f: f.stat().st_mtime,
reverse=True,
)
return jsonl_files[0] if jsonl_files else None
def parse_transcript(path: Path) -> list[dict]:
"""Parse a session JSONL file into a list of message entries."""
entries = []
with open(path) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
entries.append(json.loads(line))
except json.JSONDecodeError:
continue
return entriesStage 2: Extract Session Context
From the parsed transcript, extract structured information about the session's goals, constraints, tools, and patterns.
EXTRACTION_PROMPT = """
Analyze this session transcript and extract structured information for
generating a reusable goal-seeking agent.
Return a JSON object with these fields:
{
"primary_goal": "One sentence describing the main objective",
"sub_goals": ["List of specific sub-tasks accomplished or attempted"],
"constraints": ["Technical, operational, or time constraints observed"],
"tools_used": ["CLI tools, APIs, libraries, and Claude Code tools used"],
"patterns_observed": ["Strategies, approaches, and problem-solving patterns"],
"domain_knowledge": ["Domain-specific facts and insights gained"],
"success_criteria": ["How success was measured or should be measured"],
"failure_modes": ["What went wrong and how it was recovered"],
"estimated_complexity": "simple | moderate | complex",
"suggested_agent_name": "kebab-case name for the agent"
}
IMPORTANT:
- Focus on REPEATABLE aspects of the workflow
- Omit session-specific details (specific file paths, temp values)
- Generalize constraints where possible
- Include both explicit and implicit goals
Transcript (last 5000 characters):
{transcript_tail}
"""
def extract_session_context(entries: list[dict]) -> dict:
"""Extract structured context from transcript entries.
This function builds a text representation of the session and
uses the extraction prompt above to produce structured output.
In practice, Claude Code itself performs this extraction as part
of skill execution -- the prompt is provided here as reference.
"""
# Build text from human and assistant messages
text_parts = []
for entry in entries:
role = entry.get("role", "")
content = entry.get("content", "")
if isinstance(content, list):
# Handle content blocks (text, tool_use, tool_result)
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
text_parts.append(f"[{role}] {block['text']}")
elif isinstance(content, str):
text_parts.append(f"[{role}] {content}")
transcript_text = "\n".join(text_parts)
# Take the last ~5000 chars to stay within token limits
transcript_tail = transcript_text[-5000:]
# In actual execution, Claude reads the transcript and applies
# the extraction prompt internally. The result is a dict matching
# the schema above.
return {
"transcript_tail": transcript_tail,
"prompt": EXTRACTION_PROMPT.format(transcript_tail=transcript_tail),
}Stage 3: Generate Prompt File
Transform the extracted context into a prompt.md file suitable for amplihack new --file.
PROMPT_TEMPLATE = """# Goal: {primary_goal}
## Objective
{primary_goal}
### Sub-Goals
{sub_goals_md}
## Success Criteria
{success_criteria_md}
## Constraints
{constraints_md}
## Domain Knowledge
{domain_knowledge_md}
## Patterns and Strategies
{patterns_md}
## Tools and Capabilities Required
{tools_md}
## Failure Modes and Recovery
{failure_modes_md}
"""
def generate_prompt_file(context: dict, output_path: Path) -> Path:
"""Generate a prompt.md file from extracted session context.
Args:
context: Structured extraction result (see Stage 2 schema).
output_path: Where to write the prompt file.
Returns:
Path to the generated prompt.md file.
"""
def to_md_list(items: list[str]) -> str:
if not items:
return "- None identified\n"
return "\n".join(f"- {item}" for item in items) + "\n"
content = PROMPT_TEMPLATE.format(
primary_goal=context.get("primary_goal", "Unnamed goal"),
sub_goals_md=to_md_list(context.get("sub_goals", [])),
success_criteria_md=to_md_list(context.get("success_criteria", [])),
constraints_md=to_md_list(context.get("constraints", [])),
domain_knowledge_md=to_md_list(context.get("domain_knowledge", [])),
patterns_md=to_md_list(context.get("patterns_observed", [])),
tools_md=to_md_list(context.get("tools_used", [])),
failure_modes_md=to_md_list(context.get("failure_modes", [])),
)
output_path.write_text(content)
return output_pathStage 4: Run Agent Generator
Invoke the amplihack new CLI to create the goal-seeking agent.
amplihack new \
--file /tmp/session-agent-prompt.md \
--name "${suggested_agent_name}" \
--sdk copilot \
--enable-memory \
--output ./goal_agents/${suggested_agent_name}The CLI pipeline:
1. PromptAnalyzer -- parses the prompt.md into a GoalDefinition 2. ObjectivePlanner -- generates a multi-phase ExecutionPlan 3. SkillSynthesizer -- maps capabilities to skills and SDK tools 4. AgentAssembler -- creates a GoalAgentBundle 5. GoalAgentPackager -- writes the agent directory
Stage 5: Memory Export (Optional)
When --enable-memory is set, the skill offers to export the current session's Kuzu memory database as the agent's initial knowledge base.
import shutil
from pathlib import Path
def export_memory_to_agent(
agent_dir: Path,
kuzu_db_path: Path | None = None,
) -> bool:
"""Copy the current Kuzu DB into the agent's data directory.
Args:
agent_dir: Root directory of the generated agent.
kuzu_db_path: Path to the Kuzu database directory.
Defaults to .amplihack/kuzu_db in the project root.
Returns:
True if export succeeded, False otherwise.
"""
if kuzu_db_path is None:
# Default location in amplihack projects
kuzu_db_path = Path(".amplihack") / "kuzu_db"
if not kuzu_db_path.exists():
return False
dest = agent_dir / "data" / "initial_memory"
dest.mkdir(parents=True, exist_ok=True)
try:
shutil.copytree(kuzu_db_path, dest / "kuzu_db", dirs_exist_ok=True)
return True
except Exception:
return False2. Configuration Options
| Option | Default | Description |
|---|---|---|
--sdk | copilot | Target SDK: copilot, claude, microsoft, mini |
--enable-memory | false | Enable Kuzu memory backend for the agent |
--multi-agent | false | Generate coordinator + sub-agent architecture |
--enable-spawning | false | Allow dynamic sub-agent spawning (requires multi-agent) |
--name | auto | Custom agent name (kebab-case) |
--output | ./goal_agents | Output directory for the generated agent |
--verbose | false | Show detailed generation logs |
3. Integration Points
With goal-seeking-agent-pattern Skill
The session-to-agent skill produces agents that follow the goal-seeking agent pattern. The extracted goals map to GoalDefinition, execution phases map to ExecutionPlan, and tools map to SkillDefinition objects.
With knowledge-extractor Skill
Before generating the agent, the skill can invoke the knowledge-extractor to capture discoveries and patterns from the session. These feed into the agent's initial memory when --enable-memory is used.
With session-learning Skill
Session learnings (from ~/.amplihack/.claude/data/learnings/) can be injected into the generated agent's prompt as domain knowledge, ensuring cross-session insights are preserved.
With self-improving-agent-builder Skill
After generating the agent, the self-improving-agent-builder can run eval loops to measure and improve the agent's performance over time.
4. Session Transcript Format
Claude Code stores session transcripts as JSONL files. Each line is a JSON object representing a message or event:
{"type": "human", "role": "user", "content": "Add JWT auth to the API"}
{"type": "assistant", "role": "assistant", "content": [{"type": "text", "text": "I'll implement..."}]}
{"type": "assistant", "role": "assistant", "content": [{"type": "tool_use", "name": "Read", ...}]}
{"type": "tool_result", "content": "file contents..."}The extraction algorithm processes both text content and tool usage to understand the full scope of the session's work.
5. Error Handling
| Scenario | Handling |
|---|---|
| No session transcript found | Report error, suggest running from active session |
| Transcript too short (<10 entries) | Warn that extraction may be incomplete |
amplihack new fails | Show error, preserve prompt.md for manual retry |
| Kuzu DB not found | Skip memory export, agent works without it |
| Extraction returns empty goals | Prompt user for manual goal description |
6. Output Structure
After successful generation, the agent directory contains:
goal_agents/<agent-name>/
agent.md # Agent definition with goal and phases
prompt.md # The goal prompt (editable for re-generation)
main.py # Entry point for running the agent
plan.yaml # Multi-phase execution plan
skills.yaml # Required skills and tool mappings
metadata.json # SDK, memory, and configuration metadata
data/
initial_memory/ # (Optional) Exported Kuzu DB snapshot
kuzu_db/