@cortexkit/magic-context 0.30.7 → 0.31.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/dist/index.js +432 -178
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -13389,11 +13389,71 @@ var init_migrate = __esm(async () => {
|
|
|
13389
13389
|
await init_sqlite();
|
|
13390
13390
|
});
|
|
13391
13391
|
|
|
13392
|
+
// ../plugin/src/shared/logger.ts
|
|
13393
|
+
import * as fs from "node:fs";
|
|
13394
|
+
import * as path2 from "node:path";
|
|
13395
|
+
function ensureDir5(filePath) {
|
|
13396
|
+
const dir = path2.dirname(filePath);
|
|
13397
|
+
if (dir === lastEnsuredDir)
|
|
13398
|
+
return;
|
|
13399
|
+
try {
|
|
13400
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
13401
|
+
lastEnsuredDir = dir;
|
|
13402
|
+
} catch {}
|
|
13403
|
+
}
|
|
13404
|
+
function flush() {
|
|
13405
|
+
if (flushTimer) {
|
|
13406
|
+
clearTimeout(flushTimer);
|
|
13407
|
+
flushTimer = null;
|
|
13408
|
+
}
|
|
13409
|
+
if (buffer.length === 0)
|
|
13410
|
+
return;
|
|
13411
|
+
const data = buffer.join("");
|
|
13412
|
+
buffer = [];
|
|
13413
|
+
try {
|
|
13414
|
+
const logFile = getMagicContextLogPath();
|
|
13415
|
+
ensureDir5(logFile);
|
|
13416
|
+
fs.appendFileSync(logFile, data);
|
|
13417
|
+
} catch {}
|
|
13418
|
+
}
|
|
13419
|
+
function scheduleFlush() {
|
|
13420
|
+
if (flushTimer)
|
|
13421
|
+
return;
|
|
13422
|
+
flushTimer = setTimeout(() => {
|
|
13423
|
+
flushTimer = null;
|
|
13424
|
+
flush();
|
|
13425
|
+
}, FLUSH_INTERVAL_MS);
|
|
13426
|
+
}
|
|
13427
|
+
function log3(message, data) {
|
|
13428
|
+
if (isTestEnv)
|
|
13429
|
+
return;
|
|
13430
|
+
try {
|
|
13431
|
+
const timestamp = new Date().toISOString();
|
|
13432
|
+
const serialized = data === undefined ? "" : data instanceof Error ? ` ${data.message}${data.stack ? `
|
|
13433
|
+
${data.stack}` : ""}` : ` ${JSON.stringify(data)}`;
|
|
13434
|
+
buffer.push(`[${timestamp}] ${message}${serialized}
|
|
13435
|
+
`);
|
|
13436
|
+
if (buffer.length >= BUFFER_SIZE_LIMIT) {
|
|
13437
|
+
flush();
|
|
13438
|
+
} else {
|
|
13439
|
+
scheduleFlush();
|
|
13440
|
+
}
|
|
13441
|
+
} catch {}
|
|
13442
|
+
}
|
|
13443
|
+
var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, lastEnsuredDir = null;
|
|
13444
|
+
var init_logger = __esm(() => {
|
|
13445
|
+
init_data_path();
|
|
13446
|
+
buffer = [];
|
|
13447
|
+
if (!isTestEnv) {
|
|
13448
|
+
process.on("exit", flush);
|
|
13449
|
+
}
|
|
13450
|
+
});
|
|
13451
|
+
|
|
13392
13452
|
// ../plugin/src/features/magic-context/memory/project-identity.ts
|
|
13393
13453
|
import { execFileSync as execFileSync4 } from "node:child_process";
|
|
13394
13454
|
import { createHash } from "node:crypto";
|
|
13395
|
-
import { statSync as statSync5 } from "node:fs";
|
|
13396
|
-
import
|
|
13455
|
+
import { existsSync as existsSync13, realpathSync, statSync as statSync5 } from "node:fs";
|
|
13456
|
+
import path3 from "node:path";
|
|
13397
13457
|
function asError(error) {
|
|
13398
13458
|
return error instanceof Error ? error : undefined;
|
|
13399
13459
|
}
|
|
@@ -13431,7 +13491,7 @@ function getErrorStderr(error) {
|
|
|
13431
13491
|
return "";
|
|
13432
13492
|
}
|
|
13433
13493
|
function directoryFallback(directory) {
|
|
13434
|
-
const canonical =
|
|
13494
|
+
const canonical = path3.resolve(directory);
|
|
13435
13495
|
const hash = createHash("md5").update(canonical, "utf8").digest("hex").slice(0, 12);
|
|
13436
13496
|
return `dir:${hash}`;
|
|
13437
13497
|
}
|
|
@@ -13469,21 +13529,27 @@ function classifyGitError(error, rawDirectory) {
|
|
|
13469
13529
|
return new ProjectIdentityError("permission_denied", rawDirectory, "Permission denied while spawning git", asError(error));
|
|
13470
13530
|
}
|
|
13471
13531
|
const stderr = getErrorStderr(error).toLowerCase();
|
|
13532
|
+
if (stderr.includes("detected dubious ownership")) {
|
|
13533
|
+
return new ProjectIdentityError("dubious_ownership", rawDirectory, "git refused to read the repository because it detected dubious ownership", asError(error));
|
|
13534
|
+
}
|
|
13472
13535
|
if (stderr.includes("not a git repository") || stderr.includes("does not have any commits yet") || stderr.includes("ambiguous argument 'head'") || stderr.includes("unknown revision or path")) {
|
|
13473
13536
|
return new ProjectIdentityError("not_git_repo", rawDirectory, "Directory has no git root commit; caller may use directory fallback", asError(error));
|
|
13474
13537
|
}
|
|
13475
13538
|
return new ProjectIdentityError("unknown", rawDirectory, "git rev-list failed while resolving project identity", asError(error));
|
|
13476
13539
|
}
|
|
13477
13540
|
function resolveProjectIdentityStrict(directory) {
|
|
13478
|
-
const canonical =
|
|
13541
|
+
const canonical = path3.resolve(directory);
|
|
13479
13542
|
const cached = identityCache.get(canonical);
|
|
13480
13543
|
if (cached !== undefined) {
|
|
13481
13544
|
return cached;
|
|
13482
13545
|
}
|
|
13483
13546
|
assertDirectoryUsable(canonical, directory);
|
|
13547
|
+
if (!hasGitDir(canonical)) {
|
|
13548
|
+
throw new ProjectIdentityError("not_git_repo", directory, "Directory has no git metadata; caller may use directory fallback");
|
|
13549
|
+
}
|
|
13484
13550
|
let output;
|
|
13485
13551
|
try {
|
|
13486
|
-
output =
|
|
13552
|
+
output = execFileSyncForIdentity("git", ["rev-list", "--max-parents=0", "HEAD"], {
|
|
13487
13553
|
cwd: canonical,
|
|
13488
13554
|
encoding: "utf8",
|
|
13489
13555
|
env: { ...process.env, LC_ALL: "C", LANG: "C" },
|
|
@@ -13501,13 +13567,76 @@ function resolveProjectIdentityStrict(directory) {
|
|
|
13501
13567
|
}
|
|
13502
13568
|
const identity = `git:${rootCommit}`;
|
|
13503
13569
|
identityCache.set(canonical, identity);
|
|
13570
|
+
lastKnownGitIdentityCache.set(canonical, identity);
|
|
13571
|
+
transientFailureCooldown.delete(canonical);
|
|
13572
|
+
dubiousOwnershipFallbackDirectories.delete(canonical);
|
|
13573
|
+
transientGitIdentityReuseLoggedDirectories.delete(canonical);
|
|
13504
13574
|
return identity;
|
|
13505
13575
|
}
|
|
13506
13576
|
function shouldUseDirectoryFallback(error) {
|
|
13507
|
-
return error.errorClass
|
|
13577
|
+
return error.errorClass !== "permission_denied";
|
|
13578
|
+
}
|
|
13579
|
+
function getActiveCooldown(canonical) {
|
|
13580
|
+
const until = transientFailureCooldown.get(canonical);
|
|
13581
|
+
if (until === undefined)
|
|
13582
|
+
return;
|
|
13583
|
+
if (nowMs() < until)
|
|
13584
|
+
return until;
|
|
13585
|
+
transientFailureCooldown.delete(canonical);
|
|
13586
|
+
return;
|
|
13587
|
+
}
|
|
13588
|
+
function lastKnownGitIdentity(canonical) {
|
|
13589
|
+
return lastKnownGitIdentityCache.get(canonical) ?? identityCache.get(canonical);
|
|
13590
|
+
}
|
|
13591
|
+
function nearestLastKnownGitIdentity(canonical) {
|
|
13592
|
+
const visited = new Set;
|
|
13593
|
+
const walk = (start) => {
|
|
13594
|
+
let current = start;
|
|
13595
|
+
while (!visited.has(current)) {
|
|
13596
|
+
visited.add(current);
|
|
13597
|
+
const cached = lastKnownGitIdentity(current);
|
|
13598
|
+
if (cached !== undefined)
|
|
13599
|
+
return { identity: cached, source: current };
|
|
13600
|
+
const parent = path3.dirname(current);
|
|
13601
|
+
if (parent === current)
|
|
13602
|
+
break;
|
|
13603
|
+
current = parent;
|
|
13604
|
+
}
|
|
13605
|
+
return;
|
|
13606
|
+
};
|
|
13607
|
+
const exactOrAncestor = walk(canonical);
|
|
13608
|
+
if (exactOrAncestor)
|
|
13609
|
+
return exactOrAncestor;
|
|
13610
|
+
try {
|
|
13611
|
+
const realCanonical = realpathSync.native(canonical);
|
|
13612
|
+
if (realCanonical !== canonical)
|
|
13613
|
+
return walk(realCanonical);
|
|
13614
|
+
} catch {}
|
|
13615
|
+
return;
|
|
13616
|
+
}
|
|
13617
|
+
function reuseLastKnownGitIdentity(canonical) {
|
|
13618
|
+
const cached = nearestLastKnownGitIdentity(canonical);
|
|
13619
|
+
if (cached === undefined)
|
|
13620
|
+
return;
|
|
13621
|
+
if (!transientGitIdentityReuseLoggedDirectories.has(canonical)) {
|
|
13622
|
+
transientGitIdentityReuseLoggedDirectories.add(canonical);
|
|
13623
|
+
const sourceNote = cached.source === canonical ? "" : ` from ancestor ${cached.source}`;
|
|
13624
|
+
log3(`[magic-context] git identity resolution is temporarily unavailable for ${canonical}; reusing the last successful project identity${sourceNote} to avoid splitting project-scoped memory`);
|
|
13625
|
+
}
|
|
13626
|
+
return cached.identity;
|
|
13627
|
+
}
|
|
13628
|
+
function formatDubiousOwnershipWarning(canonical) {
|
|
13629
|
+
return `Magic Context: git refused to read ${canonical} (dubious ownership — the repo is owned by a different user). Using a directory-based project identity for now, which keeps memory separate from this repo's normal identity. Fix: git config --global --add safe.directory ${canonical}`;
|
|
13630
|
+
}
|
|
13631
|
+
function recordDubiousOwnershipFallback(canonical) {
|
|
13632
|
+
dubiousOwnershipFallbackDirectories.add(canonical);
|
|
13633
|
+
if (dubiousOwnershipLoggedDirectories.has(canonical))
|
|
13634
|
+
return;
|
|
13635
|
+
dubiousOwnershipLoggedDirectories.add(canonical);
|
|
13636
|
+
log3(`[magic-context] ${formatDubiousOwnershipWarning(canonical)}`);
|
|
13508
13637
|
}
|
|
13509
13638
|
function resolveProjectIdentity(directory) {
|
|
13510
|
-
const canonical =
|
|
13639
|
+
const canonical = path3.resolve(directory);
|
|
13511
13640
|
const cachedFallback = directoryFallbackCache.get(canonical);
|
|
13512
13641
|
if (cachedFallback !== undefined) {
|
|
13513
13642
|
if (!hasGitDir(canonical)) {
|
|
@@ -13515,13 +13644,33 @@ function resolveProjectIdentity(directory) {
|
|
|
13515
13644
|
}
|
|
13516
13645
|
directoryFallbackCache.delete(canonical);
|
|
13517
13646
|
}
|
|
13647
|
+
if (getActiveCooldown(canonical) !== undefined) {
|
|
13648
|
+
if (hasGitDir(canonical)) {
|
|
13649
|
+
const cachedGitIdentity = reuseLastKnownGitIdentity(canonical);
|
|
13650
|
+
if (cachedGitIdentity !== undefined) {
|
|
13651
|
+
return cachedGitIdentity;
|
|
13652
|
+
}
|
|
13653
|
+
}
|
|
13654
|
+
return directoryFallback(canonical);
|
|
13655
|
+
}
|
|
13518
13656
|
try {
|
|
13519
13657
|
return resolveProjectIdentityStrict(directory);
|
|
13520
13658
|
} catch (error) {
|
|
13521
13659
|
if (error instanceof ProjectIdentityError && shouldUseDirectoryFallback(error)) {
|
|
13522
13660
|
const fallback = directoryFallback(canonical);
|
|
13523
|
-
|
|
13661
|
+
const hasGitMetadata = hasGitDir(canonical);
|
|
13662
|
+
if (!hasGitMetadata) {
|
|
13524
13663
|
directoryFallbackCache.set(canonical, fallback);
|
|
13664
|
+
transientFailureCooldown.delete(canonical);
|
|
13665
|
+
} else {
|
|
13666
|
+
transientFailureCooldown.set(canonical, nowMs() + TRANSIENT_FAILURE_COOLDOWN_MS);
|
|
13667
|
+
const cachedGitIdentity = reuseLastKnownGitIdentity(canonical);
|
|
13668
|
+
if (cachedGitIdentity !== undefined) {
|
|
13669
|
+
return cachedGitIdentity;
|
|
13670
|
+
}
|
|
13671
|
+
}
|
|
13672
|
+
if (error.errorClass === "dubious_ownership") {
|
|
13673
|
+
recordDubiousOwnershipFallback(canonical);
|
|
13525
13674
|
}
|
|
13526
13675
|
return fallback;
|
|
13527
13676
|
}
|
|
@@ -13529,17 +13678,42 @@ function resolveProjectIdentity(directory) {
|
|
|
13529
13678
|
}
|
|
13530
13679
|
}
|
|
13531
13680
|
function hasGitDir(canonical) {
|
|
13532
|
-
|
|
13533
|
-
statSync5(path2.join(canonical, ".git"));
|
|
13681
|
+
if (hasGitDirInAncestorChain(canonical)) {
|
|
13534
13682
|
return true;
|
|
13683
|
+
}
|
|
13684
|
+
try {
|
|
13685
|
+
const realCanonical = realpathSync.native(canonical);
|
|
13686
|
+
return realCanonical !== canonical && hasGitDirInAncestorChain(realCanonical);
|
|
13535
13687
|
} catch {
|
|
13536
13688
|
return false;
|
|
13537
13689
|
}
|
|
13538
13690
|
}
|
|
13539
|
-
|
|
13691
|
+
function hasGitDirInAncestorChain(startDirectory) {
|
|
13692
|
+
let current = startDirectory;
|
|
13693
|
+
while (true) {
|
|
13694
|
+
if (existsSync13(path3.join(current, ".git"))) {
|
|
13695
|
+
return true;
|
|
13696
|
+
}
|
|
13697
|
+
const parent = path3.dirname(current);
|
|
13698
|
+
if (parent === current) {
|
|
13699
|
+
return false;
|
|
13700
|
+
}
|
|
13701
|
+
current = parent;
|
|
13702
|
+
}
|
|
13703
|
+
}
|
|
13704
|
+
var GIT_TIMEOUT_MS = 5000, TRANSIENT_FAILURE_COOLDOWN_MS, identityCache, lastKnownGitIdentityCache, directoryFallbackCache, transientFailureCooldown, dubiousOwnershipFallbackDirectories, dubiousOwnershipLoggedDirectories, dubiousOwnershipWarnedDirectories, transientGitIdentityReuseLoggedDirectories, execFileSyncForIdentity, nowMs = () => Date.now(), ProjectIdentityError;
|
|
13540
13705
|
var init_project_identity = __esm(() => {
|
|
13706
|
+
init_logger();
|
|
13707
|
+
TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
|
|
13541
13708
|
identityCache = new Map;
|
|
13709
|
+
lastKnownGitIdentityCache = new Map;
|
|
13542
13710
|
directoryFallbackCache = new Map;
|
|
13711
|
+
transientFailureCooldown = new Map;
|
|
13712
|
+
dubiousOwnershipFallbackDirectories = new Set;
|
|
13713
|
+
dubiousOwnershipLoggedDirectories = new Set;
|
|
13714
|
+
dubiousOwnershipWarnedDirectories = new Set;
|
|
13715
|
+
transientGitIdentityReuseLoggedDirectories = new Set;
|
|
13716
|
+
execFileSyncForIdentity = execFileSync4;
|
|
13543
13717
|
ProjectIdentityError = class ProjectIdentityError extends Error {
|
|
13544
13718
|
errorClass;
|
|
13545
13719
|
rawDirectory;
|
|
@@ -13681,9 +13855,9 @@ __export(exports_migrate_session, {
|
|
|
13681
13855
|
planMigrateSession: () => planMigrateSession,
|
|
13682
13856
|
applyMigrateSession: () => applyMigrateSession
|
|
13683
13857
|
});
|
|
13684
|
-
import { copyFileSync, existsSync as
|
|
13858
|
+
import { copyFileSync, existsSync as existsSync14, realpathSync as realpathSync2 } from "node:fs";
|
|
13685
13859
|
import { homedir as homedir8 } from "node:os";
|
|
13686
|
-
import
|
|
13860
|
+
import path4, { join as join12 } from "node:path";
|
|
13687
13861
|
function existingSessionColumns(db) {
|
|
13688
13862
|
const rows = db.prepare("PRAGMA table_info(session)").all();
|
|
13689
13863
|
return new Set(rows.map((r2) => r2.name).filter((n2) => typeof n2 === "string"));
|
|
@@ -13711,7 +13885,7 @@ function planMigrateSession(sessionId, rawTargetDirectory, deps) {
|
|
|
13711
13885
|
ocProjectId = "global";
|
|
13712
13886
|
ocWorktree = globalRow.worktree || "/";
|
|
13713
13887
|
}
|
|
13714
|
-
const sessionPath =
|
|
13888
|
+
const sessionPath = path4.relative(ocWorktree, targetDirectory);
|
|
13715
13889
|
const ownershipRow = deps.contextDb.prepare("SELECT project_path FROM session_projects WHERE session_id = ? AND harness = 'opencode'").get(sessionId);
|
|
13716
13890
|
const fromMcIdentity = ownershipRow?.project_path ?? (sessionRow.directory ? deps.resolveIdentity(sessionRow.directory) : "");
|
|
13717
13891
|
const toMcIdentity = deps.resolveIdentity(targetDirectory);
|
|
@@ -13844,8 +14018,8 @@ function realDeps(opencodeDb, contextDb) {
|
|
|
13844
14018
|
opencodeDb,
|
|
13845
14019
|
contextDb,
|
|
13846
14020
|
resolveIdentity: resolveProjectIdentity,
|
|
13847
|
-
hasGitDir: (dir) =>
|
|
13848
|
-
realpath: (p2) =>
|
|
14021
|
+
hasGitDir: (dir) => existsSync14(join12(dir, ".git")),
|
|
14022
|
+
realpath: (p2) => realpathSync2(p2)
|
|
13849
14023
|
};
|
|
13850
14024
|
}
|
|
13851
14025
|
function valueAfter(args, flag) {
|
|
@@ -13923,7 +14097,7 @@ async function runMigrateSessionCli(args) {
|
|
|
13923
14097
|
return 1;
|
|
13924
14098
|
}
|
|
13925
14099
|
const expandedTo = toDir.startsWith("~") ? join12(homedir8(), toDir.slice(1).replace(/^[/\\]/, "")) : toDir;
|
|
13926
|
-
if (!
|
|
14100
|
+
if (!existsSync14(expandedTo)) {
|
|
13927
14101
|
console.error(`Target directory does not exist: ${expandedTo}`);
|
|
13928
14102
|
return 1;
|
|
13929
14103
|
}
|
|
@@ -14071,66 +14245,6 @@ var init_compartment_storage = __esm(() => {
|
|
|
14071
14245
|
insertCompartmentStatements = new WeakMap;
|
|
14072
14246
|
insertFactStatements = new WeakMap;
|
|
14073
14247
|
});
|
|
14074
|
-
// ../plugin/src/shared/logger.ts
|
|
14075
|
-
import * as fs from "node:fs";
|
|
14076
|
-
import * as path4 from "node:path";
|
|
14077
|
-
function ensureDir5(filePath) {
|
|
14078
|
-
const dir = path4.dirname(filePath);
|
|
14079
|
-
if (dir === lastEnsuredDir)
|
|
14080
|
-
return;
|
|
14081
|
-
try {
|
|
14082
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
14083
|
-
lastEnsuredDir = dir;
|
|
14084
|
-
} catch {}
|
|
14085
|
-
}
|
|
14086
|
-
function flush() {
|
|
14087
|
-
if (flushTimer) {
|
|
14088
|
-
clearTimeout(flushTimer);
|
|
14089
|
-
flushTimer = null;
|
|
14090
|
-
}
|
|
14091
|
-
if (buffer.length === 0)
|
|
14092
|
-
return;
|
|
14093
|
-
const data = buffer.join("");
|
|
14094
|
-
buffer = [];
|
|
14095
|
-
try {
|
|
14096
|
-
const logFile = getMagicContextLogPath();
|
|
14097
|
-
ensureDir5(logFile);
|
|
14098
|
-
fs.appendFileSync(logFile, data);
|
|
14099
|
-
} catch {}
|
|
14100
|
-
}
|
|
14101
|
-
function scheduleFlush() {
|
|
14102
|
-
if (flushTimer)
|
|
14103
|
-
return;
|
|
14104
|
-
flushTimer = setTimeout(() => {
|
|
14105
|
-
flushTimer = null;
|
|
14106
|
-
flush();
|
|
14107
|
-
}, FLUSH_INTERVAL_MS);
|
|
14108
|
-
}
|
|
14109
|
-
function log3(message, data) {
|
|
14110
|
-
if (isTestEnv)
|
|
14111
|
-
return;
|
|
14112
|
-
try {
|
|
14113
|
-
const timestamp = new Date().toISOString();
|
|
14114
|
-
const serialized = data === undefined ? "" : data instanceof Error ? ` ${data.message}${data.stack ? `
|
|
14115
|
-
${data.stack}` : ""}` : ` ${JSON.stringify(data)}`;
|
|
14116
|
-
buffer.push(`[${timestamp}] ${message}${serialized}
|
|
14117
|
-
`);
|
|
14118
|
-
if (buffer.length >= BUFFER_SIZE_LIMIT) {
|
|
14119
|
-
flush();
|
|
14120
|
-
} else {
|
|
14121
|
-
scheduleFlush();
|
|
14122
|
-
}
|
|
14123
|
-
} catch {}
|
|
14124
|
-
}
|
|
14125
|
-
var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, lastEnsuredDir = null;
|
|
14126
|
-
var init_logger = __esm(() => {
|
|
14127
|
-
init_data_path();
|
|
14128
|
-
buffer = [];
|
|
14129
|
-
if (!isTestEnv) {
|
|
14130
|
-
process.on("exit", flush);
|
|
14131
|
-
}
|
|
14132
|
-
});
|
|
14133
|
-
|
|
14134
14248
|
// ../plugin/src/shared/sqlite-helpers.ts
|
|
14135
14249
|
function closeQuietly(db) {
|
|
14136
14250
|
if (!db)
|
|
@@ -148295,6 +148409,15 @@ var init_migrations = __esm(() => {
|
|
|
148295
148409
|
);
|
|
148296
148410
|
`);
|
|
148297
148411
|
}
|
|
148412
|
+
},
|
|
148413
|
+
{
|
|
148414
|
+
version: 50,
|
|
148415
|
+
description: "add durable ctx-wrapup session marker",
|
|
148416
|
+
up(db) {
|
|
148417
|
+
if (tableExists(db, "session_meta")) {
|
|
148418
|
+
ensureColumn(db, "session_meta", "wrapup_in_progress_state", "TEXT");
|
|
148419
|
+
}
|
|
148420
|
+
}
|
|
148298
148421
|
}
|
|
148299
148422
|
];
|
|
148300
148423
|
LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m3) => Math.max(max, m3.version), 0);
|
|
@@ -148346,7 +148469,7 @@ var init_tool_definition_tokens = __esm(() => {
|
|
|
148346
148469
|
});
|
|
148347
148470
|
|
|
148348
148471
|
// ../plugin/src/features/magic-context/tool-owner-backfill.ts
|
|
148349
|
-
import { existsSync as
|
|
148472
|
+
import { existsSync as existsSync15 } from "node:fs";
|
|
148350
148473
|
import { join as join13 } from "node:path";
|
|
148351
148474
|
function resolveOpencodeDbPath() {
|
|
148352
148475
|
return join13(getDataDir(), "opencode", "opencode.db");
|
|
@@ -148384,7 +148507,7 @@ function runToolOwnerBackfill(db) {
|
|
|
148384
148507
|
return result;
|
|
148385
148508
|
}
|
|
148386
148509
|
const opencodeDbPath = resolveOpencodeDbPath();
|
|
148387
|
-
if (!
|
|
148510
|
+
if (!existsSync15(opencodeDbPath)) {
|
|
148388
148511
|
log3(`[backfill] OpenCode DB not found at ${opencodeDbPath} — marking all unbackfilled sessions as skipped. Lazy adoption (defense-in-depth) handles legacy rows at runtime.`);
|
|
148389
148512
|
markAllUnbackfilledSessionsSkipped(db);
|
|
148390
148513
|
result.sessionsSkippedNoOcDb = countSessionsByStatus(db, "skipped");
|
|
@@ -148608,7 +148731,7 @@ var init_tool_owner_backfill = __esm(() => {
|
|
|
148608
148731
|
});
|
|
148609
148732
|
|
|
148610
148733
|
// ../plugin/src/features/magic-context/storage-db.ts
|
|
148611
|
-
import { chmodSync as chmodSync2, copyFileSync as copyFileSync2, cpSync, existsSync as
|
|
148734
|
+
import { chmodSync as chmodSync2, copyFileSync as copyFileSync2, cpSync, existsSync as existsSync16, mkdirSync as mkdirSync7, mkdtempSync } from "node:fs";
|
|
148612
148735
|
import { dirname as dirname8, join as join14 } from "node:path";
|
|
148613
148736
|
function ensureSecureStorageDir(dir) {
|
|
148614
148737
|
mkdirSync7(dir, { recursive: true, mode: 448 });
|
|
@@ -148625,7 +148748,7 @@ function restrictDatabaseFilePermissions(dbPath) {
|
|
|
148625
148748
|
return;
|
|
148626
148749
|
for (const suffix of ["", "-wal", "-shm"]) {
|
|
148627
148750
|
const file = `${dbPath}${suffix}`;
|
|
148628
|
-
if (!
|
|
148751
|
+
if (!existsSync16(file))
|
|
148629
148752
|
continue;
|
|
148630
148753
|
try {
|
|
148631
148754
|
chmodSync2(file, 384);
|
|
@@ -148648,11 +148771,11 @@ function resolveDatabasePath(dbPathOverride) {
|
|
|
148648
148771
|
return { dbDir, dbPath: join14(dbDir, "context.db") };
|
|
148649
148772
|
}
|
|
148650
148773
|
function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
|
|
148651
|
-
if (
|
|
148774
|
+
if (existsSync16(targetDbPath))
|
|
148652
148775
|
return;
|
|
148653
148776
|
const legacyDir = getLegacyOpenCodeMagicContextStorageDir();
|
|
148654
148777
|
const legacyDbPath = join14(legacyDir, "context.db");
|
|
148655
|
-
if (!
|
|
148778
|
+
if (!existsSync16(legacyDbPath))
|
|
148656
148779
|
return;
|
|
148657
148780
|
log3(`[magic-context] migrating legacy plugin storage: ${legacyDir} -> ${targetDbDir} (legacy left in place as backup)`);
|
|
148658
148781
|
ensureSecureStorageDir(targetDbDir);
|
|
@@ -148669,7 +148792,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
|
|
|
148669
148792
|
for (const suffix of ["", "-wal", "-shm"]) {
|
|
148670
148793
|
const src = `${legacyDbPath}${suffix}`;
|
|
148671
148794
|
const dst = join14(targetDbDir, `context.db${suffix}`);
|
|
148672
|
-
if (
|
|
148795
|
+
if (existsSync16(src)) {
|
|
148673
148796
|
try {
|
|
148674
148797
|
copyFileSync2(src, dst);
|
|
148675
148798
|
} catch (error) {
|
|
@@ -148679,7 +148802,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
|
|
|
148679
148802
|
}
|
|
148680
148803
|
const legacyModelsDir = join14(legacyDir, "models");
|
|
148681
148804
|
const targetModelsDir = join14(targetDbDir, "models");
|
|
148682
|
-
if (
|
|
148805
|
+
if (existsSync16(legacyModelsDir) && !existsSync16(targetModelsDir)) {
|
|
148683
148806
|
try {
|
|
148684
148807
|
cpSync(legacyModelsDir, targetModelsDir, { recursive: true });
|
|
148685
148808
|
} catch (error) {
|
|
@@ -149270,6 +149393,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
149270
149393
|
force_emergency_bypass_used INTEGER NOT NULL DEFAULT 0,
|
|
149271
149394
|
emergency_drain_active INTEGER NOT NULL DEFAULT 0,
|
|
149272
149395
|
historian_drain_failure_at INTEGER NOT NULL DEFAULT 0,
|
|
149396
|
+
wrapup_in_progress_state TEXT,
|
|
149273
149397
|
cached_m0_materialized_at INTEGER,
|
|
149274
149398
|
cached_m0_session_facts_version INTEGER,
|
|
149275
149399
|
cached_m0_upgrade_state TEXT,
|
|
@@ -149558,6 +149682,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
149558
149682
|
ensureColumn(db, "session_meta", "force_emergency_bypass_used", "INTEGER NOT NULL DEFAULT 0");
|
|
149559
149683
|
ensureColumn(db, "session_meta", "emergency_drain_active", "INTEGER NOT NULL DEFAULT 0");
|
|
149560
149684
|
ensureColumn(db, "session_meta", "historian_drain_failure_at", "INTEGER NOT NULL DEFAULT 0");
|
|
149685
|
+
ensureColumn(db, "session_meta", "wrapup_in_progress_state", "TEXT");
|
|
149561
149686
|
ensureColumn(db, "session_meta", "cached_m0_materialized_at", "INTEGER");
|
|
149562
149687
|
ensureColumn(db, "session_meta", "cached_m0_session_facts_version", "INTEGER");
|
|
149563
149688
|
ensureColumn(db, "session_meta", "cached_m0_upgrade_state", "TEXT");
|
|
@@ -149742,7 +149867,7 @@ function closeDatabase() {
|
|
|
149742
149867
|
}
|
|
149743
149868
|
}
|
|
149744
149869
|
}
|
|
149745
|
-
var databases, persistenceByDatabase, persistenceErrorByDatabase, pathByDatabase, lastSchemaFenceRejection = null, LATEST_SUPPORTED_VERSION =
|
|
149870
|
+
var databases, persistenceByDatabase, persistenceErrorByDatabase, pathByDatabase, lastSchemaFenceRejection = null, LATEST_SUPPORTED_VERSION = 50, PERMISSIONS_ENFORCEABLE, sqlitePragmaConfig, CHANNEL2_CLAIM_TTL_MS = 120000;
|
|
149746
149871
|
var init_storage_db = __esm(async () => {
|
|
149747
149872
|
init_data_path();
|
|
149748
149873
|
init_logger();
|
|
@@ -149779,7 +149904,7 @@ var init_storage_memory_mutation_log = __esm(() => {
|
|
|
149779
149904
|
});
|
|
149780
149905
|
|
|
149781
149906
|
// ../plugin/src/features/magic-context/storage-meta-persisted.ts
|
|
149782
|
-
var AUTO_SEARCH_NO_HINT_REASONS, DRAIN_WINDOW_MS, EMERGENCY_DRAIN_MAX_LATCH_MS;
|
|
149907
|
+
var AUTO_SEARCH_NO_HINT_REASONS, DRAIN_WINDOW_MS, WRAPUP_IN_PROGRESS_TTL_MS, EMERGENCY_DRAIN_MAX_LATCH_MS;
|
|
149783
149908
|
var init_storage_meta_persisted = __esm(() => {
|
|
149784
149909
|
init_logger();
|
|
149785
149910
|
init_storage_meta_shared();
|
|
@@ -149792,6 +149917,7 @@ var init_storage_meta_persisted = __esm(() => {
|
|
|
149792
149917
|
"too-short"
|
|
149793
149918
|
]);
|
|
149794
149919
|
DRAIN_WINDOW_MS = 10 * 60 * 1000;
|
|
149920
|
+
WRAPUP_IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
|
|
149795
149921
|
EMERGENCY_DRAIN_MAX_LATCH_MS = 30 * 60 * 1000;
|
|
149796
149922
|
});
|
|
149797
149923
|
|
|
@@ -149917,7 +150043,7 @@ var init_storage = __esm(async () => {
|
|
|
149917
150043
|
|
|
149918
150044
|
// ../plugin/src/features/magic-context/v22-deferred-backfill.ts
|
|
149919
150045
|
import { createHash as createHash2 } from "node:crypto";
|
|
149920
|
-
import { realpathSync as
|
|
150046
|
+
import { realpathSync as realpathSync3 } from "node:fs";
|
|
149921
150047
|
import path5 from "node:path";
|
|
149922
150048
|
function readMeta(db, key) {
|
|
149923
150049
|
const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(key);
|
|
@@ -149938,7 +150064,10 @@ function countFailures(db) {
|
|
|
149938
150064
|
}
|
|
149939
150065
|
function classifyBackfillError(error) {
|
|
149940
150066
|
if (error instanceof ProjectIdentityError) {
|
|
149941
|
-
return {
|
|
150067
|
+
return {
|
|
150068
|
+
errorClass: error.errorClass === "dubious_ownership" ? "unknown" : error.errorClass,
|
|
150069
|
+
errorMessage: error.message
|
|
150070
|
+
};
|
|
149942
150071
|
}
|
|
149943
150072
|
if (error instanceof Error) {
|
|
149944
150073
|
return { errorClass: "unknown", errorMessage: error.message };
|
|
@@ -149958,7 +150087,7 @@ function resolveBackfillIdentity(rawProjectPath) {
|
|
|
149958
150087
|
function computeLegacyRustDirIdentity(rawProjectPath) {
|
|
149959
150088
|
let canonical;
|
|
149960
150089
|
try {
|
|
149961
|
-
canonical =
|
|
150090
|
+
canonical = realpathSync3(rawProjectPath);
|
|
149962
150091
|
} catch {
|
|
149963
150092
|
canonical = path5.isAbsolute(rawProjectPath) ? rawProjectPath : path5.join(process.cwd(), rawProjectPath);
|
|
149964
150093
|
}
|
|
@@ -165422,7 +165551,6 @@ var init_magic_context = __esm(() => {
|
|
|
165422
165551
|
enabled: exports_external.boolean().default(true).describe("Enable magic context (default: true)"),
|
|
165423
165552
|
auto_update: exports_external.boolean().optional().describe("Enable automatic npm self-update checks for the OpenCode plugin. Security: USER-only in config loader, so hostile project configs cannot suppress updates."),
|
|
165424
165553
|
language: exports_external.string().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian, dreamer, sidekick, and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
|
|
165425
|
-
ctx_reduce_enabled: exports_external.boolean().default(true).describe("When false, ctx_reduce tool is hidden, all nudges disabled, and prompt guidance about ctx_reduce stripped. Heuristic cleanup, compartments, memory, and other features still work. (default: true)"),
|
|
165426
165554
|
historian: HistorianConfigSchema.describe("Historian agent configuration (model, fallback_models, variant, temperature, maxTokens, permission, two_pass, etc.)"),
|
|
165427
165555
|
dreamer: DreamerConfigSchema.optional().describe("Dreamer agent + scheduling configuration (model, fallback_models, disable, schedule, tasks, etc.)"),
|
|
165428
165556
|
cache_ttl: exports_external.union([exports_external.string(), exports_external.object({ default: exports_external.string() }).catchall(exports_external.string())]).default("5m").describe('Cache TTL: string (e.g. "5m") or per-model object ({ default: "5m", "model-id": "10m" })'),
|
|
@@ -165461,9 +165589,9 @@ var init_magic_context = __esm(() => {
|
|
|
165461
165589
|
keep_subagents: exports_external.boolean().default(false).describe("Debug: keep the child sessions Magic Context spawns for its own subagents (historian, dreamer, sidekick, memory-migration) instead of deleting them on success. Useful for short-term inspection/data collection — their full transcript (prompt, tool calls, token usage, output) stays in the host session store. Kept sessions accumulate until manually cleared; leave false for normal use. Requires a restart to take effect."),
|
|
165462
165590
|
smart_drops: exports_external.boolean().default(false).describe("Content-aware reclaim of provably-superseded tool output, layered on the existing execute-pass auto-drop. When on: superseded todowrite (keep newest 1), spent ctx_reduce (keep newest 5), and zero-value meta (bash_status, bash_kill, ctx_note read/dismiss) outputs are dropped; older edits to a file are compressed to a filePath-preserving marker while the newest edit per file stays full. Only acts on passes already busting the cache, so it never originates a cache bust. Honors the protected-tag reserve. Experimental: opt-in, default off until cache stability is proven; when off the wire is byte-identical to the positional-only reclaim. Requires a restart."),
|
|
165463
165591
|
caveman_text_compression: exports_external.object({
|
|
165464
|
-
enabled: exports_external.boolean().default(false).describe("Apply deterministic caveman-style text compression to old conversation text.
|
|
165592
|
+
enabled: exports_external.boolean().default(false).describe("Apply deterministic caveman-style text compression to old conversation text. Active for primary sessions when enabled; never for subagents. Compresses user/assistant text in oldest-first tiers: ultra (oldest 20%), full, lite, untouched (newest 40%)."),
|
|
165465
165593
|
min_chars: exports_external.number().min(100).max(1e4).default(500).describe("Text parts shorter than this (characters) stay untouched. Min 100, max 10000. Default: 500.")
|
|
165466
|
-
}).default({ enabled: false, min_chars: 500 }).describe("Age-tier caveman compression for long user/assistant text parts.
|
|
165594
|
+
}).default({ enabled: false, min_chars: 500 }).describe("Age-tier caveman compression for long user/assistant text parts. Active for primary sessions when enabled; never for subagents. Oldest 20% of eligible tags (outside protected tail) go to ultra, next 20% to full, next 20% to lite, newest 40% untouched. Graduated from experimental.caveman_text_compression; opt-in, default off (lossy)."),
|
|
165467
165595
|
memory: exports_external.object({
|
|
165468
165596
|
enabled: exports_external.boolean().default(true).describe("Enable cross-session memory (default: true)"),
|
|
165469
165597
|
injection_budget_tokens: exports_external.number().min(500).max(20000).default(4000).describe("Token budget for memory injection on session start (min: 500, max: 20000, default: 4000)"),
|
|
@@ -165497,7 +165625,7 @@ var init_magic_context = __esm(() => {
|
|
|
165497
165625
|
});
|
|
165498
165626
|
|
|
165499
165627
|
// ../plugin/src/config/variable.ts
|
|
165500
|
-
import { existsSync as
|
|
165628
|
+
import { existsSync as existsSync17, readFileSync as readFileSync8 } from "node:fs";
|
|
165501
165629
|
import { homedir as homedir9 } from "node:os";
|
|
165502
165630
|
import { dirname as dirname9, isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
|
|
165503
165631
|
function sensitiveFilePathReason(resolvedPath) {
|
|
@@ -165572,7 +165700,7 @@ function substituteConfigVariables(input) {
|
|
|
165572
165700
|
if (sensitiveReason) {
|
|
165573
165701
|
warnings.push(`${token} resolves to a sensitive path (${sensitiveReason}: ${filePath}); ` + "inlining its contents into config — make sure this is intentional.");
|
|
165574
165702
|
}
|
|
165575
|
-
if (!
|
|
165703
|
+
if (!existsSync17(filePath)) {
|
|
165576
165704
|
warnings.push(`File not found for ${token} (resolved to ${filePath}); using empty string`);
|
|
165577
165705
|
continue;
|
|
165578
165706
|
}
|
|
@@ -165597,7 +165725,7 @@ var init_variable = __esm(() => {
|
|
|
165597
165725
|
});
|
|
165598
165726
|
|
|
165599
165727
|
// ../plugin/src/config/index.ts
|
|
165600
|
-
import { existsSync as
|
|
165728
|
+
import { existsSync as existsSync18, readFileSync as readFileSync9 } from "node:fs";
|
|
165601
165729
|
function getUserConfigBasePath() {
|
|
165602
165730
|
return cortexKitUserConfigBasePath();
|
|
165603
165731
|
}
|
|
@@ -165605,10 +165733,10 @@ function getProjectConfigBasePath(directory) {
|
|
|
165605
165733
|
return cortexKitProjectConfigBasePath(directory);
|
|
165606
165734
|
}
|
|
165607
165735
|
function resolveLegacyReadFallback(sources) {
|
|
165608
|
-
return { source: sources.find((s) =>
|
|
165736
|
+
return { source: sources.find((s) => existsSync18(s.path)) ?? null };
|
|
165609
165737
|
}
|
|
165610
165738
|
function loadConfigFileDetailed(configPath, source) {
|
|
165611
|
-
if (!
|
|
165739
|
+
if (!existsSync18(configPath)) {
|
|
165612
165740
|
return null;
|
|
165613
165741
|
}
|
|
165614
165742
|
let rawText;
|
|
@@ -165823,8 +165951,8 @@ function loadPluginConfigDetailed(directory) {
|
|
|
165823
165951
|
const harnessLegacy = resolveLegacyConfigSourcesForHarness(directory, "opencode");
|
|
165824
165952
|
const userLegacyFallback = userDetected.format === "none" ? resolveLegacyReadFallback(harnessLegacy.user) : { source: null };
|
|
165825
165953
|
const projectLegacyFallback = projectDetected.format === "none" ? resolveLegacyReadFallback(harnessLegacy.project) : { source: null };
|
|
165826
|
-
const legacyUserUnmigrated = userDetected.format === "none" && !userLegacyFallback.source && legacySources.user.some((source) =>
|
|
165827
|
-
const legacyProjectUnmigrated = projectDetected.format === "none" && !projectLegacyFallback.source && legacySources.project.some((source) =>
|
|
165954
|
+
const legacyUserUnmigrated = userDetected.format === "none" && !userLegacyFallback.source && legacySources.user.some((source) => existsSync18(source.path));
|
|
165955
|
+
const legacyProjectUnmigrated = projectDetected.format === "none" && !projectLegacyFallback.source && legacySources.project.some((source) => existsSync18(source.path));
|
|
165828
165956
|
const userLoaded = userDetected.format !== "none" ? loadConfigFileDetailed(userDetected.path, "user") : userLegacyFallback.source ? loadConfigFileDetailed(userLegacyFallback.source.path, "user") : null;
|
|
165829
165957
|
const projectLoaded = projectDetected.format !== "none" ? loadConfigFileDetailed(projectDetected.path, "project") : projectLegacyFallback.source ? loadConfigFileDetailed(projectLegacyFallback.source.path, "project") : null;
|
|
165830
165958
|
const allWarnings = [];
|
|
@@ -166009,7 +166137,7 @@ var DEFAULT_TIMEOUT_MS = 1e4, MAX_PREVIEW_CHARS = 240;
|
|
|
166009
166137
|
// ../plugin/src/shared/tui-config.ts
|
|
166010
166138
|
import {
|
|
166011
166139
|
chmodSync as chmodSync3,
|
|
166012
|
-
existsSync as
|
|
166140
|
+
existsSync as existsSync19,
|
|
166013
166141
|
mkdirSync as mkdirSync8,
|
|
166014
166142
|
readFileSync as readFileSync10,
|
|
166015
166143
|
renameSync as renameSync3,
|
|
@@ -166059,9 +166187,9 @@ function resolveTuiConfigPath() {
|
|
|
166059
166187
|
const configDir = getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
|
|
166060
166188
|
const jsoncPath = join15(configDir, "tui.jsonc");
|
|
166061
166189
|
const jsonPath = join15(configDir, "tui.json");
|
|
166062
|
-
if (
|
|
166190
|
+
if (existsSync19(jsoncPath))
|
|
166063
166191
|
return jsoncPath;
|
|
166064
|
-
if (
|
|
166192
|
+
if (existsSync19(jsonPath))
|
|
166065
166193
|
return jsonPath;
|
|
166066
166194
|
return jsoncPath;
|
|
166067
166195
|
}
|
|
@@ -166069,7 +166197,7 @@ function ensureTuiPluginEntry() {
|
|
|
166069
166197
|
try {
|
|
166070
166198
|
const configPath = resolveTuiConfigPath();
|
|
166071
166199
|
let config2 = {};
|
|
166072
|
-
if (
|
|
166200
|
+
if (existsSync19(configPath)) {
|
|
166073
166201
|
const raw = readFileSync10(configPath, "utf-8");
|
|
166074
166202
|
config2 = import_comment_json6.parse(raw) ?? {};
|
|
166075
166203
|
}
|
|
@@ -166469,7 +166597,7 @@ var init_redaction2 = __esm(() => {
|
|
|
166469
166597
|
});
|
|
166470
166598
|
|
|
166471
166599
|
// src/lib/diagnostics-opencode.ts
|
|
166472
|
-
import { existsSync as
|
|
166600
|
+
import { existsSync as existsSync20, readdirSync as readdirSync2, readFileSync as readFileSync11, statSync as statSync7 } from "node:fs";
|
|
166473
166601
|
import { createRequire as createRequire2 } from "node:module";
|
|
166474
166602
|
import { homedir as homedir11 } from "node:os";
|
|
166475
166603
|
import { join as join16 } from "node:path";
|
|
@@ -166490,7 +166618,7 @@ function getPluginCacheInfo() {
|
|
|
166490
166618
|
let cached2;
|
|
166491
166619
|
for (const installedPkgPath of getOpenCodePluginPackageJsonPaths()) {
|
|
166492
166620
|
try {
|
|
166493
|
-
if (
|
|
166621
|
+
if (existsSync20(installedPkgPath)) {
|
|
166494
166622
|
const pkg = JSON.parse(readFileSync11(installedPkgPath, "utf-8"));
|
|
166495
166623
|
cached2 = typeof pkg.version === "string" ? pkg.version : undefined;
|
|
166496
166624
|
if (cached2)
|
|
@@ -166508,7 +166636,7 @@ function getStorageDir() {
|
|
|
166508
166636
|
}
|
|
166509
166637
|
function fileSize(path6) {
|
|
166510
166638
|
try {
|
|
166511
|
-
return
|
|
166639
|
+
return existsSync20(path6) ? statSync7(path6).size : 0;
|
|
166512
166640
|
} catch {
|
|
166513
166641
|
return 0;
|
|
166514
166642
|
}
|
|
@@ -166520,7 +166648,7 @@ function sanitizeValue(value) {
|
|
|
166520
166648
|
return sanitizeConfigValue(value);
|
|
166521
166649
|
}
|
|
166522
166650
|
function readConfig2(path6) {
|
|
166523
|
-
if (!
|
|
166651
|
+
if (!existsSync20(path6))
|
|
166524
166652
|
return { value: null };
|
|
166525
166653
|
try {
|
|
166526
166654
|
const raw = readFileSync11(path6, "utf-8");
|
|
@@ -166581,7 +166709,7 @@ function parseHistorianDumpMeta(path6) {
|
|
|
166581
166709
|
}
|
|
166582
166710
|
}
|
|
166583
166711
|
function listDumpsInDir(dir, limit) {
|
|
166584
|
-
if (!
|
|
166712
|
+
if (!existsSync20(dir))
|
|
166585
166713
|
return { count: 0, recent: [] };
|
|
166586
166714
|
try {
|
|
166587
166715
|
const entries = readdirSync2(dir).filter((name2) => name2.endsWith(".xml")).map((name2) => {
|
|
@@ -166650,7 +166778,7 @@ function collectHistorianDumps(recentSessions) {
|
|
|
166650
166778
|
}
|
|
166651
166779
|
async function collectRecentSessions() {
|
|
166652
166780
|
const opencodeDbPath = join16(homedir11(), ".local", "share", "opencode", "opencode.db");
|
|
166653
|
-
if (!
|
|
166781
|
+
if (!existsSync20(opencodeDbPath))
|
|
166654
166782
|
return [];
|
|
166655
166783
|
if (typeof globalThis.Bun === "undefined") {
|
|
166656
166784
|
return [];
|
|
@@ -166685,7 +166813,7 @@ async function collectRecentSessions() {
|
|
|
166685
166813
|
}
|
|
166686
166814
|
async function collectHistorianFailures(storageDirPath) {
|
|
166687
166815
|
const contextDbPath = join16(storageDirPath, "context.db");
|
|
166688
|
-
if (!
|
|
166816
|
+
if (!existsSync20(contextDbPath))
|
|
166689
166817
|
return [];
|
|
166690
166818
|
if (typeof globalThis.Bun === "undefined") {
|
|
166691
166819
|
return [];
|
|
@@ -166719,7 +166847,7 @@ async function collectHistorianFailures(storageDirPath) {
|
|
|
166719
166847
|
}
|
|
166720
166848
|
async function collectHistorianRuns(storageDirPath) {
|
|
166721
166849
|
const contextDbPath = join16(storageDirPath, "context.db");
|
|
166722
|
-
if (!
|
|
166850
|
+
if (!existsSync20(contextDbPath))
|
|
166723
166851
|
return [];
|
|
166724
166852
|
if (typeof globalThis.Bun === "undefined")
|
|
166725
166853
|
return [];
|
|
@@ -166790,7 +166918,7 @@ async function collectDiagnostics() {
|
|
|
166790
166918
|
const storageDirPath = getStorageDir();
|
|
166791
166919
|
const contextDbPath = join16(storageDirPath, "context.db");
|
|
166792
166920
|
const logPath = getMagicContextLogPath2("opencode");
|
|
166793
|
-
const logFileSize =
|
|
166921
|
+
const logFileSize = existsSync20(logPath) ? statSync7(logPath).size : 0;
|
|
166794
166922
|
const conflictResult = detectConflicts(process.cwd());
|
|
166795
166923
|
const recentSessions = await collectRecentSessions();
|
|
166796
166924
|
const openCodeDetection = detectOpenCode();
|
|
@@ -166809,14 +166937,14 @@ async function collectDiagnostics() {
|
|
|
166809
166937
|
opencodeConfigHasPlugin: configHasPluginEntry(opencodeConfig.value),
|
|
166810
166938
|
tuiConfigHasPlugin: configHasPluginEntry(tuiConfig.value),
|
|
166811
166939
|
magicContextConfig: {
|
|
166812
|
-
exists:
|
|
166940
|
+
exists: existsSync20(configPaths.magicContextConfig),
|
|
166813
166941
|
...magicContextConfig.error ? { parseError: magicContextConfig.error } : {},
|
|
166814
166942
|
flags: sanitizeValue(magicContextConfig.value ?? {}) ?? {}
|
|
166815
166943
|
},
|
|
166816
166944
|
pluginCache: getPluginCacheInfo(),
|
|
166817
166945
|
storageDir: {
|
|
166818
166946
|
path: storageDirPath,
|
|
166819
|
-
exists:
|
|
166947
|
+
exists: existsSync20(storageDirPath),
|
|
166820
166948
|
contextDbSizeBytes: fileSize(contextDbPath)
|
|
166821
166949
|
},
|
|
166822
166950
|
conflicts: {
|
|
@@ -166825,7 +166953,7 @@ async function collectDiagnostics() {
|
|
|
166825
166953
|
},
|
|
166826
166954
|
logFile: {
|
|
166827
166955
|
path: logPath,
|
|
166828
|
-
exists:
|
|
166956
|
+
exists: existsSync20(logPath),
|
|
166829
166957
|
sizeKb: Math.round(logFileSize / 1024)
|
|
166830
166958
|
},
|
|
166831
166959
|
recentSessions,
|
|
@@ -166964,9 +167092,113 @@ var init_diagnostics_opencode = __esm(() => {
|
|
|
166964
167092
|
});
|
|
166965
167093
|
|
|
166966
167094
|
// src/lib/embedding-runtime.ts
|
|
166967
|
-
import {
|
|
167095
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
167096
|
+
import { existsSync as existsSync21 } from "node:fs";
|
|
166968
167097
|
import { createRequire as createRequire3 } from "node:module";
|
|
166969
167098
|
import { dirname as dirname11, join as join17, sep } from "node:path";
|
|
167099
|
+
function describeError(error51) {
|
|
167100
|
+
const message = error51 instanceof Error ? error51.message : String(error51 ?? "unknown error");
|
|
167101
|
+
const code = error51?.code;
|
|
167102
|
+
return typeof code === "string" && code.length > 0 ? `${code}: ${message}` : message;
|
|
167103
|
+
}
|
|
167104
|
+
function runOnnxRuntimeNodeLoadProbeChild(packageDir) {
|
|
167105
|
+
return spawnSync2("node", ["-e", ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT], {
|
|
167106
|
+
encoding: "utf8",
|
|
167107
|
+
env: { ...process.env, [ONNX_LOAD_PROBE_PACKAGE_DIR_ENV]: packageDir },
|
|
167108
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
167109
|
+
timeout: ONNX_LOAD_PROBE_TIMEOUT_MS
|
|
167110
|
+
});
|
|
167111
|
+
}
|
|
167112
|
+
function outputText(output) {
|
|
167113
|
+
if (typeof output === "string")
|
|
167114
|
+
return output;
|
|
167115
|
+
if (Buffer.isBuffer(output))
|
|
167116
|
+
return output.toString("utf8");
|
|
167117
|
+
return "";
|
|
167118
|
+
}
|
|
167119
|
+
function outputSnippet(output) {
|
|
167120
|
+
const normalized = outputText(output).replace(/\s+/g, " ").trim();
|
|
167121
|
+
if (normalized.length <= ONNX_LOAD_PROBE_OUTPUT_LIMIT)
|
|
167122
|
+
return normalized;
|
|
167123
|
+
return `${normalized.slice(0, ONNX_LOAD_PROBE_OUTPUT_LIMIT)}…`;
|
|
167124
|
+
}
|
|
167125
|
+
function stderrSuffix(result) {
|
|
167126
|
+
const stderr = outputSnippet(result.stderr);
|
|
167127
|
+
return stderr.length > 0 ? `; stderr: ${stderr}` : "";
|
|
167128
|
+
}
|
|
167129
|
+
function stdoutSuffix(result) {
|
|
167130
|
+
const stdout2 = outputSnippet(result.stdout);
|
|
167131
|
+
return stdout2.length > 0 ? `; stdout: ${stdout2}` : "";
|
|
167132
|
+
}
|
|
167133
|
+
function parseOnnxProbeVerdict(output) {
|
|
167134
|
+
const candidates = output.trim().split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).reverse();
|
|
167135
|
+
for (const candidate of candidates) {
|
|
167136
|
+
try {
|
|
167137
|
+
const parsed = JSON.parse(candidate);
|
|
167138
|
+
if (typeof parsed.ok === "boolean") {
|
|
167139
|
+
return {
|
|
167140
|
+
ok: parsed.ok,
|
|
167141
|
+
reason: typeof parsed.reason === "string" ? parsed.reason : undefined
|
|
167142
|
+
};
|
|
167143
|
+
}
|
|
167144
|
+
} catch {}
|
|
167145
|
+
}
|
|
167146
|
+
return null;
|
|
167147
|
+
}
|
|
167148
|
+
function probeOnnxRuntimeNodeLoad(packageDir) {
|
|
167149
|
+
const result = runOnnxRuntimeNodeLoadProbeChildForRuntime(packageDir);
|
|
167150
|
+
const errorCode = result.error?.code;
|
|
167151
|
+
if (errorCode === "ETIMEDOUT") {
|
|
167152
|
+
return {
|
|
167153
|
+
state: "load-failed",
|
|
167154
|
+
packageDir,
|
|
167155
|
+
reason: `probe timed out after ${ONNX_LOAD_PROBE_TIMEOUT_MS}ms${stderrSuffix(result)}`
|
|
167156
|
+
};
|
|
167157
|
+
}
|
|
167158
|
+
if (result.error) {
|
|
167159
|
+
return {
|
|
167160
|
+
state: "load-failed",
|
|
167161
|
+
packageDir,
|
|
167162
|
+
reason: `probe process failed: ${describeError(result.error)}${stderrSuffix(result)}`
|
|
167163
|
+
};
|
|
167164
|
+
}
|
|
167165
|
+
if (result.signal) {
|
|
167166
|
+
return {
|
|
167167
|
+
state: "load-failed",
|
|
167168
|
+
packageDir,
|
|
167169
|
+
reason: `probe terminated by signal ${result.signal}${stderrSuffix(result)}`
|
|
167170
|
+
};
|
|
167171
|
+
}
|
|
167172
|
+
if (typeof result.status === "number" && result.status !== 0) {
|
|
167173
|
+
return {
|
|
167174
|
+
state: "load-failed",
|
|
167175
|
+
packageDir,
|
|
167176
|
+
reason: `probe exited with code ${result.status}${stderrSuffix(result)}`
|
|
167177
|
+
};
|
|
167178
|
+
}
|
|
167179
|
+
const verdict = parseOnnxProbeVerdict(outputText(result.stdout));
|
|
167180
|
+
if (verdict?.ok === true)
|
|
167181
|
+
return null;
|
|
167182
|
+
if (verdict?.ok === false) {
|
|
167183
|
+
return {
|
|
167184
|
+
state: "load-failed",
|
|
167185
|
+
packageDir,
|
|
167186
|
+
reason: verdict.reason ?? "onnxruntime-node failed to load"
|
|
167187
|
+
};
|
|
167188
|
+
}
|
|
167189
|
+
return {
|
|
167190
|
+
state: "load-failed",
|
|
167191
|
+
packageDir,
|
|
167192
|
+
reason: `probe returned no JSON verdict${stdoutSuffix(result)}${stderrSuffix(result)}`
|
|
167193
|
+
};
|
|
167194
|
+
}
|
|
167195
|
+
function isLocalEmbeddingRuntimeBroken(status) {
|
|
167196
|
+
return status.state === "package-missing" || status.state === "binary-missing" || status.state === "load-failed";
|
|
167197
|
+
}
|
|
167198
|
+
function formatLocalEmbeddingRuntimeDoctorWarning(status) {
|
|
167199
|
+
const cause = status.state === "package-missing" ? "package is not installed" : status.state === "binary-missing" ? "expected platform binding file is absent" : `binding failed to load: ${status.reason}`;
|
|
167200
|
+
return "Embedding provider: local — onnxruntime-node native binding missing — " + `${cause}; its postinstall likely failed. Embeddings will not work. ` + "Reinstall with network access to the npm registry and GitHub releases, " + "or switch `embedding.provider` to an HTTP endpoint (`openai-compatible`).";
|
|
167201
|
+
}
|
|
166970
167202
|
function expectedBinaryRelPath(platform, arch) {
|
|
166971
167203
|
const supportedPlatform = platform === "linux" || platform === "darwin" || platform === "win32";
|
|
166972
167204
|
const supportedArch = arch === "x64" || arch === "arm64";
|
|
@@ -166976,21 +167208,21 @@ function expectedBinaryRelPath(platform, arch) {
|
|
|
166976
167208
|
}
|
|
166977
167209
|
function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch) {
|
|
166978
167210
|
const packageDir = join17(installRoot, "node_modules", "onnxruntime-node");
|
|
166979
|
-
if (!
|
|
167211
|
+
if (!existsSync21(join17(packageDir, "package.json"))) {
|
|
166980
167212
|
return { state: "package-missing", packageDir };
|
|
166981
167213
|
}
|
|
166982
167214
|
const rel = expectedBinaryRelPath(platform, arch);
|
|
166983
167215
|
if (rel === null) {
|
|
166984
|
-
return { state: "ok", binaryPath: packageDir };
|
|
167216
|
+
return probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath: packageDir };
|
|
166985
167217
|
}
|
|
166986
167218
|
const binaryPath = join17(packageDir, rel);
|
|
166987
|
-
if (!
|
|
167219
|
+
if (!existsSync21(binaryPath)) {
|
|
166988
167220
|
return { state: "binary-missing", packageDir, expectedBinary: binaryPath };
|
|
166989
167221
|
}
|
|
166990
|
-
return { state: "ok", binaryPath };
|
|
167222
|
+
return probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath };
|
|
166991
167223
|
}
|
|
166992
167224
|
function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch) {
|
|
166993
|
-
const existing = installRoots.filter((root) =>
|
|
167225
|
+
const existing = installRoots.filter((root) => existsSync21(root));
|
|
166994
167226
|
if (existing.length === 0) {
|
|
166995
167227
|
return {
|
|
166996
167228
|
state: "unknown",
|
|
@@ -167013,7 +167245,7 @@ function packageDirFromResolved(resolvedPath, packageName) {
|
|
|
167013
167245
|
return idx >= 0 ? resolvedPath.slice(0, idx + marker.length) : dirname11(resolvedPath);
|
|
167014
167246
|
}
|
|
167015
167247
|
function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch) {
|
|
167016
|
-
if (!
|
|
167248
|
+
if (!existsSync21(join17(pluginDir, "package.json"))) {
|
|
167017
167249
|
return { state: "unknown", reason: "plugin package dir not found" };
|
|
167018
167250
|
}
|
|
167019
167251
|
let onnxDir = null;
|
|
@@ -167046,15 +167278,37 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
|
|
|
167046
167278
|
}
|
|
167047
167279
|
const rel = expectedBinaryRelPath(platform, arch);
|
|
167048
167280
|
if (rel === null) {
|
|
167049
|
-
return { state: "ok", binaryPath: onnxDir };
|
|
167281
|
+
return probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
|
|
167050
167282
|
}
|
|
167051
167283
|
const binaryPath = join17(onnxDir, rel);
|
|
167052
|
-
if (!
|
|
167284
|
+
if (!existsSync21(binaryPath)) {
|
|
167053
167285
|
return { state: "binary-missing", packageDir: onnxDir, expectedBinary: binaryPath };
|
|
167054
167286
|
}
|
|
167055
|
-
return { state: "ok", binaryPath };
|
|
167056
|
-
}
|
|
167057
|
-
var
|
|
167287
|
+
return probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath };
|
|
167288
|
+
}
|
|
167289
|
+
var ONNX_LOAD_PROBE_TIMEOUT_MS = 1e4, ONNX_LOAD_PROBE_OUTPUT_LIMIT = 800, ONNX_LOAD_PROBE_PACKAGE_DIR_ENV = "MAGIC_CONTEXT_ONNX_RUNTIME_NODE_PACKAGE_DIR", ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT, runOnnxRuntimeNodeLoadProbeChildForRuntime;
|
|
167290
|
+
var init_embedding_runtime = __esm(() => {
|
|
167291
|
+
ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT = [
|
|
167292
|
+
'const { createRequire } = require("node:module");',
|
|
167293
|
+
'const { join } = require("node:path");',
|
|
167294
|
+
"function describe(error) {",
|
|
167295
|
+
' const message = error instanceof Error ? error.message : String(error ?? "unknown error");',
|
|
167296
|
+
' const code = error && typeof error === "object" && typeof error.code === "string" ? error.code : "";',
|
|
167297
|
+
' return code ? code + ": " + message : message;',
|
|
167298
|
+
"}",
|
|
167299
|
+
"try {",
|
|
167300
|
+
` const packageDir = process.env.${ONNX_LOAD_PROBE_PACKAGE_DIR_ENV};`,
|
|
167301
|
+
` if (!packageDir) throw new Error("${ONNX_LOAD_PROBE_PACKAGE_DIR_ENV} is not set");`,
|
|
167302
|
+
' const req = createRequire(join(packageDir, "package.json"));',
|
|
167303
|
+
" req(packageDir);",
|
|
167304
|
+
" process.stdout.write(JSON.stringify({ ok: true }));",
|
|
167305
|
+
"} catch (error) {",
|
|
167306
|
+
" process.stdout.write(JSON.stringify({ ok: false, reason: describe(error) }));",
|
|
167307
|
+
"}"
|
|
167308
|
+
].join(`
|
|
167309
|
+
`);
|
|
167310
|
+
runOnnxRuntimeNodeLoadProbeChildForRuntime = runOnnxRuntimeNodeLoadProbeChild;
|
|
167311
|
+
});
|
|
167058
167312
|
|
|
167059
167313
|
// src/lib/issue-body.ts
|
|
167060
167314
|
function isErrorLogLine(line) {
|
|
@@ -167498,11 +167752,11 @@ function migrateExperimentalPinKeyFilesForDoctor(mcConfig) {
|
|
|
167498
167752
|
}
|
|
167499
167753
|
|
|
167500
167754
|
// src/commands/doctor-opencode-cache.ts
|
|
167501
|
-
import { existsSync as
|
|
167755
|
+
import { existsSync as existsSync22, readFileSync as readFileSync13, rmSync as rmSync2 } from "node:fs";
|
|
167502
167756
|
function readCachedPluginVersion(pluginCacheDir) {
|
|
167503
167757
|
try {
|
|
167504
167758
|
const installedPkgPath = getOpenCodePluginPackageJsonPath(pluginCacheDir);
|
|
167505
|
-
if (!
|
|
167759
|
+
if (!existsSync22(installedPkgPath))
|
|
167506
167760
|
return;
|
|
167507
167761
|
const pkg = JSON.parse(readFileSync13(installedPkgPath, "utf-8"));
|
|
167508
167762
|
return typeof pkg.version === "string" ? pkg.version : undefined;
|
|
@@ -167513,7 +167767,7 @@ function readCachedPluginVersion(pluginCacheDir) {
|
|
|
167513
167767
|
async function clearPluginCache(options = {}, deps = {}) {
|
|
167514
167768
|
const remove = deps.remove ?? ((path6) => rmSync2(path6, { recursive: true, force: true }));
|
|
167515
167769
|
const pluginCacheRoots = getOpenCodePluginCacheRoots();
|
|
167516
|
-
const existingRoots = pluginCacheRoots.filter((root) =>
|
|
167770
|
+
const existingRoots = pluginCacheRoots.filter((root) => existsSync22(root));
|
|
167517
167771
|
if (existingRoots.length === 0) {
|
|
167518
167772
|
return { action: "not_found", path: pluginCacheRoots[0] ?? "" };
|
|
167519
167773
|
}
|
|
@@ -167578,8 +167832,8 @@ var init_doctor_opencode_cache = __esm(() => {
|
|
|
167578
167832
|
});
|
|
167579
167833
|
|
|
167580
167834
|
// src/commands/doctor-opencode.ts
|
|
167581
|
-
import { execSync as execSync2, spawnSync as
|
|
167582
|
-
import { existsSync as
|
|
167835
|
+
import { execSync as execSync2, spawnSync as spawnSync3 } from "node:child_process";
|
|
167836
|
+
import { existsSync as existsSync23, readFileSync as readFileSync14, statSync as statSync8 } from "node:fs";
|
|
167583
167837
|
import { createRequire as createRequire4 } from "node:module";
|
|
167584
167838
|
import { homedir as homedir13 } from "node:os";
|
|
167585
167839
|
import { join as join19 } from "node:path";
|
|
@@ -167678,15 +167932,15 @@ function isGhInstalled() {
|
|
|
167678
167932
|
function openBrowser(url2) {
|
|
167679
167933
|
try {
|
|
167680
167934
|
if (process.platform === "darwin") {
|
|
167681
|
-
const child =
|
|
167935
|
+
const child = spawnSync3("open", [url2], { stdio: "ignore" });
|
|
167682
167936
|
if (child.status === 0)
|
|
167683
167937
|
return;
|
|
167684
167938
|
} else if (process.platform === "linux") {
|
|
167685
|
-
const child =
|
|
167939
|
+
const child = spawnSync3("xdg-open", [url2], { stdio: "ignore" });
|
|
167686
167940
|
if (child.status === 0)
|
|
167687
167941
|
return;
|
|
167688
167942
|
} else if (process.platform === "win32") {
|
|
167689
|
-
const child =
|
|
167943
|
+
const child = spawnSync3("cmd", ["/c", "start", "", url2], { stdio: "ignore" });
|
|
167690
167944
|
if (child.status === 0)
|
|
167691
167945
|
return;
|
|
167692
167946
|
}
|
|
@@ -167730,7 +167984,7 @@ async function runIssueFlow() {
|
|
|
167730
167984
|
s.stop(`Report written to ${bundled.path}`);
|
|
167731
167985
|
const shouldSubmit = await confirm2("Submit this issue on GitHub now?", true);
|
|
167732
167986
|
if (shouldSubmit && isGhInstalled()) {
|
|
167733
|
-
const result =
|
|
167987
|
+
const result = spawnSync3("gh", [
|
|
167734
167988
|
"issue",
|
|
167735
167989
|
"create",
|
|
167736
167990
|
"-R",
|
|
@@ -167764,15 +168018,15 @@ async function runIssueFlow() {
|
|
|
167764
168018
|
}
|
|
167765
168019
|
function checkLocalEmbeddingRuntimeForDoctor() {
|
|
167766
168020
|
const runtime = checkLocalEmbeddingRuntime(getOpenCodePluginCacheRoots());
|
|
167767
|
-
if (runtime
|
|
167768
|
-
log2.warn(
|
|
168021
|
+
if (isLocalEmbeddingRuntimeBroken(runtime)) {
|
|
168022
|
+
log2.warn(formatLocalEmbeddingRuntimeDoctorWarning(runtime));
|
|
167769
168023
|
return { issues: 1, localRuntimeBroken: true };
|
|
167770
168024
|
}
|
|
167771
168025
|
log2.success("Embedding provider: local (Xenova/all-MiniLM-L6-v2 bundled)");
|
|
167772
168026
|
return { issues: 0 };
|
|
167773
168027
|
}
|
|
167774
168028
|
async function checkEmbeddingConfig(magicContextConfigPath) {
|
|
167775
|
-
if (!
|
|
168029
|
+
if (!existsSync23(magicContextConfigPath)) {
|
|
167776
168030
|
return checkLocalEmbeddingRuntimeForDoctor();
|
|
167777
168031
|
}
|
|
167778
168032
|
let rawText;
|
|
@@ -167948,7 +168202,7 @@ async function runDoctor(options = {}) {
|
|
|
167948
168202
|
} else {
|
|
167949
168203
|
pass(`OpenCode config: ${paths.opencodeConfig}`);
|
|
167950
168204
|
}
|
|
167951
|
-
if (
|
|
168205
|
+
if (existsSync23(paths.magicContextConfig)) {
|
|
167952
168206
|
pass(`Magic Context config: ${paths.magicContextConfig}`);
|
|
167953
168207
|
try {
|
|
167954
168208
|
const raw = readFileSync14(paths.magicContextConfig, "utf-8");
|
|
@@ -167976,7 +168230,7 @@ async function runDoctor(options = {}) {
|
|
|
167976
168230
|
warn(`No magic-context.jsonc found — using defaults`);
|
|
167977
168231
|
log2.info(" Run 'setup' to create one with model recommendations");
|
|
167978
168232
|
}
|
|
167979
|
-
if (
|
|
168233
|
+
if (existsSync23(paths.magicContextConfig)) {
|
|
167980
168234
|
try {
|
|
167981
168235
|
const mcRaw = readFileSync14(paths.magicContextConfig, "utf-8");
|
|
167982
168236
|
const mcConfig = import_comment_json8.parse(mcRaw);
|
|
@@ -168167,7 +168421,7 @@ async function runDoctor(options = {}) {
|
|
|
168167
168421
|
pass("Added TUI sidebar plugin to tui.json");
|
|
168168
168422
|
warn("Restart OpenCode to see the sidebar");
|
|
168169
168423
|
fixed++;
|
|
168170
|
-
} else if (
|
|
168424
|
+
} else if (existsSync23(paths.tuiConfig)) {
|
|
168171
168425
|
try {
|
|
168172
168426
|
const tuiRaw = readFileSync14(paths.tuiConfig, "utf-8");
|
|
168173
168427
|
const tuiConfig = import_comment_json8.parse(tuiRaw);
|
|
@@ -168215,7 +168469,7 @@ async function runDoctor(options = {}) {
|
|
|
168215
168469
|
} else {
|
|
168216
168470
|
pass("TUI sidebar plugin configured (tui.json created)");
|
|
168217
168471
|
}
|
|
168218
|
-
if (
|
|
168472
|
+
if (existsSync23(paths.magicContextConfig)) {
|
|
168219
168473
|
try {
|
|
168220
168474
|
const mcRaw = readFileSync14(paths.magicContextConfig, "utf-8");
|
|
168221
168475
|
const mcConfig = import_comment_json8.parse(mcRaw);
|
|
@@ -168236,7 +168490,7 @@ async function runDoctor(options = {}) {
|
|
|
168236
168490
|
else
|
|
168237
168491
|
passCount++;
|
|
168238
168492
|
const dbPath = join19(getMagicContextStorageDir(), "context.db");
|
|
168239
|
-
if (!
|
|
168493
|
+
if (!existsSync23(dbPath)) {
|
|
168240
168494
|
log2.info(`Shared context DB not yet created at ${dbPath} (will be created on first run)`);
|
|
168241
168495
|
} else {
|
|
168242
168496
|
pass(`Shared context DB exists at ${dbPath}`);
|
|
@@ -168304,7 +168558,7 @@ async function runDoctor(options = {}) {
|
|
|
168304
168558
|
{
|
|
168305
168559
|
const ageWarnings = [];
|
|
168306
168560
|
const npmrcPath = join19(homedir13(), ".npmrc");
|
|
168307
|
-
if (
|
|
168561
|
+
if (existsSync23(npmrcPath)) {
|
|
168308
168562
|
try {
|
|
168309
168563
|
const npmrc = readFileSync14(npmrcPath, "utf-8");
|
|
168310
168564
|
for (const line of npmrc.split(`
|
|
@@ -168330,7 +168584,7 @@ async function runDoctor(options = {}) {
|
|
|
168330
168584
|
}
|
|
168331
168585
|
}
|
|
168332
168586
|
const logPath = getMagicContextLogPath2("opencode");
|
|
168333
|
-
if (
|
|
168587
|
+
if (existsSync23(logPath)) {
|
|
168334
168588
|
const logStat = statSync8(logPath);
|
|
168335
168589
|
const sizeKb = (logStat.size / 1024).toFixed(0);
|
|
168336
168590
|
log2.info(`Log file: ${logPath} (${sizeKb} KB)`);
|
|
@@ -168405,7 +168659,7 @@ var init_doctor_opencode = __esm(async () => {
|
|
|
168405
168659
|
});
|
|
168406
168660
|
|
|
168407
168661
|
// ../pi-plugin/src/config/index.ts
|
|
168408
|
-
import { existsSync as
|
|
168662
|
+
import { existsSync as existsSync24, readFileSync as readFileSync15 } from "node:fs";
|
|
168409
168663
|
function getProjectConfigPaths(cwd) {
|
|
168410
168664
|
const basePath = cortexKitProjectConfigBasePath(cwd);
|
|
168411
168665
|
return [`${basePath}.jsonc`, `${basePath}.json`];
|
|
@@ -168415,10 +168669,10 @@ function getUserConfigPaths() {
|
|
|
168415
168669
|
return [`${basePath}.jsonc`, `${basePath}.json`];
|
|
168416
168670
|
}
|
|
168417
168671
|
function resolveFirstExisting(paths) {
|
|
168418
|
-
return paths.find((path6) =>
|
|
168672
|
+
return paths.find((path6) => existsSync24(path6));
|
|
168419
168673
|
}
|
|
168420
168674
|
function resolvePiLegacyFallback(sources) {
|
|
168421
|
-
return sources.find((source) =>
|
|
168675
|
+
return sources.find((source) => existsSync24(source.path)) ?? null;
|
|
168422
168676
|
}
|
|
168423
168677
|
function loadConfigFile(path6, scope) {
|
|
168424
168678
|
try {
|
|
@@ -168555,7 +168809,7 @@ function loadPiConfig(opts = {}) {
|
|
|
168555
168809
|
if (loaded)
|
|
168556
168810
|
loadedFiles.push(loaded);
|
|
168557
168811
|
}
|
|
168558
|
-
const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) =>
|
|
168812
|
+
const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync24(source.path));
|
|
168559
168813
|
const userPath = resolveFirstExisting(getUserConfigPaths());
|
|
168560
168814
|
const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
|
|
168561
168815
|
const userReadPath = userPath ?? userLegacyFallback?.path;
|
|
@@ -168564,7 +168818,7 @@ function loadPiConfig(opts = {}) {
|
|
|
168564
168818
|
if (loaded)
|
|
168565
168819
|
loadedFiles.push(loaded);
|
|
168566
168820
|
}
|
|
168567
|
-
const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) =>
|
|
168821
|
+
const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync24(source.path));
|
|
168568
168822
|
if (userLegacyFallback) {
|
|
168569
168823
|
warnings.push(`[user config] reading legacy config from ${userLegacyFallback.path} until migration completes; run \`npx @cortexkit/magic-context doctor\` to consolidate into the shared CortexKit location.`);
|
|
168570
168824
|
} else if (legacyUserUnmigrated) {
|
|
@@ -168618,7 +168872,7 @@ var init_config2 = __esm(() => {
|
|
|
168618
168872
|
|
|
168619
168873
|
// src/lib/diagnostics-pi.ts
|
|
168620
168874
|
import { createHash as createHash3 } from "node:crypto";
|
|
168621
|
-
import { existsSync as
|
|
168875
|
+
import { existsSync as existsSync25, readdirSync as readdirSync3, readFileSync as readFileSync16, statSync as statSync9 } from "node:fs";
|
|
168622
168876
|
import { createRequire as createRequire5 } from "node:module";
|
|
168623
168877
|
import { homedir as homedir14, userInfo as userInfo2 } from "node:os";
|
|
168624
168878
|
import { join as join20 } from "node:path";
|
|
@@ -168636,7 +168890,7 @@ function getSelfVersion3() {
|
|
|
168636
168890
|
}
|
|
168637
168891
|
function fileSize2(path6) {
|
|
168638
168892
|
try {
|
|
168639
|
-
return
|
|
168893
|
+
return existsSync25(path6) ? statSync9(path6).size : 0;
|
|
168640
168894
|
} catch {
|
|
168641
168895
|
return 0;
|
|
168642
168896
|
}
|
|
@@ -168686,7 +168940,7 @@ function sanitizeValue2(value, key = "") {
|
|
|
168686
168940
|
return value;
|
|
168687
168941
|
}
|
|
168688
168942
|
function readJsonc3(path6) {
|
|
168689
|
-
if (!
|
|
168943
|
+
if (!existsSync25(path6))
|
|
168690
168944
|
return { value: {} };
|
|
168691
168945
|
try {
|
|
168692
168946
|
return {
|
|
@@ -168706,7 +168960,7 @@ function readConfigDiagnostic(path6) {
|
|
|
168706
168960
|
const parsed = readJsonc3(path6);
|
|
168707
168961
|
return {
|
|
168708
168962
|
path: path6,
|
|
168709
|
-
exists:
|
|
168963
|
+
exists: existsSync25(path6),
|
|
168710
168964
|
...parsed.parseError ? { parseError: parsed.parseError } : {},
|
|
168711
168965
|
flags: sanitizeValue2(parsed.value)
|
|
168712
168966
|
};
|
|
@@ -168724,7 +168978,7 @@ function reverseSlugToDirectory(slug) {
|
|
|
168724
168978
|
}
|
|
168725
168979
|
function collectPiRecentSessions() {
|
|
168726
168980
|
const sessionsRoot = join20(homedir14(), ".pi", "agent", "sessions");
|
|
168727
|
-
if (!
|
|
168981
|
+
if (!existsSync25(sessionsRoot))
|
|
168728
168982
|
return [];
|
|
168729
168983
|
try {
|
|
168730
168984
|
const slugs = readdirSync3(sessionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
@@ -168793,7 +169047,7 @@ function parseHistorianDumpMeta2(path6) {
|
|
|
168793
169047
|
}
|
|
168794
169048
|
}
|
|
168795
169049
|
function listDumpsInDir2(dir, limit) {
|
|
168796
|
-
if (!
|
|
169050
|
+
if (!existsSync25(dir))
|
|
168797
169051
|
return { count: 0, recent: [] };
|
|
168798
169052
|
try {
|
|
168799
169053
|
const entries = readdirSync3(dir).filter((name2) => name2.endsWith(".xml")).map((name2) => {
|
|
@@ -168871,7 +169125,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
|
|
|
168871
169125
|
const storageDirPath = getMagicContextStorageDir();
|
|
168872
169126
|
const dbPath = join20(storageDirPath, "context.db");
|
|
168873
169127
|
const logPath = getMagicContextLogPath2("pi");
|
|
168874
|
-
const logFileSize =
|
|
169128
|
+
const logFileSize = existsSync25(logPath) ? statSync9(logPath).size : 0;
|
|
168875
169129
|
const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
|
|
168876
169130
|
const recentSessions = collectPiRecentSessions();
|
|
168877
169131
|
const historianDumps = collectPiHistorianDumps(recentSessions);
|
|
@@ -168886,7 +169140,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
|
|
|
168886
169140
|
piVersion: pi ? getPiVersion(pi.path) : null,
|
|
168887
169141
|
settings: {
|
|
168888
169142
|
path: settingsPath,
|
|
168889
|
-
exists:
|
|
169143
|
+
exists: existsSync25(settingsPath),
|
|
168890
169144
|
...settingsParsed.parseError ? { parseError: settingsParsed.parseError } : {},
|
|
168891
169145
|
hasMagicContextPackage: hasPiMagicContextPackage(packages),
|
|
168892
169146
|
packages: sanitizeValue2(packages)
|
|
@@ -168902,7 +169156,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
|
|
|
168902
169156
|
loadWarnings: loaded.warnings.map(sanitizeString2),
|
|
168903
169157
|
storageDir: {
|
|
168904
169158
|
path: storageDirPath,
|
|
168905
|
-
exists:
|
|
169159
|
+
exists: existsSync25(storageDirPath),
|
|
168906
169160
|
contextDbSizeBytes: fileSize2(dbPath)
|
|
168907
169161
|
},
|
|
168908
169162
|
conflicts: {
|
|
@@ -168911,7 +169165,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
|
|
|
168911
169165
|
},
|
|
168912
169166
|
logFile: {
|
|
168913
169167
|
path: logPath,
|
|
168914
|
-
exists:
|
|
169168
|
+
exists: existsSync25(logPath),
|
|
168915
169169
|
sizeKb: Math.round(logFileSize / 1024)
|
|
168916
169170
|
},
|
|
168917
169171
|
recentSessions,
|
|
@@ -169082,8 +169336,8 @@ var init_logs_pi = __esm(() => {
|
|
|
169082
169336
|
});
|
|
169083
169337
|
|
|
169084
169338
|
// src/commands/doctor-pi.ts
|
|
169085
|
-
import { execFileSync as execFileSync5, spawnSync as
|
|
169086
|
-
import { existsSync as
|
|
169339
|
+
import { execFileSync as execFileSync5, spawnSync as spawnSync4 } from "node:child_process";
|
|
169340
|
+
import { existsSync as existsSync26, mkdirSync as mkdirSync9, readdirSync as readdirSync4, readFileSync as readFileSync18, rmSync as rmSync3, statSync as statSync10 } from "node:fs";
|
|
169087
169341
|
import { createRequire as createRequire6 } from "node:module";
|
|
169088
169342
|
import { homedir as homedir15 } from "node:os";
|
|
169089
169343
|
import { dirname as dirname12, isAbsolute as isAbsolute3, join as join22 } from "node:path";
|
|
@@ -169200,13 +169454,13 @@ function piPluginDirCandidates(packages, cwd) {
|
|
|
169200
169454
|
}
|
|
169201
169455
|
dirs.push(join22(agentDir, "npm", "node_modules", PACKAGE_NAME));
|
|
169202
169456
|
dirs.push(join22(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME));
|
|
169203
|
-
return dirs.filter((dir) =>
|
|
169457
|
+
return dirs.filter((dir) => existsSync26(join22(dir, "package.json")));
|
|
169204
169458
|
}
|
|
169205
169459
|
function projectConfigPath(cwd) {
|
|
169206
169460
|
return resolveCortexKitProjectConfigPath(cwd);
|
|
169207
169461
|
}
|
|
169208
169462
|
function readConfigForEmbedding(path6, isProjectConfig) {
|
|
169209
|
-
if (!
|
|
169463
|
+
if (!existsSync26(path6))
|
|
169210
169464
|
return null;
|
|
169211
169465
|
try {
|
|
169212
169466
|
const rawText = readFileSync18(path6, "utf-8");
|
|
@@ -169281,7 +169535,7 @@ function cacheRoots() {
|
|
|
169281
169535
|
function findPiMagicContextCacheDirs(self, force = false) {
|
|
169282
169536
|
const found = new Map;
|
|
169283
169537
|
const visit = (path6, depth) => {
|
|
169284
|
-
if (depth < 0 || !
|
|
169538
|
+
if (depth < 0 || !existsSync26(path6))
|
|
169285
169539
|
return;
|
|
169286
169540
|
let stat;
|
|
169287
169541
|
try {
|
|
@@ -169292,7 +169546,7 @@ function findPiMagicContextCacheDirs(self, force = false) {
|
|
|
169292
169546
|
if (!stat.isDirectory())
|
|
169293
169547
|
return;
|
|
169294
169548
|
const packageJson = join22(path6, "package.json");
|
|
169295
|
-
if (
|
|
169549
|
+
if (existsSync26(packageJson)) {
|
|
169296
169550
|
try {
|
|
169297
169551
|
const pkg = JSON.parse(readFileSync18(packageJson, "utf-8"));
|
|
169298
169552
|
const name2 = typeof pkg.name === "string" ? pkg.name : "";
|
|
@@ -169351,7 +169605,7 @@ async function runHealthChecks(options) {
|
|
|
169351
169605
|
}
|
|
169352
169606
|
const settingsPath = getPiUserExtensionsPath();
|
|
169353
169607
|
let packages = [];
|
|
169354
|
-
if (!
|
|
169608
|
+
if (!existsSync26(settingsPath)) {
|
|
169355
169609
|
add(results, "warn", `Pi settings not found at ${settingsPath}`);
|
|
169356
169610
|
repairPlan.addPackageEntry = true;
|
|
169357
169611
|
} else {
|
|
@@ -169375,7 +169629,7 @@ async function runHealthChecks(options) {
|
|
|
169375
169629
|
["user", userConfigPath, true],
|
|
169376
169630
|
["project", projectPath, false]
|
|
169377
169631
|
]) {
|
|
169378
|
-
if (!
|
|
169632
|
+
if (!existsSync26(path6)) {
|
|
169379
169633
|
if (required2) {
|
|
169380
169634
|
add(results, "warn", `No ${label} magic-context.jsonc found at ${path6}`);
|
|
169381
169635
|
if (userConfigMigrationRefused) {
|
|
@@ -169413,7 +169667,7 @@ async function runHealthChecks(options) {
|
|
|
169413
169667
|
}
|
|
169414
169668
|
const storageDir = getMagicContextStorageDir();
|
|
169415
169669
|
const dbPath = join22(storageDir, "context.db");
|
|
169416
|
-
const existedBeforeOpen =
|
|
169670
|
+
const existedBeforeOpen = existsSync26(dbPath);
|
|
169417
169671
|
if (existedBeforeOpen)
|
|
169418
169672
|
add(results, "pass", `Shared context DB exists at ${dbPath}`);
|
|
169419
169673
|
else
|
|
@@ -169491,8 +169745,8 @@ async function runHealthChecks(options) {
|
|
|
169491
169745
|
runtimeReported = true;
|
|
169492
169746
|
break;
|
|
169493
169747
|
}
|
|
169494
|
-
if (runtime
|
|
169495
|
-
add(results, "warn",
|
|
169748
|
+
if (isLocalEmbeddingRuntimeBroken(runtime)) {
|
|
169749
|
+
add(results, "warn", formatLocalEmbeddingRuntimeDoctorWarning(runtime));
|
|
169496
169750
|
runtimeReported = true;
|
|
169497
169751
|
break;
|
|
169498
169752
|
}
|
|
@@ -169521,7 +169775,7 @@ async function runHealthChecks(options) {
|
|
|
169521
169775
|
add(results, "pass", "Pi extension cache clean (no stale cached package found)");
|
|
169522
169776
|
}
|
|
169523
169777
|
const logPath = getMagicContextLogPath2("pi");
|
|
169524
|
-
if (
|
|
169778
|
+
if (existsSync26(logPath)) {
|
|
169525
169779
|
const stat = statSync10(logPath);
|
|
169526
169780
|
const sizeKb = (stat.size / 1024).toFixed(0);
|
|
169527
169781
|
const lines = readFileSync18(logPath, "utf-8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
@@ -169581,7 +169835,7 @@ function repair(plan, prompts) {
|
|
|
169581
169835
|
}
|
|
169582
169836
|
if (plan.writeUserConfig) {
|
|
169583
169837
|
const configPath = getPiUserConfigPath();
|
|
169584
|
-
if (!
|
|
169838
|
+
if (!existsSync26(configPath)) {
|
|
169585
169839
|
try {
|
|
169586
169840
|
writeDefaultMagicContextConfig(configPath);
|
|
169587
169841
|
prompts.log.success(`Wrote default Magic Context config to ${configPath}`);
|
|
@@ -169790,7 +170044,7 @@ var init_doctor_pi = __esm(async () => {
|
|
|
169790
170044
|
closeDatabase,
|
|
169791
170045
|
now: () => new Date,
|
|
169792
170046
|
execFileSync: execFileSync5,
|
|
169793
|
-
spawnSync:
|
|
170047
|
+
spawnSync: spawnSync4
|
|
169794
170048
|
};
|
|
169795
170049
|
});
|
|
169796
170050
|
|
|
@@ -169799,7 +170053,7 @@ var exports_doctor = {};
|
|
|
169799
170053
|
__export(exports_doctor, {
|
|
169800
170054
|
runDoctor: () => runDoctor3
|
|
169801
170055
|
});
|
|
169802
|
-
import { existsSync as
|
|
170056
|
+
import { existsSync as existsSync27, rmSync as rmSync4 } from "node:fs";
|
|
169803
170057
|
async function runDoctor3(options) {
|
|
169804
170058
|
if (options.clear)
|
|
169805
170059
|
return runClear();
|
|
@@ -169888,7 +170142,7 @@ async function runClear() {
|
|
|
169888
170142
|
const s = spinner2();
|
|
169889
170143
|
s.start(`Clearing ${item.path}`);
|
|
169890
170144
|
try {
|
|
169891
|
-
if (
|
|
170145
|
+
if (existsSync27(item.path)) {
|
|
169892
170146
|
rmSync4(item.path, { recursive: true, force: true });
|
|
169893
170147
|
}
|
|
169894
170148
|
s.stop(`Cleared ${item.path}`);
|