Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feat(coding-agent): ACP semantic-edges-v1 provenance producer (#1885)

Sebastian Müller1768ace56653
diff --git a/packages/coding-agent/.changes/acp-semantic-edges-producer.md b/packages/coding-agent/.changes/acp-semantic-edges-producer.md
new file mode 100644
index 0000000000..201ef64460
--- /dev/null
+++ b/packages/coding-agent/.changes/acp-semantic-edges-producer.md
@@ -0,0 +1 @@
+- Added an ACP semantic-edges-v1 producer: each agent session appends an append-only `semantic-edges.jsonl` ledger beside its session artifacts, every provider turn and compaction summary call carries one opaque request ID on `X-ACP-Model-Request-ID` and `Idempotency-Key` (minted before the call, committed or failed when its stream resolves, and stable across retry attempts of the same call body), spawned subagents record their parent session and spawning request while successful children record their return, and `deriveSemanticEdges` folds a session tree's ledgers into commit-gated `continuation`/`subagent_call`/`subagent_return`/`compaction` edges matching the verifiers semantic-edges-v1 schema. Derivation only — nothing publishes or reads the ledger yet.
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts
index 21dd2c9ff0..113f6ed92e 100644
--- a/packages/coding-agent/src/core/agent-session-runtime.ts
+++ b/packages/coding-agent/src/core/agent-session-runtime.ts
@@ -343,6 +343,8 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
rlmSessionDir: options.sessionDir,
rlmParentNodeId: options.rlmParentNodeId,
rlmParentAgent: options.parentSession.sessionName ?? options.parentSession.sessionId,
+ semanticParentSessionId: options.parentSession.sessionId,
+ semanticSpawnedByRequestId: options.spawnedByRequestId,
},
runtimeMetadata: {
kind: "subagent",
diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.ts
index e1622530b9..085bab55e7 100644
--- a/packages/coding-agent/src/core/agent-session-services.ts
+++ b/packages/coding-agent/src/core/agent-session-services.ts
@@ -62,6 +62,8 @@ export interface AgentSessionCreationOptions {
rlmSessionDir?: string;
rlmParentNodeId?: string;
rlmParentAgent?: string;
+ semanticParentSessionId?: string;
+ semanticSpawnedByRequestId?: string;
subagentRuntimeHost?: SubagentRuntimeHost;
rlmHeartbeatController?: AgentRlmHeartbeatController;
prewarmIpythonKernel?: boolean;
@@ -251,6 +253,8 @@ export async function createAgentSessionFromServices(
rlmSessionDir: options.rlmSessionDir,
rlmParentNodeId: options.rlmParentNodeId,
rlmParentAgent: options.rlmParentAgent,
+ semanticParentSessionId: options.semanticParentSessionId,
+ semanticSpawnedByRequestId: options.semanticSpawnedByRequestId,
subagentRuntimeHost: options.subagentRuntimeHost,
rlmHeartbeatController: options.rlmHeartbeatController,
sessionStartEvent: options.sessionStartEvent,
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index d321f6d067..d6fde798d7 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -231,6 +231,12 @@ import {
type RlmSubagentRuntime,
type SubagentRuntimeHost,
} from "./rlm-runtime.js";
+import {
+ modelRequestHeaders,
+ SEMANTIC_EDGES_LEDGER_FILENAME,
+ SemanticEdgeRecorder,
+ wrapStreamFnWithSemanticEdges,
+} from "./semantic-edges.js";
import {
ActionStore,
type ActionTicket,
@@ -442,6 +448,8 @@ export interface AgentSessionConfig {
rlmSessionDir?: string;
rlmParentNodeId?: string;
rlmParentAgent?: string;
+ semanticParentSessionId?: string;
+ semanticSpawnedByRequestId?: string;
subagentRuntimeHost?: SubagentRuntimeHost;
autonomous?: AgentAutonomousConfig;
prewarmIpythonKernel?: boolean;
@@ -1167,6 +1175,7 @@ export class AgentSession {
private _rlmMaxDepth: number;
private _rlmMaxDepthSource: RlmMaxDepthSource;
private _rlmSessionDir?: string;
+ private readonly _semanticEdges: SemanticEdgeRecorder;
private _rlmParentNodeId?: string;
private _rlmParentAgent?: string;
private _repliedToParentSinceTask: boolean | undefined;
@@ -1275,6 +1284,14 @@ export class AgentSession {
this._rlmSessionDir = config.rlmSessionDir;
this._rlmParentNodeId = config.rlmParentNodeId;
this._rlmParentAgent = config.rlmParentAgent;
+ const semanticEdgesDir = this._rlmSessionDir ?? this.sessionManager.getSessionArtifactDir();
+ this._semanticEdges = new SemanticEdgeRecorder({
+ ledgerPath: semanticEdgesDir ? join(semanticEdgesDir, SEMANTIC_EDGES_LEDGER_FILENAME) : undefined,
+ sessionId: this.sessionManager.getSessionId(),
+ parentSessionId: config.semanticParentSessionId,
+ spawnedByRequestId: config.semanticSpawnedByRequestId,
+ });
+ this.agent.streamFn = wrapStreamFnWithSemanticEdges(this.agent.streamFn, this._semanticEdges);
// A resumed child may have replied before this process started; false would
// claim knowledge that is not present in the session transcript.
this._repliedToParentSinceTask =
@@ -3741,6 +3758,7 @@ export class AgentSession {
}
private _resolveRetry(): void {
+ this._semanticEdges.clearTurnRetry();
if (this._retryResolve) {
this._retryResolve();
this._retryResolve = undefined;
@@ -4302,6 +4320,10 @@ export class AgentSession {
return this._rlmDepth;
}
+ get semanticEdges(): SemanticEdgeRecorder {
+ return this._semanticEdges;
+ }
+
get rlmMaxDepth(): number {
return this._rlmMaxDepth;
}
@@ -7533,41 +7555,100 @@ export class AgentSession {
let extensionCompaction: CompactionResult | undefined;
let fromExtension = false;
- if (this._extensionRunner.hasHandlers("session_before_compact")) {
- const result = (await this._extensionRunner.emit({
- type: "session_before_compact",
- preparation,
- branchEntries: pathEntries,
- customInstructions,
- signal,
- })) as SessionBeforeCompactResult | undefined;
+ const semanticCompaction = this._semanticEdges.beginCompaction();
+ let compactionRecorded = false;
+ const uncommittedSlices: string[] = [];
+ let summary: string;
+ let firstKeptEntryId: string;
+ let tokensBefore: number;
+ let details: CompactionResult["details"];
+ try {
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
+ const result = (await this._extensionRunner.emit({
+ type: "session_before_compact",
+ preparation,
+ branchEntries: pathEntries,
+ customInstructions,
+ signal,
+ })) as SessionBeforeCompactResult | undefined;
- if (result?.cancel) {
- throw new Error("Compaction cancelled");
+ if (result?.cancel) {
+ throw new Error("Compaction cancelled");
+ }
+
+ if (result?.compaction) {
+ extensionCompaction = result.compaction;
+ fromExtension = true;
+ }
}
- if (result?.compaction) {
- extensionCompaction = result.compaction;
- fromExtension = true;
+ if (extensionCompaction) {
+ ({ summary, firstKeptEntryId, tokensBefore, details } = extensionCompaction);
+ } else {
+ // Each summary wire call gets its own request ID: split turns send two
+ // different bodies, and one Idempotency-Key must never cover both. A slice
+ // that succeeds on the wire stays uncommitted until the compaction itself
+ // commits: a racing sibling's failure (or an abort) must leave no committed
+ // summary request for the next turn's continuation edge to attach to.
+ const summaryCall = async <T>(
+ call: (callHeaders: Record<string, string> | undefined) => Promise<T>,
+ ): Promise<T> => {
+ const requestId = this._semanticEdges.startCompactionRequest(semanticCompaction.compactionId);
+ if (requestId === undefined) {
+ return call(headers);
+ }
+ try {
+ const result = await call({ ...headers, ...modelRequestHeaders(requestId) });
+ uncommittedSlices.push(requestId);
+ return result;
+ } catch (error) {
+ this._semanticEdges.failRequest(requestId);
+ throw error;
+ }
+ };
+ ({ summary, firstKeptEntryId, tokensBefore, details } = await compact(
+ preparation,
+ model,
+ apiKey,
+ headers,
+ customInstructions,
+ signal,
+ this.thinkingLevel,
+ summaryCall,
+ ));
}
- }
- const { summary, firstKeptEntryId, tokensBefore, details } =
- extensionCompaction ??
- (await compact(preparation, model, apiKey, headers, customInstructions, signal, this.thinkingLevel));
+ if (signal.aborted) {
+ throw new Error("Compaction cancelled");
+ }
- if (signal.aborted) {
- throw new Error("Compaction cancelled");
+ // Ledger-before-effect: the compaction outcome is durable before the transcript
+ // commits it. Marked first: the ID is consumed even when the write throws, and a
+ // second finish attempt would mask the original I/O error.
+ compactionRecorded = true;
+ for (const requestId of uncommittedSlices.splice(0)) {
+ this._semanticEdges.finishRequest(requestId);
+ }
+ this._semanticEdges.finishCompaction(semanticCompaction.compactionId, "completed");
+ this.sessionManager.appendCompaction(
+ summary,
+ firstKeptEntryId,
+ tokensBefore,
+ details,
+ fromExtension,
+ customInstructions,
+ );
+ } catch (error) {
+ for (const requestId of uncommittedSlices.splice(0)) {
+ this._semanticEdges.failRequest(requestId);
+ }
+ if (!compactionRecorded) {
+ const cancelled =
+ error instanceof Error && (error.name === "AbortError" || error.message === "Compaction cancelled");
+ this._semanticEdges.finishCompaction(semanticCompaction.compactionId, cancelled ? "cancelled" : "failed");
+ }
+ throw error;
}
-
- this.sessionManager.appendCompaction(
- summary,
- firstKeptEntryId,
- tokensBefore,
- details,
- fromExtension,
- customInstructions,
- );
const newEntries = this.sessionManager.getEntries();
this.agent.state.messages = this.sessionManager.buildSessionContext().messages;
this._mergeUnpersistedOutcomes(this.agent.state.messages);
@@ -9501,6 +9582,7 @@ export class AgentSession {
sessionDir: string;
model: Model<any>;
thinkingLevel?: ThinkingLevel;
+ spawnedByRequestId?: string;
}): CreateRlmSubagentRuntimeOptions {
return {
parentSession: this,
@@ -9523,6 +9605,7 @@ export class AgentSession {
rlmDepth: this._rlmDepth + 1,
rlmMaxDepth: this._rlmMaxDepth,
rlmParentNodeId: options.id,
+ spawnedByRequestId: options.spawnedByRequestId,
};
}
@@ -9588,6 +9671,8 @@ export class AgentSession {
rlmSessionDir: options.sessionDir,
rlmParentNodeId: options.rlmParentNodeId,
rlmParentAgent: options.parentSession.sessionName ?? options.parentSession.sessionId,
+ semanticParentSessionId: options.parentSession.sessionId,
+ semanticSpawnedByRequestId: options.spawnedByRequestId,
sessionStartEvent: { type: "session_start", reason: "startup" },
});
if (child.sessionName !== options.sessionName) {
@@ -10445,6 +10530,10 @@ export class AgentSession {
kwargs: Record<string, unknown> = {},
spawnCode?: string,
): Promise<RlmSpawnHandle> {
+ // Snapshot before any await: the spawning request is the turn whose tool call is
+ // executing now. A spawn arriving outside an active run (a detached kernel task
+ // firing while the parent is idle) has no such turn; an absent edge beats a wrong one.
+ const spawnedByRequestId = this.isStreaming ? this._semanticEdges.lastTurnRequestId : undefined;
const { name: rawName, model: rawModel, thinking: rawThinking, ...unsupported } = kwargs;
const unsupportedKwargs = Object.keys(unsupported);
if (unsupportedKwargs.length > 0) {
@@ -10538,6 +10627,7 @@ export class AgentSession {
sessionDir: childSessionDir,
model: modelSelection.model,
thinkingLevel: requestedThinkingLevel,
+ spawnedByRequestId,
}),
onSessionPublished: publishChildSession,
};
@@ -10682,6 +10772,11 @@ export class AgentSession {
await child.waitForRlmQuiescence();
if (run.error) throw new Error(run.error);
run.status = "done";
+ // Only successful completions return; the edge lands on the parent's next commit.
+ const childLastCommitted = child.semanticEdges.lastCommittedRequestId;
+ if (childLastCommitted !== undefined) {
+ this._semanticEdges.recordChildReturned(child.sessionId, childLastCommitted);
+ }
run.durationMs = Date.now() - startedAt;
run.activity = undefined;
emitChildUpdate();
@@ -10716,6 +10811,13 @@ export class AgentSession {
run.status = "error";
run.error = runError.message;
}
+ // A failed child still returns an error outcome the parent consumes;
+ // cancelled runs and zero-commit children return nothing.
+ const failedChild = childSession ?? childRuntime?.session;
+ const failedLastCommitted = failedChild?.semanticEdges.lastCommittedRequestId;
+ if (run.status === "error" && failedChild && failedLastCommitted !== undefined) {
+ this._semanticEdges.recordChildReturned(failedChild.sessionId, failedLastCommitted);
+ }
run.durationMs = Date.now() - startedAt;
run.activity = undefined;
if (run.status === "error" && childSession === undefined) {
@@ -11038,6 +11140,11 @@ export class AgentSession {
}
const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
+ // Park now: the retry re-issues the failed call and must reuse its Idempotency-Key.
+ // Payload hooks mutate the wire body after the hash point, so reuse is forfeited.
+ if (!this._extensionRunner.hasHandlers("before_provider_request")) {
+ this._semanticEdges.prepareTurnRetry();
+ }
this._emit({
type: "auto_retry_start",
diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.ts
index cdda5ed080..a11dae6b95 100644
--- a/packages/coding-agent/src/core/compaction/compaction.ts
+++ b/packages/coding-agent/src/core/compaction/compaction.ts
@@ -670,6 +670,11 @@ Be concise. Focus on what's needed to understand the kept suffix.`;
* @param preparation - Pre-calculated preparation from prepareCompaction()
* @param customInstructions - Optional custom focus for the summary
*/
+/** Runs one summary wire call; hosts decorate each call with its own request identity. */
+export type SummaryCallRunner = <T>(
+ call: (callHeaders: Record<string, string> | undefined) => Promise<T>,
+) => Promise<T>;
+
export async function compact(
preparation: CompactionPreparation,
model: Model<any>,
@@ -678,6 +683,7 @@ export async function compact(
customInstructions?: string,
signal?: AbortSignal,
thinkingLevel?: ThinkingLevel,
+ summaryCall: SummaryCallRunner = (call) => call(headers),
): Promise<CompactionResult> {
const {
firstKeptEntryId,
@@ -692,42 +698,49 @@ export async function compact(
let summary: string;
if (isSplitTurn && turnPrefixMessages.length > 0) {
+ // Split turns make two wire calls with different bodies; each needs its own identity.
const [historyResult, turnPrefixResult] = await Promise.all([
messagesToSummarize.length > 0
- ? generateSummary(
- messagesToSummarize,
- model,
- settings.reserveTokens,
- apiKey,
- headers,
- signal,
- customInstructions,
- previousSummary,
- thinkingLevel,
+ ? summaryCall((callHeaders) =>
+ generateSummary(
+ messagesToSummarize,
+ model,
+ settings.reserveTokens,
+ apiKey,
+ callHeaders,
+ signal,
+ customInstructions,
+ previousSummary,
+ thinkingLevel,
+ ),
)
: Promise.resolve("No prior history."),
- generateTurnPrefixSummary(
- turnPrefixMessages,
+ summaryCall((callHeaders) =>
+ generateTurnPrefixSummary(
+ turnPrefixMessages,
+ model,
+ settings.reserveTokens,
+ apiKey,
+ callHeaders,
+ signal,
+ thinkingLevel,
+ ),
+ ),
+ ]);
+ summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
+ } else {
+ summary = await summaryCall((callHeaders) =>
+ generateSummary(
+ messagesToSummarize,
model,
settings.reserveTokens,
apiKey,
- headers,
+ callHeaders,
signal,
+ customInstructions,
+ previousSummary,
thinkingLevel,
),
- ]);
- summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
- } else {
- summary = await generateSummary(
- messagesToSummarize,
- model,
- settings.reserveTokens,
- apiKey,
- headers,
- signal,
- customInstructions,
- previousSummary,
- thinkingLevel,
);
}
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.ts
index 976b7b040d..470224cc53 100644
--- a/packages/coding-agent/src/core/rlm-runtime.ts
+++ b/packages/coding-agent/src/core/rlm-runtime.ts
@@ -233,6 +233,8 @@ export interface CreateRlmSubagentRuntimeOptions {
rlmDepth: number;
rlmMaxDepth: number;
rlmParentNodeId: string;
+ /** Request ID of the parent model call whose tool call caused this spawn. */
+ spawnedByRequestId?: string;
/** Source of the Python cell that spawned this subagent, for display. */
spawnCode?: string;
/** Publish the session to the parent before a host makes the runtime addressable. */
diff --git a/packages/coding-agent/src/core/sdk.ts b/packages/coding-agent/src/core/sdk.ts
index 72b740e980..0202492932 100644
--- a/packages/coding-agent/src/core/sdk.ts
+++ b/packages/coding-agent/src/core/sdk.ts
@@ -370,6 +370,8 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
rlmSessionDir: options.rlmSessionDir,
rlmParentNodeId: options.rlmParentNodeId,
rlmParentAgent: options.rlmParentAgent,
+ semanticParentSessionId: options.semanticParentSessionId,
+ semanticSpawnedByRequestId: options.semanticSpawnedByRequestId,
subagentRuntimeHost: options.subagentRuntimeHost,
sessionStartEvent: options.sessionStartEvent,
prewarmIpythonKernel: options.prewarmIpythonKernel,
diff --git a/packages/coding-agent/src/core/semantic-edges.ts b/packages/coding-agent/src/core/semantic-edges.ts
new file mode 100644
index 0000000000..0dc64ca2fd
--- /dev/null
+++ b/packages/coding-agent/src/core/semantic-edges.ts
@@ -0,0 +1,617 @@
+import { createHash, randomUUID } from "node:crypto";
+import { appendFileSync, existsSync, mkdirSync, readFileSync, truncateSync } from "node:fs";
+import { dirname } from "node:path";
+import type { StreamFn } from "@earendil-works/pi-agent-core";
+
+/**
+ * ACP semantic-edges-v1 producer: a durable per-agent ledger of model-request
+ * events plus a pure fold that derives sparse semantic edges between logical
+ * request IDs (published downstream under ai.prime.acp/semantic-edges-v1).
+ *
+ * Ledger events are written before the effects they describe. Edges are
+ * commit-gated: they materialize only when their target request finishes.
+ * prime-agent has no prompt rollback (unlike nano-rlm's checkpoint/restore),
+ * so a failed request simply returns its inbound edges to the session's
+ * pending set and they attach to the next committed request in that session.
+ * A request whose stream never completes (hard crash, torn tail) stays
+ * in-flight and produces no edges.
+ *
+ * Divergence from nano-rlm: compaction summary requests claim no pending
+ * edges (and no spawn). nano-rlm's single summary request can claim safely;
+ * prime-agent's split turns run several racing slices, so pending edges would
+ * land on whichever slice started first — a dead end when a different slice
+ * commits last. Pending therefore defers past summary slices; a COMPLETED
+ * compaction flushes it to its last-committed slice — the same request that
+ * sources the compaction edge — so pending always lands on a committed
+ * request even when the session never runs another turn. Failed or cancelled
+ * compactions leave pending for the next turn.
+ */
+
+export const MODEL_REQUEST_ID_HEADER = "X-ACP-Model-Request-ID";
+export const IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
+export const SEMANTIC_EDGES_LEDGER_FILENAME = "semantic-edges.jsonl";
+
+export type SemanticEdgeType = "continuation" | "subagent_call" | "subagent_return" | "compaction";
+export type CompactionStatus = "completed" | "failed" | "cancelled";
+
+export interface SessionRegisteredEvent {
+ type: "session_registered";
+ session_id: string;
+ parent_session_id?: string;
+ spawned_by_request_id?: string;
+}
+
+export interface RequestStartedEvent {
+ type: "request_started";
+ request_id: string;
+ session_id: string;
+ compaction_id?: string;
+}
+
+export interface RequestFinishedEvent {
+ type: "request_finished";
+ request_id: string;
+}
+
+export interface RequestFailedEvent {
+ type: "request_failed";
+ request_id: string;
+}
+
+export interface CompactionBegunEvent {
+ type: "compaction_begun";
+ compaction_id: string;
+ session_id: string;
+}
+
+export interface CompactionFinishedEvent {
+ type: "compaction_finished";
+ compaction_id: string;
+ status: CompactionStatus;
+}
+
+export interface ChildReturnedEvent {
+ type: "child_returned";
+ /** The session whose ledger this is: the parent claiming the return. */
+ session_id: string;
+ child_session_id: string;
+ /** The child's last committed request, captured at the success point. */
+ request_id: string;
+}
+
+export type SemanticEdgeLedgerEvent =
+ | SessionRegisteredEvent
+ | RequestStartedEvent
+ | RequestFinishedEvent
+ | RequestFailedEvent
+ | CompactionBegunEvent
+ | CompactionFinishedEvent
+ | ChildReturnedEvent;
+
+export interface SemanticEdge {
+ source_request_id: string;
+ target_request_id: string;
+ type: SemanticEdgeType;
+}
+
+export function modelRequestHeaders(requestId: string): Record<string, string> {
+ return {
+ [MODEL_REQUEST_ID_HEADER]: requestId,
+ [IDEMPOTENCY_KEY_HEADER]: requestId,
+ };
+}
+
+function mintId(): string {
+ return randomUUID().replaceAll("-", "");
+}
+
+/** Content hash of one turn call body; Idempotency-Key reuse is only safe for a byte-identical retry. */
+export function hashTurnBody(
+ model: { provider: string; id: string },
+ context: {
+ systemPrompt?: string;
+ messages: unknown[];
+ tools?: unknown[];
+ },
+ options?: {
+ reasoning?: unknown;
+ thinkingBudgets?: unknown;
+ temperature?: number;
+ maxTokens?: number;
+ serviceTier?: unknown;
+ },
+): string {
+ return createHash("sha256")
+ .update(
+ JSON.stringify({
+ provider: model.provider,
+ model: model.id,
+ systemPrompt: context.systemPrompt,
+ messages: context.messages,
+ tools: context.tools,
+ reasoning: options?.reasoning,
+ thinkingBudgets: options?.thinkingBudgets,
+ temperature: options?.temperature,
+ maxTokens: options?.maxTokens,
+ serviceTier: options?.serviceTier,
+ }),
+ )
+ .digest("hex");
+}
+
+/**
+ * Append-only semantic-edge recorder for one agent session. It only WRITES
+ * events; edge semantics live in the pure {@link deriveSemanticEdges} fold.
+ *
+ * Constructing a recorder over an existing ledger replays it; registration is
+ * idempotent across resumes.
+ */
+export class SemanticEdgeRecorder {
+ readonly sessionId: string;
+ private readonly _ledgerPath?: string;
+ private _pendingRepair?: { truncateToBytes: number } | { terminateLine: true };
+ private _disabled = false;
+ private _epoch = 0;
+ private _lastTurn?: { requestId: string; epoch: number; bodyHash?: string };
+ private _parkedRetry?: { requestId: string; epoch: number; bodyHash?: string };
+ private _lastCommittedRequestId?: string;
+ private _openCompactions = new Set<string>();
+
+ constructor(options: {
+ ledgerPath?: string;
+ sessionId: string;
+ parentSessionId?: string;
+ spawnedByRequestId?: string;
+ }) {
+ this.sessionId = options.sessionId;
+ this._ledgerPath = options.ledgerPath;
+
+ let existing: SemanticEdgeLedgerEvent[] = [];
+ try {
+ existing = this._loadExisting();
+ } catch (error) {
+ this._disable(error);
+ return;
+ }
+ const registered = existing.some(
+ (event) => event.type === "session_registered" && event.session_id === this.sessionId,
+ );
+ if (registered) {
+ for (const event of existing) {
+ this._replay(event);
+ }
+ return;
+ }
+
+ this._append({
+ type: "session_registered",
+ session_id: this.sessionId,
+ ...(options.parentSessionId !== undefined ? { parent_session_id: options.parentSessionId } : {}),
+ ...(options.spawnedByRequestId !== undefined ? { spawned_by_request_id: options.spawnedByRequestId } : {}),
+ });
+ }
+
+ // Provenance is best-effort: the first ledger failure permanently disables all
+ // writes (one warning), and callers stop emitting request IDs on the wire so
+ // the ledger-before-wire invariant is preserved rather than weakened.
+ private _disable(error: unknown): void {
+ if (this._disabled) return;
+ this._disabled = true;
+ console.warn(
+ `semantic-edge ledger disabled at ${this._ledgerPath}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+
+ get lastTurnRequestId(): string | undefined {
+ return this._lastTurn?.requestId;
+ }
+
+ get lastCommittedRequestId(): string | undefined {
+ return this._lastCommittedRequestId;
+ }
+
+ /**
+ * Mint (or, for a body-identical retry, reuse) the request ID for one turn
+ * call. The body hash is captured eagerly, before the wire call, so a later
+ * mutation of the live message objects can never alias two different bodies
+ * under one parked Idempotency-Key. A reused retry re-logs request_started
+ * so the fold re-claims the failed attempt's returned pending edges.
+ */
+ startTurnRequest(bodyHash?: string): string | undefined {
+ const parked = this._parkedRetry;
+ const requestId =
+ parked && parked.epoch === this._epoch && parked.bodyHash !== undefined && parked.bodyHash === bodyHash
+ ? parked.requestId
+ : mintId();
+ if (requestId === parked?.requestId) {
+ this._parkedRetry = undefined;
+ }
+ const recorded = this._append({
+ type: "request_started",
+ request_id: requestId,
+ session_id: this.sessionId,
+ });
+ if (!recorded) {
+ return undefined;
+ }
+ this._lastTurn = { requestId, epoch: this._epoch, bodyHash };
+ return requestId;
+ }
+
+ /** Park the last turn request so the upcoming auto-retry reuses its ID. */
+ prepareTurnRetry(): void {
+ this._parkedRetry = this._lastTurn;
+ }
+
+ clearTurnRetry(): void {
+ this._parkedRetry = undefined;
+ }
+
+ finishRequest(requestId: string | undefined): void {
+ if (requestId === undefined) return;
+ this._append({ type: "request_finished", request_id: requestId });
+ }
+
+ failRequest(requestId: string | undefined): void {
+ if (requestId === undefined) return;
+ this._append({ type: "request_failed", request_id: requestId });
+ }
+
+ beginCompaction(): { compactionId: string } {
+ const compactionId = mintId();
+ this._append({ type: "compaction_begun", compaction_id: compactionId, session_id: this.sessionId });
+ return { compactionId };
+ }
+
+ /** Mint the summary request for a wire compaction; extension-supplied summaries make no request. */
+ startCompactionRequest(compactionId: string): string | undefined {
+ const requestId = mintId();
+ const recorded = this._append({
+ type: "request_started",
+ request_id: requestId,
+ session_id: this.sessionId,
+ compaction_id: compactionId,
+ });
+ return recorded ? requestId : undefined;
+ }
+
+ finishCompaction(compactionId: string, status: CompactionStatus): void {
+ if (this._disabled) return;
+ if (!this._openCompactions.has(compactionId)) {
+ throw new Error(`unknown semantic-edge compaction: ${compactionId}`);
+ }
+ this._append({ type: "compaction_finished", compaction_id: compactionId, status });
+ }
+
+ /** The parent claims a successfully returned child; failed or cancelled children never return. */
+ recordChildReturned(childSessionId: string, childLastCommittedRequestId: string | undefined): void {
+ if (childLastCommittedRequestId === undefined) return;
+ this._append({
+ type: "child_returned",
+ session_id: this.sessionId,
+ child_session_id: childSessionId,
+ request_id: childLastCommittedRequestId,
+ });
+ }
+
+ private _replay(event: SemanticEdgeLedgerEvent): void {
+ switch (event.type) {
+ case "request_started":
+ // Restores spawn attribution after resume; the body hash is unknowable, so
+ // a parked retry from a replayed request can never be reused.
+ if (event.session_id === this.sessionId && event.compaction_id === undefined) {
+ this._lastTurn = { requestId: event.request_id, epoch: this._epoch };
+ }
+ break;
+ case "request_finished":
+ this._lastCommittedRequestId = event.request_id;
+ break;
+ case "compaction_begun":
+ if (event.session_id === this.sessionId) {
+ this._openCompactions.add(event.compaction_id);
+ }
+ break;
+ case "compaction_finished":
+ if (this._openCompactions.delete(event.compaction_id) && event.status === "completed") {
+ this._epoch += 1;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Construction never mutates the file: a viewer may be reading a live
+ // writer's ledger. Torn-tail repair is deferred to this recorder's first append.
+ private _loadExisting(): SemanticEdgeLedgerEvent[] {
+ if (!this._ledgerPath || !existsSync(this._ledgerPath)) {
+ return [];
+ }
+ const raw = readFileSync(this._ledgerPath, "utf8");
+ const parsed = parseLedgerContent(raw);
+ if (parsed.validLength < raw.length) {
+ this._pendingRepair = { truncateToBytes: Buffer.byteLength(raw.slice(0, parsed.validLength)) };
+ } else if (raw.length > 0 && !raw.endsWith("\n")) {
+ this._pendingRepair = { terminateLine: true };
+ }
+ return parsed.events;
+ }
+
+ // Durable append first, in-memory state second: a failed write must not leave
+ // commit state pointing at events that never reached the ledger.
+ private _append(event: SemanticEdgeLedgerEvent): boolean {
+ if (this._disabled) {
+ return false;
+ }
+ if (this._ledgerPath) {
+ try {
+ mkdirSync(dirname(this._ledgerPath), { recursive: true });
+ if (this._pendingRepair) {
+ if ("truncateToBytes" in this._pendingRepair) {
+ // Discard the torn tail line so it never becomes mid-file corruption.
+ truncateSync(this._ledgerPath, this._pendingRepair.truncateToBytes);
+ } else {
+ appendFileSync(this._ledgerPath, "\n");
+ }
+ this._pendingRepair = undefined;
+ }
+ appendFileSync(this._ledgerPath, `${JSON.stringify(event)}\n`);
+ } catch (error) {
+ this._disable(error);
+ return false;
+ }
+ }
+ this._replay(event);
+ return true;
+ }
+}
+
+/**
+ * Parse a ledger, tolerating only a torn final line: malformed AND
+ * unterminated (a killed mid-append). A newline-terminated malformed line is
+ * real corruption anywhere in the file and throws.
+ */
+function parseLedgerContent(raw: string): { events: SemanticEdgeLedgerEvent[]; validLength: number } {
+ const events: SemanticEdgeLedgerEvent[] = [];
+ let offset = 0;
+ let validLength = 0;
+ let lineNumber = 0;
+ while (offset < raw.length) {
+ const newlineIndex = raw.indexOf("\n", offset);
+ const end = newlineIndex === -1 ? raw.length : newlineIndex + 1;
+ const line = raw.slice(offset, end);
+ lineNumber += 1;
+ if (line.trim().length > 0) {
+ try {
+ events.push(JSON.parse(line) as SemanticEdgeLedgerEvent);
+ } catch (error) {
+ if (newlineIndex === -1) {
+ return { events, validLength };
+ }
+ throw new Error(`corrupt semantic-edge ledger line ${lineNumber}: ${String(error)}`);
+ }
+ }
+ offset = end;
+ validLength = end;
+ }
+ return { events, validLength };
+}
+
+export function readSemanticEdgeLedger(path: string): SemanticEdgeLedgerEvent[] {
+ return parseLedgerContent(readFileSync(path, "utf8")).events;
+}
+
+interface FoldSession {
+ spawnedByRequestId?: string;
+ spawnClaimed: boolean;
+ lastRequestId?: string;
+ pending: Array<{ source: string; type: SemanticEdgeType }>;
+}
+
+/**
+ * Pure fold from one-or-more ledgers to the semantic edge set. Each event
+ * carries the session it acts on, and child returns are recorded in the
+ * parent's ledger with the child's last committed request, so ledgers can be
+ * folded in any order without cross-ledger sequencing.
+ */
+export function deriveSemanticEdges(ledgers: SemanticEdgeLedgerEvent[][]): { edges: SemanticEdge[] } {
+ const sessions = new Map<string, FoldSession>();
+ const inFlight = new Map<
+ string,
+ { sessionId: string; summary: boolean; inbound: Array<{ source: string; type: SemanticEdgeType }> }
+ >();
+ const compactions = new Map<string, { sessionId: string; summaryRequestIds: Set<string> }>();
+ const returnedChildren = new Set<string>();
+ const edges: SemanticEdge[] = [];
+
+ const session = (sessionId: string): FoldSession => {
+ let state = sessions.get(sessionId);
+ if (!state) {
+ state = { spawnClaimed: false, pending: [] };
+ sessions.set(sessionId, state);
+ }
+ return state;
+ };
+
+ for (const event of ledgers.flat()) {
+ switch (event.type) {
+ case "session_registered": {
+ if (!sessions.has(event.session_id)) {
+ sessions.set(event.session_id, {
+ spawnedByRequestId: event.spawned_by_request_id,
+ spawnClaimed: false,
+ pending: [],
+ });
+ }
+ break;
+ }
+ case "request_started": {
+ const state = session(event.session_id);
+ const isSummary = event.compaction_id !== undefined;
+ // Summary slices claim no pending edges and no spawn: pending defers to
+ // the post-compaction turn, the request that actually consumes it.
+ const inbound = isSummary ? [] : state.pending;
+ if (!isSummary) {
+ state.pending = [];
+ if (!state.spawnClaimed && state.spawnedByRequestId !== undefined) {
+ inbound.push({ source: state.spawnedByRequestId, type: "subagent_call" });
+ state.spawnClaimed = true;
+ }
+ }
+ if (state.lastRequestId !== undefined && !inbound.some((edge) => edge.source === state.lastRequestId)) {
+ inbound.push({ source: state.lastRequestId, type: "continuation" });
+ }
+ inFlight.set(event.request_id, { sessionId: event.session_id, summary: isSummary, inbound });
+ if (isSummary && event.compaction_id !== undefined) {
+ const compaction = compactions.get(event.compaction_id);
+ // A split-turn compaction sends several summary slices; all belong to it.
+ if (compaction && compaction.sessionId === event.session_id) {
+ compaction.summaryRequestIds.add(event.request_id);
+ }
+ }
+ break;
+ }
+ case "request_finished": {
+ const request = inFlight.get(event.request_id);
+ if (!request) {
+ break;
+ }
+ inFlight.delete(event.request_id);
+ for (const inbound of request.inbound) {
+ edges.push({
+ source_request_id: inbound.source,
+ target_request_id: event.request_id,
+ type: inbound.type,
+ });
+ }
+ session(request.sessionId).lastRequestId = event.request_id;
+ break;
+ }
+ case "request_failed": {
+ const request = inFlight.get(event.request_id);
+ if (!request) {
+ break;
+ }
+ inFlight.delete(event.request_id);
+ // A failed summary slice returns nothing: it claimed nothing, and its
+ // continuation regenerates from the unchanged last commit (several
+ // failed slices would otherwise requeue duplicate continuations).
+ if (!request.summary) {
+ const state = session(request.sessionId);
+ state.pending = [...request.inbound, ...state.pending];
+ }
+ break;
+ }
+ case "compaction_begun":
+ compactions.set(event.compaction_id, { sessionId: event.session_id, summaryRequestIds: new Set() });
+ break;
+ case "compaction_finished": {
+ const compaction = compactions.get(event.compaction_id);
+ compactions.delete(event.compaction_id);
+ if (event.status !== "completed" || !compaction) {
+ break;
+ }
+ const state = session(compaction.sessionId);
+ // The session's last commit must be one of the compaction's summary slices;
+ // an interrupted or extension-supplied compaction produces no edge.
+ if (state.lastRequestId !== undefined && compaction.summaryRequestIds.has(state.lastRequestId)) {
+ const slice = state.lastRequestId;
+ // nano's source-only suppression, applied at flush time: a pending edge
+ // from X replaces the slice's generated continuation from X, whatever
+ // the pending edge's type, so the flush can never emit a duplicate.
+ for (const source of new Set(state.pending.map((edge) => edge.source))) {
+ const generated = edges.findIndex(
+ (edge) =>
+ edge.source_request_id === source &&
+ edge.target_request_id === slice &&
+ edge.type === "continuation",
+ );
+ if (generated !== -1) {
+ edges.splice(generated, 1);
+ }
+ }
+ // Terminal flush: deliver deferred pending edges to the committed slice
+ // now, so they survive even when the session never runs another turn.
+ for (const pending of state.pending) {
+ edges.push({
+ source_request_id: pending.source,
+ target_request_id: slice,
+ type: pending.type,
+ });
+ }
+ state.pending = [{ source: slice, type: "compaction" }];
+ }
+ break;
+ }
+ case "child_returned": {
+ if (returnedChildren.has(event.child_session_id)) {
+ break;
+ }
+ returnedChildren.add(event.child_session_id);
+ session(event.session_id).pending.push({ source: event.request_id, type: "subagent_return" });
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ return { edges };
+}
+
+const SEMANTIC_INNER_STREAM_FN = Symbol.for("prime-agent.semantic-edges.inner-stream-fn");
+
+/** Unwrap a semantic-edge-bound stream function; aux calls outside session history use this. */
+export function unwrapSemanticEdgeStreamFn(streamFn: StreamFn): StreamFn {
+ return ((streamFn as { [SEMANTIC_INNER_STREAM_FN]?: StreamFn })[SEMANTIC_INNER_STREAM_FN] ?? streamFn) as StreamFn;
+}
+
+/**
+ * Bind a stream function to one session's recorder. Re-wrapping an already
+ * wrapped function rebinds the original, so a child session that inherits its
+ * parent's streamFn attributes calls to its own ledger. request_started is
+ * appended before the wire call; the request commits or fails when its stream
+ * resolves (an error/aborted final message is a failure). When the recorder is
+ * disabled (its ledger failed), calls carry no request ID at all.
+ */
+export function wrapStreamFnWithSemanticEdges(streamFn: StreamFn, recorder: SemanticEdgeRecorder): StreamFn {
+ const inner = unwrapSemanticEdgeStreamFn(streamFn);
+ const wrapped: StreamFn = (model, context, options) => {
+ const requestId = recorder.startTurnRequest(hashTurnBody(model, context, options));
+ if (requestId === undefined) {
+ return inner(model, context, options);
+ }
+ const observe = (stream: Awaited<ReturnType<StreamFn>>) => {
+ void stream.result().then(
+ (message) => {
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
+ recorder.failRequest(requestId);
+ } else {
+ recorder.finishRequest(requestId);
+ }
+ },
+ () => recorder.failRequest(requestId),
+ );
+ return stream;
+ };
+ let result: ReturnType<StreamFn>;
+ try {
+ result = inner(model, context, {
+ ...options,
+ headers: { ...options?.headers, ...modelRequestHeaders(requestId) },
+ });
+ } catch (error) {
+ recorder.failRequest(requestId);
+ throw error;
+ }
+ if (result instanceof Promise) {
+ return result.then(observe, (error) => {
+ recorder.failRequest(requestId);
+ throw error;
+ });
+ }
+ return observe(result);
+ };
+ (wrapped as { [SEMANTIC_INNER_STREAM_FN]?: StreamFn })[SEMANTIC_INNER_STREAM_FN] = inner;
+ return wrapped;
+}
diff --git a/packages/coding-agent/src/core/side-question.ts b/packages/coding-agent/src/core/side-question.ts
index 02d970cd8c..9a3d0e3f0b 100644
--- a/packages/coding-agent/src/core/side-question.ts
+++ b/packages/coding-agent/src/core/side-question.ts
@@ -1,5 +1,6 @@
import { Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
import type { AssistantMessage, UserMessage } from "@earendil-works/pi-ai";
+import { unwrapSemanticEdgeStreamFn } from "./semantic-edges.js";
export type SideQuestionStatus = "running" | "complete" | "cancelled" | "error";
@@ -89,7 +90,8 @@ export function startSideQuestion(
},
convertToLlm: parent.convertToLlm,
transformContext: parent.transformContext,
- streamFn: parent.streamFn,
+ // Side questions are excluded from session history; their calls carry no provenance.
+ streamFn: unwrapSemanticEdgeStreamFn(parent.streamFn),
getApiKey: parent.getApiKey,
onPayload: parent.onPayload,
onResponse: parent.onResponse,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index aa66982c26..599c5359d4 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -2563,6 +2563,8 @@ export class AgentDaemon {
rlmSessionDir: options.sessionDir,
rlmParentNodeId: options.rlmParentNodeId,
rlmParentAgent: options.parentSession.sessionName ?? options.parentSession.sessionId,
+ semanticParentSessionId: options.parentSession.sessionId,
+ semanticSpawnedByRequestId: options.spawnedByRequestId,
},
runtimeMetadata: {
kind: "subagent",
diff --git a/packages/coding-agent/test/agent-session-semantic-edges.test.ts b/packages/coding-agent/test/agent-session-semantic-edges.test.ts
new file mode 100644
index 0000000000..bc4c220fc8
--- /dev/null
+++ b/packages/coding-agent/test/agent-session-semantic-edges.test.ts
@@ -0,0 +1,911 @@
+import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { Agent, type StreamFn } from "@earendil-works/pi-agent-core";
+import {
+ type AssistantMessage,
+ type Context,
+ createAssistantMessageEventStream,
+ fauxAssistantMessage,
+ getModel,
+ type Usage,
+} from "@earendil-works/pi-ai";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AgentSession } from "../src/core/agent-session.js";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import { convertToLlm } from "../src/core/messages.js";
+import { ModelRegistry } from "../src/core/model-registry.js";
+import type { SubagentRuntimeHost } from "../src/core/rlm-runtime.js";
+import {
+ deriveSemanticEdges,
+ IDEMPOTENCY_KEY_HEADER,
+ MODEL_REQUEST_ID_HEADER,
+ readSemanticEdgeLedger,
+ SEMANTIC_EDGES_LEDGER_FILENAME,
+ type SemanticEdgeLedgerEvent,
+} from "../src/core/semantic-edges.js";
+import { SessionManager } from "../src/core/session-manager.js";
+import { type Settings, SettingsManager } from "../src/core/settings-manager.js";
+import { startSideQuestion } from "../src/core/side-question.js";
+import { createHarness, type Harness } from "./suite/harness.js";
+import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.js";
+
+const model = getModel("anthropic", "claude-sonnet-4-5")!;
+
+function usage(): Usage {
+ return {
+ input: 7,
+ output: 3,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 10,
+ cost: { input: 7, output: 3, cacheRead: 0, cacheWrite: 0, total: 10 },
+ };
+}
+
+function assistantMessage(text: string, options: { errorMessage?: string } = {}): AssistantMessage {
+ return {
+ role: "assistant",
+ content: [{ type: "text", text }],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage: usage(),
+ stopReason: options.errorMessage ? "error" : "stop",
+ errorMessage: options.errorMessage,
+ timestamp: Date.now(),
+ };
+}
+
+function lastUserText(context: Context): string {
+ for (let i = context.messages.length - 1; i >= 0; i--) {
+ const message = context.messages[i];
+ if (message?.role !== "user") continue;
+ if (typeof message.content === "string") return message.content;
+ return message.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
+ }
+ return "";
+}
+
+type ScriptedResponse = { text: string; errorMessage?: string };
+
+async function waitForAsync(condition: () => Promise<boolean>): Promise<void> {
+ const deadline = Date.now() + 5000;
+ while (!(await condition())) {
+ if (Date.now() > deadline) throw new Error("Timed out waiting for condition");
+ await sleep(10);
+ }
+}
+
+describe("AgentSession semantic edges", () => {
+ let tempDir: string;
+ let sessions: AgentSession[];
+ let harnesses: Harness[];
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-semantic-session-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(tempDir, { recursive: true });
+ sessions = [];
+ harnesses = [];
+ });
+
+ afterEach(() => {
+ for (const session of sessions) {
+ session.dispose();
+ }
+ while (harnesses.length > 0) {
+ harnesses.pop()?.cleanup();
+ }
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ function createSession(
+ options: {
+ responses?: ScriptedResponse[];
+ settings?: Partial<Settings>;
+ sessionManager?: SessionManager;
+ rlmSessionDir?: string;
+ extensionsResult?: Awaited<ReturnType<typeof createTestExtensionsResult>>;
+ subagentRuntimeHost?: SubagentRuntimeHost;
+ hangMarker?: string;
+ onChildCallStarted?: () => void;
+ } = {},
+ ) {
+ const capturedHeaders: Array<Record<string, string> | undefined> = [];
+ const responses = options.responses;
+ const streamFn: StreamFn = (_model, context, streamOptions) => {
+ capturedHeaders.push(streamOptions?.headers);
+ const stream = createAssistantMessageEventStream();
+ if (options.hangMarker && lastUserText(context).includes(options.hangMarker)) {
+ options.onChildCallStarted?.();
+ return stream;
+ }
+ const next = responses?.shift() ?? { text: "ok" };
+ queueMicrotask(() => {
+ const message = assistantMessage(next.text, { errorMessage: next.errorMessage });
+ if (next.errorMessage) {
+ stream.push({ type: "error", reason: "error", error: message });
+ } else {
+ stream.push({ type: "done", reason: "stop", message });
+ }
+ });
+ return stream;
+ };
+
+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const sessionManager = options.sessionManager ?? SessionManager.create(tempDir, join(tempDir, "sessions"));
+ const settingsManager = options.settings
+ ? SettingsManager.inMemory(options.settings)
+ : SettingsManager.create(tempDir, tempDir);
+
+ const agent = new Agent({
+ convertToLlm,
+ getApiKey: () => "test-key",
+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },
+ streamFn,
+ });
+
+ const session = new AgentSession({
+ agent,
+ sessionManager,
+ settingsManager,
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),
+ resourceLoader: createTestResourceLoader(
+ options.extensionsResult ? { extensionsResult: options.extensionsResult } : undefined,
+ ),
+ rlmSessionDir: options.rlmSessionDir,
+ subagentRuntimeHost: options.subagentRuntimeHost,
+ });
+ sessions.push(session);
+ return { session, sessionManager, capturedHeaders };
+ }
+
+ function ledgerFor(session: AgentSession): SemanticEdgeLedgerEvent[] {
+ const artifactDir = session.sessionManager.getSessionArtifactDir();
+ if (!artifactDir) throw new Error("Missing session artifact dir");
+ return readSemanticEdgeLedger(join(artifactDir, SEMANTIC_EDGES_LEDGER_FILENAME));
+ }
+
+ function startedRequestIds(events: SemanticEdgeLedgerEvent[]): string[] {
+ return events
+ .filter((event) => event.type === "request_started")
+ .map((event) => (event.type === "request_started" ? event.request_id : ""));
+ }
+
+ function childLedgerPath(sessionDir: string): string {
+ return join(sessionDir, SEMANTIC_EDGES_LEDGER_FILENAME);
+ }
+
+ it("sends one ledger-backed request ID per turn on both wire headers", async () => {
+ const { session, capturedHeaders } = createSession();
+
+ await session.prompt("first");
+ await session.prompt("second");
+
+ expect(capturedHeaders).toHaveLength(2);
+ const requestIds = capturedHeaders.map((headers) => headers?.[MODEL_REQUEST_ID_HEADER]);
+ expect(requestIds[0]).toMatch(/^[0-9a-f]{32}$/);
+ expect(requestIds[1]).toMatch(/^[0-9a-f]{32}$/);
+ expect(requestIds[0]).not.toBe(requestIds[1]);
+ for (const headers of capturedHeaders) {
+ expect(headers?.[IDEMPOTENCY_KEY_HEADER]).toBe(headers?.[MODEL_REQUEST_ID_HEADER]);
+ }
+
+ // Every wire request ID was written to the durable ledger before the call,
+ // committed on stream completion, and the committed chain derives edges.
+ const events = ledgerFor(session);
+ expect(startedRequestIds(events)).toEqual(requestIds);
+ expect(events.filter((event) => event.type === "request_finished")).toHaveLength(2);
+ expect(deriveSemanticEdges([events]).edges).toEqual([
+ { source_request_id: requestIds[0], target_request_id: requestIds[1], type: "continuation" },
+ ]);
+ });
+
+ it("writes the request event before the provider call is made", async () => {
+ const observed: Array<{ wireId: string | undefined; ledgerIds: string[] }> = [];
+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const sessionManager = SessionManager.create(tempDir, join(tempDir, "sessions"));
+ const streamFn: StreamFn = (_model, _context, streamOptions) => {
+ const ledgerPath = join(sessionManager.getSessionArtifactDir() ?? "", SEMANTIC_EDGES_LEDGER_FILENAME);
+ observed.push({
+ wireId: streamOptions?.headers?.[MODEL_REQUEST_ID_HEADER],
+ ledgerIds: startedRequestIds(readSemanticEdgeLedger(ledgerPath)),
+ });
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "done", reason: "stop", message: assistantMessage("ok") });
+ });
+ return stream;
+ };
+ const agent = new Agent({
+ convertToLlm,
+ getApiKey: () => "test-key",
+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },
+ streamFn,
+ });
+ const session = new AgentSession({
+ agent,
+ sessionManager,
+ settingsManager: SettingsManager.create(tempDir, tempDir),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),
+ resourceLoader: createTestResourceLoader(),
+ });
+ sessions.push(session);
+
+ await session.prompt("prove ordering");
+
+ expect(observed).toHaveLength(1);
+ expect(observed[0]?.wireId).toBeDefined();
+ expect(observed[0]?.ledgerIds).toContain(observed[0]?.wireId);
+ });
+
+ it("reuses the same request ID across auto-retry attempts of one call", async () => {
+ const { session, capturedHeaders } = createSession({
+ responses: [{ text: "", errorMessage: "overloaded_error" }, { text: "recovered" }],
+ settings: { retry: { enabled: true, maxRetries: 3, baseDelayMs: 1 } },
+ });
+
+ await session.prompt("retry me");
+
+ expect(capturedHeaders).toHaveLength(2);
+ expect(capturedHeaders[0]?.[MODEL_REQUEST_ID_HEADER]).toBeDefined();
+ expect(capturedHeaders[1]?.[MODEL_REQUEST_ID_HEADER]).toBe(capturedHeaders[0]?.[MODEL_REQUEST_ID_HEADER]);
+
+ // started, failed, re-logged start, finished — and no self-referential edges.
+ const events = ledgerFor(session);
+ const requestEvents = events.filter(
+ (event) =>
+ event.type === "request_started" || event.type === "request_failed" || event.type === "request_finished",
+ );
+ expect(requestEvents.map((event) => event.type)).toEqual([
+ "request_started",
+ "request_failed",
+ "request_started",
+ "request_finished",
+ ]);
+ expect(deriveSemanticEdges([events]).edges).toEqual([]);
+ });
+
+ it("forfeits retry-ID reuse when a payload-mutating hook is registered", async () => {
+ // before_provider_request rewrites the wire body AFTER the hash point, so a
+ // reused Idempotency-Key could sit on two different bodies.
+ const extensionsResult = await createTestExtensionsResult(
+ [
+ (pi: any) => {
+ pi.on("before_provider_request", async (payload: any) => payload);
+ },
+ ],
+ tempDir,
+ );
+ const { session, capturedHeaders } = createSession({
+ responses: [{ text: "", errorMessage: "overloaded_error" }, { text: "recovered" }],
+ settings: { retry: { enabled: true, maxRetries: 3, baseDelayMs: 1 } },
+ extensionsResult,
+ });
+
+ await session.prompt("retry me");
+
+ expect(capturedHeaders).toHaveLength(2);
+ expect(capturedHeaders[1]?.[MODEL_REQUEST_ID_HEADER]).toBeDefined();
+ expect(capturedHeaders[1]?.[MODEL_REQUEST_ID_HEADER]).not.toBe(capturedHeaders[0]?.[MODEL_REQUEST_ID_HEADER]);
+ });
+
+ it("excludes side questions from the ledger and the continuation chain", async () => {
+ const { session, capturedHeaders } = createSession();
+
+ await session.prompt("first");
+ const events: string[] = [];
+ const run = startSideQuestion(session.agent, "sq-1", "what changed?", (event) => {
+ events.push(event.status);
+ });
+ await run.done;
+ expect(events.at(-1)).toBe("complete");
+ await session.prompt("second");
+
+ // The side call reached the wire without provenance headers or ledger entries.
+ expect(capturedHeaders).toHaveLength(3);
+ expect(capturedHeaders[1]?.[MODEL_REQUEST_ID_HEADER]).toBeUndefined();
+ const ledger = ledgerFor(session);
+ const requestIds = startedRequestIds(ledger);
+ expect(requestIds).toHaveLength(2);
+ expect(deriveSemanticEdges([ledger]).edges).toEqual([
+ { source_request_id: requestIds[0], target_request_id: requestIds[1], type: "continuation" },
+ ]);
+ });
+
+ /** Attribution requires an active run: production spawns execute inside a turn's tool call. */
+ function spawnDuringRun<T>(session: AgentSession, spawn: () => Promise<T>): Promise<T> {
+ const activeRun = vi.spyOn(session, "isStreaming", "get").mockReturnValue(true);
+ return spawn().finally(() => activeRun.mockRestore());
+ }
+
+ it("records spawned-child ancestry from the latest turn and returns it on success", async () => {
+ const { session: root, capturedHeaders } = createSession();
+
+ await root.prompt("parent turn one");
+ await root.prompt("parent turn two");
+ const spawned = await spawnDuringRun(root, () => root.runRlmChild("child task"));
+ const childId = basename(spawned.session_dir);
+ await waitForAsync(async () => (await root.listRlmSubagents()).subagents[0]?.status === "completed");
+
+ const rootEvents = ledgerFor(root);
+ expect(existsSync(childLedgerPath(spawned.session_dir))).toBe(true);
+ const childEvents = readSemanticEdgeLedger(childLedgerPath(spawned.session_dir));
+
+ // Ancestry points at the latest parent request at spawn time, not the first.
+ const rootRequestIds = startedRequestIds(rootEvents);
+ expect(rootRequestIds.length).toBeGreaterThanOrEqual(2);
+ expect(childEvents.find((event) => event.type === "session_registered")).toMatchObject({
+ parent_session_id: root.sessionId,
+ spawned_by_request_id: rootRequestIds[1],
+ });
+
+ // Exactly one committed child request, minted in the child ledger only, and on the wire.
+ const childRequestIds = startedRequestIds(childEvents);
+ expect(childRequestIds).toHaveLength(1);
+ expect(rootRequestIds).not.toContain(childRequestIds[0]);
+ expect(capturedHeaders.map((headers) => headers?.[MODEL_REQUEST_ID_HEADER])).toContain(childRequestIds[0]);
+
+ // The parent claimed the successful return with the child's last commit.
+ expect(rootEvents.filter((event) => event.type === "child_returned")).toEqual([
+ {
+ type: "child_returned",
+ session_id: root.sessionId,
+ child_session_id: root.getRlmChildSession(childId)?.sessionId,
+ request_id: childRequestIds[0],
+ },
+ ]);
+
+ // The next committed parent request carries both the call and return edges.
+ await root.prompt("after the child");
+ const edges = deriveSemanticEdges([ledgerFor(root), childEvents]).edges;
+ expect(edges).toContainEqual({
+ source_request_id: rootRequestIds[1],
+ target_request_id: childRequestIds[0],
+ type: "subagent_call",
+ });
+ const returnEdges = edges.filter((edge) => edge.type === "subagent_return");
+ expect(returnEdges).toHaveLength(1);
+ expect(returnEdges[0]?.source_request_id).toBe(childRequestIds[0]);
+ });
+
+ it("records no spawn attribution for a child spawned outside an active run", async () => {
+ const { session: root } = createSession();
+ await root.prompt("completed turn");
+ expect(root.semanticEdges.lastTurnRequestId).toBeDefined();
+
+ const spawned = await root.runRlmChild("out-of-band child");
+ await waitForAsync(async () => (await root.listRlmSubagents()).subagents[0]?.status === "completed");
+
+ const registration = readSemanticEdgeLedger(childLedgerPath(spawned.session_dir)).find(
+ (event) => event.type === "session_registered",
+ );
+ expect(registration).toMatchObject({ parent_session_id: root.sessionId });
+ expect(registration?.type === "session_registered" ? registration.spawned_by_request_id : "set").toBeUndefined();
+ const childEvents = readSemanticEdgeLedger(childLedgerPath(spawned.session_dir));
+ const edges = deriveSemanticEdges([ledgerFor(root), childEvents]).edges;
+ expect(edges.filter((edge) => edge.type === "subagent_call")).toEqual([]);
+ });
+
+ it("restores spawn attribution from the ledger after a resume", async () => {
+ const { session: first } = createSession();
+ await first.prompt("turn before resume");
+ const requestBeforeResume = startedRequestIds(ledgerFor(first))[0];
+ const sessionFile = first.sessionFile;
+ if (!sessionFile) throw new Error("Missing session file");
+ first.dispose();
+
+ const resumedManager = SessionManager.open(sessionFile, join(tempDir, "sessions"));
+ const { session: resumed } = createSession({ sessionManager: resumedManager });
+ const spawned = await spawnDuringRun(resumed, () => resumed.runRlmChild("child after resume"));
+ await waitForAsync(async () => (await resumed.listRlmSubagents()).subagents[0]?.status === "completed");
+
+ const childEvents = readSemanticEdgeLedger(childLedgerPath(spawned.session_dir));
+ expect(childEvents.find((event) => event.type === "session_registered")).toMatchObject({
+ parent_session_id: resumed.sessionId,
+ spawned_by_request_id: requestBeforeResume,
+ });
+ const edges = deriveSemanticEdges([ledgerFor(resumed), childEvents]).edges;
+ expect(edges.filter((edge) => edge.type === "subagent_call")).toHaveLength(1);
+ });
+
+ it("snapshots spawn ancestry at the spawn entry point, before preflight awaits", async () => {
+ const { session: root } = createSession();
+ await root.prompt("turn one");
+ const firstId = startedRequestIds(ledgerFor(root))[0];
+
+ // Advance the parent's lineage while runRlmChild is still awaiting preflight.
+ const spawnPromise = spawnDuringRun(root, () => root.runRlmChild("child task"));
+ const laterId = root.semanticEdges.startTurnRequest("later-body-hash");
+ const spawned = await spawnPromise;
+ await waitForAsync(async () => (await root.listRlmSubagents()).subagents[0]?.status === "completed");
+
+ const childEvents = readSemanticEdgeLedger(childLedgerPath(spawned.session_dir));
+ const registration = childEvents.find((event) => event.type === "session_registered");
+ expect(registration).toMatchObject({ spawned_by_request_id: firstId });
+ expect(registration?.type === "session_registered" ? registration.spawned_by_request_id : undefined).not.toBe(
+ laterId,
+ );
+ });
+
+ function failingChildHost(options: { commitBeforeFailure: boolean }) {
+ const state: { child?: AgentSession } = {};
+ const host: SubagentRuntimeHost = {
+ createRlmSubagentRuntime: async (hostOptions) => {
+ const childManager = SessionManager.create(tempDir, hostOptions.sessionDir);
+ const created = createSession({
+ sessionManager: childManager,
+ rlmSessionDir: hostOptions.sessionDir,
+ }).session;
+ if (options.commitBeforeFailure) {
+ await created.prompt("child work before the failure");
+ }
+ vi.spyOn(created, "promptAndWait").mockRejectedValue(new Error("child run failed"));
+ state.child = created;
+ hostOptions.onSessionPublished?.(created);
+ return { session: created };
+ },
+ deleteRlmSubagentRuntime: async (_childId, session) => {
+ await session?.disposeAsync();
+ },
+ };
+ return { host, state };
+ }
+
+ it("claims a failed child's return with its last committed request", async () => {
+ const { host, state } = failingChildHost({ commitBeforeFailure: true });
+ const { session: root } = createSession({ subagentRuntimeHost: host });
+
+ await root.prompt("parent turn");
+ await root.runRlmChild("doomed child");
+ await waitForAsync(async () => (await root.listRlmSubagents()).subagents[0]?.status !== "running");
+
+ const child = state.child;
+ if (!child) throw new Error("Missing child session");
+ const childCommitted = child.semanticEdges.lastCommittedRequestId;
+ expect(childCommitted).toBeDefined();
+ expect(ledgerFor(root).filter((event) => event.type === "child_returned")).toEqual([
+ {
+ type: "child_returned",
+ session_id: root.sessionId,
+ child_session_id: child.sessionId,
+ request_id: childCommitted,
+ },
+ ]);
+
+ // The error outcome the parent consumes links the child's last commit forward.
+ await root.prompt("after the failure");
+ const edges = deriveSemanticEdges([ledgerFor(root)]).edges;
+ const returns = edges.filter((edge) => edge.type === "subagent_return");
+ expect(returns).toHaveLength(1);
+ expect(returns[0]?.source_request_id).toBe(childCommitted);
+ });
+
+ it("never claims a return for a failed child with no committed request", async () => {
+ const { host, state } = failingChildHost({ commitBeforeFailure: false });
+ const { session: root } = createSession({ subagentRuntimeHost: host });
+
+ await root.prompt("parent turn");
+ await root.runRlmChild("doomed child");
+ await waitForAsync(async () => (await root.listRlmSubagents()).subagents[0]?.status !== "running");
+
+ expect(state.child).toBeDefined();
+ expect(ledgerFor(root).filter((event) => event.type === "child_returned")).toEqual([]);
+ const edges = deriveSemanticEdges([ledgerFor(root)]).edges;
+ expect(edges.filter((edge) => edge.type === "subagent_return")).toEqual([]);
+ });
+
+ it("never claims a return for a cancelled child run", async () => {
+ let childStarted = false;
+ const { session: root } = createSession({
+ hangMarker: "hang-task",
+ onChildCallStarted: () => {
+ childStarted = true;
+ },
+ });
+
+ await root.prompt("parent turn");
+ const spawned = await root.runRlmChild("hang-task");
+ await waitForAsync(async () => childStarted);
+ expect(root.cancelRlmChildRun(basename(spawned.session_dir))).toBe(true);
+ await waitForAsync(async () => {
+ const entry = (await root.listRlmSubagents()).subagents[0];
+ return entry === undefined || entry.status !== "running";
+ });
+
+ expect(ledgerFor(root).filter((event) => event.type === "child_returned")).toEqual([]);
+ });
+
+ it("never claims a return for a cancelled child even with committed work", async () => {
+ let releaseRun: ((error: Error) => void) | undefined;
+ const state: { child?: AgentSession } = {};
+ const host: SubagentRuntimeHost = {
+ createRlmSubagentRuntime: async (hostOptions) => {
+ const childManager = SessionManager.create(tempDir, hostOptions.sessionDir);
+ const created = createSession({
+ sessionManager: childManager,
+ rlmSessionDir: hostOptions.sessionDir,
+ }).session;
+ await created.prompt("child work before the cancellation");
+ vi.spyOn(created, "promptAndWait").mockImplementation(
+ () =>
+ new Promise((_resolve, reject) => {
+ releaseRun = reject;
+ }),
+ );
+ state.child = created;
+ hostOptions.onSessionPublished?.(created);
+ return { session: created };
+ },
+ deleteRlmSubagentRuntime: async (_childId, session) => {
+ await session?.disposeAsync();
+ },
+ };
+ const { session: root } = createSession({ subagentRuntimeHost: host });
+
+ await root.prompt("parent turn");
+ const spawned = await root.runRlmChild("cancel me later");
+ await waitForAsync(async () => releaseRun !== undefined);
+ expect(state.child?.semanticEdges.lastCommittedRequestId).toBeDefined();
+ expect(root.cancelRlmChildRun(basename(spawned.session_dir))).toBe(true);
+ releaseRun?.(new Error("run torn down"));
+ await waitForAsync(async () => {
+ const entry = (await root.listRlmSubagents()).subagents[0];
+ return entry === undefined || entry.status !== "running";
+ });
+
+ // Cancelled runs return nothing, even when the child had committed work.
+ expect(ledgerFor(root).filter((event) => event.type === "child_returned")).toEqual([]);
+ });
+
+ async function createCompactionSession() {
+ const extensionsResult = await createTestExtensionsResult(
+ [
+ (pi: any) => {
+ pi.on("session_before_compact", async (event: any) => {
+ if (event.customInstructions === "cancel-me") {
+ return { cancel: true };
+ }
+ return {
+ compaction: {
+ summary: "summarized",
+ firstKeptEntryId: event.preparation.firstKeptEntryId,
+ tokensBefore: event.preparation.tokensBefore,
+ details: {},
+ },
+ };
+ });
+ },
+ ],
+ tempDir,
+ );
+
+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+ authStorage.setRuntimeApiKey("anthropic", "test-key");
+ const sessionManager = SessionManager.create(tempDir, join(tempDir, "sessions"));
+ const agent = new Agent({
+ convertToLlm,
+ getApiKey: () => "test-key",
+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },
+ streamFn: () => {
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "done", reason: "stop", message: assistantMessage("answer") });
+ });
+ return stream;
+ },
+ });
+ const session = new AgentSession({
+ agent,
+ sessionManager,
+ settingsManager: SettingsManager.inMemory({ compaction: { keepRecentTokens: 1 } }),
+ cwd: tempDir,
+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),
+ resourceLoader: createTestResourceLoader({ extensionsResult }),
+ });
+ sessions.push(session);
+ return { session, sessionManager };
+ }
+
+ it("records extension compactions without a summary request or compaction edge", async () => {
+ const { session } = await createCompactionSession();
+
+ await session.prompt("one");
+ await session.prompt("two");
+
+ await expect(session.compact("cancel-me")).rejects.toThrow("Compaction cancelled");
+ let events = ledgerFor(session);
+ expect(events.filter((event) => event.type === "compaction_begun")).toHaveLength(1);
+ expect(events.at(-1)).toMatchObject({ type: "compaction_finished", status: "cancelled" });
+
+ await session.compact();
+ events = ledgerFor(session);
+ expect(events.filter((event) => event.type === "compaction_finished").at(-1)).toMatchObject({
+ status: "completed",
+ });
+ // Extension-supplied summaries make no wire request.
+ expect(startedRequestIds(events)).toHaveLength(2);
+
+ // The chain continues across the compaction; there is no compaction edge without a summary request.
+ await session.prompt("three");
+ const requestIds = startedRequestIds(ledgerFor(session));
+ const edges = deriveSemanticEdges([ledgerFor(session)]).edges;
+ expect(edges).toEqual([
+ { source_request_id: requestIds[0], target_request_id: requestIds[1], type: "continuation" },
+ { source_request_id: requestIds[1], target_request_id: requestIds[2], type: "continuation" },
+ ]);
+ });
+
+ it("commits the completed-compaction ledger event before the transcript entry", async () => {
+ const { session, sessionManager } = await createCompactionSession();
+ await session.prompt("one");
+ await session.prompt("two");
+
+ const original = sessionManager.appendCompaction.bind(sessionManager);
+ let finishedAtCommit: SemanticEdgeLedgerEvent[] = [];
+ vi.spyOn(sessionManager, "appendCompaction").mockImplementation(((
+ ...args: Parameters<SessionManager["appendCompaction"]>
+ ) => {
+ finishedAtCommit = ledgerFor(session).filter((event) => event.type === "compaction_finished");
+ return original(...args);
+ }) as SessionManager["appendCompaction"]);
+
+ await session.compact();
+
+ expect(finishedAtCommit).toEqual([expect.objectContaining({ status: "completed" })]);
+ });
+
+ it("does not double-finish the compaction when the transcript commit fails", async () => {
+ const { session, sessionManager } = await createCompactionSession();
+ await session.prompt("one");
+ await session.prompt("two");
+
+ vi.spyOn(sessionManager, "appendCompaction").mockImplementationOnce(() => {
+ throw new Error("append failed");
+ });
+
+ await expect(session.compact()).rejects.toThrow("append failed");
+
+ const finished = ledgerFor(session).filter((event) => event.type === "compaction_finished");
+ expect(finished).toEqual([expect.objectContaining({ status: "completed" })]);
+ });
+
+ it("keeps prompting and settling children when the session ledger becomes unwritable", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const { session: root, capturedHeaders } = createSession();
+ await root.prompt("first");
+ expect(capturedHeaders[0]?.[MODEL_REQUEST_ID_HEADER]).toBeDefined();
+
+ const artifactDir = root.sessionManager.getSessionArtifactDir();
+ if (!artifactDir) throw new Error("Missing session artifact dir");
+ const ledgerPath = join(artifactDir, SEMANTIC_EDGES_LEDGER_FILENAME);
+ rmSync(ledgerPath);
+ mkdirSync(ledgerPath);
+
+ // Prompts keep working, without request IDs on the wire.
+ await root.prompt("second");
+ expect(capturedHeaders[1]?.[MODEL_REQUEST_ID_HEADER]).toBeUndefined();
+ expect(warn).toHaveBeenCalledOnce();
+
+ // Child runs still settle normally; the parent's return claim is a no-op.
+ await root.runRlmChild("child task");
+ await waitForAsync(async () => (await root.listRlmSubagents()).subagents[0]?.status === "completed");
+ expect(warn).toHaveBeenCalledOnce();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("still compacts when the session ledger becomes unwritable", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const { session, sessionManager } = await createCompactionSession();
+ await session.prompt("one");
+ await session.prompt("two");
+
+ const artifactDir = sessionManager.getSessionArtifactDir();
+ if (!artifactDir) throw new Error("Missing session artifact dir");
+ const ledgerPath = join(artifactDir, SEMANTIC_EDGES_LEDGER_FILENAME);
+ rmSync(ledgerPath);
+ mkdirSync(ledgerPath);
+
+ const result = await session.compact();
+ expect(result.summary).toBe("summarized");
+ expect(sessionManager.getEntries().some((entry) => entry.type === "compaction")).toBe(true);
+ expect(warn).toHaveBeenCalledOnce();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("propagates the original error when the completed-compaction ledger write fails", async () => {
+ const { session } = await createCompactionSession();
+ await session.prompt("one");
+ await session.prompt("two");
+
+ const finishCompaction = vi.spyOn(session.semanticEdges, "finishCompaction").mockImplementation(() => {
+ throw new Error("ledger write failed");
+ });
+
+ await expect(session.compact()).rejects.toThrow("ledger write failed");
+
+ // The consumed ID is never finished a second time, so nothing masks the I/O error.
+ expect(finishCompaction).toHaveBeenCalledOnce();
+ expect(finishCompaction).toHaveBeenCalledWith(expect.any(String), "completed");
+ expect(ledgerFor(session).filter((event) => event.type === "compaction_finished")).toEqual([]);
+ });
+
+ it("fails the summary requests when compaction is aborted mid-summary", async () => {
+ const harness = await createHarness({
+ persistSession: true,
+ settings: { compaction: { keepRecentTokens: 1 } },
+ });
+ harnesses.push(harness);
+ const ledgerPath = join(harness.sessionManager.getSessionArtifactDir() ?? "", SEMANTIC_EDGES_LEDGER_FILENAME);
+
+ harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+ const preCompactionIds = startedRequestIds(readSemanticEdgeLedger(ledgerPath));
+
+ const abortingStep = () => {
+ harness.session.abortCompaction();
+ return fauxAssistantMessage("partial summary");
+ };
+ harness.setResponses([abortingStep, abortingStep]);
+ await expect(harness.session.compact()).rejects.toThrow("Compaction cancelled");
+
+ // Aborted summaries may be partial: they must never commit into the chain.
+ const events = readSemanticEdgeLedger(ledgerPath);
+ const summaryIds = startedRequestIds(events).filter((requestId) => !preCompactionIds.includes(requestId));
+ expect(summaryIds.length).toBeGreaterThanOrEqual(1);
+ const finished = events
+ .filter((event) => event.type === "request_finished")
+ .map((event) => (event.type === "request_finished" ? event.request_id : ""));
+ for (const summaryId of summaryIds) {
+ expect(finished).not.toContain(summaryId);
+ }
+ expect(events.filter((event) => event.type === "compaction_finished").at(-1)).toMatchObject({
+ status: "cancelled",
+ });
+
+ // The next turn continues from the PRE-compaction request.
+ harness.setResponses([fauxAssistantMessage("after")]);
+ await harness.session.prompt("after");
+ const finalEvents = readSemanticEdgeLedger(ledgerPath);
+ const afterId = startedRequestIds(finalEvents).at(-1);
+ const inboundEdges = deriveSemanticEdges([finalEvents]).edges.filter(
+ (edge) => edge.target_request_id === afterId,
+ );
+ expect(inboundEdges).toEqual([
+ { source_request_id: preCompactionIds.at(-1), target_request_id: afterId, type: "continuation" },
+ ]);
+ });
+
+ it("commits no summary slice when a racing split-turn sibling fails", async () => {
+ const harness = await createHarness({
+ persistSession: true,
+ settings: { compaction: { keepRecentTokens: 1 } },
+ });
+ harnesses.push(harness);
+ const ledgerPath = join(harness.sessionManager.getSessionArtifactDir() ?? "", SEMANTIC_EDGES_LEDGER_FILENAME);
+
+ harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+ const preCompactionIds = startedRequestIds(readSemanticEdgeLedger(ledgerPath));
+
+ // One slice succeeds on the wire well before its sibling rejects the whole compaction.
+ const successStep = () => fauxAssistantMessage("the summary");
+ const failingStep = async () => {
+ await sleep(25);
+ return fauxAssistantMessage("nope", { stopReason: "error", errorMessage: "summary slice failed" });
+ };
+ harness.setResponses([successStep, failingStep]);
+ await expect(harness.session.compact()).rejects.toThrow(/failed/);
+
+ // A failed compaction leaves NO committed summary request for edges to attach to.
+ const events = readSemanticEdgeLedger(ledgerPath);
+ const summaryIds = startedRequestIds(events).filter((requestId) => !preCompactionIds.includes(requestId));
+ expect(summaryIds).toHaveLength(2);
+ const finished = events
+ .filter((event) => event.type === "request_finished")
+ .map((event) => (event.type === "request_finished" ? event.request_id : ""));
+ for (const summaryId of summaryIds) {
+ expect(finished).not.toContain(summaryId);
+ }
+ expect(events.filter((event) => event.type === "compaction_finished").at(-1)).toMatchObject({
+ status: "failed",
+ });
+
+ // The next turn continues from the pre-compaction request, not the phantom slice.
+ harness.setResponses([fauxAssistantMessage("after")]);
+ await harness.session.prompt("after");
+ const finalEvents = readSemanticEdgeLedger(ledgerPath);
+ const afterId = startedRequestIds(finalEvents).at(-1);
+ expect(deriveSemanticEdges([finalEvents]).edges.filter((edge) => edge.target_request_id === afterId)).toEqual([
+ { source_request_id: preCompactionIds.at(-1), target_request_id: afterId, type: "continuation" },
+ ]);
+ });
+
+ it("mints a distinct request identity for each split-turn summary call", async () => {
+ const harness = await createHarness({
+ persistSession: true,
+ settings: { compaction: { keepRecentTokens: 1 } },
+ });
+ harnesses.push(harness);
+ const fauxModel = harness.getModel();
+ harness.session.modelRegistry.registerProvider(fauxModel.provider, {
+ baseUrl: fauxModel.baseUrl,
+ apiKey: "faux-key",
+ api: harness.faux.api,
+ headers: { "x-semantic-sentinel": "keep-me" },
+ models: harness.faux.models.map((registeredModel) => ({
+ id: registeredModel.id,
+ name: registeredModel.name,
+ api: registeredModel.api,
+ reasoning: registeredModel.reasoning,
+ input: registeredModel.input,
+ cost: registeredModel.cost,
+ contextWindow: registeredModel.contextWindow,
+ maxTokens: registeredModel.maxTokens,
+ baseUrl: registeredModel.baseUrl,
+ })),
+ });
+ const ledgerPath = join(harness.sessionManager.getSessionArtifactDir() ?? "", SEMANTIC_EDGES_LEDGER_FILENAME);
+
+ harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+
+ const captured: Array<Record<string, string> | undefined> = [];
+ const ledgerAtCall: SemanticEdgeLedgerEvent[][] = [];
+ const summaryStep = (_context: unknown, streamOptions: { headers?: Record<string, string> } | undefined) => {
+ captured.push(streamOptions?.headers);
+ ledgerAtCall.push(readSemanticEdgeLedger(ledgerPath));
+ return fauxAssistantMessage("the summary");
+ };
+ // A split-turn compaction makes two summary calls with DIFFERENT bodies:
+ // one shared Idempotency-Key would be rejected (or replayed) downstream.
+ harness.setResponses([summaryStep, summaryStep]);
+ await harness.session.compact();
+
+ expect(captured).toHaveLength(2);
+ const wireIds = captured.map((headers) => headers?.[MODEL_REQUEST_ID_HEADER]);
+ expect(wireIds[0]).toMatch(/^[0-9a-f]{32}$/);
+ expect(wireIds[1]).toMatch(/^[0-9a-f]{32}$/);
+ expect(wireIds[0]).not.toBe(wireIds[1]);
+ for (const [index, headers] of captured.entries()) {
+ expect(headers?.["x-semantic-sentinel"]).toBe("keep-me");
+ expect(headers?.[IDEMPOTENCY_KEY_HEADER]).toBe(wireIds[index]);
+ // Each request event was durable before its own provider call went out.
+ expect(ledgerAtCall[index]).toContainEqual(
+ expect.objectContaining({ type: "request_started", request_id: wireIds[index] }),
+ );
+ }
+
+ // Exactly one compaction edge, sourced at the last-committed summary slice.
+ harness.setResponses([fauxAssistantMessage("after")]);
+ await harness.session.prompt("after");
+ const events = readSemanticEdgeLedger(ledgerPath);
+ const committedSlices = events
+ .filter((event) => event.type === "request_finished")
+ .map((event) => (event.type === "request_finished" ? event.request_id : ""))
+ .filter((requestId) => wireIds.includes(requestId));
+ expect(committedSlices).toHaveLength(2);
+ const edges = deriveSemanticEdges([events]).edges;
+ const afterId = startedRequestIds(events).at(-1);
+ const compactionEdges = edges.filter((edge) => edge.type === "compaction");
+ expect(compactionEdges).toEqual([
+ { source_request_id: committedSlices[1], target_request_id: afterId, type: "compaction" },
+ ]);
+ // The continuation from that slice is suppressed in favor of the compaction edge.
+ expect(edges.filter((edge) => edge.target_request_id === afterId)).toHaveLength(1);
+ });
+});
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index aef6e10385..51ec6aee69 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -1008,6 +1008,67 @@ describe("daemon mode helpers", () => {
}
});
+ it("plumbs semantic-edge ancestry into daemon-hosted child session options", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lineage-ancestry-"));
+ try {
+ const sessionDir = join(tempDir, "sessions");
+ const parentManager = SessionManager.create(tempDir, sessionDir);
+ parentManager.newSession();
+ parentManager.appendSessionInfo("parent");
+ const parentSessionFile = parentManager.getSessionFile();
+ if (!parentSessionFile) throw new Error("Missing parent session file");
+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => ({
+ session: makeRuntimeSession(options.sessionManager),
+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<
+ ReturnType<CreateAgentSessionRuntimeFactory>
+ >["extensionsResult"],
+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<
+ ReturnType<CreateAgentSessionRuntimeFactory>
+ >["services"],
+ diagnostics: [],
+ }));
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },
+ createRuntime,
+ });
+ const internals = daemon as unknown as {
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ createRlmSubagentRuntime(
+ parentState: ActiveSessionState,
+ options: CreateRlmSubagentRuntimeOptions,
+ ): Promise<ActiveSessionState["runtime"]>;
+ };
+ const parentState = await internals.createRuntime({ type: "create", sessionPath: parentSessionFile });
+ const spawnedByRequestId = "b".repeat(32);
+ await internals.createRlmSubagentRuntime(parentState, {
+ parentSession: parentState.runtime.session,
+ id: "lineage-child",
+ prompt: "carry ancestry",
+ sessionName: "lineage-worker",
+ sessionDir: join(parentManager.getSessionArtifactDir()!, "lineage-child"),
+ model: { provider: "test", id: "model" } as Model<Api>,
+ thinkingLevel: "off",
+ serviceTier: null,
+ scopedModels: [],
+ activeToolNames: [],
+ customTools: [],
+ includeGoals: false,
+ includeCompactSkill: false,
+ rlmDepth: 1,
+ rlmMaxDepth: 4,
+ rlmParentNodeId: "lineage-child",
+ spawnedByRequestId,
+ });
+
+ const childCreate = createRuntime.mock.calls.at(-1)?.[0];
+ expect(childCreate?.sessionOptions).toMatchObject({
+ semanticParentSessionId: parentState.runtime.session.sessionId,
+ semanticSpawnedByRequestId: spawnedByRequestId,
+ });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
it("discovers a non-resident child left running in the persisted registry", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-orphan-running-child-"));
try {
diff --git a/packages/coding-agent/test/semantic-edges.test.ts b/packages/coding-agent/test/semantic-edges.test.ts
new file mode 100644
index 0000000000..c2938d94f5
--- /dev/null
+++ b/packages/coding-agent/test/semantic-edges.test.ts
@@ -0,0 +1,920 @@
+import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { StreamFn } from "@earendil-works/pi-agent-core";
+import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ deriveSemanticEdges,
+ hashTurnBody,
+ IDEMPOTENCY_KEY_HEADER,
+ MODEL_REQUEST_ID_HEADER,
+ modelRequestHeaders,
+ readSemanticEdgeLedger,
+ type SemanticEdgeLedgerEvent,
+ SemanticEdgeRecorder,
+ wrapStreamFnWithSemanticEdges,
+} from "../src/core/semantic-edges.js";
+
+describe("SemanticEdgeRecorder", () => {
+ let tempDir: string;
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-semantic-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(tempDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ function createRecorder(overrides: Partial<ConstructorParameters<typeof SemanticEdgeRecorder>[0]> = {}) {
+ return new SemanticEdgeRecorder({
+ ledgerPath: join(tempDir, "semantic-edges.jsonl"),
+ sessionId: "root-session",
+ ...overrides,
+ });
+ }
+
+ function ledger(): SemanticEdgeLedgerEvent[] {
+ return readSemanticEdgeLedger(join(tempDir, "semantic-edges.jsonl"));
+ }
+
+ it("emits both wire headers with one opaque uuid4-hex request ID", () => {
+ const recorder = createRecorder();
+ const requestId = recorder.startTurnRequest();
+ expect(requestId).toMatch(/^[0-9a-f]{32}$/);
+ // Literal names: the wire contract must survive a renamed production constant.
+ expect(modelRequestHeaders(requestId ?? "")).toEqual({
+ "X-ACP-Model-Request-ID": requestId,
+ "Idempotency-Key": requestId,
+ });
+ expect(MODEL_REQUEST_ID_HEADER).toBe("X-ACP-Model-Request-ID");
+ });
+
+ it("appends registration, request, and outcome events in order", () => {
+ const recorder = createRecorder();
+ const requestId = recorder.startTurnRequest();
+ recorder.finishRequest(requestId);
+ expect(ledger()).toEqual([
+ { type: "session_registered", session_id: "root-session" },
+ { type: "request_started", request_id: requestId, session_id: "root-session" },
+ { type: "request_finished", request_id: requestId },
+ ]);
+ expect(recorder.lastCommittedRequestId).toBe(requestId);
+ });
+
+ it("reuses a parked retry ID only for a byte-identical body and re-logs the start", () => {
+ const recorder = createRecorder();
+ const body = hashTurnBody({ provider: "p", id: "m" }, { messages: [{ role: "user", content: "hi" }] });
+ const failedId = recorder.startTurnRequest(body);
+ recorder.failRequest(failedId);
+ recorder.prepareTurnRetry();
+
+ // Same message count and roles but different content must not steal the key.
+ const sideBody = hashTurnBody(
+ { provider: "p", id: "m" },
+ { messages: [{ role: "user", content: "side question" }] },
+ );
+ const sideId = recorder.startTurnRequest(sideBody);
+ expect(sideId).not.toBe(failedId);
+
+ const retryId = recorder.startTurnRequest(body);
+ expect(retryId).toBe(failedId);
+ // The reused retry re-logs request_started so the fold re-claims returned edges.
+ const startEvents = ledger().filter((event) => event.type === "request_started");
+ expect(startEvents.map((event) => event.request_id)).toEqual([failedId, sideId, failedId]);
+ });
+
+ it("keys retry identity on model identity too", () => {
+ const recorder = createRecorder();
+ const messages = [{ role: "user", content: "hi" }];
+ const failedId = recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m1" }, { messages }));
+ recorder.prepareTurnRetry();
+ expect(recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m2" }, { messages }))).not.toBe(failedId);
+ });
+
+ it("keys retry identity on the provider too", () => {
+ const recorder = createRecorder();
+ const messages = [{ role: "user", content: "hi" }];
+ const failedId = recorder.startTurnRequest(hashTurnBody({ provider: "p1", id: "m" }, { messages }));
+ recorder.prepareTurnRetry();
+ expect(recorder.startTurnRequest(hashTurnBody({ provider: "p2", id: "m" }, { messages }))).not.toBe(failedId);
+ });
+
+ it("keys retry identity on the system prompt too", () => {
+ const recorder = createRecorder();
+ const messages = [{ role: "user", content: "hi" }];
+ const failedId = recorder.startTurnRequest(
+ hashTurnBody({ provider: "p", id: "m" }, { systemPrompt: "a", messages }),
+ );
+ recorder.prepareTurnRetry();
+ expect(
+ recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m" }, { systemPrompt: "b", messages })),
+ ).not.toBe(failedId);
+ });
+
+ it("keys retry identity on the tool set too", () => {
+ const recorder = createRecorder();
+ const messages = [{ role: "user", content: "hi" }];
+ const failedId = recorder.startTurnRequest(
+ hashTurnBody({ provider: "p", id: "m" }, { messages, tools: [{ name: "bash" }] }),
+ );
+ recorder.prepareTurnRetry();
+ // An extension toggling tools during backoff changes the wire body.
+ expect(recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m" }, { messages, tools: [] }))).not.toBe(
+ failedId,
+ );
+ });
+
+ it("keys retry identity on request-shaping options too", () => {
+ const recorder = createRecorder();
+ const messages = [{ role: "user", content: "hi" }];
+ const context = { messages };
+ const failedId = recorder.startTurnRequest(
+ hashTurnBody({ provider: "p", id: "m" }, context, { reasoning: "high" }),
+ );
+ recorder.prepareTurnRetry();
+ expect(
+ recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m" }, context, { reasoning: "low" })),
+ ).not.toBe(failedId);
+ });
+
+ it("hashes the body at request time, not at park time", () => {
+ const recorder = createRecorder();
+ const messages: Array<{ role: string; content: Array<{ type: string; text: string }> }> = [
+ { role: "user", content: [{ type: "text", text: "original" }] },
+ ];
+ const context = { systemPrompt: "s", messages };
+ const failedId = recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m" }, context));
+
+ // TOCTOU: the live message objects mutate between the call and the park.
+ messages[0]!.content[0]!.text = "mutated";
+ recorder.prepareTurnRetry();
+
+ const retryId = recorder.startTurnRequest(hashTurnBody({ provider: "p", id: "m" }, context));
+ expect(retryId).not.toBe(failedId);
+ });
+
+ it("mints a fresh ID when a compaction completed between failure and retry", () => {
+ const recorder = createRecorder();
+ const failedId = recorder.startTurnRequest("body-hash");
+ recorder.prepareTurnRetry();
+ const compaction = recorder.beginCompaction();
+ recorder.finishCompaction(compaction.compactionId, "completed");
+ expect(recorder.startTurnRequest("body-hash")).not.toBe(failedId);
+ });
+
+ it("keeps the parked ID across a failed compaction", () => {
+ const recorder = createRecorder();
+ const failedId = recorder.startTurnRequest("body-hash");
+ recorder.prepareTurnRetry();
+ const compaction = recorder.beginCompaction();
+ recorder.finishCompaction(compaction.compactionId, "failed");
+ expect(recorder.startTurnRequest("body-hash")).toBe(failedId);
+ });
+
+ it("clears a parked retry ID", () => {
+ const recorder = createRecorder();
+ const failedId = recorder.startTurnRequest("body-hash");
+ recorder.prepareTurnRetry();
+ recorder.clearTurnRetry();
+ expect(recorder.startTurnRequest("body-hash")).not.toBe(failedId);
+ });
+
+ it("never reuses a retry parked from a replayed ledger (body unknowable)", () => {
+ const first = createRecorder();
+ first.startTurnRequest("body-hash");
+
+ const resumed = createRecorder();
+ expect(resumed.lastTurnRequestId).toBe(first.lastTurnRequestId);
+ resumed.prepareTurnRetry();
+ expect(resumed.startTurnRequest("body-hash")).not.toBe(first.lastTurnRequestId);
+ });
+
+ it("never matches an undefined parked hash against an undefined call hash", () => {
+ const first = createRecorder();
+ first.startTurnRequest("body-hash");
+
+ const resumed = createRecorder();
+ resumed.prepareTurnRetry();
+ // Both sides unknown must still mint fresh; undefined === undefined is not identity.
+ expect(resumed.startTurnRequest(undefined)).not.toBe(first.lastTurnRequestId);
+ });
+
+ it("replays an existing ledger instead of re-registering on resume", () => {
+ const first = createRecorder();
+ const requestId = first.startTurnRequest();
+ first.finishRequest(requestId);
+
+ const resumed = createRecorder();
+ expect(resumed.lastTurnRequestId).toBe(requestId);
+ expect(resumed.lastCommittedRequestId).toBe(requestId);
+ expect(ledger().filter((event) => event.type === "session_registered")).toHaveLength(1);
+ });
+
+ it("does not treat a compaction summary request as the spawnable last turn", () => {
+ const recorder = createRecorder();
+ const turnId = recorder.startTurnRequest();
+ const compaction = recorder.beginCompaction();
+ recorder.startCompactionRequest(compaction.compactionId);
+ expect(recorder.lastTurnRequestId).toBe(turnId);
+
+ const resumed = createRecorder();
+ expect(resumed.lastTurnRequestId).toBe(turnId);
+ });
+
+ it("rejects finishing an unknown compaction", () => {
+ const recorder = createRecorder();
+ expect(() => recorder.finishCompaction("ghost", "completed")).toThrow(/unknown semantic-edge compaction/);
+ });
+
+ it("disables itself permanently after the first failed append", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const recorder = createRecorder();
+ const first = recorder.startTurnRequest();
+ expect(first).toBeDefined();
+
+ // appendFileSync on a directory fails even when running as root.
+ const path = join(tempDir, "semantic-edges.jsonl");
+ rmSync(path);
+ mkdirSync(path);
+
+ expect(recorder.startTurnRequest()).toBeUndefined();
+ expect(warn).toHaveBeenCalledOnce();
+
+ // Every later write is a silent no-op: no throws, no more warnings.
+ expect(recorder.startTurnRequest()).toBeUndefined();
+ recorder.finishRequest(first);
+ recorder.failRequest(first);
+ const compaction = recorder.beginCompaction();
+ expect(recorder.startCompactionRequest(compaction.compactionId)).toBeUndefined();
+ recorder.finishCompaction(compaction.compactionId, "completed");
+ recorder.recordChildReturned("child", first);
+ expect(warn).toHaveBeenCalledOnce();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("does not advance commit state when the append fails", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const recorder = createRecorder();
+ const requestId = recorder.startTurnRequest();
+
+ const path = join(tempDir, "semantic-edges.jsonl");
+ rmSync(path);
+ mkdirSync(path);
+
+ recorder.finishRequest(requestId);
+ // The commit never reached the ledger, so it must not become claimable.
+ expect(recorder.lastCommittedRequestId).toBeUndefined();
+ expect(warn).toHaveBeenCalledOnce();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("degrades to disabled when the ledger is unreadable at construction", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const path = join(tempDir, "semantic-edges.jsonl");
+ mkdirSync(path);
+ const recorder = createRecorder();
+ expect(recorder.startTurnRequest()).toBeUndefined();
+ expect(warn).toHaveBeenCalledOnce();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("tolerates a torn (unterminated) final line and repairs it on the first append only", () => {
+ const recorder = createRecorder();
+ recorder.startTurnRequest();
+ const path = join(tempDir, "semantic-edges.jsonl");
+ appendFileSync(path, '{"type":"request_started","request_id":"torn');
+ const tornBytes = readFileSync(path);
+
+ expect(readSemanticEdgeLedger(path)).toHaveLength(2);
+
+ // Construction (e.g. a viewer over a live writer's ledger) must not mutate the file.
+ const resumed = createRecorder();
+ expect(readFileSync(path).equals(tornBytes)).toBe(true);
+
+ const requestId = resumed.startTurnRequest();
+ const events = readSemanticEdgeLedger(path);
+ expect(events.filter((event) => event.type === "session_registered")).toHaveLength(1);
+ expect(events.at(-1)).toMatchObject({ type: "request_started", request_id: requestId });
+ // The torn line was truncated away, so the whole file parses again.
+ expect(events).toHaveLength(3);
+ });
+
+ it("readSemanticEdgeLedger never mutates the file", () => {
+ const recorder = createRecorder();
+ recorder.startTurnRequest();
+ const path = join(tempDir, "semantic-edges.jsonl");
+ appendFileSync(path, '{"type":"request_started","request_id":"torn');
+ const before = readFileSync(path);
+
+ readSemanticEdgeLedger(path);
+
+ expect(readFileSync(path).equals(before)).toBe(true);
+ });
+
+ it("readSemanticEdgeLedger never opens the ledger for writing", () => {
+ // A write-mode open would create the missing file instead of throwing.
+ const missing = join(tempDir, "missing.jsonl");
+ expect(() => readSemanticEdgeLedger(missing)).toThrow(/ENOENT/);
+ expect(existsSync(missing)).toBe(false);
+ });
+
+ it("applies torn-tail repair exactly once, not on every append", () => {
+ const recorder = createRecorder();
+ const originalId = recorder.startTurnRequest();
+ const path = join(tempDir, "semantic-edges.jsonl");
+ appendFileSync(path, '{"type":"request_started","request_id":"torn');
+
+ const resumed = createRecorder();
+ const firstId = resumed.startTurnRequest();
+ // A re-applied truncation here would chop the first appended event.
+ const secondId = resumed.startTurnRequest();
+
+ const requestIds = readSemanticEdgeLedger(path)
+ .filter((event) => event.type === "request_started")
+ .map((event) => (event.type === "request_started" ? event.request_id : ""));
+ expect(requestIds).toEqual([originalId, firstId, secondId]);
+ });
+
+ it("newline-terminates a valid unterminated final line before appending", () => {
+ const recorder = createRecorder();
+ const firstId = recorder.startTurnRequest();
+ const path = join(tempDir, "semantic-edges.jsonl");
+ const raw = readFileSync(path, "utf8");
+ rmSync(path);
+ appendFileSync(path, raw.slice(0, -1));
+
+ const resumed = createRecorder();
+ const secondId = resumed.startTurnRequest();
+ const requestIds = readSemanticEdgeLedger(path)
+ .filter((event) => event.type === "request_started")
+ .map((event) => (event.type === "request_started" ? event.request_id : ""));
+ expect(requestIds).toEqual([firstId, secondId]);
+ });
+
+ it("treats a newline-terminated malformed final line as corruption, not a torn append", () => {
+ const path = join(tempDir, "semantic-edges.jsonl");
+ const recorder = createRecorder();
+ recorder.startTurnRequest();
+ appendFileSync(path, '{"broken\n');
+ expect(() => readSemanticEdgeLedger(path)).toThrow(/corrupt semantic-edge ledger line 3/);
+ });
+
+ it("rejects mid-file ledger corruption loudly", () => {
+ const path = join(tempDir, "semantic-edges.jsonl");
+ const recorder = createRecorder();
+ recorder.startTurnRequest();
+ const lines = readFileSync(path, "utf8").trimEnd().split("\n");
+ lines[0] = '{"broken';
+ rmSync(path);
+ appendFileSync(path, `${lines.join("\n")}\n`);
+ expect(() => readSemanticEdgeLedger(path)).toThrow(/corrupt semantic-edge ledger line 1/);
+ });
+});
+
+describe("deriveSemanticEdges", () => {
+ let tempDir: string;
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-semantic-derive-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(tempDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ function recorderAt(name: string, options: { parentSessionId?: string; spawnedByRequestId?: string } = {}) {
+ return new SemanticEdgeRecorder({
+ ledgerPath: join(tempDir, name),
+ sessionId: name.replace(".jsonl", ""),
+ ...options,
+ });
+ }
+
+ function eventsAt(name: string): SemanticEdgeLedgerEvent[] {
+ return readSemanticEdgeLedger(join(tempDir, name));
+ }
+
+ /** The verifiers consumer rejects duplicate (source, target, type) tuples. */
+ function expectUniqueEdges(edges: Array<{ source_request_id: string; target_request_id: string; type: string }>) {
+ const seen = new Set<string>();
+ for (const edge of edges) {
+ const identity = `${edge.source_request_id}->${edge.target_request_id}:${edge.type}`;
+ expect(seen.has(identity), `duplicate semantic edge: ${identity}`).toBe(false);
+ seen.add(identity);
+ }
+ }
+
+ it("links a committed turn chain with continuation edges", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: r2, type: "continuation" },
+ ]);
+ });
+
+ it("defers the subagent_call edge to the child's first COMMITTED request", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+
+ const child = recorderAt("child.jsonl", { parentSessionId: "root", spawnedByRequestId: r1 });
+ const c1 = child.startTurnRequest();
+ child.failRequest(c1);
+ const c2 = child.startTurnRequest();
+ child.finishRequest(c2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl"), eventsAt("child.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: c2, type: "subagent_call" },
+ ]);
+ });
+
+ it("routes subagent_return to the parent's next committed request", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+
+ const child = recorderAt("child.jsonl", { parentSessionId: "root", spawnedByRequestId: r1 });
+ const c1 = child.startTurnRequest();
+ child.finishRequest(c1);
+
+ root.recordChildReturned("child", c1);
+ // A duplicate return claim for the same child is ignored.
+ root.recordChildReturned("child", c1);
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl"), eventsAt("child.jsonl")]).edges).toEqual([
+ { source_request_id: c1, target_request_id: r2, type: "subagent_return" },
+ { source_request_id: r1, target_request_id: r2, type: "continuation" },
+ { source_request_id: r1, target_request_id: c1, type: "subagent_call" },
+ ]);
+ });
+
+ it("emits a compaction edge and suppresses the continuation from the same summary", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const compaction = root.beginCompaction();
+ const s1 = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(s1);
+ root.finishCompaction(compaction.compactionId, "completed");
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: s1, type: "continuation" },
+ { source_request_id: s1, target_request_id: r2, type: "compaction" },
+ ]);
+ });
+
+ it("keys the compaction edge off the last-committed summary slice of a split turn", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const compaction = root.beginCompaction();
+ const sliceA = root.startCompactionRequest(compaction.compactionId);
+ const sliceB = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(sliceA);
+ root.finishRequest(sliceB);
+ root.finishCompaction(compaction.compactionId, "completed");
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: sliceA, type: "continuation" },
+ { source_request_id: r1, target_request_id: sliceB, type: "continuation" },
+ { source_request_id: sliceB, target_request_id: r2, type: "compaction" },
+ ]);
+ });
+
+ it("flushes pending edges once to the last-committed summary slice", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const child = recorderAt("child.jsonl", { parentSessionId: "root", spawnedByRequestId: r1 });
+ const c1 = child.startTurnRequest();
+ child.finishRequest(c1);
+ root.recordChildReturned("child", c1);
+
+ const compaction = root.beginCompaction();
+ const sliceA = root.startCompactionRequest(compaction.compactionId);
+ const sliceB = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(sliceA);
+ root.finishRequest(sliceB);
+ root.finishCompaction(compaction.compactionId, "completed");
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ // Slices carry only their continuations; the completed compaction flushes
+ // the pending subagent_return to its last-committed slice exactly once,
+ // and the post-compaction turn carries only the compaction edge.
+ const edges = deriveSemanticEdges([eventsAt("root.jsonl"), eventsAt("child.jsonl")]).edges;
+ expectUniqueEdges(edges);
+ expect(edges).toEqual([
+ { source_request_id: r1, target_request_id: sliceA, type: "continuation" },
+ { source_request_id: r1, target_request_id: sliceB, type: "continuation" },
+ { source_request_id: c1, target_request_id: sliceB, type: "subagent_return" },
+ { source_request_id: sliceB, target_request_id: r2, type: "compaction" },
+ { source_request_id: r1, target_request_id: c1, type: "subagent_call" },
+ ]);
+ });
+
+ it("keeps a pending return that a terminal completed compaction would otherwise strand", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const child = recorderAt("child.jsonl", { parentSessionId: "root", spawnedByRequestId: r1 });
+ const c1 = child.startTurnRequest();
+ child.finishRequest(c1);
+ root.recordChildReturned("child", c1);
+
+ // The completed compaction is the session's final activity: no post-turn exists.
+ const compaction = root.beginCompaction();
+ const s1 = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(s1);
+ root.finishCompaction(compaction.compactionId, "completed");
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl"), eventsAt("child.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: s1, type: "continuation" },
+ { source_request_id: c1, target_request_id: s1, type: "subagent_return" },
+ { source_request_id: r1, target_request_id: c1, type: "subagent_call" },
+ ]);
+ });
+
+ it("flushes a reclaimed continuation without duplicating the slice's own", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ // r2 fails: its reclaimed continuation from r1 sits in pending.
+ const r2 = root.startTurnRequest();
+ root.failRequest(r2);
+
+ const compaction = root.beginCompaction();
+ const s1 = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(s1);
+ root.finishCompaction(compaction.compactionId, "completed");
+
+ const edges = deriveSemanticEdges([eventsAt("root.jsonl")]).edges;
+ expectUniqueEdges(edges);
+ expect(edges).toEqual([{ source_request_id: r1, target_request_id: s1, type: "continuation" }]);
+ });
+
+ it("suppresses the generated continuation when a pending edge shares its source", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ // Back-to-back compactions: the first one's compaction edge is still
+ // pending (sourced at s1) when the second summary generates s1 -> s2.
+ const first = root.beginCompaction();
+ const s1 = root.startCompactionRequest(first.compactionId);
+ root.finishRequest(s1);
+ root.finishCompaction(first.compactionId, "completed");
+ const second = root.beginCompaction();
+ const s2 = root.startCompactionRequest(second.compactionId);
+ root.finishRequest(s2);
+ root.finishCompaction(second.compactionId, "completed");
+
+ const edges = deriveSemanticEdges([eventsAt("root.jsonl")]).edges;
+ expectUniqueEdges(edges);
+ expect(edges).toEqual([
+ { source_request_id: r1, target_request_id: s1, type: "continuation" },
+ { source_request_id: s1, target_request_id: s2, type: "compaction" },
+ ]);
+ });
+
+ it("emits no compaction edge when another request committed after the summary", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const compaction = root.beginCompaction();
+ const s1 = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(s1);
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+ root.finishCompaction(compaction.compactionId, "completed");
+ const r3 = root.startTurnRequest();
+ root.finishRequest(r3);
+
+ // The summary is no longer the session's last commit, so the gate holds.
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: s1, type: "continuation" },
+ { source_request_id: s1, target_request_id: r2, type: "continuation" },
+ { source_request_id: r2, target_request_id: r3, type: "continuation" },
+ ]);
+ });
+
+ it("emits no compaction edge when the compaction fails after a committed summary", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const compaction = root.beginCompaction();
+ const s1 = root.startCompactionRequest(compaction.compactionId);
+ root.finishRequest(s1);
+ root.finishCompaction(compaction.compactionId, "failed");
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ // Only a COMPLETED compaction may push the edge, even with a committed summary.
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: s1, type: "continuation" },
+ { source_request_id: s1, target_request_id: r2, type: "continuation" },
+ ]);
+ });
+
+ it("emits no compaction edge for a failed compaction and re-claims the pending continuation", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const compaction = root.beginCompaction();
+ const s1 = root.startCompactionRequest(compaction.compactionId);
+ root.failRequest(s1);
+ root.finishCompaction(compaction.compactionId, "failed");
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: r2, type: "continuation" },
+ ]);
+ });
+
+ it("emits no compaction edge for an extension-supplied compaction (no summary request)", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const compaction = root.beginCompaction();
+ root.finishCompaction(compaction.compactionId, "completed");
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: r2, type: "continuation" },
+ ]);
+ });
+
+ it("re-claims a failed request's edges on the next commit", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const r2 = root.startTurnRequest();
+ root.failRequest(r2);
+ const r3 = root.startTurnRequest();
+ root.finishRequest(r3);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r1, target_request_id: r3, type: "continuation" },
+ ]);
+ });
+
+ it("commits a retried request's edges exactly once under ID reuse", () => {
+ const root = recorderAt("root.jsonl");
+ const r0 = root.startTurnRequest();
+ root.finishRequest(r0);
+ const r1 = root.startTurnRequest("body-hash");
+ root.failRequest(r1);
+ root.prepareTurnRetry();
+ const retried = root.startTurnRequest("body-hash");
+ expect(retried).toBe(r1);
+ root.finishRequest(r1);
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([
+ { source_request_id: r0, target_request_id: r1, type: "continuation" },
+ ]);
+ });
+
+ it("tolerates an in-flight request at the ledger tail without edges or throws", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ root.startTurnRequest();
+
+ expect(deriveSemanticEdges([eventsAt("root.jsonl")]).edges).toEqual([]);
+ });
+
+ it("derives the same edges regardless of ledger order", () => {
+ const root = recorderAt("root.jsonl");
+ const r1 = root.startTurnRequest();
+ root.finishRequest(r1);
+ const child = recorderAt("child.jsonl", { parentSessionId: "root", spawnedByRequestId: r1 });
+ const c1 = child.startTurnRequest();
+ child.finishRequest(c1);
+ root.recordChildReturned("child", c1);
+ const r2 = root.startTurnRequest();
+ root.finishRequest(r2);
+
+ const forward = deriveSemanticEdges([eventsAt("root.jsonl"), eventsAt("child.jsonl")]).edges;
+ const reversed = deriveSemanticEdges([eventsAt("child.jsonl"), eventsAt("root.jsonl")]).edges;
+ expect(new Set(reversed.map((edge) => JSON.stringify(edge)))).toEqual(
+ new Set(forward.map((edge) => JSON.stringify(edge))),
+ );
+ expect(forward).toHaveLength(3);
+ });
+});
+
+describe("wrapStreamFnWithSemanticEdges", () => {
+ let tempDir: string;
+
+ beforeEach(() => {
+ tempDir = join(tmpdir(), `pi-semantic-wrap-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(tempDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ const model = { provider: "p", id: "m" } as Parameters<StreamFn>[0];
+ const context = { systemPrompt: "s", messages: [], tools: [] } as unknown as Parameters<StreamFn>[1];
+
+ function recorderIn(name: string): SemanticEdgeRecorder {
+ return new SemanticEdgeRecorder({ ledgerPath: join(tempDir, name), sessionId: name });
+ }
+
+ function message(stopReason: "stop" | "error" | "aborted") {
+ return {
+ role: "assistant",
+ content: [],
+ api: "a",
+ provider: "p",
+ model: "m",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason,
+ timestamp: Date.now(),
+ };
+ }
+
+ it("adds both wire headers on top of caller headers without dropping them", () => {
+ const recorder = recorderIn("a.jsonl");
+ const captured: Array<Record<string, string> | undefined> = [];
+ const inner: StreamFn = (_model, _context, options) => {
+ captured.push(options?.headers);
+ return createAssistantMessageEventStream();
+ };
+ const wrapped = wrapStreamFnWithSemanticEdges(inner, recorder);
+
+ wrapped(model, context, { headers: { "x-sentinel": "keep-me" } });
+
+ expect(captured).toHaveLength(1);
+ const headers = captured[0] ?? {};
+ expect(headers["x-sentinel"]).toBe("keep-me");
+ expect(headers[MODEL_REQUEST_ID_HEADER]).toMatch(/^[0-9a-f]{32}$/);
+ expect(headers[IDEMPOTENCY_KEY_HEADER]).toBe(headers[MODEL_REQUEST_ID_HEADER]);
+ expect(headers[MODEL_REQUEST_ID_HEADER]).toBe(recorder.lastTurnRequestId);
+ });
+
+ function outcomeHarness(name: string) {
+ const recorder = recorderIn(name);
+ const streams: Array<ReturnType<typeof createAssistantMessageEventStream>> = [];
+ const inner: StreamFn = () => {
+ const stream = createAssistantMessageEventStream();
+ streams.push(stream);
+ return stream;
+ };
+ const wrapped = wrapStreamFnWithSemanticEdges(inner, recorder);
+ const outcomes = () =>
+ readSemanticEdgeLedger(join(tempDir, name))
+ .filter((event) => event.type === "request_finished" || event.type === "request_failed")
+ .map((event) => event.type);
+ return { wrapped, streams, outcomes };
+ }
+
+ it("commits the request when its stream resolves with a stop", async () => {
+ const { wrapped, streams, outcomes } = outcomeHarness("stop.jsonl");
+ wrapped(model, context, undefined);
+ streams[0]!.push({ type: "done", reason: "stop", message: message("stop") as never });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(outcomes()).toEqual(["request_finished"]);
+ });
+
+ it("fails the request when its stream resolves with an error message", async () => {
+ const { wrapped, streams, outcomes } = outcomeHarness("error.jsonl");
+ wrapped(model, context, undefined);
+ streams[0]!.push({ type: "error", reason: "error", error: message("error") as never });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(outcomes()).toEqual(["request_failed"]);
+ });
+
+ it("fails the request when its stream resolves with an aborted message", async () => {
+ const { wrapped, streams, outcomes } = outcomeHarness("aborted.jsonl");
+ wrapped(model, context, undefined);
+ streams[0]!.push({ type: "error", reason: "aborted", error: message("aborted") as never });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(outcomes()).toEqual(["request_failed"]);
+ });
+
+ it("fails the request when the inner stream function returns a rejected promise", async () => {
+ const recorder = recorderIn("rejected.jsonl");
+ const inner: StreamFn = async () => {
+ throw new Error("transport rejected");
+ };
+ const wrapped = wrapStreamFnWithSemanticEdges(inner, recorder);
+
+ await expect(wrapped(model, context, undefined)).rejects.toThrow("transport rejected");
+
+ const rejectedOutcomes = readSemanticEdgeLedger(join(tempDir, "rejected.jsonl"))
+ .filter((event) => event.type === "request_finished" || event.type === "request_failed")
+ .map((event) => event.type);
+ expect(rejectedOutcomes).toEqual(["request_failed"]);
+ });
+ it("degrades to headerless calls when the ledger fails mid-flight", async () => {
+ const recorder = recorderIn("degrade.jsonl");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const unhandled: unknown[] = [];
+ const onUnhandled = (reason: unknown) => unhandled.push(reason);
+ process.on("unhandledRejection", onUnhandled);
+ try {
+ const captured: Array<Record<string, string> | undefined> = [];
+ const streams: Array<ReturnType<typeof createAssistantMessageEventStream>> = [];
+ const inner: StreamFn = (_model, _context, options) => {
+ captured.push(options?.headers);
+ const stream = createAssistantMessageEventStream();
+ streams.push(stream);
+ return stream;
+ };
+ const wrapped = wrapStreamFnWithSemanticEdges(inner, recorder);
+
+ const returned = wrapped(model, context, undefined) as ReturnType<typeof createAssistantMessageEventStream>;
+ expect(captured[0]?.[MODEL_REQUEST_ID_HEADER]).toBeDefined();
+
+ // The ledger breaks while the call is in flight; the outcome write disables the recorder.
+ rmSync(join(tempDir, "degrade.jsonl"));
+ mkdirSync(join(tempDir, "degrade.jsonl"));
+ streams[0]!.push({ type: "done", reason: "stop", message: message("stop") as never });
+
+ // The model call still resolves and the process never sees a rejection.
+ await expect(returned.result()).resolves.toMatchObject({ stopReason: "stop" });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(unhandled).toEqual([]);
+ expect(warn).toHaveBeenCalledOnce();
+
+ // Later calls carry no request ID: their request_started can never be durable.
+ wrapped(model, context, undefined);
+ expect(captured[1]?.[MODEL_REQUEST_ID_HEADER]).toBeUndefined();
+ expect(captured[1]?.[IDEMPOTENCY_KEY_HEADER]).toBeUndefined();
+ streams[1]!.push({ type: "done", reason: "stop", message: message("stop") as never });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(unhandled).toEqual([]);
+ expect(warn).toHaveBeenCalledOnce();
+ } finally {
+ process.off("unhandledRejection", onUnhandled);
+ warn.mockRestore();
+ }
+ });
+
+ it("fails the request when the inner stream function throws", () => {
+ const recorder = recorderIn("c.jsonl");
+ const inner: StreamFn = () => {
+ throw new Error("no transport");
+ };
+ const wrapped = wrapStreamFnWithSemanticEdges(inner, recorder);
+
+ expect(() => wrapped(model, context, undefined)).toThrow("no transport");
+ const events = readSemanticEdgeLedger(join(tempDir, "c.jsonl"));
+ expect(events.at(-1)).toMatchObject({ type: "request_failed" });
+ });
+
+ it("rebinding a wrapped streamFn attributes calls to the new recorder only", () => {
+ const parentRecorder = recorderIn("parent.jsonl");
+ const childRecorder = recorderIn("child.jsonl");
+ let innerCalls = 0;
+ const inner: StreamFn = () => {
+ innerCalls += 1;
+ return createAssistantMessageEventStream();
+ };
+ const parentWrapped = wrapStreamFnWithSemanticEdges(inner, parentRecorder);
+ const childWrapped = wrapStreamFnWithSemanticEdges(parentWrapped, childRecorder);
+
+ childWrapped(model, context, undefined);
+
+ expect(innerCalls).toBe(1);
+ expect(childRecorder.lastTurnRequestId).toBeDefined();
+ // A double-wrap would also mint a parent request for the child's call.
+ expect(parentRecorder.lastTurnRequestId).toBeUndefined();
+ expect(
+ readSemanticEdgeLedger(join(tempDir, "parent.jsonl")).filter((event) => event.type === "request_started"),
+ ).toHaveLength(0);
+ });
+});
diff --git a/packages/coding-agent/test/suite/agent-session-runtime.test.ts b/packages/coding-agent/test/suite/agent-session-runtime.test.ts
index c405ead4be..ead54cfe1f 100644
--- a/packages/coding-agent/test/suite/agent-session-runtime.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-runtime.test.ts
@@ -15,6 +15,7 @@ import {
} from "../../src/core/agent-session-runtime.js";
import { AuthStorage } from "../../src/core/auth-storage.js";
import type { SubagentRuntimeHost } from "../../src/core/rlm-runtime.js";
+import { readSemanticEdgeLedger, SEMANTIC_EDGES_LEDGER_FILENAME } from "../../src/core/semantic-edges.js";
import { SessionManager } from "../../src/core/session-manager.js";
import type {
ExtensionAPI,
@@ -416,6 +417,38 @@ describe("AgentSessionRuntime characterization", () => {
await runtime.deleteRlmSubagentRuntime("parent-agent-child", childRuntime.session);
});
+ it("plumbs semantic-edge ancestry into runtime-created child ledgers", async () => {
+ const { runtime, tempDir } = await createRuntimeForTest(() => {});
+ const spawnedByRequestId = "a".repeat(32);
+ const sessionDir = join(tempDir, "lineage-child");
+ const childRuntime = await runtime.createRlmSubagentRuntime({
+ parentSession: runtime.session,
+ id: "lineage-child",
+ prompt: "carry ancestry",
+ sessionName: "lineage-worker",
+ sessionDir,
+ model: runtime.session.model!,
+ thinkingLevel: "off",
+ serviceTier: null,
+ scopedModels: [],
+ activeToolNames: [],
+ customTools: [],
+ includeGoals: false,
+ includeCompactSkill: false,
+ rlmDepth: 1,
+ rlmMaxDepth: 2,
+ rlmParentNodeId: "lineage-child",
+ spawnedByRequestId,
+ });
+
+ expect(readSemanticEdgeLedger(join(sessionDir, SEMANTIC_EDGES_LEDGER_FILENAME))[0]).toMatchObject({
+ type: "session_registered",
+ parent_session_id: runtime.session.sessionId,
+ spawned_by_request_id: spawnedByRequestId,
+ });
+ await runtime.deleteRlmSubagentRuntime("lineage-child", childRuntime.session);
+ });
+
it("disposes hosted RLM children during session replacement", async () => {
const disposeRlmSubagentRuntimes = vi.fn(async () => {});
const host: SubagentRuntimeHost = {