session-fixture-layout.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 {
  7. decodeSeqRanges,
  8. decodeStorageRecord,
  9. packChunkRuns,
  10. SessionLogOffset,
  11. type SessionEvent,
  12. } from '@deepseek-ai/dsh-session'
  13. import type { SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
  14. import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
  15. /** Physical persistence artifacts validated by the WebWorker runtime fixture spec. */
  16. const WEBWORKER_PHYSICAL_SESSION_FIXTURE_ROOT =
  17. 'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/'
  18. /** Installed-runtime snapshots that preserve the JSONL writer's physical encoding. */
  19. const PYTHON_RUNTIME_PHYSICAL_SESSION_FIXTURE_ROOT =
  20. 'scripts/snapshots/python-sdk-single-exe/'
  21. /** One repository session fixture and its canonical projected representation. */
  22. export interface SessionFixtureLayout {
  23. /** Repository-relative path with `/` separators. */
  24. path: string
  25. /** Current fixture bytes decoded as UTF-8. */
  26. source: string
  27. /** Canonical projected fixture bytes. */
  28. canonical: string
  29. }
  30. /**
  31. * Whether a repository JSONL preserves physical persistence encoding rather
  32. * than the logical event projection owned by this script.
  33. * @param path - Repository-relative path with `/` separators.
  34. * @returns True for physical WebWorker and installed-runtime session logs.
  35. */
  36. export function isPhysicalSessionFixture(path: string): boolean {
  37. if (path.startsWith(WEBWORKER_PHYSICAL_SESSION_FIXTURE_ROOT)) {
  38. return /\/session(?:\.v[1-9]\d*)?\.jsonl$/.test(path)
  39. }
  40. return path.startsWith(PYTHON_RUNTIME_PHYSICAL_SESSION_FIXTURE_ROOT)
  41. && /\/session(?:\.[1-9]\d*)?(?:\.v[1-9]\d*)?\.jsonl$/.test(path)
  42. }
  43. function isSessionHeader(value: unknown): boolean {
  44. return value !== null && typeof value === 'object' && (value as { type?: unknown }).type === 'session'
  45. }
  46. function validationHeader(value: unknown): unknown {
  47. if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
  48. const header = { ...value as Record<string, unknown> }
  49. if (header.version === 0 && !Object.hasOwn(header, 'delegationDepth')) header.delegationDepth = 0
  50. if (typeof header.cwd === 'string' && /^\{\{cwd\}\}(?:\/|$)/.test(header.cwd)) {
  51. header.cwd = header.cwd.replace('{{cwd}}', '/dsh-snapshot-cwd')
  52. }
  53. return header
  54. }
  55. function renderFixture(headerLine: string, events: readonly SessionEvent[]): string {
  56. return [
  57. headerLine,
  58. ...packChunkRuns(events).map((stored) => {
  59. const record = { ...stored } as unknown as Record<string, unknown>
  60. delete record.seq
  61. delete record.time
  62. delete record.seq0
  63. delete record.time0
  64. return JSON.stringify(record)
  65. }),
  66. '',
  67. ].join('\n')
  68. }
  69. function projectedRowCardinality(record: Readonly<Record<string, unknown>>): number {
  70. const data = record.data
  71. if (data === null || typeof data !== 'object' || Array.isArray(data)) return 1
  72. const key = record.type === 'tool-call-chunks' ? 'args' : 'texts'
  73. const values = (data as Record<string, unknown>)[key]
  74. return Array.isArray(values) && values.length > 0 ? values.length : 1
  75. }
  76. function parseFixtureObjectLine(line: string, lineNumber: number): Record<string, unknown> {
  77. let value: unknown
  78. try {
  79. value = JSON.parse(line) as unknown
  80. } catch (error) {
  81. throw new Error(`session snapshot line ${lineNumber} contains invalid JSON`, { cause: error })
  82. }
  83. if (value === null || typeof value !== 'object' || Array.isArray(value)) {
  84. throw new Error(`session snapshot line ${lineNumber} must be a JSON object`)
  85. }
  86. return value as Record<string, unknown>
  87. }
  88. function parseFixtureRows(content: string, headerValue: unknown): SessionEvent[] {
  89. const rows: Record<string, unknown>[] = []
  90. const rowLines: number[] = []
  91. let nextSeq: SessionLogOffsetType = SessionLogOffset(0)
  92. let headerSkipped = false
  93. for (const [index, line] of content.split(/\r?\n/).entries()) {
  94. if (line.trim().length === 0) continue
  95. if (!headerSkipped) {
  96. headerSkipped = true
  97. continue
  98. }
  99. const record = parseFixtureObjectLine(line, index + 1)
  100. const packed = record.type === 'text-chunks'
  101. || record.type === 'reasoning-chunks'
  102. || record.type === 'tool-call-chunks'
  103. const seqKey = packed ? 'seq0' : 'seq'
  104. const timeKey = packed ? 'time0' : 'time'
  105. if (!Object.hasOwn(record, seqKey)) record[seqKey] = nextSeq
  106. if (!Object.hasOwn(record, timeKey)) record[timeKey] = 0
  107. rows.push(record)
  108. rowLines.push(index + 1)
  109. nextSeq = SessionLogOffset(nextSeq + projectedRowCardinality(record))
  110. }
  111. // Versionless protocol fixtures are outside the released format catalog;
  112. // they exercise only the current storage-row projection.
  113. if (headerValue === null || typeof headerValue !== 'object' || Array.isArray(headerValue)
  114. || !Object.hasOwn(headerValue, 'version')) {
  115. return rows.flatMap((source, index) => {
  116. const record = { ...source }
  117. try {
  118. if (Object.hasOwn(record, 'sourceEventSeqs')) {
  119. record.sourceEventSeqs = decodeSeqRanges(record.sourceEventSeqs)
  120. }
  121. return decodeStorageRecord(record)
  122. } catch (error) {
  123. const detail = error instanceof Error ? error.message : String(error)
  124. throw new Error(`session snapshot line ${rowLines[index] ?? 1}: ${detail}`, { cause: error })
  125. }
  126. })
  127. }
  128. try {
  129. return [
  130. ...sessionFormatCatalog.decodeArtifact(validationHeader(headerValue), rows).events,
  131. ] as unknown as SessionEvent[]
  132. } catch (error) {
  133. const detail = error instanceof Error ? error.message : String(error)
  134. const storedRow = /\brow (\d+)\b/.exec(detail)
  135. const line = storedRow === null ? 1 : rowLines[Number(storedRow[1])] ?? 1
  136. throw new Error(`session snapshot line ${line}: ${detail}`, { cause: error })
  137. }
  138. }
  139. function withoutEnvelope(events: readonly SessionEvent[]): Array<Omit<SessionEvent, 'seq' | 'time'>> {
  140. return events.map((event) => {
  141. const { seq: _seq, time: _time, ...projected } = event
  142. return projected
  143. })
  144. }
  145. /**
  146. * Canonicalize one JSONL document when its first record is a session header.
  147. * The header line remains byte-identical; body records decode to logical events,
  148. * re-encode with {@link packChunkRuns}, and omit storage sequence/time envelopes.
  149. * Non-session JSONL returns undefined.
  150. *
  151. * @param content - JSONL source text.
  152. * @param label - path-like diagnostic label.
  153. * @returns Canonical text for a session fixture, otherwise undefined.
  154. */
  155. export function canonicalSessionFixture(content: string, label = '<session-fixture>'): string | undefined {
  156. const headerLine = content.split(/\r?\n/).find(line => line.trim().length > 0)
  157. if (headerLine === undefined) return undefined
  158. let headerValue: unknown
  159. try {
  160. headerValue = JSON.parse(headerLine) as unknown
  161. } catch {
  162. return undefined
  163. }
  164. if (!isSessionHeader(headerValue)) return undefined
  165. let events
  166. try {
  167. events = parseFixtureRows(content, headerValue)
  168. } catch (error) {
  169. const detail = error instanceof Error ? error.message : String(error)
  170. throw new Error(`${label}: ${detail}`, { cause: error })
  171. }
  172. const canonical = renderFixture(headerLine, events)
  173. const decoded = parseFixtureRows(canonical, headerValue)
  174. try {
  175. deepStrictEqual(withoutEnvelope(decoded), withoutEnvelope(events))
  176. } catch (error) {
  177. throw new Error(`${label}: packed snapshot rewrite changed the event payload stream`, { cause: error })
  178. }
  179. if (renderFixture(headerLine, decoded) !== canonical) {
  180. throw new Error(`${label}: packed rewrite is not idempotent`)
  181. }
  182. return canonical
  183. }
  184. /**
  185. * Discover tracked and unignored untracked JSONL files through Git.
  186. *
  187. * @param root - repository root.
  188. * @returns Stable repository-relative paths.
  189. */
  190. function discoverJsonlFiles(root: string): string[] {
  191. return execFileSync(
  192. 'git',
  193. ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '*.jsonl'],
  194. { cwd: root, encoding: 'utf8' },
  195. ).split('\0')
  196. .filter(path => path.length > 0 && existsSync(resolve(root, path)))
  197. .sort()
  198. }
  199. /**
  200. * Inspect every repository JSONL whose first record is a session header.
  201. *
  202. * @param root - repository root.
  203. * @returns Session fixtures with current and canonical text.
  204. */
  205. export function inspectSessionFixtureLayouts(root: string): SessionFixtureLayout[] {
  206. return discoverJsonlFiles(root).flatMap((path) => {
  207. if (isPhysicalSessionFixture(path)) return []
  208. const source = readFileSync(resolve(root, path), 'utf8')
  209. const canonical = canonicalSessionFixture(source, path)
  210. return canonical === undefined ? [] : [{ path, source, canonical }]
  211. })
  212. }