workflow-driver-git-grep.test.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. /**
  2. * git.* / files.glob / files.grep world reads(driver 侧)。见 docs/execution-engine.md 的
  3. * "World-read execution, per op family" 与 "Cap enforcement sits in the driver, with the
  4. * constants in the pure package"。
  5. *
  6. * 这份用例钉三件事,每一件都是"只读按构造"的一部分:
  7. *
  8. * 1. **每个 op 的 argv 逐元素精确**。argv 就是这个原语的安全边界——没有 shell 字符串,
  9. * path 总在 `--` 之后,base 缺省是 HEAD。所以断言不是"包含 diff",而是整个数组相等:
  10. * 多一个元素、少一个 `--`,都是一次真实的语义变化。
  11. * 2. **实参校验在 driver**(Boundary A 只承诺按位置原样送达)。尾部可选的接受/拒绝矩阵,
  12. * 以及 base / path 的字符集拒绝,都在这里。
  13. * 3. **上限溢出拒绝节点**(`WorldReadCapExceeded`),既不截断也不折成 DriverError。
  14. *
  15. * 为什么独立成文件而不并入 workflow-driver.test.ts:那份用例经 helpers 在运行时 import
  16. * `@zcode/core`(真实 AgentRuntime),而本文件只碰 driver 的世界读取面(它对 `@zcode/core`
  17. * 只有类型导入),因此不依赖模型侧的任何东西。同 workflow-driver-world-read-args.test.ts。
  18. */
  19. import { describe, expect, it } from "vitest";
  20. import type {
  21. ExecutionPort,
  22. ExecutionRequest,
  23. ExecutionResult,
  24. FileSystemPort,
  25. FileSystemSearchFilesRequest,
  26. FileSystemSearchTextEntry,
  27. FileSystemSearchTextRequest,
  28. } from "@zcode/contracts";
  29. import {
  30. FACADE_DTS,
  31. InMemoryJournalStore,
  32. WORLD_READ_CAPS,
  33. type WorkflowReportSink,
  34. } from "@zcode/dynamic-workflow";
  35. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  36. import { createAgentRuntimeWorkflowDriver } from "../src/app/workflow-driver.js";
  37. const CWD = "/ws";
  38. /** 一次被记录下来的 git 调用(argv 与 cwd 都要能断言)。 */
  39. interface GitCall {
  40. argv: string[];
  41. cwd?: string;
  42. maxInlineBytes?: number;
  43. }
  44. /** 一条脚本化的 git 响应;按调用顺序取用。 */
  45. interface GitReply {
  46. stdout?: string;
  47. /** stdout 的总字节数;缺省按 stdout 算。用于伪造"被截断的大输出"。 */
  48. bytes?: number;
  49. truncated?: boolean;
  50. exitCode?: number;
  51. status?: ExecutionResult["status"];
  52. stderr?: string;
  53. }
  54. /**
  55. * 拼一段 `-z` 输出:段以 NUL **终止**(不是分隔),所以末尾也有一个 NUL——真 git 就是这样,
  56. * 而它会在 split 后留下一个空段,解析器必须容得下。
  57. */
  58. function nul(...segments: string[]): string {
  59. return segments.map((segment) => `${segment}\u0000`).join("");
  60. }
  61. /** `rev-parse --show-prefix` 在仓库根的回复:空前缀(只有一个换行)。 */
  62. const PREFIX_AT_ROOT: GitReply = { stdout: "\n" };
  63. function fakeExecutionPort(replies: GitReply[]): {
  64. port: ExecutionPort;
  65. calls: GitCall[];
  66. } {
  67. const calls: GitCall[] = [];
  68. let at = 0;
  69. const port: ExecutionPort = {
  70. async run(request: ExecutionRequest): Promise<ExecutionResult> {
  71. if (request.command.mode !== "argv") {
  72. // 只读按构造的核心:driver 绝不构造 shell 命令。走到这里就是回归。
  73. throw new Error(`world-read git 必须用 argv 模式,收到 ${request.command.mode}`);
  74. }
  75. expect(request.command.file).toBe("git");
  76. calls.push({
  77. argv: [...(request.command.args ?? [])],
  78. ...(request.cwd === undefined ? {} : { cwd: request.cwd }),
  79. ...(request.outputLimit?.maxInlineBytes === undefined
  80. ? {}
  81. : { maxInlineBytes: request.outputLimit.maxInlineBytes }),
  82. });
  83. const reply = replies[at] ?? {};
  84. at += 1;
  85. const stdout = reply.stdout ?? "";
  86. return {
  87. status: reply.status ?? "completed",
  88. exitCode: reply.exitCode ?? 0,
  89. stdout: {
  90. text: stdout,
  91. bytes: reply.bytes ?? Buffer.byteLength(stdout, "utf8"),
  92. truncated: reply.truncated ?? false,
  93. },
  94. stderr: { text: reply.stderr ?? "", bytes: 0, truncated: false },
  95. durationMs: 0,
  96. timedOut: false,
  97. cancelled: false,
  98. startedAt: new Date(0),
  99. completedAt: new Date(0),
  100. };
  101. },
  102. };
  103. return { calls, port };
  104. }
  105. /** fs 端口:只实现 searchText(grep),其余被触及即失败。 */
  106. function fakeFileSystemPort(
  107. entries: FileSystemSearchTextEntry[],
  108. options: { truncated?: boolean; globFiles?: string[]; globTruncated?: boolean } = {},
  109. ): {
  110. port: FileSystemPort;
  111. requests: FileSystemSearchTextRequest[];
  112. readPaths: string[];
  113. globRequests: FileSystemSearchFilesRequest[];
  114. } {
  115. const requests: FileSystemSearchTextRequest[] = [];
  116. const readPaths: string[] = [];
  117. const globRequests: FileSystemSearchFilesRequest[] = [];
  118. const unsupported = (name: string) => () => {
  119. throw new Error(`fakeFileSystemPort.${name} 不应被本用例触及`);
  120. };
  121. const port = {
  122. async searchFiles(request: FileSystemSearchFilesRequest) {
  123. globRequests.push(request);
  124. const all = options.globFiles ?? [];
  125. // 复刻真适配器的截断语义:maxResults 之内切片,truncated 表示还有剩余。
  126. const files = request.maxResults === undefined ? [...all] : all.slice(0, request.maxResults);
  127. return {
  128. path: request.path,
  129. pattern: request.pattern,
  130. durationMs: 0,
  131. files,
  132. numFiles: files.length,
  133. truncated: options.globTruncated ?? files.length < all.length,
  134. };
  135. },
  136. async searchText(request: FileSystemSearchTextRequest) {
  137. requests.push(request);
  138. const limited =
  139. request.headLimit === undefined ? entries : entries.slice(0, request.headLimit);
  140. return {
  141. path: request.path,
  142. pattern: request.pattern,
  143. mode: "content" as const,
  144. durationMs: 0,
  145. files: [...new Set(limited.map((e) => e.path))],
  146. entries: limited,
  147. numMatches: limited.length,
  148. truncated: options.truncated ?? entries.length > (request.headLimit ?? Infinity),
  149. };
  150. },
  151. async readTextFile(request: { path: string }) {
  152. readPaths.push(request.path);
  153. return {
  154. path: request.path,
  155. content: "body",
  156. encoding: "utf-8",
  157. bytesRead: 4,
  158. sizeBytes: 4,
  159. truncated: false,
  160. };
  161. },
  162. createDirectory: unsupported("createDirectory"),
  163. stat: unsupported("stat"),
  164. readBinaryFile: unsupported("readBinaryFile"),
  165. readTextFileRange: unsupported("readTextFileRange"),
  166. writeTextFile: unsupported("writeTextFile"),
  167. removeFile: unsupported("removeFile"),
  168. listDirectory: unsupported("listDirectory"),
  169. } as unknown as FileSystemPort;
  170. return { port, readPaths, requests, globRequests };
  171. }
  172. function noopSink(): WorkflowReportSink {
  173. const unexpected = (name: string) => (): never => {
  174. throw new Error(`noopSink.${name} 不应被触及`);
  175. };
  176. return {
  177. askSubmitAttempted: unexpected("askSubmitAttempted"),
  178. askTurnEnded: unexpected("askTurnEnded"),
  179. askProgress: unexpected("askProgress"),
  180. askStats: unexpected("askStats"),
  181. askFailed: unexpected("askFailed"),
  182. };
  183. }
  184. function makeDriver(input: {
  185. git?: GitReply[];
  186. grep?: FileSystemSearchTextEntry[];
  187. grepTruncated?: boolean;
  188. glob?: string[];
  189. globTruncated?: boolean;
  190. }) {
  191. const exec = fakeExecutionPort(input.git ?? []);
  192. const fs = fakeFileSystemPort(input.grep ?? [], {
  193. ...(input.grepTruncated === undefined ? {} : { truncated: input.grepTruncated }),
  194. ...(input.glob === undefined ? {} : { globFiles: input.glob }),
  195. ...(input.globTruncated === undefined ? {} : { globTruncated: input.globTruncated }),
  196. });
  197. const driver = createAgentRuntimeWorkflowDriver({
  198. cwd: CWD,
  199. emit: () => undefined,
  200. escalationRegistry: createWorkflowEscalationRegistry(),
  201. executionPort: exec.port,
  202. fileSystemPort: fs.port,
  203. journal: new InMemoryJournalStore(),
  204. runId: "run",
  205. runtimeFactory: () => {
  206. throw new Error("世界读取不该创建 actor runtime");
  207. },
  208. })(noopSink());
  209. return {
  210. driver,
  211. gitCalls: exec.calls,
  212. grepRequests: fs.requests,
  213. readPaths: fs.readPaths,
  214. globRequests: fs.globRequests,
  215. };
  216. }
  217. // ————————————————————————————————————————————————————————————————
  218. // argv:只读的边界就是这几个数组
  219. // ————————————————————————————————————————————————————————————————
  220. describe("git world reads — exact argv", () => {
  221. it("changedFiles with no base unions tracked changes with untracked files", async () => {
  222. // 两条命令的并集。未跟踪文件对读者而言就是改动——漏掉它们会让这个原语在一条刚开的
  223. // feature 分支上毫无用处。前面还有一次 rev-parse:线上路径是仓库根相对的,要剥前缀。
  224. const { driver, gitCalls } = makeDriver({
  225. git: [PREFIX_AT_ROOT, { stdout: nul("b.ts", "a.ts") }, { stdout: nul("c.ts", "a.ts") }],
  226. });
  227. await expect(driver.executeWorldRead("git-changed-files", [])).resolves.toEqual([
  228. "a.ts",
  229. "b.ts",
  230. "c.ts",
  231. ]);
  232. expect(gitCalls.map((c) => c.argv)).toEqual([
  233. ["rev-parse", "--show-prefix"],
  234. ["diff", "--no-ext-diff", "--no-textconv", "--name-only", "-z", "HEAD", "--", "."],
  235. ["ls-files", "--others", "--exclude-standard", "-z", "--full-name", "--", "."],
  236. ]);
  237. // 每次调用都以工作区根为 cwd。
  238. expect(gitCalls.every((c) => c.cwd === CWD)).toBe(true);
  239. });
  240. it("changedFiles with a base asks only about tracked history", async () => {
  241. // "相对某个 ref 改了什么"是关于已跟踪历史的问题——一个从未进过 git 的文件与任何 ref
  242. // 都无从比较,所以这一路**没有** ls-files。
  243. const { driver, gitCalls } = makeDriver({
  244. git: [PREFIX_AT_ROOT, { stdout: nul("src/a.ts") }],
  245. });
  246. await expect(driver.executeWorldRead("git-changed-files", ["main"])).resolves.toEqual([
  247. "src/a.ts",
  248. ]);
  249. expect(gitCalls.map((c) => c.argv)).toEqual([
  250. ["rev-parse", "--show-prefix"],
  251. ["diff", "--no-ext-diff", "--no-textconv", "--name-only", "-z", "main", "--", "."],
  252. ]);
  253. });
  254. it("diff defaults base to HEAD and pathspec to the workspace, always after --", async () => {
  255. // 无 path 时 pathspec 缺省为 `.`:否则 changedFiles 说"只有 a.md 变了",而 diff 交出
  256. // 一段仓库级补丁——两个原语会对"什么算改动"给出不同答案。
  257. const noPath = makeDriver({ git: [{ stdout: "@@ -1 +1 @@\n" }] });
  258. await expect(noPath.driver.executeWorldRead("git-diff", [])).resolves.toContain("@@");
  259. expect(noPath.gitCalls[0]?.argv).toEqual([
  260. "diff",
  261. "--no-ext-diff",
  262. "--no-textconv",
  263. "--relative",
  264. "HEAD",
  265. "--",
  266. ".",
  267. ]);
  268. const withPath = makeDriver({ git: [{ stdout: "diff" }] });
  269. await withPath.driver.executeWorldRead("git-diff", ["main", "src/a.ts"]);
  270. // `--` 是契约的一部分:一个恰好与分支同名的路径不能被 git 解读成 ref(也不能反过来)。
  271. // 显式 path **取代**缺省 pathspec。
  272. expect(withPath.gitCalls[0]?.argv).toEqual([
  273. "diff",
  274. "--no-ext-diff",
  275. "--no-textconv",
  276. "--relative",
  277. "main",
  278. "--",
  279. "src/a.ts",
  280. ]);
  281. const pathOnly = makeDriver({ git: [{ stdout: "diff" }] });
  282. await pathOnly.driver.executeWorldRead("git-diff", [undefined, "src/a.ts"]);
  283. expect(pathOnly.gitCalls[0]?.argv).toEqual([
  284. "diff",
  285. "--no-ext-diff",
  286. "--no-textconv",
  287. "--relative",
  288. "HEAD",
  289. "--",
  290. "src/a.ts",
  291. ]);
  292. });
  293. it("does not need a prefix lookup for the patch diff (git --relative does that base)", async () => {
  294. // 补丁文本不是我们解析的路径列表,没法事后剥前缀,所以这一条靠 git 自己的 --relative
  295. // 对齐基准——也因此不必多跑一次 rev-parse。
  296. const { driver, gitCalls } = makeDriver({ git: [{ stdout: "diff" }] });
  297. await driver.executeWorldRead("git-diff", []);
  298. expect(gitCalls).toHaveLength(1);
  299. expect(gitCalls[0]?.argv[0]).toBe("diff");
  300. });
  301. it("normalizes a windows-style relative path into a git pathspec", async () => {
  302. // 模型写 windows 风格的相对路径是常事;git 的 pathspec 在三个平台上都吃 `/`。
  303. const { driver, gitCalls } = makeDriver({ git: [{ stdout: "diff" }] });
  304. await driver.executeWorldRead("git-diff", ["HEAD", "src\\app\\a.ts"]);
  305. expect(gitCalls[0]?.argv).toEqual([
  306. "diff",
  307. "--no-ext-diff",
  308. "--no-textconv",
  309. "--relative",
  310. "HEAD",
  311. "--",
  312. "src/app/a.ts",
  313. ]);
  314. });
  315. it("status and log use their fixed argv", async () => {
  316. const status = makeDriver({
  317. git: [PREFIX_AT_ROOT, { stdout: nul("# branch.head main") }],
  318. });
  319. await status.driver.executeWorldRead("git-status", []);
  320. expect(status.gitCalls.map((c) => c.argv)).toEqual([
  321. ["rev-parse", "--show-prefix"],
  322. ["status", "--porcelain=v2", "-z", "--branch", "--", "."],
  323. ]);
  324. const dflt = makeDriver({ git: [{ stdout: "" }] });
  325. await dflt.driver.executeWorldRead("git-log", []);
  326. // log 刻意**不带** pathspec 也不带 -z:commit 是仓库级对象,给它加 pathspec 会把语义改成
  327. // "碰过工作区的那些 commit";而 %s 按定义单行,所以按行切记录是可靠的。
  328. expect(dflt.gitCalls[0]?.argv).toEqual([
  329. "log",
  330. `-n${WORLD_READ_CAPS.gitLogDefaultCount}`,
  331. "--pretty=format:%H%x00%s%x00%an%x00%aI",
  332. ]);
  333. expect(dflt.gitCalls).toHaveLength(1);
  334. const five = makeDriver({ git: [{ stdout: "" }] });
  335. await five.driver.executeWorldRead("git-log", [5]);
  336. expect(five.gitCalls[0]?.argv).toEqual([
  337. "log",
  338. "-n5",
  339. "--pretty=format:%H%x00%s%x00%an%x00%aI",
  340. ]);
  341. });
  342. });
  343. // ————————————————————————————————————————————————————————————————
  344. // 工作区收束:线上是仓库根相对,交出去是工作区相对
  345. // ————————————————————————————————————————————————————————————————
  346. describe("git world reads — workspace-relative paths", () => {
  347. it("strips the workspace prefix when the workspace is a repo subdirectory", async () => {
  348. // 实测事实:`-z` 让 porcelain status 输出**仓库根相对**路径,且没有任何 flag/config 能
  349. // 改回 cwd 相对;`diff --name-only` 默认也是根相对。所以基准统一在线上取根相对,由这一侧
  350. // 剥一次前缀——三条命令各依赖一个不同的 git 默认值,才是那个会吐出两种基准路径的 bug。
  351. const { driver } = makeDriver({
  352. git: [
  353. { stdout: "sub/nested/\n" },
  354. { stdout: nul("sub/nested/deep.ts", "sub/nested/other.ts") },
  355. { stdout: nul("sub/nested/untracked.ts") },
  356. ],
  357. });
  358. await expect(driver.executeWorldRead("git-changed-files", [])).resolves.toEqual([
  359. "deep.ts",
  360. "other.ts",
  361. "untracked.ts",
  362. ]);
  363. });
  364. it("strips the prefix in status buckets too", async () => {
  365. const { driver } = makeDriver({
  366. git: [
  367. { stdout: "sub/\n" },
  368. {
  369. stdout: nul(
  370. "# branch.head main",
  371. "1 M. N... 100644 100644 100644 aaa bbb sub/staged.ts",
  372. "? sub/new.ts",
  373. ),
  374. },
  375. ],
  376. });
  377. await expect(driver.executeWorldRead("git-status", [])).resolves.toEqual({
  378. branch: "main",
  379. clean: false,
  380. staged: ["staged.ts"],
  381. unstaged: [],
  382. untracked: ["new.ts"],
  383. });
  384. });
  385. it("fails loudly if git reports a path outside the workspace prefix", async () => {
  386. // pathspec 已经保证了范围,所以走到这里说明某个假设塌了。此时把一个带 ../ 的路径交给
  387. // 脚本,正是这套收束要防的那件事——而脚本会拿它去 files.read。
  388. const { driver } = makeDriver({
  389. git: [{ stdout: "sub/\n" }, { stdout: nul("outside/elsewhere.ts") }],
  390. });
  391. await expect(driver.executeWorldRead("git-changed-files", ["main"])).rejects.toMatchObject({
  392. code: "DriverError",
  393. });
  394. });
  395. it("is identity at the repo root (the common case pays nothing)", async () => {
  396. const { driver } = makeDriver({
  397. git: [PREFIX_AT_ROOT, { stdout: nul("a.ts", "sub/b.ts") }],
  398. });
  399. await expect(driver.executeWorldRead("git-changed-files", ["main"])).resolves.toEqual([
  400. "a.ts",
  401. "sub/b.ts",
  402. ]);
  403. });
  404. });
  405. // ————————————————————————————————————————————————————————————————
  406. // porcelain v2 解析
  407. // ————————————————————————————————————————————————————————————————
  408. describe("git status — porcelain v2 -z parsing", () => {
  409. /** 一次 status 读取:先一条根前缀回复,再一段 `-z` porcelain。 */
  410. function statusDriver(...segments: string[]) {
  411. return makeDriver({ git: [PREFIX_AT_ROOT, { stdout: nul(...segments) }] });
  412. }
  413. it("reports a clean tree with its branch", async () => {
  414. // 头信息段同样以 NUL 终止(不是换行)——实测确认。
  415. const { driver } = statusDriver(
  416. "# branch.oid 1111111111111111111111111111111111111111",
  417. "# branch.head main",
  418. "# branch.upstream origin/main",
  419. "# branch.ab +0 -0",
  420. );
  421. await expect(driver.executeWorldRead("git-status", [])).resolves.toEqual({
  422. branch: "main",
  423. clean: true,
  424. staged: [],
  425. unstaged: [],
  426. untracked: [],
  427. });
  428. });
  429. it("splits staged / unstaged / untracked, and reports a file in both when it is", async () => {
  430. // `XY` 的两位分别是暂存区与工作区状态,`.` 表示未变。所以"改了、暂存了、又接着改"的
  431. // 文件同时出现在 staged 与 unstaged——这不是重复,是两条不同的事实。
  432. const { driver } = statusDriver(
  433. "# branch.head feature/x",
  434. "1 M. N... 100644 100644 100644 aaa bbb staged-only.ts",
  435. "1 .M N... 100644 100644 100644 aaa bbb worktree only.ts",
  436. "1 MM N... 100644 100644 100644 aaa bbb both.ts",
  437. "? untracked one.ts",
  438. "? another.ts",
  439. );
  440. await expect(driver.executeWorldRead("git-status", [])).resolves.toEqual({
  441. branch: "feature/x",
  442. clean: false,
  443. // 路径可以含空格:解析按"跳过 N 个定长字段取余文",绝不整段 split。
  444. staged: ["both.ts", "staged-only.ts"],
  445. unstaged: ["both.ts", "worktree only.ts"],
  446. untracked: ["another.ts", "untracked one.ts"],
  447. });
  448. });
  449. it("consumes a rename entry's second segment instead of misreading it as a record", async () => {
  450. // `-z` 下 rename/copy 项占**两段**:`2 … R100 <新路径>\0<原路径>`(不带 -z 时用 TAB 分隔)。
  451. // 少消费那一段,原路径就会被当成下一条记录——它不以类型字符开头,于是被静默丢掉,而紧随
  452. // 其后的真记录会被错位读取。这里用 rename 后面紧跟一条真记录来抓住这种错位。
  453. const { driver } = statusDriver(
  454. "# branch.head main",
  455. "2 R. N... 100644 100644 100644 aaa bbb R100 new/name.ts",
  456. "old/name.ts",
  457. "1 .M N... 100644 100644 100644 aaa bbb after-rename.ts",
  458. );
  459. await expect(driver.executeWorldRead("git-status", [])).resolves.toEqual({
  460. branch: "main",
  461. clean: false,
  462. // 只交出**新**路径:facade 报告的是"现在哪些路径变了"。原路径不出现在任何桶里。
  463. staged: ["new/name.ts"],
  464. unstaged: ["after-rename.ts"],
  465. untracked: [],
  466. });
  467. });
  468. it("carries a non-ASCII filename through verbatim", async () => {
  469. // 不加 `-z` 时 core.quotePath 会把它 C 引用成 `"\346\226\207..."`。在本仓库的用户身上
  470. // 这是常态而不是边角,所以这条是 `-z` 存在的第一个理由。
  471. const { driver } = statusDriver(
  472. "# branch.head main",
  473. "1 .M N... 100644 100644 100644 aaa bbb 文档 中文.md",
  474. "? 未跟踪.txt",
  475. );
  476. await expect(driver.executeWorldRead("git-status", [])).resolves.toMatchObject({
  477. unstaged: ["文档 中文.md"],
  478. untracked: ["未跟踪.txt"],
  479. });
  480. });
  481. it("carries a newline-containing filename through intact", async () => {
  482. // `-z` 存在的第二个理由:按行切会把这个文件名劈成两个不存在的路径,且不报任何错——
  483. // "少见且静默错误"正是这套代码不接受的失败形态。
  484. const { driver } = statusDriver("# branch.head main", "? has\nnewline.txt");
  485. await expect(driver.executeWorldRead("git-status", [])).resolves.toMatchObject({
  486. untracked: ["has\nnewline.txt"],
  487. });
  488. });
  489. it("omits branch entirely on a detached HEAD", async () => {
  490. // git 写字面量 "(detached)"。把它当分支名交出去,脚本就会拿它去 diff。
  491. const { driver } = statusDriver("# branch.oid abc", "# branch.head (detached)");
  492. const status = (await driver.executeWorldRead("git-status", [])) as Record<string, unknown>;
  493. expect(status.branch).toBeUndefined();
  494. expect("branch" in status).toBe(false);
  495. expect(status.clean).toBe(true);
  496. });
  497. it("counts an unmerged entry as unstaged work", async () => {
  498. // 冲突文件确实"有待办",但它不是"已经准备好提交",所以落 unstaged 而不是 staged。
  499. const { driver } = statusDriver(
  500. "# branch.head main",
  501. "u UU N... 100644 100644 100644 100644 aaa bbb ccc conflicted.ts",
  502. );
  503. await expect(driver.executeWorldRead("git-status", [])).resolves.toMatchObject({
  504. clean: false,
  505. staged: [],
  506. unstaged: ["conflicted.ts"],
  507. });
  508. });
  509. });
  510. describe("git path lists — -z parsing", () => {
  511. it("carries non-ASCII and newline-containing filenames through changedFiles", async () => {
  512. const { driver } = makeDriver({
  513. git: [
  514. PREFIX_AT_ROOT,
  515. { stdout: nul("文档 中文.md", "src/a.ts") },
  516. { stdout: nul("未跟踪.txt", "has\nnewline.txt") },
  517. ],
  518. });
  519. await expect(driver.executeWorldRead("git-changed-files", [])).resolves.toEqual([
  520. "has\nnewline.txt",
  521. "src/a.ts",
  522. "文档 中文.md",
  523. "未跟踪.txt",
  524. ]);
  525. });
  526. it("tolerates the trailing NUL terminator without emitting an empty path", async () => {
  527. const { driver } = makeDriver({
  528. git: [PREFIX_AT_ROOT, { stdout: nul("a.ts") }],
  529. });
  530. await expect(driver.executeWorldRead("git-changed-files", ["main"])).resolves.toEqual(["a.ts"]);
  531. });
  532. it("returns an empty list for an empty -z output", async () => {
  533. const { driver } = makeDriver({ git: [PREFIX_AT_ROOT, { stdout: "" }] });
  534. await expect(driver.executeWorldRead("git-changed-files", ["main"])).resolves.toEqual([]);
  535. });
  536. });
  537. describe("git log — NUL field parsing", () => {
  538. it("parses NUL-separated records into commits, newest first", async () => {
  539. const { driver } = makeDriver({
  540. git: [
  541. {
  542. stdout:
  543. "aaa\u0000feat: add thing\u0000Ada\u00002026-08-20T10:00:00+08:00\n" +
  544. "bbb\u0000fix: a | pipe, a: colon and spaces\u0000Bob Builder\u00002026-08-19T09:00:00+08:00",
  545. },
  546. ],
  547. });
  548. await expect(driver.executeWorldRead("git-log", [2])).resolves.toEqual([
  549. { hash: "aaa", subject: "feat: add thing", author: "Ada", date: "2026-08-20T10:00:00+08:00" },
  550. {
  551. hash: "bbb",
  552. // NUL 分隔而不是别的分隔符,正是为了让 subject 里的 `|` / `:` / 连续空格都安全。
  553. subject: "fix: a | pipe, a: colon and spaces",
  554. author: "Bob Builder",
  555. date: "2026-08-19T09:00:00+08:00",
  556. },
  557. ]);
  558. });
  559. it("returns an empty list for an empty log", async () => {
  560. const { driver } = makeDriver({ git: [{ stdout: "" }] });
  561. await expect(driver.executeWorldRead("git-log", [])).resolves.toEqual([]);
  562. });
  563. it("fails loudly on a record whose field count is wrong", async () => {
  564. // 格式串与解析器在同一个模块里,两者不一致只可能是本地改动出了岔子;一条只填了一半的
  565. // commit 会一路流进 journal 与模型的上下文。
  566. const { driver } = makeDriver({ git: [{ stdout: "aaa\u0000only-two" }] });
  567. await expect(driver.executeWorldRead("git-log", [])).rejects.toMatchObject({
  568. code: "DriverError",
  569. });
  570. });
  571. });
  572. // ————————————————————————————————————————————————————————————————
  573. // 实参校验:base / path / count
  574. // ————————————————————————————————————————————————————————————————
  575. describe("git world reads — argument validation", () => {
  576. const rejects = async (op: "git-diff" | "git-changed-files" | "git-log", args: unknown[]) => {
  577. const { driver, gitCalls } = makeDriver({ git: [PREFIX_AT_ROOT, { stdout: "" }] });
  578. await expect(driver.executeWorldRead(op, args)).rejects.toMatchObject({
  579. code: "DriverError",
  580. });
  581. // 校验失败**不得**已经 spawn 出一个 git:argv 在跑任何东西之前就构造好,所以坏 base /
  582. // 坏 path 连 rev-parse 都不该发生。
  583. expect(gitCalls).toEqual([]);
  584. };
  585. it("rejects a base that would be read as an option", async () => {
  586. // `-foo` 会被 git 当成选项而不是 ref,而"哪些选项存在"不由我们决定。
  587. await rejects("git-diff", ["-foo"]);
  588. await rejects("git-changed-files", ["--cached"]);
  589. });
  590. it("rejects a range base (v1 accepts a single ref only)", async () => {
  591. await rejects("git-diff", ["main..HEAD"]);
  592. await rejects("git-diff", ["main...HEAD"]);
  593. await rejects("git-changed-files", ["a..b"]);
  594. });
  595. it("rejects whitespace and reflog/rev syntax in a base", async () => {
  596. await rejects("git-diff", ["main HEAD"]);
  597. await rejects("git-diff", ["main\tx"]);
  598. await rejects("git-diff", ["HEAD@{1}"]);
  599. await rejects("git-diff", ["HEAD:src/a.ts"]);
  600. await rejects("git-diff", [""]);
  601. });
  602. it("accepts the single-ref forms a script actually writes", async () => {
  603. for (const base of ["HEAD", "HEAD~3", "HEAD^", "main", "origin/main", "v1.2.3", "abc123"]) {
  604. const { driver, gitCalls } = makeDriver({ git: [{ stdout: "" }] });
  605. await driver.executeWorldRead("git-diff", [base]);
  606. expect(gitCalls[0]?.argv).toEqual([
  607. "diff",
  608. "--no-ext-diff",
  609. "--no-textconv",
  610. "--relative",
  611. base,
  612. "--",
  613. ".",
  614. ]);
  615. }
  616. });
  617. it("accepts a legitimate nested path", async () => {
  618. const { driver, gitCalls } = makeDriver({ git: [{ stdout: "" }] });
  619. await driver.executeWorldRead("git-diff", ["HEAD", "sub/nested/deep.ts"]);
  620. expect(gitCalls[0]?.argv).toEqual([
  621. "diff",
  622. "--no-ext-diff",
  623. "--no-textconv",
  624. "--relative",
  625. "HEAD",
  626. "--",
  627. "sub/nested/deep.ts",
  628. ]);
  629. });
  630. it("rejects an absolute or escaping path", async () => {
  631. await rejects("git-diff", ["HEAD", "/etc/passwd"]);
  632. // 平台无关:posix 的 isAbsolute 认不出 `C:\x`,而这道校验要在三个平台上给同一个答案。
  633. await rejects("git-diff", ["HEAD", "C:\\Windows\\x"]);
  634. await rejects("git-diff", ["HEAD", "\\\\server\\share"]);
  635. await rejects("git-diff", ["HEAD", "../outside/a.ts"]);
  636. await rejects("git-diff", ["HEAD", "src/../../a.ts"]);
  637. // `--` 之后 `-foo` 已经安全,但仍然拒绝:`--` 一旦哪天漏掉,它就是一个选项。
  638. await rejects("git-diff", ["HEAD", "-foo"]);
  639. await rejects("git-diff", ["HEAD", ""]);
  640. });
  641. it("rejects a log count above the cap rather than silently clamping it", async () => {
  642. // 请求 500 条却拿到 100 条,会在脚本自己的逻辑里变成一个查不明白的"历史怎么这么短"。
  643. await rejects("git-log", [WORLD_READ_CAPS.gitLogMaxCount + 1]);
  644. await rejects("git-log", [1000]);
  645. await rejects("git-log", [0]);
  646. await rejects("git-log", [-1]);
  647. await rejects("git-log", [2.5]);
  648. await rejects("git-log", ["5"]);
  649. await rejects("git-log", [5, 6]);
  650. });
  651. it("accepts a log count exactly at the cap", async () => {
  652. const { driver, gitCalls } = makeDriver({ git: [{ stdout: "" }] });
  653. await driver.executeWorldRead("git-log", [WORLD_READ_CAPS.gitLogMaxCount]);
  654. expect(gitCalls[0]?.argv[1]).toBe(`-n${WORLD_READ_CAPS.gitLogMaxCount}`);
  655. });
  656. it("rejects extra arguments on a no-argument op", async () => {
  657. const { driver, gitCalls } = makeDriver({ git: [{ stdout: "" }] });
  658. await expect(driver.executeWorldRead("git-status", ["extra"])).rejects.toMatchObject({
  659. code: "DriverError",
  660. });
  661. await expect(driver.executeWorldRead("git-diff", ["a", "b", "c"])).rejects.toMatchObject({
  662. code: "DriverError",
  663. });
  664. expect(gitCalls).toEqual([]);
  665. });
  666. });
  667. // ————————————————————————————————————————————————————————————————
  668. // 失败与上限
  669. // ————————————————————————————————————————————————————————————————
  670. describe("git world reads — failure and caps", () => {
  671. it("turns a non-repository / missing-binary failure into a catchable DriverError", async () => {
  672. // spec 的 fall-back-to-files.glob 惯用法就是一个纯 try/catch,所以这条失败必须是
  673. // **node 级**且带上 stderr 的线索。
  674. const failed: GitReply = {
  675. exitCode: 128,
  676. status: "failed",
  677. stderr: "fatal: not a git repository\n",
  678. };
  679. // 非仓库时**第一条**命令(rev-parse)就已经失败,所以两次断言各只消耗一条回复。
  680. const { driver } = makeDriver({ git: [failed, failed] });
  681. await expect(driver.executeWorldRead("git-status", [])).rejects.toMatchObject({
  682. code: "DriverError",
  683. });
  684. await expect(driver.executeWorldRead("git-status", [])).rejects.toThrow(/not a git repository/);
  685. });
  686. it("treats a spawn error as a DriverError too", async () => {
  687. const { driver } = makeDriver({
  688. git: [{ status: "spawn_error", stderr: "spawn git ENOENT" }],
  689. });
  690. await expect(driver.executeWorldRead("git-log", [])).rejects.toMatchObject({
  691. code: "DriverError",
  692. });
  693. });
  694. it("rejects an over-cap diff with WorldReadCapExceeded and actionable guidance", async () => {
  695. const cap = WORLD_READ_CAPS.gitDiffMaxBytes;
  696. const overflowing: GitReply = { stdout: "x".repeat(64), bytes: cap + 1, truncated: true };
  697. const { driver, gitCalls } = makeDriver({ git: [overflowing, overflowing] });
  698. await expect(driver.executeWorldRead("git-diff", [])).rejects.toMatchObject({
  699. code: "WorldReadCapExceeded",
  700. });
  701. await expect(driver.executeWorldRead("git-diff", [])).rejects.toThrow(/path/);
  702. // cap + 1 的 inline 上限是溢出探测的手法:刚好 cap 字节与"被截断"必须可区分。
  703. expect(gitCalls[0]?.maxInlineBytes).toBe(cap + 1);
  704. });
  705. it("passes a diff exactly at the cap through", async () => {
  706. const cap = WORLD_READ_CAPS.gitDiffMaxBytes;
  707. const { driver } = makeDriver({ git: [{ stdout: "ok", bytes: cap, truncated: false }] });
  708. await expect(driver.executeWorldRead("git-diff", [])).resolves.toBe("ok");
  709. });
  710. });
  711. // ————————————————————————————————————————————————————————————————
  712. // files.glob
  713. // ————————————————————————————————————————————————————————————————
  714. // 这组用例钉的是 2026-08-26 的一次真实事故(seq-map bug 扫描 run dwfrun-00cefbcb):
  715. // worldGlob 曾把文件系统端口的结果原样交出——绝对路径、mtime 降序、并静默继承端口
  716. // 面向 UI 工具的 100 条默认上限。绝对路径让脚本的 `startsWith("apps/…")` 路由全部
  717. // 落空,6 路扇出坍缩成 1 路;mtime 序让同一脚本两次提交扇出次序不同;100 条静默截断
  718. // 则违反 caps 的"拒绝、绝不截断"总则。三条契约在此各有一枚钉子。
  719. describe("files.glob world read", () => {
  720. it("maps the port's mtime-ordered absolute paths to lexicographic workspace-relative", async () => {
  721. const { driver, globRequests } = makeDriver({
  722. // 端口按 mtime 降序、绝对/相对混合(真适配器给绝对路径;形状归一是 driver 的事)。
  723. glob: ["/ws/src/z.ts", "/ws/a.ts", "src/m.ts"],
  724. });
  725. await expect(driver.executeWorldRead("glob", ["**/*.ts"])).resolves.toEqual([
  726. "a.ts",
  727. "src/m.ts",
  728. "src/z.ts",
  729. ]);
  730. expect(globRequests[0]).toMatchObject({
  731. path: CWD,
  732. pattern: "**/*.ts",
  733. // cap+1 惯用法(与 grep 同族):恰好 cap 条无从区分"正好"与"截掉了一百万条"。
  734. maxResults: WORLD_READ_CAPS.globMaxFiles + 1,
  735. });
  736. });
  737. it("rejects over-cap file counts with actionable guidance, never a truncated view", async () => {
  738. // 截断的世界视图会被 journal 记录、被 resume 原样重放,脚本还会拿它去扇出。
  739. const cap = WORLD_READ_CAPS.globMaxFiles;
  740. const tooMany = Array.from({ length: cap + 1 }, (_, i) => `/ws/f${i}.ts`);
  741. const { driver } = makeDriver({ glob: tooMany });
  742. await expect(driver.executeWorldRead("glob", ["**/*"])).rejects.toMatchObject({
  743. code: "WorldReadCapExceeded",
  744. });
  745. await expect(driver.executeWorldRead("glob", ["**/*"])).rejects.toThrow(/pattern/);
  746. });
  747. it("passes a file count exactly at the cap through", async () => {
  748. const cap = WORLD_READ_CAPS.globMaxFiles;
  749. const exact = Array.from({ length: cap }, (_, i) => `/ws/f${i}.ts`);
  750. const { driver } = makeDriver({ glob: exact });
  751. const files = (await driver.executeWorldRead("glob", ["**/*"])) as string[];
  752. expect(files).toHaveLength(cap);
  753. });
  754. it("rejects when the port reports truncation even under the count cap", async () => {
  755. // 与 grep 同一条线:端口若因别的原因截断,我们手上就不是完整结果了。
  756. const { driver } = makeDriver({ glob: ["/ws/a.ts"], globTruncated: true });
  757. await expect(driver.executeWorldRead("glob", ["*.ts"])).rejects.toMatchObject({
  758. code: "WorldReadCapExceeded",
  759. });
  760. });
  761. });
  762. // ————————————————————————————————————————————————————————————————
  763. // files.grep
  764. // ————————————————————————————————————————————————————————————————
  765. describe("files.grep world read", () => {
  766. it("maps port entries to workspace-relative {path, line, text}", async () => {
  767. const { driver, grepRequests } = makeDriver({
  768. grep: [
  769. { path: "/ws/src/a.ts", lineNumber: 12, text: "// TODO: fix" },
  770. { path: "src/b.ts", lineNumber: 3, text: "// TODO: later" },
  771. // 端口在别的 outputMode 下会产出没有行号的条目;那不是一条内容命中。
  772. { path: "/ws/src/c.ts", count: 4 },
  773. ],
  774. });
  775. await expect(driver.executeWorldRead("grep", ["TODO", "*.ts"])).resolves.toEqual([
  776. { path: "src/a.ts", line: 12, text: "// TODO: fix" },
  777. { path: "src/b.ts", line: 3, text: "// TODO: later" },
  778. ]);
  779. expect(grepRequests[0]).toMatchObject({
  780. path: CWD,
  781. pattern: "TODO",
  782. glob: "*.ts",
  783. outputMode: "content",
  784. showLineNumbers: true,
  785. headLimit: WORLD_READ_CAPS.grepMaxMatches + 1,
  786. });
  787. });
  788. it("omits glob entirely when the script did not pass one", async () => {
  789. const { driver, grepRequests } = makeDriver({ grep: [] });
  790. await expect(driver.executeWorldRead("grep", ["TODO"])).resolves.toEqual([]);
  791. expect("glob" in grepRequests[0]!).toBe(false);
  792. // 显式 undefined 是脚本可写的(`grep(p, undefined)`),归一成同一个"缺席"。
  793. const explicit = makeDriver({ grep: [] });
  794. await explicit.driver.executeWorldRead("grep", ["TODO", undefined]);
  795. expect("glob" in explicit.grepRequests[0]!).toBe(false);
  796. });
  797. it("rejects over-cap match counts with actionable guidance, never a truncated view", async () => {
  798. // 截断把一份悄悄残缺的世界视图交给脚本,而脚本接下来会拿它去扇出——扇出才是贵的那一步。
  799. const cap = WORLD_READ_CAPS.grepMaxMatches;
  800. const tooMany = Array.from({ length: cap + 1 }, (_, i) => ({
  801. path: `/ws/f${i}.ts`,
  802. lineNumber: 1,
  803. text: "hit",
  804. }));
  805. const { driver } = makeDriver({ grep: tooMany });
  806. await expect(driver.executeWorldRead("grep", ["."])).rejects.toMatchObject({
  807. code: "WorldReadCapExceeded",
  808. });
  809. await expect(driver.executeWorldRead("grep", ["."])).rejects.toThrow(/glob/);
  810. });
  811. it("passes a match count exactly at the cap through", async () => {
  812. const cap = WORLD_READ_CAPS.grepMaxMatches;
  813. const exact = Array.from({ length: cap }, (_, i) => ({
  814. path: `f${i}.ts`,
  815. lineNumber: 1,
  816. text: "h",
  817. }));
  818. const { driver } = makeDriver({ grep: exact });
  819. const matches = (await driver.executeWorldRead("grep", ["."])) as unknown[];
  820. expect(matches).toHaveLength(cap);
  821. });
  822. it("rejects when the port reports truncation even under the count cap", async () => {
  823. // 端口若因别的原因截断,我们手上就不是完整结果了——这与"命中数超限"是同一件事。
  824. const { driver } = makeDriver({
  825. grep: [{ path: "a.ts", lineNumber: 1, text: "h" }],
  826. grepTruncated: true,
  827. });
  828. await expect(driver.executeWorldRead("grep", ["."])).rejects.toMatchObject({
  829. code: "WorldReadCapExceeded",
  830. });
  831. });
  832. it("rejects an over-cap serialized size even when the match count is fine", async () => {
  833. // 两个上限**先到先拒**:少量命中也可以很大(一行 minified bundle)。
  834. const bigLine = "x".repeat(WORLD_READ_CAPS.grepMaxSerializedBytes);
  835. const { driver } = makeDriver({
  836. grep: [{ path: "bundle.js", lineNumber: 1, text: bigLine }],
  837. });
  838. await expect(driver.executeWorldRead("grep", ["x"])).rejects.toMatchObject({
  839. code: "WorldReadCapExceeded",
  840. });
  841. });
  842. it("rejects malformed grep arity", async () => {
  843. const { driver } = makeDriver({ grep: [] });
  844. await expect(driver.executeWorldRead("grep", [])).rejects.toMatchObject({
  845. code: "DriverError",
  846. });
  847. await expect(driver.executeWorldRead("grep", [42])).rejects.toMatchObject({
  848. code: "DriverError",
  849. });
  850. await expect(driver.executeWorldRead("grep", ["a", 42])).rejects.toMatchObject({
  851. code: "DriverError",
  852. });
  853. await expect(driver.executeWorldRead("grep", ["a", "b", "c"])).rejects.toMatchObject({
  854. code: "DriverError",
  855. });
  856. });
  857. });
  858. // ————————————————————————————————————————————————————————————————
  859. // facade 与 driver 的形状一致性
  860. // ————————————————————————————————————————————————————————————————
  861. describe("facade / driver shape agreement", () => {
  862. it("returns exactly the fields the facade declares", () => {
  863. // driver 侧的 GrepMatch / GitStatus / GitCommit 是 FACADE_DTS 的 TS 镜像(facade 是一个
  864. // 字符串资产,没法直接 import 它的类型)。这条断言让"镜像走形"在这里失败,而不是在
  865. // 某个脚本读到 undefined 字段的时候。
  866. for (const declaration of [
  867. "declare interface GrepMatch",
  868. "declare interface GitStatus",
  869. "declare interface GitCommit",
  870. "declare const git",
  871. "glob(pattern: string): Promise<string[]>",
  872. "grep(pattern: string, glob?: string)",
  873. "changedFiles(base?: string)",
  874. "diff(base?: string, path?: string)",
  875. "status(): Promise<GitStatus>",
  876. "log(count?: number): Promise<GitCommit[]>",
  877. ]) {
  878. expect(FACADE_DTS).toContain(declaration);
  879. }
  880. });
  881. });
  882. // ————————————————————————————————————————————————————————————————
  883. // 工作区收束:files.read 的路径必须落在工作区之内
  884. // ————————————————————————————————————————————————————————————————
  885. describe("files.read — workspace containment", () => {
  886. it("resolves a legitimate nested path against the workspace", async () => {
  887. const { driver, readPaths } = makeDriver({});
  888. await expect(driver.executeWorldRead("read", ["sub/nested/a.ts"])).resolves.toBe("body");
  889. expect(readPaths).toEqual([`${CWD}/sub/nested/a.ts`]);
  890. });
  891. it("rejects a path that escapes the workspace with ..", async () => {
  892. // 这道检查是 git.* 落地才变得要紧的:`changedFiles() → files.read(p)` 是那个最显然的
  893. // 两行组合,而 git 的原生输出在工作区是仓库子目录时会带 ../ 前缀。一个原语的显然组合
  894. // 不该是个陷阱。
  895. const { driver, readPaths } = makeDriver({});
  896. for (const escape of ["../outside.ts", "sub/../../outside.ts", "../../etc/passwd"]) {
  897. await expect(driver.executeWorldRead("read", [escape])).rejects.toMatchObject({
  898. code: "DriverError",
  899. });
  900. }
  901. // 一次都没打到端口:拒绝发生在解析之后、读取之前。
  902. expect(readPaths).toEqual([]);
  903. });
  904. it("rejects an absolute path outside the workspace", async () => {
  905. const { driver, readPaths } = makeDriver({});
  906. await expect(driver.executeWorldRead("read", ["/etc/passwd"])).rejects.toMatchObject({
  907. code: "DriverError",
  908. });
  909. expect(readPaths).toEqual([]);
  910. });
  911. it("accepts a path that normalizes back inside the workspace", async () => {
  912. // `sub/../a.ts` 归一成 `a.ts`,仍在工作区内——判据是**解析之后**的位置,不是字面量里
  913. // 有没有出现过 `..`。
  914. const { driver } = makeDriver({});
  915. await expect(driver.executeWorldRead("read", ["sub/../a.ts"])).resolves.toBe("body");
  916. });
  917. });