translation-pairing.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /** Regression tests for bilingual snapshots, corpus scope, and structure. */
  2. import { execFileSync, spawnSync } from 'node:child_process'
  3. import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { describe, expect, it } from 'vitest'
  7. import { gitBlobHash, readGitIndexBlob, storeGitBlob } from './translation-pairing-git.ts'
  8. import {
  9. parseTranslationPairingRecord,
  10. renderTranslationPairingRecord,
  11. translationPairPaths,
  12. } from './translation-pairing-record.ts'
  13. import {
  14. blobHash,
  15. isTranslationScopeFile,
  16. pairAnchorOfArgument,
  17. parseTranslationMarkdown,
  18. parseTranslationPairingCliArgs,
  19. parseTranslationPairingManifest,
  20. partitionGeneratedRegions,
  21. requiresSourceLanguageSwitcher,
  22. translationStructureDiff,
  23. translationStructureSignature,
  24. } from './translation-pairing.ts'
  25. function signature(markdown: string) {
  26. return translationStructureSignature(parseTranslationMarkdown(markdown), 'counterpart.zh.md')
  27. }
  28. function gitSupportsObjectFormat(format: 'sha256'): boolean {
  29. const root = mkdtempSync(join(tmpdir(), 'dsh-git-object-format-'))
  30. try {
  31. return spawnSync('git', ['init', '--quiet', `--object-format=${format}`, root], {
  32. stdio: 'ignore',
  33. }).status === 0
  34. } finally {
  35. rmSync(root, { recursive: true, force: true })
  36. }
  37. }
  38. const supportsSha256ObjectFormat = gitSupportsObjectFormat('sha256')
  39. describe('translation pairing snapshots', () => {
  40. it('stores exact uncommitted bytes for later recovery by object ID', () => {
  41. const root = mkdtempSync(join(tmpdir(), 'dsh-translation-pairing-'))
  42. try {
  43. execFileSync('git', ['init', '--quiet', root], {
  44. env: { ...process.env, GIT_DEFAULT_HASH: 'sha1' },
  45. })
  46. const content = Buffer.from([0x75, 0x6e, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x0a, 0xff])
  47. const objectId = storeGitBlob(root, content)
  48. expect(objectId).toBe(gitBlobHash(content))
  49. expect(execFileSync('git', [
  50. '-C', root, 'rev-parse', `refs/dsh/translation-pairing/snapshots/${objectId}`,
  51. ], { encoding: 'utf8' }).trim()).toBe(objectId)
  52. execFileSync('git', ['-C', root, 'gc', '--prune=now'])
  53. expect(execFileSync('git', ['-C', root, 'cat-file', '-p', objectId])).toEqual(content)
  54. } finally {
  55. rmSync(root, { recursive: true, force: true })
  56. }
  57. })
  58. it('fails before a sidecar can reference an unavailable object', () => {
  59. const root = mkdtempSync(join(tmpdir(), 'dsh-translation-pairing-'))
  60. try {
  61. expect(() => storeGitBlob(root, Buffer.from('snapshot'))).toThrow('git hash-object -w --stdin failed')
  62. } finally {
  63. rmSync(root, { recursive: true, force: true })
  64. }
  65. })
  66. it('fails clearly when Git cannot be started', () => {
  67. const previousPath = process.env.PATH
  68. try {
  69. process.env.PATH = ''
  70. expect(() => storeGitBlob('.', Buffer.from('snapshot'))).toThrow('git hash-object -w --stdin failed')
  71. } finally {
  72. process.env.PATH = previousPath
  73. }
  74. })
  75. it('reads staged bytes independently of the working tree', () => {
  76. const root = mkdtempSync(join(tmpdir(), 'dsh-translation-pairing-index-'))
  77. try {
  78. execFileSync('git', ['init', '--quiet', root], {
  79. env: { ...process.env, GIT_DEFAULT_HASH: 'sha1' },
  80. })
  81. execFileSync('git', ['-C', root, 'config', 'user.email', 'pairing@example.test'])
  82. execFileSync('git', ['-C', root, 'config', 'user.name', 'Pairing Test'])
  83. writeFileSync(join(root, 'owner.md'), 'staged')
  84. execFileSync('git', ['-C', root, 'add', 'owner.md'])
  85. writeFileSync(join(root, 'owner.md'), 'unstaged')
  86. const indexed = readGitIndexBlob(root, 'owner.md')
  87. expect(indexed?.content.toString('utf8')).toBe('staged')
  88. expect(indexed?.objectId).toBe(gitBlobHash(Buffer.from('staged')))
  89. expect(readGitIndexBlob(root, 'absent.md')).toBeUndefined()
  90. } finally {
  91. rmSync(root, { recursive: true, force: true })
  92. }
  93. })
  94. it.skipIf(!supportsSha256ObjectFormat)('rejects an object format that pairing records cannot represent', () => {
  95. const root = mkdtempSync(join(tmpdir(), 'dsh-translation-pairing-'))
  96. try {
  97. execFileSync('git', ['init', '--quiet', '--object-format=sha256', root])
  98. expect(() => storeGitBlob(root, Buffer.from('snapshot'))).toThrow('returned unexpected object ID')
  99. } finally {
  100. rmSync(root, { recursive: true, force: true })
  101. }
  102. })
  103. })
  104. describe('translation pairing manifest', () => {
  105. it('accepts an exclusions-only manifest', () => {
  106. expect(parseTranslationPairingManifest(JSON.stringify({
  107. excluded: ['docs/generated/'],
  108. }))).toEqual({
  109. excluded: ['docs/generated/'],
  110. })
  111. })
  112. it.each([
  113. ['required', ['packages/README.md']],
  114. ['requiredClasses', ['readme']],
  115. ['requiredSince', '2026-07-14'],
  116. ] as const)('rejects obsolete policy field %s instead of accepting an inert requirement', (field, value) => {
  117. expect(() => parseTranslationPairingManifest(JSON.stringify({
  118. excluded: [],
  119. [field]: value,
  120. }))).toThrow(`unsupported field(s): ${field}; every in-scope document is required`)
  121. })
  122. it('rejects a missing or non-string exclusion list', () => {
  123. expect(() => parseTranslationPairingManifest('{}')).toThrow('excluded must be an array of strings')
  124. expect(() => parseTranslationPairingManifest(JSON.stringify({
  125. excluded: [42],
  126. }))).toThrow('excluded must be an array of strings')
  127. })
  128. })
  129. describe('translation pairing switchers', () => {
  130. it('exempts only paired generated English sources from reciprocal switchers', () => {
  131. expect(requiresSourceLanguageSwitcher('docs/config-catalog.md')).toBe(false)
  132. expect(requiresSourceLanguageSwitcher('docs/cordis-api/context.md')).toBe(false)
  133. expect(requiresSourceLanguageSwitcher('docs/cordis-api/inherited.md')).toBe(false)
  134. expect(requiresSourceLanguageSwitcher('docs/architecture.md')).toBe(true)
  135. expect(requiresSourceLanguageSwitcher('packages/core/session/README.md')).toBe(true)
  136. })
  137. })
  138. describe('translation pairing records', () => {
  139. const paths = translationPairPaths('docs/foo.md')
  140. const record = {
  141. sourceHash: '1'.repeat(40),
  142. zhHash: '2'.repeat(40),
  143. }
  144. it('round-trips the canonical two-hash record', () => {
  145. expect(parseTranslationPairingRecord(renderTranslationPairingRecord(paths, record), paths)).toEqual(record)
  146. })
  147. it('rejects duplicate or unexpected keys', () => {
  148. expect(parseTranslationPairingRecord([
  149. `foo.md: ${'1'.repeat(40)}`,
  150. `foo.md: ${'3'.repeat(40)}`,
  151. `foo.zh.md: ${'2'.repeat(40)}`,
  152. '',
  153. ].join('\n'), paths)).toBeUndefined()
  154. expect(parseTranslationPairingRecord([
  155. `foo.md: ${'1'.repeat(40)}`,
  156. `bar.zh.md: ${'2'.repeat(40)}`,
  157. '',
  158. ].join('\n'), paths)).toBeUndefined()
  159. })
  160. })
  161. describe('translation scope discovery', () => {
  162. it.each([
  163. 'README.md',
  164. 'CONTRIBUTING.md',
  165. 'CONTRIBUTING.zh.md',
  166. 'CONTRIBUTING.i18n.yaml',
  167. 'apps/cli/README.md',
  168. 'future/subtree/readme.md',
  169. 'packages/example/README.zh.md',
  170. 'native/example/README.i18n.yaml',
  171. '.agents/notes/proposed/feature.md',
  172. 'docs/guide.md',
  173. 'python/guide.md',
  174. ])('includes %s', (file) => {
  175. expect(isTranslationScopeFile(file)).toBe(true)
  176. })
  177. it.each([
  178. 'packages/example/guide.md',
  179. 'packages/example/CONTRIBUTING.md',
  180. 'examples/tutorial.md',
  181. 'website/reference.md',
  182. 'packages/example/README.txt',
  183. 'vendor/example/README.md',
  184. 'packages/example/node_modules/dependency/README.md',
  185. 'packages/example/lib/README.md',
  186. 'coverage/report/README.md',
  187. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-macos-arm64/README.md',
  188. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/README.md',
  189. ])('excludes non-source or non-README path %s', (file) => {
  190. expect(isTranslationScopeFile(file)).toBe(false)
  191. })
  192. })
  193. describe('translation structural signature', () => {
  194. it('accepts matching list kinds, starts, and item counts', () => {
  195. const source = signature('3. One\n4. Two\n\n- A\n- B\n')
  196. const counterpart = signature('3. 一\n4. 二\n\n- 甲\n- 乙\n')
  197. expect(translationStructureDiff(source, counterpart)).toEqual([])
  198. })
  199. it('rejects an altered ordered-list start', () => {
  200. const source = signature('3. One\n4. Two\n\n- A\n- B\n')
  201. const counterpart = signature('1. 一\n2. 二\n\n- 甲\n- 乙\n')
  202. expect(translationStructureDiff(source, counterpart)).toEqual([
  203. 'list (kind, start, item count) #1 diverges between the pair: "ordered:start=3:items=2" vs "ordered:start=1:items=2"',
  204. ])
  205. })
  206. it('rejects a missing list item', () => {
  207. const source = signature('- A\n- B\n')
  208. const counterpart = signature('- 甲\n')
  209. expect(translationStructureDiff(source, counterpart)).toEqual([
  210. 'list (kind, start, item count) #1 diverges between the pair: "bullet:items=2" vs "bullet:items=1"',
  211. ])
  212. })
  213. it('rejects altered table row or column counts', () => {
  214. const source = signature('| A | B |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n')
  215. const counterpart = signature('| 甲 | 乙 |\n|---|---|\n| 一 | 二 |\n')
  216. expect(translationStructureDiff(source, counterpart)).toEqual([
  217. 'table (row x column count) #1 diverges between the pair: "3x2" vs "2x2"',
  218. ])
  219. })
  220. })
  221. describe('pair CLI arguments', () => {
  222. it('normalizes any pair file or bare stem to the English anchor', () => {
  223. expect(pairAnchorOfArgument('docs/foo.md')).toBe('docs/foo.md')
  224. expect(pairAnchorOfArgument('docs/foo.zh.md')).toBe('docs/foo.md')
  225. expect(pairAnchorOfArgument('docs/foo.i18n.yaml')).toBe('docs/foo.md')
  226. expect(pairAnchorOfArgument('docs/foo')).toBe('docs/foo.md')
  227. expect(pairAnchorOfArgument('.\\docs\\foo.zh.md')).toBe('docs/foo.md')
  228. })
  229. it('scopes a check to named pairs and dedupes the three spellings', () => {
  230. expect(parseTranslationPairingCliArgs(['docs/foo.zh.md', 'docs/foo.i18n.yaml', 'docs/bar.md'])).toEqual({
  231. input: 'worktree',
  232. mode: 'check',
  233. scope: 'pairs',
  234. anchors: ['docs/bar.md', 'docs/foo.md'],
  235. })
  236. expect(parseTranslationPairingCliArgs([])).toEqual({
  237. input: 'worktree',
  238. mode: 'check',
  239. scope: 'corpus',
  240. anchors: [],
  241. })
  242. })
  243. it('requires --write to name confirmed pairs or opt into --all', () => {
  244. expect(() => parseTranslationPairingCliArgs(['--write'])).toThrow('requires the pair(s) you confirmed')
  245. expect(parseTranslationPairingCliArgs(['--write', 'docs/foo.md'])).toEqual({
  246. input: 'worktree',
  247. mode: 'write',
  248. scope: 'pairs',
  249. anchors: ['docs/foo.md'],
  250. })
  251. expect(parseTranslationPairingCliArgs(['--write', '--all'])).toEqual({
  252. input: 'worktree',
  253. mode: 'write',
  254. scope: 'corpus',
  255. anchors: [],
  256. })
  257. expect(() => parseTranslationPairingCliArgs(['--write', '--all', 'docs/foo.md'])).toThrow('not both')
  258. })
  259. it('keeps --list corpus-only and rejects unknown flags', () => {
  260. expect(parseTranslationPairingCliArgs(['--list'])).toEqual({
  261. input: 'worktree',
  262. mode: 'list',
  263. scope: 'corpus',
  264. anchors: [],
  265. })
  266. expect(() => parseTranslationPairingCliArgs(['--list', 'docs/foo.md'])).toThrow('takes no other flags or paths')
  267. expect(() => parseTranslationPairingCliArgs(['--all'])).toThrow('--all only applies to --write')
  268. expect(() => parseTranslationPairingCliArgs(['--frobnicate'])).toThrow('unknown flag(s): --frobnicate')
  269. })
  270. it('makes cached verification a named, read-only index check', () => {
  271. expect(parseTranslationPairingCliArgs(['--cached', 'docs/foo.i18n.yaml'])).toEqual({
  272. input: 'index',
  273. mode: 'check',
  274. scope: 'pairs',
  275. anchors: ['docs/foo.md'],
  276. })
  277. expect(() => parseTranslationPairingCliArgs(['--cached'])).toThrow('requires the staged pair paths')
  278. expect(() => parseTranslationPairingCliArgs(['--cached', '--write', 'docs/foo.md'])).toThrow('read-only')
  279. })
  280. })
  281. describe('generated regions', () => {
  282. const BEGIN = '<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->'
  283. const END = '<!-- END GENERATED cordis-surface -->'
  284. it('partitions marker-delimited regions from the hand-owned remainder', () => {
  285. const doc = `# T\n\nprose\n\n${BEGIN}\ninjected\n${END}\ntail\n`
  286. const { regions, stripped } = partitionGeneratedRegions(doc)
  287. expect(regions).toEqual([`${BEGIN}\ninjected\n${END}`])
  288. expect(stripped).toBe('# T\n\nprose\n\ntail\n')
  289. })
  290. it('treats a document without markers as one hand-owned remainder', () => {
  291. const { regions, stripped } = partitionGeneratedRegions('# T\n\nprose\n')
  292. expect(regions).toEqual([])
  293. expect(stripped).toBe('# T\n\nprose\n')
  294. })
  295. it('rejects unbalanced or nested markers', () => {
  296. expect(() => partitionGeneratedRegions(`${END}\n`)).toThrow('without a BEGIN')
  297. expect(() => partitionGeneratedRegions(`${BEGIN}\n`)).toThrow('without an END')
  298. expect(() => partitionGeneratedRegions(`${BEGIN}\n${BEGIN}\n${END}\n`)).toThrow('nested')
  299. })
  300. it('rejects mismatched slugs and malformed marker lines', () => {
  301. expect(() => partitionGeneratedRegions('<!-- BEGIN GENERATED a -->\nx\n<!-- END GENERATED b -->\n'))
  302. .toThrow("END slug 'b' does not match its BEGIN slug 'a'")
  303. expect(() => partitionGeneratedRegions('<!-- BEGIN GENERATED a --> trailing\nx\n<!-- END GENERATED a -->\n'))
  304. .toThrow('malformed generated region marker line')
  305. expect(() => partitionGeneratedRegions('x\n<!-- END GENERATED a --> tail\n'))
  306. .toThrow('malformed generated region marker line')
  307. })
  308. it('computes the exact git blob hash', () => {
  309. // `git hash-object` of the empty file and of "x\n" — pinned upstream values.
  310. expect(blobHash(Buffer.from(''))).toBe('e69de29bb2d1d6434b8b29ae775ad8c2e48c5391')
  311. expect(blobHash(Buffer.from('x\n'))).toBe('587be6b4c3f93f93c489c0111bba5596147a26cb')
  312. })
  313. })