@cortexkit/pi-magic-context 0.40.1 → 0.41.0
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/README.md +9 -0
- package/dist/historian-calibration-extension.js +58 -0
- package/dist/index-3k71e196.js +378 -0
- package/dist/{index-fre7qcqg.js → index-ts6nabp0.js} +319 -260
- package/dist/index.js +1109 -455
- package/dist/{safe-notification-target-q00qgjm6.js → safe-notification-target-g8fx80va.js} +1 -1
- package/dist/subagent-entry.js +2 -2
- package/package.json +87 -87
- package/dist/index-hk6sj7dn.js +0 -147
- /package/dist/{index-8sseka65.js → index-wnrygn5h.js} +0 -0
|
@@ -4,8 +4,9 @@ import {
|
|
|
4
4
|
getLegacyOpenCodeMagicContextStorageDir,
|
|
5
5
|
getMagicContextStorageDir,
|
|
6
6
|
log,
|
|
7
|
+
sanitizeDiagnosticText,
|
|
7
8
|
sessionLog
|
|
8
|
-
} from "./index-
|
|
9
|
+
} from "./index-3k71e196.js";
|
|
9
10
|
import {
|
|
10
11
|
__commonJS,
|
|
11
12
|
__export,
|
|
@@ -8283,153 +8284,6 @@ function migrateMagicContextConfigLocations(directory, logger) {
|
|
|
8283
8284
|
return warnings;
|
|
8284
8285
|
}
|
|
8285
8286
|
|
|
8286
|
-
// ../plugin/src/shared/redaction.ts
|
|
8287
|
-
import { homedir as homedir2, userInfo } from "node:os";
|
|
8288
|
-
function escapeRegex(value) {
|
|
8289
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
8290
|
-
}
|
|
8291
|
-
var SECRET_WORDS = [
|
|
8292
|
-
"key",
|
|
8293
|
-
"token",
|
|
8294
|
-
"secret",
|
|
8295
|
-
"password",
|
|
8296
|
-
"auth",
|
|
8297
|
-
"authorization",
|
|
8298
|
-
"bearer",
|
|
8299
|
-
"credential"
|
|
8300
|
-
];
|
|
8301
|
-
var SECRET_SEGMENT_PATTERN = new RegExp(`^(?:${SECRET_WORDS.map((w) => `${w}s?`).join("|")})$`, "i");
|
|
8302
|
-
var TRAILING_DESCRIPTORS = new Set(["id", "ids", "value", "values", "header", "headers"]);
|
|
8303
|
-
function redactionTypeForKey(key) {
|
|
8304
|
-
const normalized = key.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, "_");
|
|
8305
|
-
const suffix = normalized.split(".").filter(Boolean).at(-1) ?? normalized;
|
|
8306
|
-
return suffix || "secret";
|
|
8307
|
-
}
|
|
8308
|
-
function isNonSecretScalarValue(value) {
|
|
8309
|
-
const v = value.trim();
|
|
8310
|
-
if (v === "true" || v === "false" || v === "null" || v === "undefined")
|
|
8311
|
-
return true;
|
|
8312
|
-
return /^[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(v);
|
|
8313
|
-
}
|
|
8314
|
-
var SECRET_QUALIFIERS = new Set([
|
|
8315
|
-
"api",
|
|
8316
|
-
"access",
|
|
8317
|
-
"private",
|
|
8318
|
-
"client",
|
|
8319
|
-
"auth",
|
|
8320
|
-
"authorization",
|
|
8321
|
-
"secret",
|
|
8322
|
-
"bearer",
|
|
8323
|
-
"session",
|
|
8324
|
-
"refresh",
|
|
8325
|
-
"service",
|
|
8326
|
-
"x",
|
|
8327
|
-
"openai",
|
|
8328
|
-
"anthropic",
|
|
8329
|
-
"google",
|
|
8330
|
-
"github",
|
|
8331
|
-
"huggingface",
|
|
8332
|
-
"aws",
|
|
8333
|
-
"azure"
|
|
8334
|
-
]);
|
|
8335
|
-
function sanitizePathString(value) {
|
|
8336
|
-
const home = homedir2();
|
|
8337
|
-
const username = userInfo().username;
|
|
8338
|
-
let sanitized = value;
|
|
8339
|
-
if (home) {
|
|
8340
|
-
sanitized = sanitized.replace(new RegExp(escapeRegex(home), "g"), "~");
|
|
8341
|
-
}
|
|
8342
|
-
sanitized = sanitized.replace(/\/Users\/[^/]+\//g, "/Users/<USER>/");
|
|
8343
|
-
sanitized = sanitized.replace(/\/home\/[^/]+\//g, "/home/<USER>/");
|
|
8344
|
-
sanitized = sanitized.replace(/C:\\Users\\[^\\]+\\/g, "C:\\Users\\<USER>\\");
|
|
8345
|
-
if (username) {
|
|
8346
|
-
sanitized = sanitized.replace(new RegExp(escapeRegex(username), "g"), "<USER>");
|
|
8347
|
-
}
|
|
8348
|
-
return sanitized;
|
|
8349
|
-
}
|
|
8350
|
-
var SECRET_TEXT_PATTERNS = [
|
|
8351
|
-
{
|
|
8352
|
-
pattern: /\bsk-ant-(?:api03-)?[A-Za-z0-9_-]{32,}/g,
|
|
8353
|
-
replacement: "<ANTHROPIC_API_KEY_REDACTED>"
|
|
8354
|
-
},
|
|
8355
|
-
{
|
|
8356
|
-
pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/g,
|
|
8357
|
-
replacement: "<OPENAI_API_KEY_REDACTED>"
|
|
8358
|
-
},
|
|
8359
|
-
{
|
|
8360
|
-
pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
8361
|
-
replacement: "<GITHUB_PAT_REDACTED>"
|
|
8362
|
-
},
|
|
8363
|
-
{
|
|
8364
|
-
pattern: /\b(?:gh[opsu]|ghr)_[A-Za-z0-9]{30,}/g,
|
|
8365
|
-
replacement: "<GITHUB_TOKEN_REDACTED>"
|
|
8366
|
-
},
|
|
8367
|
-
{
|
|
8368
|
-
pattern: /\bhf_[A-Za-z0-9]{30,}/g,
|
|
8369
|
-
replacement: "<HUGGINGFACE_TOKEN_REDACTED>"
|
|
8370
|
-
},
|
|
8371
|
-
{
|
|
8372
|
-
pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
|
|
8373
|
-
replacement: "<AWS_ACCESS_KEY_ID_REDACTED>"
|
|
8374
|
-
},
|
|
8375
|
-
{
|
|
8376
|
-
pattern: /\bxox[abprsuvc]-[A-Za-z0-9-]{10,}/g,
|
|
8377
|
-
replacement: "<SLACK_TOKEN_REDACTED>"
|
|
8378
|
-
},
|
|
8379
|
-
{
|
|
8380
|
-
pattern: /\bAIza[A-Za-z0-9_-]{35}\b/g,
|
|
8381
|
-
replacement: "<GOOGLE_API_KEY_REDACTED>"
|
|
8382
|
-
},
|
|
8383
|
-
{
|
|
8384
|
-
pattern: /\b(Authorization\s*:\s*Bearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi,
|
|
8385
|
-
replacement: (_full, prefix) => `${prefix}<REDACTED:bearer>`
|
|
8386
|
-
},
|
|
8387
|
-
{
|
|
8388
|
-
pattern: /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
|
|
8389
|
-
replacement: "<JWT_REDACTED>"
|
|
8390
|
-
},
|
|
8391
|
-
{
|
|
8392
|
-
pattern: /(["'])([^"']*(?:key|token|secret|password|auth|bearer|credential)[^"']*)\1(\s*:\s*)(["'])([^"']*)\4/gi,
|
|
8393
|
-
replacement: (full, quote, key, separator, valueQuote, value) => isNonSecretScalarValue(value) ? full : `${quote}${key}${quote}${separator}${valueQuote}<REDACTED:${redactionTypeForKey(key)}>${valueQuote}`
|
|
8394
|
-
},
|
|
8395
|
-
{
|
|
8396
|
-
pattern: /\b([A-Za-z0-9_.-]*(?:key|token|secret|password|auth|bearer|credential)[A-Za-z0-9_.-]*)\s*=\s*([^\s'"`]+)/gi,
|
|
8397
|
-
replacement: (full, key, value) => isNonSecretScalarValue(value) ? full : `${key}=<REDACTED:${redactionTypeForKey(key)}>`
|
|
8398
|
-
}
|
|
8399
|
-
];
|
|
8400
|
-
function redactSecretText(value) {
|
|
8401
|
-
let redacted = value;
|
|
8402
|
-
for (const { pattern, replacement } of SECRET_TEXT_PATTERNS) {
|
|
8403
|
-
if (typeof replacement === "string") {
|
|
8404
|
-
redacted = redacted.replace(pattern, replacement);
|
|
8405
|
-
} else {
|
|
8406
|
-
redacted = redacted.replace(pattern, replacement);
|
|
8407
|
-
}
|
|
8408
|
-
}
|
|
8409
|
-
return redacted;
|
|
8410
|
-
}
|
|
8411
|
-
function sanitizeDiagnosticText(value) {
|
|
8412
|
-
return redactSecretText(sanitizePathString(value));
|
|
8413
|
-
}
|
|
8414
|
-
var SHAREABILITY_SENSITIVE_PATTERNS = [
|
|
8415
|
-
/\bC:\/Users\/[^/\s]+/i,
|
|
8416
|
-
/(?:^|\s)~\/[^\s]+/,
|
|
8417
|
-
/\b(?:api[_-]?key|secret|token|password|passwd|pwd|client[_-]?secret|access[_-]?key)\b\s*[:=]\s*\S+/i,
|
|
8418
|
-
/\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\b/i,
|
|
8419
|
-
/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
|
|
8420
|
-
/\b192\.168\.\d{1,3}\.\d{1,3}\b/,
|
|
8421
|
-
/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/
|
|
8422
|
-
];
|
|
8423
|
-
function hasShareabilitySensitiveText(text) {
|
|
8424
|
-
try {
|
|
8425
|
-
if (sanitizeDiagnosticText(text) !== text)
|
|
8426
|
-
return true;
|
|
8427
|
-
return SHAREABILITY_SENSITIVE_PATTERNS.some((pattern) => pattern.test(text));
|
|
8428
|
-
} catch {
|
|
8429
|
-
return true;
|
|
8430
|
-
}
|
|
8431
|
-
}
|
|
8432
|
-
|
|
8433
8287
|
// ../plugin/src/features/magic-context/fail-closed-block.ts
|
|
8434
8288
|
var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
|
|
8435
8289
|
var FAIL_CLOSED_REPROBE_EVERY_N = 5;
|
|
@@ -8656,7 +8510,7 @@ function createFailClosedController(options) {
|
|
|
8656
8510
|
import { execFileSync } from "node:child_process";
|
|
8657
8511
|
import { createHash } from "node:crypto";
|
|
8658
8512
|
import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
|
|
8659
|
-
import { homedir as
|
|
8513
|
+
import { homedir as homedir2 } from "node:os";
|
|
8660
8514
|
import path from "node:path";
|
|
8661
8515
|
var GIT_TIMEOUT_MS = 5000;
|
|
8662
8516
|
var TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
|
|
@@ -8670,7 +8524,7 @@ var dubiousOwnershipLoggedDirectories = new Set;
|
|
|
8670
8524
|
var dubiousOwnershipWarnedDirectories = new Set;
|
|
8671
8525
|
var transientGitIdentityReuseLoggedDirectories = new Set;
|
|
8672
8526
|
var execFileSyncForIdentity = execFileSync;
|
|
8673
|
-
var userHomeDirectoryForIdentity = () =>
|
|
8527
|
+
var userHomeDirectoryForIdentity = () => homedir2();
|
|
8674
8528
|
var nowMs = () => Date.now();
|
|
8675
8529
|
|
|
8676
8530
|
class ProjectIdentityError extends Error {
|
|
@@ -9026,7 +8880,7 @@ function scheduleAfterBootQuiet(task, additionalDelayMs = 0) {
|
|
|
9026
8880
|
// ../plugin/src/hooks/magic-context/read-session-formatting.ts
|
|
9027
8881
|
import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
9028
8882
|
import { createRequire } from "node:module";
|
|
9029
|
-
import { homedir as
|
|
8883
|
+
import { homedir as homedir3 } from "node:os";
|
|
9030
8884
|
import { dirname as dirname2, join as join2, resolve } from "node:path";
|
|
9031
8885
|
import { pathToFileURL } from "node:url";
|
|
9032
8886
|
|
|
@@ -9143,7 +8997,7 @@ var tokenizerLoadPromise;
|
|
|
9143
8997
|
var tokenizerWarningSent = false;
|
|
9144
8998
|
function tokenizerPackageRoots() {
|
|
9145
8999
|
const cwd = process.cwd();
|
|
9146
|
-
const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(
|
|
9000
|
+
const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir3(), ".cache"), "opencode");
|
|
9147
9001
|
const roots = [cwd, openCodeCache];
|
|
9148
9002
|
const candidates = [];
|
|
9149
9003
|
for (const root of roots) {
|
|
@@ -9961,6 +9815,7 @@ function closeQuietly(db) {
|
|
|
9961
9815
|
|
|
9962
9816
|
// ../plugin/src/features/magic-context/context-authority.ts
|
|
9963
9817
|
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
9818
|
+
var observedAuthorityRoutingByProject = new Map;
|
|
9964
9819
|
var moduleNoteEvaluationBridges = new Map;
|
|
9965
9820
|
function getModuleNoteEvaluationBridge(projectPath) {
|
|
9966
9821
|
return moduleNoteEvaluationBridges.get(projectPath);
|
|
@@ -10162,6 +10017,17 @@ function unescapeXml(s) {
|
|
|
10162
10017
|
return s.replace(/&/g, "&").replace(/'/g, "'").replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">");
|
|
10163
10018
|
}
|
|
10164
10019
|
|
|
10020
|
+
// ../plugin/src/shared/write-transaction-timing.ts
|
|
10021
|
+
var SLOW_WRITE_TRANSACTION_THRESHOLD_MS = 1000;
|
|
10022
|
+
function logSlowWriteTransaction(site, startedAt, thresholdMs = SLOW_WRITE_TRANSACTION_THRESHOLD_MS) {
|
|
10023
|
+
try {
|
|
10024
|
+
const durationMs = performance.now() - startedAt;
|
|
10025
|
+
if (durationMs < thresholdMs)
|
|
10026
|
+
return;
|
|
10027
|
+
log(`[magic-context] slow write transaction: site=${site} held=${durationMs.toFixed(1)}ms`);
|
|
10028
|
+
} catch {}
|
|
10029
|
+
}
|
|
10030
|
+
|
|
10165
10031
|
// ../plugin/src/features/magic-context/storage-schema-helpers.ts
|
|
10166
10032
|
function ensureColumn(db, table, column, definition) {
|
|
10167
10033
|
if (!/^[a-z][a-z0-9_]*$/.test(table) || !/^[a-z][a-z0-9_]*$/.test(column) || !/^[A-Z0-9_"'(),[\]\s]+$/i.test(definition)) {
|
|
@@ -12709,6 +12575,15 @@ var MIGRATIONS = [
|
|
|
12709
12575
|
);
|
|
12710
12576
|
`);
|
|
12711
12577
|
}
|
|
12578
|
+
},
|
|
12579
|
+
{
|
|
12580
|
+
version: 82,
|
|
12581
|
+
description: "record the origin of memory file-independent mappings",
|
|
12582
|
+
up(db) {
|
|
12583
|
+
if (!tableExists2(db, "memory_verifications"))
|
|
12584
|
+
return;
|
|
12585
|
+
ensureColumn(db, "memory_verifications", "mapping_origin", "TEXT NOT NULL DEFAULT 'mapper'");
|
|
12586
|
+
}
|
|
12712
12587
|
}
|
|
12713
12588
|
];
|
|
12714
12589
|
var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
|
|
@@ -12754,6 +12629,7 @@ function runMigrations(db) {
|
|
|
12754
12629
|
let migration;
|
|
12755
12630
|
let currentVersion = 0;
|
|
12756
12631
|
try {
|
|
12632
|
+
const transactionStartedAt = performance.now();
|
|
12757
12633
|
const applied = db.transaction(() => {
|
|
12758
12634
|
currentVersion = getCurrentVersion(db);
|
|
12759
12635
|
migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
|
|
@@ -12768,6 +12644,7 @@ function runMigrations(db) {
|
|
|
12768
12644
|
db.prepare("INSERT INTO schema_migrations (version, description, applied_at) VALUES (?, ?, ?)").run(migration.version, migration.description, Date.now());
|
|
12769
12645
|
return true;
|
|
12770
12646
|
}).immediate();
|
|
12647
|
+
logSlowWriteTransaction("migration-runner", transactionStartedAt);
|
|
12771
12648
|
if (!applied || !migration)
|
|
12772
12649
|
break;
|
|
12773
12650
|
if (migration.version <= 61)
|
|
@@ -12792,7 +12669,9 @@ function runMigrations(db) {
|
|
|
12792
12669
|
}
|
|
12793
12670
|
if (touchedLegacyAuthorityBatch) {
|
|
12794
12671
|
try {
|
|
12672
|
+
const transactionStartedAt = performance.now();
|
|
12795
12673
|
db.transaction(() => installLatestAuthorityTriggers(db)).immediate();
|
|
12674
|
+
logSlowWriteTransaction("migration-runner", transactionStartedAt);
|
|
12796
12675
|
} catch (error) {
|
|
12797
12676
|
throw new Error(`Migration authority-trigger postcondition failed: ${error instanceof Error ? error.message : String(error)}. Database may need manual repair.`);
|
|
12798
12677
|
}
|
|
@@ -13143,7 +13022,7 @@ function getSchemaFenceRejection() {
|
|
|
13143
13022
|
function getMigrationOnOpenRefusal() {
|
|
13144
13023
|
return lastMigrationOnOpenRefusal;
|
|
13145
13024
|
}
|
|
13146
|
-
var LATEST_SUPPORTED_VERSION =
|
|
13025
|
+
var LATEST_SUPPORTED_VERSION = 82;
|
|
13147
13026
|
var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
|
|
13148
13027
|
var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
|
|
13149
13028
|
var storagePermissionFs = defaultStoragePermissionFs;
|
|
@@ -13892,8 +13771,10 @@ function initializeDatabase(db) {
|
|
|
13892
13771
|
-- verified_at=0 means "mapped (files known) but not yet content-verified".
|
|
13893
13772
|
-- map-memories sets mapped_at + verified_at=0; verify sets verified_at=now.
|
|
13894
13773
|
verified_at INTEGER NOT NULL,
|
|
13895
|
-
|
|
13896
|
-
|
|
13774
|
+
mapped_at INTEGER NOT NULL DEFAULT 0,
|
|
13775
|
+
-- Distinguishes mapper-authored independence from a host rejection fallback.
|
|
13776
|
+
mapping_origin TEXT NOT NULL DEFAULT 'mapper',
|
|
13777
|
+
PRIMARY KEY (memory_id, file_path)
|
|
13897
13778
|
);
|
|
13898
13779
|
CREATE INDEX IF NOT EXISTS idx_memory_verifications_memory ON memory_verifications(memory_id);
|
|
13899
13780
|
|
|
@@ -15154,6 +15035,13 @@ function clearCachedM0M1(db, sessionId) {
|
|
|
15154
15035
|
var emergencyRecoveryArmedSessions = new Set;
|
|
15155
15036
|
var emergencyRecoveryArmedAtBySession = new Map;
|
|
15156
15037
|
var providerOverflowReconfirmedSessions = new Set;
|
|
15038
|
+
function describeProtectedTailDrainBudgetSkip(result) {
|
|
15039
|
+
const state = result.budgetState;
|
|
15040
|
+
if (!state)
|
|
15041
|
+
return "historian skip: internal drain budget spent";
|
|
15042
|
+
const resetMinutes = Math.max(1, Math.ceil(state.resetInMs / 60000));
|
|
15043
|
+
return `historian skip: internal drain budget spent (${state.spentTokens}/${state.limitTokens} tokens; resets in ${resetMinutes}m)`;
|
|
15044
|
+
}
|
|
15157
15045
|
var CAS_RETRY_LIMIT = 5;
|
|
15158
15046
|
var AUTO_SEARCH_NO_HINT_REASONS = new Set([
|
|
15159
15047
|
"below-threshold",
|
|
@@ -15500,19 +15388,28 @@ function reserveProtectedTailDrainTokens(args) {
|
|
|
15500
15388
|
const now = args.now ?? Date.now();
|
|
15501
15389
|
const requested = Math.max(0, Math.floor(args.trueRawTokens));
|
|
15502
15390
|
if (requested === 0) {
|
|
15503
|
-
return {
|
|
15391
|
+
return {
|
|
15392
|
+
ok: true,
|
|
15393
|
+
reservedTokens: 0,
|
|
15394
|
+
overQuotaBypass: false,
|
|
15395
|
+
reservation: null,
|
|
15396
|
+
budgetState: null
|
|
15397
|
+
};
|
|
15504
15398
|
}
|
|
15505
15399
|
let result = {
|
|
15506
15400
|
ok: false,
|
|
15507
15401
|
reservedTokens: 0,
|
|
15508
15402
|
overQuotaBypass: false,
|
|
15509
15403
|
reservation: null,
|
|
15510
|
-
|
|
15404
|
+
budgetState: null,
|
|
15405
|
+
skippedReason: "internal drain budget spent"
|
|
15511
15406
|
};
|
|
15512
15407
|
args.db.transaction(() => {
|
|
15513
15408
|
ensureSessionMetaRow(args.db, args.sessionId);
|
|
15514
15409
|
let meta = loadProtectedTailMeta(args.db, args.sessionId);
|
|
15515
|
-
|
|
15410
|
+
const windowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
15411
|
+
const windowExpired = windowStartedAt <= 0 || windowStartedAt > now || now - windowStartedAt >= DRAIN_WINDOW_MS;
|
|
15412
|
+
if (windowExpired) {
|
|
15516
15413
|
args.db.prepare(`UPDATE session_meta
|
|
15517
15414
|
SET protected_tail_drain_window_started_at = ?, protected_tail_drain_tokens = 0
|
|
15518
15415
|
WHERE session_id = ?`).run(now, args.sessionId);
|
|
@@ -15537,22 +15434,35 @@ function reserveProtectedTailDrainTokens(args) {
|
|
|
15537
15434
|
const remaining = Math.max(0, budget - meta.protectedTailDrainTokens);
|
|
15538
15435
|
let reserved = Math.min(requested, args.perRunCap, remaining);
|
|
15539
15436
|
let bypass = false;
|
|
15540
|
-
const inFailureBackoff = meta.historianDrainFailureAt > 0 && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
|
|
15437
|
+
const inFailureBackoff = meta.historianDrainFailureAt > 0 && meta.historianDrainFailureAt <= now && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
|
|
15541
15438
|
if (reserved <= 0 && latchActive && !inFailureBackoff) {
|
|
15542
15439
|
reserved = Math.min(requested, args.perRunCap);
|
|
15543
15440
|
bypass = true;
|
|
15544
15441
|
}
|
|
15545
|
-
|
|
15442
|
+
const activeWindowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
15443
|
+
const budgetState = (spentTokens) => ({
|
|
15444
|
+
windowStartedAt: activeWindowStartedAt,
|
|
15445
|
+
resetsAt: activeWindowStartedAt + DRAIN_WINDOW_MS,
|
|
15446
|
+
resetInMs: Math.max(0, activeWindowStartedAt + DRAIN_WINDOW_MS - now),
|
|
15447
|
+
spentTokens,
|
|
15448
|
+
limitTokens: budget
|
|
15449
|
+
});
|
|
15450
|
+
if (reserved <= 0) {
|
|
15451
|
+
result = {
|
|
15452
|
+
...result,
|
|
15453
|
+
budgetState: budgetState(meta.protectedTailDrainTokens)
|
|
15454
|
+
};
|
|
15546
15455
|
return;
|
|
15456
|
+
}
|
|
15547
15457
|
args.db.prepare(`UPDATE session_meta
|
|
15548
|
-
SET
|
|
15549
|
-
|
|
15550
|
-
WHERE session_id = ?`).run(now, reserved, args.sessionId);
|
|
15458
|
+
SET protected_tail_drain_tokens = COALESCE(protected_tail_drain_tokens, 0) + ?
|
|
15459
|
+
WHERE session_id = ?`).run(reserved, args.sessionId);
|
|
15551
15460
|
result = {
|
|
15552
15461
|
ok: true,
|
|
15553
15462
|
reservedTokens: reserved,
|
|
15554
15463
|
overQuotaBypass: bypass,
|
|
15555
|
-
reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved }
|
|
15464
|
+
reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved },
|
|
15465
|
+
budgetState: budgetState(meta.protectedTailDrainTokens + reserved)
|
|
15556
15466
|
};
|
|
15557
15467
|
})();
|
|
15558
15468
|
return result;
|
|
@@ -15626,19 +15536,38 @@ function parseChannel1NudgeState(raw) {
|
|
|
15626
15536
|
try {
|
|
15627
15537
|
const parsed = JSON.parse(raw);
|
|
15628
15538
|
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
15629
|
-
|
|
15539
|
+
const state = {
|
|
15630
15540
|
level: normalizeLastNudgeLevel(parsed.level),
|
|
15631
15541
|
ordinal: typeof parsed.ordinal === "number" ? Math.max(0, Math.round(parsed.ordinal)) : 0
|
|
15632
15542
|
};
|
|
15543
|
+
if (parsed.postReduceGracePending === true)
|
|
15544
|
+
state.postReduceGracePending = true;
|
|
15545
|
+
if (typeof parsed.postReduceGraceBaselineU === "number" && Number.isFinite(parsed.postReduceGraceBaselineU)) {
|
|
15546
|
+
state.postReduceGraceBaselineU = Math.max(0, Math.round(parsed.postReduceGraceBaselineU));
|
|
15547
|
+
}
|
|
15548
|
+
const preLevel = normalizeLastNudgeLevel(parsed.postReduceGracePreLevel);
|
|
15549
|
+
if (preLevel !== "" || parsed.postReduceGracePreLevel === "") {
|
|
15550
|
+
state.postReduceGracePreLevel = preLevel;
|
|
15551
|
+
}
|
|
15552
|
+
return state;
|
|
15633
15553
|
}
|
|
15634
15554
|
} catch {}
|
|
15635
15555
|
return { level: normalizeLastNudgeLevel(raw), ordinal: 0 };
|
|
15636
15556
|
}
|
|
15637
15557
|
function serializeChannel1NudgeState(value) {
|
|
15638
|
-
|
|
15558
|
+
const serialized = {
|
|
15639
15559
|
level: normalizeLastNudgeLevel(value.level),
|
|
15640
15560
|
ordinal: Math.max(0, Math.round(value.ordinal))
|
|
15641
|
-
}
|
|
15561
|
+
};
|
|
15562
|
+
if (value.postReduceGracePending === true)
|
|
15563
|
+
serialized.postReduceGracePending = true;
|
|
15564
|
+
if (value.postReduceGraceBaselineU !== undefined) {
|
|
15565
|
+
serialized.postReduceGraceBaselineU = Math.max(0, Math.round(value.postReduceGraceBaselineU));
|
|
15566
|
+
}
|
|
15567
|
+
if (value.postReduceGracePreLevel !== undefined) {
|
|
15568
|
+
serialized.postReduceGracePreLevel = normalizeLastNudgeLevel(value.postReduceGracePreLevel);
|
|
15569
|
+
}
|
|
15570
|
+
return JSON.stringify(serialized);
|
|
15642
15571
|
}
|
|
15643
15572
|
function getLastNudgeUndropped(db, sessionId) {
|
|
15644
15573
|
const result = db.prepare("SELECT last_nudge_undropped FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
@@ -15660,20 +15589,36 @@ function setChannel1NudgeState(db, sessionId, value) {
|
|
|
15660
15589
|
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
|
|
15661
15590
|
})();
|
|
15662
15591
|
}
|
|
15663
|
-
function
|
|
15664
|
-
db.transaction(() => {
|
|
15592
|
+
function markChannel1PostReduceGracePending(db, sessionId) {
|
|
15593
|
+
return db.transaction(() => {
|
|
15665
15594
|
ensureSessionMetaRow(db, sessionId);
|
|
15666
|
-
|
|
15595
|
+
const current = getChannel1NudgeState(db, sessionId);
|
|
15596
|
+
const next = {
|
|
15597
|
+
level: current.level,
|
|
15598
|
+
ordinal: current.ordinal,
|
|
15599
|
+
postReduceGracePending: true,
|
|
15600
|
+
postReduceGracePreLevel: current.level
|
|
15601
|
+
};
|
|
15602
|
+
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
|
|
15603
|
+
return next;
|
|
15667
15604
|
})();
|
|
15668
15605
|
}
|
|
15669
|
-
function
|
|
15670
|
-
|
|
15671
|
-
db.transaction(() => {
|
|
15606
|
+
function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
|
|
15607
|
+
return db.transaction(() => {
|
|
15672
15608
|
ensureSessionMetaRow(db, sessionId);
|
|
15673
|
-
const
|
|
15674
|
-
|
|
15609
|
+
const current = getChannel1NudgeState(db, sessionId);
|
|
15610
|
+
if (current.postReduceGracePending !== true)
|
|
15611
|
+
return current;
|
|
15612
|
+
const baselineU = Math.max(0, Math.round(measuredUndropped));
|
|
15613
|
+
const next = {
|
|
15614
|
+
level: current.level,
|
|
15615
|
+
ordinal: current.ordinal,
|
|
15616
|
+
postReduceGraceBaselineU: baselineU,
|
|
15617
|
+
postReduceGracePreLevel: current.postReduceGracePreLevel ?? current.level
|
|
15618
|
+
};
|
|
15619
|
+
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
|
|
15620
|
+
return next;
|
|
15675
15621
|
})();
|
|
15676
|
-
return changed;
|
|
15677
15622
|
}
|
|
15678
15623
|
function isChannel2StateRow(row) {
|
|
15679
15624
|
return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
|
|
@@ -16473,9 +16418,11 @@ function retryPendingSessionCleanups(db, limit = 200) {
|
|
|
16473
16418
|
return { attempted: rows.length, cleared, failedSessionIds };
|
|
16474
16419
|
}
|
|
16475
16420
|
function clearSession(db, sessionId) {
|
|
16421
|
+
const transactionStartedAt = performance.now();
|
|
16476
16422
|
db.transaction(() => {
|
|
16477
16423
|
deleteSessionScopedRows(db, [sessionId]);
|
|
16478
16424
|
})();
|
|
16425
|
+
logSlowWriteTransaction("clear-session", transactionStartedAt);
|
|
16479
16426
|
}
|
|
16480
16427
|
// ../plugin/src/hooks/magic-context/todo-view.ts
|
|
16481
16428
|
import { createHash as createHash4 } from "node:crypto";
|
|
@@ -17356,15 +17303,32 @@ function buildToolArcs(messages) {
|
|
|
17356
17303
|
}
|
|
17357
17304
|
return arcs.sort((a, b) => a.invOrdinal - b.invOrdinal || (a.resOrdinal ?? Number.MAX_SAFE_INTEGER) - (b.resOrdinal ?? Number.MAX_SAFE_INTEGER));
|
|
17358
17305
|
}
|
|
17306
|
+
function fenceBoundaryForCompletedToolArcs(candidate, arcs, publicationFloorOrdinal) {
|
|
17307
|
+
const completed = arcs.filter((arc) => arc.resOrdinal !== null).map((arc) => ({ invocation: arc.invOrdinal, result: arc.resOrdinal }));
|
|
17308
|
+
const component = completed.filter((arc) => completedToolArcCrossesBoundary(arc.invocation, arc.result, candidate));
|
|
17309
|
+
if (component.length === 0)
|
|
17310
|
+
return candidate;
|
|
17311
|
+
for (let pass = 0;pass <= completed.length; pass += 1) {
|
|
17312
|
+
const minInvocation2 = Math.min(...component.map((arc) => arc.invocation));
|
|
17313
|
+
const maxResult2 = Math.max(...component.map((arc) => arc.result));
|
|
17314
|
+
const before = component.length;
|
|
17315
|
+
for (const arc of completed) {
|
|
17316
|
+
if (arc.invocation <= maxResult2 && arc.result >= minInvocation2 && !component.includes(arc)) {
|
|
17317
|
+
component.push(arc);
|
|
17318
|
+
}
|
|
17319
|
+
}
|
|
17320
|
+
if (component.length === before)
|
|
17321
|
+
break;
|
|
17322
|
+
}
|
|
17323
|
+
const minInvocation = Math.min(...component.map((arc) => arc.invocation));
|
|
17324
|
+
const maxResult = Math.max(...component.map((arc) => arc.result));
|
|
17325
|
+
return minInvocation < publicationFloorOrdinal ? maxResult + 1 : minInvocation;
|
|
17326
|
+
}
|
|
17359
17327
|
function fenceBoundaryForToolArcs(candidate, arcs, lastCompartmentEndOrdinal, recentOpenArcCutoff) {
|
|
17360
|
-
|
|
17328
|
+
const boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
|
|
17361
17329
|
for (const arc of arcs) {
|
|
17362
|
-
if (arc.resOrdinal !== null)
|
|
17363
|
-
if (completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, boundary)) {
|
|
17364
|
-
boundary = arc.resOrdinal + 1;
|
|
17365
|
-
}
|
|
17330
|
+
if (arc.resOrdinal !== null)
|
|
17366
17331
|
continue;
|
|
17367
|
-
}
|
|
17368
17332
|
if (arc.invOrdinal < recentOpenArcCutoff)
|
|
17369
17333
|
continue;
|
|
17370
17334
|
if (arc.invOrdinal >= lastCompartmentEndOrdinal + 1 && arc.invOrdinal < boundary) {
|
|
@@ -19806,47 +19770,74 @@ function decideChannel1(input) {
|
|
|
19806
19770
|
const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
|
|
19807
19771
|
const undroppedTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
|
|
19808
19772
|
const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
|
|
19809
|
-
const
|
|
19810
|
-
|
|
19811
|
-
|
|
19812
|
-
|
|
19773
|
+
const previousLevel = input.lastNudgeLevel;
|
|
19774
|
+
let lastNudge = Math.max(0, input.lastNudgeUndropped);
|
|
19775
|
+
let nextLevel = previousLevel;
|
|
19776
|
+
let clearPostReduceGrace = false;
|
|
19777
|
+
const quiet = (level2 = "gentle") => ({
|
|
19813
19778
|
fire: false,
|
|
19814
|
-
|
|
19779
|
+
sticky: false,
|
|
19780
|
+
level: level2,
|
|
19815
19781
|
undroppedTokens,
|
|
19816
19782
|
tailTokens,
|
|
19817
19783
|
severity,
|
|
19818
19784
|
nextLastNudge: lastNudge,
|
|
19819
|
-
nextLastNudgeLevel:
|
|
19785
|
+
nextLastNudgeLevel: nextLevel,
|
|
19786
|
+
clearPostReduceGrace
|
|
19820
19787
|
});
|
|
19821
19788
|
if (input.evaluable === false || input.generationInvalidated === true)
|
|
19822
19789
|
return quiet();
|
|
19823
|
-
if (input.hasRecentReduce)
|
|
19824
|
-
return quiet();
|
|
19825
|
-
if (tailTokens < CHANNEL1_MIN_TOKENS)
|
|
19790
|
+
if (input.hasRecentReduce || input.postReduceGracePending)
|
|
19826
19791
|
return quiet();
|
|
19827
|
-
|
|
19828
|
-
|
|
19829
|
-
|
|
19830
|
-
|
|
19831
|
-
|
|
19832
|
-
|
|
19833
|
-
|
|
19834
|
-
|
|
19835
|
-
|
|
19836
|
-
|
|
19837
|
-
|
|
19838
|
-
const
|
|
19839
|
-
|
|
19840
|
-
|
|
19792
|
+
let level = "";
|
|
19793
|
+
if (tailTokens >= CHANNEL1_MIN_TOKENS && undroppedTokens >= CHANNEL1_FLOOR_TOKENS && severity >= S_GENTLE) {
|
|
19794
|
+
if (severity >= S_URGENT)
|
|
19795
|
+
level = "urgent";
|
|
19796
|
+
else if (severity >= S_FIRM)
|
|
19797
|
+
level = "firm";
|
|
19798
|
+
else
|
|
19799
|
+
level = "gentle";
|
|
19800
|
+
}
|
|
19801
|
+
const previousRank = previousLevel === "" ? 0 : LEVEL_RANK[previousLevel];
|
|
19802
|
+
const currentRank = level === "" ? 0 : LEVEL_RANK[level];
|
|
19803
|
+
const graceBaseline = input.postReduceGraceBaselineU;
|
|
19804
|
+
if (graceBaseline !== undefined) {
|
|
19805
|
+
const preReduceLevel = input.postReduceGracePreLevel ?? previousLevel;
|
|
19806
|
+
const preReduceRank = preReduceLevel === "" ? 0 : LEVEL_RANK[preReduceLevel];
|
|
19807
|
+
const regrowthReached = undroppedTokens - Math.max(0, graceBaseline) >= channel1RefireTokens(tailTokens);
|
|
19808
|
+
const escalatedAbovePreReduceBand = currentRank > preReduceRank;
|
|
19809
|
+
if (!regrowthReached && !escalatedAbovePreReduceBand) {
|
|
19810
|
+
return quiet(level === "" ? "gentle" : level);
|
|
19811
|
+
}
|
|
19812
|
+
clearPostReduceGrace = true;
|
|
19813
|
+
}
|
|
19814
|
+
if (level === "") {
|
|
19815
|
+
nextLevel = "";
|
|
19816
|
+
lastNudge = 0;
|
|
19841
19817
|
return quiet();
|
|
19818
|
+
}
|
|
19819
|
+
if (currentRank < previousRank) {
|
|
19820
|
+
nextLevel = level;
|
|
19821
|
+
lastNudge = undroppedTokens;
|
|
19822
|
+
return quiet(level);
|
|
19823
|
+
}
|
|
19824
|
+
const crossedFromBelow = currentRank > previousRank;
|
|
19825
|
+
const cadenceReached = currentRank === previousRank && undroppedTokens - lastNudge >= channel1RefireTokens(tailTokens);
|
|
19826
|
+
const currentTurn = input.currentRealUserTurnCount;
|
|
19827
|
+
const lastFireTurn = input.lastFireOrdinal;
|
|
19828
|
+
const stickyTurnGapReached = currentTurn === undefined || lastFireTurn === undefined || lastFireTurn > currentTurn || currentTurn - lastFireTurn >= CHANNEL1_STICKY_REAL_USER_TURN_GAP;
|
|
19829
|
+
if (!crossedFromBelow && (!cadenceReached || !stickyTurnGapReached))
|
|
19830
|
+
return quiet(level);
|
|
19842
19831
|
return {
|
|
19843
19832
|
fire: true,
|
|
19833
|
+
sticky: !crossedFromBelow,
|
|
19844
19834
|
level,
|
|
19845
19835
|
undroppedTokens,
|
|
19846
19836
|
tailTokens,
|
|
19847
19837
|
severity,
|
|
19848
19838
|
nextLastNudge: undroppedTokens,
|
|
19849
|
-
nextLastNudgeLevel: level
|
|
19839
|
+
nextLastNudgeLevel: level,
|
|
19840
|
+
clearPostReduceGrace
|
|
19850
19841
|
};
|
|
19851
19842
|
}
|
|
19852
19843
|
var CHANNEL2_SEVERITY_THRESHOLD = 0.75;
|
|
@@ -19883,44 +19874,42 @@ function formatOldestReclaimableHint(hint) {
|
|
|
19883
19874
|
return rendered.length > 0 ? `
|
|
19884
19875
|
oldest reclaimable: ${rendered}.` : "";
|
|
19885
19876
|
}
|
|
19886
|
-
function
|
|
19887
|
-
|
|
19888
|
-
|
|
19877
|
+
function reclaimableToolOutputCount(parts) {
|
|
19878
|
+
return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
|
|
19879
|
+
}
|
|
19880
|
+
function formatReclaimableOutputSummary(count, tokens) {
|
|
19881
|
+
const outputCount = Math.max(0, Math.floor(count));
|
|
19882
|
+
const outputs = outputCount === 0 ? "spent tool outputs" : `${outputCount} spent tool output${outputCount === 1 ? "" : "s"}`;
|
|
19883
|
+
return `${outputs} (~${approxThousands(tokens)} tokens)`;
|
|
19884
|
+
}
|
|
19885
|
+
function buildChannel2Reminder(undroppedTokens, reclaimableToolOutputs, hint) {
|
|
19886
|
+
const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
|
|
19889
19887
|
const hintText = formatOldestReclaimableHint(hint);
|
|
19890
19888
|
return `<system-reminder>
|
|
19891
|
-
` + `Routine housekeeping:
|
|
19889
|
+
` + `Routine housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.${hintText}
|
|
19892
19890
|
` + `</system-reminder>`;
|
|
19893
19891
|
}
|
|
19894
|
-
var CHANNEL1_STICKY_REAL_USER_TURN_GAP =
|
|
19895
|
-
function
|
|
19896
|
-
|
|
19897
|
-
return false;
|
|
19898
|
-
if (input.lastOrdinal > input.currentRealUserTurnCount)
|
|
19899
|
-
return false;
|
|
19900
|
-
const gap = input.currentRealUserTurnCount - input.lastOrdinal;
|
|
19901
|
-
return gap >= 0 && gap < CHANNEL1_STICKY_REAL_USER_TURN_GAP;
|
|
19902
|
-
}
|
|
19903
|
-
function buildChannel1Reminder(level, undroppedTokens, usableWindowTokens, hint, sticky = false) {
|
|
19892
|
+
var CHANNEL1_STICKY_REAL_USER_TURN_GAP = 5;
|
|
19893
|
+
function buildChannel1Reminder(level, undroppedTokens, reclaimableToolOutputs, hint, sticky = false) {
|
|
19894
|
+
const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
|
|
19904
19895
|
const hintText = formatOldestReclaimableHint(hint);
|
|
19905
19896
|
if (sticky) {
|
|
19906
19897
|
return `
|
|
19907
19898
|
|
|
19908
19899
|
<system-reminder>
|
|
19909
|
-
Reminder:
|
|
19900
|
+
Reminder: ${summary} are still reclaimable — ctx_reduce them at a natural stopping point.${hintText}
|
|
19910
19901
|
</system-reminder>`;
|
|
19911
19902
|
}
|
|
19912
|
-
const amount = approxThousands(undroppedTokens);
|
|
19913
|
-
const usableWindow = approxThousands(usableWindowTokens);
|
|
19914
19903
|
let body;
|
|
19915
19904
|
switch (level) {
|
|
19916
19905
|
case "gentle":
|
|
19917
|
-
body = `Housekeeping:
|
|
19906
|
+
body = `Housekeeping: ${summary} are reclaimable — drop the ones you have already processed with ctx_reduce at a natural stopping point.`;
|
|
19918
19907
|
break;
|
|
19919
19908
|
case "firm":
|
|
19920
|
-
body = `Housekeeping:
|
|
19909
|
+
body = `Housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.`;
|
|
19921
19910
|
break;
|
|
19922
19911
|
case "urgent":
|
|
19923
|
-
body = `Housekeeping backlog:
|
|
19912
|
+
body = `Housekeeping backlog: ${summary} are reclaimable — a ctx_reduce pass is due.`;
|
|
19924
19913
|
break;
|
|
19925
19914
|
}
|
|
19926
19915
|
return `
|
|
@@ -19981,8 +19970,8 @@ function planEmergencyDrop(input) {
|
|
|
19981
19970
|
if (!Number.isFinite(currentTotalInputTokens) || currentTotalInputTokens <= 0) {
|
|
19982
19971
|
return noop("unknown-usage");
|
|
19983
19972
|
}
|
|
19984
|
-
if (hasPriorDrop
|
|
19985
|
-
return noop(
|
|
19973
|
+
if (hasPriorDrop) {
|
|
19974
|
+
return noop(`pressure-episode-latched (prior sample ${priorInputSample}; awaiting exit or independent bust)`);
|
|
19986
19975
|
}
|
|
19987
19976
|
let tailTokens = 0;
|
|
19988
19977
|
for (const tag of floorTags) {
|
|
@@ -20111,6 +20100,7 @@ function updateTagByteSize(db, sessionId, tagNumber, newByteSize) {
|
|
|
20111
20100
|
getUpdateTagByteSizeStatement(db).run(newByteSize, sessionId, tagNumber);
|
|
20112
20101
|
}
|
|
20113
20102
|
var CONTENT_ID_SUFFIX = /:(?:p|file)\d+$/;
|
|
20103
|
+
var recentTagOwnerStatements = new WeakMap;
|
|
20114
20104
|
function ownerMessageIdForTagRow(row) {
|
|
20115
20105
|
if (row.type === "tool") {
|
|
20116
20106
|
return row.tool_owner_message_id ?? row.message_id;
|
|
@@ -21220,22 +21210,28 @@ function getToolCallIds(content) {
|
|
|
21220
21210
|
}
|
|
21221
21211
|
return ids;
|
|
21222
21212
|
}
|
|
21223
|
-
function
|
|
21213
|
+
function readPiSessionSnapshot(ctx) {
|
|
21224
21214
|
const sm = ctx.sessionManager;
|
|
21225
21215
|
if (sm === undefined)
|
|
21226
|
-
return [];
|
|
21216
|
+
return { branchEntries: [], rawMessages: [] };
|
|
21227
21217
|
const getBranch = sm.getBranch;
|
|
21228
21218
|
if (typeof getBranch !== "function")
|
|
21229
|
-
return [];
|
|
21219
|
+
return { branchEntries: [], rawMessages: [] };
|
|
21230
21220
|
let entries;
|
|
21231
21221
|
try {
|
|
21232
21222
|
entries = getBranch.call(sm);
|
|
21233
21223
|
} catch {
|
|
21234
|
-
return [];
|
|
21224
|
+
return { branchEntries: [], rawMessages: [] };
|
|
21235
21225
|
}
|
|
21236
21226
|
if (!Array.isArray(entries))
|
|
21237
|
-
return [];
|
|
21238
|
-
return
|
|
21227
|
+
return { branchEntries: [], rawMessages: [] };
|
|
21228
|
+
return {
|
|
21229
|
+
branchEntries: entries,
|
|
21230
|
+
rawMessages: convertEntriesToRawMessages(entries)
|
|
21231
|
+
};
|
|
21232
|
+
}
|
|
21233
|
+
function readPiSessionMessages(ctx) {
|
|
21234
|
+
return readPiSessionSnapshot(ctx).rawMessages;
|
|
21239
21235
|
}
|
|
21240
21236
|
function findLastModelKeyFromBranch(entries) {
|
|
21241
21237
|
if (!Array.isArray(entries))
|
|
@@ -21785,7 +21781,7 @@ function migrateLegacyExperimental(rawConfig, warnings) {
|
|
|
21785
21781
|
}
|
|
21786
21782
|
|
|
21787
21783
|
// ../plugin/src/config/schema/magic-context.ts
|
|
21788
|
-
import { homedir as
|
|
21784
|
+
import { homedir as homedir4 } from "node:os";
|
|
21789
21785
|
|
|
21790
21786
|
// ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
|
|
21791
21787
|
var exports_external = {};
|
|
@@ -22412,7 +22408,7 @@ __export(exports_util, {
|
|
|
22412
22408
|
createTransparentProxy: () => createTransparentProxy,
|
|
22413
22409
|
defineLazy: () => defineLazy,
|
|
22414
22410
|
esc: () => esc,
|
|
22415
|
-
escapeRegex: () =>
|
|
22411
|
+
escapeRegex: () => escapeRegex,
|
|
22416
22412
|
explicitlyAborted: () => explicitlyAborted,
|
|
22417
22413
|
extend: () => extend,
|
|
22418
22414
|
finalizeIssue: () => finalizeIssue,
|
|
@@ -22689,7 +22685,7 @@ var primitiveTypes = /* @__PURE__ */ new Set([
|
|
|
22689
22685
|
"symbol",
|
|
22690
22686
|
"undefined"
|
|
22691
22687
|
]);
|
|
22692
|
-
function
|
|
22688
|
+
function escapeRegex(str) {
|
|
22693
22689
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
22694
22690
|
}
|
|
22695
22691
|
function clone(inst, def, params) {
|
|
@@ -23399,7 +23395,7 @@ function emoji() {
|
|
|
23399
23395
|
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
|
|
23400
23396
|
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
|
|
23401
23397
|
var mac = (delimiter) => {
|
|
23402
|
-
const escapedDelim =
|
|
23398
|
+
const escapedDelim = escapeRegex(delimiter ?? ":");
|
|
23403
23399
|
return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
|
|
23404
23400
|
};
|
|
23405
23401
|
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
|
|
@@ -23900,7 +23896,7 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins
|
|
|
23900
23896
|
});
|
|
23901
23897
|
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
|
|
23902
23898
|
$ZodCheck.init(inst, def);
|
|
23903
|
-
const escapedRegex =
|
|
23899
|
+
const escapedRegex = escapeRegex(def.includes);
|
|
23904
23900
|
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
|
|
23905
23901
|
def.pattern = pattern;
|
|
23906
23902
|
inst._zod.onattach.push((inst2) => {
|
|
@@ -23924,7 +23920,7 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst,
|
|
|
23924
23920
|
});
|
|
23925
23921
|
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
|
|
23926
23922
|
$ZodCheck.init(inst, def);
|
|
23927
|
-
const pattern = new RegExp(`^${
|
|
23923
|
+
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
|
|
23928
23924
|
def.pattern ?? (def.pattern = pattern);
|
|
23929
23925
|
inst._zod.onattach.push((inst2) => {
|
|
23930
23926
|
const bag = inst2._zod.bag;
|
|
@@ -23947,7 +23943,7 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i
|
|
|
23947
23943
|
});
|
|
23948
23944
|
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
|
|
23949
23945
|
$ZodCheck.init(inst, def);
|
|
23950
|
-
const pattern = new RegExp(`.*${
|
|
23946
|
+
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
|
|
23951
23947
|
def.pattern ?? (def.pattern = pattern);
|
|
23952
23948
|
inst._zod.onattach.push((inst2) => {
|
|
23953
23949
|
const bag = inst2._zod.bag;
|
|
@@ -25594,7 +25590,7 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
|
|
|
25594
25590
|
const values = getEnumValues(def.entries);
|
|
25595
25591
|
const valuesSet = new Set(values);
|
|
25596
25592
|
inst._zod.values = valuesSet;
|
|
25597
|
-
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ?
|
|
25593
|
+
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
|
|
25598
25594
|
inst._zod.parse = (payload, _ctx) => {
|
|
25599
25595
|
const input = payload.value;
|
|
25600
25596
|
if (valuesSet.has(input)) {
|
|
@@ -25616,7 +25612,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
|
|
|
25616
25612
|
}
|
|
25617
25613
|
const values = new Set(def.values);
|
|
25618
25614
|
inst._zod.values = values;
|
|
25619
|
-
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ?
|
|
25615
|
+
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
|
|
25620
25616
|
inst._zod.parse = (payload, _ctx) => {
|
|
25621
25617
|
const input = payload.value;
|
|
25622
25618
|
if (values.has(input)) {
|
|
@@ -25981,7 +25977,7 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i
|
|
|
25981
25977
|
const end = source.endsWith("$") ? source.length - 1 : source.length;
|
|
25982
25978
|
regexParts.push(source.slice(start, end));
|
|
25983
25979
|
} else if (part === null || primitiveTypes.has(typeof part)) {
|
|
25984
|
-
regexParts.push(
|
|
25980
|
+
regexParts.push(escapeRegex(`${part}`));
|
|
25985
25981
|
} else {
|
|
25986
25982
|
throw new Error(`Invalid template literal part: ${part}`);
|
|
25987
25983
|
}
|
|
@@ -36557,9 +36553,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
|
|
|
36557
36553
|
function expandConfigPath(value) {
|
|
36558
36554
|
const trimmed = value.trim();
|
|
36559
36555
|
if (trimmed === "~")
|
|
36560
|
-
return
|
|
36556
|
+
return homedir4();
|
|
36561
36557
|
if (trimmed.startsWith("~/"))
|
|
36562
|
-
return `${
|
|
36558
|
+
return `${homedir4()}/${trimmed.slice(2)}`;
|
|
36563
36559
|
return trimmed;
|
|
36564
36560
|
}
|
|
36565
36561
|
var BaseEmbeddingConfigSchema = exports_external.object({
|
|
@@ -39000,12 +38996,12 @@ function loadRawConfigFile(options) {
|
|
|
39000
38996
|
|
|
39001
38997
|
// ../plugin/src/config/variable.ts
|
|
39002
38998
|
import { existsSync as existsSync10, readFileSync as readFileSync9 } from "node:fs";
|
|
39003
|
-
import { homedir as
|
|
38999
|
+
import { homedir as homedir5 } from "node:os";
|
|
39004
39000
|
import { dirname as dirname6, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
|
|
39005
39001
|
var ENV_PATTERN = /\{env:([^}]+)\}/g;
|
|
39006
39002
|
var FILE_PATTERN = /\{file:([^}]+)\}/g;
|
|
39007
39003
|
function sensitiveFilePathReason(resolvedPath) {
|
|
39008
|
-
const home =
|
|
39004
|
+
const home = homedir5();
|
|
39009
39005
|
const sensitiveDirs = [
|
|
39010
39006
|
{ dir: resolve4(home, ".ssh"), label: "SSH keys" },
|
|
39011
39007
|
{ dir: resolve4(home, ".aws"), label: "AWS credentials" },
|
|
@@ -39068,7 +39064,7 @@ function substituteConfigVariables(input) {
|
|
|
39068
39064
|
}
|
|
39069
39065
|
let filePath = rawPath.trim();
|
|
39070
39066
|
if (filePath.startsWith("~/")) {
|
|
39071
|
-
filePath = resolve4(
|
|
39067
|
+
filePath = resolve4(homedir5(), filePath.slice(2));
|
|
39072
39068
|
} else if (!isAbsolute3(filePath)) {
|
|
39073
39069
|
filePath = resolve4(configDir, filePath);
|
|
39074
39070
|
}
|
|
@@ -44071,6 +44067,13 @@ function markProjectLoadUntrusted(projectIdentity) {
|
|
|
44071
44067
|
untrustedLoadProjects.add(projectIdentity);
|
|
44072
44068
|
}
|
|
44073
44069
|
var testProviderFactory = null;
|
|
44070
|
+
|
|
44071
|
+
class TestProviderFactoryRequiredError extends Error {
|
|
44072
|
+
constructor() {
|
|
44073
|
+
super("test constructed a network-capable embedding provider without a test factory — install _setTestProviderFactoryForProject or set embedding.provider off in the fixture");
|
|
44074
|
+
this.name = "TestProviderFactoryRequiredError";
|
|
44075
|
+
}
|
|
44076
|
+
}
|
|
44074
44077
|
function synapseConfigFields(config2) {
|
|
44075
44078
|
const raw = config2;
|
|
44076
44079
|
return {
|
|
@@ -44149,11 +44152,14 @@ function resolveEmbeddingConfig(config2) {
|
|
|
44149
44152
|
throw new Error("Unknown embedding provider");
|
|
44150
44153
|
}
|
|
44151
44154
|
function createProvider(config2, context) {
|
|
44155
|
+
if (config2.provider === "off") {
|
|
44156
|
+
return null;
|
|
44157
|
+
}
|
|
44152
44158
|
if (testProviderFactory) {
|
|
44153
44159
|
return testProviderFactory(config2);
|
|
44154
44160
|
}
|
|
44155
|
-
if (
|
|
44156
|
-
|
|
44161
|
+
if (process.env.MAGIC_CONTEXT_TEST_DATA_DIR?.trim()) {
|
|
44162
|
+
throw new TestProviderFactoryRequiredError;
|
|
44157
44163
|
}
|
|
44158
44164
|
if (config2.provider === "openai-compatible") {
|
|
44159
44165
|
return new OpenAICompatibleEmbeddingProvider({
|
|
@@ -45555,6 +45561,10 @@ var STATUS_COLOR = {
|
|
|
45555
45561
|
completed: "success",
|
|
45556
45562
|
cancelled: "error"
|
|
45557
45563
|
};
|
|
45564
|
+
var SPIN_FRAMES = ["◐", "◓", "◑", "◒"];
|
|
45565
|
+
function spinGlyph() {
|
|
45566
|
+
return SPIN_FRAMES[Math.floor(Date.now() / 160) % SPIN_FRAMES.length];
|
|
45567
|
+
}
|
|
45558
45568
|
var snapshotsBySession = new Map;
|
|
45559
45569
|
var MAX_TODOWRITE_RENDER_CACHE_ENTRIES = 50;
|
|
45560
45570
|
var cachedTodowriteTodosByToolCallId = new Map;
|
|
@@ -45695,7 +45705,7 @@ function formatCounts(counts) {
|
|
|
45695
45705
|
return parts.join(" · ");
|
|
45696
45706
|
}
|
|
45697
45707
|
function formatTodoLine(todo, theme, options = {}) {
|
|
45698
|
-
const glyph = theme.fg(STATUS_COLOR[todo.status], STATUS_GLYPH[todo.status]);
|
|
45708
|
+
const glyph = theme.fg(STATUS_COLOR[todo.status], todo.status === "in_progress" ? spinGlyph() : STATUS_GLYPH[todo.status]);
|
|
45699
45709
|
const id = options.showId && todo.id ? `${theme.fg("accent", `#${todo.id}`)} ` : "";
|
|
45700
45710
|
const color = todo.status === "pending" || todo.status === "in_progress" ? "text" : "dim";
|
|
45701
45711
|
let content = theme.fg(color, todo.content);
|
|
@@ -45714,6 +45724,9 @@ function lineComponent(renderLines) {
|
|
|
45714
45724
|
invalidate() {}
|
|
45715
45725
|
};
|
|
45716
45726
|
}
|
|
45727
|
+
function hasAnimatedRow(rows) {
|
|
45728
|
+
return capTodoRows(rows).visible.some(({ todo }) => todo.status === "in_progress");
|
|
45729
|
+
}
|
|
45717
45730
|
function capTodoRows(rows) {
|
|
45718
45731
|
if (rows.length <= MAX_TODO_CONTENT_ROWS) {
|
|
45719
45732
|
return { visible: [...rows], hiddenCount: 0 };
|
|
@@ -45802,6 +45815,20 @@ function isOverlayLive(todo) {
|
|
|
45802
45815
|
}
|
|
45803
45816
|
|
|
45804
45817
|
class TodoOverlay {
|
|
45818
|
+
spinTimer;
|
|
45819
|
+
syncSpinTimer(hasInProgress) {
|
|
45820
|
+
if (hasInProgress && this.widgetRegistered) {
|
|
45821
|
+
if (this.spinTimer)
|
|
45822
|
+
return;
|
|
45823
|
+
this.spinTimer = setInterval(() => {
|
|
45824
|
+
this.tui?.requestRender();
|
|
45825
|
+
}, 160);
|
|
45826
|
+
this.spinTimer.unref?.();
|
|
45827
|
+
} else if (this.spinTimer) {
|
|
45828
|
+
clearInterval(this.spinTimer);
|
|
45829
|
+
this.spinTimer = undefined;
|
|
45830
|
+
}
|
|
45831
|
+
}
|
|
45805
45832
|
uiCtx;
|
|
45806
45833
|
sessionId;
|
|
45807
45834
|
widgetRegistered = false;
|
|
@@ -45829,6 +45856,10 @@ class TodoOverlay {
|
|
|
45829
45856
|
this.uiCtx.setWidget(WIDGET_KEY, undefined);
|
|
45830
45857
|
this.widgetRegistered = false;
|
|
45831
45858
|
this.tui = undefined;
|
|
45859
|
+
if (this.spinTimer) {
|
|
45860
|
+
clearInterval(this.spinTimer);
|
|
45861
|
+
this.spinTimer = undefined;
|
|
45862
|
+
}
|
|
45832
45863
|
}
|
|
45833
45864
|
return;
|
|
45834
45865
|
}
|
|
@@ -45840,11 +45871,17 @@ class TodoOverlay {
|
|
|
45840
45871
|
invalidate: () => {
|
|
45841
45872
|
this.widgetRegistered = false;
|
|
45842
45873
|
this.tui = undefined;
|
|
45874
|
+
if (this.spinTimer) {
|
|
45875
|
+
clearInterval(this.spinTimer);
|
|
45876
|
+
this.spinTimer = undefined;
|
|
45877
|
+
}
|
|
45843
45878
|
}
|
|
45844
45879
|
};
|
|
45845
45880
|
}, { placement: "aboveEditor" });
|
|
45846
45881
|
this.widgetRegistered = true;
|
|
45882
|
+
this.syncSpinTimer(hasAnimatedRow(visible));
|
|
45847
45883
|
} else {
|
|
45884
|
+
this.syncSpinTimer(hasAnimatedRow(visible));
|
|
45848
45885
|
this.tui?.requestRender();
|
|
45849
45886
|
}
|
|
45850
45887
|
}
|
|
@@ -45868,6 +45905,10 @@ class TodoOverlay {
|
|
|
45868
45905
|
this.dispose();
|
|
45869
45906
|
}
|
|
45870
45907
|
dispose() {
|
|
45908
|
+
if (this.spinTimer) {
|
|
45909
|
+
clearInterval(this.spinTimer);
|
|
45910
|
+
this.spinTimer = undefined;
|
|
45911
|
+
}
|
|
45871
45912
|
if (this.uiCtx)
|
|
45872
45913
|
this.uiCtx.setWidget(WIDGET_KEY, undefined);
|
|
45873
45914
|
this.widgetRegistered = false;
|
|
@@ -50752,6 +50793,7 @@ var memoryImportanceColumnCache = new WeakMap;
|
|
|
50752
50793
|
var memoryScopeColumnCache = new WeakMap;
|
|
50753
50794
|
var memoryShareableColumnCache = new WeakMap;
|
|
50754
50795
|
var memoryClassifiedAtColumnCache = new WeakMap;
|
|
50796
|
+
var memoryVerificationsTableCache = new WeakMap;
|
|
50755
50797
|
function hasMemoryImportanceColumn(db) {
|
|
50756
50798
|
const cached2 = memoryImportanceColumnCache.get(db);
|
|
50757
50799
|
if (cached2 !== undefined)
|
|
@@ -50788,6 +50830,14 @@ function hasMemoryClassifiedAtColumn(db) {
|
|
|
50788
50830
|
memoryClassifiedAtColumnCache.set(db, hasColumn);
|
|
50789
50831
|
return hasColumn;
|
|
50790
50832
|
}
|
|
50833
|
+
function hasMemoryVerificationsTable(db) {
|
|
50834
|
+
const cached2 = memoryVerificationsTableCache.get(db);
|
|
50835
|
+
if (cached2 !== undefined)
|
|
50836
|
+
return cached2;
|
|
50837
|
+
const hasTable = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_verifications'").get());
|
|
50838
|
+
memoryVerificationsTableCache.set(db, hasTable);
|
|
50839
|
+
return hasTable;
|
|
50840
|
+
}
|
|
50791
50841
|
function getUnclassifiedMemoryIds(db, memoryIds) {
|
|
50792
50842
|
if (!hasMemoryClassifiedAtColumn(db))
|
|
50793
50843
|
return [...memoryIds];
|
|
@@ -51280,6 +51330,9 @@ function updateMemoryContent(db, id, content, normalizedHash) {
|
|
|
51280
51330
|
const rejectionReset = hasMuralCueRejectionCountColumn(db) ? ", mural_cue_rejection_count = 0" : "";
|
|
51281
51331
|
db.prepare(`UPDATE memories SET mural_cue = NULL, mural_cue_hash = NULL, mural_cue_at = NULL${rejectionReset} WHERE id = ?`).run(id);
|
|
51282
51332
|
}
|
|
51333
|
+
if (hasMemoryVerificationsTable(db)) {
|
|
51334
|
+
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(id);
|
|
51335
|
+
}
|
|
51283
51336
|
let stmt = deleteEmbeddingOnContentUpdateStatements.get(db);
|
|
51284
51337
|
if (!stmt) {
|
|
51285
51338
|
stmt = db.prepare("DELETE FROM memory_embeddings WHERE memory_id = ?");
|
|
@@ -51550,13 +51603,13 @@ function placeholders3(values) {
|
|
|
51550
51603
|
function uniqueSortedFiles(files) {
|
|
51551
51604
|
return Array.from(new Set(files.filter((file2) => file2 !== MEMORY_VERIFICATION_SENTINEL))).sort();
|
|
51552
51605
|
}
|
|
51553
|
-
function recordMemoryMapping(db, memoryId, normalizedFiles, now) {
|
|
51606
|
+
function recordMemoryMapping(db, memoryId, normalizedFiles, now, mappingOrigin = "mapper") {
|
|
51554
51607
|
const realFiles = uniqueSortedFiles(normalizedFiles);
|
|
51555
51608
|
const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
|
|
51556
51609
|
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
|
|
51557
|
-
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, 0, ?)");
|
|
51610
|
+
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, 0, ?, ?)");
|
|
51558
51611
|
for (const file2 of filesToWrite) {
|
|
51559
|
-
insert.run(memoryId, file2, now);
|
|
51612
|
+
insert.run(memoryId, file2, now, mappingOrigin);
|
|
51560
51613
|
}
|
|
51561
51614
|
return filesToWrite.length;
|
|
51562
51615
|
}
|
|
@@ -51564,7 +51617,7 @@ function recordMemoryVerifications(db, memoryId, normalizedFiles, now) {
|
|
|
51564
51617
|
const realFiles = uniqueSortedFiles(normalizedFiles);
|
|
51565
51618
|
const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
|
|
51566
51619
|
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
|
|
51567
|
-
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, ?,
|
|
51620
|
+
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, ?, ?, 'mapper')");
|
|
51568
51621
|
for (const file2 of filesToWrite) {
|
|
51569
51622
|
insert.run(memoryId, file2, now, now);
|
|
51570
51623
|
}
|
|
@@ -51586,7 +51639,7 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
51586
51639
|
const result = new Map;
|
|
51587
51640
|
if (ids.length === 0)
|
|
51588
51641
|
return result;
|
|
51589
|
-
const rows = db.prepare(`SELECT memory_id, file_path, verified_at, mapped_at
|
|
51642
|
+
const rows = db.prepare(`SELECT memory_id, file_path, verified_at, mapped_at, mapping_origin
|
|
51590
51643
|
FROM memory_verifications
|
|
51591
51644
|
WHERE memory_id IN (${placeholders3(ids)})
|
|
51592
51645
|
ORDER BY memory_id, file_path`).all(...ids);
|
|
@@ -51594,6 +51647,7 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
51594
51647
|
const existing = result.get(row.memory_id) ?? {
|
|
51595
51648
|
files: [],
|
|
51596
51649
|
hasSentinel: false,
|
|
51650
|
+
mappingOrigin: "mapper",
|
|
51597
51651
|
verifiedAt: 0,
|
|
51598
51652
|
mappedAt: 0
|
|
51599
51653
|
};
|
|
@@ -51602,6 +51656,9 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
51602
51656
|
} else if (!existing.files.includes(row.file_path)) {
|
|
51603
51657
|
existing.files.push(row.file_path);
|
|
51604
51658
|
}
|
|
51659
|
+
if (row.mapping_origin === "host_rejected_fallback") {
|
|
51660
|
+
existing.mappingOrigin = "host_rejected_fallback";
|
|
51661
|
+
}
|
|
51605
51662
|
existing.verifiedAt = Math.max(existing.verifiedAt, row.verified_at);
|
|
51606
51663
|
existing.mappedAt = Math.max(existing.mappedAt, row.mapped_at ?? 0);
|
|
51607
51664
|
result.set(row.memory_id, existing);
|
|
@@ -52279,7 +52336,7 @@ import { isAbsolute as isAbsolute5 } from "node:path";
|
|
|
52279
52336
|
|
|
52280
52337
|
// ../retina-local-fs/src/path-fence.ts
|
|
52281
52338
|
import { lstat, readlink, realpath } from "node:fs/promises";
|
|
52282
|
-
import { homedir as
|
|
52339
|
+
import { homedir as homedir6 } from "node:os";
|
|
52283
52340
|
import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute4, join as join10, relative, resolve as resolve5, sep } from "node:path";
|
|
52284
52341
|
|
|
52285
52342
|
// ../retina-local-fs/src/errors.ts
|
|
@@ -52304,7 +52361,7 @@ async function resolveAndFenceProviderPath(configuredPath, options) {
|
|
|
52304
52361
|
return canonical;
|
|
52305
52362
|
}
|
|
52306
52363
|
async function resolveFenceRoots(options) {
|
|
52307
|
-
const configuredHomePath = resolve5(options.homeDirectory ?? process.env.HOME ??
|
|
52364
|
+
const configuredHomePath = resolve5(options.homeDirectory ?? process.env.HOME ?? homedir6());
|
|
52308
52365
|
let home;
|
|
52309
52366
|
try {
|
|
52310
52367
|
home = await realpath(configuredHomePath);
|
|
@@ -55913,12 +55970,14 @@ function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
|
|
|
55913
55970
|
updateTagStatus(db, sessionId, tagNumber, "dropped");
|
|
55914
55971
|
}
|
|
55915
55972
|
function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSummaryMessageId) {
|
|
55973
|
+
const transactionStartedAt = performance.now();
|
|
55916
55974
|
db.transaction(() => {
|
|
55917
55975
|
setPersistedCompactionMarkerState(db, sessionId, state);
|
|
55918
55976
|
if (replacedSummaryMessageId !== null) {
|
|
55919
55977
|
dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
|
|
55920
55978
|
}
|
|
55921
55979
|
})();
|
|
55980
|
+
logSlowWriteTransaction("marker-drain", transactionStartedAt);
|
|
55922
55981
|
}
|
|
55923
55982
|
function getCompartmentEndMessageIdForOrdinal(db, sessionId, endOrdinal) {
|
|
55924
55983
|
const row = db.prepare(`SELECT end_message_id
|
|
@@ -56868,4 +56927,4 @@ function registerMagicContextTools(pi, opts) {
|
|
|
56868
56927
|
}
|
|
56869
56928
|
}
|
|
56870
56929
|
|
|
56871
|
-
export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, hasShareabilitySensitiveText, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, 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, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, 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, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, 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, clearPendingOps, 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, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, buildChannel2Reminder, shouldUseStickyChannel1Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, 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, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, resolveModelConfigOrDefault, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, 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 };
|
|
56930
|
+
export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, 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, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, logSlowWriteTransaction, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, 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, clearPendingOps, 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, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, 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, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, resolveModelConfigOrDefault, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionSnapshot, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, 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 };
|