opencode-codex-memory 0.10.1 → 0.10.3

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 (47) 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 +4 -145
  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 +9 -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 +20 -14
  40. package/dist/src/v2/tools.js +14 -14
  41. package/dist/src/v2/tui.js +14 -4
  42. package/dist/src/workspace.js +13 -4
  43. package/dist/tools/control.d.ts +4 -33
  44. package/dist/tools/control.js +29 -28
  45. package/dist/tools/memory.d.ts +5 -70
  46. package/dist/tools/memory.js +164 -89
  47. package/package.json +32 -20
@@ -3,8 +3,8 @@ import { loadTranscript, selectEligibleSessions } from "./capture.js";
3
3
  import { serializeTieredInput } from "./rollout-input.js";
4
4
  import { redact, isMemoryExcludedFragment } from "./redact.js";
5
5
  import { stripCitations } from "./citation.js";
6
- import { extractViaSubagent, SubagentCancelledError } from "./llm.js";
7
- import { checkRateLimit, isProviderCapacityBlocked, markRateLimitUsed, ProviderCapacityError, } from "./ratelimit.js";
6
+ import { extractViaSubagent, MAX_TRANSCRIPT_BYTES, SubagentCancelledError } from "./llm.js";
7
+ import { checkRateLimit, isProviderCapacityBlocked, markRateLimitUsed, ProviderCapacityError } from "./ratelimit.js";
8
8
  import { isPluginShuttingDown } from "./lifecycle.js";
9
9
  import { recordDiagnostic } from "./diagnostics.js";
10
10
  import { currentMemoryVersion, withMemoryVersion } from "./memory-version.js";
@@ -16,15 +16,6 @@ export const DEFAULT_PHASE1_OPTIONS = {
16
16
  maxClaimed: 2,
17
17
  maxUnusedDays: 30,
18
18
  };
19
- // codex serializes the full transcript and truncates at 70% of the model
20
- // context window, falling back to 150k tokens; ~4 chars/token puts the
21
- // char-estimate equivalent at 600k.
22
- const TRANSCRIPT_MAX_CHARS = 600_000;
23
- // When truncating, keep the head and the tail: the start carries the user's
24
- // framing, the end carries the final outcome and feedback. codex splits the
25
- // budget 50/50 between head and tail (truncate.rs split_budget).
26
- const TRANSCRIPT_HEAD_CHARS = 300_000;
27
- const TRANSCRIPT_TAIL_CHARS = 300_000;
28
19
  export async function runPhase1(store, opts = DEFAULT_PHASE1_OPTIONS, rateLimitCheck = checkRateLimit) {
29
20
  return withMemoryVersion(store.version, () => runVersionPhase1(store, opts, rateLimitCheck));
30
21
  }
@@ -77,12 +68,12 @@ async function runVersionPhase1(store, opts, rateLimitCheck) {
77
68
  try {
78
69
  const session = sessionById.get(sid);
79
70
  const sourceUpdatedAt = session?.updated_at ?? Date.now();
80
- const transcript = await buildTranscript(sid);
71
+ const transcript = await prepareTranscript(sid);
81
72
  if (isPluginShuttingDown()) {
82
73
  store.releaseStage1OnShutdown(sid, claim.ownershipToken);
83
74
  return;
84
75
  }
85
- if (!transcript.trim()) {
76
+ if (!transcript) {
86
77
  // A newly empty chat is a legitimate no-output result. An existing
87
78
  // extraction plus an empty API success is anomalous: retry instead of
88
79
  // permanently forgetting memory because of a transient host glitch.
@@ -133,12 +124,16 @@ async function runVersionPhase1(store, opts, rateLimitCheck) {
133
124
  });
134
125
  }
135
126
  export async function buildTranscript(sessionId) {
127
+ return (await prepareTranscript(sessionId))?.(MAX_TRANSCRIPT_BYTES) ?? "";
128
+ }
129
+ async function prepareTranscript(sessionId) {
136
130
  const msgs = await loadTranscript(sessionId);
137
131
  if (msgs.length === 0)
138
- return "";
132
+ return null;
139
133
  if (currentMemoryVersion() === "v2") {
140
- const tiered = serializeTieredInput(msgs, TRANSCRIPT_MAX_CHARS);
141
- return redact(stripCitations(tiered));
134
+ const render = (limit) => redact(stripCitations(serializeTieredInput(msgs, limit)));
135
+ const initial = render(MAX_TRANSCRIPT_BYTES);
136
+ return initial.trim() ? (limit) => (Buffer.byteLength(initial) <= limit ? initial : render(limit)) : null;
142
137
  }
143
138
  const lines = [];
144
139
  for (const m of msgs) {
@@ -160,11 +155,7 @@ export async function buildTranscript(sessionId) {
160
155
  lines.push(`### ${role}\n${redact(stripCitations(text))}`);
161
156
  }
162
157
  const full = lines.join("\n\n");
163
- if (full.length <= TRANSCRIPT_MAX_CHARS)
164
- return full;
165
- return (full.slice(0, TRANSCRIPT_HEAD_CHARS) +
166
- "\n\n[... transcript truncated ...]\n\n" +
167
- full.slice(full.length - TRANSCRIPT_TAIL_CHARS));
158
+ return full ? (limit) => truncateToBytes(full, limit) : null;
168
159
  }
169
160
  async function runPool(items, concurrency, fn) {
170
161
  let cursor = 0;
@@ -2,7 +2,7 @@ import { PHASE2_HEARTBEAT_SECONDS } from "./store.js";
2
2
  import { checkRateLimit } from "./ratelimit.js";
3
3
  import { ensureLayout, rebuildRawMemories, writeRolloutSummaries, pruneExtensionResources, EXTENSION_RESOURCE_RETENTION_DAYS, writeWorkspaceDiff, validateConsolidationArtifactsForVersion, removeMemorySymlinks, } from "./workspace.js";
4
4
  import { ensureBaseline, captureWorkspaceDiff, resetBaseline, DIFF_ARTIFACT } from "./git-baseline.js";
5
- import { consolidateViaSubagent, getPluginInput, SubagentCancelledError, SubagentShutdownError, } from "./llm.js";
5
+ import { consolidateViaSubagent, getPluginInput, SubagentCancelledError, SubagentShutdownError } from "./llm.js";
6
6
  import { hostSessionLiveness, withHostTimeout } from "./host-client.js";
7
7
  import { invalidateCache } from "./source.js";
8
8
  import { withMemoryVersion } from "./memory-version.js";
@@ -151,7 +151,7 @@ async function runVersionPhase2(store, opts) {
151
151
  // files stay visible as additions. Stale stage-1
152
152
  // output pruning happens in phase 1, before the rate gate (codex
153
153
  // start.rs ordering).
154
- if (!await withHostTimeout(ensureBaseline(), GIT_TIMEOUT_MS, "ensureBaseline")) {
154
+ if (!(await withHostTimeout(ensureBaseline(), GIT_TIMEOUT_MS, "ensureBaseline"))) {
155
155
  store.markPhase2Failed(claim.ownershipToken, "git baseline failed");
156
156
  return { status: "baseline_failed" };
157
157
  }
@@ -293,7 +293,7 @@ async function runVersionPhase2(store, opts) {
293
293
  store.markPhase2Failed(claim.ownershipToken, `failed_invalid_artifacts: ${artifacts.reason}`);
294
294
  return { status: "failed_invalid_artifacts" };
295
295
  }
296
- if (!await withHostTimeout(resetBaseline(diff.extensionSnapshot), GIT_TIMEOUT_MS, "resetBaseline")) {
296
+ if (!(await withHostTimeout(resetBaseline(diff.extensionSnapshot), GIT_TIMEOUT_MS, "resetBaseline"))) {
297
297
  store.markPhase2Failed(claim.ownershipToken, "baseline reset failed");
298
298
  return { status: "baseline_reset_failed" };
299
299
  }
@@ -2,4 +2,11 @@ export declare const REASONING_VARIANT_LADDER: readonly ["none", "minimal", "low
2
2
  export type ReasoningVariant = (typeof REASONING_VARIANT_LADDER)[number];
3
3
  export declare function nearestReasoningVariant(preferred: string, available: Iterable<string>): string | undefined;
4
4
  export declare function enabledVariantKeys(variants: unknown): string[];
5
+ export declare function catalogModel(data: unknown, providerID: string, modelID: string): {
6
+ variants?: unknown;
7
+ limit?: {
8
+ context?: number;
9
+ input?: number;
10
+ };
11
+ } | undefined;
5
12
  export declare function catalogVariantKeys(data: unknown, providerID: string, modelID: string): string[] | undefined;
@@ -27,14 +27,17 @@ export function enabledVariantKeys(variants) {
27
27
  return [];
28
28
  const out = [];
29
29
  for (const [name, value] of Object.entries(variants)) {
30
- if (value && typeof value === "object" && !Array.isArray(value) && value.disabled === true) {
30
+ if (value &&
31
+ typeof value === "object" &&
32
+ !Array.isArray(value) &&
33
+ value.disabled === true) {
31
34
  continue;
32
35
  }
33
36
  out.push(name);
34
37
  }
35
38
  return out;
36
39
  }
37
- export function catalogVariantKeys(data, providerID, modelID) {
40
+ export function catalogModel(data, providerID, modelID) {
38
41
  if (!data || typeof data !== "object")
39
42
  return undefined;
40
43
  const root = data;
@@ -47,6 +50,12 @@ export function catalogVariantKeys(data, providerID, modelID) {
47
50
  const model = provider.models[modelID];
48
51
  if (!model || typeof model !== "object" || Array.isArray(model))
49
52
  return undefined;
53
+ return model;
54
+ }
55
+ export function catalogVariantKeys(data, providerID, modelID) {
56
+ const model = catalogModel(data, providerID, modelID);
57
+ if (!model)
58
+ return undefined;
50
59
  if (!Object.prototype.hasOwnProperty.call(model, "variants"))
51
60
  return undefined;
52
61
  return enabledVariantKeys(model.variants);
@@ -21,10 +21,8 @@ function isEnvContext(text) {
21
21
  }
22
22
  function isOtherAgent(text) {
23
23
  const trimmed = text.trimStart();
24
- return (trimmed.startsWith("<subagent_notification>")
25
- || (trimmed.startsWith("Message Type:")
26
- && trimmed.includes("\nTask name:")
27
- && trimmed.includes("\nSender:")));
24
+ return (trimmed.startsWith("<subagent_notification>") ||
25
+ (trimmed.startsWith("Message Type:") && trimmed.includes("\nTask name:") && trimmed.includes("\nSender:")));
28
26
  }
29
27
  function classify(msg) {
30
28
  if (msg.type === "reasoning" || msg.type === "step-start" || msg.type === "step-finish")
@@ -65,7 +63,7 @@ function rowText(msg, tier) {
65
63
  return "[file omitted]";
66
64
  let text = redact(stripCitations(msg.userReply
67
65
  ? `Assistant question: ${msg.userReply.question}\nHuman reply: ${msg.userReply.answer}`
68
- : msg.text ?? ""));
66
+ : (msg.text ?? "")));
69
67
  if (tier === "tool")
70
68
  text = truncateToBytes(text, TOOL_ROW_BYTES - TRUNCATION_RESERVE_BYTES);
71
69
  text = truncateToBytes(text, MAX_ROW_BYTES - TRUNCATION_RESERVE_BYTES);
@@ -9,10 +9,8 @@ export function sessionMemoryVersion(sessionId) {
9
9
  if (!sessionId)
10
10
  return pluginOptions.version;
11
11
  const db = openSessionMetaDb();
12
- db.prepare("INSERT OR IGNORE INTO memory_session_versions (session_id, version) VALUES (?, ?)")
13
- .run(sessionId, pluginOptions.version);
14
- return db.prepare("SELECT version FROM memory_session_versions WHERE session_id = ?")
15
- .get(sessionId).version;
12
+ db.prepare("INSERT OR IGNORE INTO memory_session_versions (session_id, version) VALUES (?, ?)").run(sessionId, pluginOptions.version);
13
+ return db.prepare("SELECT version FROM memory_session_versions WHERE session_id = ?").get(sessionId).version;
16
14
  }
17
15
  export function withSessionMemoryVersion(sessionId, run) {
18
16
  return withMemoryVersion(sessionMemoryVersion(sessionId), run);
@@ -21,7 +19,8 @@ export function withSessionMemoryVersion(sessionId, run) {
21
19
  export function peekSessionMemoryVersion(sessionId) {
22
20
  if (!sessionId)
23
21
  return pluginOptions.version;
24
- const row = openSessionMetaDb().prepare("SELECT version FROM memory_session_versions WHERE session_id = ?")
22
+ const row = openSessionMetaDb()
23
+ .prepare("SELECT version FROM memory_session_versions WHERE session_id = ?")
25
24
  .get(sessionId);
26
25
  return row?.version ?? pluginOptions.version;
27
26
  }
@@ -91,8 +91,12 @@ export function buildMemorySystemPrompt(dedicatedTools) {
91
91
  const template = readTemplate();
92
92
  const v2 = currentMemoryVersion() === "v2";
93
93
  const searchStep = dedicatedTools
94
- ? (v2 ? SEARCH_STEP_TOOLS_V2 : SEARCH_STEP_TOOLS)
95
- : (v2 ? SEARCH_STEP_FILES_V2 : SEARCH_STEP_FILES);
94
+ ? v2
95
+ ? SEARCH_STEP_TOOLS_V2
96
+ : SEARCH_STEP_TOOLS
97
+ : v2
98
+ ? SEARCH_STEP_FILES_V2
99
+ : SEARCH_STEP_FILES;
96
100
  return fillTemplate(template, {
97
101
  search_step: searchStep,
98
102
  skill_step: dedicatedTools ? SKILL_STEP_TOOLS : SKILL_STEP_FILES,
@@ -41,7 +41,7 @@ export type Phase2ClaimResult = {
41
41
  type: "skipped_retry_unavailable";
42
42
  };
43
43
  /** Wipe jobs/outputs in every versioned DB. Leaves memory_session_meta on memory.db. */
44
- export declare function clearAllVersionMemoryData(): void;
44
+ export declare function clearAllVersionMemoryData(wipeWorkspace: () => void): void;
45
45
  /** Include inactive existing stores for deletion, reset guards and diagnostics. */
46
46
  export declare function existingMemoryStores(): MemoryStore[];
47
47
  export declare const PHASE2_HEARTBEAT_SECONDS = 90;
@@ -92,6 +92,7 @@ export declare class MemoryStore {
92
92
  claimGlobalPhase2Job(opts?: {
93
93
  bypassCooldown?: boolean;
94
94
  }): Phase2ClaimResult;
95
+ private claimPhase2;
95
96
  heartbeatPhase2Job(ownershipToken: string): boolean;
96
97
  /**
97
98
  * Marks the phase-2 job done and records exactly which stage-1 snapshots the
@@ -165,7 +166,7 @@ export declare class MemoryStore {
165
166
  * surface is model-invoked mid-session, so hooks can race the wipe.
166
167
  */
167
168
  clearMemoryData(): void;
168
- setMemoryMode(sessionId: string, mode: "enabled" | "disabled" | "polluted"): void;
169
+ setMemoryMode(sessionId: string, mode: "enabled" | "disabled" | "polluted", approvedRestore?: boolean): void;
169
170
  /**
170
171
  * Stamp a mode only when the session has no meta row yet — used to mark
171
172
  * sessions seen while generate_memories=false as permanently 'disabled'
package/dist/src/store.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from "fs";
2
2
  import os from "os";
3
- import { openDb, openSessionMetaDb, openTransientDb } from "./db.js";
4
- import { allJobDbPaths, sessionMetaDbPath, memoryDbPath } from "./paths.js";
3
+ import { openDb, openSessionMetaDb } from "./db.js";
4
+ import { memoryDbPath } from "./paths.js";
5
5
  import { currentMemoryVersion, MEMORY_VERSIONS, withMemoryVersion } from "./memory-version.js";
6
6
  import { isProviderCapacityError } from "./ratelimit.js";
7
7
  export const DEFAULT_RETRY_REMAINING = 3;
@@ -19,31 +19,33 @@ function clearJobTables(db) {
19
19
  db.run("DELETE FROM memory_jobs");
20
20
  db.run("DELETE FROM memory_citation_usage");
21
21
  db.run("UPDATE consolidation_progress SET max_thread_count = 0");
22
- db
23
- .prepare(`INSERT INTO memory_jobs
22
+ db.prepare(`INSERT INTO memory_jobs
24
23
  (kind, job_key, status, finished_at, last_error, retry_remaining, last_success_watermark)
25
- VALUES ('memory_consolidate_global', 'global', 'done', ?, NULL, ?, 0)`)
26
- .run(nowSec(), DEFAULT_RETRY_REMAINING);
24
+ VALUES ('memory_consolidate_global', 'global', 'done', ?, NULL, ?, 0)`).run(nowSec(), DEFAULT_RETRY_REMAINING);
27
25
  }).immediate();
28
26
  }
29
27
  /** Wipe jobs/outputs in every versioned DB. Leaves memory_session_meta on memory.db. */
30
- export function clearAllVersionMemoryData() {
31
- for (const dbPath of allJobDbPaths()) {
32
- if (dbPath !== sessionMetaDbPath() && !fs.existsSync(dbPath))
33
- continue;
34
- const db = openTransientDb(dbPath);
35
- try {
36
- clearJobTables(db);
37
- }
38
- finally {
39
- db.close();
28
+ export function clearAllVersionMemoryData(wipeWorkspace) {
29
+ const catalog = openSessionMetaDb();
30
+ catalog
31
+ .transaction(() => {
32
+ const stores = existingMemoryStores();
33
+ for (const store of stores) {
34
+ const job = store.phase2JobSnapshot();
35
+ if (job?.status === "running" && (job.lease_until === null || job.lease_until > nowSec())) {
36
+ throw new Error(`Reset refused: ${store.version} memory consolidation has an active lease.`);
37
+ }
40
38
  }
41
- }
39
+ // No peer can claim either version until the filesystem wipe finishes.
40
+ wipeWorkspace();
41
+ for (const store of stores)
42
+ store.clearMemoryData();
43
+ })
44
+ .immediate();
42
45
  }
43
46
  /** Include inactive existing stores for deletion, reset guards and diagnostics. */
44
47
  export function existingMemoryStores() {
45
- return MEMORY_VERSIONS.filter((version) => version === "v1" || fs.existsSync(memoryDbPath(version)))
46
- .map((version) => withMemoryVersion(version, () => new MemoryStore()));
48
+ return MEMORY_VERSIONS.filter((version) => version === "v1" || fs.existsSync(memoryDbPath(version))).map((version) => withMemoryVersion(version, () => new MemoryStore()));
47
49
  }
48
50
  function newId() {
49
51
  return crypto.randomUUID();
@@ -103,9 +105,7 @@ export class MemoryStore {
103
105
  return this.db.prepare("SELECT COUNT(*) AS count FROM memory_stage1_outputs").get().count;
104
106
  }
105
107
  hasStage1Output(sessionId) {
106
- return this.db
107
- .prepare("SELECT 1 FROM memory_stage1_outputs WHERE session_id = ?")
108
- .get(sessionId) !== null;
108
+ return this.db.prepare("SELECT 1 FROM memory_stage1_outputs WHERE session_id = ?").get(sessionId) !== null;
109
109
  }
110
110
  /**
111
111
  * Deletes stale rows; snapshots consumed by the last successful Phase 2 are
@@ -162,10 +162,12 @@ export class MemoryStore {
162
162
  // upgrade failure under cross-process access.
163
163
  const ts = now();
164
164
  const stmt = this.db.prepare("UPDATE memory_stage1_outputs SET usage_count = usage_count + 1, last_usage = ? WHERE session_id = ?");
165
- this.db.transaction(() => {
165
+ this.db
166
+ .transaction(() => {
166
167
  for (const id of sessionIds)
167
168
  stmt.run(ts, id);
168
- }).immediate();
169
+ })
170
+ .immediate();
169
171
  }
170
172
  /**
171
173
  * Record citations from a durable assistant message exactly once. V2 can
@@ -182,7 +184,8 @@ export class MemoryStore {
182
184
  VALUES (?, ?, ?, ?)`);
183
185
  const update = this.db.prepare("UPDATE memory_stage1_outputs SET usage_count = usage_count + 1, last_usage = ? WHERE session_id = ?");
184
186
  const ts = now();
185
- this.db.transaction(() => {
187
+ this.db
188
+ .transaction(() => {
186
189
  for (const citedSessionId of ids) {
187
190
  const result = insert.run(sessionId, assistantMessageId, citedSessionId, ts);
188
191
  if (result.changes === 0)
@@ -197,7 +200,8 @@ export class MemoryStore {
197
200
  .run(sessionId, assistantMessageId, citedSessionId);
198
201
  }
199
202
  }
200
- }).immediate();
203
+ })
204
+ .immediate();
201
205
  return fresh;
202
206
  }
203
207
  claimStage1Jobs(sessions, excludeSession, maxClaimed) {
@@ -263,7 +267,8 @@ export class MemoryStore {
263
267
  return claimed;
264
268
  }
265
269
  markStage1Succeeded(sessionId, ownershipToken, out) {
266
- this.db.transaction(() => {
270
+ this.db
271
+ .transaction(() => {
267
272
  const res = this.db
268
273
  .prepare(`UPDATE memory_jobs SET status='done', finished_at=?, lease_until=NULL, last_error=NULL,
269
274
  last_success_watermark=?, retry_at=NULL
@@ -275,11 +280,13 @@ export class MemoryStore {
275
280
  this.upsertStage1Output(out);
276
281
  this.enqueueGlobalConsolidation(out.source_updated_at);
277
282
  }
278
- }).immediate();
283
+ })
284
+ .immediate();
279
285
  }
280
286
  /** Extraction succeeded but produced nothing worth keeping: finish the job and drop any stale output. */
281
287
  markStage1SucceededNoOutput(sessionId, ownershipToken, sourceUpdatedAt) {
282
- this.db.transaction(() => {
288
+ this.db
289
+ .transaction(() => {
283
290
  const res = this.db
284
291
  .prepare(`UPDATE memory_jobs SET status='done', finished_at=?, lease_until=NULL, last_error=NULL,
285
292
  last_success_watermark=?, retry_at=NULL
@@ -290,7 +297,8 @@ export class MemoryStore {
290
297
  const deleted = this.db.prepare("DELETE FROM memory_stage1_outputs WHERE session_id = ?").run(sessionId);
291
298
  if (deleted.changes > 0)
292
299
  this.enqueueGlobalConsolidation(sourceUpdatedAt);
293
- }).immediate();
300
+ })
301
+ .immediate();
294
302
  }
295
303
  markStage1Failed(sessionId, ownershipToken, error) {
296
304
  const message = failureMessage(error);
@@ -337,13 +345,15 @@ export class MemoryStore {
337
345
  let n = 0;
338
346
  const stmt = this.db.prepare(`UPDATE memory_jobs SET status='pending', retry_remaining=?
339
347
  WHERE kind='memory_stage1' AND job_key=? AND status='failed'`);
340
- this.db.transaction(() => {
348
+ this.db
349
+ .transaction(() => {
341
350
  for (const row of rows) {
342
351
  if (!isProviderCapacityError(row.last_error))
343
352
  continue;
344
353
  n += stmt.run(DEFAULT_RETRY_REMAINING, row.job_key).changes;
345
354
  }
346
- }).immediate();
355
+ })
356
+ .immediate();
347
357
  return n;
348
358
  }
349
359
  /**
@@ -389,6 +399,13 @@ export class MemoryStore {
389
399
  .run(DEFAULT_RETRY_REMAINING, inputWatermark);
390
400
  }
391
401
  claimGlobalPhase2Job(opts = {}) {
402
+ // V1 already claims under the shared catalog write lock. Take that same
403
+ // lock first for V2, including its very first claim after a reset.
404
+ return this.meta === this.db
405
+ ? this.claimPhase2(opts)
406
+ : this.meta.transaction(() => this.claimPhase2(opts)).immediate();
407
+ }
408
+ claimPhase2(opts) {
392
409
  const workerId = phase2WorkerId();
393
410
  const ownershipToken = newId();
394
411
  const tNow = nowSec();
@@ -458,7 +475,8 @@ export class MemoryStore {
458
475
  // mark_global_phase2_job_succeeded does the same): a crash between them
459
476
  // must not leave a done job whose retention flags still describe the
460
477
  // previous run — pruning could then delete inputs backing the artifacts.
461
- this.db.transaction(() => {
478
+ this.db
479
+ .transaction(() => {
462
480
  const res = this.db
463
481
  .prepare(`UPDATE memory_jobs SET status='done', finished_at=?, lease_until=NULL, last_error=NULL, retry_remaining=?,
464
482
  last_success_watermark=MAX(COALESCE(last_success_watermark, 0), ?), retry_at=NULL
@@ -466,7 +484,8 @@ export class MemoryStore {
466
484
  .run(nowSec(), DEFAULT_RETRY_REMAINING, watermark, ownershipToken);
467
485
  if (res.changes === 0)
468
486
  return;
469
- this.db.prepare("UPDATE consolidation_progress SET max_thread_count = MAX(max_thread_count, ?)")
487
+ this.db
488
+ .prepare("UPDATE consolidation_progress SET max_thread_count = MAX(max_thread_count, ?)")
470
489
  .run(new Set(selected.map((s) => s.session_id)).size);
471
490
  this.db.run("UPDATE memory_stage1_outputs SET selected_for_phase2 = 0, selected_for_phase2_source_updated_at = NULL");
472
491
  const mark = this.db.prepare(`UPDATE memory_stage1_outputs
@@ -474,12 +493,12 @@ export class MemoryStore {
474
493
  WHERE session_id = ? AND source_updated_at = ?`);
475
494
  for (const s of selected)
476
495
  mark.run(s.source_updated_at, s.session_id, s.source_updated_at);
477
- }).immediate();
496
+ })
497
+ .immediate();
478
498
  }
479
499
  /** High-water mark of distinct sessions consumed by one successful run. */
480
500
  maxConsolidatedThreadCount() {
481
- return this.db.prepare("SELECT max_thread_count FROM consolidation_progress WHERE singleton = 1")
482
- .get().max_thread_count;
501
+ return this.db.prepare("SELECT max_thread_count FROM consolidation_progress WHERE singleton = 1").get().max_thread_count;
483
502
  }
484
503
  /**
485
504
  * Phase-2 job snapshot for memory_inspect. Always returns the global job row
@@ -495,9 +514,7 @@ export class MemoryStore {
495
514
  .get();
496
515
  if (!row)
497
516
  return null;
498
- const cleanSuccess = row.last_error === null &&
499
- row.finished_at !== null &&
500
- (row.status === "done" || row.status === "pending");
517
+ const cleanSuccess = row.last_error === null && row.finished_at !== null && (row.status === "done" || row.status === "pending");
501
518
  // Codex initializes pending global jobs with watermark 0, so zero proves a
502
519
  // success only while the row itself is a clean completed attempt.
503
520
  const watermark = row.last_success_watermark === null
@@ -648,7 +665,8 @@ export class MemoryStore {
648
665
  * job, then enqueue forgetting if phase 2 had consumed that output.
649
666
  */
650
667
  deleteSessionMemory(sessionId) {
651
- return this.db.transaction(() => {
668
+ return this.db
669
+ .transaction(() => {
652
670
  const existing = this.db
653
671
  .prepare("SELECT selected_for_phase2 FROM memory_stage1_outputs WHERE session_id = ?")
654
672
  .get(sessionId);
@@ -658,7 +676,8 @@ export class MemoryStore {
658
676
  if (shouldConsolidate)
659
677
  this.enqueueGlobalConsolidation(now());
660
678
  return shouldConsolidate;
661
- }).immediate();
679
+ })
680
+ .immediate();
662
681
  }
663
682
  /**
664
683
  * codex clear_memory_data deletes extracted memories and jobs but explicitly
@@ -675,12 +694,18 @@ export class MemoryStore {
675
694
  clearMemoryData() {
676
695
  clearJobTables(this.db);
677
696
  }
678
- setMemoryMode(sessionId, mode) {
679
- this.meta
697
+ setMemoryMode(sessionId, mode, approvedRestore = false) {
698
+ if (mode === "polluted")
699
+ return this.markPolluted(sessionId);
700
+ const updated = this.meta
680
701
  .prepare(`INSERT INTO memory_session_meta (session_id, memory_mode, polluted, updated_at)
681
- VALUES (?, ?, ?, ?)
682
- ON CONFLICT(session_id) DO UPDATE SET memory_mode=excluded.memory_mode, polluted=excluded.polluted, updated_at=excluded.updated_at`)
683
- .run(sessionId, mode, mode === "polluted" ? 1 : 0, now());
702
+ VALUES (?, ?, 0, ?)
703
+ ON CONFLICT(session_id) DO UPDATE SET memory_mode=excluded.memory_mode,
704
+ polluted=CASE WHEN excluded.memory_mode='enabled' THEN 0 ELSE polluted END, updated_at=excluded.updated_at
705
+ WHERE excluded.memory_mode='disabled' OR polluted=0 OR ?`)
706
+ .run(sessionId, mode, now(), approvedRestore ? 1 : 0);
707
+ if (!updated.changes)
708
+ throw new Error("Restoring learning for this session requires approval.");
684
709
  }
685
710
  /**
686
711
  * Stamp a mode only when the session has no meta row yet — used to mark
@@ -47,17 +47,16 @@ export function buildMemorizeAgent() {
47
47
  * store. Pass the same directory the session is created in.
48
48
  */
49
49
  export function consolidationPermissions(root, sessionDir) {
50
- return [
51
- { action: "*", resource: "*", effect: "deny" },
52
- ...workspacePermissions(root, sessionDir),
53
- ];
50
+ return [{ action: "*", resource: "*", effect: "deny" }, ...workspacePermissions(root, sessionDir)];
54
51
  }
55
52
  function workspacePermissions(root, sessionDir) {
56
53
  const absolute = [root, path.join(root, "*")];
57
54
  return [
58
55
  ...sessionRelativePermissions(root, sessionDir),
59
56
  ...["read", "edit", "external_directory"].flatMap((action) => absolute.map((resource) => ({
60
- action, resource, effect: "allow",
57
+ action,
58
+ resource,
59
+ effect: "allow",
61
60
  }))),
62
61
  // These actions check the search pattern, not a path. search-sandbox.ts
63
62
  // wraps the built-in executors to enforce this helper's single root.
@@ -79,10 +78,12 @@ function sessionRelativePermissions(root, sessionDir) {
79
78
  const posix = rel.split(path.sep).join("/");
80
79
  const inside = !posix || posix.split("/").every((seg) => seg === "..");
81
80
  const escape = posix ? `${posix}/..` : "..";
82
- return ["read", "edit"].flatMap((action) => inside ? [
83
- { action, resource: "*", effect: "allow" },
84
- ...["/*", "?:/*", escape, `${escape}/*`].map((resource) => ({ action, resource, effect: "deny" })),
85
- ] : [posix, `${posix}/*`].map((resource) => ({ action, resource, effect: "allow" })));
81
+ return ["read", "edit"].flatMap((action) => inside
82
+ ? [
83
+ { action, resource: "*", effect: "allow" },
84
+ ...["/*", "?:/*", escape, `${escape}/*`].map((resource) => ({ action, resource, effect: "deny" })),
85
+ ]
86
+ : [posix, `${posix}/*`].map((resource) => ({ action, resource, effect: "allow" })));
86
87
  }
87
88
  /**
88
89
  * Hidden extraction definition. Unused at runtime (extraction goes through
@@ -204,11 +205,7 @@ export async function ensureV2Agents(ctx) {
204
205
  recordAgentConfig({ agent: effective }, true, shippedV1AgentForHealth());
205
206
  }
206
207
  function isShippedIncomplete(id, existing, shipped) {
207
- const system = typeof existing.system === "string"
208
- ? existing.system
209
- : typeof existing.prompt === "string"
210
- ? existing.prompt
211
- : "";
208
+ const system = typeof existing.system === "string" ? existing.system : typeof existing.prompt === "string" ? existing.prompt : "";
212
209
  if (system !== shipped.system)
213
210
  return false;
214
211
  if (typeof existing.description === "string" && existing.description !== shipped.description)
@@ -17,7 +17,15 @@ export function isModelSelectionUnavailable(error, model) {
17
17
  const tag = current._tag ?? current.name;
18
18
  if (["InvalidRequestError", "Generate.ModelSelectionError"].includes(tag) && current.message === message)
19
19
  return true;
20
- if (tag === "ServiceUnavailableError" && current.service === "plugin" && current.message === PLUGIN_ACTIVATION_PENDING)
20
+ // OpenCode 2.4 reports missing explicit models separately from provider failures.
21
+ if (model &&
22
+ (tag === "ModelNotFoundError" || tag === "Generate.ModelNotFoundError") &&
23
+ current.providerID === model.providerID &&
24
+ current.modelID === model.id)
25
+ return true;
26
+ if (tag === "ServiceUnavailableError" &&
27
+ current.service === "plugin" &&
28
+ current.message === PLUGIN_ACTIVATION_PENDING)
21
29
  return true;
22
30
  }
23
31
  return false;