dynamic-workflow-import.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /**
  2. * amend-resume 导入构建器的单元测试(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Amend-resume」与
  3. * 「转录源解析」两行)。
  4. *
  5. * 被测对象是纯函数 `buildImportedCache`:喂一份真实的 InMemoryJournalStore(journal 契约的
  6. * 两个实现之一,语义由 journal-contract.ts 钉住),断言门与表。端到端的「命中真的短路了模型」
  7. * 在 run-service 测试里,这里只管**表构建得对不对**。
  8. */
  9. import { describe, expect, it } from "vitest";
  10. import { InMemoryJournalStore, type PersonaSpec } from "@zcode/dynamic-workflow";
  11. import type { MessageWithParts, SessionId } from "@zcode/contracts";
  12. import { buildImportedCache, preflightAmendImport } from "../src/app/dynamic-workflow-import.js";
  13. import type { ActorTranscriptStore } from "../src/app/workflow-actor-transcript.js";
  14. const PERSONA: PersonaSpec = { name: "worker", system: "you are a worker" };
  15. /** 一份预置的前驱 journal:一个 run + 若干 actor 行 + 若干 node 行。 */
  16. function makeJournal(): InMemoryJournalStore {
  17. return new InMemoryJournalStore();
  18. }
  19. function putRun(
  20. journal: InMemoryJournalStore,
  21. input: {
  22. runId: string;
  23. status?: "completed" | "errored" | "stopped" | "running" | "pending";
  24. resumedFrom?: string;
  25. },
  26. ): void {
  27. journal.createRun({
  28. runId: input.runId,
  29. caps: { maxConcurrency: 4 },
  30. spentTokens: 0,
  31. status: input.status ?? "completed",
  32. ...(input.resumedFrom === undefined ? {} : { resumedFrom: input.resumedFrom }),
  33. });
  34. }
  35. function putActor(
  36. journal: InMemoryJournalStore,
  37. input: {
  38. runId: string;
  39. siteId?: string;
  40. ordinal?: number;
  41. name?: string;
  42. persona?: PersonaSpec;
  43. sessionId?: string;
  44. resolvedModel?: string;
  45. },
  46. ): { siteId: string; ordinal: number } {
  47. const siteId = input.siteId ?? "actor#1";
  48. const ordinal = input.ordinal ?? 1;
  49. journal.putActor({
  50. runId: input.runId,
  51. siteId,
  52. ordinal,
  53. ...(input.name === undefined ? {} : { name: input.name }),
  54. persona: input.persona ?? PERSONA,
  55. ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }),
  56. ...(input.resolvedModel === undefined ? {} : { resolvedModel: input.resolvedModel }),
  57. });
  58. return { siteId, ordinal };
  59. }
  60. function putAsk(
  61. journal: InMemoryJournalStore,
  62. input: {
  63. runId: string;
  64. actor: { siteId: string; ordinal: number };
  65. seq: number;
  66. siteId?: string;
  67. ordinal?: number;
  68. status?: "completed" | "failed" | "running";
  69. result?: unknown;
  70. inputHash?: string;
  71. messageBoundary?: number;
  72. stats?: { inputTokens: number; outputTokens: number; totalTokens: number };
  73. },
  74. ): void {
  75. journal.putNode({
  76. runId: input.runId,
  77. siteId: input.siteId ?? "ask#1",
  78. ordinal: input.ordinal ?? input.seq + 1,
  79. kind: "ask",
  80. actorSiteId: input.actor.siteId,
  81. actorOrdinal: input.actor.ordinal,
  82. actorSeq: input.seq,
  83. inputHash: input.inputHash ?? `hash-${input.seq}`,
  84. status: input.status ?? "completed",
  85. ...(input.status === "running" ? {} : { result: input.result ?? `answer-${input.seq}` }),
  86. ...(input.messageBoundary === undefined ? {} : { messageBoundary: input.messageBoundary }),
  87. ...(input.stats === undefined ? {} : { stats: input.stats }),
  88. });
  89. }
  90. function putWorld(
  91. journal: InMemoryJournalStore,
  92. input: {
  93. runId: string;
  94. siteId: string;
  95. ordinal: number;
  96. kind?: "world-read" | "world-run";
  97. inputHash: string;
  98. status?: "completed" | "failed";
  99. result?: unknown;
  100. },
  101. ): void {
  102. journal.putNode({
  103. runId: input.runId,
  104. siteId: input.siteId,
  105. ordinal: input.ordinal,
  106. kind: input.kind ?? "world-read",
  107. inputHash: input.inputHash,
  108. status: input.status ?? "completed",
  109. result: input.result,
  110. });
  111. }
  112. /** 转录读面替身:每个会话 id 一个消息条数(本模块只数长度,不看内容)。 */
  113. function transcriptsWith(lengths: Record<string, number>): ActorTranscriptStore {
  114. return {
  115. async messages({ sessionID }: { sessionID: SessionId }): Promise<MessageWithParts[]> {
  116. const count = lengths[sessionID as string];
  117. if (count === undefined) throw new Error(`session not found: ${sessionID}`);
  118. return Array.from({ length: count }, () => ({}) as MessageWithParts);
  119. },
  120. async saveMessage() {
  121. throw new Error("not used");
  122. },
  123. async savePart() {
  124. throw new Error("not used");
  125. },
  126. };
  127. }
  128. /** 一个「两条完结 ask + 有会话」的最小可导入前驱。 */
  129. function seedSimplePredecessor(journal: InMemoryJournalStore, runId = "runA"): void {
  130. putRun(journal, { runId });
  131. const actor = putActor(journal, { runId, name: "worker", sessionId: "sess-A" });
  132. putAsk(journal, { runId, actor, seq: 0, messageBoundary: 2 });
  133. putAsk(journal, { runId, actor, seq: 1, messageBoundary: 5 });
  134. }
  135. describe("buildImportedCache — 三道门", () => {
  136. it("前驱不存在 → run_not_found", async () => {
  137. const result = await buildImportedCache({ journal: makeJournal() }, "missing");
  138. expect(result).toEqual({ ok: false, reason: "run_not_found" });
  139. });
  140. // 构建仍要求终态:amend 路径先停下在飞前驱并等它结算,再来构建;到这里还非终态是接线故障。
  141. it("前驱非终态 → not_amendable(构建的内部不变式)", async () => {
  142. const journal = makeJournal();
  143. putRun(journal, { runId: "runA", status: "running" });
  144. const result = await buildImportedCache({ journal }, "runA");
  145. expect(result).toEqual({ ok: false, reason: "not_amendable" });
  146. });
  147. // 可修订集 = **任意**终态,含 completed(用户裁决:温启动扩展分析是本特性的主用例之一)。
  148. // 刻意与 plain resume 的可恢复集(stopped)不同。
  149. it.each(["completed", "errored", "stopped"] as const)("终态 %s 都可修订", async (status) => {
  150. const journal = makeJournal();
  151. putRun(journal, { runId: "runA", status });
  152. const result = await buildImportedCache({ journal }, "runA");
  153. expect(result.ok).toBe(true);
  154. });
  155. it("已完结 ask 缺 messageBoundary → missing_boundaries(整体拒绝)", async () => {
  156. const journal = makeJournal();
  157. putRun(journal, { runId: "runA" });
  158. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  159. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  160. putAsk(journal, { runId: "runA", actor, seq: 1 });
  161. const result = await buildImportedCache({ journal }, "runA");
  162. expect(result).toEqual({ ok: false, reason: "missing_boundaries" });
  163. });
  164. // 未完结的 ask 从不进导入前缀,所以它们没有边界是正常的——门只看 completed 行。
  165. it("failed / running 的 ask 无边界不触发门", async () => {
  166. const journal = makeJournal();
  167. putRun(journal, { runId: "runA" });
  168. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  169. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  170. putAsk(journal, { runId: "runA", actor, seq: 1, status: "failed" });
  171. putAsk(journal, { runId: "runA", actor, seq: 2, status: "running", ordinal: 3 });
  172. const result = await buildImportedCache({ journal }, "runA");
  173. expect(result.ok).toBe(true);
  174. });
  175. });
  176. // amend 的预检(docs/execution-engine.md「Amend-resume」):在停止前驱**之前**判定,所以不看状态——
  177. // 在飞的前驱通过预检,随后被停下;被拒的 amend 因此永远不会留下一个白白停掉的 run。
  178. describe("preflightAmendImport — 停止之前的两道门", () => {
  179. it("前驱不存在 → run_not_found", () => {
  180. expect(preflightAmendImport(makeJournal(), "missing")).toEqual({
  181. ok: false,
  182. reason: "run_not_found",
  183. });
  184. });
  185. it.each(["running", "pending", "completed", "errored", "stopped"] as const)(
  186. "状态 %s 的前驱通过预检并交出记录",
  187. (status) => {
  188. const journal = makeJournal();
  189. putRun(journal, { runId: "runA", status });
  190. const result = preflightAmendImport(journal, "runA");
  191. expect(result.ok).toBe(true);
  192. if (result.ok) expect(result.run.runId).toBe("runA");
  193. },
  194. );
  195. it("在飞前驱的已完结 ask 缺边界 → missing_boundaries,未完结的 ask 无边界不触发", () => {
  196. const journal = makeJournal();
  197. putRun(journal, { runId: "runA", status: "running" });
  198. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  199. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  200. putAsk(journal, { runId: "runA", actor, seq: 1, status: "running", ordinal: 2 });
  201. expect(preflightAmendImport(journal, "runA").ok).toBe(true);
  202. putAsk(journal, { runId: "runA", actor, seq: 2, ordinal: 3 });
  203. expect(preflightAmendImport(journal, "runA")).toEqual({
  204. ok: false,
  205. reason: "missing_boundaries",
  206. });
  207. });
  208. });
  209. describe("buildImportedCache — actor 前缀", () => {
  210. it("收下全 completed 前缀,带 result / stats / 边界", async () => {
  211. const journal = makeJournal();
  212. putRun(journal, { runId: "runA" });
  213. const actor = putActor(journal, {
  214. runId: "runA",
  215. name: "worker",
  216. sessionId: "sess-A",
  217. resolvedModel: "anthropic/claude-x",
  218. });
  219. const stats = { inputTokens: 3, outputTokens: 4, totalTokens: 7 };
  220. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2, stats });
  221. putAsk(journal, { runId: "runA", actor, seq: 1, messageBoundary: 6 });
  222. const result = await buildImportedCache({ journal }, "runA");
  223. expect(result.ok).toBe(true);
  224. if (!result.ok) return;
  225. expect(result.resumedFrom).toBe("runA");
  226. const candidate = result.cache.actors.get("worker");
  227. expect(candidate).toEqual({
  228. persona: PERSONA,
  229. entries: [
  230. { inputHash: "hash-0", result: "answer-0", messageBoundary: 2, stats },
  231. { inputHash: "hash-1", result: "answer-1", messageBoundary: 6 },
  232. ],
  233. transcriptSourceSessionId: "sess-A",
  234. resolvedModel: "anthropic/claude-x",
  235. });
  236. });
  237. // failed ask 终结可导前缀:它自己不导入(失败对新 run 无约束力),其后的更不导入——
  238. // 跳过它去导入后续条目会走私上下文(那一轮的问答仍在源会话转录里)。
  239. it("前缀停在 failed 处", async () => {
  240. const journal = makeJournal();
  241. putRun(journal, { runId: "runA" });
  242. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  243. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  244. putAsk(journal, { runId: "runA", actor, seq: 1, status: "failed" });
  245. putAsk(journal, { runId: "runA", actor, seq: 2, messageBoundary: 9, ordinal: 3 });
  246. const result = await buildImportedCache({ journal }, "runA");
  247. expect(result.ok).toBe(true);
  248. if (!result.ok) return;
  249. expect(result.cache.actors.get("worker")?.entries).toHaveLength(1);
  250. });
  251. it("前缀停在 running 处(崩溃中的 ask 不导入)", async () => {
  252. const journal = makeJournal();
  253. putRun(journal, { runId: "runA", status: "stopped" });
  254. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  255. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  256. putAsk(journal, { runId: "runA", actor, seq: 1, status: "running" });
  257. const result = await buildImportedCache({ journal }, "runA");
  258. expect(result.ok).toBe(true);
  259. if (!result.ok) return;
  260. expect(result.cache.actors.get("worker")?.entries).toHaveLength(1);
  261. });
  262. it("前缀停在序号空洞处", async () => {
  263. const journal = makeJournal();
  264. putRun(journal, { runId: "runA" });
  265. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  266. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  267. putAsk(journal, { runId: "runA", actor, seq: 2, messageBoundary: 8, ordinal: 3 });
  268. const result = await buildImportedCache({ journal }, "runA");
  269. expect(result.ok).toBe(true);
  270. if (!result.ok) return;
  271. expect(result.cache.actors.get("worker")?.entries).toHaveLength(1);
  272. });
  273. it("空前缀(seq 0 就失败)不产候选", async () => {
  274. const journal = makeJournal();
  275. putRun(journal, { runId: "runA", status: "errored" });
  276. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  277. putAsk(journal, { runId: "runA", actor, seq: 0, status: "failed" });
  278. const result = await buildImportedCache({ journal }, "runA");
  279. expect(result.ok).toBe(true);
  280. if (!result.ok) return;
  281. expect(result.cache.actors.size).toBe(0);
  282. });
  283. it("匿名 actor 不产候选(名字是缓存身份键)", async () => {
  284. const journal = makeJournal();
  285. putRun(journal, { runId: "runA" });
  286. const actor = putActor(journal, { runId: "runA", sessionId: "sess-A" });
  287. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  288. const result = await buildImportedCache({ journal }, "runA");
  289. expect(result.ok).toBe(true);
  290. if (!result.ok) return;
  291. expect(result.cache.actors.size).toBe(0);
  292. });
  293. // 重名两个都不收:按名取候选在重名前驱上是掷骰子,错挑的代价是把另一个 actor 的会话前缀
  294. // 当成本 actor 的上文。引擎的 DuplicateActorName 是新加的运行期不变式,早于它的 journal
  295. // 里可以真的存在重名行。
  296. it("前驱内重名 actor 全部跳过", async () => {
  297. const journal = makeJournal();
  298. putRun(journal, { runId: "runA" });
  299. const first = putActor(journal, {
  300. runId: "runA",
  301. name: "worker",
  302. siteId: "actor#1",
  303. sessionId: "sess-1",
  304. });
  305. const second = putActor(journal, {
  306. runId: "runA",
  307. name: "worker",
  308. siteId: "actor#2",
  309. sessionId: "sess-2",
  310. });
  311. putAsk(journal, { runId: "runA", actor: first, seq: 0, messageBoundary: 2 });
  312. putAsk(journal, { runId: "runA", actor: second, seq: 0, siteId: "ask#2", messageBoundary: 3 });
  313. const result = await buildImportedCache({ journal }, "runA");
  314. expect(result.ok).toBe(true);
  315. if (!result.ok) return;
  316. expect(result.cache.actors.size).toBe(0);
  317. });
  318. it("persona 缺席的 actor 行不产候选", async () => {
  319. const journal = makeJournal();
  320. putRun(journal, { runId: "runA" });
  321. journal.putActor({
  322. runId: "runA",
  323. siteId: "actor#1",
  324. ordinal: 1,
  325. name: "worker",
  326. sessionId: "s",
  327. });
  328. putAsk(journal, {
  329. runId: "runA",
  330. actor: { siteId: "actor#1", ordinal: 1 },
  331. seq: 0,
  332. messageBoundary: 2,
  333. });
  334. const result = await buildImportedCache({ journal }, "runA");
  335. expect(result.ok).toBe(true);
  336. if (!result.ok) return;
  337. expect(result.cache.actors.size).toBe(0);
  338. });
  339. });
  340. describe("buildImportedCache — 转录源解析", () => {
  341. // 链式修订:B 里该 actor 全程命中 ⇒ B 没给它建会话;C 从 B 修订时,转录源在 A。
  342. it("沿 resumed_from 走两跳找到会话与 pin", async () => {
  343. const journal = makeJournal();
  344. putRun(journal, { runId: "runA" });
  345. putActor(journal, {
  346. runId: "runA",
  347. name: "worker",
  348. sessionId: "sess-A",
  349. resolvedModel: "anthropic/claude-a",
  350. });
  351. putRun(journal, { runId: "runB", resumedFrom: "runA" });
  352. putActor(journal, { runId: "runB", name: "worker", siteId: "actor#7" });
  353. putRun(journal, { runId: "runC", resumedFrom: "runB" });
  354. const actorC = putActor(journal, { runId: "runC", name: "worker", siteId: "actor#9" });
  355. putAsk(journal, { runId: "runC", actor: actorC, seq: 0, messageBoundary: 4 });
  356. const result = await buildImportedCache({ journal }, "runC");
  357. expect(result.ok).toBe(true);
  358. if (!result.ok) return;
  359. const candidate = result.cache.actors.get("worker");
  360. expect(candidate?.transcriptSourceSessionId).toBe("sess-A");
  361. // pin 与会话取自同一行:承诺的是「接续**这段**转录时别换模型」。
  362. expect(candidate?.resolvedModel).toBe("anthropic/claude-a");
  363. });
  364. it("链末无会话 → 弃该候选(全新重跑),其余 actor 不受影响", async () => {
  365. const journal = makeJournal();
  366. putRun(journal, { runId: "runA" });
  367. putActor(journal, { runId: "runA", name: "worker", siteId: "actor#1" });
  368. putRun(journal, { runId: "runB", resumedFrom: "runA" });
  369. const orphan = putActor(journal, { runId: "runB", name: "worker", siteId: "actor#1" });
  370. const kept = putActor(journal, {
  371. runId: "runB",
  372. name: "keeper",
  373. siteId: "actor#2",
  374. sessionId: "sess-keeper",
  375. });
  376. putAsk(journal, { runId: "runB", actor: orphan, seq: 0, messageBoundary: 2 });
  377. putAsk(journal, { runId: "runB", actor: kept, seq: 0, siteId: "ask#2", messageBoundary: 3 });
  378. const result = await buildImportedCache({ journal }, "runB");
  379. expect(result.ok).toBe(true);
  380. if (!result.ok) return;
  381. expect(result.cache.actors.has("worker")).toBe(false);
  382. expect(result.cache.actors.get("keeper")?.transcriptSourceSessionId).toBe("sess-keeper");
  383. });
  384. it("链上出现重名 → 停止上溯、弃候选", async () => {
  385. const journal = makeJournal();
  386. putRun(journal, { runId: "runA" });
  387. putActor(journal, { runId: "runA", name: "worker", siteId: "actor#1", sessionId: "sess-A1" });
  388. putActor(journal, { runId: "runA", name: "worker", siteId: "actor#2", sessionId: "sess-A2" });
  389. putRun(journal, { runId: "runB", resumedFrom: "runA" });
  390. const actorB = putActor(journal, { runId: "runB", name: "worker", siteId: "actor#1" });
  391. putAsk(journal, { runId: "runB", actor: actorB, seq: 0, messageBoundary: 2 });
  392. const result = await buildImportedCache({ journal }, "runB");
  393. expect(result.ok).toBe(true);
  394. if (!result.ok) return;
  395. expect(result.cache.actors.size).toBe(0);
  396. });
  397. // 纯防御:supersede 只指向已终结的更早 run,构造不出环;但损坏数据不该变成死循环。
  398. it("resumed_from 成环时终止而不是死循环", async () => {
  399. const journal = makeJournal();
  400. putRun(journal, { runId: "runA", resumedFrom: "runB" });
  401. putActor(journal, { runId: "runA", name: "worker", siteId: "actor#1" });
  402. putRun(journal, { runId: "runB", resumedFrom: "runA" });
  403. const actorB = putActor(journal, { runId: "runB", name: "worker", siteId: "actor#1" });
  404. putAsk(journal, { runId: "runB", actor: actorB, seq: 0, messageBoundary: 2 });
  405. const result = await buildImportedCache({ journal }, "runB");
  406. expect(result.ok).toBe(true);
  407. if (!result.ok) return;
  408. expect(result.cache.actors.size).toBe(0);
  409. });
  410. // 源诚实性检查:会话被清理 / 被截断到边界以下时在构建期就弃候选,driver 侧的
  411. // DriverError 因此退化成 corruption 级兜底而不是一条可达的用户路径。
  412. it("源会话短于边界 → 弃候选(转录面在场时)", async () => {
  413. const journal = makeJournal();
  414. seedSimplePredecessor(journal);
  415. const short = await buildImportedCache(
  416. { actorTranscriptStore: transcriptsWith({ "sess-A": 4 }), journal },
  417. "runA",
  418. );
  419. expect(short.ok).toBe(true);
  420. if (!short.ok) return;
  421. expect(short.cache.actors.size).toBe(0);
  422. const enough = await buildImportedCache(
  423. { actorTranscriptStore: transcriptsWith({ "sess-A": 5 }), journal },
  424. "runA",
  425. );
  426. expect(enough.ok).toBe(true);
  427. if (!enough.ok) return;
  428. expect(enough.cache.actors.size).toBe(1);
  429. });
  430. it("源会话读不到 → 弃候选", async () => {
  431. const journal = makeJournal();
  432. seedSimplePredecessor(journal);
  433. const result = await buildImportedCache(
  434. { actorTranscriptStore: transcriptsWith({}), journal },
  435. "runA",
  436. );
  437. expect(result.ok).toBe(true);
  438. if (!result.ok) return;
  439. expect(result.cache.actors.size).toBe(0);
  440. });
  441. // 转录面缺席的装配(无会话存储):候选照收,兑现由 driver 把关。
  442. it("无转录面时不做诚实性检查", async () => {
  443. const journal = makeJournal();
  444. seedSimplePredecessor(journal);
  445. const result = await buildImportedCache({ journal }, "runA");
  446. expect(result.ok).toBe(true);
  447. if (!result.ok) return;
  448. expect(result.cache.actors.size).toBe(1);
  449. });
  450. });
  451. /**
  452. * 「一条完结 ask(边界 3)+ 紧随其后一条在飞 ask」的前驱,转录源是它自己的会话 `sess-A`。
  453. * 这正是「修订一个跑到一半的 run」最常见的形状。
  454. */
  455. function seedInFlightPredecessor(journal: InMemoryJournalStore, runId = "runA"): void {
  456. putRun(journal, { runId, status: "stopped" });
  457. const actor = putActor(journal, { runId, name: "worker", sessionId: "sess-A" });
  458. putAsk(journal, { runId, actor, seq: 0, messageBoundary: 3 });
  459. putAsk(journal, { runId, actor, seq: 1, status: "running", inputHash: "hash-live" });
  460. }
  461. // 在飞 ask 的接续(docs/execution-engine.md「What is imported」):前驱停下时还在飞的那条 ask
  462. // 没有结果可导入,导入的是**它已经跑出来的那段转录**。
  463. describe("buildImportedCache — 在飞 ask", () => {
  464. it("前缀之后的 running 行 → inFlight 带整个会话的消息数", async () => {
  465. const journal = makeJournal();
  466. seedInFlightPredecessor(journal);
  467. const result = await buildImportedCache(
  468. { actorTranscriptStore: transcriptsWith({ "sess-A": 7 }), journal },
  469. "runA",
  470. );
  471. expect(result.ok).toBe(true);
  472. if (!result.ok) return;
  473. const candidate = result.cache.actors.get("worker");
  474. expect(candidate?.entries).toHaveLength(1);
  475. // 边界是**整个会话**的条数(含那半场未完的问答),不是某一条 ask 的记账边界。
  476. expect(candidate?.inFlight).toEqual({ inputHash: "hash-live", messageBoundary: 7 });
  477. });
  478. // 扇出第一轮在飞时被修订:一条都没做完的候选照样是候选。
  479. it("空前缀 + 在飞 ask → 候选带 inFlight、entries 为空", async () => {
  480. const journal = makeJournal();
  481. putRun(journal, { runId: "runA", status: "stopped" });
  482. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  483. putAsk(journal, { runId: "runA", actor, seq: 0, status: "running", inputHash: "hash-live" });
  484. const result = await buildImportedCache(
  485. { actorTranscriptStore: transcriptsWith({ "sess-A": 2 }), journal },
  486. "runA",
  487. );
  488. expect(result.ok).toBe(true);
  489. if (!result.ok) return;
  490. const candidate = result.cache.actors.get("worker");
  491. expect(candidate?.entries).toEqual([]);
  492. expect(candidate?.inFlight).toEqual({ inputHash: "hash-live", messageBoundary: 2 });
  493. });
  494. it("前缀之后是 failed 行 → 不接续,前缀照收", async () => {
  495. const journal = makeJournal();
  496. putRun(journal, { runId: "runA", status: "errored" });
  497. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  498. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 3 });
  499. putAsk(journal, { runId: "runA", actor, seq: 1, status: "failed" });
  500. const result = await buildImportedCache(
  501. { actorTranscriptStore: transcriptsWith({ "sess-A": 7 }), journal },
  502. "runA",
  503. );
  504. expect(result.ok).toBe(true);
  505. if (!result.ok) return;
  506. const candidate = result.cache.actors.get("worker");
  507. expect(candidate?.entries).toHaveLength(1);
  508. expect(candidate?.inFlight).toBeUndefined();
  509. });
  510. // 空洞与「running 行不在前缀正后方」是同一件事:紧接前缀的那个位置上没有在飞的 ask。
  511. it("前缀之后是序号空洞 → 不接续", async () => {
  512. const journal = makeJournal();
  513. putRun(journal, { runId: "runA", status: "stopped" });
  514. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  515. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 3 });
  516. putAsk(journal, { runId: "runA", actor, seq: 2, status: "running", ordinal: 3 });
  517. const result = await buildImportedCache(
  518. { actorTranscriptStore: transcriptsWith({ "sess-A": 7 }), journal },
  519. "runA",
  520. );
  521. expect(result.ok).toBe(true);
  522. if (!result.ok) return;
  523. expect(result.cache.actors.get("worker")?.inFlight).toBeUndefined();
  524. });
  525. // 那半场对话只存在于前驱自己的会话里;从更早祖先解析出的源只有完整前缀。
  526. it("转录源来自更早的祖先 → 只带前缀,不接续", async () => {
  527. const journal = makeJournal();
  528. putRun(journal, { runId: "runA" });
  529. putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  530. putRun(journal, { runId: "runB", status: "stopped", resumedFrom: "runA" });
  531. const actorB = putActor(journal, { runId: "runB", name: "worker", siteId: "actor#7" });
  532. putAsk(journal, { runId: "runB", actor: actorB, seq: 0, messageBoundary: 3 });
  533. putAsk(journal, { runId: "runB", actor: actorB, seq: 1, status: "running" });
  534. const result = await buildImportedCache(
  535. { actorTranscriptStore: transcriptsWith({ "sess-A": 9 }), journal },
  536. "runB",
  537. );
  538. expect(result.ok).toBe(true);
  539. if (!result.ok) return;
  540. const candidate = result.cache.actors.get("worker");
  541. expect(candidate?.transcriptSourceSessionId).toBe("sess-A");
  542. expect(candidate?.entries).toHaveLength(1);
  543. expect(candidate?.inFlight).toBeUndefined();
  544. });
  545. // 排队却从未派发的 ask 没有多出来的转录可带;种子的 messageCount 也绝不能等于前缀边界
  546. // (那已经是前缀自己的位置),更不能是 0。
  547. it("会话条数不严格大于前缀边界 → 不接续", async () => {
  548. const journal = makeJournal();
  549. seedInFlightPredecessor(journal);
  550. const result = await buildImportedCache(
  551. { actorTranscriptStore: transcriptsWith({ "sess-A": 3 }), journal },
  552. "runA",
  553. );
  554. expect(result.ok).toBe(true);
  555. if (!result.ok) return;
  556. const candidate = result.cache.actors.get("worker");
  557. expect(candidate?.entries).toHaveLength(1);
  558. expect(candidate?.inFlight).toBeUndefined();
  559. });
  560. it("空前缀且会话为空 → 整个候选都不产(没有任何可接续的东西)", async () => {
  561. const journal = makeJournal();
  562. putRun(journal, { runId: "runA", status: "stopped" });
  563. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  564. putAsk(journal, { runId: "runA", actor, seq: 0, status: "running" });
  565. const result = await buildImportedCache(
  566. { actorTranscriptStore: transcriptsWith({ "sess-A": 0 }), journal },
  567. "runA",
  568. );
  569. expect(result.ok).toBe(true);
  570. if (!result.ok) return;
  571. expect(result.cache.actors.size).toBe(0);
  572. });
  573. it("无转录面 → 不接续(数不出接续位置),前缀照收", async () => {
  574. const journal = makeJournal();
  575. seedInFlightPredecessor(journal);
  576. const result = await buildImportedCache({ journal }, "runA");
  577. expect(result.ok).toBe(true);
  578. if (!result.ok) return;
  579. const candidate = result.cache.actors.get("worker");
  580. expect(candidate?.entries).toHaveLength(1);
  581. expect(candidate?.inFlight).toBeUndefined();
  582. });
  583. it("源会话读不到 → 整个候选弃置", async () => {
  584. const journal = makeJournal();
  585. seedInFlightPredecessor(journal);
  586. const result = await buildImportedCache(
  587. { actorTranscriptStore: transcriptsWith({}), journal },
  588. "runA",
  589. );
  590. expect(result.ok).toBe(true);
  591. if (!result.ok) return;
  592. expect(result.cache.actors.size).toBe(0);
  593. });
  594. });
  595. // 静默闸门(docs/execution-engine.md「Tool contract and refusals」的 import 行):被取代的前驱
  596. // 刚被 abort,它的 turn 可能还在落最后几条消息——此刻数出来的条数不可信。
  597. describe("buildImportedCache — 会话静默", () => {
  598. it("会话仍在被写入 → 只带前缀,不接续", async () => {
  599. const journal = makeJournal();
  600. seedInFlightPredecessor(journal);
  601. const result = await buildImportedCache(
  602. { actorTranscriptStore: transcriptsWith({ "sess-A": 7 }), journal },
  603. "runA",
  604. { quietSessions: new Set<string>() },
  605. );
  606. expect(result.ok).toBe(true);
  607. if (!result.ok) return;
  608. const candidate = result.cache.actors.get("worker");
  609. expect(candidate?.entries).toHaveLength(1);
  610. expect(candidate?.inFlight).toBeUndefined();
  611. });
  612. it("会话在静默集合里 → 照常接续", async () => {
  613. const journal = makeJournal();
  614. seedInFlightPredecessor(journal);
  615. const result = await buildImportedCache(
  616. { actorTranscriptStore: transcriptsWith({ "sess-A": 7 }), journal },
  617. "runA",
  618. { quietSessions: new Set(["sess-A"]) },
  619. );
  620. expect(result.ok).toBe(true);
  621. if (!result.ok) return;
  622. expect(result.cache.actors.get("worker")?.inFlight).toEqual({
  623. inputHash: "hash-live",
  624. messageBoundary: 7,
  625. });
  626. });
  627. // resume 侧的重建不带这个集合:那时前驱早已结算、进程里没有它的 driver,没有东西在写。
  628. // 闸门若把「缺席」读成「都不静默」,重建出的表就会比提交时那张少一个 inFlight。
  629. it("静默集合缺席 = 全部静默(resume 重建与提交时构建给出同一张表)", async () => {
  630. const journal = makeJournal();
  631. seedInFlightPredecessor(journal);
  632. const deps = { actorTranscriptStore: transcriptsWith({ "sess-A": 7 }), journal };
  633. const built = await buildImportedCache(deps, "runA", { quietSessions: new Set(["sess-A"]) });
  634. const rebuilt = await buildImportedCache(deps, "runA");
  635. expect(rebuilt).toEqual(built);
  636. });
  637. });
  638. describe("buildImportedCache — world 表", () => {
  639. it("按内容哈希分队列,队内保持 journal 插入序", async () => {
  640. const journal = makeJournal();
  641. putRun(journal, { runId: "runA" });
  642. putWorld(journal, {
  643. runId: "runA",
  644. siteId: "w#1",
  645. ordinal: 1,
  646. inputHash: "h1",
  647. result: "first",
  648. });
  649. putWorld(journal, {
  650. runId: "runA",
  651. siteId: "w#2",
  652. ordinal: 1,
  653. inputHash: "h2",
  654. result: "other",
  655. });
  656. putWorld(journal, {
  657. runId: "runA",
  658. siteId: "w#1",
  659. ordinal: 2,
  660. inputHash: "h1",
  661. result: "second",
  662. });
  663. const result = await buildImportedCache({ journal }, "runA");
  664. expect(result.ok).toBe(true);
  665. if (!result.ok) return;
  666. expect(result.cache.world.get("h1")?.map((entry) => entry.result)).toEqual(["first", "second"]);
  667. expect(result.cache.world.get("h2")?.map((entry) => entry.result)).toEqual(["other"]);
  668. });
  669. // world-run 的导入是**安全特性**:修订续跑绝不静默重放一次已 journal 的效应。
  670. it("world-run 与 world-read 同表,report / ask 不入表", async () => {
  671. const journal = makeJournal();
  672. putRun(journal, { runId: "runA" });
  673. putWorld(journal, {
  674. runId: "runA",
  675. siteId: "w#1",
  676. ordinal: 1,
  677. kind: "world-run",
  678. inputHash: "hrun",
  679. result: { exitCode: 0 },
  680. });
  681. journal.putNode({
  682. runId: "runA",
  683. siteId: "report#1",
  684. ordinal: 1,
  685. kind: "report",
  686. inputHash: "hreport",
  687. status: "completed",
  688. result: "progress",
  689. });
  690. const result = await buildImportedCache({ journal }, "runA");
  691. expect(result.ok).toBe(true);
  692. if (!result.ok) return;
  693. expect(result.cache.world.get("hrun")?.[0]).toEqual({
  694. inputHash: "hrun",
  695. kind: "world-run",
  696. result: { exitCode: 0 },
  697. });
  698. expect(result.cache.world.has("hreport")).toBe(false);
  699. });
  700. it("失败的 world 节点不入表(重新执行)", async () => {
  701. const journal = makeJournal();
  702. putRun(journal, { runId: "runA", status: "errored" });
  703. putWorld(journal, {
  704. runId: "runA",
  705. siteId: "w#1",
  706. ordinal: 1,
  707. inputHash: "h1",
  708. status: "failed",
  709. });
  710. const result = await buildImportedCache({ journal }, "runA");
  711. expect(result.ok).toBe(true);
  712. if (!result.ok) return;
  713. expect(result.cache.world.size).toBe(0);
  714. });
  715. });
  716. // 确定性不是风格偏好而是正确性前提:崩溃后 resume 用同一个函数重建同一张表,两次不等
  717. // 就意味着「重建」变成了「另建一张」。
  718. it("同一份 journal 状态两次构建逐字段相等", async () => {
  719. const journal = makeJournal();
  720. putRun(journal, { runId: "runA" });
  721. const actor = putActor(journal, { runId: "runA", name: "worker", sessionId: "sess-A" });
  722. putAsk(journal, { runId: "runA", actor, seq: 0, messageBoundary: 2 });
  723. putAsk(journal, { runId: "runA", actor, seq: 1, messageBoundary: 5 });
  724. const other = putActor(journal, {
  725. runId: "runA",
  726. name: "reviewer",
  727. siteId: "actor#2",
  728. sessionId: "sess-B",
  729. });
  730. putAsk(journal, { runId: "runA", actor: other, seq: 0, siteId: "ask#2", messageBoundary: 3 });
  731. putWorld(journal, { runId: "runA", siteId: "w#1", ordinal: 1, inputHash: "h1", result: 1 });
  732. putWorld(journal, { runId: "runA", siteId: "w#1", ordinal: 2, inputHash: "h1", result: 2 });
  733. const first = await buildImportedCache({ journal }, "runA");
  734. const second = await buildImportedCache({ journal }, "runA");
  735. expect(first).toEqual(second);
  736. expect(first.ok).toBe(true);
  737. if (!first.ok || !second.ok) return;
  738. // Map 的遍历序也必须一致(引擎不依赖它,但「同一张表」的说法要经得起逐项核对)。
  739. expect([...first.cache.actors.keys()]).toEqual([...second.cache.actors.keys()]);
  740. expect([...first.cache.world.keys()]).toEqual([...second.cache.world.keys()]);
  741. });