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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 = 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 = 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 = 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 = 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 = 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. // 所有事件的 hookInvocationId 一致
  401. const invocationIds = new Set(
  402. hookLifecycleEvents.map(
  403. (event) => (event.payload as Record<string, unknown>).hookInvocationId,
  404. ),
  405. );
  406. expect(invocationIds.size).toBe(1);
  407. } finally {
  408. await app.close();
  409. sessionStore.close();
  410. }
  411. });
  412. // 持久信任只影响之后自然发生的生命周期事件;SessionStart 不做 catch-up。
  413. it("两个 pending SessionStart 信任后,当前任务后续 turn 不补跑", async () => {
  414. const root = await mkdtemp(join(tmpdir(), "zcode-hook-h2-scenario-b-"));
  415. roots.push(root);
  416. const workspace = join(root, "workspace");
  417. const userConfigPath = join(root, "home", "config.json");
  418. const storageRoot = join(root, "storage");
  419. await mkdir(join(workspace, ".git"), { recursive: true });
  420. await mkdir(join(workspace, ".zcode"), { recursive: true });
  421. await mkdir(join(root, "home"), { recursive: true });
  422. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: storageRoot } }));
  423. await writeFile(
  424. join(workspace, ".zcode", "config.json"),
  425. JSON.stringify({
  426. hooks: {
  427. enabled: true,
  428. events: {
  429. SessionStart: [
  430. { hooks: [{ type: "command", command: "echo session-start-a" }] },
  431. { hooks: [{ type: "command", command: "echo session-start-b" }] },
  432. ],
  433. },
  434. },
  435. }),
  436. );
  437. const commands: string[] = [];
  438. const eventStore = createInMemorySessionEventStore();
  439. const sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  440. const app = await createZCodeApp({
  441. env: {},
  442. eventStore,
  443. executionPort: executionPort(commands),
  444. modelExecutor: stopModelExecutor(),
  445. runtimeConfig: {
  446. mcp: { enabled: false, servers: {} },
  447. workingDirectory: workspace,
  448. },
  449. sessionStore,
  450. userConfigPath,
  451. workspaceHookTrustEnabled: true,
  452. workspaceHookReviewHost: {
  453. taskId: "task-review",
  454. runId: "run-review",
  455. workspaceLabel: "Review workspace",
  456. },
  457. });
  458. try {
  459. // ── 第一 turn:两个 SessionStart 都 pending → 全部 blocked ──
  460. await app.submitPrompt("turn-1");
  461. expect(commands).toEqual([]);
  462. const turn1Events = await eventStore.getEvents(app.sessionId);
  463. const turn1Blocked = turn1Events.filter(
  464. (event) => event.type === SessionEventType.HookRunBlocked,
  465. );
  466. // 2 条 blocked execution
  467. expect(turn1Blocked).toHaveLength(2);
  468. // hookCount=2
  469. const turn1Payload = turn1Blocked[0]?.payload as Record<string, unknown>;
  470. expect(turn1Payload.hookCount).toBe(2);
  471. // ── 持久信任当前快照中的全部声明 ──
  472. const admissionEvent = await waitForEvent(
  473. eventStore,
  474. app.sessionId,
  475. SessionEventType.WorkspaceHookAdmissionUpdated,
  476. );
  477. const admissionSnapshot = admissionEvent.payload as {
  478. bundleDigest: string;
  479. workspaceIdentity?: string;
  480. };
  481. await app.requestWorkspaceHookReview({
  482. workspaceIdentity: admissionSnapshot.workspaceIdentity!,
  483. bundleDigest: admissionSnapshot.bundleDigest,
  484. });
  485. const requestEvent = await waitForEvent(
  486. eventStore,
  487. app.sessionId,
  488. SessionEventType.WorkspaceHookReviewRequested,
  489. );
  490. const request = (requestEvent.payload as { request: any }).request;
  491. await expect(
  492. app.respondWorkspaceHookReview({
  493. sessionId: app.sessionId,
  494. taskId: request.taskId,
  495. runId: request.runId,
  496. ...(request.remoteSessionId ? { remoteSessionId: request.remoteSessionId } : {}),
  497. workspaceIdentity: request.workspaceIdentity,
  498. bundleDigest: request.bundleDigest,
  499. reviewFlowId: request.reviewFlowId,
  500. generation: request.generation,
  501. interactionId: request.interactionId,
  502. decision: {
  503. action: "trust_selected",
  504. reviewItemIds: request.items.map((item: { reviewItemId: string }) => item.reviewItemId),
  505. },
  506. }),
  507. ).resolves.toMatchObject({ accepted: true });
  508. // ── 第二 turn:SessionStart 不补跑 ──
  509. await app.submitPrompt("turn-2");
  510. expect(commands).toEqual([]);
  511. // ── 第三 turn:仍不补跑 ──
  512. await app.submitPrompt("turn-3");
  513. expect(commands).toEqual([]);
  514. } finally {
  515. await app.close();
  516. sessionStore.close();
  517. }
  518. });
  519. });
  520. async function waitForEvent(
  521. store: ReturnType<typeof createInMemorySessionEventStore>,
  522. sessionId: Parameters<typeof store.getEvents>[0],
  523. type: string,
  524. ) {
  525. for (let attempt = 0; attempt < 100; attempt += 1) {
  526. const event = (await store.getEvents(sessionId)).find((candidate) => candidate.type === type);
  527. if (event) return event;
  528. await new Promise((resolve) => setTimeout(resolve, 10));
  529. }
  530. throw new Error(`Timed out waiting for ${type}`);
  531. }
  532. function executionPort(commands: string[]): ExecutionPort {
  533. return {
  534. async run(request) {
  535. commands.push(
  536. request.command.mode === "shell" ? request.command.command : request.command.file,
  537. );
  538. const now = new Date("2026-08-06T00:00:00.000Z");
  539. return {
  540. status: "completed",
  541. exitCode: 0,
  542. stdout: { text: "", bytes: 0, truncated: false },
  543. stderr: { text: "", bytes: 0, truncated: false },
  544. durationMs: 1,
  545. timedOut: false,
  546. cancelled: false,
  547. startedAt: now,
  548. completedAt: now,
  549. };
  550. },
  551. };
  552. }
  553. function stopModelExecutor() {
  554. return {
  555. async generateText() {
  556. return {
  557. finishReason: "stop",
  558. text: "ok",
  559. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  560. };
  561. },
  562. async *streamText() {
  563. yield {
  564. finishReason: "stop",
  565. type: "finish",
  566. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  567. };
  568. },
  569. } as never;
  570. }