@liang-hz/agent-in-chrome 0.55.0 → 0.55.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { execFileSync } from "node:child_process";
3
4
  import fs from "node:fs";
4
5
  import os from "node:os";
5
6
  import path from "node:path";
@@ -17,6 +18,13 @@ import {
17
18
  antigravityDataDir,
18
19
  antigravityConversationId,
19
20
  readAntigravityWorkspace,
21
+ readAntigravitySessionTitle,
22
+ codexHome,
23
+ codexThreadId,
24
+ readCodexSessionTitle,
25
+ opencodeDataDir,
26
+ isOpencodeClient,
27
+ opencodeSessionOf,
20
28
  readSessionIdentity,
21
29
  hasTty,
22
30
  walkSurface,
@@ -25,6 +33,7 @@ import {
25
33
  readClientSessionFile,
26
34
  readHostSessionTitle,
27
35
  readWorkbuddySessionTitle,
36
+ workbuddyConversationId,
28
37
  informativeName,
29
38
  composeAgent,
30
39
  probeLocal,
@@ -92,6 +101,23 @@ const CHAINS = {
92
101
  [970, { ppid: 971, tty: "??", command: "/Users/u/.nvm/versions/node/v24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
93
102
  [971, { ppid: 1, tty: "??", command: "/Applications/WorkBuddy.app/Contents/MacOS/Electron /Applications/WorkBuddy.app/Contents/Resources/app.asar/main/daemon-app-server-entry.js --stdio" }],
94
103
  ]),
104
+ cliFromGui: new Map([
105
+ [990, { ppid: 991, tty: "??", command: "/opt/homebrew/Cellar/node/24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
106
+ [991, { ppid: 992, tty: "??", command: "/opt/homebrew/bin/opencode run --auto 用 browser_status 查一次浏览器状态" }],
107
+ [992, { ppid: 993, tty: "??", command: "/bin/zsh -c . '/Users/u/.workbuddy-ai/shell-snapshots/snapshot-zsh-1789611597980-n9i4qa.sh' && opencode run" }],
108
+ [993, { ppid: 994, tty: "??", command: "/Applications/WorkBuddy AI.app/Contents/MacOS/Electron /Applications/WorkBuddy AI.app/Contents/Resources/app.asar/out/main/index.js" }],
109
+ [994, { ppid: 1, tty: "??", command: "/Applications/WorkBuddy AI.app/Contents/MacOS/Electron" }],
110
+ ]),
111
+ qoderDeep: new Map([
112
+ [995, { ppid: 996, tty: "??", command: "/opt/homebrew/Cellar/node/24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
113
+ [996, { ppid: 997, tty: "??", command: "/Applications/Qoder CN.app/Contents/Resources/app/resources/bin/aarch64_darwin/QoderCN start --workDir /Users/u/Library" }],
114
+ [997, { ppid: 1, tty: "??", command: "/Applications/Qoder CN.app/Contents/MacOS/Electron" }],
115
+ ]),
116
+ cliMentionsApp: new Map([
117
+ [985, { ppid: 986, tty: "??", command: "/opt/homebrew/Cellar/node/24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
118
+ [986, { ppid: 987, tty: "??", command: "/usr/local/bin/some-cli --config /Applications/Claude.app/Contents/Resources/app.asar/config.json" }],
119
+ [987, { ppid: 1, tty: "??", command: "/Applications/Claude.app/Contents/MacOS/Claude" }],
120
+ ]),
95
121
  };
96
122
 
97
123
  const SELF = "/Users/u/.agent-in-chrome/agent-in-chrome/server.mjs";
@@ -135,6 +161,27 @@ console.log("\n\x1b[1m形态与品牌:认父进程链上的证据\x1b[0m");
135
161
  const w = walk("workbuddy", 970);
136
162
  check("WorkBuddy:Electron 主进程直接 spawn,认包名", w.surface === "app" && w.brand === "WorkBuddy", JSON.stringify(w));
137
163
 
164
+ const g = walk("cliFromGui", 990);
165
+ check(
166
+ "从 GUI 里起的 CLI:不认祖先的 .app,报无证据(宁可不显示也不显示错)",
167
+ g.surface === null && g.brand === null,
168
+ JSON.stringify(g)
169
+ );
170
+
171
+ const m = walk("cliMentionsApp", 985);
172
+ check(
173
+ "参数里提到别的 .app 不算数:照旧报无证据",
174
+ m.surface === null && m.brand === null,
175
+ JSON.stringify(m)
176
+ );
177
+
178
+ const qd = walk("qoderDeep", 995);
179
+ check(
180
+ "客户端在包里但不在 Contents/MacOS 下:仍然认这个包",
181
+ qd.surface === "app" && qd.brand === "Qoder CN" && qd.appDir === "/Applications/Qoder CN.app",
182
+ JSON.stringify(qd)
183
+ );
184
+
138
185
  const none = walkSurface(950, new Map(), {});
139
186
  check("查不到进程就报没有形态,不猜", none.surface === null && none.brand === null, JSON.stringify(none));
140
187
  }
@@ -200,13 +247,13 @@ console.log("\n\x1b[1m会话标题:客户端写在磁盘上的那份\x1b[0m");
200
247
 
201
248
  check("读得到客户端的会话记录", readClientSessionFile(7001, { home })?.entrypoint === "cli");
202
249
  check("pid 对不上的残留文件当没有", readClientSessionFile(7002, { home }) === null);
203
- check("凑出来的会话名(derived)不当标题——它跟工作区那段重复", readSessionTitle({ clientPid: 7001, hostSessionId: null }, { home }) === null);
250
+ check("凑出来的会话名(derived)不当标题——它跟工作区那段重复", readSessionTitle({ clientPid: 7001, hostSessionId: null }, { home, env: {} }) === null);
204
251
 
205
252
  fs.writeFileSync(
206
253
  path.join(sessions, "7003.json"),
207
254
  JSON.stringify({ pid: 7003, cwd: "/tmp/z", entrypoint: "cli", name: "查竞品定价", nameSource: "auto" })
208
255
  );
209
- check("不是凑出来的会话名就当标题", readSessionTitle({ clientPid: 7003, hostSessionId: null }, { home }) === "查竞品定价");
256
+ check("不是凑出来的会话名就当标题", readSessionTitle({ clientPid: 7003, hostSessionId: null }, { home, env: {} }) === "查竞品定价");
210
257
 
211
258
  const hostDir = path.join(home, "Library", "Application Support", "Claude", "claude-code-sessions", "org1", "user1");
212
259
  fs.mkdirSync(hostDir, { recursive: true });
@@ -214,25 +261,29 @@ console.log("\n\x1b[1m会话标题:客户端写在磁盘上的那份\x1b[0m");
214
261
  check("宿主管的标题读得到(逐级列目录找到那两层)", readHostSessionTitle("local_abc-123", { home }) === "修 sid 漂移与组认领");
215
262
  check("没有这个会话 id 就是没有", readHostSessionTitle("local_nope", { home }) === null);
216
263
  check("会话 id 里有路径分隔符一律不认(别人给的字符串,不许拼进路径)", readHostSessionTitle("../../etc/passwd", { home }) === null);
217
- check("宿主的标题优先于客户端记的会话名", readSessionTitle({ clientPid: 7003, hostSessionId: "local_abc-123" }, { home }) === "修 sid 漂移与组认领");
264
+ check("宿主的标题优先于客户端记的会话名", readSessionTitle({ clientPid: 7003, hostSessionId: "local_abc-123" }, { home, env: {} }) === "修 sid 漂移与组认领");
218
265
 
219
266
  const late = path.join(hostDir, "local_late.json");
220
- check("标题还没生成时就是没有", readSessionTitle({ clientPid: 0, hostSessionId: "local_late" }, { home }) === null);
267
+ check("标题还没生成时就是没有", readSessionTitle({ clientPid: 0, hostSessionId: "local_late" }, { home, env: {} }) === null);
221
268
  fs.writeFileSync(late, JSON.stringify({ title: "后来才有的标题" }));
222
- check("标题后来出现了要能读到(所以不能只在握手时读一次)", readSessionTitle({ clientPid: 0, hostSessionId: "local_late" }, { home }) === "后来才有的标题");
269
+ check("标题后来出现了要能读到(所以不能只在握手时读一次)", readSessionTitle({ clientPid: 0, hostSessionId: "local_late" }, { home, env: {} }) === "后来才有的标题");
223
270
 
224
271
  fs.rmSync(home, { recursive: true, force: true });
225
272
  }
226
273
 
227
- console.log("\n\x1b[1mWorkBuddy 的会话标题:活着的对话恰好一个才归属\x1b[0m");
274
+ console.log("\n\x1b[1mWorkBuddy 的会话标题:协议级 → 引擎进程 → 活会话计数\x1b[0m");
228
275
  {
229
276
  const wb = fs.mkdtempSync(path.join(os.tmpdir(), "aic-wb-"));
230
277
  fs.mkdirSync(path.join(wb, "sessions"));
231
278
  const put = (pid, extra) => fs.writeFileSync(path.join(wb, "sessions", `${pid}.json`), JSON.stringify({ pid, ...extra }));
232
- put(7100, { kind: "interactive", sessionId: "649aa100-f37d-4bff-b8db-7518eef9a95d" });
279
+ const A = "649aa100-f37d-4bff-b8db-7518eef9a95d";
280
+ const B = "0f179b98-cf6a-4c42-a9e5-02766f6d131f";
281
+ put(7100, { kind: "interactive", sessionId: A });
233
282
  put(7101, { kind: "interactive", sessionId: "interactive-7101" });
234
- put(7102, { kind: "prewarm", sessionId: "0f179b98-cf6a-4c42-a9e5-02766f6d131f" });
235
- put(7103, { kind: "interactive", sessionId: "0f179b98-cf6a-4c42-a9e5-02766f6d131f" });
283
+ put(7102, { kind: "prewarm", sessionId: B });
284
+ put(7103, { kind: "interactive", sessionId: B });
285
+ put(7200, { pid: 9999, kind: "interactive", sessionId: B });
286
+ put(7300, { kind: "interactive", sessionId: A });
236
287
 
237
288
  const env = { WORKBUDDY_CONFIG_DIR: wb };
238
289
  let asked = null;
@@ -240,27 +291,90 @@ console.log("\n\x1b[1mWorkBuddy 的会话标题:活着的对话恰好一个才
240
291
  asked = { bin, sql: args[args.length - 1] };
241
292
  return "查竞品定价\n";
242
293
  };
294
+ const oneLive = (p) => p === 7100;
243
295
 
244
- const one = readWorkbuddySessionTitle({ env, exec: fakeExec, alive: (p) => p === 7100 });
245
- check("恰好一个活着的对话:读它的标题", one === "查竞品定价", JSON.stringify(one));
246
- check("查库带的是那段对话的 uuid(先验过形状才拼 SQL)", /649aa100-f37d-4bff-b8db-7518eef9a95d/.test(asked?.sql || ""), asked?.sql);
247
- check("CLI host / prewarm 的假会话不算对话", one === "查竞品定价");
248
- check("两段对话都活着:分不出是谁,不猜", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => true }) === null);
249
- check("对话都结束了就是没有", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => false }) === null);
296
+ const one = readWorkbuddySessionTitle({ env, exec: fakeExec, alive: oneLive });
297
+ check("兜底:恰好一个活着的对话时读它的标题", one === "查竞品定价", JSON.stringify(one));
298
+ check("兜底:查库带的是那段对话的 uuid(先验过形状才拼 SQL)", /649aa100-f37d-4bff-b8db-7518eef9a95d/.test(asked?.sql || ""), asked?.sql);
299
+ check("兜底:CLI host / prewarm 的假会话不算对话", one === "查竞品定价");
300
+ check(
301
+ "兜底:两段对话都活着又没有别的证据时仍然不猜",
302
+ readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => true }) === null
303
+ );
304
+ check("兜底:对话都结束了就是没有", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => false }) === null);
250
305
  check("没有 WORKBUDDY_CONFIG_DIR(别家客户端)一律 null", readWorkbuddySessionTitle({ env: {}, exec: fakeExec }) === null);
251
- check("库读不动就不显示,不许编", readWorkbuddySessionTitle({ env, exec: () => { throw new Error("no db"); }, alive: (p) => p === 7100 }) === null);
306
+ check(
307
+ "库读不动就不显示,不许编",
308
+ readWorkbuddySessionTitle({ env, exec: () => { throw new Error("no db"); }, alive: oneLive }) === null
309
+ );
310
+
311
+ asked = null;
312
+ const byMeta = readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => true, meta: { "workbuddy.ai/conversationId": B } });
313
+ check("协议级:_meta 报的会话 id 优先于活会话计数(多开对话照样归属)", byMeta === "查竞品定价", JSON.stringify(byMeta));
314
+ check("协议级:查的是 _meta 报的那个 uuid,不是「活着的那个」", /0f179b98-cf6a-4c42-a9e5-02766f6d131f/.test(asked?.sql || ""), asked?.sql);
315
+
316
+ asked = null;
317
+ const byBaggage = readWorkbuddySessionTitle({
318
+ env,
319
+ exec: fakeExec,
320
+ alive: () => true,
321
+ meta: { progressToken: 7, baggage: "codebuddy.session_id=" + A + ",other=1" },
322
+ });
323
+ check("协议级:baggage 里的 codebuddy.session_id 是同一份值的第二处写法", byBaggage === "查竞品定价" && /649aa100/.test(asked?.sql || ""), asked?.sql);
324
+
325
+ asked = null;
326
+ readWorkbuddySessionTitle({
327
+ env,
328
+ exec: fakeExec,
329
+ alive: () => true,
330
+ meta: { "workbuddy.ai/conversationId": B, baggage: "codebuddy.session_id=" + A },
331
+ });
332
+ check("协议级:命名空间键优先于 baggage(两处都带时以前者为准)", /0f179b98/.test(asked?.sql || ""), asked?.sql);
333
+
334
+ check("协议级:形状锚只放行 uuid(不是 uuid 就当没报)", workbuddyConversationId({ "workbuddy.ai/conversationId": "abc" }) === null);
335
+ check("协议级:meta 不是对象时不炸", workbuddyConversationId(null) === null && workbuddyConversationId("x") === null);
336
+
337
+ asked = null;
338
+ const byPid = readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => true, enginePid: 7100 });
339
+ check("进程级:引擎 pid 的记录直接给出会话 id(真机上就是它)", byPid === "查竞品定价" && /649aa100/.test(asked?.sql || ""), asked?.sql);
340
+ check("进程级:引擎 pid 的文件里 pid 对不上(pid 被复用)就不认", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => false, enginePid: 7200 }) === null);
341
+ check("进程级:指向预热池那种非 interactive 的记录不认", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => false, enginePid: 7102 }) === null);
342
+ check("进程级:指着一个不存在的 pid 就是没有,不炸", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => false, enginePid: 7999 }) === null);
343
+ check("进程级:没给引擎 pid 时这一档整个跳过", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: oneLive, enginePid: null }) === "查竞品定价");
344
+ asked = null;
345
+ readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => true, enginePid: 7100, meta: { "workbuddy.ai/conversationId": B } });
346
+ check("协议级压过进程级(调用方自己说的那句最硬)", /0f179b98/.test(asked?.sql || ""), asked?.sql);
347
+
252
348
  {
253
349
  const evil = fs.mkdtempSync(path.join(os.tmpdir(), "aic-wb-evil-"));
254
350
  fs.mkdirSync(path.join(evil, "sessions"));
255
351
  fs.writeFileSync(path.join(evil, "sessions", "8000.json"),
256
352
  JSON.stringify({ pid: 8000, kind: "interactive", sessionId: "1' or '1'='1" }));
257
- check("带引号的 sessionId 不进 SQL(正则先挡)",
258
- readWorkbuddySessionTitle({ env: { WORKBUDDY_CONFIG_DIR: evil }, exec: () => { throw new Error("绝不该拿注入载荷查库"); }, alive: () => true }) === null);
353
+ const never = () => { throw new Error("绝不该拿注入载荷查库"); };
354
+ check("带引号的 sessionId 不进 SQL(活会话那条路的正则先挡)",
355
+ readWorkbuddySessionTitle({ env: { WORKBUDDY_CONFIG_DIR: evil }, exec: never, alive: () => true }) === null);
356
+ check("带引号的 _meta.conversationId 不进 SQL(协议级那条路同样先挡)",
357
+ readWorkbuddySessionTitle({ env: { WORKBUDDY_CONFIG_DIR: evil }, exec: never, meta: { "workbuddy.ai/conversationId": "1' or '1'='1" } }) === null);
358
+ check("带引号的 baggage 不进 SQL",
359
+ readWorkbuddySessionTitle({ env: { WORKBUDDY_CONFIG_DIR: evil }, exec: never, meta: { baggage: "codebuddy.session_id=x' or 1=1--" } }) === null);
360
+ check("带引号的引擎记录同样进不去 SQL",
361
+ readWorkbuddySessionTitle({ env: { WORKBUDDY_CONFIG_DIR: evil }, exec: never, enginePid: 8000 }) === null);
259
362
  fs.rmSync(evil, { recursive: true, force: true });
260
363
  }
261
364
 
262
- const t = readSessionTitle({ clientPid: 0, hostSessionId: null }, { home: wb, env, exec: fakeExec, alive: (p) => p === 7100 });
365
+ const t = readSessionTitle({ clientPid: 0, hostSessionId: null }, { home: wb, env, exec: fakeExec, alive: oneLive });
263
366
  check("readSessionTitle 兜到 WorkBuddy 这条来源", t === "查竞品定价", JSON.stringify(t));
367
+ const t2 = readSessionTitle(
368
+ { clientPid: 0, hostSessionId: null },
369
+ { home: wb, env, exec: fakeExec, alive: () => true, meta: { "workbuddy.ai/conversationId": B } }
370
+ );
371
+ check("readSessionTitle 把 _meta 一路传给了 WorkBuddy 这一条(不传的话多开对话就丢会话名)", t2 === "查竞品定价", JSON.stringify(t2));
372
+ asked = null;
373
+ const t3 = readSessionTitle(
374
+ { clientPid: 7100, hostSessionId: null },
375
+ { home: wb, env, exec: fakeExec, alive: () => true }
376
+ );
377
+ check("readSessionTitle 把 clientPid 当作引擎 pid 传下去", t3 === "查竞品定价" && /649aa100/.test(asked?.sql || ""), asked?.sql);
264
378
 
265
379
  fs.rmSync(wb, { recursive: true, force: true });
266
380
  }
@@ -740,7 +854,7 @@ if (typeof zlib.zstdCompressSync !== "function") {
740
854
  const idn = readSessionIdentity(localFor(), { home, tmp: path.join(home, "unused-tmp") });
741
855
  check("标题与工作区同源于同一段会话", idn.title === "改注册器" && idn.workspace === "my-cool-repo" && idn.workspaceKind === "git", JSON.stringify(idn));
742
856
  resetTitleMemo();
743
- const other = readSessionIdentity({ clientCommand: "node /a/b.js", clientPid: 1, hostSessionId: null, sessionName: null }, { home });
857
+ const other = readSessionIdentity({ clientCommand: "node /a/b.js", clientPid: 1, hostSessionId: null, sessionName: null }, { home, env: {} });
744
858
  check("非 dsh 客户端走 readSessionIdentity 行为不变(工作区不盖)", other.title === null && other.workspace === null, JSON.stringify(other));
745
859
  fs.rmSync(home, { recursive: true, force: true });
746
860
  }
@@ -965,14 +1079,410 @@ console.log("\n\x1b[1mAntigravity:数据目录自报 + 会话库里的工作
965
1079
  fs.mkdirSync(path.join(proj, ".git"), { recursive: true });
966
1080
  writeRaw(home, `${ID}.db`, agBytes(ID, proj));
967
1081
  resetTitleMemo();
968
- const idn = readSessionIdentity(localFor(), { home, meta: metaFor(), tmp: path.join(home, "unused-tmp") });
1082
+ const idn = readSessionIdentity(localFor(), { home, meta: metaFor(), env: {}, tmp: path.join(home, "unused-tmp") });
969
1083
  check("readSessionIdentity 接上了:工作区来自会话库", idn.workspace === "ag-wired" && idn.workspaceKind === "git", JSON.stringify(idn));
970
- check("会话标题本地没有证据:返回 null,不猜", idn.title === null, JSON.stringify(idn));
1084
+ check("库里没有 steps 表时标题是 null,工作区照旧", idn.title === null, JSON.stringify(idn));
971
1085
  resetTitleMemo();
972
1086
  const bare = readSessionIdentity(localFor(), { home, meta: { progressToken: "p1" }, tmp: path.join(home, "unused-tmp") });
973
1087
  check("同一个客户端、帧里没有会话 id 时不盖工作区", bare.workspace === null, JSON.stringify(bare));
974
1088
  fs.rmSync(home, { recursive: true, force: true });
975
1089
  }
1090
+
1091
+ console.log("\n\x1b[1mAntigravity:会话库 steps 表里的会话标题\x1b[0m");
1092
+ {
1093
+ const SQLITE = process.platform === "win32" ? "sqlite3" : "/usr/bin/sqlite3";
1094
+ const pbInt = (field, n) => Buffer.concat([pbVarint(field * 8), pbVarint(n)]);
1095
+ const pbSub = (field, buf) => Buffer.concat([pbVarint(field * 8 + 2), pbVarint(buf.length), buf]);
1096
+ const stepPayload = ({ title, goal, metaMsg = true } = {}) =>
1097
+ Buffer.concat([
1098
+ pbInt(1, 23),
1099
+ pbInt(4, 3),
1100
+ pbStr(5, "run-instance-metadata"),
1101
+ metaMsg
1102
+ ? pbSub(
1103
+ 30,
1104
+ Buffer.concat([
1105
+ pbInt(9, 1),
1106
+ title ? pbStr(4, title) : Buffer.alloc(0),
1107
+ pbInt(12, 5),
1108
+ goal ? pbStr(19, goal) : Buffer.alloc(0),
1109
+ pbInt(24, 2),
1110
+ ])
1111
+ )
1112
+ : Buffer.alloc(0),
1113
+ ]);
1114
+ const writeDb = (file, rows, { wal = false } = {}) => {
1115
+ const sql = [
1116
+ wal ? "PRAGMA journal_mode=WAL;" : "",
1117
+ "CREATE TABLE steps (idx INTEGER, step_type INTEGER, status INTEGER, has_subtrajectory INTEGER, metadata BLOB, error_details BLOB, permissions BLOB, task_details BLOB, render_info BLOB, step_payload BLOB, step_format INTEGER);",
1118
+ ...rows.map(([idx, type, payload]) => `INSERT INTO steps (idx, step_type, step_payload) VALUES (${idx}, ${type}, ${payload ? `x'${payload.toString("hex")}'` : "NULL"});`),
1119
+ ].join("\n");
1120
+ execFileSync(SQLITE, [file], { input: `${sql}\n`, encoding: "utf8" });
1121
+ };
1122
+ const dbPath = (home, id = ID) => path.join(home, ".gemini", "antigravity-ide", "conversations", `${id}.db`);
1123
+ const titleOf = (home, meta = metaFor(), opts = {}) => {
1124
+ resetTitleMemo();
1125
+ return readAntigravitySessionTitle(meta, localFor(), { home, ...opts });
1126
+ };
1127
+ const agTmpLeft = () => fs.readdirSync(os.tmpdir()).filter((f) => f.startsWith("ag-title-"));
1128
+ const tmpBefore = agTmpLeft().length;
1129
+
1130
+ {
1131
+ const home = agHome();
1132
+ writeDb(dbPath(home), [
1133
+ [3, 7, stepPayload({ title: "不是 23 行的标题", goal: "干扰" })],
1134
+ [30, 23, stepPayload({ title: "后面那一个不算", goal: "续会话" })],
1135
+ [10, 23, stepPayload({ metaMsg: false })],
1136
+ [20, 23, stepPayload({ title: "商机判定反馈逻辑优化", goal: "帮我看一下商机判定这块" })],
1137
+ [40, 23, stepPayload({ goal: "compaction 追加的行只有 f19" })],
1138
+ [50, 23, null],
1139
+ ]);
1140
+ const t = titleOf(home);
1141
+ check("有 f4:按 idx 升序取第一个 f30.f4", t === "商机判定反馈逻辑优化", String(t));
1142
+ check("step_type ≠ 23 的行一概不读", t !== "不是 23 行的标题", String(t));
1143
+ check("23 行里没有 f30 的照样往下走,不当成到头", t === "商机判定反馈逻辑优化", String(t));
1144
+ check("别的会话 id 查不到自己的库:null", titleOf(home, metaFor("11111111-2222-3333-4444-555555555555")) === null);
1145
+ fs.rmSync(home, { recursive: true, force: true });
1146
+ }
1147
+
1148
+ {
1149
+ const home = agHome();
1150
+ const goal = "帮我把这个仓库里所有会话标题相关的实现整理一遍,然后写一份自足的文档给我看,要能直接照着做" + "尾巴".repeat(20);
1151
+ writeDb(dbPath(home), [
1152
+ [10, 23, stepPayload({ goal })],
1153
+ [20, 23, stepPayload({ goal: "第二条的目标不该被取" })],
1154
+ ]);
1155
+ const t = titleOf(home);
1156
+ check("一行 f4 都没有:兜底第一条 23 行的 f19", t === goal.slice(0, 60), String(t));
1157
+ check("兜底值 clip 到 60(标题来自别人磁盘上的内容,外发前必截)", t.length === 60, String(t.length));
1158
+ fs.rmSync(home, { recursive: true, force: true });
1159
+ }
1160
+
1161
+ {
1162
+ const home = agHome();
1163
+ writeDb(dbPath(home), [
1164
+ [5, 23, stepPayload({ title: "小行里的标题", goal: "首条用户消息" })],
1165
+ [301, 23, stepPayload({ goal: "上下文".repeat(200_000) })],
1166
+ ]);
1167
+ const t = titleOf(home);
1168
+ check("库里有 1MB 以上的 compaction 行时照样取得到标题(hex 会撑爆默认 stdout 缓冲)", t === "小行里的标题", String(t));
1169
+ const only = agHome();
1170
+ writeDb(dbPath(only), [[301, 23, stepPayload({ goal: "上下文".repeat(200_000) })]]);
1171
+ check("超大的 23 行不参与兜底,取不到就是 null", titleOf(only) === null);
1172
+ fs.rmSync(home, { recursive: true, force: true });
1173
+ fs.rmSync(only, { recursive: true, force: true });
1174
+ }
1175
+
1176
+ {
1177
+ const home = agHome();
1178
+ const rows = [[1, 23, stepPayload({ title: "多行大库里的标题", goal: "x".repeat(60_000) })]];
1179
+ for (let i = 2; i <= 16; i++) rows.push([i, 23, stepPayload({ goal: "y".repeat(60_000) })]);
1180
+ writeDb(dbPath(home), rows);
1181
+ check("16 行都贴着单行上限时(hex 近 2MB)仍取得到标题", titleOf(home) === "多行大库里的标题");
1182
+ fs.rmSync(home, { recursive: true, force: true });
1183
+ }
1184
+
1185
+ {
1186
+ const home = agHome();
1187
+ writeDb(dbPath(home), []);
1188
+ check("空表:null", titleOf(home) === null);
1189
+ writeDb(dbPath(home, "22222222-3333-4444-5555-666666666666"), [[1, 7, stepPayload({ title: "别家 step_type" })]]);
1190
+ check("一行 23 都没有:null", titleOf(home, metaFor("22222222-3333-4444-5555-666666666666")) === null);
1191
+ check("库文件根本不存在:null,不抛", titleOf(home, metaFor("33333333-4444-5555-6666-777777777777")) === null);
1192
+ fs.rmSync(home, { recursive: true, force: true });
1193
+ }
1194
+
1195
+ {
1196
+ let copies = 0;
1197
+ let mkdtemps = 0;
1198
+ let execs = 0;
1199
+ const bigFs = {
1200
+ statSync: () => ({ size: 300 * 1024 * 1024 }),
1201
+ mkdtempSync: () => {
1202
+ mkdtemps++;
1203
+ return "/nope";
1204
+ },
1205
+ copyFileSync: () => {
1206
+ copies++;
1207
+ },
1208
+ rmSync: () => {},
1209
+ };
1210
+ resetTitleMemo();
1211
+ const t = readAntigravitySessionTitle(metaFor(), localFor(), {
1212
+ fs: bigFs,
1213
+ home: "/h",
1214
+ exec: () => {
1215
+ execs++;
1216
+ return "";
1217
+ },
1218
+ });
1219
+ check("超 256MB 的会话库:null,而且没拷、没建临时目录、没起 sqlite3", t === null && copies === 0 && mkdtemps === 0 && execs === 0, `copy=${copies} mkdtemp=${mkdtemps} exec=${execs}`);
1220
+ }
1221
+
1222
+ {
1223
+ let touched = 0;
1224
+ const noFs = new Proxy(
1225
+ {},
1226
+ {
1227
+ get: () => () => {
1228
+ touched++;
1229
+ throw new Error("不该碰盘");
1230
+ },
1231
+ }
1232
+ );
1233
+ const noExec = () => {
1234
+ touched++;
1235
+ throw new Error("不该起 sqlite3");
1236
+ };
1237
+ const run = (meta) => {
1238
+ resetTitleMemo();
1239
+ return readAntigravitySessionTitle(meta, localFor(), { fs: noFs, home: "/h", exec: noExec });
1240
+ };
1241
+ check("畸形 id:null,且一次文件读取都不发生", run({ "antigravity.google/conversation_id": "../../etc/passwd" }) === null && touched === 0, `touched=${touched}`);
1242
+ check("id 带引号(SQL/路径注入形状)也在读盘前停住", run({ "antigravity.google/conversation_id": `${ID}'; drop table steps--` }) === null && touched === 0, `touched=${touched}`);
1243
+ check("不是它家的帧:null,不读盘", run({ session_id: "sess_x" }) === null && touched === 0, `touched=${touched}`);
1244
+ check("_meta 缺席不抛", run(null) === null && touched === 0, `touched=${touched}`);
1245
+ }
1246
+
1247
+ {
1248
+ const home = agHome();
1249
+ writeDb(dbPath(home), [[1, 23, stepPayload({ title: "记住我" })]]);
1250
+ resetTitleMemo();
1251
+ const first = readAntigravitySessionTitle(metaFor(), localFor(), { home });
1252
+ fs.rmSync(dbPath(home));
1253
+ const again = readAntigravitySessionTitle(metaFor(), localFor(), { home });
1254
+ check("查到过就记住,库读不到了也不改口", first === "记住我" && again === "记住我", `${first} / ${again}`);
1255
+ resetTitleMemo();
1256
+ check("resetTitleMemo() 之后重新问:库没了就是 null", readAntigravitySessionTitle(metaFor(), localFor(), { home }) === null);
1257
+ fs.rmSync(home, { recursive: true, force: true });
1258
+ }
1259
+
1260
+ {
1261
+ const home = agHome();
1262
+ writeDb(dbPath(home), [[1, 23, stepPayload({ title: "WAL 库也读得出" })]], { wal: true });
1263
+ const before = fs.readFileSync(dbPath(home));
1264
+ const t = titleOf(home);
1265
+ check("WAL 模式的库读得出标题", t === "WAL 库也读得出", String(t));
1266
+ check("原库字节不变(读的是拷贝件,没碰客户端的活文件)", Buffer.compare(before, fs.readFileSync(dbPath(home))) === 0);
1267
+ fs.rmSync(home, { recursive: true, force: true });
1268
+ }
1269
+
1270
+ {
1271
+ const home = agHome();
1272
+ const proj = path.join(home, "repos", "ag-titled");
1273
+ fs.mkdirSync(path.join(proj, ".git"), { recursive: true });
1274
+ writeDb(dbPath(home), [[1, 23, stepPayload({ title: "排查待办记录异常", goal: "待办记录不对" })]]);
1275
+ resetTitleMemo();
1276
+ check("readSessionTitle 走到 Antigravity 这一支", readSessionTitle(localFor(), { home, env: {}, meta: metaFor() }) === "排查待办记录异常");
1277
+ fs.appendFileSync(dbPath(home), agBytes(ID, proj));
1278
+ resetTitleMemo();
1279
+ const idn = readSessionIdentity(localFor(), { home, env: {}, meta: metaFor(), tmp: path.join(home, "unused-tmp") });
1280
+ check("readSessionIdentity 一次拿到标题和工作区", idn.title === "排查待办记录异常" && idn.workspace === "ag-titled", JSON.stringify(idn));
1281
+ resetTitleMemo();
1282
+ const bare = readSessionIdentity(localFor(), { home, env: {}, meta: { progressToken: "p1" }, tmp: path.join(home, "unused-tmp") });
1283
+ check("帧里没有会话 id 时标题也不盖", bare.title === null, JSON.stringify(bare));
1284
+ fs.rmSync(home, { recursive: true, force: true });
1285
+ }
1286
+
1287
+ check("跑完 tmp 下没有 ag-title-* 残留(拷贝件用完即删)", agTmpLeft().length === tmpBefore, agTmpLeft().join(","));
1288
+ }
1289
+ }
1290
+
1291
+ console.log("\n\x1b[1mCodex:_meta 的 thread_id 精确归属 + session_index.jsonl 里的线程名\x1b[0m");
1292
+ {
1293
+ const ID = "01a0935a-5d74-7680-8d59-be86c5e590c3";
1294
+ const metaFor = (id = ID) => ({
1295
+ "x-codex-turn-metadata": { session_id: id, thread_id: id, workspace_kind: "project", turn_id: "01a09376-ce13-7862-8a7e-eeef069cd3cf", model: "gpt-6-astra" },
1296
+ threadId: id,
1297
+ itemId: "ctc_0ac0",
1298
+ progressToken: 1,
1299
+ });
1300
+ const row = (id, name, at = "2026-09-12T02:02:56.925418Z") =>
1301
+ JSON.stringify({ id, thread_name: name, updated_at: at }) + "\n";
1302
+ const cxHome = (lines) => {
1303
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-cx-"));
1304
+ fs.mkdirSync(path.join(home, ".codex"), { recursive: true });
1305
+ if (lines !== null) fs.writeFileSync(path.join(home, ".codex", "session_index.jsonl"), lines);
1306
+ return home;
1307
+ };
1308
+ const at = (meta, home, env = {}) => {
1309
+ resetTitleMemo();
1310
+ return readCodexSessionTitle(meta, { home, env });
1311
+ };
1312
+
1313
+ check("thread_id 在 x-codex-turn-metadata 里", codexThreadId(metaFor()) === ID);
1314
+ check("没有那段时兜底顶层 threadId", codexThreadId({ threadId: ID, progressToken: 1 }) === ID);
1315
+ check("前后空白去掉再判(sid 那一路和这一路必须给同一个答案)", codexThreadId({ threadId: ` ${ID} ` }) === ID);
1316
+ check("不是它家的帧(没有这两个键):null", codexThreadId({ session_id: "sess_x", progressToken: 1 }) === null);
1317
+ check("_meta 缺席不抛", codexThreadId(null) === null && codexThreadId(undefined) === null && codexThreadId("x") === null);
1318
+ check("形状不对的 id 一律不认", codexThreadId({ threadId: "01a0935a" }) === null && codexThreadId({ threadId: "../../etc/passwd" }) === null);
1319
+
1320
+ check("默认是 ~/.codex", codexHome({ env: {}, home: "/h" }) === path.join("/h", ".codex"));
1321
+ check("CODEX_HOME 覆盖(写死路径会读到另一个安装的索引)", codexHome({ env: { CODEX_HOME: "/tmp/cx" }, home: "/h" }) === "/tmp/cx");
1322
+ check("CODEX_HOME 是空白串时当没设", codexHome({ env: { CODEX_HOME: " " }, home: "/h" }) === path.join("/h", ".codex"));
1323
+
1324
+ {
1325
+ const home = cxHome(row("00000000-0000-4000-8000-000000000001", "别的线程") + row(ID, "检查 Todo 清单链路"));
1326
+ check("正常命中:拿到这一段线程的名字", at(metaFor(), home) === "检查 Todo 清单链路");
1327
+ check("顶层 threadId 兜底形式也命中", at({ threadId: ID }, home) === "检查 Todo 清单链路");
1328
+ check("索引里没有的线程:null", at(metaFor("00000000-0000-4000-8000-0000000000ff"), home) === null);
1329
+ fs.rmSync(home, { recursive: true, force: true });
1330
+ }
1331
+
1332
+ {
1333
+ const home = cxHome(row(ID, "旧名字") + row("00000000-0000-4000-8000-000000000001", "别的线程") + row(ID, "改过之后的名字"));
1334
+ check("同 id 多行取最后一行(从头找会读到被改掉的旧名)", at(metaFor(), home) === "改过之后的名字");
1335
+ fs.rmSync(home, { recursive: true, force: true });
1336
+ }
1337
+
1338
+ {
1339
+ const home = cxHome(row(ID, "默认目录里的名字"));
1340
+ const other = fs.mkdtempSync(path.join(os.tmpdir(), "aic-cx2-"));
1341
+ fs.writeFileSync(path.join(other, "session_index.jsonl"), row(ID, "CODEX_HOME 指过去的名字"));
1342
+ check("CODEX_HOME 指到哪就读哪", at(metaFor(), home, { CODEX_HOME: other }) === "CODEX_HOME 指过去的名字");
1343
+ fs.rmSync(home, { recursive: true, force: true });
1344
+ fs.rmSync(other, { recursive: true, force: true });
1345
+ }
1346
+
1347
+ {
1348
+ const bad = cxHome('{"id":"' + ID + '"\n' + row(ID, "") + row(ID, " "));
1349
+ check("坏 JSON 行 + thread_name 是空串/全空白 → null,不抛", at(metaFor(), bad) === null);
1350
+ const missing = cxHome(JSON.stringify({ id: ID, updated_at: "2026-09-12T02:02:56Z" }) + "\n");
1351
+ check("最后一行缺 thread_name → null(不许往前翻去捡旧名)", at(metaFor(), missing) === null);
1352
+ const stale = cxHome(row(ID, "上一次的名字") + JSON.stringify({ id: ID }) + "\n");
1353
+ check("最后一行没名字时前面那行也不算数", at(metaFor(), stale) === null);
1354
+ const wrongType = cxHome(JSON.stringify({ id: ID, thread_name: { t: "x" } }) + "\n");
1355
+ check("thread_name 不是字符串 → null", at(metaFor(), wrongType) === null);
1356
+ const nofile = cxHome(null);
1357
+ check("索引文件还没建 → null,不抛", at(metaFor(), nofile) === null);
1358
+ for (const h of [bad, missing, stale, wrongType, nofile]) fs.rmSync(h, { recursive: true, force: true });
1359
+ }
1360
+
1361
+ {
1362
+ const home = cxHome(row(ID, "真名") + row("00000000-0000-4000-8000-000000000002", `别人提到了 "id":"${ID}"`));
1363
+ check("字面命中但 id 对不上的行跳过,继续往前找", at(metaFor(), home) === "真名");
1364
+ fs.rmSync(home, { recursive: true, force: true });
1365
+ }
1366
+
1367
+ {
1368
+ let touched = 0;
1369
+ const noFs = new Proxy(
1370
+ {},
1371
+ {
1372
+ get: () => () => {
1373
+ touched++;
1374
+ throw new Error("不该碰盘");
1375
+ },
1376
+ }
1377
+ );
1378
+ const run = (meta) => {
1379
+ resetTitleMemo();
1380
+ return readCodexSessionTitle(meta, { fs: noFs, home: "/h", env: {} });
1381
+ };
1382
+ check("畸形 id:null,且一次文件读取都不发生", run({ threadId: "../../etc/passwd" }) === null && touched === 0, `touched=${touched}`);
1383
+ check("id 带引号(路径注入形状)也在读盘前停住", run({ threadId: `${ID}"` }) === null && touched === 0, `touched=${touched}`);
1384
+ check("不是它家的帧:null,不读盘", run({ session_id: "sess_x" }) === null && touched === 0, `touched=${touched}`);
1385
+ check("_meta 缺席不抛、不读盘", run(null) === null && touched === 0, `touched=${touched}`);
1386
+ }
1387
+
1388
+ {
1389
+ const tail = row("00000000-0000-4000-8000-000000000003", "尾部的别人") + row(ID, "超大索引里最近的那行");
1390
+ const buf = Buffer.from(tail, "utf8");
1391
+ const SIZE = (64 << 20) + buf.length;
1392
+ let wholeReads = 0;
1393
+ let lastPos = null;
1394
+ const bigFs = {
1395
+ statSync: () => ({ size: SIZE }),
1396
+ openSync: () => 7,
1397
+ closeSync: () => {},
1398
+ readSync: (fd, out, off, len, pos) => {
1399
+ lastPos = pos;
1400
+ const start = SIZE - buf.length;
1401
+ out.fill(0x20, 0, len);
1402
+ let n = 0;
1403
+ for (let i = 0; i < len; i++) {
1404
+ const abs = pos + i;
1405
+ if (abs >= SIZE) break;
1406
+ out[i] = abs >= start ? buf[abs - start] : 0x0a;
1407
+ n++;
1408
+ }
1409
+ return n;
1410
+ },
1411
+ readFileSync: () => {
1412
+ wholeReads++;
1413
+ throw new Error("不该整份读进内存");
1414
+ },
1415
+ };
1416
+ resetTitleMemo();
1417
+ const t = readCodexSessionTitle(metaFor(), { fs: bigFs, home: "/h", env: {} });
1418
+ check("超上限时只读尾部,仍能命中最近的那行", t === "超大索引里最近的那行" && wholeReads === 0, `${t} / whole=${wholeReads}`);
1419
+ check("读的位置就是文件末尾那 4MB", lastPos === SIZE - (4 << 20), String(lastPos));
1420
+ }
1421
+
1422
+ {
1423
+ const home = cxHome(row(ID, "记住我"));
1424
+ resetTitleMemo();
1425
+ let reads = 0;
1426
+ const counting = {
1427
+ statSync: (...a) => fs.statSync(...a),
1428
+ readFileSync: (...a) => {
1429
+ reads++;
1430
+ return fs.readFileSync(...a);
1431
+ },
1432
+ openSync: fs.openSync,
1433
+ readSync: fs.readSync,
1434
+ closeSync: fs.closeSync,
1435
+ };
1436
+ const first = readCodexSessionTitle(metaFor(), { home, env: {}, fs: counting });
1437
+ readCodexSessionTitle(metaFor(), { home, env: {}, fs: counting });
1438
+ readCodexSessionTitle(metaFor(), { home, env: {}, fs: counting });
1439
+ check("查到过就不再读第二次盘", first === "记住我" && reads === 1, `${first} / 读了 ${reads} 次`);
1440
+ fs.rmSync(path.join(home, ".codex", "session_index.jsonl"));
1441
+ check("查到过就记住,索引没了也不改口", readCodexSessionTitle(metaFor(), { home, env: {} }) === "记住我");
1442
+
1443
+ resetTitleMemo();
1444
+ reads = 0;
1445
+ check("索引还没落盘:null", readCodexSessionTitle(metaFor(), { home, env: {}, fs: counting }) === null);
1446
+ check("退避窗内不重读(否则每帧都要扫一遍索引)", readCodexSessionTitle(metaFor(), { home, env: {}, fs: counting }) === null && reads === 0, `读了 ${reads} 次`);
1447
+ fs.writeFileSync(path.join(home, ".codex", "session_index.jsonl"), row(ID, "8 秒后才落盘的名字"));
1448
+ resetTitleMemo();
1449
+ check("落盘之后补得上", readCodexSessionTitle(metaFor(), { home, env: {} }) === "8 秒后才落盘的名字");
1450
+ fs.rmSync(home, { recursive: true, force: true });
1451
+ }
1452
+
1453
+ {
1454
+ const long = "标".repeat(80);
1455
+ const home = cxHome(row(ID, long));
1456
+ const t = at(metaFor(), home);
1457
+ check("线程名截到 60 个字符", t === long.slice(0, 60) && t.length === 60, String(t?.length));
1458
+ fs.rmSync(home, { recursive: true, force: true });
1459
+ }
1460
+
1461
+ {
1462
+ const home = cxHome(row(ID, "协议级认到的 Codex 线程名"));
1463
+ fs.mkdirSync(path.join(home, ".claude", "sessions"), { recursive: true });
1464
+ fs.writeFileSync(
1465
+ path.join(home, ".claude", "sessions", "7101.json"),
1466
+ JSON.stringify({ pid: 7101, sessionId: "s", name: "本机取证认到的名字", nameSource: "generated" })
1467
+ );
1468
+ const local = { clientPid: 7101, hostSessionId: null, sessionName: null, clientCommand: null, userDataDir: null, brandAppDir: null };
1469
+ resetTitleMemo();
1470
+ check(
1471
+ "readSessionTitle 走到 Codex 这一支(协议级优先于会话记录文件)",
1472
+ readSessionTitle(local, { home, env: {}, meta: metaFor() }) === "协议级认到的 Codex 线程名"
1473
+ );
1474
+ resetTitleMemo();
1475
+ check(
1476
+ "同一个 local 没有 Codex meta 时行为一字不变",
1477
+ readSessionTitle(local, { home, env: {} }) === "本机取证认到的名字"
1478
+ );
1479
+ resetTitleMemo();
1480
+ check(
1481
+ "readSessionIdentity 也拿得到(工作区没有会话级证据时不盖进程级那份)",
1482
+ readSessionIdentity(local, { home, env: {}, meta: metaFor(), tmp: path.join(home, "unused-tmp") }).title === "协议级认到的 Codex 线程名"
1483
+ );
1484
+ fs.rmSync(home, { recursive: true, force: true });
1485
+ }
976
1486
  }
977
1487
 
978
1488
  console.log("\n\x1b[1mWindows:同样四段身份,换一套证据\x1b[0m");
@@ -1121,6 +1631,121 @@ console.log("\n\x1b[1m这一帧是主会话发的,还是哪个 subagent 发的
1121
1631
  fs.rmSync(home, { recursive: true, force: true });
1122
1632
  }
1123
1633
 
1634
+ console.log("\n\x1b[1mopencode:帧里只有 progressToken,靠「这一次调用的工具名 + 收到时刻」回 part 表对账\x1b[0m");
1635
+ {
1636
+ const AT = 1789609837611;
1637
+ const SID = "ses_f52f11014ffe5AvaDK6EDroFDE";
1638
+ const CWD = "/private/tmp/aic-oc-probe";
1639
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-oc-"));
1640
+ fs.mkdirSync(path.join(home, ".local", "share", "opencode"), { recursive: true });
1641
+ fs.writeFileSync(path.join(home, ".local", "share", "opencode", "opencode.db"), "");
1642
+
1643
+ const toolRow = (o = {}) => ({
1644
+ sid: SID,
1645
+ head: JSON.stringify({ type: "tool", tool: "agent-in-chrome_browser_status", callID: "call_00_x" }),
1646
+ title: "获取浏览器状态原始JSON结果",
1647
+ dir: CWD,
1648
+ ...o,
1649
+ });
1650
+ const filler = (o = {}) => ({ sid: SID, head: JSON.stringify({ type: "step-start" }), title: "获取浏览器状态原始JSON结果", dir: CWD, ...o });
1651
+
1652
+ let asked = null;
1653
+ let calls = [];
1654
+ const execOf = (rows) => (bin, args) => {
1655
+ asked = { bin, args, sql: args[args.length - 1] };
1656
+ calls.push(args);
1657
+ if (rows === "throw") throw new Error("no db");
1658
+ return typeof rows === "string" ? rows : JSON.stringify(rows);
1659
+ };
1660
+ const at = (tool, t, { rows = [toolRow()], opts = {} } = {}) => {
1661
+ resetTitleMemo();
1662
+ calls = [];
1663
+ return opencodeSessionOf(tool, t, { home, env: {}, cwd: CWD, exec: execOf(rows), ...opts });
1664
+ };
1665
+
1666
+ const r = at("browser_status", AT);
1667
+ check("对上了:标题和工作区一起拿回来", r?.title === "获取浏览器状态原始JSON结果" && r?.directory === CWD, JSON.stringify(r));
1668
+ check("走的是系统自带 sqlite3 的只读模式", asked?.bin === "/usr/bin/sqlite3" && asked?.args.includes("-readonly"));
1669
+ check("要的是 JSON 输出,不按分隔符切(标题里有换行/制表符也切不错)", asked?.args.includes(".mode json"));
1670
+ check("SQL 带 ±3s 时间窗", /between 1789609834611 and 1789609840611/.test(asked?.sql || ""), asked?.sql);
1671
+
1672
+ check(
1673
+ "server 名换了(按 _<工具名> 后缀认)照样对得上",
1674
+ at("browser_status", AT, { rows: [toolRow({ head: JSON.stringify({ type: "tool", tool: "我的浏览器_browser_status" }) })] })?.title ===
1675
+ "获取浏览器状态原始JSON结果"
1676
+ );
1677
+ check(
1678
+ "窗里别的工具的行不算数",
1679
+ at("browser_status", AT, { rows: [toolRow({ head: JSON.stringify({ type: "tool", tool: "agent-in-chrome_browser_click" }) })] }) === null
1680
+ );
1681
+ check("同一会话的多行(step-start / reasoning / tool)收敛成一个候选", at("browser_status", AT, { rows: [filler(), filler(), toolRow()] })?.title === "获取浏览器状态原始JSON结果");
1682
+
1683
+ check("窗内两个会话都调了同一个工具:null,不猜", at("browser_status", AT, { rows: [toolRow(), toolRow({ sid: "ses_other00000000000000000" })] }) === null);
1684
+
1685
+ const r6 = at("browser_status", AT, { rows: [toolRow({ title: "New session - 2026-09-17T01:50:32.427Z" })] });
1686
+ check("New session - <ISO> 是占位标题,不算名字;工作区照样留着", r6?.title === null && r6?.directory === CWD, JSON.stringify(r6));
1687
+
1688
+ check("会话目录对不上我们被 spawn 的目录:null", at("browser_status", AT, { rows: [toolRow({ dir: "/Users/u/proj-b" })] }) === null);
1689
+ check("畸形会话 id 一律不认(它要拼进下一段 SQL)", at("browser_status", AT, { rows: [toolRow({ sid: "ses_x' or 1=1 --" })] }) === null);
1690
+
1691
+ resetTitleMemo();
1692
+ calls = [];
1693
+ check(
1694
+ "工具名带引号/分号:null 且一次盘都不查",
1695
+ opencodeSessionOf("x'; drop table part; --", AT, { home, env: {}, cwd: CWD, exec: execOf([toolRow()]) }) === null && calls.length === 0,
1696
+ JSON.stringify(calls)
1697
+ );
1698
+ resetTitleMemo();
1699
+ calls = [];
1700
+ check(
1701
+ "大写工具名不认(我们自己的工具名全小写)",
1702
+ opencodeSessionOf("Browser_Status", AT, { home, env: {}, cwd: CWD, exec: execOf([toolRow()]) }) === null && calls.length === 0
1703
+ );
1704
+
1705
+ check("库读不动:null,不编", at("browser_status", AT, { rows: "throw" }) === null);
1706
+ check("输出不是 JSON:null", at("browser_status", AT, { rows: "not json at all" }) === null);
1707
+ check("窗里一行都没有:null", at("browser_status", AT, { rows: [] }) === null);
1708
+
1709
+ resetTitleMemo();
1710
+ let reads = 0;
1711
+ const counting = () => {
1712
+ reads += 1;
1713
+ return JSON.stringify([toolRow()]);
1714
+ };
1715
+ const c1 = opencodeSessionOf("browser_status", AT, { home, env: {}, cwd: CWD, exec: counting });
1716
+ const c2 = opencodeSessionOf("browser_status", AT, { home, env: {}, cwd: CWD, exec: counting });
1717
+ check("同一次调用只查一次盘", c1?.title === "获取浏览器状态原始JSON结果" && c2?.title === c1.title && reads === 1, `查了 ${reads} 次`);
1718
+
1719
+ check("默认落在 ~/.local/share/opencode", opencodeDataDir({ env: {}, home: "/h" }) === path.join("/h", ".local", "share", "opencode"));
1720
+ check("XDG_DATA_HOME 覆盖(写死路径会读到另一个安装的库)", opencodeDataDir({ env: { XDG_DATA_HOME: "/x" }, home: "/h" }) === "/x/opencode");
1721
+
1722
+ check("认 CLI(brew 里那个真身)", isOpencodeClient("/opt/homebrew/Cellar/opencode/1.18.31/bin/opencode"));
1723
+ check("认桌面端", isOpencodeClient("/Applications/OpenCode.app/Contents/MacOS/OpenCode"));
1724
+ check("不认同前缀的别的程序", !isOpencodeClient("/usr/local/bin/opencode-helper --x"));
1725
+ check("不认 Claude Code", !isOpencodeClient("/usr/local/bin/claude --mcp-config {}"));
1726
+
1727
+ resetTitleMemo();
1728
+ calls = [];
1729
+ const viaTitle = readSessionTitle(
1730
+ { clientCommand: "/opt/homebrew/bin/opencode", clientPid: 1 },
1731
+ { home, env: {}, exec: execOf([toolRow({ dir: process.cwd() })]), tool: "browser_status", at: AT }
1732
+ );
1733
+ check("接上了:opencode 的帧读得出会话名", viaTitle === "获取浏览器状态原始JSON结果", String(viaTitle));
1734
+ resetTitleMemo();
1735
+ calls = [];
1736
+ const notOurs = readSessionTitle(
1737
+ { clientCommand: "/usr/local/bin/claude", clientPid: 1 },
1738
+ { home, env: {}, exec: execOf([toolRow({ dir: process.cwd() })]), tool: "browser_status", at: AT }
1739
+ );
1740
+ check(
1741
+ "别家客户端不为这条路付代价(opencode 那条查询一次都没发)",
1742
+ notOurs === null && calls.every((a) => !a.includes(".mode json")),
1743
+ JSON.stringify(calls)
1744
+ );
1745
+
1746
+ fs.rmSync(home, { recursive: true, force: true });
1747
+ }
1748
+
1124
1749
  console.log("\n\x1b[1m真机上跑一遍:不许抛,也不许卡住\x1b[0m");
1125
1750
  {
1126
1751
  const t0 = Date.now();