Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

refactor(history): one index model and selection in the core

chipfighter15a578fe1f40
diff --git a/docs/design.md b/docs/design.md
index aa23f4f..dae88bb 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -23,8 +23,8 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
| 引擎 | `proxy.ts`(入口)、`core/engine/transport.ts`、`adapters/codex/engine.ts`、`adapters/claude/engine.ts`、`engine.ts`、`core/routes.ts` | 本机代理:按绑定线路转发、改写请求、记录每个任务最近一次请求的统计;全机只有一个 |
| 插件服务 | `plugin-server.ts` | Codex 为每个会话启动的 MCP 服务:拉起并看守引擎,给面板提供数据;v0.3 起还给模型提供取图工具 |
| 面板 | `panel/panel.html`、`panel/page.ts`、`panel/panel-state.ts` | 侧边面板里的 MCP 应用,以及它要显示的数据 |
-| 任务索引 | `adapters/codex/thread-index.ts`、`adapters/protocols/openai-responses/images.ts`、`core/images.ts`、`core/thumbnail.ts`、`core/png.ts`、`adapters/codex/thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
-| 改写 | `core/plan.ts`、`core/words.ts`、`adapters/protocols/openai-responses/rewrite.ts`、`selection.ts`、`core/request-stats.ts`、`core/notes.ts` | 每张图发不发、换成什么字(两个平台共用);发给模型的全部文字;把决定落进 Responses 请求;勾选状态;请求统计;特征行 |
+| 任务索引 | `adapters/codex/thread-index.ts`、`adapters/codex/children.ts`、`adapters/protocols/openai-responses/images.ts`、`core/images.ts`、`core/session.ts`、`core/pixels.ts`、`core/thumbnail.ts`、`core/png.ts`、`adapters/codex/thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
+| 改写 | `core/plan.ts`、`core/words.ts`、`adapters/protocols/openai-responses/rewrite.ts`、`core/selection.ts`、`adapters/codex/selection.ts`、`adapters/claude/selection.ts`、`core/request-stats.ts`、`core/notes.ts` | 每张图发不发、换成什么字(两个平台共用);发给模型的全部文字;把决定落进 Responses 请求;勾选状态;请求统计;特征行 |
| 接入和安装 | `adapters/codex/`:`codexconfig.ts`、`setup.ts`、`install.ts`、`codexcli.ts`、`plugin-cache.ts`、`binding.ts`;`cam.ts` | 管理 Codex 配置里带标记的块;用 Codex 的命令行装卸插件;保护升级中的旧运行文件;新任务绑定;`cam` 命令行 |
| 其他 | `language.ts`、`messages.ts`、`core/paths.ts`、`core/migrate-data.ts`、`core/entry.ts` | 语言、文字表、数据目录、旧数据迁移 |
| Claude 接入(v0.4) | `hooks/register.js`(Mod,不在 `plugin/src`) | 把会话的请求地址指向引擎;`/cam` 打开面板(v0.6 起有图时自动打开);取图工具免确认 |
@@ -109,8 +109,8 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
- “重复”占位符只指向之前各轮仍在发送的图,也就是勾成每轮都发的;“已提供”标签也只加在这些图前面。这一轮的新图和取回的副本都不算:它们是这一轮中途才出现的,算进去的话,前面的占位符会在取图前后变样,缓存就断了。这样取图前后,这一轮前面的历史逐字节不变(有单元测试)。
- 副本只在取回的那一轮发送;之后换成一句说明(“IMG-xxx 的原图:模型当时用 cam_view_image 取回,只在那一轮提供,现在已省略”)。关掉自动以后也这样,因为面板不单列副本,用户没法取消它。
- 关着时,传给改写的参数和 v0.2 一样,输出逐字节相同:对照 v0.2 的改写代码,所有勾选组合(中英文、像素相同与否)都比过。
- - v0.6 起新任务默认开着(`selection.ts`):引擎和插件服务启动时,在勾选目录里写下这个版本第一次运行的时间(`auto-default.json`,只写一次,Codex 和 Claude 各一份)。任务没有自己的开关时,开始时间(会话记录第一条 `session_meta` 的时间,分叉的按来源任务算,`threadStartedAt`)不早于它,就当作开着,从开始时算起;还没有会话记录的算新的。默认值不写进勾选文件,面板里一改就写下来。读勾选的地方都经过它:改写、是否需要改写(所以新任务从一开始就走 HTTP)、面板、取图工具。
-- **子代理和旁聊**(v0.7,`proxy.ts`、`selection.ts`、`thread-index.ts`、`children.ts`;Codex 的做法见第 11 节):
+ - v0.6 起新任务默认开着(`core/selection.ts`):引擎和插件服务启动时,在勾选目录里写下这个版本第一次运行的时间(`auto-default.json`,只写一次,Codex 和 Claude 各一份)。任务没有自己的开关时,开始时间(会话记录第一条 `session_meta` 的时间,分叉的按来源任务算,`threadStartedAt`)不早于它,就当作开着,从开始时算起;还没有会话记录的算新的。默认值不写进勾选文件,面板里一改就写下来。读勾选的地方都经过它:改写、是否需要改写(所以新任务从一开始就走 HTTP)、面板、取图工具。
+- **子代理和旁聊**(v0.7,`proxy.ts`、`adapters/codex/selection.ts`、`thread-index.ts`、`adapters/codex/children.ts`;Codex 的做法见第 11 节):
- 认出来源:`x-codex-turn-metadata` 里除了 `thread_id`、`turn_id`,还读 `forked_from_thread_id`、`parent_thread_id`(没有时看请求头 `x-codex-parent-thread-id`)、`subagent_kind`,一起记进日志。
- 开关:v0.7 是主任务勾选文件里的 `childrenAuto`;v0.8 起没有开关,一律按自动选图管,0.7 写下的 `childrenAuto` 不再读。
- 旁聊:请求所属的任务没有会话记录、请求里又有 `forked_from_thread_id`,就是旁聊(`sideChatOrigin`;用户自己分叉的任务有记录,照旧按分叉规则)。用原任务的索引改写:原任务的各轮都算之前的轮次,所以带过来的图都换成自动版占位符,原任务里每轮都发的照发(`sideChatSelection`)。
@@ -295,7 +295,7 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
- 保留消息的压缩(v0.10,`claude-index.ts` 的 `relinked`):Claude Code 2.1.304 起压缩记录带 `compactMetadata.preservedSegment`(`headUuid`、`anchorUuid` 即摘要、`tailUuid`)或 `preservedMessages`(`anchorUuid`、`uuids`),原样保留最后几条消息。它读记录时(2.1.309 程序里的函数)对最后一个压缩点:保留的消息接在摘要后面;原来接在摘要上的记录,以及接在被它删掉的记录(压缩点之前、没被保留的)上的消息,接到最后一条保留消息后面;然后删掉那些记录。文件里存的是改接之前的样子:新消息接在保留消息上时,按文件连对话链会绕过压缩点。插件照同样的规则改接(只改 `activeChain` 用的父节点,不改记录),但不删历史:压缩点往前接到第一条保留消息原来的前一条,压缩前的图照旧标 `compacted`。
- 续接后的记录(v0.10,`withHistory`、`originalOf`、`readHistoryTranscript`):在桌面版里改一条之前的消息再发送(回退)时,桌面版从那里分叉出新会话,新记录文件只有改接后剩下的记录,从最近一个压缩点开始;只是重启进程的,还写原来的记录文件。插件找到压缩发生的那个记录文件:先看摘要里 Claude Code 写的“read the full transcript at: …”(取最后一处,只认 `<home>/projects` 下、含同一个压缩点且压缩点前面还有记录的文件),找不到再在同一个项目文件夹里、压缩之后改动过的记录里按压缩点的 uuid 找;它也可能是续接来的,逐层往回。旧记录只取压缩点之前、带 uuid 的记录,图片只留指纹,原始数据用到时再按位置从文件读(`onDisk`);文件不变就不重读。这样编号和续接前一样,压缩前的图照样能放回、能取回。
- 换算老记录行(v0.10,`translator`、`oldNumbering`、`familyOf`):修复之前,续接后的文件从自己的起点编号,那段时间写下的记录行和取回副本前面那行字用的是这套编号。同一项目文件夹里,第一条对话记录是会话起点或某个压缩点的记录文件,就是这个会话的全部记录文件,各自的创建时间是开头第一条带时间的记录;一条记录行是写它时最近开的那个文件的进程写的。那个文件从压缩点开始的,就按“从那里数起”的旧编号找到图(key),再换成恢复后的编号;会话起点开始的不用换。只换算 `claude/selection/stable-ids.json` 记下的这个版本第一次运行之前写的(和 v0.6 的 auto-default.json 一样,引擎和插件服务启动时写一次)。文件里还记着编号规则的版本(`rules`,2 是补上不在链上的并行调用):规则变了,第一次运行的时间就重新记。有 `offChain` 记录时,会话起点开始的文件也要换:旧编号跳过这些记录,再经图片换成现在的编号。旧编号只数到那个时刻,算一次就缓存。真实会话回放:两组会话,分别 6 个和 3 个记录文件,同一张图编号一致;挂错的特征行都回到对的图(`local/` 里的评估报告)。
- - 勾选沿用(v0.10,`selection.ts` 的 `claudeOwnSelection`、`ClaudeIndex.previous`):会话还没有自己的勾选文件时,按 `previous`(分叉时复制来的记录里留着的原会话 id 在前,然后是同一会话里更早开的记录文件,近的在前)找第一个有勾选文件的,沿用续接那一刻之前的标记和开关,写成自己的文件。
+ - 勾选沿用(v0.10,`adapters/claude/selection.ts` 的 `claudeOwnSelection`、`ClaudeIndex.previous`):会话还没有自己的勾选文件时,按 `previous`(分叉时复制来的记录里留着的原会话 id 在前,然后是同一会话里更早开的记录文件,近的在前)找第一个有勾选文件的,沿用续接那一刻之前的标记和开关,写成自己的文件。
- 代价(v0.10,用户要先看再定):最长的真实会话(9 个记录文件、210 张图)堆内存 83 → 145 MB,第一次建索引约 1.8 秒;之后记录有变化时重建约 10 毫秒,同一请求里其余几次读取用缓存(按当前记录数组、记录数和 `since` 判断)。
- 先算好要补哪些,再跑 v0.4 的改写,最后补图;面板统计里 `compacted` 记下补了哪几张(`resent`),面板的“上一次请求”写“补回压缩前的图 N 张”。
- 面板里压缩前的图照常可勾,标“压缩前”;请求预估把勾着的算作这次加上的。
diff --git a/plugin/src/adapters/claude/claude-index.ts b/plugin/src/adapters/claude/claude-index.ts
index 71d394f..ac5d868 100644
--- a/plugin/src/adapters/claude/claude-index.ts
+++ b/plugin/src/adapters/claude/claude-index.ts
@@ -25,20 +25,22 @@ import { basename, dirname, join, resolve, sep } from "node:path";
import { baseName, FETCHED_STATE, imageDigest, type ImageKind } from "../../core/images.ts";
import type { ImageRef } from "../protocols/openai-responses/images.ts";
import { addNotes, copyNotes, type Notes } from "../../core/notes.ts";
-import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "../codex/thread-index.ts";
+import { pixelHashOfData } from "../../core/pixels.ts";
+import type { FetchedCopy } from "../../core/session.ts";
+import type { IndexedImage as SessionImage, SessionIndex } from "../../core/session.ts";
type Json = Record<string, any>;
export type ClaudeRecord = Json & { type: string; uuid?: string; parentUuid?: string | null; logicalParentUuid?: string | null };
// Where an image sits: the record (its position in the conversation) and block, and for a tool result the image's
// position within that result's content.
-export type ClaudeImage = IndexedImage & { recordUuid: string; toolUseId: string | null; sub: number | null; compacted: boolean };
+export type ClaudeImage = ImageRef & SessionImage & { recordUuid: string; toolUseId: string | null; sub: number | null; compacted: boolean };
// The records with pasted images, in conversation order, with the digests of their images: what a request's user
// messages are matched against. compacted: before the latest compaction, so no longer in requests.
export type UploadRecord = { uuid: string; contentIds: string[]; compacted: boolean };
// v0.10: the session's transcripts (this one, the ones it was resumed or forked from), each with the record it starts
// at and when it was started, oldest first.
export type FamilyFile = { sessionId: string; start: string; created: string; forkedFrom: string | null };
-export type ClaudeIndex = ThreadIndex & {
+export type ClaudeIndex = SessionIndex<ClaudeImage> & {
images: ClaudeImage[];
byKey: Map<string, ClaudeImage>;
uploads: UploadRecord[];
diff --git a/plugin/src/adapters/claude/engine.ts b/plugin/src/adapters/claude/engine.ts
index d061e1a..50010cd 100644
--- a/plugin/src/adapters/claude/engine.ts
+++ b/plugin/src/adapters/claude/engine.ts
@@ -9,8 +9,10 @@ import type { IncomingHttpHeaders } from "node:http";
import { decodeBody, encodeBody, hasUnsafeInteger } from "../../core/engine/transport.ts";
import { claudeSelectionDirOf } from "../../core/paths.ts";
import { currentLang } from "../../language.ts";
-import { claudeSelection, stableIdsSince } from "../../selection.ts";
-import { awaitingLine, pixelHashOfData } from "../codex/thread-index.ts";
+import { claudeSelection } from "./selection.ts";
+import { stableIdsSince } from "../../core/selection.ts";
+import { awaitingLine } from "../../core/session.ts";
+import { pixelHashOfData } from "../../core/pixels.ts";
import { keepCacheRead, marksOutside, sentPrefixOf, type SentPrefix } from "../protocols/anthropic-messages/cache.ts";
import { addCompacted, summaryAt, type RequestImage, type Resend } from "../protocols/anthropic-messages/rewrite.ts";
import { chainOf, fitThinking, type ThinkingRecord } from "../protocols/anthropic-messages/thinking.ts";
diff --git a/plugin/src/adapters/claude/selection.ts b/plugin/src/adapters/claude/selection.ts
new file mode 100644
index 0000000..c0e2603
--- /dev/null
+++ b/plugin/src/adapters/claude/selection.ts
@@ -0,0 +1,31 @@
+// Purpose: v0.6 — a Claude Code session's selection with the default applied; v0.10: a resumed or forked session
+// starts with the selection of the one it continues (v0.11: split from selection.ts, docs/v0.11/plan.md).
+
+import { autoDefaultSince, fileFor, readSelection, THREAD_ID, withAutoDefault, writeSelection, type Mark, type Selection } from "../../core/selection.ts";
+import { existsSync } from "node:fs";
+
+// v0.6: a Claude Code session's selection with the default applied, given when it started (claudeStartedAt).
+// v0.10: `previous`, the sessions it continues (ClaudeIndex.previous), for one without a selection of its own.
+export function claudeSelection(sessionId: string, dir: string, startedAt: string | null, previous: Array<{ sessionId: string; at: string | null }> = []): Selection {
+ return withAutoDefault(claudeOwnSelection(sessionId, dir, previous), startedAt, autoDefaultSince(dir));
+}
+
+// v0.10: Claude Desktop resumes a session as a new one, and a fork is one too: without a selection of its own, it
+// starts with that of the latest session it continues that has one — the marks made by the time it took over, and
+// the switch if it was last switched by then — kept as its own file from then on, as a Codex fork (ownSelection).
+function claudeOwnSelection(sessionId: string, dir: string, previous: Array<{ sessionId: string; at: string | null }>): Selection {
+ if (!previous.length || existsSync(fileFor(sessionId, dir))) return readSelection(sessionId, dir);
+ for (const { sessionId: other, at } of previous) {
+ if (!THREAD_ID.test(other) || other === sessionId || !existsSync(fileFor(other, dir))) continue;
+ const from = readSelection(other, dir);
+ const before = (entries: Record<string, Mark> = {}) => Object.fromEntries(Object.entries(entries).filter(([, entry]) => !at || entry.at <= at));
+ const unchecked = before(from.unchecked);
+ const pinned = before(from.pinned);
+ const switched = typeof from.auto === "boolean" && (!at || !from.autoAt || from.autoAt <= at);
+ const switches = switched ? { auto: from.auto, ...(from.autoAt ? { autoAt: from.autoAt } : {}), ...(from.autoSince ? { autoSince: from.autoSince } : {}) } : {};
+ const inherited: Selection = { threadId: sessionId, unchecked, ...switches, ...(Object.keys(pinned).length ? { pinned } : {}), inheritedFrom: other };
+ writeSelection(inherited, dir);
+ return inherited;
+ }
+ return readSelection(sessionId, dir);
+}
diff --git a/plugin/src/children.ts b/plugin/src/adapters/codex/children.ts
similarity index 95%
rename from plugin/src/children.ts
rename to plugin/src/adapters/codex/children.ts
index 9a0a195..be8bac6 100644
--- a/plugin/src/children.ts
+++ b/plugin/src/adapters/codex/children.ts
@@ -6,9 +6,9 @@
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { childrenDirOf } from "./core/paths.ts";
+import { childrenDirOf } from "../../core/paths.ts";
import { mainTaskOf } from "./selection.ts";
-import { sideChatOrigin, spawnParent } from "./adapters/codex/thread-index.ts";
+import { sideChatOrigin, spawnParent } from "./thread-index.ts";
export type Child = { kind: "subagent" | "side"; from: string; at: string };
const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
diff --git a/plugin/src/adapters/codex/engine.ts b/plugin/src/adapters/codex/engine.ts
index 50fc573..c409230 100644
--- a/plugin/src/adapters/codex/engine.ts
+++ b/plugin/src/adapters/codex/engine.ts
@@ -11,11 +11,13 @@ import { join } from "node:path";
import { decodeBody, encodeBody, hasUnsafeInteger } from "../../core/engine/transport.ts";
import type { Described } from "../../core/words.ts";
import { currentLang } from "../../language.ts";
-import { effectiveSelection, selectionDir, sideChatSelection } from "../../selection.ts";
+import { effectiveSelection, sideChatSelection } from "./selection.ts";
+import { selectionDir } from "../../core/selection.ts";
import { findImages, type ImageRef } from "../protocols/openai-responses/images.ts";
import { addCodexCompacted, rewriteItems } from "../protocols/openai-responses/rewrite.ts";
import { codexHome } from "./codexconfig.ts";
-import { awaitingLine, imageData, loadThreadIndex, pixelHashOf, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";
+import { awaitingLine } from "../../core/session.ts";
+import { imageData, loadThreadIndex, pixelHashOf, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
export const UPSTREAM_HOST = "chatgpt.com";
diff --git a/plugin/src/adapters/codex/selection.ts b/plugin/src/adapters/codex/selection.ts
new file mode 100644
index 0000000..eb4a697
--- /dev/null
+++ b/plugin/src/adapters/codex/selection.ts
@@ -0,0 +1,57 @@
+// Purpose: P3 — a forked Codex task starts with what its parent had unchecked when the fork was made (user decision
+// 2026-09-24); from then on the two are independent. v0.7 — a task's subagents (started without history) and side
+// chats get automatic selection. (v0.11: split from selection.ts, docs/v0.11/plan.md.)
+
+import { existsSync } from "node:fs";
+import { autoDefaultSince, fileFor, readSelection, selectionDir, withAutoDefault, writeSelection, type Mark, type Selection } from "../../core/selection.ts";
+import { forkOrigin, spawnParent, threadStartedAt } from "./thread-index.ts";
+
+// The thread's own selection; a fork without one takes the images its parent had unchecked by the time of the fork
+// (a fork of a fork asks its own parent in turn) and keeps them as its own file from then on. v0.3: likewise the
+// pinned images and the switch, when it was turned on before the fork. v0.6: then the default applies, a fork
+// counting from the thread it came from.
+// v0.7: a subagent without a switch of its own has automatic selection instead.
+export function effectiveSelection(threadId: string, sessionsDir: string, dir = selectionDir, depth = 0): Selection {
+ const own = ownSelection(threadId, sessionsDir, dir, depth);
+ const subagent = typeof own.auto === "boolean" || depth > 16 ? false : mainTaskOf(sessionsDir, threadId) !== null;
+ if (subagent) return childSelection(own, threadStartedAt(sessionsDir, threadId));
+ return withAutoDefault(own, threadStartedAt(sessionsDir, threadId), autoDefaultSince(dir));
+}
+
+// v0.7: the task a subagent started without history belongs to: its parent, followed up while that is such a subagent
+// too. null for any other thread.
+export function mainTaskOf(sessionsDir: string, threadId: string, depth = 0): string | null {
+ const parent = spawnParent(sessionsDir, threadId);
+ if (!parent) return null;
+ return (depth < 16 ? mainTaskOf(sessionsDir, parent, depth + 1) : null) ?? parent;
+}
+
+// v0.7: automatic selection from the subagent's start.
+export function childSelection(own: Selection, startedAt: string | null): Selection {
+ return { ...own, auto: true, autoSince: own.autoSince ?? startedAt ?? new Date().toISOString() };
+}
+
+// v0.7: what a side chat forked from `origin` is sent with: the images of that task, every one of its turns counting as
+// earlier, so all of them are left out but the ones pinned there.
+export function sideChatSelection(origin: string, sessionsDir: string, dir = selectionDir): Selection {
+ const from = effectiveSelection(origin, sessionsDir, dir);
+ return { threadId: origin, unchecked: {}, auto: true, autoSince: from.autoSince ?? new Date().toISOString(), ...(from.pinned ? { pinned: from.pinned } : {}) };
+}
+
+function ownSelection(threadId: string, sessionsDir: string, dir: string, depth: number): Selection {
+ if (existsSync(fileFor(threadId, dir)) || depth > 16) return readSelection(threadId, dir);
+ const origin = forkOrigin(sessionsDir, threadId);
+ if (!origin) return { threadId, unchecked: {} };
+ const parent = effectiveSelection(origin.parent, sessionsDir, dir, depth + 1);
+ const before = (entries: Record<string, Mark> = {}) => Object.fromEntries(Object.entries(entries).filter(([, entry]) => !origin.at || entry.at <= origin.at));
+ const unchecked = before(parent.unchecked);
+ const pinned = before(parent.pinned);
+ const used = !!parent.autoSince && (!origin.at || parent.autoSince <= origin.at);
+ // On at the fork if it is on now and was last switched before the fork.
+ const auto = used && parent.auto === true && (!origin.at || !parent.autoAt || parent.autoAt <= origin.at);
+ if (!Object.keys(unchecked).length && !Object.keys(pinned).length && !used) return { threadId, unchecked: {} };
+ const switches = used ? { auto, autoSince: parent.autoSince, ...(auto ? { autoAt: parent.autoAt } : {}) } : {};
+ const inherited: Selection = { threadId, unchecked, ...switches, ...(Object.keys(pinned).length ? { pinned } : {}), inheritedFrom: origin.parent };
+ writeSelection(inherited, dir);
+ return inherited;
+}
diff --git a/plugin/src/adapters/codex/thread-index.ts b/plugin/src/adapters/codex/thread-index.ts
index bf043cb..7e84322 100644
--- a/plugin/src/adapters/codex/thread-index.ts
+++ b/plugin/src/adapters/codex/thread-index.ts
@@ -13,37 +13,24 @@
// v0.8 — what the model noted about the images in record lines at the end of its replies (notes.ts), by image id.
// Input: the sessions directory and a thread id. Output: ThreadIndex (in memory; files are parsed incrementally).
-import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
+import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { zstdDecompressSync } from "node:zlib";
import { findImages, type ImageRef } from "../protocols/openai-responses/images.ts";
import { addNotes, type Notes } from "../../core/notes.ts";
-import { decodePng } from "../../core/png.ts";
+import { pixelHashOfData } from "../../core/pixels.ts";
+import type { FetchedCopy, IndexedImage as SessionImage, SessionIndex } from "../../core/session.ts";
type Json = Record<string, any>;
-// v0.10: compacted, before Codex last compacted the thread and not in the history it kept (its tool outputs): the
-// engine puts it back after the compaction (openai-responses/rewrite.ts, addCodexCompacted); for Claude, before the latest compaction.
-export type IndexedImage = ImageRef & { id: string; turn: number | null; bytes: number; pixelSha256: string | null; compacted?: boolean };
-// v0.3: an image the model fetched with our tool, a copy of `of` sent in its own turn only (spec: automatic selection).
-export type FetchedCopy = { key: string; of: string; turn: number | null };
-// v0.10 (Codex): items, the items of the history, which image positions point into. interrupted: the turns the user
-// stopped before the model wrote its last reply (its record lines); skipped: turns that are only Claude Code's mark of
-// such a stop.
-export type ThreadIndex = { threadId: string; images: IndexedImage[]; byKey: Map<string, IndexedImage>; turns: number; turnNumbers: Map<string, number>; copies: Map<string, FetchedCopy>; notes: Map<string, Notes>; items?: Json[]; interrupted?: Set<number>; skipped?: Set<number> };
-
-// v0.10 (docs/v0.10/plan.md): an image of an interrupted turn without a feature line yet, with no turn finished since:
-// sent once more in the current turn, so the model can write its line (automatic selection would leave it out).
-export function awaitingLine(index: ThreadIndex, image: IndexedImage, current: number): boolean {
- if (image.turn === null || image.turn >= current || index.notes.get(image.id)?.line || !index.interrupted?.has(image.turn)) return false;
- for (let turn = image.turn + 1; turn < current; turn++) if (!index.interrupted.has(turn) && !index.skipped?.has(turn)) return false;
- return true;
-}
+// v0.11: the shape of the index and awaitingLine are the core's (core/session.ts); a Codex image also carries where it
+// sits in its item (ImageRef).
+export type IndexedImage = ImageRef & SessionImage;
+export type ThreadIndex = SessionIndex<IndexedImage>;
export type Parsed = { offset: number; type: string; payload: Json; timestamp: string | null };
type FileCache = { size: number; mtimeMs: number; parsedTo: number; records: Parsed[] };
const SEGMENT_NAME = /^rollout-[0-9T:-]+-([0-9a-f-]{36})(?:_([0-9a-f-]{36}))?\.jsonl(?:\.zst)?$/;
const files = new Map<string, FileCache>();
-const pixelHashes = new Map<string, string | null>();
function walk(directory: string): string[] {
let entries;
@@ -180,48 +167,6 @@ function effective(segments: Map<string, string>, segmentId: string, endOffset =
return [...inherited, ...records(file).filter((record) => record.offset < endOffset)];
}
-// The engine and the plugin services (Codex starts one per task) share pixel fingerprints through this folder, so a
-// new process does not decode every PNG again. Only fingerprints are stored, never image content. Unset: memory only
-// (tests). "-" marks a PNG our decoder cannot read.
-let pixelCacheDir: string | null = null;
-export function setPixelCache(dir: string | null): void { pixelCacheDir = dir; }
-const SHA256 = /^[0-9a-f]{64}$/;
-
-function storedPixelHash(contentId: string): string | null | undefined {
- if (!pixelCacheDir || !SHA256.test(contentId)) return undefined;
- try {
- const text = readFileSync(join(pixelCacheDir, contentId.slice(0, 2), contentId), "utf8").trim();
- return text === "-" ? null : SHA256.test(text) ? text : undefined;
- } catch { return undefined; }
-}
-
-function storePixelHash(contentId: string, hash: string | null): void {
- if (!pixelCacheDir || !SHA256.test(contentId)) return;
- try {
- const folder = join(pixelCacheDir, contentId.slice(0, 2));
- mkdirSync(folder, { recursive: true });
- writeFileSync(join(folder, contentId), hash ?? "-", { flag: "wx" });
- } catch { /* best effort; another process may have written it first */ }
-}
-
-function pixelHash(ref: ImageRef, value: string): string | null {
- if (ref.mime !== "image/png") return null;
- if (!pixelHashes.has(ref.contentId)) {
- let hash = storedPixelHash(ref.contentId);
- if (hash === undefined) {
- try { hash = decodePng(Buffer.from(value, "base64")).pixelSha256; } catch { hash = null; }
- storePixelHash(ref.contentId, hash);
- }
- pixelHashes.set(ref.contentId, hash);
- }
- return pixelHashes.get(ref.contentId) ?? null;
-}
-
-// v0.4: the same fingerprint for an image held elsewhere (a Claude Code transcript), by its digest and base64.
-export function pixelHashOfData(ref: Pick<ImageRef, "contentId" | "mime">, value: string): string | null {
- return pixelHash(ref as ImageRef, value);
-}
-
export function imageData(items: Json[], ref: ImageRef): string | null {
const item = items[ref.item];
if (ref.part === null) return typeof item?.result === "string" ? item.result : null;
@@ -231,7 +176,7 @@ export function imageData(items: Json[], ref: ImageRef): string | null {
export function pixelHashOf(items: Json[], ref: ImageRef): string | null {
const value = imageData(items, ref);
- return value === null ? null : pixelHash(ref, value);
+ return value === null ? null : pixelHashOfData(ref, value);
}
export function buildIndex(threadId: string, history: Parsed[]): ThreadIndex {
diff --git a/plugin/src/core/pixels.ts b/plugin/src/core/pixels.ts
new file mode 100644
index 0000000..bf59504
--- /dev/null
+++ b/plugin/src/core/pixels.ts
@@ -0,0 +1,46 @@
+// Purpose: v0.1-11 — pixel fingerprints of PNG images, so the same picture saved with different bytes counts as the same
+// content (v0.11: moved here from thread-index.ts, docs/v0.11/plan.md). The engine and the plugin services (Codex
+// starts one per task) share them through a folder in the data directory, so a new process does not decode every PNG
+// again. Only fingerprints are stored, never image content. Unset: memory only (tests). "-" marks a PNG our decoder
+// cannot read.
+// Input: an image's digest and base64. Output: the sha256 of its decoded pixels, or null.
+
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import type { ImageDigest } from "./images.ts";
+import { decodePng } from "./png.ts";
+
+const pixelHashes = new Map<string, string | null>();
+let pixelCacheDir: string | null = null;
+export function setPixelCache(dir: string | null): void { pixelCacheDir = dir; }
+const SHA256 = /^[0-9a-f]{64}$/;
+
+function storedPixelHash(contentId: string): string | null | undefined {
+ if (!pixelCacheDir || !SHA256.test(contentId)) return undefined;
+ try {
+ const text = readFileSync(join(pixelCacheDir, contentId.slice(0, 2), contentId), "utf8").trim();
+ return text === "-" ? null : SHA256.test(text) ? text : undefined;
+ } catch { return undefined; }
+}
+
+function storePixelHash(contentId: string, hash: string | null): void {
+ if (!pixelCacheDir || !SHA256.test(contentId)) return;
+ try {
+ const folder = join(pixelCacheDir, contentId.slice(0, 2));
+ mkdirSync(folder, { recursive: true });
+ writeFileSync(join(folder, contentId), hash ?? "-", { flag: "wx" });
+ } catch { /* best effort; another process may have written it first */ }
+}
+
+export function pixelHashOfData(ref: Pick<ImageDigest, "contentId" | "mime">, value: string): string | null {
+ if (ref.mime !== "image/png") return null;
+ if (!pixelHashes.has(ref.contentId)) {
+ let hash = storedPixelHash(ref.contentId);
+ if (hash === undefined) {
+ try { hash = decodePng(Buffer.from(value, "base64")).pixelSha256; } catch { hash = null; }
+ storePixelHash(ref.contentId, hash);
+ }
+ pixelHashes.set(ref.contentId, hash);
+ }
+ return pixelHashes.get(ref.contentId) ?? null;
+}
diff --git a/plugin/src/core/selection.ts b/plugin/src/core/selection.ts
new file mode 100644
index 0000000..5fbd340
--- /dev/null
+++ b/plugin/src/core/selection.ts
@@ -0,0 +1,108 @@
+// Purpose: P2 — per-session selection state (a Codex task, a Claude Code session): which image occurrences the user
+// unchecked. Written by the panel, read by the engine on every request of that session.
+// v0.3 — automatic selection: a switch per thread and the images pinned while it is on ("固定发送"), kept apart from
+// the manual checks, which come back as they were when it is switched off. `autoAt` is when it was last switched,
+// `autoSince` when it was first switched on: from then on the history may hold copies the model fetched, which the
+// engine leaves out of later turns even with the switch off.
+// v0.6 — automatic selection is on by default in a thread started after this version first ran here (user
+// 2026-10-13: every new task and session, in Codex and Claude Code; the ones from before keep what they had). That
+// time is written once next to the selections (auto-default.json); a thread's own switch always wins, and the default
+// itself is never written down.
+// v0.11: the platform's own rules (a Codex fork or subagent, a resumed Claude session) are in its adapter's
+// selection.ts (docs/v0.11/plan.md).
+// Input/Output: <data dir>/selection/<thread id>.json, e.g. { "threadId": "…", "unchecked": { "<key>": { "id": "IMG-003", "at": "…" } } },
+// plus "auto", "autoAt", "autoSince" and "pinned" (same shape as "unchecked") once automatic selection has been used.
+
+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { selectionDirOf } from "./paths.ts";
+
+export type Mark = { id: string; at: string };
+export type Selection = { threadId: string; unchecked: Record<string, Mark>; auto?: boolean; autoAt?: string; autoSince?: string; pinned?: Record<string, Mark>; inheritedFrom?: string };
+
+export const selectionDir = selectionDirOf();
+export const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const cache = new Map<string, { mtimeMs: number; size: number; selection: Selection }>();
+
+export function fileFor(threadId: string, dir: string): string {
+ if (!THREAD_ID.test(threadId)) throw new Error(`not a thread id: ${threadId}`);
+ return join(dir, `${threadId}.json`);
+}
+
+export function readSelection(threadId: string, dir = selectionDir): Selection {
+ const file = fileFor(threadId, dir);
+ if (!existsSync(file)) return { threadId, unchecked: {} };
+ const { mtimeMs, size } = statSync(file);
+ const known = cache.get(file);
+ if (known && known.mtimeMs === mtimeMs && known.size === size) return known.selection;
+ const selection = JSON.parse(readFileSync(file, "utf8")) as Selection;
+ cache.set(file, { mtimeMs, size, selection });
+ return selection;
+}
+
+// Written to a temporary file first, so the proxy never reads a half-written selection.
+export function writeSelection(selection: Selection, dir = selectionDir): void {
+ const file = fileFor(selection.threadId, dir);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(`${file}.tmp`, JSON.stringify(selection, null, 2));
+ renameSync(`${file}.tmp`, file);
+}
+
+// v0.6: written by the engine and the plugin service when they start; the first one wins.
+const AUTO_DEFAULT = "auto-default.json";
+// v0.10: when this version first ran here. Before it, a Claude session resumed after a compaction was numbered from
+// its transcript's own start; claude-index.ts translates what was written then (docs/v0.10/plan.md).
+const STABLE_IDS = "stable-ids.json";
+const sinceOf = new Map<string, string>();
+function ensureSince(name: string, dir: string, now: Date): void {
+ mkdirSync(dir, { recursive: true });
+ try {
+ writeFileSync(join(dir, name), JSON.stringify({ since: now.toISOString() }, null, 2), { flag: "wx" });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ }
+}
+function sinceIn(name: string, dir: string): string | null {
+ const key = join(dir, name);
+ const known = sinceOf.get(key);
+ if (known) return known;
+ try {
+ const since = JSON.parse(readFileSync(key, "utf8")).since;
+ if (typeof since === "string") sinceOf.set(key, since);
+ return typeof since === "string" ? since : null;
+ } catch {
+ return null;
+ }
+}
+export const ensureAutoDefault = (dir = selectionDir, now = new Date()): void => ensureSince(AUTO_DEFAULT, dir, now);
+// null until this version has run here: then nothing is on by default.
+export const autoDefaultSince = (dir = selectionDir): string | null => sinceIn(AUTO_DEFAULT, dir);
+// The numbering rules the ids follow. 2: the calls of a reply found off the chain, when their results came back out of
+// order, get ids too (claude-index.ts). Under newer rules the start time starts again, so what was written under the
+// earlier ones is translated.
+const ID_RULES = 2;
+export function ensureStableIds(dir = selectionDir, now = new Date()): void {
+ const file = join(dir, STABLE_IDS);
+ let rules: unknown;
+ try {
+ rules = JSON.parse(readFileSync(file, "utf8")).rules;
+ } catch {
+ mkdirSync(dir, { recursive: true });
+ try { writeFileSync(file, JSON.stringify({ since: now.toISOString(), rules: ID_RULES }, null, 2), { flag: "wx" }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
+ return;
+ }
+ if (rules === ID_RULES) return;
+ writeFileSync(file, JSON.stringify({ since: now.toISOString(), rules: ID_RULES }, null, 2));
+ sinceOf.delete(file);
+}
+// null until this version has run here: then nothing is translated.
+export const stableIdsSince = (dir = selectionDir): string | null => sinceIn(STABLE_IDS, dir);
+
+// A thread with no switch of its own that started at or after `since` has automatic selection on, from its start;
+// one with no history yet (startedAt null) is just starting.
+export function withAutoDefault(selection: Selection, startedAt: string | null, since: string | null): Selection {
+ if (typeof selection.auto === "boolean" || !since) return selection;
+ const started = startedAt ?? new Date().toISOString();
+ if (Date.parse(started) < Date.parse(since)) return selection;
+ return { ...selection, auto: true, autoSince: selection.autoSince ?? started };
+}
diff --git a/plugin/src/core/session.ts b/plugin/src/core/session.ts
new file mode 100644
index 0000000..6155d56
--- /dev/null
+++ b/plugin/src/core/session.ts
@@ -0,0 +1,31 @@
+// Purpose: what the core knows of a session's images, whatever the platform reads them from (v0.11: the shape both the
+// Codex and the Claude index had, moved here from thread-index.ts, docs/v0.11/plan.md). Ids follow the order the
+// images first appeared in, and never change.
+// Input: a platform's index. Output: types, and whether an image is waiting for its feature line.
+
+import type { ImageDigest, ImageKind, ImageSource } from "./images.ts";
+import type { Notes } from "./notes.ts";
+
+type Json = Record<string, any>;
+
+// An image occurrence of the session. key: names the same occurrence in a request and in the records. v0.10:
+// compacted, before the platform last compacted the session and not in the history it kept: the engine puts it back
+// after the compaction.
+export type IndexedImage = ImageDigest & {
+ key: string; kind: ImageKind; name: string | null; label: string | null; source: ImageSource; replaceable: boolean;
+ id: string; turn: number | null; bytes: number; pixelSha256: string | null; compacted?: boolean;
+};
+// v0.3: an image the model fetched with our tool, a copy of `of` sent in its own turn only (spec: automatic selection).
+export type FetchedCopy = { key: string; of: string; turn: number | null };
+// v0.10: items, the items of the history (Codex), which image positions point into. interrupted: the turns the user
+// stopped before the model wrote its last reply (its record lines); skipped: turns that are only Claude Code's mark of
+// such a stop.
+export type SessionIndex<I extends IndexedImage = IndexedImage> = { threadId: string; images: I[]; byKey: Map<string, I>; turns: number; turnNumbers: Map<string, number>; copies: Map<string, FetchedCopy>; notes: Map<string, Notes>; items?: Json[]; interrupted?: Set<number>; skipped?: Set<number> };
+
+// v0.10 (docs/v0.10/plan.md): an image of an interrupted turn without a feature line yet, with no turn finished since:
+// sent once more in the current turn, so the model can write its line (automatic selection would leave it out).
+export function awaitingLine(index: SessionIndex<IndexedImage>, image: IndexedImage, current: number): boolean {
+ if (image.turn === null || image.turn >= current || index.notes.get(image.id)?.line || !index.interrupted?.has(image.turn)) return false;
+ for (let turn = image.turn + 1; turn < current; turn++) if (!index.interrupted.has(turn) && !index.skipped?.has(turn)) return false;
+ return true;
+}
diff --git a/plugin/src/panel/panel-state.ts b/plugin/src/panel/panel-state.ts
index b89a195..023a8d5 100644
--- a/plugin/src/panel/panel-state.ts
+++ b/plugin/src/panel/panel-state.ts
@@ -13,13 +13,15 @@
// Input: thread id, the sessions directory (rollouts are only read) and the tool's data directory.
// Output: PanelState as plain JSON; selection changes are written to <data dir>/selection/.
-import { readChildren } from "../children.ts";
+import { readChildren } from "../adapters/codex/children.ts";
import { claudeHome, claudeImageData, claudeStartedAt, isPrompt, loadClaudeIndex, type ClaudeIndex, type ClaudeRecord } from "../adapters/claude/claude-index.ts";
import type { ImageSource } from "../core/images.ts";
import { sceneOf, withoutRecords } from "../core/notes.ts";
import { childrenDirOf, claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "../core/paths.ts";
import { readRequestStats, type RequestStats } from "../core/request-stats.ts";
-import { claudeSelection, effectiveSelection, stableIdsSince, writeSelection, type Mark, type Selection } from "../selection.ts";
+import { claudeSelection } from "../adapters/claude/selection.ts";
+import { effectiveSelection } from "../adapters/codex/selection.ts";
+import { stableIdsSince, writeSelection, type Mark, type Selection } from "../core/selection.ts";
import { buildIndex, imageData, readThreadHistory, sessionMetaOf, type IndexedImage, type ThreadIndex } from "../adapters/codex/thread-index.ts";
import { threadTitle } from "../adapters/codex/thread-names.ts";
import { pngThumbnail } from "../core/thumbnail.ts";
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 071897e..9186116 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -38,9 +38,12 @@ import { panelHtml } from "./panel/page.ts";
import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel/panel-state.ts";
import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./core/paths.ts";
import { fetchedLabel, fetchWords } from "./core/words.ts";
-import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, stableIdsSince } from "./selection.ts";
+import { claudeSelection } from "./adapters/claude/selection.ts";
+import { effectiveSelection } from "./adapters/codex/selection.ts";
+import { ensureAutoDefault, ensureStableIds, stableIdsSince } from "./core/selection.ts";
import { connectDirectly, useEngine, usesEngine } from "./adapters/codex/setup.ts";
-import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache, sideChatOrigin } from "./adapters/codex/thread-index.ts";
+import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, sideChatOrigin } from "./adapters/codex/thread-index.ts";
+import { setPixelCache } from "./core/pixels.ts";
import { threadTitle } from "./adapters/codex/thread-names.ts";
type Json = Record<string, any>;
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 615a591..06e8af0 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -26,14 +26,14 @@ import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import type { Duplex } from "node:stream";
import { setTimeout as sleep } from "node:timers/promises";
-import { childOf, recordChild } from "./children.ts";
+import { childOf, recordChild } from "./adapters/codex/children.ts";
import { claudeHome, loadClaudeIndex } from "./adapters/claude/claude-index.ts";
import { CLAUDE_HOST, claudeConversationRequest, claudeIdentity, claudeImageSizes, claudeNeedsRewrite, LATE_STEP_MS, LATE_WAIT_MS, rewriteClaudeBody, thinkingRejected, type ClaudeAttempt } from "./adapters/claude/engine.ts";
import { claudePanelApi, claudePanelPage, PANEL_PAGE_CSP } from "./adapters/claude/panel-web.ts";
import { codexHome } from "./adapters/codex/codexconfig.ts";
import { CODEX_BASE, imageSizesOf, needsRewrite, OPENAI_API_HOST, requestIdentity, rewriteBody, UPSTREAM_HOST, type RequestIdentity } from "./adapters/codex/engine.ts";
import { connectDirectly, pluginGone, usesEngine } from "./adapters/codex/setup.ts";
-import { setPixelCache } from "./adapters/codex/thread-index.ts";
+import { setPixelCache } from "./core/pixels.ts";
import { REMEMBERED, type SentPrefix } from "./adapters/protocols/anthropic-messages/cache.ts";
import { readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./adapters/protocols/anthropic-messages/thinking.ts";
import { connectUpstream, decodeBody, HOP_BY_HOP, log, outboundProxy, ownRequest, readSystemProxy, redactImages } from "./core/engine/transport.ts";
@@ -45,7 +45,7 @@ import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, t
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
import { currentLang } from "./language.ts";
import { say } from "./messages.ts";
-import { ensureAutoDefault, ensureStableIds, selectionDir, stableIdsSince } from "./selection.ts";
+import { ensureAutoDefault, ensureStableIds, selectionDir, stableIdsSince } from "./core/selection.ts";
type Json = Record<string, any>;
diff --git a/plugin/src/selection.ts b/plugin/src/selection.ts
deleted file mode 100644
index 99aad7a..0000000
--- a/plugin/src/selection.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-// Purpose: P2 — per-thread selection state: which image occurrences the user unchecked. Written by the CLI (later
-// the panel), read by the proxy on every request of that thread.
-// P3 — a forked thread starts with what its parent had unchecked when the fork was made (user decision 2026-09-24);
-// from then on the two are independent.
-// v0.3 — automatic selection: a switch per thread and the images pinned while it is on ("固定发送"), kept apart from
-// the manual checks, which come back as they were when it is switched off. `autoAt` is when it was last switched,
-// `autoSince` when it was first switched on: from then on the history may hold copies the model fetched, which the
-// engine leaves out of later turns even with the switch off.
-// v0.6 — automatic selection is on by default in a thread started after this version first ran here (user
-// 2026-10-13: every new task and session, in Codex and Claude Code; the ones from before keep what they had). That
-// time is written once next to the selections (auto-default.json); a thread's own switch always wins, and the default
-// itself is never written down.
-// v0.7 — a task's subagents (started without history) and side chats get automatic selection, whatever the task's own
-// switch says. v0.8: always; the panel's switch for them is gone (user 2026-10-19), and a "childrenAuto": false that
-// v0.7 wrote is ignored.
-// Input/Output: <data dir>/selection/<thread id>.json, e.g. { "threadId": "…", "unchecked": { "<key>": { "id": "IMG-003", "at": "…" } } },
-// plus "auto", "autoAt", "autoSince" and "pinned" (same shape as "unchecked") once automatic selection has been used.
-
-import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
-import { selectionDirOf } from "./core/paths.ts";
-import { forkOrigin, spawnParent, threadStartedAt } from "./adapters/codex/thread-index.ts";
-
-export type Mark = { id: string; at: string };
-export type Selection = { threadId: string; unchecked: Record<string, Mark>; auto?: boolean; autoAt?: string; autoSince?: string; pinned?: Record<string, Mark>; inheritedFrom?: string };
-
-export const selectionDir = selectionDirOf();
-const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
-const cache = new Map<string, { mtimeMs: number; size: number; selection: Selection }>();
-
-function fileFor(threadId: string, dir: string): string {
- if (!THREAD_ID.test(threadId)) throw new Error(`not a thread id: ${threadId}`);
- return join(dir, `${threadId}.json`);
-}
-
-export function readSelection(threadId: string, dir = selectionDir): Selection {
- const file = fileFor(threadId, dir);
- if (!existsSync(file)) return { threadId, unchecked: {} };
- const { mtimeMs, size } = statSync(file);
- const known = cache.get(file);
- if (known && known.mtimeMs === mtimeMs && known.size === size) return known.selection;
- const selection = JSON.parse(readFileSync(file, "utf8")) as Selection;
- cache.set(file, { mtimeMs, size, selection });
- return selection;
-}
-
-// Written to a temporary file first, so the proxy never reads a half-written selection.
-export function writeSelection(selection: Selection, dir = selectionDir): void {
- const file = fileFor(selection.threadId, dir);
- mkdirSync(dir, { recursive: true });
- writeFileSync(`${file}.tmp`, JSON.stringify(selection, null, 2));
- renameSync(`${file}.tmp`, file);
-}
-
-// v0.6: written by the engine and the plugin service when they start; the first one wins.
-const AUTO_DEFAULT = "auto-default.json";
-// v0.10: when this version first ran here. Before it, a Claude session resumed after a compaction was numbered from
-// its transcript's own start; claude-index.ts translates what was written then (docs/v0.10/plan.md).
-const STABLE_IDS = "stable-ids.json";
-const sinceOf = new Map<string, string>();
-function ensureSince(name: string, dir: string, now: Date): void {
- mkdirSync(dir, { recursive: true });
- try {
- writeFileSync(join(dir, name), JSON.stringify({ since: now.toISOString() }, null, 2), { flag: "wx" });
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
- }
-}
-function sinceIn(name: string, dir: string): string | null {
- const key = join(dir, name);
- const known = sinceOf.get(key);
- if (known) return known;
- try {
- const since = JSON.parse(readFileSync(key, "utf8")).since;
- if (typeof since === "string") sinceOf.set(key, since);
- return typeof since === "string" ? since : null;
- } catch {
- return null;
- }
-}
-export const ensureAutoDefault = (dir = selectionDir, now = new Date()): void => ensureSince(AUTO_DEFAULT, dir, now);
-// null until this version has run here: then nothing is on by default.
-export const autoDefaultSince = (dir = selectionDir): string | null => sinceIn(AUTO_DEFAULT, dir);
-// The numbering rules the ids follow. 2: the calls of a reply found off the chain, when their results came back out of
-// order, get ids too (claude-index.ts). Under newer rules the start time starts again, so what was written under the
-// earlier ones is translated.
-const ID_RULES = 2;
-export function ensureStableIds(dir = selectionDir, now = new Date()): void {
- const file = join(dir, STABLE_IDS);
- let rules: unknown;
- try {
- rules = JSON.parse(readFileSync(file, "utf8")).rules;
- } catch {
- mkdirSync(dir, { recursive: true });
- try { writeFileSync(file, JSON.stringify({ since: now.toISOString(), rules: ID_RULES }, null, 2), { flag: "wx" }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
- return;
- }
- if (rules === ID_RULES) return;
- writeFileSync(file, JSON.stringify({ since: now.toISOString(), rules: ID_RULES }, null, 2));
- sinceOf.delete(file);
-}
-// null until this version has run here: then nothing is translated.
-export const stableIdsSince = (dir = selectionDir): string | null => sinceIn(STABLE_IDS, dir);
-
-// A thread with no switch of its own that started at or after `since` has automatic selection on, from its start;
-// one with no history yet (startedAt null) is just starting.
-export function withAutoDefault(selection: Selection, startedAt: string | null, since: string | null): Selection {
- if (typeof selection.auto === "boolean" || !since) return selection;
- const started = startedAt ?? new Date().toISOString();
- if (Date.parse(started) < Date.parse(since)) return selection;
- return { ...selection, auto: true, autoSince: selection.autoSince ?? started };
-}
-
-// v0.6: a Claude Code session's selection with the default applied, given when it started (claudeStartedAt).
-// v0.10: `previous`, the sessions it continues (ClaudeIndex.previous), for one without a selection of its own.
-export function claudeSelection(sessionId: string, dir: string, startedAt: string | null, previous: Array<{ sessionId: string; at: string | null }> = []): Selection {
- return withAutoDefault(claudeOwnSelection(sessionId, dir, previous), startedAt, autoDefaultSince(dir));
-}
-
-// v0.10: Claude Desktop resumes a session as a new one, and a fork is one too: without a selection of its own, it
-// starts with that of the latest session it continues that has one — the marks made by the time it took over, and
-// the switch if it was last switched by then — kept as its own file from then on, as a Codex fork (ownSelection).
-function claudeOwnSelection(sessionId: string, dir: string, previous: Array<{ sessionId: string; at: string | null }>): Selection {
- if (!previous.length || existsSync(fileFor(sessionId, dir))) return readSelection(sessionId, dir);
- for (const { sessionId: other, at } of previous) {
- if (!THREAD_ID.test(other) || other === sessionId || !existsSync(fileFor(other, dir))) continue;
- const from = readSelection(other, dir);
- const before = (entries: Record<string, Mark> = {}) => Object.fromEntries(Object.entries(entries).filter(([, entry]) => !at || entry.at <= at));
- const unchecked = before(from.unchecked);
- const pinned = before(from.pinned);
- const switched = typeof from.auto === "boolean" && (!at || !from.autoAt || from.autoAt <= at);
- const switches = switched ? { auto: from.auto, ...(from.autoAt ? { autoAt: from.autoAt } : {}), ...(from.autoSince ? { autoSince: from.autoSince } : {}) } : {};
- const inherited: Selection = { threadId: sessionId, unchecked, ...switches, ...(Object.keys(pinned).length ? { pinned } : {}), inheritedFrom: other };
- writeSelection(inherited, dir);
- return inherited;
- }
- return readSelection(sessionId, dir);
-}
-
-// The thread's own selection; a fork without one takes the images its parent had unchecked by the time of the fork
-// (a fork of a fork asks its own parent in turn) and keeps them as its own file from then on. v0.3: likewise the
-// pinned images and the switch, when it was turned on before the fork. v0.6: then the default applies, a fork
-// counting from the thread it came from.
-// v0.7: a subagent without a switch of its own has automatic selection instead.
-export function effectiveSelection(threadId: string, sessionsDir: string, dir = selectionDir, depth = 0): Selection {
- const own = ownSelection(threadId, sessionsDir, dir, depth);
- const subagent = typeof own.auto === "boolean" || depth > 16 ? false : mainTaskOf(sessionsDir, threadId) !== null;
- if (subagent) return childSelection(own, threadStartedAt(sessionsDir, threadId));
- return withAutoDefault(own, threadStartedAt(sessionsDir, threadId), autoDefaultSince(dir));
-}
-
-// v0.7: the task a subagent started without history belongs to: its parent, followed up while that is such a subagent
-// too. null for any other thread.
-export function mainTaskOf(sessionsDir: string, threadId: string, depth = 0): string | null {
- const parent = spawnParent(sessionsDir, threadId);
- if (!parent) return null;
- return (depth < 16 ? mainTaskOf(sessionsDir, parent, depth + 1) : null) ?? parent;
-}
-
-// v0.7: automatic selection from the subagent's start.
-export function childSelection(own: Selection, startedAt: string | null): Selection {
- return { ...own, auto: true, autoSince: own.autoSince ?? startedAt ?? new Date().toISOString() };
-}
-
-// v0.7: what a side chat forked from `origin` is sent with: the images of that task, every one of its turns counting as
-// earlier, so all of them are left out but the ones pinned there.
-export function sideChatSelection(origin: string, sessionsDir: string, dir = selectionDir): Selection {
- const from = effectiveSelection(origin, sessionsDir, dir);
- return { threadId: origin, unchecked: {}, auto: true, autoSince: from.autoSince ?? new Date().toISOString(), ...(from.pinned ? { pinned: from.pinned } : {}) };
-}
-
-function ownSelection(threadId: string, sessionsDir: string, dir: string, depth: number): Selection {
- if (existsSync(fileFor(threadId, dir)) || depth > 16) return readSelection(threadId, dir);
- const origin = forkOrigin(sessionsDir, threadId);
- if (!origin) return { threadId, unchecked: {} };
- const parent = effectiveSelection(origin.parent, sessionsDir, dir, depth + 1);
- const before = (entries: Record<string, Mark> = {}) => Object.fromEntries(Object.entries(entries).filter(([, entry]) => !origin.at || entry.at <= origin.at));
- const unchecked = before(parent.unchecked);
- const pinned = before(parent.pinned);
- const used = !!parent.autoSince && (!origin.at || parent.autoSince <= origin.at);
- // On at the fork if it is on now and was last switched before the fork.
- const auto = used && parent.auto === true && (!origin.at || !parent.autoAt || parent.autoAt <= origin.at);
- if (!Object.keys(unchecked).length && !Object.keys(pinned).length && !used) return { threadId, unchecked: {} };
- const switches = used ? { auto, autoSince: parent.autoSince, ...(auto ? { autoAt: parent.autoAt } : {}) } : {};
- const inherited: Selection = { threadId, unchecked, ...switches, ...(Object.keys(pinned).length ? { pinned } : {}), inheritedFrom: origin.parent };
- writeSelection(inherited, dir);
- return inherited;
-}
diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.ts
index 9893308..079b291 100644
--- a/spike/scripts/panel-dev.ts
+++ b/spike/scripts/panel-dev.ts
@@ -368,7 +368,7 @@ function writeStats(kind: string): void {
}
// v0.8: the two copies' last requests (turn 7), and a subagent and a side chat of the auto one.
{
- const { recordChild } = await import("../../plugin/src/children.ts");
+ const { recordChild } = await import("../../plugin/src/adapters/codex/children.ts");
const { childrenDirOf } = await import("../../plugin/src/core/paths.ts");
const stats = requestStatsDirOf(process.env.CAM_DATA_DIR);
for (const [id, file, auto] of V08_TASKS.flatMap(([main, manual]) => [[main, `rollout-2026-09-24T13-00-00-${main}.jsonl`, true], [manual, `rollout-2026-09-24T13-30-00-${manual}.jsonl`, false]] as const)) {
diff --git a/spike/src/children-retry.test.ts b/spike/src/children-retry.test.ts
index 1c42842..ce96dbd 100644
--- a/spike/src/children-retry.test.ts
+++ b/spike/src/children-retry.test.ts
@@ -4,7 +4,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { readChildren, recordChild } from "../../plugin/src/children.ts";
+import { readChildren, recordChild } from "../../plugin/src/adapters/codex/children.ts";
test("a child can be recorded again after its first write fails", (t) => {
const root = mkdtempSync(join(tmpdir(), "cam-children-retry-"));
diff --git a/spike/src/children.test.ts b/spike/src/children.test.ts
index a866acd..b2f4c8b 100644
--- a/spike/src/children.test.ts
+++ b/spike/src/children.test.ts
@@ -7,7 +7,7 @@ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { childOf, readChildren, recordChild } from "../../plugin/src/children.ts";
+import { childOf, readChildren, recordChild } from "../../plugin/src/adapters/codex/children.ts";
const MAIN = "01a0d307-0000-7000-8000-0000000000c0";
const CHILD = "01a0d307-0000-7000-8000-0000000000c1";
diff --git a/spike/src/claude-compaction.test.ts b/spike/src/claude-compaction.test.ts
index a229043..116f360 100644
--- a/spike/src/claude-compaction.test.ts
+++ b/spike/src/claude-compaction.test.ts
@@ -10,7 +10,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { buildClaudeIndex, claudeImageData, loadClaudeIndex, readHistoryTranscript } from "../../plugin/src/adapters/claude/claude-index.ts";
-import { claudeSelection, writeSelection } from "../../plugin/src/selection.ts";
+import { claudeSelection } from "../../plugin/src/adapters/claude/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { image, pngA, pngB, pngC, text, transcript } from "./claude-fixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/claude-panel.test.ts b/spike/src/claude-panel.test.ts
index 6309740..ceafd00 100644
--- a/spike/src/claude-panel.test.ts
+++ b/spike/src/claude-panel.test.ts
@@ -14,7 +14,7 @@ import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.t
import { claudeNeedsRewrite, rewriteClaudeBody } from "../../plugin/src/adapters/claude/engine.ts";
import { claudePanelApi, claudePanelPage } from "../../plugin/src/adapters/claude/panel-web.ts";
import { ownRequest } from "../../plugin/src/core/engine/transport.ts";
-import { ensureAutoDefault } from "../../plugin/src/selection.ts";
+import { ensureAutoDefault } from "../../plugin/src/core/selection.ts";
import { pngC, usualRequest, usualSession } from "./claude-fixtures.ts";
process.env.CAM_LANG = "zh";
diff --git a/spike/src/codex-compaction.test.ts b/spike/src/codex-compaction.test.ts
index 2d8c6e5..b0f52a9 100644
--- a/spike/src/codex-compaction.test.ts
+++ b/spike/src/codex-compaction.test.ts
@@ -13,7 +13,7 @@ import zlib from "node:zlib";
import { rewriteBody } from "../../plugin/src/adapters/codex/engine.ts";
import { addCodexCompacted } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
import { compactList } from "../../plugin/src/core/words.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.ts
index ded8fed..f2387e6 100644
--- a/spike/src/engine.test.ts
+++ b/spike/src/engine.test.ts
@@ -16,7 +16,7 @@ import { fileURLToPath } from "node:url";
import { buildOf, compareVersions, countClaudeInPs, countClaudeProcesses, countCodexInPs, countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, shouldReplace, watchForCodex, type Health } from "../../plugin/src/engine.ts";
import { selectionDirOf } from "../../plugin/src/core/paths.ts";
import { readRequestStats, recordRequest } from "../../plugin/src/core/request-stats.ts";
-import { autoDefaultSince, writeSelection } from "../../plugin/src/selection.ts";
+import { autoDefaultSince, writeSelection } from "../../plugin/src/core/selection.ts";
const here = dirname(fileURLToPath(import.meta.url));
const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
diff --git a/spike/src/feature-backfill.test.ts b/spike/src/feature-backfill.test.ts
index acbf10c..f6ee6de 100644
--- a/spike/src/feature-backfill.test.ts
+++ b/spike/src/feature-backfill.test.ts
@@ -13,8 +13,9 @@ import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.
import { rewriteBody } from "../../plugin/src/adapters/codex/engine.ts";
import { rewriteClaudeBody } from "../../plugin/src/adapters/claude/engine.ts";
import { featureNote } from "../../plugin/src/core/words.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
-import { awaitingLine, loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
+import { awaitingLine } from "../../plugin/src/core/session.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/layers.test.ts b/spike/src/layers.test.ts
index eeae1f8..28e767a 100644
--- a/spike/src/layers.test.ts
+++ b/spike/src/layers.test.ts
@@ -15,19 +15,16 @@ import { fileURLToPath } from "node:url";
const src = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "plugin", "src");
const PENDING = new Set<string>([
- "adapters/claude/claude-index.ts -> adapters/codex/thread-index.ts",
- "adapters/claude/engine.ts -> adapters/codex/thread-index.ts",
"adapters/claude/engine.ts -> language.ts",
- "adapters/claude/engine.ts -> selection.ts",
"adapters/codex/engine.ts -> language.ts",
- "adapters/codex/engine.ts -> selection.ts",
"adapters/codex/install.ts -> language.ts",
"adapters/codex/install.ts -> messages.ts",
"panel/panel-state.ts -> adapters/claude/claude-index.ts",
+ "panel/panel-state.ts -> adapters/claude/selection.ts",
+ "panel/panel-state.ts -> adapters/codex/children.ts",
+ "panel/panel-state.ts -> adapters/codex/selection.ts",
"panel/panel-state.ts -> adapters/codex/thread-index.ts",
"panel/panel-state.ts -> adapters/codex/thread-names.ts",
- "panel/panel-state.ts -> children.ts",
- "panel/panel-state.ts -> selection.ts",
]);
type Layer = "core" | "panel" | "protocols" | `adapter:${string}` | "top";
diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.ts
index d1f6bec..cbfbd90 100644
--- a/spike/src/panel-state.test.ts
+++ b/spike/src/panel-state.test.ts
@@ -10,9 +10,9 @@ import test from "node:test";
import { decodePng } from "../../plugin/src/core/png.ts";
import { applySelection, imageFor, loadPanelState, panelStateOf, requestedIds, sendInfo } from "../../plugin/src/panel/panel-state.ts";
import { childrenDirOf, requestStatsDirOf } from "../../plugin/src/core/paths.ts";
-import { recordChild } from "../../plugin/src/children.ts";
+import { recordChild } from "../../plugin/src/adapters/codex/children.ts";
import { recordRequest } from "../../plugin/src/core/request-stats.ts";
-import { readSelection, writeSelection } from "../../plugin/src/selection.ts";
+import { readSelection, writeSelection } from "../../plugin/src/core/selection.ts";
import { assistant, line, red, sampleSessions, startThread, THREAD, turn, upload } from "./testfixtures.ts";
import { shrink } from "../../plugin/src/core/thumbnail.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/plugin-server.test.ts b/spike/src/plugin-server.test.ts
index 4c4291c..d5cb4d1 100644
--- a/spike/src/plugin-server.test.ts
+++ b/spike/src/plugin-server.test.ts
@@ -10,7 +10,7 @@ import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import { callTool, fromModel, PANEL_MIME, PANEL_URI, readResource, threadOf, TOOLS } from "../../plugin/src/plugin-server.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { line, red, sampleSessions, startThread, THREAD, turn, upload } from "./testfixtures.ts";
// These tests check the Chinese wording: the language is fixed, so neither the system's language nor one a panel
diff --git a/spike/src/proxy-provider-http.test.ts b/spike/src/proxy-provider-http.test.ts
index a36bcf6..0fa7c5f 100644
--- a/spike/src/proxy-provider-http.test.ts
+++ b/spike/src/proxy-provider-http.test.ts
@@ -10,7 +10,7 @@ import test, { type TestContext } from "node:test";
import { fileURLToPath } from "node:url";
import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";
import { assistant, line, red, turn, upload, THREAD } from "./testfixtures.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { engineTestPort } from "./proxy-test-ports.ts";
async function bounded<T>(value: Promise<T>, ms = 8000): Promise<T> {
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index 12e7c76..2cfbb0f 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -12,7 +12,7 @@ import { claudeIdentity } from "../../plugin/src/adapters/claude/engine.ts";
import { describeBody, forwardHeaders, routeOf } from "../../plugin/src/proxy.ts";
import { hasUnsafeInteger, macProxy, outboundProxy, redactImages } from "../../plugin/src/core/engine/transport.ts";
import { imageSizesOf, needsRewrite, rewriteBody, requestIdentity } from "../../plugin/src/adapters/codex/engine.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { png } from "./testkit.ts";
// These tests check the Chinese wording: the language is fixed, so neither the system's language nor one a panel
diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.ts
index 9764bf0..f9a7241 100644
--- a/spike/src/selection.test.ts
+++ b/spike/src/selection.test.ts
@@ -8,7 +8,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { needsRewrite } from "../../plugin/src/adapters/codex/engine.ts";
-import { autoDefaultSince, effectiveSelection, ensureAutoDefault, ensureStableIds, mainTaskOf, readSelection, sideChatSelection, stableIdsSince, writeSelection } from "../../plugin/src/selection.ts";
+import { autoDefaultSince, ensureAutoDefault, ensureStableIds, readSelection, stableIdsSince, writeSelection } from "../../plugin/src/core/selection.ts";
+import { effectiveSelection, mainTaskOf, sideChatSelection } from "../../plugin/src/adapters/codex/selection.ts";
import { startThread } from "./testfixtures.ts";
const PARENT = "01a0d301-0000-7000-8000-0000000000f0";
diff --git a/spike/src/thread-index.test.ts b/spike/src/thread-index.test.ts
index 8d7327e..0e4ff66 100644
--- a/spike/src/thread-index.test.ts
+++ b/spike/src/thread-index.test.ts
@@ -12,7 +12,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { zstdCompressSync } from "node:zlib";
-import { buildIndex, forkOrigin, hasRollout, loadThreadIndex, readThreadHistory, setPixelCache, spawnParent, threadStartedAt, threadsStartedSince } from "../../plugin/src/adapters/codex/thread-index.ts";
+import { buildIndex, forkOrigin, hasRollout, loadThreadIndex, readThreadHistory, spawnParent, threadStartedAt, threadsStartedSince } from "../../plugin/src/adapters/codex/thread-index.ts";
+import { setPixelCache } from "../../plugin/src/core/pixels.ts";
import { startThread, todayFolder } from "./testfixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/v01-needs-selftest.ts b/spike/src/v01-needs-selftest.ts
index a2eebd3..1123b03 100644
--- a/spike/src/v01-needs-selftest.ts
+++ b/spike/src/v01-needs-selftest.ts
@@ -22,7 +22,7 @@ import { languageFileOf, rememberLang } from "../../plugin/src/language.ts";
import { askedIn } from "../../plugin/src/panel/panel-state.ts";
import { selectionDirOf } from "../../plugin/src/core/paths.ts";
import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, png, runTurn, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
diff --git a/spike/src/v01-placeholder-selftest.ts b/spike/src/v01-placeholder-selftest.ts
index c1cec48..7bc65d9 100644
--- a/spike/src/v01-placeholder-selftest.ts
+++ b/spike/src/v01-placeholder-selftest.ts
@@ -20,7 +20,7 @@ import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang } from "../../plugin/src/language.ts";
import { selectionDirOf } from "../../plugin/src/core/paths.ts";
import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { archiveThreads, runTurn, TEST_EFFORT, TEST_MODEL, testImages, text } from "./testkit.ts";
import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
diff --git a/spike/src/v03-auto-selftest.ts b/spike/src/v03-auto-selftest.ts
index b6588b3..c578298 100644
--- a/spike/src/v03-auto-selftest.ts
+++ b/spike/src/v03-auto-selftest.ts
@@ -27,7 +27,7 @@ import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang, type Lang } from "../../plugin/src/language.ts";
import { requestStatsDirOf, selectionDirOf } from "../../plugin/src/core/paths.ts";
import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { writeSelection } from "../../plugin/src/core/selection.ts";
import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, CORNER_IMAGES, runTurn, says, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";