translation-pairing.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. * Also the one home of the generated-region grammar and the pair-record
  6. * primitives, shared by the pairing gate and the region-injecting generators.
  7. */
  8. import { createHash } from 'node:crypto'
  9. import { basename } from 'node:path'
  10. import { fromMarkdown } from 'mdast-util-from-markdown'
  11. import { gfmFromMarkdown } from 'mdast-util-gfm'
  12. import { gfm } from 'micromark-extension-gfm'
  13. import type { Nodes } from 'mdast'
  14. /** Complete opening marker line: `<!-- BEGIN GENERATED <slug> … -->` (slug captured). */
  15. const GENERATED_REGION_BEGIN_LINE = /^<!-- BEGIN GENERATED (\S+)(?: [^>]*)? -->$/
  16. /** Complete closing marker line: `<!-- END GENERATED <slug> -->` (slug captured). */
  17. const GENERATED_REGION_END_LINE = /^<!-- END GENERATED (\S+) -->$/
  18. /** Loose marker detector: any line that LOOKS like a region marker must parse as one. */
  19. const GENERATED_REGION_MARKER_HINT = /^<!-- (?:BEGIN|END) GENERATED /
  20. /**
  21. * Extract every generated region (markers included) and the document with
  22. * those regions removed. Regions are line-delimited: a marker occupies its
  23. * whole line, must be a complete well-formed marker, and the closing slug
  24. * must match the opener. The stripped form is what "human content" means for
  25. * the region-aware pair-record guard.
  26. *
  27. * @param content - Full Markdown document text.
  28. * @returns The regions in document order and the region-free remainder.
  29. * @throws Error on an unopened END, unclosed BEGIN, nested BEGIN, malformed
  30. * marker line, or a closing slug that does not match its opener.
  31. */
  32. export function partitionGeneratedRegions(content: string): { regions: string[]; stripped: string } {
  33. const lines = content.split('\n')
  34. const regions: string[] = []
  35. const kept: string[] = []
  36. let open: { slug: string; lines: string[] } | null = null
  37. for (const line of lines) {
  38. const begin = GENERATED_REGION_BEGIN_LINE.exec(line)
  39. if (begin?.[1]) {
  40. if (open) throw new Error('generated region BEGIN marker nested inside an open region')
  41. open = { slug: begin[1], lines: [line] }
  42. continue
  43. }
  44. const end = GENERATED_REGION_END_LINE.exec(line)
  45. if (end?.[1]) {
  46. if (!open) throw new Error('generated region END marker without a BEGIN')
  47. if (end[1] !== open.slug) throw new Error(`generated region END slug '${end[1]}' does not match its BEGIN slug '${open.slug}'`)
  48. open.lines.push(line)
  49. regions.push(open.lines.join('\n'))
  50. open = null
  51. continue
  52. }
  53. if (GENERATED_REGION_MARKER_HINT.test(line)) {
  54. throw new Error(`malformed generated region marker line: ${JSON.stringify(line)}`)
  55. }
  56. if (open) open.lines.push(line)
  57. else kept.push(line)
  58. }
  59. if (open) throw new Error('generated region BEGIN marker without an END')
  60. return { regions, stripped: kept.join('\n') }
  61. }
  62. /**
  63. * Full git blob hash of file content (what `git hash-object` prints).
  64. * @param content - Exact file bytes.
  65. * @returns The 40-hex-digit SHA-1 blob hash.
  66. */
  67. export function blobHash(content: Buffer): string {
  68. const hash = createHash('sha1')
  69. hash.update(`blob ${content.byteLength}\0`)
  70. hash.update(content)
  71. return hash.digest('hex')
  72. }
  73. const PAIR_META_LINE = /^([^:#]+\.md): ([0-9a-f]{40})$/
  74. /**
  75. * Parse a `foo.i18n.yaml` consistency record into basename → recorded blob
  76. * hash, or undefined when any non-comment line deviates from the exact
  77. * `<basename>.md: <40-hex>` format or repeats a key. Consumers must
  78. * additionally require exactly the two expected basenames — a renamed key is
  79. * a malformed record, never a silently-missing entry.
  80. * @param content - Sidecar file text.
  81. * @returns The recorded map, or undefined for a malformed record.
  82. */
  83. export function parsePairMeta(content: string): Map<string, string> | undefined {
  84. const out = new Map<string, string>()
  85. for (const line of content.split('\n')) {
  86. if (line === '' || line.startsWith('#')) continue
  87. const match = PAIR_META_LINE.exec(line)
  88. if (!match?.[1] || !match[2]) return undefined
  89. if (out.has(match[1])) return undefined
  90. out.set(match[1], match[2])
  91. }
  92. return out
  93. }
  94. /**
  95. * Render a `foo.i18n.yaml` consistency record.
  96. * @param source - Repo-relative English path.
  97. * @param sourceHash - Blob hash of the English side.
  98. * @param zh - Repo-relative Chinese path.
  99. * @param zhHash - Blob hash of the Chinese side.
  100. * @returns The exact sidecar file content.
  101. */
  102. export function renderPairMeta(source: string, sourceHash: string, zh: string, zhHash: string): string {
  103. return [
  104. '# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each',
  105. '# side as of the last confirmed-consistent state. Both languages carry equal authority;',
  106. '# after editing either side, bring the other along and re-record with:',
  107. `# pnpm run verify-translation-pairing --write ${source}`,
  108. `${basename(source)}: ${sourceHash}`,
  109. `${basename(zh)}: ${zhHash}`,
  110. '',
  111. ].join('\n')
  112. }
  113. /** Validated fields of `scripts/translation-pairing.manifest.json`. */
  114. export interface TranslationPairingManifest {
  115. /** Source documents exempt from pairing because they are generated, instructional, or bilingual by construction. */
  116. excluded: string[]
  117. }
  118. const README_ARTIFACT = /(?:^|\/)readme(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
  119. const ROOT_CONTRIBUTING_ARTIFACT = /^contributing(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
  120. const ROOT_BRAND_GUIDELINES_ARTIFACT = /^brand_guidelines(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
  121. const NON_SOURCE_DIRECTORIES = new Set([
  122. 'node_modules',
  123. 'lib',
  124. '.pnpm-store',
  125. '.cache',
  126. 'coverage',
  127. '.sessions',
  128. '.storages',
  129. 'tmp',
  130. 'dist-exe',
  131. '__pycache__',
  132. '.pytest_cache',
  133. '.artifacts',
  134. 'vendor',
  135. ])
  136. /** Glob traversal exclusions corresponding to the non-source path predicate. */
  137. export const TRANSLATION_SCOPE_GLOB_EXCLUDES = [
  138. '.agents/notes/archived/**',
  139. '**/node_modules/**',
  140. '**/lib/**',
  141. '**/.pnpm-store/**',
  142. '**/.cache/**',
  143. '**/coverage/**',
  144. '**/.doc-typecheck-*/**',
  145. '**/.node-next-types-*/**',
  146. '**/.sessions/**',
  147. '**/.storages/**',
  148. '**/tmp/**',
  149. '**/dist-exe/**',
  150. '**/__pycache__/**',
  151. '**/.pytest_cache/**',
  152. 'apps/web/dist/**',
  153. '.artifacts/**',
  154. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-*/**',
  155. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/**',
  156. 'vendor/**',
  157. ]
  158. /** Whether a repository-relative path belongs to a dependency or generated tree. */
  159. function isTranslationSourceExcluded(file: string): boolean {
  160. const segments = file.split('/')
  161. return segments.some(segment => NON_SOURCE_DIRECTORIES.has(segment)
  162. || segment.startsWith('.doc-typecheck-')
  163. || segment.startsWith('.node-next-types-'))
  164. || file.startsWith('apps/web/dist/')
  165. || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-')
  166. || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/')
  167. }
  168. /** Whether one discovered Markdown or sidecar path belongs to the bilingual source corpus. */
  169. export function isTranslationScopeFile(file: string): boolean {
  170. return !file.startsWith('.agents/notes/archived/')
  171. && !isTranslationSourceExcluded(file) && (README_ARTIFACT.test(file)
  172. || ROOT_CONTRIBUTING_ARTIFACT.test(file)
  173. || ROOT_BRAND_GUIDELINES_ARTIFACT.test(file)
  174. || file.startsWith('.agents/notes/')
  175. || file.startsWith('docs/')
  176. || file.startsWith('python/'))
  177. }
  178. /** Read the manifest exclusion list or fail before enforcement starts. */
  179. function excludedField(record: Record<string, unknown>): string[] {
  180. const value = record.excluded
  181. if (!Array.isArray(value)) {
  182. throw new Error('translation-pairing.manifest.json: excluded must be an array of strings')
  183. }
  184. const entries: unknown[] = value
  185. if (!entries.every((entry): entry is string => typeof entry === 'string')) {
  186. throw new Error('translation-pairing.manifest.json: excluded must be an array of strings')
  187. }
  188. return entries
  189. }
  190. /** Parse and validate the checked-in bilingual manifest. */
  191. export function parseTranslationPairingManifest(content: string): TranslationPairingManifest {
  192. const value: unknown = JSON.parse(content)
  193. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  194. throw new Error('translation-pairing.manifest.json: expected an object')
  195. }
  196. const record = value as Record<string, unknown>
  197. const unsupported = Object.keys(record).filter(field => field !== 'excluded')
  198. if (unsupported.length > 0) {
  199. throw new Error(`translation-pairing.manifest.json: unsupported field(s): ${unsupported.join(', ')}; every in-scope document is required`)
  200. }
  201. return { excluded: excludedField(record) }
  202. }
  203. /**
  204. * Normalize one CLI pair argument to its English anchor path: any of the
  205. * pair's three files (`foo.md`, `foo.zh.md`, `foo.i18n.yaml`) or the bare
  206. * `foo` stem names the same pair, and platform separators are accepted.
  207. *
  208. * @param argument - Repo-relative path as passed on a command line.
  209. * @returns The pair's `foo.md` anchor path with `/` separators.
  210. */
  211. export function pairAnchorOfArgument(argument: string): string {
  212. const normalized = argument.split('\\').join('/').replace(/^\.\//, '')
  213. if (normalized.endsWith('.zh.md')) return `${normalized.slice(0, -'.zh.md'.length)}.md`
  214. if (normalized.endsWith('.i18n.yaml')) return `${normalized.slice(0, -'.i18n.yaml'.length)}.md`
  215. if (normalized.endsWith('.md')) return normalized
  216. return `${normalized}.md`
  217. }
  218. /** A parsed `verify-translation-pairing` invocation. */
  219. export interface TranslationPairingCliRequest {
  220. /** Content plane read by the check. Writes and corpus checks use the working tree. */
  221. input: 'worktree' | 'index'
  222. mode: 'check' | 'list' | 'write'
  223. /** `corpus` runs discovery over the whole tree; `pairs` touches only the named anchors. */
  224. scope: 'corpus' | 'pairs'
  225. /** English anchor paths, empty for corpus scope. */
  226. anchors: string[]
  227. }
  228. /**
  229. * Parse and validate `verify-translation-pairing` CLI arguments.
  230. *
  231. * Check accepts optional pair paths; `--write` requires either pair paths or
  232. * `--all` so a bulk re-record is always an explicit choice — a bare
  233. * `--write` would silently bless every drifted pair in the tree, including
  234. * ones the caller never confirmed. `--list` is corpus-only.
  235. *
  236. * @param argv - Arguments after the script name.
  237. * @returns The validated request.
  238. * @throws Error when flags or their combination are invalid.
  239. */
  240. export function parseTranslationPairingCliArgs(argv: string[]): TranslationPairingCliRequest {
  241. const flags = argv.filter(argument => argument.startsWith('--'))
  242. const anchors = [...new Set(argv.filter(argument => !argument.startsWith('--')).map(pairAnchorOfArgument))].sort()
  243. const unknown = flags.filter(flag => !['--list', '--write', '--all', '--cached'].includes(flag))
  244. if (unknown.length > 0) throw new Error(`unknown flag(s): ${unknown.join(', ')}`)
  245. const listMode = flags.includes('--list')
  246. const writeMode = flags.includes('--write')
  247. const allMode = flags.includes('--all')
  248. const cachedMode = flags.includes('--cached')
  249. if (listMode && (writeMode || allMode || cachedMode || anchors.length > 0)) {
  250. throw new Error('--list reports the whole corpus and takes no other flags or paths')
  251. }
  252. if (allMode && !writeMode) throw new Error('--all only applies to --write')
  253. if (cachedMode && writeMode) throw new Error('--cached is a read-only index check and cannot be combined with --write')
  254. if (cachedMode && anchors.length === 0) throw new Error('--cached requires the staged pair paths to check')
  255. if (writeMode) {
  256. if (anchors.length > 0 && allMode) throw new Error('--write takes either pair paths or --all, not both')
  257. if (anchors.length === 0 && !allMode) {
  258. throw new Error('--write requires the pair(s) you confirmed (any file of a pair), or --all to re-record every complete pair; recording pairs you did not review blesses unconfirmed content')
  259. }
  260. return { input: 'worktree', mode: 'write', scope: allMode ? 'corpus' : 'pairs', anchors }
  261. }
  262. if (listMode) return { input: 'worktree', mode: 'list', scope: 'corpus', anchors: [] }
  263. return {
  264. input: cachedMode ? 'index' : 'worktree',
  265. mode: 'check',
  266. scope: anchors.length > 0 ? 'pairs' : 'corpus',
  267. anchors,
  268. }
  269. }
  270. /** The structural signature compared between the two sides of a pair. */
  271. export interface TranslationStructureSignature {
  272. /** Heading depths in document order (h2 -> 2). */
  273. headings: number[]
  274. /** Fenced code blocks verbatim: info string plus content, in order. */
  275. code: string[]
  276. /** Row and column count of each table, in order. */
  277. tables: string[]
  278. /** Kind, ordered-list start, and direct item count of each list, in order. */
  279. lists: string[]
  280. /** Every link target in order; the language switcher is excluded. */
  281. links: string[]
  282. }
  283. /** Parse Markdown with the same GFM extensions used by the pairing gate. */
  284. export function parseTranslationMarkdown(content: string): Nodes {
  285. return fromMarkdown(content, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  286. }
  287. const PUBLIC_REPOSITORY_BLOB_ROOT = 'https://github.com/deepseek-ai/deepseek-harness/blob/master/'
  288. /** Return the accepted relative and public-repository links to one counterpart. */
  289. export function languageSwitcherTargets(counterpart: string): string[] {
  290. return [basename(counterpart), `${PUBLIC_REPOSITORY_BLOB_ROOT}${counterpart}`]
  291. }
  292. /** Whether the tree contains a link to any accepted target. */
  293. export function linksTo(tree: Nodes, targets: string | readonly string[]): boolean {
  294. const accepted = new Set(typeof targets === 'string' ? [targets] : targets)
  295. let found = false
  296. const visit = (node: Nodes): void => {
  297. if (node.type === 'link' && accepted.has(node.url)) found = true
  298. if ('children' in node) for (const child of node.children) visit(child)
  299. }
  300. visit(tree)
  301. return found
  302. }
  303. /** Generated English sources cannot carry a switcher without making their generator stale. */
  304. export function requiresSourceLanguageSwitcher(source: string): boolean {
  305. return ![
  306. 'docs/agent-lifecycle.md',
  307. 'docs/capability-seams.md',
  308. 'docs/config-catalog.md',
  309. 'docs/cordis-api/context.md',
  310. 'docs/cordis-api/events.md',
  311. 'docs/cordis-api/fiber.md',
  312. // Excluded from pairing, but kept here for generated-category completeness and direct spec coverage.
  313. 'docs/cordis-api/inherited.md',
  314. 'docs/cordis-api/registry.md',
  315. 'docs/cordis-api/service.md',
  316. 'docs/event-producer-consumer.md',
  317. 'docs/graph-atlas.md',
  318. 'docs/module-graph.md',
  319. 'docs/persistence-catalog.md',
  320. 'docs/tool-catalog.md',
  321. 'docs/tool-execution-pipeline.md',
  322. ].includes(source)
  323. }
  324. /** Collect the ordered structural signature, skipping accepted switcher targets. */
  325. export function translationStructureSignature(
  326. tree: Nodes,
  327. switcherTargets: string | readonly string[],
  328. ): TranslationStructureSignature {
  329. const acceptedSwitchers = new Set(
  330. typeof switcherTargets === 'string' ? [switcherTargets] : switcherTargets,
  331. )
  332. const sig: TranslationStructureSignature = { headings: [], code: [], tables: [], lists: [], links: [] }
  333. const visit = (node: Nodes): void => {
  334. switch (node.type) {
  335. case 'heading':
  336. sig.headings.push(node.depth)
  337. break
  338. case 'code':
  339. sig.code.push(`\`\`\`${node.lang ?? ''}${node.meta ? ` ${node.meta}` : ''}\n${node.value}`)
  340. break
  341. case 'table':
  342. sig.tables.push(`${node.children.length}x${node.children[0]?.children.length ?? 0}`)
  343. break
  344. case 'list':
  345. sig.lists.push(node.ordered
  346. ? `ordered:start=${node.start ?? 1}:items=${node.children.length}`
  347. : `bullet:items=${node.children.length}`)
  348. break
  349. case 'link':
  350. if (!acceptedSwitchers.has(node.url)) sig.links.push(node.url)
  351. break
  352. default:
  353. // Every other node kind is prose or a container, not part of the signature.
  354. break
  355. }
  356. if ('children' in node) for (const child of node.children) visit(child)
  357. }
  358. visit(tree)
  359. return sig
  360. }
  361. /** Render a signature element for an error message, truncated for readability. */
  362. function show(value: string | number | undefined): string {
  363. if (value === undefined) return 'nothing'
  364. const text = JSON.stringify(value)
  365. return text.length > 72 ? `${text.slice(0, 72)}…` : text
  366. }
  367. /** Return the first divergence for each structural field; empty means equal. */
  368. export function translationStructureDiff(
  369. source: TranslationStructureSignature,
  370. zh: TranslationStructureSignature,
  371. ): string[] {
  372. const out: string[] = []
  373. const fields: [string, (string | number)[], (string | number)[]][] = [
  374. ['heading (depth)', source.headings, zh.headings],
  375. ['code block', source.code, zh.code],
  376. ['table (row x column count)', source.tables, zh.tables],
  377. ['list (kind, start, item count)', source.lists, zh.lists],
  378. ['link target', source.links, zh.links],
  379. ]
  380. for (const [field, sourceValues, zhValues] of fields) {
  381. const length = Math.max(sourceValues.length, zhValues.length)
  382. for (let index = 0; index < length; index++) {
  383. if (sourceValues[index] !== zhValues[index]) {
  384. out.push(`${field} #${index + 1} diverges between the pair: ${show(sourceValues[index])} vs ${show(zhValues[index])}`)
  385. break
  386. }
  387. }
  388. }
  389. return out
  390. }