flower-trellis 0.6.13-beta.11 → 0.6.13-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/enhancements/0.6/scripts/confirmation.md +1 -1
- package/enhancements/0.6/scripts/confirmation_policy.py +15 -4
- package/enhancements/MANIFEST.json +2 -2
- package/package.json +3 -3
- package/src/assets/flower_confirmation_runtime/claude.py +70 -3
- package/src/assets/flower_confirmation_runtime/codex.py +126 -8
- package/src/assets/flower_confirmation_runtime/runtime.py +24 -7
- package/src/assets/flower_confirmation_runtime/session_log.py +62 -1
|
@@ -22,7 +22,7 @@ Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前
|
|
|
22
22
|
先从项目根执行 `python3 .trellis/scripts/flower_confirmation_hook.py --entry`,读取实际返回的 `entry` argv,后续在其后追加 `prepare`、`wait` 等子命令。入口固定为项目内 `.trellis/scripts/flower_confirmation.py`,内部复用当前 Python 解释器,仅依赖标准库和项目脚本。`entry=null` 或工具失败才报告实际原因;不能用无 stdout 的 `test -f` 推断入口不存在。确认阶段无需 Node、npm、全局 Flower 或额外 pip 安装。
|
|
23
23
|
|
|
24
24
|
1. 在 gitignored `.trellis/.runtime/` 为当前平台和会话写一个 JSON 材料文件,路径不得复用于并行会话。不要把它放入提交集合,不生成公开报告附件。使用结构化文件写入,用户正文和 message 不拼入 shell。
|
|
25
|
-
2. JSON 的公共字段为 `kind: brief|check|push`、`task
|
|
25
|
+
2. JSON 的公共字段为 `kind: brief|check|push`、`task`。Brief 必须指定目标活动任务的精确相对路径,正文读取该任务 `brief.md`;当前会话允许尚未绑定任务,已有绑定须与目标一致。会话绑定另行冻结,等待期间变化使旧确认失效。Check/Push 使用当前精确任务相对路径,无任务为 null,另提供完整标准报告/计划的 `body`。
|
|
26
26
|
3. Check 必填 `reportVersion`、`dispositionVersion`(非空版本字符串)及 `findings: [{id:"CHK-001",status:"pending"}]`;status 只接受 pending/accepted/resolved。必须覆盖当前全部条目,禁止只传准备修复的子集来改变默认动作。
|
|
27
27
|
4. Push 必填 `mode: push|commit-only`、`evidence: {check:passed|accepted|focused,spec:no-op|written,unresolvedRisks:0}` 和有序 `repositories`。每仓包含 `root`、实际 `branch`、完整 `head`(初始空仓为 null)、实际 `upstream`(没有为 null)、精确 `message`、完整 `files` 路径列表。把已展示的生成命令、任务记录 exact files 与顺序一并保存在输入中,不在领取后扩大范围。
|
|
28
28
|
5. 从项目根执行 `python3 -X utf8 .trellis/scripts/flower_confirmation.py prepare --platform codex|claude --input <相对路径>`;用户明确指定本次时长时加 `--seconds <正整数秒>`。仅 `prepared=true` 可继续,任何错误或 false 保持原人工提示。
|
|
@@ -19,6 +19,7 @@ from pathlib import Path
|
|
|
19
19
|
|
|
20
20
|
from common.config import parse_simple_yaml
|
|
21
21
|
from common.active_task import resolve_active_task
|
|
22
|
+
from common.tasks import normalize_closeout
|
|
22
23
|
|
|
23
24
|
|
|
24
25
|
VERSION = 1
|
|
@@ -342,8 +343,14 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
342
343
|
raise ValueError("未知确认种类")
|
|
343
344
|
active = resolve_active_task(root, {"session_id": session_id}, platform,
|
|
344
345
|
allow_single_session_fallback=False, allow_environment_context=False)
|
|
345
|
-
task = active.task_path
|
|
346
|
-
if
|
|
346
|
+
task = material.get("task") if kind == "brief" else active.task_path
|
|
347
|
+
if kind == "brief":
|
|
348
|
+
# Brief 先确认再 start,因此目标任务来自材料;会话绑定另行冻结以检测等待期间的切换。
|
|
349
|
+
if active.source_type != "session" or active.stale:
|
|
350
|
+
raise ValueError("Brief 确认的当前会话任务状态无效")
|
|
351
|
+
if not isinstance(task, str) or not re.fullmatch(r"\.trellis/tasks/[^/]+", task):
|
|
352
|
+
raise ValueError("Brief 确认必须指定活动任务目录")
|
|
353
|
+
if (kind != "brief" or active.task_path is not None) and material.get("task") != active.task_path:
|
|
347
354
|
raise ValueError("确认材料与当前会话任务不符")
|
|
348
355
|
task_manual_only = False
|
|
349
356
|
task_files = {}
|
|
@@ -352,6 +359,10 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
352
359
|
task_metadata = json.loads(metadata_bytes.decode("utf-8"))
|
|
353
360
|
if not isinstance(task_metadata, dict) or not isinstance(task_metadata.get("meta", {}), dict):
|
|
354
361
|
raise ValueError("任务元数据无效")
|
|
362
|
+
if kind == "brief":
|
|
363
|
+
closeout = normalize_closeout(task_metadata)
|
|
364
|
+
if not closeout["valid"] or closeout["status"] == "closed":
|
|
365
|
+
raise ValueError("Brief 确认目标任务已关闭或关闭状态无效")
|
|
355
366
|
task_manual_only = task_metadata.get("meta", {}).get("confirmationTimeoutDisabled") is True
|
|
356
367
|
task_files["task.json"] = hashlib.sha256(metadata_bytes).hexdigest()
|
|
357
368
|
for name in ("prd.md", "design.md", "implement.md", "brief.md"):
|
|
@@ -359,8 +370,6 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
359
370
|
continue
|
|
360
371
|
task_files[name] = _fingerprint(_inside(root, task + "/" + name), optional=True)
|
|
361
372
|
if kind == "brief":
|
|
362
|
-
if not task:
|
|
363
|
-
raise ValueError("Brief 确认缺少当前任务")
|
|
364
373
|
brief_bytes = _bytes(_inside(root, task + "/brief.md"))
|
|
365
374
|
task_files["brief.md"] = hashlib.sha256(brief_bytes).hexdigest()
|
|
366
375
|
body = brief_bytes.decode("utf-8")
|
|
@@ -372,6 +381,8 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
372
381
|
if len(body.encode("utf-8")) > DOCUMENT_BYTES:
|
|
373
382
|
raise ValueError("确认正文超过 512 KiB 展示预算")
|
|
374
383
|
facts = {"task": task, "taskFiles": task_files, "inputHash": hashlib.sha256(input_bytes).hexdigest()}
|
|
384
|
+
if kind == "brief":
|
|
385
|
+
facts["sessionTask"] = active.task_path
|
|
375
386
|
count = 0
|
|
376
387
|
if kind == "check":
|
|
377
388
|
if not all(isinstance(material.get(key), str) and material[key] for key in ("reportVersion", "dispositionVersion")):
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"syncedAt": "2026-11-
|
|
2
|
+
"syncedAt": "2026-11-13T09:09:34.584Z",
|
|
3
3
|
"syncedFrom": "vendor/skill-garden",
|
|
4
|
-
"sourceCommit": "
|
|
4
|
+
"sourceCommit": "db2d70b197010028391bfd00271709e594709c2a",
|
|
5
5
|
"common": {
|
|
6
6
|
"codexSkills": [
|
|
7
7
|
"aliyun-ops",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "flower-trellis",
|
|
3
|
-
"version": "0.6.13-beta.
|
|
3
|
+
"version": "0.6.13-beta.13",
|
|
4
4
|
"description": "一键安装/升级 Trellis 并自动融合 skill-garden 强化包(默认 Claude + agents)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -73,9 +73,9 @@
|
|
|
73
73
|
"commit-and-tag-version": "^12.7.3"
|
|
74
74
|
},
|
|
75
75
|
"flowerReleaseNotes": {
|
|
76
|
-
"version": "0.6.13-beta.
|
|
76
|
+
"version": "0.6.13-beta.13",
|
|
77
77
|
"source": "CHANGELOG.md",
|
|
78
|
-
"body": "### 🐛 修复 Bug Fixes\n\n* **confirmation:**
|
|
78
|
+
"body": "### 🐛 修复 Bug Fixes\n\n* **confirmation:** 支持未绑定任务的 Brief 确认 ([d6a2cd1](https://github.com/SilentFlower/flower-trellis/commit/d6a2cd19ae662af92466e59cf05fbebf51fd1fb1))",
|
|
79
79
|
"truncated": false
|
|
80
80
|
},
|
|
81
81
|
"optionalDependencies": {
|
|
@@ -176,6 +176,8 @@ class ClaudeClient:
|
|
|
176
176
|
self.project = self.store.project
|
|
177
177
|
self.session_id = self.store.session_id
|
|
178
178
|
self.session_log = SessionLog()
|
|
179
|
+
self.log_start = None
|
|
180
|
+
self.prepare_turn = None
|
|
179
181
|
self.frontend = None
|
|
180
182
|
|
|
181
183
|
def connect(self):
|
|
@@ -188,14 +190,24 @@ class ClaudeClient:
|
|
|
188
190
|
or native.get("sessionId") != self.session_id or native.get("ended")):
|
|
189
191
|
raise ValueError("Claude 原生确认 Hook 不可用或会话已退出,保持人工确认")
|
|
190
192
|
confirmation_id(native.get("runId"))
|
|
191
|
-
|
|
193
|
+
|
|
194
|
+
def prepare_snapshot(self):
|
|
195
|
+
"""核对当前回合,以该回合的完整记录作为本次观察起点。
|
|
196
|
+
|
|
197
|
+
@return: 本次准备的会话快照及冻结起点。
|
|
198
|
+
"""
|
|
199
|
+
return self._snapshot(preparing=True)
|
|
192
200
|
|
|
193
201
|
def snapshot(self):
|
|
194
202
|
"""增量核验 transcript 的真实人工和任务通知来源。
|
|
195
203
|
|
|
196
204
|
@return: 人工基线、当前回合、通知和 runId。
|
|
197
205
|
"""
|
|
198
|
-
|
|
206
|
+
return self._snapshot(preparing=False)
|
|
207
|
+
|
|
208
|
+
def _snapshot(self, preparing):
|
|
209
|
+
state = self.store.read() or {}
|
|
210
|
+
native = state.get("native") or {}
|
|
199
211
|
if not native or native.get("ended"):
|
|
200
212
|
raise ValueError("Claude 会话状态不可用")
|
|
201
213
|
if self.platform == "win32":
|
|
@@ -210,6 +222,47 @@ class ClaudeClient:
|
|
|
210
222
|
if file.name != self.session_id + ".jsonl":
|
|
211
223
|
raise ValueError("Claude 缺少精确会话记录路径")
|
|
212
224
|
hook_notice = native.get("notification") or {}
|
|
225
|
+
if preparing:
|
|
226
|
+
turn = native.get("turn") or {}
|
|
227
|
+
prompt_id = confirmation_id(turn.get("id"))
|
|
228
|
+
if turn.get("status") != "inProgress":
|
|
229
|
+
raise ValueError("正式确认必须由当前活动回合准备")
|
|
230
|
+
key = (native["runId"], prompt_id)
|
|
231
|
+
if self.prepare_turn != key or self.log_start is None:
|
|
232
|
+
baseline = None
|
|
233
|
+
|
|
234
|
+
def matches(entry):
|
|
235
|
+
nonlocal baseline
|
|
236
|
+
if entry.get("promptId") != prompt_id:
|
|
237
|
+
return False
|
|
238
|
+
evidence = {"humanId": None, "notifications": {}}
|
|
239
|
+
self._consume_transcript(evidence, entry)
|
|
240
|
+
if evidence["humanId"] == prompt_id:
|
|
241
|
+
baseline = prompt_id
|
|
242
|
+
return True
|
|
243
|
+
task_id = hook_notice.get("taskId")
|
|
244
|
+
previous = state.get("request") or {}
|
|
245
|
+
if (previous.get("state") == "consumed"
|
|
246
|
+
and hook_notice.get("requestId") == previous["id"]
|
|
247
|
+
and native.get("tasks", {}).get(task_id) == previous["id"]
|
|
248
|
+
and task_id == previous.get("queueId")
|
|
249
|
+
and hook_notice.get("promptId") == evidence["notifications"].get(task_id) == prompt_id):
|
|
250
|
+
# 已核对的内部唤醒沿用前一个请求的人工基线。
|
|
251
|
+
baseline = confirmation_id(previous.get("baselineMessageId"))
|
|
252
|
+
return True
|
|
253
|
+
return False
|
|
254
|
+
|
|
255
|
+
start = SessionLog.locate(file, prompt_id, matches)
|
|
256
|
+
self._resume_log(start, baseline)
|
|
257
|
+
self.prepare_turn = key
|
|
258
|
+
else:
|
|
259
|
+
request = state.get("request") or {}
|
|
260
|
+
start = (request.get("contract") or {}).get("claudeLogStart")
|
|
261
|
+
if not start:
|
|
262
|
+
raise ValueError("Claude 请求缺少当前确认的记录起点,保持人工确认")
|
|
263
|
+
if self.log_start != start:
|
|
264
|
+
self._resume_log(start, confirmation_id(request.get("baselineMessageId")))
|
|
265
|
+
self.prepare_turn = None
|
|
213
266
|
initial = {"humanId": None, "notifications": {}}
|
|
214
267
|
record, observation = self.session_log.read(file, initial, self._consume_transcript)
|
|
215
268
|
human_id = record["humanId"]
|
|
@@ -225,12 +278,26 @@ class ClaudeClient:
|
|
|
225
278
|
and bool(hook_notice.get("requestId"))
|
|
226
279
|
and (notification or {}).get("promptId") != hook_notice.get("promptId"))
|
|
227
280
|
return {"humanId": human_id, "turn": native.get("turn"), "notification": notification,
|
|
228
|
-
"notificationPending": pending, "runId": native.get("runId"), "logObservation": observation
|
|
281
|
+
"notificationPending": pending, "runId": native.get("runId"), "logObservation": observation,
|
|
282
|
+
"claudeLogStart": self.log_start, "prepareBaseline": self.prepare_baseline}
|
|
283
|
+
|
|
284
|
+
def _resume_log(self, start, baseline):
|
|
285
|
+
self.session_log.resume(start, {"humanId": baseline, "notifications": {}})
|
|
286
|
+
self.log_start = start
|
|
287
|
+
self.prepare_baseline = baseline
|
|
229
288
|
|
|
230
289
|
def _consume_transcript(self, record, entry):
|
|
231
290
|
if entry.get("type") != "user" or entry.get("isSidechain") or entry.get("sessionId") != self.session_id:
|
|
232
291
|
return
|
|
233
292
|
kind = (entry.get("origin") or {}).get("kind")
|
|
293
|
+
turn_origin = entry.get("turnOrigin")
|
|
294
|
+
other = (isinstance(kind, str) and kind and kind not in ("human", "task-notification", "task_notification")
|
|
295
|
+
and ("turnOrigin" not in entry or turn_origin == kind))
|
|
296
|
+
transcript_only = (kind == "task-notification" and entry.get("queueTranscriptOnly") is True
|
|
297
|
+
and ("turnOrigin" not in entry or turn_origin == "task_notification"))
|
|
298
|
+
if other or transcript_only:
|
|
299
|
+
# 一致的其它来源与只写日志的通知都不提供人工输入或唤醒证据。
|
|
300
|
+
return
|
|
234
301
|
# Windows 原生记录可能只写结构化 origin;出现 turnOrigin 时仍要求两者一致。
|
|
235
302
|
only_origin = self.platform == "win32" and "turnOrigin" not in entry
|
|
236
303
|
if kind == "human" and (only_origin or entry.get("turnOrigin") == "human"):
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import json
|
|
5
6
|
import os
|
|
6
7
|
import re
|
|
7
8
|
import select
|
|
@@ -12,7 +13,7 @@ from pathlib import Path
|
|
|
12
13
|
from uuid import uuid4
|
|
13
14
|
|
|
14
15
|
from flower_tui_lifetime import bind_origin, check_binding, check_frontend_coverage, open_binding
|
|
15
|
-
from .session_log import DISPLAY_BYTES, SessionLog
|
|
16
|
+
from .session_log import DISPLAY_BYTES, RECORD_BYTES, SessionLog
|
|
16
17
|
from .store import ACTIVE, ConfirmationStore, confirmation_id, now_ms, wake_id, wake_message
|
|
17
18
|
from .transport import CodexTransport, RpcError
|
|
18
19
|
from .windows_process import check_listener_coverage, hook_frontend, listener_identity, open_identity
|
|
@@ -70,14 +71,15 @@ class CodexClient:
|
|
|
70
71
|
"""
|
|
71
72
|
self.platform = platform or sys.platform
|
|
72
73
|
if self.platform not in ("linux", "win32") or (self.platform == "win32" and sys.platform != "win32"):
|
|
73
|
-
raise ValueError("
|
|
74
|
+
raise ValueError("Codex 后台确认需要 Linux/WSL 或原生 Windows 的共享服务")
|
|
74
75
|
self.project = Path(project).resolve(strict=True)
|
|
75
76
|
self.session_id = confirmation_id(session_id)
|
|
77
|
+
self.store = ConfirmationStore(self.project, self.session_id, "codex")
|
|
76
78
|
environment = os.environ if env is None else env
|
|
77
79
|
self.home = Path(environment.get("CODEX_HOME") or (Path.home() / ".codex")).resolve(strict=True)
|
|
78
80
|
self.executable = None
|
|
79
81
|
if self.platform == "win32":
|
|
80
|
-
native = (
|
|
82
|
+
native = (self.store.read() or {}).get("native") or {}
|
|
81
83
|
if native.get("project") != str(self.project) or native.get("sessionId") != self.session_id or not native.get("hookProcess"):
|
|
82
84
|
raise ValueError("缺少 Windows Codex 原生输入 Hook,保持人工确认")
|
|
83
85
|
# 使用真实 Hook 祖先进程的映像,避免在项目目录或 PATH 中挑选代理程序。
|
|
@@ -92,6 +94,8 @@ class CodexClient:
|
|
|
92
94
|
proxy=self.executable, env=environment)
|
|
93
95
|
self.rollout = None
|
|
94
96
|
self.session_log = SessionLog()
|
|
97
|
+
self.log_start = None
|
|
98
|
+
self.prepare_turn = None
|
|
95
99
|
self.humans = []
|
|
96
100
|
self.seen = OrderedDict()
|
|
97
101
|
self.window_fd = None
|
|
@@ -125,11 +129,21 @@ class CodexClient:
|
|
|
125
129
|
"""
|
|
126
130
|
return self.transport.rpc(method, params)
|
|
127
131
|
|
|
132
|
+
def prepare_snapshot(self):
|
|
133
|
+
"""从当前原生 Hook 对应的回合建立本次观察起点。
|
|
134
|
+
|
|
135
|
+
@return: 当前回合的来源证据和冻结起点。
|
|
136
|
+
"""
|
|
137
|
+
return self._snapshot(preparing=True)
|
|
138
|
+
|
|
128
139
|
def snapshot(self):
|
|
129
140
|
"""被动读取精确线程及消息来源,观察前台退出。
|
|
130
141
|
|
|
131
142
|
@return: 人工基线、当前回合及内部唤醒快照。
|
|
132
143
|
"""
|
|
144
|
+
return self._snapshot(preparing=False)
|
|
145
|
+
|
|
146
|
+
def _snapshot(self, preparing):
|
|
133
147
|
if self.window_fd is not None:
|
|
134
148
|
if self._frontend_exited():
|
|
135
149
|
raise ValueError("frontend_exited")
|
|
@@ -144,7 +158,59 @@ class CodexClient:
|
|
|
144
158
|
raise ValueError("Codex 目标会话或项目目录不匹配")
|
|
145
159
|
if thread.get("archived") or (thread.get("status") or {}).get("type") == "systemError":
|
|
146
160
|
raise ValueError("Codex 目标线程处于错误状态")
|
|
147
|
-
|
|
161
|
+
state = self.store.read() or {}
|
|
162
|
+
request = state.get("request") or {}
|
|
163
|
+
file = self._rollout_path(thread.get("path"))
|
|
164
|
+
if preparing:
|
|
165
|
+
native = state.get("native") or {}
|
|
166
|
+
if (native.get("version") != 2 or native.get("project") != str(self.project)
|
|
167
|
+
or native.get("sessionId") != self.session_id or not native.get("turnId")):
|
|
168
|
+
raise ValueError("当前会话尚未收到确认输入 Hook,保持人工确认")
|
|
169
|
+
turn_id = confirmation_id(native["turnId"])
|
|
170
|
+
if self.prepare_turn != turn_id:
|
|
171
|
+
def matches(entry):
|
|
172
|
+
event = entry.get("payload")
|
|
173
|
+
return (entry.get("type") == "event_msg" and isinstance(event, dict)
|
|
174
|
+
and event.get("type") in ("task_started", "turn_started")
|
|
175
|
+
and event.get("turn_id") == turn_id and event.get("thread_id") in (None, self.session_id))
|
|
176
|
+
|
|
177
|
+
start = SessionLog.locate(file, turn_id, matches)
|
|
178
|
+
prior = ({key: request.get(key) for key in ("id", "baselineMessageId")}
|
|
179
|
+
if request.get("state") == "consumed" else {})
|
|
180
|
+
self._resume_rollout(file, start, turn_id, prior=prior)
|
|
181
|
+
source = self._read_rollout(file)
|
|
182
|
+
if source.get("turn") != {"id": turn_id, "status": "inProgress"} or not source.get("inputAnchor"):
|
|
183
|
+
raise ValueError("Codex 缺少可核验的当前回合输入")
|
|
184
|
+
identifier, internal = source["inputAnchor"]
|
|
185
|
+
|
|
186
|
+
def matches_input(entry):
|
|
187
|
+
event = entry.get("payload")
|
|
188
|
+
if (entry.get("type") != "event_msg" or not isinstance(event, dict)
|
|
189
|
+
or event.get("type") != "item_completed" or event.get("turn_id") != turn_id
|
|
190
|
+
or event.get("thread_id") not in (None, self.session_id)):
|
|
191
|
+
return False
|
|
192
|
+
item = event.get("item")
|
|
193
|
+
return (isinstance(item, dict) and item.get("type") == "UserMessage" and item.get("id") == identifier
|
|
194
|
+
and self._wake_id(item) == internal)
|
|
195
|
+
|
|
196
|
+
# 同回合在 prepare 之前的插话是基线;从其完整记录之后观察新的输入。
|
|
197
|
+
self._resume_rollout(file, SessionLog.locate(file, identifier, matches_input), turn_id,
|
|
198
|
+
baseline=source["humanId"])
|
|
199
|
+
self.prepare_turn = turn_id
|
|
200
|
+
record = self._read_rollout(file)
|
|
201
|
+
if (record.get("base") is None or record.get("newHuman") or record.get("rolledBack")
|
|
202
|
+
or record.get("turn") != {"id": turn_id, "status": "inProgress"}):
|
|
203
|
+
raise ValueError("Codex 当前回合或人工输入已变化,或缺少可核验的当前回合输入")
|
|
204
|
+
elif request:
|
|
205
|
+
start = (request.get("contract") or {}).get("codexLogStart")
|
|
206
|
+
if not start:
|
|
207
|
+
raise ValueError("Codex 请求缺少当前确认的记录起点,保持人工确认")
|
|
208
|
+
if self.log_start != start:
|
|
209
|
+
self._resume_rollout(file, start, request["originTurnId"], baseline=confirmation_id(request["baselineMessageId"]))
|
|
210
|
+
self.prepare_turn = None
|
|
211
|
+
record = self._read_rollout(file)
|
|
212
|
+
else:
|
|
213
|
+
record = self._read_rollout(file)
|
|
148
214
|
if not record["humanId"]:
|
|
149
215
|
raise ValueError("Codex 会话没有可核验的人工消息基线")
|
|
150
216
|
self.seen[record["humanId"]] = True
|
|
@@ -152,8 +218,11 @@ class CodexClient:
|
|
|
152
218
|
wake = record["wake"]
|
|
153
219
|
if wake and wake["turnId"] != (record["turn"] or {}).get("id"):
|
|
154
220
|
wake = None
|
|
221
|
+
if record.get("newHuman"):
|
|
222
|
+
humans = [*humans, record["newHuman"]]
|
|
155
223
|
return {"humanId": record["humanId"], "humanEvents": humans, "turn": record["turn"],
|
|
156
|
-
"status": thread.get("status"), "wake": wake, "logObservation": self.session_log.observation
|
|
224
|
+
"status": thread.get("status"), "wake": wake, "logObservation": self.session_log.observation,
|
|
225
|
+
"codexLogStart": self.log_start, "prepareBaseline": record.get("base")}
|
|
157
226
|
|
|
158
227
|
def read_rollout(self, filename):
|
|
159
228
|
"""按文件身份增量读取原生 JSONL,保留未完成行。
|
|
@@ -161,6 +230,9 @@ class CodexClient:
|
|
|
161
230
|
@param filename: thread/read 返回的准确路径。
|
|
162
231
|
@return: 有界消息来源和最终正文缓存。
|
|
163
232
|
"""
|
|
233
|
+
return self._read_rollout(self._rollout_path(filename))
|
|
234
|
+
|
|
235
|
+
def _rollout_path(self, filename):
|
|
164
236
|
if not isinstance(filename, str) or not Path(filename).name.endswith("-" + self.session_id + ".jsonl"):
|
|
165
237
|
raise ValueError("Codex 未提供精确会话记录路径")
|
|
166
238
|
file = Path(filename)
|
|
@@ -168,13 +240,42 @@ class CodexClient:
|
|
|
168
240
|
file.resolve(strict=True).relative_to(self.home / "sessions")
|
|
169
241
|
except ValueError:
|
|
170
242
|
raise ValueError("Codex 会话记录路径越界")
|
|
243
|
+
return file
|
|
244
|
+
|
|
245
|
+
def _resume_rollout(self, file, start, turn_id, baseline=None, prior=None):
|
|
246
|
+
# 首条身份记录独立于当前回合;只读这一行,保留线程身份约束。
|
|
247
|
+
if start["identity"][0] != str(file):
|
|
248
|
+
raise ValueError("Codex 会话记录路径已变化")
|
|
249
|
+
with file.open("rb") as stream:
|
|
250
|
+
info = os.fstat(stream.fileno())
|
|
251
|
+
if [info.st_dev, info.st_ino] != start["identity"][1:]:
|
|
252
|
+
raise ValueError("Codex 会话记录在打开时已替换")
|
|
253
|
+
line = stream.readline(RECORD_BYTES + 1)
|
|
254
|
+
if not line.endswith(b"\n") or len(line) > RECORD_BYTES:
|
|
255
|
+
raise ValueError("Codex 缺少原生会话身份记录")
|
|
256
|
+
header = json.loads(line)
|
|
257
|
+
if header.get("type") != "session_meta" or (header.get("payload") or {}).get("id") != self.session_id:
|
|
258
|
+
raise ValueError("Codex 会话记录标识不符")
|
|
259
|
+
self.session_log.resume(start, {"verified": True, "humanId": baseline, "base": baseline,
|
|
260
|
+
"anchorTurn": turn_id, "prior": prior or {}, "findingInput": baseline is None,
|
|
261
|
+
"turn": {"id": turn_id, "status": "inProgress"}, "wake": None,
|
|
262
|
+
"displays": OrderedDict()})
|
|
263
|
+
self.log_start = start
|
|
264
|
+
|
|
265
|
+
def _read_rollout(self, file):
|
|
171
266
|
initial = {"verified": False, "humanId": None, "turn": None, "wake": None, "displays": OrderedDict()}
|
|
172
267
|
record, _ = self.session_log.read(file, initial, self._consume_rollout)
|
|
173
268
|
if not record["verified"]:
|
|
174
269
|
raise ValueError("Codex 缺少原生会话身份记录")
|
|
270
|
+
if record.get("rolledBack"):
|
|
271
|
+
raise ValueError("Codex 会话在本次观察期间已回滚,保持人工确认")
|
|
175
272
|
self.rollout = record
|
|
176
273
|
return record
|
|
177
274
|
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _wake_id(item):
|
|
277
|
+
return wake_id({"type": "userMessage", "content": item.get("content"), "clientId": item.get("client_id")})
|
|
278
|
+
|
|
178
279
|
def _consume_rollout(self, record, entry):
|
|
179
280
|
if entry.get("type") == "session_meta":
|
|
180
281
|
if (entry.get("payload") or {}).get("id") != self.session_id:
|
|
@@ -195,16 +296,33 @@ class CodexClient:
|
|
|
195
296
|
if kind == "thread_rolled_back":
|
|
196
297
|
record.update(humanId=None, turn=None, wake=None)
|
|
197
298
|
record["displays"].clear()
|
|
299
|
+
if record.get("anchorTurn"):
|
|
300
|
+
record["rolledBack"] = True
|
|
198
301
|
if kind != "item_completed":
|
|
199
302
|
return
|
|
200
303
|
item = event.get("item") or {}
|
|
201
304
|
if item.get("type") == "UserMessage":
|
|
202
|
-
internal =
|
|
305
|
+
internal = self._wake_id(item)
|
|
203
306
|
if internal:
|
|
204
307
|
record["wake"] = {"requestId": internal, "turnId": event.get("turn_id")}
|
|
308
|
+
if record.get("anchorTurn") and record.get("base") is None:
|
|
309
|
+
prior = record["prior"]
|
|
310
|
+
if event.get("turn_id") != record["anchorTurn"] or prior.get("id") != internal:
|
|
311
|
+
raise ValueError("Codex 当前回合的队列唤醒来源不符")
|
|
312
|
+
record["base"] = record["humanId"] = confirmation_id(prior.get("baselineMessageId"))
|
|
313
|
+
record["inputAnchor"] = (confirmation_id(item.get("id")), internal)
|
|
205
314
|
else:
|
|
206
|
-
|
|
207
|
-
|
|
315
|
+
identifier = confirmation_id(item.get("id"))
|
|
316
|
+
if record.get("anchorTurn"):
|
|
317
|
+
if record.get("findingInput"):
|
|
318
|
+
if event.get("turn_id") != record["anchorTurn"]:
|
|
319
|
+
raise ValueError("Codex 当前回合缺少可核验的人工输入")
|
|
320
|
+
record["base"] = identifier
|
|
321
|
+
record["inputAnchor"] = (identifier, None)
|
|
322
|
+
elif record["base"] != identifier:
|
|
323
|
+
record.setdefault("newHuman", identifier)
|
|
324
|
+
record["humanId"] = identifier
|
|
325
|
+
if not record.get("findingInput") and item.get("type") == "AgentMessage" and item.get("phase") == "final_answer":
|
|
208
326
|
parts = item.get("content")
|
|
209
327
|
if not isinstance(parts, list) or any(part.get("type") != "Text" or not isinstance(part.get("text"), str) for part in parts):
|
|
210
328
|
raise ValueError("Codex 最终正文结构不可核验")
|
|
@@ -160,14 +160,22 @@ def prepare(store, client, input_path, seconds=None):
|
|
|
160
160
|
frozen = inspect_confirmation(store, input_path, seconds)
|
|
161
161
|
if not frozen["enabled"]:
|
|
162
162
|
return {"prepared": False, "mode": "manual", "reason": frozen.get("reason")}
|
|
163
|
-
|
|
163
|
+
observe_prepare = getattr(client, "prepare_snapshot", client.snapshot)
|
|
164
|
+
snapshot = observe_prepare()
|
|
164
165
|
if (snapshot.get("turn") or {}).get("status") != "inProgress":
|
|
165
166
|
raise ValueError("正式确认必须由当前活动回合准备")
|
|
166
167
|
lifetime = ({"windowBinding": client.capture_window(snapshot["turn"]["id"])} if store.platform == "codex"
|
|
167
168
|
else {"runId": confirmation_id(snapshot.get("runId"))})
|
|
168
|
-
current =
|
|
169
|
-
|
|
169
|
+
current = observe_prepare()
|
|
170
|
+
human_events = snapshot.get("humanEvents", []) + current.get("humanEvents", [])
|
|
171
|
+
if current["humanId"] != snapshot["humanId"] or any(identifier != snapshot["humanId"] for identifier in human_events):
|
|
170
172
|
raise ValueError("准备期间出现新人工输入")
|
|
173
|
+
log_start = "codexLogStart" if store.platform == "codex" else "claudeLogStart"
|
|
174
|
+
if snapshot.get(log_start):
|
|
175
|
+
if (current.get(log_start) != snapshot[log_start]
|
|
176
|
+
or current["humanId"] != current["prepareBaseline"]):
|
|
177
|
+
raise ValueError("准备期间确认回合或人工输入已变化")
|
|
178
|
+
lifetime[log_start] = current[log_start]
|
|
171
179
|
if snapshot.get("logObservation"):
|
|
172
180
|
SessionLog.verify(snapshot["logObservation"], current.get("logObservation"))
|
|
173
181
|
lifetime["logObservation"] = current["logObservation"]
|
|
@@ -176,7 +184,10 @@ def prepare(store, client, input_path, seconds=None):
|
|
|
176
184
|
"frozenDigest": _frozen_digest(frozen), **lifetime}
|
|
177
185
|
previous = []
|
|
178
186
|
def apply(old):
|
|
179
|
-
|
|
187
|
+
native = (old or {}).get("native") or {}
|
|
188
|
+
if ((old or {}).get("generation", 0) != generation
|
|
189
|
+
or lifetime.get("claudeLogStart") and native.get("turn") != current.get("turn")
|
|
190
|
+
or lifetime.get("codexLogStart") and native.get("turnId") != current["turn"]["id"]):
|
|
180
191
|
raise ValueError("准备期间确认代次已变化")
|
|
181
192
|
if old and old.get("request"):
|
|
182
193
|
previous.append(old["request"])
|
|
@@ -217,7 +228,7 @@ def _validate(store, client, request, stage, snapshot=None):
|
|
|
217
228
|
raise ValueError("确认材料、策略或当前任务已变化")
|
|
218
229
|
if stage == "display" and _normalize_display(render_confirmation(current)) not in _normalize_display(client.assistant_text(request["originTurnId"])):
|
|
219
230
|
raise ValueError("原回合未完整展示冻结材料、时长及默认动作")
|
|
220
|
-
if stage == "claim":
|
|
231
|
+
if stage == "claim" or (stage == "start" and (contract.get("claudeLogStart") or contract.get("codexLogStart"))):
|
|
221
232
|
if store.platform == "codex":
|
|
222
233
|
wake = snapshot.get("wake") or {}
|
|
223
234
|
if wake.get("requestId") != request["id"] or wake.get("turnId") != (snapshot.get("turn") or {}).get("id"):
|
|
@@ -369,7 +380,11 @@ def claim(store, client, request_id):
|
|
|
369
380
|
time.sleep(0.02)
|
|
370
381
|
request = (store.read() or {}).get("request") or {}
|
|
371
382
|
frozen = _validate(store, client, request, "claim", snapshot)
|
|
372
|
-
|
|
383
|
+
latest = client.snapshot()
|
|
384
|
+
_observe(store, request_id, latest)
|
|
385
|
+
claude_turn = (snapshot.get("turn") or {}).get("id") if request["contract"].get("claudeLogStart") else None
|
|
386
|
+
if claude_turn and (latest.get("turn") or {}).get("id") != claude_turn:
|
|
387
|
+
raise ValueError("Claude 领取期间回合已变化")
|
|
373
388
|
result = denied("not_ready")
|
|
374
389
|
def consume(current, state):
|
|
375
390
|
nonlocal result
|
|
@@ -377,12 +392,13 @@ def claim(store, client, request_id):
|
|
|
377
392
|
result = denied(current["state"])
|
|
378
393
|
return
|
|
379
394
|
if (state["generation"] != current["generation"] or state["lastHumanMessageId"] != current["baselineMessageId"]
|
|
395
|
+
or claude_turn and ((state.get("native") or {}).get("turn") or {}).get("id") != claude_turn
|
|
380
396
|
or now_ms() > current["claimDeadline"] or message_hash(current["message"]) != current["messageSha256"]):
|
|
381
397
|
current.update(state="failed", error="claim_validation_failed")
|
|
382
398
|
result = denied("claim_validation_failed")
|
|
383
399
|
return
|
|
384
400
|
receipt = {"id": str(uuid4()), "at": now_ms(), "source": "policy_timeout", "materialHash": frozen["materialHash"]}
|
|
385
|
-
current.update(state="consumed", receipt=receipt)
|
|
401
|
+
current.update(state="consumed", receipt=receipt, wakeTurnId=claude_turn)
|
|
386
402
|
result = {"claimed": True, "requestId": request_id, "source": "policy_timeout", "action": frozen["action"],
|
|
387
403
|
"receipt": receipt, "context": {**frozen["plan"], "body": frozen["body"], "facts": frozen["facts"],
|
|
388
404
|
"materialHash": frozen["materialHash"], "policyHash": frozen["policyHash"]}}
|
|
@@ -427,6 +443,7 @@ def record_result(store, client, request_id, receipt, outcome):
|
|
|
427
443
|
native = state.get("native") or {}
|
|
428
444
|
run_id = request["contract"].get("runId")
|
|
429
445
|
if (state["generation"] != request["generation"] or state["lastHumanMessageId"] != request["baselineMessageId"]
|
|
446
|
+
or request.get("wakeTurnId") and (native.get("turn") or {}).get("id") != request["wakeTurnId"]
|
|
430
447
|
or (run_id and (native.get("runId") != run_id or native.get("ended"))) or request.get("execution")):
|
|
431
448
|
return
|
|
432
449
|
elif (request.get("execution") or {}).get("state") != "started":
|
|
@@ -23,6 +23,66 @@ class SessionLog:
|
|
|
23
23
|
self.offset = 0
|
|
24
24
|
self.anchor = None
|
|
25
25
|
self.result = None
|
|
26
|
+
self._verify_resume = False
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def locate(cls, file, identifier, matches):
|
|
30
|
+
"""在有界文件尾部定位当前回合的完整记录。
|
|
31
|
+
|
|
32
|
+
@param file: 宿主报告的精确会话路径。
|
|
33
|
+
@param identifier: 原生回合 ID。
|
|
34
|
+
@param matches: 核对候选记录及其结构化身份。
|
|
35
|
+
@return: 可跨进程续读的记录边界。
|
|
36
|
+
"""
|
|
37
|
+
info = file.lstat()
|
|
38
|
+
if not stat.S_ISREG(info.st_mode):
|
|
39
|
+
raise ValueError("原生会话记录必须是普通文件")
|
|
40
|
+
identity = [str(file), info.st_dev, info.st_ino]
|
|
41
|
+
start = max(0, info.st_size - 2 * RECORD_BYTES)
|
|
42
|
+
needle = identifier.encode("ascii")
|
|
43
|
+
with file.open("rb") as stream:
|
|
44
|
+
opened = os.fstat(stream.fileno())
|
|
45
|
+
if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino):
|
|
46
|
+
raise ValueError("原生会话记录在打开时已替换")
|
|
47
|
+
stream.seek(start)
|
|
48
|
+
raw = stream.read(info.st_size - start)
|
|
49
|
+
end = file.lstat()
|
|
50
|
+
if (len(raw) != info.st_size - start or (end.st_dev, end.st_ino) != (info.st_dev, info.st_ino)
|
|
51
|
+
or end.st_size < info.st_size or (end.st_size == info.st_size and end.st_mtime_ns != info.st_mtime_ns)):
|
|
52
|
+
raise ValueError("原生会话记录在读取时已变化")
|
|
53
|
+
lines = raw.split(b"\n")
|
|
54
|
+
offset = info.st_size - len(lines.pop())
|
|
55
|
+
# 只解析可能属于当前回合的完整行。窗口左侧可能落在某条旧记录中间。
|
|
56
|
+
for index in range(len(lines) - 1, -1, -1):
|
|
57
|
+
line = lines[index]
|
|
58
|
+
if (index or not start) and len(line) < RECORD_BYTES and needle in line:
|
|
59
|
+
try:
|
|
60
|
+
entry = json.loads(line)
|
|
61
|
+
except (ValueError, UnicodeError):
|
|
62
|
+
entry = None
|
|
63
|
+
if isinstance(entry, dict) and matches(entry):
|
|
64
|
+
anchor = raw[max(0, offset - start - ANCHOR_BYTES):offset - start]
|
|
65
|
+
if len(anchor) != min(ANCHOR_BYTES, offset):
|
|
66
|
+
anchor_hash = cls._anchor(stream, offset).hex()
|
|
67
|
+
else:
|
|
68
|
+
anchor_hash = sha256(anchor).hexdigest()
|
|
69
|
+
return {"identity": identity, "size": info.st_size, "modified": info.st_mtime_ns,
|
|
70
|
+
"offset": offset, "anchor": anchor_hash}
|
|
71
|
+
offset -= len(line) + 1
|
|
72
|
+
raise ValueError("当前回合缺少可核验的完整记录,保持人工确认")
|
|
73
|
+
|
|
74
|
+
def resume(self, observation, initial):
|
|
75
|
+
"""从冻结位置继续观察,并在首读时核对文件身份和边界。
|
|
76
|
+
|
|
77
|
+
@param observation: 已核对的记录边界。
|
|
78
|
+
@param initial: 起点处的初始证据。
|
|
79
|
+
@return: None。
|
|
80
|
+
"""
|
|
81
|
+
self.observation = observation
|
|
82
|
+
self.offset = observation["offset"]
|
|
83
|
+
self.anchor = bytes.fromhex(observation["anchor"])
|
|
84
|
+
self.result = initial
|
|
85
|
+
self._verify_resume = True
|
|
26
86
|
|
|
27
87
|
def read(self, file, initial, consume):
|
|
28
88
|
"""读取普通 JSONL 文件并累计当前会话证据。
|
|
@@ -41,7 +101,7 @@ class SessionLog:
|
|
|
41
101
|
if (identity != previous["identity"] or info.st_size < previous["size"]
|
|
42
102
|
or (info.st_size == previous["size"] and info.st_mtime_ns != previous["modified"])):
|
|
43
103
|
raise ValueError("原生会话记录已替换、截断或重写")
|
|
44
|
-
if info.st_size == previous["size"]:
|
|
104
|
+
if info.st_size == previous["size"] and not self._verify_resume:
|
|
45
105
|
return self.result, previous
|
|
46
106
|
|
|
47
107
|
result = deepcopy(self.result) if previous else initial
|
|
@@ -72,6 +132,7 @@ class SessionLog:
|
|
|
72
132
|
raise ValueError("原生会话记录在读取时已变化")
|
|
73
133
|
|
|
74
134
|
self.offset, self.anchor, self.result = offset, anchor, result
|
|
135
|
+
self._verify_resume = False
|
|
75
136
|
self.observation = {"identity": identity, "size": info.st_size, "modified": info.st_mtime_ns,
|
|
76
137
|
"offset": offset, "anchor": anchor.hex()}
|
|
77
138
|
return result, self.observation
|