@cortexkit/pi-magic-context 0.22.3 → 0.22.4

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.
package/dist/index.js CHANGED
@@ -46,214 +46,6 @@ var __export = (target, all) => {
46
46
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
47
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
48
48
 
49
- // ../plugin/src/shared/harness.ts
50
- function setHarness(value) {
51
- if (harnessLocked && currentHarness !== value) {
52
- throw new Error(`Magic Context: harness already locked to "${currentHarness}"; cannot change to "${value}"`);
53
- }
54
- currentHarness = value;
55
- harnessLocked = true;
56
- }
57
- function getHarness() {
58
- return currentHarness;
59
- }
60
- var currentHarness = "opencode", harnessLocked = false;
61
-
62
- // ../plugin/src/shared/data-path.ts
63
- import * as os from "node:os";
64
- import * as path2 from "node:path";
65
- function getDataDir() {
66
- return process.env.XDG_DATA_HOME ?? path2.join(os.homedir(), ".local", "share");
67
- }
68
- function getMagicContextTempDir(harness = getHarness()) {
69
- return path2.join(os.tmpdir(), harness, "magic-context");
70
- }
71
- function getMagicContextLogPath(harness = getHarness()) {
72
- return path2.join(getMagicContextTempDir(harness), "magic-context.log");
73
- }
74
- function getProjectMagicContextDir(directory) {
75
- return path2.join(directory, ".opencode", "magic-context");
76
- }
77
- function getProjectMagicContextHistorianDir(directory) {
78
- return path2.join(getProjectMagicContextDir(directory), "historian");
79
- }
80
- function getOpenCodeStorageDir() {
81
- return path2.join(getDataDir(), "opencode", "storage");
82
- }
83
- function getMagicContextStorageDir() {
84
- return path2.join(getDataDir(), "cortexkit", "magic-context");
85
- }
86
- function getLegacyOpenCodeMagicContextStorageDir() {
87
- return path2.join(getOpenCodeStorageDir(), "plugin", "magic-context");
88
- }
89
- var init_data_path = () => {};
90
-
91
- // ../plugin/src/shared/logger.ts
92
- import * as fs from "node:fs";
93
- import * as path3 from "node:path";
94
- function ensureDir(filePath) {
95
- const dir = path3.dirname(filePath);
96
- if (dir === lastEnsuredDir)
97
- return;
98
- try {
99
- fs.mkdirSync(dir, { recursive: true });
100
- lastEnsuredDir = dir;
101
- } catch {}
102
- }
103
- function flush() {
104
- if (flushTimer) {
105
- clearTimeout(flushTimer);
106
- flushTimer = null;
107
- }
108
- if (buffer.length === 0)
109
- return;
110
- const data = buffer.join("");
111
- buffer = [];
112
- try {
113
- const logFile = getMagicContextLogPath();
114
- ensureDir(logFile);
115
- fs.appendFileSync(logFile, data);
116
- } catch {}
117
- }
118
- function scheduleFlush() {
119
- if (flushTimer)
120
- return;
121
- flushTimer = setTimeout(() => {
122
- flushTimer = null;
123
- flush();
124
- }, FLUSH_INTERVAL_MS);
125
- }
126
- function log(message, data) {
127
- if (isTestEnv)
128
- return;
129
- try {
130
- const timestamp = new Date().toISOString();
131
- const serialized = data === undefined ? "" : data instanceof Error ? ` ${data.message}${data.stack ? `
132
- ${data.stack}` : ""}` : ` ${JSON.stringify(data)}`;
133
- buffer.push(`[${timestamp}] ${message}${serialized}
134
- `);
135
- if (buffer.length >= BUFFER_SIZE_LIMIT) {
136
- flush();
137
- } else {
138
- scheduleFlush();
139
- }
140
- } catch {}
141
- }
142
- function sessionLog(sessionId, message, data) {
143
- log(`[magic-context][${sessionId}] ${message}`, data);
144
- }
145
- var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, lastEnsuredDir = null;
146
- var init_logger = __esm(() => {
147
- init_data_path();
148
- buffer = [];
149
- if (!isTestEnv) {
150
- process.on("exit", flush);
151
- }
152
- });
153
-
154
- // ../plugin/src/shared/sqlite.ts
155
- function buildNodeSqliteDatabaseClass(DatabaseSync) {
156
- const SAVEPOINT = "mc_tx_sp";
157
-
158
- class NodeSqliteDatabase extends DatabaseSync {
159
- constructor(filename, options) {
160
- const translated = { ...options };
161
- if (options && "readonly" in options) {
162
- translated.readOnly = options.readonly;
163
- delete translated.readonly;
164
- }
165
- super(typeof filename === "string" ? filename : ":memory:", translated);
166
- }
167
- transaction(fn) {
168
- const self = this;
169
- const wrapped = function(...args) {
170
- const nested = self.isTransaction === true;
171
- self.exec(nested ? `SAVEPOINT ${SAVEPOINT}` : "BEGIN");
172
- try {
173
- const result = fn.apply(this, args);
174
- self.exec(nested ? `RELEASE ${SAVEPOINT}` : "COMMIT");
175
- return result;
176
- } catch (error) {
177
- if (nested) {
178
- self.exec(`ROLLBACK TO ${SAVEPOINT}`);
179
- self.exec(`RELEASE ${SAVEPOINT}`);
180
- } else {
181
- self.exec("ROLLBACK");
182
- }
183
- throw error;
184
- }
185
- };
186
- return wrapped;
187
- }
188
- }
189
- return NodeSqliteDatabase;
190
- }
191
- var isBun, bunSpec, nodeSpec, sqliteModule, DatabaseImpl, Database;
192
- var init_sqlite = __esm(async () => {
193
- isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
194
- bunSpec = "bun:" + "sqlite";
195
- nodeSpec = "node:" + "sqlite";
196
- sqliteModule = isBun ? await import(bunSpec) : await import(nodeSpec);
197
- DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
198
- Database = DatabaseImpl;
199
- });
200
-
201
- // ../plugin/src/shared/sqlite-helpers.ts
202
- function closeQuietly(db) {
203
- if (!db)
204
- return;
205
- try {
206
- db.close();
207
- } catch {}
208
- }
209
-
210
- // ../plugin/src/hooks/magic-context/read-session-db.ts
211
- import { existsSync } from "node:fs";
212
- import { join as join2 } from "node:path";
213
- function getOpenCodeDbPath() {
214
- return join2(getDataDir(), "opencode", "opencode.db");
215
- }
216
- function openCodeDbExists() {
217
- return existsSync(getOpenCodeDbPath());
218
- }
219
- function closeCachedReadOnlyDb() {
220
- if (!cachedReadOnlyDb) {
221
- return;
222
- }
223
- try {
224
- closeQuietly(cachedReadOnlyDb.db);
225
- } catch (error) {
226
- log("[magic-context] failed to close cached OpenCode read-only DB:", error);
227
- } finally {
228
- cachedReadOnlyDb = null;
229
- }
230
- }
231
- function getReadOnlySessionDb() {
232
- const dbPath = getOpenCodeDbPath();
233
- if (cachedReadOnlyDb?.path === dbPath) {
234
- return cachedReadOnlyDb.db;
235
- }
236
- closeCachedReadOnlyDb();
237
- const db = new Database(dbPath, { readonly: true });
238
- cachedReadOnlyDb = { path: dbPath, db };
239
- return db;
240
- }
241
- function withReadOnlySessionDb(fn) {
242
- return fn(getReadOnlySessionDb());
243
- }
244
- function getRawSessionMessageCountFromDb(db, sessionId) {
245
- const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
246
- AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
247
- AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
248
- return typeof row?.count === "number" ? row.count : 0;
249
- }
250
- var cachedReadOnlyDb = null;
251
- var init_read_session_db = __esm(async () => {
252
- init_data_path();
253
- init_logger();
254
- await init_sqlite();
255
- });
256
-
257
49
  // ../../node_modules/.bun/esprima@4.0.1/node_modules/esprima/dist/esprima.js
258
50
  var require_esprima = __commonJS((exports, module) => {
259
51
  (function webpackUniversalModuleDefinition(root, factory) {
@@ -8282,8 +8074,115 @@ function hasGitDir(canonical) {
8282
8074
  }
8283
8075
  }
8284
8076
 
8285
- // ../plugin/src/features/magic-context/message-index-async.ts
8286
- init_logger();
8077
+ // ../plugin/src/shared/logger.ts
8078
+ import * as fs from "node:fs";
8079
+ import * as path3 from "node:path";
8080
+
8081
+ // ../plugin/src/shared/data-path.ts
8082
+ import * as os from "node:os";
8083
+ import * as path2 from "node:path";
8084
+
8085
+ // ../plugin/src/shared/harness.ts
8086
+ var currentHarness = "opencode";
8087
+ var harnessLocked = false;
8088
+ function setHarness(value) {
8089
+ if (harnessLocked && currentHarness !== value) {
8090
+ throw new Error(`Magic Context: harness already locked to "${currentHarness}"; cannot change to "${value}"`);
8091
+ }
8092
+ currentHarness = value;
8093
+ harnessLocked = true;
8094
+ }
8095
+ function getHarness() {
8096
+ return currentHarness;
8097
+ }
8098
+
8099
+ // ../plugin/src/shared/data-path.ts
8100
+ function getDataDir() {
8101
+ return process.env.XDG_DATA_HOME ?? path2.join(os.homedir(), ".local", "share");
8102
+ }
8103
+ function getMagicContextTempDir(harness = getHarness()) {
8104
+ return path2.join(os.tmpdir(), harness, "magic-context");
8105
+ }
8106
+ function getMagicContextLogPath(harness = getHarness()) {
8107
+ return path2.join(getMagicContextTempDir(harness), "magic-context.log");
8108
+ }
8109
+ function getProjectMagicContextDir(directory) {
8110
+ return path2.join(directory, ".opencode", "magic-context");
8111
+ }
8112
+ function getProjectMagicContextHistorianDir(directory) {
8113
+ return path2.join(getProjectMagicContextDir(directory), "historian");
8114
+ }
8115
+ function getOpenCodeStorageDir() {
8116
+ return path2.join(getDataDir(), "opencode", "storage");
8117
+ }
8118
+ function getMagicContextStorageDir() {
8119
+ return path2.join(getDataDir(), "cortexkit", "magic-context");
8120
+ }
8121
+ function getLegacyOpenCodeMagicContextStorageDir() {
8122
+ return path2.join(getOpenCodeStorageDir(), "plugin", "magic-context");
8123
+ }
8124
+
8125
+ // ../plugin/src/shared/logger.ts
8126
+ var isTestEnv = false;
8127
+ var buffer = [];
8128
+ var flushTimer = null;
8129
+ var FLUSH_INTERVAL_MS = 500;
8130
+ var BUFFER_SIZE_LIMIT = 50;
8131
+ var lastEnsuredDir = null;
8132
+ function ensureDir(filePath) {
8133
+ const dir = path3.dirname(filePath);
8134
+ if (dir === lastEnsuredDir)
8135
+ return;
8136
+ try {
8137
+ fs.mkdirSync(dir, { recursive: true });
8138
+ lastEnsuredDir = dir;
8139
+ } catch {}
8140
+ }
8141
+ function flush() {
8142
+ if (flushTimer) {
8143
+ clearTimeout(flushTimer);
8144
+ flushTimer = null;
8145
+ }
8146
+ if (buffer.length === 0)
8147
+ return;
8148
+ const data = buffer.join("");
8149
+ buffer = [];
8150
+ try {
8151
+ const logFile = getMagicContextLogPath();
8152
+ ensureDir(logFile);
8153
+ fs.appendFileSync(logFile, data);
8154
+ } catch {}
8155
+ }
8156
+ function scheduleFlush() {
8157
+ if (flushTimer)
8158
+ return;
8159
+ flushTimer = setTimeout(() => {
8160
+ flushTimer = null;
8161
+ flush();
8162
+ }, FLUSH_INTERVAL_MS);
8163
+ }
8164
+ function log(message, data) {
8165
+ if (isTestEnv)
8166
+ return;
8167
+ try {
8168
+ const timestamp = new Date().toISOString();
8169
+ const serialized = data === undefined ? "" : data instanceof Error ? ` ${data.message}${data.stack ? `
8170
+ ${data.stack}` : ""}` : ` ${JSON.stringify(data)}`;
8171
+ buffer.push(`[${timestamp}] ${message}${serialized}
8172
+ `);
8173
+ if (buffer.length >= BUFFER_SIZE_LIMIT) {
8174
+ flush();
8175
+ } else {
8176
+ scheduleFlush();
8177
+ }
8178
+ } catch {}
8179
+ }
8180
+ function sessionLog(sessionId, message, data) {
8181
+ log(`[magic-context][${sessionId}] ${message}`, data);
8182
+ }
8183
+ if (!isTestEnv) {
8184
+ process.on("exit", flush);
8185
+ }
8287
8186
 
8288
8187
  // ../plugin/src/shared/internal-initiator-marker.ts
8289
8188
  var OMO_INTERNAL_INITIATOR_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
@@ -8297,8 +8196,102 @@ function removeSystemReminders(text) {
8297
8196
  return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
8298
8197
  }
8299
8198
 
8300
- // ../plugin/src/hooks/magic-context/read-session-chunk.ts
8301
- await init_read_session_db();
8199
+ // ../plugin/src/hooks/magic-context/read-session-db.ts
8200
+ import { existsSync } from "node:fs";
8201
+ import { join as join2 } from "node:path";
8202
+
8203
+ // ../plugin/src/shared/sqlite.ts
8204
+ var isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
8205
+ var bunSpec = "bun:" + "sqlite";
8206
+ var nodeSpec = "node:" + "sqlite";
8207
+ var sqliteModule = isBun ? await import(bunSpec) : await import(nodeSpec);
8208
+ var DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
8209
+ function buildNodeSqliteDatabaseClass(DatabaseSync) {
8210
+ const SAVEPOINT = "mc_tx_sp";
8211
+
8212
+ class NodeSqliteDatabase extends DatabaseSync {
8213
+ constructor(filename, options) {
8214
+ const translated = { ...options };
8215
+ if (options && "readonly" in options) {
8216
+ translated.readOnly = options.readonly;
8217
+ delete translated.readonly;
8218
+ }
8219
+ super(typeof filename === "string" ? filename : ":memory:", translated);
8220
+ }
8221
+ transaction(fn) {
8222
+ const self = this;
8223
+ const wrapped = function(...args) {
8224
+ const nested = self.isTransaction === true;
8225
+ self.exec(nested ? `SAVEPOINT ${SAVEPOINT}` : "BEGIN");
8226
+ try {
8227
+ const result = fn.apply(this, args);
8228
+ self.exec(nested ? `RELEASE ${SAVEPOINT}` : "COMMIT");
8229
+ return result;
8230
+ } catch (error) {
8231
+ if (nested) {
8232
+ self.exec(`ROLLBACK TO ${SAVEPOINT}`);
8233
+ self.exec(`RELEASE ${SAVEPOINT}`);
8234
+ } else {
8235
+ self.exec("ROLLBACK");
8236
+ }
8237
+ throw error;
8238
+ }
8239
+ };
8240
+ return wrapped;
8241
+ }
8242
+ }
8243
+ return NodeSqliteDatabase;
8244
+ }
8245
+ var Database = DatabaseImpl;
8246
+
8247
+ // ../plugin/src/shared/sqlite-helpers.ts
8248
+ function closeQuietly(db) {
8249
+ if (!db)
8250
+ return;
8251
+ try {
8252
+ db.close();
8253
+ } catch {}
8254
+ }
8255
+
8256
+ // ../plugin/src/hooks/magic-context/read-session-db.ts
8257
+ function getOpenCodeDbPath() {
8258
+ return join2(getDataDir(), "opencode", "opencode.db");
8259
+ }
8260
+ function openCodeDbExists() {
8261
+ return existsSync(getOpenCodeDbPath());
8262
+ }
8263
+ var cachedReadOnlyDb = null;
8264
+ function closeCachedReadOnlyDb() {
8265
+ if (!cachedReadOnlyDb) {
8266
+ return;
8267
+ }
8268
+ try {
8269
+ closeQuietly(cachedReadOnlyDb.db);
8270
+ } catch (error) {
8271
+ log("[magic-context] failed to close cached OpenCode read-only DB:", error);
8272
+ } finally {
8273
+ cachedReadOnlyDb = null;
8274
+ }
8275
+ }
8276
+ function getReadOnlySessionDb() {
8277
+ const dbPath = getOpenCodeDbPath();
8278
+ if (cachedReadOnlyDb?.path === dbPath) {
8279
+ return cachedReadOnlyDb.db;
8280
+ }
8281
+ closeCachedReadOnlyDb();
8282
+ const db = new Database(dbPath, { readonly: true });
8283
+ cachedReadOnlyDb = { path: dbPath, db };
8284
+ return db;
8285
+ }
8286
+ function withReadOnlySessionDb(fn) {
8287
+ return fn(getReadOnlySessionDb());
8288
+ }
8289
+ function getRawSessionMessageCountFromDb(db, sessionId) {
8290
+ const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
8291
+ AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
8292
+ AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
8293
+ return typeof row?.count === "number" ? row.count : 0;
8294
+ }
8302
8295
 
8303
8296
  // ../../node_modules/.bun/ai-tokenizer@1.0.6/node_modules/ai-tokenizer/dist/index.js
8304
8297
  function _typeof(o) {
@@ -141342,6 +141335,7 @@ function readSessionChunk(sessionId, tokenBudget, offset = 1, eligibleEndOrdinal
141342
141335
  toolOnlyRanges
141343
141336
  };
141344
141337
  }
141338
+
141345
141339
  // ../plugin/src/features/magic-context/compression-depth-storage.ts
141346
141340
  var incrementDepthStatements = new WeakMap;
141347
141341
  var totalDepthStatements = new WeakMap;
@@ -141745,6 +141739,7 @@ function parseReportedLimit(message) {
141745
141739
  }
141746
141740
  return;
141747
141741
  }
141742
+
141748
141743
  // ../plugin/src/features/magic-context/compartment-lease.ts
141749
141744
  var COMPARTMENT_LEASE_TTL_MS = 5 * 60 * 1000;
141750
141745
  var COMPARTMENT_LEASE_RENEWAL_MS = 60 * 1000;
@@ -141815,6 +141810,9 @@ var SESSION_META_SELECT_COLUMNS = [
141815
141810
  "cached_m0_materialized_at",
141816
141811
  "cached_m0_session_facts_version",
141817
141812
  "cached_m0_upgrade_state",
141813
+ "cached_m0_system_hash",
141814
+ "cached_m0_tool_set_hash",
141815
+ "cached_m0_model_key",
141818
141816
  "last_observed_model_key",
141819
141817
  "upgrade_reminded_at",
141820
141818
  "pi_stable_id_scheme"
@@ -141851,6 +141849,9 @@ var META_COLUMNS = {
141851
141849
  cachedM0MaterializedAt: "cached_m0_materialized_at",
141852
141850
  cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
141853
141851
  cachedM0UpgradeState: "cached_m0_upgrade_state",
141852
+ cachedM0SystemHash: "cached_m0_system_hash",
141853
+ cachedM0ToolSetHash: "cached_m0_tool_set_hash",
141854
+ cachedM0ModelKey: "cached_m0_model_key",
141854
141855
  lastObservedModelKey: "last_observed_model_key",
141855
141856
  upgradeRemindedAt: "upgrade_reminded_at",
141856
141857
  piStableIdScheme: "pi_stable_id_scheme"
@@ -141893,7 +141894,7 @@ function isSessionMetaRow(row) {
141893
141894
  if (row === null || typeof row !== "object")
141894
141895
  return false;
141895
141896
  const r = row;
141896
- return typeof r.session_id === "string" && typeof r.last_response_time === "number" && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && typeof r.is_subagent === "number" && typeof r.last_context_percentage === "number" && typeof r.last_input_tokens === "number" && isNumberOrNull(r.observed_safe_input_tokens) && isNumberOrNull(r.cache_alert_sent) && isNumberOrNull(r.times_execute_threshold_reached) && isNumberOrNull(r.compartment_in_progress) && (r.system_prompt_hash === null || typeof r.system_prompt_hash === "string" || typeof r.system_prompt_hash === "number") && isNumberOrNull(r.system_prompt_tokens) && isNumberOrNull(r.conversation_tokens) && isNumberOrNull(r.tool_call_tokens) && isNumberOrNull(r.cleared_reasoning_through_tag) && isStringOrNull(r.last_todo_state) && isBlobOrNull(r.cached_m0_bytes) && isBlobOrNull(r.cached_m1_bytes) && isNumberOrNull(r.cached_m0_project_memory_epoch) && isNumberOrNull(r.cached_m0_project_user_profile_version) && isNumberOrNull(r.cached_m0_max_compartment_seq) && isNumberOrNull(r.cached_m0_max_memory_id) && isNumberOrNull(r.cached_m0_max_mutation_id) && isNumberOrNull(r.cached_m0_max_memory_mutation_id) && isStringOrNull(r.cached_m0_project_docs_hash) && isNumberOrNull(r.cached_m0_materialized_at) && isNumberOrNull(r.cached_m0_session_facts_version) && isStringOrNull(r.cached_m0_upgrade_state) && isStringOrNull(r.last_observed_model_key) && isNumberOrNull(r.upgrade_reminded_at) && isNumberOrNull(r.pi_stable_id_scheme);
141897
+ return typeof r.session_id === "string" && typeof r.last_response_time === "number" && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && typeof r.is_subagent === "number" && typeof r.last_context_percentage === "number" && typeof r.last_input_tokens === "number" && isNumberOrNull(r.observed_safe_input_tokens) && isNumberOrNull(r.cache_alert_sent) && isNumberOrNull(r.times_execute_threshold_reached) && isNumberOrNull(r.compartment_in_progress) && (r.system_prompt_hash === null || typeof r.system_prompt_hash === "string" || typeof r.system_prompt_hash === "number") && isNumberOrNull(r.system_prompt_tokens) && isNumberOrNull(r.conversation_tokens) && isNumberOrNull(r.tool_call_tokens) && isNumberOrNull(r.cleared_reasoning_through_tag) && isStringOrNull(r.last_todo_state) && isBlobOrNull(r.cached_m0_bytes) && isBlobOrNull(r.cached_m1_bytes) && isNumberOrNull(r.cached_m0_project_memory_epoch) && isNumberOrNull(r.cached_m0_project_user_profile_version) && isNumberOrNull(r.cached_m0_max_compartment_seq) && isNumberOrNull(r.cached_m0_max_memory_id) && isNumberOrNull(r.cached_m0_max_mutation_id) && isNumberOrNull(r.cached_m0_max_memory_mutation_id) && isStringOrNull(r.cached_m0_project_docs_hash) && isNumberOrNull(r.cached_m0_materialized_at) && isNumberOrNull(r.cached_m0_session_facts_version) && isStringOrNull(r.cached_m0_upgrade_state) && isStringOrNull(r.cached_m0_system_hash) && isStringOrNull(r.cached_m0_tool_set_hash) && isStringOrNull(r.cached_m0_model_key) && isStringOrNull(r.last_observed_model_key) && isNumberOrNull(r.upgrade_reminded_at) && isNumberOrNull(r.pi_stable_id_scheme);
141897
141898
  }
141898
141899
  function getDefaultSessionMeta(sessionId) {
141899
141900
  return {
@@ -141929,6 +141930,9 @@ function getDefaultSessionMeta(sessionId) {
141929
141930
  cachedM0MaterializedAt: null,
141930
141931
  cachedM0SessionFactsVersion: null,
141931
141932
  cachedM0UpgradeState: null,
141933
+ cachedM0SystemHash: null,
141934
+ cachedM0ToolSetHash: null,
141935
+ cachedM0ModelKey: null,
141932
141936
  lastObservedModelKey: null,
141933
141937
  upgradeRemindedAt: null,
141934
141938
  piStableIdScheme: null
@@ -141980,6 +141984,9 @@ function toSessionMeta(row) {
141980
141984
  cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
141981
141985
  cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
141982
141986
  cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
141987
+ cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
141988
+ cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
141989
+ cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
141983
141990
  lastObservedModelKey: stringOrNull(row.last_observed_model_key),
141984
141991
  upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
141985
141992
  piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
@@ -141999,8 +142006,11 @@ function persistCachedM0(db, sessionId, payload) {
141999
142006
  cached_m0_project_docs_hash = ?,
142000
142007
  cached_m0_materialized_at = ?,
142001
142008
  cached_m0_session_facts_version = ?,
142002
- cached_m0_upgrade_state = ?
142003
- WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.projectMemoryEpoch, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, sessionId);
142009
+ cached_m0_upgrade_state = ?,
142010
+ cached_m0_system_hash = ?,
142011
+ cached_m0_tool_set_hash = ?,
142012
+ cached_m0_model_key = ?
142013
+ WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.projectMemoryEpoch, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.toolSetHash ?? "", payload.modelKey ?? "", sessionId);
142004
142014
  }
142005
142015
  function clearCachedM0M1(db, sessionId) {
142006
142016
  ensureSessionMetaRow(db, sessionId);
@@ -142018,6 +142028,9 @@ function clearCachedM0M1(db, sessionId) {
142018
142028
  ["cached_m0_materialized_at", null],
142019
142029
  ["cached_m0_session_facts_version", null],
142020
142030
  ["cached_m0_upgrade_state", null],
142031
+ ["cached_m0_system_hash", null],
142032
+ ["cached_m0_tool_set_hash", null],
142033
+ ["cached_m0_model_key", null],
142021
142034
  ["cached_m0_last_baseline_end_message_id", null],
142022
142035
  ["memory_block_cache", ""],
142023
142036
  ["memory_block_count", 0],
@@ -142223,11 +142236,7 @@ function escapeXmlAttr(s) {
142223
142236
  function escapeXmlContent(s) {
142224
142237
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
142225
142238
  }
142226
- // ../plugin/src/features/magic-context/migrations.ts
142227
- init_logger();
142228
-
142229
142239
  // ../plugin/src/features/magic-context/storage-db.ts
142230
- init_data_path();
142231
142240
  import { copyFileSync, cpSync, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "node:fs";
142232
142241
  import { dirname as dirname2, join as join5 } from "node:path";
142233
142242
 
@@ -142307,12 +142316,7 @@ function safeString(value) {
142307
142316
  }
142308
142317
  }
142309
142318
 
142310
- // ../plugin/src/features/magic-context/storage-db.ts
142311
- init_logger();
142312
- await init_sqlite();
142313
-
142314
142319
  // ../plugin/src/features/magic-context/key-files/project-key-files.ts
142315
- init_logger();
142316
142320
  import { createHash as createHash2 } from "node:crypto";
142317
142321
  import { existsSync as existsSync2, readFileSync, realpathSync } from "node:fs";
142318
142322
  import { join as join3, resolve, sep } from "node:path";
@@ -142482,8 +142486,6 @@ function loadToolDefinitionMeasurements(db) {
142482
142486
  }
142483
142487
 
142484
142488
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
142485
- init_data_path();
142486
- init_logger();
142487
142489
  import { existsSync as existsSync3 } from "node:fs";
142488
142490
  import { join as join4 } from "node:path";
142489
142491
  var LEASE_DURATION_MS = 5 * 60 * 1000;
@@ -142731,7 +142733,7 @@ var databases = new Map;
142731
142733
  var persistenceByDatabase = new WeakMap;
142732
142734
  var persistenceErrorByDatabase = new WeakMap;
142733
142735
  var lastSchemaFenceRejection = null;
142734
- var LATEST_SUPPORTED_VERSION = 29;
142736
+ var LATEST_SUPPORTED_VERSION = 30;
142735
142737
  function resolveDatabasePath(dbPathOverride) {
142736
142738
  if (dbPathOverride) {
142737
142739
  return { dbDir: dirname2(dbPathOverride), dbPath: dbPathOverride };
@@ -143196,6 +143198,9 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
143196
143198
  cached_m0_materialized_at INTEGER,
143197
143199
  cached_m0_session_facts_version INTEGER,
143198
143200
  cached_m0_upgrade_state TEXT,
143201
+ cached_m0_system_hash TEXT,
143202
+ cached_m0_tool_set_hash TEXT,
143203
+ cached_m0_model_key TEXT,
143199
143204
  cached_m0_last_baseline_end_message_id TEXT,
143200
143205
  upgrade_reminded_at INTEGER,
143201
143206
  pi_stable_id_scheme INTEGER
@@ -143387,6 +143392,9 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
143387
143392
  ensureColumn(db, "session_meta", "cached_m0_materialized_at", "INTEGER");
143388
143393
  ensureColumn(db, "session_meta", "cached_m0_session_facts_version", "INTEGER");
143389
143394
  ensureColumn(db, "session_meta", "cached_m0_upgrade_state", "TEXT");
143395
+ ensureColumn(db, "session_meta", "cached_m0_system_hash", "TEXT");
143396
+ ensureColumn(db, "session_meta", "cached_m0_tool_set_hash", "TEXT");
143397
+ ensureColumn(db, "session_meta", "cached_m0_model_key", "TEXT");
143390
143398
  ensureColumn(db, "session_meta", "cached_m0_last_baseline_end_message_id", "TEXT");
143391
143399
  ensureColumn(db, "session_meta", "upgrade_reminded_at", "INTEGER");
143392
143400
  db.exec(`
@@ -144316,6 +144324,28 @@ var MIGRATIONS = [
144316
144324
  db.exec("ALTER TABLE notes ADD COLUMN anchor_ordinal INTEGER");
144317
144325
  }
144318
144326
  }
144327
+ },
144328
+ {
144329
+ version: 30,
144330
+ description: "HARD-bust m[0] markers: cached system/tool-set/model identity",
144331
+ up: (db) => {
144332
+ const hasSessionMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='session_meta' LIMIT 1").get();
144333
+ if (!hasSessionMeta)
144334
+ return;
144335
+ ensureColumn(db, "session_meta", "cached_m0_system_hash", "TEXT");
144336
+ ensureColumn(db, "session_meta", "cached_m0_tool_set_hash", "TEXT");
144337
+ ensureColumn(db, "session_meta", "cached_m0_model_key", "TEXT");
144338
+ const columns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
144339
+ if (columns.has("cached_m0_bytes")) {
144340
+ db.prepare(`UPDATE session_meta SET
144341
+ cached_m0_bytes = NULL,
144342
+ cached_m1_bytes = NULL,
144343
+ cached_m0_materialized_at = NULL,
144344
+ cached_m0_system_hash = NULL,
144345
+ cached_m0_tool_set_hash = NULL,
144346
+ cached_m0_model_key = NULL`).run();
144347
+ }
144348
+ }
144319
144349
  }
144320
144350
  ];
144321
144351
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -144614,7 +144644,6 @@ function getMaxMemoryMutationId(db, projectPath) {
144614
144644
  return row?.max_id ?? null;
144615
144645
  }
144616
144646
  // ../plugin/src/features/magic-context/storage-meta-persisted.ts
144617
- init_logger();
144618
144647
  var CAS_RETRY_LIMIT = 5;
144619
144648
  var AUTO_SEARCH_NO_HINT_REASONS = new Set([
144620
144649
  "below-threshold",
@@ -145077,8 +145106,6 @@ function setSessionWorkMetrics(db, sessionId, newWorkTokens, totalInputTokens) {
145077
145106
  import { Buffer as Buffer3 } from "node:buffer";
145078
145107
 
145079
145108
  // ../plugin/src/features/magic-context/resolve-subagent-fallback.ts
145080
- init_logger();
145081
- await init_read_session_db();
145082
145109
  function resolveIsSubagentFromOpenCodeDb(sessionId) {
145083
145110
  try {
145084
145111
  return withReadOnlySessionDb((openCodeDb) => {
@@ -145112,6 +145139,9 @@ var SESSION_META_FALLBACK_SELECTS = {
145112
145139
  cached_m0_materialized_at: "NULL AS cached_m0_materialized_at",
145113
145140
  cached_m0_session_facts_version: "NULL AS cached_m0_session_facts_version",
145114
145141
  cached_m0_upgrade_state: "NULL AS cached_m0_upgrade_state",
145142
+ cached_m0_system_hash: "NULL AS cached_m0_system_hash",
145143
+ cached_m0_tool_set_hash: "NULL AS cached_m0_tool_set_hash",
145144
+ cached_m0_model_key: "NULL AS cached_m0_model_key",
145115
145145
  last_observed_model_key: "NULL AS last_observed_model_key",
145116
145146
  upgrade_reminded_at: "NULL AS upgrade_reminded_at"
145117
145147
  };
@@ -145344,7 +145374,6 @@ function markNoteChecked(db, noteId) {
145344
145374
  db.prepare("UPDATE notes SET last_checked_at = ?, updated_at = ? WHERE id = ? AND type = 'smart'").run(now, now, noteId);
145345
145375
  }
145346
145376
  // ../plugin/src/features/magic-context/storage-ops.ts
145347
- init_logger();
145348
145377
  var queuePendingOpStatements = new WeakMap;
145349
145378
  var getPendingOpsStatements = new WeakMap;
145350
145379
  var clearPendingOpsStatements = new WeakMap;
@@ -145746,7 +145775,6 @@ var ERROR_CLASSES = new Set([
145746
145775
  "unknown"
145747
145776
  ]);
145748
145777
  // ../plugin/src/features/magic-context/v22-deferred-backfill.ts
145749
- init_logger();
145750
145778
  import { createHash as createHash4 } from "node:crypto";
145751
145779
  import { realpathSync as realpathSync2 } from "node:fs";
145752
145780
  import path5 from "node:path";
@@ -146025,8 +146053,6 @@ function getAgentFallbackModels(agent) {
146025
146053
  }
146026
146054
 
146027
146055
  // ../plugin/src/shared/models-dev-cache.ts
146028
- init_data_path();
146029
- init_logger();
146030
146056
  import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync, writeFileSync } from "node:fs";
146031
146057
  import { join as join6 } from "node:path";
146032
146058
  var MIN_SANE_LIMIT = 20000;
@@ -146136,7 +146162,6 @@ function resolveHistorianContextLimit(historianModelOverride) {
146136
146162
  }
146137
146163
 
146138
146164
  // ../plugin/src/hooks/magic-context/event-resolvers.ts
146139
- init_logger();
146140
146165
  var DEFAULT_CONTEXT_LIMIT = 128000;
146141
146166
  var MAX_EXECUTE_THRESHOLD = 80;
146142
146167
  function resolveCacheTtl(cacheTtl, modelKey) {
@@ -146269,7 +146294,6 @@ function resolveTokensMatchWithKey(tokensConfig, modelKey) {
146269
146294
  }
146270
146295
 
146271
146296
  // ../plugin/src/hooks/magic-context/note-nudger.ts
146272
- init_logger();
146273
146297
  var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
146274
146298
  var lastDeliveredAt = new Map;
146275
146299
  function getPersistedNoteNudgeDeliveredAt(_db, sessionId) {
@@ -146437,7 +146461,6 @@ function isTodoItem(value) {
146437
146461
  }
146438
146462
 
146439
146463
  // ../plugin/src/hooks/magic-context/upgrade-reminder.ts
146440
- init_logger();
146441
146464
  var remindedThisProcess = new Set;
146442
146465
  var UPGRADE_REMINDER_TEXT = [
146443
146466
  "\uD83C\uDF86 Historian V2 is released!",
@@ -146538,7 +146561,6 @@ async function maybeSendUpgradeReminder(deps, sessionId) {
146538
146561
  }
146539
146562
 
146540
146563
  // ../plugin/src/shared/announcement.ts
146541
- init_data_path();
146542
146564
  import * as fs2 from "node:fs";
146543
146565
  import * as path6 from "node:path";
146544
146566
  var ANNOUNCEMENT_VERSION = "0.22.0";
@@ -146584,9 +146606,14 @@ function shouldShowAnnouncement() {
146584
146606
  return lastVersion !== ANNOUNCEMENT_VERSION;
146585
146607
  }
146586
146608
 
146587
- // src/index.ts
146588
- init_data_path();
146589
- init_logger();
146609
+ // ../plugin/src/shared/keep-subagents.ts
146610
+ var keepSubagents = false;
146611
+ function setKeepSubagents(value) {
146612
+ keepSubagents = value === true;
146613
+ }
146614
+ function shouldKeepSubagents() {
146615
+ return keepSubagents;
146616
+ }
146590
146617
 
146591
146618
  // ../plugin/src/shared/resolve-fallbacks.ts
146592
146619
  function resolveFallbackChain(agentName, userFallbacks) {
@@ -146653,9 +146680,6 @@ function isEmptySidekickResult(text) {
146653
146680
  return trimmed.length === 0 || trimmed === "no relevant memories found";
146654
146681
  }
146655
146682
 
146656
- // src/commands/ctx-aug.ts
146657
- init_logger();
146658
-
146659
146683
  // src/subagent-runner.ts
146660
146684
  import * as childProcess from "node:child_process";
146661
146685
  import { existsSync as existsSync6 } from "node:fs";
@@ -146665,7 +146689,6 @@ import { createInterface } from "node:readline";
146665
146689
  import { fileURLToPath } from "node:url";
146666
146690
 
146667
146691
  // ../plugin/src/features/magic-context/subagent-token-capture.ts
146668
- init_logger();
146669
146692
  function asNumber(value) {
146670
146693
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
146671
146694
  }
@@ -146756,7 +146779,6 @@ function recordChildInvocation(input) {
146756
146779
  }
146757
146780
 
146758
146781
  // src/subagent-runner.ts
146759
- init_logger();
146760
146782
  function resolveBundledPiCli() {
146761
146783
  try {
146762
146784
  const require_ = createRequire2(import.meta.url);
@@ -147529,18 +147551,10 @@ function clearStaleEntries(db, maxAgeMs, projectIdentity) {
147529
147551
  const result = projectIdentity ? db.prepare("DELETE FROM dream_queue WHERE project_path = ? AND started_at IS NOT NULL AND started_at < ?").run(projectIdentity, cutoff) : db.prepare("DELETE FROM dream_queue WHERE started_at IS NOT NULL AND started_at < ?").run(cutoff);
147530
147552
  return result.changes;
147531
147553
  }
147532
-
147533
- // src/commands/ctx-dream.ts
147534
- init_logger();
147535
147554
  // ../plugin/src/features/magic-context/dreamer/runner.ts
147536
147555
  import { existsSync as existsSync8 } from "node:fs";
147537
147556
  import { join as join11 } from "node:path";
147538
-
147539
- // ../plugin/src/shared/index.ts
147540
- init_logger();
147541
-
147542
147557
  // ../plugin/src/shared/model-suggestion-retry.ts
147543
- init_logger();
147544
147558
  function extractMessage(error) {
147545
147559
  if (typeof error === "string")
147546
147560
  return error;
@@ -147775,40 +147789,66 @@ function extractLatestAssistantText(messages) {
147775
147789
  `) || null;
147776
147790
  }
147777
147791
 
147778
- // ../plugin/src/features/magic-context/dreamer/runner.ts
147779
- init_data_path();
147780
- init_logger();
147781
- await init_sqlite();
147782
-
147783
147792
  // ../plugin/src/features/magic-context/key-files/identify-key-files.ts
147784
147793
  import { readFileSync as readFileSync6 } from "node:fs";
147785
- import { isAbsolute, join as join10, relative as relative2 } from "node:path";
147786
- init_logger();
147794
+ import { isAbsolute as isAbsolute2, join as join10, relative as relative2 } from "node:path";
147787
147795
 
147788
147796
  // ../plugin/src/features/magic-context/key-files/aft-availability.ts
147789
147797
  var import_comment_json = __toESM(require_src2(), 1);
147790
147798
  import { existsSync as existsSync7, readFileSync as readFileSync5 } from "node:fs";
147791
147799
  import { homedir as homedir2 } from "node:os";
147792
- import { join as join9 } from "node:path";
147800
+ import { isAbsolute, join as join9, resolve as resolve2 } from "node:path";
147801
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
147793
147802
  var overrideAvailability = null;
147794
147803
  function parseConfig(path7) {
147795
147804
  if (!existsSync7(path7))
147796
147805
  return null;
147797
147806
  return import_comment_json.parse(readFileSync5(path7, "utf-8"));
147798
147807
  }
147799
- function entryMatchesAft(entry) {
147808
+ var AFT_NAME_NEEDLES = ["@cortexkit/aft", "aft-opencode", "aft-pi"];
147809
+ function stringMentionsAft(value) {
147810
+ return AFT_NAME_NEEDLES.some((needle) => value.includes(needle));
147811
+ }
147812
+ function resolveLocalEntryPackageName(value, configDir) {
147813
+ let dir = null;
147814
+ if (value.startsWith("file://")) {
147815
+ try {
147816
+ dir = fileURLToPath2(value);
147817
+ } catch {
147818
+ return null;
147819
+ }
147820
+ } else if (value.startsWith("~/")) {
147821
+ dir = join9(homedir2(), value.slice(2));
147822
+ } else if (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) {
147823
+ dir = isAbsolute(value) ? value : resolve2(configDir, value);
147824
+ } else {
147825
+ return null;
147826
+ }
147827
+ try {
147828
+ const pkg = JSON.parse(readFileSync5(join9(dir, "package.json"), "utf-8"));
147829
+ return typeof pkg.name === "string" ? pkg.name : null;
147830
+ } catch {
147831
+ return null;
147832
+ }
147833
+ }
147834
+ function entryMatchesAft(entry, configDir) {
147800
147835
  const value = Array.isArray(entry) ? entry[0] : entry;
147801
- return typeof value === "string" && (value.includes("@cortexkit/aft") || value.includes("aft-opencode") || value.includes("aft-pi"));
147836
+ if (typeof value !== "string")
147837
+ return false;
147838
+ if (stringMentionsAft(value))
147839
+ return true;
147840
+ const name2 = resolveLocalEntryPackageName(value, configDir);
147841
+ return name2 != null && stringMentionsAft(name2);
147802
147842
  }
147803
- function hasAftInArray(value) {
147804
- return Array.isArray(value) && value.some(entryMatchesAft);
147843
+ function hasAftInArray(value, configDir) {
147844
+ return Array.isArray(value) && value.some((entry) => entryMatchesAft(entry, configDir));
147805
147845
  }
147806
- function hasAftAtKeys(value, keys) {
147846
+ function hasAftAtKeys(value, keys, configDir) {
147807
147847
  if (!value || typeof value !== "object")
147808
147848
  return false;
147809
147849
  const record = value;
147810
147850
  for (const key of keys) {
147811
- if (hasAftInArray(record[key]))
147851
+ if (hasAftInArray(record[key], configDir))
147812
147852
  return true;
147813
147853
  }
147814
147854
  return false;
@@ -147825,7 +147865,8 @@ function getAftAvailability() {
147825
147865
  for (const path7 of opencodePaths) {
147826
147866
  try {
147827
147867
  const config = parseConfig(path7);
147828
- if (hasAftAtKeys(config, ["plugin", "plugins", "mcp", "mcp_servers"])) {
147868
+ const configDir = join9(path7, "..");
147869
+ if (hasAftAtKeys(config, ["plugin", "plugins", "mcp", "mcp_servers"], configDir)) {
147829
147870
  opencode = true;
147830
147871
  break;
147831
147872
  }
@@ -147835,12 +147876,13 @@ function getAftAvailability() {
147835
147876
  for (const path7 of piPaths) {
147836
147877
  try {
147837
147878
  const config = parseConfig(path7);
147838
- if (hasAftAtKeys(config, ["packages", "extensions"])) {
147879
+ const configDir = join9(path7, "..");
147880
+ if (hasAftAtKeys(config, ["packages", "extensions"], configDir)) {
147839
147881
  pi = true;
147840
147882
  break;
147841
147883
  }
147842
147884
  const agent = config?.agent;
147843
- if (hasAftAtKeys(agent, ["packages", "extensions"])) {
147885
+ if (hasAftAtKeys(agent, ["packages", "extensions"], configDir)) {
147844
147886
  pi = true;
147845
147887
  break;
147846
147888
  }
@@ -147860,7 +147902,7 @@ function isAftAvailable() {
147860
147902
 
147861
147903
  // ../plugin/src/features/magic-context/key-files/read-history.ts
147862
147904
  import { realpathSync as realpathSync3 } from "node:fs";
147863
- import { relative, resolve as resolve2 } from "node:path";
147905
+ import { relative, resolve as resolve3 } from "node:path";
147864
147906
  function toMs(value) {
147865
147907
  if (typeof value === "number" && Number.isFinite(value))
147866
147908
  return value;
@@ -147897,7 +147939,7 @@ function coalesceRanges(ranges) {
147897
147939
  }
147898
147940
  function normalizeProjectRelativePath(projectPath, filePath) {
147899
147941
  const root = realpathSync3(projectPath);
147900
- const abs = filePath.startsWith("/") ? resolve2(filePath) : resolve2(root, filePath);
147942
+ const abs = filePath.startsWith("/") ? resolve3(filePath) : resolve3(root, filePath);
147901
147943
  let real = abs;
147902
147944
  try {
147903
147945
  real = realpathSync3(abs);
@@ -148040,9 +148082,6 @@ function collectKeyFileCandidates(args) {
148040
148082
  })).sort((a, b) => b.totalReads - a.totalReads || b.lastReadAt - a.lastReadAt).slice(0, 200);
148041
148083
  }
148042
148084
 
148043
- // ../plugin/src/features/magic-context/key-files/storage-key-files.ts
148044
- init_logger();
148045
-
148046
148085
  // ../plugin/src/features/magic-context/key-files/identify-key-files.ts
148047
148086
  var KEY_FILES_SYSTEM_PROMPT = "You are a file importance evaluator. Given read statistics about files in a coding session, identify which are core orientation files worth pinning in context. Return a JSON array.";
148048
148087
  class KeyFilesValidationError extends Error {
@@ -148262,11 +148301,13 @@ async function runKeyFilesLlm(args) {
148262
148301
  const text = extractLatestAssistantText(messages);
148263
148302
  if (!text)
148264
148303
  throw new Error("Dreamer returned no key-files output.");
148265
- return text;
148304
+ return { text, messages };
148266
148305
  } finally {
148267
- await args.client.session.delete({ path: { id: agentSessionId } }).catch(() => {
148268
- return;
148269
- });
148306
+ if (!shouldKeepSubagents()) {
148307
+ await args.client.session.delete({ path: { id: agentSessionId } }).catch(() => {
148308
+ return;
148309
+ });
148310
+ }
148270
148311
  }
148271
148312
  }
148272
148313
  async function runKeyFilesTask(args) {
@@ -148312,9 +148353,27 @@ async function runKeyFilesTask(args) {
148312
148353
  log(`[key-files] lease renewal threw: ${getErrorMessage(error)}`);
148313
148354
  }
148314
148355
  }, 60000);
148356
+ let invocationRecorded = false;
148357
+ const llmStartedAt = Date.now();
148358
+ const recordKeyFilesInvocation = (params) => {
148359
+ if (!args.parentSessionId || invocationRecorded)
148360
+ return;
148361
+ invocationRecorded = true;
148362
+ recordChildInvocation({
148363
+ db: args.db,
148364
+ parentSessionId: args.parentSessionId,
148365
+ harness: getHarness(),
148366
+ subagent: "dreamer",
148367
+ task: "key files",
148368
+ startedAt: llmStartedAt,
148369
+ status: params.status,
148370
+ messages: params.messages,
148371
+ error: params.error
148372
+ });
148373
+ };
148315
148374
  try {
148316
148375
  try {
148317
- const raw = await runKeyFilesLlm({
148376
+ const { text: raw, messages: llmMessages } = await runKeyFilesLlm({
148318
148377
  client: args.client,
148319
148378
  parentSessionId: args.parentSessionId,
148320
148379
  projectPath,
@@ -148322,8 +148381,10 @@ async function runKeyFilesTask(args) {
148322
148381
  deadline: args.deadline,
148323
148382
  fallbackModels: args.fallbackModels
148324
148383
  });
148384
+ recordKeyFilesInvocation({ status: "completed", messages: llmMessages });
148325
148385
  validated = validateLlmOutput(raw, args.config, projectPath, new Set(candidates.map((candidate) => candidate.path)));
148326
148386
  } catch (error) {
148387
+ recordKeyFilesInvocation({ status: "failed", error });
148327
148388
  log(`[key-files] LLM validation failed: ${getErrorMessage(error)}`);
148328
148389
  throw error;
148329
148390
  }
@@ -148917,9 +148978,6 @@ function getMemoryCountsByStatus(db, projectPath) {
148917
148978
  return counts;
148918
148979
  }
148919
148980
 
148920
- // ../plugin/src/features/magic-context/user-memory/review-user-memories.ts
148921
- init_logger();
148922
-
148923
148981
  // ../plugin/src/features/magic-context/dreamer/task-prompts.ts
148924
148982
  var DREAMER_SYSTEM_PROMPT = `You are a memory maintenance agent for the magic-context system.
148925
148983
  You run during scheduled dream windows to maintain a project's cross-session memory store and codebase documentation.
@@ -149422,7 +149480,8 @@ If no promotions are warranted, return empty arrays. Always consume reviewed can
149422
149480
  db: args.db,
149423
149481
  parentSessionId: args.parentSessionId,
149424
149482
  harness: "opencode",
149425
- subagent: "user_memory_review",
149483
+ subagent: "dreamer",
149484
+ task: "user memories",
149426
149485
  startedAt,
149427
149486
  status: params.status,
149428
149487
  messages: params.messages,
@@ -149546,7 +149605,7 @@ If no promotions are warranted, return empty arrays. Always consume reviewed can
149546
149605
  return result;
149547
149606
  } finally {
149548
149607
  clearInterval(leaseInterval);
149549
- if (agentSessionId) {
149608
+ if (agentSessionId && !shouldKeepSubagents()) {
149550
149609
  await args.client.session.delete({
149551
149610
  path: { id: agentSessionId },
149552
149611
  query: { directory: args.sessionDirectory }
@@ -149870,14 +149929,14 @@ async function runDream(args) {
149870
149929
  }
149871
149930
  } finally {
149872
149931
  clearInterval(leaseRenewalInterval);
149873
- if (agentSessionId && !taskFailed) {
149932
+ if (agentSessionId && !taskFailed && !shouldKeepSubagents()) {
149874
149933
  await args.client.session.delete({
149875
149934
  path: { id: agentSessionId }
149876
149935
  }).catch((error) => {
149877
149936
  log("[dreamer] failed to delete child session:", error);
149878
149937
  });
149879
- } else if (agentSessionId && taskFailed) {
149880
- log(`[dreamer] KEEPING failed child session ${agentSessionId} for task ${taskName} (debugging)`);
149938
+ } else if (agentSessionId && (taskFailed || shouldKeepSubagents())) {
149939
+ log(`[dreamer] KEEPING child session ${agentSessionId} for task ${taskName} (${taskFailed ? "failed" : "keep_subagents"})`);
149881
149940
  }
149882
149941
  }
149883
149942
  if (lostLease) {
@@ -150162,7 +150221,7 @@ Only include notes whose conditions you could definitively evaluate against exte
150162
150221
  parts: [{ type: "text", text: evaluationPrompt, synthetic: true }]
150163
150222
  }
150164
150223
  }, {
150165
- timeoutMs: Math.min(remainingMs, 300000),
150224
+ timeoutMs: Math.min(remainingMs, 5 * 60 * 1000),
150166
150225
  signal: abortController.signal,
150167
150226
  fallbackModels: args.fallbackModels,
150168
150227
  callContext: "dreamer:smart-notes"
@@ -150238,7 +150297,7 @@ Only include notes whose conditions you could definitively evaluate against exte
150238
150297
  });
150239
150298
  } finally {
150240
150299
  clearInterval(leaseInterval);
150241
- if (agentSessionId) {
150300
+ if (agentSessionId && !shouldKeepSubagents()) {
150242
150301
  await args.client.session.delete({
150243
150302
  path: { id: agentSessionId }
150244
150303
  }).catch(() => {});
@@ -150249,7 +150308,7 @@ var MAX_LEASE_RETRIES = 3;
150249
150308
  async function processDreamQueue(args) {
150250
150309
  const maxRuntimeMs = args.maxRuntimeMinutes * 60 * 1000;
150251
150310
  if (!hasActiveDreamLease(args.db)) {
150252
- clearStaleEntries(args.db, maxRuntimeMs + 1800000, args.projectIdentity);
150311
+ clearStaleEntries(args.db, maxRuntimeMs + 30 * 60 * 1000, args.projectIdentity);
150253
150312
  }
150254
150313
  const entry = dequeueNext(args.db, args.projectIdentity);
150255
150314
  if (!entry) {
@@ -150292,7 +150351,6 @@ async function processDreamQueue(args) {
150292
150351
  return result;
150293
150352
  }
150294
150353
  // ../plugin/src/features/magic-context/dreamer/scheduler.ts
150295
- init_logger();
150296
150354
  function parseScheduleWindow(schedule) {
150297
150355
  const match = /^(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})$/.exec(schedule.trim());
150298
150356
  if (!match)
@@ -150367,7 +150425,6 @@ function checkScheduleAndEnqueue(db, schedule, ownProjectIdentity) {
150367
150425
  return enqueued;
150368
150426
  }
150369
150427
  // ../plugin/src/features/magic-context/git-commits/git-log-reader.ts
150370
- init_logger();
150371
150428
  import { execFile } from "node:child_process";
150372
150429
  import { promisify } from "node:util";
150373
150430
  var execFileAsync = promisify(execFile);
@@ -150451,9 +150508,6 @@ ${body}` : subject;
150451
150508
  }
150452
150509
  return commits;
150453
150510
  }
150454
- // ../plugin/src/features/magic-context/git-commits/indexer.ts
150455
- init_logger();
150456
-
150457
150511
  // ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
150458
150512
  var exports_external = {};
150459
150513
  __export(exports_external, {
@@ -164894,6 +164948,7 @@ var MagicContextConfigSchema = exports_external.object({
164894
164948
  model: DEFAULT_LOCAL_EMBEDDING_MODEL
164895
164949
  }).describe("Embedding provider configuration"),
164896
164950
  temporal_awareness: exports_external.boolean().default(true).describe('Inject wall-clock gap markers (<!-- +Xm -->) between user messages where > 5 min elapsed since the previous message, and add start/end date attributes on compartments. Gives the agent a sense of session pacing and "how long ago" across multi-day sessions. Graduated from experimental.temporal_awareness; default: true (set false to opt out).'),
164951
+ keep_subagents: exports_external.boolean().default(false).describe("Debug: keep the child sessions Magic Context spawns for its own subagents (historian, dreamer, sidekick, memory-migration) instead of deleting them on success. Useful for short-term inspection/data collection — their full transcript (prompt, tool calls, token usage, output) stays in the host session store. Kept sessions accumulate until manually cleared; leave false for normal use. Requires a restart to take effect."),
164897
164952
  caveman_text_compression: exports_external.object({
164898
164953
  enabled: exports_external.boolean().default(false).describe("Apply deterministic caveman-style text compression to old conversation text. Only active when ctx_reduce_enabled=false. Compresses user/assistant text in oldest-first tiers: ultra (oldest 20%), full, lite, untouched (newest 40%)."),
164899
164954
  min_chars: exports_external.number().min(100).max(1e4).default(500).describe("Text parts shorter than this (characters) stay untouched. Min 100, max 10000. Default: 500.")
@@ -164929,9 +164984,6 @@ var MagicContextConfigSchema = exports_external.object({
164929
164984
  };
164930
164985
  });
164931
164986
 
164932
- // ../plugin/src/features/magic-context/memory/embedding.ts
164933
- init_logger();
164934
-
164935
164987
  // ../plugin/src/features/magic-context/memory/cosine-similarity.ts
164936
164988
  function cosineSimilarity(a, b) {
164937
164989
  if (a.length !== b.length) {
@@ -164977,8 +165029,6 @@ import { mkdirSync as mkdirSync5 } from "node:fs";
164977
165029
  import { open, stat, unlink, writeFile } from "node:fs/promises";
164978
165030
  import { dirname as dirname4, join as join12 } from "node:path";
164979
165031
  import { pathToFileURL } from "node:url";
164980
- init_data_path();
164981
- init_logger();
164982
165032
  var LOCK_POLL_MS = 150;
164983
165033
  var STALE_LOCK_MS = 3 * 60000;
164984
165034
  var MAX_LOCK_WAIT_MS = 5 * 60000;
@@ -165017,7 +165067,7 @@ async function acquireModelLoadLock(lockPath) {
165017
165067
  if (Date.now() - waitStart > MAX_LOCK_WAIT_MS) {
165018
165068
  throw new Error(`[magic-context] embedding-load lock wait exceeded ${MAX_LOCK_WAIT_MS}ms; another process is still loading the model. Skipping this init attempt to avoid an unsynchronized native load.`);
165019
165069
  }
165020
- await new Promise((resolve3) => setTimeout(resolve3, LOCK_POLL_MS));
165070
+ await new Promise((resolve4) => setTimeout(resolve4, LOCK_POLL_MS));
165021
165071
  }
165022
165072
  }
165023
165073
  }
@@ -165186,7 +165236,7 @@ class LocalEmbeddingProvider {
165186
165236
  }
165187
165237
  const delayMs = 300 * attempt + Math.floor(Math.random() * 200);
165188
165238
  log(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
165189
- await new Promise((resolve3) => setTimeout(resolve3, delayMs));
165239
+ await new Promise((resolve4) => setTimeout(resolve4, delayMs));
165190
165240
  }
165191
165241
  }
165192
165242
  if (this.pipeline) {
@@ -165214,8 +165264,8 @@ class LocalEmbeddingProvider {
165214
165264
  if (this.inFlight === 0) {
165215
165265
  return Promise.resolve();
165216
165266
  }
165217
- return new Promise((resolve3) => {
165218
- this.inFlightWaiters.push(resolve3);
165267
+ return new Promise((resolve4) => {
165268
+ this.inFlightWaiters.push(resolve4);
165219
165269
  });
165220
165270
  }
165221
165271
  finishInFlight() {
@@ -165314,7 +165364,6 @@ class LocalEmbeddingProvider {
165314
165364
  }
165315
165365
 
165316
165366
  // ../plugin/src/features/magic-context/memory/embedding-openai.ts
165317
- init_logger();
165318
165367
  function normalizeEndpoint2(endpoint) {
165319
165368
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
165320
165369
  }
@@ -165530,7 +165579,6 @@ class OpenAICompatibleEmbeddingProvider {
165530
165579
 
165531
165580
  // ../plugin/src/features/magic-context/project-embedding-registry.ts
165532
165581
  import { createHash as createHash7, randomUUID } from "node:crypto";
165533
- init_logger();
165534
165582
 
165535
165583
  // ../plugin/src/features/magic-context/git-commits/storage-git-commit-embeddings.ts
165536
165584
  var saveStatements = new WeakMap;
@@ -166064,7 +166112,6 @@ async function embedText(text, signal) {
166064
166112
  var SWEEP_MAX_WALL_CLOCK_MS2 = 10 * 60 * 1000;
166065
166113
 
166066
166114
  // ../plugin/src/features/magic-context/git-commits/storage-git-commits.ts
166067
- init_logger();
166068
166115
  var insertStatements = new WeakMap;
166069
166116
  var existingShasStatements = new WeakMap;
166070
166117
  var projectCountStatements = new WeakMap;
@@ -166276,9 +166323,6 @@ async function embedUnembeddedCommits(db, projectPath) {
166276
166323
  embedInProgress.delete(projectPath);
166277
166324
  }
166278
166325
  }
166279
- // ../plugin/src/features/magic-context/git-commits/search-git-commits.ts
166280
- init_logger();
166281
-
166282
166326
  // ../plugin/src/features/magic-context/memory/storage-memory-fts.ts
166283
166327
  var DEFAULT_SEARCH_LIMIT = 10;
166284
166328
  var searchStatements = new WeakMap;
@@ -166441,7 +166485,6 @@ function searchGitCommitsSync(db, projectPath, query, options) {
166441
166485
  return results.slice(0, options.limit);
166442
166486
  }
166443
166487
  // ../plugin/src/plugin/dream-timer.ts
166444
- init_logger();
166445
166488
  var DREAM_TIMER_INTERVAL_MS = 15 * 60 * 1000;
166446
166489
  var activeTimer = null;
166447
166490
  function openTimerDatabaseOrNull(context) {
@@ -166601,7 +166644,6 @@ async function sweepGitCommits(args) {
166601
166644
 
166602
166645
  // ../plugin/src/plugin/embedding-bootstrap-helpers.ts
166603
166646
  import { createHash as createHash8 } from "node:crypto";
166604
- init_logger();
166605
166647
  var EMBEDDING_AFFECTING_KEYS = new Set([
166606
166648
  "embedding.api_key",
166607
166649
  "embedding.endpoint",
@@ -166769,7 +166811,7 @@ function migrateLegacyExperimental(rawConfig, warnings) {
166769
166811
  // ../plugin/src/config/variable.ts
166770
166812
  import { existsSync as existsSync9, readFileSync as readFileSync7 } from "node:fs";
166771
166813
  import { homedir as homedir3 } from "node:os";
166772
- import { dirname as dirname5, isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
166814
+ import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
166773
166815
 
166774
166816
  // ../plugin/src/shared/jsonc-parser.ts
166775
166817
  function stripJsonComments(content) {
@@ -166879,9 +166921,9 @@ function substituteConfigVariables(input) {
166879
166921
  }
166880
166922
  let filePath = rawPath.trim();
166881
166923
  if (filePath.startsWith("~/")) {
166882
- filePath = resolve3(homedir3(), filePath.slice(2));
166883
- } else if (!isAbsolute2(filePath)) {
166884
- filePath = resolve3(configDir, filePath);
166924
+ filePath = resolve4(homedir3(), filePath.slice(2));
166925
+ } else if (!isAbsolute3(filePath)) {
166926
+ filePath = resolve4(configDir, filePath);
166885
166927
  }
166886
166928
  if (!existsSync9(filePath)) {
166887
166929
  warnings.push(`File not found for ${token} (resolved to ${filePath}); using empty string`);
@@ -167496,7 +167538,6 @@ function registerCtxDreamCommand(pi, deps) {
167496
167538
  }
167497
167539
 
167498
167540
  // ../plugin/src/hooks/magic-context/execute-flush.ts
167499
- init_logger();
167500
167541
  function executeFlush(db, sessionId) {
167501
167542
  try {
167502
167543
  const pendingOps = getPendingOps(db, sessionId);
@@ -167528,7 +167569,6 @@ function executeFlush(db, sessionId) {
167528
167569
  import * as crypto2 from "node:crypto";
167529
167570
 
167530
167571
  // ../plugin/src/features/magic-context/scheduler.ts
167531
- init_logger();
167532
167572
  var TTL_PATTERN = /^(\d+)([smh])$/;
167533
167573
  var NUMERIC_PATTERN = /^\d+$/;
167534
167574
  var UNIT_TO_MS = {
@@ -167583,6 +167623,7 @@ function createScheduler(config2) {
167583
167623
  }
167584
167624
  };
167585
167625
  }
167626
+
167586
167627
  // ../plugin/src/features/magic-context/tagger.ts
167587
167628
  var TOOL_COMPOSITE_KEY_SEP = "\x00";
167588
167629
  function makeToolCompositeKey(ownerMsgId, callId) {
@@ -168342,7 +168383,6 @@ function replayCavemanCompression(sessionId, db, targets, tags) {
168342
168383
  }
168343
168384
 
168344
168385
  // ../plugin/src/hooks/magic-context/compartment-trigger.ts
168345
- init_logger();
168346
168386
  var PROACTIVE_TRIGGER_OFFSET_PERCENTAGE = 2;
168347
168387
  var POST_DROP_TARGET_RATIO = 0.75;
168348
168388
  var MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE = 6000;
@@ -168579,9 +168619,6 @@ class BoundedSessionMap {
168579
168619
  }
168580
168620
  }
168581
168621
 
168582
- // ../plugin/src/hooks/magic-context/inject-compartments.ts
168583
- init_logger();
168584
-
168585
168622
  // ../plugin/src/hooks/magic-context/decay-curve.ts
168586
168623
  var H50 = 24;
168587
168624
  var D = 25;
@@ -168751,7 +168788,6 @@ function extractM0Block(m0Text, tag) {
168751
168788
  // ../plugin/src/hooks/magic-context/key-files-block.ts
168752
168789
  import { readFileSync as readFileSync9, realpathSync as realpathSync4 } from "node:fs";
168753
168790
  import { join as join14, sep as sep2 } from "node:path";
168754
- init_logger();
168755
168791
  var cachedKeyFilesBySession = new Map;
168756
168792
  var staleUpdates = new Map;
168757
168793
  function staleKey(update) {
@@ -168849,9 +168885,6 @@ ${blocks.join(`
168849
168885
  return rendered;
168850
168886
  }
168851
168887
 
168852
- // ../plugin/src/hooks/magic-context/inject-compartments.ts
168853
- await init_read_session_db();
168854
-
168855
168888
  // ../plugin/src/hooks/magic-context/temporal-awareness.ts
168856
168889
  var TEMPORAL_AWARENESS_THRESHOLD_SECONDS = 300;
168857
168890
  var SECONDS_PER_MINUTE = 60;
@@ -169008,9 +169041,6 @@ function renderMemoryBlockV2(memories, wrapper = "project-memory") {
169008
169041
  `);
169009
169042
  }
169010
169043
 
169011
- // ../plugin/src/hooks/magic-context/nudger.ts
169012
- init_logger();
169013
-
169014
169044
  // ../plugin/src/shared/format-bytes.ts
169015
169045
  function formatBytes(bytes) {
169016
169046
  if (bytes < 1024)
@@ -169212,9 +169242,6 @@ function estimateProjectedPercentage(db, sessionId, contextUsage, preloadedTags)
169212
169242
  return contextUsage.percentage * (1 - dropRatio);
169213
169243
  }
169214
169244
 
169215
- // src/context-handler.ts
169216
- init_logger();
169217
-
169218
169245
  // ../plugin/src/shared/tag-transcript.ts
169219
169246
  function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
169220
169247
  const skipPrefixInjection = options.skipPrefixInjection === true;
@@ -169516,9 +169543,6 @@ function buildToolTarget(part, message) {
169516
169543
  };
169517
169544
  }
169518
169545
 
169519
- // ../plugin/src/features/magic-context/search.ts
169520
- init_logger();
169521
-
169522
169546
  // ../plugin/src/features/magic-context/literal-probes.ts
169523
169547
  var MAX_PROBES = 5;
169524
169548
  var MIN_PROBE_LENGTH = 3;
@@ -169575,7 +169599,6 @@ function containsProbeVerbatim(text, probes) {
169575
169599
  return probes.some((probe) => haystack.includes(probe.toLowerCase()));
169576
169600
  }
169577
169601
  // ../plugin/src/features/magic-context/memory/embedding-backfill.ts
169578
- init_logger();
169579
169602
  async function ensureMemoryEmbeddings(args) {
169580
169603
  const snapshot = getProjectEmbeddingSnapshot(args.projectIdentity);
169581
169604
  if (!snapshot?.enabled) {
@@ -169614,7 +169637,6 @@ async function ensureMemoryEmbeddings(args) {
169614
169637
  return args.existingEmbeddings;
169615
169638
  }
169616
169639
  // ../plugin/src/features/magic-context/memory/promotion.ts
169617
- init_logger();
169618
169640
  function isPromotableCategory(category) {
169619
169641
  return PROMOTABLE_CATEGORIES.some((promotableCategory) => promotableCategory === category);
169620
169642
  }
@@ -170116,17 +170138,16 @@ ${trimmedBody}…
170116
170138
  }
170117
170139
 
170118
170140
  // src/auto-search-pi.ts
170119
- init_logger();
170120
170141
  var AUTO_SEARCH_TIMEOUT_MS = 3000;
170121
170142
  var DEFAULT_SCORE_THRESHOLD = 0.55;
170122
170143
  var DEFAULT_MIN_PROMPT_CHARS = 20;
170123
170144
  async function unifiedSearchWithTimeout(db, sessionId, projectPath, prompt, options, timeoutMs) {
170124
170145
  const controller = new AbortController;
170125
170146
  let timer;
170126
- const timeoutPromise = new Promise((resolve4) => {
170147
+ const timeoutPromise = new Promise((resolve5) => {
170127
170148
  timer = setTimeout(() => {
170128
170149
  controller.abort();
170129
- resolve4(null);
170150
+ resolve5(null);
170130
170151
  }, timeoutMs);
170131
170152
  });
170132
170153
  try {
@@ -170346,7 +170367,6 @@ ${hintText}`;
170346
170367
  function clearAutoSearchForPiSession(_sessionId) {}
170347
170368
 
170348
170369
  // src/compaction-marker-manager-pi.ts
170349
- init_logger();
170350
170370
  function applyDeferredPiCompactionMarker(deps, sessionId, pending) {
170351
170371
  try {
170352
170372
  const matches = getCompartmentsByEndMessageId(deps.db, sessionId, pending.endMessageId);
@@ -170488,7 +170508,6 @@ function stripSystemInjection(text) {
170488
170508
  }
170489
170509
 
170490
170510
  // src/heuristic-cleanup-pi.ts
170491
- init_logger();
170492
170511
  var DEDUP_SAFE_TOOLS = new Set([
170493
170512
  "mcp_grep",
170494
170513
  "mcp_read",
@@ -170738,9 +170757,6 @@ function buildMessageIdToMaxTagFromTargets(targets) {
170738
170757
  return byMessage;
170739
170758
  }
170740
170759
 
170741
- // src/inject-compartments-pi.ts
170742
- init_logger();
170743
-
170744
170760
  // src/read-session-pi.ts
170745
170761
  var SYNTH_USER_ID_PREFIX = "synth-user-";
170746
170762
  function resolvePiStableId(msg, index, entryIds, entryIdByRef) {
@@ -171123,6 +171139,13 @@ function safeGetActiveUserMemoriesPi(db) {
171123
171139
  throw error51;
171124
171140
  }
171125
171141
  }
171142
+ var EMPTY_PI_HARD_SIGNALS = {
171143
+ systemHash: "",
171144
+ toolSetHash: "",
171145
+ modelKey: "",
171146
+ cacheExpired: false,
171147
+ lastResponseTime: 0
171148
+ };
171126
171149
  function decodeCachedM0(value) {
171127
171150
  if (!value)
171128
171151
  return null;
@@ -171169,7 +171192,10 @@ function getCachedMarkers(db, state, compartmentsForNormalization) {
171169
171192
  sessionFactsVersion: meta3.cachedM0SessionFactsVersion,
171170
171193
  materializedAt: meta3.cachedM0MaterializedAt,
171171
171194
  upgradeState: meta3.cachedM0UpgradeState,
171172
- lastBaselineEndMessageId: cachedBoundary
171195
+ lastBaselineEndMessageId: cachedBoundary,
171196
+ systemHash: meta3.cachedM0SystemHash ?? "",
171197
+ toolSetHash: meta3.cachedM0ToolSetHash ?? "",
171198
+ modelKey: meta3.cachedM0ModelKey ?? ""
171173
171199
  };
171174
171200
  }
171175
171201
  function lastBaselineEndMessageId(compartments) {
@@ -171197,7 +171223,10 @@ function readCurrentMarkersFromCompartments(db, state, compartments, projectDocs
171197
171223
  sessionFactsVersion: getSessionFactsVersion(db, state.sessionId),
171198
171224
  materializedAt: Date.now(),
171199
171225
  upgradeState: `${PI_M0_UPGRADE_STATE}:${compartments.some((c) => c.legacy === 1) ? "legacy" : "ready"}`,
171200
- lastBaselineEndMessageId: lastBaselineEndMessageId(compartments)
171226
+ lastBaselineEndMessageId: lastBaselineEndMessageId(compartments),
171227
+ systemHash: (state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).systemHash,
171228
+ toolSetHash: (state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).toolSetHash,
171229
+ modelKey: (state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey
171201
171230
  };
171202
171231
  }
171203
171232
  function mustMaterializePi(state, db, currentCompartmentsOverride) {
@@ -171214,7 +171243,19 @@ function mustMaterializePi(state, db, currentCompartmentsOverride) {
171214
171243
  if (getCachedMarkers(db, state, currentCompartments) === null) {
171215
171244
  return { value: true, reason: "cache_invalid" };
171216
171245
  }
171217
- const cachedMaxCompartmentSeq = normalizeCachedMaxCompartmentSeq(meta3.cachedM0MaxCompartmentSeq ?? EMPTY_MAX_COMPARTMENT_SEQ, currentCompartments);
171246
+ const hard = state.hardSignals ?? EMPTY_PI_HARD_SIGNALS;
171247
+ if (hard.modelKey !== "" && hard.modelKey !== (meta3.cachedM0ModelKey ?? "")) {
171248
+ return { value: true, reason: "model_change" };
171249
+ }
171250
+ if (hard.systemHash !== "" && hard.systemHash !== (meta3.cachedM0SystemHash ?? "")) {
171251
+ return { value: true, reason: "system_hash" };
171252
+ }
171253
+ if (hard.toolSetHash !== "" && hard.toolSetHash !== (meta3.cachedM0ToolSetHash ?? "")) {
171254
+ return { value: true, reason: "tool_set_hash" };
171255
+ }
171256
+ if (hard.cacheExpired && hard.lastResponseTime > 0 && hard.lastResponseTime > (meta3.cachedM0MaterializedAt ?? 0)) {
171257
+ return { value: true, reason: "ttl_idle" };
171258
+ }
171218
171259
  if (meta3.cachedM0UpgradeState !== current.upgradeState) {
171219
171260
  return { value: true, reason: "renderer_upgrade" };
171220
171261
  }
@@ -171224,15 +171265,9 @@ function mustMaterializePi(state, db, currentCompartmentsOverride) {
171224
171265
  if (current.projectMemoryEpoch !== (meta3.cachedM0ProjectMemoryEpoch ?? 0)) {
171225
171266
  return { value: true, reason: "project_memory_change" };
171226
171267
  }
171227
- if (current.projectUserProfileVersion !== (meta3.cachedM0ProjectUserProfileVersion ?? 0)) {
171228
- return { value: true, reason: "user_profile_change" };
171229
- }
171230
171268
  if (current.maxMutationId !== (meta3.cachedM0MaxMutationId ?? 0)) {
171231
171269
  return { value: true, reason: "pending_mutations" };
171232
171270
  }
171233
- if (current.maxCompartmentSeq !== cachedMaxCompartmentSeq) {
171234
- return { value: true, reason: "new_compartment" };
171235
- }
171236
171271
  return { value: false, reason: null };
171237
171272
  }
171238
171273
  function renderUserProfileBlock(db, wrapper = "user-profile", memoriesOverride) {
@@ -171312,7 +171347,10 @@ function readFrozenM0InputsPi(state, db, docs = readProjectDocsCanonical(state.p
171312
171347
  sessionFactsVersion: getSessionFactsVersion(db, state.sessionId),
171313
171348
  materializedAt: Date.now(),
171314
171349
  upgradeState: `${PI_M0_UPGRADE_STATE}:${compartments.some((c) => c.legacy === 1) ? "legacy" : "ready"}`,
171315
- lastBaselineEndMessageId: lastBaselineEndMessageId(compartments)
171350
+ lastBaselineEndMessageId: lastBaselineEndMessageId(compartments),
171351
+ systemHash: (state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).systemHash,
171352
+ toolSetHash: (state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).toolSetHash,
171353
+ modelKey: (state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey
171316
171354
  };
171317
171355
  return { docs, markers, compartments, memories, userProfile };
171318
171356
  });
@@ -171388,7 +171426,10 @@ function materializeM0Pi(state, db) {
171388
171426
  projectDocsHash: snapshotMarkers.projectDocsHash,
171389
171427
  materializedAt: snapshotMarkers.materializedAt,
171390
171428
  sessionFactsVersion: snapshotMarkers.sessionFactsVersion,
171391
- upgradeState: snapshotMarkers.upgradeState
171429
+ upgradeState: snapshotMarkers.upgradeState,
171430
+ systemHash: snapshotMarkers.systemHash,
171431
+ toolSetHash: snapshotMarkers.toolSetHash,
171432
+ modelKey: snapshotMarkers.modelKey
171392
171433
  });
171393
171434
  db.prepare("UPDATE session_meta SET memory_block_count = ?, memory_block_ids = ? WHERE session_id = ?").run(renderedMemoryIds.length, JSON.stringify(renderedMemoryIds), state.sessionId);
171394
171435
  setCachedBoundary(db, state.sessionId, snapshotMarkers.lastBaselineEndMessageId);
@@ -171554,6 +171595,9 @@ function readCachedPiM0M1Row(db, sessionId) {
171554
171595
  cached_m0_materialized_at,
171555
171596
  cached_m0_session_facts_version,
171556
171597
  cached_m0_upgrade_state,
171598
+ cached_m0_system_hash,
171599
+ cached_m0_tool_set_hash,
171600
+ cached_m0_model_key,
171557
171601
  cached_m0_last_baseline_end_message_id,
171558
171602
  memory_block_ids
171559
171603
  FROM session_meta
@@ -171591,14 +171635,17 @@ function markersFromCachedPiRow(row, compartmentsForNormalization) {
171591
171635
  materializedAt: row.cached_m0_materialized_at,
171592
171636
  sessionFactsVersion: row.cached_m0_session_facts_version,
171593
171637
  upgradeState: row.cached_m0_upgrade_state,
171594
- lastBaselineEndMessageId: typeof row.cached_m0_last_baseline_end_message_id === "string" && row.cached_m0_last_baseline_end_message_id.length > 0 ? row.cached_m0_last_baseline_end_message_id : null
171638
+ lastBaselineEndMessageId: typeof row.cached_m0_last_baseline_end_message_id === "string" && row.cached_m0_last_baseline_end_message_id.length > 0 ? row.cached_m0_last_baseline_end_message_id : null,
171639
+ systemHash: row.cached_m0_system_hash ?? "",
171640
+ toolSetHash: row.cached_m0_tool_set_hash ?? "",
171641
+ modelKey: row.cached_m0_model_key ?? ""
171595
171642
  };
171596
171643
  }
171597
171644
  function cachedPiRowMatchesSnapshot(args) {
171598
171645
  const rowMarkers = markersFromCachedPiRow(args.row, args.compartmentsForNormalization);
171599
171646
  if (!rowMarkers)
171600
171647
  return false;
171601
- return bufferEqualsNullable(args.row.cached_m0_bytes, args.m0Bytes) && rowMarkers.projectMemoryEpoch === args.markers.projectMemoryEpoch && rowMarkers.projectUserProfileVersion === args.markers.projectUserProfileVersion && rowMarkers.maxCompartmentSeq === args.markers.maxCompartmentSeq && rowMarkers.maxMemoryId === args.markers.maxMemoryId && rowMarkers.maxMutationId === args.markers.maxMutationId && rowMarkers.maxMemoryMutationId === args.markers.maxMemoryMutationId && (rowMarkers.projectDocsHash ?? "") === (args.markers.projectDocsHash ?? "") && rowMarkers.materializedAt === args.markers.materializedAt && rowMarkers.sessionFactsVersion === args.markers.sessionFactsVersion && (rowMarkers.upgradeState ?? null) === (args.markers.upgradeState ?? null);
171648
+ return bufferEqualsNullable(args.row.cached_m0_bytes, args.m0Bytes) && rowMarkers.projectMemoryEpoch === args.markers.projectMemoryEpoch && rowMarkers.projectUserProfileVersion === args.markers.projectUserProfileVersion && rowMarkers.maxCompartmentSeq === args.markers.maxCompartmentSeq && rowMarkers.maxMemoryId === args.markers.maxMemoryId && rowMarkers.maxMutationId === args.markers.maxMutationId && rowMarkers.maxMemoryMutationId === args.markers.maxMemoryMutationId && (rowMarkers.projectDocsHash ?? "") === (args.markers.projectDocsHash ?? "") && rowMarkers.materializedAt === args.markers.materializedAt && rowMarkers.sessionFactsVersion === args.markers.sessionFactsVersion && (rowMarkers.upgradeState ?? null) === (args.markers.upgradeState ?? null) && (rowMarkers.systemHash ?? "") === (args.markers.systemHash ?? "") && (rowMarkers.toolSetHash ?? "") === (args.markers.toolSetHash ?? "") && (rowMarkers.modelKey ?? "") === (args.markers.modelKey ?? "");
171602
171649
  }
171603
171650
  function decodeCachedM1(row, sessionId) {
171604
171651
  if (!row.cached_m1_bytes) {
@@ -171658,12 +171705,14 @@ function softRefreshCachedM1Pi(args) {
171658
171705
  }
171659
171706
  const rendered = renderM1PiWithMetadata(args.state, args.db, markers, parseMemoryBlockIds(row.memory_block_ids), preRenderedKeyFilesBlock);
171660
171707
  const m1Bytes = Buffer.from(rendered.text, "utf8");
171661
- args.db.prepare("UPDATE session_meta SET cached_m1_bytes = ? WHERE session_id = ?").run(m1Bytes, args.state.sessionId);
171708
+ const latestCompartment = args.compartmentsForNormalization.at(-1);
171709
+ const advancedBoundary = latestCompartment?.endMessageId && latestCompartment.endMessageId.length > 0 ? latestCompartment.endMessageId : markers.lastBaselineEndMessageId;
171710
+ args.db.prepare("UPDATE session_meta SET cached_m1_bytes = ?, cached_m0_last_baseline_end_message_id = ? WHERE session_id = ?").run(m1Bytes, advancedBoundary, args.state.sessionId);
171662
171711
  args.db.exec("COMMIT");
171663
171712
  return {
171664
171713
  m0: decodeCachedM0(row.cached_m0_bytes) ?? "",
171665
171714
  m1: rendered.text,
171666
- markers,
171715
+ markers: { ...markers, lastBaselineEndMessageId: advancedBoundary },
171667
171716
  memoryUpdateCount: rendered.memoryUpdateCount,
171668
171717
  recomputed: true
171669
171718
  };
@@ -171783,7 +171832,10 @@ function injectM0M1Pi(state, db, piMessages, entryIds, recomputeM1ThisPass = fal
171783
171832
  markers = replayed.markers;
171784
171833
  }
171785
171834
  const M0_DRIFT_RATIO_FLOOR = 2000;
171786
- if (!materialized && !contentionExhausted && m1Recomputed && recomputeM1ThisPass && (memoryUpdateCount > 40 || m1 !== PI_M1_PLACEHOLDER && m0.length >= M0_DRIFT_RATIO_FLOOR && m1.length > m0.length * 0.15)) {
171835
+ const M1_ABSOLUTE_CAP_RATIO = 0.2;
171836
+ const m1AbsoluteBudget = (state.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS) * M1_ABSOLUTE_CAP_RATIO;
171837
+ const m1OverAbsoluteCap = m1 !== PI_M1_PLACEHOLDER && estimateTokens(m1) > m1AbsoluteBudget;
171838
+ if (!materialized && !contentionExhausted && m1Recomputed && recomputeM1ThisPass && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1 !== PI_M1_PLACEHOLDER && m0.length >= M0_DRIFT_RATIO_FLOOR && m1.length > m0.length * 0.15)) {
171787
171839
  decision = { value: true, reason: "drift" };
171788
171840
  try {
171789
171841
  const result = materializeM0PiWithRetry(state, db);
@@ -171966,7 +172018,6 @@ function isRecord3(value) {
171966
172018
  }
171967
172019
 
171968
172020
  // ../plugin/src/features/magic-context/compartment-embedding.ts
171969
- init_logger();
171970
172021
  async function embedAndStoreCompartments(db, sessionId, projectPath, compartments) {
171971
172022
  if (compartments.length === 0)
171972
172023
  return;
@@ -172863,7 +172914,6 @@ Memory is disabled for this project: do NOT emit a <facts> block. Produce compar
172863
172914
  }
172864
172915
 
172865
172916
  // ../plugin/src/hooks/magic-context/compartment-runner-drop-queue.ts
172866
- init_logger();
172867
172917
  function queueDropsForCompartmentalizedMessages(db, sessionId, upToMessageIndex) {
172868
172918
  const tags = getTagsBySession(db, sessionId);
172869
172919
  const { messageFileKeys, toolObservations } = getRawSessionTagKeysThrough(sessionId, upToMessageIndex);
@@ -174987,7 +175037,6 @@ function buildReferenceBlocks(args) {
174987
175037
  }
174988
175038
 
174989
175039
  // src/pi-historian-runner.ts
174990
- init_logger();
174991
175040
  var HISTORIAN_AGENT_NAME = "magic-context-historian";
174992
175041
  var DEFAULT_HISTORIAN_TIMEOUT_MS2 = 120000;
174993
175042
  var HISTORIAN_ALERT_COOLDOWN_MS = 60 * 1000;
@@ -175770,7 +175819,6 @@ function replayStrippedInlineThinkingPi(args) {
175770
175819
  }
175771
175820
 
175772
175821
  // src/strip-placeholders-pi.ts
175773
- init_logger();
175774
175822
  var DROPPED_SEGMENT_PATTERN = /^\[dropped(?: §[^§]+§)?\]$/;
175775
175823
  function isDroppedOnlyText(text) {
175776
175824
  const trimmed = text.trim();
@@ -175974,7 +176022,6 @@ Prefer many small targeted operations over one large blanket operation, and keep
175974
176022
  }
175975
176023
 
175976
176024
  // src/system-prompt.ts
175977
- init_logger();
175978
176025
  var MAGIC_CONTEXT_MARKER = "## Magic Context";
175979
176026
  var stickyDateBySession = new Map;
175980
176027
  function buildMagicContextBlock(opts) {
@@ -176094,8 +176141,8 @@ function injectPiTemporalMarkers(messages) {
176094
176141
  // src/timeout.ts
176095
176142
  function withTimeout(p, ms) {
176096
176143
  let handle;
176097
- const timeout = new Promise((resolve4) => {
176098
- handle = setTimeout(() => resolve4(undefined), ms);
176144
+ const timeout = new Promise((resolve5) => {
176145
+ handle = setTimeout(() => resolve5(undefined), ms);
176099
176146
  handle.unref?.();
176100
176147
  });
176101
176148
  return Promise.race([p, timeout]).finally(() => {
@@ -177827,9 +177874,18 @@ async function runPipeline(args) {
177827
177874
  if (args.injection) {
177828
177875
  try {
177829
177876
  const tInjection = performance.now();
177830
- if (args.isCacheBusting || deferredHistoryRefresh) {
177831
- clearM0M1PiCache(args.db, args.sessionId, args.isCacheBusting ? "history refresh" : "deferred history refresh");
177832
- }
177877
+ const hardMeta = getOrCreateSessionMeta(args.db, args.sessionId);
177878
+ let piTtlMs = 5 * 60 * 1000;
177879
+ try {
177880
+ piTtlMs = parseCacheTtl(hardMeta.cacheTtl);
177881
+ } catch {}
177882
+ const piHardSignals = {
177883
+ systemHash: typeof hardMeta.systemPromptHash === "string" ? hardMeta.systemPromptHash : "",
177884
+ toolSetHash: "",
177885
+ modelKey: liveModelBySession.get(args.sessionId) ?? "",
177886
+ cacheExpired: hardMeta.lastResponseTime > 0 && Date.now() - hardMeta.lastResponseTime >= piTtlMs,
177887
+ lastResponseTime: hardMeta.lastResponseTime
177888
+ };
177833
177889
  injectionResult = injectM0M1Pi({
177834
177890
  sessionId: args.sessionId,
177835
177891
  projectIdentity: args.projectIdentity,
@@ -177837,8 +177893,9 @@ async function runPipeline(args) {
177837
177893
  injectionBudgetTokens: args.injection.injectionBudgetTokens,
177838
177894
  historyBudgetTokens: args.injection.historyBudgetTokens,
177839
177895
  keyFilesEnabled: args.injection.keyFilesEnabled,
177840
- keyFilesTokenBudget: args.injection.keyFilesTokenBudget
177841
- }, args.db, args.messages, args.entryIds, executedWorkThisPass);
177896
+ keyFilesTokenBudget: args.injection.keyFilesTokenBudget,
177897
+ hardSignals: piHardSignals
177898
+ }, args.db, args.messages, args.entryIds, args.isCacheBusting || deferredHistoryRefresh || executedWorkThisPass);
177842
177899
  if (args.isCacheBusting) {
177843
177900
  historyRefreshSessions.delete(args.sessionId);
177844
177901
  historyWasConsumedThisPass = true;
@@ -178191,12 +178248,8 @@ ${result}`;
178191
178248
  });
178192
178249
  }
178193
178250
 
178194
- // ../plugin/src/hooks/magic-context/compartment-runner.ts
178195
- init_logger();
178196
-
178197
178251
  // ../plugin/src/hooks/magic-context/historian-state-file.ts
178198
178252
  import { mkdirSync as mkdirSync6, unlinkSync, writeFileSync as writeFileSync3 } from "node:fs";
178199
- init_data_path();
178200
178253
  function cleanupHistorianStateFile(path7) {
178201
178254
  if (!path7)
178202
178255
  return;
@@ -178204,13 +178257,7 @@ function cleanupHistorianStateFile(path7) {
178204
178257
  unlinkSync(path7);
178205
178258
  } catch {}
178206
178259
  }
178207
- // ../plugin/src/hooks/magic-context/compartment-runner-incremental.ts
178208
- init_logger();
178209
-
178210
178260
  // ../plugin/src/features/magic-context/compaction-marker.ts
178211
- init_data_path();
178212
- init_logger();
178213
- await init_sqlite();
178214
178261
  import { join as join15 } from "node:path";
178215
178262
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
178216
178263
  function randomBase62(length) {
@@ -178365,9 +178412,6 @@ function removeCompactionMarker(state) {
178365
178412
  }
178366
178413
 
178367
178414
  // ../plugin/src/hooks/magic-context/compaction-marker-manager.ts
178368
- init_data_path();
178369
- init_logger();
178370
- await init_sqlite();
178371
178415
  var MARKER_SUMMARY_TEXT = "[Compacted by magic-context — session history is managed by the plugin]";
178372
178416
  function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEnd, directory) {
178373
178417
  const existing = getPersistedCompactionMarkerState(db, sessionId);
@@ -178401,7 +178445,6 @@ function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEn
178401
178445
  // ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
178402
178446
  import { mkdirSync as mkdirSync7, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "node:fs";
178403
178447
  import { join as join16 } from "node:path";
178404
- init_data_path();
178405
178448
  function historianResponseDumpDir(directory) {
178406
178449
  return getProjectMagicContextHistorianDir(directory);
178407
178450
  }
@@ -178601,12 +178644,12 @@ async function runHistorianPrompt(args) {
178601
178644
  error: `Historian failed while processing this session: ${desc.brief}`
178602
178645
  };
178603
178646
  } finally {
178604
- if (agentSessionId && outcomeOk) {
178647
+ if (agentSessionId && outcomeOk && !shouldKeepSubagents()) {
178605
178648
  await client.session.delete({ path: { id: agentSessionId } }).catch((e) => {
178606
178649
  sessionLog(parentSessionId, "compartment agent: session cleanup failed", getErrorMessage(e));
178607
178650
  });
178608
- } else if (agentSessionId && !outcomeOk) {
178609
- sessionLog(parentSessionId, `historian: KEEPING failed child session ${agentSessionId} for debugging (not deleted)`);
178651
+ } else if (agentSessionId && (!outcomeOk || shouldKeepSubagents())) {
178652
+ sessionLog(parentSessionId, `historian: KEEPING child session ${agentSessionId} (${outcomeOk ? "keep_subagents" : "failed"}) — not deleted`);
178610
178653
  }
178611
178654
  }
178612
178655
  }
@@ -178685,8 +178728,8 @@ function isTransientHistorianPromptError(message) {
178685
178728
  ].some((token) => normalized.includes(token));
178686
178729
  }
178687
178730
  function sleep(ms) {
178688
- return new Promise((resolve4) => {
178689
- setTimeout(resolve4, ms);
178731
+ return new Promise((resolve5) => {
178732
+ setTimeout(resolve5, ms);
178690
178733
  });
178691
178734
  }
178692
178735
  function cleanupHistorianDump(sessionId, dumpPath) {
@@ -178727,7 +178770,6 @@ function sanitizeDumpName(value) {
178727
178770
  }
178728
178771
 
178729
178772
  // ../plugin/src/hooks/magic-context/send-session-notification.ts
178730
- init_logger();
178731
178773
  function hasNotificationSessionClient(client) {
178732
178774
  if (client === null || typeof client !== "object")
178733
178775
  return false;
@@ -178826,11 +178868,7 @@ async function sendIgnoredMessage(client, sessionId, text, params, forcePersist
178826
178868
  var HISTORIAN_ALERT_COOLDOWN_MS2 = 60 * 1000;
178827
178869
  var lastHistorianAlertBySession2 = new Map;
178828
178870
 
178829
- // ../plugin/src/hooks/magic-context/compartment-runner-partial-recomp.ts
178830
- init_logger();
178831
-
178832
178871
  // ../plugin/src/hooks/magic-context/compartment-runner-recomp.ts
178833
- init_logger();
178834
178872
  function insertRecompCompartmentRows(db, sessionId, compartments, now) {
178835
178873
  const stmt = db.prepare("INSERT INTO compartments (session_id, sequence, start_message, end_message, start_message_id, end_message_id, title, content, p1, p2, p3, p4, importance, episode_type, legacy, created_at, harness) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
178836
178874
  for (const c of compartments) {
@@ -179599,9 +179637,6 @@ async function executeContextRecompWithResult(deps, options = {}) {
179599
179637
  }
179600
179638
  }
179601
179639
 
179602
- // src/commands/ctx-recomp.ts
179603
- init_logger();
179604
-
179605
179640
  // src/pi-recomp-client-shared.ts
179606
179641
  function createPiHistorianClient(args) {
179607
179642
  const sessions = new Map;
@@ -179733,9 +179768,6 @@ function resolvePiReadBranchEntries2(ctx) {
179733
179768
  };
179734
179769
  }
179735
179770
 
179736
- // src/pi-recomp-runner.ts
179737
- init_logger();
179738
-
179739
179771
  // src/status-line.ts
179740
179772
  var STATUS_KEY = "magic-context";
179741
179773
  var RECENT_FAILURE_MS = 60000;
@@ -180064,7 +180096,6 @@ function inferLevel(text) {
180064
180096
  }
180065
180097
 
180066
180098
  // ../plugin/src/features/magic-context/memory/memory-migration.ts
180067
- init_logger();
180068
180099
  function memoryMigrationGuardKey(projectPath) {
180069
180100
  return `memory_migration_5cat:${projectPath}`;
180070
180101
  }
@@ -180174,11 +180205,7 @@ function contextualizeUpgradeReason(reason) {
180174
180205
  return rewritten;
180175
180206
  }
180176
180207
 
180177
- // src/commands/ctx-session-upgrade.ts
180178
- init_logger();
180179
-
180180
180208
  // src/pi-memory-migration.ts
180181
- init_logger();
180182
180209
  var MIGRATION_SYSTEM_PROMPT2 = "You re-organize a software project's long-term memory into a stricter taxonomy. " + "Follow the user instructions exactly. Output ONLY the requested XML blocks, nothing else.";
180183
180210
  async function runPiMemoryMigration(deps) {
180184
180211
  const projectPath = resolveProjectIdentity(deps.directory);
@@ -180453,7 +180480,6 @@ ${migrationSummary}` : "",
180453
180480
  }
180454
180481
 
180455
180482
  // ../plugin/src/hooks/magic-context/execute-status.ts
180456
- init_logger();
180457
180483
  function formatExecuteThreshold(thresholdPercentage, mode, contextLimit) {
180458
180484
  if (mode === "tokens" && contextLimit > 0) {
180459
180485
  const tokens = Math.floor(thresholdPercentage / 100 * contextLimit);
@@ -180620,7 +180646,7 @@ function formatThresholdPercent(value) {
180620
180646
  // package.json
180621
180647
  var package_default = {
180622
180648
  name: "@cortexkit/pi-magic-context",
180623
- version: "0.22.3",
180649
+ version: "0.22.4",
180624
180650
  type: "module",
180625
180651
  description: "Pi coding agent extension for Magic Context — cross-session memory and context management",
180626
180652
  main: "dist/index.js",
@@ -185358,7 +185384,6 @@ function createCtxExpandTool(deps) {
185358
185384
  }
185359
185385
 
185360
185386
  // src/tools/ctx-memory.ts
185361
- init_logger();
185362
185387
  var DEFAULT_LIST_LIMIT = 10;
185363
185388
  var VALID_CATEGORIES = new Set(CATEGORY_PRIORITY);
185364
185389
  function isMemoryCategory2(value) {
@@ -186526,6 +186551,7 @@ async function src_default2(pi) {
186526
186551
  mmapSizeMb: config2.sqlite.mmap_size_mb
186527
186552
  });
186528
186553
  applySqliteTuningPragmas(db);
186554
+ setKeepSubagents(config2.keep_subagents === true);
186529
186555
  if (!config2.enabled) {
186530
186556
  info("plugin DISABLED via config (enabled: false) — skipping registration");
186531
186557
  return;