ULUSOY_DIGITAL
← Tüm Yazılar
Teknoloji

Build a SuperClaude Framework Workflow with Commands, Agents, Modes, and Session Memory

Otomatik Bot 24 May 2026 0 görüntülenme
Build a SuperClaude Framework Workflow with Commands, Agents, Modes, and Session Memory

In this tutorial, we build an advanced workflow using the SuperClaude Framework as a structured layer on top of the Anthropic API. We clone the framework, discover its commands, agents, and modes, and create a Python bridge that dynamically loads the relevant Markdown behavior files into the system prompt before each model call. Through practical examples, we explore brainstorming, frontend implementation, security analysis, business strategy, deep research planning, token-efficient responses, and a chained multi-step development workflow with session save and load support. We also learn how these reusable framework assets make our prompts more consistent, role-aware, and suitable for complex AI-assisted software development tasks.

import subprocess, sys, os, json, textwrap, getpass, time
from pathlib import Path
def _pip(pkg):
   subprocess.run([sys.executable, "-m", "pip", "install", "-q", pkg], check=True)
for mod, pkg in [("anthropic", "anthropic>=0.40.0"), ("rich", "rich")]:
   try:
       __import__(mod)
   except ImportError:
       print(f"📦 Installing {pkg} …")
       _pip(pkg)
from anthropic import Anthropic
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
console = Console()
REPO_DIR = Path("/content/SuperClaude_Framework")
if not REPO_DIR.exists():
   console.print("📥 Cloning SuperClaude Framework …", style="cyan")
   subprocess.run(
       ["git", "clone", "--depth", "1",
        "https://github.com/SuperClaude-Org/SuperClaude_Framework.git",
        str(REPO_DIR)],
       check=True, capture_output=True,
   )
console.print(f"✅ Framework ready at {REPO_DIR}", style="green")

We install the required Python packages and import the core libraries needed for the tutorial. We initialize the Rich console so that our Colab output looks clean, structured, and readable. We then clone the SuperClaude Framework repository and make sure the framework files are available locally.

def discover_assets(root: Path) -> dict:
   """Walk the repo and bucket every .md by folder keyword."""
   buckets = {"commands": {}, "agents": {}, "modes": {}}
   for md in root.rglob("*.md"):
       rel = str(md.relative_to(root)).lower().replace("\\", "/")
       name = md.stem.lower()
       if "/commands/" in f"/{rel}":
           buckets["commands"].setdefault(name, md)
       elif "/agents/" in f"/{rel}":
           buckets["agents"].setdefault(name, md)
       elif "/modes/" in f"/{rel}" or "mode" in name:
           buckets["modes"].setdefault(name, md)
   return buckets
ASSETS = discover_assets(REPO_DIR)
console.print(
   f"🔎 Loaded {len(ASSETS['commands'])} commands, "
   f"{len(ASSETS['agents'])} agents, {len(ASSETS['modes'])} modes",
   style="bold magenta",
)
def show_inventory():
   for kind in ("commands", "agents", "modes"):
       items = sorted(ASSETS[kind])
       if not items: continue
       t = Table(title=f"{kind.title()} ({len(items)})")
       t.add_column("Name", style="cyan")
       for n in items: t.add_row(n)
       console.print(t)
show_inventory()
if "ANTHROPIC_API_KEY" not in os.environ:
   try:
       from google.colab import userdata
       os.environ["ANTHROPIC_API_KEY"] = userdata.get("ANTHROPIC_API_KEY")
       console.print("🔑 Loaded ANTHROPIC_API_KEY from Colab secrets.", style="green")
   except Exception:
       os.environ["ANTHROPIC_API_KEY"] = getpass.getpass(
           "🔑 Paste your ANTHROPIC_API_KEY (hidden): "
       )
client = Anthropic()
MODEL  = "claude-sonnet-4-5"

We scan the cloned repository and discover all Markdown-based commands, agents, and modes. We organize these assets into separate buckets so they can be loaded dynamically during model calls. We also configure the Anthropic API key and set the Claude model that powers the SuperClaude bridge.

class SuperClaude:
   """
   Mimics what Claude Code does at session start:
     • reads Markdown behavior files for the active command/agent/modes,
     • concatenates them into one system prompt,
     • runs the conversation through the Anthropic API.
   """
   BASE_SYSTEM = textwrap.dedent("""
   You are operating inside the SuperClaude Framework — a structured
   development platform layered on top of Claude. Treat the <framework>
   block as your behavioral contract for this turn. If a behavioral
   instruction conflicts with the user request, prefer the instruction.
   Begin every answer with a short '▶ Active context:' line that names the
   command / agent / modes currently in effect.
   """).strip()
   def __init__(self, model=MODEL):
       self.model, self.history = model, []
   def _load(self, kind, name):
       if not name: return ""
       p = ASSETS[kind].get(name.lower())
       return p.read_text(encoding="utf-8", errors="ignore") if p else \
              f"# {kind}:{name} (not found — using inline defaults)"
   def _system(self, command=None, agent=None, modes=None, extra=None):
       parts = [self.BASE_SYSTEM, "<framework>"]
       if command: parts += [f"## Command /sc:{command}", self._load("commands", command)]
       if agent:   parts += [f"## Agent {agent}",         self._load("agents",   agent)]
       for m in (modes or []):
           parts += [f"## Mode {m}", self._load("modes", m)]
       if extra:   parts += ["## Extra directives", extra]
       parts.append("</framework>")
       return "\n\n".join(parts)
   def run(self, prompt, *, command=None, agent=None, modes=None, extra=None,
           max_tokens=1800, stream=True, remember=True):
       sys_prompt = self._system(command, agent, modes, extra)
       msgs = self.history + [{"role": "user", "content": prompt}]
       console.rule(
           f"[bold cyan]► /sc:{command or '—'}  agent={agent or '—'}  modes={modes or []}"
       )
       console.print(Panel(prompt, title="USER", border_style="blue"))
       console.print("[bold green]ASSISTANT ↓[/bold green]")
       text = ""
       try:
           if stream:
               with client.messages.stream(
                   model=self.model, max_tokens=max_tokens,
                   system=sys_prompt, messages=msgs,
               ) as s:
                   for chunk in s.text_stream:
                       sys.stdout.write(chunk); sys.stdout.flush()
                       text += chunk
                   print()
           else:
               r = client.messages.create(
                   model=self.model, max_tokens=max_tokens,
                   system=sys_prompt, messages=msgs,
               )
               text = "".join(b.text for b in r.content if b.type == "text")
               console.print(text)
       except Exception as e:
           console.print(f"[red]API error: {e}[/red]")
           return ""
       if remember:
           self.history += [{"role": "user", "content": prompt},
                            {"role": "assistant", "content": text}]
       return text
   def save(self, path="/content/sc_session.json", note=""):
       Path(path).write_text(json.dumps(
           {"meta": {"note": note, "saved_at": time.time(), "model": self.model},
            "history": self.history}, indent=2))
       console.print(f"💾 Session → {path}", style="bold yellow")
   def load(self, path="/content/sc_session.json"):
       d = json.loads(Path(path).read_text())
       self.history = d["history"]
       console.print(f"📂 Loaded {len(self.history)//2} prior turns", style="bold yellow")
sc = SuperClaude()

We define the SuperClaude class that connects the framework assets with the Anthropic API. We build system prompts by combining the base instruction with selected commands, agents, and modes. We also add run, save, and load methods to execute guided workflows and preserve session history.

sc.run(
   "I want to build an AI-assisted personal-finance app for college students. "
   "Drive a structured brainstorm: target users, must-have features, "
   "differentiators, risks, and an MVP cut.",
   command="brainstorm", modes=["brainstorming"], max_tokens=1200, remember=False,
)
sc.run(
   "Implement a React + TypeScript component `BudgetRing` that renders monthly "
   "spend vs. budget as an animated SVG ring with a hover tooltip. Tailwind "
   "for styling, no external chart libraries, full code + a usage example.",
   command="implement", agent="frontend-architect", max_tokens=2000, remember=False,
)
SNIPPET = """
@app.post("/login")
def login(req):
   user = db.query(f"SELECT * FROM users WHERE name='{req.name}'")
   if user and user.password == req.password:
       token = jwt.encode({"u": user.id}, "secret123")
       return {"token": token}
"""
sc.run(
   "Security-review this Flask login handler. Rank issues by severity "
   "(Critical/High/Medium/Low), explain the attack vector, and give a "
   "concrete fix for each.\n\n```python" + SNIPPET + "```",
   command="analyze", agent="security-engineer", max_tokens=1500, remember=False,
)
sc.run(
   "We are launching a B2B SaaS for compliance automation in healthcare. "
   "Convene a business panel: positioning, ICP, GTM plan, top-3 risks, "
   "6-month milestones, and a 'kill criteria' list.",
   command="business-panel", max_tokens=1800, remember=False,
)
sc.run(
   "Topic: 'state of vector databases in 2026'. Produce: (a) a Deep-Research "
   "plan — hops, sources to query, quality thresholds; (b) a synthesis of "
   "what is most likely true based on your knowledge; (c) open questions.",
   command="research", modes=["deep-research"], max_tokens=2000, remember=False,
)
sc.run(
   "Compare OAuth 2.0, OIDC, and SAML across: purpose, tokens, primary "
   "use-case, and one common pitfall each.",
   modes=["token-efficiency"], max_tokens=600, remember=False,
)

We test the bridge through several practical SuperClaude workflows, including brainstorming and implementation. We use different commands, agents, and modes to guide Claude for frontend coding, security review, and business analysis. We also explore deep research planning and token-efficient comparison to show how modes change the response style.

console.rule("[bold magenta]🛠 MULTI-STEP WORKFLOW")
sc.history = []
sc.run("Project: a CLI tool that summarizes any GitHub repo from its URL. "
      "Brainstorm scope and constraints.",
      command="brainstorm", max_tokens=900)
sc.run("Design the architecture: modules, data flow, key external dependencies, "
      "and a small ASCII component diagram.",
      command="design", max_tokens=1100)
sc.run("Implement the core `summarize_repo(url: str) -> dict` in Python. "
      "Use only the standard library + `requests`. Return a structured dict.",
      command="implement", max_tokens=1500)
sc.run("Generate pytest tests for `summarize_repo`. Mock all network calls.",
      command="test", max_tokens=900)
sc.run("Write a concise README.md (install, usage, example, limitations).",
      command="document", max_tokens=900)
sc.save(note="repo-summarizer-cli end-to-end build")
console.rule("[bold green]✅ Tutorial complete")
console.print(Panel.fit(
   "[bold]Try next:[/bold]\n"
   f"• Inspect a command file:  open  {REPO_DIR}/<...>/Commands/<name>.md\n"
   "• Add your own command:    drop a new .md into a Commands/ folder, then\n"
   "                           rerun discover_assets() and ASSETS = …\n"
   "• Swap models:             sc = SuperClaude(model='claude-opus-4-5')\n"
   "• Stack agents + modes:    sc.run(p, command='implement',\n"
   "                                   agent='backend-architect',\n"
   "                                   modes=['token-efficiency'])\n"
   "• Resume a saved session:  sc.load(); sc.run('continue from here …')",
   border_style="green",
))

We run a comprehensive multi-step workflow to build a CLI tool for summarizing GitHub repositories. We move through brainstorming, architecture design, implementation, testing, and documentation in one shared session. We save the session at the end and print extension ideas for customizing commands, switching models, and resuming work later.

In conclusion, we had a working SuperClaude-style execution environment that helps us apply commands, agents, and modes in a repeatable way. We saw how structured prompts can guide Claude toward more specialized behavior for coding, analysis, research, planning, and documentation tasks. This workflow gives us a flexible foundation for experimenting with custom commands, combining agents with modes, switching models, and building longer AI-assisted development sessions that preserve context across multiple steps. We also understood how this setup can be extended into personal development copilots, research assistants, security reviewers, and end-to-end project builders.


Check out the Full Codes with NotebookAlso, feel free to follow us on Twitter and don’t forget to join our 150k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us

The post Build a SuperClaude Framework Workflow with Commands, Agents, Modes, and Session Memory appeared first on MarkTechPost.

📌 Kaynak: MarkTechPost

#Teknoloji