translation-pairing.ts 16 KB

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