1
0

verify-translation-pairing.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /**
  2. * Enforce complete English/Chinese pairs, matching structure, and recorded git
  3. * blob hashes under the bilingual manifest. Required files and date-named docs
  4. * at or after `requiredSince` must be paired; excluded docs may have neither a
  5. * counterpart nor sidecar. `--list` reports state and `--write` records both
  6. * sides after human review. Translation quality remains a review responsibility.
  7. * See `docs/i18n/README.md` for the owning contract.
  8. */
  9. import { createHash } from 'node:crypto'
  10. import { existsSync, globSync, readFileSync, writeFileSync } from 'node:fs'
  11. import { basename, join, resolve, sep } from 'node:path'
  12. import {
  13. datedDocumentDate,
  14. linksTo,
  15. parseTranslationMarkdown,
  16. parseTranslationPairingManifest,
  17. requiresPairByDate,
  18. translationStructureDiff,
  19. translationStructureSignature,
  20. } from './translation-pairing.ts'
  21. const root = resolve(import.meta.dirname, '..')
  22. const listMode = process.argv.includes('--list')
  23. const writeMode = process.argv.includes('--write')
  24. /** Scope of the bilingual contract: the root README, the docs tree, and the Python SDK tree. */
  25. const SCOPE_PATTERNS = ['README.md', 'README.zh.md', 'README.i18n.yaml', 'docs/**/*.md', 'docs/**/*.i18n.yaml', 'python/**/*.md', 'python/**/*.i18n.yaml']
  26. const manifest = parseTranslationPairingManifest(readFileSync(join(root, 'scripts/translation-pairing.manifest.json'), 'utf8'))
  27. /**
  28. * An excluded entry ending in `/` excludes the whole directory. The trailing
  29. * slash IS the path boundary — `docs/tool-catalog/` cannot prefix-match a
  30. * sibling like `docs/tool-catalog-notes/x.md` — so directory entries in the
  31. * manifest must keep their trailing slash.
  32. */
  33. function isExcluded(file: string): boolean {
  34. return manifest.excluded.some(entry => (entry.endsWith('/') ? file.startsWith(entry) : file === entry))
  35. }
  36. /** Full git blob hash (what `git hash-object` prints). */
  37. function blobHash(content: Buffer): string {
  38. const hash = createHash('sha1')
  39. hash.update(`blob ${content.byteLength}\0`)
  40. hash.update(content)
  41. return hash.digest('hex')
  42. }
  43. /** The three paths of a pair, derived from the English-file path. */
  44. function pairPaths(source: string): { zh: string; meta: string } {
  45. return { zh: source.replace(/\.md$/, '.zh.md'), meta: source.replace(/\.md$/, '.i18n.yaml') }
  46. }
  47. const META_LINE = /^([^:#]+\.md): ([0-9a-f]{40})$/
  48. /** Parse a `foo.i18n.yaml` consistency record: basename → recorded blob hash. */
  49. function parseMeta(content: string): Map<string, string> | undefined {
  50. const out = new Map<string, string>()
  51. for (const line of content.split('\n')) {
  52. if (line === '' || line.startsWith('#')) continue
  53. const match = META_LINE.exec(line)
  54. if (!match?.[1] || !match[2]) return undefined
  55. out.set(match[1], match[2])
  56. }
  57. return out
  58. }
  59. /** Render a `foo.i18n.yaml` consistency record. */
  60. function renderMeta(source: string, sourceHash: string, zh: string, zhHash: string): string {
  61. return [
  62. '# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each',
  63. '# side as of the last confirmed-consistent state. Both languages carry equal authority;',
  64. '# after editing either side, bring the other along and re-record with:',
  65. '# pnpm run verify-translation-pairing --write',
  66. `${basename(source)}: ${sourceHash}`,
  67. `${basename(zh)}: ${zhHash}`,
  68. '',
  69. ].join('\n')
  70. }
  71. // Enumerate the scope once.
  72. const files = new Set<string>()
  73. for (const pattern of SCOPE_PATTERNS) {
  74. for (const match of globSync(pattern, { cwd: root })) files.add(match.split(sep).join('/'))
  75. }
  76. const translations = [...files].filter(f => f.endsWith('.zh.md')).sort()
  77. const metas = [...files].filter(f => f.endsWith('.i18n.yaml')).sort()
  78. const sources = [...files].filter(f => f.endsWith('.md') && !f.endsWith('.zh.md')).sort()
  79. // --write: (re)record both hashes for every complete pair, creating missing records.
  80. if (writeMode) {
  81. let written = 0
  82. for (const source of sources) {
  83. if (isExcluded(source)) continue
  84. const { zh, meta } = pairPaths(source)
  85. if (!existsSync(join(root, zh))) continue
  86. const record = renderMeta(source, blobHash(readFileSync(join(root, source))), zh, blobHash(readFileSync(join(root, zh))))
  87. if (existsSync(join(root, meta)) && readFileSync(join(root, meta), 'utf8') === record) continue
  88. writeFileSync(join(root, meta), record)
  89. console.log(`verify-translation-pairing: recorded ${meta}`)
  90. written++
  91. }
  92. console.log(`verify-translation-pairing: ${written} record(s) written; run the check to validate the pairs.`)
  93. process.exit(0)
  94. }
  95. const errors: string[] = []
  96. const state = new Map<string, 'ok' | 'out-of-sync' | 'missing'>()
  97. // 1. Required pairs exist.
  98. for (const req of manifest.required) {
  99. if (!existsSync(join(root, req))) {
  100. errors.push(`${req}: listed in translation-pairing.manifest.json \`required\` but the file does not exist`)
  101. continue
  102. }
  103. const { zh } = pairPaths(req)
  104. if (!existsSync(join(root, zh))) {
  105. errors.push(`${req}: required to have a translation, but ${zh} does not exist`)
  106. state.set(req, 'missing')
  107. }
  108. }
  109. // 2. Date-named documents (RFCs) dated on/after the requiredSince cutoff merge
  110. // bilingual: a new RFC lands with its pair or not at all. Deterministic from
  111. // the filename alone — no git history, so it holds on shallow CI checkouts.
  112. for (const source of sources) {
  113. if (isExcluded(source)) continue
  114. const date = datedDocumentDate(source)
  115. if (!requiresPairByDate(source, manifest.requiredSince) || date === undefined) continue
  116. const { zh } = pairPaths(source)
  117. if (!existsSync(join(root, zh))) {
  118. errors.push(`${source}: dated ${date} — documents dated on/after ${manifest.requiredSince} merge bilingual (docs/i18n/README.md); add the counterpart and record the pair`)
  119. state.set(source, 'missing')
  120. }
  121. }
  122. // 3. Every pair that exists at all is complete and consistent. Anchor on the
  123. // union of .zh.md files and .i18n.yaml records so a half-deleted pair is
  124. // caught from either remnant.
  125. const pairAnchors = new Set<string>()
  126. for (const zh of translations) pairAnchors.add(zh.replace(/\.zh\.md$/, '.md'))
  127. for (const meta of metas) pairAnchors.add(meta.replace(/\.i18n\.yaml$/, '.md'))
  128. for (const source of [...pairAnchors].sort()) {
  129. const { zh, meta } = pairPaths(source)
  130. const have = { source: existsSync(join(root, source)), zh: existsSync(join(root, zh)), meta: existsSync(join(root, meta)) }
  131. if (isExcluded(source)) {
  132. if (have.zh) errors.push(`${zh}: ${source} is excluded from pairing (generated or bilingual-by-construction); this translation must not exist`)
  133. if (have.meta) errors.push(`${meta}: ${source} is excluded from pairing; this consistency record must not exist`)
  134. continue
  135. }
  136. const missing = Object.entries(have).filter(([, ok]) => !ok).map(([k]) => (k === 'source' ? source : k === 'zh' ? zh : meta))
  137. if (missing.length > 0) {
  138. errors.push(`${source}: incomplete pair — missing ${missing.join(', ')} (pairs merge whole: both languages plus the .i18n.yaml record)`)
  139. continue
  140. }
  141. const sourceContent = readFileSync(join(root, source))
  142. const zhContent = readFileSync(join(root, zh))
  143. const record = parseMeta(readFileSync(join(root, meta), 'utf8'))
  144. if (!record || record.size !== 2 || !record.has(basename(source)) || !record.has(basename(zh))) {
  145. errors.push(`${meta}: malformed consistency record (expected exactly \`${basename(source)}: <40-hex>\` and \`${basename(zh)}: <40-hex>\`)`)
  146. continue
  147. }
  148. let consistent = true
  149. for (const [file, content] of [[source, sourceContent], [zh, zhContent]] as const) {
  150. const current = blobHash(content)
  151. if (record.get(basename(file)) !== current) {
  152. errors.push(`${file}: out of sync — content no longer matches the pair's last confirmed-consistent state in ${meta} (bring the other side along, then re-record with --write)`)
  153. consistent = false
  154. }
  155. }
  156. if (!consistent) {
  157. state.set(source, 'out-of-sync')
  158. continue
  159. }
  160. const sourceTree = parseTranslationMarkdown(sourceContent.toString('utf8'))
  161. const zhTree = parseTranslationMarkdown(zhContent.toString('utf8'))
  162. if (!linksTo(zhTree, basename(source))) {
  163. errors.push(`${zh}: missing language switcher — no link to ${basename(source)}`)
  164. }
  165. if (!linksTo(sourceTree, basename(zh))) {
  166. errors.push(`${source}: missing language switcher — no link back to ${basename(zh)}`)
  167. }
  168. for (const divergence of translationStructureDiff(
  169. translationStructureSignature(sourceTree, basename(zh)),
  170. translationStructureSignature(zhTree, basename(source)),
  171. )) {
  172. errors.push(`${source} ↔ ${zh}: ${divergence}`)
  173. }
  174. if (!state.has(source)) state.set(source, 'ok')
  175. }
  176. // Complete the state map for --list: any in-scope, non-excluded document with no pair yet is backlog.
  177. for (const source of sources) {
  178. if (!isExcluded(source) && !state.has(source)) state.set(source, 'missing')
  179. }
  180. if (listMode) {
  181. const order = { 'out-of-sync': 0, missing: 1, ok: 2 } as const
  182. const rows = [...state.entries()].sort((a, b) => order[a[1]] - order[b[1]] || a[0].localeCompare(b[0]))
  183. for (const [file, status] of rows) {
  184. const required = manifest.required.includes(file)
  185. const tag = required ? ' (required)' : requiresPairByDate(file, manifest.requiredSince) ? ' (required by date)' : ' (backlog)'
  186. console.log(`${status.padEnd(11)} ${file}${status === 'missing' ? tag : ''}`)
  187. }
  188. const counts = { 'ok': 0, 'out-of-sync': 0, 'missing': 0 }
  189. for (const status of state.values()) counts[status]++
  190. console.log(`verify-translation-pairing: ${counts.ok} ok, ${counts['out-of-sync']} out-of-sync, ${counts.missing} missing (of ${state.size} in scope)`)
  191. process.exit(0)
  192. }
  193. if (errors.length === 0) {
  194. console.log(`verify-translation-pairing: ${pairAnchors.size} pair(s) checked against ${manifest.required.length} required, all consistent.`)
  195. process.exit(0)
  196. }
  197. console.error('verify-translation-pairing: bilingual pairing contract violated (see docs/i18n/README.md):')
  198. for (const message of errors) console.error(` ${message}`)
  199. process.exit(1)