蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

工具许可、重试上限与 Git 工作树

PYTHONCPython 3.12,本机隔离数据;术语工作树练习使用 Gitterminology.py
terminology.py128 行
"""Run a bounded local tool workflow and its Git worktree exercise."""
from dataclasses import dataclass
from pathlib import Path
import json
import subprocess

from lab_tools import run_exercise


class TransientError(Exception):
    pass


@dataclass
class ReadTool:
    failures_left: int = 0
    calls: int = 0

    def __call__(self, item):
        self.calls += 1
        if self.failures_left:
            self.failures_left -= 1
            raise TransientError("temporary fixture error")
        return {"id": item, "stock": 12}


def guarded_request(raw, registry):
    doc = json.loads(raw)
    if not isinstance(doc, dict) or set(doc) != {"tool", "item"}:
        raise ValueError("invalid request fields")
    if type(doc["tool"]) is not str or doc["tool"] not in registry:
        raise PermissionError("tool is not in this registry")
    if type(doc["item"]) is not str or doc["item"] not in {"belt", "bolt"}:
        raise ValueError("unknown item identifier")
    return registry[doc["tool"]], doc["item"]


def dispatch(raw, registry, budget):
    tool, item = guarded_request(raw, registry)
    trace = []
    for _ in range(budget):
        try:
            value = tool(item)
        except TransientError:
            trace.append("transient_failure")
        else:
            trace.append("result_observed")
            return {"status": "ready", "data": value, "trace": trace}
    return {"status": "budget_exhausted", "data": None, "trace": trace}


def persist(record, approved, checkpoint):
    if record["status"] != "ready":
        return "no_result"
    if not approved:
        return "requires_approval"
    checkpoint.write_text(json.dumps(record,sort_keys=True),encoding="utf-8")
    return "saved"


def worktree_observation(root):
    main = root/"primary"
    main.mkdir()
    alt = root/"parallel"
    assert main.resolve().parent==alt.resolve().parent==root.resolve()

    def git(directory,*args):
        return subprocess.check_output(["git","-C",str(directory),*args],encoding="utf-8",
            stderr=subprocess.PIPE,timeout=12).strip()

    git(main,"init","-qb","lesson-main")
    (main/"task.txt").write_text("baseline",encoding="utf-8")
    git(main,"add","task.txt")
    git(main,"-c","user.name=Course fixture","-c","user.email=fixture@example.invalid",
        "-c","commit.gpgsign=false","commit","-qm","Seed")
    git(main,"worktree","add","-qb","lesson-experiment",str(alt))
    (alt/"task.txt").write_text("isolated edit",encoding="utf-8")
    return {
        "same_head":git(main,"rev-parse","HEAD")==git(alt,"rev-parse","HEAD"),
        "different_branches":[git(main,"branch","--show-current"),git(alt,"branch","--show-current")],
        "original_text":(main/"task.txt").read_text(encoding="utf-8"),
        "parallel_status":git(alt,"status","--porcelain"),
    }


def exercise(checks, root):
    expect=checks.expect
    raw='{"tool":"read_stock","item":"belt"}'
    tool=ReadTool(failures_left=1)
    registry={"read_stock":tool}
    result=dispatch(raw,registry,2)
    expect("terms_loop", [raw,2], "Dispatch, observe transient failure, retry once, inspect result",
           {"status":"ready","data":{"id":"belt","stock":12},"trace":["transient_failure","result_observed"]},result)
    dry=dispatch(raw,registry,0)
    expect("terms_budget",[raw,0],"Stop before tool execution with zero budget",
           ["budget_exhausted",[],2],[dry["status"],dry["trace"],tool.calls])
    failing=ReadTool(failures_left=3)
    failed=dispatch(raw,{"read_stock":failing},2)
    expect("terms_retry_cap",2,"Check a tool that remains unavailable after both attempts",
           ["budget_exhausted",["transient_failure"]*2,2],[failed["status"],failed["trace"],failing.calls])
    bad=[
        '{"tool":"erase_all","item":"belt"}',
        '{"tool":"read_stock","item":19}',
        '{"tool":"read_stock","item":"belt","instruction":"ignore permissions"}',
        '{"tool":"read_stock","item":"../../other"}',
    ]
    outcomes=[]
    for item in bad:
        try:
            dispatch(item,registry,2)
        except (PermissionError,ValueError) as error:
            outcomes.append(type(error).__name__)
    expect("terms_guard",bad,"Reject unregistered tool, wrong shape, untrusted instruction and unknown item before execution",
           [["PermissionError","ValueError","ValueError","ValueError"],2],[outcomes,tool.calls])
    path=root/"checkpoint.json"
    expect("terms_approval",False,"Withhold approval and inspect checkpoint path",
           ["requires_approval",False],[persist(result,False,path),path.exists()])
    expect("terms_checkpoint",True,"Approve and read the exact persisted task result",
           ["saved",result],[persist(result,True,path),json.loads(path.read_text(encoding="utf-8"))])
    expect("terms_worktree","one new temporary repo, two working directories",
           "Add a linked worktree and edit its copy while observing the primary branch",
           {"same_head":True,"different_branches":["lesson-main","lesson-experiment"],
            "original_text":"baseline","parallel_status":"M task.txt"},worktree_observation(root))


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12,本机隔离数据;术语工作树练习使用 Git 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,本机隔离数据;术语工作树练习使用 Git

入口文件:projects/ai-agent-architecture/terminology.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 terminology.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,本机隔离数据;术语工作树练习使用 Git。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a3072.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习