translation-pairing.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 NON_SOURCE_DIRECTORIES = new Set([
  121. 'node_modules',
  122. 'lib',
  123. '.pnpm-store',
  124. '.cache',
  125. 'coverage',
  126. '.sessions',
  127. '.storages',
  128. 'tmp',
  129. 'dist-exe',
  130. '__pycache__',
  131. '.pytest_cache',
  132. '.artifacts',
  133. 'vendor',
  134. ])
  135. /** Glob traversal exclusions corresponding to the non-source path predicate. */
  136. export const TRANSLATION_SCOPE_GLOB_EXCLUDES = [
  137. '.agents/notes/archived/**',
  138. '**/node_modules/**',
  139. '**/lib/**',
  140. '**/.pnpm-store/**',
  141. '**/.cache/**',
  142. '**/coverage/**',
  143. '**/.doc-typecheck-*/**',
  144. '**/.node-next-types-*/**',
  145. '**/.sessions/**',
  146. '**/.storages/**',
  147. '**/tmp/**',
  148. '**/dist-exe/**',
  149. '**/__pycache__/**',
  150. '**/.pytest_cache/**',
  151. 'apps/web/dist/**',
  152. '.artifacts/**',
  153. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-*/**',
  154. 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/**',
  155. 'vendor/**',
  156. ]
  157. /** Whether a repository-relative path belongs to a dependency or generated tree. */
  158. function isTranslationSourceExcluded(file: string): boolean {
  159. const segments = file.split('/')
  160. return segments.some(segment => NON_SOURCE_DIRECTORIES.has(segment)
  161. || segment.startsWith('.doc-typecheck-')
  162. || segment.startsWith('.node-next-types-'))
  163. || file.startsWith('apps/web/dist/')
  164. || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-')
  165. || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/')
  166. }
  167. /** Whether one discovered Markdown or sidecar path belongs to the bilingual source corpus. */
  168. export function isTranslationScopeFile(file: string): boolean {
  169. return !file.startsWith('.agents/notes/archived/')
  170. && !isTranslationSourceExcluded(file) && (README_ARTIFACT.test(file)
  171. || ROOT_CONTRIBUTING_ARTIFACT.test(file)
  172. || file.startsWith('.agents/notes/')
  173. || file.startsWith('docs/')
  174. || file.startsWith('python/'))
  175. }
  176. /** Read the manifest exclusion list or fail before enforcement starts. */
  177. function excludedField(record: Record<string, unknown>): string[] {
  178. const value = record.excluded
  179. if (!Array.isArray(value)) {
  180. throw new Error('translation-pairing.manifest.json: excluded must be an array of strings')
  181. }
  182. const entries: unknown[] = value
  183. if (!entries.every((entry): entry is string => typeof entry === 'string')) {
  184. throw new Error('translation-pairing.manifest.json: excluded must be an array of strings')
  185. }
  186. return entries
  187. }
  188. /** Parse and validate the checked-in bilingual manifest. */
  189. export function parseTranslationPairingManifest(content: string): TranslationPairingManifest {
  190. const value: unknown = JSON.parse(content)
  191. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  192. throw new Error('translation-pairing.manifest.json: expected an object')
  193. }
  194. const record = value as Record<string, unknown>
  195. const unsupported = Object.keys(record).filter(field => field !== 'excluded')
  196. if (unsupported.length > 0) {
  197. throw new Error(`translation-pairing.manifest.json: unsupported field(s): ${unsupported.join(', ')}; every in-scope document is required`)
  198. }
  199. return { excluded: excludedField(record) }
  200. }
  201. /**
  202. * Normalize one CLI pair argument to its English anchor path: any of the
  203. * pair's three files (`foo.md`, `foo.zh.md`, `foo.i18n.yaml`) or the bare
  204. * `foo` stem names the same pair, and platform separators are accepted.
  205. *
  206. * @param argument - Repo-relative path as passed on a command line.
  207. * @returns The pair's `foo.md` anchor path with `/` separators.
  208. */
  209. export function pairAnchorOfArgument(argument: string): string {
  210. const normalized = argument.split('\\').join('/').replace(/^\.\//, '')
  211. if (normalized.endsWith('.zh.md')) return `${normalized.slice(0, -'.zh.md'.length)}.md`
  212. if (normalized.endsWith('.i18n.yaml')) return `${normalized.slice(0, -'.i18n.yaml'.length)}.md`
  213. if (normalized.endsWith('.md')) return normalized
  214. return `${normalized}.md`
  215. }
  216. /** A parsed `verify-translation-pairing` invocation. */
  217. export interface TranslationPairingCliRequest {
  218. /** Content plane read by the check. Writes and corpus checks use the working tree. */
  219. input: 'worktree' | 'index'
  220. mode: 'check' | 'list' | 'write'
  221. /** `corpus` runs discovery over the whole tree; `pairs` touches only the named anchors. */
  222. scope: 'corpus' | 'pairs'
  223. /** English anchor paths, empty for corpus scope. */
  224. anchors: string[]
  225. }
  226. /**
  227. * Parse and validate `verify-translation-pairing` CLI arguments.
  228. *
  229. * Check accepts optional pair paths; `--write` requires either pair paths or
  230. * `--all` so a bulk re-record is always an explicit choice — a bare
  231. * `--write` would silently bless every drifted pair in the tree, including
  232. * ones the caller never confirmed. `--list` is corpus-only.
  233. *
  234. * @param argv - Arguments after the script name.
  235. * @returns The validated request.
  236. * @throws Error when flags or their combination are invalid.
  237. */
  238. export function parseTranslationPairingCliArgs(argv: string[]): TranslationPairingCliRequest {
  239. const flags = argv.filter(argument => argument.startsWith('--'))
  240. const anchors = [...new Set(argv.filter(argument => !argument.startsWith('--')).map(pairAnchorOfArgument))].sort()
  241. const unknown = flags.filter(flag => !['--list', '--write', '--all', '--cached'].includes(flag))
  242. if (unknown.length > 0) throw new Error(`unknown flag(s): ${unknown.join(', ')}`)
  243. const listMode = flags.includes('--list')
  244. const writeMode = flags.includes('--write')
  245. const allMode = flags.includes('--all')
  246. const cachedMode = flags.includes('--cached')
  247. if (listMode && (writeMode || allMode || cachedMode || anchors.length > 0)) {
  248. throw new Error('--list reports the whole corpus and takes no other flags or paths')
  249. }
  250. if (allMode && !writeMode) throw new Error('--all only applies to --write')
  251. if (cachedMode && writeMode) throw new Error('--cached is a read-only index check and cannot be combined with --write')
  252. if (cachedMode && anchors.length === 0) throw new Error('--cached requires the staged pair paths to check')
  253. if (writeMode) {
  254. if (anchors.length > 0 && allMode) throw new Error('--write takes either pair paths or --all, not both')
  255. if (anchors.length === 0 && !allMode) {
  256. 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')
  257. }
  258. return { input: 'worktree', mode: 'write', scope: allMode ? 'corpus' : 'pairs', anchors }
  259. }
  260. if (listMode) return { input: 'worktree', mode: 'list', scope: 'corpus', anchors: [] }
  261. return {
  262. input: cachedMode ? 'index' : 'worktree',
  263. mode: 'check',
  264. scope: anchors.length > 0 ? 'pairs' : 'corpus',
  265. anchors,
  266. }
  267. }
  268. /** The structural signature compared between the two sides of a pair. */
  269. export interface TranslationStructureSignature {
  270. /** Heading depths in document order (h2 -> 2). */
  271. headings: number[]
  272. /** Fenced code blocks verbatim: info string plus content, in order. */
  273. code: string[]
  274. /** Row and column count of each table, in order. */
  275. tables: string[]
  276. /** Kind, ordered-list start, and direct item count of each list, in order. */
  277. lists: string[]
  278. /** Every link target in order; the language switcher is excluded. */
  279. links: string[]
  280. }
  281. /** Parse Markdown with the same GFM extensions used by the pairing gate. */
  282. export function parseTranslationMarkdown(content: string): Nodes {
  283. return fromMarkdown(content, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  284. }
  285. /** Whether the tree contains a link to exactly `target`. */
  286. export function linksTo(tree: Nodes, target: string): boolean {
  287. let found = false
  288. const visit = (node: Nodes): void => {
  289. if (node.type === 'link' && node.url === target) found = true
  290. if ('children' in node) for (const child of node.children) visit(child)
  291. }
  292. visit(tree)
  293. return found
  294. }
  295. /** Generated English sources cannot carry a switcher without making their generator stale. */
  296. export function requiresSourceLanguageSwitcher(source: string): boolean {
  297. return ![
  298. 'docs/agent-lifecycle.md',
  299. 'docs/capability-seams.md',
  300. 'docs/config-catalog.md',
  301. 'docs/cordis-api/context.md',
  302. 'docs/cordis-api/events.md',
  303. 'docs/cordis-api/fiber.md',
  304. // Excluded from pairing, but kept here for generated-category completeness and direct spec coverage.
  305. 'docs/cordis-api/inherited.md',
  306. 'docs/cordis-api/registry.md',
  307. 'docs/cordis-api/service.md',
  308. 'docs/event-producer-consumer.md',
  309. 'docs/graph-atlas.md',
  310. 'docs/module-graph.md',
  311. 'docs/persistence-catalog.md',
  312. 'docs/tool-catalog.md',
  313. 'docs/tool-execution-pipeline.md',
  314. ].includes(source)
  315. }
  316. /** Collect the ordered structural signature, skipping one switcher target. */
  317. export function translationStructureSignature(tree: Nodes, switcherTarget: string): TranslationStructureSignature {
  318. const sig: TranslationStructureSignature = { headings: [], code: [], tables: [], lists: [], links: [] }
  319. const visit = (node: Nodes): void => {
  320. switch (node.type) {
  321. case 'heading':
  322. sig.headings.push(node.depth)
  323. break
  324. case 'code':
  325. sig.code.push(`\`\`\`${node.lang ?? ''}${node.meta ? ` ${node.meta}` : ''}\n${node.value}`)
  326. break
  327. case 'table':
  328. sig.tables.push(`${node.children.length}x${node.children[0]?.children.length ?? 0}`)
  329. break
  330. case 'list':
  331. sig.lists.push(node.ordered
  332. ? `ordered:start=${node.start ?? 1}:items=${node.children.length}`
  333. : `bullet:items=${node.children.length}`)
  334. break
  335. case 'link':
  336. if (node.url !== switcherTarget) sig.links.push(node.url)
  337. break
  338. default:
  339. // Every other node kind is prose or a container, not part of the signature.
  340. break
  341. }
  342. if ('children' in node) for (const child of node.children) visit(child)
  343. }
  344. visit(tree)
  345. return sig
  346. }
  347. /** Render a signature element for an error message, truncated for readability. */
  348. function show(value: string | number | undefined): string {
  349. if (value === undefined) return 'nothing'
  350. const text = JSON.stringify(value)
  351. return text.length > 72 ? `${text.slice(0, 72)}…` : text
  352. }
  353. /** Return the first divergence for each structural field; empty means equal. */
  354. export function translationStructureDiff(
  355. source: TranslationStructureSignature,
  356. zh: TranslationStructureSignature,
  357. ): string[] {
  358. const out: string[] = []
  359. const fields: [string, (string | number)[], (string | number)[]][] = [
  360. ['heading (depth)', source.headings, zh.headings],
  361. ['code block', source.code, zh.code],
  362. ['table (row x column count)', source.tables, zh.tables],
  363. ['list (kind, start, item count)', source.lists, zh.lists],
  364. ['link target', source.links, zh.links],
  365. ]
  366. for (const [field, sourceValues, zhValues] of fields) {
  367. const length = Math.max(sourceValues.length, zhValues.length)
  368. for (let index = 0; index < length; index++) {
  369. if (sourceValues[index] !== zhValues[index]) {
  370. out.push(`${field} #${index + 1} diverges between the pair: ${show(sourceValues[index])} vs ${show(zhValues[index])}`)
  371. break
  372. }
  373. }
  374. }
  375. return out
  376. }