translation-pairing.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /**
  2. * Pure parsing and structural helpers for the bilingual-document pairing
  3. * gate. Kept separate from the CLI so corpus discovery and signature behavior
  4. * can be regression-tested without reading or mutating the repository tree.
  5. */
  6. import { fromMarkdown } from 'mdast-util-from-markdown'
  7. import { gfmFromMarkdown } from 'mdast-util-gfm'
  8. import { gfm } from 'micromark-extension-gfm'
  9. import type { Nodes } from 'mdast'
  10. /** Validated shape of `scripts/translation-pairing.manifest.json`. */
  11. export interface TranslationPairingManifest {
  12. /** Source documents exempt from pairing because they are generated, instructional, or bilingual by construction. */
  13. excluded: string[]
  14. }
  15. const README_ARTIFACT = /(?:^|\/)readme(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
  16. const NON_SOURCE_DIRECTORIES = new Set([
  17. 'node_modules',
  18. 'lib',
  19. '.pnpm-store',
  20. '.cache',
  21. 'coverage',
  22. '.sessions',
  23. '.storages',
  24. 'tmp',
  25. 'dist-exe',
  26. '__pycache__',
  27. '.pytest_cache',
  28. '.artifacts',
  29. 'vendor',
  30. ])
  31. /** Glob traversal exclusions corresponding to the non-source path predicate. */
  32. export const TRANSLATION_SCOPE_GLOB_EXCLUDES = [
  33. '.agents/notes/archived/**',
  34. '**/node_modules/**',
  35. '**/lib/**',
  36. '**/.pnpm-store/**',
  37. '**/.cache/**',
  38. '**/coverage/**',
  39. '**/.doc-typecheck-*/**',
  40. '**/.node-next-types-*/**',
  41. '**/.sessions/**',
  42. '**/.storages/**',
  43. '**/tmp/**',
  44. '**/dist-exe/**',
  45. '**/__pycache__/**',
  46. '**/.pytest_cache/**',
  47. 'apps/web/dist/**',
  48. '.artifacts/**',
  49. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-*/**',
  50. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/**',
  51. 'vendor/**',
  52. ]
  53. /** Whether a repository-relative path belongs to a dependency or generated tree. */
  54. function isTranslationSourceExcluded(file: string): boolean {
  55. const segments = file.split('/')
  56. return segments.some(segment => NON_SOURCE_DIRECTORIES.has(segment)
  57. || segment.startsWith('.doc-typecheck-')
  58. || segment.startsWith('.node-next-types-'))
  59. || file.startsWith('apps/web/dist/')
  60. || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-')
  61. || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/')
  62. }
  63. /** Whether one discovered Markdown or sidecar path belongs to the bilingual source corpus. */
  64. export function isTranslationScopeFile(file: string): boolean {
  65. return !file.startsWith('.agents/notes/archived/')
  66. && !isTranslationSourceExcluded(file) && (README_ARTIFACT.test(file)
  67. || file.startsWith('.agents/notes/')
  68. || file.startsWith('docs/')
  69. || file.startsWith('python/'))
  70. }
  71. /** Read the manifest exclusion list or fail before enforcement starts. */
  72. function excludedField(record: Record<string, unknown>): string[] {
  73. const value = record.excluded
  74. if (!Array.isArray(value)) {
  75. throw new Error('translation-pairing.manifest.json: excluded must be an array of strings')
  76. }
  77. const entries: unknown[] = value
  78. if (!entries.every((entry): entry is string => typeof entry === 'string')) {
  79. throw new Error('translation-pairing.manifest.json: excluded must be an array of strings')
  80. }
  81. return entries
  82. }
  83. /** Parse and validate the checked-in bilingual manifest. */
  84. export function parseTranslationPairingManifest(content: string): TranslationPairingManifest {
  85. const value: unknown = JSON.parse(content)
  86. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  87. throw new Error('translation-pairing.manifest.json: expected an object')
  88. }
  89. const record = value as Record<string, unknown>
  90. const unsupported = Object.keys(record).filter(field => field !== 'excluded')
  91. if (unsupported.length > 0) {
  92. throw new Error(`translation-pairing.manifest.json: unsupported field(s): ${unsupported.join(', ')}; every in-scope document is required`)
  93. }
  94. return { excluded: excludedField(record) }
  95. }
  96. /** The structural surface compared between the two sides of a pair. */
  97. export interface TranslationStructureSignature {
  98. /** Heading depths in document order (h2 -> 2). */
  99. headings: number[]
  100. /** Fenced code blocks verbatim: info string plus content, in order. */
  101. code: string[]
  102. /** Row and column count of each table, in order. */
  103. tables: string[]
  104. /** Kind, ordered-list start, and direct item count of each list, in order. */
  105. lists: string[]
  106. /** Every link target in order; the language switcher is excluded. */
  107. links: string[]
  108. }
  109. /** Parse Markdown with the same GFM extensions used by the pairing gate. */
  110. export function parseTranslationMarkdown(content: string): Nodes {
  111. return fromMarkdown(content, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  112. }
  113. /** Whether the tree contains a link to exactly `target`. */
  114. export function linksTo(tree: Nodes, target: string): boolean {
  115. let found = false
  116. const visit = (node: Nodes): void => {
  117. if (node.type === 'link' && node.url === target) found = true
  118. if ('children' in node) for (const child of node.children) visit(child)
  119. }
  120. visit(tree)
  121. return found
  122. }
  123. /** Collect the ordered structural signature, skipping one switcher target. */
  124. export function translationStructureSignature(tree: Nodes, switcherTarget: string): TranslationStructureSignature {
  125. const sig: TranslationStructureSignature = { headings: [], code: [], tables: [], lists: [], links: [] }
  126. const visit = (node: Nodes): void => {
  127. switch (node.type) {
  128. case 'heading':
  129. sig.headings.push(node.depth)
  130. break
  131. case 'code':
  132. sig.code.push(`\`\`\`${node.lang ?? ''}${node.meta ? ` ${node.meta}` : ''}\n${node.value}`)
  133. break
  134. case 'table':
  135. sig.tables.push(`${node.children.length}x${node.children[0]?.children.length ?? 0}`)
  136. break
  137. case 'list':
  138. sig.lists.push(node.ordered
  139. ? `ordered:start=${node.start ?? 1}:items=${node.children.length}`
  140. : `bullet:items=${node.children.length}`)
  141. break
  142. case 'link':
  143. if (node.url !== switcherTarget) sig.links.push(node.url)
  144. break
  145. default:
  146. // Every other node kind is prose or a container, not part of the signature.
  147. break
  148. }
  149. if ('children' in node) for (const child of node.children) visit(child)
  150. }
  151. visit(tree)
  152. return sig
  153. }
  154. /** Render a signature element for an error message, truncated for readability. */
  155. function show(value: string | number | undefined): string {
  156. if (value === undefined) return 'nothing'
  157. const text = JSON.stringify(value)
  158. return text.length > 72 ? `${text.slice(0, 72)}…` : text
  159. }
  160. /** Return the first divergence for each structural field; empty means equal. */
  161. export function translationStructureDiff(
  162. source: TranslationStructureSignature,
  163. zh: TranslationStructureSignature,
  164. ): string[] {
  165. const out: string[] = []
  166. const fields: [string, (string | number)[], (string | number)[]][] = [
  167. ['heading (depth)', source.headings, zh.headings],
  168. ['code block', source.code, zh.code],
  169. ['table (row x column count)', source.tables, zh.tables],
  170. ['list (kind, start, item count)', source.lists, zh.lists],
  171. ['link target', source.links, zh.links],
  172. ]
  173. for (const [field, sourceValues, zhValues] of fields) {
  174. const length = Math.max(sourceValues.length, zhValues.length)
  175. for (let index = 0; index < length; index++) {
  176. if (sourceValues[index] !== zhValues[index]) {
  177. out.push(`${field} #${index + 1} diverges between the pair: ${show(sourceValues[index])} vs ${show(zhValues[index])}`)
  178. break
  179. }
  180. }
  181. }
  182. return out
  183. }