auto-driver.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /**
  2. * AutoDriver:集成测试用的**自治** fake driver——同时扮演 Boundary B 的 driver port 与"模型"。
  3. * 引擎核心的 fake-driver 套件(pure 包 tests/engine)里由 test 手动调 report sink;本包的集成测试
  4. * 需要一个能在 `startAsk` 到达时**自动**按脚本回报(stats + submit/turn-end/fail)的 driver,
  5. * 因为沙箱子进程是实时跑的,test 无法逐拍插手。
  6. *
  7. * 不用 timer / 时钟 / 会话 / 磁盘:回报经 queueMicrotask 异步推进(避免在引擎调用栈里同步重入)。
  8. * 与 pure 包的 FakeDriver 是同一模式的自治版,按房规不跨包 import 测试树——独立实现于此。
  9. */
  10. import type {
  11. ActorRef,
  12. ArtifactPublishRequest,
  13. ArtifactVersionRecord,
  14. AskMessage,
  15. AskStats,
  16. InstanceRef,
  17. JournalStorePort,
  18. PersonaSpec,
  19. RunEvent,
  20. SessionRef,
  21. SubmitVerdict,
  22. WorkflowDriver,
  23. WorkflowError,
  24. WorkflowReportSink,
  25. WorldReadOp,
  26. } from "@zcode/dynamic-workflow";
  27. import { refToString } from "@zcode/dynamic-workflow";
  28. /** 单次 ask 派发后,driver 代"模型"要做的一步动作。 */
  29. export type AskAction =
  30. /**
  31. * `delayMs`:这一步不在微任务上、而是在真定时器之后才执行。给「谁先结算」承重的测试用:两个
  32. * 请求行可能落在子进程 stdout 的两个 chunk 里、被父进程在两个 tick 里准入,此时「多一个来回
  33. * 就晚结算」的微任务计数论证不再成立,只有真时间差能钉住次序(resume.test.ts)。
  34. */
  35. | { type: "submit"; payload: unknown; stats?: AskStats; delayMs?: number }
  36. | { type: "text"; finalText: string; stats?: AskStats }
  37. | { type: "fail"; error: WorkflowError }
  38. /** 确定性模型侧错误:driver 不结算节点,经 `stopRun` 让整个 run 停下(ProviderStop)。 */
  39. | { type: "stop-run"; error: WorkflowError };
  40. /** 某 ask 站点的应答器:据实例/消息给出一步或一串动作(串用于 repair/nudge 序列)。 */
  41. export type AskResponder = (ctx: { instance: InstanceRef; message: AskMessage }) => AskAction | AskAction[];
  42. export interface AutoDriverConfig {
  43. /** 按 site id 的 ask 应答器。typed ask 必须给(否则默认提交 `{}`,多半校验失败)。 */
  44. asks?: Record<string, AskResponder>;
  45. /** world-read 处理器(args 为位置实参数组);缺省对 glob 返回 []、对 read 返回 ""。 */
  46. worldReads?: (op: WorldReadOp, args: unknown[]) => unknown | Promise<unknown>;
  47. /**
  48. * 内容产物的发布处理器(用户面产物,docs/dynamic-workflow/authoring.md)。缺省回一条按请求
  49. * 回显的记录——真 driver 在这里读字节写 store,集成测试只关心请求形状与记录能不能原样
  50. * 回到 journal。抛错/拒绝即模拟 `ArtifactSourceMissing` 那一族的节点级拒绝。
  51. */
  52. artifacts?: (request: ArtifactPublishRequest) => ArtifactVersionRecord | Promise<ArtifactVersionRecord>;
  53. /** startAsk 钩子(resume 测试用它断言"零派发"或主动失败)。 */
  54. onStartAsk?: (instance: InstanceRef, message: AskMessage) => void;
  55. }
  56. interface StartAskCall {
  57. session: SessionRef;
  58. instance: InstanceRef;
  59. message: AskMessage;
  60. }
  61. export class AutoDriver implements WorkflowDriver {
  62. readonly events: RunEvent[] = [];
  63. readonly startAsks: StartAskCall[] = [];
  64. readonly sessionCreations: ActorRef[] = [];
  65. readonly cancels: InstanceRef[] = [];
  66. /** 每次内容产物发布收到的请求(断言线协议与引擎透传)。 */
  67. readonly artifactPublishes: ArtifactPublishRequest[] = [];
  68. private sink: WorkflowReportSink | undefined;
  69. private readonly scripts = new Map<string, { actions: AskAction[]; idx: number }>();
  70. constructor(
  71. readonly journal: JournalStorePort,
  72. private readonly config: AutoDriverConfig = {},
  73. ) {}
  74. /** harness 构造引擎后回填 sink(打破 driver↔engine 环依赖)。 */
  75. attach(sink: WorkflowReportSink): void {
  76. this.sink = sink;
  77. }
  78. createActorSession(actor: ActorRef, _persona: PersonaSpec): Promise<SessionRef> {
  79. this.sessionCreations.push(actor);
  80. return Promise.resolve({ id: `session:${refToString(actor)}` });
  81. }
  82. startAsk(session: SessionRef, instance: InstanceRef, message: AskMessage): void {
  83. this.startAsks.push({ session, instance, message });
  84. this.config.onStartAsk?.(instance, message);
  85. const responder = this.config.asks?.[instance.siteId];
  86. const raw = responder ? responder({ instance, message }) : defaultAction(message);
  87. const actions = Array.isArray(raw) ? raw : [raw];
  88. this.scripts.set(refToString(instance), { actions, idx: 0 });
  89. this.perform(instance);
  90. }
  91. respondToSubmit(instance: InstanceRef, verdict: SubmitVerdict): void {
  92. if (verdict.kind === "accept") return;
  93. // reject / nudge → 推进到下一步动作(脚本化 repair/nudge 序列)。
  94. const script = this.scripts.get(refToString(instance));
  95. if (script === undefined) return;
  96. script.idx++;
  97. this.perform(instance);
  98. }
  99. cancelAsk(instance: InstanceRef): void {
  100. this.cancels.push(instance);
  101. }
  102. executeWorldRead(op: WorldReadOp, args: unknown[]): Promise<unknown> {
  103. const handler = this.config.worldReads ?? defaultWorldRead;
  104. return Promise.resolve(handler(op, args));
  105. }
  106. // async 而不是 `Promise.resolve(handler(...))`:处理器同步抛出时,后者会让异常从
  107. // executeArtifactPublish **同步**逃出去,落在 harness 的 readline 回调里变成一个没人接的
  108. // 异常,run 随之永远挂着。async 把同步抛出转成拒绝——真 driver 是 async 方法,天然如此。
  109. async executeArtifactPublish(request: ArtifactPublishRequest): Promise<ArtifactVersionRecord> {
  110. this.artifactPublishes.push(request);
  111. const handler = this.config.artifacts ?? defaultArtifactPublish;
  112. return handler(request);
  113. }
  114. emit(event: RunEvent): void {
  115. this.events.push(event);
  116. }
  117. private perform(instance: InstanceRef): void {
  118. const script = this.scripts.get(refToString(instance));
  119. if (script === undefined) return;
  120. const action = script.actions[script.idx];
  121. if (action === undefined) return; // 无更多动作:引擎会耗尽 repair/nudge 后自行结算失败。
  122. const delayMs = action.type === "submit" ? action.delayMs : undefined;
  123. const schedule = (fn: () => void): void => {
  124. if (delayMs === undefined) queueMicrotask(fn);
  125. else setTimeout(fn, delayMs);
  126. };
  127. schedule(() => {
  128. const sink = this.sink;
  129. if (sink === undefined) throw new Error("AutoDriver: sink 未 attach");
  130. if (action.type !== "fail" && action.type !== "stop-run" && action.stats !== undefined)
  131. sink.askStats(instance, action.stats);
  132. switch (action.type) {
  133. case "submit":
  134. sink.askSubmitAttempted(instance, action.payload);
  135. return;
  136. case "text":
  137. sink.askTurnEnded(instance, action.finalText);
  138. return;
  139. case "fail":
  140. sink.askFailed(instance, action.error);
  141. return;
  142. case "stop-run":
  143. sink.stopRun(action.error);
  144. return;
  145. }
  146. });
  147. }
  148. // ——————————————————————————————— 断言辅助 ———————————————————————————————
  149. startAskCount(): number {
  150. return this.startAsks.length;
  151. }
  152. eventsOfType<T extends RunEvent["type"]>(type: T): Array<Extract<RunEvent, { type: T }>> {
  153. return this.events.filter((e) => e.type === type) as Array<Extract<RunEvent, { type: T }>>;
  154. }
  155. }
  156. /** 无应答器时的兜底:untyped ask 回一句最终文本;typed ask 提交 `{}`(多半校验失败,仅兜底)。 */
  157. function defaultAction(message: AskMessage): AskAction {
  158. return message.typed ? { type: "submit", payload: {} } : { type: "text", finalText: "ok" };
  159. }
  160. /** 缺省的产物发布:按请求回显一条记录(字节的家在 store,测试不关心它)。 */
  161. function defaultArtifactPublish(request: ArtifactPublishRequest): ArtifactVersionRecord {
  162. return {
  163. id: request.id,
  164. kind: request.op,
  165. version: request.version,
  166. contentType: request.op === "markdown" ? "text/markdown" : "application/octet-stream",
  167. bytes: (request.content ?? request.path ?? "").length,
  168. uri: `zcode-artifact://auto/${request.id}/${request.version}`,
  169. ...(request.path === undefined ? {} : { sourcePath: request.path }),
  170. publishedAt: 1,
  171. };
  172. }
  173. /** 缺省 world-read:glob → [],read → ""。 */
  174. function defaultWorldRead(op: WorldReadOp): unknown {
  175. return op === "glob" ? [] : "";
  176. }