session-fixture-layout.ts 12 KB

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