Skip to content

Commit 3dc3370

Browse files
authored
fix(copilot): keep tool transcript groups structurally complete (#114403)
* refactor(copilot): make SQLite own transcripts * fix(copilot): harden transcript event projection * test(copilot): tighten transcript journal types * fix(copilot): retain unmatched usage metadata * refactor(copilot): commit tool groups atomically * fix(copilot): break journal bridge import cycle * fix(copilot): preserve grouped transcript replay * test(copilot): cover opaque replay state * fix(copilot): invalidate lossy transcript replay * fix(copilot): guard transcript rewrite topology * fix(copilot): drain transcript finalization * fix(copilot): preserve resumed session history * fix(copilot): dedupe replayed transcript snapshots * fix(copilot): isolate transcript write hooks * fix(copilot): track staged transcript identities * fix(copilot): isolate ephemeral transcript events * fix(copilot): coalesce assistant snapshots * fix(copilot): invalidate unprojected SDK context * fix(copilot): guard resumed transcript replay * fix(plugin-sdk): expose strict transcript append * fix(copilot): persist journal provenance safely * fix(copilot): separate live and durable deltas * fix(copilot): require durable projection ownership * fix(copilot): preserve strict append typing * fix(copilot): gate deferred session deletion * fix(copilot): preserve transcript replay identity * fix(copilot): retain cited replay history * fix(copilot): require complete replay provenance * fix(copilot): reject ambiguous assistant snapshots * fix(copilot): return latest assistant snapshot * chore(copilot): align transcript lint gates * test(lint): cover Copilot line budgets * test(ci): dedupe Codex prewarm shard
1 parent bbc73c3 commit 3dc3370

26 files changed

Lines changed: 3882 additions & 1275 deletions

‎.oxlintrc.json‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,18 @@
362362
"rules": {
363363
"max-lines": ["error", { "max": 1000, "skipBlankLines": true, "skipComments": true }]
364364
}
365+
},
366+
{
367+
"files": ["extensions/copilot/src/event-bridge.ts"],
368+
"rules": {
369+
"max-lines": ["error", { "max": 950, "skipBlankLines": true, "skipComments": true }]
370+
}
371+
},
372+
{
373+
"files": ["extensions/copilot/src/attempt-transcript-journal.test.ts"],
374+
"rules": {
375+
"max-lines": ["error", { "max": 1200, "skipBlankLines": true, "skipComments": true }]
376+
}
365377
}
366378
]
367379
}

‎extensions/copilot/harness.test.ts‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -947,7 +947,7 @@ describe("createCopilotAgentHarness", () => {
947947
sdkSessionId: "sdk-sess-warm",
948948
pooledClient: { key: TEST_POOL_KEY, client },
949949
});
950-
return ATTEMPT_RESULT;
950+
return { ...ATTEMPT_RESULT, journalValidated: true, sdkSessionId: "sdk-sess-warm" };
951951
});
952952
const harness = createCopilotAgentHarness({ pool });
953953

@@ -956,13 +956,46 @@ describe("createCopilotAgentHarness", () => {
956956

957957
expect(mocks.runCopilotAttempt).toHaveBeenCalledTimes(2);
958958
const secondCallParams = mocks.runCopilotAttempt.mock.calls[1]?.[0] as {
959-
initialReplayState?: { sdkSessionId?: string; replayInvalid?: boolean };
959+
initialReplayState?: {
960+
journalValidated?: boolean;
961+
sdkSessionId?: string;
962+
replayInvalid?: boolean;
963+
};
960964
};
961965
expect(secondCallParams.initialReplayState?.sdkSessionId).toBe("sdk-sess-warm");
966+
expect(secondCallParams.initialReplayState?.journalValidated).toBe(true);
962967
// Must not synthesize a replayInvalid signal: undefined → resumable.
963968
expect(secondCallParams.initialReplayState?.replayInvalid).toBeUndefined();
964969
});
965970

971+
it("clears journal provenance before a resumed attempt and restores it after validation", async () => {
972+
const pool = makePoolMock();
973+
const client = createMockCopilotClient({ deleteSession: vi.fn() });
974+
const sessionStore = makeSessionStoreMock();
975+
let call = 0;
976+
mocks.runCopilotAttempt.mockImplementation(async (_params, deps) => {
977+
call += 1;
978+
deps.onSessionEstablished?.({
979+
sdkSessionId: "sdk-sess-provenance",
980+
pooledClient: { key: TEST_POOL_KEY, client },
981+
});
982+
if (call === 2) {
983+
expect(sessionStore.entries.get("oc-sess-reuse")?.journalVersion).toBeUndefined();
984+
}
985+
return {
986+
...ATTEMPT_RESULT,
987+
journalValidated: true,
988+
sdkSessionId: "sdk-sess-provenance",
989+
};
990+
});
991+
const harness = createCopilotAgentHarness({ pool, sessionStore: sessionStore.store });
992+
993+
await harness.runAttempt(makeAttemptParams({ runId: "t1" }));
994+
await harness.runAttempt(makeAttemptParams({ runId: "t2" }));
995+
996+
expect(sessionStore.entries.get("oc-sess-reuse")?.journalVersion).toBe(1);
997+
});
998+
966999
it("blocks reuse while timed-out compaction is pending, then resumes after completion", async () => {
9671000
const pool = makePoolMock();
9681001
const sessionStore = makeSessionStoreMock();
@@ -1409,9 +1442,10 @@ describe("createCopilotAgentHarness", () => {
14091442
}),
14101443
);
14111444
const secondCallParams = mocks.runCopilotAttempt.mock.calls[1]?.[0] as {
1412-
initialReplayState?: { sdkSessionId?: string };
1445+
initialReplayState?: { journalValidated?: boolean; sdkSessionId?: string };
14131446
};
14141447
expect(secondCallParams.initialReplayState?.sdkSessionId).toBe("sdk-sess-sqlite");
1448+
expect(secondCallParams.initialReplayState?.journalValidated).toBeUndefined();
14151449
});
14161450

14171451
it("persists BYOK session compatibility with endpoint fingerprints instead of raw URLs", async () => {

‎extensions/copilot/harness.ts‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ interface CreateCopilotAgentHarnessOptions {
4444
}
4545

4646
interface TrackedSession {
47+
journalVersion?: 1;
4748
sdkSessionId: string;
4849
client: CopilotClient;
4950
clientOptions: ClientCreateOptions;
@@ -91,6 +92,7 @@ interface CopilotHistoryCompactSession {
9192

9293
export type CopilotSessionBinding = {
9394
schemaVersion: 2;
95+
journalVersion?: 1;
9496
sdkSessionId: string;
9597
compatKey: string;
9698
compactKey: string;
@@ -107,7 +109,10 @@ type LegacyCopilotSessionBinding = {
107109
updatedAt: number;
108110
};
109111

110-
type CopilotAttemptSessionBinding = Pick<CopilotSessionBinding, "compatKey" | "sdkSessionId">;
112+
type CopilotAttemptSessionBinding = Pick<
113+
CopilotSessionBinding,
114+
"compatKey" | "journalVersion" | "sdkSessionId"
115+
>;
111116
type DeferredCompactionCleanupOutcome = "aborted" | "completed" | "deadline";
112117
type DeferredCompactionCleanup = {
113118
abort: () => void;
@@ -160,6 +165,7 @@ function normalizeBinding(
160165
value.compatKey.trim() === "" ||
161166
typeof value.compactKey !== "string" ||
162167
value.compactKey.trim() === "" ||
168+
(value.journalVersion !== undefined && value.journalVersion !== 1) ||
163169
(value.authMode !== "gitHubToken" &&
164170
value.authMode !== "byok" &&
165171
value.authMode !== "useLoggedInUser") ||
@@ -175,6 +181,7 @@ function normalizeBinding(
175181
}
176182
return {
177183
schemaVersion: 2,
184+
...(value.journalVersion === 1 ? { journalVersion: 1 as const } : {}),
178185
sdkSessionId: value.sdkSessionId.trim(),
179186
compatKey: value.compatKey,
180187
compactKey: value.compactKey,
@@ -704,12 +711,13 @@ export function createCopilotAgentHarness(
704711
? undefined
705712
: lookupStoredBinding(options?.sessionStore, openclawSessionId)
706713
: undefined;
707-
const resumableSessionId =
714+
const resumableBinding =
708715
tracked && tracked.compatKey === currentCompatKey
709-
? tracked.sdkSessionId
716+
? tracked
710717
: !tracked && stored && stored.compatKey === currentCompatKey
711-
? stored.sdkSessionId
718+
? stored
712719
: undefined;
720+
const resumableSessionId = resumableBinding?.sdkSessionId;
713721
if (operation === "settled-tool-finalization" && !resumableSessionId) {
714722
throw new Error(
715723
"[copilot] cannot safely finalize a settled tool turn without its compatible SDK session",
@@ -739,15 +747,19 @@ export function createCopilotAgentHarness(
739747
// still requiring the exact compatible native session above.
740748
initialReplayState:
741749
operation === "settled-tool-finalization"
742-
? { sdkSessionId: resumableSessionId }
750+
? {
751+
...(resumableBinding?.journalVersion === 1 ? { journalValidated: true } : {}),
752+
sdkSessionId: resumableSessionId,
753+
}
743754
: {
744755
...params.initialReplayState,
756+
...(resumableBinding?.journalVersion === 1 ? { journalValidated: true } : {}),
745757
sdkSessionId: resumableSessionId,
746758
},
747759
} as AgentHarnessAttemptParams)
748760
: params;
749761

750-
return runCopilotAttempt(effectiveParams, {
762+
const result = await runCopilotAttempt(effectiveParams, {
751763
pool,
752764
...(operation === "settled-tool-finalization" ? { operation } : {}),
753765
onSessionEstablished:
@@ -835,6 +847,32 @@ export function createCopilotAgentHarness(
835847
}
836848
: undefined,
837849
});
850+
if (operation === "attempt" && openclawSessionId) {
851+
const attemptResult = result as AgentHarnessAttemptResult & {
852+
journalValidated?: boolean;
853+
sdkSessionId?: string;
854+
};
855+
const sdkSessionId = attemptResult.sdkSessionId;
856+
const trackedSession = trackedSessions.get(openclawSessionId);
857+
if (sdkSessionId && trackedSession?.sdkSessionId === sdkSessionId) {
858+
const { journalVersion: _journalVersion, ...baseTracked } = trackedSession;
859+
const nextTracked: TrackedSession = {
860+
...baseTracked,
861+
...(attemptResult.journalValidated ? { journalVersion: 1 } : {}),
862+
};
863+
trackedSessions.set(openclawSessionId, nextTracked);
864+
registerStoredBinding(options?.sessionStore, openclawSessionId, {
865+
schemaVersion: 2,
866+
...(attemptResult.journalValidated ? { journalVersion: 1 } : {}),
867+
sdkSessionId,
868+
compatKey: nextTracked.compatKey,
869+
compactKey: nextTracked.compactKey,
870+
...sessionAuthFields(nextTracked),
871+
updatedAt: Date.now(),
872+
});
873+
}
874+
}
875+
return result;
838876
})();
839877
inFlight.add(attemptPromise);
840878
try {

‎extensions/copilot/src/attempt-cleanup.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export function deferBackgroundCompactionCleanup(params: {
5454
pool: CopilotClientPool;
5555
cleanupByokProxy?: () => Promise<void>;
5656
cleanupToolBridge?: () => void;
57+
deleteSessionOnIncompleteCleanup: boolean;
5758
finalizeNativeSubagents?: () => void;
5859
sdkSessionId?: string;
5960
session: SessionLike;
@@ -81,7 +82,11 @@ export function deferBackgroundCompactionCleanup(params: {
8182
} catch {}
8283
params.cleanupToolBridge?.();
8384
await params.cleanupByokProxy?.();
84-
if (outcome !== "completed" && params.sdkSessionId) {
85+
if (
86+
outcome !== "completed" &&
87+
params.deleteSessionOnIncompleteCleanup &&
88+
params.sdkSessionId
89+
) {
8590
try {
8691
await params.handle.client.deleteSession(params.sdkSessionId);
8792
} catch {}

‎extensions/copilot/src/attempt-config.ts‎

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,19 @@ export function createResult(
3030
params: AttemptParamsLike,
3131
state: {
3232
aborted?: boolean;
33+
assistantTranscriptOwned?: boolean;
34+
assistantTranscriptIdempotencyKey?: string;
3335
assistantTexts?: string[];
3436
currentAttemptAssistant?: AssistantMessage;
3537
currentAttemptCompletedAssistant?: AssistantMessage;
3638
downgradedFromResume?: boolean;
3739
externalAbort?: boolean;
3840
itemLifecycle?: { activeCount: number; completedCount: number; startedCount: number };
3941
lastAssistant?: AssistantMessage;
42+
journalValidated?: boolean;
4043
lastToolError?: AgentHarnessAttemptResult["lastToolError"];
4144
messagesSnapshot: AgentMessage[];
45+
nativeReplayInvalid?: boolean;
4246
now: () => number;
4347
promptError: Error | undefined;
4448
resumeFailureRecovered?: boolean;
@@ -52,13 +56,21 @@ export function createResult(
5256
},
5357
): AttemptResultWithSdkSessionId {
5458
const promptError = state.promptError;
59+
const transcriptPersistenceFailed =
60+
(promptError as PromptErrorWithCode | undefined)?.code === "transcript_persistence_failed";
5561
const timedOut = state.timedOut === true;
5662
const toolMetas = state.toolMetas ?? [];
5763
const replayMetadata =
5864
params.operation === "settled-tool-finalization"
59-
? { hadPotentialSideEffects: false, replaySafe: true }
65+
? {
66+
hadPotentialSideEffects: false,
67+
replaySafe: state.nativeReplayInvalid !== true && !transcriptPersistenceFailed,
68+
}
6069
: computeReplayMetadata({
61-
priorReplayInvalid: params.initialReplayState?.replayInvalid,
70+
priorReplayInvalid:
71+
params.initialReplayState?.replayInvalid === true ||
72+
state.nativeReplayInvalid === true ||
73+
transcriptPersistenceFailed,
6274
priorHadPotentialSideEffects: params.initialReplayState?.hadPotentialSideEffects,
6375
thisAttemptTimedOut: timedOut,
6476
thisAttemptHadPotentialSideEffects: copilotToolMetasHavePotentialSideEffects(toolMetas),
@@ -82,7 +94,16 @@ export function createResult(
8294
promptError !== undefined ? withPromptFailure(interruption, promptError) : interruption;
8395
return {
8496
terminal,
97+
...(state.assistantTranscriptOwned
98+
? {
99+
assistantTranscriptOwned: true,
100+
...(state.assistantTranscriptIdempotencyKey
101+
? { assistantTranscriptIdempotencyKey: state.assistantTranscriptIdempotencyKey }
102+
: {}),
103+
}
104+
: {}),
85105
...(state.sdkSessionId ? { sdkSessionId: state.sdkSessionId } : {}),
106+
...(state.journalValidated !== undefined ? { journalValidated: state.journalValidated } : {}),
86107
assistantTexts: state.assistantTexts ?? [],
87108
attemptUsage: state.usage,
88109
cloudCodeAssistFormatError: false,
@@ -334,36 +355,6 @@ export function createSystemMessageContent(
334355
export function isRawCopilotModelRun(params: AttemptParamsLike): boolean {
335356
return params.modelRun === true || params.promptMode === "none";
336357
}
337-
export function readTailUserText(messages: AgentMessage[]): string | undefined {
338-
const tail = messages[messages.length - 1];
339-
if (!tail || tail.role !== "user") {
340-
return undefined;
341-
}
342-
const content = (tail as { content?: unknown }).content;
343-
if (typeof content === "string") {
344-
return content;
345-
}
346-
if (Array.isArray(content)) {
347-
for (const part of content) {
348-
if (part && typeof part === "object" && (part as { type?: unknown }).type === "text") {
349-
const text = (part as { text?: unknown }).text;
350-
if (typeof text === "string" && text.length > 0) {
351-
return text;
352-
}
353-
}
354-
}
355-
}
356-
return undefined;
357-
}
358-
export function hasMirrorIdentity(message: AgentMessage): boolean {
359-
const record = message as unknown as { __openclaw?: unknown };
360-
const meta = record["__openclaw"];
361-
if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
362-
return false;
363-
}
364-
const id = (meta as Record<string, unknown>).mirrorIdentity;
365-
return typeof id === "string" && id.length > 0;
366-
}
367358
export function readString(value: unknown): string | undefined {
368359
return typeof value === "string" && value.length > 0 ? value : undefined;
369360
}

0 commit comments

Comments
 (0)