Mastering SKU Inventory Deduction with Superpowers: A 7‑Stage Workflow

This article walks through a complete 7‑stage Superpowers workflow—brainstorming, isolated git worktrees, fine‑grained task planning, sub‑agent execution with two‑stage reviews, strict test‑driven development, global code review, and final branch finishing—using Python 3.11, FastAPI, SQLAlchemy and Pytest to implement robust SKU inventory deduction in an e‑commerce system.

Shuge Unlimited
Shuge Unlimited
Shuge Unlimited
Mastering SKU Inventory Deduction with Superpowers: A 7‑Stage Workflow

Overview

Superpowers tackles the common AI‑coding pitfalls of skipping steps, not writing tests, and claiming completion without verification by enforcing a structured Process over Prompt workflow. The article demonstrates the workflow on a typical e‑commerce scenario: deducting stock for a SKU when an order is placed, using Python 3.11, FastAPI, SQLAlchemy 2.0 and Pytest.

Stage 1 – brainstorming (Requirement Clarification)

The AI initiates a Socratic dialogue to clarify three key decisions:

Concurrency handling – choose pessimistic lock (SELECT … FOR UPDATE) for simplicity and acceptable lock wait.

Error reporting – return detailed error with current stock.

Partial deduction – disallow; the whole operation fails if stock is insufficient.

The confirmed design is saved to

docs/superpowers/specs/2026-04-12-sku-inventory-deduction-design.md

.

Stage 2 – using‑git‑worktrees (Isolated Development Environment)

Superpowers creates an isolated Git worktree, checks it out, installs dependencies, and runs the existing test baseline (47 passed). This guarantees a clean starting point before any new code is added.

$ git worktree add .worktrees/sku-deduction -b feature/sku-deduction
$ cd .worktrees/sku-deduction
$ pip install -r requirements.txt
$ pytest tests/ -v
================== 47 passed, 0 failed ==================

Stage 3 – writing‑plans (Task Decomposition)

The feature is broken into 2‑5 minute tasks, each with a concrete file path, code, and verification command. Example task “SKU model definition”:

Create app/models/sku.py and tests/test_sku_model.py.

Write a failing test.

Run the test (fails because the module does not exist).

Implement the minimal model code.

Run the test again (passes).

Commit the changes.

# tests/test_sku_model.py
from app.models.sku import SKU

def test_sku_creation():
    sku = SKU(product_id=1, specs={"color": "black", "size": "M"}, stock=100)
    assert sku.stock == 100
    assert sku.specs == {"color": "black", "size": "M"}
# app/models/sku.py
from sqlalchemy import Column, Integer, JSON, ForeignKey
from sqlalchemy.orm import relationship
from app.database import Base

class SKU(Base):
    __tablename__ = "skus"
    id = Column(Integer, primary_key=True, index=True)
    product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
    specs = Column(JSON, nullable=False)
    stock = Column(Integer, nullable=False, default=0)
    product = relationship("Product", back_populates="skus")

Stage 4 – subagent‑driven‑development (Sub‑Agent Execution with Two‑Stage Review)

Each task is handed to an isolated sub‑agent. After implementation, two automatic reviews run:

Specification compliance review – checks that the code matches the design doc, flags missing or extra functionality.

Code‑quality review – examines style, naming, boundary handling, performance, and test coverage.

Example: the inventory‑deduction task initially missed handling of a non‑existent SKU and used an inappropriate InsufficientStockError. The spec reviewer caught the issue, the sub‑agent fixed it, and the quality reviewer suggested adding a check for non‑positive quantities.

# app/services/inventory.py (after sub‑agent fixes)
class InventoryService:
    def __init__(self, session: Session):
        self.session = session

    def deduct(self, sku_id: int, quantity: int) -> None:
        if quantity <= 0:
            raise ValueError("扣减数量必须大于 0")
        try:
            stmt = (select(SKU).where(SKU.id == sku_id).with_for_update())
            sku = self.session.execute(stmt).scalar_one()
            if sku.stock < quantity:
                raise InsufficientStockError(sku_id, quantity, sku.stock)
            sku.stock -= quantity
            self.session.commit()
        except NoResultFound:
            raise ValueError(f"SKU {sku_id} 不存在")
        except Exception:
            self.session.rollback()
            raise

Stage 5 – test‑driven‑development (RED‑GREEN‑REFACTOR)

For the inventory service, the RED step writes failing tests for successful deduction and insufficient stock. The GREEN step adds the minimal implementation shown above. After running pytest, both tests pass.

# tests/test_inventory_service.py
import pytest
from app.services.inventory import InventoryService

def test_deduct_stock_success(db_session):
    sku = create_test_sku(db_session, stock=100)
    service = InventoryService(db_session)
    service.deduct(sku.id, quantity=3)
    db_session.refresh(sku)
    assert sku.stock == 97

def test_deduct_stock_insufficient(db_session):
    sku = create_test_sku(db_session, stock=5)
    service = InventoryService(db_session)
    with pytest.raises(ValueError, match="库存不足"):
        service.deduct(sku.id, quantity=10)

Stage 6 – requesting‑code‑review (Global Review)

After all tasks finish, a global review evaluates overall quality. Strengths include high test coverage and correct pessimistic lock usage. Important issues flagged:

Missing rollback on session.commit() failure.

Potential long lock wait in batch deductions.

The article shows the corrected code with a batch_deduct helper that sorts items by sku_id to avoid deadlocks.

# app/services/inventory.py (batch deduction)
def batch_deduct(self, items: list[tuple[int, int]]) -> None:
    """批量扣减,按 sku_id 排序避免死锁"""
    sorted_items = sorted(items, key=lambda x: x[0])
    for sku_id, quantity in sorted_items:
        self.deduct(sku_id, quantity)

Stage 7 – finishing‑a‑development‑branch (Delivery)

The final step runs the full test suite (56 passed), merges the feature branch back to main, and removes the worktree.

$ pytest tests/ -v
================== 56 passed, 0 failed ==================
$ git checkout main
$ git pull
$ git merge feature/sku-deduction
$ git worktree remove .worktrees/sku-deduction

Advanced Tips – Skill Combination Patterns

Three reusable patterns are presented:

Bug‑fix flow:

systematic-debugging → test-driven-development → verification-before-completion

Quick‑implementation flow: brainstorming → writing-plans → executing-plans Large‑feature flow:

brainstorming → writing-plans → subagent-driven-development → requesting-code-review → finishing-a-development-branch

Progressive Learning Roadmap

A suggested weekly adoption path starts with brainstorming, adds writing-plans in week 2, introduces test-driven-development in week 3, experiments with subagent-driven-development in week 4, and finally runs the full 7‑stage workflow.

7-stage workflow diagram
7-stage workflow diagram

Conclusion

Superpowers’ value lies in the engineering discipline it enforces: think before you code, write tests before code, and review before delivery . The three key takeaways are:

Process over Prompt – a fixed workflow yields far better AI‑generated code.

Task granularity decides success – breaking a feature into 2‑5 minute tasks creates a solid design process.

Reviews cannot be skipped – the two‑stage sub‑agent review catches many “AI thinks it’s correct” mistakes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonFastAPIAI programmingtest‑driven developmentSQLAlchemysuperpowersGit worktreesSKU inventory
Shuge Unlimited
Written by

Shuge Unlimited

Formerly "Ops with Skill", now officially upgraded. Fully dedicated to AI, we share both the why (fundamental insights) and the how (practical implementation). From technical operations to breakthrough thinking, we help you understand AI's transformation and master the core abilities needed to shape the future. ShugeX: boundless exploration, skillful execution.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.