opencode-codex-memory 0.10.1 → 0.10.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.
Files changed (45) hide show
  1. package/README.md +10 -12
  2. package/dist/src/agent-health.js +10 -7
  3. package/dist/src/capture.js +7 -7
  4. package/dist/src/citation.js +12 -3
  5. package/dist/src/claude-import.js +1 -3
  6. package/dist/src/codex-interop.js +20 -5
  7. package/dist/src/db.d.ts +0 -2
  8. package/dist/src/db.js +0 -4
  9. package/dist/src/git-baseline.d.ts +4 -6
  10. package/dist/src/git-baseline.js +45 -68
  11. package/dist/src/host-client.d.ts +5 -0
  12. package/dist/src/host-client.js +24 -0
  13. package/dist/src/index.d.ts +1 -1
  14. package/dist/src/index.js +56 -99
  15. package/dist/src/llm.d.ts +4 -1
  16. package/dist/src/llm.js +41 -13
  17. package/dist/src/options.d.ts +7 -0
  18. package/dist/src/options.js +20 -2
  19. package/dist/src/paths.d.ts +1 -0
  20. package/dist/src/paths.js +5 -2
  21. package/dist/src/phase1.js +12 -21
  22. package/dist/src/phase2.js +3 -3
  23. package/dist/src/reasoning-variant.d.ts +7 -0
  24. package/dist/src/reasoning-variant.js +11 -2
  25. package/dist/src/rollout-input.js +3 -5
  26. package/dist/src/session-version.js +4 -5
  27. package/dist/src/source.js +6 -2
  28. package/dist/src/store.d.ts +3 -2
  29. package/dist/src/store.js +72 -47
  30. package/dist/src/v2/agents.js +11 -14
  31. package/dist/src/v2/model-readiness.js +3 -1
  32. package/dist/src/v2/plugin.js +81 -109
  33. package/dist/src/v2/search-sandbox.js +1 -1
  34. package/dist/src/v2/service.js +5 -0
  35. package/dist/src/v2/shim.d.ts +3 -0
  36. package/dist/src/v2/shim.js +144 -90
  37. package/dist/src/v2/status-rpc.js +40 -14
  38. package/dist/src/v2/status.js +4 -7
  39. package/dist/src/v2/tools.d.ts +15 -9
  40. package/dist/src/v2/tools.js +9 -9
  41. package/dist/src/v2/tui.js +14 -4
  42. package/dist/src/workspace.js +13 -4
  43. package/dist/tools/control.js +29 -28
  44. package/dist/tools/memory.js +163 -89
  45. package/package.json +22 -9
package/README.md CHANGED
@@ -34,9 +34,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
34
34
  ```jsonc
35
35
  {
36
36
  "$schema": "https://opencode.ai/config.json",
37
- "plugins": [
38
- { "package": "opencode-codex-memory@0.10.1" }
39
- ]
37
+ "plugins": [{ "package": "opencode-codex-memory@0.10.2" }],
40
38
  }
41
39
  ```
42
40
 
@@ -45,7 +43,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
45
43
  ```json
46
44
  {
47
45
  "$schema": "https://opencode.ai/config.json",
48
- "plugin": ["opencode-codex-memory@0.10.1"]
46
+ "plugin": ["opencode-codex-memory@0.10.2"]
49
47
  }
50
48
  ```
51
49
 
@@ -93,14 +91,14 @@ privacy, backups, and relocation.
93
91
 
94
92
  ## Start here
95
93
 
96
- | I want to… | Read |
97
- |---|---|
98
- | Recall past work, save a note, or pause learning | [Using memory](./docs/usage.md) |
99
- | Choose or switch memory behavior | [Memory V1 and Memory V2](./docs/memory-versions.md) |
100
- | Set models, learning frequency, or other options | [Configuration](./docs/configuration.md) |
101
- | Find, back up, move, or reset my data | [Storage and privacy](./docs/storage-and-privacy.md) |
102
- | Share with Codex CLI or import Claude Code memories | [Integrations](./docs/integrations.md) |
103
- | Fix missing memory or check an update | [Troubleshooting](./docs/troubleshooting.md) |
94
+ | I want to… | Read |
95
+ | --------------------------------------------------- | ---------------------------------------------------- |
96
+ | Recall past work, save a note, or pause learning | [Using memory](./docs/usage.md) |
97
+ | Choose or switch memory behavior | [Memory V1 and Memory V2](./docs/memory-versions.md) |
98
+ | Set models, learning frequency, or other options | [Configuration](./docs/configuration.md) |
99
+ | Find, back up, move, or reset my data | [Storage and privacy](./docs/storage-and-privacy.md) |
100
+ | Share with Codex CLI or import Claude Code memories | [Integrations](./docs/integrations.md) |
101
+ | Fix missing memory or check an update | [Troubleshooting](./docs/troubleshooting.md) |
104
102
 
105
103
  ## Learn more and contribute
106
104
 
@@ -11,7 +11,11 @@ const SAFE_ALLOWS = {
11
11
  memorize: new Set(["read", "edit", "write", "glob", "grep", "external_directory"]),
12
12
  "memorize-extract": new Set(["StructuredOutput"]),
13
13
  };
14
- const initialEntry = () => ({ source: "missing", healthy: false, issues: ["config hook has not run"] });
14
+ const initialEntry = () => ({
15
+ source: "missing",
16
+ healthy: false,
17
+ issues: ["config hook has not run"],
18
+ });
15
19
  let snapshot = {
16
20
  observed: false,
17
21
  generationEnabled: null,
@@ -102,11 +106,7 @@ export function recordAgentConfig(config, generationEnabled, shipped) {
102
106
  const agents = {};
103
107
  for (const name of AGENT_NAMES) {
104
108
  const definition = configured?.[name];
105
- const source = definition === undefined
106
- ? "missing"
107
- : definitionsEqual(shipped[name], definition)
108
- ? "shipped"
109
- : "user_override";
109
+ const source = definition === undefined ? "missing" : definitionsEqual(shipped[name], definition) ? "shipped" : "user_override";
110
110
  agents[name] = inspectAgent(name, definition, source);
111
111
  if (!generationEnabled && definition === undefined) {
112
112
  agents[name] = { source: "missing", healthy: true, issues: ["generation disabled; agent not injected"] };
@@ -120,7 +120,10 @@ export function getAgentHealth() {
120
120
  generationEnabled: snapshot.generationEnabled,
121
121
  agents: {
122
122
  memorize: { ...snapshot.agents.memorize, issues: [...snapshot.agents.memorize.issues] },
123
- "memorize-extract": { ...snapshot.agents["memorize-extract"], issues: [...snapshot.agents["memorize-extract"].issues] },
123
+ "memorize-extract": {
124
+ ...snapshot.agents["memorize-extract"],
125
+ issues: [...snapshot.agents["memorize-extract"].issues],
126
+ },
124
127
  },
125
128
  };
126
129
  }
@@ -1,7 +1,7 @@
1
1
  import { SCAN_LIMIT } from "./store.js";
2
2
  import { getPluginInput } from "./llm.js";
3
3
  import { recordDiscoveryStatus } from "./diagnostics.js";
4
- import { hostListSessionsGlobal, hostPartType, hostSessionMessages, pluginHttpGet, withHostTimeout } from "./host-client.js";
4
+ import { hostListSessionsGlobal, hostPartType, hostSessionMessages, pluginHttpGet, withHostTimeout, } from "./host-client.js";
5
5
  const API_TIMEOUT_MS = 60_000;
6
6
  /**
7
7
  * Global session discovery through the official API:
@@ -22,9 +22,7 @@ export function resetDiscoveryCacheForTest() {
22
22
  }
23
23
  export async function listRecentSessions(limit = SCAN_LIMIT) {
24
24
  const now = Date.now();
25
- if (discoveryCache &&
26
- discoveryCache.limit >= limit &&
27
- now - discoveryCache.at < DISCOVERY_CACHE_MS) {
25
+ if (discoveryCache && discoveryCache.limit >= limit && now - discoveryCache.at < DISCOVERY_CACHE_MS) {
28
26
  return discoveryCache.rows.slice(0, limit);
29
27
  }
30
28
  const client = getPluginInput()?.client;
@@ -103,9 +101,11 @@ export async function loadTranscript(sessionId) {
103
101
  for (const part of row?.parts ?? []) {
104
102
  const question = part;
105
103
  const answer = question?.state?.output;
106
- const userReply = question?.tool === "question" && question.ignored !== true
107
- && typeof answer === "string" && answer.startsWith("User has answered your questions:")
108
- && /"="(?!Unanswered")[^"]+"/.test(answer)
104
+ const userReply = question?.tool === "question" &&
105
+ question.ignored !== true &&
106
+ typeof answer === "string" &&
107
+ answer.startsWith("User has answered your questions:") &&
108
+ /"="(?!Unanswered")[^"]+"/.test(answer)
109
109
  ? { question: JSON.stringify(question.state?.input ?? {}), answer }
110
110
  : undefined;
111
111
  out.push({
@@ -21,7 +21,10 @@ export function parseCitationBody(body) {
21
21
  continue;
22
22
  const sessions = trimmed.match(SESSIONS_LINE_RE);
23
23
  if (sessions) {
24
- for (const id of sessions[1].split(/[\s,]+/).map((s) => s.trim()).filter(Boolean)) {
24
+ for (const id of sessions[1]
25
+ .split(/[\s,]+/)
26
+ .map((s) => s.trim())
27
+ .filter(Boolean)) {
25
28
  if (!seen.has(id)) {
26
29
  seen.add(id);
27
30
  sessionIds.push(id);
@@ -108,7 +111,10 @@ export function parseCitations(text) {
108
111
  }
109
112
  else if (entriesBlock && entries.length === 0) {
110
113
  // Legacy format: <citation_entries> held a comma-separated session-id list.
111
- for (const id of entriesBlock.split(",").map((s) => s.trim()).filter(Boolean)) {
114
+ for (const id of entriesBlock
115
+ .split(",")
116
+ .map((s) => s.trim())
117
+ .filter(Boolean)) {
112
118
  if (!seen.has(id)) {
113
119
  seen.add(id);
114
120
  sessionIds.push(id);
@@ -134,5 +140,8 @@ export function extractCitedSessionIds(text) {
134
140
  return Array.from(seen);
135
141
  }
136
142
  export function stripCitations(text) {
137
- return text.replace(CITATION_BLOCK_RE, "").replace(/[ \t]*\n{3,}/g, "\n\n").trimEnd();
143
+ return text
144
+ .replace(CITATION_BLOCK_RE, "")
145
+ .replace(/[ \t]*\n{3,}/g, "\n\n")
146
+ .trimEnd();
138
147
  }
@@ -402,9 +402,7 @@ export function syncClaudeImport(opts) {
402
402
  const allFiles = discoverExternalMemoryFiles(claudeHome);
403
403
  const byProject = groupByProject(allFiles);
404
404
  const sourceKeys = new Set(byProject.keys());
405
- const allowlist = opts.projects && opts.projects.length > 0
406
- ? new Set(opts.projects.filter(isSafeProjectKey))
407
- : null;
405
+ const allowlist = opts.projects && opts.projects.length > 0 ? new Set(opts.projects.filter(isSafeProjectKey)) : null;
408
406
  // Desired set: allowlist, or every source project (cwd checked per project).
409
407
  const desired = new Set();
410
408
  if (allowlist) {
@@ -2,6 +2,7 @@ import fs from "fs";
2
2
  import path from "path";
3
3
  import os from "os";
4
4
  import { currentMemoryVersion } from "./memory-version.js";
5
+ import { pluginOptions } from "./options.js";
5
6
  import { memoryRoot } from "./paths.js";
6
7
  import { isValidV2Summary } from "./workspace.js";
7
8
  import { readRegularFileNoFollow, safeResolveUnderRoot, writeRegularFileNoFollow } from "./path-guard.js";
@@ -470,7 +471,7 @@ function classifyCodexInterop(opts, warn) {
470
471
  codexMemoryRoot,
471
472
  codexVersion: version.version,
472
473
  importEnabled: opts.import,
473
- exportEnabled: opts.export,
474
+ exportEnabled: opts.export && currentMemoryVersion() === pluginOptions.version,
474
475
  },
475
476
  };
476
477
  }
@@ -499,6 +500,17 @@ function readIfFile(file) {
499
500
  return null;
500
501
  }
501
502
  }
503
+ /** Only a confirmed missing artifact authorizes forgetting its previous copy. */
504
+ function readSource(file) {
505
+ try {
506
+ return readRegularFileNoFollow(file).content;
507
+ }
508
+ catch (error) {
509
+ if (error.code === "ENOENT")
510
+ return null;
511
+ throw error;
512
+ }
513
+ }
502
514
  /** Writes only when content differs (codex byte-equality sync). Returns true when written. */
503
515
  function writeIfChanged(file, content) {
504
516
  const next = typeof content === "string" ? Buffer.from(content, "utf8") : content;
@@ -547,8 +559,10 @@ function syncExtension(sourceRoot, targetRoot, extension, subdir, instructions,
547
559
  return false;
548
560
  const extensionDir = safeResolveUnderRoot(targetRoot, path.join("extensions", extension));
549
561
  const resDir = safeResolveUnderRoot(targetRoot, path.join("extensions", extension, "resources", subdir));
550
- const sourceAvailable = artifacts.some((name) => readIfFile(path.join(sourceRoot, name)) !== null);
551
- if (!sourceAvailable) {
562
+ const sources = artifacts.map((name) => [name, readSource(path.join(sourceRoot, name))]);
563
+ if (!fs.statSync(sourceRoot).isDirectory())
564
+ return false;
565
+ if (sources.every(([, content]) => content === null)) {
552
566
  // Root exists but the artifacts for this store are gone (e.g. codex memory
553
567
  // cleared, or a v2 root with no summary). Drop our copies so the workspace
554
568
  // diff carries the deletion signal. Keep instructions.md — prune and
@@ -562,8 +576,7 @@ function syncExtension(sourceRoot, targetRoot, extension, subdir, instructions,
562
576
  if (writeIfChanged(path.join(extensionDir, "instructions.md"), instructions))
563
577
  changed = true;
564
578
  const active = new Set(artifacts);
565
- for (const name of artifacts) {
566
- const source = readIfFile(path.join(sourceRoot, name));
579
+ for (const [name, source] of sources) {
567
580
  const target = path.join(resDir, name);
568
581
  if (source === null) {
569
582
  if (removeIfPresent(target))
@@ -631,6 +644,8 @@ function exportPlan(codexVersion) {
631
644
  };
632
645
  }
633
646
  export function exportToCodexMemory(codexMemoryRoot, version) {
647
+ if (currentMemoryVersion() !== pluginOptions.version)
648
+ return false;
634
649
  let rootStat;
635
650
  try {
636
651
  rootStat = fs.statSync(codexMemoryRoot);
package/dist/src/db.d.ts CHANGED
@@ -2,8 +2,6 @@ import { Database } from "bun:sqlite";
2
2
  import type { MemoryVersion } from "./options.js";
3
3
  /** Both versioned handles stay open while their pipelines run concurrently. */
4
4
  export declare function openDb(version?: MemoryVersion): Database;
5
- /** One-shot connection for reset across versioned files. Caller must close. */
6
- export declare function openTransientDb(dbPath: string): Database;
7
5
  /** Always memory.db — shared session_meta catalog across versions. */
8
6
  export declare function openSessionMetaDb(): Database;
9
7
  export declare function closeDb(): void;
package/dist/src/db.js CHANGED
@@ -74,10 +74,6 @@ function connection(dbPath) {
74
74
  export function openDb(version) {
75
75
  return connection(memoryDbPath(version));
76
76
  }
77
- /** One-shot connection for reset across versioned files. Caller must close. */
78
- export function openTransientDb(dbPath) {
79
- return openSqlite(dbPath);
80
- }
81
77
  /** Always memory.db — shared session_meta catalog across versions. */
82
78
  export function openSessionMetaDb() {
83
79
  return connection(sessionMetaDbPath());
@@ -7,9 +7,8 @@ export interface WorkspaceDiff {
7
7
  changes: WorkspaceChange[];
8
8
  unifiedDiff: string;
9
9
  /**
10
- * Content hash of every `extensions/` file at capture time. Notes written
11
- * while the consolidator runs are not in this diff; resetBaseline keeps
12
- * them out of the new baseline so the next run still sees them.
10
+ * Git blob for each extension input seen by the consolidator. The new
11
+ * baseline stages these exact bytes even if a file has since disappeared.
13
12
  */
14
13
  extensionSnapshot?: ReadonlyMap<string, string>;
15
14
  }
@@ -28,8 +27,7 @@ export declare function captureWorkspaceDiff(): Promise<WorkspaceDiff>;
28
27
  * single-commit baseline so deleted/redacted memory content is not retained
29
28
  * in unreachable git objects (history is intentionally dropped).
30
29
  *
31
- * Divergence: `extensions/` files added or edited after `captured` (e.g. a
32
- * memory_add_note during the consolidator turn) stay out of the baseline, so
33
- * they appear as added in the next diff instead of never being consolidated.
30
+ * Stage captured extension blobs alongside live consolidator outputs. This
31
+ * preserves concurrent additions, edits AND deletions for the next diff.
34
32
  */
35
33
  export declare function resetBaseline(captured?: ReadonlyMap<string, string>): Promise<boolean>;
@@ -1,4 +1,3 @@
1
- import { createHash } from "crypto";
2
1
  import fs from "fs";
3
2
  import path from "path";
4
3
  import { memoryRoot } from "./paths.js";
@@ -25,24 +24,11 @@ function isHiddenBaselinePath(filepath) {
25
24
  return filepath.split("/").some((part) => part.startsWith("."));
26
25
  }
27
26
  const EXTENSIONS_PREFIX = "extensions/";
28
- function workdirHash(dir, filepath) {
29
- try {
30
- const file = safeResolveUnderRoot(dir, filepath);
31
- if (fs.lstatSync(file).size > MAX_BASELINE_FILE_BYTES)
32
- return null;
33
- const content = readRegularFileNoFollow(file).content;
34
- return createHash("sha1").update(content).digest("hex");
35
- }
36
- catch {
37
- return null;
38
- }
39
- }
40
27
  function removeDiffArtifact(dir) {
41
28
  try {
42
29
  fs.unlinkSync(path.join(dir, DIFF_ARTIFACT));
43
30
  }
44
- catch {
45
- }
31
+ catch { }
46
32
  }
47
33
  function baselineVersionPath(dir) {
48
34
  return path.join(dir, ".git", BASELINE_VERSION_FILE);
@@ -68,10 +54,11 @@ function isOversizedFile(dir, filepath) {
68
54
  return false;
69
55
  }
70
56
  }
71
- function statusMatrix(dir) {
57
+ function statusMatrix(dir, gitdir) {
72
58
  return isogit.statusMatrix({
73
59
  fs,
74
60
  dir,
61
+ gitdir,
75
62
  filter: (filepath) => !isHiddenBaselinePath(filepath) && !isOversizedFile(dir, filepath),
76
63
  });
77
64
  }
@@ -105,34 +92,6 @@ async function ensureVersionedBaseline(dir) {
105
92
  if (!(await hasVersionedBaseline(dir)))
106
93
  await initEmptyBaseline(dir);
107
94
  }
108
- // statusMatrix rows are [filepath, head, workdir, stage]; head !== workdir
109
- // means the working tree differs from HEAD (added, modified, or deleted).
110
- async function stageAll(dir, skip) {
111
- const matrix = await statusMatrix(dir);
112
- let changes = 0;
113
- for (const [filepath, head, workdir, stage] of matrix) {
114
- if (head === 1 && workdir === 1 && stage === 1)
115
- continue;
116
- if (workdir !== 0 && skip?.(filepath))
117
- continue;
118
- if (workdir === 0) {
119
- // isogit.add throws on deleted files; they must be staged via remove
120
- await isogit.remove({ fs, dir, filepath });
121
- }
122
- else {
123
- await isogit.add({ fs, dir, filepath });
124
- }
125
- if (head !== workdir)
126
- changes++;
127
- }
128
- return changes;
129
- }
130
- async function commitBaseline(dir, skip) {
131
- await stageAll(dir, skip);
132
- const oid = await isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR });
133
- fs.writeFileSync(baselineVersionPath(dir), BASELINE_VERSION);
134
- return oid;
135
- }
136
95
  /**
137
96
  * Mirrors codex prepare_memory_workspace: a current-version baseline is
138
97
  * preserved untouched so the phase-2 diff spans last-successful-run -> now —
@@ -172,12 +131,12 @@ async function readBaselineText(dir, headOid, filepath) {
172
131
  return "";
173
132
  }
174
133
  }
175
- function readWorkdirText(dir, filepath) {
134
+ function readWorkingFile(dir, filepath) {
176
135
  const file = safeResolveUnderRoot(dir, filepath);
177
136
  if (fs.lstatSync(file).size > MAX_BASELINE_FILE_BYTES) {
178
137
  throw new Error(`file grew beyond the snapshot file limit during diff: ${filepath}`);
179
138
  }
180
- return readRegularFileNoFollow(file).content.toString("utf8");
139
+ return readRegularFileNoFollow(file).content;
181
140
  }
182
141
  /**
183
142
  * Every non-hidden regular file above the snapshot limit. Used to invalidate a
@@ -209,8 +168,7 @@ function collectOversizedPaths(dir) {
209
168
  if (fs.lstatSync(full).size > MAX_BASELINE_FILE_BYTES)
210
169
  out.push(rel);
211
170
  }
212
- catch {
213
- }
171
+ catch { }
214
172
  }
215
173
  }
216
174
  };
@@ -261,21 +219,23 @@ export async function captureWorkspaceDiff() {
261
219
  // no commits yet — every file diffs against empty
262
220
  }
263
221
  const patches = [];
222
+ const extensionSnapshot = new Map();
264
223
  for (const [filepath, head, workdir] of changedRows) {
265
224
  const oldText = head === 1 && headOid ? await readBaselineText(dir, headOid, filepath) : "";
266
- const newText = workdir === 0 ? "" : readWorkdirText(dir, filepath);
225
+ const content = workdir === 0 ? null : readWorkingFile(dir, filepath);
226
+ const newText = content?.toString("utf8") ?? "";
227
+ if (content && filepath.startsWith(EXTENSIONS_PREFIX))
228
+ extensionSnapshot.set(filepath, await isogit.writeBlob({ fs, dir, blob: content }));
267
229
  // Per-file patches render in full; only the global 4 MiB truncation in
268
230
  // writeWorkspaceDiff caps the rendered diff. Files above the baseline
269
231
  // snapshot limit never reach this loop.
270
232
  patches.push(createPatch(filepath, oldText, newText));
271
233
  }
272
- const extensionSnapshot = new Map();
273
234
  for (const [filepath, , workdir] of matrix) {
274
- if (workdir === 0 || !filepath.startsWith(EXTENSIONS_PREFIX))
275
- continue;
276
- const hash = workdirHash(dir, filepath);
277
- if (hash)
278
- extensionSnapshot.set(filepath, hash);
235
+ if (workdir === 1 && filepath.startsWith(EXTENSIONS_PREFIX) && headOid) {
236
+ // Unchanged at status capture: use HEAD, not a second live read.
237
+ extensionSnapshot.set(filepath, (await isogit.readBlob({ fs, dir, oid: headOid, filepath })).oid);
238
+ }
279
239
  }
280
240
  return { changes, unifiedDiff: patches.join("\n"), extensionSnapshot };
281
241
  }
@@ -284,25 +244,42 @@ export async function captureWorkspaceDiff() {
284
244
  * single-commit baseline so deleted/redacted memory content is not retained
285
245
  * in unreachable git objects (history is intentionally dropped).
286
246
  *
287
- * Divergence: `extensions/` files added or edited after `captured` (e.g. a
288
- * memory_add_note during the consolidator turn) stay out of the baseline, so
289
- * they appear as added in the next diff instead of never being consolidated.
247
+ * Stage captured extension blobs alongside live consolidator outputs. This
248
+ * preserves concurrent additions, edits AND deletions for the next diff.
290
249
  */
291
250
  export async function resetBaseline(captured) {
292
251
  try {
293
252
  const dir = memoryRoot();
294
253
  removeDiffArtifact(dir);
295
- fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
296
- await isogit.init({ fs, dir });
297
- const skip = captured
298
- ? (filepath) => {
299
- if (!filepath.startsWith(EXTENSIONS_PREFIX))
300
- return false;
301
- const hash = workdirHash(dir, filepath);
302
- return hash !== null && captured.get(filepath) !== hash;
254
+ await ensureVersionedBaseline(dir);
255
+ const old = path.join(dir, ".git");
256
+ // Inside plugin-owned metadata: a crash while building leaves the old
257
+ // baseline valid, and the next attempt discards the unfinished staging dir.
258
+ const gitdir = path.join(old, "codex-next");
259
+ fs.rmSync(gitdir, { recursive: true, force: true });
260
+ await isogit.init({ fs, dir, gitdir });
261
+ for (const [filepath, , workdir] of await statusMatrix(dir, gitdir)) {
262
+ if (workdir !== 0 && !(captured && filepath.startsWith(EXTENSIONS_PREFIX))) {
263
+ await isogit.add({ fs, dir, gitdir, filepath });
303
264
  }
304
- : undefined;
305
- await commitBaseline(dir, skip);
265
+ }
266
+ for (const [filepath, oid] of captured ?? []) {
267
+ const { blob } = await isogit.readBlob({ fs, dir, oid });
268
+ await isogit.writeBlob({ fs, dir, gitdir, blob });
269
+ await isogit.updateIndex({ fs, dir, gitdir, filepath, oid, mode: 0o100644, add: true });
270
+ }
271
+ await isogit.commit({ fs, dir, gitdir, message: "memory baseline", author: AUTHOR });
272
+ // The version marker brackets promotion: interrupted promotions recover
273
+ // as an empty baseline instead of trusting a partial repository.
274
+ fs.unlinkSync(baselineVersionPath(dir));
275
+ for (const name of fs.readdirSync(old)) {
276
+ if (name !== "codex-next")
277
+ fs.rmSync(path.join(old, name), { recursive: true, force: true });
278
+ }
279
+ for (const name of fs.readdirSync(gitdir))
280
+ fs.renameSync(path.join(gitdir, name), path.join(old, name));
281
+ fs.rmdirSync(gitdir);
282
+ fs.writeFileSync(baselineVersionPath(dir), BASELINE_VERSION);
306
283
  return true;
307
284
  }
308
285
  catch (err) {
@@ -98,6 +98,11 @@ export declare function hostMcpStatus(client: PluginInput["client"] | null, sign
98
98
  error?: unknown;
99
99
  data?: unknown;
100
100
  } | null>;
101
+ /** Coalesce concurrent reads within one location; never reuse a stale MCP catalog. */
102
+ export declare function externalContextClassifier(status: (signal: AbortSignal) => Promise<{
103
+ data?: unknown;
104
+ error?: unknown;
105
+ } | null>, legacyPrefix?: boolean): (tool: string) => Promise<boolean>;
101
106
  /** session.messages — weakly typed parts; centralize the cast. */
102
107
  export declare function hostSessionMessages(client: PluginInput["client"] | null | undefined, sessionId: string, signal?: AbortSignal): Promise<{
103
108
  error?: unknown;
@@ -115,6 +115,30 @@ export async function hostMcpStatus(client, signal) {
115
115
  return null;
116
116
  return (await mcp.status({ signal }));
117
117
  }
118
+ /** Coalesce concurrent reads within one location; never reuse a stale MCP catalog. */
119
+ export function externalContextClassifier(status, legacyPrefix = false) {
120
+ let inFlight;
121
+ return async (tool) => {
122
+ if (tool === "websearch" || tool === "webfetch")
123
+ return true;
124
+ if (!inFlight) {
125
+ const controller = new AbortController();
126
+ inFlight = withHostTimeout(status(controller.signal), 1000, "mcp.status", controller)
127
+ .then((result) => {
128
+ if (result?.error || !result?.data || typeof result.data !== "object" || Array.isArray(result.data))
129
+ return [];
130
+ return Object.entries(result.data)
131
+ .filter(([, server]) => typeof server?.status === "string")
132
+ .map(([name]) => name.replace(/[^a-zA-Z0-9_-]/g, "_"));
133
+ })
134
+ .catch(() => [])
135
+ .finally(() => {
136
+ inFlight = undefined;
137
+ });
138
+ }
139
+ return (await inFlight).some((name) => tool.startsWith(`${name}_`) || (legacyPrefix && tool.startsWith(`mcp_${name}_`)));
140
+ };
141
+ }
118
142
  /** session.messages — weakly typed parts; centralize the cast. */
119
143
  export async function hostSessionMessages(client, sessionId, signal) {
120
144
  if (!client || typeof client.session?.messages !== "function") {
@@ -19,6 +19,7 @@ declare const _default: {
19
19
  id: string;
20
20
  setup: typeof setupV2;
21
21
  server(input: PluginInput, opts?: PluginOptions): Promise<{
22
+ dispose(): Promise<void>;
22
23
  tool: {
23
24
  memory_read: {
24
25
  description: string;
@@ -238,7 +239,6 @@ declare const _default: {
238
239
  properties: unknown;
239
240
  };
240
241
  }): Promise<void>;
241
- dispose(): Promise<void>;
242
242
  }>;
243
243
  };
244
244
  export default _default;