verify-translation-prompt.ts 4.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /** Verify that the committed translation prompt renders and parses as documented. */
  2. import { readFileSync } from 'node:fs'
  3. import { join, resolve } from 'node:path'
  4. import {
  5. consumeTranslationResponse,
  6. documentedTranslationPromptPlaceholders,
  7. parseTranslationResponse,
  8. renderTranslationPrompt,
  9. renderTranslationRequest,
  10. renderTranslationResponse,
  11. TRANSLATION_PROMPT_PLACEHOLDERS,
  12. type TranslationExample,
  13. } from './translation-prompt.ts'
  14. const root = resolve(import.meta.dirname, '..')
  15. function read(path: string): string {
  16. return readFileSync(join(root, path), 'utf8')
  17. }
  18. try {
  19. const mode = process.argv[2]
  20. if (mode !== undefined && mode !== '--snapshot') throw new Error(`unsupported argument ${JSON.stringify(mode)}`)
  21. const document = read('docs/i18n/translation-prompt.md')
  22. const terminology = read('docs/i18n/terminology.md')
  23. // Synthetic reviewed examples, not live documents: editing a paired document must not
  24. // churn the prompt snapshot. Each pair mirrors the other side's structure and uses
  25. // terminology-table forms.
  26. const examplePaths = [
  27. ['scripts/fixtures/translation-prompt/examples/product.md', 'scripts/fixtures/translation-prompt/examples/product.zh.md'],
  28. ['scripts/fixtures/translation-prompt/examples/rules.md', 'scripts/fixtures/translation-prompt/examples/rules.zh.md'],
  29. [
  30. 'scripts/fixtures/translation-prompt/examples/agent-note.md',
  31. 'scripts/fixtures/translation-prompt/examples/agent-note.zh.md',
  32. ],
  33. ] as const
  34. const examples: TranslationExample[] = examplePaths.map(([english, chinese]) => ({
  35. english: read(english),
  36. chinese: read(chinese),
  37. }))
  38. const sourceDocument = read('scripts/fixtures/translation-prompt/snapshot-note.md')
  39. const recordedResponse = read('scripts/fixtures/translation-prompt/response.txt')
  40. const documented = documentedTranslationPromptPlaceholders(document)
  41. if (documented.join('\n') !== TRANSLATION_PROMPT_PLACEHOLDERS.join('\n')) {
  42. throw new Error(`placeholder table must list exactly: ${TRANSLATION_PROMPT_PLACEHOLDERS.join(', ')}`)
  43. }
  44. const englishInput = { sourceLanguage: 'English' as const, sourceFilename: 'snapshot-note.md', terminology }
  45. const englishSource = renderTranslationPrompt(document, englishInput)
  46. const chineseSource = renderTranslationPrompt(document, {
  47. sourceLanguage: 'Chinese',
  48. sourceFilename: 'snapshot-note.zh.md',
  49. terminology,
  50. })
  51. if (englishSource.includes('{{') || chineseSource.includes('{{')) throw new Error('rendered prompt contains an unresolved placeholder')
  52. if (!englishSource.includes('from English to Chinese')) throw new Error('English-source render does not translate into Chinese')
  53. if (!chineseSource.includes('from Chinese to English')) throw new Error('Chinese-source render does not translate into English')
  54. const example = /```xml\n([\s\S]*?)\n```/.exec(englishSource)?.[1]
  55. if (example === undefined) throw new Error('rendered prompt has no three-section response example')
  56. parseTranslationResponse(example)
  57. const roundTrip = { translation: 'first pass\n\nwith **markdown**', review: '- 无修正', final: 'final text' }
  58. const parsed = parseTranslationResponse(renderTranslationResponse(roundTrip))
  59. if (JSON.stringify(parsed) !== JSON.stringify(roundTrip)) throw new Error('three-section response does not round-trip')
  60. const request = renderTranslationRequest(document, { ...englishInput, sourceDocument, examples })
  61. if (request.targetFilename !== 'snapshot-note.zh.md') throw new Error('English request resolves the wrong target filename')
  62. const expectedRoles = ['system', ...examples.flatMap(() => ['user', 'assistant']), 'user']
  63. if (request.messages.map(message => message.role).join('\n') !== expectedRoles.join('\n')) {
  64. throw new Error('reviewed examples are not assembled as system, example pairs, then source')
  65. }
  66. const consumed = consumeTranslationResponse(recordedResponse, englishInput)
  67. const expectedFinalPrefix = [
  68. '---',
  69. 'layout: doc',
  70. '---',
  71. '',
  72. '# 快照说明',
  73. '',
  74. '[English](snapshot-note.md) | 中文',
  75. '',
  76. ].join('\n')
  77. if (!consumed.final.startsWith(expectedFinalPrefix)) {
  78. throw new Error('recorded frontmatter response does not preserve metadata and receive the canonical target switcher')
  79. }
  80. if (mode === '--snapshot') {
  81. process.stdout.write(`${JSON.stringify({ request, response: consumed }, null, 2)}\n`)
  82. } else {
  83. console.log('verify-translation-prompt: both directions render, reviewed examples assemble, and the consumed response is target-path correct.')
  84. }
  85. } catch (error) {
  86. const message = error instanceof Error ? error.message : String(error)
  87. console.error(`verify-translation-prompt: ${message}`)
  88. process.exit(1)
  89. }