fix(dsh): align recovery, scheduling audit and credential guarantees

This commit is contained in:
阿白叔 committed 2026-10-31 14:16:27 +08:00
1 parent e565f67b46
commit 9552f1eb95
32 files changed
+514 -135

No files matched your search

@@ -81,10 +81,10 @@
- Modify: `docs/user/dsh-ai-supervision.md`
**Interfaces:**
- `IssueBrokerConfig.from_environment()`, `IssueBroker.exchange(payload) -> dict`, and `IssueTransport.credentials(...)` with `instance_proof`, `idempotency_key`, `expires_in`.
- `IssueBrokerConfig.from_environment()`, `IssueBroker.exchange(payload) -> dict`, and `IssueTransport.credentials(...)` with `instance_proof`, `idempotency_key`, `credential_kind=revocable_static / expires_utc=null`.
- Reference HTTP endpoints: `GET /healthz`, `POST /v1/issue-token`.
- [x] Write tests for fixed target, HMAC instance proof, idempotency, short expiry, invalid scope, and no secret in response logs.
- [x] Write tests for fixed target, HMAC instance proof, idempotency, explicit static credential lifetime, bounded cache, invalid scope, and no secret in response logs.
- [x] Run focused tests and observe expected failure.
- [x] Implement the broker with stdlib `ThreadingHTTPServer`, fixed target configuration, environment-only secret/token, bounded requests and no redirects.
- [x] Require broker exchange metadata in the client and reject responses with missing expiry or wrong target.
@@ -66,7 +66,7 @@
**Interfaces:**
- Produces `IssueTransport(config_path).credentials(target, *, now=None) -> dict` with only in-memory `headers`, `source`, `expires_utc`, and `rotation_required`.
- Supports `broker_url` plus instance ID and a short-lived exchange response; direct bootstrap/Git credential fallback is tagged and never cached as a token.
- Supports `broker_url` plus instance ID and an explicitly revocable static credential response without a token TTL; direct bootstrap/Git credential fallback is tagged and never cached as a token.
- [x] Write tests for fixed target validation before credentials, broker success, broker expiry, direct fallback warning, and no-token cache/log output.
- [x] Run focused tests and observe expected failure.
@@ -20,7 +20,7 @@
### 4. 生产工单中转
`dsh/issue_transport.py` 的 broker 模式扩展为可部署的固定目标中转协议:服务端校验安装实例签名、仓库和事件幂等键,签发短期 issue-only token;客户端不缓存 token。新增 stdlib broker 参考服务和协议测试,生产部署仍需由运维配置服务端 secret 与 Git 凭据。
`dsh/issue_transport.py` 的 broker 模式扩展为可部署的固定目标中转协议:服务端校验安装实例签名、仓库和事件幂等键,分发长期可吊销 issue-only token(不提供自动到期保证);客户端不缓存 token。新增 stdlib broker 参考服务和协议测试,生产部署仍需由运维配置服务端 secret 与 Git 凭据。
## 约束
@@ -9,7 +9,7 @@
- 模型仍不能直接写 CAD、绕过原生确认、扩大重试额度或提交任意 URL。
- 排期仍要求任务中心打开且空闲;异常处理仍只使用已授权的原执行上下文。
- 健康信息只读;不向远端发送工程源文件、模型隐藏思维或凭据。
- 工单提交保持固定仓库和事件标记去重;优先使用中转服务短期令牌,直连凭据只作为明确配置的兼容路径。
- 工单提交保持固定仓库和事件标记去重;优先使用中转分发的长期可吊销令牌,直连凭据只作为明确配置的兼容路径。
## 组件
@@ -27,7 +27,7 @@
### 工单凭据生命周期
新增 `dsh/issue_transport.py`,支持固定仓库的中转模式:客户端只保存中转地址和安装实例标识,通过一次性或短期令牌换取服务端签发的 issue-only 访问凭据;令牌只用于固定服务器、仓库、事件标记和工单创建/附件上传。缓存只保存凭据来源、过期时间和错误码,不保存访问令牌。
新增 `dsh/issue_transport.py`,支持固定仓库的中转模式:客户端只保存中转地址和安装实例标识,通过实例 HMAC 证明获取服务端分发的长期可吊销 issue-only 访问凭据;令牌只用于固定服务器、仓库、事件标记和工单创建/附件上传。缓存只保存凭据来源、无到期保证的状态和错误码,不保存访问令牌。
兼容模式继续读取本机 Git credential,但预置静态令牌只作为开发/验收 fallback,并在健康中心标记为 `credential_rotation_required`。任何目标校验都必须在获取凭据前完成。
@@ -0,0 +1,36 @@
# PR #11 评论 #106 修复验证
## 修复范围
- 恢复差异通过真实服务计算当前计划哈希;比较最后持久回执和当前计数、队列完成及中断证据,变化时阻断恢复。缺少历史计数时明确标记基线不可用。
- 健康执行状态由桌面真实 live run、确认窗口和 workers 提供;未观测时不报告空闲。
- 参考 broker 明确分发长期可吊销 Git 凭据,不提供短期失效保证。响应不再包含虚假 expires_in;校验目标,缓存默认最多 1024 项并清理过期项,缓存到期不会吊销 Git token。
- 排期的 dispatchable 表示已保存原生预先授权且当前门禁通过。模型请求仍需原生确认才能保存授权。派发/结果写入 SQLite schedule_events;claim 与派发审计为同一事务,审计写入失败则回滚,不启动执行。
- 经验索引按允许证据文件的元数据变化刷新;终态执行历史显示持久回执,避免重复预检。监管各区块读取失败分别降级,保留其他信息。
- 单任务/批次预检异常显示操作员提示并返回;基础回执持久化后,补充回执失败返回真实执行结果和 reporting_errors。
## 自动验证
- 真实服务的回归覆盖计划变化、证据计数变化、原检查点完成项、桌面执行状态及补充回执失败。
- 真实 SQLite 回归覆盖重启、并发只领取一次、无预先授权拒绝自动领取、派发/结果事件、事件插入失败回滚。
- 完整 DSH/UI/队列/打包回归:275 passed。
- 批次重试、工程任务 UI、操作生命周期、关闭归档及执行反馈:20 passed。
- 独立 reviewer:7 项定向回归通过,未发现可复现的重要问题。
- 官方 runtime CLI 门禁、模型结果裁剪及 dock 启动校验通过;compileall、修改 JS/MJS 语法和 diff 检查通过。
- 使用本机配置的两份凭据逐字节扫描 PR 变更:0 匹配;没有输出凭据。
## 实际点击验收
报告:`build/dsh-pr11-review106/20261031-141258/report.json`。
通过真实 Qt 原生按钮和嵌入 Chromium CDP 点击执行,两次启动均正常退出:
- 自然语言意图触发只读影响检查及原生执行确认,提示词没有工具名。
- 第一项结束后安全暂停;第二进程恢复同一 run/queue,跳过已完成项。
- 取消排期未保存;原生勾选将来执行授权后到期执行一次。
- 排期页显示持久化派发记录及实际结果记录。
- 7 个监管页签、经验验证标记、未知/确定位号数量及用量设置持久化正常。
- 损坏审计显式降级,独立区块和排期继续工作,损坏原文件字节不变。
- 已绑定工单通过真实只读 GET 同步;验收中的自动工单发布入口已禁用。
本轮为隔离 fixture 与受控未命中执行器,3 次队列步骤均唯一、源 fixture 哈希不变;realCadStarted=false、remoteIssuesCreated=false。未验证现场 DxDesigner 写入、生产 HTTPS broker 部署或凭据吊销轮换;未构建 EXE、未合并 PR。
@@ -16,3 +16,6 @@
## 限制
参考 broker 只完成协议和安全边界验证,尚未部署到生产 HTTPS 服务;生产环境仍需运维配置 Git issue-only 凭据、实例注册、吊销和轮换。CAD 适配器复用现有私有桌面和前后探针,验收仍使用隔离 fixture,不代表真实用户工程已经写入成功。
审查 #106 更正:此前记录中的短期仅检查了响应元数据,不能证明 Git 凭据会到期。当前参考 broker 明确分发长期可吊销凭据(credential_kind=revocable_static,expires_utc=null),客户端不落盘;缓存到期仅清理服务端内存,默认最多 1024 项,不会使 Git token 失效。实际失效依赖服务端吊销/轮换,本轮未部署生产 broker。
@@ -19,3 +19,6 @@
## 当前验收边界
本轮没有部署真实中转服务,因此 broker 只用受控 HTTP 响应验证协议和凭据不落盘行为;生产部署仍需配置固定服务器、实例注册、短期令牌过期和吊销策略。没有改变真实 CAD 写入门禁,也没有构建新 EXE。
审查 #106 更正:此前记录中的短期仅检查了响应元数据,不能证明 Git 凭据会到期。当前参考 broker 明确分发长期可吊销凭据(credential_kind=revocable_static,expires_utc=null),客户端不落盘;缓存到期仅清理服务端内存,默认最多 1024 项,不会使 Git token 失效。实际失效依赖服务端吊销/轮换,本轮未部署生产 broker。
+3 -1
View File
@@ -105,7 +105,9 @@ Harness 使用任务中心数据目录下独立的 `dsh/harness-home` 保存会
每次自动介入在数据目录 `dsh/incidents/<事件编号>/` 保存:前后任务快照、脱敏诊断包、事件时间线、规则门禁明细、模型可见会话、尝试动作、实际核验结果、工单草稿和带 SHA256 清单的 `evidence.zip`。保留可审阅的诊断说明,不要求模型输出隐藏思维过程;“取证”只收集本工具已有的日志与运行记录,不扫描无关网络流量、工程源文件或用户文件。
工单默认提交到 `https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement`。生产环境优先配置固定仓库的中转地址、安装实例标识、实例证明和事件幂等键:客户端使用这些信息换取短期 `write:issue` 凭据,令牌只在内存中使用,不进入模型、缓存、日志或工单正文。中转不可用时才进入本机 Git credential 或预置令牌兼容路径,概览健康会标记“需要轮换凭据”。预置账户必须是非管理员、仅绑定本仓库的 `write:issue` 权限,并支持服务端吊销和轮换。
工单默认提交到 `https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement`。生产环境可配置固定仓库的中转地址、安装实例标识、实例证明和事件幂等键:参考 broker 分发长期可吊销的 `write:issue` 凭据,不提供自动到期保证。令牌只在客户端内存中使用,不进入模型、客户端缓存、日志或工单正文。中转缓存默认最多 1024 项、300 秒,缓存到期不会使 Git token 失效,仍需服务端吊销和轮换,健康中心会明确标记降级。未配置中转时可使用本机 Git credential 或预置令牌;已配置中转但不可用时返回错误。预置账户必须是非管理员、仅绑定本仓库的 `write:issue` 权限。
排期创建时勾选自动启动并经原生窗口确认,才保存将来执行授权。到期后仍检查原任务范围、计划哈希、依赖和执行门禁;未授权排期需要即时确认。每次派发及结果保存在 `dsh-state.sqlite3` 的 `schedule_events`,可在排期页查看。派发事件与领取排期在同一事务,写入失败不会启动。此表为持久化运行审计,与异常决策的 SHA256 链分别记录,不声称具备哈希链防篡改能力。
开发/验收预填资源为 `integration/dsh/issue-bootstrap.json`,已加入 Git 忽略;生产打包不应依赖它,而应配置中转地址和实例注册流程。管理员侧的账户密码和令牌恢复资料单独保存在本机 DPAPI 文件,不能随包分发。没有中转或明确兼容凭据时,工单保留本地证据并显示待提交状态。
+6 -1
View File
@@ -161,7 +161,12 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
blockerList(row.blockers),actions(
button('dx-schedule-run-'+row.schedule_id,'核对并执行',()=>perform({operation:'run_schedule',schedule_id:row.schedule_id}),pending||row.ready!==true),
button('dx-schedule-cancel-'+row.schedule_id,'取消排期',()=>perform({operation:'cancel_schedule',schedule_id:row.schedule_id}),pending||row.status!=='pending')))),
!operations.schedules?.length&&empty('暂无排期。'));
!operations.schedules?.length&&empty('暂无排期。'),
...(operations.schedule_events||[]).slice(0,10).map(row=>card('schedule-event-'+row.sequence,
row.event==='dispatch'?'排期派发记录':'排期结果记录',
detail('时间',time(row.at_utc)),detail('排期',row.schedule_id),detail('执行',row.run_id),
detail('授权',row.payload?.authority==='native_future_authorization'?'原生预先授权':row.payload?.authority==='native_confirmation'?'原生即时确认':'—'),
detail('结果',status(row.payload?.status||'claimed')))));
}
function ExperiencesPanel({operations,perform,pending}){
const[query,setQuery]=React.useState('');
@@ -4,7 +4,7 @@ const fields=(value,keys)=>Object.fromEntries(keys.filter(k=>value?.[k]!==undefi
const run=row=>({...fields(row,['run_id','queue_id','status','task_ids','remaining_task_ids','counters','blockers','resume_ready','started_utc']),
diff:row.diff?fields(row.diff,['safe','changed','completed','remaining','plan_changes','evidence_changes','blockers']):undefined,
result:row.result?fields(row.result,['status','tasks','message','cad_verification']):undefined});
const schedule=row=>fields(row,['schedule_id','title','task_ids','priority','not_before','due_at','dependencies','auto_start','status','ready','blockers','run_id']);
const schedule=row=>fields(row,['schedule_id','title','task_ids','priority','not_before','due_at','dependencies','auto_start','status','ready','requires_confirmation','dispatchable','dispatch_authority','blockers','run_id']);
const experience=row=>({...fields(row,['incident_id','issue_code','verified','verification','evidence','evidence_refs','evidence_references','status']),
attempts:row.attempts,analyses:row.analyses?.slice(0,2),outcome:row.outcome,
summary:short(row.summary,1200),message:short(row.message)});
@@ -28,6 +28,10 @@ export function compactResult(value){
if(result.tasks)result.tasks=result.tasks.map(t=>({...t,...t.note?{note:short(t.note,300)}:{}}));
if(result.runs)result.runs=result.runs.slice(0,5).map(run);
if(result.schedules)result.schedules=result.schedules.slice(0,10).map(schedule);
if(result.schedule_events)result.schedule_events=result.schedule_events.slice(0,10).map(row=>({
...fields(row,['sequence','schedule_id','at_utc','event','run_id']),
payload:{...fields(row.payload,['automatic','authority','status']),
receipt:row.payload?.receipt?fields(row.payload.receipt,['status','run_id','tasks','reporting_errors']):undefined}}));
if(result.schedule)result.schedule=schedule(result.schedule);
if(result.experiences)result.experiences=result.experiences.slice(0,5).map(experience);
if(result.tickets)result.tickets=result.tickets.slice(0,5).map(ticket);
@@ -42,7 +46,8 @@ export function modelSnapshot(value){
const ops=value.operations||{};
result.operations=compactResult({busy:ops.busy===true,live_run:ops.live_run,last_execution:ops.last_execution,
runs:ops.runs||[],schedules:ops.schedules||[],experiences:ops.experiences||[],tickets:ops.tickets||[],health:ops.health,
decision_audit:ops.decision_audit,decisions:ops.decisions||[]});
decision_audit:ops.decision_audit,decisions:ops.decisions||[],
section_errors:ops.section_errors||[],schedule_events:ops.schedule_events||[]});
if(value.automation?.incident_id)result.automation=fields(value.automation,['incident_id','task_id','issue_code','status','attempts','verification']);
if(value.lifecycle?.status)result.lifecycle=fields(value.lifecycle,['request_id','status','task_ids','run_id']);
return result;
+10 -4
View File
@@ -9,7 +9,7 @@ from ..trial_task_center.errors import TaskCenterError
from ..trial_task_center.task_queue import execute_task_queue
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None):
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
journal = RunJournal(root)
@@ -21,7 +21,7 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
if not current or not current['ready'] or current['plan_hashes'] != report['plan_hashes']:
raise TaskCenterError('schedule_blocked', '排期计划、依赖或执行条件已变化,未启动。')
schedules.claim(schedule['schedule_id']); claimed = True
schedules.claim(schedule['schedule_id'], run_id=run_id, automatic=automatic); claimed = True
if resume:
inspected = journal.inspect(service, resume['run_id'])
if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']:
@@ -66,12 +66,18 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
except Exception as error:
receipt['reporting_errors'].append({'task_id': entry['task_id'], 'code': getattr(error, 'code', 'context_unavailable')})
receipt['tasks'].append(actual)
journal.finish(run_id, receipt)
try:
journal.finish(run_id, receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable', 'error': type(error).__name__})
if claimed:
try:
schedules.finish(schedule['schedule_id'], 'interrupted' if status in {'paused', 'blocked'} else status,
run_id=run_id, receipt=receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
journal.finish(run_id, receipt)
try:
journal.finish(run_id, receipt)
except Exception:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable'})
return receipt
+21 -6
View File
@@ -59,11 +59,27 @@ class ExperienceStore:
self.data_root = Path(data_root)
self.root = self.data_root / "dsh" / "incidents"
self._rows: list[dict] = []
self._source_stamp = None
def refresh(self) -> list[dict]:
directories = sorted((p for p in self.root.iterdir()
if _IDENTIFIER.fullmatch(p.name) and p.is_dir() and not p.is_symlink()),
key=lambda p: p.name) if self.root.is_dir() else []
stamp = []
for directory in directories:
for name in dict.fromkeys(('incident.json', *_KNOWN_EVIDENCE)):
try:
stat = (directory / name).lstat()
stamp.append((directory.name, name, stat.st_mtime_ns, stat.st_ctime_ns,
stat.st_size, stat.st_ino, stat.st_mode))
except FileNotFoundError:
stamp.append((directory.name, name, None))
index = self.data_root / 'dsh' / 'experience' / 'index.json'
if stamp == self._source_stamp and index.is_file():
return [dict(row) for row in self._rows]
rows = []
if self.root.is_dir():
for directory in sorted(self.root.iterdir(), key=lambda p: p.name):
if directories:
for directory in directories:
path = directory / "incident.json"
if not directory.is_dir() or directory.is_symlink() or not path.is_file() or path.is_symlink():
continue
@@ -75,6 +91,7 @@ class ExperienceStore:
rows.append(row)
self._rows = rows
write_json(self.data_root / "dsh" / "experience" / "index.json", {"version": 1, "entries": rows})
self._source_stamp = stamp
return [dict(row) for row in rows]
def _entry(self, directory: Path, record: dict) -> dict | None:
@@ -152,8 +169,7 @@ class ExperienceStore:
def search(self, issue_code: str = "", *, limit: int = 5) -> list[dict]:
if not isinstance(limit, int) or limit <= 0:
return []
if not self._rows:
self.refresh()
self.refresh()
query = str(issue_code or "").strip().casefold()
matches = []
for row in self._rows:
@@ -170,8 +186,7 @@ class ExperienceStore:
return matches[:min(limit, 50)]
def summary(self) -> dict:
if not self._rows:
self.refresh()
self.refresh()
counts = {}
for row in self._rows:
code = row.get("issue_code", "") or "unknown"
+14 -11
View File
@@ -13,13 +13,22 @@ def _now():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def execution_check(state=None):
values = {'running': ('execution_running', '任务中心正在执行工程操作'),
'busy': ('worker_active', '任务中心有后台操作'),
'confirmation': ('awaiting_confirmation', '等待原生确认'),
'idle': ('idle', '任务中心空闲')}
code, message = values.get(state, ('execution_not_observed', '尚未获取桌面执行状态'))
return {'name': 'execution', 'status': 'ok' if state == 'idle' else 'degraded', 'code': code, 'message': message}
class HealthStore:
def __init__(self, data_root):
self.data_root = Path(data_root)
def snapshot(self, service, *, now=None):
def snapshot(self, service, *, now=None, execution=None):
checked = now.isoformat(timespec="seconds") if now is not None else _now()
checks = [self._provider(), self._execution(service), self._stores(), self._tickets(), self._credentials()]
checks = [self._provider(), execution_check(execution), self._stores(), self._tickets(), self._credentials()]
status = "ok" if all(row["status"] == "ok" for row in checks) else (
"blocked" if any(row["status"] == "blocked" for row in checks) else "degraded")
return scrub({"status": status, "checked_utc": checked, "checks": checks})
@@ -35,12 +44,6 @@ class HealthStore:
"code": "ready" if configured else "provider_unconfigured",
"message": "模型提供方已配置" if configured else "尚未配置模型提供方"}
def _execution(self, service):
active = bool(getattr(service, "_workers", set()))
return {"name": "execution", "status": "degraded" if active else "ok",
"code": "worker_active" if active else "idle",
"message": "任务中心有后台操作" if active else "任务中心空闲"}
def _stores(self):
dsh = self.data_root / "dsh"
try:
@@ -65,13 +68,13 @@ class HealthStore:
try:
config = issue_target(self.data_root / 'dsh' / 'issue-config.json')
if config.get('broker_url') and config.get('instance_id') and config.get('instance_proof') and config.get('idempotency_key'):
return {"name": "issue_credentials", "status": "ok", "code": "broker_configured",
"message": "已配置固定目标短期凭据中转"}
return {"name": "issue_credentials", "status": "degraded", "code": "broker_static_credential",
"message": "已配置长期可吊销工单凭据中转,仍需服务端轮换;未验证连通性"}
except (OSError, ValueError, TypeError):
pass
value = load_bootstrap()
if value:
return {"name": "issue_credentials", "status": "degraded", "code": "credential_rotation_required",
"message": "当前使用预置工单凭据,建议切换短期中转凭据"}
"message": "当前使用预置工单凭据,需要服务端吊销和轮换管理"}
return {"name": "issue_credentials", "status": "ok", "code": "machine_credential_or_disabled",
"message": "未发现预置工单凭据"}
+40 -19
View File
@@ -1,54 +1,75 @@
"""Fixed-target issue-token broker core used by the reference HTTP service."""
from __future__ import annotations
from dataclasses import dataclass
from collections import OrderedDict
from dataclasses import dataclass, field
from hashlib import sha256
import hmac
import os
import time
from threading import Lock
from urllib.parse import urlsplit
@dataclass(frozen=True)
class IssueBrokerConfig:
server: str
repository: str
token: str
secret: str
expires_in: int = 300
token: str = field(repr=False)
secret: str = field(repr=False)
cache_seconds: int = 300
max_entries: int = 1024
@classmethod
def from_environment(cls, values=None):
values = os.environ if values is None else values
server, repository = str(values.get('server') or values.get('DSH_ISSUE_SERVER') or ''), str(values.get('repository') or values.get('DSH_ISSUE_REPOSITORY') or '')
token, secret = str(values.get('token') or values.get('DSH_ISSUE_TOKEN') or ''), str(values.get('secret') or values.get('DSH_BROKER_SECRET') or '')
if not server.startswith('https://') or repository.count('/') != 1 or not token or not secret:
parsed = urlsplit(server)
if (parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password
or parsed.path not in {'', '/'} or parsed.query or parsed.fragment
or repository.count('/') != 1 or not token or not secret):
raise ValueError('invalid_broker_config')
return cls(server.rstrip('/'), repository, token, secret, max(30, min(int(values.get('expires_in', 300)), 3600)))
return cls(server.rstrip('/'), repository, token, secret,
max(1, min(int(values.get('cache_seconds', 300)), 3600)),
max(1, min(int(values.get('max_entries', 1024)), 10000)))
class IssueBroker:
def __init__(self, config):
self.config = config
self._issued = {}
self._issued = OrderedDict()
self._lock = Lock()
def proof(self, instance_id):
return hmac.new(self.config.secret.encode(), str(instance_id).encode(), 'sha256').hexdigest()
def exchange(self, payload):
if not isinstance(payload, dict):
raise ValueError('invalid_payload')
if (payload.get('server', '').rstrip('/') != self.config.server
or payload.get('repository') != self.config.repository):
raise ValueError('invalid_target')
instance = str(payload.get('instance_id', ''))[:128]
if not instance or not hmac.compare_digest(str(payload.get('instance_proof', '')), self.proof(instance)):
instance = str(payload.get('instance_id', ''))
if not 1 <= len(instance) <= 128 or not hmac.compare_digest(str(payload.get('instance_proof', '')), self.proof(instance)):
raise ValueError('invalid_instance_proof')
key = str(payload.get('idempotency_key', ''))[:160]
if not key:
key = str(payload.get('idempotency_key', ''))
if not 1 <= len(key) <= 160:
raise ValueError('missing_idempotency_key')
prior = self._issued.get(key)
if prior is not None:
return dict(prior)
value = {'token': self.config.token, 'expires_in': self.config.expires_in,
'server': self.config.server, 'repository': self.config.repository,
'issued_at': int(time.time())}
self._issued[key] = value
return dict(value)
with self._lock:
now = time.monotonic()
for identity in [identity for identity, (until, _) in self._issued.items() if until <= now]:
del self._issued[identity]
identity = (instance, key)
if identity in self._issued:
self._issued.move_to_end(identity)
return dict(self._issued[identity][1])
# This reference service distributes a revocable static Git token.
# Cache expiry is not token expiry; never advertise a false TTL.
value = {'token': self.config.token, 'credential_kind': 'revocable_static', 'expires_utc': None,
'server': self.config.server, 'repository': self.config.repository,
'issued_at': int(time.time())}
self._issued[identity] = (now + self.config.cache_seconds, value)
while len(self._issued) > self.config.max_entries:
self._issued.popitem(last=False)
return dict(value)
+9 -7
View File
@@ -1,7 +1,6 @@
"""Fixed-target issue credentials with optional short-lived broker exchange."""
"""Fixed-target issue credentials with explicit static broker provenance."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import json
from pathlib import Path
import urllib.parse
@@ -34,7 +33,8 @@ class IssueTransport:
if broker:
try:
parsed = urllib.parse.urlsplit(str(broker))
if parsed.scheme != "https" or not parsed.hostname:
if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
or parsed.query or parsed.fragment):
raise ValueError("invalid_broker_url")
instance = str(config.get("instance_id", ""))[:128]
proof = instance_proof or config.get('instance_proof')
@@ -44,13 +44,15 @@ class IssueTransport:
response = _post_broker(broker, {"server": target["server"], "repository": target["repository"],
"instance_id": instance, "instance_proof": str(proof)[:128],
"idempotency_key": str(idem)[:160]})
if (not isinstance(response, dict) or not self._same_target(response, target)
or response.get('credential_kind') != 'revocable_static'
or response.get('expires_utc') is not None or 'expires_in' in response):
raise ValueError('invalid_broker_response')
token = response.get("token")
expires = int(response.get("expires_in", 0))
if not isinstance(token, str) or not token or not 30 <= expires <= 3600:
if not isinstance(token, str) or not 1 <= len(token) <= 4096 or '\n' in token or '\r' in token:
raise ValueError("invalid_broker_response")
stamp = now or datetime.now(timezone.utc)
return {"headers": {"Authorization": "token " + token}, "source": "broker",
"expires_utc": (stamp + timedelta(seconds=expires)).isoformat(), "rotation_required": False}
"credential_kind": "revocable_static", "expires_utc": None, "rotation_required": True}
except Exception as error:
return {"source": "broker_unavailable", "error": type(error).__name__, "rotation_required": True}
bootstrap = load_bootstrap()
+27 -12
View File
@@ -2,27 +2,42 @@
from __future__ import annotations
def resume_diff(service, inspected_run):
def resume_diff(service, inspected_run, *, current_plan_hashes=None):
from ..trial_task_center.task_queue import _plan_hash
ids = list(inspected_run.get('task_ids') or [])
expected = dict(inspected_run.get('plan_hashes') or {})
current = dict(getattr(service, 'current_plan_hashes', {}) or {})
changed = [task_id for task_id in ids if task_id in current and current[task_id] != expected.get(task_id)]
completed = [row['task_id'] for row in inspected_run.get('tasks', []) if row.get('status') == 'completed']
remaining = [task_id for task_id in ids if task_id not in completed]
current = {} if current_plan_hashes is None else dict(current_plan_hashes)
blockers = list(inspected_run.get('blockers') or [])
if changed: blockers.append('plan_changed')
if any(row.get('interrupted') for row in inspected_run.get('tasks', [])):
blockers.append('interrupted')
contexts = {}
for task_id in ids:
try:
if bool(getattr(service.task_context(task_id), 'interrupted', False)):
contexts[task_id] = service.task_context(task_id)
if current_plan_hashes is None:
current[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
if contexts[task_id].interrupted:
blockers.append('interrupted')
except Exception:
blockers.append('task_unavailable')
if not inspected_run.get('queue_available', False):
blockers.append('queue_missing')
changed = [key for key in ids if not expected.get(key) or not current.get(key) or current[key] != expected[key]]
if changed:
blockers.append('plan_changed')
remaining = list(inspected_run.get('remaining_task_ids', ids))
completed = [key for key in ids if key not in remaining]
baseline = {row['task_id']: row for row in (inspected_run.get('result') or {}).get('tasks', [])}
evidence_changes = []
for task_id, context in contexts.items():
saved = baseline.get(task_id, {})
actual = {'interrupted': context.interrupted,
**{field: getattr(context.progress, field, None) for field in
('saved_items', 'failed_items', 'no_match_items', 'queue_complete')}}
for field, value in actual.items():
if saved.get(field) is not None and value != saved[field]:
evidence_changes.append({'task_id': task_id, 'field': field, 'saved': saved[field], 'current': value})
if evidence_changes:
blockers.append('evidence_changed')
blockers = list(dict.fromkeys(blockers))
return {'safe': bool(inspected_run.get('resume_ready')) and not blockers,
'changed': changed[:20], 'completed': completed[:20], 'remaining': remaining[:20],
'plan_changes': [{'task_id': task_id, 'saved': expected.get(task_id), 'current': current.get(task_id)} for task_id in changed[:20]],
'evidence_changes': [], 'blockers': blockers[:20]}
'evidence_changes': evidence_changes[:100], 'evidence_baseline_available': bool(baseline),
'blockers': blockers[:20]}
+7 -2
View File
@@ -174,6 +174,7 @@ class RunJournal:
counters = {"completed": 0, "total": 0, "saved_items": 0, "failed_items": 0, "no_match_items": 0}
tasks = []
has_evidence = False
current_hashes = {}
for task_id in row["task_ids"]:
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
try:
@@ -193,7 +194,8 @@ class RunJournal:
if getattr(progress, "failed_items", 0):
blockers.append("failed_items")
from ..trial_task_center.task_queue import _plan_hash
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
current_hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
if current_hashes[task_id] != row["plan_hashes"][task_id]:
blockers.append("plan_changed")
except Exception:
blockers.append("task_unavailable")
@@ -220,5 +222,8 @@ class RunJournal:
"requires_confirmation": True,
"cad_execution_started": False, "original_scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}}
from .resume_diff import resume_diff
value['diff'] = resume_diff(service, value)
value['diff'] = resume_diff(service, value, current_plan_hashes=current_hashes)
if not value['diff']['safe']:
value['blockers'] = value['diff']['blockers']
value['resume_ready'] = False
return value
+33 -4
View File
@@ -57,6 +57,9 @@ class ScheduleStore:
auto_start INTEGER NOT NULL, idle_only INTEGER NOT NULL, title TEXT NOT NULL,
status TEXT NOT NULL, created_utc TEXT NOT NULL, updated_utc TEXT NOT NULL,
claimed_utc TEXT, finished_utc TEXT, run_id TEXT, result TEXT)""")
db.execute("""CREATE TABLE IF NOT EXISTS schedule_events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT, schedule_id TEXT NOT NULL,
at_utc TEXT NOT NULL, event TEXT NOT NULL, run_id TEXT, payload TEXT NOT NULL)""")
@contextmanager
def _connect(self):
@@ -168,16 +171,34 @@ class ScheduleStore:
db.execute("COMMIT")
return self.get(schedule_id)
def claim(self, schedule_id):
def events(self, limit=20):
limit = max(1, min(int(limit), 100))
with self._connect() as db:
rows = db.execute('SELECT * FROM schedule_events ORDER BY sequence DESC LIMIT ?', (limit,)).fetchall()
return [{**dict(row), 'payload': json.loads(row['payload'])} for row in rows]
@staticmethod
def _event(db, schedule_id, stamp, event, run_id, payload):
from .evidence import scrub
db.execute('INSERT INTO schedule_events (schedule_id, at_utc, event, run_id, payload) VALUES (?, ?, ?, ?, ?)',
(schedule_id, stamp, event, run_id, json.dumps(scrub(payload), ensure_ascii=False)))
def claim(self, schedule_id, *, run_id=None, automatic=False):
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
row = db.execute("SELECT * FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
if row is None:
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
if row["status"] != "pending":
db.execute("ROLLBACK"); raise TaskCenterError("schedule_claimed", "schedule is already claimed or finished")
if automatic and not row['auto_start']:
db.execute('ROLLBACK'); raise TaskCenterError('schedule_authority', 'automatic dispatch requires saved native authorization')
stamp = _now().isoformat(timespec="seconds")
db.execute("UPDATE schedules SET status = 'claimed', claimed_utc = ?, updated_utc = ? WHERE schedule_id = ?", (stamp, stamp, schedule_id))
db.execute("UPDATE schedules SET status = 'claimed', claimed_utc = ?, updated_utc = ?, run_id = ? WHERE schedule_id = ?", (stamp, stamp, run_id, schedule_id))
self._event(db, schedule_id, stamp, 'dispatch', run_id, {
'automatic': bool(automatic),
'authority': 'native_future_authorization' if automatic else 'native_confirmation',
'scope': {'task_ids': json.loads(row['task_ids']), 'plan_hashes': json.loads(row['plan_hashes'])}})
db.execute("COMMIT")
return self.get(schedule_id)
@@ -194,6 +215,7 @@ class ScheduleStore:
stamp = _now().isoformat(timespec="seconds")
db.execute("UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, run_id = ?, result = ? WHERE schedule_id = ?",
(status, stamp, stamp, values.get("run_id"), json.dumps(values, ensure_ascii=False), schedule_id))
self._event(db, schedule_id, stamp, 'result', values.get('run_id'), {'status': status, **values})
db.execute("COMMIT")
return self.get(schedule_id)
@@ -213,6 +235,12 @@ class ScheduleStore:
from ..trial_task_center.task_queue import _plan_hash
for row in self.list_schedules():
blockers = []
if row['status'] != 'pending':
rows.append({**row, 'blockers': ['already_claimed' if row['status'] == 'claimed' else 'finished'],
'ready': False, 'requires_confirmation': not row['auto_start'], 'dispatchable': False,
'dispatch_authority': 'native_future_authorization' if row['auto_start'] else 'native_confirmation_required',
'scope': {'task_ids': row['task_ids'], 'plan_hashes': row['plan_hashes']}})
continue
if row["status"] == "claimed": blockers.append("already_claimed")
elif row["status"] != "pending": blockers.append("finished")
if datetime.fromisoformat(row["not_before"]) > when.astimezone(timezone.utc): blockers.append("not_due")
@@ -235,7 +263,8 @@ class ScheduleStore:
if row["dependencies"] and not all(self._completed(service, task_id) for task_id in row["dependencies"]): blockers.append("dependency_incomplete")
blockers = list(dict.fromkeys(blockers))
rows.append({**row, "blockers": blockers, "ready": not blockers,
"requires_confirmation": True, "dispatchable": False,
"requires_confirmation": not row['auto_start'], "dispatchable": not blockers and row['auto_start'],
"dispatch_authority": 'native_future_authorization' if row['auto_start'] else 'native_confirmation_required',
"scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}})
rows.sort(key=lambda item: (-_PRIORITY[item["priority"]], item["not_before"], item["created_utc"]))
return rows
@@ -17,7 +17,7 @@ from ...dsh.scheduling import ScheduleStore
from ...dsh.experience import ExperienceStore
from ...dsh.ticket_tracking import TicketTracker
from ...dsh.impact import execution_impact
from ...dsh.health import HealthStore
from ...dsh.health import HealthStore, execution_check
from ...dsh.decision_log import DecisionLog
from ..errors import TaskCenterError
from .dsh_task_lifecycle import DshLifecycleDialog
@@ -73,8 +73,10 @@ class DshOperationsController(QObject):
self.dialog = None
self.worker = None
self.request_id = None
self._observed_execution = None
self.results = {}
self.cache = {'runs': [], 'schedules': [], 'experiences': [], 'tickets': [], 'decisions': [],
self.cache = {'runs': [], 'schedules': [], 'schedule_events': [], 'section_errors': [],
'experiences': [], 'tickets': [], 'decisions': [],
'decision_audit': {'status': 'unknown'},
'health': {'status': 'degraded', 'checks': []}, 'activity': {}}
self.timer = QTimer(self)
@@ -93,7 +95,23 @@ class DshOperationsController(QObject):
view.stopped.connect(self.runtime_stopped)
def context(self):
return {**self.cache, 'busy': bool(self.busy or self.window._workers or self._other_dialog())}
value = {**self.cache, 'busy': bool(self.busy or self.window._workers or self._other_dialog())}
health = self.cache.get('health', {})
if health.get('checks'):
checks = [execution_check(self._execution_state()) if row['name'] == 'execution' else dict(row)
for row in health['checks']]
value['health'] = {**health, 'checks': checks,
'status': 'blocked' if any(row['status'] == 'blocked' for row in checks) else
'degraded' if any(row['status'] == 'degraded' for row in checks) else 'ok'}
return value
def _execution_state(self):
if self.window._dsh_live_run.get('active'):
return 'running'
if self.dialog or any(getattr(ctl, 'dialog', None) for ctl in
(self.window._dsh_lifecycle, self.window._dsh_task_creation)):
return 'confirmation'
return 'busy' if any(worker is not self.worker for worker in self.window._workers) else 'idle'
def _state(self, status, message='', **values):
self.cache['activity'] = {'status': status, 'message': message, **values}
@@ -117,6 +135,7 @@ class DshOperationsController(QObject):
code=getattr(error, 'code', 'operations_error'))
def _work(self, action, done, *, request_id=None, reserve_lane=True):
self._observed_execution = self._execution_state()
worker = ServiceWorker(action)
self.worker = worker
if reserve_lane:
@@ -168,29 +187,56 @@ class DshOperationsController(QObject):
def _read(self, *, synchronize_tickets=False):
service = self.window.service
runs = []
for row in self.runs.list_runs():
value = self.runs.inspect(service, row['run_id'])
if not value.get('remaining_task_ids') or value['status'] == 'completed':
value['resume_ready'] = False
runs.append(value)
tickets = self.tickets.list_tickets()
if synchronize_tickets:
errors = []
def observe(section, operation, default):
try:
return operation()
except Exception:
errors.append({'section': section, 'code': 'section_unavailable'})
return default
def read_runs():
rows = []
for row in self.runs.list_runs():
if row['status'] in {'completed', 'failed'}:
# Terminal history displays its persisted outcome, without
# rehashing current CAD inputs on every timer tick.
value = {**row, 'tasks': (row.get('result') or {}).get('tasks', []),
'resume_ready': False, 'remaining_task_ids': [], 'blockers': []}
else:
value = self.runs.inspect(service, row['run_id'])
if not value.get('remaining_task_ids'):
value['resume_ready'] = False
rows.append(value)
return rows
def read_tickets():
tickets = self.tickets.list_tickets()
# One existing ticket per refresh keeps the desktop responsive and
# avoids polling every model turn or creating any remote content.
candidates = sorted(tickets, key=lambda row: row.get('last_attempt_at') or '')
candidates = sorted(tickets, key=lambda row: row.get('last_attempt_at') or '') if synchronize_tickets else []
if candidates:
self.tickets.refresh(candidates[0]['incident_id'])
tickets = self.tickets.list_tickets()
return tickets[:20]
result = {
'runs': observe('runs', read_runs, []),
'schedules': observe('schedules', lambda: self.schedules.evaluate(service), []),
'schedule_events': observe('schedule_events', self.schedules.events, []),
'experiences': observe('experiences', lambda: self.experiences.refresh()[:20], []),
'tickets': observe('tickets', read_tickets, [])}
decisions, audit = self._read_decisions()
health = self.health.snapshot(service)
health = observe('health', lambda: self.health.snapshot(service, execution=self._observed_execution),
{'status': 'degraded', 'checks': []})
health['checks'].append({'name': 'decision_audit', 'status': 'ok' if audit['status'] == 'ok' else 'degraded',
'code': audit['code'], 'message': audit['message']})
if audit['status'] != 'ok' and health['status'] == 'ok':
health['status'] = 'degraded'
return {'runs': runs, 'schedules': self.schedules.evaluate(service),
'experiences': self.experiences.refresh()[:20], 'tickets': tickets[:20],
'health': health, 'decisions': decisions, 'decision_audit': audit}
for error in errors:
health['checks'].append({'name': error['section'], 'status': 'degraded',
'code': error['code'], 'message': '此区块暂不可读,请保留原记录并检查访问权限。'})
if errors and health['status'] == 'ok':
health['status'] = 'degraded'
return {**result, 'section_errors': errors,
'health': health, 'decisions': decisions, 'decision_audit': audit}
def refresh(self, *, synchronize_tickets=False):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
@@ -212,7 +258,7 @@ class DshOperationsController(QObject):
def ready(value):
self.cache.update(value)
self.window._bind_dsh_context()
candidate = next((r for r in value['schedules'] if r['ready'] and r['auto_start']), None)
candidate = next((r for r in value['schedules'] if r['dispatchable']), None)
if candidate and not self.window.plan_panel.has_unsaved_plan(candidate['task_ids']):
# Preserve the original native future-run authorization. This
# is not a model-supplied confirmation flag.
@@ -242,7 +242,7 @@ class DshTaskLifecycleController(QObject):
def check():
current = next((r for r in self.window._dsh_operations.schedules.evaluate(self.window.service)
if r['schedule_id'] == row['schedule_id']), None)
if not current or not current['ready'] or (automatic and not current['auto_start']):
if not current or not current['ready'] or (automatic and not current['dispatchable']):
raise TaskCenterError('schedule_blocked', '排期尚未满足时间、依赖或执行门禁。')
return current, api.preflight(self.window.service, current['task_ids'])
self._work(check, lambda pair: self._preflight_ready(request_id, 'execute', pair[0]['task_ids'], pair[1],
@@ -282,7 +282,7 @@ class DshTaskLifecycleController(QObject):
stop = self.window._batch_stop
def operation():
return execute_confirmed_run(self.window.service, self.window.service.layout_settings_path.parent,
ids, report, stop, run_id, resume=resume, schedule=schedule)
ids, report, stop, run_id, resume=resume, schedule=schedule, automatic=automatic)
def done(result):
self.window._finish_run(); self.active_ids = ()
self.window._metadata_changed(None)
@@ -649,7 +649,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
context = self._context
enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules)
from ...dsh import task_lifecycle as lifecycle
report = lifecycle.preflight(self.service, [context.task.task_id])
try:
report = lifecycle.preflight(self.service, [context.task.task_id])
except Exception as error:
self._show_error(error, owner_task_id=context.task.task_id)
return
self._dsh_confirmation_impact = report.get('impact', {})
if not self._quick_run_confirmer('current', 1, enabled):
return
@@ -692,7 +696,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
report = None
if len(ids) <= 20:
from ...dsh import task_lifecycle as lifecycle
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
try:
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
except Exception as error:
self._show_error(error, owner_task_id=ids[0])
return
self._dsh_confirmation_impact = report.get('impact', {}) if report else {}
if not self._quick_run_confirmer('batch', len(ids), 0):
return
+15
View File
@@ -23,6 +23,21 @@ GOOD = {'queue_complete': True, 'failed_items': 0, 'interrupted': False, 'paused
'saved_items': 1, 'completed_items': 1}
def test_unchanged_refresh_does_not_rewrite_index_and_evidence_changes_invalidate(tmp_path):
import os
directory = incident(tmp_path, verification=GOOD)
store = ExperienceStore(tmp_path)
assert store.refresh()[0]['verified'] is True
index = tmp_path / 'dsh/experience/index.json'
os.utime(index, ns=(1000000000, 1000000000))
before = index.stat().st_mtime_ns
assert store.refresh()[0]['verified'] is True
assert index.stat().st_mtime_ns == before
(directory / 'verification.json').write_text(json.dumps(GOOD | {'failed_items': 1}), encoding='utf8')
assert store.refresh()[0]['verified'] is False
assert index.stat().st_mtime_ns != before
def test_verified_experience_requires_persisted_verification_and_evidence(tmp_path):
incident(tmp_path, verification=GOOD)
store = ExperienceStore(tmp_path)
+2 -5
View File
@@ -5,7 +5,7 @@ from dx_productivity.dsh.health import HealthStore
class _Service:
_workers = set()
pass
def test_health_snapshot_reports_unconfigured_provider_and_local_stores(tmp_path, monkeypatch):
@@ -19,14 +19,11 @@ def test_health_snapshot_reports_unconfigured_provider_and_local_stores(tmp_path
def test_health_snapshot_marks_active_worker_and_static_issue_token(tmp_path, monkeypatch):
class Busy(_Service):
_workers = {object()}
provider = tmp_path / 'dsh' / 'provider.json'
provider.parent.mkdir(parents=True)
provider.write_text(json.dumps({'base_url': 'https://example.test/v1', 'default_model': 'm'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.health.load_bootstrap', lambda: {'token': 'secret', 'username': 'u', 'scopes': ['write:issue'], 'server': 'https://git.test', 'repository': 'o/r'})
value = HealthStore(tmp_path).snapshot(Busy())
value = HealthStore(tmp_path).snapshot(_Service(), execution='busy')
checks = {row['name']: row for row in value['checks']}
assert checks['execution']['status'] == 'degraded'
assert checks['execution']['code'] == 'worker_active'
+13 -2
View File
@@ -6,13 +6,15 @@ from dx_productivity.dsh.issue_broker import IssueBroker, IssueBrokerConfig
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_broker_exchange_issues_short_lived_fixed_target_token(monkeypatch):
def test_broker_identifies_static_revocable_token_without_false_expiry(monkeypatch):
monkeypatch.setenv('DSH_BROKER_SECRET', 'server-secret')
config = IssueBrokerConfig.from_environment({**TARGET, 'token': 'git-issue-token', 'secret': 'server-secret'})
broker = IssueBroker(config)
value = broker.exchange({**TARGET, 'instance_id': 'machine-1', 'instance_proof': broker.proof('machine-1'),
'idempotency_key': 'event-1'})
assert value['token'] == 'git-issue-token' and 30 <= value['expires_in'] <= 3600
assert value['token'] == 'git-issue-token'
assert value['credential_kind'] == 'revocable_static' and value['expires_utc'] is None
assert 'expires_in' not in value
assert value['repository'] == TARGET['repository']
@@ -30,3 +32,12 @@ def test_broker_rejects_wrong_target_and_reuses_idempotency(monkeypatch):
assert str(error) == 'invalid_target'
else:
raise AssertionError('wrong target accepted')
def test_broker_cache_is_bounded_and_partitioned_by_instance():
config = IssueBrokerConfig.from_environment({**TARGET, 'token': 't', 'secret': 's', 'max_entries': 2})
broker = IssueBroker(config)
for index in range(5):
instance = f'machine-{index}'
broker.exchange({**TARGET, 'instance_id': instance, 'instance_proof': broker.proof(instance), 'idempotency_key': 'same'})
assert len(broker._issued) == 2
+18 -7
View File
@@ -6,16 +6,17 @@ from dx_productivity.dsh.issue_transport import IssueTransport
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_transport_uses_short_lived_broker_credential_without_caching_token(tmp_path, monkeypatch):
def test_transport_reports_revocable_static_broker_credential_without_caching_token(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange', 'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {'token': 'short-secret', 'expires_in': 120})
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {**TARGET, 'token': 'static-broker-secret', 'credential_kind': 'revocable_static', 'expires_utc': None})
value = IssueTransport(config).credentials(TARGET)
assert value['source'] == 'broker'
assert value['headers']['Authorization'] == 'token short-secret'
assert value['rotation_required'] is False
assert value['headers']['Authorization'] == 'token static-broker-secret'
assert value['rotation_required'] is True
assert value['expires_utc'] is None and value['credential_kind'] == 'revocable_static'
cache = list(tmp_path.rglob('*'))
assert all('short-secret' not in p.read_text(encoding='utf8', errors='ignore') for p in cache if p.is_file())
assert all('static-broker-secret' not in p.read_text(encoding='utf8', errors='ignore') for p in cache if p.is_file())
def test_transport_marks_bootstrap_fallback_for_rotation(tmp_path, monkeypatch):
@@ -40,7 +41,17 @@ def test_git_publisher_connection_prefers_broker_transport(tmp_path, monkeypatch
from dx_productivity.dsh.git_issues import GitIssuePublisher
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange', 'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {'token': 'ephemeral', 'expires_in': 60})
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {**TARGET, 'token': 'broker-token', 'credential_kind': 'revocable_static', 'expires_utc': None})
_, headers, source = GitIssuePublisher(config).connection()
assert headers == {'Authorization': 'token ephemeral'}
assert headers == {'Authorization': 'token broker-token'}
assert source == 'broker'
def test_transport_rejects_wrong_broker_response_target(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange',
'instance_id': 'machine-1', 'instance_proof': 'proof', 'idempotency_key': 'event-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {
**TARGET, 'repository': 'other/repo', 'token': 'private', 'credential_kind': 'revocable_static', 'expires_utc': None})
value = IssueTransport(config).credentials(TARGET)
assert 'headers' not in value and value['source'] == 'broker_unavailable'
+38 -22
View File
@@ -1,32 +1,48 @@
from types import SimpleNamespace as NS
from dx_productivity.dsh.resume_diff import resume_diff
from dx_productivity.dsh.run_journal import RunJournal
from test_run_journal import project_service, checkpoint, evidence
class Service:
def __init__(self, contexts, hashes=None): self.contexts, self.current_plan_hashes = contexts, hashes or {'t1': 'h1', 't2': 'h2'}
def task_context(self, task_id): return self.contexts[task_id]
def test_real_service_plan_changes_are_reported(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
rule = service.rules(ids[0])[0]
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='DIFFERENT', enabled=True)
report = journal.inspect(service, 'a' * 32)
assert ids[0] in report['diff']['changed']
change = next(row for row in report['diff']['plan_changes'] if row['task_id'] == ids[0])
assert change['saved'] == hashes[ids[0]] and change['current'] != change['saved']
assert report['diff']['safe'] is False
def context(status='ready', interrupted=False):
return NS(task=NS(status=NS(value=status), name='Board'), progress=NS(queue_complete=status == 'completed',
saved_items=1 if status == 'completed' else 0, failed_items=0, no_match_items=0), interrupted=interrupted)
def test_real_service_uses_original_checkpoint_remaining_scope(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
report = journal.inspect(service, 'a' * 32)
assert report['diff']['safe'] is True
assert report['diff']['remaining'] == ids
assert report['diff']['completed'] == []
def inspected():
return {'run_id': 'a' * 32, 'task_ids': ['t1', 't2'], 'remaining_task_ids': ['t2'],
'plan_hashes': {'t1': 'h1', 't2': 'h2'}, 'queue_available': True, 'resume_ready': True,
'blockers': [], 'tasks': [{'task_id': 't1', 'status': 'completed'}, {'task_id': 't2', 'status': 'ready'}]}
def test_evidence_counter_changes_since_receipt_are_visible(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('a' * 32, ids, hashes)
checkpoint(data, 'a' * 32, ids, hashes)
journal.finish('a' * 32, {'status': 'paused', 'tasks': [{'task_id': ids[0], 'no_match_items': 0}]})
evidence(service, ids[0])
report = journal.inspect(service, 'a' * 32)
assert {'task_id': ids[0], 'field': 'no_match_items', 'saved': 0, 'current': 1} in report['diff']['evidence_changes']
assert 'evidence_changed' in report['diff']['blockers']
def test_resume_diff_is_safe_for_unchanged_frozen_scope():
value = resume_diff(Service({'t1': context('completed'), 't2': context()}), inspected())
assert value['safe'] is True and value['completed'] == ['t1'] and value['remaining'] == ['t2']
assert value['changed'] == []
def test_resume_diff_blocks_plan_change_and_uncertainty():
row = inspected()
value = resume_diff(Service({'t1': context('completed', interrupted=True), 't2': context()}, {'t1': 'changed', 't2': 'h2'}), row)
def test_missing_current_hash_cannot_be_silently_ignored(project_service):
service, _, _, ids, hashes = project_service
value = resume_diff(service, {'task_ids': ids, 'plan_hashes': {}, 'remaining_task_ids': ids,
'queue_available': True, 'resume_ready': True, 'tasks': []})
assert value['safe'] is False
assert 'plan_changed' in value['blockers'] and 'interrupted' in value['blockers']
assert value['changed'] == ids
+35 -2
View File
@@ -49,12 +49,45 @@ def test_due_order_and_manual_confirmation_without_execution(project_service):
urgent = schedules.save(spec(ids, priority='urgent', auto_start=True), hashes)
rows = schedules.evaluate(service, now=NOW)
assert [row['schedule_id'] for row in rows] == [urgent['schedule_id'], normal['schedule_id']]
assert rows[0]['ready'] and rows[0]['requires_confirmation'] is True
assert rows[0]['dispatchable'] is False # model-supplied auto_start never grants authority
assert rows[0]['ready'] and rows[0]['requires_confirmation'] is False
assert rows[0]['dispatchable'] is True # save follows native future-run authorization
assert rows[0]['dispatch_authority'] == 'native_future_authorization'
assert rows[1]['requires_confirmation'] and not rows[1]['dispatchable']
assert not list(data.rglob('command.tsv'))
assert all('worker_busy' in row['blockers'] for row in schedules.evaluate(service, now=NOW, busy=True))
def test_dispatch_and_result_audit_are_durable_and_automatic_claim_needs_authority(project_service):
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
manual = schedules.save(spec(ids), hashes)
with pytest.raises(TaskCenterError, match='schedule_authority'):
schedules.claim(manual['schedule_id'], automatic=True, run_id='a' * 32)
assert schedules.get(manual['schedule_id'])['status'] == 'pending'
assert schedules.events() == []
row = schedules.save(spec(ids, auto_start=True), hashes)
schedules.claim(row['schedule_id'], automatic=True, run_id='b' * 32)
schedules.finish(row['schedule_id'], 'completed', run_id='b' * 32, receipt={'status': 'completed'})
events = ScheduleStore(data).events()
assert [e['event'] for e in reversed(events)] == ['dispatch', 'result']
assert events[1]['payload']['scope'] == {'task_ids': ids, 'plan_hashes': hashes}
assert events[1]['payload']['authority'] == 'native_future_authorization'
assert events[0]['payload']['receipt']['status'] == 'completed'
assert all(e['run_id'] == 'b' * 32 for e in events)
def test_audit_insert_failure_rolls_back_claim_before_execution(project_service):
import sqlite3
_, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
row = schedules.save(spec(ids, auto_start=True), hashes)
with sqlite3.connect(schedules.path) as db:
db.execute("CREATE TRIGGER reject_event BEFORE INSERT ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled audit fault'); END")
with pytest.raises(sqlite3.IntegrityError):
schedules.claim(row['schedule_id'], automatic=True, run_id='b' * 32)
assert ScheduleStore(data).get(row['schedule_id'])['status'] == 'pending'
def test_future_and_changed_plans_do_not_become_ready(project_service):
service, _, data, ids, hashes = project_service
schedules = ScheduleStore(data)
+54
View File
@@ -25,6 +25,40 @@ def test_live_snapshot_reports_running_and_pause_request_without_claiming_paused
assert not view.operations['live_run']['active']
def test_execution_health_follows_real_window_run_state(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
ui.window._begin_run(ui.tasks[0].task_id)
ui.window._bind_dsh_context()
check = next(row for row in view.operations['health']['checks'] if row['name'] == 'execution')
assert check['code'] == 'execution_running'
ui.window._finish_run()
check = next(row for row in view.operations['health']['checks'] if row['name'] == 'execution')
assert check['code'] == 'idle'
def test_receipt_enrichment_failure_does_not_erase_executor_result(ui, monkeypatch):
from threading import Event
from dx_productivity.dsh import task_lifecycle as api
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal
original = RunJournal.finish
calls = []
def fail_enrichment(self, run_id, receipt):
calls.append(run_id)
if len(calls) > 1:
raise OSError('controlled enrichment persistence failure')
return original(self, run_id, receipt)
monkeypatch.setattr(RunJournal, 'finish', fail_enrichment)
ids = [ui.tasks[0].task_id]
receipt = execute_confirmed_run(ui.service, ui.data, ids, api.preflight(ui.service, ids), Event(), 'f' * 32)
assert receipt['status'] == 'completed'
assert receipt['reporting_errors'][0]['code'] == 'receipt_enrichment_unavailable'
assert RunJournal(ui.data).get('f' * 32)['result']['entries'][0]['state'] == 'completed'
def test_live_owner_and_saved_counts_do_not_follow_selected_task(ui, monkeypatch, qtbot):
from dx_productivity.dsh.live_state import read_live_run
from dx_productivity.trial_task_center.execution_feedback import ExecutionFeedback
@@ -165,6 +199,22 @@ def test_audit_read_error_does_not_hide_health_or_leak_error_text(ui, monkeypatc
assert 'private-test-value' not in json.dumps(view.operations)
@pytest.mark.parametrize('section', ['experiences', 'schedule_events'])
def test_independent_section_failure_keeps_schedules_and_health_visible(ui, monkeypatch, qtbot, section):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
def unavailable(*_args, **_kwargs):
raise OSError('Authorization: Bearer private-test-value')
target, method = (ctl.experiences, 'refresh') if section == 'experiences' else (ctl.schedules, 'events')
monkeypatch.setattr(target, method, unavailable)
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
assert view.operations['section_errors'] == [{'section': section, 'code': 'section_unavailable'}]
assert view.operations['health']['status'] == 'degraded'
assert isinstance(view.operations['schedules'], list)
assert 'private-test-value' not in json.dumps(view.operations)
def test_stopping_generation_does_not_request_pause_of_confirmed_task(ui, monkeypatch):
view = setup_view(ui, monkeypatch); ctl=ui.window._dsh_lifecycle
task_id=ui.tasks[0].task_id; ui.window._begin_run(task_id)
@@ -204,6 +254,10 @@ def test_scheduled_run_requires_native_confirmation_and_executes_once(ui, monkey
ctl.tick(); ui.settle()
assert len(ui.calls) == 1
assert view.operations['last_execution']['tasks'][0]['no_match_items'] == 1
events = ctl.schedules.events()
assert [row['event'] for row in events] == ['result', 'dispatch']
assert events[1]['payload']['automatic'] is True
assert events[0]['payload']['receipt']['tasks'][0]['no_match_items'] == 1
def test_ops_impact_and_history_are_read_only_and_native_cancel_does_not_schedule(ui, monkeypatch, qtbot):
@@ -9,6 +9,21 @@ from PySide6.QtCore import Qt
from PySide6.QtGui import QCloseEvent
@pytest.mark.parametrize('entry', ['current', 'batch'])
def test_native_preflight_error_is_visible_and_does_not_start_execution(ui, monkeypatch, entry):
from dx_productivity.trial_task_center.errors import TaskCenterError
def failed(*args, **kwargs):
raise TaskCenterError('assistant_stale', '受控预检异常,请重新核对。')
monkeypatch.setattr('dx_productivity.dsh.task_lifecycle.preflight', failed)
window = ui.window
if entry == 'current':
window._prepare_quick_run()
else:
window._execute_project_tasks()
assert '受控预检异常' in window.run_panel.operator_band.text()
assert not ui.calls and not window._dsh_authorized_tasks
@pytest.mark.parametrize('accept',[False,True])
def test_current_task_executes_only_after_confirmation_and_no_match_is_completed(ui,accept):
w=ui.window;confirmations=[]
+5 -1
View File
@@ -1,4 +1,8 @@
"""Reference fixed-target DSH issue broker; secrets are environment-only."""
"""Reference fixed-target DSH static credential distributor; secrets are environment-only.
Git credentials remain valid until revoked/rotated on the server. The bounded
response cache is not a token expiry mechanism. Deploy behind managed HTTPS.
"""
from __future__ import annotations
import argparse
+9
View File
@@ -24,4 +24,13 @@ assert.equal(auditSnapshot.operations.decision_audit.status,'corrupt');
assert.equal(auditSnapshot.operations.decision_audit.code,'audit_log_corrupt');
assert.equal(auditSnapshot.operations.decision_audit.checked,2001);
assert.equal(auditSnapshot.operations.decision_audit.raw_error,undefined);
const scheduleSnapshot=modelSnapshot({operations:{schedules:[{schedule_id:'s',dispatchable:true,
requires_confirmation:false,dispatch_authority:'native_future_authorization',plan_hashes:{task:'frozen'}}],
schedule_events:Array.from({length:25},(_,i)=>({sequence:i,event:'dispatch',payload:{automatic:true,
authority:'native_future_authorization',scope:{plan_hashes:{task:'frozen'}}}}))}});
assert.equal(scheduleSnapshot.operations.schedules[0].dispatchable,true);
assert.equal(scheduleSnapshot.operations.schedules[0].requires_confirmation,false);
assert.equal(scheduleSnapshot.operations.schedule_events.length,10);
assert.equal(scheduleSnapshot.operations.schedule_events[0].payload.authority,'native_future_authorization');
assert.ok(!JSON.stringify(scheduleSnapshot).includes('frozen'));
console.log(JSON.stringify({status:'passed',committedIdsPreserved:true,impactRowsBounded:true,snapshotBounded:true}));
+10
View File
@@ -114,6 +114,7 @@ try{
await select('Board-A');
await send('现在执行 Board-A 任务,只运行这一个工程,按原生确认的范围处理。结束后告诉我真实保存、失败和未命中数量。');
await wait(async()=>(await context()).operations?.live_run?.active===true,'live controlled run');
assert.equal((await context()).operations.health.checks.find(row=>row.name==='execution')?.code,'execution_running');
await pauseLiveRun();
await wait(async()=>{const d=await context();return d.operations?.last_execution?.status==='paused'&&!d.operations?.live_run?.active;},'safe pause receipt');
const receipt=(await context()).operations.last_execution;assert.equal(receipt.tasks[0].no_match_items,1);assert.equal(receipt.tasks[0].saved_items,0);
@@ -148,6 +149,15 @@ try{
const schedule=(await context()).operations.schedules[0];assert.equal(schedule.auto_start,true);report.schedule=schedule;
await new Promise(r=>setTimeout(r,17000));await click('dx-schedules-refresh');
await wait(async()=>(await context()).operations?.schedules?.[0]?.status==='completed','schedule remains terminal');
await wait(async()=>{const events=(await context()).operations?.schedule_events||[];
return events.some(row=>row.event==='dispatch')&&events.some(row=>row.event==='result');},'persisted schedule audit events');
const scheduleEvents=(await context()).operations.schedule_events;
assert.equal(scheduleEvents.find(row=>row.event==='dispatch').payload.authority,'native_future_authorization');
assert.equal(scheduleEvents.find(row=>row.event==='result').payload.receipt.status,'completed');
await wait(()=>c.evaluate(`document.body.innerText.includes('排期派发记录')&&document.body.innerText.includes('排期结果记录')`),'schedule audit cards rendered');
report.scheduleEvents=scheduleEvents;
await c.screenshot(path.join(output,'schedule-audit-events.png'));
report.checks.push('native future-run dispatch and actual receipt persisted and rendered in schedule audit cards');
report.checks.push('cancel saved nothing; explicit future-run authorization executed due mapping scope exactly once');
await tab('usage');
assert.deepEqual(await c.evaluate(`fetch('/dx/runtime').then(r=>r.json()).then(x=>x.settings)`),{response_timeout_seconds:120,model_context_limit:12000});