Skip to content

Commit dcfd375

Browse files
committed
fix(server): harden Codex title repair
Bound session-index reads, preserve concurrent manual renames, recover fallback titles from imported history, and isolate repair failures.
1 parent 2b6a3c6 commit dcfd375

4 files changed

Lines changed: 482 additions & 44 deletions

File tree

‎apps/server/src/project/AgentSessionImporter.test.ts‎

Lines changed: 178 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -372,9 +372,36 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
372372
expect(result).toEqual({ importedCount: 1, skippedCount: 0 });
373373
expect(commands).toMatchObject([
374374
{
375-
type: "thread.meta.update",
375+
type: "thread.title.generate.complete",
376376
threadId,
377377
title: "Prototype MetaApi trade replication",
378+
expectedTitle: "<recommended_plugins>",
379+
expectedVersion: null,
380+
needsRefinement: false,
381+
},
382+
]);
383+
384+
commands.length = 0;
385+
expect(
386+
yield* runImport({
387+
scanner,
388+
engine,
389+
directory,
390+
snapshots: makeSnapshotsLayer({
391+
project: makeProject(),
392+
getThread: () =>
393+
Option.some({
394+
...makeProjectedThread({ source: "codex", imported: true }),
395+
title: "# AGENTS.md instructions for /tmp/project",
396+
}),
397+
}),
398+
}),
399+
).toEqual({ importedCount: 1, skippedCount: 0 });
400+
expect(commands).toMatchObject([
401+
{
402+
type: "thread.title.generate.complete",
403+
expectedTitle: "# AGENTS.md instructions for /tmp/project",
404+
title: "Prototype MetaApi trade replication",
378405
},
379406
]);
380407

@@ -390,6 +417,11 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
390417
Option.some({
391418
...makeProjectedThread({ source: "codex", imported: true }),
392419
title: "My custom thread title",
420+
titleState: {
421+
source: "manual",
422+
version: CommandId.make("manual-title"),
423+
needsRefinement: false,
424+
},
393425
}),
394426
}),
395427
}),
@@ -398,6 +430,151 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
398430
}),
399431
);
400432

433+
it.effect(
434+
"repairs a legacy title from imported history when the Codex index has no title",
435+
() =>
436+
Effect.gen(function* () {
437+
const thread = makeThread("codex");
438+
const source = makeThreadOutcome(thread).source;
439+
const threadId = ThreadId.make(
440+
`import:${source.providerInstanceId}:${source.providerSessionId}`,
441+
);
442+
const commands: Array<OrchestrationCommand> = [];
443+
const scanner = AgentSessionScanner.AgentSessionScanner.of({
444+
scan: Effect.die("unused"),
445+
recentThreads: () =>
446+
Stream.succeed({ _tag: "AlreadyImported", source, canonicalTitle: null }),
447+
});
448+
const engine = OrchestrationEngine.OrchestrationEngineService.of({
449+
dispatch: (command) => Effect.sync(() => ({ sequence: commands.push(command) })),
450+
readEvents: () => Stream.empty,
451+
readThreadEvents: () => Stream.empty,
452+
getThreadReplayStats: () => Effect.die("unused"),
453+
streamDomainEvents: Stream.empty,
454+
subscribeDomainEvents: Effect.succeed(Stream.empty),
455+
latestSequence: Effect.succeed(0),
456+
});
457+
const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
458+
upsert: () => Effect.die("unused"),
459+
getProvider: () => Effect.die("unused"),
460+
recordImportedTranscript: () => Effect.die("must not rewrite completed history"),
461+
getBinding: () => Effect.die("unused"),
462+
listThreadIds: () => Effect.die("unused"),
463+
listBindings: () => Effect.die("unused"),
464+
});
465+
const projected = makeProjectedThread({ source: "codex", imported: true });
466+
467+
const result = yield* runImport({
468+
scanner,
469+
engine,
470+
directory,
471+
snapshots: makeSnapshotsLayer({
472+
project: makeProject(),
473+
getThread: () =>
474+
Option.some({
475+
...projected,
476+
title: "<user_instructions>",
477+
messages: [
478+
{
479+
...projected.messages[0]!,
480+
text: "<user_instructions>\nInternal setup instructions",
481+
},
482+
{
483+
...projected.messages[0]!,
484+
id: MessageId.make("user-followup"),
485+
text: "Do not use this follow-up",
486+
},
487+
{
488+
...projected.messages[0]!,
489+
id: MessageId.make(`${threadId}:000001`),
490+
text: "Recovered from imported history",
491+
},
492+
],
493+
}),
494+
}),
495+
});
496+
497+
expect(result).toEqual({ importedCount: 1, skippedCount: 0 });
498+
expect(commands).toMatchObject([
499+
{
500+
type: "thread.title.generate.complete",
501+
threadId,
502+
expectedTitle: "<user_instructions>",
503+
title: "Recovered from imported history",
504+
needsRefinement: false,
505+
},
506+
]);
507+
}),
508+
);
509+
510+
it.effect("records an existing import when Codex title repair fails", () =>
511+
Effect.gen(function* () {
512+
const thread = makeThread("codex");
513+
const outcome = makeThreadOutcome(thread);
514+
const threadId = ThreadId.make(
515+
`import:${thread.providerInstanceId}:${thread.providerSessionId}`,
516+
);
517+
let recorded = 0;
518+
const scanner = AgentSessionScanner.AgentSessionScanner.of({
519+
scan: Effect.die("unused"),
520+
recentThreads: () => Stream.succeed(outcome),
521+
});
522+
const engine = OrchestrationEngine.OrchestrationEngineService.of({
523+
dispatch: (command) =>
524+
command.type === "thread.title.generate.complete"
525+
? Effect.fail(
526+
new OrchestrationCommandInvariantError({
527+
commandType: command.type,
528+
detail: "Temporary title repair failure.",
529+
}),
530+
)
531+
: Effect.die("must not dispatch another command"),
532+
readEvents: () => Stream.empty,
533+
readThreadEvents: () => Stream.empty,
534+
getThreadReplayStats: () => Effect.die("unused"),
535+
streamDomainEvents: Stream.empty,
536+
subscribeDomainEvents: Effect.succeed(Stream.empty),
537+
latestSequence: Effect.succeed(0),
538+
});
539+
const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
540+
upsert: () => Effect.die("must not replace the existing binding"),
541+
getProvider: () => Effect.die("unused"),
542+
recordImportedTranscript: () => Effect.sync(() => void (recorded += 1)),
543+
getBinding: () =>
544+
Effect.succeed(
545+
Option.some({
546+
threadId,
547+
provider: ProviderDriverKind.make("codex"),
548+
providerInstanceId: ProviderInstanceId.make("codex"),
549+
status: "stopped" as const,
550+
resumeCursor: { threadId: thread.providerSessionId },
551+
runtimeMode: "full-access" as const,
552+
runtimePayload: { cwd: WORKSPACE_ROOT },
553+
}),
554+
),
555+
listThreadIds: () => Effect.die("unused"),
556+
listBindings: () => Effect.die("unused"),
557+
});
558+
559+
const result = yield* runImport({
560+
scanner,
561+
engine,
562+
directory,
563+
snapshots: makeSnapshotsLayer({
564+
project: makeProject(),
565+
getThread: () =>
566+
Option.some({
567+
...makeProjectedThread({ source: "codex", imported: true }),
568+
title: "<recommended_plugins>",
569+
}),
570+
}),
571+
});
572+
573+
expect(result).toEqual({ importedCount: 1, skippedCount: 0 });
574+
expect(recorded).toBe(1);
575+
}),
576+
);
577+
401578
it.effect("counts scanner skips without writing a thread or binding", () =>
402579
Effect.gen(function* () {
403580
const scanner = AgentSessionScanner.AgentSessionScanner.of({

‎apps/server/src/project/AgentSessionImporter.ts‎

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,14 +70,26 @@ function hasImportedHistory(thread: OrchestrationThread): boolean {
7070
return thread.messages.some((message) => isImportedAgentSessionMessageId(message.id));
7171
}
7272

73+
/** Identify titles produced by the old first-line Codex import fallback. */
7374
function hasLegacyCodexContextTitle(title: string): boolean {
7475
return (
7576
title === "<recommended_plugins>" ||
76-
title === "# AGENTS.md instructions" ||
77-
title === "<environment_context>"
77+
title === "<environment_context>" ||
78+
title === "<user_instructions>" ||
79+
/^# AGENTS\.md instructions(?:\s|$)/.test(title)
7880
);
7981
}
8082

83+
/** Recover a fallback title from the imported user messages already in the projection. */
84+
function deriveImportedCodexTitle(thread: OrchestrationThread): string | null {
85+
for (const message of thread.messages) {
86+
if (message.role !== "user" || !isImportedAgentSessionMessageId(message.id)) continue;
87+
const title = AgentSessionScanner.deriveImportedThreadTitle(message.text, "codex");
88+
if (title !== null) return title;
89+
}
90+
return null;
91+
}
92+
8193
function hasImportBlockingActivity(
8294
thread: OrchestrationThread,
8395
importedHistoryPresent: boolean,
@@ -146,21 +158,27 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
146158

147159
const repairImportedCodexTitle = Effect.fn("repairImportedCodexTitle")(function* (
148160
threadId: ThreadId,
149-
canonicalTitle: string,
161+
canonicalTitle: string | null,
150162
) {
151163
const existingThread = yield* snapshots.getThreadDetailById(threadId);
164+
if (Option.isNone(existingThread)) return;
165+
const existingTitle = existingThread.value.title;
166+
const replacementTitle = canonicalTitle ?? deriveImportedCodexTitle(existingThread.value);
152167
if (
153-
Option.isNone(existingThread) ||
154-
!hasLegacyCodexContextTitle(existingThread.value.title) ||
155-
existingThread.value.title === canonicalTitle
168+
replacementTitle === null ||
169+
!hasLegacyCodexContextTitle(existingTitle) ||
170+
existingTitle === replacementTitle
156171
) {
157172
return;
158173
}
159174
yield* engine.dispatch({
160-
type: "thread.meta.update",
175+
type: "thread.title.generate.complete",
161176
commandId: CommandId.make(yield* crypto.randomUUIDv4),
162177
threadId,
163-
title: canonicalTitle,
178+
title: replacementTitle,
179+
expectedTitle: existingTitle,
180+
expectedVersion: existingThread.value.titleState?.version ?? null,
181+
needsRefinement: false,
164182
});
165183
});
166184

@@ -175,7 +193,7 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
175193
`import:${outcome.source.providerInstanceId}:${outcome.source.providerSessionId}`,
176194
);
177195
if (outcome._tag === "AlreadyImported") {
178-
if (outcome.source.provider === "codex" && outcome.canonicalTitle !== null) {
196+
if (outcome.source.provider === "codex") {
179197
yield* repairImportedCodexTitle(threadId, outcome.canonicalTitle).pipe(
180198
Effect.catch((cause) =>
181199
Effect.logWarning("Could not repair an imported Codex thread title", {
@@ -238,7 +256,14 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
238256
Option.isSome(existingBinding)
239257
) {
240258
if (thread.source === "codex") {
241-
yield* repairImportedCodexTitle(threadId, thread.title);
259+
yield* repairImportedCodexTitle(threadId, thread.title).pipe(
260+
Effect.catch((cause) =>
261+
Effect.logWarning("Could not repair an imported Codex thread title", {
262+
threadId,
263+
cause,
264+
}),
265+
),
266+
);
242267
}
243268
yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
244269
return true;

0 commit comments

Comments
 (0)