v4-native-goal-compact.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // L2:v4 原生 goal/compact 命令组(compact / sendGoalCommand / pauseGoal / resumeGoal)——
  2. // 验证自旧 server-operations compactSession/goalSession 搬运的状态机 barrier 在原生层保真:
  3. // compact 去重幂等、active /goal 入队、重复 set 收敛 replace、goal 续跑的锁生命周期。
  4. import { describe, expect, it, vi } from "vitest";
  5. import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  6. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  7. import type {
  8. V4CommandCoreHost,
  9. V4SessionRecordView,
  10. } from "../src/zcode-protocol-v4/commands/types.js";
  11. function makeApp(overrides: Record<string, unknown> = {}) {
  12. return {
  13. sessionId: "s1",
  14. runtime: {
  15. getActiveTurnInfo: vi.fn().mockReturnValue(undefined),
  16. setExecutionState: vi.fn().mockResolvedValue(undefined),
  17. },
  18. getModel: vi.fn().mockReturnValue("primary-provider/default-model"),
  19. getThoughtLevel: vi.fn().mockReturnValue("high"),
  20. getMode: vi.fn().mockReturnValue("auto"),
  21. submitPrompt: vi.fn().mockResolvedValue({}),
  22. steerTurn: vi.fn().mockResolvedValue({ kind: "queued" }),
  23. setQueueAutoDrain: vi.fn().mockResolvedValue(undefined),
  24. readTarget: vi.fn().mockResolvedValue(null),
  25. setTarget: vi.fn().mockImplementation(async (input: { objective: string }) => ({
  26. targetID: "g1",
  27. objective: input.objective,
  28. status: "active",
  29. })),
  30. updateTargetStatus: vi
  31. .fn()
  32. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "active" }),
  33. continueActiveTarget: vi.fn().mockResolvedValue(null),
  34. ...overrides,
  35. };
  36. }
  37. function makeRecord(
  38. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  39. ): V4SessionRecordView {
  40. return {
  41. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  42. workspace: { workspacePath: "/w" },
  43. persistence: "immediate",
  44. ...overrides,
  45. } as V4SessionRecordView;
  46. }
  47. function makeHost(
  48. record: V4SessionRecordView,
  49. overrides: Partial<V4CommandCoreHost> = {},
  50. ): V4CommandCoreHost & {
  51. legacyMutations: string[];
  52. } {
  53. const legacyMutations: string[] = [];
  54. return {
  55. getRecord: (id) => (id === "s1" ? record : undefined),
  56. afterLegacyStateMutation: async (_r, reason) => {
  57. legacyMutations.push(reason);
  58. },
  59. ...overrides,
  60. legacyMutations,
  61. };
  62. }
  63. function envelope(type: string, payload: unknown): CommandEnvelope {
  64. return {
  65. type,
  66. payload,
  67. sessionId: "s1",
  68. commandId: "cmd-1",
  69. baseRevision: 0,
  70. } as unknown as CommandEnvelope;
  71. }
  72. async function settle() {
  73. // 后台 turn 是 void 起跑的微任务链,flush 两轮保证 finally 执行完。
  74. await new Promise((r) => setTimeout(r, 0));
  75. await new Promise((r) => setTimeout(r, 0));
  76. }
  77. describe("v4 原生 compact", () => {
  78. it("正路径:后台 submitPrompt('/compact') + 上锁 + ready 边界释放", async () => {
  79. let finishCompact!: () => void;
  80. const compactGate = new Promise<Record<string, never>>((resolve) => {
  81. finishCompact = () => resolve({});
  82. });
  83. const app = makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) });
  84. const record = makeRecord({ app });
  85. const host = makeHost(record);
  86. host.recordPersistentCommandFact = vi.fn().mockResolvedValue(undefined);
  87. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  88. // 提交即返:execute 已回,compact 仍挂起 → Stop 可用的锁必须在。
  89. expect(record.activeAbortController).toBeDefined();
  90. expect(app.submitPrompt).toHaveBeenCalledWith(
  91. "/compact",
  92. expect.objectContaining({ inputId: "cmd-1" }),
  93. );
  94. finishCompact();
  95. await settle();
  96. // ready 边界:compact 结束先释放锁再 legacy 广播。
  97. expect(record.activeAbortController).toBeUndefined();
  98. expect(host.recordPersistentCommandFact).toHaveBeenCalledWith(
  99. "s1",
  100. "timeline",
  101. expect.objectContaining({ commandId: "cmd-1", status: "accepted" }),
  102. { lifecycleStatus: "success" },
  103. );
  104. expect(host.legacyMutations).toEqual(["session_compacted"]);
  105. });
  106. it("释放 active lock 后,state mutation 收尾完成前仍持有 residency lease", async () => {
  107. let finishCompact!: () => void;
  108. let finishMutation!: () => void;
  109. let mutationStarted!: () => void;
  110. const compactGate = new Promise<Record<string, never>>((resolve) => {
  111. finishCompact = () => resolve({});
  112. });
  113. const mutationGate = new Promise<void>((resolve) => {
  114. finishMutation = resolve;
  115. });
  116. const mutationStartedGate = new Promise<void>((resolve) => {
  117. mutationStarted = resolve;
  118. });
  119. const record = makeRecord({
  120. app: makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) }),
  121. });
  122. const host = makeHost(record, {
  123. afterLegacyStateMutation: async () => {
  124. mutationStarted();
  125. await mutationGate;
  126. },
  127. });
  128. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  129. expect(record.residencyFinalizationCount).toBe(1);
  130. finishCompact();
  131. await mutationStartedGate;
  132. expect(record.activeAbortController).toBeUndefined();
  133. expect(record.residencyFinalizationCount).toBe(1);
  134. finishMutation();
  135. await settle();
  136. expect(record.residencyFinalizationCount).toBe(0);
  137. });
  138. it("compact 进行中:显式拒绝(不再次提交)", async () => {
  139. const app = makeApp({
  140. runtime: {
  141. getActiveTurnInfo: vi
  142. .fn()
  143. .mockReturnValue({ kind: "compact", queueLength: 0, steerable: false }),
  144. },
  145. });
  146. const controller = new AbortController();
  147. const record = makeRecord({ app, activeAbortController: controller });
  148. const host = makeHost(record);
  149. await expect(
  150. new V4CommandExecutor(host).execute(envelope("compact", {})),
  151. ).rejects.toMatchObject({ reasonCode: "compactOperationLock" });
  152. expect(app.submitPrompt).not.toHaveBeenCalled();
  153. // 显式拒绝不得触碰进行中 compact 的锁。
  154. expect(record.activeAbortController).toBe(controller);
  155. });
  156. it("其他 active turn:/compact 以 typed maintenance intent 入队,不立即提交", async () => {
  157. const app = makeApp({
  158. runtime: {
  159. getActiveTurnInfo: vi
  160. .fn()
  161. .mockReturnValue({ kind: "primaryTurn", queueLength: 0, steerable: true }),
  162. },
  163. });
  164. const record = makeRecord({ app, activeAbortController: new AbortController() });
  165. await new V4CommandExecutor(makeHost(record)).execute(envelope("compact", {}));
  166. expect(app.steerTurn).toHaveBeenCalledWith(
  167. "/compact",
  168. expect.objectContaining({
  169. commandKind: "compact",
  170. delivery: "queue",
  171. inputId: "cmd-1",
  172. intent: expect.objectContaining({
  173. kind: "compact",
  174. text: "/compact",
  175. requestedDelivery: "queue",
  176. }),
  177. }),
  178. );
  179. expect(app.submitPrompt).not.toHaveBeenCalled();
  180. });
  181. it("goal verifier busy routing:即使没有 steerable active turn,也进入 deferred FIFO", async () => {
  182. const enqueueDeferredInput = vi.fn().mockResolvedValue({ kind: "queued" });
  183. const app = makeApp({ enqueueDeferredInput });
  184. const record = makeRecord({ app });
  185. await new V4CommandExecutor(
  186. makeHost(record, { getInputRoutingMode: vi.fn().mockReturnValue("enqueue") }),
  187. ).execute(envelope("compact", {}));
  188. expect(enqueueDeferredInput).toHaveBeenCalledWith(
  189. "/compact",
  190. expect.objectContaining({ commandKind: "compact", delivery: "queue" }),
  191. );
  192. expect(app.submitPrompt).not.toHaveBeenCalled();
  193. });
  194. it("已有 queued compact:compactOperationLock 拒绝,避免 FIFO 内重复维护意图", async () => {
  195. const app = makeApp();
  196. const record = makeRecord({ app });
  197. await expect(
  198. new V4CommandExecutor(
  199. makeHost(record, { hasQueueItemKind: vi.fn().mockReturnValue(true) }),
  200. ).execute(envelope("compact", {})),
  201. ).rejects.toMatchObject({ reasonCode: "compactOperationLock" });
  202. expect(app.steerTurn).not.toHaveBeenCalled();
  203. expect(app.submitPrompt).not.toHaveBeenCalled();
  204. });
  205. it("后台 compact 登记 runtime active turn 前重复提交:同步 operation lock 仍拒绝", async () => {
  206. let finishCompact!: () => void;
  207. const compactGate = new Promise<Record<string, never>>((resolve) => {
  208. finishCompact = () => resolve({});
  209. });
  210. const app = makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) });
  211. const record = makeRecord({ app });
  212. const host = makeHost(record);
  213. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  214. await expect(
  215. new V4CommandExecutor(host).execute({
  216. ...envelope("compact", {}),
  217. commandId: "cmd-2",
  218. }),
  219. ).rejects.toMatchObject({ reasonCode: "compactOperationLock" });
  220. finishCompact();
  221. await settle();
  222. });
  223. it("compact 失败:finally 仍释放锁,reason=session_compact_failed", async () => {
  224. const app = makeApp({
  225. submitPrompt: vi.fn().mockRejectedValue(new Error("boom")),
  226. });
  227. const record = makeRecord({ app });
  228. const host = makeHost(record);
  229. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  230. await settle();
  231. expect(record.activeAbortController).toBeUndefined();
  232. expect(host.legacyMutations).toEqual(["session_compact_failed"]);
  233. });
  234. it("queued compact 失败且后方仍有输入:关闭 autoDrain,保持 FIFO failure barrier", async () => {
  235. const app = makeApp({
  236. submitPrompt: vi.fn().mockRejectedValue(new Error("boom")),
  237. });
  238. const record = makeRecord({ app });
  239. const host = makeHost(record, { getQueueLength: vi.fn().mockReturnValue(1) });
  240. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  241. await settle();
  242. expect(app.setQueueAutoDrain).toHaveBeenCalledWith(false);
  243. expect(host.legacyMutations).toEqual(["session_compact_failed"]);
  244. });
  245. });
  246. describe("v4 原生 sendGoalCommand", () => {
  247. it("set 正路径:setTarget(active) + 后台续跑 + 锁生命周期", async () => {
  248. let finishContinuation!: () => void;
  249. const continuationGate = new Promise<null>((resolve) => {
  250. finishContinuation = () => resolve(null);
  251. });
  252. const app = makeApp({
  253. continueActiveTarget: vi.fn().mockReturnValue(continuationGate),
  254. });
  255. const record = makeRecord({ app });
  256. const host = makeHost(record);
  257. await new V4CommandExecutor(host).execute(
  258. envelope("sendGoalCommand", {
  259. text: " 完成登录页 ",
  260. displayText: "/TaRgEt replace 完成登录页",
  261. modelSelection: {
  262. providerId: "alternate-provider",
  263. modelId: "goal-model",
  264. options: { reasoningLevel: "max" },
  265. },
  266. mode: "yolo",
  267. }),
  268. );
  269. // objective 落库为 trim 后文本,状态直接 active。
  270. expect(app.setTarget).toHaveBeenCalledWith(
  271. expect.objectContaining({
  272. displayText: "/TaRgEt replace 完成登录页",
  273. objective: "完成登录页",
  274. status: "active",
  275. intent: expect.objectContaining({
  276. sourceCommandId: "cmd-1",
  277. modelSelection: {
  278. providerId: "alternate-provider",
  279. modelId: "goal-model",
  280. options: { reasoningLevel: "max" },
  281. },
  282. mode: "yolo",
  283. }),
  284. }),
  285. );
  286. // 续跑期间持锁(连续 /goal 会被 active turn barrier 拒绝)。
  287. expect(record.activeAbortController).toBeDefined();
  288. expect(host.legacyMutations).toEqual(["goal_set"]);
  289. finishContinuation();
  290. await settle();
  291. expect(app.continueActiveTarget).toHaveBeenCalledWith(
  292. expect.objectContaining({
  293. inputId: "cmd-1",
  294. intent: expect.objectContaining({
  295. modelSelection: {
  296. providerId: "alternate-provider",
  297. modelId: "goal-model",
  298. options: { reasoningLevel: "max" },
  299. },
  300. mode: "yolo",
  301. }),
  302. }),
  303. );
  304. // 续跑结束释放锁(旧实现修过的 bug:占锁会让连续 /goal 误判活跃 turn)。
  305. expect(record.activeAbortController).toBeUndefined();
  306. expect(host.legacyMutations).toEqual(["goal_set", "goal_continuation_completed"]);
  307. });
  308. it("重复 set:已有 target 收敛 replace 语义(reason=goal_replaced)", async () => {
  309. const app = makeApp({
  310. readTarget: vi
  311. .fn()
  312. .mockResolvedValue({ targetID: "g0", objective: "旧目标", status: "active" }),
  313. });
  314. const record = makeRecord({ app });
  315. const host = makeHost(record);
  316. await new V4CommandExecutor(host).execute(envelope("sendGoalCommand", { text: "新目标" }));
  317. await settle();
  318. // 不要求用户先 clear/replace:直接覆盖写入新目标。
  319. expect(app.setTarget).toHaveBeenCalledWith(
  320. expect.objectContaining({
  321. displayText: "/goal 新目标",
  322. objective: "新目标",
  323. status: "active",
  324. intent: expect.objectContaining({ sourceCommandId: "cmd-1" }),
  325. }),
  326. );
  327. expect(host.legacyMutations[0]).toBe("goal_replaced");
  328. });
  329. it("active turn 存在:入队为 goal command,不立即写 target", async () => {
  330. const app = makeApp();
  331. const record = makeRecord({ app, activeAbortController: new AbortController() });
  332. await new V4CommandExecutor(makeHost(record)).execute(
  333. envelope("sendGoalCommand", {
  334. text: "x",
  335. displayText: "/target x",
  336. modelSelection: { providerId: "queued-provider", modelId: "queued-model" },
  337. mode: "edit",
  338. }),
  339. );
  340. expect(app.steerTurn).toHaveBeenCalledWith(
  341. "/target x",
  342. expect.objectContaining({
  343. commandKind: "sendGoalCommand",
  344. inputId: "cmd-1",
  345. queryId: "cmd-1",
  346. intent: expect.objectContaining({
  347. kind: "sendGoalCommand",
  348. text: "x",
  349. modelSelection: { providerId: "queued-provider", modelId: "queued-model" },
  350. mode: "edit",
  351. }),
  352. }),
  353. );
  354. expect(app.setTarget).not.toHaveBeenCalled();
  355. });
  356. it("goal verifier routing 早于 controller:/goal 仍进入 deferred FIFO", async () => {
  357. const enqueueDeferredInput = vi.fn().mockResolvedValue({ kind: "queued" });
  358. const app = makeApp({
  359. enqueueDeferredInput,
  360. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue(undefined) },
  361. });
  362. const record = makeRecord({ app });
  363. await new V4CommandExecutor(
  364. makeHost(record, { getInputRoutingMode: vi.fn().mockReturnValue("enqueue") }),
  365. ).execute(envelope("sendGoalCommand", { text: "验证后继续目标" }));
  366. expect(enqueueDeferredInput).toHaveBeenCalledWith(
  367. "/goal 验证后继续目标",
  368. expect.objectContaining({ commandKind: "sendGoalCommand", delivery: "queue" }),
  369. );
  370. expect(app.setTarget).not.toHaveBeenCalled();
  371. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  372. });
  373. it("active turn queue 拒绝:显式失败,不伪装成已受理", async () => {
  374. const app = makeApp({
  375. steerTurn: vi.fn().mockResolvedValue({ kind: "rejected", reason: "input_too_large" }),
  376. });
  377. const record = makeRecord({ app, activeAbortController: new AbortController() });
  378. await expect(
  379. new V4CommandExecutor(makeHost(record)).execute(
  380. envelope("sendGoalCommand", { text: "过大的目标" }),
  381. ),
  382. ).rejects.toMatchObject({ reasonCode: "proto.payloadTooLarge" });
  383. expect(app.setTarget).not.toHaveBeenCalled();
  384. });
  385. it("Plan 与 Goal 互斥:拒绝同时开启,不先落库目标", async () => {
  386. const app = makeApp({ getMode: vi.fn().mockReturnValue("plan") });
  387. const record = makeRecord({ app });
  388. const host = makeHost(record);
  389. await expect(
  390. new V4CommandExecutor(host).execute(envelope("sendGoalCommand", { text: "目标" })),
  391. ).rejects.toMatchObject({ reasonCode: "guard.planGoalMutuallyExclusive" });
  392. await settle();
  393. expect(app.setTarget).not.toHaveBeenCalled();
  394. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  395. expect(record.activeAbortController).toBeUndefined();
  396. expect(host.legacyMutations).toEqual([]);
  397. });
  398. });
  399. describe("v4 原生 resumeGoal", () => {
  400. it("Plan 中不能把暂停目标恢复为 active", async () => {
  401. const app = makeApp({
  402. runtime: { getPlanEnabled: () => true },
  403. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "paused" }),
  404. });
  405. await expect(
  406. new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(envelope("resumeGoal", {})),
  407. ).rejects.toMatchObject({ reasonCode: "guard.planGoalMutuallyExclusive" });
  408. expect(app.updateTargetStatus).not.toHaveBeenCalled();
  409. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  410. });
  411. it("正路径:updateTargetStatus(active) + 后台续跑", async () => {
  412. const app = makeApp();
  413. const record = makeRecord({ app });
  414. const host = makeHost(record);
  415. await new V4CommandExecutor(host).execute(envelope("resumeGoal", {}));
  416. await settle();
  417. expect(app.updateTargetStatus).toHaveBeenCalledWith("active");
  418. expect(app.continueActiveTarget).toHaveBeenCalledWith(
  419. expect.objectContaining({ inputId: "cmd-1" }),
  420. );
  421. expect(record.activeAbortController).toBeUndefined();
  422. expect(host.legacyMutations).toContain("goal_resumed");
  423. expect(host.legacyMutations).toContain("goal_continuation_completed");
  424. });
  425. it("无 target:幂等成功(不抛错、不续跑、不广播)", async () => {
  426. const app = makeApp({ updateTargetStatus: vi.fn().mockResolvedValue(null) });
  427. const record = makeRecord({ app });
  428. const host = makeHost(record);
  429. await expect(
  430. new V4CommandExecutor(host).execute(envelope("resumeGoal", {})),
  431. ).resolves.toBeUndefined();
  432. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  433. expect(host.legacyMutations).toEqual([]);
  434. });
  435. });
  436. describe("v4 原生 pauseGoal", () => {
  437. it("没有 active work 也会独立暂停 target,不触发 stop queue 语义", async () => {
  438. const app = makeApp({
  439. readTarget: vi
  440. .fn()
  441. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "active" }),
  442. updateTargetStatus: vi
  443. .fn()
  444. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "paused" }),
  445. });
  446. const record = makeRecord({ app });
  447. const host = makeHost(record);
  448. await new V4CommandExecutor(host).execute(envelope("pauseGoal", {}));
  449. expect(app.updateTargetStatus).toHaveBeenCalledWith("paused");
  450. expect(app.setQueueAutoDrain).not.toHaveBeenCalled();
  451. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  452. expect(host.legacyMutations).toEqual(["goal_paused"]);
  453. });
  454. it("先结算 paused target,再终止当前 goal work", async () => {
  455. const controller = new AbortController();
  456. const app = makeApp({
  457. readTarget: vi
  458. .fn()
  459. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "active" }),
  460. updateTargetStatus: vi.fn().mockImplementation(async () => {
  461. expect(controller.signal.aborted).toBe(false);
  462. return { targetID: "g1", objective: "旧目标", status: "paused" };
  463. }),
  464. });
  465. const record = makeRecord({ app, activeAbortController: controller });
  466. await new V4CommandExecutor(makeHost(record)).execute(envelope("pauseGoal", {}));
  467. expect(controller.signal.aborted).toBe(true);
  468. });
  469. it("没有 active target 时幂等 noop", async () => {
  470. const app = makeApp();
  471. const host = makeHost(makeRecord({ app }));
  472. await expect(
  473. new V4CommandExecutor(host).execute(envelope("pauseGoal", {})),
  474. ).resolves.toBeUndefined();
  475. expect(app.updateTargetStatus).not.toHaveBeenCalled();
  476. expect(host.legacyMutations).toEqual([]);
  477. });
  478. });
  479. describe("supports 分流(goal/compact 组)", () => {
  480. it("compact/sendGoalCommand/pauseGoal/resumeGoal 已原生", () => {
  481. const executor = new V4CommandExecutor(makeHost(makeRecord()));
  482. expect(executor.supports("compact")).toBe(true);
  483. expect(executor.supports("sendGoalCommand")).toBe(true);
  484. expect(executor.supports("pauseGoal")).toBe(true);
  485. expect(executor.supports("resumeGoal")).toBe(true);
  486. });
  487. });