verify-translation-pairing.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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; `--write <pairs...>` records the named confirmed
  6. * pairs (`--write --all` records every complete pair); `--cached <pairs...>`
  7. * checks exact index bytes for hooks. A check or write named with pair paths
  8. * touches only those pairs, so update iteration does not pay for a corpus
  9. * scan. Translation quality remains a review responsibility.
  10. * See `docs/i18n/README.md` for the owning contract.
  11. */
  12. import { existsSync, globSync, readFileSync, statSync, writeFileSync } from 'node:fs'
  13. import { basename, join, resolve, sep } from 'node:path'
  14. import {
  15. gitBlobHash,
  16. gitIndexPaths,
  17. readGitIndexBlob,
  18. storeGitBlob,
  19. } from './translation-pairing-git.ts'
  20. import {
  21. parseTranslationPairingRecord,
  22. renderTranslationPairingRecord,
  23. translationPairPaths,
  24. } from './translation-pairing-record.ts'
  25. import {
  26. languageSwitcherTargets,
  27. parseTranslationMarkdown,
  28. parseTranslationPairingCliArgs,
  29. parseTranslationPairingManifest,
  30. partitionGeneratedRegions,
  31. requiresSourceLanguageSwitcher,
  32. isTranslationPairingManifestExcluded,
  33. isTranslationScopeFile,
  34. TRANSLATION_SCOPE_GLOB_EXCLUDES,
  35. translationPairSourcePredicate,
  36. translationStructureDiff,
  37. translationStructureSignature,
  38. } from './translation-pairing.ts'
  39. import {
  40. hasLanguageSwitcher,
  41. normalizeTranslationMarkdownLinks,
  42. translationLinkLocaleViolations,
  43. } from './translation-links.ts'
  44. const root = resolve(import.meta.dirname, '..')
  45. let request: ReturnType<typeof parseTranslationPairingCliArgs>
  46. try {
  47. request = parseTranslationPairingCliArgs(process.argv.slice(2))
  48. } catch (error) {
  49. console.error(`verify-translation-pairing: ${error instanceof Error ? error.message : String(error)}`)
  50. process.exit(2)
  51. }
  52. const listMode = request.mode === 'list'
  53. const writeMode = request.mode === 'write'
  54. const indexMode = request.input === 'index'
  55. const indexFiles = indexMode ? gitIndexPaths(root) : undefined
  56. const contentCache = new Map<string, Buffer | undefined>()
  57. /** Read one repository path from the selected worktree or index plane. */
  58. function readRepositoryFile(file: string): Buffer | undefined {
  59. if (contentCache.has(file)) return contentCache.get(file)
  60. const content = indexMode
  61. ? indexFiles?.has(file) ? readGitIndexBlob(root, file)?.content : undefined
  62. : existsSync(join(root, file)) && statSync(join(root, file)).isFile()
  63. ? readFileSync(join(root, file))
  64. : undefined
  65. contentCache.set(file, content)
  66. return content
  67. }
  68. /** Whether one path exists in the selected content plane. */
  69. function repositoryFileExists(file: string): boolean {
  70. return indexMode ? indexFiles?.has(file) === true : readRepositoryFile(file) !== undefined
  71. }
  72. /** Discover source Markdown and pairing sidecars before applying the corpus predicate. */
  73. const SCOPE_PATTERNS = [
  74. '**/*.md',
  75. '**/*.i18n.yaml',
  76. '.agents/notes/**/*.md',
  77. '.agents/notes/**/*.i18n.yaml',
  78. ]
  79. const manifestContent = readRepositoryFile('scripts/translation-pairing.manifest.json')
  80. if (manifestContent === undefined) {
  81. throw new Error('scripts/translation-pairing.manifest.json is missing from the selected content plane')
  82. }
  83. const manifest = parseTranslationPairingManifest(manifestContent.toString('utf8'))
  84. const isTranslationPairSource = translationPairSourcePredicate(manifest)
  85. /**
  86. * An excluded entry ending in `/` excludes the whole directory. The trailing
  87. * slash IS the path boundary — `docs/tool-catalog/` cannot prefix-match a
  88. * sibling like `docs/tool-catalog-notes/x.md` — so directory entries in the
  89. * manifest must keep their trailing slash.
  90. */
  91. function isExcluded(file: string): boolean {
  92. return isTranslationPairingManifestExcluded(file, manifest)
  93. }
  94. // Enumerate the scope once: the whole corpus, or exactly the named pairs'
  95. // three files (a named pair whose files are absent is caught by the same
  96. // completeness rules that cover discovered remnants).
  97. const files = new Set<string>()
  98. if (request.scope === 'pairs') {
  99. for (const anchor of request.anchors) {
  100. const { source, zh, meta } = translationPairPaths(anchor)
  101. for (const file of [source, zh, meta]) {
  102. if (repositoryFileExists(file)) files.add(file)
  103. }
  104. // A named worktree anchor with no files still enters the source list so
  105. // an interactive check reports it. An index check accepts a complete
  106. // three-file deletion and still rejects every partial deletion below.
  107. if (!indexMode && !repositoryFileExists(anchor)) files.add(anchor)
  108. }
  109. } else {
  110. for (const pattern of SCOPE_PATTERNS) {
  111. for (const match of globSync(pattern, { cwd: root, exclude: TRANSLATION_SCOPE_GLOB_EXCLUDES })) {
  112. const normalized = match.split(sep).join('/')
  113. if (isTranslationScopeFile(normalized)) files.add(normalized)
  114. }
  115. }
  116. }
  117. const translations = [...files].filter(f => f.endsWith('.zh.md')).sort()
  118. const metas = [...files].filter(f => f.endsWith('.i18n.yaml')).sort()
  119. const sources = [...files].filter(f => f.endsWith('.md') && !f.endsWith('.zh.md')).sort()
  120. if (request.scope === 'pairs') {
  121. const rejected = request.anchors.filter(anchor => !isTranslationScopeFile(anchor) || isExcluded(anchor))
  122. const absent = request.anchors.filter((anchor) => {
  123. const { source, zh, meta } = translationPairPaths(anchor)
  124. return ![source, zh, meta].some(repositoryFileExists)
  125. })
  126. if (rejected.length > 0 || (!indexMode && absent.length > 0)) {
  127. for (const anchor of rejected) {
  128. console.error(`verify-translation-pairing: ${anchor} is not an in-scope pair (excluded or outside the documentation corpus; see docs/i18n/README.md)`)
  129. }
  130. for (const anchor of absent) {
  131. console.error(`verify-translation-pairing: ${anchor} names no pair on disk (none of its three files exist)`)
  132. }
  133. process.exit(2)
  134. }
  135. }
  136. // --write: (re)record both hashes for the requested complete pairs, creating
  137. // missing records. A named pair that cannot be recorded (missing counterpart)
  138. // fails loud; corpus scope (--all) skips pairless sources as before.
  139. if (writeMode) {
  140. let written = 0
  141. for (const source of sources) {
  142. if (isExcluded(source)) continue
  143. const paths = translationPairPaths(source)
  144. const { zh, meta } = paths
  145. if (!repositoryFileExists(source) || !repositoryFileExists(zh)) {
  146. if (request.scope === 'pairs') {
  147. console.error(`verify-translation-pairing: cannot record ${source}: missing ${repositoryFileExists(source) ? zh : source}`)
  148. process.exit(2)
  149. }
  150. continue
  151. }
  152. const sourceContent = readRepositoryFile(source)
  153. const zhContent = readRepositoryFile(zh)
  154. if (sourceContent === undefined || zhContent === undefined) throw new Error(`${source}: complete pair became unreadable`)
  155. // A consistency record is also a recovery pointer for the briefing
  156. // generator. Persist both snapshots even when the sidecar text is already
  157. // current, because the bytes may exist only in this working tree.
  158. const record = renderTranslationPairingRecord(paths, {
  159. sourceHash: storeGitBlob(root, sourceContent),
  160. zhHash: storeGitBlob(root, zhContent),
  161. })
  162. if (existsSync(join(root, meta)) && readFileSync(join(root, meta), 'utf8') === record) continue
  163. writeFileSync(join(root, meta), record)
  164. console.log(`verify-translation-pairing: recorded ${meta}`)
  165. written++
  166. }
  167. console.log(`verify-translation-pairing: ${written} record(s) written; run the check to validate the pairs.`)
  168. process.exit(0)
  169. }
  170. const errors: string[] = []
  171. const state = new Map<string, 'ok' | 'out-of-sync' | 'missing'>()
  172. // 1. Every discovered, non-excluded source merges bilingual.
  173. for (const source of sources) {
  174. if (isExcluded(source)) continue
  175. const { zh } = translationPairPaths(source)
  176. if (!repositoryFileExists(zh)) {
  177. errors.push(`${source}: in-scope documentation must merge bilingual (docs/i18n/README.md); add the counterpart and record the pair`)
  178. state.set(source, 'missing')
  179. }
  180. }
  181. // 2. Every pair that exists at all is complete and consistent. Anchor on the
  182. // union of .zh.md files and .i18n.yaml records so a half-deleted pair is
  183. // caught from either remnant.
  184. const pairAnchors = new Set<string>()
  185. for (const zh of translations) pairAnchors.add(zh.replace(/\.zh\.md$/, '.md'))
  186. for (const meta of metas) pairAnchors.add(meta.replace(/\.i18n\.yaml$/, '.md'))
  187. for (const source of [...pairAnchors].sort()) {
  188. const paths = translationPairPaths(source)
  189. const { zh, meta } = paths
  190. const have = {
  191. source: repositoryFileExists(source),
  192. zh: repositoryFileExists(zh),
  193. meta: repositoryFileExists(meta),
  194. }
  195. if (isExcluded(source)) {
  196. if (have.zh) errors.push(`${zh}: ${source} is excluded from pairing (generated or bilingual-by-construction); this translation must not exist`)
  197. if (have.meta) errors.push(`${meta}: ${source} is excluded from pairing; this consistency record must not exist`)
  198. continue
  199. }
  200. const missing = Object.entries(have).filter(([, ok]) => !ok).map(([k]) => (k === 'source' ? source : k === 'zh' ? zh : meta))
  201. if (missing.length > 0) {
  202. errors.push(`${source}: incomplete pair — missing ${missing.join(', ')} (pairs merge whole: both languages plus the .i18n.yaml record)`)
  203. continue
  204. }
  205. const sourceContent = readRepositoryFile(source)
  206. const zhContent = readRepositoryFile(zh)
  207. const metaContent = readRepositoryFile(meta)
  208. if (sourceContent === undefined || zhContent === undefined || metaContent === undefined) {
  209. throw new Error(`${source}: complete pair became unreadable`)
  210. }
  211. const record = parseTranslationPairingRecord(metaContent.toString('utf8'), paths)
  212. if (record === undefined) {
  213. errors.push(`${meta}: malformed consistency record (expected exactly \`${basename(source)}: <40-hex>\` and \`${basename(zh)}: <40-hex>\`)`)
  214. continue
  215. }
  216. let consistent = true
  217. for (const [file, content] of [[source, sourceContent], [zh, zhContent]] as const) {
  218. const current = gitBlobHash(content)
  219. const recorded = file === source ? record.sourceHash : record.zhHash
  220. if (recorded !== current) {
  221. 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)`)
  222. consistent = false
  223. }
  224. }
  225. if (!consistent) {
  226. state.set(source, 'out-of-sync')
  227. continue
  228. }
  229. const sourceText = sourceContent.toString('utf8')
  230. const zhText = zhContent.toString('utf8')
  231. const sourceSwitcherTargets = languageSwitcherTargets(source)
  232. const zhSwitcherTargets = languageSwitcherTargets(zh)
  233. for (const violation of [
  234. ...translationLinkLocaleViolations(sourceText, {
  235. repoRoot: root,
  236. sourcePath: source,
  237. isTranslationPairSource,
  238. repositoryFileExists,
  239. }, zhSwitcherTargets),
  240. ...translationLinkLocaleViolations(zhText, {
  241. repoRoot: root,
  242. sourcePath: zh,
  243. isTranslationPairSource,
  244. repositoryFileExists,
  245. }, sourceSwitcherTargets),
  246. ]) {
  247. errors.push(`${violation.sourcePath}:${violation.line}: link target ${JSON.stringify(violation.url)} uses the wrong locale; expected ${JSON.stringify(violation.expectedUrl)}`)
  248. state.set(source, 'out-of-sync')
  249. }
  250. // Generated regions must remain byte-identical after paired document paths
  251. // are normalized to one semantic target. The structural signature below
  252. // compares their contents again as part of the whole document; this named
  253. // check rejects any prose, ordering, code, marker, or non-locale URL drift.
  254. let sourceRegions: { regions: string[]; stripped: string }
  255. let zhRegions: { regions: string[]; stripped: string }
  256. try {
  257. sourceRegions = partitionGeneratedRegions(sourceText)
  258. zhRegions = partitionGeneratedRegions(zhText)
  259. } catch (error) {
  260. errors.push(`${source} ↔ ${zh}: ${error instanceof Error ? error.message : String(error)}`)
  261. state.set(source, 'out-of-sync')
  262. continue
  263. }
  264. const normalizedSourceRegions = sourceRegions.regions.map(region => normalizeTranslationMarkdownLinks(region, {
  265. repoRoot: root,
  266. sourcePath: source,
  267. isTranslationPairSource,
  268. repositoryFileExists,
  269. }))
  270. const normalizedZhRegions = zhRegions.regions.map(region => normalizeTranslationMarkdownLinks(region, {
  271. repoRoot: root,
  272. sourcePath: zh,
  273. isTranslationPairSource,
  274. repositoryFileExists,
  275. }))
  276. if (normalizedSourceRegions.length !== normalizedZhRegions.length
  277. || normalizedSourceRegions.some((region, index) => region !== normalizedZhRegions[index])) {
  278. errors.push(`${source} ↔ ${zh}: generated regions differ beyond paired-document locale paths — regenerate both sides`)
  279. state.set(source, 'out-of-sync')
  280. }
  281. const sourceTree = parseTranslationMarkdown(sourceText)
  282. const zhTree = parseTranslationMarkdown(zhText)
  283. if (!hasLanguageSwitcher(zhTree, zhText, sourceSwitcherTargets)) {
  284. errors.push(`${zh}: missing language switcher — no link to ${basename(source)}`)
  285. }
  286. if (requiresSourceLanguageSwitcher(source) && !hasLanguageSwitcher(sourceTree, sourceText, zhSwitcherTargets)) {
  287. errors.push(`${source}: missing language switcher — no link back to ${basename(zh)}`)
  288. }
  289. for (const divergence of translationStructureDiff(
  290. translationStructureSignature(sourceTree, zhSwitcherTargets, {
  291. repoRoot: root,
  292. sourcePath: source,
  293. isTranslationPairSource,
  294. repositoryFileExists,
  295. markdown: sourceText,
  296. }),
  297. translationStructureSignature(zhTree, sourceSwitcherTargets, {
  298. repoRoot: root,
  299. sourcePath: zh,
  300. isTranslationPairSource,
  301. repositoryFileExists,
  302. markdown: zhText,
  303. }),
  304. )) {
  305. errors.push(`${source} ↔ ${zh}: ${divergence}`)
  306. }
  307. if (!state.has(source)) state.set(source, 'ok')
  308. }
  309. // Complete the state map for --list: any in-scope, non-excluded document with no pair is missing.
  310. for (const source of sources) {
  311. if (!isExcluded(source) && !state.has(source)) state.set(source, 'missing')
  312. }
  313. if (listMode) {
  314. const order = { 'out-of-sync': 0, missing: 1, ok: 2 } as const
  315. const rows = [...state.entries()].sort((a, b) => order[a[1]] - order[b[1]] || a[0].localeCompare(b[0]))
  316. for (const [file, status] of rows) {
  317. console.log(`${status.padEnd(11)} ${file}${status === 'missing' ? ' (required)' : ''}`)
  318. }
  319. const counts = { 'ok': 0, 'out-of-sync': 0, 'missing': 0 }
  320. for (const status of state.values()) counts[status]++
  321. console.log(`verify-translation-pairing: ${counts.ok} ok, ${counts['out-of-sync']} out-of-sync, ${counts.missing} missing (of ${state.size} in scope)`)
  322. process.exit(0)
  323. }
  324. if (errors.length === 0) {
  325. console.log(request.scope === 'pairs'
  326. ? `verify-translation-pairing: ${pairAnchors.size} named ${indexMode ? 'staged ' : ''}pair(s) consistent; the corpus-wide check still runs in doc-sync.`
  327. : `verify-translation-pairing: ${pairAnchors.size} pair(s) checked across all in-scope documentation, all consistent.`)
  328. process.exit(0)
  329. }
  330. console.error('verify-translation-pairing: bilingual pairing rules violated (see docs/i18n/README.md):')
  331. for (const message of errors) console.error(` ${message}`)
  332. process.exit(1)