verify-translation-pairing.ts 13 KB

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