fix(session): snapshot seed + appended data at the boundary (review #31)

The source-level JSON-serializability invariant was only a preflight: the
Session constructor copied the seed array but shared every event/data
object with the caller, and append() stored the caller's `data` reference
verbatim. A post-create/post-append mutation could rewrite the durable
log or reintroduce a non-JSON-serializable value AFTER validation, so
session.events could diverge from what was validated / what a backend
can persist.

- ctor deep-clones each seed event after validation (not just the array).
- append() stores structuredClone(data) (serializability already checked,
  so the clone is safe); the returned event carries the same snapshot.

Regression tests: mutating the original seed / the passed append object
after the call leaves session.events unchanged. Adapted the dev-freeze
invariants test to assert on the logged clone (append no longer freezes
the caller's input). Documented isJsonValue's exact scope (own enumerable
string keys, matching JSON.stringify) and synced the README create()
signature with meta.createdAt.
This commit is contained in:
Tianyi Cui
2026-06-15 23:33:00 +08:00
parent 611791ba7f
commit 5299e43bed
5 changed files with 68 additions and 7 deletions

View File

@@ -241,12 +241,15 @@ describe('dev-freeze', () => {
// mutable. deepFreeze must descend into the already-frozen object and
// freeze the descendant, not short-circuit on the frozen container —
// otherwise dev-mode misses exactly the history mutation ADR 0012 catches.
// `append` snapshots `data`, so the freeze applies to the LOGGED clone, not
// the caller's input — read the event back and assert on its data.
const innerContent: { type: 'text'; text: string }[] = [{ type: 'text', text: 'inner' }]
const block = Object.freeze({ type: 'tool-result' as const, toolCallId: CallId('c1'), content: innerContent, isError: false })
session.append('user/message', { content: [block], source: { kind: 'user' } })
expect(Object.isFrozen(block.content)).toBe(true)
expect(Object.isFrozen(block.content[0])).toBe(true)
expect(() => { block.content.push({ type: 'text', text: 'mutation' }) }).toThrow()
const event = session.append('user/message', { content: [block], source: { kind: 'user' } })
const logged = event.data.content[0] as { content: { type: 'text'; text: string }[] }
expect(Object.isFrozen(logged.content)).toBe(true)
expect(Object.isFrozen(logged.content[0])).toBe(true)
expect(() => { logged.content.push({ type: 'text', text: 'mutation' }) }).toThrow()
})
it('terminates on a cyclic event datum (WeakSet guard)', async () => {