session-fixture-layout.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /** Canonical packed-row and envelope projection 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 { packChunkRuns, type SessionEvent } from '@deepseek-ai/dsh-session'
  7. import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  8. /** Physical persistence artifacts validated by the WebWorker runtime fixture spec. */
  9. const PHYSICAL_SESSION_FIXTURE_ROOT =
  10. 'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/'
  11. /** One repository session fixture and its canonical projected representation. */
  12. export interface SessionFixtureLayout {
  13. /** Repository-relative path with `/` separators. */
  14. path: string
  15. /** Current fixture bytes decoded as UTF-8. */
  16. source: string
  17. /** Canonical projected fixture bytes. */
  18. canonical: string
  19. }
  20. /**
  21. * Whether a repository JSONL is a production-layout persistence artifact rather
  22. * than an envelope-free replay snapshot owned by this script.
  23. * @param path - Repository-relative path with `/` separators.
  24. * @returns True only for Session logs under the WebWorker VFS example root.
  25. */
  26. export function isPhysicalSessionFixture(path: string): boolean {
  27. return path.startsWith(PHYSICAL_SESSION_FIXTURE_ROOT) && path.endsWith('/session.jsonl')
  28. }
  29. function isSessionHeader(value: unknown): boolean {
  30. return value !== null && typeof value === 'object' && (value as { type?: unknown }).type === 'session'
  31. }
  32. function renderFixture(headerLine: string, events: readonly SessionEvent[]): string {
  33. return [
  34. headerLine,
  35. ...packChunkRuns(events).map((stored) => {
  36. const record = stored as unknown as Record<string, unknown>
  37. delete record.seq
  38. delete record.time
  39. delete record.seq0
  40. delete record.time0
  41. return JSON.stringify(record)
  42. }),
  43. '',
  44. ].join('\n')
  45. }
  46. function withoutEnvelope(events: readonly SessionEvent[]): Array<Omit<SessionEvent, 'seq' | 'time'>> {
  47. return events.map((event) => {
  48. const { seq: _seq, time: _time, ...projected } = event
  49. return projected
  50. })
  51. }
  52. /**
  53. * Canonicalize one JSONL document when its first record is a session header.
  54. * The header line remains byte-identical; body records decode to logical events,
  55. * re-encode with {@link packChunkRuns}, and omit storage sequence/time envelopes.
  56. * Non-session JSONL returns undefined.
  57. *
  58. * @param content - JSONL source text.
  59. * @param label - path-like diagnostic label.
  60. * @returns Canonical text for a session fixture, otherwise undefined.
  61. */
  62. export function canonicalSessionFixture(content: string, label = '<session-fixture>'): string | undefined {
  63. const headerLine = content.split(/\r?\n/).find(line => line.trim().length > 0)
  64. if (headerLine === undefined) return undefined
  65. let headerValue: unknown
  66. try {
  67. headerValue = JSON.parse(headerLine) as unknown
  68. } catch {
  69. return undefined
  70. }
  71. if (!isSessionHeader(headerValue)) return undefined
  72. let events
  73. try {
  74. events = parseSessionLog(content)
  75. } catch (error) {
  76. const detail = error instanceof Error ? error.message : String(error)
  77. throw new Error(`${label}: ${detail}`, { cause: error })
  78. }
  79. const canonical = renderFixture(headerLine, events)
  80. const decoded = parseSessionLog(canonical)
  81. try {
  82. deepStrictEqual(withoutEnvelope(decoded), withoutEnvelope(events))
  83. } catch (error) {
  84. throw new Error(`${label}: packed snapshot rewrite changed the event payload stream`, { cause: error })
  85. }
  86. if (renderFixture(headerLine, decoded) !== canonical) {
  87. throw new Error(`${label}: packed rewrite is not idempotent`)
  88. }
  89. return canonical
  90. }
  91. /**
  92. * Discover tracked and unignored untracked JSONL files through Git.
  93. *
  94. * @param root - repository root.
  95. * @returns Stable repository-relative paths.
  96. */
  97. function discoverJsonlFiles(root: string): string[] {
  98. return execFileSync(
  99. 'git',
  100. ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '*.jsonl'],
  101. { cwd: root, encoding: 'utf8' },
  102. ).split('\0')
  103. .filter(path => path.length > 0 && existsSync(resolve(root, path)))
  104. .sort()
  105. }
  106. /**
  107. * Inspect every repository JSONL whose first record is a session header.
  108. *
  109. * @param root - repository root.
  110. * @returns Session fixtures with current and canonical text.
  111. */
  112. export function inspectSessionFixtureLayouts(root: string): SessionFixtureLayout[] {
  113. return discoverJsonlFiles(root).flatMap((path) => {
  114. if (isPhysicalSessionFixture(path)) return []
  115. const source = readFileSync(resolve(root, path), 'utf8')
  116. const canonical = canonicalSessionFixture(source, path)
  117. return canonical === undefined ? [] : [{ path, source, canonical }]
  118. })
  119. }