flower-trellis 0.6.13-beta.13 → 0.6.13-beta.15

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.
@@ -29,11 +29,27 @@ Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前
29
29
  6. 两端运行同一个 `python3 -X utf8 .trellis/scripts/flower_confirmation.py wait --platform <平台> --session <prepare.sessionId> --request <UUID>`。Claude 用 Bash `run_in_background:true`。Codex 用原生 `exec_command` 短 `yield_time_ms`(例如 1000)启动,取得持续运行的 terminal session 后结束当前回合;不等待命令完成、不轮询、不启动子代理、不用 clock.sleep。后台 worker 到期会经原生同会话队列唤醒。
30
30
  7. 最终回复完整展示 prepare 返回的 `display`;它包含标准正文和本次时长/默认动作。可在前后补必要说明,但不能省略、改写 display。后台会核验原回合最终正文,展示完成才开始计时;工具启动和生成时间不扣减等待时间。
31
31
 
32
- Git 整仓快照、仅用于哈希的文件以及两端会话记录不按总字节数拒绝。需要解析或展示的单条记录、材料和状态各有读取预算。Git 命令、Push 快照和策略检查分别使用超时预算,失败时展示实际阶段及原因。等待原回合完成展示与唤醒后等待领取分别过期;两者与用户设定的倒计时独立。
32
+ Git 整仓快照、仅用于哈希的文件以及两端会话记录不按总字节数拒绝。需要解析或展示的单条记录、材料和状态各有读取预算。Git 命令、Push 快照和策略检查分别使用超时预算,失败时展示实际阶段及原因。展示与领取不另设固定过期时间,许可时效由人工新输入、材料变化、原窗口和运行状态决定。用户设定的倒计时仍在完整展示后开始。
33
+
34
+ 会话记录只提取本次必要的输入、原生通知和最终正文。新增字段、未知附加事件、技能说明和内容分块不单独触发人工确认。通知文案和重复来源字段不充当执行门槛;以明确的原生身份及当前请求关系核验,必要证据缺失时在实际使用处处理。
33
35
 
34
36
  ## 到期领取与原流程续接
35
37
 
36
- 原生提醒仅唤醒:先执行 `python3 -X utf8 .trellis/scripts/flower_confirmation.py claim --platform <平台> --request <UUID>`。必须实际取得 `claimed=true`、`source=policy_timeout`、预期 action 和当前冻结 context,才可续接。false、错误、材料或会话漂移时结束旧提醒,不执行旧动作、不重复领取、不假称用户已确认。
38
+ 原生提醒仅唤醒:先执行 `python3 -X utf8 .trellis/scripts/flower_confirmation.py claim --platform <平台> --request <UUID>`。必须实际取得 `claimed=true`、`source=policy_timeout`、预期 action 和当前冻结 context,才可续接。false、错误、材料或会话漂移时停止旧动作,不重复领取旧请求、不假称用户已确认;在同一回合进入下述恢复分支。
39
+
40
+ ### 失效提醒的自动恢复
41
+
42
+ 领取失败表示本次旧许可无效,不是当前工作流的终止条件。旧版提醒中的“结束本回合”按本节恢复规则处理。先读取当前用户消息及已有工作流上下文,再执行一次 `python3 -X utf8 .trellis/scripts/flower_confirmation.py status --platform <平台>`。只查询当前项目和当前原生会话,不搜索其它会话的许可,也不改用 status 返回的新请求 ID 领取旧通知。
43
+
44
+ - 当前有 `prepared`、`waiting`、`dispatching` 或 `queued` 请求:保留当前请求及其后台等待,不重新准备、不重置计时、不重复启动 worker。迟到提醒到此处理完毕;继续当前用户消息中已授权的工作。当前请求由其自己的原生提醒领取。
45
+ - 当前为 `consumed`:读取 `receipt` 和 `execution`,由原 owner 核对实际进度。已 `started` 的动作先据实恢复和记账,已完成的动作进入下一步;禁止重新执行旧默认动作。缺少 started 记录时也不能借本次旧通知补领或补启动。
46
+ - 当前为 `absent`、`cancelled` 或 `failed`:从当前任务、最新报告或精确 Git 计划恢复原 owner。当前工作仍需要确认且范围已明确时,重建最新材料,自动执行原 prepare/wait/display 并重新计时。新请求必须完整展示并独立取得 claim 与 started;不沿用旧倒计时、旧回执或旧材料。没有待续工作时仅忽略旧提醒。
47
+ - 当前为 `delivery_unknown`:先由原 owner 核对队列及实际执行结果,再按实际进度恢复。投递结果未知本身不授权重发或重执行业务。
48
+ - 用户已明确暂停、取消或改变方向时,优先执行该指令。新的范围或产品取舍、风险接受、Spec 歧义、宿主权限及能力缺失仍按入口决策处理;只有这些实际条件才回到相应人工流程。单纯 `not_current` 或旧许可失效不要求用户再手动确认。
49
+
50
+ 一次提醒最多自动重新准备一次。准备或等待实际失败时报告具体原因并沿原人工分支交接,不在本回合循环领取、轮询或反复重建计时器。
51
+
52
+ ### 有效领取后的原流程续接
37
53
 
38
54
  领取后、首个业务动作前,执行 `python3 -X utf8 .trellis/scripts/flower_confirmation.py result --platform <平台> --request <UUID> --receipt <回执 UUID> --state started`。只有 `recorded=true` 才进入对应 owner;重复 started 不能再次执行。Brief 继续原 `task.py start` 与 route;Check 继续原“修复全部”及重检;Push 继续原精确范围和逐仓预检、提交、推送、进度/Close 及失败恢复。不得把 receipt 当成新产品决策、原生审批或任意 shell 的授权。
39
55
 
@@ -1,7 +1,7 @@
1
1
  {
2
- "syncedAt": "2026-11-13T09:09:34.584Z",
2
+ "syncedAt": "2026-11-16T07:48:52.097Z",
3
3
  "syncedFrom": "vendor/skill-garden",
4
- "sourceCommit": "db2d70b197010028391bfd00271709e594709c2a",
4
+ "sourceCommit": "d12d725d69473f990ffc6854ad0d08958ea32c46",
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.13",
3
+ "version": "0.6.13-beta.15",
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.13",
76
+ "version": "0.6.13-beta.15",
77
77
  "source": "CHANGELOG.md",
78
- "body": "### 🐛 修复 Bug Fixes\n\n* **confirmation:** 支持未绑定任务的 Brief 确认 ([d6a2cd1](https://github.com/SilentFlower/flower-trellis/commit/d6a2cd19ae662af92466e59cf05fbebf51fd1fb1))",
78
+ "body": "### 🐛 修复 Bug Fixes\n\n* **confirmation:** 分离回合来源并移除多余确认拦截 ([3702d40](https://github.com/SilentFlower/flower-trellis/commit/3702d40b09c2c190a0d421064fca57ae4c81f849))\n* **confirmation:** 支持未绑定任务的 Brief 确认 ([1203748](https://github.com/SilentFlower/flower-trellis/commit/1203748888a536f99f4608797eeda831fdf98557))",
79
79
  "truncated": false
80
80
  },
81
81
  "optionalDependencies": {
@@ -9,15 +9,16 @@ from pathlib import Path
9
9
  from uuid import uuid4
10
10
 
11
11
  from .session_log import DISPLAY_BYTES, SessionLog
12
- from .store import ACTIVE, ConfirmationStore, confirmation_id, now_ms, wake_message
12
+ from .store import ACTIVE, ConfirmationStore, confirmation_id, native_id, now_ms, text_content, validate_turn_origin, wake_message
13
13
  from .windows_process import hook_frontend, open_identity
14
14
 
15
15
 
16
16
  def _task_notice(text):
17
- if not isinstance(text, str) or not text.startswith("<task-notification>\n") or not text.endswith("\n</task-notification>"):
17
+ matches = {value.strip() for value in re.findall(r"<task-id>\s*([^<>]+?)\s*</task-id>", text_content(text))}
18
+ if len(matches) != 1:
18
19
  return None
19
- matches = re.findall(r"<task-id>([A-Za-z0-9_-]{1,100})</task-id>", text)
20
- return matches[0] if len(matches) == 1 else None
20
+ identifier = matches.pop()
21
+ return identifier or None
21
22
 
22
23
 
23
24
  def _wait_command(command, project, session_id, request_id):
@@ -74,7 +75,7 @@ def record_event(payload, *, platform=None):
74
75
  return {}
75
76
  session_id = confirmation_id(payload["session_id"])
76
77
  transcript = payload.get("transcript_path")
77
- if not isinstance(transcript, str) or Path(transcript).name != session_id + ".jsonl":
78
+ if not isinstance(transcript, str) or not transcript:
78
79
  raise ValueError("Claude 缺少精确会话记录路径")
79
80
  store = ConfirmationStore(project, session_id, "claude")
80
81
  frontend = hook_frontend("claude.exe") if (platform or sys.platform) == "win32" else None
@@ -99,6 +100,7 @@ def record_event(payload, *, platform=None):
99
100
  if previous:
100
101
  previous.close()
101
102
  native["ambiguous"] = True
103
+ value.pop("turnOrigin", None)
102
104
  value["generation"] += 1
103
105
  if request and request["state"] in ACTIVE:
104
106
  request.update(state="cancelled", error="frontend_ambiguous")
@@ -109,12 +111,15 @@ def record_event(payload, *, platform=None):
109
111
  raise ValueError("Windows Claude Hook 未绑定唯一的原始前台")
110
112
  native.update(transcript=transcript, at=now_ms())
111
113
  if event == "SessionStart":
114
+ value.pop("turnOrigin", None)
112
115
  native.update(runId=str(uuid4()), ended=False, tasks={}, humanId=None, turn=None)
113
116
  value["generation"] += 1
114
117
  if request and request["state"] in ACTIVE:
115
118
  request.update(state="cancelled", error="session_restarted")
116
119
  elif event == "UserPromptSubmit":
117
- prompt_id = confirmation_id(payload.get("prompt_id"))
120
+ prompt_id = native_id(payload.get("prompt_id"))
121
+ if (value.get("turnOrigin") or {}).get("turnId") != prompt_id:
122
+ value.pop("turnOrigin", None)
118
123
  task_id = _task_notice(payload.get("prompt"))
119
124
  owned = native.get("tasks", {}).get(task_id)
120
125
  native.update(turn={"id": prompt_id, "status": "inProgress"}, ended=False)
@@ -122,13 +127,14 @@ def record_event(payload, *, platform=None):
122
127
  native["notification"] = {"taskId": task_id, "requestId": owned, "promptId": prompt_id}
123
128
  reminders.append(wake_message(owned, "claude"))
124
129
  elif native.get("humanId") != prompt_id:
130
+ value.pop("turnOrigin", None)
125
131
  native["humanId"] = prompt_id
126
132
  value["lastHumanMessageId"] = prompt_id
127
133
  value["generation"] += 1
128
134
  if request and request["state"] in ACTIVE:
129
135
  request.update(state="cancelled", error="user_replied")
130
136
  elif event == "Stop":
131
- prompt_id = confirmation_id(payload.get("prompt_id"))
137
+ prompt_id = native_id(payload.get("prompt_id"))
132
138
  text = payload.get("last_assistant_message")
133
139
  if not isinstance(text, str) or len(text.encode("utf-8")) > DISPLAY_BYTES:
134
140
  raise ValueError("Claude 最终展示正文不可核验")
@@ -139,13 +145,13 @@ def record_event(payload, *, platform=None):
139
145
  or not _wait_command(task.get("command"), project, session_id, request["id"])):
140
146
  continue
141
147
  task_id = task.get("id")
142
- if not isinstance(task_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,100}", task_id):
143
- raise ValueError("Claude 原生任务 ID 无效")
148
+ native_id(task_id)
144
149
  native["tasks"][task_id] = request["id"]
145
150
  request["nativeTaskId"] = task_id
146
151
  for identifier in list(native["tasks"])[:-8]:
147
152
  del native["tasks"][identifier]
148
153
  else:
154
+ value.pop("turnOrigin", None)
149
155
  native["ended"] = True
150
156
  value["generation"] += 1
151
157
  if request and request["state"] in ACTIVE:
@@ -178,6 +184,7 @@ class ClaudeClient:
178
184
  self.session_log = SessionLog()
179
185
  self.log_start = None
180
186
  self.prepare_turn = None
187
+ self.prepare_origin = None
181
188
  self.frontend = None
182
189
 
183
190
  def connect(self):
@@ -219,41 +226,61 @@ class ClaudeClient:
219
226
  if self.frontend.exited() or self.frontend.identity != identity:
220
227
  raise ValueError("frontend_exited")
221
228
  file = Path(native["transcript"])
222
- if file.name != self.session_id + ".jsonl":
223
- raise ValueError("Claude 缺少精确会话记录路径")
224
229
  hook_notice = native.get("notification") or {}
225
230
  if preparing:
226
231
  turn = native.get("turn") or {}
227
- prompt_id = confirmation_id(turn.get("id"))
232
+ prompt_id = native_id(turn.get("id"))
228
233
  if turn.get("status") != "inProgress":
229
234
  raise ValueError("正式确认必须由当前活动回合准备")
230
235
  key = (native["runId"], prompt_id)
236
+ origin = validate_turn_origin(state.get("turnOrigin"), "claude", self.session_id)
231
237
  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:
238
+ if origin and origin["turnId"] == prompt_id:
239
+ if origin["runId"] != native["runId"] or origin.get("frontend") != native.get("frontend"):
240
+ raise ValueError("Claude 当前回合来源属于旧运行或窗口")
241
+ if origin["kind"] == "internal":
242
+ task_id = origin["taskId"]
243
+ expected = {"taskId": task_id, "requestId": origin["wakeRequestId"], "promptId": prompt_id}
244
+ if (any(hook_notice.get(key) != value for key, value in expected.items())
245
+ or native.get("tasks", {}).get(task_id) != origin["wakeRequestId"]):
246
+ raise ValueError("Claude 当前回合的原生通知来源已变化")
247
+ self._resume_log(origin["logStart"], origin["baselineMessageId"])
248
+ self.session_log.read(file, {}, self._consume_transcript)
249
+ SessionLog.verify(origin["logObservation"], self.session_log.observation)
250
+ self.prepare_origin = {key: value for key, value in origin.items() if key != "logObservation"}
251
+ else:
252
+ baseline = None
253
+ internal = None
254
+
255
+ def matches(entry):
256
+ nonlocal baseline, internal
257
+ if entry.get("promptId") != prompt_id:
258
+ return False
259
+ evidence = {"humanId": None, "notifications": {}}
260
+ self._consume_transcript(evidence, entry)
261
+ if evidence["humanId"] == prompt_id:
262
+ baseline = prompt_id
263
+ return True
264
+ task_id = hook_notice.get("taskId")
265
+ previous = state.get("request") or {}
266
+ if (previous.get("state") == "consumed"
267
+ and hook_notice.get("requestId") == previous["id"]
268
+ and native.get("tasks", {}).get(task_id) == previous["id"]
269
+ and task_id == previous.get("queueId")
270
+ and hook_notice.get("promptId") == evidence["notifications"].get(task_id) == prompt_id):
271
+ # 首次核验旧状态后,来源独立保存,后续替换只更新请求。
272
+ baseline = native_id(previous.get("baselineMessageId"))
273
+ internal = previous["id"]
274
+ return True
237
275
  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)
276
+
277
+ start = SessionLog.locate(file, prompt_id, matches)
278
+ self._resume_log(start, baseline)
279
+ self.prepare_origin = {"version": 1, "platform": "claude", "sessionId": self.session_id,
280
+ "turnId": prompt_id, "inputId": prompt_id, "baselineMessageId": baseline,
281
+ "kind": "internal" if internal else "human", "wakeRequestId": internal,
282
+ "taskId": hook_notice.get("taskId") if internal else None,
283
+ "runId": native["runId"], "frontend": native.get("frontend"), "logStart": start}
257
284
  self.prepare_turn = key
258
285
  else:
259
286
  request = state.get("request") or {}
@@ -261,7 +288,7 @@ class ClaudeClient:
261
288
  if not start:
262
289
  raise ValueError("Claude 请求缺少当前确认的记录起点,保持人工确认")
263
290
  if self.log_start != start:
264
- self._resume_log(start, confirmation_id(request.get("baselineMessageId")))
291
+ self._resume_log(start, native_id(request.get("baselineMessageId")))
265
292
  self.prepare_turn = None
266
293
  initial = {"humanId": None, "notifications": {}}
267
294
  record, observation = self.session_log.read(file, initial, self._consume_transcript)
@@ -279,7 +306,8 @@ class ClaudeClient:
279
306
  and (notification or {}).get("promptId") != hook_notice.get("promptId"))
280
307
  return {"humanId": human_id, "turn": native.get("turn"), "notification": notification,
281
308
  "notificationPending": pending, "runId": native.get("runId"), "logObservation": observation,
282
- "claudeLogStart": self.log_start, "prepareBaseline": self.prepare_baseline}
309
+ "claudeLogStart": self.log_start, "prepareBaseline": self.prepare_baseline,
310
+ "turnOrigin": self.prepare_origin if preparing else None}
283
311
 
284
312
  def _resume_log(self, start, baseline):
285
313
  self.session_log.resume(start, {"humanId": baseline, "notifications": {}})
@@ -287,31 +315,29 @@ class ClaudeClient:
287
315
  self.prepare_baseline = baseline
288
316
 
289
317
  def _consume_transcript(self, record, entry):
318
+ if not isinstance(entry, dict):
319
+ return
290
320
  if entry.get("type") != "user" or entry.get("isSidechain") or entry.get("sessionId") != self.session_id:
291
321
  return
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
- # 一致的其它来源与只写日志的通知都不提供人工输入或唤醒证据。
322
+ prompt_id = entry.get("promptId")
323
+ if not isinstance(prompt_id, str) or not prompt_id:
300
324
  return
301
- # Windows 原生记录可能只写结构化 origin;出现 turnOrigin 时仍要求两者一致。
302
- only_origin = self.platform == "win32" and "turnOrigin" not in entry
303
- if kind == "human" and (only_origin or entry.get("turnOrigin") == "human"):
304
- record["humanId"] = confirmation_id(entry.get("promptId"))
305
- elif kind == "task-notification" and (only_origin or entry.get("turnOrigin") == "task_notification"):
306
- task_id = _task_notice((entry.get("message") or {}).get("content"))
325
+ origin = entry.get("origin")
326
+ kind = origin.get("kind") if isinstance(origin, dict) else None
327
+ if not kind:
328
+ kind = entry.get("turnOrigin")
329
+ # 只提取必要的正向证据;新增上下文记录不会让整个自动流程失败。
330
+ if kind == "human":
331
+ record["humanId"] = native_id(prompt_id)
332
+ elif kind in ("task-notification", "task_notification") and entry.get("queueTranscriptOnly") is not True:
333
+ message = entry.get("message")
334
+ task_id = _task_notice(message.get("content") if isinstance(message, dict) else None)
307
335
  if task_id:
308
336
  notices = record["notifications"]
309
337
  notices.pop(task_id, None)
310
338
  notices[task_id] = entry.get("promptId")
311
339
  if len(notices) > 8:
312
340
  del notices[next(iter(notices))]
313
- elif isinstance((entry.get("message") or {}).get("content"), str) and not entry.get("isCompactSummary"):
314
- raise ValueError("Claude 消息来源字段不可核验,保持人工确认")
315
341
 
316
342
  def assistant_text(self, turn_id):
317
343
  """读取 Stop 绑定的原始展示。
@@ -14,7 +14,7 @@ from uuid import uuid4
14
14
 
15
15
  from flower_tui_lifetime import bind_origin, check_binding, check_frontend_coverage, open_binding
16
16
  from .session_log import DISPLAY_BYTES, RECORD_BYTES, SessionLog
17
- from .store import ACTIVE, ConfirmationStore, confirmation_id, now_ms, wake_id, wake_message
17
+ from .store import ACTIVE, ConfirmationStore, confirmation_id, native_id, now_ms, text_content, validate_turn_origin, wake_id, wake_message
18
18
  from .transport import CodexTransport, RpcError
19
19
  from .windows_process import check_listener_coverage, hook_frontend, listener_identity, open_identity
20
20
 
@@ -36,15 +36,19 @@ def record_event(payload):
36
36
  def apply(old):
37
37
  value = old or {"version": 2, "sessionId": session_id, "generation": 0,
38
38
  "lastHumanMessageId": None, "request": None}
39
+ if (value.get("turnOrigin") or {}).get("turnId") != payload.get("turn_id"):
40
+ value.pop("turnOrigin", None)
39
41
  value["native"] = {"version": 2, "project": str(project), "sessionId": session_id,
40
42
  "at": now_ms(), "turnId": payload.get("turn_id")}
41
43
  if frontend is not None:
42
44
  value["native"]["hookProcess"] = frontend
43
45
  request = value.get("request")
44
46
  internal = (payload["hook_event_name"] == "UserPromptSubmit" and request
45
- and request["state"] in ("dispatching", "queued") and payload.get("prompt") == wake_message(request["id"]))
47
+ and request["state"] in ("dispatching", "queued")
48
+ and wake_id({"type": "userMessage", "clientId": request["id"], "content": payload.get("prompt")}) == request["id"])
46
49
  # Hook 缺少 client_id,仅暂缓精确提醒取消;claim 仍核对原生记录来源。
47
50
  if not internal:
51
+ value.pop("turnOrigin", None)
48
52
  value["generation"] += 1
49
53
  value["lastHumanMessageId"] = str(uuid4())
50
54
  if request and request["state"] in ACTIVE:
@@ -96,6 +100,7 @@ class CodexClient:
96
100
  self.session_log = SessionLog()
97
101
  self.log_start = None
98
102
  self.prepare_turn = None
103
+ self.prepare_origin = None
99
104
  self.humans = []
100
105
  self.seen = OrderedDict()
101
106
  self.window_fd = None
@@ -106,8 +111,9 @@ class CodexClient:
106
111
  params = packet.get("params") or {}
107
112
  item = params.get("item") or {}
108
113
  if (params.get("threadId") == self.session_id and packet.get("method") in ("item/started", "item/completed")
109
- and item.get("type") == "userMessage" and not wake_id(item) and item.get("id") not in self.seen):
110
- identifier = confirmation_id(item.get("id"))
114
+ and item.get("type") == "userMessage" and isinstance(item.get("id"), str)
115
+ and item["id"] and not wake_id(item) and item["id"] not in self.seen):
116
+ identifier = native_id(item.get("id"))
111
117
  self.seen[identifier] = True
112
118
  self.humans.append(identifier)
113
119
  while len(self.seen) > 4096:
@@ -166,36 +172,50 @@ class CodexClient:
166
172
  if (native.get("version") != 2 or native.get("project") != str(self.project)
167
173
  or native.get("sessionId") != self.session_id or not native.get("turnId")):
168
174
  raise ValueError("当前会话尚未收到确认输入 Hook,保持人工确认")
169
- turn_id = confirmation_id(native["turnId"])
175
+ turn_id = native_id(native["turnId"])
176
+ origin = validate_turn_origin(state.get("turnOrigin"), "codex", self.session_id)
170
177
  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"])
178
+ if origin and origin["turnId"] == turn_id:
179
+ # 来源与当前请求各自持久化,替换请求后仍从原输入边界核验。
180
+ self.verify_window(origin["windowBinding"])
181
+ self._resume_rollout(file, origin["logStart"], turn_id, baseline=origin["baselineMessageId"])
182
+ self._read_rollout(file)
183
+ SessionLog.verify(origin["logObservation"], self.session_log.observation)
184
+ self.prepare_origin = {key: value for key, value in origin.items()
185
+ if key != "logObservation"}
186
+ else:
187
+ def matches(entry):
188
+ event = entry.get("payload")
189
+ return (entry.get("type") == "event_msg" and isinstance(event, dict)
190
+ and event.get("type") in ("task_started", "turn_started")
191
+ and event.get("turn_id") == turn_id and event.get("thread_id") in (None, self.session_id))
192
+
193
+ start = SessionLog.locate(file, turn_id, matches)
194
+ prior = ({key: request.get(key) for key in ("id", "baselineMessageId")}
195
+ if request.get("state") == "consumed" else {})
196
+ self._resume_rollout(file, start, turn_id, prior=prior)
197
+ source = self._read_rollout(file)
198
+ if source.get("turn") != {"id": turn_id, "status": "inProgress"} or not source.get("inputAnchor"):
199
+ raise ValueError("Codex 缺少可核验的当前回合输入")
200
+ identifier, internal = source["inputAnchor"]
201
+
202
+ def matches_input(entry):
203
+ event = entry.get("payload")
204
+ if (entry.get("type") != "event_msg" or not isinstance(event, dict)
205
+ or event.get("type") != "item_completed" or event.get("turn_id") != turn_id
206
+ or event.get("thread_id") not in (None, self.session_id)):
207
+ return False
208
+ item = event.get("item")
209
+ return (isinstance(item, dict) and item.get("type") == "UserMessage" and item.get("id") == identifier
210
+ and self._wake_id(item) == internal)
211
+
212
+ # 同回合在 prepare 之前的插话是基线;从其完整记录之后观察新的输入。
213
+ self._resume_rollout(file, SessionLog.locate(file, identifier, matches_input), turn_id,
214
+ baseline=source["humanId"])
215
+ self.prepare_origin = {"version": 1, "platform": "codex", "sessionId": self.session_id,
216
+ "turnId": turn_id, "inputId": identifier, "baselineMessageId": source["humanId"],
217
+ "kind": "internal" if internal else "human", "wakeRequestId": internal,
218
+ "logStart": self.log_start}
199
219
  self.prepare_turn = turn_id
200
220
  record = self._read_rollout(file)
201
221
  if (record.get("base") is None or record.get("newHuman") or record.get("rolledBack")
@@ -206,7 +226,7 @@ class CodexClient:
206
226
  if not start:
207
227
  raise ValueError("Codex 请求缺少当前确认的记录起点,保持人工确认")
208
228
  if self.log_start != start:
209
- self._resume_rollout(file, start, request["originTurnId"], baseline=confirmation_id(request["baselineMessageId"]))
229
+ self._resume_rollout(file, start, request["originTurnId"], baseline=native_id(request["baselineMessageId"]))
210
230
  self.prepare_turn = None
211
231
  record = self._read_rollout(file)
212
232
  else:
@@ -222,7 +242,8 @@ class CodexClient:
222
242
  humans = [*humans, record["newHuman"]]
223
243
  return {"humanId": record["humanId"], "humanEvents": humans, "turn": record["turn"],
224
244
  "status": thread.get("status"), "wake": wake, "logObservation": self.session_log.observation,
225
- "codexLogStart": self.log_start, "prepareBaseline": record.get("base")}
245
+ "codexLogStart": self.log_start, "prepareBaseline": record.get("base"),
246
+ "turnOrigin": self.prepare_origin if preparing else None}
226
247
 
227
248
  def read_rollout(self, filename):
228
249
  """按文件身份增量读取原生 JSONL,保留未完成行。
@@ -233,7 +254,7 @@ class CodexClient:
233
254
  return self._read_rollout(self._rollout_path(filename))
234
255
 
235
256
  def _rollout_path(self, filename):
236
- if not isinstance(filename, str) or not Path(filename).name.endswith("-" + self.session_id + ".jsonl"):
257
+ if not isinstance(filename, str) or not filename:
237
258
  raise ValueError("Codex 未提供精确会话记录路径")
238
259
  file = Path(filename)
239
260
  try:
@@ -277,15 +298,19 @@ class CodexClient:
277
298
  return wake_id({"type": "userMessage", "content": item.get("content"), "clientId": item.get("client_id")})
278
299
 
279
300
  def _consume_rollout(self, record, entry):
301
+ if not isinstance(entry, dict):
302
+ return
280
303
  if entry.get("type") == "session_meta":
281
- if (entry.get("payload") or {}).get("id") != self.session_id:
304
+ if not record["verified"] and (entry.get("payload") or {}).get("id") != self.session_id:
282
305
  raise ValueError("Codex 会话记录标识不符")
283
306
  record["verified"] = True
284
307
  if entry.get("type") != "event_msg":
285
308
  return
286
309
  event = entry.get("payload") or {}
310
+ if not isinstance(event, dict):
311
+ return
287
312
  if event.get("thread_id") and event["thread_id"] != self.session_id:
288
- raise ValueError("Codex 记录中混入其他会话事件")
313
+ return
289
314
  kind = event.get("type")
290
315
  if kind in ("task_started", "turn_started"):
291
316
  record["turn"] = {"id": event.get("turn_id"), "status": "inProgress"}
@@ -301,7 +326,11 @@ class CodexClient:
301
326
  if kind != "item_completed":
302
327
  return
303
328
  item = event.get("item") or {}
329
+ if not isinstance(item, dict):
330
+ return
304
331
  if item.get("type") == "UserMessage":
332
+ if not isinstance(item.get("id"), str) or not item["id"]:
333
+ return
305
334
  internal = self._wake_id(item)
306
335
  if internal:
307
336
  record["wake"] = {"requestId": internal, "turnId": event.get("turn_id")}
@@ -309,10 +338,10 @@ class CodexClient:
309
338
  prior = record["prior"]
310
339
  if event.get("turn_id") != record["anchorTurn"] or prior.get("id") != internal:
311
340
  raise ValueError("Codex 当前回合的队列唤醒来源不符")
312
- record["base"] = record["humanId"] = confirmation_id(prior.get("baselineMessageId"))
313
- record["inputAnchor"] = (confirmation_id(item.get("id")), internal)
341
+ record["base"] = record["humanId"] = native_id(prior.get("baselineMessageId"))
342
+ record["inputAnchor"] = (native_id(item.get("id")), internal)
314
343
  else:
315
- identifier = confirmation_id(item.get("id"))
344
+ identifier = native_id(item.get("id"))
316
345
  if record.get("anchorTurn"):
317
346
  if record.get("findingInput"):
318
347
  if event.get("turn_id") != record["anchorTurn"]:
@@ -323,13 +352,11 @@ class CodexClient:
323
352
  record.setdefault("newHuman", identifier)
324
353
  record["humanId"] = identifier
325
354
  if not record.get("findingInput") and item.get("type") == "AgentMessage" and item.get("phase") == "final_answer":
326
- parts = item.get("content")
327
- if not isinstance(parts, list) or any(part.get("type") != "Text" or not isinstance(part.get("text"), str) for part in parts):
328
- raise ValueError("Codex 最终正文结构不可核验")
355
+ text = text_content(item.get("content"))
329
356
  turn_id = event.get("turn_id")
330
357
  previous = record["displays"].get(turn_id, "")
331
358
  if previous is not None:
332
- text = previous + "".join(part["text"] for part in parts)
359
+ text = previous + text
333
360
  # 超大历史正文不应阻塞后续回合;该回合自身仍无法通过完整展示核验。
334
361
  record["displays"][turn_id] = text if len(text.encode("utf-8")) <= DISPLAY_BYTES else None
335
362
  while len(record["displays"]) > 8:
@@ -10,7 +10,7 @@ import time
10
10
  from uuid import uuid4
11
11
 
12
12
  from .session_log import SessionLog
13
- from .store import ACTIVE, CLAIM_BUDGET, DISPLAY_BUDGET, confirmation_id, message_hash, now_ms, read_json
13
+ from .store import ACTIVE, confirmation_id, message_hash, now_ms, read_json, validate_turn_origin
14
14
 
15
15
 
16
16
  ACTION_NAMES = {"implement": "按当前完整 Brief 开工", "repair_all_and_recheck": "修复当前全部待处置问题并重检",
@@ -108,6 +108,7 @@ def _observe(store, request_id, snapshot, *, observed=None):
108
108
  continue
109
109
  state["lastHumanMessageId"] = identifier
110
110
  state["generation"] += 1
111
+ state.pop("turnOrigin", None)
111
112
  if request["state"] in ACTIVE:
112
113
  request.update(state="cancelled", error="user_replied")
113
114
  return store.change(request_id, apply)
@@ -179,6 +180,18 @@ def prepare(store, client, input_path, seconds=None):
179
180
  if snapshot.get("logObservation"):
180
181
  SessionLog.verify(snapshot["logObservation"], current.get("logObservation"))
181
182
  lifetime["logObservation"] = current["logObservation"]
183
+ origin = current.get("turnOrigin")
184
+ if origin != snapshot.get("turnOrigin"):
185
+ raise ValueError("准备期间当前回合来源已变化")
186
+ if origin:
187
+ if store.platform == "codex" and origin.get("windowBinding") is not None and origin["windowBinding"] != lifetime["windowBinding"]:
188
+ raise ValueError("准备期间当前回合的原窗口身份已变化")
189
+ origin = {**origin, "logObservation": current["logObservation"],
190
+ **({"windowBinding": lifetime["windowBinding"]} if store.platform == "codex" else {})}
191
+ validate_turn_origin(origin, store.platform, store.session_id)
192
+ if (origin["turnId"] != current["turn"]["id"] or origin["baselineMessageId"] != current["humanId"]
193
+ or origin["logStart"] != lifetime.get(log_start)):
194
+ raise ValueError("当前回合来源与准备基线不符")
182
195
  # 状态只保存整个计划的摘要;领取时用同一材料重算并返回原有完整上下文。
183
196
  contract = {"version": CONTRACT_VERSION, "platform": store.platform, "input": input_path, "secondsOverride": seconds,
184
197
  "frozenDigest": _frozen_digest(frozen), **lifetime}
@@ -194,6 +207,7 @@ def prepare(store, client, input_path, seconds=None):
194
207
  next_generation = generation + 1
195
208
  return {"version": 2, "sessionId": store.session_id, "generation": next_generation,
196
209
  "lastHumanMessageId": snapshot["humanId"], **({"native": old["native"]} if old and old.get("native") else {}),
210
+ **({"turnOrigin": origin} if origin else {}),
197
211
  "request": {"id": str(uuid4()), "generation": next_generation, "baselineMessageId": snapshot["humanId"],
198
212
  "seconds": frozen["seconds"], "message": frozen["action"], "messageSha256": message_hash(frozen["action"]),
199
213
  "originTurnId": snapshot["turn"]["id"], "state": "prepared", "createdAt": now_ms(), "deadline": None,
@@ -287,8 +301,6 @@ def wait(store, client, request_id, interrupted=lambda: False, notify=lambda val
287
301
  if time.monotonic() - began > 2 * 86400:
288
302
  raise ValueError("worker_lifetime_exceeded")
289
303
  if request["state"] == "prepared":
290
- if time.monotonic() - began > DISPLAY_BUDGET:
291
- raise ValueError("display_completion_unverified")
292
304
  turn = snapshot.get("turn") or {}
293
305
  if turn.get("id") == request["originTurnId"] and turn.get("status") == "inProgress":
294
306
  time.sleep(0.05)
@@ -324,7 +336,7 @@ def wait(store, client, request_id, interrupted=lambda: False, notify=lambda val
324
336
  def record_queue(current, state):
325
337
  current["queueId"] = queued["id"]
326
338
  if current["state"] == "dispatching":
327
- current.update(state="queued", claimDeadline=now_ms() + CLAIM_BUDGET * 1000)
339
+ current.update(state="queued")
328
340
  value = store.change(request_id, record_queue)
329
341
  current = (value or {}).get("request") or {}
330
342
  if current.get("id") != request_id or current["state"] != "queued":
@@ -333,8 +345,6 @@ def wait(store, client, request_id, interrupted=lambda: False, notify=lambda val
333
345
  notify({"event": "queued", "requestId": request_id, "queueId": queued["id"]})
334
346
  if client.delivery_on_exit:
335
347
  return current
336
- elif request["state"] == "queued" and now_ms() > request["claimDeadline"]:
337
- raise ValueError("claim_expired")
338
348
  time.sleep(0.05)
339
349
  except Exception as error:
340
350
  def fail(current, state):
@@ -393,7 +403,7 @@ def claim(store, client, request_id):
393
403
  return
394
404
  if (state["generation"] != current["generation"] or state["lastHumanMessageId"] != current["baselineMessageId"]
395
405
  or claude_turn and ((state.get("native") or {}).get("turn") or {}).get("id") != claude_turn
396
- or now_ms() > current["claimDeadline"] or message_hash(current["message"]) != current["messageSha256"]):
406
+ or message_hash(current["message"]) != current["messageSha256"]):
397
407
  current.update(state="failed", error="claim_validation_failed")
398
408
  result = denied("claim_validation_failed")
399
409
  return
@@ -30,7 +30,7 @@ class SessionLog:
30
30
  """在有界文件尾部定位当前回合的完整记录。
31
31
 
32
32
  @param file: 宿主报告的精确会话路径。
33
- @param identifier: 原生回合 ID。
33
+ @param identifier: 用于失败诊断的原生标识,准确匹配由 matches 完成。
34
34
  @param matches: 核对候选记录及其结构化身份。
35
35
  @return: 可跨进程续读的记录边界。
36
36
  """
@@ -39,7 +39,6 @@ class SessionLog:
39
39
  raise ValueError("原生会话记录必须是普通文件")
40
40
  identity = [str(file), info.st_dev, info.st_ino]
41
41
  start = max(0, info.st_size - 2 * RECORD_BYTES)
42
- needle = identifier.encode("ascii")
43
42
  with file.open("rb") as stream:
44
43
  opened = os.fstat(stream.fileno())
45
44
  if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino):
@@ -52,10 +51,10 @@ class SessionLog:
52
51
  raise ValueError("原生会话记录在读取时已变化")
53
52
  lines = raw.split(b"\n")
54
53
  offset = info.st_size - len(lines.pop())
55
- # 只解析可能属于当前回合的完整行。窗口左侧可能落在某条旧记录中间。
54
+ # 在有界窗口内按解析后的身份匹配,避免依赖原生 ID 的 JSON 转义形式。
56
55
  for index in range(len(lines) - 1, -1, -1):
57
56
  line = lines[index]
58
- if (index or not start) and len(line) < RECORD_BYTES and needle in line:
57
+ if (index or not start) and len(line) < RECORD_BYTES:
59
58
  try:
60
59
  entry = json.loads(line)
61
60
  except (ValueError, UnicodeError):
@@ -69,7 +68,7 @@ class SessionLog:
69
68
  return {"identity": identity, "size": info.st_size, "modified": info.st_mtime_ns,
70
69
  "offset": offset, "anchor": anchor_hash}
71
70
  offset -= len(line) + 1
72
- raise ValueError("当前回合缺少可核验的完整记录,保持人工确认")
71
+ raise ValueError("当前回合缺少可核验的完整记录,保持人工确认:" + identifier)
73
72
 
74
73
  def resume(self, observation, initial):
75
74
  """从冻结位置继续观察,并在首读时核对文件身份和边界。
@@ -19,8 +19,6 @@ ACTIVE = frozenset(("prepared", "waiting", "dispatching", "queued"))
19
19
  STATES = ACTIVE | {"cancelled", "failed", "delivery_unknown", "consumed"}
20
20
  MAX_BYTES = 1024 * 1024
21
21
  STATE_BYTES = 2 * 1024 * 1024
22
- DISPLAY_BUDGET = 300
23
- CLAIM_BUDGET = 300
24
22
  UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", re.I)
25
23
 
26
24
 
@@ -35,6 +33,17 @@ def confirmation_id(value):
35
33
  return value
36
34
 
37
35
 
36
+ def native_id(value):
37
+ """读取原生不透明标识,资源预算由状态与日志层控制。
38
+
39
+ @param value: 原生回合、消息或任务标识。
40
+ @return: 原始非空字符串。
41
+ """
42
+ if not isinstance(value, str) or not value:
43
+ raise ValueError("原生标识必须为非空字符串")
44
+ return value
45
+
46
+
38
47
  def wake_message(request_id, platform="codex"):
39
48
  """生成只唤醒原工作流的完整内部消息。
40
49
 
@@ -48,23 +57,39 @@ def wake_message(request_id, platform="codex"):
48
57
  return ("[flower-confirmation:v2:" + request_id + "]\n后台确认已到期。"
49
58
  "先按 .trellis/scripts/confirmation.md 定位本项目的 Python 入口,再执行 claim --platform "
50
59
  + platform + " --request " + request_id + "。只有返回 claimed=true 才按返回的 action 和冻结 context 进入原流程;"
51
- "必须继续执行原有范围检查与失败恢复。claimed=false 或失败表示已失效,结束本回合,不重试、不执行旧动作。")
60
+ "必须继续执行原有范围检查与失败恢复。claimed=false 或失败时,停止旧动作,"
61
+ "按协议读取当前 status 并恢复当前流程。已有有效等待予以保留;需要新等待时自动重新准备、完整展示并计时。"
62
+ "不得仅因旧提醒失效要求人工再确认,也不得重试领取旧请求或执行旧动作。")
63
+
64
+
65
+ def text_content(content):
66
+ """提取正文文本,附加内容块不参与文本核验。
67
+
68
+ @param content: 原生字符串或内容块列表。
69
+ @return: 拼接的文本,未知结构为空。
70
+ """
71
+ if isinstance(content, str):
72
+ return content
73
+ if not isinstance(content, list):
74
+ return ""
75
+ return "".join(part if isinstance(part, str) else part.get("text", "") for part in content
76
+ if isinstance(part, str) or isinstance(part, dict) and isinstance(part.get("text"), str))
52
77
 
53
78
 
54
79
  def wake_id(item):
55
- """核对内部正文与 Codex 原生 clientId。
80
+ """按稳定请求标记与原生 clientId 识别通知。
56
81
 
57
82
  @param item: 原生 userMessage。
58
83
  @return: 匹配的请求 UUID,普通消息返回 None。
59
84
  """
60
- content = item.get("content")
61
- if item.get("type") != "userMessage" or not isinstance(content, list) or len(content) != 1:
85
+ if item.get("type") != "userMessage":
62
86
  return None
63
- part = content[0]
64
- text = part.get("text") if isinstance(part, dict) and part.get("type") == "text" else None
65
- match = re.match(r"^\[flower-confirmation:v2:([0-9a-f-]{36})\]", text, re.I) if isinstance(text, str) else None
66
- if match and UUID.fullmatch(match[1]) and item.get("clientId") == match[1] and text == wake_message(match[1]):
67
- return match[1]
87
+ content = text_content(item.get("content"))
88
+ identifiers = set(re.findall(r"\[flower-confirmation:v2:([0-9a-f-]{36})\]", content, re.I))
89
+ if len(identifiers) == 1:
90
+ identifier = identifiers.pop()
91
+ if UUID.fullmatch(identifier) and item.get("clientId") == identifier:
92
+ return identifier
68
93
  return None
69
94
 
70
95
 
@@ -76,6 +101,43 @@ def now_ms():
76
101
  return int(time.time() * 1000)
77
102
 
78
103
 
104
+ def validate_turn_origin(origin, platform, session_id):
105
+ """校验独立来源的范围和有界结构,许可仍由当前请求决定。
106
+
107
+ @param origin: 可选的当前回合来源。
108
+ @param platform: 精确平台。
109
+ @param session_id: 精确原生会话。
110
+ @return: 已校验来源或 None。
111
+ """
112
+ if origin is None:
113
+ return None
114
+ if (not isinstance(origin, dict) or type(origin.get("version")) is not int or origin["version"] != 1
115
+ or origin.get("platform") != platform or origin.get("sessionId") != session_id
116
+ or origin.get("kind") not in ("human", "internal")):
117
+ raise ValueError("当前回合来源版本、平台或会话不符")
118
+ for key in ("turnId", "inputId", "baselineMessageId"):
119
+ native_id(origin.get(key))
120
+ if origin["kind"] == "internal":
121
+ confirmation_id(origin.get("wakeRequestId"))
122
+ elif origin.get("wakeRequestId") is not None:
123
+ raise ValueError("人工回合来源混入内部唤醒标识")
124
+ for key in ("logStart", "logObservation"):
125
+ point = origin.get(key)
126
+ if (not isinstance(point, dict) or not isinstance(point.get("identity"), list) or len(point["identity"]) != 3
127
+ or not isinstance(point["identity"][0], str)
128
+ or any(type(point.get(name)) is not int or point[name] < 0 for name in ("size", "modified", "offset"))
129
+ or point["offset"] > point["size"] or not isinstance(point.get("anchor"), str)
130
+ or not re.fullmatch(r"[0-9a-f]{64}", point["anchor"])):
131
+ raise ValueError("当前回合来源缺少有效日志边界")
132
+ if platform == "claude":
133
+ confirmation_id(origin.get("runId"))
134
+ if origin["kind"] == "internal":
135
+ native_id(origin.get("taskId"))
136
+ elif not isinstance(origin.get("windowBinding"), dict):
137
+ raise ValueError("当前回合来源缺少原始窗口身份")
138
+ return origin
139
+
140
+
79
141
  def message_hash(message):
80
142
  """计算动作正文摘要。
81
143
 
@@ -342,6 +404,8 @@ def cancel_project(project, reason="project_disabled"):
342
404
  store = ConfirmationStore(project, file.stem, platform)
343
405
  def apply(value):
344
406
  nonlocal count
407
+ if value:
408
+ value.pop("turnOrigin", None)
345
409
  if value and value.get("request"):
346
410
  value["generation"] += 1
347
411
  if value["request"]["state"] in ACTIVE: