workspace-hook-runtime-admission.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { createConfig } from "@zcode/adapters/config";
  6. import {
  7. createDefaultFileWorkspaceHookTrustStore,
  8. createInMemorySessionEventStore,
  9. createSqliteSessionStore,
  10. } from "@zcode/adapters/storage";
  11. import { createWorkspaceHookTrustRecords } from "@zcode/core";
  12. import { SessionEventType, type ExecutionPort } from "@zcode/contracts";
  13. import { createRegistryBackedTestApp as createZCodeApp } from "./helpers/registry-backed-test-app.js";
  14. const roots: string[] = [];
  15. afterEach(async () => {
  16. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  17. });
  18. describe("createZCodeApp workspace Hook admission", () => {
  19. it("首次 activation 等待 Trust store load;pending blocked,exact pretrust 后执行同一 snapshot", async () => {
  20. const root = await mkdtemp(join(tmpdir(), "zcode-workspace-hook-runtime-"));
  21. roots.push(root);
  22. const workspace = join(root, "workspace");
  23. const userConfigPath = join(root, "home", "config.json");
  24. const storageRoot = join(root, "storage");
  25. await mkdir(join(workspace, ".git"), { recursive: true });
  26. await mkdir(join(workspace, ".zcode"), { recursive: true });
  27. await mkdir(join(root, "home"), { recursive: true });
  28. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: storageRoot } }));
  29. await writeFile(
  30. join(workspace, ".zcode", "config.json"),
  31. JSON.stringify({
  32. hooks: {
  33. enabled: true,
  34. events: {
  35. SessionStart: [
  36. {
  37. matcher: "startup",
  38. hooks: [{ type: "command", command: "echo trusted-project-hook" }],
  39. },
  40. ],
  41. },
  42. },
  43. }),
  44. );
  45. const blockedCommands: string[] = [];
  46. const blockedEvents = createInMemorySessionEventStore();
  47. const blockedSessionStore = await createSqliteSessionStore({
  48. dbPath: ":memory:",
  49. });
  50. const blockedApp = await createZCodeApp({
  51. env: {},
  52. eventStore: blockedEvents,
  53. executionPort: executionPort(blockedCommands),
  54. modelExecutor: stopModelExecutor(),
  55. runtimeConfig: {
  56. mcp: { enabled: false, servers: {} },
  57. workingDirectory: workspace,
  58. },
  59. sessionStore: blockedSessionStore,
  60. userConfigPath,
  61. workspaceHookTrustEnabled: true,
  62. });
  63. try {
  64. await blockedApp.submitPrompt("hello");
  65. expect(blockedCommands).toEqual([]);
  66. const events = await blockedEvents.getEvents(blockedApp.sessionId);
  67. expect(events).toContainEqual(
  68. expect.objectContaining({
  69. type: SessionEventType.HookRunBlocked,
  70. payload: expect.objectContaining({
  71. descriptor: expect.objectContaining({ sourceKind: "project" }),
  72. errorCode: "workspace_hooks_pending_trust",
  73. }),
  74. }),
  75. );
  76. } finally {
  77. await blockedApp.close();
  78. blockedSessionStore.close();
  79. }
  80. const configResult = createConfig({
  81. env: {},
  82. userConfigPath,
  83. workingDirectory: workspace,
  84. });
  85. const snapshot = configResult.sources.project.workspaceHookSnapshot;
  86. if (!snapshot) throw new Error("expected workspace Hook snapshot");
  87. const trustStore = await createDefaultFileWorkspaceHookTrustStore({
  88. userConfigPath,
  89. });
  90. await trustStore.grant(
  91. createWorkspaceHookTrustRecords({
  92. snapshot,
  93. reviewItemIds: snapshot.hooks.map((entry) => entry.reviewItemId),
  94. grantedAt: "2026-08-06T00:00:00.000Z",
  95. }),
  96. );
  97. const trustedCommands: string[] = [];
  98. const trustedEvents = createInMemorySessionEventStore();
  99. const trustedSessionStore = await createSqliteSessionStore({
  100. dbPath: ":memory:",
  101. });
  102. const trustedApp = await createZCodeApp({
  103. env: {},
  104. eventStore: trustedEvents,
  105. executionPort: executionPort(trustedCommands),
  106. modelExecutor: stopModelExecutor(),
  107. runtimeConfig: {
  108. mcp: { enabled: false, servers: {} },
  109. workingDirectory: workspace,
  110. },
  111. sessionStore: trustedSessionStore,
  112. userConfigPath,
  113. workspaceHookTrustEnabled: true,
  114. });
  115. try {
  116. await trustedApp.submitPrompt("hello");
  117. expect(trustedCommands).toEqual(["echo trusted-project-hook"]);
  118. const events = await trustedEvents.getEvents(trustedApp.sessionId);
  119. expect(
  120. events.some(
  121. (event) =>
  122. event.type === SessionEventType.HookRunStarted &&
  123. event.payload.descriptor?.sourceKind === "project",
  124. ),
  125. ).toBe(true);
  126. } finally {
  127. await trustedApp.close();
  128. trustedSessionStore.close();
  129. }
  130. });
  131. it("feature flag 关闭时即使已有 persistent Trust 也不执行且不发 review", async () => {
  132. const root = await mkdtemp(join(tmpdir(), "zcode-workspace-hook-rollout-off-"));
  133. roots.push(root);
  134. const workspace = join(root, "workspace");
  135. const userConfigPath = join(root, "home", "config.json");
  136. const storageRoot = join(root, "storage");
  137. await mkdir(join(workspace, ".git"), { recursive: true });
  138. await mkdir(join(workspace, ".zcode"), { recursive: true });
  139. await mkdir(join(root, "home"), { recursive: true });
  140. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: storageRoot } }));
  141. await writeFile(
  142. join(workspace, ".zcode", "config.json"),
  143. JSON.stringify({
  144. hooks: {
  145. enabled: true,
  146. events: {
  147. SessionStart: [{ hooks: [{ type: "command", command: "echo rollout-off" }] }],
  148. },
  149. },
  150. }),
  151. );
  152. const configResult = createConfig({
  153. env: {},
  154. userConfigPath,
  155. workingDirectory: workspace,
  156. });
  157. const snapshot = configResult.sources.project.workspaceHookSnapshot;
  158. if (!snapshot) throw new Error("expected workspace Hook snapshot");
  159. const trustStore = await createDefaultFileWorkspaceHookTrustStore({
  160. userConfigPath,
  161. });
  162. await trustStore.grant(
  163. createWorkspaceHookTrustRecords({
  164. snapshot,
  165. reviewItemIds: snapshot.hooks.map((entry) => entry.reviewItemId),
  166. grantedAt: "2026-08-06T00:00:00.000Z",
  167. }),
  168. );
  169. const commands: string[] = [];
  170. const events = createInMemorySessionEventStore();
  171. const sessionStore = await createSqliteSessionStore({ dbPath: ":memory:" });
  172. const app = await createZCodeApp({
  173. env: {},
  174. eventStore: events,
  175. executionPort: executionPort(commands),
  176. modelExecutor: stopModelExecutor(),
  177. runtimeConfig: {
  178. mcp: { enabled: false, servers: {} },
  179. workingDirectory: workspace,
  180. },
  181. sessionStore,
  182. userConfigPath,
  183. workspaceHookTrustEnabled: false,
  184. workspaceHookReviewHost: {
  185. taskId: "task-rollout-off",
  186. runId: "run-rollout-off",
  187. workspaceLabel: "Rollout off",
  188. },
  189. });
  190. try {
  191. await app.submitPrompt("hello");
  192. expect(commands).toEqual([]);
  193. const recorded = await events.getEvents(app.sessionId);
  194. expect(recorded).toContainEqual(
  195. expect.objectContaining({
  196. type: SessionEventType.HookRunBlocked,
  197. payload: expect.objectContaining({
  198. errorCode: "workspace_hooks_feature_disabled",
  199. }),
  200. }),
  201. );
  202. expect(
  203. recorded.some((event) => event.type === SessionEventType.WorkspaceHookReviewRequested),
  204. ).toBe(false);
  205. } finally {
  206. await app.close();
  207. sessionStore.close();
  208. }
  209. });
  210. it("软门禁:activation 跳过 pending hooks,信任选中项后只更新后续准入", async () => {
  211. const root = await mkdtemp(join(tmpdir(), "zcode-workspace-hook-review-runtime-"));
  212. roots.push(root);
  213. const workspace = join(root, "workspace");
  214. const userConfigPath = join(root, "home", "config.json");
  215. const storageRoot = join(root, "storage");
  216. await mkdir(join(workspace, ".git"), { recursive: true });
  217. await mkdir(join(workspace, ".zcode"), { recursive: true });
  218. await mkdir(join(root, "home"), { recursive: true });
  219. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: storageRoot } }));
  220. await writeFile(
  221. join(workspace, ".zcode", "config.json"),
  222. JSON.stringify({
  223. hooks: {
  224. enabled: true,
  225. events: {
  226. SessionStart: [{ hooks: [{ type: "command", command: "echo reviewed-once" }] }],
  227. },
  228. },
  229. }),
  230. );
  231. const commands: string[] = [];
  232. const eventStore = createInMemorySessionEventStore();
  233. const sessionStore = await createSqliteSessionStore({ dbPath: ":memory:" });
  234. const app = await createZCodeApp({
  235. env: {},
  236. eventStore,
  237. executionPort: executionPort(commands),
  238. modelExecutor: stopModelExecutor(),
  239. runtimeConfig: {
  240. mcp: { enabled: false, servers: {} },
  241. workingDirectory: workspace,
  242. },
  243. sessionStore,
  244. userConfigPath,
  245. workspaceHookTrustEnabled: true,
  246. workspaceHookReviewHost: {
  247. taskId: "task-review",
  248. runId: "run-review",
  249. workspaceLabel: "Review workspace",
  250. },
  251. });
  252. try {
  253. // 软门禁:prompt 触发 activation,pending hooks 直接跳过,turn 照常执行
  254. const prompt = app.submitPrompt("hello");
  255. await prompt;
  256. // pending hooks 被跳过,命令未执行
  257. expect(commands).toEqual([]);
  258. // admission updated 事件已发出(pendingCount > 0)
  259. const admissionEvent = await waitForEvent(
  260. eventStore,
  261. app.sessionId,
  262. SessionEventType.WorkspaceHookAdmissionUpdated,
  263. );
  264. expect(admissionEvent.payload).toMatchObject({ pendingCount: 1 });
  265. // 用户点击「去审核」→ 开 review flow
  266. const admissionSnapshot = admissionEvent.payload as {
  267. bundleDigest: string;
  268. workspaceIdentity?: string;
  269. };
  270. await app.requestWorkspaceHookReview({
  271. workspaceIdentity: admissionSnapshot.workspaceIdentity!,
  272. bundleDigest: admissionSnapshot.bundleDigest,
  273. });
  274. const requestEvent = await waitForEvent(
  275. eventStore,
  276. app.sessionId,
  277. SessionEventType.WorkspaceHookReviewRequested,
  278. );
  279. const request = (requestEvent.payload as { request: any }).request;
  280. // 持久信任选中项;已错过的 SessionStart 不会在当前任务追补。
  281. await expect(
  282. app.respondWorkspaceHookReview({
  283. sessionId: app.sessionId,
  284. taskId: request.taskId,
  285. runId: request.runId,
  286. ...(request.remoteSessionId ? { remoteSessionId: request.remoteSessionId } : {}),
  287. workspaceIdentity: request.workspaceIdentity,
  288. bundleDigest: request.bundleDigest,
  289. reviewFlowId: request.reviewFlowId,
  290. generation: request.generation,
  291. interactionId: request.interactionId,
  292. decision: {
  293. action: "trust_selected",
  294. reviewItemIds: [request.items[0].reviewItemId],
  295. },
  296. }),
  297. ).resolves.toMatchObject({ accepted: true });
  298. const events = await eventStore.getEvents(app.sessionId);
  299. expect(events).toContainEqual(
  300. expect.objectContaining({
  301. type: SessionEventType.WorkspaceHookReviewSettled,
  302. payload: expect.objectContaining({
  303. interactionId: request.interactionId,
  304. state: "resolved",
  305. }),
  306. }),
  307. );
  308. expect(commands).toEqual([]);
  309. // 软门禁(D2):settle 后 admission updated 重算 pendingCount=0
  310. expect(events).toContainEqual(
  311. expect.objectContaining({
  312. type: SessionEventType.WorkspaceHookAdmissionUpdated,
  313. payload: expect.objectContaining({ pendingCount: 0 }),
  314. }),
  315. );
  316. } finally {
  317. await app.close();
  318. sessionStore.close();
  319. }
  320. });
  321. // Bug 回归(H1 症状 1+2):两个 SessionStart 声明,一个 configured-disabled
  322. // (admission skipLifecycle),一个 pending(admission blocked 但参与生命周期)。
  323. // 修复前:clientVisibleHookCount=2,skipLifecycle 的 hook 不发事件 → 投影层
  324. // executions.length(1) < hookCount(2) → 行永久 running,UI 计时器走秒不终止。
  325. // 修复后:skipLifecycle 的 hook 从参与列表剔除 → hookCount=1,1 条 blocked
  326. // execution,state 终态。
  327. it("H1 场景 A:configured-disabled + pending SessionStart → hookCount=1、1 blocked、state 终态", async () => {
  328. const root = await mkdtemp(join(tmpdir(), "zcode-hook-h1-scenario-a-"));
  329. roots.push(root);
  330. const workspace = join(root, "workspace");
  331. const userConfigPath = join(root, "home", "config.json");
  332. const storageRoot = join(root, "storage");
  333. await mkdir(join(workspace, ".git"), { recursive: true });
  334. await mkdir(join(workspace, ".zcode"), { recursive: true });
  335. await mkdir(join(root, "home"), { recursive: true });
  336. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: storageRoot } }));
  337. await writeFile(
  338. join(workspace, ".zcode", "config.json"),
  339. JSON.stringify({
  340. hooks: {
  341. enabled: true,
  342. events: {
  343. SessionStart: [
  344. {
  345. hooks: [
  346. {
  347. type: "command",
  348. command: "echo session-start-a",
  349. enabled: false,
  350. },
  351. ],
  352. },
  353. {
  354. hooks: [{ type: "command", command: "echo session-start-b" }],
  355. },
  356. ],
  357. },
  358. },
  359. }),
  360. );
  361. const commands: string[] = [];
  362. const eventStore = createInMemorySessionEventStore();
  363. const sessionStore = await createSqliteSessionStore({ dbPath: ":memory:" });
  364. const app = await createZCodeApp({
  365. env: {},
  366. eventStore,
  367. executionPort: executionPort(commands),
  368. modelExecutor: stopModelExecutor(),
  369. runtimeConfig: {
  370. mcp: { enabled: false, servers: {} },
  371. workingDirectory: workspace,
  372. },
  373. sessionStore,
  374. userConfigPath,
  375. workspaceHookTrustEnabled: true,
  376. });
  377. try {
  378. await app.submitPrompt("hello");
  379. // configured-disabled 的 hook 不执行命令
  380. // pending 的 hook 也被 blocked → 无命令执行
  381. expect(commands).toEqual([]);
  382. const events = await eventStore.getEvents(app.sessionId);
  383. const hookLifecycleEvents = events.filter(
  384. (event) =>
  385. event.type === SessionEventType.HookRunBlocked ||
  386. event.type === SessionEventType.HookRunStarted ||
  387. event.type === SessionEventType.HookRunCompleted ||
  388. event.type === SessionEventType.HookRunFailed,
  389. );
  390. // 只有 1 条 blocked execution(pending 的 B),configured-disabled 的 A 完全不可见
  391. expect(hookLifecycleEvents).toHaveLength(1);
  392. expect(hookLifecycleEvents[0]?.type).toBe(SessionEventType.HookRunBlocked);
  393. const payload = hookLifecycleEvents[0]?.payload as Record<string, unknown>;
  394. // hookCount 必须是 1,否则投影层会等一个永远不来的 execution(H1 核心断言)
  395. expect(payload.hookCount).toBe(1);
  396. expect(payload.errorCode).toBe("workspace_hooks_pending_trust");
  397. expect(payload.descriptor).toMatchObject({
  398. commandDisplay: "echo session-start-b",
  399. });
  400. } finally {
  401. await app.close();
  402. sessionStore.close();
  403. }
  404. });
  405. // 持久信任只影响之后自然发生的生命周期事件;SessionStart 不做 catch-up。
  406. it("两个 pending SessionStart 信任后,当前任务后续 turn 不补跑", async () => {
  407. const root = await mkdtemp(join(tmpdir(), "zcode-hook-h2-scenario-b-"));
  408. roots.push(root);
  409. const workspace = join(root, "workspace");
  410. const userConfigPath = join(root, "home", "config.json");
  411. const storageRoot = join(root, "storage");
  412. await mkdir(join(workspace, ".git"), { recursive: true });
  413. await mkdir(join(workspace, ".zcode"), { recursive: true });
  414. await mkdir(join(root, "home"), { recursive: true });
  415. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: storageRoot } }));
  416. await writeFile(
  417. join(workspace, ".zcode", "config.json"),
  418. JSON.stringify({
  419. hooks: {
  420. enabled: true,
  421. events: {
  422. SessionStart: [
  423. { hooks: [{ type: "command", command: "echo session-start-a" }] },
  424. { hooks: [{ type: "command", command: "echo session-start-b" }] },
  425. ],
  426. },
  427. },
  428. }),
  429. );
  430. const commands: string[] = [];
  431. const eventStore = createInMemorySessionEventStore();
  432. const sessionStore = await createSqliteSessionStore({ dbPath: ":memory:" });
  433. const app = await createZCodeApp({
  434. env: {},
  435. eventStore,
  436. executionPort: executionPort(commands),
  437. modelExecutor: stopModelExecutor(),
  438. runtimeConfig: {
  439. mcp: { enabled: false, servers: {} },
  440. workingDirectory: workspace,
  441. },
  442. sessionStore,
  443. userConfigPath,
  444. workspaceHookTrustEnabled: true,
  445. workspaceHookReviewHost: {
  446. taskId: "task-review",
  447. runId: "run-review",
  448. workspaceLabel: "Review workspace",
  449. },
  450. });
  451. try {
  452. // ── 第一 turn:两个 SessionStart 都 pending → 全部 blocked ──
  453. await app.submitPrompt("turn-1");
  454. expect(commands).toEqual([]);
  455. const turn1Events = await eventStore.getEvents(app.sessionId);
  456. const turn1Blocked = turn1Events.filter(
  457. (event) => event.type === SessionEventType.HookRunBlocked,
  458. );
  459. // 2 条 blocked execution
  460. expect(turn1Blocked).toHaveLength(2);
  461. // hookCount=2
  462. const turn1Payload = turn1Blocked[0]?.payload as Record<string, unknown>;
  463. expect(turn1Payload.hookCount).toBe(2);
  464. // ── 持久信任当前快照中的全部声明 ──
  465. const admissionEvent = await waitForEvent(
  466. eventStore,
  467. app.sessionId,
  468. SessionEventType.WorkspaceHookAdmissionUpdated,
  469. );
  470. const admissionSnapshot = admissionEvent.payload as {
  471. bundleDigest: string;
  472. workspaceIdentity?: string;
  473. };
  474. await app.requestWorkspaceHookReview({
  475. workspaceIdentity: admissionSnapshot.workspaceIdentity!,
  476. bundleDigest: admissionSnapshot.bundleDigest,
  477. });
  478. const requestEvent = await waitForEvent(
  479. eventStore,
  480. app.sessionId,
  481. SessionEventType.WorkspaceHookReviewRequested,
  482. );
  483. const request = (requestEvent.payload as { request: any }).request;
  484. await expect(
  485. app.respondWorkspaceHookReview({
  486. sessionId: app.sessionId,
  487. taskId: request.taskId,
  488. runId: request.runId,
  489. ...(request.remoteSessionId ? { remoteSessionId: request.remoteSessionId } : {}),
  490. workspaceIdentity: request.workspaceIdentity,
  491. bundleDigest: request.bundleDigest,
  492. reviewFlowId: request.reviewFlowId,
  493. generation: request.generation,
  494. interactionId: request.interactionId,
  495. decision: {
  496. action: "trust_selected",
  497. reviewItemIds: request.items.map((item: { reviewItemId: string }) => item.reviewItemId),
  498. },
  499. }),
  500. ).resolves.toMatchObject({ accepted: true });
  501. // ── 第二 turn:SessionStart 不补跑 ──
  502. await app.submitPrompt("turn-2");
  503. expect(commands).toEqual([]);
  504. // ── 第三 turn:仍不补跑 ──
  505. await app.submitPrompt("turn-3");
  506. expect(commands).toEqual([]);
  507. } finally {
  508. await app.close();
  509. sessionStore.close();
  510. }
  511. });
  512. });
  513. async function waitForEvent(
  514. store: ReturnType<typeof createInMemorySessionEventStore>,
  515. sessionId: Parameters<typeof store.getEvents>[0],
  516. type: string,
  517. ) {
  518. for (let attempt = 0; attempt < 100; attempt += 1) {
  519. const event = (await store.getEvents(sessionId)).find((candidate) => candidate.type === type);
  520. if (event) return event;
  521. await new Promise((resolve) => setTimeout(resolve, 10));
  522. }
  523. throw new Error(`Timed out waiting for ${type}`);
  524. }
  525. function executionPort(commands: string[]): ExecutionPort {
  526. return {
  527. async run(request) {
  528. commands.push(
  529. request.command.mode === "shell" ? request.command.command : request.command.file,
  530. );
  531. const now = new Date("2026-08-06T00:00:00.000Z");
  532. return {
  533. status: "completed",
  534. exitCode: 0,
  535. stdout: { text: "", bytes: 0, truncated: false },
  536. stderr: { text: "", bytes: 0, truncated: false },
  537. durationMs: 1,
  538. timedOut: false,
  539. cancelled: false,
  540. startedAt: now,
  541. completedAt: now,
  542. };
  543. },
  544. };
  545. }
  546. function stopModelExecutor() {
  547. return {
  548. async generateText() {
  549. return {
  550. finishReason: "stop",
  551. text: "ok",
  552. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  553. };
  554. },
  555. async *streamText() {
  556. yield {
  557. finishReason: "stop",
  558. type: "finish",
  559. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  560. };
  561. },
  562. } as never;
  563. }