@wolfx/pi-magic-context 0.22.1-patch.0 → 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.
@@ -46,170 +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 path from "node:path";
65
- function getDataDir() {
66
- return process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share");
67
- }
68
- function getMagicContextTempDir(harness = getHarness()) {
69
- return path.join(os.tmpdir(), harness, "magic-context");
70
- }
71
- function getMagicContextLogPath(harness = getHarness()) {
72
- return path.join(getMagicContextTempDir(harness), "magic-context.log");
73
- }
74
- function getProjectMagicContextDir(directory) {
75
- return path.join(directory, ".magic-context");
76
- }
77
- function getProjectMagicContextHistorianDir(directory) {
78
- return path.join(getProjectMagicContextDir(directory), "historian");
79
- }
80
- function getOpenCodeStorageDir() {
81
- return path.join(getDataDir(), "opencode", "storage");
82
- }
83
- function getMagicContextStorageDir() {
84
- return path.join(getDataDir(), "cortexkit", "magic-context");
85
- }
86
- function getLegacyOpenCodeMagicContextStorageDir() {
87
- return path.join(getOpenCodeStorageDir(), "plugin", "magic-context");
88
- }
89
- function getCacheDir() {
90
- return process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache");
91
- }
92
- var init_data_path = () => {};
93
-
94
- // ../plugin/src/shared/logger.ts
95
- import * as fs from "node:fs";
96
- import * as path2 from "node:path";
97
- function ensureDir(filePath) {
98
- const dir = path2.dirname(filePath);
99
- if (dir === lastEnsuredDir)
100
- return;
101
- try {
102
- fs.mkdirSync(dir, { recursive: true });
103
- lastEnsuredDir = dir;
104
- } catch {}
105
- }
106
- function flush() {
107
- if (flushTimer) {
108
- clearTimeout(flushTimer);
109
- flushTimer = null;
110
- }
111
- if (buffer.length === 0)
112
- return;
113
- const data = buffer.join("");
114
- buffer = [];
115
- try {
116
- const logFile = getMagicContextLogPath();
117
- ensureDir(logFile);
118
- fs.appendFileSync(logFile, data);
119
- } catch {}
120
- }
121
- function scheduleFlush() {
122
- if (flushTimer)
123
- return;
124
- flushTimer = setTimeout(() => {
125
- flushTimer = null;
126
- flush();
127
- }, FLUSH_INTERVAL_MS);
128
- }
129
- function log(message, data) {
130
- if (isTestEnv)
131
- return;
132
- try {
133
- const timestamp = new Date().toISOString();
134
- const serialized = data === undefined ? "" : data instanceof Error ? ` ${data.message}${data.stack ? `
135
- ${data.stack}` : ""}` : ` ${JSON.stringify(data)}`;
136
- buffer.push(`[${timestamp}] ${message}${serialized}
137
- `);
138
- if (buffer.length >= BUFFER_SIZE_LIMIT) {
139
- flush();
140
- } else {
141
- scheduleFlush();
142
- }
143
- } catch {}
144
- }
145
- function sessionLog(sessionId, message, data) {
146
- log(`[magic-context][${sessionId}] ${message}`, data);
147
- }
148
- var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, lastEnsuredDir = null;
149
- var init_logger = __esm(() => {
150
- init_data_path();
151
- buffer = [];
152
- if (!isTestEnv) {
153
- process.on("exit", flush);
154
- }
155
- });
156
-
157
- // ../plugin/src/shared/sqlite.ts
158
- function buildNodeSqliteDatabaseClass(DatabaseSync) {
159
- const SAVEPOINT = "mc_tx_sp";
160
-
161
- class NodeSqliteDatabase extends DatabaseSync {
162
- constructor(filename, options) {
163
- const translated = { ...options };
164
- if (options && "readonly" in options) {
165
- translated.readOnly = options.readonly;
166
- delete translated.readonly;
167
- }
168
- super(typeof filename === "string" ? filename : ":memory:", translated);
169
- }
170
- transaction(fn) {
171
- const self = this;
172
- const wrapped = function(...args) {
173
- const nested = self.isTransaction === true;
174
- self.exec(nested ? `SAVEPOINT ${SAVEPOINT}` : "BEGIN");
175
- try {
176
- const result = fn.apply(this, args);
177
- self.exec(nested ? `RELEASE ${SAVEPOINT}` : "COMMIT");
178
- return result;
179
- } catch (error) {
180
- if (nested) {
181
- self.exec(`ROLLBACK TO ${SAVEPOINT}`);
182
- self.exec(`RELEASE ${SAVEPOINT}`);
183
- } else {
184
- self.exec("ROLLBACK");
185
- }
186
- throw error;
187
- }
188
- };
189
- return wrapped;
190
- }
191
- }
192
- return NodeSqliteDatabase;
193
- }
194
- var isBun, bunSpec, nodeSpec, sqliteModule, DatabaseImpl, Database;
195
- var init_sqlite = __esm(async () => {
196
- isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
197
- bunSpec = "bun:" + "sqlite";
198
- nodeSpec = "node:" + "sqlite";
199
- sqliteModule = isBun ? await import(bunSpec) : await import(nodeSpec);
200
- DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
201
- Database = DatabaseImpl;
202
- });
203
-
204
- // ../plugin/src/shared/sqlite-helpers.ts
205
- function closeQuietly(db) {
206
- if (!db)
207
- return;
208
- try {
209
- db.close();
210
- } catch {}
211
- }
212
-
213
49
  // ../../node_modules/.bun/esprima@4.0.1/node_modules/esprima/dist/esprima.js
214
50
  var require_esprima = __commonJS((exports, module) => {
215
51
  (function webpackUniversalModuleDefinition(root, factory) {
@@ -7967,57 +7803,53 @@ var require_src2 = __commonJS((exports, module) => {
7967
7803
  };
7968
7804
  });
7969
7805
 
7970
- // ../plugin/src/hooks/magic-context/read-session-db.ts
7971
- import { existsSync as existsSync6 } from "node:fs";
7972
- import { join as join7 } from "node:path";
7973
- function getOpenCodeDbPath() {
7974
- return join7(getDataDir(), "opencode", "opencode.db");
7806
+ // ../plugin/src/features/magic-context/storage-db.ts
7807
+ import { copyFileSync, cpSync, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "node:fs";
7808
+ import { dirname as dirname2, join as join4 } from "node:path";
7809
+
7810
+ // ../plugin/src/shared/data-path.ts
7811
+ import * as os from "node:os";
7812
+ import * as path from "node:path";
7813
+
7814
+ // ../plugin/src/shared/harness.ts
7815
+ var currentHarness = "opencode";
7816
+ var harnessLocked = false;
7817
+ function setHarness(value) {
7818
+ if (harnessLocked && currentHarness !== value) {
7819
+ throw new Error(`Magic Context: harness already locked to "${currentHarness}"; cannot change to "${value}"`);
7820
+ }
7821
+ currentHarness = value;
7822
+ harnessLocked = true;
7975
7823
  }
7976
- function openCodeDbExists() {
7977
- return existsSync6(getOpenCodeDbPath());
7824
+ function getHarness() {
7825
+ return currentHarness;
7978
7826
  }
7979
- function closeCachedReadOnlyDb() {
7980
- if (!cachedReadOnlyDb) {
7981
- return;
7982
- }
7983
- try {
7984
- closeQuietly(cachedReadOnlyDb.db);
7985
- } catch (error51) {
7986
- log("[magic-context] failed to close cached OpenCode read-only DB:", error51);
7987
- } finally {
7988
- cachedReadOnlyDb = null;
7989
- }
7827
+
7828
+ // ../plugin/src/shared/data-path.ts
7829
+ function getDataDir() {
7830
+ return process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share");
7990
7831
  }
7991
- function getReadOnlySessionDb() {
7992
- const dbPath = getOpenCodeDbPath();
7993
- if (cachedReadOnlyDb?.path === dbPath) {
7994
- return cachedReadOnlyDb.db;
7995
- }
7996
- closeCachedReadOnlyDb();
7997
- const db = new Database(dbPath, { readonly: true });
7998
- cachedReadOnlyDb = { path: dbPath, db };
7999
- return db;
7832
+ function getMagicContextTempDir(harness = getHarness()) {
7833
+ return path.join(os.tmpdir(), harness, "magic-context");
8000
7834
  }
8001
- function withReadOnlySessionDb(fn) {
8002
- return fn(getReadOnlySessionDb());
7835
+ function getMagicContextLogPath(harness = getHarness()) {
7836
+ return path.join(getMagicContextTempDir(harness), "magic-context.log");
8003
7837
  }
8004
- function getRawSessionMessageCountFromDb(db, sessionId) {
8005
- const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
8006
- AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
8007
- AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
8008
- return typeof row?.count === "number" ? row.count : 0;
7838
+ function getProjectMagicContextDir(directory) {
7839
+ return path.join(directory, ".magic-context");
7840
+ }
7841
+ function getProjectMagicContextHistorianDir(directory) {
7842
+ return path.join(getProjectMagicContextDir(directory), "historian");
7843
+ }
7844
+ function getOpenCodeStorageDir() {
7845
+ return path.join(getDataDir(), "opencode", "storage");
7846
+ }
7847
+ function getMagicContextStorageDir() {
7848
+ return path.join(getDataDir(), "cortexkit", "magic-context");
7849
+ }
7850
+ function getLegacyOpenCodeMagicContextStorageDir() {
7851
+ return path.join(getOpenCodeStorageDir(), "plugin", "magic-context");
8009
7852
  }
8010
- var cachedReadOnlyDb = null;
8011
- var init_read_session_db = __esm(async () => {
8012
- init_data_path();
8013
- init_logger();
8014
- await init_sqlite();
8015
- });
8016
-
8017
- // ../plugin/src/features/magic-context/storage-db.ts
8018
- init_data_path();
8019
- import { copyFileSync, cpSync, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "node:fs";
8020
- import { dirname as dirname2, join as join4 } from "node:path";
8021
7853
 
8022
7854
  // ../plugin/src/shared/error-message.ts
8023
7855
  function getErrorMessage(error) {
@@ -8095,12 +7927,124 @@ function safeString(value) {
8095
7927
  }
8096
7928
  }
8097
7929
 
8098
- // ../plugin/src/features/magic-context/storage-db.ts
8099
- init_logger();
8100
- await init_sqlite();
7930
+ // ../plugin/src/shared/logger.ts
7931
+ import * as fs from "node:fs";
7932
+ import * as path2 from "node:path";
7933
+ var isTestEnv = false;
7934
+ var buffer = [];
7935
+ var flushTimer = null;
7936
+ var FLUSH_INTERVAL_MS = 500;
7937
+ var BUFFER_SIZE_LIMIT = 50;
7938
+ var lastEnsuredDir = null;
7939
+ function ensureDir(filePath) {
7940
+ const dir = path2.dirname(filePath);
7941
+ if (dir === lastEnsuredDir)
7942
+ return;
7943
+ try {
7944
+ fs.mkdirSync(dir, { recursive: true });
7945
+ lastEnsuredDir = dir;
7946
+ } catch {}
7947
+ }
7948
+ function flush() {
7949
+ if (flushTimer) {
7950
+ clearTimeout(flushTimer);
7951
+ flushTimer = null;
7952
+ }
7953
+ if (buffer.length === 0)
7954
+ return;
7955
+ const data = buffer.join("");
7956
+ buffer = [];
7957
+ try {
7958
+ const logFile = getMagicContextLogPath();
7959
+ ensureDir(logFile);
7960
+ fs.appendFileSync(logFile, data);
7961
+ } catch {}
7962
+ }
7963
+ function scheduleFlush() {
7964
+ if (flushTimer)
7965
+ return;
7966
+ flushTimer = setTimeout(() => {
7967
+ flushTimer = null;
7968
+ flush();
7969
+ }, FLUSH_INTERVAL_MS);
7970
+ }
7971
+ function log(message, data) {
7972
+ if (isTestEnv)
7973
+ return;
7974
+ try {
7975
+ const timestamp = new Date().toISOString();
7976
+ const serialized = data === undefined ? "" : data instanceof Error ? ` ${data.message}${data.stack ? `
7977
+ ${data.stack}` : ""}` : ` ${JSON.stringify(data)}`;
7978
+ buffer.push(`[${timestamp}] ${message}${serialized}
7979
+ `);
7980
+ if (buffer.length >= BUFFER_SIZE_LIMIT) {
7981
+ flush();
7982
+ } else {
7983
+ scheduleFlush();
7984
+ }
7985
+ } catch {}
7986
+ }
7987
+ function sessionLog(sessionId, message, data) {
7988
+ log(`[magic-context][${sessionId}] ${message}`, data);
7989
+ }
7990
+ if (!isTestEnv) {
7991
+ process.on("exit", flush);
7992
+ }
7993
+
7994
+ // ../plugin/src/shared/sqlite.ts
7995
+ var isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
7996
+ var bunSpec = "bun:" + "sqlite";
7997
+ var nodeSpec = "node:" + "sqlite";
7998
+ var sqliteModule = isBun ? await import(bunSpec) : await import(nodeSpec);
7999
+ var DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
8000
+ function buildNodeSqliteDatabaseClass(DatabaseSync) {
8001
+ const SAVEPOINT = "mc_tx_sp";
8002
+
8003
+ class NodeSqliteDatabase extends DatabaseSync {
8004
+ constructor(filename, options) {
8005
+ const translated = { ...options };
8006
+ if (options && "readonly" in options) {
8007
+ translated.readOnly = options.readonly;
8008
+ delete translated.readonly;
8009
+ }
8010
+ super(typeof filename === "string" ? filename : ":memory:", translated);
8011
+ }
8012
+ transaction(fn) {
8013
+ const self = this;
8014
+ const wrapped = function(...args) {
8015
+ const nested = self.isTransaction === true;
8016
+ self.exec(nested ? `SAVEPOINT ${SAVEPOINT}` : "BEGIN");
8017
+ try {
8018
+ const result = fn.apply(this, args);
8019
+ self.exec(nested ? `RELEASE ${SAVEPOINT}` : "COMMIT");
8020
+ return result;
8021
+ } catch (error) {
8022
+ if (nested) {
8023
+ self.exec(`ROLLBACK TO ${SAVEPOINT}`);
8024
+ self.exec(`RELEASE ${SAVEPOINT}`);
8025
+ } else {
8026
+ self.exec("ROLLBACK");
8027
+ }
8028
+ throw error;
8029
+ }
8030
+ };
8031
+ return wrapped;
8032
+ }
8033
+ }
8034
+ return NodeSqliteDatabase;
8035
+ }
8036
+ var Database = DatabaseImpl;
8037
+
8038
+ // ../plugin/src/shared/sqlite-helpers.ts
8039
+ function closeQuietly(db) {
8040
+ if (!db)
8041
+ return;
8042
+ try {
8043
+ db.close();
8044
+ } catch {}
8045
+ }
8101
8046
 
8102
8047
  // ../plugin/src/features/magic-context/key-files/project-key-files.ts
8103
- init_logger();
8104
8048
  import { createHash } from "node:crypto";
8105
8049
  import { existsSync, readFileSync, realpathSync } from "node:fs";
8106
8050
  import { join as join2, resolve, sep } from "node:path";
@@ -8217,7 +8161,6 @@ function isRelativeProjectFile(projectPath, relativePath) {
8217
8161
  }
8218
8162
 
8219
8163
  // ../plugin/src/features/magic-context/migrations.ts
8220
- init_logger();
8221
8164
  function tableExists(db, name) {
8222
8165
  return Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?").get(name));
8223
8166
  }
@@ -8919,6 +8862,60 @@ var MIGRATIONS = [
8919
8862
  ON tags(session_id, entry_fingerprint)
8920
8863
  WHERE type='message' AND entry_fingerprint IS NOT NULL`);
8921
8864
  }
8865
+ },
8866
+ {
8867
+ version: 28,
8868
+ description: "Add git commit sweep coordinator lease/cooldown table",
8869
+ up: (db) => {
8870
+ db.exec(`
8871
+ CREATE TABLE IF NOT EXISTS git_sweep_coordinator (
8872
+ project_path TEXT PRIMARY KEY,
8873
+ lease_holder TEXT,
8874
+ lease_expires_at INTEGER,
8875
+ last_swept_at INTEGER
8876
+ );
8877
+ CREATE INDEX IF NOT EXISTS idx_git_sweep_coordinator_lease_expires
8878
+ ON git_sweep_coordinator(lease_expires_at);
8879
+ CREATE INDEX IF NOT EXISTS idx_git_sweep_coordinator_last_swept
8880
+ ON git_sweep_coordinator(last_swept_at);
8881
+ `);
8882
+ }
8883
+ },
8884
+ {
8885
+ version: 29,
8886
+ description: "Add anchor_ordinal to notes (traceback to the conversation tail)",
8887
+ up: (db) => {
8888
+ const notesExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='notes'").get();
8889
+ if (!notesExists) {
8890
+ return;
8891
+ }
8892
+ const columns = db.prepare("PRAGMA table_info(notes)").all();
8893
+ if (!columns.some((column) => column.name === "anchor_ordinal")) {
8894
+ db.exec("ALTER TABLE notes ADD COLUMN anchor_ordinal INTEGER");
8895
+ }
8896
+ }
8897
+ },
8898
+ {
8899
+ version: 30,
8900
+ description: "HARD-bust m[0] markers: cached system/tool-set/model identity",
8901
+ up: (db) => {
8902
+ const hasSessionMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='session_meta' LIMIT 1").get();
8903
+ if (!hasSessionMeta)
8904
+ return;
8905
+ ensureColumn(db, "session_meta", "cached_m0_system_hash", "TEXT");
8906
+ ensureColumn(db, "session_meta", "cached_m0_tool_set_hash", "TEXT");
8907
+ ensureColumn(db, "session_meta", "cached_m0_model_key", "TEXT");
8908
+ const columns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
8909
+ if (columns.has("cached_m0_bytes")) {
8910
+ db.prepare(`UPDATE session_meta SET
8911
+ cached_m0_bytes = NULL,
8912
+ cached_m1_bytes = NULL,
8913
+ cached_m0_materialized_at = NULL,
8914
+ cached_m0_system_hash = NULL,
8915
+ cached_m0_tool_set_hash = NULL,
8916
+ cached_m0_model_key = NULL`).run();
8917
+ }
8918
+ }
8922
8919
  }
8923
8920
  ];
8924
8921
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -141634,8 +141631,6 @@ function loadToolDefinitionMeasurements(db) {
141634
141631
  }
141635
141632
 
141636
141633
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
141637
- init_data_path();
141638
- init_logger();
141639
141634
  import { existsSync as existsSync2 } from "node:fs";
141640
141635
  import { join as join3 } from "node:path";
141641
141636
  var LEASE_DURATION_MS = 5 * 60 * 1000;
@@ -141883,7 +141878,7 @@ var databases = new Map;
141883
141878
  var persistenceByDatabase = new WeakMap;
141884
141879
  var persistenceErrorByDatabase = new WeakMap;
141885
141880
  var lastSchemaFenceRejection = null;
141886
- var LATEST_SUPPORTED_VERSION = 27;
141881
+ var LATEST_SUPPORTED_VERSION = 30;
141887
141882
  function resolveDatabasePath(dbPathOverride) {
141888
141883
  if (dbPathOverride) {
141889
141884
  return { dbDir: dirname2(dbPathOverride), dbPath: dbPathOverride };
@@ -142203,6 +142198,17 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
142203
142198
  updated_at INTEGER NOT NULL DEFAULT 0
142204
142199
  );
142205
142200
 
142201
+ CREATE TABLE IF NOT EXISTS git_sweep_coordinator (
142202
+ project_path TEXT PRIMARY KEY,
142203
+ lease_holder TEXT,
142204
+ lease_expires_at INTEGER,
142205
+ last_swept_at INTEGER
142206
+ );
142207
+ CREATE INDEX IF NOT EXISTS idx_git_sweep_coordinator_lease_expires
142208
+ ON git_sweep_coordinator(lease_expires_at);
142209
+ CREATE INDEX IF NOT EXISTS idx_git_sweep_coordinator_last_swept
142210
+ ON git_sweep_coordinator(last_swept_at);
142211
+
142206
142212
  CREATE TABLE IF NOT EXISTS m0_mutation_log (
142207
142213
  id INTEGER PRIMARY KEY AUTOINCREMENT,
142208
142214
  session_id TEXT NOT NULL,
@@ -142337,6 +142343,9 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
142337
142343
  cached_m0_materialized_at INTEGER,
142338
142344
  cached_m0_session_facts_version INTEGER,
142339
142345
  cached_m0_upgrade_state TEXT,
142346
+ cached_m0_system_hash TEXT,
142347
+ cached_m0_tool_set_hash TEXT,
142348
+ cached_m0_model_key TEXT,
142340
142349
  cached_m0_last_baseline_end_message_id TEXT,
142341
142350
  upgrade_reminded_at INTEGER,
142342
142351
  pi_stable_id_scheme INTEGER
@@ -142528,6 +142537,9 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
142528
142537
  ensureColumn(db, "session_meta", "cached_m0_materialized_at", "INTEGER");
142529
142538
  ensureColumn(db, "session_meta", "cached_m0_session_facts_version", "INTEGER");
142530
142539
  ensureColumn(db, "session_meta", "cached_m0_upgrade_state", "TEXT");
142540
+ ensureColumn(db, "session_meta", "cached_m0_system_hash", "TEXT");
142541
+ ensureColumn(db, "session_meta", "cached_m0_tool_set_hash", "TEXT");
142542
+ ensureColumn(db, "session_meta", "cached_m0_model_key", "TEXT");
142531
142543
  ensureColumn(db, "session_meta", "cached_m0_last_baseline_end_message_id", "TEXT");
142532
142544
  ensureColumn(db, "session_meta", "upgrade_reminded_at", "INTEGER");
142533
142545
  db.exec(`
@@ -142723,9 +142735,6 @@ function openDatabase(dbPathOrOptions) {
142723
142735
  }
142724
142736
  }
142725
142737
 
142726
- // src/subagent-entry.ts
142727
- init_logger();
142728
-
142729
142738
  // src/config/index.ts
142730
142739
  import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
142731
142740
  import { homedir as homedir3 } from "node:os";
@@ -157310,6 +157319,7 @@ var MagicContextConfigSchema = exports_external.object({
157310
157319
  model: DEFAULT_LOCAL_EMBEDDING_MODEL
157311
157320
  }).describe("Embedding provider configuration"),
157312
157321
  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).'),
157322
+ 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."),
157313
157323
  caveman_text_compression: exports_external.object({
157314
157324
  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%)."),
157315
157325
  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.")
@@ -157409,46 +157419,6 @@ function stripJsonComments(content) {
157409
157419
  }
157410
157420
  return result;
157411
157421
  }
157412
- function stripTrailingCommas(content) {
157413
- let result = "";
157414
- let inString = false;
157415
- let escaped = false;
157416
- for (let index = 0;index < content.length; index += 1) {
157417
- const char = content[index];
157418
- if (inString) {
157419
- result += char;
157420
- if (escaped) {
157421
- escaped = false;
157422
- } else if (char === "\\") {
157423
- escaped = true;
157424
- } else if (char === '"') {
157425
- inString = false;
157426
- }
157427
- continue;
157428
- }
157429
- if (char === '"') {
157430
- inString = true;
157431
- result += char;
157432
- continue;
157433
- }
157434
- if (char === ",") {
157435
- let lookahead = index + 1;
157436
- while (lookahead < content.length && /\s/.test(content[lookahead] ?? "")) {
157437
- lookahead += 1;
157438
- }
157439
- const next = content[lookahead];
157440
- if (next === "}" || next === "]") {
157441
- continue;
157442
- }
157443
- }
157444
- result += char;
157445
- }
157446
- return result;
157447
- }
157448
- function parseJsonc(content) {
157449
- const normalized = stripTrailingCommas(stripJsonComments(content));
157450
- return JSON.parse(normalized);
157451
- }
157452
157422
 
157453
157423
  // ../plugin/src/config/variable.ts
157454
157424
  var ENV_PATTERN = /\{env:([^}]+)\}/g;
@@ -157763,9 +157733,6 @@ function loadPiConfigDetailed(opts = {}) {
157763
157733
  };
157764
157734
  }
157765
157735
 
157766
- // ../plugin/src/features/magic-context/memory/embedding.ts
157767
- init_logger();
157768
-
157769
157736
  // ../plugin/src/features/magic-context/memory/cosine-similarity.ts
157770
157737
  function cosineSimilarity(a, b) {
157771
157738
  if (a.length !== b.length) {
@@ -157821,8 +157788,6 @@ import { mkdirSync as mkdirSync3 } from "node:fs";
157821
157788
  import { open, stat, unlink, writeFile } from "node:fs/promises";
157822
157789
  import { dirname as dirname4, join as join6 } from "node:path";
157823
157790
  import { pathToFileURL } from "node:url";
157824
- init_data_path();
157825
- init_logger();
157826
157791
  var LOCK_POLL_MS = 150;
157827
157792
  var STALE_LOCK_MS = 3 * 60000;
157828
157793
  var MAX_LOCK_WAIT_MS = 5 * 60000;
@@ -158158,7 +158123,6 @@ class LocalEmbeddingProvider {
158158
158123
  }
158159
158124
 
158160
158125
  // ../plugin/src/features/magic-context/memory/embedding-openai.ts
158161
- init_logger();
158162
158126
  function normalizeEndpoint2(endpoint) {
158163
158127
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
158164
158128
  }
@@ -158448,8 +158412,7 @@ function getDistinctStoredModelIds(db, projectPath) {
158448
158412
  }
158449
158413
 
158450
158414
  // ../plugin/src/features/magic-context/project-embedding-registry.ts
158451
- import { createHash as createHash3 } from "node:crypto";
158452
- init_logger();
158415
+ import { createHash as createHash3, randomUUID } from "node:crypto";
158453
158416
 
158454
158417
  // ../plugin/src/features/magic-context/git-commits/storage-git-commit-embeddings.ts
158455
158418
  var saveStatements = new WeakMap;
@@ -158552,6 +158515,125 @@ function getDistinctCommitEmbeddingModelIds(db, projectPath) {
158552
158515
  return new Set(rows.map((row) => typeof row.modelId === "string" ? row.modelId : null));
158553
158516
  }
158554
158517
 
158518
+ // ../plugin/src/features/magic-context/git-commits/sweep-coordinator.ts
158519
+ var GIT_SWEEP_COOLDOWN_MS = 10 * 60 * 1000;
158520
+ var GIT_SWEEP_LEASE_TTL_MS = 5 * 60 * 1000;
158521
+ var GIT_SWEEP_LEASE_RENEWAL_MS = 60 * 1000;
158522
+ function runImmediate(db, body) {
158523
+ db.exec("BEGIN IMMEDIATE");
158524
+ let committed = false;
158525
+ try {
158526
+ const result = body();
158527
+ db.exec("COMMIT");
158528
+ committed = true;
158529
+ return result;
158530
+ } finally {
158531
+ if (!committed) {
158532
+ try {
158533
+ db.exec("ROLLBACK");
158534
+ } catch {}
158535
+ }
158536
+ }
158537
+ }
158538
+ function rowToState(row) {
158539
+ return {
158540
+ projectPath: row.project_path,
158541
+ leaseHolder: row.lease_holder,
158542
+ leaseExpiresAt: row.lease_expires_at,
158543
+ lastSweptAt: row.last_swept_at
158544
+ };
158545
+ }
158546
+ function getGitSweepCoordinatorState(db, projectPath) {
158547
+ const row = db.prepare(`SELECT project_path, lease_holder, lease_expires_at, last_swept_at
158548
+ FROM git_sweep_coordinator
158549
+ WHERE project_path = ?`).get(projectPath);
158550
+ return row ? rowToState(row) : null;
158551
+ }
158552
+ function acquireGitSweepLease(db, projectPath, holderId, options = {}) {
158553
+ const cooldownMs = options.cooldownMs ?? GIT_SWEEP_COOLDOWN_MS;
158554
+ const leaseTtlMs = options.leaseTtlMs ?? GIT_SWEEP_LEASE_TTL_MS;
158555
+ return runImmediate(db, () => {
158556
+ const now = Date.now();
158557
+ const row = getGitSweepCoordinatorState(db, projectPath);
158558
+ if (row?.leaseHolder && row.leaseExpiresAt !== null && row.leaseExpiresAt > now) {
158559
+ return {
158560
+ acquired: false,
158561
+ projectPath,
158562
+ reason: "lease_active",
158563
+ leaseHolder: row.leaseHolder,
158564
+ leaseExpiresAt: row.leaseExpiresAt,
158565
+ lastSweptAt: row.lastSweptAt,
158566
+ nextAllowedAt: null
158567
+ };
158568
+ }
158569
+ if (!options.ignoreCooldown && row?.lastSweptAt !== null && row?.lastSweptAt !== undefined) {
158570
+ const nextAllowedAt = row.lastSweptAt + cooldownMs;
158571
+ if (nextAllowedAt > now) {
158572
+ return {
158573
+ acquired: false,
158574
+ projectPath,
158575
+ reason: "cooldown_active",
158576
+ leaseHolder: row.leaseHolder,
158577
+ leaseExpiresAt: row.leaseExpiresAt,
158578
+ lastSweptAt: row.lastSweptAt,
158579
+ nextAllowedAt
158580
+ };
158581
+ }
158582
+ }
158583
+ const leaseExpiresAt = now + leaseTtlMs;
158584
+ db.prepare(`INSERT INTO git_sweep_coordinator (
158585
+ project_path,
158586
+ lease_holder,
158587
+ lease_expires_at,
158588
+ last_swept_at
158589
+ ) VALUES (?, ?, ?, NULL)
158590
+ ON CONFLICT(project_path) DO UPDATE SET
158591
+ lease_holder = excluded.lease_holder,
158592
+ lease_expires_at = excluded.lease_expires_at`).run(projectPath, holderId, leaseExpiresAt);
158593
+ return {
158594
+ acquired: true,
158595
+ projectPath,
158596
+ holderId,
158597
+ acquiredAt: now,
158598
+ leaseExpiresAt
158599
+ };
158600
+ });
158601
+ }
158602
+ function renewGitSweepLease(db, projectPath, holderId, leaseTtlMs = GIT_SWEEP_LEASE_TTL_MS) {
158603
+ return runImmediate(db, () => {
158604
+ const now = Date.now();
158605
+ const leaseExpiresAt = now + leaseTtlMs;
158606
+ const result = db.prepare(`UPDATE git_sweep_coordinator
158607
+ SET lease_expires_at = ?
158608
+ WHERE project_path = ?
158609
+ AND lease_holder = ?
158610
+ AND lease_expires_at > ?`).run(leaseExpiresAt, projectPath, holderId, now);
158611
+ return result.changes === 1;
158612
+ });
158613
+ }
158614
+ function markGitSweepSuccessAndRelease(db, projectPath, holderId) {
158615
+ return runImmediate(db, () => {
158616
+ const now = Date.now();
158617
+ const result = db.prepare(`UPDATE git_sweep_coordinator
158618
+ SET lease_holder = NULL,
158619
+ lease_expires_at = NULL,
158620
+ last_swept_at = ?
158621
+ WHERE project_path = ?
158622
+ AND lease_holder = ?
158623
+ AND lease_expires_at > ?`).run(now, projectPath, holderId, now);
158624
+ return result.changes === 1;
158625
+ });
158626
+ }
158627
+ function releaseGitSweepLease(db, projectPath, holderId) {
158628
+ runImmediate(db, () => {
158629
+ db.prepare(`UPDATE git_sweep_coordinator
158630
+ SET lease_holder = NULL,
158631
+ lease_expires_at = NULL
158632
+ WHERE project_path = ?
158633
+ AND lease_holder = ?`).run(projectPath, holderId);
158634
+ });
158635
+ }
158636
+
158555
158637
  // ../plugin/src/features/magic-context/memory/embedding-cache.ts
158556
158638
  var DEFAULT_EMBEDDING_CACHE_TTL_MS = 60000;
158557
158639
  var projectEmbeddingCache = new Map;
@@ -159068,7 +159150,6 @@ function hasGitDir(canonical) {
159068
159150
 
159069
159151
  // ../plugin/src/plugin/embedding-bootstrap-helpers.ts
159070
159152
  import { createHash as createHash5 } from "node:crypto";
159071
- init_logger();
159072
159153
  var EMBEDDING_AFFECTING_KEYS = new Set([
159073
159154
  "embedding.api_key",
159074
159155
  "embedding.endpoint",
@@ -159156,6 +159237,7 @@ async function ensureProjectRegisteredFromPiDirectory(directory, db) {
159156
159237
  };
159157
159238
  registerProjectEmbeddingAndMaybeWipe(db, projectIdentity, detailed.config.embedding, features, directory);
159158
159239
  }
159240
+
159159
159241
  // ../plugin/src/features/magic-context/compartment-lease.ts
159160
159242
  var COMPARTMENT_LEASE_TTL_MS = 5 * 60 * 1000;
159161
159243
  var COMPARTMENT_LEASE_RENEWAL_MS = 60 * 1000;
@@ -159249,6 +159331,9 @@ var SESSION_META_SELECT_COLUMNS = [
159249
159331
  "cached_m0_materialized_at",
159250
159332
  "cached_m0_session_facts_version",
159251
159333
  "cached_m0_upgrade_state",
159334
+ "cached_m0_system_hash",
159335
+ "cached_m0_tool_set_hash",
159336
+ "cached_m0_model_key",
159252
159337
  "last_observed_model_key",
159253
159338
  "upgrade_reminded_at",
159254
159339
  "pi_stable_id_scheme"
@@ -159285,6 +159370,9 @@ var META_COLUMNS = {
159285
159370
  cachedM0MaterializedAt: "cached_m0_materialized_at",
159286
159371
  cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
159287
159372
  cachedM0UpgradeState: "cached_m0_upgrade_state",
159373
+ cachedM0SystemHash: "cached_m0_system_hash",
159374
+ cachedM0ToolSetHash: "cached_m0_tool_set_hash",
159375
+ cachedM0ModelKey: "cached_m0_model_key",
159288
159376
  lastObservedModelKey: "last_observed_model_key",
159289
159377
  upgradeRemindedAt: "upgrade_reminded_at",
159290
159378
  piStableIdScheme: "pi_stable_id_scheme"
@@ -159327,7 +159415,7 @@ function isSessionMetaRow(row) {
159327
159415
  if (row === null || typeof row !== "object")
159328
159416
  return false;
159329
159417
  const r = row;
159330
- 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);
159418
+ 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);
159331
159419
  }
159332
159420
  function getDefaultSessionMeta(sessionId) {
159333
159421
  return {
@@ -159363,6 +159451,9 @@ function getDefaultSessionMeta(sessionId) {
159363
159451
  cachedM0MaterializedAt: null,
159364
159452
  cachedM0SessionFactsVersion: null,
159365
159453
  cachedM0UpgradeState: null,
159454
+ cachedM0SystemHash: null,
159455
+ cachedM0ToolSetHash: null,
159456
+ cachedM0ModelKey: null,
159366
159457
  lastObservedModelKey: null,
159367
159458
  upgradeRemindedAt: null,
159368
159459
  piStableIdScheme: null
@@ -159414,6 +159505,9 @@ function toSessionMeta(row) {
159414
159505
  cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
159415
159506
  cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
159416
159507
  cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
159508
+ cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
159509
+ cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
159510
+ cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
159417
159511
  lastObservedModelKey: stringOrNull(row.last_observed_model_key),
159418
159512
  upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
159419
159513
  piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
@@ -159433,8 +159527,11 @@ function persistCachedM0(db, sessionId, payload) {
159433
159527
  cached_m0_project_docs_hash = ?,
159434
159528
  cached_m0_materialized_at = ?,
159435
159529
  cached_m0_session_facts_version = ?,
159436
- cached_m0_upgrade_state = ?
159437
- 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);
159530
+ cached_m0_upgrade_state = ?,
159531
+ cached_m0_system_hash = ?,
159532
+ cached_m0_tool_set_hash = ?,
159533
+ cached_m0_model_key = ?
159534
+ 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);
159438
159535
  }
159439
159536
  function clearCachedM0M1(db, sessionId) {
159440
159537
  ensureSessionMetaRow(db, sessionId);
@@ -159452,6 +159549,9 @@ function clearCachedM0M1(db, sessionId) {
159452
159549
  ["cached_m0_materialized_at", null],
159453
159550
  ["cached_m0_session_facts_version", null],
159454
159551
  ["cached_m0_upgrade_state", null],
159552
+ ["cached_m0_system_hash", null],
159553
+ ["cached_m0_tool_set_hash", null],
159554
+ ["cached_m0_model_key", null],
159455
159555
  ["cached_m0_last_baseline_end_message_id", null],
159456
159556
  ["memory_block_cache", ""],
159457
159557
  ["memory_block_count", 0],
@@ -159658,8 +159758,47 @@ function escapeXmlContent(s) {
159658
159758
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
159659
159759
  }
159660
159760
 
159661
- // ../plugin/src/hooks/magic-context/read-session-chunk.ts
159662
- await init_read_session_db();
159761
+ // ../plugin/src/hooks/magic-context/read-session-db.ts
159762
+ import { existsSync as existsSync6 } from "node:fs";
159763
+ import { join as join7 } from "node:path";
159764
+ function getOpenCodeDbPath() {
159765
+ return join7(getDataDir(), "opencode", "opencode.db");
159766
+ }
159767
+ function openCodeDbExists() {
159768
+ return existsSync6(getOpenCodeDbPath());
159769
+ }
159770
+ var cachedReadOnlyDb = null;
159771
+ function closeCachedReadOnlyDb() {
159772
+ if (!cachedReadOnlyDb) {
159773
+ return;
159774
+ }
159775
+ try {
159776
+ closeQuietly(cachedReadOnlyDb.db);
159777
+ } catch (error51) {
159778
+ log("[magic-context] failed to close cached OpenCode read-only DB:", error51);
159779
+ } finally {
159780
+ cachedReadOnlyDb = null;
159781
+ }
159782
+ }
159783
+ function getReadOnlySessionDb() {
159784
+ const dbPath = getOpenCodeDbPath();
159785
+ if (cachedReadOnlyDb?.path === dbPath) {
159786
+ return cachedReadOnlyDb.db;
159787
+ }
159788
+ closeCachedReadOnlyDb();
159789
+ const db = new Database(dbPath, { readonly: true });
159790
+ cachedReadOnlyDb = { path: dbPath, db };
159791
+ return db;
159792
+ }
159793
+ function withReadOnlySessionDb(fn) {
159794
+ return fn(getReadOnlySessionDb());
159795
+ }
159796
+ function getRawSessionMessageCountFromDb(db, sessionId) {
159797
+ const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
159798
+ AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
159799
+ AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
159800
+ return typeof row?.count === "number" ? row.count : 0;
159801
+ }
159663
159802
 
159664
159803
  // ../plugin/src/hooks/magic-context/read-session-raw.ts
159665
159804
  function isRawMessageRow(row) {
@@ -159723,14 +159862,48 @@ function readRawSessionMessagesFromDb(db, sessionId) {
159723
159862
  var encoder = new TextEncoder;
159724
159863
  var TAG_PREFIX_REGEX = /^(?:§\d+§\s*)+/;
159725
159864
  var MALFORMED_TAG_PREFIX_REGEX = /^(?:§\d+">§(?:\d+§)?\s*)+/;
159865
+ var COMPLETE_TAG_PAIR_GLOBAL_REGEX = /\u00a7\d+\u00a7/g;
159866
+ var MALFORMED_TAG_GLOBAL_REGEX = /\u00a7\d+">(?:\u00a7(?:\d+\u00a7)?)?/g;
159867
+ var STRAY_SECTION_CHAR_REGEX = /\u00a7/g;
159868
+ function stripWellFormedLeadingTagPrefix(value) {
159869
+ return value.replace(/^(\u00a7\d+\u00a7\s*)+/, "");
159870
+ }
159871
+ function stripCompleteTagPairsGlobally(value) {
159872
+ return value.replace(COMPLETE_TAG_PAIR_GLOBAL_REGEX, "");
159873
+ }
159874
+ function stripMalformedTagNotationGlobally(value) {
159875
+ return value.replace(MALFORMED_TAG_GLOBAL_REGEX, "");
159876
+ }
159877
+ function stripTagSectionCharacters(value) {
159878
+ return value.replace(STRAY_SECTION_CHAR_REGEX, "");
159879
+ }
159880
+ function stripPersistedAssistantText(value) {
159881
+ let text = stripWellFormedLeadingTagPrefix(value);
159882
+ text = stripCompleteTagPairsGlobally(text);
159883
+ text = stripMalformedTagNotationGlobally(text);
159884
+ text = stripTagSectionCharacters(text);
159885
+ return text.trim();
159886
+ }
159726
159887
  function byteSize(value) {
159727
159888
  return encoder.encode(value).length;
159728
159889
  }
159729
159890
  function stripTagPrefix(value) {
159730
- let stripped = value.replace(MALFORMED_TAG_PREFIX_REGEX, "");
159731
- stripped = stripped.replace(TAG_PREFIX_REGEX, "");
159891
+ let stripped = value;
159892
+ for (let pass = 0;pass < 8; pass++) {
159893
+ const prev = stripped;
159894
+ stripped = stripped.replace(MALFORMED_TAG_PREFIX_REGEX, "");
159895
+ stripped = stripped.replace(TAG_PREFIX_REGEX, "");
159896
+ if (stripped === prev)
159897
+ break;
159898
+ }
159732
159899
  return stripped;
159733
159900
  }
159901
+ function peelLeadingMcTagNotation(value) {
159902
+ const body = stripTagPrefix(value);
159903
+ if (body === value)
159904
+ return { tagPrefix: "", body };
159905
+ return { tagPrefix: value.slice(0, value.length - body.length), body };
159906
+ }
159734
159907
  function prependTag(tagId, value) {
159735
159908
  const stripped = stripTagPrefix(value);
159736
159909
  return `§${tagId}§ ${stripped}`;
@@ -159772,7 +159945,9 @@ function hasMeaningfulPart(part) {
159772
159945
  return false;
159773
159946
  const type = part.type;
159774
159947
  if (type === "text") {
159775
- return typeof part.text === "string" && part.text.trim().length > 0;
159948
+ if (typeof part.text !== "string")
159949
+ return false;
159950
+ return stripTagPrefix(part.text).trim().length > 0;
159776
159951
  }
159777
159952
  if (typeof type !== "string")
159778
159953
  return false;
@@ -164518,7 +164693,6 @@ var CATEGORY_DEFAULT_TTL = {
164518
164693
  KNOWN_ISSUES: 30 * 24 * 60 * 60 * 1000
164519
164694
  };
164520
164695
  // ../plugin/src/features/magic-context/memory/embedding-backfill.ts
164521
- init_logger();
164522
164696
  async function ensureMemoryEmbeddings(args) {
164523
164697
  const snapshot = getProjectEmbeddingSnapshot(args.projectIdentity);
164524
164698
  if (!snapshot?.enabled) {
@@ -164556,9 +164730,6 @@ async function ensureMemoryEmbeddings(args) {
164556
164730
  }
164557
164731
  return args.existingEmbeddings;
164558
164732
  }
164559
- // ../plugin/src/features/magic-context/memory/promotion.ts
164560
- init_logger();
164561
-
164562
164733
  // ../plugin/src/features/magic-context/memory/storage-memory.ts
164563
164734
  var COLUMN_MAP = {
164564
164735
  id: "id",
@@ -165458,7 +165629,6 @@ function getMaxMemoryMutationId(db, projectPath) {
165458
165629
  return row?.max_id ?? null;
165459
165630
  }
165460
165631
  // ../plugin/src/features/magic-context/storage-meta-persisted.ts
165461
- init_logger();
165462
165632
  var CAS_RETRY_LIMIT = 5;
165463
165633
  var AUTO_SEARCH_NO_HINT_REASONS = new Set([
165464
165634
  "below-threshold",
@@ -165921,8 +166091,6 @@ function setSessionWorkMetrics(db, sessionId, newWorkTokens, totalInputTokens) {
165921
166091
  import { Buffer as Buffer3 } from "node:buffer";
165922
166092
 
165923
166093
  // ../plugin/src/features/magic-context/resolve-subagent-fallback.ts
165924
- init_logger();
165925
- await init_read_session_db();
165926
166094
  function resolveIsSubagentFromOpenCodeDb(sessionId) {
165927
166095
  try {
165928
166096
  return withReadOnlySessionDb((openCodeDb) => {
@@ -165956,6 +166124,9 @@ var SESSION_META_FALLBACK_SELECTS = {
165956
166124
  cached_m0_materialized_at: "NULL AS cached_m0_materialized_at",
165957
166125
  cached_m0_session_facts_version: "NULL AS cached_m0_session_facts_version",
165958
166126
  cached_m0_upgrade_state: "NULL AS cached_m0_upgrade_state",
166127
+ cached_m0_system_hash: "NULL AS cached_m0_system_hash",
166128
+ cached_m0_tool_set_hash: "NULL AS cached_m0_tool_set_hash",
166129
+ cached_m0_model_key: "NULL AS cached_m0_model_key",
165959
166130
  last_observed_model_key: "NULL AS last_observed_model_key",
165960
166131
  upgrade_reminded_at: "NULL AS upgrade_reminded_at"
165961
166132
  };
@@ -166047,7 +166218,8 @@ function toNote(row) {
166047
166218
  updatedAt: row.updated_at,
166048
166219
  lastCheckedAt: toNullableNumber(row.last_checked_at),
166049
166220
  readyAt: toNullableNumber(row.ready_at),
166050
- readyReason: toNullableString(row.ready_reason)
166221
+ readyReason: toNullableString(row.ready_reason),
166222
+ anchorOrdinal: toNullableNumber(row.anchor_ordinal)
166051
166223
  };
166052
166224
  }
166053
166225
  function getNoteById(db, noteId) {
@@ -166099,7 +166271,7 @@ function getNotes(db, options3 = {}) {
166099
166271
  }
166100
166272
  function addNote(db, type, options3) {
166101
166273
  const now = Date.now();
166102
- const result = type === "session" ? db.prepare("INSERT INTO notes (type, status, content, session_id, created_at, updated_at, harness) VALUES ('session', 'active', ?, ?, ?, ?, ?) RETURNING *").get(options3.content, options3.sessionId, now, now, getHarness()) : db.prepare("INSERT INTO notes (type, status, content, session_id, project_path, surface_condition, created_at, updated_at, harness) VALUES ('smart', 'pending', ?, ?, ?, ?, ?, ?, ?) RETURNING *").get(options3.content, options3.sessionId ?? null, options3.projectPath, options3.surfaceCondition, now, now, getHarness());
166274
+ const result = type === "session" ? db.prepare("INSERT INTO notes (type, status, content, session_id, created_at, updated_at, harness, anchor_ordinal) VALUES ('session', 'active', ?, ?, ?, ?, ?, ?) RETURNING *").get(options3.content, options3.sessionId, now, now, getHarness(), options3.anchorOrdinal ?? null) : db.prepare("INSERT INTO notes (type, status, content, session_id, project_path, surface_condition, created_at, updated_at, harness, anchor_ordinal) VALUES ('smart', 'pending', ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *").get(options3.content, options3.sessionId ?? null, options3.projectPath, options3.surfaceCondition, now, now, getHarness(), options3.anchorOrdinal ?? null);
166103
166275
  if (!isNoteRow(result)) {
166104
166276
  throw new Error("[notes] failed to insert note");
166105
166277
  }
@@ -166187,7 +166359,6 @@ function markNoteChecked(db, noteId) {
166187
166359
  db.prepare("UPDATE notes SET last_checked_at = ?, updated_at = ? WHERE id = ? AND type = 'smart'").run(now, now, noteId);
166188
166360
  }
166189
166361
  // ../plugin/src/features/magic-context/storage-ops.ts
166190
- init_logger();
166191
166362
  var queuePendingOpStatements = new WeakMap;
166192
166363
  var getPendingOpsStatements = new WeakMap;
166193
166364
  var clearPendingOpsStatements = new WeakMap;
@@ -166589,7 +166760,6 @@ var ERROR_CLASSES = new Set([
166589
166760
  "unknown"
166590
166761
  ]);
166591
166762
  // src/tools/ctx-memory.ts
166592
- init_logger();
166593
166763
  var DEFAULT_LIST_LIMIT = 10;
166594
166764
  var VALID_CATEGORIES = new Set(CATEGORY_PRIORITY);
166595
166765
  function isMemoryCategory2(value) {
@@ -166953,15 +167123,26 @@ function err3(text) {
166953
167123
  isError: true
166954
167124
  };
166955
167125
  }
167126
+ function captureAnchorOrdinal(db, sessionId) {
167127
+ try {
167128
+ const ordinal = getLastIndexedOrdinal(db, sessionId);
167129
+ return ordinal > 0 ? ordinal : null;
167130
+ } catch {
167131
+ return null;
167132
+ }
167133
+ }
167134
+ function anchorSuffix(note) {
167135
+ return note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
167136
+ }
166956
167137
  function formatNoteLine(note) {
166957
167138
  if (note.type === "smart") {
166958
167139
  const conditionLine = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
166959
167140
  const statusSuffix2 = note.status === "active" ? "" : ` (${note.status})`;
166960
- return `- **#${note.id}**${statusSuffix2}: ${note.content}
167141
+ return `- **#${note.id}**${statusSuffix2}: ${note.content}${anchorSuffix(note)}
166961
167142
  *Condition*: ${conditionLine}`;
166962
167143
  }
166963
167144
  const statusSuffix = note.status === "active" ? "" : ` (${note.status})`;
166964
- return `- **#${note.id}**${statusSuffix}: ${note.content}`;
167145
+ return `- **#${note.id}**${statusSuffix}: ${note.content}${anchorSuffix(note)}`;
166965
167146
  }
166966
167147
  var DISMISS_FOOTER = `
166967
167148
 
@@ -166983,6 +167164,7 @@ function createCtxNoteTool(deps) {
166983
167164
  const content = params.content?.trim();
166984
167165
  if (!content)
166985
167166
  return err3("Error: 'content' is required when action is 'write'.");
167167
+ const anchorOrdinal = captureAnchorOrdinal(deps.db, sessionId);
166986
167168
  const surfaceCondition = params.surface_condition?.trim();
166987
167169
  if (surfaceCondition) {
166988
167170
  if (deps.dreamerEnabled !== true) {
@@ -166995,13 +167177,18 @@ function createCtxNoteTool(deps) {
166995
167177
  const note2 = addNote(deps.db, "smart", {
166996
167178
  content,
166997
167179
  projectPath: projectIdentity,
166998
- surfaceCondition
167180
+ surfaceCondition,
167181
+ anchorOrdinal
166999
167182
  });
167000
167183
  return ok3(`Created smart note #${note2.id}. Dreamer will evaluate the condition during nightly runs:
167001
167184
  - Content: ${content}
167002
167185
  - Condition: ${surfaceCondition}`);
167003
167186
  }
167004
- const note = addNote(deps.db, "session", { sessionId, content });
167187
+ const note = addNote(deps.db, "session", {
167188
+ sessionId,
167189
+ content,
167190
+ anchorOrdinal
167191
+ });
167005
167192
  return ok3(`Saved session note #${note.id}.`);
167006
167193
  }
167007
167194
  if (action2 === "dismiss") {
@@ -167064,9 +167251,13 @@ function createCtxNoteTool(deps) {
167064
167251
 
167065
167252
  No notes for the current filter.`);
167066
167253
  }
167067
- return ok3(`${sections.join(`
167254
+ const body = sections.join(`
167068
167255
 
167069
- `)}${DISMISS_FOOTER}`);
167256
+ `);
167257
+ const anchorHint = body.includes("↳ @msg ") ? `
167258
+
167259
+ ↳ @msg N marks the conversation tail when a note was written. To see what led to it: ctx_expand(start=N-x, end=N) (pick x for how far back to look).` : "";
167260
+ return ok3(`${body}${anchorHint}${DISMISS_FOOTER}`);
167070
167261
  }
167071
167262
  };
167072
167263
  }
@@ -167285,11 +167476,7 @@ function createCtxReduceTool(deps) {
167285
167476
  };
167286
167477
  }
167287
167478
 
167288
- // ../plugin/src/features/magic-context/search.ts
167289
- init_logger();
167290
-
167291
167479
  // ../plugin/src/features/magic-context/git-commits/git-log-reader.ts
167292
- init_logger();
167293
167480
  import { execFile } from "node:child_process";
167294
167481
  import { promisify } from "node:util";
167295
167482
  var execFileAsync = promisify(execFile);
@@ -167302,6 +167489,7 @@ async function readGitCommits(directory, options3 = {}) {
167302
167489
  if (revision.startsWith("-")) {
167303
167490
  throw new Error(`readGitCommits: refusing revision that looks like an option: "${revision}"`);
167304
167491
  }
167492
+ const projectLabel = options3.projectIdentity ?? "<project>";
167305
167493
  const args = [
167306
167494
  "log",
167307
167495
  revision,
@@ -167324,11 +167512,11 @@ async function readGitCommits(directory, options3 = {}) {
167324
167512
  stdout = result.stdout;
167325
167513
  } catch (error51) {
167326
167514
  const message = error51 instanceof Error ? error51.message : String(error51);
167327
- log(`[git-commits] readGitCommits failed at cwd=${directory}: ${message.slice(0, 500)}`);
167515
+ log(`[git-commits] readGitCommits failed for ${projectLabel}: ${message.slice(0, 500)}`);
167328
167516
  return [];
167329
167517
  }
167330
167518
  if (stdout.trim().length === 0) {
167331
- log(`[git-commits] readGitCommits returned empty stdout at cwd=${directory} (sinceMs=${options3.sinceMs ?? "none"} args=${args.slice(0, 4).join(" ")})`);
167519
+ log(`[git-commits] readGitCommits returned empty stdout for ${projectLabel} (sinceMs=${options3.sinceMs ?? "none"} args=${args.slice(0, 4).join(" ")})`);
167332
167520
  }
167333
167521
  return parseGitLogOutput(stdout);
167334
167522
  }
@@ -167372,15 +167560,12 @@ ${body}` : subject;
167372
167560
  }
167373
167561
  return commits;
167374
167562
  }
167375
- // ../plugin/src/features/magic-context/git-commits/indexer.ts
167376
- init_logger();
167377
-
167378
167563
  // ../plugin/src/features/magic-context/git-commits/storage-git-commits.ts
167379
- init_logger();
167380
167564
  var insertStatements = new WeakMap;
167381
167565
  var existingShasStatements = new WeakMap;
167382
167566
  var projectCountStatements = new WeakMap;
167383
167567
  var evictStatements = new WeakMap;
167568
+ var evictOverflowStatements = new WeakMap;
167384
167569
  var latestCommitTimeStatements = new WeakMap;
167385
167570
  function getInsertStatement(db) {
167386
167571
  let stmt = insertStatements.get(db);
@@ -167423,17 +167608,17 @@ function getLatestCommitTimeStatement(db) {
167423
167608
  }
167424
167609
  return stmt;
167425
167610
  }
167426
- function getEvictStatement(db) {
167427
- let stmt = evictStatements.get(db);
167611
+ function getEvictOverflowStatement(db) {
167612
+ let stmt = evictOverflowStatements.get(db);
167428
167613
  if (!stmt) {
167429
167614
  stmt = db.prepare(`DELETE FROM git_commits
167430
- WHERE sha IN (
167431
- SELECT sha FROM git_commits
167615
+ WHERE rowid IN (
167616
+ SELECT rowid FROM git_commits
167432
167617
  WHERE project_path = ?
167433
- ORDER BY committed_at ASC
167434
- LIMIT ?
167618
+ ORDER BY committed_at DESC, sha DESC
167619
+ LIMIT -1 OFFSET ?
167435
167620
  )`);
167436
- evictStatements.set(db, stmt);
167621
+ evictOverflowStatements.set(db, stmt);
167437
167622
  }
167438
167623
  return stmt;
167439
167624
  }
@@ -167471,22 +167656,15 @@ function getLatestIndexedCommitTimeMs(db, projectPath) {
167471
167656
  const row = getLatestCommitTimeStatement(db).get(projectPath);
167472
167657
  return row?.latest ?? null;
167473
167658
  }
167474
- function evictOldestCommits(db, projectPath, excess) {
167475
- if (excess <= 0)
167476
- return 0;
167477
- const before = getCommitCount(db, projectPath);
167478
- getEvictStatement(db).run(projectPath, excess);
167479
- const after = getCommitCount(db, projectPath);
167480
- return Math.max(0, before - after);
167481
- }
167482
167659
  function enforceProjectCap(db, projectPath, maxCommits) {
167483
167660
  if (maxCommits <= 0)
167484
167661
  return 0;
167485
167662
  const count = getCommitCount(db, projectPath);
167486
167663
  if (count <= maxCommits)
167487
167664
  return 0;
167488
- const excess = count - maxCommits;
167489
- const evicted = evictOldestCommits(db, projectPath, excess);
167665
+ getEvictOverflowStatement(db).run(projectPath, maxCommits);
167666
+ const after = getCommitCount(db, projectPath);
167667
+ const evicted = Math.max(0, count - after);
167490
167668
  if (evicted > 0) {
167491
167669
  log(`[git-commits] evicted ${evicted} oldest commits for project ${projectPath} (cap=${maxCommits}, was=${count})`);
167492
167670
  }
@@ -167518,7 +167696,8 @@ async function indexCommitsForProject(db, projectPath, directory, options3) {
167518
167696
  const sinceMs = latestIndexed !== null ? Math.max(latestIndexed - 60000, Date.now() - options3.sinceDays * MS_PER_DAY) : Date.now() - options3.sinceDays * MS_PER_DAY;
167519
167697
  const commits = await readGitCommits(directory, {
167520
167698
  sinceMs,
167521
- maxCommits: options3.maxCommits
167699
+ maxCommits: options3.maxCommits,
167700
+ projectIdentity: projectPath
167522
167701
  });
167523
167702
  result.scanned = commits.length;
167524
167703
  if (commits.length === 0) {
@@ -167594,7 +167773,6 @@ async function embedUnembeddedCommits(db, projectPath) {
167594
167773
  }
167595
167774
  }
167596
167775
  // ../plugin/src/features/magic-context/git-commits/search-git-commits.ts
167597
- init_logger();
167598
167776
  var ftsStatements = new WeakMap;
167599
167777
  var ftsPlainStatements = new WeakMap;
167600
167778
  var getBySHAStatements = new WeakMap;
@@ -167725,6 +167903,62 @@ function searchGitCommitsSync(db, projectPath, query, options3) {
167725
167903
  });
167726
167904
  return results.slice(0, options3.limit);
167727
167905
  }
167906
+ // ../plugin/src/features/magic-context/literal-probes.ts
167907
+ var MAX_PROBES = 5;
167908
+ var MIN_PROBE_LENGTH = 3;
167909
+ var SLASH_COMMAND_RE = /\/[a-z][a-z0-9]*(?:-[a-z0-9]+)+/gi;
167910
+ var KEBAB_SNAKE_RE = /[a-z][a-z0-9]*(?:[-_][a-z0-9]+)+/gi;
167911
+ var DOTTED_RE = /[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9_-]+)+/gi;
167912
+ var CAMEL_RE = /\b[a-zA-Z][a-z0-9]*(?:[A-Z][a-z0-9]*)+\b/g;
167913
+ var SHA_RE = /\b[0-9a-f]{7,40}\b/gi;
167914
+ var ERROR_CODE_RE = /\b(?:TS\d{4,}|ERR_[A-Z][A-Z0-9_]*)\b/g;
167915
+ var QUOTED_RE = /["`]([^"`]{3,80})["`]/g;
167916
+ function looksLikeSha(token) {
167917
+ return /[0-9]/.test(token) && /^[0-9a-f]{7,40}$/i.test(token);
167918
+ }
167919
+ function extractLiteralProbes(query) {
167920
+ const trimmed = query.trim();
167921
+ if (trimmed.length === 0)
167922
+ return [];
167923
+ const ordered = [];
167924
+ const seen = new Set;
167925
+ const add = (raw) => {
167926
+ if (!raw)
167927
+ return;
167928
+ const probe = raw.trim();
167929
+ if (probe.length < MIN_PROBE_LENGTH)
167930
+ return;
167931
+ const key = probe.toLowerCase();
167932
+ if (seen.has(key))
167933
+ return;
167934
+ seen.add(key);
167935
+ ordered.push(probe);
167936
+ };
167937
+ for (const m of trimmed.matchAll(QUOTED_RE))
167938
+ add(m[1]);
167939
+ for (const m of trimmed.matchAll(SLASH_COMMAND_RE))
167940
+ add(m[0]);
167941
+ for (const m of trimmed.matchAll(ERROR_CODE_RE))
167942
+ add(m[0]);
167943
+ for (const m of trimmed.matchAll(DOTTED_RE))
167944
+ add(m[0]);
167945
+ for (const m of trimmed.matchAll(KEBAB_SNAKE_RE))
167946
+ add(m[0]);
167947
+ for (const m of trimmed.matchAll(CAMEL_RE))
167948
+ add(m[0]);
167949
+ for (const m of trimmed.matchAll(SHA_RE)) {
167950
+ if (looksLikeSha(m[0]))
167951
+ add(m[0]);
167952
+ }
167953
+ return ordered.slice(0, MAX_PROBES);
167954
+ }
167955
+ function containsProbeVerbatim(text, probes) {
167956
+ if (probes.length === 0)
167957
+ return false;
167958
+ const haystack = text.toLowerCase();
167959
+ return probes.some((probe) => haystack.includes(probe.toLowerCase()));
167960
+ }
167961
+
167728
167962
  // ../plugin/src/features/magic-context/search.ts
167729
167963
  var DEFAULT_UNIFIED_SEARCH_LIMIT = 10;
167730
167964
  var FTS_SEMANTIC_CANDIDATE_LIMIT = 50;
@@ -167902,36 +168136,82 @@ function linearDecayScore(rank, total) {
167902
168136
  return 0;
167903
168137
  return Math.max(0, 1 - rank / total);
167904
168138
  }
167905
- function searchMessages(args) {
167906
- const sanitizedQuery = sanitizeFtsQuery(args.query.trim());
167907
- if (sanitizedQuery.length === 0) {
168139
+ function runMessageFtsQuery(db, sessionId, ftsQuery, fetchLimit, cutoff) {
168140
+ if (ftsQuery.length === 0)
167908
168141
  return [];
167909
- }
167910
- const fetchLimit = args.maxOrdinal != null && args.maxOrdinal >= 0 ? args.limit * 3 : args.limit;
167911
- const rows = getMessageSearchStatement(args.db).all(args.sessionId, sanitizedQuery, fetchLimit).map((row) => row);
167912
- const cutoff = args.maxOrdinal != null && args.maxOrdinal >= 0 ? args.maxOrdinal : null;
167913
- const filtered = rows.map((row) => {
168142
+ const rows = getMessageSearchStatement(db).all(sessionId, ftsQuery, fetchLimit).map((row) => row);
168143
+ const result = [];
168144
+ for (const row of rows) {
167914
168145
  const messageOrdinal = getMessageOrdinal(row.messageOrdinal);
167915
168146
  if (messageOrdinal === null || typeof row.messageId !== "string" || typeof row.role !== "string" || typeof row.content !== "string") {
167916
- return null;
168147
+ continue;
167917
168148
  }
167918
168149
  if (cutoff !== null && messageOrdinal > cutoff) {
167919
- return null;
168150
+ continue;
167920
168151
  }
167921
- return {
168152
+ result.push({
167922
168153
  messageOrdinal,
167923
168154
  messageId: row.messageId,
167924
168155
  role: row.role,
167925
168156
  content: row.content
167926
- };
167927
- }).filter((result) => result !== null).slice(0, args.limit);
167928
- return filtered.map((row, rank) => ({
168157
+ });
168158
+ }
168159
+ return result;
168160
+ }
168161
+ var RRF_K = 60;
168162
+ var VERBATIM_PROBE_BONUS = 0.5;
168163
+ function searchMessages(args) {
168164
+ const cutoff = args.maxOrdinal != null && args.maxOrdinal >= 0 ? args.maxOrdinal : null;
168165
+ const fetchLimit = args.maxOrdinal != null && args.maxOrdinal >= 0 ? args.limit * 3 : args.limit;
168166
+ const baseQuery = sanitizeFtsQuery(args.query.trim());
168167
+ const probes = args.probes ?? [];
168168
+ if (probes.length === 0) {
168169
+ const filtered = runMessageFtsQuery(args.db, args.sessionId, baseQuery, fetchLimit, cutoff).slice(0, args.limit);
168170
+ return filtered.map((row, rank) => ({
168171
+ source: "message",
168172
+ content: previewText(row.content),
168173
+ score: linearDecayScore(rank, filtered.length),
168174
+ messageOrdinal: row.messageOrdinal,
168175
+ messageId: row.messageId,
168176
+ role: row.role
168177
+ }));
168178
+ }
168179
+ const queryLists = [];
168180
+ if (baseQuery.length > 0) {
168181
+ queryLists.push(runMessageFtsQuery(args.db, args.sessionId, baseQuery, fetchLimit, cutoff));
168182
+ }
168183
+ for (const probe of probes) {
168184
+ const probeQuery = sanitizeFtsQuery(probe);
168185
+ if (probeQuery.length === 0)
168186
+ continue;
168187
+ queryLists.push(runMessageFtsQuery(args.db, args.sessionId, probeQuery, fetchLimit, cutoff));
168188
+ }
168189
+ const fused = new Map;
168190
+ for (const list of queryLists) {
168191
+ list.forEach((row, rank) => {
168192
+ const rrf = 1 / (RRF_K + rank);
168193
+ const existing = fused.get(row.messageId);
168194
+ if (existing) {
168195
+ existing.score += rrf;
168196
+ } else {
168197
+ fused.set(row.messageId, { row, score: rrf });
168198
+ }
168199
+ });
168200
+ }
168201
+ for (const entry of fused.values()) {
168202
+ if (containsProbeVerbatim(entry.row.content, probes)) {
168203
+ entry.score += VERBATIM_PROBE_BONUS;
168204
+ }
168205
+ }
168206
+ const ranked = [...fused.values()].sort((a, b) => b.score !== a.score ? b.score - a.score : a.row.messageOrdinal - b.row.messageOrdinal).slice(0, args.limit);
168207
+ const maxScore = ranked.length > 0 ? ranked[0].score : 1;
168208
+ return ranked.map((entry) => ({
167929
168209
  source: "message",
167930
- content: previewText(row.content),
167931
- score: linearDecayScore(rank, filtered.length),
167932
- messageOrdinal: row.messageOrdinal,
167933
- messageId: row.messageId,
167934
- role: row.role
168210
+ content: previewText(entry.row.content),
168211
+ score: maxScore > 0 ? entry.score / maxScore : 0,
168212
+ messageOrdinal: entry.row.messageOrdinal,
168213
+ messageId: entry.row.messageId,
168214
+ role: entry.row.role
167935
168215
  }));
167936
168216
  }
167937
168217
  function getSourceBoost(result) {
@@ -168015,12 +168295,14 @@ async function unifiedSearch(db, sessionId, projectPath, query, options3 = {}) {
168015
168295
  return null;
168016
168296
  }) : Promise.resolve(null);
168017
168297
  await Promise.resolve();
168298
+ const messageProbes = options3.explicitSearch ? extractLiteralProbes(trimmedQuery) : [];
168018
168299
  const messageResults = runMessages ? searchMessages({
168019
168300
  db,
168020
168301
  sessionId,
168021
168302
  query: trimmedQuery,
168022
168303
  limit: tierLimit,
168023
- maxOrdinal: options3.maxMessageOrdinal
168304
+ maxOrdinal: options3.maxMessageOrdinal,
168305
+ probes: messageProbes
168024
168306
  }) : [];
168025
168307
  const queryEmbedding = await queryEmbeddingPromise;
168026
168308
  const [memoryResults, gitCommitResults] = await Promise.all([
@@ -168161,9 +168443,6 @@ class BoundedSessionMap {
168161
168443
  }
168162
168444
  }
168163
168445
 
168164
- // ../plugin/src/hooks/magic-context/inject-compartments.ts
168165
- init_logger();
168166
-
168167
168446
  // ../plugin/src/hooks/magic-context/decay-curve.ts
168168
168447
  var H50 = 24;
168169
168448
  var D = 25;
@@ -168338,26 +168617,58 @@ import { join as join9, sep as sep2 } from "node:path";
168338
168617
  var import_comment_json2 = __toESM(require_src2(), 1);
168339
168618
  import { existsSync as existsSync7, readFileSync as readFileSync5 } from "node:fs";
168340
168619
  import { homedir as homedir4 } from "node:os";
168341
- import { join as join8 } from "node:path";
168620
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "node:path";
168621
+ import { fileURLToPath } from "node:url";
168342
168622
  var overrideAvailability = null;
168343
168623
  function parseConfig(path5) {
168344
168624
  if (!existsSync7(path5))
168345
168625
  return null;
168346
168626
  return import_comment_json2.parse(readFileSync5(path5, "utf-8"));
168347
168627
  }
168348
- function entryMatchesAft(entry) {
168628
+ var AFT_NAME_NEEDLES = ["@cortexkit/aft", "aft-opencode", "aft-pi"];
168629
+ function stringMentionsAft(value) {
168630
+ return AFT_NAME_NEEDLES.some((needle) => value.includes(needle));
168631
+ }
168632
+ function resolveLocalEntryPackageName(value, configDir) {
168633
+ let dir = null;
168634
+ if (value.startsWith("file://")) {
168635
+ try {
168636
+ dir = fileURLToPath(value);
168637
+ } catch {
168638
+ return null;
168639
+ }
168640
+ } else if (value.startsWith("~/")) {
168641
+ dir = join8(homedir4(), value.slice(2));
168642
+ } else if (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) {
168643
+ dir = isAbsolute2(value) ? value : resolve3(configDir, value);
168644
+ } else {
168645
+ return null;
168646
+ }
168647
+ try {
168648
+ const pkg = JSON.parse(readFileSync5(join8(dir, "package.json"), "utf-8"));
168649
+ return typeof pkg.name === "string" ? pkg.name : null;
168650
+ } catch {
168651
+ return null;
168652
+ }
168653
+ }
168654
+ function entryMatchesAft(entry, configDir) {
168349
168655
  const value = Array.isArray(entry) ? entry[0] : entry;
168350
- return typeof value === "string" && (value.includes("@cortexkit/aft") || value.includes("aft-opencode") || value.includes("aft-pi"));
168656
+ if (typeof value !== "string")
168657
+ return false;
168658
+ if (stringMentionsAft(value))
168659
+ return true;
168660
+ const name2 = resolveLocalEntryPackageName(value, configDir);
168661
+ return name2 != null && stringMentionsAft(name2);
168351
168662
  }
168352
- function hasAftInArray(value) {
168353
- return Array.isArray(value) && value.some(entryMatchesAft);
168663
+ function hasAftInArray(value, configDir) {
168664
+ return Array.isArray(value) && value.some((entry) => entryMatchesAft(entry, configDir));
168354
168665
  }
168355
- function hasAftAtKeys(value, keys2) {
168666
+ function hasAftAtKeys(value, keys2, configDir) {
168356
168667
  if (!value || typeof value !== "object")
168357
168668
  return false;
168358
168669
  const record4 = value;
168359
168670
  for (const key of keys2) {
168360
- if (hasAftInArray(record4[key]))
168671
+ if (hasAftInArray(record4[key], configDir))
168361
168672
  return true;
168362
168673
  }
168363
168674
  return false;
@@ -168374,7 +168685,8 @@ function getAftAvailability() {
168374
168685
  for (const path5 of opencodePaths) {
168375
168686
  try {
168376
168687
  const config2 = parseConfig(path5);
168377
- if (hasAftAtKeys(config2, ["plugin", "plugins", "mcp", "mcp_servers"])) {
168688
+ const configDir = join8(path5, "..");
168689
+ if (hasAftAtKeys(config2, ["plugin", "plugins", "mcp", "mcp_servers"], configDir)) {
168378
168690
  opencode = true;
168379
168691
  break;
168380
168692
  }
@@ -168384,12 +168696,13 @@ function getAftAvailability() {
168384
168696
  for (const path5 of piPaths) {
168385
168697
  try {
168386
168698
  const config2 = parseConfig(path5);
168387
- if (hasAftAtKeys(config2, ["packages", "extensions"])) {
168699
+ const configDir = join8(path5, "..");
168700
+ if (hasAftAtKeys(config2, ["packages", "extensions"], configDir)) {
168388
168701
  pi = true;
168389
168702
  break;
168390
168703
  }
168391
168704
  const agent = config2?.agent;
168392
- if (hasAftAtKeys(agent, ["packages", "extensions"])) {
168705
+ if (hasAftAtKeys(agent, ["packages", "extensions"], configDir)) {
168393
168706
  pi = true;
168394
168707
  break;
168395
168708
  }
@@ -168408,7 +168721,6 @@ function isAftAvailable() {
168408
168721
  }
168409
168722
 
168410
168723
  // ../plugin/src/hooks/magic-context/key-files-block.ts
168411
- init_logger();
168412
168724
  var cachedKeyFilesBySession = new Map;
168413
168725
  var staleUpdates = new Map;
168414
168726
  function staleKey(update2) {
@@ -168506,9 +168818,6 @@ ${blocks.join(`
168506
168818
  return rendered;
168507
168819
  }
168508
168820
 
168509
- // ../plugin/src/hooks/magic-context/inject-compartments.ts
168510
- await init_read_session_db();
168511
-
168512
168821
  // ../plugin/src/hooks/magic-context/temporal-awareness.ts
168513
168822
  var TEMPORAL_AWARENESS_THRESHOLD_SECONDS = 300;
168514
168823
  var SECONDS_PER_MINUTE = 60;
@@ -168791,7 +169100,8 @@ function createCtxSearchTool(deps) {
168791
169100
  maxMessageOrdinal: lastCompartmentEnd >= 0 ? lastCompartmentEnd : undefined,
168792
169101
  gitCommitsEnabled,
168793
169102
  sources: params.sources,
168794
- visibleMemoryIds
169103
+ visibleMemoryIds,
169104
+ explicitSearch: true
168795
169105
  });
168796
169106
  return {
168797
169107
  content: [{ type: "text", text: formatSearchResults(query, results) }],