femo-plugin 1.0.0

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.
Files changed (166) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +627 -0
  3. package/femo2host/__init__.py +4 -0
  4. package/femo2host/femoToolcall/chronica.py +156 -0
  5. package/femo2host/femoToolcall/femo-chat.mjs +69 -0
  6. package/femo2host/femoToolcall/femo_debugger.py +1515 -0
  7. package/femo2host/femo_api.py +437 -0
  8. package/femo2host/femo_gen_api.jsx +77 -0
  9. package/femoBridges/ContextExample.py +555 -0
  10. package/femoBridges/MemoryExample.py +163 -0
  11. package/femoBridges/__init__.py +1 -0
  12. package/femoBridges/getDir/get_dir.py +56 -0
  13. package/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
  14. package/femoBridges/llmBridge.py +247 -0
  15. package/femoBridges/llmProviders.py +308 -0
  16. package/femoCompiler/FEMO_CLIrenderer.py +198 -0
  17. package/femoCompiler/FEMO_config.py +35 -0
  18. package/femoCompiler/FEMO_errors.py +278 -0
  19. package/femoCompiler/FEMO_interpreter.py +163 -0
  20. package/femoCompiler/FEMO_normalizer.py +396 -0
  21. package/femoCompiler/FEMO_parser.py +2468 -0
  22. package/femoCompiler/FEMO_runtime.py +3630 -0
  23. package/femoCompiler/FEMO_scope_resolver.py +209 -0
  24. package/femoCompiler/__init__.py +1 -0
  25. package/femoCompiler/actor_resolver.py +86 -0
  26. package/femoCompiler/block_collector.py +441 -0
  27. package/femoCompiler/db_utils.py +485 -0
  28. package/femoCompiler/femoAsync.py +401 -0
  29. package/femoCompiler/host_manifest.py +68 -0
  30. package/femoCompiler/job_manager.py +767 -0
  31. package/femoCompiler/protocol.py +126 -0
  32. package/femoCompiler/save_dialog.py +402 -0
  33. package/femoCompiler/task_world.py +544 -0
  34. package/femoCompiler/vars/__init__.py +19 -0
  35. package/femoCompiler/vars/checkpoint.py +113 -0
  36. package/femoCompiler/vars/env.py +686 -0
  37. package/femoCompiler/vars/evaluator.py +567 -0
  38. package/femoCompiler/vars/join.py +303 -0
  39. package/femoCompiler/vars/merge.py +157 -0
  40. package/femoCompiler/vars/model.py +245 -0
  41. package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
  42. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
  43. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
  44. package/femoExamples/LuxFiat/luxfiat.femo +38 -0
  45. package/femoExamples/LuxFiat/wait.py +29 -0
  46. package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
  47. package/femoExamples/discussion.femo +70 -0
  48. package/femoExamples/goal-mode.femo +23 -0
  49. package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
  50. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
  51. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
  52. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
  53. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
  54. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
  55. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
  56. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +392 -0
  57. package/femoGen/document_ch.html +2352 -0
  58. package/femoGen/document_en.html +2279 -0
  59. package/femoGen/index.html +19 -0
  60. package/femoGen/intro_ch.html +942 -0
  61. package/femoGen/intro_en.html +932 -0
  62. package/femoGen/package-lock.json +1698 -0
  63. package/femoGen/package.json +19 -0
  64. package/femoGen/public/character_need.ttf +0 -0
  65. package/femoGen/public/favicon.ico +0 -0
  66. package/femoGen/public/femo-logo-slogan.svg +83 -0
  67. package/femoGen/public/femo-logo.svg +55 -0
  68. package/femoGen/public/logo-fullsize.ico +0 -0
  69. package/femoGen/src/FemoWorAuto.jsx +5444 -0
  70. package/femoGen/src/actionModal.jsx +358 -0
  71. package/femoGen/src/bubbleOverlay.jsx +701 -0
  72. package/femoGen/src/canvasNodes.jsx +608 -0
  73. package/femoGen/src/common.jsx +715 -0
  74. package/femoGen/src/debugPanel.jsx +530 -0
  75. package/femoGen/src/faIcons.jsx +84 -0
  76. package/femoGen/src/femoDiagnostics.js +122 -0
  77. package/femoGen/src/femoFileList.jsx +357 -0
  78. package/femoGen/src/femoGenerator.jsx +1198 -0
  79. package/femoGen/src/femoLog.js +107 -0
  80. package/femoGen/src/femoParser.jsx +2255 -0
  81. package/femoGen/src/femoPreview.jsx +297 -0
  82. package/femoGen/src/graphBuilder.jsx +358 -0
  83. package/femoGen/src/libPanel.jsx +519 -0
  84. package/femoGen/src/main.jsx +22 -0
  85. package/femoGen/src/mobileView.jsx +2796 -0
  86. package/femoGen/src/projectPanel.jsx +529 -0
  87. package/femoGen/src/soulModal.jsx +162 -0
  88. package/femoGen/src/styles/font.css +10 -0
  89. package/femoGen/src/themes.js +465 -0
  90. package/femoGen/src/useCanvasInteraction.jsx +319 -0
  91. package/femoGen/vite.config.js +28 -0
  92. package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
  93. package/hostAdapter/dshAdapter/README.md +68 -0
  94. package/hostAdapter/dshAdapter/build.mjs +75 -0
  95. package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
  96. package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
  97. package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
  98. package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
  99. package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
  100. package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
  101. package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
  102. package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
  103. package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
  104. package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
  105. package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
  106. package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
  107. package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
  108. package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
  109. package/hostAdapter/dshAdapter/client/client.tsx +518 -0
  110. package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
  111. package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
  112. package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
  113. package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
  114. package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
  115. package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
  116. package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
  117. package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
  118. package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
  119. package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
  120. package/hostAdapter/dshAdapter/host/config.ts +124 -0
  121. package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
  122. package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
  123. package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
  124. package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
  125. package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
  126. package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
  127. package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
  128. package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
  129. package/hostAdapter/dshAdapter/host/http.ts +66 -0
  130. package/hostAdapter/dshAdapter/host/index.ts +633 -0
  131. package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
  132. package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
  133. package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
  134. package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
  135. package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
  136. package/hostAdapter/dshAdapter/host/persona.ts +146 -0
  137. package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
  138. package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
  139. package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
  140. package/hostAdapter/dshAdapter/host/projection.ts +742 -0
  141. package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
  142. package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
  143. package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
  144. package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
  145. package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
  146. package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
  147. package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
  148. package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
  149. package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
  150. package/hostAdapter/dshAdapter/host/tools.ts +486 -0
  151. package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
  152. package/hostAdapter/dshAdapter/host.manifest.json +6 -0
  153. package/hostAdapter/dshAdapter/lib/client.js +19161 -0
  154. package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
  155. package/hostAdapter/dshAdapter/lib/index.js +8173 -0
  156. package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
  157. package/hostAdapter/dshAdapter/package-lock.json +500 -0
  158. package/hostAdapter/dshAdapter/package.json +55 -0
  159. package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
  160. package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
  161. package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
  162. package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
  163. package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
  164. package/hostAdapter/dshAdapter/tsconfig.json +21 -0
  165. package/package.json +40 -0
  166. package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
@@ -0,0 +1,767 @@
1
+ # femoCompiler/job_manager.py
2
+ """
3
+ job_manager.py — Job 状态机与状态文件(运行状态链路重构,施工清单 v3 §4.1)。
4
+ ==================================================================
5
+
6
+ 职责四样(架构提案 v2 §二"引擎拥有"):
7
+ 1. Job 状态机 + 状态文件:每个 Job(一次运行)一份
8
+ `<user_data>/runs/<job_id>.json`,temp+rename 原子写(C5 死于结构);
9
+ 2. 启动对账 reconcile:扫目录,state==running 而无执行体 → suspended(reason=crash);
10
+ 3. 命令裁决:create_job 活跃排他(B4)+ resume 六关(§八.18);
11
+ 4. 断点编解码:复用 vars/checkpoint.py 的 dump/restore 产物(本文件只存取,
12
+ 不重复造)。
13
+
14
+ 依赖方向(试金石=直连模式):只 import 标准库 + get_dir.get_user_dir +
15
+ db_utils.session_exists(六关第⑤关用,只读)。**不 import FEMO_runtime**——
16
+ 构造 Runner、起 worker 线程全留在 bridge(bridge 是"接入陌生 agent 框架的
17
+ 翻译模块"雏形,猫猫 2026-09-05 纲领原话)。收益:JobManager 可脱离引擎
18
+ 单测,对账/裁决/并发落盘测试不需要拉起真 Runner。
19
+
20
+ 状态机(提案 §3.4):
21
+ (不存在)--job_start--> running --flow_done--> finished
22
+ |--job_pause----> suspended(user_pause)
23
+ |--取消路径-----> suspended(user_pause|cancelled)
24
+ |--FEMORunPaused-> suspended(node_pause)
25
+ |--节点异常-----> failed
26
+ (启动时)running 且无执行体 --> suspended(crash)
27
+ suspended --job_resume(六关)--> running
28
+
29
+ 写码纪律(猫猫 2026-09-04):def 归属想清楚——新逻辑全部进本文件,
30
+ FEMO_runtime/vars 六件套只动清单列明的旁挂点与两课。
31
+ """
32
+
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import re
37
+ import sys
38
+ import threading
39
+ from dataclasses import dataclass, field
40
+ from datetime import datetime
41
+ from typing import Any, Dict, Optional
42
+
43
+ from femoBridges.getDir.get_dir import get_user_dir
44
+
45
+ # ── 状态机常量 ────────────────────────────────────────────────────────────
46
+
47
+ STATE_RUNNING = 'running'
48
+ STATE_SUSPENDED = 'suspended'
49
+ STATE_FINISHED = 'finished'
50
+ STATE_FAILED = 'failed'
51
+
52
+ # suspended 的原因(crash 只来自对账;user_pause 来自 pause/取消;node_pause 来自直连 AI 失败挂起)
53
+ REASON_USER_PAUSE = 'user_pause'
54
+ REASON_CRASH = 'crash'
55
+ REASON_NODE_PAUSE = 'node_pause'
56
+
57
+ # finalize 只接受这两种终态(幂等闸门内的合法性校验)
58
+ _FINAL_STATES = (STATE_FINISHED, STATE_FAILED)
59
+
60
+
61
+ def fingerprint_script(text: str) -> str:
62
+ """剧本文本指纹:CRLF→LF 归一 + sha256,形如 "sha256:<hex>"。
63
+
64
+ 镜像宿主旧 state-files.scriptFingerprint 语义(JS: text.replace(/\\r\\n/g,'\\n')
65
+ + sha256(hex)),便于对账调试;引擎自洽使用,不依赖宿主。
66
+ 指纹裁决归引擎 job_resume 第④关——宿主不再算指纹(单一职责)。"""
67
+ normalized = (text or '').replace('\r\n', '\n')
68
+ digest = hashlib.sha256(normalized.encode('utf-8')).hexdigest()
69
+ return f"sha256:{digest}"
70
+
71
+
72
+ # ── flow 域指纹(2026-09-06 用户拍板的宽松续跑语义)───────────────────────
73
+ #
74
+ # 断点由三部分组成(vars/checkpoint.py dump_state):位置账本(node_id +
75
+ # 模块栈 + 循环合成节点)、per-task 变量世界、场次挂钩。其中**只有位置账本
76
+ # 强依赖流程图结构**——变量世界整包恢复(新剧本装配的世界被丢弃),action
77
+ # 的 prompt/in/out 改动由"从断点往后跑新定义"自然消化。故续跑可行性指纹
78
+ # = flow + mainflow 结构:
79
+ # - 布局(sketch 注释)、台词、vars 增删、注释与空白 → 不触发重跑
80
+ # - 流程节点/连线/分支结构变了 → 断点位置在新图里无处安放 → 必须重跑
81
+ # ⚠️ 已知边界(拍板接受):恢复=整包替换,新增 vars 不会进入恢复后的世界,
82
+ # 续跑路径"先赋值再读"才安全;根治需恢复后补种新声明变量(另行立项)。
83
+
84
+ def _strip_flow_comment(line: str) -> str:
85
+ """剥一行注释:首个 # 或 // 起整段丢弃(含 sketch 布局——节点拖动只改
86
+ 注释坐标,天然不入指纹)。flow 区无字符串字面量的常规形态下安全;
87
+ 引号内出现 #/// 的病理情形接受误伤(只影响指纹相等性,不影响执行)。"""
88
+ cut = len(line)
89
+ for mark in ('#', '//'):
90
+ i = line.find(mark)
91
+ if 0 <= i < cut:
92
+ cut = i
93
+ return line[:cut]
94
+
95
+
96
+ def _flow_scope_groups(region_lines: list) -> list:
97
+ """区域行 → 规范化语句组:一行 + 其缩进更深的后续行(控制块体)为一组,
98
+ 组内去全部空白,组间排序——声明/书写顺序不参与指纹(画布重排不触发重跑,
99
+ for/fork 体与自己的头绑定不散架)。"""
100
+ groups: list = []
101
+ cur_indent = None
102
+ for raw in region_lines:
103
+ if not raw.strip():
104
+ continue
105
+ indent = len(raw) - len(raw.lstrip())
106
+ if cur_indent is None or indent <= cur_indent:
107
+ cur_indent = indent
108
+ groups.append([raw])
109
+ else:
110
+ groups[-1].append(raw)
111
+ out = []
112
+ for lines in groups:
113
+ body = ''.join(''.join(l.split()) for l in lines)
114
+ if body:
115
+ out.append(body)
116
+ out.sort()
117
+ return out
118
+
119
+
120
+ def extract_flow_scope(text: str) -> str:
121
+ """提取剧本的 flow/mainflow 区域并规范化(check_fingerprint 的比对域):
122
+ 1) 顶层切出 mainflow: 块与各 module 的 flow: 子块;
123
+ 2) 每行剥 # 与 // 注释;3) 去除全部空白;4) 语句组排序后拼接。
124
+ 返回规范化串(空串=两份文本都无 flow 区,视为相等由调用方裁决)。"""
125
+ if not text:
126
+ return ''
127
+ lines = [_strip_flow_comment(l) for l in text.replace('\r\n', '\n').split('\n')]
128
+ # 顶层块边界:非注释后仍非空、且零缩进的行开一块
129
+ tops = [i for i, l in enumerate(lines) if l.strip() and not l[0].isspace()]
130
+ regions: list = []
131
+ for k, start in enumerate(tops):
132
+ end = tops[k + 1] if k + 1 < len(tops) else len(lines)
133
+ header = lines[start].strip()
134
+ if header == 'mainflow:':
135
+ regions.append(lines[start + 1:end])
136
+ continue
137
+ if re.match(r'^module\s+.+:$', header):
138
+ block = lines[start + 1:end]
139
+ for j, l in enumerate(block):
140
+ if l.strip() != 'flow:':
141
+ continue
142
+ flow_indent = len(l) - len(l.lstrip())
143
+ sub_end = len(block)
144
+ for j2 in range(j + 1, len(block)):
145
+ l2 = block[j2]
146
+ if not l2.strip():
147
+ continue
148
+ if len(l2) - len(l2.lstrip()) <= flow_indent:
149
+ sub_end = j2
150
+ break
151
+ regions.append(block[j + 1:sub_end])
152
+ break
153
+ parts: list = []
154
+ for r in regions:
155
+ parts.extend(_flow_scope_groups(r))
156
+ parts.sort()
157
+ return '\x00'.join(parts)
158
+
159
+
160
+ def flow_scope_hash(text: str) -> str:
161
+ """flow 域指纹:extract_flow_scope 规范化串的 sha256。"""
162
+ return hashlib.sha256(extract_flow_scope(text).encode('utf-8')).hexdigest()
163
+
164
+
165
+ # ── Job 档案 ──────────────────────────────────────────────────────────────
166
+
167
+ @dataclass
168
+ class JobRecord:
169
+ """一个 Job 的完整档案(提案 §3.1 字段全表)。job_id 与场次号两套编号
170
+ 各数各的(场次=书,Job=阅读)。"""
171
+ job_id: int
172
+ state: str = STATE_RUNNING
173
+ reason: str = '' # suspended 的原因:user_pause / crash / node_pause
174
+ waiting_human: bool = False # running 的子标记(human_wait 置 / human_done 清 / 挂起清)
175
+ script_fingerprint: str = ''
176
+ script_name: str = '' # 诊断可读(list_jobs/日志里人能看懂)
177
+ script_path: str = '' # 开跑时宿主给的剧本文件地址(未保存=''/缺省)
178
+ script_text: str = '' # 开跑那一刻的剧本原文快照(运行快照,resume 六关保证不漂移)
179
+ host_ref: str = '' # 宿主塞的不透明标签(如其会话标识),透传存档,引擎不懂
180
+ femo_session_id: Optional[int] = None # 挂靠场次(on_flow_start 回填;resume 裁决用)
181
+ checkpoints: Dict[str, str] = field(default_factory=dict) # {task_id: node_id}
182
+ checkpoint_labels: Dict[str, str] = field(default_factory=dict) # {task_id: label}(D1)
183
+ vars_state: Optional[Dict[str, Any]] = None # dump_state 整包(编解码走 vars/checkpoint.py)
184
+ error: str = '' # failed 摘要(诊断)
185
+ created_at: str = ''
186
+ updated_at: str = ''
187
+
188
+ def to_dict(self) -> Dict[str, Any]:
189
+ return {
190
+ 'job_id': self.job_id,
191
+ 'state': self.state,
192
+ 'reason': self.reason,
193
+ 'waiting_human': self.waiting_human,
194
+ 'script_fingerprint': self.script_fingerprint,
195
+ 'script_name': self.script_name,
196
+ 'script_path': self.script_path,
197
+ 'script_text': self.script_text,
198
+ 'host_ref': self.host_ref,
199
+ 'femo_session_id': self.femo_session_id,
200
+ 'checkpoints': dict(self.checkpoints),
201
+ 'checkpoint_labels': dict(self.checkpoint_labels),
202
+ 'vars_state': self.vars_state,
203
+ 'error': self.error,
204
+ 'created_at': self.created_at,
205
+ 'updated_at': self.updated_at,
206
+ }
207
+
208
+ @classmethod
209
+ def from_dict(cls, data: Dict[str, Any]) -> 'JobRecord':
210
+ """缺键容忍默认、未知键忽略(前向兼容写入)。"""
211
+ if not isinstance(data, dict):
212
+ raise ValueError(f"JobRecord.from_dict 需要 dict,得到 {type(data).__name__}")
213
+ return cls(
214
+ job_id=int(data.get('job_id', 0)),
215
+ state=str(data.get('state', STATE_RUNNING)),
216
+ reason=str(data.get('reason', '')),
217
+ waiting_human=bool(data.get('waiting_human', False)),
218
+ script_fingerprint=str(data.get('script_fingerprint', '')),
219
+ script_name=str(data.get('script_name', '')),
220
+ script_path=str(data.get('script_path', '')),
221
+ script_text=str(data.get('script_text', '')),
222
+ # 旧档案键 owner_tag 兼容读(改名前的存档文件)
223
+ host_ref=str(data.get('host_ref', data.get('owner_tag', ''))),
224
+ femo_session_id=data.get('femo_session_id'),
225
+ checkpoints=dict(data.get('checkpoints') or {}),
226
+ checkpoint_labels=dict(data.get('checkpoint_labels') or {}),
227
+ vars_state=data.get('vars_state'),
228
+ error=str(data.get('error', '')),
229
+ created_at=str(data.get('created_at', '')),
230
+ updated_at=str(data.get('updated_at', '')),
231
+ )
232
+
233
+
234
+ class JobError(Exception):
235
+ """结构化错误:.code 给宿主分发,.detail 是人话(命令-结果契约,B5 死于结构)。"""
236
+
237
+ def __init__(self, code: str, detail: str = ''):
238
+ self.code = code
239
+ self.detail = detail or code
240
+ super().__init__(f"[{code}] {self.detail}")
241
+
242
+
243
+ class JobBusyError(JobError):
244
+ """活跃排他失败(B4"Job 创建即占位"):另带活跃 Job 归属,供宿主信息化文案。"""
245
+
246
+ def __init__(self, active_job_id: int, active_host_ref: str = ''):
247
+ self.active_job_id = active_job_id
248
+ self.active_host_ref = active_host_ref
249
+ super().__init__(
250
+ 'another_job_active',
251
+ f'Job {active_job_id}(宿主标签 {active_host_ref or "?"})活跃中,'
252
+ f'可先暂停或等它挂起')
253
+
254
+
255
+ def _now_iso() -> str:
256
+ return datetime.now().isoformat(timespec='seconds')
257
+
258
+
259
+ # ── JobManager ────────────────────────────────────────────────────────────
260
+
261
+ class JobManager:
262
+ """Job 状态机唯一权威(每引擎进程一个;bridge main() 装配)。
263
+
264
+ 落盘线程模型(§八.19):同一 Job 的全部落盘(checkpoint 落盘 + finalize)
265
+ 都在 worker 单线程,天然串行无并发写;进程内锁保留为防御性
266
+ (防未来异步化落盘),§12.2.8 用 8 线程并发 _save 验证它保序。
267
+ """
268
+
269
+ def __init__(self, runs_dir: Optional[str] = None):
270
+ if runs_dir is None:
271
+ runs_dir = os.path.join(get_user_dir(), 'user_data', 'jobs', 'runs')
272
+ self.runs_dir = runs_dir
273
+ os.makedirs(self.runs_dir, exist_ok=True)
274
+ # §八.2 防御锁:同 Job 落盘串行化(世界单调推进,后写自然含先写)
275
+ self._lock = threading.RLock()
276
+ # 挂靠登记 job_id → 活跃 FEMORunner 实例(duck 访问:.stop() /
277
+ # .engine.human_input;本文件不 import FEMO_runtime)
278
+ self._bound: Dict[int, Any] = {}
279
+
280
+ # ── 路径与读写 ──
281
+
282
+ def _job_path(self, job_id: int) -> str:
283
+ return os.path.join(self.runs_dir, f'{job_id}.json')
284
+
285
+ def _meta_path(self, job_id: int) -> str:
286
+ """元数据侧写地址(.meta 结尾,刻意不带 .json——allocate/list_jobs 的
287
+ 主档扫描都按 '.json'+纯数字词干过滤,侧写天然不进主档名单)。"""
288
+ return os.path.join(self.runs_dir, f'{job_id}.meta')
289
+
290
+ def _load(self, job_id: int) -> Optional[JobRecord]:
291
+ """读单份档案。文件缺失 → None;JSON 损坏 → rename 留证(.corrupt-<ts>)
292
+ + stderr 大声报错 → None(对账判定就靠这文件,坏档不能静默当存在)。"""
293
+ path = self._job_path(job_id)
294
+ try:
295
+ with open(path, 'r', encoding='utf-8') as f:
296
+ raw = f.read()
297
+ except FileNotFoundError:
298
+ return None
299
+ try:
300
+ return JobRecord.from_dict(json.loads(raw))
301
+ except (json.JSONDecodeError, ValueError, TypeError) as exc:
302
+ stamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
303
+ quarantined = f'{path}.corrupt-{stamp}'
304
+ try:
305
+ os.rename(path, quarantined)
306
+ sys.stderr.write(
307
+ f'[job_manager] ⚠️ Job 档案损坏,原档已隔离留证: {quarantined}({exc})\n')
308
+ except OSError as rename_exc:
309
+ sys.stderr.write(
310
+ f'[job_manager] ⚠️ Job 档案损坏且隔离失败: {exc} / {rename_exc}\n')
311
+ return None
312
+
313
+ def _save(self, rec: JobRecord) -> None:
314
+ """原子落盘:temp 同目录(.<id>.tmp-<pid>)→ os.replace 原子替换(C5)。
315
+ RLock 内(同 Job 串行化,保序防旧快照覆盖新快照);updated_at 刷新。
316
+ 主档落盘后同步写 <id>.meta 元数据侧写(list_jobs 加速档,~200B)——
317
+ list_jobs 优先读它,不再全量 json.loads 主档案(script_text/checkpoints/
318
+ vars_state 都可能很大)。侧写与主档非联合原子:断电窗口内可能落后一拍,
319
+ 下次 _save 自愈;缺失/损坏由读侧回落全量 _load 兜底,绝不阻塞读。"""
320
+ with self._lock:
321
+ rec.updated_at = _now_iso()
322
+ path = self._job_path(rec.job_id)
323
+ tmp = os.path.join(self.runs_dir, f'.{rec.job_id}.tmp-{os.getpid()}')
324
+ with open(tmp, 'w', encoding='utf-8') as f:
325
+ json.dump(rec.to_dict(), f, ensure_ascii=False, default=str)
326
+ # 同目录 replace:Windows/POSIX 上都是原子替换——断电瞬间要么旧
327
+ # 文件要么新文件,绝无半截 JSON(C5 死于结构的结构修复)。
328
+ os.replace(tmp, path)
329
+ # 元数据侧写:写失败不影响主档(读侧回落全量 _load),只大声留痕。
330
+ meta_tmp = os.path.join(self.runs_dir, f'.{rec.job_id}.meta-{os.getpid()}')
331
+ try:
332
+ with open(meta_tmp, 'w', encoding='utf-8') as f:
333
+ json.dump(self._meta_fields(rec), f, ensure_ascii=False, default=str)
334
+ os.replace(meta_tmp, self._meta_path(rec.job_id))
335
+ except OSError as exc:
336
+ sys.stderr.write(
337
+ f'[job_manager] ⚠️ Job 元数据侧写失败(list_jobs 将回落全量读取): {exc}\n')
338
+
339
+ def allocate_job_id(self) -> int:
340
+ """扫目录现有 job_id 取 max+1。无独立计数文件——文件在编号就在,
341
+ 断电不丢号。"""
342
+ best = 0
343
+ try:
344
+ names = os.listdir(self.runs_dir)
345
+ except OSError:
346
+ names = []
347
+ for name in names:
348
+ if name.endswith('.json') and name[:1].isdigit():
349
+ stem = name[:-len('.json')]
350
+ if stem.isdigit():
351
+ best = max(best, int(stem))
352
+ return best + 1
353
+
354
+ # ── 懒对账(2026-09-07 214 事故改造:启动扫全目录 → 摸到才对账)────────
355
+ #
356
+ # 旧 reconcile() 在 bridge 启动时无条件扫 runs/ 全目录,把所有 running
357
+ # 档案按"不在我内存里=主人死了"判 crash。判定依据是【本进程】的 _bound,
358
+ # 而档案是磁盘上多进程共享资源——pytest/第二个宿主的 bridge 一启动,
359
+ # 就会把活着进程的 Job 误杀成 crash(214 实锤:引擎僵死挂着 runner,
360
+ # 测试 bridge 启动对账把它写成 crash,之后每次暂停都落进幂等空转)。
361
+ # 改为懒对账:只对【本宿主 session 路由会摸到的那个 job】、在【被摸到的
362
+ # 时刻】裁决;_bound 主人检查永远先行(我是主人=它活着,哪怕循环僵死
363
+ # 也轮不到对账判死)。
364
+
365
+ # 触摸式对账的新鲜度下限:档案 updated_at 距今不足该秒数不动手——
366
+ # 防 create_job 落盘后、worker attach 前的窗口被并发的状态查询误判
367
+ # (镜像 prearm 已在宿主侧挡住正常路径,此为纵深保险)。
368
+ RECONCILE_MIN_AGE_SECONDS = 60.0
369
+
370
+ def reconcile_stale(self, job_id: int) -> Optional[dict]:
371
+ """单档案懒对账:running 且无挂靠执行体 → suspended(reason=crash)。
372
+ 返回对账后的档案 dict(动了才返回,None=没动)。
373
+ 三道闸门(顺序即安全序):
374
+ ① `_bound` 主人检查——本进程挂着执行体=它活着(哪怕引擎循环僵死),
375
+ 绝不动手;
376
+ ② 非 running 档案不碰(幂等:suspended/finished/failed 原样);
377
+ ③ updated_at 距今不足 RECONCILE_MIN_AGE_SECONDS 不碰(新鲜度保险,
378
+ 见上注释)。"""
379
+ with self._lock:
380
+ if job_id in self._bound:
381
+ return None # ① 我是主人:它活着,不判死
382
+ rec = self._load(job_id)
383
+ if rec is None or rec.state != STATE_RUNNING:
384
+ return None # ② 非 running:没的可对
385
+ try:
386
+ age = (datetime.now() - datetime.fromisoformat(rec.updated_at)).total_seconds()
387
+ except (ValueError, TypeError):
388
+ age = self.RECONCILE_MIN_AGE_SECONDS # 时间戳坏档:按够旧处理
389
+ if age < self.RECONCILE_MIN_AGE_SECONDS:
390
+ return None # ③ 新鲜档案:可能正在 attach,不动手
391
+ rec.state = STATE_SUSPENDED
392
+ rec.reason = REASON_CRASH
393
+ rec.waiting_human = False
394
+ self._save(rec)
395
+ sys.stderr.write(
396
+ f'[job_manager] ⚠️ 懒对账:Job {job_id} 档案 running 但无挂靠执行体'
397
+ f'(updated_at={rec.updated_at},距今 {age:.0f}s)→ 判 crash 挂起\n')
398
+ return rec.to_dict()
399
+
400
+ # ── 命令裁决 ──
401
+
402
+ def create_job(self, fingerprint: str, host_ref: str = '',
403
+ script_name: str = '', script_path: str = '',
404
+ script_text: str = '') -> JobRecord:
405
+ """开新 Job。活跃排他裁决(B4):_bound 非空 → JobBusyError(带归属)。
406
+ → allocate → 建 running 档 → 落盘 → 返回。
407
+ script_path/script_text = 开跑那一刻的剧本快照(文本+地址,有啥存啥):
408
+ resume 六关的 fingerprint_mismatch 保证可续跑 Job 的文本不漂移,
409
+ 故只需在 create 时存一次。"""
410
+ with self._lock:
411
+ if self._bound:
412
+ active = self.active_job()
413
+ active_id = active.job_id if active is not None else -1
414
+ active_tag = active.host_ref if active is not None else ''
415
+ raise JobBusyError(active_id, active_tag)
416
+ rec = JobRecord(
417
+ job_id=self.allocate_job_id(),
418
+ state=STATE_RUNNING,
419
+ script_fingerprint=fingerprint,
420
+ script_name=script_name,
421
+ script_path=script_path,
422
+ script_text=script_text,
423
+ host_ref=host_ref,
424
+ created_at=_now_iso(),
425
+ )
426
+ self._save(rec)
427
+ return rec
428
+
429
+ def resume_job(self, job_id: int, fingerprint: str,
430
+ host_ref: str = '', new_text: str = '') -> JobRecord:
431
+ """续跑六关裁决(§八.18 顺序),任一关失败 raise JobError(code, 人话)。
432
+ 全过 → 返回 rec(state 置 running 由调用方在 Runner 构造成功后经
433
+ mark_running 确认——裁决通过到构造成功之间文件仍是 suspended,
434
+ 构造失败 worker except 收口 failed,不停僵尸 running)。
435
+ new_text:本次续跑提交的剧本文本(flow 域比对用,见第④关)。"""
436
+ with self._lock:
437
+ # ① no_such_job:文件不存在
438
+ rec = self._load(job_id)
439
+ if rec is None:
440
+ raise JobError('no_such_job', f'Job {job_id} 不存在(无该运行的档案文件)')
441
+ # ② already_running:running 态(_bound 有挂靠=真活跃;无挂靠=
442
+ # 对账漏网,防御同样拒)
443
+ if rec.state == STATE_RUNNING:
444
+ raise JobError('already_running', f'Job {job_id} 正在运行中,不能续跑')
445
+ # ③ not_resumable:finished / failed(终态不可续,断点字段已作废)
446
+ if rec.state in _FINAL_STATES:
447
+ raise JobError('not_resumable',
448
+ f'Job {job_id} 已{"完整跑完" if rec.state == STATE_FINISHED else "以失败收场"}'
449
+ f'({rec.state}),不能再续跑;请 fresh_start')
450
+ # (state 应为 suspended;其余未知状态按 not_resumable 处理)
451
+ if rec.state != STATE_SUSPENDED:
452
+ raise JobError('not_resumable',
453
+ f'Job {job_id} 状态为 {rec.state!r},不可续跑')
454
+ # ④ fingerprint_mismatch:断点可行性=流程图结构(flow/mainflow)。
455
+ # 【2026-09-06 宽松化,用户拍板】vars 增删(runtime 补种新声明)、
456
+ # 台词/prompt、布局(sketch 注释)、注释与空白改动不再触发重跑;
457
+ # 只有流程结构变了,断点位置在新图里才真的无处安放。
458
+ # 新档案(有 script_text 快照)走 flow 域比对;旧档案回退整文指纹。
459
+ if rec.script_text:
460
+ if extract_flow_scope(rec.script_text) != extract_flow_scope(new_text or ''):
461
+ raise JobError('fingerprint_mismatch',
462
+ f'Job {job_id} 的断点所属的流程图(flow/mainflow)'
463
+ f'与提交版本不一致。流程结构变了断点无处安放'
464
+ f'——请 fresh_start 从头跑')
465
+ elif rec.script_fingerprint and rec.script_fingerprint != fingerprint:
466
+ raise JobError('fingerprint_mismatch',
467
+ f'Job {job_id} 的断点属于另一个版本的剧本(指纹不符)。'
468
+ f'改了剧本就是新戏——请 fresh_start 从头跑,或先恢复原剧本文本')
469
+ # ⑤ session_missing:挂靠场次不存在=拒绝失忆续跑(现状
470
+ # FEMO_runtime resume 分支同语义平移;None=无场次可校验则跳过)
471
+ if rec.femo_session_id is not None:
472
+ from femoCompiler.db_utils import session_exists
473
+ if not session_exists(int(rec.femo_session_id)):
474
+ raise JobError('session_missing',
475
+ f'Job {job_id} 的断点指向的场次 {rec.femo_session_id} 不存在'
476
+ f'(运行台账可能已被清空),拒绝失忆续跑;请 fresh_start')
477
+ # ⑥ no_breakpoint:文件在但断点为空(防御关)
478
+ if not rec.checkpoints:
479
+ raise JobError('no_breakpoint',
480
+ f'Job {job_id} 没有可续跑的断点(档案存在但执行位置为空)')
481
+ # 全过:host_ref 更新为本次续跑发起方(透传存档)
482
+ rec.host_ref = host_ref or rec.host_ref
483
+ self._save(rec)
484
+ return rec
485
+
486
+ def check_fingerprint(self, job_id: int, new_text: str) -> dict:
487
+ """续跑可行性指纹校验(不 raise——诊断/宿主查询用,裁决仍在
488
+ resume_job 第④关,同一套判定)。
489
+ - mode='flow':新档案有快照文本 → flow/mainflow 结构比对(宽松语义:
490
+ vars 增删/台词/布局/注释不触发,流程结构变才触发);
491
+ - mode='raw':旧档案只有整文指纹 → 整文 sha256 比对;
492
+ - mode='no_such_job' / 'none':档案缺失/无指纹可校验。"""
493
+ rec = self._load(job_id)
494
+ if rec is None:
495
+ return {'match': False, 'mode': 'no_such_job',
496
+ 'detail': f'Job {job_id} 不存在'}
497
+ if rec.script_text:
498
+ return {'match': extract_flow_scope(rec.script_text) == extract_flow_scope(new_text or ''),
499
+ 'mode': 'flow', 'detail': 'flow/mainflow 结构比对(宽松语义)'}
500
+ if rec.script_fingerprint:
501
+ return {'match': rec.script_fingerprint == fingerprint_script(new_text or ''),
502
+ 'mode': 'raw', 'detail': '整文 sha256 比对(旧档案回退)'}
503
+ return {'match': False, 'mode': 'none', 'detail': '档案既无快照文本也无指纹'}
504
+
505
+ def mark_running(self, job_id: int) -> None:
506
+ """resume 的 Runner 构造成功后调用:state=running, reason='' 落盘。"""
507
+ rec = self._load(job_id)
508
+ if rec is None:
509
+ raise JobError('no_such_job', f'Job {job_id} 不存在,无法置 running')
510
+ rec.state = STATE_RUNNING
511
+ rec.reason = ''
512
+ self._save(rec)
513
+
514
+ def pause_job(self, job_id: int) -> dict:
515
+ """暂停一个 Job(=挂起,断点保留可续跑;2026-09-12 stop→pause 全链路改名,原名 stop_job)。幂等。
516
+ - running 且 _bound 有挂靠 → runner.stop()(flow_paused 照发、协程取消
517
+ 链启动);**状态落盘不在这一步**——suspended 的落盘在 Runtime 取消
518
+ 路径的 on_state_change 回调(状态机变更单一来源=回调+finalize,
519
+ 防双写竞态)。
520
+ - running 但无挂靠(B5 死过的窗口)→ 直接落盘 suspended(reason=user_pause)
521
+ (诚实化:没有执行体就是挂起,不是成功)。
522
+ - 非 running → {paused:True, state:<现态>} 幂等返回。"""
523
+ with self._lock:
524
+ rec = self._load(job_id)
525
+ if rec is None:
526
+ raise JobError('no_such_job', f'Job {job_id} 不存在,无法暂停')
527
+ if rec.state == STATE_RUNNING:
528
+ runner = self._bound.get(job_id)
529
+ if runner is not None:
530
+ runner.stop()
531
+ return {'paused': True, 'state': rec.state}
532
+ # running 但无执行体:诚实化(B5 死于结构)
533
+ rec.state = STATE_SUSPENDED
534
+ rec.reason = REASON_USER_PAUSE
535
+ rec.waiting_human = False
536
+ self._save(rec)
537
+ return {'paused': True, 'state': rec.state}
538
+ return {'paused': True, 'state': rec.state}
539
+
540
+ def deliver_human_input(self, job_id: int, wait_key: str, body) -> dict:
541
+ """人类/AI 回传投递。活跃+_bound 校验(B6/孤儿信投递侧防线:不盲投信箱)。
542
+ 不活跃/无挂靠 → {delivered:False, error:...},不假成功(B5 死于结构)。"""
543
+ rec = self._load(job_id)
544
+ if rec is None:
545
+ return {'delivered': False, 'error': 'no_such_job'}
546
+ runner = self._bound.get(job_id)
547
+ if rec.state != STATE_RUNNING or runner is None:
548
+ return {'delivered': False, 'error': 'job_not_active'}
549
+ runner.engine.human_input.provide_input(wait_key, body)
550
+ return {'delivered': True}
551
+
552
+ # ── 查询 ──
553
+
554
+ def get_job_state(self, job_id: int) -> dict:
555
+ """文件原文 to_dict;不存在 → {'error':'no_such_job'}。"""
556
+ rec = self._load(job_id)
557
+ if rec is None:
558
+ return {'error': 'no_such_job'}
559
+ return rec.to_dict()
560
+
561
+ def _meta_fields(self, rec: JobRecord) -> dict:
562
+ """list_jobs 行字段(元数据侧写内容)。与 list_jobs 返回行逐字段一致;
563
+ has_breakpoint 派生自 checkpoints 非空。"""
564
+ return {
565
+ 'job_id': rec.job_id,
566
+ 'state': rec.state,
567
+ 'reason': rec.reason,
568
+ 'waiting_human': rec.waiting_human,
569
+ 'femo_session_id': rec.femo_session_id,
570
+ 'host_ref': rec.host_ref,
571
+ 'script_name': rec.script_name,
572
+ 'created_at': rec.created_at,
573
+ 'updated_at': rec.updated_at,
574
+ 'has_breakpoint': bool(rec.checkpoints),
575
+ }
576
+
577
+ def _load_meta_row(self, job_id: int) -> Optional[dict]:
578
+ """list_jobs 单行:优先读 <id>.meta 侧写(~200B),缺失/损坏/job_id
579
+ 对不上(半截写入等)一律回落全量 _load 取元数据字段。回落成功时顺手
580
+ 补写侧写——存量老档案第一次被扫到即完成迁移,之后永远走快路径。
581
+ 补写失败静默(读路径不嗓噪,下次再试)。"""
582
+ try:
583
+ with open(self._meta_path(job_id), 'r', encoding='utf-8') as f:
584
+ row = json.load(f)
585
+ except (OSError, ValueError):
586
+ row = None
587
+ if isinstance(row, dict) and row.get('job_id') == job_id:
588
+ row['has_breakpoint'] = bool(row.get('has_breakpoint'))
589
+ return row
590
+ rec = self._load(job_id)
591
+ if rec is None:
592
+ return None
593
+ row = self._meta_fields(rec)
594
+ try:
595
+ meta_tmp = os.path.join(self.runs_dir, f'.{job_id}.meta-{os.getpid()}')
596
+ with open(meta_tmp, 'w', encoding='utf-8') as f:
597
+ json.dump(row, f, ensure_ascii=False, default=str)
598
+ os.replace(meta_tmp, self._meta_path(job_id))
599
+ except OSError:
600
+ pass
601
+ return row
602
+
603
+ def list_jobs(self) -> list:
604
+ """扫目录元数据行——优先读 <id>.meta 侧写,不全量 json.loads 主档案
605
+ (script_text/checkpoints/vars_state 都可能很大;读侧写从根上免疫档案
606
+ 体积增长)。主档案仍是存在性权威:只认 '.json'+纯数字词干,侧写/隔离
607
+ 留证文件天然不在名单里。供 /jobs 路由与 femo-run list_jobs 消费
608
+ (幽灵书签可达性,§八.14)。"""
609
+ jobs = []
610
+ try:
611
+ names = os.listdir(self.runs_dir)
612
+ except OSError:
613
+ return jobs
614
+ for name in sorted(names, key=lambda n: (len(n), n)):
615
+ if not name.endswith('.json') or not name[:1].isdigit():
616
+ continue
617
+ stem = name[:-len('.json')]
618
+ if not stem.isdigit():
619
+ continue
620
+ row = self._load_meta_row(int(stem))
621
+ if row is None:
622
+ continue
623
+ jobs.append(row)
624
+ return jobs
625
+
626
+ # ── 挂靠登记族 ──
627
+
628
+ def attach(self, job_id: int, runner: Any) -> None:
629
+ """挂靠登记:拿到 Runner 就绪开跑的时刻。顺带调
630
+ runner.engine.human_input.discard_all()——任何"就绪开跑"时刻信箱
631
+ 必须从零开始(清无主滞留信,同 Runner 生命周期内的保险,幂等零成本)。"""
632
+ self._bound[job_id] = runner
633
+ try:
634
+ runner.engine.human_input.discard_all()
635
+ except AttributeError:
636
+ # 防御:测试假 runner 无 discard_all 时跳过(真实引擎必然有,步2 落地)
637
+ pass
638
+
639
+ def detach(self, job_id: int) -> None:
640
+ self._bound.pop(job_id, None)
641
+
642
+ def runner_of(self, job_id: int) -> Optional[Any]:
643
+ return self._bound.get(job_id)
644
+
645
+ def active_job(self) -> Optional[JobRecord]:
646
+ """引擎活跃 Job(全引擎同时至多一个=_bound 至多一个挂靠)。"""
647
+ if not self._bound:
648
+ return None
649
+ job_id = next(iter(self._bound))
650
+ return self._load(job_id)
651
+
652
+ # ── 状态机旁挂(bridge 事件入口,职责表 §7.5)──
653
+
654
+ def observe_event(self, job_id: int, event_type: str, data: dict) -> None:
655
+ """bridge per-job 事件包装的旁挂入口:
656
+ checkpoint → merge_checkpoint;flow_done → finalize(finished);
657
+ human_wait/human_done → mark_waiting(True/False);其余忽略
658
+ (flow_paused 不在此落盘——suspended 单一来源=on_state_change 回调)。"""
659
+ if event_type == 'checkpoint':
660
+ self.merge_checkpoint(job_id, data if isinstance(data, dict) else {})
661
+ elif event_type == 'flow_done':
662
+ self.finalize(job_id, STATE_FINISHED)
663
+ elif event_type == 'human_wait':
664
+ self.mark_waiting(job_id, True)
665
+ elif event_type == 'human_done':
666
+ self.mark_waiting(job_id, False)
667
+ # 其余事件不参与状态机(显示事件)
668
+
669
+ def merge_checkpoint(self, job_id: int, payload: dict) -> None:
670
+ """checkpoint 落盘(§八.17 防半失忆):
671
+ - checkpoints/checkpoint_labels 全量覆盖;
672
+ - payload 带 'state' 才覆盖 vars_state(条件保留旧值——照搬现状
673
+ 宿主侧 checkpoint 分支防线:引擎去重后仅变量变化时携带,
674
+ 无条件覆盖会写出"只有位置没有变量"的残缺文件);
675
+ - 带 session_id 回填 femo_session_id;落盘。"""
676
+ with self._lock:
677
+ rec = self._load(job_id)
678
+ if rec is None:
679
+ # Job 文件不在(极端:档案被外部移走)——响亮不静默
680
+ sys.stderr.write(f'[job_manager] ⚠️ checkpoint for missing job {job_id}\n')
681
+ return
682
+ cp = payload.get('checkpoints')
683
+ if isinstance(cp, dict):
684
+ rec.checkpoints = {str(k): str(v) for k, v in cp.items()}
685
+ labels = payload.get('checkpoint_labels')
686
+ if isinstance(labels, dict):
687
+ rec.checkpoint_labels = {str(k): str(v) for k, v in labels.items()}
688
+ if payload.get('state') is not None and isinstance(payload.get('state'), dict):
689
+ rec.vars_state = payload['state']
690
+ sid = payload.get('session_id')
691
+ if isinstance(sid, int) and sid > 0:
692
+ rec.femo_session_id = sid
693
+ self._save(rec)
694
+
695
+ def mark_waiting(self, job_id: int, waiting: bool) -> None:
696
+ """waiting_human 子标记置/清 + 落盘(human_wait/human_done 走既有事件,
697
+ Runtime 零新触点)。"""
698
+ with self._lock:
699
+ rec = self._load(job_id)
700
+ if rec is None:
701
+ return
702
+ if rec.waiting_human == waiting:
703
+ return
704
+ rec.waiting_human = waiting
705
+ self._save(rec)
706
+
707
+ def mark_session(self, job_id: int, session_id: Optional[int]) -> None:
708
+ """femo_session_id 回填(on_flow_start 落点)。"""
709
+ if not isinstance(session_id, int) or session_id <= 0:
710
+ return
711
+ with self._lock:
712
+ rec = self._load(job_id)
713
+ if rec is None:
714
+ return
715
+ rec.femo_session_id = session_id
716
+ self._save(rec)
717
+
718
+ def suspend(self, job_id: int, reason: str) -> None:
719
+ """挂起落盘(on_state_change('suspended', ...) 落点):
720
+ state=suspended, reason=..., waiting_human=False。"""
721
+ with self._lock:
722
+ rec = self._load(job_id)
723
+ if rec is None:
724
+ return
725
+ rec.state = STATE_SUSPENDED
726
+ rec.reason = reason
727
+ rec.waiting_human = False
728
+ self._save(rec)
729
+
730
+ def finalize(self, job_id: int, final_state: str, error: str = '') -> None:
731
+ """幂等终态化:**仅 rec.state==running 时生效**(§八.10 三面收口的
732
+ 统一闸门——回调链已落 suspended/finished 则 no-op);断点字段作废=
733
+ checkpoints/labels 清空 + vars_state=None(文件保留,红线);final_state
734
+ 合法性校验(只接受 finished/failed)。"""
735
+ if final_state not in _FINAL_STATES:
736
+ raise JobError('invalid_final_state',
737
+ f'finalize 只接受 finished/failed,得到 {final_state!r}')
738
+ with self._lock:
739
+ rec = self._load(job_id)
740
+ if rec is None:
741
+ return
742
+ if rec.state != STATE_RUNNING:
743
+ return # 已终态/已挂起:幂等 no-op
744
+ rec.state = final_state
745
+ rec.error = error or rec.error
746
+ rec.waiting_human = False
747
+ rec.checkpoints = {}
748
+ rec.checkpoint_labels = {}
749
+ rec.vars_state = None
750
+ self._save(rec)
751
+
752
+ # ── 续跑载荷 ──
753
+
754
+ def build_resume_state(self, rec: JobRecord) -> dict:
755
+ """构造 FEMORunner 的 resume_state 载荷:{checkpoints, session_id,
756
+ state: vars_state}。vars_state None 且 checkpoints 非空 = 异常态
757
+ (防御:raise JobError('job_file_inconsistent'),诚实不半失忆——
758
+ 半失忆续跑=位置在变量丢,比 fresh 更危险)。"""
759
+ if rec.vars_state is None and rec.checkpoints:
760
+ raise JobError('job_file_inconsistent',
761
+ f'Job {rec.job_id} 档案不一致:有断点位置但没有变量世界快照,'
762
+ f'拒绝半失忆续跑(请 fresh_start)')
763
+ return {
764
+ 'checkpoints': dict(rec.checkpoints),
765
+ **({'session_id': int(rec.femo_session_id)} if rec.femo_session_id is not None else {}),
766
+ **({'state': rec.vars_state} if rec.vars_state is not None else {}),
767
+ }