verify-translation-pairing.ts 9.8 KB

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