@cortexkit/pi-magic-context 0.33.0 → 0.33.1
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-f3jfb2ed.js → index-e3kftg52.js} +682 -94
- package/dist/index.js +92 -544
- package/dist/subagent-entry.js +1 -1
- package/package.json +2 -2
|
@@ -8757,30 +8757,11 @@ function buildNodeSqliteDatabaseClass(DatabaseSync) {
|
|
|
8757
8757
|
}
|
|
8758
8758
|
var Database = DatabaseImpl;
|
|
8759
8759
|
var privilegeDepth = new WeakMap;
|
|
8760
|
-
var registeredPrivilegeFunctions = new WeakSet;
|
|
8761
|
-
var privilegeUdfAvailable = new WeakSet;
|
|
8762
|
-
function registerPrivilegedWriter(db) {
|
|
8763
|
-
if (registeredPrivilegeFunctions.has(db))
|
|
8764
|
-
return;
|
|
8765
|
-
const native = db;
|
|
8766
|
-
const implementation = () => (privilegeDepth.get(db) ?? 0) > 0 ? 1 : 0;
|
|
8767
|
-
if (typeof native.function === "function") {
|
|
8768
|
-
native.function("mc_privileged_writer", implementation);
|
|
8769
|
-
} else if (typeof native.createFunction === "function") {
|
|
8770
|
-
native.createFunction("mc_privileged_writer", implementation);
|
|
8771
|
-
} else {
|
|
8772
|
-
registeredPrivilegeFunctions.add(db);
|
|
8773
|
-
return;
|
|
8774
|
-
}
|
|
8775
|
-
privilegeUdfAvailable.add(db);
|
|
8776
|
-
registeredPrivilegeFunctions.add(db);
|
|
8777
|
-
}
|
|
8778
8760
|
function isInTransaction(db) {
|
|
8779
8761
|
const candidate = db;
|
|
8780
8762
|
return candidate.inTransaction === true || candidate.isTransaction === true;
|
|
8781
8763
|
}
|
|
8782
8764
|
function withPrivilegedWriter(db, operation) {
|
|
8783
|
-
registerPrivilegedWriter(db);
|
|
8784
8765
|
const previousDepth = privilegeDepth.get(db) ?? 0;
|
|
8785
8766
|
const nested = isInTransaction(db);
|
|
8786
8767
|
const savepoint = "mc_privilege_scope";
|
|
@@ -8791,11 +8772,9 @@ function withPrivilegedWriter(db, operation) {
|
|
|
8791
8772
|
}
|
|
8792
8773
|
privilegeDepth.set(db, previousDepth + 1);
|
|
8793
8774
|
try {
|
|
8794
|
-
|
|
8795
|
-
db.prepare("INSERT INTO context_privilege_state(id, enabled) VALUES (1, 1) ON CONFLICT(id) DO UPDATE SET enabled = 1").run();
|
|
8796
|
-
}
|
|
8775
|
+
db.prepare("INSERT INTO context_privilege_state(id, enabled) VALUES (1, 1) ON CONFLICT(id) DO UPDATE SET enabled = 1").run();
|
|
8797
8776
|
const result = operation();
|
|
8798
|
-
if (
|
|
8777
|
+
if (previousDepth === 0) {
|
|
8799
8778
|
db.prepare("UPDATE context_privilege_state SET enabled = 0 WHERE id = 1").run();
|
|
8800
8779
|
}
|
|
8801
8780
|
if (nested) {
|
|
@@ -8860,6 +8839,184 @@ function ensureContextStoreUuid(db) {
|
|
|
8860
8839
|
var MAX_AUTHORITY_SEED_FRAME_BYTES = 900 * 1024;
|
|
8861
8840
|
var mirrorFlights = new WeakMap;
|
|
8862
8841
|
|
|
8842
|
+
// ../plugin/src/hooks/magic-context/compartment-parser.ts
|
|
8843
|
+
var COMPARTMENT_REGEX = /<compartment\s+([^>]*?)\s*>(.*?)<\/compartment>/gs;
|
|
8844
|
+
var ATTR_START_REGEX = /\bstart="(\d+)"/;
|
|
8845
|
+
var ATTR_END_REGEX = /\bend="(\d+)"/;
|
|
8846
|
+
var ATTR_TITLE_REGEX = /\btitle="([^"]*)"/;
|
|
8847
|
+
var ATTR_EPISODE_REGEX = /\bepisode_type="([^"]*)"/;
|
|
8848
|
+
var ATTR_IMPORTANCE_REGEX = /\bimportance="(\d+)"/;
|
|
8849
|
+
function makeTierOpenRegex(n) {
|
|
8850
|
+
return new RegExp(`<p${n}\\s*(/?)>`);
|
|
8851
|
+
}
|
|
8852
|
+
var TIER_OPEN_REGEXES = [
|
|
8853
|
+
makeTierOpenRegex(1),
|
|
8854
|
+
makeTierOpenRegex(2),
|
|
8855
|
+
makeTierOpenRegex(3),
|
|
8856
|
+
makeTierOpenRegex(4)
|
|
8857
|
+
];
|
|
8858
|
+
var TIER_CLOSE_ANY_REGEX = /<\/p\d/;
|
|
8859
|
+
var TIER_OPEN_ANY_REGEX = /<p\d/;
|
|
8860
|
+
var CATEGORY_BLOCK_REGEX = /<(PROJECT_RULES|ARCHITECTURE|CONSTRAINTS|CONFIG_VALUES|NAMING)>(.*?)<\/\1>/gs;
|
|
8861
|
+
var FACT_ITEM_REGEX = /^\s*\*\s*(.+)$/gm;
|
|
8862
|
+
var UNPROCESSED_REGEX = /<unprocessed_from>(\d+)<\/unprocessed_from>/;
|
|
8863
|
+
var USER_OBSERVATIONS_REGEX = /<user_observations>(.*?)<\/user_observations>/s;
|
|
8864
|
+
var USER_OBS_ITEM_REGEX = /^\s*\*\s*(.+)$/gm;
|
|
8865
|
+
var PRIMER_CANDIDATES_REGEX = /<primer_candidates>(.*?)<\/primer_candidates>/s;
|
|
8866
|
+
var PRIMER_ELEMENT_REGEX = /<primer\s+at_compartment="(\d+)"\s*>(.*?)<\/primer>/gs;
|
|
8867
|
+
var PRIMER_ITEM_REGEX = /^\s*(?:\*|-|\d+\.)\s*(.+)$/gm;
|
|
8868
|
+
var FACTS_BLOCK_REGEX = /<facts>(.*?)<\/facts>/s;
|
|
8869
|
+
var EVENTS_BLOCK_REGEX = /<events>(.*?)<\/events>/s;
|
|
8870
|
+
var EVENT_ELEMENT_REGEX = /<([a-z_]+)\s+at_compartment="(\d+)"\s*>(.*?)<\/\1>/gs;
|
|
8871
|
+
var EVENT_FIELD_REGEX = /<([a-z_]+)\s*>(.*?)<\/\1>/gs;
|
|
8872
|
+
function extractTier(inner, index) {
|
|
8873
|
+
const openMatch = TIER_OPEN_REGEXES[index].exec(inner);
|
|
8874
|
+
if (!openMatch)
|
|
8875
|
+
return;
|
|
8876
|
+
if (openMatch[1] === "/")
|
|
8877
|
+
return "";
|
|
8878
|
+
const rest = inner.slice(openMatch.index + openMatch[0].length);
|
|
8879
|
+
const closeAt = rest.search(TIER_CLOSE_ANY_REGEX);
|
|
8880
|
+
let body = closeAt === -1 ? rest : rest.slice(0, closeAt);
|
|
8881
|
+
const openInside = body.search(TIER_OPEN_ANY_REGEX);
|
|
8882
|
+
if (openInside !== -1)
|
|
8883
|
+
body = body.slice(0, openInside);
|
|
8884
|
+
return unescapeXml(body.trim());
|
|
8885
|
+
}
|
|
8886
|
+
function extractTiersFromInner(inner) {
|
|
8887
|
+
return {
|
|
8888
|
+
p1: extractTier(inner, 0),
|
|
8889
|
+
p2: extractTier(inner, 1),
|
|
8890
|
+
p3: extractTier(inner, 2),
|
|
8891
|
+
p4: extractTier(inner, 3)
|
|
8892
|
+
};
|
|
8893
|
+
}
|
|
8894
|
+
function parseCompartmentOutput(text) {
|
|
8895
|
+
const compartments = [];
|
|
8896
|
+
const facts = [];
|
|
8897
|
+
for (const match of text.matchAll(COMPARTMENT_REGEX)) {
|
|
8898
|
+
const attrs = match[1];
|
|
8899
|
+
const inner = match[2];
|
|
8900
|
+
const startMatch = attrs.match(ATTR_START_REGEX);
|
|
8901
|
+
const endMatch = attrs.match(ATTR_END_REGEX);
|
|
8902
|
+
const titleMatch = attrs.match(ATTR_TITLE_REGEX);
|
|
8903
|
+
if (!startMatch || !endMatch || !titleMatch)
|
|
8904
|
+
continue;
|
|
8905
|
+
const startMessage = parseInt(startMatch[1], 10);
|
|
8906
|
+
const endMessage = parseInt(endMatch[1], 10);
|
|
8907
|
+
const title = unescapeXml(titleMatch[1]);
|
|
8908
|
+
if (Number.isNaN(startMessage) || Number.isNaN(endMessage) || !title)
|
|
8909
|
+
continue;
|
|
8910
|
+
const episodeMatch = attrs.match(ATTR_EPISODE_REGEX);
|
|
8911
|
+
const importanceMatch = attrs.match(ATTR_IMPORTANCE_REGEX);
|
|
8912
|
+
const episodeType = episodeMatch ? unescapeXml(episodeMatch[1]) : undefined;
|
|
8913
|
+
const importance = importanceMatch ? parseInt(importanceMatch[1], 10) : undefined;
|
|
8914
|
+
const p1 = extractTier(inner, 0);
|
|
8915
|
+
if (typeof p1 === "string" && p1.length > 0) {
|
|
8916
|
+
const p2 = extractTier(inner, 1);
|
|
8917
|
+
const p3 = extractTier(inner, 2);
|
|
8918
|
+
const p4 = extractTier(inner, 3);
|
|
8919
|
+
compartments.push({
|
|
8920
|
+
startMessage,
|
|
8921
|
+
endMessage,
|
|
8922
|
+
title,
|
|
8923
|
+
content: p1,
|
|
8924
|
+
p1,
|
|
8925
|
+
p2: typeof p2 === "string" ? p2 : p1,
|
|
8926
|
+
p3: typeof p3 === "string" ? p3 : typeof p2 === "string" ? p2 : p1,
|
|
8927
|
+
p4: typeof p4 === "string" ? p4 : "",
|
|
8928
|
+
importance,
|
|
8929
|
+
episodeType
|
|
8930
|
+
});
|
|
8931
|
+
continue;
|
|
8932
|
+
}
|
|
8933
|
+
const content = unescapeXml(inner.trim());
|
|
8934
|
+
if (content) {
|
|
8935
|
+
compartments.push({
|
|
8936
|
+
startMessage,
|
|
8937
|
+
endMessage,
|
|
8938
|
+
title,
|
|
8939
|
+
content,
|
|
8940
|
+
importance,
|
|
8941
|
+
episodeType
|
|
8942
|
+
});
|
|
8943
|
+
}
|
|
8944
|
+
}
|
|
8945
|
+
const factsBlockMatch = text.match(FACTS_BLOCK_REGEX);
|
|
8946
|
+
const factsScope = factsBlockMatch ? factsBlockMatch[1] : text.replace(EVENTS_BLOCK_REGEX, "").replace(/<compartment\s+[^>]*?\s*>.*?<\/compartment>/gs, "");
|
|
8947
|
+
for (const categoryMatch of factsScope.matchAll(CATEGORY_BLOCK_REGEX)) {
|
|
8948
|
+
const category = categoryMatch[1];
|
|
8949
|
+
const blockContent = categoryMatch[2];
|
|
8950
|
+
for (const itemMatch of blockContent.matchAll(FACT_ITEM_REGEX)) {
|
|
8951
|
+
const content = unescapeXml(itemMatch[1].trim());
|
|
8952
|
+
if (content) {
|
|
8953
|
+
facts.push({ category, content });
|
|
8954
|
+
}
|
|
8955
|
+
}
|
|
8956
|
+
}
|
|
8957
|
+
const unprocessedMatch = text.match(UNPROCESSED_REGEX);
|
|
8958
|
+
const unprocessedFrom = unprocessedMatch ? parseInt(unprocessedMatch[1], 10) : null;
|
|
8959
|
+
const userObservations = [];
|
|
8960
|
+
const userObsMatch = text.match(USER_OBSERVATIONS_REGEX);
|
|
8961
|
+
if (userObsMatch) {
|
|
8962
|
+
for (const itemMatch of userObsMatch[1].matchAll(USER_OBS_ITEM_REGEX)) {
|
|
8963
|
+
const obs = unescapeXml(itemMatch[1].trim());
|
|
8964
|
+
if (obs)
|
|
8965
|
+
userObservations.push(obs);
|
|
8966
|
+
}
|
|
8967
|
+
}
|
|
8968
|
+
const primerCandidates = [];
|
|
8969
|
+
const primerMatch = text.match(PRIMER_CANDIDATES_REGEX);
|
|
8970
|
+
if (primerMatch) {
|
|
8971
|
+
const block = primerMatch[1];
|
|
8972
|
+
let sawElement = false;
|
|
8973
|
+
for (const el of block.matchAll(PRIMER_ELEMENT_REGEX)) {
|
|
8974
|
+
sawElement = true;
|
|
8975
|
+
const question = unescapeXml(el[2].trim());
|
|
8976
|
+
if (question) {
|
|
8977
|
+
primerCandidates.push({
|
|
8978
|
+
question,
|
|
8979
|
+
originCompartmentIndex: Number.parseInt(el[1], 10)
|
|
8980
|
+
});
|
|
8981
|
+
}
|
|
8982
|
+
}
|
|
8983
|
+
if (!sawElement) {
|
|
8984
|
+
for (const itemMatch of block.matchAll(PRIMER_ITEM_REGEX)) {
|
|
8985
|
+
const question = unescapeXml(itemMatch[1].trim());
|
|
8986
|
+
if (question)
|
|
8987
|
+
primerCandidates.push({ question });
|
|
8988
|
+
}
|
|
8989
|
+
}
|
|
8990
|
+
}
|
|
8991
|
+
const events = parseEvents(text);
|
|
8992
|
+
compartments.sort((a, b) => a.startMessage - b.startMessage);
|
|
8993
|
+
return { compartments, facts, events, unprocessedFrom, userObservations, primerCandidates };
|
|
8994
|
+
}
|
|
8995
|
+
function parseEvents(text) {
|
|
8996
|
+
const blockMatch = text.match(EVENTS_BLOCK_REGEX);
|
|
8997
|
+
if (!blockMatch)
|
|
8998
|
+
return [];
|
|
8999
|
+
const block = blockMatch[1];
|
|
9000
|
+
const events = [];
|
|
9001
|
+
for (const elMatch of block.matchAll(EVENT_ELEMENT_REGEX)) {
|
|
9002
|
+
const kind = elMatch[1];
|
|
9003
|
+
const atRaw = parseInt(elMatch[2], 10);
|
|
9004
|
+
const atCompartment = Number.isNaN(atRaw) ? null : atRaw;
|
|
9005
|
+
const fields = {};
|
|
9006
|
+
for (const fieldMatch of elMatch[3].matchAll(EVENT_FIELD_REGEX)) {
|
|
9007
|
+
const name = fieldMatch[1];
|
|
9008
|
+
const value = unescapeXml(fieldMatch[2].trim());
|
|
9009
|
+
if (value)
|
|
9010
|
+
fields[name] = value;
|
|
9011
|
+
}
|
|
9012
|
+
events.push({ kind, atCompartment, fields });
|
|
9013
|
+
}
|
|
9014
|
+
return events;
|
|
9015
|
+
}
|
|
9016
|
+
function unescapeXml(s) {
|
|
9017
|
+
return s.replace(/&/g, "&").replace(/'/g, "'").replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">");
|
|
9018
|
+
}
|
|
9019
|
+
|
|
8863
9020
|
// ../plugin/src/features/magic-context/storage-schema-helpers.ts
|
|
8864
9021
|
function ensureColumn(db, table, column, definition) {
|
|
8865
9022
|
if (!/^[a-z][a-z0-9_]*$/.test(table) || !/^[a-z][a-z0-9_]*$/.test(column) || !/^[A-Z0-9_"'(),[\]\s]+$/i.test(definition)) {
|
|
@@ -9285,15 +9442,38 @@ function isSqliteLockError(error) {
|
|
|
9285
9442
|
function tableExists2(db, name) {
|
|
9286
9443
|
return Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?").get(name));
|
|
9287
9444
|
}
|
|
9445
|
+
function healMismatchedTierClose(db, table, hasLegacy) {
|
|
9446
|
+
if (!tableExists2(db, table))
|
|
9447
|
+
return;
|
|
9448
|
+
const columns = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((row) => row.name));
|
|
9449
|
+
for (const required of ["content", "p1", "p2", "p3", "p4"]) {
|
|
9450
|
+
if (!columns.has(required))
|
|
9451
|
+
return;
|
|
9452
|
+
}
|
|
9453
|
+
if (hasLegacy && !columns.has("legacy"))
|
|
9454
|
+
return;
|
|
9455
|
+
const predicate = hasLegacy ? "legacy = 1 AND p1 IS NULL AND content LIKE '%<p1%'" : "p1 IS NULL AND content LIKE '%<p1%'";
|
|
9456
|
+
const rows = db.prepare(`SELECT id, content FROM ${table} WHERE ${predicate}`).all();
|
|
9457
|
+
const update = db.prepare(`UPDATE ${table} SET p1 = ?, p2 = ?, p3 = ?, p4 = ?${hasLegacy ? ", legacy = 0" : ""} WHERE id = ?`);
|
|
9458
|
+
for (const row of rows) {
|
|
9459
|
+
const tiers = extractTiersFromInner(row.content);
|
|
9460
|
+
if (typeof tiers.p1 !== "string" || tiers.p1.length === 0)
|
|
9461
|
+
continue;
|
|
9462
|
+
const p1 = tiers.p1;
|
|
9463
|
+
const p2 = typeof tiers.p2 === "string" ? tiers.p2 : p1;
|
|
9464
|
+
const p3 = typeof tiers.p3 === "string" ? tiers.p3 : p2;
|
|
9465
|
+
const p4 = typeof tiers.p4 === "string" ? tiers.p4 : "";
|
|
9466
|
+
update.run(p1, p2, p3, p4, row.id);
|
|
9467
|
+
}
|
|
9468
|
+
}
|
|
9288
9469
|
function assertForeignKeyIntegrity(db, table) {
|
|
9289
9470
|
const rows = (table ? db.prepare(`PRAGMA foreign_key_check(${table})`) : db.prepare("PRAGMA foreign_key_check")).all();
|
|
9290
9471
|
if (rows.length > 0) {
|
|
9291
9472
|
throw new Error(`foreign_key_check failed after embedding table rebuild${table ? ` (${table})` : ""} (${rows.length} violation(s))`);
|
|
9292
9473
|
}
|
|
9293
9474
|
}
|
|
9294
|
-
function authorityPrivilegeCheck(
|
|
9295
|
-
|
|
9296
|
-
return typeof native.function === "function" || typeof native.createFunction === "function" ? "mc_privileged_writer() = 0" : "COALESCE((SELECT enabled FROM context_privilege_state WHERE id = 1), 0) = 0";
|
|
9475
|
+
function authorityPrivilegeCheck() {
|
|
9476
|
+
return "COALESCE((SELECT enabled FROM context_privilege_state WHERE id = 1), 0) = 0";
|
|
9297
9477
|
}
|
|
9298
9478
|
function managedAuthorityNoteRow(row) {
|
|
9299
9479
|
return `(
|
|
@@ -9312,7 +9492,7 @@ function managedAuthorityNoteRow(row) {
|
|
|
9312
9492
|
)`;
|
|
9313
9493
|
}
|
|
9314
9494
|
function installLatestAuthorityTriggers(db) {
|
|
9315
|
-
const privilegeCheck = authorityPrivilegeCheck(
|
|
9495
|
+
const privilegeCheck = authorityPrivilegeCheck();
|
|
9316
9496
|
if (tableExists2(db, "memories")) {
|
|
9317
9497
|
db.exec(`
|
|
9318
9498
|
DROP TRIGGER IF EXISTS memories_authority_guard_insert;
|
|
@@ -11238,6 +11418,21 @@ var MIGRATIONS = [
|
|
|
11238
11418
|
ON memory_mutation_log(project_path, target_memory_id, id);
|
|
11239
11419
|
`);
|
|
11240
11420
|
}
|
|
11421
|
+
},
|
|
11422
|
+
{
|
|
11423
|
+
version: 70,
|
|
11424
|
+
description: "heal legacy compartments stranded by mismatched tier closing tags (issue #246)",
|
|
11425
|
+
up(db) {
|
|
11426
|
+
healMismatchedTierClose(db, "compartments", true);
|
|
11427
|
+
healMismatchedTierClose(db, "recomp_compartments", false);
|
|
11428
|
+
}
|
|
11429
|
+
},
|
|
11430
|
+
{
|
|
11431
|
+
version: 71,
|
|
11432
|
+
description: "rebuild authority guard triggers to the durable state-table form (issue #253)",
|
|
11433
|
+
up(db) {
|
|
11434
|
+
installLatestAuthorityTriggers(db);
|
|
11435
|
+
}
|
|
11241
11436
|
}
|
|
11242
11437
|
];
|
|
11243
11438
|
var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
|
|
@@ -144266,7 +144461,7 @@ var lastSchemaFenceRejection = null;
|
|
|
144266
144461
|
function getSchemaFenceRejection() {
|
|
144267
144462
|
return lastSchemaFenceRejection;
|
|
144268
144463
|
}
|
|
144269
|
-
var LATEST_SUPPORTED_VERSION =
|
|
144464
|
+
var LATEST_SUPPORTED_VERSION = 71;
|
|
144270
144465
|
var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
|
|
144271
144466
|
function ensureSecureStorageDir(dir) {
|
|
144272
144467
|
mkdirSync2(dir, { recursive: true, mode: 448 });
|
|
@@ -145531,7 +145726,6 @@ function openDatabase(dbPathOrOptions) {
|
|
|
145531
145726
|
if (!enforceSchemaFence(existing, dbPath, latestSupportedVersion)) {
|
|
145532
145727
|
return null;
|
|
145533
145728
|
}
|
|
145534
|
-
registerPrivilegedWriter(existing);
|
|
145535
145729
|
if (!persistenceByDatabase.has(existing)) {
|
|
145536
145730
|
persistenceByDatabase.set(existing, true);
|
|
145537
145731
|
}
|
|
@@ -145544,7 +145738,6 @@ function openDatabase(dbPathOrOptions) {
|
|
|
145544
145738
|
}
|
|
145545
145739
|
ensureSecureStorageDir(dbDir);
|
|
145546
145740
|
const db = new Database(dbPath);
|
|
145547
|
-
registerPrivilegedWriter(db);
|
|
145548
145741
|
if (!enforceSchemaFence(db, dbPath, latestSupportedVersion)) {
|
|
145549
145742
|
closeQuietly(db);
|
|
145550
145743
|
return null;
|
|
@@ -145583,7 +145776,6 @@ async function openDatabaseAsync(dbPathOrOptions) {
|
|
|
145583
145776
|
migrateLegacyStorageIfNeeded(dbPath, dbDir);
|
|
145584
145777
|
ensureSecureStorageDir(dbDir);
|
|
145585
145778
|
db = new Database(dbPath);
|
|
145586
|
-
registerPrivilegedWriter(db);
|
|
145587
145779
|
if (!enforceSchemaFence(db, dbPath, latestSupportedVersion)) {
|
|
145588
145780
|
closeQuietly(db);
|
|
145589
145781
|
return null;
|
|
@@ -165562,62 +165754,6 @@ function nextDueAtMs(expression, afterMs, consumedScheduledAtMs, maxSearchMs = M
|
|
|
165562
165754
|
return next ? next.getTime() : null;
|
|
165563
165755
|
}
|
|
165564
165756
|
|
|
165565
|
-
// ../plugin/src/features/magic-context/dreamer/task-registry.ts
|
|
165566
|
-
var CANONICAL_DREAM_TASKS = [
|
|
165567
|
-
"map-memories",
|
|
165568
|
-
"verify",
|
|
165569
|
-
"verify-broad",
|
|
165570
|
-
"curate",
|
|
165571
|
-
"compress-cues",
|
|
165572
|
-
"classify-memories",
|
|
165573
|
-
"retrospective",
|
|
165574
|
-
"maintain-docs",
|
|
165575
|
-
"evaluate-smart-notes",
|
|
165576
|
-
"review-user-memories",
|
|
165577
|
-
"promote-primers",
|
|
165578
|
-
"refresh-primers"
|
|
165579
|
-
];
|
|
165580
|
-
var AGENTIC_DREAM_TASKS = ["curate", "maintain-docs"];
|
|
165581
|
-
var MEMORY_DOMAIN_TASKS = [
|
|
165582
|
-
"map-memories",
|
|
165583
|
-
"verify",
|
|
165584
|
-
"verify-broad",
|
|
165585
|
-
"curate",
|
|
165586
|
-
"compress-cues",
|
|
165587
|
-
"classify-memories",
|
|
165588
|
-
"retrospective",
|
|
165589
|
-
"promote-primers",
|
|
165590
|
-
"refresh-primers"
|
|
165591
|
-
];
|
|
165592
|
-
var MEMORY_DOMAIN_SET = new Set(MEMORY_DOMAIN_TASKS);
|
|
165593
|
-
function leaseKindFor(task) {
|
|
165594
|
-
if (MEMORY_DOMAIN_SET.has(task))
|
|
165595
|
-
return "memory";
|
|
165596
|
-
switch (task) {
|
|
165597
|
-
case "review-user-memories":
|
|
165598
|
-
return "user-memories";
|
|
165599
|
-
case "promote-primers":
|
|
165600
|
-
case "refresh-primers":
|
|
165601
|
-
return "memory";
|
|
165602
|
-
case "maintain-docs":
|
|
165603
|
-
return "maintain-docs";
|
|
165604
|
-
case "evaluate-smart-notes":
|
|
165605
|
-
return "evaluate-smart-notes";
|
|
165606
|
-
default:
|
|
165607
|
-
return "memory";
|
|
165608
|
-
}
|
|
165609
|
-
}
|
|
165610
|
-
function leaseKeyFor(task, projectIdentity) {
|
|
165611
|
-
const kind = leaseKindFor(task);
|
|
165612
|
-
return kind === "user-memories" ? "user-memories" : `${kind}:${projectIdentity}`;
|
|
165613
|
-
}
|
|
165614
|
-
function isCanonicalDreamTask(value) {
|
|
165615
|
-
return CANONICAL_DREAM_TASKS.includes(value);
|
|
165616
|
-
}
|
|
165617
|
-
function compareTaskOrder(a, b) {
|
|
165618
|
-
return CANONICAL_DREAM_TASKS.indexOf(a) - CANONICAL_DREAM_TASKS.indexOf(b);
|
|
165619
|
-
}
|
|
165620
|
-
|
|
165621
165757
|
// ../plugin/src/config/schema/agent-overrides.ts
|
|
165622
165758
|
var PermissionValueSchema = exports_external.enum(["ask", "allow", "deny"]);
|
|
165623
165759
|
var PermissionSchema = exports_external.object({
|
|
@@ -165650,8 +165786,7 @@ var EXECUTE_THRESHOLD_CAP_MESSAGE = "execute_threshold is capped at 80% for cach
|
|
|
165650
165786
|
var DEFAULT_HISTORIAN_TIMEOUT_MS = 300000;
|
|
165651
165787
|
var DEFAULT_HISTORY_BUDGET_PERCENTAGE = 0.15;
|
|
165652
165788
|
var DEFAULT_LOCAL_EMBEDDING_MODEL = "Xenova/all-MiniLM-L6-v2";
|
|
165653
|
-
var
|
|
165654
|
-
var PiThinkingLevelSchema = exports_external.enum(["off", "minimal", "low", "medium", "high", "xhigh"]).optional();
|
|
165789
|
+
var PiThinkingLevelSchema = exports_external.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]).optional();
|
|
165655
165790
|
var PiConfigSchema = exports_external.object({
|
|
165656
165791
|
subagent_extensions: exports_external.array(exports_external.string().trim().min(1)).optional().describe("User-only allowlist of Pi extensions for Magic Context subagent children. When set, children use --no-extensions and load only these entries (plus Magic Context's scoped child extension where applicable). Relative paths resolve from ~/.pi/agent, matching Pi's settings.json package location. Unset preserves normal Pi extension discovery.")
|
|
165657
165792
|
}).optional();
|
|
@@ -165724,7 +165859,7 @@ var SidekickConfigSchema = AgentOverrideConfigSchema.extend({
|
|
|
165724
165859
|
}).optional();
|
|
165725
165860
|
var HistorianConfigSchema = AgentOverrideConfigSchema.extend({
|
|
165726
165861
|
two_pass: exports_external.boolean().default(false).describe("Run a second editor pass over historian output to clean low-signal U: lines and cross-compartment duplicates. Adds ~1 extra API call and ~1.3x cost per historian run. Useful for models without extended thinking support. (default: false)"),
|
|
165727
|
-
thinking_level: PiThinkingLevelSchema.describe("Pi only: explicit thinking level passed as --thinking <level> to Pi historian subagent invocations. Required when using reasoning models (e.g. github-copilot/gpt-5.4) because Pi's default thinking-level resolution can pick a value the provider rejects. OpenCode users set variant instead. Valid: off | minimal | low | medium | high | xhigh"),
|
|
165862
|
+
thinking_level: PiThinkingLevelSchema.describe("Pi only: explicit thinking level passed as --thinking <level> to Pi historian subagent invocations. Required when using reasoning models (e.g. github-copilot/gpt-5.4) because Pi's default thinking-level resolution can pick a value the provider rejects. OpenCode users set variant instead. Valid: off | minimal | low | medium | high | xhigh | max"),
|
|
165728
165863
|
disallowed_tools: exports_external.array(exports_external.enum(["*", "read", "aft_outline", "aft_zoom", "aft_search"])).default([]).describe(`OpenCode only. Tools to REMOVE from the historian's default allow-list [read, aft_outline, aft_zoom, aft_search]. Applies to both historian and historian-editor agents. Use ["*"] to strip all tool definitions from the model request — this prevents weak instruction-following models (e.g. mistral-small-latest) from entering tool-calling loops. Individual tool names remove just that tool. Note: a user-supplied historian.permission override can re-allow a tool that disallowed_tools removed — disallowed_tools sets the baseline, permission overrides take precedence. (default: [])`)
|
|
165729
165864
|
}).optional();
|
|
165730
165865
|
var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-compatible", "off"]);
|
|
@@ -171331,6 +171466,9 @@ var shadowWorker = null;
|
|
|
171331
171466
|
var SHADOW_MAX_ITEMS_PER_TICK = 64;
|
|
171332
171467
|
var SHADOW_MAX_BYTES_PER_TICK = 512 * 1024;
|
|
171333
171468
|
var SHADOW_MAX_WALL_CLOCK_MS = 2000;
|
|
171469
|
+
var pendingShadowBackfills = new Map;
|
|
171470
|
+
var shadowBackfillLastIds = new Map;
|
|
171471
|
+
var shadowBackfillStopReasons = new Map;
|
|
171334
171472
|
var loadUnembeddedMemoriesStatements = new WeakMap;
|
|
171335
171473
|
var upsertActiveIdentityStatements = new WeakMap;
|
|
171336
171474
|
var backfillActiveIdentityStatements = new Map;
|
|
@@ -171777,7 +171915,7 @@ function startShadowWorker() {
|
|
|
171777
171915
|
return;
|
|
171778
171916
|
shadowWorker = runShadowWorker().finally(() => {
|
|
171779
171917
|
shadowWorker = null;
|
|
171780
|
-
if (shadowQueue.length > 0)
|
|
171918
|
+
if (shadowQueue.length > 0 || hasPendingShadowBackfill())
|
|
171781
171919
|
startShadowWorker();
|
|
171782
171920
|
});
|
|
171783
171921
|
}
|
|
@@ -171824,6 +171962,95 @@ function enqueueShadowEmbeddingItems(projectIdentity, scope, ids) {
|
|
|
171824
171962
|
shadowQueue.push({ projectIdentity, scope, ids: [...ids] });
|
|
171825
171963
|
startShadowWorker();
|
|
171826
171964
|
}
|
|
171965
|
+
function shadowBackfillMissingBase(scope, primaryModelId, shadowModelId, projectIdentity) {
|
|
171966
|
+
if (scope === "memory") {
|
|
171967
|
+
return {
|
|
171968
|
+
sql: `SELECT m.id AS id
|
|
171969
|
+
FROM memories m
|
|
171970
|
+
JOIN memory_embeddings mp ON mp.memory_id = m.id AND mp.model_id = ?
|
|
171971
|
+
LEFT JOIN memory_embeddings ms ON ms.memory_id = m.id AND ms.model_id = ?
|
|
171972
|
+
WHERE m.project_path = ? AND m.status = 'active' AND ms.memory_id IS NULL`,
|
|
171973
|
+
params: [primaryModelId, shadowModelId, projectIdentity],
|
|
171974
|
+
orderBy: " ORDER BY m.id"
|
|
171975
|
+
};
|
|
171976
|
+
}
|
|
171977
|
+
if (scope === "commit") {
|
|
171978
|
+
return {
|
|
171979
|
+
sql: `SELECT gc.sha AS id
|
|
171980
|
+
FROM git_commits gc
|
|
171981
|
+
JOIN git_commit_embeddings gp ON gp.sha = gc.sha AND gp.model_id = ?
|
|
171982
|
+
LEFT JOIN git_commit_embeddings gs ON gs.sha = gc.sha AND gs.model_id = ?
|
|
171983
|
+
WHERE gc.project_path = ? AND gs.sha IS NULL`,
|
|
171984
|
+
params: [primaryModelId, shadowModelId, projectIdentity],
|
|
171985
|
+
orderBy: " ORDER BY gc.committed_at DESC, gc.sha"
|
|
171986
|
+
};
|
|
171987
|
+
}
|
|
171988
|
+
return {
|
|
171989
|
+
sql: `SELECT DISTINCT cp.compartment_id AS id
|
|
171990
|
+
FROM compartment_chunk_embeddings cp
|
|
171991
|
+
WHERE cp.project_path = ? AND cp.model_id = ?
|
|
171992
|
+
AND NOT EXISTS (
|
|
171993
|
+
SELECT 1 FROM compartment_chunk_embeddings cs
|
|
171994
|
+
WHERE cs.compartment_id = cp.compartment_id AND cs.model_id = ?
|
|
171995
|
+
)`,
|
|
171996
|
+
params: [projectIdentity, primaryModelId, shadowModelId],
|
|
171997
|
+
orderBy: " ORDER BY cp.compartment_id"
|
|
171998
|
+
};
|
|
171999
|
+
}
|
|
172000
|
+
function shadowBackfillMissingIds(db, projectIdentity, scope, primaryModelId, shadowModelId, limit) {
|
|
172001
|
+
const { sql, params, orderBy } = shadowBackfillMissingBase(scope, primaryModelId, shadowModelId, projectIdentity);
|
|
172002
|
+
const rows = db.prepare(`${sql}${orderBy} LIMIT ?`).all(...params, limit);
|
|
172003
|
+
return rows.map((row) => String(row.id));
|
|
172004
|
+
}
|
|
172005
|
+
function shadowModelIdForScope(registration, scope) {
|
|
172006
|
+
return scope === "chunk" ? registration.chunkModelId : registration.modelId;
|
|
172007
|
+
}
|
|
172008
|
+
function hasPendingShadowBackfill(projectIdentity) {
|
|
172009
|
+
if (projectIdentity === undefined)
|
|
172010
|
+
return pendingShadowBackfills.size > 0;
|
|
172011
|
+
const scopes = pendingShadowBackfills.get(projectIdentity);
|
|
172012
|
+
return scopes !== undefined && scopes.size > 0;
|
|
172013
|
+
}
|
|
172014
|
+
function pumpShadowBackfill() {
|
|
172015
|
+
for (const [projectIdentity, scopes] of pendingShadowBackfills) {
|
|
172016
|
+
const db = dbForShadowQueue.get(projectIdentity);
|
|
172017
|
+
const shadow = shadowRegistrations.get(projectIdentity);
|
|
172018
|
+
const primary = projectRegistrations.get(projectIdentity);
|
|
172019
|
+
if (!db || !shadow || !primary) {
|
|
172020
|
+
pendingShadowBackfills.delete(projectIdentity);
|
|
172021
|
+
continue;
|
|
172022
|
+
}
|
|
172023
|
+
for (const scope of [...scopes]) {
|
|
172024
|
+
const primaryModelId = shadowModelIdForScope(primary, scope);
|
|
172025
|
+
const shadowModelId = shadowModelIdForScope(shadow, scope);
|
|
172026
|
+
const stallKey = `${projectIdentity}:${scope}`;
|
|
172027
|
+
if (primaryModelId === "off" || shadowModelId === "off") {
|
|
172028
|
+
scopes.delete(scope);
|
|
172029
|
+
shadowBackfillLastIds.delete(stallKey);
|
|
172030
|
+
continue;
|
|
172031
|
+
}
|
|
172032
|
+
const ids = shadowBackfillMissingIds(db, projectIdentity, scope, primaryModelId, shadowModelId, SHADOW_MAX_ITEMS_PER_TICK);
|
|
172033
|
+
if (ids.length === 0) {
|
|
172034
|
+
shadowBackfillStopReasons.set(stallKey, "drained");
|
|
172035
|
+
scopes.delete(scope);
|
|
172036
|
+
shadowBackfillLastIds.delete(stallKey);
|
|
172037
|
+
continue;
|
|
172038
|
+
}
|
|
172039
|
+
const signature = ids.join(",");
|
|
172040
|
+
if (shadowBackfillLastIds.get(stallKey) === signature) {
|
|
172041
|
+
shadowBackfillStopReasons.set(stallKey, "stalled_no_progress");
|
|
172042
|
+
log(`[shadow] backfill scope ${scope} for ${projectIdentity} retired without progress — ` + `the last batch produced no writes (provider failure or timeout is the usual cause); ` + `${ids.length}+ items remain and retry on the next registration or manual --shadow run`);
|
|
172043
|
+
scopes.delete(scope);
|
|
172044
|
+
shadowBackfillLastIds.delete(stallKey);
|
|
172045
|
+
continue;
|
|
172046
|
+
}
|
|
172047
|
+
shadowBackfillLastIds.set(stallKey, signature);
|
|
172048
|
+
shadowQueue.push({ projectIdentity, scope, ids });
|
|
172049
|
+
}
|
|
172050
|
+
if (scopes.size === 0)
|
|
172051
|
+
pendingShadowBackfills.delete(projectIdentity);
|
|
172052
|
+
}
|
|
172053
|
+
}
|
|
171827
172054
|
async function embedShadowItems(registration, items, db, scope) {
|
|
171828
172055
|
const raw = registration.config;
|
|
171829
172056
|
const fingerprint = typeof raw.synapse_fingerprint === "string" ? raw.synapse_fingerprint : "";
|
|
@@ -171947,7 +172174,15 @@ async function runShadowWorker() {
|
|
|
171947
172174
|
const startedAt = Date.now();
|
|
171948
172175
|
let processed = 0;
|
|
171949
172176
|
let processedBytes = 0;
|
|
171950
|
-
|
|
172177
|
+
for (;; ) {
|
|
172178
|
+
if (shadowQueue.length === 0) {
|
|
172179
|
+
pumpShadowBackfill();
|
|
172180
|
+
if (shadowQueue.length === 0)
|
|
172181
|
+
break;
|
|
172182
|
+
}
|
|
172183
|
+
if (processed >= SHADOW_MAX_ITEMS_PER_TICK || Date.now() - startedAt >= SHADOW_MAX_WALL_CLOCK_MS) {
|
|
172184
|
+
break;
|
|
172185
|
+
}
|
|
171951
172186
|
const item = shadowQueue.shift();
|
|
171952
172187
|
if (!item)
|
|
171953
172188
|
break;
|
|
@@ -178182,7 +178417,6 @@ class ModuleMemoryAuthorityError extends Error {
|
|
|
178182
178417
|
}
|
|
178183
178418
|
}
|
|
178184
178419
|
function assertTsMemoryWriteAllowed(db, projectPath) {
|
|
178185
|
-
registerPrivilegedWriter(db);
|
|
178186
178420
|
try {
|
|
178187
178421
|
const managed = db.prepare("SELECT 1 FROM authority_managed WHERE project_path = ? UNION SELECT 1 FROM authority_repair_pending WHERE project_path = ? LIMIT 1").get(projectPath, projectPath);
|
|
178188
178422
|
if (managed)
|
|
@@ -182161,6 +182395,353 @@ class BoundedSessionMap {
|
|
|
182161
182395
|
}
|
|
182162
182396
|
}
|
|
182163
182397
|
|
|
182398
|
+
// ../plugin/src/features/magic-context/compaction-marker.ts
|
|
182399
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
182400
|
+
import { existsSync as existsSync9 } from "node:fs";
|
|
182401
|
+
import { join as join7 } from "node:path";
|
|
182402
|
+
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
182403
|
+
var ID_PREFIX_HEX_LENGTH = 12;
|
|
182404
|
+
var ID_SUFFIX_LENGTH = 14;
|
|
182405
|
+
var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
|
|
182406
|
+
function deterministicBase62(seed, length) {
|
|
182407
|
+
let value = BigInt(`0x${createHash16("sha256").update(seed).digest("hex")}`);
|
|
182408
|
+
const chars = Array(length);
|
|
182409
|
+
for (let index = length - 1;index >= 0; index -= 1) {
|
|
182410
|
+
chars[index] = BASE62_CHARS[Number(value % 62n)];
|
|
182411
|
+
value /= 62n;
|
|
182412
|
+
}
|
|
182413
|
+
return chars.join("");
|
|
182414
|
+
}
|
|
182415
|
+
function generateId(prefix, timestampMs, counter, identity) {
|
|
182416
|
+
const encoded = BigInt(Math.max(0, Math.floor(timestampMs))) * 0x1000n + counter & ID_PREFIX_MASK;
|
|
182417
|
+
const hex3 = encoded.toString(16).padStart(ID_PREFIX_HEX_LENGTH, "0");
|
|
182418
|
+
return `${prefix}_${hex3}${deterministicBase62(`${prefix}\x00${identity}`, ID_SUFFIX_LENGTH)}`;
|
|
182419
|
+
}
|
|
182420
|
+
function generateMessageId(timestampMs, counter = 0n, identity = "") {
|
|
182421
|
+
return generateId("msg", timestampMs, counter, identity);
|
|
182422
|
+
}
|
|
182423
|
+
function generatePartId(timestampMs, counter = 0n, identity = "") {
|
|
182424
|
+
return generateId("prt", timestampMs, counter, identity);
|
|
182425
|
+
}
|
|
182426
|
+
function getOpenCodeDbPath2() {
|
|
182427
|
+
return join7(getDataDir(), "opencode", "opencode.db");
|
|
182428
|
+
}
|
|
182429
|
+
var cachedWriteDb = null;
|
|
182430
|
+
var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
|
|
182431
|
+
var REQUIRED_PART_COLUMNS = [
|
|
182432
|
+
"id",
|
|
182433
|
+
"message_id",
|
|
182434
|
+
"session_id",
|
|
182435
|
+
"time_created",
|
|
182436
|
+
"time_updated",
|
|
182437
|
+
"data"
|
|
182438
|
+
];
|
|
182439
|
+
var cachedSchemaCompatible = null;
|
|
182440
|
+
function isOpenCodeSchemaCompatible(db, dbPath) {
|
|
182441
|
+
if (cachedSchemaCompatible?.path === dbPath) {
|
|
182442
|
+
return cachedSchemaCompatible.compatible;
|
|
182443
|
+
}
|
|
182444
|
+
try {
|
|
182445
|
+
const messageCols = new Set(db.prepare("PRAGMA table_info(message)").all().map((r) => r.name ?? "").filter((n) => n.length > 0));
|
|
182446
|
+
const partCols = new Set(db.prepare("PRAGMA table_info(part)").all().map((r) => r.name ?? "").filter((n) => n.length > 0));
|
|
182447
|
+
const missingMessage = REQUIRED_MESSAGE_COLUMNS.filter((c) => !messageCols.has(c));
|
|
182448
|
+
const missingPart = REQUIRED_PART_COLUMNS.filter((c) => !partCols.has(c));
|
|
182449
|
+
if (missingMessage.length > 0 || missingPart.length > 0) {
|
|
182450
|
+
log(`[magic-context] compaction-marker: OpenCode DB schema missing required columns ` + `(message: [${missingMessage.join(", ")}], part: [${missingPart.join(", ")}]). ` + `Marker injection disabled for this process. ` + `This usually means OpenCode was updated and magic-context is out of date.`);
|
|
182451
|
+
cachedSchemaCompatible = { path: dbPath, compatible: false };
|
|
182452
|
+
return false;
|
|
182453
|
+
}
|
|
182454
|
+
cachedSchemaCompatible = { path: dbPath, compatible: true };
|
|
182455
|
+
return true;
|
|
182456
|
+
} catch (error51) {
|
|
182457
|
+
log(`[magic-context] compaction-marker: schema probe failed: ${error51 instanceof Error ? error51.message : String(error51)}. ` + `Marker injection disabled until next process restart.`);
|
|
182458
|
+
cachedSchemaCompatible = { path: dbPath, compatible: false };
|
|
182459
|
+
return false;
|
|
182460
|
+
}
|
|
182461
|
+
}
|
|
182462
|
+
function getWritableOpenCodeDb() {
|
|
182463
|
+
const dbPath = getOpenCodeDbPath2();
|
|
182464
|
+
if (cachedWriteDb?.path === dbPath) {
|
|
182465
|
+
return cachedWriteDb.db;
|
|
182466
|
+
}
|
|
182467
|
+
if (cachedWriteDb) {
|
|
182468
|
+
try {
|
|
182469
|
+
closeQuietly(cachedWriteDb.db);
|
|
182470
|
+
} catch {}
|
|
182471
|
+
}
|
|
182472
|
+
if (!existsSync9(dbPath)) {
|
|
182473
|
+
throw new Error(`OpenCode database not found at ${dbPath} (is OpenCode installed?)`);
|
|
182474
|
+
}
|
|
182475
|
+
const db = new Database(dbPath);
|
|
182476
|
+
db.exec("PRAGMA busy_timeout=5000");
|
|
182477
|
+
db.exec("PRAGMA journal_mode=WAL");
|
|
182478
|
+
cachedWriteDb = { path: dbPath, db };
|
|
182479
|
+
return db;
|
|
182480
|
+
}
|
|
182481
|
+
function getNonSummaryMessageSortKey(sessionId, messageId) {
|
|
182482
|
+
const db = getWritableOpenCodeDb();
|
|
182483
|
+
const row = db.prepare(`SELECT time_created, id
|
|
182484
|
+
FROM message
|
|
182485
|
+
WHERE session_id = ?
|
|
182486
|
+
AND id = ?
|
|
182487
|
+
AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
|
|
182488
|
+
AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')
|
|
182489
|
+
LIMIT 1`).get(sessionId, messageId);
|
|
182490
|
+
if (typeof row?.time_created !== "number" || typeof row.id !== "string") {
|
|
182491
|
+
return null;
|
|
182492
|
+
}
|
|
182493
|
+
return { id: row.id, timeCreated: row.time_created };
|
|
182494
|
+
}
|
|
182495
|
+
function findBoundaryUserMessage(sessionId, endMessageId) {
|
|
182496
|
+
const db = getWritableOpenCodeDb();
|
|
182497
|
+
const target2 = getNonSummaryMessageSortKey(sessionId, endMessageId);
|
|
182498
|
+
if (!target2)
|
|
182499
|
+
return null;
|
|
182500
|
+
const boundary = db.prepare(`SELECT id, time_created, data
|
|
182501
|
+
FROM message
|
|
182502
|
+
WHERE session_id = ?
|
|
182503
|
+
AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
|
|
182504
|
+
AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')
|
|
182505
|
+
AND COALESCE(json_extract(data, '$.role'), '') = 'user'
|
|
182506
|
+
AND (time_created < ? OR (time_created = ? AND id <= ?))
|
|
182507
|
+
ORDER BY time_created DESC, id DESC
|
|
182508
|
+
LIMIT 1`).get(sessionId, target2.timeCreated, target2.timeCreated, target2.id);
|
|
182509
|
+
if (typeof boundary?.id !== "string" || typeof boundary.time_created !== "number") {
|
|
182510
|
+
return null;
|
|
182511
|
+
}
|
|
182512
|
+
return { id: boundary.id, timeCreated: boundary.time_created };
|
|
182513
|
+
}
|
|
182514
|
+
function compareOpenCodeMessagesByCanonicalOrder(sessionId, leftMessageId, rightMessageId) {
|
|
182515
|
+
const left = getNonSummaryMessageSortKey(sessionId, leftMessageId);
|
|
182516
|
+
const right = getNonSummaryMessageSortKey(sessionId, rightMessageId);
|
|
182517
|
+
if (!left || !right)
|
|
182518
|
+
return null;
|
|
182519
|
+
if (left.timeCreated < right.timeCreated)
|
|
182520
|
+
return -1;
|
|
182521
|
+
if (left.timeCreated > right.timeCreated)
|
|
182522
|
+
return 1;
|
|
182523
|
+
if (left.id < right.id)
|
|
182524
|
+
return -1;
|
|
182525
|
+
if (left.id > right.id)
|
|
182526
|
+
return 1;
|
|
182527
|
+
return 0;
|
|
182528
|
+
}
|
|
182529
|
+
function removeLegacyMarkerLineageRows(db, args) {
|
|
182530
|
+
const legacySummaries = db.prepare(`SELECT m.id
|
|
182531
|
+
FROM message m
|
|
182532
|
+
WHERE m.session_id = ?
|
|
182533
|
+
AND m.id <> ?
|
|
182534
|
+
AND COALESCE(json_extract(m.data, '$.summary'), 0) = 1
|
|
182535
|
+
AND COALESCE(json_extract(m.data, '$.finish'), '') = 'stop'
|
|
182536
|
+
AND COALESCE(json_extract(m.data, '$.parentID'), '') = ?
|
|
182537
|
+
AND EXISTS (
|
|
182538
|
+
SELECT 1
|
|
182539
|
+
FROM part p
|
|
182540
|
+
WHERE p.session_id = m.session_id
|
|
182541
|
+
AND p.message_id = m.id
|
|
182542
|
+
AND COALESCE(json_extract(p.data, '$.type'), '') = 'text'
|
|
182543
|
+
AND COALESCE(json_extract(p.data, '$.text'), '') = ?
|
|
182544
|
+
)`).all(args.sessionId, args.summaryMessageId, args.boundaryMessageId, args.summaryText);
|
|
182545
|
+
const legacySummaryIds = legacySummaries.flatMap((row) => typeof row.id === "string" ? [row.id] : []);
|
|
182546
|
+
if (legacySummaryIds.length === 0)
|
|
182547
|
+
return;
|
|
182548
|
+
const deleteSummaryParts = db.prepare("DELETE FROM part WHERE session_id = ? AND message_id = ?");
|
|
182549
|
+
const deleteSummary = db.prepare("DELETE FROM message WHERE session_id = ? AND id = ?");
|
|
182550
|
+
for (const summaryMessageId of legacySummaryIds) {
|
|
182551
|
+
deleteSummaryParts.run(args.sessionId, summaryMessageId);
|
|
182552
|
+
deleteSummary.run(args.sessionId, summaryMessageId);
|
|
182553
|
+
}
|
|
182554
|
+
db.prepare(`DELETE FROM part
|
|
182555
|
+
WHERE session_id = ?
|
|
182556
|
+
AND message_id = ?
|
|
182557
|
+
AND id <> ?
|
|
182558
|
+
AND COALESCE(json_extract(data, '$.type'), '') = 'compaction'
|
|
182559
|
+
AND COALESCE(json_extract(data, '$.auto'), 0) = 1`).run(args.sessionId, args.boundaryMessageId, args.compactionPartId);
|
|
182560
|
+
}
|
|
182561
|
+
function injectCompactionMarker(args) {
|
|
182562
|
+
const db = getWritableOpenCodeDb();
|
|
182563
|
+
if (!isOpenCodeSchemaCompatible(db, getOpenCodeDbPath2())) {
|
|
182564
|
+
return null;
|
|
182565
|
+
}
|
|
182566
|
+
const boundary = args.resolvedBoundary ?? findBoundaryUserMessage(args.sessionId, args.endMessageId);
|
|
182567
|
+
if (!boundary) {
|
|
182568
|
+
log(`[magic-context] compaction-marker: no user message found at or before endMessageId ${args.endMessageId} (ordinal ${args.endOrdinal})`);
|
|
182569
|
+
return null;
|
|
182570
|
+
}
|
|
182571
|
+
const boundaryTime = boundary.timeCreated;
|
|
182572
|
+
const markerIdentity = `${args.sessionId}\x00${args.endMessageId}`;
|
|
182573
|
+
const summaryMsgId = generateMessageId(boundaryTime + 1, 1n, `${markerIdentity}\x00summary-message`);
|
|
182574
|
+
const compactionPartId = generatePartId(boundaryTime, 1n, `${markerIdentity}\x00compaction-part`);
|
|
182575
|
+
const summaryPartId = generatePartId(boundaryTime + 1, 2n, `${markerIdentity}\x00summary-part`);
|
|
182576
|
+
const summaryMsgData = JSON.stringify({
|
|
182577
|
+
role: "assistant",
|
|
182578
|
+
parentID: boundary.id,
|
|
182579
|
+
summary: true,
|
|
182580
|
+
finish: "stop",
|
|
182581
|
+
mode: "compaction",
|
|
182582
|
+
agent: "compaction",
|
|
182583
|
+
path: { cwd: args.directory, root: args.directory },
|
|
182584
|
+
cost: 0,
|
|
182585
|
+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
182586
|
+
modelID: "magic-context",
|
|
182587
|
+
providerID: "magic-context",
|
|
182588
|
+
time: { created: boundaryTime + 1 }
|
|
182589
|
+
});
|
|
182590
|
+
try {
|
|
182591
|
+
db.transaction(() => {
|
|
182592
|
+
removeLegacyMarkerLineageRows(db, {
|
|
182593
|
+
sessionId: args.sessionId,
|
|
182594
|
+
boundaryMessageId: boundary.id,
|
|
182595
|
+
summaryText: args.summaryText,
|
|
182596
|
+
summaryMessageId: summaryMsgId,
|
|
182597
|
+
compactionPartId
|
|
182598
|
+
});
|
|
182599
|
+
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data)
|
|
182600
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
182601
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
182602
|
+
message_id = excluded.message_id,
|
|
182603
|
+
session_id = excluded.session_id,
|
|
182604
|
+
time_created = excluded.time_created,
|
|
182605
|
+
time_updated = excluded.time_updated,
|
|
182606
|
+
data = excluded.data`).run(compactionPartId, boundary.id, args.sessionId, boundaryTime, boundaryTime, '{"type":"compaction","auto":true}');
|
|
182607
|
+
db.prepare(`INSERT INTO message (id, session_id, time_created, time_updated, data)
|
|
182608
|
+
VALUES (?, ?, ?, ?, ?)
|
|
182609
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
182610
|
+
session_id = excluded.session_id,
|
|
182611
|
+
time_created = excluded.time_created,
|
|
182612
|
+
time_updated = excluded.time_updated,
|
|
182613
|
+
data = excluded.data`).run(summaryMsgId, args.sessionId, boundaryTime + 1, boundaryTime + 1, summaryMsgData);
|
|
182614
|
+
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data)
|
|
182615
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
182616
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
182617
|
+
message_id = excluded.message_id,
|
|
182618
|
+
session_id = excluded.session_id,
|
|
182619
|
+
time_created = excluded.time_created,
|
|
182620
|
+
time_updated = excluded.time_updated,
|
|
182621
|
+
data = excluded.data`).run(summaryPartId, summaryMsgId, args.sessionId, boundaryTime + 1, boundaryTime + 1, JSON.stringify({ type: "text", text: args.summaryText }));
|
|
182622
|
+
})();
|
|
182623
|
+
log(`[magic-context] compaction-marker: injected boundary at user msg ${boundary.id} (ordinal ~${args.endOrdinal}), summary msg ${summaryMsgId}`);
|
|
182624
|
+
return {
|
|
182625
|
+
boundaryMessageId: boundary.id,
|
|
182626
|
+
summaryMessageId: summaryMsgId,
|
|
182627
|
+
compactionPartId,
|
|
182628
|
+
summaryPartId
|
|
182629
|
+
};
|
|
182630
|
+
} catch (error51) {
|
|
182631
|
+
log(`[magic-context] compaction-marker: injection failed: ${error51 instanceof Error ? error51.message : String(error51)}`);
|
|
182632
|
+
return null;
|
|
182633
|
+
}
|
|
182634
|
+
}
|
|
182635
|
+
function removeCompactionMarker(state) {
|
|
182636
|
+
try {
|
|
182637
|
+
const db = getWritableOpenCodeDb();
|
|
182638
|
+
db.transaction(() => {
|
|
182639
|
+
db.prepare("DELETE FROM part WHERE id = ?").run(state.summaryPartId);
|
|
182640
|
+
db.prepare("DELETE FROM message WHERE id = ?").run(state.summaryMessageId);
|
|
182641
|
+
db.prepare("DELETE FROM part WHERE id = ?").run(state.compactionPartId);
|
|
182642
|
+
})();
|
|
182643
|
+
return true;
|
|
182644
|
+
} catch (error51) {
|
|
182645
|
+
log(`[magic-context] compaction-marker: removal failed: ${error51 instanceof Error ? error51.message : String(error51)}`);
|
|
182646
|
+
return false;
|
|
182647
|
+
}
|
|
182648
|
+
}
|
|
182649
|
+
|
|
182650
|
+
// ../plugin/src/hooks/magic-context/compaction-marker-manager.ts
|
|
182651
|
+
var MARKER_SUMMARY_TEXT = "[Compacted by magic-context — session history is managed by the plugin]";
|
|
182652
|
+
function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
|
|
182653
|
+
const tagNumber = getTagNumberByMessageId(db, sessionId, `${summaryMessageId}:p0`);
|
|
182654
|
+
if (tagNumber !== null)
|
|
182655
|
+
updateTagStatus(db, sessionId, tagNumber, "dropped");
|
|
182656
|
+
}
|
|
182657
|
+
function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSummaryMessageId) {
|
|
182658
|
+
db.transaction(() => {
|
|
182659
|
+
setPersistedCompactionMarkerState(db, sessionId, state);
|
|
182660
|
+
if (replacedSummaryMessageId !== null) {
|
|
182661
|
+
dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
|
|
182662
|
+
}
|
|
182663
|
+
})();
|
|
182664
|
+
}
|
|
182665
|
+
function getCompartmentEndMessageIdForOrdinal(db, sessionId, endOrdinal) {
|
|
182666
|
+
const row = db.prepare(`SELECT end_message_id
|
|
182667
|
+
FROM compartments
|
|
182668
|
+
WHERE session_id = ? AND end_message = ?
|
|
182669
|
+
ORDER BY sequence DESC
|
|
182670
|
+
LIMIT 1`).get(sessionId, endOrdinal);
|
|
182671
|
+
return typeof row?.end_message_id === "string" && row.end_message_id.length > 0 ? row.end_message_id : null;
|
|
182672
|
+
}
|
|
182673
|
+
function existingMarkerAlreadyCoversTarget(sessionId, existing, targetOrdinal, targetEndMessageId) {
|
|
182674
|
+
if (existing.boundaryOrdinal < targetOrdinal) {
|
|
182675
|
+
return false;
|
|
182676
|
+
}
|
|
182677
|
+
if (existing.boundaryOrdinal === targetOrdinal) {
|
|
182678
|
+
const boundaryCompare = compareOpenCodeMessagesByCanonicalOrder(sessionId, existing.boundaryMessageId, targetEndMessageId);
|
|
182679
|
+
if (boundaryCompare === null || boundaryCompare > 0) {
|
|
182680
|
+
return false;
|
|
182681
|
+
}
|
|
182682
|
+
if (existing.targetEndMessageId !== null && existing.targetEndMessageId !== targetEndMessageId) {
|
|
182683
|
+
return false;
|
|
182684
|
+
}
|
|
182685
|
+
return true;
|
|
182686
|
+
}
|
|
182687
|
+
if (existing.targetEndMessageId !== null) {
|
|
182688
|
+
const targetCompare = compareOpenCodeMessagesByCanonicalOrder(sessionId, existing.targetEndMessageId, targetEndMessageId);
|
|
182689
|
+
if (targetCompare !== null && targetCompare <= 0) {
|
|
182690
|
+
return false;
|
|
182691
|
+
}
|
|
182692
|
+
}
|
|
182693
|
+
return true;
|
|
182694
|
+
}
|
|
182695
|
+
function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEnd, directory) {
|
|
182696
|
+
if (getHarness() !== "opencode") {
|
|
182697
|
+
return true;
|
|
182698
|
+
}
|
|
182699
|
+
const targetEndMessageId = getCompartmentEndMessageIdForOrdinal(db, sessionId, lastCompartmentEnd);
|
|
182700
|
+
if (!targetEndMessageId) {
|
|
182701
|
+
sessionLog(sessionId, `compaction-marker: no compartment endMessageId for ordinal ${lastCompartmentEnd}; preserving existing marker`);
|
|
182702
|
+
return false;
|
|
182703
|
+
}
|
|
182704
|
+
const existing = getPersistedCompactionMarkerState(db, sessionId);
|
|
182705
|
+
const removedSummaryMessageId = existing?.summaryMessageId ?? null;
|
|
182706
|
+
if (existing) {
|
|
182707
|
+
if (existingMarkerAlreadyCoversTarget(sessionId, existing, lastCompartmentEnd, targetEndMessageId)) {
|
|
182708
|
+
return true;
|
|
182709
|
+
}
|
|
182710
|
+
}
|
|
182711
|
+
const boundary = findBoundaryUserMessage(sessionId, targetEndMessageId);
|
|
182712
|
+
if (!boundary) {
|
|
182713
|
+
sessionLog(sessionId, `compaction-marker: no user boundary found at or before endMessageId ${targetEndMessageId} (ordinal ${lastCompartmentEnd}); preserving existing marker`);
|
|
182714
|
+
return false;
|
|
182715
|
+
}
|
|
182716
|
+
if (existing) {
|
|
182717
|
+
const removed = removeCompactionMarker(existing);
|
|
182718
|
+
if (!removed) {
|
|
182719
|
+
sessionLog(sessionId, `compaction-marker: failed to remove old boundary at ordinal ${existing.boundaryOrdinal}; preserving persisted state for retry (not injecting new marker this pass)`);
|
|
182720
|
+
return false;
|
|
182721
|
+
}
|
|
182722
|
+
persistMarkerStateAndDropReplacedTag(db, sessionId, null, removedSummaryMessageId);
|
|
182723
|
+
sessionLog(sessionId, `compaction-marker: removed old boundary at ordinal ${existing.boundaryOrdinal}, moving to ${lastCompartmentEnd}`);
|
|
182724
|
+
}
|
|
182725
|
+
const result = injectCompactionMarker({
|
|
182726
|
+
sessionId,
|
|
182727
|
+
endOrdinal: lastCompartmentEnd,
|
|
182728
|
+
endMessageId: targetEndMessageId,
|
|
182729
|
+
summaryText: MARKER_SUMMARY_TEXT,
|
|
182730
|
+
directory: directory ?? process.cwd(),
|
|
182731
|
+
resolvedBoundary: boundary
|
|
182732
|
+
});
|
|
182733
|
+
if (result) {
|
|
182734
|
+
persistMarkerStateAndDropReplacedTag(db, sessionId, {
|
|
182735
|
+
...result,
|
|
182736
|
+
boundaryOrdinal: lastCompartmentEnd,
|
|
182737
|
+
targetEndMessageId
|
|
182738
|
+
}, removedSummaryMessageId);
|
|
182739
|
+
sessionLog(sessionId, `compaction-marker: injected at ordinal ${lastCompartmentEnd}, boundary user msg ${result.boundaryMessageId}`);
|
|
182740
|
+
return true;
|
|
182741
|
+
}
|
|
182742
|
+
return false;
|
|
182743
|
+
}
|
|
182744
|
+
|
|
182164
182745
|
// ../plugin/src/hooks/magic-context/compartment-render-epoch.ts
|
|
182165
182746
|
var COMPARTMENT_RENDER_EPOCH = "cre2";
|
|
182166
182747
|
var EPOCH_COMPONENT_PREFIX = "|compartment-render:";
|
|
@@ -182450,6 +183031,13 @@ var INJECTION_CACHE_MAX = 100;
|
|
|
182450
183031
|
var injectionCache = new BoundedSessionMap(INJECTION_CACHE_MAX);
|
|
182451
183032
|
function clearInjectionCache(sessionId) {
|
|
182452
183033
|
injectionCache.delete(sessionId);
|
|
183034
|
+
resetDegradedReanchorState(sessionId);
|
|
183035
|
+
}
|
|
183036
|
+
var degradedRebuildCountBySession = new BoundedSessionMap(INJECTION_CACHE_MAX);
|
|
183037
|
+
var reAnchorLoggedBySession = new BoundedSessionMap(INJECTION_CACHE_MAX);
|
|
183038
|
+
function resetDegradedReanchorState(sessionId) {
|
|
183039
|
+
degradedRebuildCountBySession.delete(sessionId);
|
|
183040
|
+
reAnchorLoggedBySession.delete(sessionId);
|
|
182453
183041
|
}
|
|
182454
183042
|
function getVisibleMemoryIds(db, sessionId) {
|
|
182455
183043
|
try {
|
|
@@ -182980,4 +183568,4 @@ function registerMagicContextTools(pi, opts) {
|
|
|
182980
183568
|
}
|
|
182981
183569
|
}
|
|
182982
183570
|
|
|
182983
|
-
export { isDreamerRunnable, migrateMagicContextConfigLocations,
|
|
183571
|
+
export { isDreamerRunnable, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, estimateTokens, normalizeText, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, stableStringify, getSchemaFenceRejection, getDatabasePath, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, isSaneLimit, getSdkContextLimit, normalizeTodoStateJson, buildSyntheticTodoPart, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, piModelRefToCanonical, resolveModelRefForPi, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, computeNormalizedHash, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, invalidateMemory, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, computeCueContentHash, getMuralCueState, memoryNeedsCue, setMuralCue, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };
|