archived-agent-notes.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /** Pure archive-format, triplet, and immutable-manifest helpers. */
  2. import { createHash } from 'node:crypto'
  3. import { basename } from 'node:path'
  4. import { AGENT_NOTE_CLASSES } from './agent-note-tree.ts'
  5. /** Versioned shape of the frozen-content manifest. */
  6. export interface ArchiveManifest {
  7. version: 1
  8. files: Readonly<Record<string, string>>
  9. }
  10. /** Hash one archived artifact independently of the repository's Git object format. */
  11. function archiveContentHash(content: Buffer): string {
  12. return `sha256:${createHash('sha256').update(content).digest('hex')}`
  13. }
  14. /** Compute the SHA-1 Git blob id used by bilingual consistency sidecars. */
  15. export function gitBlobHash(content: Buffer): string {
  16. const hash = createHash('sha1')
  17. hash.update(`blob ${content.byteLength}\0`)
  18. hash.update(content)
  19. return hash.digest('hex')
  20. }
  21. function isRecord(value: unknown): value is Record<string, unknown> {
  22. return typeof value === 'object' && value !== null && !Array.isArray(value)
  23. }
  24. /** Parse the archive manifest and reject fields or hashes outside its closed schema. */
  25. export function parseArchiveManifest(content: string): ArchiveManifest {
  26. const value: unknown = JSON.parse(content)
  27. if (!isRecord(value)) throw new Error('expected a JSON object')
  28. const fields = Object.keys(value).sort()
  29. if (fields.join(',') !== 'files,version') throw new Error('expected exactly the fields `version` and `files`')
  30. if (value.version !== 1) throw new Error('unsupported manifest version (expected 1)')
  31. if (!isRecord(value.files)) throw new Error('`files` must be an object')
  32. const files: Record<string, string> = {}
  33. for (const [path, hash] of Object.entries(value.files)) {
  34. if (typeof hash !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(hash)) {
  35. throw new Error(`invalid content hash for ${path}`)
  36. }
  37. files[path] = hash
  38. }
  39. return { version: 1, files }
  40. }
  41. /** Render the archive manifest with deterministic path ordering. */
  42. export function renderArchiveManifest(files: Readonly<Record<string, string>>): string {
  43. return `${JSON.stringify({
  44. version: 1,
  45. files: Object.fromEntries(Object.entries(files).sort(([left], [right]) => left.localeCompare(right))),
  46. }, null, 2)}\n`
  47. }
  48. function validDate(value: string): boolean {
  49. const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
  50. if (match === null) return false
  51. const year = Number(match[1])
  52. const month = Number(match[2])
  53. const day = Number(match[3])
  54. const date = new Date(Date.UTC(year, month - 1, day))
  55. return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
  56. }
  57. interface Triplet {
  58. source?: Buffer
  59. zh?: Buffer
  60. meta?: Buffer
  61. }
  62. function pairMeta(content: string): Map<string, string> | undefined {
  63. const entries = new Map<string, string>()
  64. for (const line of content.split('\n')) {
  65. if (line === '' || line.startsWith('#')) continue
  66. const match = /^([^:#]+\.md): ([0-9a-f]{40})$/.exec(line)
  67. if (match?.[1] === undefined || match[2] === undefined) return undefined
  68. entries.set(match[1], match[2])
  69. }
  70. return entries
  71. }
  72. function validateHeader(path: string, content: Buffer, sourceBase: string, chinese: boolean): string[] {
  73. const errors: string[] = []
  74. const lines = content.toString('utf8').split('\n')
  75. if (!/^# Agent Note: \S/.test(lines[0] ?? '')) errors.push(`${path}: line 1 must be \`# Agent Note: <title>\``)
  76. if (lines[1] !== '') errors.push(`${path}: line 2 must be blank`)
  77. if (lines[2] !== 'Status: implemented') errors.push(`${path}: line 3 must be \`Status: implemented\``)
  78. const archived = /^Archived: (\d{4}-\d{2}-\d{2})$/.exec(lines[3] ?? '')?.[1]
  79. if (archived === undefined || !validDate(archived)) {
  80. errors.push(`${path}: line 4 must be \`Archived: YYYY-MM-DD\` with a valid date`)
  81. } else if (archived < sourceBase.slice(0, 10)) {
  82. errors.push(`${path}: archive date ${archived} predates the note filename`)
  83. }
  84. if (lines[4] !== '') errors.push(`${path}: line 5 must be blank`)
  85. const switcher = chinese
  86. ? `[English](${sourceBase}.md) | 中文`
  87. : `English | [中文](${sourceBase}.zh.md)`
  88. if (lines[5] !== switcher) errors.push(`${path}: line 6 must be ${JSON.stringify(switcher)}`)
  89. return errors
  90. }
  91. /** Validate the closed kind tree, implemented/archive headers, and complete bilingual triplets. */
  92. export function validateArchiveArtifacts(artifacts: ReadonlyMap<string, Buffer>): string[] {
  93. const errors: string[] = []
  94. const triplets = new Map<string, Triplet>()
  95. for (const [path, content] of artifacts) {
  96. const match = /^([^/]+)\/(\d{4}-\d{2}-\d{2}-.+?)(\.zh\.md|\.i18n\.yaml|\.md)$/.exec(path)
  97. if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) {
  98. errors.push(`${path}: expected {kind}/yyyy-mm-dd-topic.{md,zh.md,i18n.yaml}`)
  99. continue
  100. }
  101. if (!(AGENT_NOTE_CLASSES as readonly string[]).includes(match[1])) {
  102. errors.push(`${path}: unknown Agent Note kind ${JSON.stringify(match[1])}`)
  103. continue
  104. }
  105. const key = `${match[1]}/${match[2]}`
  106. const triplet = triplets.get(key) ?? {}
  107. if (match[3] === '.md') triplet.source = content
  108. else if (match[3] === '.zh.md') triplet.zh = content
  109. else triplet.meta = content
  110. triplets.set(key, triplet)
  111. }
  112. for (const [key, triplet] of [...triplets].sort(([left], [right]) => left.localeCompare(right))) {
  113. const sourcePath = `${key}.md`
  114. const zhPath = `${key}.zh.md`
  115. const metaPath = `${key}.i18n.yaml`
  116. const { source, zh, meta } = triplet
  117. const missing = [
  118. source === undefined ? sourcePath : undefined,
  119. zh === undefined ? zhPath : undefined,
  120. meta === undefined ? metaPath : undefined,
  121. ].filter((path): path is string => path !== undefined)
  122. if (source === undefined || zh === undefined || meta === undefined) {
  123. errors.push(`${key}: incomplete archived triplet; missing ${missing.join(', ')}`)
  124. continue
  125. }
  126. const sourceBase = basename(key)
  127. errors.push(...validateHeader(sourcePath, source, sourceBase, false))
  128. errors.push(...validateHeader(zhPath, zh, sourceBase, true))
  129. const sourceDate = /^Archived: (\d{4}-\d{2}-\d{2})$/m.exec(source.toString('utf8'))?.[1]
  130. const zhDate = /^Archived: (\d{4}-\d{2}-\d{2})$/m.exec(zh.toString('utf8'))?.[1]
  131. if (sourceDate !== undefined && zhDate !== undefined && sourceDate !== zhDate) {
  132. errors.push(`${key}: English and Chinese archive dates differ (${sourceDate} vs ${zhDate})`)
  133. }
  134. const pair = pairMeta(meta.toString('utf8'))
  135. if (pair === undefined || pair.size !== 2
  136. || pair.get(`${sourceBase}.md`) !== gitBlobHash(source)
  137. || pair.get(`${sourceBase}.zh.md`) !== gitBlobHash(zh)) {
  138. errors.push(`${metaPath}: consistency record must contain the current Git blob hashes of both archived sides`)
  139. }
  140. }
  141. return errors
  142. }
  143. /** Preserve every sealed path/hash and append hashes for newly archived artifacts. */
  144. export function extendArchiveManifest(
  145. existing: ArchiveManifest,
  146. artifacts: ReadonlyMap<string, Buffer>,
  147. ): { files: Record<string, string>; added: string[]; errors: string[] } {
  148. const errors: string[] = []
  149. const files: Record<string, string> = { ...existing.files }
  150. for (const [path, expected] of Object.entries(existing.files)) {
  151. const content = artifacts.get(path)
  152. if (content === undefined) errors.push(`${path}: sealed artifact is missing`)
  153. else if (archiveContentHash(content) !== expected) errors.push(`${path}: sealed content hash changed`)
  154. }
  155. const added: string[] = []
  156. for (const [path, content] of [...artifacts].sort(([left], [right]) => left.localeCompare(right))) {
  157. if (files[path] !== undefined) continue
  158. files[path] = archiveContentHash(content)
  159. added.push(path)
  160. }
  161. return { files, added, errors }
  162. }