1
0

gen-translation-brief.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /**
  2. * Print the minimal-update briefing for out-of-sync translation pairs:
  3. * `pnpm run gen-translation-brief [--apply] [pair paths...]`. With no
  4. * arguments it discovers every out-of-sync pair; with arguments (any file
  5. * of a pair) it briefs exactly those pairs and fails loud on in-sync,
  6. * incomplete, or out-of-scope requests. Each briefing maps the change at
  7. * the narrowest safe granularity — code-fence-only splice, changed
  8. * Markdown units, heading sections, whole document — and `--apply` writes
  9. * the computed counterpart for pairs whose change is code-fence-only.
  10. * The briefing contract lives in `scripts/translation-brief.ts`; the
  11. * consuming workflow is `.agents/skills/dsh-translate-docs/SKILL.md`.
  12. */
  13. import { spawnSync } from 'node:child_process'
  14. import { existsSync, globSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  15. import { tmpdir } from 'node:os'
  16. import { basename, join, resolve, sep } from 'node:path'
  17. import {
  18. isTranslationScopeFile,
  19. pairAnchorOfArgument,
  20. parseTranslationMarkdown,
  21. parseTranslationPairingManifest,
  22. TRANSLATION_SCOPE_GLOB_EXCLUDES,
  23. translationStructureDiff,
  24. translationStructureSignature,
  25. } from './translation-pairing.ts'
  26. import {
  27. changedSpanIndices,
  28. computeMechanicalUpdate,
  29. firstOccurrenceContext,
  30. markdownUnits,
  31. relevantTerminologyRows,
  32. renderTranslationBrief,
  33. sectionSpans,
  34. spansAligned,
  35. type BriefBundle,
  36. type BriefDirection,
  37. type BriefScope,
  38. type MarkdownSpan,
  39. } from './translation-brief.ts'
  40. const root = resolve(import.meta.dirname, '..')
  41. const manifest = parseTranslationPairingManifest(readFileSync(join(root, 'scripts/translation-pairing.manifest.json'), 'utf8'))
  42. const terminology = readFileSync(join(root, 'docs/i18n/terminology.md'), 'utf8')
  43. function isExcluded(file: string): boolean {
  44. return manifest.excluded.some(entry => (entry.endsWith('/') ? file.startsWith(entry) : file === entry))
  45. }
  46. /** Recorded hashes of one consistency record: basename → blob hash. */
  47. function parseMeta(content: string): Map<string, string> | undefined {
  48. const out = new Map<string, string>()
  49. for (const line of content.split('\n')) {
  50. if (line === '' || line.startsWith('#')) continue
  51. const match = /^([^:#]+\.md): ([0-9a-f]{40})$/.exec(line)
  52. if (!match?.[1] || !match[2]) return undefined
  53. out.set(match[1], match[2])
  54. }
  55. return out
  56. }
  57. function git(args: string[], allowedExitCodes: number[] = [0]): string {
  58. const result = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 1 << 26 })
  59. if (result.error) throw result.error
  60. if (!allowedExitCodes.includes(result.status ?? -1)) {
  61. throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`)
  62. }
  63. return result.stdout
  64. }
  65. function blobText(hash: string): string {
  66. return git(['cat-file', '-p', hash])
  67. }
  68. /** Unified diff between two texts, headers stripped, via `git diff --no-index`. */
  69. function diffTexts(before: string, after: string): string {
  70. const dir = mkdtempSync(join(tmpdir(), 'translation-brief-'))
  71. try {
  72. writeFileSync(join(dir, 'last-confirmed.md'), before)
  73. writeFileSync(join(dir, 'current.md'), after)
  74. const raw = git(['diff', '--no-index', '--unified=2', join(dir, 'last-confirmed.md'), join(dir, 'current.md')], [0, 1])
  75. return raw.split('\n')
  76. .filter(line => !line.startsWith('diff --git') && !line.startsWith('index ') && !line.startsWith('--- ') && !line.startsWith('+++ '))
  77. .join('\n')
  78. .trim()
  79. } finally {
  80. rmSync(dir, { recursive: true, force: true })
  81. }
  82. }
  83. interface PairState {
  84. anchor: string
  85. zh: string
  86. meta: string
  87. enDrifted: boolean
  88. zhDrifted: boolean
  89. enLast: string
  90. zhLast: string
  91. }
  92. /** Load one pair's recorded and current state, or explain why it cannot be briefed. */
  93. function loadPair(anchor: string): PairState | string {
  94. const zh = anchor.replace(/\.md$/, '.zh.md')
  95. const meta = anchor.replace(/\.md$/, '.i18n.yaml')
  96. if (!isTranslationScopeFile(anchor) || isExcluded(anchor)) {
  97. return `${anchor}: not an in-scope documentation pair (docs/i18n/README.md)`
  98. }
  99. const missing = [anchor, zh, meta].filter(file => !existsSync(join(root, file)))
  100. if (missing.length > 0) {
  101. return `${anchor}: incomplete pair (missing ${missing.join(', ')}) — a new counterpart is whole-document translation work, not a minimal update`
  102. }
  103. const record = parseMeta(readFileSync(join(root, meta), 'utf8'))
  104. const enRecorded = record?.get(basename(anchor))
  105. const zhRecorded = record?.get(basename(zh))
  106. if (record === undefined || enRecorded === undefined || zhRecorded === undefined) {
  107. return `${meta}: malformed consistency record`
  108. }
  109. const enCurrent = readFileSync(join(root, anchor), 'utf8')
  110. const zhCurrent = readFileSync(join(root, zh), 'utf8')
  111. const enLast = blobText(enRecorded)
  112. const zhLast = blobText(zhRecorded)
  113. return {
  114. anchor,
  115. zh,
  116. meta,
  117. enDrifted: enCurrent !== enLast,
  118. zhDrifted: zhCurrent !== zhLast,
  119. enLast,
  120. zhLast,
  121. }
  122. }
  123. /** Assemble bundles for the given changed + first-occurrence span indices. */
  124. function bundlesFor(
  125. indices: number[],
  126. extraIndices: number[],
  127. confirmed: MarkdownSpan[],
  128. current: MarkdownSpan[],
  129. counterpart: MarkdownSpan[],
  130. ): BriefBundle[] {
  131. const extras = new Set(extraIndices)
  132. return [...new Set([...indices, ...extraIndices])].sort((left, right) => left - right).map((index) => {
  133. const confirmedSpan = confirmed[index]
  134. const currentSpan = current[index]
  135. const counterpartSpan = counterpart[index]
  136. if (confirmedSpan === undefined || currentSpan === undefined || counterpartSpan === undefined) {
  137. throw new Error(`gen-translation-brief: span ${index} is unmapped despite alignment`)
  138. }
  139. return {
  140. index,
  141. label: currentSpan.label,
  142. reason: extras.has(index) && confirmedSpan.text === currentSpan.text ? 'first-occurrence' as const : undefined,
  143. confirmedSourceText: confirmedSpan.text,
  144. currentSourceText: currentSpan.text,
  145. counterpartText: counterpartSpan.text,
  146. counterpartStartLine: counterpartSpan.startLine,
  147. }
  148. })
  149. }
  150. interface PlannedBrief {
  151. scope: BriefScope
  152. /** Old + new text of the changed spans, for terminology matching. */
  153. changedText: string
  154. /** Computed counterpart for a mechanical scope, for `--apply`. */
  155. mechanicalResult?: string | undefined
  156. }
  157. /** Choose the narrowest safely mapped granularity for one drifted side. */
  158. function planScope(
  159. sourceLast: string,
  160. sourceCurrent: string,
  161. counterpartCurrent: string,
  162. direction: BriefDirection,
  163. bothDrifted: boolean,
  164. ): PlannedBrief {
  165. const wholeChangedText = `${sourceLast}\n${sourceCurrent}`
  166. if (bothDrifted) {
  167. return {
  168. scope: { kind: 'document', reason: 'BOTH sides changed since the pair was last confirmed consistent, so no side is a trustworthy mapping anchor; decide which side owns each divergence.' },
  169. changedText: wholeChangedText,
  170. }
  171. }
  172. const mechanical = computeMechanicalUpdate(sourceLast, sourceCurrent, counterpartCurrent)
  173. if (mechanical !== undefined) {
  174. return { scope: { kind: 'mechanical' }, changedText: wholeChangedText, mechanicalResult: mechanical }
  175. }
  176. for (const [kind, spansOf] of [['units', markdownUnits], ['sections', sectionSpans]] as const) {
  177. const confirmed = spansOf(sourceLast)
  178. const current = spansOf(sourceCurrent)
  179. const counterpart = spansOf(counterpartCurrent)
  180. if (!spansAligned(confirmed, current) || !spansAligned(confirmed, counterpart)) continue
  181. const changed = changedSpanIndices(confirmed, current)
  182. if (changed.length === 0) continue
  183. const changedText = changed.map(index => `${confirmed[index]?.text ?? ''}\n${current[index]?.text ?? ''}`).join('\n')
  184. const rows = relevantTerminologyRows(terminology, direction, changedText)
  185. const occurrence = direction === 'en-to-zh'
  186. ? firstOccurrenceContext(sourceLast, sourceCurrent, confirmed, current, rows, new Set(changed))
  187. : { notes: [], extraSpanIndices: [] }
  188. return {
  189. scope: {
  190. kind,
  191. bundles: bundlesFor(changed, occurrence.extraSpanIndices, confirmed, current, counterpart),
  192. firstOccurrenceNotes: occurrence.notes,
  193. },
  194. changedText,
  195. }
  196. }
  197. return {
  198. scope: { kind: 'document', reason: 'Neither fine-grained units nor heading sections align one to one across the last-confirmed source, current source, and current counterpart.' },
  199. changedText: wholeChangedText,
  200. }
  201. }
  202. /** Validate a computed mechanical counterpart and write it. */
  203. function applyMechanical(counterpartPath: string, sourceCurrent: string, result: string): void {
  204. const counterpartBase = basename(counterpartPath)
  205. const sourceBase = counterpartBase.endsWith('.zh.md')
  206. ? counterpartBase.replace(/\.zh\.md$/, '.md')
  207. : counterpartBase.replace(/\.md$/, '.zh.md')
  208. const errors = translationStructureDiff(
  209. translationStructureSignature(parseTranslationMarkdown(sourceCurrent), counterpartBase),
  210. translationStructureSignature(parseTranslationMarkdown(result), sourceBase),
  211. )
  212. if (errors.length > 0) {
  213. throw new Error(`gen-translation-brief: computed mechanical update for ${counterpartPath} violates the pair structure: ${errors.join('; ')}`)
  214. }
  215. writeFileSync(join(root, counterpartPath), result)
  216. console.error(`gen-translation-brief: applied code-fence splice to ${counterpartPath}; review the diff, then record the pair.`)
  217. }
  218. /** Render (and under `--apply`, apply) the briefing for one drifted side. */
  219. function briefDirection(pair: PairState, direction: BriefDirection, apply: boolean): string {
  220. const sourceIsEnglish = direction === 'en-to-zh'
  221. const sourcePath = sourceIsEnglish ? pair.anchor : pair.zh
  222. const counterpartPath = sourceIsEnglish ? pair.zh : pair.anchor
  223. const sourceLast = sourceIsEnglish ? pair.enLast : pair.zhLast
  224. const sourceCurrent = readFileSync(join(root, sourcePath), 'utf8')
  225. const counterpartCurrent = readFileSync(join(root, counterpartPath), 'utf8')
  226. const diff = diffTexts(sourceLast, sourceCurrent)
  227. const planned = planScope(sourceLast, sourceCurrent, counterpartCurrent, direction, pair.enDrifted && pair.zhDrifted)
  228. if (apply && planned.mechanicalResult !== undefined) {
  229. applyMechanical(counterpartPath, sourceCurrent, planned.mechanicalResult)
  230. }
  231. return renderTranslationBrief({
  232. sourcePath,
  233. counterpartPath,
  234. direction,
  235. diff,
  236. scope: planned.scope,
  237. terminology: relevantTerminologyRows(terminology, direction, planned.changedText),
  238. })
  239. }
  240. const argv = process.argv.slice(2)
  241. const flags = argv.filter(argument => argument.startsWith('--'))
  242. const unknownFlags = flags.filter(flag => flag !== '--apply')
  243. if (unknownFlags.length > 0) {
  244. console.error(`gen-translation-brief: unknown flag(s): ${unknownFlags.join(', ')} (only --apply is supported)`)
  245. process.exit(2)
  246. }
  247. const applyMode = flags.includes('--apply')
  248. const requested = argv.filter(argument => !argument.startsWith('--')).map(pairAnchorOfArgument)
  249. let anchors: string[]
  250. if (requested.length > 0) {
  251. anchors = [...new Set(requested)].sort()
  252. } else {
  253. const discovered = new Set<string>()
  254. for (const match of globSync('**/*.i18n.yaml', { cwd: root, exclude: TRANSLATION_SCOPE_GLOB_EXCLUDES })) {
  255. const normalized = match.split(sep).join('/')
  256. if (isTranslationScopeFile(normalized)) discovered.add(normalized.replace(/\.i18n\.yaml$/, '.md'))
  257. }
  258. anchors = [...discovered].sort()
  259. }
  260. const briefs: string[] = []
  261. const problems: string[] = []
  262. const skipped: string[] = []
  263. for (const anchor of anchors) {
  264. const pair = loadPair(anchor)
  265. if (typeof pair === 'string') {
  266. if (requested.length > 0) problems.push(pair)
  267. continue
  268. }
  269. if (!pair.enDrifted && !pair.zhDrifted) {
  270. if (requested.length > 0) skipped.push(`${anchor}: pair is consistent with its record — nothing to brief`)
  271. continue
  272. }
  273. if (pair.enDrifted) briefs.push(briefDirection(pair, 'en-to-zh', applyMode))
  274. if (pair.zhDrifted) briefs.push(briefDirection(pair, 'zh-to-en', applyMode))
  275. }
  276. if (problems.length > 0 || skipped.length > 0) {
  277. for (const message of [...problems, ...skipped]) console.error(`gen-translation-brief: ${message}`)
  278. process.exit(2)
  279. }
  280. if (briefs.length === 0) {
  281. console.log('gen-translation-brief: every recorded pair matches its consistency record; nothing to brief.')
  282. process.exit(0)
  283. }
  284. console.log(briefs.join('\n\n---\n\n'))