Heuristic:1jehuang Jcode NDJSON Framing
| Knowledge Sources | |
|---|---|
| Domains | Networking, API_Design |
| Last Updated | 2026-10-18 00:00 GMT |
Overview
NDJSON (newline-delimited JSON) line framing over the daemon socket, with incremental decoding that handles partial frames split across TCP/socket chunk boundaries.
Description
The NDJSON_Framing heuristic uses newline-delimited JSON as the wire protocol for jcode client-server communication. Each frame is a JSON object terminated by \n. The TypeScript SDK's framing.ts implements an incremental decoder that keeps a remainder buffer and only emits complete lines, because sockets split frames anywhere — decoding per chunk would be wrong. Blank lines are skipped, matching the Rust reader. The encoder (encodeFrame) serializes a frame to JSON and appends a newline. This simple framing avoids binary length prefixes and is debuggable with standard tools.
Usage
Use this heuristic for all client-server communication over the jcode daemon socket. The framing is used by both the Rust server (reader) and the TypeScript SDK (client). When debugging protocol issues, each line in the socket stream is a complete JSON message.
The Insight (Rule of Thumb)
- Action: Use NDJSON: encode each frame as
JSON.stringify(frame) + "\n"; decode incrementally with a remainder buffer. - Value: Frames are
JSON + \n; blank lines skipped; incremental decoder handles partial frames. - Trade-off: Slightly larger than binary framing (newline overhead + JSON key names) but far easier to debug.
- Compatibility: TypeScript decoder matches the Rust reader behavior exactly.
Reasoning
Sockets can split a single write into multiple chunks, or combine multiple writes into one chunk. A naive per-chunk decode would corrupt frames at split boundaries. The incremental decoder keeps a remainder buffer: it accumulates bytes, splits on newlines, emits complete lines as frames, and keeps the trailing partial line for the next chunk. This is the standard approach for line-delimited protocols over stream sockets.
Code Evidence
Incremental decoder from sdk/typescript/src/framing.ts:1-9:
/** NDJSON line framing over a byte stream. */
/**
* Incremental newline-delimited JSON decoder.
*
* Sockets split frames anywhere, so decoding per chunk is wrong; this keeps a
* remainder buffer and only emits complete lines. Blank lines are skipped,
* matching the Rust reader.
*/
Encoder from sdk/typescript/src/framing.ts:27-28:
export function encodeFrame(frame: unknown): string {
return `${JSON.stringify(frame)}\n`;
}