skill_query.py 2.5 KB
"""c_skill_diff (named only in `sdd-mvcp-contract.json`, prose 03-C never
wrote it up) + list/get read helpers for `v_skill_library`/`v_skill_audit_log`
(02-V §2.9/§2.10). Skills live in graphlemon's own repo, not any target
project's (`src/skill_update.py`'s own docstring: "Skill 库是platform
asset,不是target-project"), so the diff runs against graphlemon's own
checkout by default -- reuses `agent_profile.py`'s own `_REPO_ROOT` pattern
rather than inventing a second way to locate it.
"""

import os
import subprocess

_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def list_skills(conn):
    rows = conn.execute(
        "SELECT skill_id, owner_org_node, file_path, current_git_commit_sha, source, "
        "migrated_from_profile, status FROM skill ORDER BY owner_org_node, skill_id"
    ).fetchall()
    return [
        {
            "skill_id": r[0], "owner_org_node": r[1], "file_path": r[2], "current_git_commit_sha": r[3],
            "source": r[4], "migrated_from_profile": r[5], "status": r[6],
        }
        for r in rows
    ]


class SkillNotFoundError(Exception):
    """NOT_FOUND -- c_skill_get's own skill_id doesn't exist."""


def get_skill_audit_log(conn, skill_id):
    """v_skill_audit_log (02-V §2.10): every skill_iteration row for this
    skill, oldest first."""
    if conn.execute("SELECT 1 FROM skill WHERE skill_id = ?", (skill_id,)).fetchone() is None:
        raise SkillNotFoundError(skill_id)
    rows = conn.execute(
        "SELECT iteration_id, triggered_by_bug_id, before_git_commit_sha, after_git_commit_sha, "
        "change_summary, applied_at, rollback_of_iteration_id FROM skill_iteration "
        "WHERE skill_id = ? ORDER BY applied_at",
        (skill_id,),
    ).fetchall()
    return [
        {
            "iteration_id": r[0], "triggered_by_bug_id": r[1], "before_git_commit_sha": r[2],
            "after_git_commit_sha": r[3], "change_summary": r[4], "applied_at": r[5],
            "rollback_of_iteration_id": r[6],
        }
        for r in rows
    ]


def get_diff(before, after, repo_path=None):
    """c_skill_diff: `git diff <before> <after>` -- skill_update.py's
    _write_and_commit makes every iteration an atomic single-file commit,
    so a plain repo-wide diff between the two commits naturally scopes
    itself to that one skill file without needing a path filter."""
    result = subprocess.run(
        ["git", "diff", before, after], cwd=repo_path or _REPO_ROOT,
        capture_output=True, text=True, check=True,
    )
    return result.stdout