dwf-journal-store.test.ts 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031
  1. /**
  2. * SQLite 版 JournalStorePort(dwf_* 表)的测试。
  3. *
  4. * 两层:共享契约套件(与内存实现同一份,来自 `@zcode/dynamic-workflow/testing`)+
  5. * 内存实现根本表达不了的 SQLite 专属语义——跨进程重开后记录还在、事件序号接着长、
  6. * run 删除级联清掉 actor/node/event。后者才是 roadmap step 8 的真正目的。
  7. */
  8. import { mkdtemp, rm } from "node:fs/promises";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { DatabaseSync } from "node:sqlite";
  12. import { afterAll, describe, expect, it } from "vitest";
  13. import type {
  14. ActorRecord,
  15. Caps,
  16. JournalStorePort,
  17. NodeRecord,
  18. RunRecord,
  19. } from "@zcode/dynamic-workflow";
  20. import { runJournalStoreContract } from "@zcode/dynamic-workflow/testing";
  21. import type { DwfRunIntrospectionQueries, DwfRunSessionListItem } from "../src/storage/index.js";
  22. import { createDwfJournalStore, createSqliteSessionStore } from "../src/storage/index.js";
  23. import { runSqliteSessionMigrations } from "../src/storage/session-store/migration-runner.js";
  24. const openDatabases: DatabaseSync[] = [];
  25. /** 每次调用开一个全新的已迁移库;契约套件要求实现之间互不共享状态。 */
  26. function openJournalDb(dbPath = ":memory:"): { db: DatabaseSync; journal: JournalStorePort } {
  27. const db = new DatabaseSync(dbPath);
  28. openDatabases.push(db);
  29. runSqliteSessionMigrations(db, dbPath);
  30. return { db, journal: createDwfJournalStore(db) };
  31. }
  32. afterAll(() => {
  33. for (const db of openDatabases) {
  34. try {
  35. db.close();
  36. } catch {
  37. // 测试用库;关闭失败不该掩盖真正的断言失败。
  38. }
  39. }
  40. });
  41. runJournalStoreContract(() => openJournalDb().journal);
  42. const CAPS: Caps = { maxConcurrency: 4 };
  43. const RUN: RunRecord = {
  44. runId: "dwf_run_1",
  45. parentSessionId: "ses_parent",
  46. cwd: "/repo",
  47. scriptText: "const planner = agent('planner');",
  48. scriptHash: "sha-1",
  49. caps: CAPS,
  50. spentTokens: 0,
  51. status: "running",
  52. };
  53. const ACTOR: ActorRecord = {
  54. runId: RUN.runId,
  55. siteId: "actor#1",
  56. ordinal: 1,
  57. name: "planner",
  58. persona: { name: "planner", system: "plan carefully" },
  59. sessionId: "ses_actor",
  60. // 冻结的 persona 与子代理实际跑的模型分列存放,两者都必须跨重开存活。
  61. resolvedModel: "anthropic/haiku",
  62. };
  63. const NODE: NodeRecord = {
  64. runId: RUN.runId,
  65. siteId: "ask#1",
  66. ordinal: 1,
  67. kind: "ask",
  68. actorSiteId: "actor#1",
  69. actorOrdinal: 1,
  70. actorSeq: 0,
  71. inputHash: "abc123",
  72. status: "completed",
  73. result: { plan: ["step one", "step two"], nested: { depth: 2 } },
  74. stats: { tokens: 120, toolCalls: 2, turns: 1 },
  75. };
  76. describe("SQLite dwf journal store", () => {
  77. it("survives closing and reopening the database file", async () => {
  78. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-journal-"));
  79. const dbPath = join(tempRoot, "session.sqlite");
  80. try {
  81. const first = createSqliteSessionStore({ dbPath });
  82. const journal = first.workflowJournalStore();
  83. journal.createRun(RUN);
  84. journal.putActor(ACTOR);
  85. journal.putNode(NODE);
  86. journal.appendEvent(RUN.runId, { type: "run-started", runId: RUN.runId, caps: CAPS });
  87. journal.appendEvent(RUN.runId, { type: "log", message: "before the crash" });
  88. // 结算前最后一次用量回写:resume 必须看到它,而不是从零重来。
  89. journal.updateRunUsage(RUN.runId, 120);
  90. first.close();
  91. const second = createSqliteSessionStore({ dbPath });
  92. const resumed = second.workflowJournalStore();
  93. expect(resumed.getRun(RUN.runId)).toEqual({ ...RUN, spentTokens: 120 });
  94. expect(resumed.getActor(RUN.runId, "actor#1", 1)).toEqual(ACTOR);
  95. expect(resumed.getNode(RUN.runId, "ask#1", 1)).toEqual(NODE);
  96. expect(resumed.listActors(RUN.runId, { withPersona: true })).toEqual([ACTOR]);
  97. expect(resumed.listNodes(RUN.runId, { kinds: "all", withResult: true })).toEqual([NODE]);
  98. expect(
  99. resumed.listEvents(RUN.runId, { types: "all", reportItems: "all" }).map((e) => e.sequence),
  100. ).toEqual([0, 1]);
  101. // 事件序号跨重开继续增长(engine-assigned、monotonic across resumes)。
  102. // 断言用 toMatchObject:追加还会带回写入时刻(StoredEvent.timeCreated),而这条用例
  103. // 说的是序号,不是时钟——时钟由契约套件的 timeCreated 用例钉住。
  104. expect(resumed.appendEvent(RUN.runId, { type: "log", message: "after resume" })).toMatchObject({
  105. sequence: 2,
  106. event: { type: "log", message: "after resume" },
  107. });
  108. expect(
  109. resumed.listEvents(RUN.runId, { types: "all", reportItems: "all" }).at(-1)?.event,
  110. ).toEqual({
  111. type: "log",
  112. message: "after resume",
  113. });
  114. second.close();
  115. } finally {
  116. await rm(tempRoot, { force: true, recursive: true });
  117. }
  118. });
  119. // `caps_max_concurrency` 的第二个写入者(docs/dynamic-workflow/concurrency.md
  120. // 「Two bounds on a run」)。契约套件已经钉住读写语义;这里钉的是内存实现表达不了的两件事:
  121. // UPDATE 真的只列了这一列(其余列逐字不动),以及新值跨进程重开还在——resume 沿用的正是它。
  122. it("retunes caps_max_concurrency in place, touching no other column", async () => {
  123. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-journal-caps-"));
  124. const dbPath = join(tempRoot, "session.sqlite");
  125. try {
  126. const first = createSqliteSessionStore({ dbPath });
  127. const journal = first.workflowJournalStore();
  128. journal.createRun(RUN);
  129. journal.updateRunUsage(RUN.runId, 120);
  130. journal.updateRunCaps(RUN.runId, { maxConcurrency: 2 });
  131. // 同一个库里,除 caps 之外的每一列都还是建 run 时的那一份。
  132. expect(journal.getRun(RUN.runId)).toEqual({
  133. ...RUN,
  134. caps: { maxConcurrency: 2 },
  135. spentTokens: 120,
  136. });
  137. first.close();
  138. const second = createSqliteSessionStore({ dbPath });
  139. expect(second.workflowJournalStore().getRun(RUN.runId)?.caps).toEqual({ maxConcurrency: 2 });
  140. second.close();
  141. } finally {
  142. await rm(tempRoot, { force: true, recursive: true });
  143. }
  144. });
  145. it("cascades a run delete to its actors, nodes and events", () => {
  146. const { db, journal } = openJournalDb();
  147. journal.createRun(RUN);
  148. journal.createRun({ ...RUN, runId: "dwf_run_2" });
  149. journal.putActor(ACTOR);
  150. journal.putNode(NODE);
  151. journal.appendEvent(RUN.runId, { type: "log", message: "doomed" });
  152. journal.putActor({ ...ACTOR, runId: "dwf_run_2" });
  153. db.prepare("delete from dwf_run where id = ?").run(RUN.runId);
  154. expect(journal.getRun(RUN.runId)).toBeUndefined();
  155. expect(journal.listActors(RUN.runId, { withPersona: true })).toEqual([]);
  156. expect(journal.listNodes(RUN.runId, { kinds: "all", withResult: true })).toEqual([]);
  157. expect(journal.listEvents(RUN.runId, { types: "all", reportItems: "all" })).toEqual([]);
  158. // 级联只吃掉被删 run 的行。
  159. expect(journal.listActors("dwf_run_2", { withPersona: true })).toHaveLength(1);
  160. });
  161. it("rejects an actor belonging to no run", () => {
  162. // FK 是开着的(migration runner 设 pragma foreign_keys = on),孤儿写入必须当场失败,
  163. // 而不是留下一条永远读不回来的记录。孤儿事件与 null/absent result 的语义已由共享契约
  164. // 套件在两个实现上一起把关,这里只补 FK 本身确实生效这一点。
  165. const { journal } = openJournalDb();
  166. expect(() => journal.putActor({ ...ACTOR, runId: "ghost" })).toThrow();
  167. });
  168. // run 产物的列。内存实现表达不了「列存在」与「旧行解码」这两件事。
  169. it("dwf_run 带 result_json 列", () => {
  170. const { db } = openJournalDb();
  171. const columns = (
  172. db.prepare("select name from pragma_table_info('dwf_run')").all() as unknown as {
  173. name: string;
  174. }[]
  175. ).map((row) => row.name);
  176. expect(columns).toContain("result_json");
  177. });
  178. it("run 产物跨重开数据库文件存活", async () => {
  179. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-result-"));
  180. const dbPath = join(tempRoot, "session.sqlite");
  181. try {
  182. const first = createSqliteSessionStore({ dbPath });
  183. const journal = first.workflowJournalStore();
  184. journal.createRun(RUN);
  185. journal.updateRunStatus(RUN.runId, "completed", {
  186. result: { report: "done", steps: [1, 2, 3] },
  187. });
  188. first.close();
  189. // 桌面实测 bug 的持久化面:进程一退,产物必须仍能从 journal 读回来。
  190. const second = createSqliteSessionStore({ dbPath });
  191. const resumed = second.workflowJournalStore().getRun(RUN.runId);
  192. expect(resumed?.status).toBe("completed");
  193. expect(resumed?.result).toEqual({ report: "done", steps: [1, 2, 3] });
  194. second.close();
  195. } finally {
  196. await rm(tempRoot, { force: true, recursive: true });
  197. }
  198. });
  199. it("result_json 为 NULL 的旧行解码不炸且 result 缺席", () => {
  200. // 0020 之前落库的 run 行:列是新加的、值为 NULL。decodeRun 必须回一条没有 result 键的
  201. // 记录,而不是 undefined 值或抛错——否则升级后所有历史 run 都读不出来。
  202. const { db, journal } = openJournalDb();
  203. journal.createRun(RUN);
  204. db.prepare("update dwf_run set result_json = null where id = ?").run(RUN.runId);
  205. const record = journal.getRun(RUN.runId);
  206. expect(record).toEqual(RUN);
  207. expect("result" in (record ?? {})).toBe(false);
  208. });
  209. // actor 的档位解析结果。同样是内存实现表达不了的两件事。
  210. it("dwf_actor 带 resolved_model 列", () => {
  211. const { db } = openJournalDb();
  212. const columns = (
  213. db.prepare("select name from pragma_table_info('dwf_actor')").all() as unknown as {
  214. name: string;
  215. }[]
  216. ).map((row) => row.name);
  217. expect(columns).toContain("resolved_model");
  218. });
  219. it("resolved_model 为 NULL 的旧行解码不炸且 resolvedModel 缺席", () => {
  220. // 0023 之前落库的 actor 行(以及宿主还没解析过的行):必须解成没有 resolvedModel 键的
  221. // 记录,而不是 undefined 值或抛错。persona 里的档位与这一列各自独立缺席。
  222. const { db, journal } = openJournalDb();
  223. journal.createRun(RUN);
  224. journal.putActor(ACTOR);
  225. db.prepare("update dwf_actor set resolved_model = null where run_id = ?").run(RUN.runId);
  226. const record = journal.getActor(RUN.runId, "actor#1", 1);
  227. expect(record).toEqual({ ...ACTOR, resolvedModel: undefined });
  228. expect("resolvedModel" in (record ?? {})).toBe(false);
  229. // persona 仍在 persona_json 里:模型记录丢了不等于身份丢了。
  230. expect(record?.persona?.system).toBe("plan carefully");
  231. });
  232. it("同键重写只换 resolved_model,persona 与 session_id 原样保留", () => {
  233. // 生产里这正是 driver 侧 `journalActorResolvedModel` 的读改写形状:putActor 是整条替换,
  234. // 所以「只更新解析结果」必须由调用方带齐其余字段,而存储层要如实照写。
  235. const { journal } = openJournalDb();
  236. journal.createRun(RUN);
  237. journal.putActor(ACTOR);
  238. journal.putActor({ ...ACTOR, resolvedModel: "anthropic/sonnet" });
  239. expect(journal.getActor(RUN.runId, "actor#1", 1)).toEqual({
  240. ...ACTOR,
  241. resolvedModel: "anthropic/sonnet",
  242. });
  243. expect(journal.listActors(RUN.runId, { withPersona: true })).toHaveLength(1);
  244. });
  245. it("终态与产物一笔写:单条 UPDATE 同时落 status 与 result_json", () => {
  246. // 分两笔写会造出「completed 但产物丢失」的崩溃窗口,正是本列要关死的损失类别。
  247. const { db, journal } = openJournalDb();
  248. journal.createRun(RUN);
  249. journal.updateRunStatus(RUN.runId, "completed", { result: "artifact text" });
  250. const row = db.prepare("select status, result_json from dwf_run where id = ?").get(RUN.runId) as
  251. | { result_json: string | null; status: string }
  252. | undefined;
  253. expect(row?.status).toBe("completed");
  254. expect(row?.result_json).toBe(JSON.stringify("artifact text"));
  255. });
  256. // `kind` 的 CHECK 含 'report'——只有对着真库才能验,内存实现连 CHECK 都没有。
  257. it("dwf_node 接受 kind:\"report\" 并原样回读", () => {
  258. const { journal } = openJournalDb();
  259. journal.createRun(RUN);
  260. const report: NodeRecord = {
  261. runId: RUN.runId,
  262. siteId: "report#1",
  263. ordinal: 1,
  264. kind: "report",
  265. inputHash: "h1",
  266. status: "completed",
  267. result: { finding: "两处重复实现", paths: ["src/a.ts", "src/b.ts"] },
  268. };
  269. journal.putNode(report);
  270. // 整条 toEqual:actor 三列必须缺席地回来(report 没有 actor),status 恒为 completed。
  271. expect(journal.getNode(RUN.runId, "report#1", 1)).toEqual(report);
  272. const stored = journal.getNode(RUN.runId, "report#1", 1);
  273. expect(stored !== undefined && "actorSeq" in stored).toBe(false);
  274. expect(stored !== undefined && "actorSiteId" in stored).toBe(false);
  275. });
  276. it("CHECK 仍然拒绝一个不存在的 kind", () => {
  277. // 重建 CHECK 的意义在于它**还在拦**:放开一个值不等于把闸门拆了。
  278. const { journal } = openJournalDb();
  279. journal.createRun(RUN);
  280. expect(() =>
  281. journal.putNode({
  282. runId: RUN.runId,
  283. siteId: "bogus#1",
  284. ordinal: 1,
  285. kind: "made-up" as NodeRecord["kind"],
  286. inputHash: "h",
  287. status: "completed",
  288. }),
  289. ).toThrow();
  290. });
  291. // `kind` 的 CHECK 含 'world-run'(world.run 的 journal 化命令执行,docs/dynamic-workflow/authoring.md)。
  292. it("dwf_node 接受 kind:\"world-run\" 并原样回读", () => {
  293. const { journal } = openJournalDb();
  294. journal.createRun(RUN);
  295. const worldRun: NodeRecord = {
  296. runId: RUN.runId,
  297. siteId: "world-read#3",
  298. ordinal: 2,
  299. kind: "world-run",
  300. inputHash: "h-run",
  301. status: "completed",
  302. result: { exitCode: 1, stdout: "", stderr: "proof failed" },
  303. };
  304. journal.putNode(worldRun);
  305. expect(journal.getNode(RUN.runId, "world-read#3", 2)).toEqual(worldRun);
  306. });
  307. it("dwf_node 带 input_json 列:有界输入原样回读,ask 行缺席", () => {
  308. // 工作区 transcript 的「what ran」(docs/dynamic-workflow/transcript-and-notifications.md)。
  309. const { db, journal } = openJournalDb();
  310. journal.createRun(RUN);
  311. const worldRun: NodeRecord = {
  312. runId: RUN.runId,
  313. siteId: "world-read#4",
  314. ordinal: 1,
  315. kind: "world-run",
  316. inputHash: "h-in",
  317. input: { op: "run", args: ["pnpm", ["vitest", "run", "--changed"], { timeoutMs: 60_000 }] },
  318. status: "running",
  319. };
  320. journal.putNode(worldRun);
  321. expect(journal.getNode(RUN.runId, "world-read#4", 1)).toEqual(worldRun);
  322. // 结算是整条 upsert:input 必须随行回来,而不是被抹成 NULL。
  323. const settled: NodeRecord = {
  324. ...worldRun,
  325. status: "completed",
  326. result: { exitCode: 1, stdout: "FAIL", stderr: "" },
  327. };
  328. journal.putNode(settled);
  329. expect(journal.getNode(RUN.runId, "world-read#4", 1)).toEqual(settled);
  330. const column = db
  331. .prepare("select input_json from dwf_node where site_id = ?")
  332. .get("world-read#4") as { input_json: string | null };
  333. expect(JSON.parse(column.input_json ?? "null")).toEqual(worldRun.input);
  334. journal.putNode(NODE);
  335. const ask = journal.getNode(RUN.runId, NODE.siteId, NODE.ordinal);
  336. expect(ask !== undefined && "input" in ask).toBe(false);
  337. });
  338. it("input_json 为 NULL 的旧行解码不炸且 input 缺席", () => {
  339. const { db, journal } = openJournalDb();
  340. journal.createRun(RUN);
  341. db.prepare(
  342. `insert into dwf_node (run_id, site_id, ordinal, kind, input_hash, status, result_json, time_created, time_updated)
  343. values (?, ?, ?, 'world-read', 'h', 'completed', ?, 1, 2)`,
  344. ).run(RUN.runId, "world-read#9", 1, JSON.stringify("file body"));
  345. const row = journal.getNode(RUN.runId, "world-read#9", 1);
  346. expect(row).toBeDefined();
  347. expect(row !== undefined && "input" in row).toBe(false);
  348. expect(row?.result).toBe("file body");
  349. });
  350. it("listWorldNodes 只回 world-read / world-run 行,按落库先后,带时间戳与正文字节数、不带正文", () => {
  351. const { journal } = openJournalDb();
  352. const queries = journal as unknown as DwfRunIntrospectionQueries;
  353. journal.createRun(RUN);
  354. journal.putNode(NODE);
  355. journal.putNode({
  356. runId: RUN.runId,
  357. siteId: "world-read#2",
  358. ordinal: 1,
  359. kind: "world-read",
  360. inputHash: "a",
  361. input: { op: "read", args: ["src/x.ts"] },
  362. status: "completed",
  363. result: "export const x = 1;\n",
  364. });
  365. journal.putNode({
  366. runId: RUN.runId,
  367. siteId: "world-read#3",
  368. ordinal: 1,
  369. kind: "world-run",
  370. inputHash: "b",
  371. input: { op: "run", args: ["lake", ["build"]] },
  372. status: "running",
  373. });
  374. journal.putNode({
  375. runId: RUN.runId,
  376. siteId: "report#1",
  377. ordinal: 1,
  378. kind: "report",
  379. inputHash: "r",
  380. status: "completed",
  381. result: { finding: "x" },
  382. });
  383. const rows = queries.listWorldNodes(RUN.runId);
  384. expect(rows.map((row) => row.siteId)).toEqual(["world-read#2", "world-read#3"]);
  385. expect(rows[0]).toMatchObject({
  386. kind: "world-read",
  387. status: "completed",
  388. input: { op: "read", args: ["src/x.ts"] },
  389. resultBytes: JSON.stringify("export const x = 1;\n").length,
  390. });
  391. expect("result" in rows[0]!).toBe(false);
  392. expect(typeof rows[0]!.timeCreated).toBe("number");
  393. expect(typeof rows[0]!.timeUpdated).toBe("number");
  394. expect("resultBytes" in rows[1]!).toBe(false);
  395. expect(queries.listWorldNodes("dwfrun-unknown")).toEqual([]);
  396. });
  397. it("listWorldNodes 用 SQLite 的 JSON 函数在库内算摘要:数组计数、run 的 exitCode 与输出字节数", () => {
  398. const { journal } = openJournalDb();
  399. const queries = journal as unknown as DwfRunIntrospectionQueries;
  400. journal.createRun(RUN);
  401. journal.putNode({
  402. runId: RUN.runId,
  403. siteId: "world-read#1",
  404. ordinal: 1,
  405. kind: "world-read",
  406. inputHash: "g",
  407. input: { op: "glob", args: ["src/**/*.ts"] },
  408. status: "completed",
  409. result: ["src/a.ts", "src/b.ts", "src/c.ts"],
  410. });
  411. journal.putNode({
  412. runId: RUN.runId,
  413. siteId: "world-read#2",
  414. ordinal: 1,
  415. kind: "world-run",
  416. inputHash: "r",
  417. input: { op: "run", args: ["pnpm", ["test"]] },
  418. status: "completed",
  419. result: { exitCode: 1, stdout: "ok\n", stderr: "é" },
  420. });
  421. journal.putNode({
  422. runId: RUN.runId,
  423. siteId: "world-read#3",
  424. ordinal: 1,
  425. kind: "world-read",
  426. inputHash: "s",
  427. input: { op: "git-status", args: [] },
  428. status: "completed",
  429. result: " M src/a.ts\n",
  430. });
  431. journal.putNode({
  432. runId: RUN.runId,
  433. siteId: "world-read#4",
  434. ordinal: 1,
  435. kind: "world-run",
  436. inputHash: "f",
  437. input: { op: "run", args: ["false"] },
  438. status: "failed",
  439. error: { code: "DriverError", message: "boom" },
  440. });
  441. const rows = queries.listWorldNodes(RUN.runId);
  442. expect(rows[0]).toMatchObject({ resultCount: 3 });
  443. expect("exitCode" in rows[0]!).toBe(false);
  444. // stderr 是一个双字节字符:报的是 UTF-8 字节数,不是字符数。
  445. expect(rows[1]).toMatchObject({ exitCode: 1, stdoutBytes: 3, stderrBytes: 2 });
  446. expect("resultCount" in rows[1]!).toBe(false);
  447. // 字符串正文:既不是数组也不是对象,摘要列全部缺席,只有字节数。
  448. expect(rows[2]).toMatchObject({ resultBytes: JSON.stringify(" M src/a.ts\n").length });
  449. expect("resultCount" in rows[2]!).toBe(false);
  450. expect("exitCode" in rows[2]!).toBe(false);
  451. // 失败行没有正文:什么摘要都没有,只有 error。
  452. expect(rows[3]).toMatchObject({ status: "failed", error: { code: "DriverError", message: "boom" } });
  453. expect("resultBytes" in rows[3]!).toBe(false);
  454. expect("exitCode" in rows[3]!).toBe(false);
  455. });
  456. // dwf_event 上的表达式索引不只要存在,还得**真的被用上**:它存在的全部理由是让看板取数
  457. // 不必扫完一条长 run 的整张事件表(那是最大的一张表)。查询计划变了这里就会响。
  458. it("dwf_event 的表达式索引真的服务于按 artifactId 取事件", () => {
  459. const { db } = openJournalDb();
  460. const plan = (
  461. db
  462. .prepare(
  463. `explain query plan
  464. select sequence from dwf_event
  465. where run_id = ? and type = 'report' and json_extract(payload_json, '$.artifactId') = ?
  466. order by sequence`,
  467. )
  468. .all("run_1", "perf") as unknown as { detail: string }[]
  469. )
  470. .map((row) => row.detail)
  471. .join(" | ");
  472. expect(plan).toContain("dwf_event_artifact_idx");
  473. });
  474. });
  475. /**
  476. * 孤儿收敛的窄查询。刻意**不在** `JournalStorePort` 上:引擎从不按父会话找 run,这条查询
  477. * 只服务于宿主侧的收敛(`bootstrap/src/app/dynamic-workflow-run-service.ts` 构造时按能力
  478. * 探测调用它)。内存实现不提供它,所以它的语义只能在这里、对着真库钉住。
  479. */
  480. interface DwfNonTerminalRunQuery {
  481. listNonTerminalRuns(parentSessionId: string): RunRecord[];
  482. }
  483. /**
  484. * 开一个带窄查询的 journal。这里用与宿主侧**同一种**能力探测:方法名一旦漂移,宿主的收敛
  485. * 会静默跳过(回到「孤儿 run 永远 running」那个 bug),所以在这里就要大声失败。
  486. */
  487. function openSweepableJournal(): JournalStorePort & DwfNonTerminalRunQuery {
  488. const { journal } = openJournalDb();
  489. if (typeof (journal as Partial<DwfNonTerminalRunQuery>).listNonTerminalRuns !== "function") {
  490. throw new Error("sqlite dwf journal 缺少 listNonTerminalRuns:宿主侧的孤儿收敛会静默跳过");
  491. }
  492. return journal as JournalStorePort & DwfNonTerminalRunQuery;
  493. }
  494. describe("SQLite dwf journal store — listNonTerminalRuns", () => {
  495. const PARENT = "ses_sweep_parent";
  496. /** 预置一行 dwf_run(只关心父会话与状态)。 */
  497. function seed(
  498. journal: JournalStorePort,
  499. input: { runId: string; status: RunRecord["status"]; parentSessionId?: string },
  500. ): void {
  501. journal.createRun({
  502. runId: input.runId,
  503. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  504. caps: CAPS,
  505. spentTokens: 0,
  506. status: input.status,
  507. });
  508. }
  509. it("只回本父会话的非终态行", () => {
  510. const journal = openSweepableJournal();
  511. seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
  512. seed(journal, { parentSessionId: PARENT, runId: "run_pending", status: "pending" });
  513. seed(journal, { parentSessionId: PARENT, runId: "run_completed", status: "completed" });
  514. seed(journal, { parentSessionId: PARENT, runId: "run_errored", status: "errored" });
  515. seed(journal, { parentSessionId: PARENT, runId: "run_stopped", status: "stopped" });
  516. // 兄弟会话正在飞的 run 与父会话缺席的行都不属于本会话——查全了就会把它们标死。
  517. seed(journal, { parentSessionId: "ses_other", runId: "run_sibling", status: "running" });
  518. seed(journal, { runId: "run_parentless", status: "running" });
  519. const rows = journal.listNonTerminalRuns(PARENT);
  520. expect(rows.map((row) => row.runId).sort()).toEqual(["run_pending", "run_running"]);
  521. // 回的是完整 RunRecord(同一个 decodeRun),收敛策略据 status 判断,不需要二次查询。
  522. expect(rows.every((row) => row.parentSessionId === PARENT)).toBe(true);
  523. expect(rows.find((row) => row.runId === "run_running")?.status).toBe("running");
  524. });
  525. it("收敛写入之后同一个查询返回空(幂等的 SQL 侧依据)", () => {
  526. const journal = openSweepableJournal();
  527. seed(journal, { parentSessionId: PARENT, runId: "run_orphan", status: "running" });
  528. journal.updateRunStatus("run_orphan", "stopped", {
  529. stopReason: "interrupted",
  530. failure: { code: "Interrupted", message: "owning process exited" },
  531. });
  532. expect(journal.listNonTerminalRuns(PARENT)).toEqual([]);
  533. });
  534. it("未知父会话返回空数组", () => {
  535. const journal = openSweepableJournal();
  536. seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
  537. expect(journal.listNonTerminalRuns("ses_never_seen")).toEqual([]);
  538. });
  539. });
  540. /**
  541. * run 内省(`ListWorkflowRuns` / `GetWorkflowRun`)的宿主侧查询面。与 listNonTerminalRuns
  542. * 同款处理:引擎从不枚举 run,所以这些方法不进领域 `JournalStorePort`,内存实现也不提供它们——
  543. * 它们的语义只能在这里、对着真库钉住(docs/dynamic-workflow/launch.md
  544. * 的「枚举查询归属」行)。
  545. */
  546. function openIntrospectableJournal(): {
  547. db: DatabaseSync;
  548. journal: JournalStorePort & DwfRunIntrospectionQueries;
  549. } {
  550. const { db, journal } = openJournalDb();
  551. // 与宿主侧**同一种**能力探测:方法名一旦漂移,两个工具会静默降级成「本会话没有这个能力」,
  552. // 所以在这里就要大声失败。
  553. for (const method of [
  554. "listRuns",
  555. "getRunRow",
  556. "countNodesByStatus",
  557. "listRecentLogEvents",
  558. "listArtifactRows",
  559. "listArtifactItems",
  560. "countTaggedReports",
  561. "listEventPage",
  562. "listRunLifeSpans",
  563. ] as const) {
  564. if (typeof (journal as Partial<DwfRunIntrospectionQueries>)[method] !== "function") {
  565. throw new Error(`sqlite dwf journal 缺少 ${method}:run 内省工具会静默不可用`);
  566. }
  567. }
  568. return { db, journal: journal as JournalStorePort & DwfRunIntrospectionQueries };
  569. }
  570. /**
  571. * 预置一行 dwf_run。`timeUpdated` 必须能被显式钉住:createRun 写的是 Date.now(),同毫秒内
  572. * 建的多个 run 会拿到相同的时间戳,倒序断言就无从谈起。
  573. */
  574. function seedRun(
  575. db: DatabaseSync,
  576. journal: JournalStorePort,
  577. input: {
  578. args?: Record<string, unknown>;
  579. cwd?: string;
  580. name?: string;
  581. parentSessionId?: string;
  582. result?: unknown;
  583. runId: string;
  584. scriptText?: string;
  585. status?: RunRecord["status"];
  586. timeUpdated?: number;
  587. },
  588. ): void {
  589. journal.createRun({
  590. runId: input.runId,
  591. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  592. ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
  593. ...(input.name === undefined ? {} : { name: input.name }),
  594. ...(input.args === undefined ? {} : { args: input.args }),
  595. ...(input.scriptText === undefined ? {} : { scriptText: input.scriptText }),
  596. caps: CAPS,
  597. spentTokens: 0,
  598. status: input.status ?? "running",
  599. });
  600. if (input.result !== undefined) {
  601. journal.updateRunStatus(input.runId, input.status ?? "completed", { result: input.result });
  602. }
  603. if (input.timeUpdated !== undefined) {
  604. db.prepare("update dwf_run set time_updated = ? where id = ?").run(
  605. input.timeUpdated,
  606. input.runId,
  607. );
  608. }
  609. }
  610. describe("SQLite dwf journal store — dwf_run.name 与 cwd 索引", () => {
  611. it("dwf_run 带 name 列,且 dwf_run_cwd_idx 的形状正对枚举查询", () => {
  612. const { db } = openJournalDb();
  613. const columns = (
  614. db.prepare("select name from pragma_table_info('dwf_run')").all() as unknown as {
  615. name: string;
  616. }[]
  617. ).map((row) => row.name);
  618. expect(columns).toContain("name");
  619. // 索引列序就是查询形状(cwd 等值 + time_updated 排序):顺序反了索引就只能扫。
  620. const indexed = (
  621. db.prepare("select name from pragma_index_info('dwf_run_cwd_idx')").all() as unknown as {
  622. name: string;
  623. }[]
  624. ).map((row) => row.name);
  625. expect(indexed).toEqual(["cwd", "time_updated"]);
  626. });
  627. it("name 为 NULL 的旧行解码不炸且 name 缺席", () => {
  628. // 0021 之前落库的 run 行:列是新加的、值为 NULL(不做回填)。decodeRun 必须回一条没有
  629. // name 键的记录,否则升级后所有历史 run 都读不出来。
  630. const { db, journal } = openJournalDb();
  631. journal.createRun(RUN);
  632. db.prepare("update dwf_run set name = null where id = ?").run(RUN.runId);
  633. const record = journal.getRun(RUN.runId);
  634. expect(record).toEqual(RUN);
  635. expect("name" in (record ?? {})).toBe(false);
  636. });
  637. it("updateRunStatus 不改写 name 列", () => {
  638. // name 只在 createRun 那一刻写入(引擎独占的元数据路)。结算语句若把 name 也列进去,
  639. // run 一结算就会丢名字。
  640. const { db, journal } = openJournalDb();
  641. journal.createRun({ ...RUN, name: "triage the flake" });
  642. journal.updateRunStatus(RUN.runId, "completed", { result: "ok" });
  643. const row = db.prepare("select name from dwf_run where id = ?").get(RUN.runId) as
  644. | { name: string | null }
  645. | undefined;
  646. expect(row?.name).toBe("triage the flake");
  647. });
  648. });
  649. describe("SQLite dwf journal store — 基线形状", () => {
  650. // docs/dynamic-workflow/authoring.md:预算构造整体移除。基线 0019 直接以终态建表,这里钉住
  651. // 「两列不存在、用量列叫 spent_tokens」,以及老形状的 run 记录经 store 读回时 caps 只剩 maxConcurrency。
  652. it("dwf_run 没有节点上限 / 预算列,用量列叫 spent_tokens", () => {
  653. const { db } = openJournalDb();
  654. const columns = (db.prepare("pragma table_info(dwf_run)").all() as Array<{ name: string }>).map(
  655. (c) => c.name,
  656. );
  657. expect(columns).not.toContain("caps_max_nodes");
  658. expect(columns).not.toContain("caps_budget_total");
  659. expect(columns).not.toContain("budget_spent");
  660. expect(columns).toContain("spent_tokens");
  661. db.prepare(
  662. `insert into dwf_run (id, caps_max_concurrency, spent_tokens, status, time_created, time_updated)
  663. values ('run_legacy', 8, 4242, 'completed', 1, 2)`,
  664. ).run();
  665. const journal = createDwfJournalStore(db);
  666. expect(journal.getRun("run_legacy")).toEqual({
  667. runId: "run_legacy",
  668. caps: { maxConcurrency: 8 },
  669. spentTokens: 4242,
  670. status: "completed",
  671. });
  672. });
  673. });
  674. describe("SQLite dwf journal store — listRuns", () => {
  675. const CWD = "/repo/project";
  676. it("只回本 cwd 的 run,按 time_updated 倒序", () => {
  677. const { db, journal } = openIntrospectableJournal();
  678. seedRun(db, journal, { runId: "run_old", cwd: CWD, timeUpdated: 1_000 });
  679. seedRun(db, journal, { runId: "run_new", cwd: CWD, timeUpdated: 3_000 });
  680. seedRun(db, journal, { runId: "run_mid", cwd: CWD, timeUpdated: 2_000 });
  681. // 他项目的 run 与没有 cwd 的行都不属于本项目:查全了就把别人的 run 摆到模型面前。
  682. seedRun(db, journal, { runId: "run_other", cwd: "/repo/elsewhere", timeUpdated: 9_000 });
  683. seedRun(db, journal, { runId: "run_cwdless", timeUpdated: 9_000 });
  684. const rows = journal.listRuns({ cwd: CWD, limit: 20 });
  685. expect(rows.map((row) => row.runId)).toEqual(["run_new", "run_mid", "run_old"]);
  686. });
  687. it("cwd 是字面匹配,不做路径规范化", () => {
  688. // 与 submit 写入同源(context.workingDirectory 原样落库、原样查询)。在读侧单方面
  689. // 规范化只会造出单侧不匹配。
  690. const { db, journal } = openIntrospectableJournal();
  691. seedRun(db, journal, { runId: "run_1", cwd: CWD });
  692. expect(journal.listRuns({ cwd: `${CWD}/`, limit: 20 })).toEqual([]);
  693. expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(1);
  694. });
  695. it("limit 只截最新的那几条", () => {
  696. const { db, journal } = openIntrospectableJournal();
  697. for (let i = 0; i < 5; i++) {
  698. seedRun(db, journal, { runId: `run_${i}`, cwd: CWD, timeUpdated: 1_000 + i });
  699. }
  700. expect(journal.listRuns({ cwd: CWD, limit: 2 }).map((row) => row.runId)).toEqual([
  701. "run_4",
  702. "run_3",
  703. ]);
  704. // 超出条数不补空位;limit 0 是空页而不是全量(`limit -1` 那个 SQLite 惯用法不适用这里)。
  705. expect(journal.listRuns({ cwd: CWD, limit: 50 })).toHaveLength(5);
  706. expect(journal.listRuns({ cwd: CWD, limit: 0 })).toEqual([]);
  707. });
  708. it("statuses 过滤到给定子集", () => {
  709. const { db, journal } = openIntrospectableJournal();
  710. seedRun(db, journal, { runId: "run_running", cwd: CWD, status: "running" });
  711. seedRun(db, journal, { runId: "run_pending", cwd: CWD, status: "pending" });
  712. seedRun(db, journal, { runId: "run_completed", cwd: CWD, status: "completed" });
  713. seedRun(db, journal, { runId: "run_errored", cwd: CWD, status: "errored" });
  714. expect(
  715. journal
  716. .listRuns({ cwd: CWD, limit: 20, statuses: ["running", "pending"] })
  717. .map((row) => row.runId)
  718. .sort(),
  719. ).toEqual(["run_pending", "run_running"]);
  720. expect(journal.listRuns({ cwd: CWD, limit: 20, statuses: ["stopped"] })).toEqual([]);
  721. // 空集合就是「不匹配任何状态」,不是「不过滤」——后者会把过滤器静默取消掉。
  722. expect(journal.listRuns({ cwd: CWD, limit: 20, statuses: [] })).toEqual([]);
  723. });
  724. it("name 过滤下推到 SQL,且与 statuses 可叠加(GUI 中枢按工作流名归属运行历史)", () => {
  725. const { db, journal } = openIntrospectableJournal();
  726. seedRun(db, journal, { runId: "run_a1", cwd: CWD, name: "release-check", timeUpdated: 3 });
  727. seedRun(db, journal, { runId: "run_a2", cwd: CWD, name: "release-check", timeUpdated: 1 });
  728. seedRun(db, journal, { runId: "run_b", cwd: CWD, name: "port-driver", timeUpdated: 2 });
  729. seedRun(db, journal, { runId: "run_nameless", cwd: CWD, timeUpdated: 9 });
  730. seedRun(db, journal, {
  731. runId: "run_a_failed",
  732. cwd: CWD,
  733. name: "release-check",
  734. status: "errored",
  735. timeUpdated: 5,
  736. });
  737. expect(
  738. journal.listRuns({ cwd: CWD, limit: 20, name: "release-check" }).map((row) => row.runId),
  739. ).toEqual(["run_a_failed", "run_a1", "run_a2"]);
  740. expect(
  741. journal
  742. .listRuns({ cwd: CWD, limit: 20, name: "release-check", statuses: ["errored"] })
  743. .map((row) => row.runId),
  744. ).toEqual(["run_a_failed"]);
  745. // 名字是字面等值;不存在的名字回空页,而不是退回「不过滤」。
  746. expect(journal.listRuns({ cwd: CWD, limit: 20, name: "nope" })).toEqual([]);
  747. // 不带 name 时行为不变(nameless 行也在)。
  748. expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(5);
  749. });
  750. it("cwd 缺省即跨所有项目枚举(全局工作流的运行历史跨 cwd),行带 cwd", () => {
  751. // 全局工作流在不同项目里被发起,dwf_run.cwd 记的是各自实际运行的项目。`workflows/runs`
  752. // 的全局变体不按 cwd 过滤,把该名字在所有项目里的历史一并取出,行带 cwd 供 GUI 标项目
  753. // (docs/dynamic-workflow/launch.md「Data path」)。
  754. const { db, journal } = openIntrospectableJournal();
  755. seedRun(db, journal, { runId: "run_a", cwd: "/repo/one", name: "deep-research", timeUpdated: 3 });
  756. seedRun(db, journal, { runId: "run_b", cwd: "/repo/two", name: "deep-research", timeUpdated: 2 });
  757. seedRun(db, journal, { runId: "run_c", cwd: "/repo/one", name: "other", timeUpdated: 5 });
  758. seedRun(db, journal, { runId: "run_cwdless", name: "deep-research", timeUpdated: 1 });
  759. const rows = journal.listRuns({ name: "deep-research", limit: 20 });
  760. // 跨两个 cwd + 没有 cwd 的行,按 time_updated 倒序;别的名字不进来。
  761. expect(rows.map((row) => row.runId)).toEqual(["run_a", "run_b", "run_cwdless"]);
  762. const byId = new Map(rows.map((row) => [row.runId, row]));
  763. expect(byId.get("run_a")?.cwd).toBe("/repo/one");
  764. expect(byId.get("run_b")?.cwd).toBe("/repo/two");
  765. // cwd 为 NULL 的行不带 cwd 键(新列不回填,缺席可分辨)。
  766. expect(byId.get("run_cwdless") !== undefined && "cwd" in (byId.get("run_cwdless") ?? {})).toBe(false);
  767. // 给了 cwd 就仍只回本项目那份(与全局变体互斥,行为逐字不变)。
  768. expect(journal.listRuns({ cwd: "/repo/one", limit: 20, name: "deep-research" }).map((r) => r.runId)).toEqual([
  769. "run_a",
  770. ]);
  771. });
  772. it("枚举行带 args(实参是小 JSON 袋,中枢的运行历史要展示它);无实参的行键缺席", () => {
  773. const { db, journal } = openIntrospectableJournal();
  774. seedRun(db, journal, {
  775. runId: "run_args",
  776. cwd: CWD,
  777. name: "release-check",
  778. args: { target: "packages/ui", skipTests: false },
  779. });
  780. seedRun(db, journal, { runId: "run_bare", cwd: CWD, name: "release-check" });
  781. const byId = new Map(journal.listRuns({ cwd: CWD, limit: 20 }).map((row) => [row.runId, row]));
  782. expect(byId.get("run_args")?.args).toEqual({ target: "packages/ui", skipTests: false });
  783. expect(byId.get("run_bare")).not.toHaveProperty("args");
  784. });
  785. it("空结果回空数组", () => {
  786. const { journal } = openIntrospectableJournal();
  787. expect(journal.listRuns({ cwd: "/never/seen", limit: 20 })).toEqual([]);
  788. });
  789. it("每行带齐下游合成真相所需的字段,但不驮 result/failure", () => {
  790. const { db, journal } = openIntrospectableJournal();
  791. seedRun(db, journal, {
  792. runId: "run_1",
  793. cwd: CWD,
  794. name: "nightly triage",
  795. parentSessionId: "ses_owner",
  796. scriptText: "const planner = agent('planner');",
  797. status: "completed",
  798. result: { big: "artifact" },
  799. timeUpdated: 4_242,
  800. });
  801. const [row] = journal.listRuns({ cwd: CWD, limit: 20 });
  802. expect(row).toMatchObject({
  803. runId: "run_1",
  804. name: "nightly triage",
  805. // parentSessionId 是 ownedByThisSession / possiblyInterrupted 的判据,scriptText 是
  806. // label 兜底的原料——两者缺一,下游就只能再查一遍。
  807. parentSessionId: "ses_owner",
  808. cwd: CWD,
  809. scriptText: "const planner = agent('planner');",
  810. status: "completed",
  811. spentTokens: 0,
  812. caps: CAPS,
  813. timeUpdated: 4_242,
  814. });
  815. expect(typeof row?.timeCreated).toBe("number");
  816. // 列表刻意轻:产物可以很大,一页 50 行全解出来等于把整库产物读进内存。
  817. expect(row !== undefined && "result" in row).toBe(false);
  818. expect(row !== undefined && "failure" in row).toBe(false);
  819. });
  820. it("name 缺席的行不带 name 键", () => {
  821. const { db, journal } = openIntrospectableJournal();
  822. seedRun(db, journal, { runId: "run_1", cwd: CWD, scriptText: "log('hi');" });
  823. const [row] = journal.listRuns({ cwd: CWD, limit: 20 });
  824. expect(row !== undefined && "name" in row).toBe(false);
  825. });
  826. });
  827. describe("SQLite dwf journal store — getRunRow", () => {
  828. it("回完整记录 + journal 时间戳", () => {
  829. const { db, journal } = openIntrospectableJournal();
  830. seedRun(db, journal, {
  831. runId: "run_1",
  832. cwd: "/repo",
  833. name: "named run",
  834. status: "completed",
  835. result: { report: "done" },
  836. timeUpdated: 5_000,
  837. });
  838. const row = journal.getRunRow("run_1");
  839. // 时间戳直读 journal:RunRecord 本身不带时间,而详情页要报 createdAt / updatedAt。
  840. expect(row).toMatchObject({
  841. runId: "run_1",
  842. name: "named run",
  843. status: "completed",
  844. result: { report: "done" },
  845. timeUpdated: 5_000,
  846. });
  847. expect(typeof row?.timeCreated).toBe("number");
  848. });
  849. it("未知 runId 回 undefined", () => {
  850. const { journal } = openIntrospectableJournal();
  851. expect(journal.getRunRow("nope")).toBeUndefined();
  852. });
  853. });
  854. describe("SQLite dwf journal store — countNodesByStatus", () => {
  855. /** 落一个节点(只关心 status 与归属 run)。 */
  856. function seedNode(
  857. journal: JournalStorePort,
  858. runId: string,
  859. siteId: string,
  860. ordinal: number,
  861. status: NodeRecord["status"],
  862. ): void {
  863. journal.putNode({ runId, siteId, ordinal, kind: "ask", inputHash: "h", status });
  864. }
  865. it("按三态计数,且只数本 run 的节点", () => {
  866. const { db, journal } = openIntrospectableJournal();
  867. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  868. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  869. seedNode(journal, "run_1", "ask#1", 1, "completed");
  870. seedNode(journal, "run_1", "ask#1", 2, "completed");
  871. seedNode(journal, "run_1", "ask#2", 1, "running");
  872. seedNode(journal, "run_1", "ask#3", 1, "failed");
  873. seedNode(journal, "run_2", "ask#1", 1, "completed");
  874. expect(journal.countNodesByStatus("run_1")).toEqual({ running: 1, completed: 2, failed: 1 });
  875. });
  876. it("无节点(含未知 run)回三个 0,而不是缺键", () => {
  877. // 下游要拿它直接算 nodesObserved;缺键会让「还没有节点」和「没有这个 run」都变成 NaN。
  878. const { db, journal } = openIntrospectableJournal();
  879. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  880. expect(journal.countNodesByStatus("run_1")).toEqual({ running: 0, completed: 0, failed: 0 });
  881. expect(journal.countNodesByStatus("nope")).toEqual({ running: 0, completed: 0, failed: 0 });
  882. });
  883. });
  884. describe("SQLite dwf journal store — listRecentLogEvents", () => {
  885. it("只取 log 事件的末 N 条,按时序回", () => {
  886. const { db, journal } = openIntrospectableJournal();
  887. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  888. journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
  889. for (const message of ["l0", "l1", "l2", "l3"]) {
  890. journal.appendEvent("run_1", { type: "log", message });
  891. journal.appendEvent("run_1", {
  892. type: "usage-updated",
  893. spentTokens: 10,
  894. });
  895. }
  896. const tail = journal.listRecentLogEvents("run_1", 3);
  897. // 末 N 条按 sequence desc 取、再反转回时序:全量读进内存再筛是这条查询存在的反面。
  898. expect(
  899. tail.map((e) => (e.event.type === "log" ? e.event.message : `<${e.event.type}>`)),
  900. ).toEqual(["l1", "l2", "l3"]);
  901. // 序号是 journal 的真序号(log 之间夹着别的事件,所以不连续),不是重新编号的下标——
  902. // 下游拿它定位「叙事走到哪」。
  903. expect(tail.map((e) => e.sequence)).toEqual([3, 5, 7]);
  904. });
  905. it("limit 超过条数时给出全部 log 事件", () => {
  906. const { db, journal } = openIntrospectableJournal();
  907. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  908. journal.appendEvent("run_1", { type: "log", message: "only" });
  909. journal.appendEvent("run_1", { type: "run-settled", status: "completed" });
  910. expect(journal.listRecentLogEvents("run_1", 20).map((e) => e.event.type)).toEqual(["log"]);
  911. });
  912. it("没有 log 事件(含未知 run、limit 0)回空数组", () => {
  913. const { db, journal } = openIntrospectableJournal();
  914. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  915. journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
  916. expect(journal.listRecentLogEvents("run_1", 20)).toEqual([]);
  917. expect(journal.listRecentLogEvents("nope", 20)).toEqual([]);
  918. expect(journal.listRecentLogEvents("run_1", 0)).toEqual([]);
  919. });
  920. it("按 runId 隔离", () => {
  921. const { db, journal } = openIntrospectableJournal();
  922. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  923. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  924. journal.appendEvent("run_1", { type: "log", message: "mine" });
  925. journal.appendEvent("run_2", { type: "log", message: "theirs" });
  926. expect(
  927. journal
  928. .listRecentLogEvents("run_1", 20)
  929. .map((e) => (e.event.type === "log" ? e.event.message : "")),
  930. ).toEqual(["mine"]);
  931. });
  932. });
  933. describe("SQLite dwf journal store — listRunsByParentSession", () => {
  934. const PARENT = "ses_enum_parent";
  935. interface DwfRunEnumerationQuery {
  936. listRunsByParentSession(parentSessionId: string, limit: number): DwfRunSessionListItem[];
  937. }
  938. /** 能力探测同宿主侧(supportsRunEnumeration):方法名漂移要在这里先红。 */
  939. function openEnumerableJournal(): JournalStorePort & DwfRunEnumerationQuery {
  940. const { journal } = openJournalDb();
  941. if (
  942. typeof (journal as Partial<DwfRunEnumerationQuery>).listRunsByParentSession !== "function"
  943. ) {
  944. throw new Error(
  945. "sqlite dwf journal 缺少 listRunsByParentSession:UI 的重启后发现面会静默为空",
  946. );
  947. }
  948. return journal as JournalStorePort & DwfRunEnumerationQuery;
  949. }
  950. function seed(
  951. journal: JournalStorePort,
  952. input: {
  953. runId: string;
  954. status: RunRecord["status"];
  955. parentSessionId?: string;
  956. toolCallId?: string;
  957. },
  958. ): void {
  959. journal.createRun({
  960. runId: input.runId,
  961. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  962. ...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),
  963. caps: CAPS,
  964. spentTokens: 0,
  965. status: input.status,
  966. });
  967. }
  968. it("只回本父会话的行,完整解码(含 toolCallId 与 failure)", () => {
  969. const journal = openEnumerableJournal();
  970. seed(journal, {
  971. parentSessionId: PARENT,
  972. runId: "run_a",
  973. status: "stopped",
  974. toolCallId: "call-a",
  975. });
  976. seed(journal, { parentSessionId: PARENT, runId: "run_b", status: "completed" });
  977. seed(journal, { parentSessionId: "ses_other", runId: "run_sibling", status: "running" });
  978. seed(journal, { runId: "run_parentless", status: "running" });
  979. journal.updateRunStatus("run_b", "stopped", {
  980. stopReason: "interrupted",
  981. failure: { code: "Interrupted", message: "owning process exited" },
  982. });
  983. const rows = journal.listRunsByParentSession(PARENT, 10);
  984. expect(rows.map((row) => row.runId).sort()).toEqual(["run_a", "run_b"]);
  985. expect(rows.find((row) => row.runId === "run_a")?.toolCallId).toBe("call-a");
  986. // 逻辑词汇原样回来:stopped + reason + 结构化失败(物理层是 cancelled + 信封)。
  987. expect(rows.find((row) => row.runId === "run_a")).toMatchObject({
  988. status: "stopped",
  989. stopReason: "user",
  990. });
  991. expect(rows.find((row) => row.runId === "run_b")).toMatchObject({
  992. status: "stopped",
  993. stopReason: "interrupted",
  994. failure: { code: "Interrupted" },
  995. });
  996. });
  997. it("最近更新在前,limit 截断在最旧一侧", async () => {
  998. const journal = openEnumerableJournal();
  999. seed(journal, { parentSessionId: PARENT, runId: "run_old", status: "completed" });
  1000. seed(journal, { parentSessionId: PARENT, runId: "run_mid", status: "completed" });
  1001. seed(journal, { parentSessionId: PARENT, runId: "run_new", status: "running" });
  1002. // 让 time_updated 真正拉开(同一毫秒内 createRun 会并列):更新最老那行,使它变最新。
  1003. await new Promise((resolve) => setTimeout(resolve, 5));
  1004. journal.updateRunUsage("run_old", 42);
  1005. const rows = journal.listRunsByParentSession(PARENT, 2);
  1006. expect(rows).toHaveLength(2);
  1007. expect(rows[0]?.runId).toBe("run_old"); // 刚被触碰过 → 最近更新
  1008. });
  1009. it("未知父会话返回空数组;limit 0 返回空", () => {
  1010. const journal = openEnumerableJournal();
  1011. seed(journal, { parentSessionId: PARENT, runId: "run_a", status: "running" });
  1012. expect(journal.listRunsByParentSession("ses_never_seen", 10)).toEqual([]);
  1013. expect(journal.listRunsByParentSession(PARENT, 0)).toEqual([]);
  1014. });
  1015. // 窄投影:枚举面报 updatedAt,所以行必须带 journal 时间戳(`RunRecord` 自己不带时间)。
  1016. it("行带 journal 时间戳(createdAt/updatedAt 的来源)", () => {
  1017. const journal = openEnumerableJournal();
  1018. seed(journal, { parentSessionId: PARENT, runId: "run_timed", status: "running" });
  1019. const [row] = journal.listRunsByParentSession(PARENT, 10);
  1020. expect(typeof row?.timeCreated).toBe("number");
  1021. expect(typeof row?.timeUpdated).toBe("number");
  1022. expect(row?.timeUpdated).toBeGreaterThanOrEqual(row?.timeCreated ?? 0);
  1023. // 元数据列齐全(标签派生要 name/scriptText,归属要 parentSessionId)。
  1024. expect(row).toMatchObject({ parentSessionId: PARENT, runId: "run_timed", status: "running" });
  1025. });
  1026. /**
  1027. * `result_json` **不进这条查询的 SQL**。
  1028. *
  1029. * 断言必须打在 SQL 上而不是解码结果上:`decodeRunListItem` 本来就不读 result_json,所以
  1030. * 把 select 改回 `select *` 之后行为**完全不变**(行里照样没有 `result` 键),只有内存代价
  1031. * 会悄悄回来——一页 run 把每个产物一起读进内存。行为断言在这里是个假哨兵,实测过。
  1032. *
  1033. * 反过来 `failure_json` 必须在 SQL 里:resumable 的谓词依赖 failure.code(见下一个用例)。
  1034. */
  1035. it("枚举查询的 SQL 取 failure_json 而不取 result_json", () => {
  1036. const db = new DatabaseSync(":memory:");
  1037. openDatabases.push(db);
  1038. runSqliteSessionMigrations(db, ":memory:");
  1039. const prepared: string[] = [];
  1040. // prepare 的旁路记录器:只为了看见这条查询真正发出的列清单。
  1041. const recordingDb = new Proxy(db, {
  1042. get(target, property, receiver) {
  1043. if (property === "prepare") {
  1044. return (sql: string) => {
  1045. prepared.push(sql);
  1046. return target.prepare(sql);
  1047. };
  1048. }
  1049. const value = Reflect.get(target, property, receiver);
  1050. return typeof value === "function" ? value.bind(target) : value;
  1051. },
  1052. }) as DatabaseSync;
  1053. const journal = createDwfJournalStore(recordingDb) as JournalStorePort & DwfRunEnumerationQuery;
  1054. seed(journal, { parentSessionId: PARENT, runId: "run_a", status: "running" });
  1055. // 只看枚举查询自己发的 SQL(建行/迁移的语句当然会提到 result_json)。
  1056. prepared.length = 0;
  1057. journal.listRunsByParentSession(PARENT, 10);
  1058. const sql = prepared.join("\n");
  1059. expect(sql).toContain("failure_json");
  1060. expect(sql).not.toContain("result_json");
  1061. expect(sql).not.toMatch(/select\s+\*/i);
  1062. });
  1063. /** failure 必须活过窄投影:Interrupted 是 resume 门认可的可恢复形态。 */
  1064. it("窄投影仍解出 failure(resumable 谓词的输入)", () => {
  1065. const journal = openEnumerableJournal();
  1066. seed(journal, { parentSessionId: PARENT, runId: "run_dead", status: "running" });
  1067. journal.updateRunStatus("run_dead", "stopped", {
  1068. stopReason: "interrupted",
  1069. failure: { code: "Interrupted", message: "owning process exited" },
  1070. });
  1071. const [row] = journal.listRunsByParentSession(PARENT, 10);
  1072. expect(row?.failure).toEqual({ code: "Interrupted", message: "owning process exited" });
  1073. expect(row?.stopReason).toBe("interrupted");
  1074. });
  1075. });
  1076. /**
  1077. * 用户面产物的两条宿主查询(docs/dynamic-workflow/authoring.md「Journal rows and events」)。
  1078. * ⚠ 这里的 artifact 是脚本发布给用户看的交付物,不是 `RunSettlement.artifact`(顶层返回值)。
  1079. *
  1080. * 两条都刻意**不在** `JournalStorePort` 上(同 `listRuns` 的论证:引擎不做的事不该进领域端口),
  1081. * 所以它们的语义只能在这里、对着真库钉住——内存实现根本不提供它们。
  1082. */
  1083. describe("SQLite dwf journal store — listArtifactRows", () => {
  1084. /** 落一条产物行(发布或声明)。 */
  1085. function seedArtifact(
  1086. journal: JournalStorePort,
  1087. runId: string,
  1088. siteId: string,
  1089. ordinal: number,
  1090. artifactId: string,
  1091. record: Record<string, unknown> | undefined,
  1092. ): void {
  1093. journal.putNode({
  1094. runId,
  1095. siteId,
  1096. ordinal,
  1097. kind: "artifact",
  1098. inputHash: `${siteId}@${ordinal}`,
  1099. status: record === undefined ? "failed" : "completed",
  1100. ...(record === undefined
  1101. ? { error: { code: "ArtifactSourceMissing" as const, message: "缺文件" } }
  1102. : { result: record }),
  1103. artifactId,
  1104. });
  1105. }
  1106. it("只回本 run 的产物行,按落库先后", () => {
  1107. const { db, journal } = openIntrospectableJournal();
  1108. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1109. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  1110. // 交错发布:同一个 id 的行**不**天然连续,所以排序只能是落库先后(版本的先后就是它)。
  1111. seedArtifact(journal, "run_1", "artifact#1", 1, "perf", {
  1112. id: "perf",
  1113. kind: "chart",
  1114. version: 1,
  1115. });
  1116. seedArtifact(journal, "run_1", "artifact#2", 1, "book", {
  1117. id: "book",
  1118. kind: "file",
  1119. version: 1,
  1120. bytes: 10,
  1121. });
  1122. seedArtifact(journal, "run_1", "artifact#2", 2, "book", {
  1123. id: "book",
  1124. kind: "file",
  1125. version: 2,
  1126. bytes: 20,
  1127. });
  1128. // 标签 report 与普通节点都不是产物行——混进来,读面会把每个数据点当成一个交付物。
  1129. journal.putNode({
  1130. runId: "run_1",
  1131. siteId: "report#1",
  1132. ordinal: 1,
  1133. kind: "report",
  1134. inputHash: "r",
  1135. status: "completed",
  1136. result: { round: 1 },
  1137. artifactId: "perf",
  1138. });
  1139. journal.putNode({
  1140. runId: "run_1",
  1141. siteId: "ask#1",
  1142. ordinal: 1,
  1143. kind: "ask",
  1144. inputHash: "k",
  1145. status: "completed",
  1146. });
  1147. // 别的 run 的产物:查全了就把别人的交付物摆到这个 run 的卡片区。
  1148. seedArtifact(journal, "run_2", "artifact#1", 1, "other", {
  1149. id: "other",
  1150. kind: "markdown",
  1151. version: 1,
  1152. });
  1153. const rows = journal.listArtifactRows("run_1");
  1154. expect(rows.map((row) => [row.siteId, row.ordinal, row.artifactId])).toEqual([
  1155. ["artifact#1", 1, "perf"],
  1156. ["artifact#2", 1, "book"],
  1157. ["artifact#2", 2, "book"],
  1158. ]);
  1159. expect(rows[2]?.result).toEqual({ id: "book", kind: "file", version: 2, bytes: 20 });
  1160. });
  1161. it("失败的发布照样在结果里(带 error、无 result)", () => {
  1162. // 筛掉失败行等于让一个用户可见的失败在每张表面上都不存在。
  1163. const { db, journal } = openIntrospectableJournal();
  1164. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1165. seedArtifact(journal, "run_1", "artifact#1", 1, "book", undefined);
  1166. const [row] = journal.listArtifactRows("run_1");
  1167. expect(row?.status).toBe("failed");
  1168. expect(row?.artifactId).toBe("book");
  1169. expect(row?.error).toEqual({ code: "ArtifactSourceMissing", message: "缺文件" });
  1170. expect(row !== undefined && "result" in row).toBe(false);
  1171. });
  1172. it("无产物(含未知 run)回空数组", () => {
  1173. const { db, journal } = openIntrospectableJournal();
  1174. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1175. expect(journal.listArtifactRows("run_1")).toEqual([]);
  1176. expect(journal.listArtifactRows("nope")).toEqual([]);
  1177. });
  1178. });
  1179. describe("SQLite dwf journal store — countTaggedReports", () => {
  1180. it("counts tagged report rows per artifact id in SQL, ignoring untagged rows, other kinds and other runs", () => {
  1181. const { db, journal } = openIntrospectableJournal();
  1182. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1183. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  1184. const put = (
  1185. runId: string,
  1186. siteId: string,
  1187. ordinal: number,
  1188. extra: Partial<NodeRecord>,
  1189. ): void =>
  1190. journal.putNode({
  1191. runId,
  1192. siteId,
  1193. ordinal,
  1194. kind: "report",
  1195. inputHash: `${siteId}@${ordinal}`,
  1196. status: "completed",
  1197. result: { big: "x".repeat(1024) },
  1198. ...extra,
  1199. });
  1200. put("run_1", "report#1", 1, { artifactId: "perf" });
  1201. put("run_1", "report#1", 2, { artifactId: "perf" });
  1202. put("run_1", "report#2", 1, { artifactId: "queue" });
  1203. put("run_1", "report#3", 1, {}); // 未打标签
  1204. put("run_1", "artifact#1", 1, { kind: "artifact", artifactId: "perf" }); // 产物行不算
  1205. put("run_2", "report#1", 1, { artifactId: "perf" }); // 别的 run
  1206. expect(journal.countTaggedReports("run_1")).toEqual(
  1207. new Map([
  1208. ["perf", 2],
  1209. ["queue", 1],
  1210. ]),
  1211. );
  1212. expect(journal.countTaggedReports("nope")).toEqual(new Map());
  1213. });
  1214. });
  1215. describe("SQLite dwf journal store — listArtifactItems", () => {
  1216. /** 足够大的字节界:只想测条数 / 游标 / 筛选的用例用它,让字节界不参与。 */
  1217. const ANY_BYTES = 1 << 30;
  1218. /** 追加一条标签 report 事件,回它拿到的 sequence。 */
  1219. function seedTaggedReport(
  1220. journal: JournalStorePort,
  1221. runId: string,
  1222. siteId: string,
  1223. ordinal: number,
  1224. item: unknown,
  1225. artifactId?: string,
  1226. ): number {
  1227. return journal.appendEvent(runId, {
  1228. type: "report",
  1229. instance: { siteId, ordinal },
  1230. item,
  1231. ...(artifactId === undefined ? {} : { artifactId }),
  1232. }).sequence;
  1233. }
  1234. it("按 sequence 升序回该 id 的条目,带站点坐标与原值", () => {
  1235. const { db, journal } = openIntrospectableJournal();
  1236. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1237. const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
  1238. const s1 = seedTaggedReport(journal, "run_1", "report#1", 2, { round: 2 }, "perf");
  1239. expect(journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: ANY_BYTES })).toEqual({
  1240. items: [
  1241. { sequence: s0, siteId: "report#1", ordinal: 1, item: { round: 1 } },
  1242. { sequence: s1, siteId: "report#1", ordinal: 2, item: { round: 2 } },
  1243. ],
  1244. hasMore: false,
  1245. });
  1246. });
  1247. it("排除未打标签的 report、别的 id、别种事件与别的 run", () => {
  1248. const { db, journal } = openIntrospectableJournal();
  1249. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1250. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  1251. seedTaggedReport(journal, "run_1", "report#1", 1, { mine: true }, "perf");
  1252. // 未打标签:payload 里根本没有 artifactId 键,SQL 的 `= ?` 不匹配 NULL。
  1253. seedTaggedReport(journal, "run_1", "report#2", 1, { untagged: true });
  1254. seedTaggedReport(journal, "run_1", "report#3", 1, { other: true }, "queue");
  1255. // 别种事件:`artifact-published` 的 id 藏在嵌套的 `artifact.id` 里,不是顶层 artifactId;
  1256. // 但 type 过滤才是这条不变式的守门人(明天别的事件可能带顶层 artifactId)。
  1257. journal.appendEvent("run_1", {
  1258. type: "artifact-published",
  1259. instance: { siteId: "artifact#1", ordinal: 1 },
  1260. artifact: { id: "perf", kind: "chart", version: 1 },
  1261. });
  1262. journal.appendEvent("run_1", { type: "log", message: "perf" });
  1263. seedTaggedReport(journal, "run_2", "report#1", 1, { crossRun: true }, "perf");
  1264. const page = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: ANY_BYTES });
  1265. expect(page.items.map((entry) => entry.item)).toEqual([{ mine: true }]);
  1266. expect(page.hasMore).toBe(false);
  1267. });
  1268. it("afterSequence 是严格大于的游标", () => {
  1269. const { db, journal } = openIntrospectableJournal();
  1270. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1271. const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, 1, "perf");
  1272. // 中间夹一条别的事件:游标是 journal 的全局 sequence,不是「第几条产物条目」。
  1273. journal.appendEvent("run_1", { type: "log", message: "between" });
  1274. const s1 = seedTaggedReport(journal, "run_1", "report#1", 2, 2, "perf");
  1275. const after = (afterSequence: number) =>
  1276. journal.listArtifactItems("run_1", "perf", { afterSequence, limit: 10, maxBytes: ANY_BYTES });
  1277. expect(after(s0).items.map((entry) => entry.sequence)).toEqual([s1]);
  1278. expect(after(s1)).toEqual({ items: [], hasMore: false });
  1279. });
  1280. it("limit 逐字兑现,hasMore 由存储层判定:页之后还有没有条目", () => {
  1281. // 存储层不加自己的天花板,也不要调用方多取一条来猜:页尾后面那一行存在与否就是 hasMore。
  1282. const { db, journal } = openIntrospectableJournal();
  1283. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1284. for (let round = 0; round < 5; round += 1) {
  1285. seedTaggedReport(journal, "run_1", "report#1", round + 1, round, "perf");
  1286. }
  1287. const page = (limit: number) =>
  1288. journal.listArtifactItems("run_1", "perf", { limit, maxBytes: ANY_BYTES });
  1289. expect(page(2)).toMatchObject({ hasMore: true });
  1290. expect(page(2).items.map((entry) => entry.item)).toEqual([0, 1]);
  1291. expect(page(4).hasMore).toBe(true);
  1292. // 恰好取尽:不报 hasMore(不会让看板白翻一页空的)。
  1293. expect(page(5)).toMatchObject({ hasMore: false });
  1294. expect(page(5).items).toHaveLength(5);
  1295. expect(page(99).items).toHaveLength(5);
  1296. });
  1297. it("字节界:再加一条就超界时收尾并报 hasMore,第一条总是带上", () => {
  1298. const { db, journal } = openIntrospectableJournal();
  1299. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1300. const pad = "x".repeat(1000);
  1301. for (let round = 0; round < 4; round += 1) {
  1302. seedTaggedReport(journal, "run_1", "report#1", round + 1, { round, pad }, "perf");
  1303. }
  1304. // 每条载荷约 1.1 KB:2.5 KB 的界放得下两条、放不下第三条。
  1305. const first = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: 2500 });
  1306. expect(first.items.map((entry) => (entry.item as { round: number }).round)).toEqual([0, 1]);
  1307. expect(first.hasMore).toBe(true);
  1308. // 续拉从页尾接上,不重不漏。
  1309. const rest = journal.listArtifactItems("run_1", "perf", {
  1310. afterSequence: first.items.at(-1)!.sequence,
  1311. limit: 10,
  1312. maxBytes: 2500,
  1313. });
  1314. expect(rest.items.map((entry) => (entry.item as { round: number }).round)).toEqual([2, 3]);
  1315. expect(rest.hasMore).toBe(false);
  1316. // 一条就超过界:它自成一页(否则翻页永远卡在这一条上),后面的照样报 hasMore。
  1317. const tiny = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: 10 });
  1318. expect(tiny.items).toHaveLength(1);
  1319. expect(tiny.hasMore).toBe(true);
  1320. });
  1321. it("limit ≤ 0 是空页,未知 run / 未知 id 同样", () => {
  1322. const { db, journal } = openIntrospectableJournal();
  1323. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1324. seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
  1325. const empty = { items: [], hasMore: false };
  1326. expect(journal.listArtifactItems("run_1", "perf", { limit: 0, maxBytes: ANY_BYTES })).toEqual(
  1327. empty,
  1328. );
  1329. expect(journal.listArtifactItems("run_1", "perf", { limit: -1, maxBytes: ANY_BYTES })).toEqual(
  1330. empty,
  1331. );
  1332. expect(journal.listArtifactItems("run_1", "nope", { limit: 10, maxBytes: ANY_BYTES })).toEqual(
  1333. empty,
  1334. );
  1335. expect(journal.listArtifactItems("nope", "perf", { limit: 10, maxBytes: ANY_BYTES })).toEqual(
  1336. empty,
  1337. );
  1338. });
  1339. it("条目原值原样回来:null、标量与数组都不被加工", () => {
  1340. const { db, journal } = openIntrospectableJournal();
  1341. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1342. seedTaggedReport(journal, "run_1", "report#1", 1, null, "perf");
  1343. seedTaggedReport(journal, "run_1", "report#1", 2, "文本", "perf");
  1344. seedTaggedReport(journal, "run_1", "report#1", 3, [1, { two: true }], "perf");
  1345. const page = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: ANY_BYTES });
  1346. expect(page.items.map((e) => e.item)).toEqual([null, "文本", [1, { two: true }]]);
  1347. });
  1348. });
  1349. describe("SQLite dwf journal store — listArtifactItems with fields", () => {
  1350. const FIELD_VALUE_BYTES = 4096;
  1351. function seed(journal: JournalStorePort, runId: string, items: unknown[]): void {
  1352. items.forEach((item, index) =>
  1353. journal.appendEvent(runId, {
  1354. type: "report",
  1355. instance: { siteId: "report#1", ordinal: index + 1 },
  1356. item,
  1357. artifactId: "perf",
  1358. }),
  1359. );
  1360. }
  1361. function readFields(
  1362. journal: JournalStorePort & DwfRunIntrospectionQueries,
  1363. paths: string[],
  1364. page: { limit?: number; maxBytes?: number; afterSequence?: number } = {},
  1365. ) {
  1366. return journal.listArtifactItems("run_1", "perf", {
  1367. limit: page.limit ?? 10,
  1368. maxBytes: page.maxBytes ?? 1 << 30,
  1369. ...(page.afterSequence === undefined ? {} : { afterSequence: page.afterSequence }),
  1370. fields: { paths, maxValueBytes: FIELD_VALUE_BYTES },
  1371. });
  1372. }
  1373. it("回点名的字段、不回整条 item;JSON 的 null 在表里,走不通的路径不在", () => {
  1374. const { db, journal } = openIntrospectableJournal();
  1375. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1376. seed(journal, "run_1", [
  1377. { round: 1, ok: true, timing: { ms: 12.5 }, note: null, big: "x".repeat(99) },
  1378. ]);
  1379. const page = readFields(journal, [
  1380. "round",
  1381. "ok",
  1382. "timing.ms",
  1383. "note",
  1384. "missing",
  1385. "round.deeper",
  1386. ]);
  1387. expect(page.hasMore).toBe(false);
  1388. expect(page.items).toEqual([
  1389. {
  1390. sequence: expect.any(Number),
  1391. siteId: "report#1",
  1392. ordinal: 1,
  1393. fields: { round: 1, ok: true, "timing.ms": 12.5, note: null },
  1394. },
  1395. ]);
  1396. expect(page.items[0]).not.toHaveProperty("item");
  1397. });
  1398. it("像整数的段在数组上是下标、在对象上是键,与渲染器的路径规则相同", () => {
  1399. const { db, journal } = openIntrospectableJournal();
  1400. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1401. seed(journal, "run_1", [
  1402. {
  1403. rows: [{ v: 1 }, { v: 2 }],
  1404. byKey: { "0": "zero", "01": "zero-one" },
  1405. empty: { "": { b: 7 } },
  1406. },
  1407. ]);
  1408. const [entry] = readFields(journal, [
  1409. "rows.1.v",
  1410. "rows.01.v", // Number("01") = 1:数组上仍是下标 1
  1411. "rows.5.v", // 越界
  1412. "rows.x", // 数组上的非整数段
  1413. "byKey.0",
  1414. "byKey.01",
  1415. "empty..b", // 空段是一个空键
  1416. ]).items;
  1417. expect(entry?.fields).toEqual({
  1418. "rows.1.v": 2,
  1419. "rows.01.v": 2,
  1420. "byKey.0": "zero",
  1421. "byKey.01": "zero-one",
  1422. "empty..b": 7,
  1423. });
  1424. });
  1425. it("键里带引号与反斜杠照样取得到", () => {
  1426. const { db, journal } = openIntrospectableJournal();
  1427. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1428. seed(journal, "run_1", [{ 'say"hi': 1, "back\\slash": 2, 中文: 3 }]);
  1429. const [entry] = readFields(journal, ['say"hi', "back\\slash", "中文"]).items;
  1430. expect(entry?.fields).toEqual({ 'say"hi': 1, "back\\slash": 2, 中文: 3 });
  1431. });
  1432. it("超过值的字节上界的值回成截短的字符串,一个大值不会整段进 JavaScript", () => {
  1433. const { db, journal } = openIntrospectableJournal();
  1434. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1435. seed(journal, "run_1", [
  1436. { text: "y".repeat(10_000), list: Array.from({ length: 2000 }, (_v, i) => i) },
  1437. ]);
  1438. const [entry] = readFields(journal, ["text", "list"]).items;
  1439. expect(entry?.fields?.text).toBe(`${"y".repeat(1000)}…`);
  1440. const list = entry?.fields?.list as string;
  1441. expect(typeof list).toBe("string");
  1442. expect(list.startsWith("[0,1,2,3")).toBe(true);
  1443. expect(list).toHaveLength(1001);
  1444. });
  1445. it("页按取出的字段值计字节:大 item 里只取一个小字段时一页装得下很多条", () => {
  1446. const { db, journal } = openIntrospectableJournal();
  1447. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1448. seed(
  1449. journal,
  1450. "run_1",
  1451. Array.from({ length: 5 }, (_v, round) => ({ round, pad: "z".repeat(50_000) })),
  1452. );
  1453. // 整条 item 每条 50 KB,但只取 round:5 条远在 1 KB 之内。
  1454. const small = readFields(journal, ["round"], { maxBytes: 1000 });
  1455. expect(small.items.map((entry) => entry.fields?.round)).toEqual([0, 1, 2, 3, 4]);
  1456. expect(small.hasMore).toBe(false);
  1457. // 取 pad(每条截短到约 1 KB)时,同样的 2.5 KB 只装得下两条,并报 hasMore。
  1458. const padded = readFields(journal, ["pad"], { maxBytes: 2500 });
  1459. expect(padded.items).toHaveLength(2);
  1460. expect(padded.hasMore).toBe(true);
  1461. // 条数界与游标照常。
  1462. const limited = readFields(journal, ["round"], { limit: 2 });
  1463. expect(limited.items.map((entry) => entry.fields?.round)).toEqual([0, 1]);
  1464. expect(limited.hasMore).toBe(true);
  1465. const rest = readFields(journal, ["round"], { afterSequence: limited.items[1]!.sequence });
  1466. expect(rest.items.map((entry) => entry.fields?.round)).toEqual([2, 3, 4]);
  1467. });
  1468. });
  1469. describe("SQLite dwf journal store — listEventPage", () => {
  1470. it("全部类型、item 原样,按条数分页并判定 hasMore", () => {
  1471. const { db, journal } = openIntrospectableJournal();
  1472. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1473. journal.appendEvent("run_1", { type: "log", message: "a" });
  1474. journal.appendEvent("run_1", {
  1475. type: "report",
  1476. instance: { siteId: "report#1", ordinal: 1 },
  1477. item: { finding: 1 },
  1478. });
  1479. journal.appendEvent("run_1", { type: "log", message: "b" });
  1480. const all = journal.listEvents("run_1", { types: "all", reportItems: "all" });
  1481. const first = journal.listEventPage("run_1", { limit: 2, maxBytes: 1 << 30 });
  1482. expect(first.events).toEqual(all.slice(0, 2));
  1483. expect(first.hasMore).toBe(true);
  1484. const rest = journal.listEventPage("run_1", {
  1485. afterSequence: first.events.at(-1)!.sequence,
  1486. limit: 2,
  1487. maxBytes: 1 << 30,
  1488. });
  1489. expect(rest).toEqual({ events: all.slice(2), hasMore: false });
  1490. });
  1491. it("字节界同看板条目:带大 item 的事件让页提前收尾,但每页至少一条", () => {
  1492. const { db, journal } = openIntrospectableJournal();
  1493. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1494. for (let ordinal = 1; ordinal <= 3; ordinal += 1) {
  1495. journal.appendEvent("run_1", {
  1496. type: "report",
  1497. instance: { siteId: "report#1", ordinal },
  1498. item: "y".repeat(4096),
  1499. });
  1500. }
  1501. const seen: number[] = [];
  1502. let cursor: number | undefined;
  1503. for (;;) {
  1504. const page = journal.listEventPage("run_1", {
  1505. ...(cursor === undefined ? {} : { afterSequence: cursor }),
  1506. limit: 500,
  1507. maxBytes: 5000,
  1508. });
  1509. expect(page.events).toHaveLength(1);
  1510. seen.push(...page.events.map((stored) => stored.sequence));
  1511. cursor = page.events.at(-1)!.sequence;
  1512. if (!page.hasMore) break;
  1513. }
  1514. expect(seen).toHaveLength(3);
  1515. });
  1516. });
  1517. // ————————————————————————————————————————————————————————————————
  1518. // 零迁移终态编码(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「The journal」):物理列仍是旧五值,
  1519. // 逻辑 `errored` / `stopped{reason}` 只活在编解码里。下面这张表就是 spec 里用户复核过的那张。
  1520. // ————————————————————————————————————————————————————————————————
  1521. describe("SqliteDwfJournalStore 终态编码(零迁移)", () => {
  1522. const PARENT = "ses_terminal";
  1523. function insertPhysicalRow(
  1524. db: DatabaseSync,
  1525. runId: string,
  1526. status: string,
  1527. failureJson: string | null,
  1528. timeUpdated = 1,
  1529. ): void {
  1530. db.prepare(
  1531. `insert into dwf_run (id, parent_session_id, cwd, caps_max_concurrency, spent_tokens, status,
  1532. failure_json, time_created, time_updated) values (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  1533. ).run(runId, PARENT, "/repo", 4, 0, status, failureJson, 1, timeUpdated);
  1534. }
  1535. it("历史行按表解码:cancelled→stopped(user),failed+Interrupted→stopped(interrupted),其余 failed→errored", () => {
  1536. const { db, journal } = openIntrospectableJournal();
  1537. insertPhysicalRow(db, "old_pending", "pending", null);
  1538. insertPhysicalRow(db, "old_running", "running", null);
  1539. insertPhysicalRow(db, "old_completed", "completed", null);
  1540. insertPhysicalRow(db, "old_cancelled", "cancelled", null);
  1541. insertPhysicalRow(
  1542. db,
  1543. "old_interrupted",
  1544. "failed",
  1545. JSON.stringify({ code: "Interrupted", message: "owning process exited" }),
  1546. );
  1547. insertPhysicalRow(
  1548. db,
  1549. "old_provider_crash",
  1550. "failed",
  1551. JSON.stringify({
  1552. code: "DriverError",
  1553. message: "Subagent turn failed",
  1554. modelFailureReason: "rate_limited",
  1555. }),
  1556. );
  1557. insertPhysicalRow(
  1558. db,
  1559. "old_script_error",
  1560. "failed",
  1561. JSON.stringify({ code: "DriverError", message: "boom" }),
  1562. );
  1563. insertPhysicalRow(
  1564. db,
  1565. "old_cap",
  1566. "failed",
  1567. JSON.stringify({ code: "ReportCapExceeded", message: "over" }),
  1568. );
  1569. insertPhysicalRow(db, "old_failed_bare", "failed", null);
  1570. const statusOf = (runId: string) => {
  1571. const record = journal.getRun(runId)!;
  1572. return { status: record.status, stopReason: record.stopReason, code: record.failure?.code };
  1573. };
  1574. expect(statusOf("old_pending")).toEqual({
  1575. status: "pending",
  1576. stopReason: undefined,
  1577. code: undefined,
  1578. });
  1579. expect(statusOf("old_running")).toEqual({
  1580. status: "running",
  1581. stopReason: undefined,
  1582. code: undefined,
  1583. });
  1584. expect(statusOf("old_completed")).toEqual({
  1585. status: "completed",
  1586. stopReason: undefined,
  1587. code: undefined,
  1588. });
  1589. expect(statusOf("old_cancelled")).toEqual({
  1590. status: "stopped",
  1591. stopReason: "user",
  1592. code: undefined,
  1593. });
  1594. expect(statusOf("old_interrupted")).toEqual({
  1595. status: "stopped",
  1596. stopReason: "interrupted",
  1597. code: "Interrupted",
  1598. });
  1599. // 第 6 行(用户复核裁决):老的 provider 崩溃仍是 errored,不可 resume。
  1600. expect(statusOf("old_provider_crash")).toEqual({
  1601. status: "errored",
  1602. stopReason: undefined,
  1603. code: "DriverError",
  1604. });
  1605. expect(statusOf("old_script_error")).toEqual({
  1606. status: "errored",
  1607. stopReason: undefined,
  1608. code: "DriverError",
  1609. });
  1610. expect(statusOf("old_cap")).toEqual({
  1611. status: "errored",
  1612. stopReason: undefined,
  1613. code: "ReportCapExceeded",
  1614. });
  1615. expect(statusOf("old_failed_bare")).toEqual({
  1616. status: "errored",
  1617. stopReason: undefined,
  1618. code: undefined,
  1619. });
  1620. // 缺席的键真的缺席(契约测的 toEqual 风格)。
  1621. expect("stopReason" in journal.getRun("old_completed")!).toBe(false);
  1622. expect("failure" in journal.getRun("old_cancelled")!).toBe(false);
  1623. });
  1624. it("新写入的 stopped 落成 cancelled + 信封,errored 落成 failed + 原样失败;往返逐字段相等", () => {
  1625. const { db, journal } = openIntrospectableJournal();
  1626. for (const runId of ["s_user", "s_model", "s_provider", "s_interrupted", "e_script"]) {
  1627. journal.createRun({
  1628. runId,
  1629. parentSessionId: PARENT,
  1630. cwd: "/repo",
  1631. caps: CAPS,
  1632. spentTokens: 0,
  1633. status: "running",
  1634. });
  1635. }
  1636. journal.updateRunStatus("s_user", "stopped", { stopReason: "user" });
  1637. journal.updateRunStatus("s_model", "stopped", { stopReason: "model" });
  1638. const providerStop = {
  1639. code: "ProviderStop" as const,
  1640. message: "Sign-in to BigModel expired.",
  1641. providerStop: {
  1642. kind: "auth" as const,
  1643. reason: "auth_failed",
  1644. providerCode: "1006",
  1645. subagent: "verify@2",
  1646. },
  1647. };
  1648. journal.updateRunStatus("s_provider", "stopped", {
  1649. stopReason: "provider",
  1650. failure: providerStop,
  1651. });
  1652. journal.updateRunStatus("s_interrupted", "stopped", {
  1653. stopReason: "interrupted",
  1654. failure: { code: "Interrupted", message: "owning process exited" },
  1655. });
  1656. journal.updateRunStatus("e_script", "errored", {
  1657. failure: { code: "DriverError", message: "boom" },
  1658. });
  1659. const physical = db
  1660. .prepare(
  1661. "select id, status, failure_json from dwf_run where parent_session_id = ? order by id",
  1662. )
  1663. .all(PARENT) as { id: string; status: string; failure_json: string | null }[];
  1664. expect(physical.map((row) => [row.id, row.status])).toEqual([
  1665. ["e_script", "failed"],
  1666. ["s_interrupted", "cancelled"],
  1667. ["s_model", "cancelled"],
  1668. ["s_provider", "cancelled"],
  1669. ["s_user", "cancelled"],
  1670. ]);
  1671. expect(JSON.parse(physical.find((row) => row.id === "s_user")!.failure_json!)).toEqual({
  1672. stopReason: "user",
  1673. });
  1674. expect(JSON.parse(physical.find((row) => row.id === "s_provider")!.failure_json!)).toEqual({
  1675. stopReason: "provider",
  1676. error: providerStop,
  1677. });
  1678. expect(JSON.parse(physical.find((row) => row.id === "e_script")!.failure_json!)).toEqual({
  1679. code: "DriverError",
  1680. message: "boom",
  1681. });
  1682. expect(journal.getRun("s_user")).toMatchObject({ status: "stopped", stopReason: "user" });
  1683. expect("failure" in journal.getRun("s_user")!).toBe(false);
  1684. expect(journal.getRun("s_model")).toMatchObject({ status: "stopped", stopReason: "model" });
  1685. expect(journal.getRun("s_provider")).toMatchObject({
  1686. status: "stopped",
  1687. stopReason: "provider",
  1688. failure: providerStop,
  1689. });
  1690. expect(journal.getRun("s_interrupted")).toMatchObject({
  1691. status: "stopped",
  1692. stopReason: "interrupted",
  1693. });
  1694. expect(journal.getRun("e_script")).toMatchObject({
  1695. status: "errored",
  1696. failure: { code: "DriverError" },
  1697. });
  1698. expect("stopReason" in journal.getRun("e_script")!).toBe(false);
  1699. // 物理终态集没变:非终态查询一条都不回。
  1700. expect(journal.listNonTerminalRuns(PARENT)).toEqual([]);
  1701. // resume 翻回 running 清掉信封(与契约套件同语义)。
  1702. journal.updateRunStatus("s_provider", "running");
  1703. expect(journal.getRun("s_provider")).toMatchObject({ status: "running" });
  1704. expect("stopReason" in journal.getRun("s_provider")!).toBe(false);
  1705. });
  1706. it("statuses 过滤在 SQL 里分清 errored 与 stopped(共享物理 failed)", () => {
  1707. const { db, journal } = openIntrospectableJournal();
  1708. insertPhysicalRow(db, "p_cancelled", "cancelled", null, 5);
  1709. insertPhysicalRow(
  1710. db,
  1711. "p_interrupted",
  1712. "failed",
  1713. JSON.stringify({ code: "Interrupted", message: "x" }),
  1714. 4,
  1715. );
  1716. insertPhysicalRow(
  1717. db,
  1718. "p_errored",
  1719. "failed",
  1720. JSON.stringify({ code: "DriverError", message: "x" }),
  1721. 3,
  1722. );
  1723. insertPhysicalRow(db, "p_errored_bare", "failed", null, 2);
  1724. insertPhysicalRow(db, "p_completed", "completed", null, 1);
  1725. journal.createRun({
  1726. runId: "n_stopped",
  1727. parentSessionId: PARENT,
  1728. cwd: "/repo",
  1729. caps: CAPS,
  1730. spentTokens: 0,
  1731. status: "running",
  1732. });
  1733. journal.updateRunStatus("n_stopped", "stopped", { stopReason: "provider" });
  1734. const ids = (statuses: RunRecord["status"][]) =>
  1735. journal
  1736. .listRuns({ cwd: "/repo", limit: 20, statuses })
  1737. .map((row) => row.runId)
  1738. .sort();
  1739. expect(ids(["stopped"])).toEqual(["n_stopped", "p_cancelled", "p_interrupted"]);
  1740. expect(ids(["errored"])).toEqual(["p_errored", "p_errored_bare"]);
  1741. expect(ids(["completed", "errored"])).toEqual(["p_completed", "p_errored", "p_errored_bare"]);
  1742. // limit 作用在过滤之后:errored 只有两条时 limit 1 回最近更新的那条,且不被 stopped 行挤占。
  1743. expect(
  1744. journal.listRuns({ cwd: "/repo", limit: 1, statuses: ["errored"] }).map((row) => row.runId),
  1745. ).toEqual(["p_errored"]);
  1746. // 枚举行带 stopReason(逻辑词汇),不带 failure(仍是窄投影)。
  1747. const stopped = journal.listRuns({ cwd: "/repo", limit: 20, statuses: ["stopped"] });
  1748. expect(stopped.find((row) => row.runId === "p_interrupted")).toMatchObject({
  1749. stopReason: "interrupted",
  1750. });
  1751. expect(stopped.find((row) => row.runId === "n_stopped")).toMatchObject({
  1752. stopReason: "provider",
  1753. });
  1754. expect(stopped.every((row) => !("failure" in row))).toBe(true);
  1755. });
  1756. });
  1757. /**
  1758. * 每一世的活动区间(完成卡的时长口径,
  1759. * docs/dynamic-workflow/transcript-and-notifications.md「How long it took」)。
  1760. *
  1761. * 事件的时刻由 appendEvent 打 `Date.now()`,所以「一世持续了多久」在测试里只能事后钉:追加完
  1762. * 事件再按 sequence 改写 `time_created`,模拟一条跑了几个小时、中间被重启打断的 run。改写的是
  1763. * 这条读面唯一读的那一列,查询形状与真库上逐字相同。
  1764. */
  1765. describe("SQLite dwf journal store — listRunLifeSpans", () => {
  1766. const RUN_ID = "run_lives";
  1767. /** 按 sequence 钉住某几条事件的时刻。 */
  1768. function stampEvent(db: DatabaseSync, sequence: number, timeCreated: number): void {
  1769. db.prepare("update dwf_event set time_created = ? where run_id = ? and sequence = ?").run(
  1770. timeCreated,
  1771. RUN_ID,
  1772. sequence,
  1773. );
  1774. }
  1775. function seedLifeRun(): {
  1776. db: DatabaseSync;
  1777. journal: JournalStorePort & DwfRunIntrospectionQueries;
  1778. } {
  1779. const { db, journal } = openIntrospectableJournal();
  1780. journal.createRun({ runId: RUN_ID, caps: CAPS, spentTokens: 0, status: "running" });
  1781. return { db, journal };
  1782. }
  1783. it("单世:从 run-started 到这一世最后一条事件", () => {
  1784. const { db, journal } = seedLifeRun();
  1785. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1786. journal.appendEvent(RUN_ID, { type: "log", message: "工作中" });
  1787. journal.appendEvent(RUN_ID, { type: "run-settled", status: "completed" });
  1788. stampEvent(db, 0, 1_000);
  1789. stampEvent(db, 1, 5_000);
  1790. stampEvent(db, 2, 61_000);
  1791. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([{ startedAt: 1_000, lastActivityAt: 61_000 }]);
  1792. });
  1793. it("多世:每一世各算一段,世与世之间的空档不出现在任何一段里", () => {
  1794. const { db, journal } = seedLifeRun();
  1795. // 第一世:跑了一小时后被重启打断(没有 run-settled)。
  1796. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1797. journal.appendEvent(RUN_ID, { type: "log", message: "第一世的最后一次动作" });
  1798. // 第二世:整个周末之后才 resume,两分钟后完成。
  1799. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1800. journal.appendEvent(RUN_ID, { type: "log", message: "重放" });
  1801. journal.appendEvent(RUN_ID, { type: "run-settled", status: "completed" });
  1802. stampEvent(db, 0, 0);
  1803. stampEvent(db, 1, 3_600_000);
  1804. stampEvent(db, 2, 200_000_000);
  1805. stampEvent(db, 3, 200_060_000);
  1806. stampEvent(db, 4, 200_120_000);
  1807. const spans = journal.listRunLifeSpans(RUN_ID);
  1808. expect(spans).toEqual([
  1809. { startedAt: 0, lastActivityAt: 3_600_000 },
  1810. { startedAt: 200_000_000, lastActivityAt: 200_120_000 },
  1811. ]);
  1812. // 活动时长之和 = 1 小时 + 2 分钟;两世之间那段死时间(≈ 54 小时)不在其中。
  1813. const activeMs = spans.reduce((sum, span) => sum + (span.lastActivityAt - span.startedAt), 0);
  1814. expect(activeMs).toBe(3_600_000 + 120_000);
  1815. });
  1816. it("一世里只有 run-started 一条事件:区间退化成 0,不是 null", () => {
  1817. const { db, journal } = seedLifeRun();
  1818. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1819. stampEvent(db, 0, 7_000);
  1820. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([{ startedAt: 7_000, lastActivityAt: 7_000 }]);
  1821. });
  1822. it("没有 run-started 的 run 与未知 run 都回空数组(无证据,不是 0 时长)", () => {
  1823. const { journal } = seedLifeRun();
  1824. journal.appendEvent(RUN_ID, { type: "log", message: "只有日志" });
  1825. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([]);
  1826. expect(journal.listRunLifeSpans("run_never_seen")).toEqual([]);
  1827. });
  1828. it("只看本 run 的事件:另一条 run 的世不混进来", () => {
  1829. const { db, journal } = seedLifeRun();
  1830. journal.createRun({ runId: "run_other", caps: CAPS, spentTokens: 0, status: "running" });
  1831. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1832. journal.appendEvent("run_other", { type: "run-started", runId: "run_other", caps: CAPS });
  1833. journal.appendEvent("run_other", { type: "log", message: "别人的活" });
  1834. stampEvent(db, 0, 10_000);
  1835. db.prepare("update dwf_event set time_created = ? where run_id = 'run_other'").run(999_000);
  1836. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([
  1837. { startedAt: 10_000, lastActivityAt: 10_000 },
  1838. ]);
  1839. expect(journal.listRunLifeSpans("run_other")).toEqual([
  1840. { startedAt: 999_000, lastActivityAt: 999_000 },
  1841. ]);
  1842. });
  1843. });