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.
TypeScript ai-agentsclaude-codeclaude-code-plugincodexcodex-plugincontext-managementdeveloper-toolsimage-generationmcpmultimodal
feat(spike): 阶段 0 的 T4–T9:重建任务、测量与附加实验
chipfighter3366c153797e
diff --git a/docs/tasks.md b/docs/tasks.mdindex 21532fe..7bf57b8 100644--- a/docs/tasks.md+++ b/docs/tasks.md@@ -37,7 +37,7 @@- 如果被沙箱拦下,请用户批准提权,或者请用户在普通终端里运行。- 完成标准:能列出样本任务。-- [ ] **T4 重建**+- [x] **T4 重建**(证据:`local/rebuild-preview.json`、`local/t4-rebuild.json`;由 Claude 执行)- 按 plan“搬迁规则”生成要注入的条目。- 新建任务,命名为 `[CAM测试] <原任务名>`。勾选 1–2 张图(例如 B),发一轮简短的请求,同时记录请求字节数。- 桌面版全程开着(这就是真实的使用场景),记录有没有出现写锁冲突或报错。@@ -49,20 +49,20 @@- [ ] **T5 可见、可续**(关卡 2)【需用户】- 先结束我们的 app-server,再请用户在桌面版里打开新任务并继续对话,然后重启桌面版,确认任务还能恢复。-- [ ] **T6 改图与重新勾选**(关卡 3)【需用户】+- [ ] **T6 改图与重新勾选**(关卡 3)【需用户】(证据:`local/turn-t6-reselect.json`、`local/turn-t6-edit.json`;Claude 已对照原图核对,待用户确认画面)- 在新任务里,让模型基于选中的图,用内置生图继续修改。- 找一张之前取消了的图(例如 A),在下一轮重新勾选并作为附件带上,检查模型能否正确描述和使用它。- 完成标准:满足 spec 关卡 3。报告附上相关的工具调用记录,画面由用户确认。-- [ ] **T7 未选不发送、请求变小**(关卡 4、5)+- [x] **T7 未选不发送、请求变小**(关卡 4、5;证据:`local/t7-calibration.json`、`local/t7-measure.json`;由 Claude 执行)- 按 plan“测量方法”检查新任务的历史和请求。- 完成标准:满足 spec 关卡 4、5,并给出与 43.8 MB 基线的对比。-- [ ] **T8 占位符有效**(关卡 6)+- [x] **T8 占位符有效**(关卡 6;证据:`local/turn-t8-placeholder.json`;由 Claude 执行)- 针对一张没有提供的图,询问画面细节,检查模型怎么回答。- 完成标准:满足 spec 关卡 6,报告里摘录这段问答。-- [ ] **T9 附加实验**(不算关卡,只记录结果)+- [x] **T9 附加实验**(不算关卡,只记录结果;证据:`local/probe-t9a-no-view-image.json`、`local/probe-t9b-mcp-meta.json`、`local/mcp-probe.jsonl`、`local/handoff/`;由 Claude 执行)- a. 关掉 `view_image` 后,整个流程是否还能用(plan 第 4 节)。- b. 如果能通过配置覆盖临时挂一个测试用的 stdio MCP 服务,记录它收到的调用里 `_meta` 有哪些内容。做不到就跳过,不要为此修改用户配置。- c. 生成一份路线 B 的交接包,记录手动继续需要哪些步骤、体验如何。diff --git a/spike/src/mcp-probe.ts b/spike/src/mcp-probe.tsnew file mode 100644index 0000000..6e7ef02--- /dev/null+++ b/spike/src/mcp-probe.ts@@ -0,0 +1,30 @@+// Purpose: T9b — a minimal stdio MCP server with one `ping` tool that records what Codex sends in tools/call,+// including `_meta`, so we can see whether a local MCP server learns which thread called it.+// Input: MCP JSON-RPC over stdio (newline-delimited); CAM_PROBE_LOG env var names the output file.+// Output: one JSON line per tools/call appended to that file (local only).++import { appendFileSync } from "node:fs";+import { createInterface } from "node:readline";++const log = process.env.CAM_PROBE_LOG;+const send = (message: Record<string, unknown>) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);++createInterface({ input: process.stdin, crlfDelay: Infinity }).on("line", (line) => {+ if (!line.trim()) return;+ const message = JSON.parse(line);+ if (message.id === undefined) return;+ switch (message.method) {+ case "initialize":+ send({ id: message.id, result: { protocolVersion: message.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "cam_probe", version: "0.0.0" } } });+ break;+ case "tools/list":+ send({ id: message.id, result: { tools: [{ name: "ping", description: "Phase 0 probe: returns pong.", inputSchema: { type: "object", properties: {} } }] } });+ break;+ case "tools/call":+ if (log) appendFileSync(log, `${JSON.stringify({ at: new Date().toISOString(), params: message.params })}\n`);+ send({ id: message.id, result: { content: [{ type: "text", text: "pong" }] } });+ break;+ default:+ send({ id: message.id, error: { code: -32601, message: `unsupported: ${message.method}` } });+ }+});diff --git a/spike/src/migrate.test.ts b/spike/src/migrate.test.tsnew file mode 100644index 0000000..451afdb--- /dev/null+++ b/spike/src/migrate.test.ts@@ -0,0 +1,78 @@+// Purpose: check the migration rules from docs/spec.md on synthetic turns (no real session data).+// Input: synthetic UI-level turns; output: Node test assertions only.++import assert from "node:assert/strict";+import test from "node:test";+import { buildMigration, redactPaths, type AssetInfo } from "./migrate.ts";++const assets: Record<string, AssetInfo> = {+ "C:\\work\\shots\\bridge.png": { assetId: "IMG-001", name: "bridge.png", width: 1672, height: 941, bytes: 2_336_942 },+ "C:\\work\\shots\\lake.png": { assetId: "IMG-002", name: "lake.png", width: 1672, height: 941, bytes: 2_869_595 },+};+const resolve = (path: string) => assets[path] ?? null;++const turns = [+ {+ status: "completed",+ items: [+ { type: "userMessage", content: [{ type: "text", text: "参考这张桥的照片" }, { type: "localImage", path: "C:\\work\\shots\\bridge.png" }] },+ { type: "reasoning", summary: ["secret chain of thought"] },+ { type: "commandExecution", command: "rg -n title 'C:\\work\\shots\\notes.md'", exitCode: 0 },+ { type: "agentMessage", text: "好的,我看过了。" },+ ],+ },+ {+ status: "failed",+ items: [+ { type: "userMessage", content: [{ type: "text", text: "再看看湖" }, { type: "localImage", path: "C:\\work\\shots\\lake.png" }] },+ { type: "imageView", path: "C:\\work\\shots\\bridge.png" },+ ],+ },+];++const texts = (items: Array<Record<string, any>>) => items.map((item) => item.content[0].text as string);++test("omitted, repeated and attached images follow the placeholder rules", () => {+ const migration = buildMigration(turns, resolve, { sourceName: "测试任务", attachments: new Map([["IMG-002", 1]]) });+ const all = texts(migration.items);+ const bridge = all.find((text) => text.includes("[素材 IMG-001"))!;+ assert.match(bridge, /bridge\.png/);+ assert.match(bridge, /不能据此判断画面细节/);+ assert.match(bridge, /需要 IMG-001/);+ const lake = all.find((text) => text.includes("[素材 IMG-002"))!;+ assert.match(lake, /作为附件 1 提供/);+ assert.ok(all.some((text) => text.includes("与 IMG-001 为同一素材")), "repeat view is a short reference");+ assert.equal(migration.imageOccurrences, 3);+ assert.equal(migration.unresolvedImages, 0);+});++test("history keeps text, drops reasoning, records tools and failed turns", () => {+ const migration = buildMigration(turns, resolve, { sourceName: "测试任务", attachments: new Map() });+ const [index, ...history] = migration.items;+ assert.equal(index.role, "developer");+ assert.match(index.content[0].text, /IMG-001|bridge\.png/);+ assert.deepEqual(history.map((item) => item.role), ["user", "assistant", "assistant", "user", "assistant", "assistant"]);+ const all = texts(migration.items).join("\n");+ assert.doesNotMatch(all, /secret chain of thought/);+ assert.match(all, /执行命令(退出码 0):rg -n title 'notes\.md'/);+ assert.match(all, /\[此轮未完成:失败\]/);+ assert.doesNotMatch(all, /C:\\work/, "no absolute path reaches the model");+});++test("redactPaths keeps only file names, including quoted paths with spaces", () => {+ assert.equal(redactPaths("rg -n x 'C:\\my docs\\a b\\c.md'"), "rg -n x 'c.md'");+ assert.equal(redactPaths('view "C:\\my docs\\shot 1.png" now'), 'view "shot 1.png" now');+ assert.equal(redactPaths("type C:\\work\\x.txt"), "type x.txt");+ assert.equal(redactPaths("cat /home/me/notes/x.md"), "cat x.md");+});++test("file changes under folders with spaces record only the file name", () => {+ const migration = buildMigration(+ [{ status: "completed", items: [{ type: "userMessage", content: [{ type: "text", text: "改一下" }] }, { type: "fileChange", changes: [{ path: "C:\\my docs\\Go To\\spec.md" }] }] }],+ resolve,+ { sourceName: "测试任务", attachments: new Map() },+ );+ const all = texts(migration.items).join("\n");+ assert.match(all, /修改文件:spec\.md/);+ assert.doesNotMatch(all, /my docs|Go To/);+});diff --git a/spike/src/migrate.ts b/spike/src/migrate.tsnew file mode 100644index 0000000..16166f3--- /dev/null+++ b/spike/src/migrate.ts@@ -0,0 +1,129 @@+// Purpose: turn a source thread's UI-level turns (app-server thread/turns/list) into the raw Responses items+// injected into a rebuilt thread: text is kept, images become placeholders, tool calls become one-line records.+// Input: turns, an image resolver, and the selection. Output: items plus bookkeeping (pure, no I/O).++type Json = Record<string, any>;+export type AssetInfo = { assetId: string; name: string; width: number | null; height: number | null; bytes: number };+export type ResolveImage = (pathOrUrl: string) => AssetInfo | null;+export type MigrationOptions = {+ sourceName: string;+ // Asset id -> attachment number in the first new turn; assets not listed are omitted.+ attachments: Map<string, number>;+};+export type FirstSeen = { asset: AssetInfo; turn: number; source: string };+export type Migration = { items: Json[]; firstSeen: FirstSeen[]; imageOccurrences: number; unresolvedImages: number };++const message = (role: "user" | "assistant" | "developer", text: string): Json => ({+ type: "message",+ role,+ content: [{ type: role === "assistant" ? "output_text" : "input_text", text }],+});++const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);+const megabytes = (bytes: number) => (bytes / 1_048_576).toFixed(1);+const dimensions = (asset: AssetInfo) => (asset.width && asset.height ? `${asset.width}×${asset.height}` : "尺寸未知");++export const baseName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path;++// Tool records keep file names but never absolute paths, so the model is not pointed at omitted files.+// Quoted paths may contain spaces and are replaced whole; unquoted paths end at whitespace.+export function redactPaths(text: string): string {+ return text+ .replace(/(['"])([A-Za-z]:\\[^'"]*|\/[^'"]*\/[^'"]*)\1/g, (_match, quote: string, path: string) => `${quote}${baseName(path)}${quote}`)+ .replace(/[A-Za-z]:\\[^\s'"]+/g, (path) => baseName(path))+ .replace(/(?<![\w.])\/(?:[^/\s'"]+\/)+[^/\s'"]+/g, (path) => baseName(path));+}++function placeholder(asset: AssetInfo, turn: number, source: string, note: string, attachment: number | undefined): string {+ const header = `[素材 ${asset.assetId}|图片|${asset.name}|${dimensions(asset)}|${megabytes(asset.bytes)} MB|原任务第 ${turn} 轮${source}]`;+ const status = attachment !== undefined+ ? `状态:已在新任务中作为附件 ${attachment} 提供。`+ : `状态:本轮未提供图像内容(为控制上下文而省略),不能据此判断画面细节。如需查看,请回复“需要 ${asset.assetId}”,用户勾选后会在下一轮作为附件提供。`;+ return `${header}\n来源说明:${note}\n${status}`;+}++function toolRecord(item: Json, imageText: (path: string) => string): string | null {+ switch (item.type) {+ case "reasoning": return null;+ case "commandExecution": return `执行命令(退出码 ${item.exitCode ?? "未知"}):${clip(redactPaths(String(item.command ?? "")), 80)}`;+ case "webSearch": return `网页搜索:${clip(String(item.query ?? ""), 60)}`;+ case "fileChange": return `修改文件:${(item.changes ?? []).map((change: Json) => baseName(String(change.path ?? ""))).join("、")}`;+ case "mcpToolCall": return `调用工具 ${item.server}.${item.tool}`;+ case "imageView": return `用看图工具查看了图片 ${imageText(item.path)}`;+ default: return `${item.type}`;+ }+}++export function buildMigration(turns: Json[], resolve: ResolveImage, options: MigrationOptions): Migration {+ const history: Json[] = [];+ const firstSeen: FirstSeen[] = [];+ const seen = new Set<string>();+ let imageOccurrences = 0;+ let unresolvedImages = 0;++ const imageText = (pathOrUrl: string, turn: number, source: string, note: string): string => {+ imageOccurrences++;+ const asset = resolve(pathOrUrl);+ if (!asset) {+ unresolvedImages++;+ return `[记录 #${imageOccurrences}:一张未能识别的图片(${source}),本轮未提供图像内容,不能据此判断画面细节]`;+ }+ if (seen.has(asset.assetId)) return `[记录 #${imageOccurrences}:与 ${asset.assetId} 为同一素材,此处不重复提供]`;+ seen.add(asset.assetId);+ firstSeen.push({ asset, turn, source });+ return placeholder(asset, turn, source, note, options.attachments.get(asset.assetId));+ };++ for (const [index, turn] of turns.entries()) {+ const number = index + 1;+ let records: string[] = [];+ const flush = () => {+ if (records.length) history.push(message("assistant", `[工具记录] ${records.join(";")}`));+ records = [];+ };+ for (const item of turn.items ?? []) {+ if (item.type === "userMessage") {+ flush();+ const text = (item.content ?? []).filter((part: Json) => part.type === "text").map((part: Json) => part.text).join("\n");+ const parts = [`【原任务第 ${number} 轮】`];+ for (const part of item.content ?? []) {+ if (part.type === "text") parts.push(part.text);+ else if (part.type === "localImage" || part.type === "image") {+ parts.push(imageText(part.path ?? part.url, number, "用户上传", `用户随附的话:“${clip(text.replace(/\s+/g, " ").trim(), 60)}”`));+ } else parts.push(`[${part.type}]`);+ }+ history.push(message("user", parts.join("\n")));+ } else if (item.type === "agentMessage") {+ flush();+ history.push(message("assistant", item.text ?? ""));+ } else {+ const record = toolRecord(item, (path) => imageText(path, number, "看图工具查看", "模型用看图工具查看"));+ if (record) records.push(record);+ }+ }+ flush();+ if (turn.status && turn.status !== "completed") {+ const label = turn.status === "failed" ? "失败" : turn.status === "interrupted" ? "被中断" : turn.status;+ history.push(message("assistant", `[此轮未完成:${label}]`));+ }+ }++ const table = firstSeen.map(({ asset, turn, source }) => {+ const attachment = options.attachments.get(asset.assetId);+ const status = attachment !== undefined ? `新任务第 1 轮附件 ${attachment}` : "未提供";+ return `- ${asset.assetId}|${asset.name}|${dimensions(asset)}|${megabytes(asset.bytes)} MB|首次出现:原任务第 ${turn} 轮(${source})|${status}`;+ });+ const index = message("developer", [+ "[Codex 附件管理器 · 重建说明]",+ `这个任务由 Codex 附件管理器从原任务「${options.sourceName}」重建。原任务的历史图片以内联数据随每次请求重复发送,请求过大后无法继续。`,+ "下面是原任务的对话文字;图片不直接附带,用素材编号和占位符表示;工具调用只保留一行记录。",+ "规则:",+ "1. 标为“未提供”的素材,你没有看到它的画面,不能据此描述或判断任何画面细节。",+ "2. 需要查看某个素材时,请直接回复“需要 IMG-xxx”,由用户勾选后在下一轮作为附件提供。不要用工具自行读取这些图片文件。",+ "3. 用户附带素材时会注明“附件 k = IMG-xxx”,此后你就能看到该素材。",+ "素材表:",+ ...table,+ ].join("\n"));++ return { items: [index, ...history], firstSeen, imageOccurrences, unresolvedImages };+}diff --git a/spike/src/rebuild.ts b/spike/src/rebuild.tsnew file mode 100644index 0000000..d1aaab4--- /dev/null+++ b/spike/src/rebuild.ts@@ -0,0 +1,224 @@+// Purpose: T4–T8 — rebuild a thread through app-server: inject migrated history, then run turns with chosen attachments.+// Input: subcommands+// preview --source <threadId> --select IMG-a,IMG-b+// create --source <threadId> --select IMG-a,IMG-b --prompt <text> [--effort medium]+// turn --thread <threadId> [--attach IMG-c] --prompt <text> --label <name> [--disable <feature>] [--effort medium]+// probe --source <threadId> --prompt <text> --label <name> [--disable <feature>] [--config key=value]… (ephemeral thread)+// Output: local/rebuild-preview.{json,md}, local/t4-rebuild.json, local/turn-<label>.json, local/probe-<label>.json+// (local only, never committed).++import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { AppServer, findBundledCodex, type Notification } from "./appserver.ts";+import { baseName, buildMigration, type AssetInfo } from "./migrate.ts";+import { decodePng } from "./png.ts";++type Json = Record<string, any>;+const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");++function option(name: string, fallback?: string): string {+ const index = process.argv.indexOf(name);+ const value = index >= 0 ? process.argv[index + 1] : undefined;+ if (value !== undefined) return value;+ if (fallback !== undefined) return fallback;+ throw new Error(`missing ${name}`);+}++// Resolves an image path to an indexed asset by content (bytes first, then pixels). When Codex resized an upload,+// content no longer matches, so user uploads fall back to the path recorded next to the image in the same message.+function loadAssets(): { resolveImage: (path: string) => AssetInfo | null; attachmentPath: (assetId: string) => string } {+ const inventory: Json = JSON.parse(readFileSync(join(localRoot, "assets.json"), "utf8"));+ const matches: Json = JSON.parse(readFileSync(join(localRoot, "matches.json"), "utf8"));+ const byByte = new Map<string, string>();+ const byPixel = new Map<string, string>();+ const info = new Map<string, AssetInfo>();+ for (const asset of inventory.assets) {+ for (const hash of asset.byteHashes) byByte.set(hash, asset.assetId);+ if (asset.pixelSha256) byPixel.set(asset.pixelSha256, asset.assetId);+ const occurrences = inventory.occurrences.filter((o: Json) => o.assetId === asset.assetId);+ const named = occurrences.map((o: Json) => o.knownLocalPath).find((path: string | null) => path && !/codex-clipboard-/.test(path));+ info.set(asset.assetId, { assetId: asset.assetId, name: named ? baseName(named) : "剪贴板图片", width: asset.width, height: asset.height, bytes: occurrences[0].byteLength });+ }+ const byUploadPath = new Map<string, string>();+ for (const occurrence of inventory.occurrences) {+ if (occurrence.source === "user_upload" && occurrence.knownLocalPath) byUploadPath.set(occurrence.knownLocalPath.toLowerCase(), occurrence.assetId);+ }+ const cache = new Map<string, AssetInfo | null>();+ const resolveImage = (path: string): AssetInfo | null => {+ if (cache.has(path)) return cache.get(path)!;+ let found: string | undefined;+ if (path && existsSync(path)) {+ const bytes = readFileSync(path);+ found = byByte.get(createHash("sha256").update(bytes).digest("hex"));+ if (!found) { try { found = byPixel.get(decodePng(bytes).pixelSha256); } catch { /* not a decodable PNG */ } }+ }+ found ??= path ? byUploadPath.get(path.toLowerCase()) : undefined;+ const result = found ? info.get(found)! : null;+ cache.set(path, result);+ return result;+ };+ const attachmentPath = (assetId: string): string => {+ const match = matches.matches.find((m: Json) => m.assetId === assetId);+ if (!match?.attachmentPath) throw new Error(`no attachment file for ${assetId}`);+ return match.attachmentPath;+ };+ return { resolveImage, attachmentPath };+}++function options(name: string): string[] {+ return process.argv.flatMap((arg, i) => (arg === name && process.argv[i + 1] !== undefined ? [process.argv[i + 1]] : []));+}++function startServer(label: string, extraArgs: string[] = [], serverRequests: Json[] = []): AppServer {+ mkdirSync(join(localRoot, "logs"), { recursive: true });+ const stamp = new Date().toISOString().replaceAll(":", "-");+ // Server requests are recorded so experiments can show what the app-server asked for; the default decline still applies.+ return new AppServer(findBundledCodex(), extraArgs, {}, join(localRoot, "logs", `${label}-appserver-${stamp}.log`), (method, params) => {+ serverRequests.push({ method, params });+ return undefined;+ });+}++async function sourceTurns(server: AppServer, threadId: string): Promise<{ thread: Json; turns: Json[] }> {+ const { thread } = await server.request<{ thread: Json }>("thread/read", { threadId, includeTurns: false });+ const turns: Json[] = [];+ let cursor: string | null = null;+ do {+ const page: Json = await server.request("thread/turns/list", { threadId, cursor, limit: 50, sortDirection: "asc", itemsView: "full" }, 300_000);+ turns.push(...page.data);+ cursor = page.nextCursor;+ } while (cursor);+ return { thread, turns };+}++function attachmentInput(assetIds: string[], attachmentPath: (id: string) => string, prompt: string): Json[] {+ const legend = assetIds.length ? `【附件管理器】本轮附件:${assetIds.map((id, i) => `附件 ${i + 1} = ${id}`).join(",")}。\n` : "";+ return [+ { type: "text", text: `${legend}${prompt}`, text_elements: [] },+ ...assetIds.map((id) => ({ type: "localImage", path: attachmentPath(id) })),+ ];+}++// Runs one turn and waits for its completion notification; returns what the turn produced.+async function runTurn(server: AppServer, threadId: string, input: Json[], effort: string): Promise<Json> {+ const startedAt = Date.now();+ const before = server.notifications.length;+ const { turn } = await server.request<{ turn: Json }>("turn/start", { threadId, input, effort }, 120_000);+ const done: Notification = await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === turn.id, 20 * 60_000);+ const mine = server.notifications.slice(before).filter((n) => n.params?.turnId === turn.id || n.params?.turn?.id === turn.id);+ const items = mine.filter((n) => n.method === "item/completed").map((n) => n.params.item);+ return {+ turnId: turn.id,+ status: done.params.turn.status,+ error: done.params.turn.error ?? null,+ wallMs: Date.now() - startedAt,+ itemTypes: items.map((item) => item.type),+ agentText: items.filter((item) => item.type === "agentMessage").map((item) => item.text).join("\n\n"),+ toolItems: items.filter((item) => !["agentMessage", "reasoning", "userMessage"].includes(item.type)).map((item) => ({+ type: item.type, status: item.status, path: item.path, server: item.server, tool: item.tool, command: item.command,+ // Content types only (never data), to see whether a tool returned an image into history.+ resultContentTypes: Array.isArray(item.result?.content) ? item.result.content.map((part: Json) => part.type) : undefined,+ })),+ errors: mine.filter((n) => n.method === "error").map((n) => n.params),+ tokenUsage: mine.filter((n) => n.method === "thread/tokenUsage/updated").map((n) => n.params.tokenUsage).at(-1) ?? null,+ };+}++async function preview(server: AppServer, sourceId: string, selected: string[]) {+ const { resolveImage, attachmentPath } = loadAssets();+ const { thread, turns } = await sourceTurns(server, sourceId);+ const attachments = new Map(selected.map((id, i) => [id, i + 1]));+ const migration = buildMigration(turns, resolveImage, { sourceName: thread.name ?? thread.preview, attachments });+ const injectedBytes = Buffer.byteLength(JSON.stringify(migration.items), "utf8");+ const summary = {+ sourceThreadId: sourceId,+ sourceName: thread.name,+ sourceTurns: turns.length,+ injectedItems: migration.items.length,+ injectedBytes,+ imageOccurrences: migration.imageOccurrences,+ unresolvedImages: migration.unresolvedImages,+ assetsInHistory: migration.firstSeen.map(({ asset, turn, source }) => ({ assetId: asset.assetId, name: asset.name, turn, source, selected: attachments.has(asset.assetId) })),+ selected: selected.map((id) => ({ assetId: id, attachmentPath: attachmentPath(id) })),+ };+ writeFileSync(join(localRoot, "rebuild-preview.json"), JSON.stringify({ ...summary, items: migration.items }, null, 2));+ writeFileSync(join(localRoot, "rebuild-preview.md"), [+ "# 重建预览(仅本机)", "",+ "```json", JSON.stringify(summary, null, 2), "```", "",+ ...migration.items.map((item, i) => `## ${i + 1}. ${item.role}\n\n${item.content[0].text}\n`),+ ].join("\n"));+ return { thread, migration, summary, attachmentPath };+}++async function main(): Promise<void> {+ const command = process.argv[2];+ const effort = option("--effort", "medium");+ if (command === "preview" || command === "create") {+ const sourceId = option("--source");+ const selected = option("--select", "").split(",").filter(Boolean);+ const server = startServer(command === "preview" ? "preview" : "t4");+ try {+ await server.initialize();+ const { thread, migration, summary, attachmentPath } = await preview(server, sourceId, selected);+ console.log(JSON.stringify({ ...summary, selected: summary.selected.map((s) => s.assetId) }, null, 2));+ if (command === "preview") return;+ const started = await server.request<{ thread: Json }>("thread/start", {+ model: thread.model, cwd: thread.cwd, approvalPolicy: "never", sandbox: "read-only", ephemeral: false,+ });+ const threadId = started.thread.id;+ await server.request("thread/inject_items", { threadId, items: migration.items }, 120_000);+ const name = `[CAM测试] ${thread.name ?? "重建任务"}`;+ await server.request("thread/name/set", { threadId, name });+ const turn = await runTurn(server, threadId, attachmentInput(selected, attachmentPath, option("--prompt")), effort);+ const result = { createdAt: new Date().toISOString(), threadId, name, model: thread.model, effort, selected, preview: summary, turn };+ writeFileSync(join(localRoot, "t4-rebuild.json"), JSON.stringify(result, null, 2));+ console.log(JSON.stringify({ threadId, name, turn: { ...turn, agentText: turn.agentText.slice(0, 600) } }, null, 2));+ } finally {+ console.log(`app-server exit code: ${await server.stop()}`);+ }+ return;+ }+ if (command === "turn") {+ const threadId = option("--thread");+ const label = option("--label");+ const attach = option("--attach", "").split(",").filter(Boolean);+ const disabled = option("--disable", "").split(",").filter(Boolean);+ const { attachmentPath } = loadAssets();+ const server = startServer(`turn-${label}`, disabled.flatMap((feature) => ["--disable", feature]));+ try {+ await server.initialize();+ await server.request("thread/resume", { threadId, approvalPolicy: "never", sandbox: "read-only" }, 300_000);+ const turn = await runTurn(server, threadId, attachmentInput(attach, attachmentPath, option("--prompt")), effort);+ const result = { createdAt: new Date().toISOString(), threadId, label, attach, disabled, effort, turn };+ writeFileSync(join(localRoot, `turn-${label}.json`), JSON.stringify(result, null, 2));+ console.log(JSON.stringify({ label, turn: { ...turn, agentText: turn.agentText.slice(0, 800) } }, null, 2));+ } finally {+ console.log(`app-server exit code: ${await server.stop()}`);+ }+ return;+ }+ if (command === "probe") {+ const label = option("--label");+ const disabled = option("--disable", "").split(",").filter(Boolean);+ const configs = options("--config");+ const serverRequests: Json[] = [];+ const server = startServer(`probe-${label}`, [...disabled.flatMap((f) => ["--disable", f]), ...configs.flatMap((c) => ["-c", c])], serverRequests);+ try {+ await server.initialize();+ const { thread } = await server.request<{ thread: Json }>("thread/read", { threadId: option("--source"), includeTurns: false });+ const started = await server.request<{ thread: Json }>("thread/start", { model: thread.model, cwd: thread.cwd, approvalPolicy: "never", sandbox: "read-only", ephemeral: true });+ const turn = await runTurn(server, started.thread.id, [{ type: "text", text: option("--prompt"), text_elements: [] }], effort);+ const result = { createdAt: new Date().toISOString(), label, disabled, configs, ephemeralThreadId: started.thread.id, turn, serverRequests };+ writeFileSync(join(localRoot, `probe-${label}.json`), JSON.stringify(result, null, 2));+ console.log(JSON.stringify({ label, serverRequests: serverRequests.map((r) => r.method), turn: { ...turn, agentText: turn.agentText.slice(0, 800) } }, null, 2));+ } finally {+ console.log(`app-server exit code: ${await server.stop()}`);+ }+ return;+ }+ throw new Error("usage: rebuild.ts preview|create|turn|probe …");+}++await main();diff --git a/spike/src/t7-measure.ts b/spike/src/t7-measure.tsnew file mode 100644index 0000000..e2f2b09--- /dev/null+++ b/spike/src/t7-measure.ts@@ -0,0 +1,75 @@+// Purpose: T7 — measure the rebuilt thread: which images its history carries and how large each request was,+// using the rollout-based estimate calibrated against real logged request sizes (see t7-calibrate.ts).+// Input: --sessions <dir>; the rebuilt thread comes from local/t4-rebuild.json, later attachments from local/turn-*.json,+// assets from local/assets.json and the baseline from local/sample.json.+// Output: local/t7-measure.json and a console table.++import { readdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { effectiveRecords, historyBytes, indexSegments, inlineImages, latestSegment, type RolloutRecord } from "./history.ts";++type Json = Record<string, any>;+const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");++function argument(name: string): string {+ const index = process.argv.indexOf(name);+ if (index < 0 || !process.argv[index + 1]) throw new Error(`missing ${name}`);+ return process.argv[index + 1];+}++const isModelOutput = (record: RolloutRecord) =>+ record.type === "response_item" &&+ (record.payload.type === "reasoning" || (record.payload.type === "message" && record.payload.role === "assistant") || /call$/.test(record.payload.type ?? ""));++function main(): void {+ const rebuilt: Json = JSON.parse(readFileSync(join(localRoot, "t4-rebuild.json"), "utf8"));+ const inventory: Json = JSON.parse(readFileSync(join(localRoot, "assets.json"), "utf8"));+ const assetByHash = new Map<string, string>();+ for (const asset of inventory.assets) for (const hash of asset.byteHashes) assetByHash.set(hash, asset.assetId);++ const segments = indexSegments(argument("--sessions"));+ const records = effectiveRecords(segments, latestSegment(segments, rebuilt.threadId));++ // First request of each turn = every history item recorded before the model's first output in that turn.+ const requests: Array<{ turn: number; historyItems: number; historyBytes: number; inlineImages: string[] }> = [];+ let turn = 0;+ let awaitingFirstOutput = false;+ for (const [index, record] of records.entries()) {+ if (record.type === "event_msg" && record.payload.type === "task_started") { turn++; awaitingFirstOutput = true; continue; }+ if (awaitingFirstOutput && isModelOutput(record)) {+ const before = records.slice(0, index);+ const { items, bytes } = historyBytes(before);+ requests.push({ turn, historyItems: items, historyBytes: bytes, inlineImages: inlineImages(before).map((image) => assetByHash.get(image.sha256) ?? `new:${image.sha256.slice(0, 8)}`) });+ awaitingFirstOutput = false;+ }+ }+ const final = historyBytes(records);+ const images = inlineImages(records).map((image) => ({ asset: assetByHash.get(image.sha256) ?? "not in index (resized or generated)", sha256: image.sha256.slice(0, 12), bytes: image.bytes, dataUrlBytes: image.dataUrlChars }));+ const carried = new Set(images.map((image) => image.asset));+ // Every asset ever attached: the rebuild selection plus any later turn's attachments on this thread.+ const attached = new Set<string>(rebuilt.selected);+ for (const file of readdirSync(localRoot).filter((name) => /^turn-.+\.json$/.test(name))) {+ const turn: Json = JSON.parse(readFileSync(join(localRoot, file), "utf8"));+ if (turn.threadId === rebuilt.threadId) for (const id of turn.attach ?? []) attached.add(id);+ }+ const neverSelected = inventory.assets.map((asset: Json) => asset.assetId).filter((id: string) => !attached.has(id));+ const sample: Json = JSON.parse(readFileSync(join(localRoot, "sample.json"), "utf8"));+ const result = {+ createdAt: new Date().toISOString(),+ threadId: rebuilt.threadId,+ requests,+ finalHistory: { items: final.items, bytes: final.bytes },+ inlineImages: images,+ neverSelected,+ unselectedCarried: neverSelected.filter((id: string) => carried.has(id)),+ attached: [...attached],+ baselineLoggedBytes: Math.max(...sample.calibration.map((c: Json) => c.logged)),+ };+ writeFileSync(join(localRoot, "t7-measure.json"), JSON.stringify(result, null, 2));+ console.table(requests.map((r) => ({ ...r, inlineImages: r.inlineImages.join(" "), vsBaseline: `${((r.historyBytes / result.baselineLoggedBytes) * 100).toFixed(1)}%` })));+ console.table(images);+ console.log(JSON.stringify({ finalHistory: result.finalHistory, neverSelected, unselectedCarried: result.unselectedCarried }));+}++main();diff --git a/spike/src/t9c-handoff.ts b/spike/src/t9c-handoff.tsnew file mode 100644index 0000000..6747599--- /dev/null+++ b/spike/src/t9c-handoff.ts@@ -0,0 +1,36 @@+// Purpose: T9c — build a route B handoff package: the migrated conversation as Markdown plus copies of the selected images,+// for a user who starts a new Codex task by hand.+// Input: local/rebuild-preview.json (from `rebuild.ts preview`) and local/matches.json. Output: local/handoff/<stamp>/.++import { copyFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { dirname, extname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");++function main(): void {+ const preview = JSON.parse(readFileSync(join(localRoot, "rebuild-preview.json"), "utf8"));+ const stamp = new Date().toISOString().replaceAll(":", "-").slice(0, 19);+ const out = join(localRoot, "handoff", stamp);+ mkdirSync(out, { recursive: true });+ const files = preview.selected.map((selected: { assetId: string; attachmentPath: string }) => {+ const name = `${selected.assetId}${extname(selected.attachmentPath)}`;+ copyFileSync(selected.attachmentPath, join(out, name));+ return name;+ });+ const roleLabel: Record<string, string> = { developer: "说明", user: "用户", assistant: "助手" };+ const markdown = [+ `# 交接包:${preview.sourceName}`,+ "",+ "使用方法:在 Codex 里新建任务,把本文件和下列图片一起附上,然后告诉 Codex“先读交接说明,再继续原任务”。",+ "",+ `随附图片:${files.map((file: string) => `\`${file}\``).join("、")}(附件编号按这个顺序:${files.map((file: string, i: number) => `附件 ${i + 1} = ${file.replace(extname(file), "")}`).join(",")})`,+ "",+ ...preview.items.map((item: { role: string; content: Array<{ text: string }> }) => `## ${roleLabel[item.role] ?? item.role}\n\n${item.content[0].text}\n`),+ ].join("\n");+ writeFileSync(join(out, "交接说明.md"), markdown);+ const bytes = statSync(join(out, "交接说明.md")).size;+ console.log(JSON.stringify({ folder: `local/handoff/${stamp}`, files: ["交接说明.md", ...files], markdownBytes: bytes }, null, 2));+}++main();