"""Offline learning exercise for profile, gateway and scheduler boundaries."""
from contextlib import closing
from datetime import datetime, timezone
import json
from pathlib import Path
import sqlite3
from tempfile import TemporaryDirectory
CASES = []
def observe(name, inputs, operation, expected, actual):
assert actual == expected, (name, expected, actual)
CASES.append(dict(name=name, input=inputs, operation=operation, expected=expected, actual=actual))
def initialize(db):
with db:
db.execute("""
CREATE TABLE messages (
platform TEXT NOT NULL,
channel TEXT NOT NULL,
event_id TEXT NOT NULL,
payload TEXT NOT NULL,
PRIMARY KEY (platform, channel, event_id)
)
""")
db.execute("CREATE TABLE dispatch (job TEXT, slot TEXT, PRIMARY KEY(job, slot))")
def ingest(db, policy, platform, channel, sender, event_id, message):
if (platform, channel, sender) not in policy:
return "denied"
with db:
change = db.execute("INSERT OR IGNORE INTO messages VALUES (?, ?, ?, ?)", (platform, channel, event_id, message))
return "queued" if change.rowcount == 1 else "duplicate"
def history(db, platform, channel):
return db.execute("SELECT payload FROM messages WHERE platform=? AND channel=? ORDER BY rowid",
(platform, channel)).fetchall()
def claim_slot(db, job, now, hour):
if now.tzinfo != timezone.utc:
raise ValueError("The local exercise only accepts UTC")
if now.hour != hour or now.minute != 0:
return False
slot = now.replace(second=0, microsecond=0).isoformat()
with db:
change = db.execute("INSERT OR IGNORE INTO dispatch VALUES (?, ?)", (job, slot))
return change.rowcount == 1
def main():
with TemporaryDirectory(prefix="mbsky-hermes-gateway-") as temp:
directory = Path(temp)
profile_a = directory / "inspection.sqlite3"
profile_b = directory / "archive.sqlite3"
policy = {("local-telegram", "harbor", "operator"), ("local-cli", "harbor", "operator")}
with closing(sqlite3.connect(profile_a)) as db:
initialize(db)
rejected = [
ingest(db, policy, "local-telegram", "harbor", "guest", "evt-1", "rejected"),
ingest(db, policy, "local-telegram", "garden", "operator", "evt-1", "rejected"),
ingest(db, set(), "local-telegram", "harbor", "operator", "evt-1", "rejected"),
]
observe("hermes_lab_inbound_allowlist", ["unknown sender", "unknown channel", "empty policy"],
"本机按平台、频道、发送者检查,读取入队历史",
[["denied", "denied", "denied"], []], [rejected, history(db, "local-telegram", "harbor")])
accepted = [
ingest(db, policy, "local-telegram", "harbor", "operator", "evt-1", "海风 4 级"),
ingest(db, policy, "local-telegram", "harbor", "operator", "evt-1", "重复事件"),
ingest(db, policy, "local-cli", "harbor", "operator", "evt-1", "本机复查"),
]
observe("hermes_lab_dedup_scope", ["same platform and channel", "different platform"],
"写入事件并核对同一来源的重复与跨平台的独立键",
["queued", "duplicate", "queued"], accepted)
with closing(sqlite3.connect(profile_a)) as reopened, closing(sqlite3.connect(profile_b)) as isolated:
initialize(isolated)
histories = [history(db, "local-telegram", "harbor") for db in (reopened, isolated)]
observe("hermes_lab_profile_reopen", ["inspection.sqlite3", "archive.sqlite3"],
"重开原档案,再读另一份空档案", [[["海风 4 级"]], []],
[[list(row) for row in records] for records in histories])
due = datetime(2026, 4, 2, 9, 0, tzinfo=timezone.utc)
early = due.replace(hour=8, minute=59)
outcomes = [claim_slot(reopened, "digest", t, 9) for t in (early, due, due)]
observe("hermes_lab_scheduled_claim", ["08:59Z", "09:00Z", "09:00Z duplicate"],
"用固定时刻核对计划占位和重复阻断,整个过程只访问本地数据库",
[False, True, False], outcomes)
with closing(sqlite3.connect(profile_a)) as reopened:
next_day = due.replace(day=3)
observe("hermes_lab_scheduled_restart", ["reopen", "same slot", "next day"],
"重开后验证旧时间槽仍不可重复领取,下一日可领取",
[False, True], [claim_slot(reopened, "digest", t, 9) for t in (due, next_day)])
print(json.dumps(CASES, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 CPython 3.12、临时 SQLite、本站自编固定事件。真实 Hermes 服务未启动。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、临时 SQLite、本站自编固定事件。真实 Hermes 服务未启动。
入口文件:projects/ai-agent-hermes/gateway_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
gateway_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、临时 SQLite、本站自编固定事件。真实 Hermes 服务未启动。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3086.zip