Skip to content

Commit 87dcacc

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 51121d5 commit 87dcacc

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
@@ -373,9 +373,36 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
373373
expect(result).toEqual({ importedCount: 1, skippedCount: 0 });
374374
expect(commands).toMatchObject([
375375
{
376-
type: "thread.meta.update",
376+
type: "thread.title.generate.complete",
377377
threadId,
378378
title: "Prototype MetaApi trade replication",
379+
expectedTitle: "<recommended_plugins>",
380+
expectedVersion: null,
381+
needsRefinement: false,
382+
},
383+
]);
384+
385+
commands.length = 0;
386+
expect(
387+
yield* runImport({
388+
scanner,
389+
engine,
390+
directory,
391+
snapshots: makeSnapshotsLayer({
392+
project: makeProject(),
393+
getThread: () =>
394+
Option.some({
395+
...makeProjectedThread({ source: "codex", imported: true }),
396+
title: "# AGENTS.md instructions for /tmp/project",
397+
}),
398+
}),
399+
}),
400+
).toEqual({ importedCount: 1, skippedCount: 0 });
401+
expect(commands).toMatchObject([
402+
{
403+
type: "thread.title.generate.complete",
404+
expectedTitle: "# AGENTS.md instructions for /tmp/project",
405+
title: "Prototype MetaApi trade replication",
379406
},
380407
]);
381408

@@ -391,6 +418,11 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
391418
Option.some({
392419
...makeProjectedThread({ source: "codex", imported: true }),
393420
title: "My custom thread title",
421+
titleState: {
422+
source: "manual",
423+
version: CommandId.make("manual-title"),
424+
needsRefinement: false,
425+
},
394426
}),
395427
}),
396428
}),
@@ -399,6 +431,151 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
399431
}),
400432
);
401433

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

148160
const repairImportedCodexTitle = Effect.fn("repairImportedCodexTitle")(function* (
149161
threadId: ThreadId,
150-
canonicalTitle: string,
162+
canonicalTitle: string | null,
151163
) {
152164
const existingThread = yield* snapshots.getThreadDetailById(threadId);
165+
if (Option.isNone(existingThread)) return;
166+
const existingTitle = existingThread.value.title;
167+
const replacementTitle = canonicalTitle ?? deriveImportedCodexTitle(existingThread.value);
153168
if (
154-
Option.isNone(existingThread) ||
155-
!hasLegacyCodexContextTitle(existingThread.value.title) ||
156-
existingThread.value.title === canonicalTitle
169+
replacementTitle === null ||
170+
!hasLegacyCodexContextTitle(existingTitle) ||
171+
existingTitle === replacementTitle
157172
) {
158173
return;
159174
}
160175
yield* engine.dispatch({
161-
type: "thread.meta.update",
176+
type: "thread.title.generate.complete",
162177
commandId: CommandId.make(yield* crypto.randomUUIDv4),
163178
threadId,
164-
title: canonicalTitle,
179+
title: replacementTitle,
180+
expectedTitle: existingTitle,
181+
expectedVersion: existingThread.value.titleState?.version ?? null,
182+
needsRefinement: false,
165183
});
166184
});
167185

@@ -176,7 +194,7 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
176194
`import:${outcome.source.providerInstanceId}:${outcome.source.providerSessionId}`,
177195
);
178196
if (outcome._tag === "AlreadyImported") {
179-
if (outcome.source.provider === "codex" && outcome.canonicalTitle !== null) {
197+
if (outcome.source.provider === "codex") {
180198
yield* repairImportedCodexTitle(threadId, outcome.canonicalTitle).pipe(
181199
Effect.catch((cause) =>
182200
Effect.logWarning("Could not repair an imported Codex thread title", {
@@ -239,7 +257,14 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
239257
Option.isSome(existingBinding)
240258
) {
241259
if (thread.source === "codex") {
242-
yield* repairImportedCodexTitle(threadId, thread.title);
260+
yield* repairImportedCodexTitle(threadId, thread.title).pipe(
261+
Effect.catch((cause) =>
262+
Effect.logWarning("Could not repair an imported Codex thread title", {
263+
threadId,
264+
cause,
265+
}),
266+
),
267+
);
243268
}
244269
yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
245270
return true;

0 commit comments

Comments
 (0)