verify-translation-pairing.ts 9.0 KB

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