translation-pairing.ts 7.3 KB

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