session-fixture-layout.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /** Canonical packed-row layout helpers for repository session fixtures. */
  2. import { deepStrictEqual } from 'node:assert'
  3. import { execFileSync } from 'node:child_process'
  4. import { existsSync, readFileSync } from 'node:fs'
  5. import { resolve } from 'node:path'
  6. import { decodeStorageRecord, packChunkRuns, type SessionEvent } from '@deepseek-ai/dsh-session'
  7. /** One repository session fixture and its canonical packed representation. */
  8. export interface SessionFixtureLayout {
  9. /** Repository-relative path with `/` separators. */
  10. path: string
  11. /** Current fixture bytes decoded as UTF-8. */
  12. source: string
  13. /** Canonical packed fixture bytes. */
  14. canonical: string
  15. }
  16. interface RecordLine {
  17. line: number
  18. text: string
  19. }
  20. function recordLines(content: string): RecordLine[] {
  21. return content.split(/\r?\n/).flatMap((text, index) => (
  22. text.trim().length === 0 ? [] : [{ line: index + 1, text }]
  23. ))
  24. }
  25. function parseRecord(line: RecordLine, label: string): unknown {
  26. try {
  27. return JSON.parse(line.text) as unknown
  28. } catch (error) {
  29. const detail = error instanceof Error ? error.message : String(error)
  30. throw new Error(`${label}:${line.line}: invalid JSON: ${detail}`, { cause: error })
  31. }
  32. }
  33. function isSessionHeader(value: unknown): boolean {
  34. return value !== null && typeof value === 'object' && (value as { type?: unknown }).type === 'session'
  35. }
  36. function decodeBody(lines: readonly RecordLine[], label: string): SessionEvent[] {
  37. return lines.flatMap(line => decodeStorageRecord(parseRecord(line, label)))
  38. }
  39. function renderFixture(headerLine: string, events: readonly SessionEvent[]): string {
  40. return [
  41. headerLine,
  42. ...packChunkRuns(events).map(record => JSON.stringify(record)),
  43. '',
  44. ].join('\n')
  45. }
  46. /**
  47. * Canonicalize one JSONL document when its first record is a session header.
  48. * The header line remains byte-identical; body records decode to logical events
  49. * and re-encode with {@link packChunkRuns}. Non-session JSONL returns undefined.
  50. *
  51. * @param content - JSONL source text.
  52. * @param label - path-like diagnostic label.
  53. * @returns Canonical text for a session fixture, otherwise undefined.
  54. */
  55. export function canonicalSessionFixture(content: string, label = '<session-fixture>'): string | undefined {
  56. const lines = recordLines(content)
  57. const header = lines[0]
  58. if (header === undefined) return undefined
  59. let headerValue: unknown
  60. try {
  61. headerValue = JSON.parse(header.text) as unknown
  62. } catch {
  63. return undefined
  64. }
  65. if (!isSessionHeader(headerValue)) return undefined
  66. const events = decodeBody(lines.slice(1), label)
  67. const canonical = renderFixture(header.text, events)
  68. const canonicalLines = recordLines(canonical)
  69. const decoded = decodeBody(canonicalLines.slice(1), label)
  70. try {
  71. deepStrictEqual(decoded, events)
  72. } catch (error) {
  73. throw new Error(`${label}: packed rewrite changed the decoded event stream`, { cause: error })
  74. }
  75. if (renderFixture(header.text, decoded) !== canonical) {
  76. throw new Error(`${label}: packed rewrite is not idempotent`)
  77. }
  78. return canonical
  79. }
  80. /**
  81. * Discover tracked and unignored untracked JSONL files through Git.
  82. *
  83. * @param root - repository root.
  84. * @returns Stable repository-relative paths.
  85. */
  86. export function discoverJsonlFiles(root: string): string[] {
  87. return execFileSync(
  88. 'git',
  89. ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '*.jsonl'],
  90. { cwd: root, encoding: 'utf8' },
  91. ).split('\0')
  92. .filter(path => path.length > 0 && existsSync(resolve(root, path)))
  93. .sort()
  94. }
  95. /**
  96. * Inspect every repository JSONL whose first record is a session header.
  97. *
  98. * @param root - repository root.
  99. * @returns Session fixtures with current and canonical text.
  100. */
  101. export function inspectSessionFixtureLayouts(root: string): SessionFixtureLayout[] {
  102. return discoverJsonlFiles(root).flatMap((path) => {
  103. const source = readFileSync(resolve(root, path), 'utf8')
  104. const canonical = canonicalSessionFixture(source, path)
  105. return canonical === undefined ? [] : [{ path, source, canonical }]
  106. })
  107. }