flower-trellis 0.6.13-beta.10 → 0.6.13-beta.11

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.
@@ -1,6 +1,6 @@
1
1
  # 原生后台确认
2
2
 
3
- 本文件由 Brief、Check-All、Push 三个 owner 按需读取。仅 Codex / Claude 的已验证 Linux/WSL 原生会话可启用;项目 `confirmation_timeout` 缺省开启。其它平台、禁用、能力或展示无法核验时维持原人工流程,不从沉默推断人工确认。
3
+ 本文件由 Brief、Check-All、Push 三个 owner 按需读取。Codex / Claude 的 Linux/WSL 或原生 Windows 会话须通过宿主能力核验;项目 `confirmation_timeout` 缺省开启。其它平台、禁用、能力或展示无法核验时维持原人工流程,不从沉默推断人工确认。
4
4
 
5
5
  ## 适用边界
6
6
 
@@ -17,7 +17,7 @@
17
17
 
18
18
  ## 准备与完整展示
19
19
 
20
- Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前根会话内置 codex_tui 的本机监听者绑定原前台;需要新输入 Hook 已实际加载。缺少服务、出生身份或可靠退出能力时保持人工。Claude 保持原来的普通 TUI。
20
+ Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前根会话内置 codex_tui 的本机监听者绑定原前台;需要新输入 Hook 已实际加载。Windows 复用当前 Codex 映像的本机代理接入已有控制端点。缺少服务、出生身份或可靠退出能力时保持人工。Claude 保持原来的普通 TUI;Windows 同时核验原生 Hook 的前台进程。
21
21
 
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
 
@@ -29,6 +29,8 @@ 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 快照和策略检查分别使用超时预算,失败时展示实际阶段及原因。等待原回合完成展示与唤醒后等待领取分别过期;两者与用户设定的倒计时独立。
33
+
32
34
  ## 到期领取与原流程续接
33
35
 
34
36
  原生提醒仅唤醒:先执行 `python3 -X utf8 .trellis/scripts/flower_confirmation.py claim --platform <平台> --request <UUID>`。必须实际取得 `claimed=true`、`source=policy_timeout`、预期 action 和当前冻结 context,才可续接。false、错误、材料或会话漂移时结束旧提醒,不执行旧动作、不重复领取、不假称用户已确认。
@@ -4,13 +4,17 @@
4
4
  from __future__ import annotations
5
5
 
6
6
  import argparse
7
+ from contextvars import ContextVar
7
8
  import hashlib
8
9
  import json
9
10
  import os
11
+ import queue
10
12
  import re
11
13
  import stat
12
14
  import subprocess
13
15
  import sys
16
+ import threading
17
+ import time
14
18
  from pathlib import Path
15
19
 
16
20
  from common.config import parse_simple_yaml
@@ -18,7 +22,12 @@ from common.active_task import resolve_active_task
18
22
 
19
23
 
20
24
  VERSION = 1
21
- MAX_BYTES = 512 * 1024
25
+ INPUT_BYTES = 1024 * 1024
26
+ DOCUMENT_BYTES = 512 * 1024
27
+ HASH_CHUNK = 64 * 1024
28
+ GIT_TIMEOUT = 10
29
+ SNAPSHOT_TIMEOUT = 30
30
+ _SNAPSHOT_DEADLINE = ContextVar("snapshot_deadline", default=None)
22
31
  MAX_SECONDS = 86400
23
32
  DEFAULTS = {
24
33
  "enabled": True,
@@ -49,25 +58,60 @@ def _inside(root, relative):
49
58
  return current
50
59
 
51
60
 
52
- def _bytes(file, optional=False):
61
+ def _bytes(file, optional=False, limit=DOCUMENT_BYTES):
53
62
  try:
54
63
  info = file.lstat()
55
64
  except FileNotFoundError:
56
65
  if optional:
57
66
  return None
58
67
  raise ValueError("确认材料不存在:" + file.name)
59
- if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_BYTES:
60
- raise ValueError("确认材料必须是有界普通文件")
68
+ if not stat.S_ISREG(info.st_mode):
69
+ raise ValueError("确认材料必须是普通文件:" + file.name)
70
+ if info.st_size > limit:
71
+ raise ValueError(f"结构化确认材料超过 {limit // 1024} KiB:{file.name}")
61
72
  with file.open("rb") as stream:
62
- value = stream.read(MAX_BYTES + 1)
63
- if len(value) > MAX_BYTES:
64
- raise ValueError("确认材料超出大小限制")
73
+ opened = os.fstat(stream.fileno())
74
+ if not _same_file_state(info, opened):
75
+ raise ValueError("确认材料在打开时已变化:" + file.name)
76
+ value = stream.read(limit + 1)
77
+ if (not _same_file_state(opened, os.fstat(stream.fileno()), same_handle=True)
78
+ or not _same_file_state(info, file.lstat())):
79
+ raise ValueError("确认材料在读取期间已变化:" + file.name)
80
+ if len(value) > limit:
81
+ raise ValueError(f"结构化确认材料超过 {limit // 1024} KiB:{file.name}")
65
82
  return value
66
83
 
67
84
 
68
- def _fingerprint(file, optional=False):
69
- data = _bytes(file, optional)
70
- return hashlib.sha256(data).hexdigest() if data is not None else None
85
+ def _fingerprint(file, optional=False, info=None):
86
+ if info is None:
87
+ try:
88
+ info = file.lstat()
89
+ except FileNotFoundError:
90
+ if optional:
91
+ return None
92
+ raise
93
+ if not stat.S_ISREG(info.st_mode):
94
+ raise ValueError("指纹材料必须是普通文件:" + str(file))
95
+ digest = hashlib.sha256()
96
+ with file.open("rb") as stream:
97
+ opened = os.fstat(stream.fileno())
98
+ if not _same_file_state(info, opened):
99
+ raise ValueError("指纹材料在打开时已变化:" + str(file))
100
+ for chunk in iter(lambda: stream.read(HASH_CHUNK), b""):
101
+ _snapshot_remaining(str(file))
102
+ digest.update(chunk)
103
+ if (not _same_file_state(opened, os.fstat(stream.fileno()), same_handle=True)
104
+ or not _same_file_state(info, file.lstat())):
105
+ raise ValueError("指纹材料在读取期间已变化:" + str(file))
106
+ return digest.hexdigest()
107
+
108
+
109
+ def _same_file_state(first, second, *, same_handle=False):
110
+ fields = ("st_dev", "st_ino", "st_mode", "st_size", "st_mtime_ns")
111
+ # Windows Python 3.12 的路径和句柄查询可能为同一文件返回不同的 ctime。
112
+ if sys.platform != "win32" or same_handle:
113
+ fields += ("st_ctime_ns",)
114
+ return all(getattr(first, field) == getattr(second, field) for field in fields)
71
115
 
72
116
 
73
117
  def _boolean(value, label):
@@ -132,17 +176,64 @@ def _policy(root):
132
176
 
133
177
 
134
178
  def _git(root, *args, optional=False):
135
- process = subprocess.run(["git", "-C", str(root), *args], stdout=subprocess.PIPE,
136
- stderr=subprocess.PIPE, timeout=10)
179
+ command = ["git", "--no-optional-locks", "-C", str(root), *args]
180
+ label = str(root) + ":git " + " ".join(args)
181
+ try:
182
+ process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
183
+ timeout=_snapshot_remaining(label, GIT_TIMEOUT))
184
+ except subprocess.TimeoutExpired as error:
185
+ raise ValueError("Git 只读快照命令超时:" + label) from error
137
186
  if process.returncode:
138
187
  if optional:
139
188
  return None
140
- raise ValueError("Git 只读快照失败:" + args[0])
141
- if len(process.stdout) > 4 * 1024 * 1024:
142
- raise ValueError("Git 快照超出大小限制")
189
+ raise ValueError("Git 只读快照命令失败:" + label)
143
190
  return process.stdout
144
191
 
145
192
 
193
+ def _snapshot_remaining(label, limit=None):
194
+ deadline = _SNAPSHOT_DEADLINE.get()
195
+ if deadline is None:
196
+ return limit
197
+ remaining = deadline - time.monotonic()
198
+ if remaining <= 0:
199
+ raise ValueError("Push 快照总耗时超出预算:" + label)
200
+ return remaining if limit is None else min(limit, remaining)
201
+
202
+
203
+ def _git_hash(root, *args):
204
+ command = ["git", "--no-optional-locks", "-C", str(root), *args]
205
+ label = str(root) + ":git " + " ".join(args)
206
+ deadline = time.monotonic() + _snapshot_remaining(label, GIT_TIMEOUT)
207
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
208
+ results = queue.Queue(maxsize=1)
209
+
210
+ def read():
211
+ try:
212
+ # 分块复现旧 JSON 十六进制摘要,避免缓存整份 Git 输出或改变既有指纹。
213
+ digest = hashlib.sha256(b'"')
214
+ with process.stdout as stream:
215
+ for chunk in iter(lambda: stream.read(HASH_CHUNK), b""):
216
+ digest.update(chunk.hex().encode("ascii"))
217
+ digest.update(b'"')
218
+ results.put(digest.hexdigest())
219
+ except OSError as error:
220
+ results.put(error)
221
+
222
+ # Windows 的匿名管道不能用 select;读线程独占 stdout,主线程负责超时回收 Git。
223
+ try:
224
+ threading.Thread(target=read, daemon=True).start()
225
+ digest = results.get(timeout=max(0, deadline - time.monotonic()))
226
+ if process.wait(timeout=max(0, deadline - time.monotonic())) or isinstance(digest, OSError):
227
+ raise ValueError("Git 只读快照命令失败:" + label)
228
+ return digest
229
+ except (queue.Empty, subprocess.TimeoutExpired) as error:
230
+ raise ValueError("Git 只读快照命令超时:" + label) from error
231
+ finally:
232
+ if process.poll() is None:
233
+ process.kill()
234
+ process.wait()
235
+
236
+
146
237
  def _git_file(root, relative):
147
238
  file = root / relative
148
239
  # Git 允许提交软链本身;只读取其链接目标,不跟随软链读取项目外内容。
@@ -161,8 +252,8 @@ def _git_file(root, relative):
161
252
  if Path(actual).resolve() != file.resolve():
162
253
  raise ValueError("计划目录不是精确 Git 子仓")
163
254
  return {"mode": "gitlink", "head": _git(file, "rev-parse", "HEAD").decode().strip(),
164
- "status": _digest(_git(file, "status", "--porcelain=v1", "-z").hex())}
165
- return {"mode": stat.S_IMODE(info.st_mode), "sha256": _fingerprint(file)}
255
+ "status": _git_hash(file, "status", "--porcelain=v1", "-z")}
256
+ return {"mode": stat.S_IMODE(info.st_mode), "sha256": _fingerprint(file, info=info)}
166
257
 
167
258
 
168
259
  def _repositories(project, material):
@@ -206,7 +297,8 @@ def _repositories(project, material):
206
297
  raise ValueError("Git 存在未完成集成状态,保持人工确认")
207
298
  if integration["MERGE_HEAD"]:
208
299
  merge = _git(root, "rev-parse", "--verify", "MERGE_HEAD").decode().strip()
209
- if material["mode"] != "push" or plan.get("mergeHead") != merge or _git(root, "ls-files", "-u"):
300
+ if (material["mode"] != "push" or plan.get("mergeHead") != merge
301
+ or _git_hash(root, "ls-files", "-u") != _digest("")):
210
302
  raise ValueError("Git merge 不符合已展示的就绪计划")
211
303
  if material["mode"] == "push" and upstream is None:
212
304
  if not all(isinstance(plan.get(key), str) and plan[key] for key in ("remote", "remoteBranch")):
@@ -216,11 +308,11 @@ def _repositories(project, material):
216
308
  snapshots.append({
217
309
  "root": str(root), "branch": branch, "head": head.decode().strip() if head else None,
218
310
  "upstream": upstream.decode().strip() if upstream else None,
219
- "remoteHash": _digest(_git(root, "remote", "-v").hex()),
220
- "indexHash": _digest(_git(root, "ls-files", "--stage", "-z").hex()),
221
- "diffHash": _digest(_git(root, "diff", "--binary").hex()),
222
- "stagedHash": _digest(_git(root, "diff", "--cached", "--binary").hex()),
223
- "statusHash": _digest(_git(root, "status", "--porcelain=v1", "-z", "--untracked-files=all").hex()),
311
+ "remoteHash": _git_hash(root, "remote", "-v"),
312
+ "indexHash": _git_hash(root, "ls-files", "--stage", "-z"),
313
+ "diffHash": _git_hash(root, "diff", "--binary"),
314
+ "stagedHash": _git_hash(root, "diff", "--cached", "--binary"),
315
+ "statusHash": _git_hash(root, "status", "--porcelain=v1", "-z", "--untracked-files=all"),
224
316
  "files": {name: _git_file(root, name) for name in files}, "integration": integration,
225
317
  })
226
318
  for key in ("branch", "head", "upstream"):
@@ -243,7 +335,8 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
243
335
  """
244
336
  root = Path(root).resolve(strict=True)
245
337
  input_file = _inside(root, input_path)
246
- material = json.loads(_bytes(input_file).decode("utf-8"))
338
+ input_bytes = _bytes(input_file, limit=INPUT_BYTES)
339
+ material = json.loads(input_bytes.decode("utf-8"))
247
340
  kind = material.get("kind")
248
341
  if kind not in ACTIONS:
249
342
  raise ValueError("未知确认种类")
@@ -253,25 +346,32 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
253
346
  if material.get("task") != task:
254
347
  raise ValueError("确认材料与当前会话任务不符")
255
348
  task_manual_only = False
349
+ task_files = {}
256
350
  if task:
257
- task_metadata = json.loads(_bytes(_inside(root, task + "/task.json")).decode("utf-8"))
351
+ metadata_bytes = _bytes(_inside(root, task + "/task.json"))
352
+ task_metadata = json.loads(metadata_bytes.decode("utf-8"))
258
353
  if not isinstance(task_metadata, dict) or not isinstance(task_metadata.get("meta", {}), dict):
259
354
  raise ValueError("任务元数据无效")
260
355
  task_manual_only = task_metadata.get("meta", {}).get("confirmationTimeoutDisabled") is True
261
- task_files = {}
262
- if task:
263
- for name in ("task.json", "prd.md", "design.md", "implement.md", "brief.md"):
356
+ task_files["task.json"] = hashlib.sha256(metadata_bytes).hexdigest()
357
+ for name in ("prd.md", "design.md", "implement.md", "brief.md"):
358
+ if kind == "brief" and name == "brief.md":
359
+ continue
264
360
  task_files[name] = _fingerprint(_inside(root, task + "/" + name), optional=True)
265
361
  if kind == "brief":
266
362
  if not task:
267
363
  raise ValueError("Brief 确认缺少当前任务")
268
- body = _bytes(_inside(root, task + "/brief.md")).decode("utf-8")
364
+ brief_bytes = _bytes(_inside(root, task + "/brief.md"))
365
+ task_files["brief.md"] = hashlib.sha256(brief_bytes).hexdigest()
366
+ body = brief_bytes.decode("utf-8")
269
367
  else:
270
368
  body = material.get("body")
271
369
  if not isinstance(body, str) or not body.strip():
272
370
  raise ValueError("确认正文不能为空")
273
371
  body = body.replace("\r\n", "\n").replace("\r", "\n").strip()
274
- facts = {"task": task, "taskFiles": task_files, "inputHash": _fingerprint(input_file)}
372
+ if len(body.encode("utf-8")) > DOCUMENT_BYTES:
373
+ raise ValueError("确认正文超过 512 KiB 展示预算")
374
+ facts = {"task": task, "taskFiles": task_files, "inputHash": hashlib.sha256(input_bytes).hexdigest()}
275
375
  count = 0
276
376
  if kind == "check":
277
377
  if not all(isinstance(material.get(key), str) and material[key] for key in ("reportVersion", "dispositionVersion")):
@@ -295,7 +395,11 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
295
395
  facts["pending"] = sorted(pending)
296
396
  count = len(pending)
297
397
  elif kind == "push":
298
- facts["repositories"] = _repositories(root, material)
398
+ token = _SNAPSHOT_DEADLINE.set(time.monotonic() + SNAPSHOT_TIMEOUT)
399
+ try:
400
+ facts["repositories"] = _repositories(root, material)
401
+ finally:
402
+ _SNAPSHOT_DEADLINE.reset(token)
299
403
  policy = _policy(root)
300
404
  config = policy[kind]
301
405
  if kind == "brief":
@@ -1,7 +1,7 @@
1
1
  {
2
- "syncedAt": "2026-11-11T08:21:21.558Z",
2
+ "syncedAt": "2026-11-11T16:46:34.601Z",
3
3
  "syncedFrom": "vendor/skill-garden",
4
- "sourceCommit": "ada1fe170443e2ffc4c0baeb1d74928628c13141",
4
+ "sourceCommit": "d3ea04730a59fa3c84e7eaccc93f95f7399842f7",
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.10",
3
+ "version": "0.6.13-beta.11",
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.10",
76
+ "version": "0.6.13-beta.11",
77
77
  "source": "CHANGELOG.md",
78
- "body": "### 🐛 修复 Bug Fixes\n\n* **update:** 清理历代自动确认遗留配置 ([c6f0c79](https://github.com/SilentFlower/flower-trellis/commit/c6f0c798ffb2cd63a8acbd48accd4b97a7d2c7d9))",
78
+ "body": "### 🐛 修复 Bug Fixes\n\n* **confirmation:** 支持原生 Windows 后台超时确认 ([ef33e72](https://github.com/SilentFlower/flower-trellis/commit/ef33e724b329aea745af069d32c31eae0341d070))\n* **confirmation:** 支持长会话与大型确认计划 ([a4f159d](https://github.com/SilentFlower/flower-trellis/commit/a4f159d58d7cc3ea0cba81e65c771947dcd58db0))",
79
79
  "truncated": false
80
80
  },
81
81
  "optionalDependencies": {
@@ -14,7 +14,7 @@ from pathlib import Path
14
14
  from flower_confirmation_runtime.store import ConfirmationStore, cancel_project, confirmation_id, wake_message
15
15
 
16
16
 
17
- HELP = """项目内原生后台确认(Linux/WSL,Codex / Claude)
17
+ HELP = """项目内原生后台确认(Linux/WSL、Windows,Codex / Claude)
18
18
 
19
19
  python3 -X utf8 .trellis/scripts/flower_confirmation.py prepare --input <项目内 JSON> [--seconds <1..86400>]
20
20
  python3 -X utf8 .trellis/scripts/flower_confirmation.py wait --request <UUID>
@@ -79,7 +79,7 @@ def main(argv=None):
79
79
  _output({"cancelled": cancel_project(project, reason)})
80
80
  return 0
81
81
  if command == "hook":
82
- if sys.platform != "linux":
82
+ if sys.platform not in ("linux", "win32"):
83
83
  _output({})
84
84
  return 0
85
85
  raw = sys.stdin.buffer.read(1024 * 1024 + 1)
@@ -33,7 +33,7 @@ def main():
33
33
  except (ValueError, OSError) as error:
34
34
  sys.stdout.write(json.dumps({"entry": None, "reason": str(error)}, ensure_ascii=True) + "\n")
35
35
  return 1
36
- if sys.platform != "linux":
36
+ if sys.platform not in ("linux", "win32"):
37
37
  return 0
38
38
  try:
39
39
  raw = sys.stdin.buffer.read(1024 * 1024 + 1)
@@ -2,15 +2,15 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import json
6
5
  import re
7
6
  import shlex
8
- import stat
9
7
  import sys
10
8
  from pathlib import Path
11
9
  from uuid import uuid4
12
10
 
11
+ from .session_log import DISPLAY_BYTES, SessionLog
13
12
  from .store import ACTIVE, ConfirmationStore, confirmation_id, now_ms, wake_message
13
+ from .windows_process import hook_frontend, open_identity
14
14
 
15
15
 
16
16
  def _task_notice(text):
@@ -28,9 +28,15 @@ def _wait_command(command, project, session_id, request_id):
28
28
  entry = next(index for index, token in enumerate(tokens)
29
29
  if Path(token).name == "flower_confirmation.py")
30
30
  executable = Path(tokens[0]).name
31
+ if sys.platform == "win32":
32
+ executable = executable.lower()
33
+ if executable.endswith(".exe"):
34
+ executable = executable[:-4]
31
35
  if not re.fullmatch(r"(?:python(?:[0-9]+(?:\.[0-9]+)*)?|py)", executable):
32
36
  return False
33
37
  prefix = tokens[1:entry]
38
+ if sys.platform == "win32" and executable == "py" and prefix and re.fullmatch(r"-3(?:\.[0-9]+)?", prefix[0]):
39
+ prefix = prefix[1:]
34
40
  if prefix not in ([], ["-X", "utf8"], ["-3"], ["-3", "-X", "utf8"]):
35
41
  return False
36
42
  if (project / tokens[entry]).resolve(strict=True) != project / ".trellis/scripts/flower_confirmation.py":
@@ -53,10 +59,11 @@ def _wait_command(command, project, session_id, request_id):
53
59
  return False
54
60
 
55
61
 
56
- def record_event(payload):
62
+ def record_event(payload, *, platform=None):
57
63
  """保存四类原生事件,内部通知在领取时再次核验来源。
58
64
 
59
65
  @param payload: 原始 Claude Hook JSON。
66
+ @param platform: 测试可注入的平台能力条件。
60
67
  @return: 空输出或本请求的原生唤醒上下文。
61
68
  """
62
69
  event = payload.get("hook_event_name")
@@ -70,6 +77,7 @@ def record_event(payload):
70
77
  if not isinstance(transcript, str) or Path(transcript).name != session_id + ".jsonl":
71
78
  raise ValueError("Claude 缺少精确会话记录路径")
72
79
  store = ConfirmationStore(project, session_id, "claude")
80
+ frontend = hook_frontend("claude.exe") if (platform or sys.platform) == "win32" else None
73
81
  reminders = []
74
82
  def apply(old):
75
83
  value = old or {"version": 2, "sessionId": session_id, "generation": 0, "lastHumanMessageId": None, "request": None}
@@ -77,8 +85,29 @@ def record_event(payload):
77
85
  "tasks": {}, "runId": str(uuid4())}
78
86
  if native.get("project") != str(project) or native.get("sessionId") != session_id:
79
87
  raise ValueError("Claude 事件会话或项目不符")
80
- native.update(transcript=transcript, at=now_ms())
81
88
  request = value.get("request")
89
+ if frontend is not None:
90
+ if native.get("frontend") and native["frontend"] != frontend:
91
+ try:
92
+ previous = open_identity(native["frontend"])
93
+ except (ProcessLookupError, ValueError):
94
+ previous = None
95
+ except OSError as error:
96
+ if getattr(error, "winerror", None) != 87:
97
+ raise
98
+ previous = None
99
+ if previous:
100
+ previous.close()
101
+ native["ambiguous"] = True
102
+ value["generation"] += 1
103
+ if request and request["state"] in ACTIVE:
104
+ request.update(state="cancelled", error="frontend_ambiguous")
105
+ return value
106
+ if event == "SessionStart":
107
+ native.update(frontend=frontend, ambiguous=False)
108
+ elif native.get("frontend") != frontend or native.get("ambiguous"):
109
+ raise ValueError("Windows Claude Hook 未绑定唯一的原始前台")
110
+ native.update(transcript=transcript, at=now_ms())
82
111
  if event == "SessionStart":
83
112
  native.update(runId=str(uuid4()), ended=False, tasks={}, humanId=None, turn=None)
84
113
  value["generation"] += 1
@@ -101,7 +130,7 @@ def record_event(payload):
101
130
  elif event == "Stop":
102
131
  prompt_id = confirmation_id(payload.get("prompt_id"))
103
132
  text = payload.get("last_assistant_message")
104
- if not isinstance(text, str) or len(text.encode("utf-8")) > 512 * 1024:
133
+ if not isinstance(text, str) or len(text.encode("utf-8")) > DISPLAY_BYTES:
105
134
  raise ValueError("Claude 最终展示正文不可核验")
106
135
  native["turn"] = {"id": prompt_id, "status": "completed"}
107
136
  native["display"] = {"turnId": prompt_id, "text": text, "at": native["at"]}
@@ -140,11 +169,14 @@ class ClaudeClient:
140
169
  @param platform: 可注入的平台能力条件。
141
170
  @return: None。
142
171
  """
143
- if (platform or sys.platform) != "linux":
144
- raise ValueError("Claude 后台确认目前只验证 Linux/WSL")
172
+ self.platform = platform or sys.platform
173
+ if self.platform not in ("linux", "win32") or (self.platform == "win32" and sys.platform != "win32"):
174
+ raise ValueError("Claude 后台确认需要可核验的 Linux/WSL 或原生 Windows 会话")
145
175
  self.store = ConfirmationStore(project, session_id, "claude")
146
176
  self.project = self.store.project
147
177
  self.session_id = self.store.session_id
178
+ self.session_log = SessionLog()
179
+ self.frontend = None
148
180
 
149
181
  def connect(self):
150
182
  """核对原生 Hook 和活动 runId。
@@ -159,46 +191,60 @@ class ClaudeClient:
159
191
  self.snapshot()
160
192
 
161
193
  def snapshot(self):
162
- """核验有界 transcript 的真实人工和任务通知来源。
194
+ """增量核验 transcript 的真实人工和任务通知来源。
163
195
 
164
196
  @return: 人工基线、当前回合、通知和 runId。
165
197
  """
166
198
  native = (self.store.read() or {}).get("native") or {}
167
199
  if not native or native.get("ended"):
168
200
  raise ValueError("Claude 会话状态不可用")
201
+ if self.platform == "win32":
202
+ identity = native.get("frontend")
203
+ if not identity or native.get("ambiguous"):
204
+ raise ValueError("Windows Claude 缺少唯一原始前台,保持人工确认")
205
+ if self.frontend is None:
206
+ self.frontend = open_identity(identity)
207
+ if self.frontend.exited() or self.frontend.identity != identity:
208
+ raise ValueError("frontend_exited")
169
209
  file = Path(native["transcript"])
170
- info = file.lstat()
171
- if not stat.S_ISREG(info.st_mode) or info.st_size > 16 * 1024 * 1024:
172
- raise ValueError("Claude 会话记录不可核验或超过预算")
173
- with file.open("rb") as stream:
174
- raw = stream.read(16 * 1024 * 1024 + 1)
175
- if len(raw) > 16 * 1024 * 1024:
176
- raise ValueError("Claude 会话记录超过预算")
177
- human_id = None
178
- notification = None
179
- for line in raw.split(b"\n")[:-1]:
180
- if not line.strip():
181
- continue
182
- entry = json.loads(line.decode("utf-8"))
183
- if entry.get("type") != "user" or entry.get("isSidechain") or entry.get("sessionId") != self.session_id:
184
- continue
185
- if (entry.get("origin") or {}).get("kind") == "human" and entry.get("turnOrigin") == "human":
186
- human_id = confirmation_id(entry.get("promptId"))
187
- elif (entry.get("origin") or {}).get("kind") == "task-notification" and entry.get("turnOrigin") == "task_notification":
188
- task_id = _task_notice((entry.get("message") or {}).get("content"))
189
- if task_id and native["tasks"].get(task_id):
190
- notification = {"taskId": task_id, "requestId": native["tasks"][task_id], "promptId": entry.get("promptId")}
191
- elif isinstance((entry.get("message") or {}).get("content"), str) and not entry.get("isCompactSummary"):
192
- raise ValueError("Claude 消息来源字段不可核验,保持人工确认")
210
+ if file.name != self.session_id + ".jsonl":
211
+ raise ValueError("Claude 缺少精确会话记录路径")
212
+ hook_notice = native.get("notification") or {}
213
+ initial = {"humanId": None, "notifications": {}}
214
+ record, observation = self.session_log.read(file, initial, self._consume_transcript)
215
+ human_id = record["humanId"]
216
+ task_id = hook_notice.get("taskId")
217
+ prompt_id = record["notifications"].get(task_id)
218
+ request_id = native.get("tasks", {}).get(task_id)
219
+ notification = ({"taskId": task_id, "requestId": request_id, "promptId": prompt_id}
220
+ if prompt_id and request_id else None)
193
221
  if not human_id:
194
222
  raise ValueError("Claude 缺少真实人工输入基线;关闭记录的会话保持人工确认")
195
- hook_notice = native.get("notification") or {}
196
223
  pending = (hook_notice.get("promptId") == (native.get("turn") or {}).get("id")
197
224
  and hook_notice.get("requestId") == native.get("tasks", {}).get(hook_notice.get("taskId"))
198
225
  and bool(hook_notice.get("requestId"))
199
226
  and (notification or {}).get("promptId") != hook_notice.get("promptId"))
200
227
  return {"humanId": human_id, "turn": native.get("turn"), "notification": notification,
201
- "notificationPending": pending, "runId": native.get("runId")}
228
+ "notificationPending": pending, "runId": native.get("runId"), "logObservation": observation}
229
+
230
+ def _consume_transcript(self, record, entry):
231
+ if entry.get("type") != "user" or entry.get("isSidechain") or entry.get("sessionId") != self.session_id:
232
+ return
233
+ kind = (entry.get("origin") or {}).get("kind")
234
+ # Windows 原生记录可能只写结构化 origin;出现 turnOrigin 时仍要求两者一致。
235
+ only_origin = self.platform == "win32" and "turnOrigin" not in entry
236
+ if kind == "human" and (only_origin or entry.get("turnOrigin") == "human"):
237
+ record["humanId"] = confirmation_id(entry.get("promptId"))
238
+ elif kind == "task-notification" and (only_origin or entry.get("turnOrigin") == "task_notification"):
239
+ task_id = _task_notice((entry.get("message") or {}).get("content"))
240
+ if task_id:
241
+ notices = record["notifications"]
242
+ notices.pop(task_id, None)
243
+ notices[task_id] = entry.get("promptId")
244
+ if len(notices) > 8:
245
+ del notices[next(iter(notices))]
246
+ elif isinstance((entry.get("message") or {}).get("content"), str) and not entry.get("isCompactSummary"):
247
+ raise ValueError("Claude 消息来源字段不可核验,保持人工确认")
202
248
 
203
249
  def assistant_text(self, turn_id):
204
250
  """读取 Stop 绑定的原始展示。
@@ -235,4 +281,6 @@ class ClaudeClient:
235
281
 
236
282
  @return: None。
237
283
  """
238
- return None
284
+ if self.frontend:
285
+ self.frontend.close()
286
+ self.frontend = None