session-fixture-layout.ts 9.8 KB

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