workflow-runs-holes.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // ============================================================
  2. // workflowRuns 归约的留白分支:`hole-reached` / `hole-filled`,以及阶段表上的留白下标
  3. // ============================================================
  4. // 从 workflow-runs-reducer.ts 拆出(max-lines 门,与 phases / started 同一先例)。
  5. // 契约见 docs/dynamic-workflow/presentation.md「Holes on the timeline」的「The model」一段与
  6. // apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Holes」。
  7. import {
  8. WORKFLOW_RUNS_LIMITS,
  9. type WorkflowRunHole,
  10. type WorkflowRunState,
  11. } from "./workflow-runs.js";
  12. import { boundedPhaseName, nonEmptyString } from "./workflow-runs-entries.js";
  13. /**
  14. * 留白的站点 id:`hole#` 加 8 位十六进制,键是留白的**名字**,与嵌套深度无关(CLI 的
  15. * analysis/hole-id.ts 铸造;apps/zcode-cli/packages/dynamic-workflow/docs/analysis.md「Sites」)。
  16. * id 里不再写嵌套关系:一个留白在哪个留白里面,看它自己的阶段 / 站上的 `fill`。
  17. */
  18. export const WORKFLOW_HOLE_SITE_ID_PATTERN = /^hole#[0-9a-f]{8}$/u;
  19. function readEpoch(value: unknown): number | undefined {
  20. return typeof value === "number" && Number.isFinite(value) && value >= 0
  21. ? Math.floor(value)
  22. : undefined;
  23. }
  24. /**
  25. * `run-launched.holes` / `hole-filled.holes` 的搬运:下标指向**被接受的**那张 `phaseNames`,所以
  26. * 越界、非整数、重复一律丢——越界的下标会让侧栏把一盏虚线灯画到一个不存在的站上。一项都不剩时
  27. * 返回 `undefined`:键不建。
  28. */
  29. export function readPhaseHoles(raw: unknown, count: number): number[] | undefined {
  30. if (!Array.isArray(raw)) return undefined;
  31. const out: number[] = [];
  32. for (const value of raw) {
  33. if (typeof value !== "number" || !Number.isInteger(value)) continue;
  34. if (value < 0 || value >= count || out.includes(value)) continue;
  35. out.push(value);
  36. if (out.length >= WORKFLOW_RUNS_LIMITS.maxPhases) break;
  37. }
  38. return out.length === 0 ? undefined : out;
  39. }
  40. /**
  41. * 载荷上的声明阶段表(`run-launched` 与 `hole-filled` 同形):按声明序、裁到与 `phases` 同一对界。
  42. * 空表返回 `undefined`,调用方据此不动已有的表。
  43. */
  44. export function readPhaseNames(raw: unknown): string[] | undefined {
  45. if (!Array.isArray(raw)) return undefined;
  46. const names: string[] = [];
  47. for (const value of raw) {
  48. if (typeof value !== "string") continue;
  49. const name = value.slice(0, WORKFLOW_RUNS_LIMITS.maxPhaseNameLength);
  50. if (name.length === 0) continue;
  51. names.push(name);
  52. if (names.length >= WORKFLOW_RUNS_LIMITS.maxPhases) break;
  53. }
  54. return names.length === 0 ? undefined : names;
  55. }
  56. /**
  57. * `hole-reached`:run 走到一个开着的留白,那条分支停驻。按**站点 id** upsert——循环里同一站点会停驻
  58. * 第二个 ordinal,表里只留最新的;重放同一条事件逐字节无变化(顶层的结构比对随即返回 null)。
  59. * `name` 是这条记录存在的全部理由(每个面都按名字标它),缺席只抬水位。触界与 nodes / actors 同族:
  60. * 拒绝新条目、已有条目照常更新、置 truncated。
  61. */
  62. /** 提示语截到上限:超长时留 499 字加 `…`,总长仍是 500。 */
  63. function boundedHolePrompt(raw: string | undefined): string | undefined {
  64. if (raw === undefined) return undefined;
  65. const max = WORKFLOW_RUNS_LIMITS.maxHolePromptLength;
  66. return raw.length <= max ? raw : `${raw.slice(0, max - 1)}…`;
  67. }
  68. export function reduceHoleReached(
  69. run: WorkflowRunState,
  70. payload: Record<string, unknown>,
  71. ): WorkflowRunState {
  72. const instance = payload.instance;
  73. if (typeof instance !== "object" || instance === null) return run;
  74. const siteId = nonEmptyString((instance as Record<string, unknown>).siteId);
  75. const ordinalRaw = (instance as Record<string, unknown>).ordinal;
  76. const ordinal = typeof ordinalRaw === "number" && Number.isInteger(ordinalRaw) ? ordinalRaw : 0;
  77. const name = boundedPhaseName(nonEmptyString(payload.name));
  78. if (siteId === undefined || name === undefined) return run;
  79. const type = nonEmptyString(payload.type)?.slice(0, WORKFLOW_RUNS_LIMITS.maxHoleTypeLength);
  80. const prompt = boundedHolePrompt(nonEmptyString(payload.prompt));
  81. // 到达时刻只能由事件携带(本模块无时钟);两个键名都认:`reachedAt` 是通知载荷的词,`since` 是投影的词。
  82. const since = readEpoch(payload.reachedAt) ?? readEpoch(payload.since);
  83. const entry: WorkflowRunHole = {
  84. siteId,
  85. ordinal,
  86. name,
  87. ...(type === undefined ? {} : { type }),
  88. ...(prompt === undefined ? {} : { prompt }),
  89. state: "waiting",
  90. ...(since === undefined ? {} : { since }),
  91. };
  92. const existing = run.holes ?? [];
  93. const index = existing.findIndex((hole) => hole.siteId === siteId);
  94. if (index >= 0) {
  95. // 已有记录(含补全过又被重新到达的——那是 resume 重放到一个还没补的站点):换成 waiting,
  96. // 类型缺席时沿用记过的那个。
  97. const previous = existing[index]!;
  98. const merged: WorkflowRunHole = {
  99. ...entry,
  100. ...(entry.type === undefined && previous.type !== undefined ? { type: previous.type } : {}),
  101. ...(entry.prompt === undefined && previous.prompt !== undefined
  102. ? { prompt: previous.prompt }
  103. : {}),
  104. };
  105. return { ...run, holes: existing.map((hole, i) => (i === index ? merged : hole)) };
  106. }
  107. if (existing.length >= WORKFLOW_RUNS_LIMITS.maxHoles) return { ...run, truncated: true };
  108. return { ...run, holes: [...existing, entry] };
  109. }
  110. /**
  111. * `hole-filled`:主代理的补全接进了 run。三件事一步做完——那条记录翻成 filled、阶段表换成补全后的
  112. * 声明表(超集:留白的体在留白的位置展开)、留白下标表整张换新。「同时在跑」表按插入位置右移:
  113. * 补全只在留白那一站之后插入 k 站,旧表里 > h 的下标一律 +k;表的形状对不上(不是这种插入)就丢掉,
  114. * 宁可侧栏少画双线段,也不把它连到错的站上。
  115. */
  116. export function reduceHoleFilled(
  117. run: WorkflowRunState,
  118. payload: Record<string, unknown>,
  119. ): WorkflowRunState {
  120. const siteId = nonEmptyString(payload.siteId);
  121. if (siteId === undefined) return run;
  122. const filledAt = readEpoch(payload.filledAt);
  123. const filledBy = nonEmptyString(payload.filledBy)?.slice(0, 128);
  124. let next: WorkflowRunState = run;
  125. const existing = run.holes ?? [];
  126. const index = existing.findIndex((hole) => hole.siteId === siteId);
  127. if (index >= 0) {
  128. // 提示语只为等待体而存在:补全后丢掉,已结算的 run 状态不背着它。
  129. const { prompt: _prompt, ...reached } = existing[index]!;
  130. void _prompt;
  131. const filled: WorkflowRunHole = {
  132. ...reached,
  133. state: "filled",
  134. ...(filledAt === undefined ? {} : { filledAt }),
  135. ...(filledBy === undefined ? {} : { filledBy }),
  136. };
  137. next = { ...next, holes: existing.map((hole, i) => (i === index ? filled : hole)) };
  138. }
  139. const phaseNames = readPhaseNames(payload.phaseNames);
  140. if (phaseNames === undefined) return next;
  141. const phaseHoles = readPhaseHoles(payload.holes, phaseNames.length);
  142. const phaseAlongside = shiftPhaseAlongside(run, phaseNames);
  143. const { phaseAlongside: _stale, phaseHoles: _staleHoles, ...rest } = next;
  144. void [_stale, _staleHoles];
  145. return {
  146. ...rest,
  147. phaseNames,
  148. ...(phaseAlongside === undefined ? {} : { phaseAlongside }),
  149. ...(phaseHoles === undefined ? {} : { phaseHoles }),
  150. };
  151. }
  152. /** 旧表 + 「留白位置之后插入 k 站」 → 新表上的「同时在跑」下标;形状对不上返回 undefined。 */
  153. function shiftPhaseAlongside(
  154. run: WorkflowRunState,
  155. names: readonly string[],
  156. ): number[][] | undefined {
  157. const old = run.phaseNames;
  158. const alongside = run.phaseAlongside;
  159. if (old === undefined || alongside === undefined) return undefined;
  160. const inserted = names.length - old.length;
  161. if (inserted < 0) return undefined;
  162. // 找插入点 h:前缀 old[0..h] 与后缀 old[h+1..] 都逐字相同。
  163. let h = -1;
  164. for (let i = 0; i < old.length; i += 1) {
  165. if (old[i] !== names[i]) break;
  166. h = i;
  167. }
  168. if (h < 0) return undefined;
  169. for (let i = h + 1; i < old.length; i += 1) {
  170. if (old[i] !== names[i + inserted]) return undefined;
  171. }
  172. const shift = (i: number): number => (i <= h ? i : i + inserted);
  173. const out: number[][] = [];
  174. for (let i = 0; i < names.length; i += 1) {
  175. const source = i <= h ? i : i - inserted;
  176. const entry = i > h && i <= h + inserted ? [] : (alongside[source] ?? []);
  177. out.push(entry.map(shift));
  178. }
  179. return out.some((entry) => entry.length > 0) ? out : undefined;
  180. }
  181. /**
  182. * 剥掉 waiting 记录(新的一世 / 终态):真相是进程内的停驻 deferred,与 pendingQuestions 同一条理由——
  183. * 一个已停的 run 没有人在等补全;resume 重跑到那个站点会再发一条 `hole-reached`。filled 记录跨世保留:
  184. * 那是接进 run 的代码,不是残影。一条不剩时整个键摘掉。
  185. */
  186. export function withoutWaitingHoles(run: WorkflowRunState): WorkflowRunState {
  187. if (run.holes === undefined) return run;
  188. const kept = run.holes.filter((hole) => hole.state === "filled");
  189. if (kept.length === run.holes.length) return run;
  190. const { holes: _dropped, ...rest } = run;
  191. void _dropped;
  192. return kept.length === 0 ? rest : { ...rest, holes: kept };
  193. }