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

从缺失运行证据恢复到实际批准

PYTHONCPython 3.12,临时 SQLite 和 AST,使用本站固定的任务与审核输入。controls.py
controls.py97 行
"""A tiny local harness with a restartable gate and architecture feedback."""
import ast
from datetime import date
from pathlib import Path
import sqlite3
from tempfile import TemporaryDirectory
import json

LAYERS = {"types": 0, "config": 1, "repo": 2, "service": 3, "runtime": 4, "ui": 5}
CASES = []


def observe(name, given, operation, expected, actual):
    assert expected == actual, (name, expected, actual)
    CASES.append(dict(name=name, input=given, operation=operation, expected=expected, actual=actual))


def architecture_errors(layer, source):
    diagnostics = []
    for node in ast.walk(ast.parse(source)):
        if isinstance(node, ast.Import):
            imports = [alias.name.split(".")[0] for alias in node.names]
        elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
            imports = [node.module.split(".")[0]]
        else:
            continue
        for name in imports:
            if name in LAYERS and LAYERS[name] > LAYERS[layer]:
                diagnostics.append(f"{layer} cannot import {name}; move the shared contract to a lower layer")
    return diagnostics


def start(db):
    db.execute("CREATE TABLE tasks (id TEXT PRIMARY KEY, state TEXT)")
    db.execute("INSERT INTO tasks VALUES ('inspection', 'planned')")
    db.commit()


def review(db, task, unit_ok, browser_ok, approved):
    if not unit_ok or not browser_ok:
        return "blocked: missing runtime evidence"
    if approved is not True:
        return "blocked: missing approval"
    transition = db.execute("UPDATE tasks SET state='done' WHERE id=? AND state='planned'", (task,))
    db.commit()
    return "done" if transition.rowcount == 1 else "blocked: no planned task"


def status(db, task):
    return db.execute("SELECT state FROM tasks WHERE id=?", (task,)).fetchone()[0]


def overdue(entries, today):
    return sorted(name for name, review_due in entries.items() if review_due < today)


def main():
    observe("harness_dependency_guard", ["repo", "from ui.widgets import render", "from types import SimpleNamespace"],
            "静态分析导入并报告可操作的修复方向",
            [["repo cannot import ui; move the shared contract to a lower layer"], []],
            [architecture_errors("repo", "from ui.widgets import render"), architecture_errors("repo", "from types import SimpleNamespace")])
    with TemporaryDirectory(prefix="mbsky-harness-") as temp:
        path = Path(temp) / "review.sqlite3"
        db = sqlite3.connect(path)
        try:
            start(db)
            denied = review(db, "inspection", True, False, True)
            observe("harness_browser_gate", [True, False, True], "单测通过,缺浏览器观察,核对状态",
                    ["blocked: missing runtime evidence", "planned"], [denied, status(db, "inspection")])
        finally:
            db.close()
        db = sqlite3.connect(path)
        try:
            resumed = status(db, "inspection")
            denial = review(db, "inspection", True, True, "true")
            waiting = status(db, "inspection")
            allowed = review(db, "inspection", True, True, True)
            observe("harness_resume_and_approval", ["重开 SQLite", "字符串 true", "布尔 true"],
                    "重新读取状态,再区分缺失批准和真实批准",
                    ["planned", "blocked: missing approval", "planned", "done", "done"],
                    [resumed, denial, waiting, allowed, status(db, "inspection")])
            observe("harness_missing_or_repeated_task", ["unknown", "inspection"],
                    "尝试更新不存在和已经完成的任务",
                    ["blocked: no planned task", "blocked: no planned task"],
                    [review(db, task, True, True, True) for task in ("unknown", "inspection")])
        finally:
            db.close()
    docs = {"handoff.md": date(2026, 2, 1), "incident.md": date(2026, 2, 15), "runbook.md": date(2026, 3, 1)}
    observe("harness_document_audit", ["2026-02-15", "三份文档各有复查日"],
            "列出早于当天的条目,保留当天到期的边界",
            ["handoff.md"], overdue(docs, date(2026, 2, 15)))
    print(json.dumps(CASES, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 CPython 3.12,临时 SQLite 和 AST,使用本站固定的任务与审核输入。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,临时 SQLite 和 AST,使用本站固定的任务与审核输入。

入口文件:projects/ai-agent-harness/controls.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 controls.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,临时 SQLite 和 AST,使用本站固定的任务与审核输入。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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