@cortexkit/magic-context 0.49.57 → 0.49.59

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.
Files changed (2) hide show
  1. package/dist/index.js +265 -178
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1756,9 +1756,6 @@ function getMagicContextHistorianDir(harness = getHarness()) {
1756
1756
  function getProjectMagicContextDir(directory) {
1757
1757
  return path.join(directory, ".cortexkit", "magic-context");
1758
1758
  }
1759
- function getProjectMagicContextHistorianDir(directory) {
1760
- return path.join(getProjectMagicContextDir(directory), "historian");
1761
- }
1762
1759
  function getOpenCodeStorageDir() {
1763
1760
  return path.join(getDataDir(), "opencode", "storage");
1764
1761
  }
@@ -16005,6 +16002,9 @@ function getMagicContextLogPath2(harness) {
16005
16002
  function getMagicContextHistorianDir2(harness) {
16006
16003
  return getMagicContextHistorianDir(harness);
16007
16004
  }
16005
+ function getProjectHistorianDumpDir(directory) {
16006
+ return join7(getProjectMagicContextDir(directory), "historian");
16007
+ }
16008
16008
  function getOpenCodePluginCacheDir() {
16009
16009
  const xdg = process.env.XDG_CACHE_HOME || join7(homedir7(), ".cache");
16010
16010
  return join7(xdg, "opencode", "packages");
@@ -48470,6 +48470,7 @@ var init_issue_log_templates_generated = __esm(() => {
48470
48470
  "[magic-context] sqlite writer site=compaction-marker-replace db=opencode acquire_ms=\x01 hold_ms=\x01 work_ms=\x01 end_ms=\x01 outcome=not_acquired",
48471
48471
  "system prompt hash changed: \x01 → \x01 (len=\x01), adopting on the request whose messages are already final; presetChanged=unknown elements=[\x01]",
48472
48472
  "[magic-context] host stall profiler enabled: threshold \x01ms, sample interval \x01ms, clock calibration unavailable, setup \x01ms, reports in \x01",
48473
+ "prefix trim: boundary \x01; pass=priced; no in-pass trim applied (Refusing a prompt that names more than one Magic Context hidden run)",
48473
48474
  "compaction-marker drain: refusing ordinal \x01 because prefix trim through \x01 was not proven; preserving deferred history refresh signal\x021i",
48474
48475
  "[magic-context] conflict-detector: resolved v2 config carried no explicit compaction.auto (\x01); falling back to file-based detection",
48475
48476
  "[magic-context] sqlite writer site=compaction-marker-inject db=opencode acquire_ms=\x01 hold_ms=\x01 work_ms=\x01 end_ms=\x01 outcome=not_acquired",
@@ -48477,6 +48478,7 @@ var init_issue_log_templates_generated = __esm(() => {
48477
48478
  "auto-search: decision outcome=timeout reason=worker-busy lanes=\x01 nearMisses=\x01 threshold=\x01 pool=\x01 rows=\x01 workerStarted=\x01 peek=\x01 elapsedMs=\x01",
48478
48479
  "history boundary repair: the cached prefix boundary \x01 is not in the host store; rebuilding it on this pass against compartment end \x01\x021i",
48479
48480
  "rust compaction-marker admission deferred: reason=output_fit fit=\x01 estimated=\x01 trusted=\x01 proxy_tokens=unavailable proxy_bytes=\x01 limit=\x01",
48481
+ "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Refusing a prompt that names more than one Magic Context hidden run)",
48480
48482
  "prefix trim: boundary \x01; pass=priced; no in-pass trim applied (Hidden child history does not contain this run's registered marker)",
48481
48483
  "[magic-context] boot phase 'hooks' exceeded the whole-server \x01ms budget; host startup will continue with Magic Context fail-closed",
48482
48484
  "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Hidden child history does not contain this run's registered marker)",
@@ -48807,6 +48809,7 @@ var init_issue_log_templates_generated = __esm(() => {
48807
48809
  "historian publish stage: stage=dangling-boundary-check status=started elapsed=0.0ms compartments=\x01",
48808
48810
  "Pi compaction-marker clear: reason=active-branch-retired endMessageId=\x01 ordinal=\x01 firstKeptEntryId=\x01\x020i",
48809
48811
  "v2 refusal: interrupting the turn before the provider request arm=blocking-transform-error cause=\x01",
48812
+ "Oh My Pi spawned session (agent kind sub) has compartments from its source session: kept primary",
48810
48813
  "[dreamer] verify safety refusal: memory_id=\x01 verdict=archive reason=directive-shaped-project-rule",
48811
48814
  "[dreamer] map-memories: all \x01 path(s) for memory \x01 were rejected; recording host_rejected_fallback",
48812
48815
  "transform: model switch \x01 -> \x01/\x01 reset — percentage=\x01% tokens=\x01 — clearing stale model-specific state\x020s,1m,2m",
@@ -49164,9 +49167,12 @@ var init_issue_log_templates_generated = __esm(() => {
49164
49167
  "historian publish stage: stage=validate status=completed elapsed=\x01ms compartments=\x01",
49165
49168
  "mc-pass-stage session=\x01 stage=historian_inline_wait event=end outcome=\x01 elapsed_ms=\x01\x020s",
49166
49169
  "transform: over-window first-pass check could not estimate the incoming history: \x01",
49170
+ "ctx_reduce served record failed after the request was decided; serving the pass:",
49167
49171
  "final wire usage capture failed after the request was decided; serving the pass:",
49168
49172
  "Pi publication commit_failed reason=envelope_unreadable; serving managed context",
49169
49173
  "Pi publication commit_failed reason=number_write_failed; serving managed context",
49174
+ "request tool list changed: ctx_reduce added; tag prefixes return on this rebuild",
49175
+ "request tool list changed: ctx_reduce removed; tag prefixes stop on this rebuild",
49170
49176
  "transform refused degraded pass site=merged-reasoning-strip-persistence-failure:",
49171
49177
  "model changed (\x01/\x01 -> \x01/\x01), clearing historian failure state and reasoning watermark\x020m,1m,2m,3m",
49172
49178
  "prompt_surface.guidance_override_path (\x01) is not a file; using built-in guidance.\x020p",
@@ -49658,6 +49664,7 @@ var init_issue_log_templates_generated = __esm(() => {
49658
49664
  "channel2 terminal-run intent clear failed; leaving lease to heal:",
49659
49665
  "compaction-off render changed the head: stripping signed thinking",
49660
49666
  "historian publish stage: stage=parse status=started elapsed=0.0ms",
49667
+ "Oh My Pi spawned session (agent kind sub): recorded as a subagent",
49661
49668
  "transform refused degraded pass site=m0-m1-injection-degradation:",
49662
49669
  "transform refused degraded pass site=overflow-state-read-failure:",
49663
49670
  "transform refused degraded pass site=tagging-persistence-failure:",
@@ -50763,6 +50770,7 @@ var init_issue_log_templates_generated = __esm(() => {
50763
50770
  "[migrations] migration worker ready: \x01\x020p",
50764
50771
  "collectMessageEntryIdsStrict failed: \x01",
50765
50772
  "compartment agent: finalizer failed: \x01",
50773
+ "ctx_reduce served record unreadable: \x01",
50766
50774
  "dreamer token budget: finalize fired \x01",
50767
50775
  "event session.error handling failed: \x01",
50768
50776
  "host checkpoint head: changed=\x01 proof=\x01",
@@ -50779,6 +50787,8 @@ var init_issue_log_templates_generated = __esm(() => {
50779
50787
  "WARN: shutdown: dreamer drain threw: \x01",
50780
50788
  "[dreamer] scheduled task run failed:",
50781
50789
  "compartment agent: finalizer failed:",
50790
+ "ctx_reduce served record not written",
50791
+ "ctx_reduce served record unreadable:",
50782
50792
  "dreamer token budget: finalize fired",
50783
50793
  "event session.error handling failed:",
50784
50794
  "lkg wrapper replay fit check failed:",
@@ -53975,10 +53985,45 @@ var init_tui_config = __esm(() => {
53975
53985
  PLUGIN_ENTRY = `${PLUGIN_NAME2}@latest`;
53976
53986
  });
53977
53987
 
53988
+ // src/lib/historian-dump-dirs.ts
53989
+ import { existsSync as existsSync46, readdirSync as readdirSync10, statSync as statSync25 } from "node:fs";
53990
+ import { join as join36 } from "node:path";
53991
+ function scanHistorianDumpFiles(dir) {
53992
+ if (!existsSync46(dir))
53993
+ return [];
53994
+ try {
53995
+ return readdirSync10(dir).filter((name) => name.endsWith(".xml")).map((name) => {
53996
+ const stat = statSync25(join36(dir, name));
53997
+ return { name, mtime: stat.mtimeMs, sizeKb: Math.round(stat.size / 1024) };
53998
+ }).sort((a, b) => b.mtime - a.mtime);
53999
+ } catch {
54000
+ return [];
54001
+ }
54002
+ }
54003
+ function scanHistorianSessionDumpDirs(root) {
54004
+ if (!existsSync46(root))
54005
+ return [];
54006
+ const sessions = [];
54007
+ try {
54008
+ for (const entry of readdirSync10(root, { withFileTypes: true })) {
54009
+ if (!entry.isDirectory())
54010
+ continue;
54011
+ const dir = join36(root, entry.name);
54012
+ const files = scanHistorianDumpFiles(dir);
54013
+ if (files.length > 0)
54014
+ sessions.push({ sessionId: entry.name, dir, files });
54015
+ }
54016
+ } catch {
54017
+ return [];
54018
+ }
54019
+ return sessions.sort((a, b) => (b.files[0]?.mtime ?? 0) - (a.files[0]?.mtime ?? 0));
54020
+ }
54021
+ var init_historian_dump_dirs = () => {};
54022
+
53978
54023
  // src/lib/diagnostics-opencode.ts
53979
- import { existsSync as existsSync46, readdirSync as readdirSync10, readFileSync as readFileSync29, statSync as statSync25 } from "node:fs";
54024
+ import { existsSync as existsSync47, readFileSync as readFileSync29, statSync as statSync26 } from "node:fs";
53980
54025
  import { createRequire as createRequire4 } from "node:module";
53981
- import { join as join36 } from "node:path";
54026
+ import { join as join37 } from "node:path";
53982
54027
  function getSelfVersion() {
53983
54028
  const require2 = createRequire4(import.meta.url);
53984
54029
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -54002,7 +54047,7 @@ function readLegacyCachedVersion(root) {
54002
54047
  function collectOpenCodePluginCacheReport(hostGeneration, opencodeConfig, npmVersions = {}) {
54003
54048
  const installs = [];
54004
54049
  for (const root of getOpenCodePluginCacheRoots()) {
54005
- if (!existsSync46(root))
54050
+ if (!existsSync47(root))
54006
54051
  continue;
54007
54052
  const spec = root.endsWith("@latest") ? "latest" : "(bare)";
54008
54053
  installs.push({
@@ -54050,7 +54095,7 @@ function getStorageResolution() {
54050
54095
  }
54051
54096
  function fileSize(path) {
54052
54097
  try {
54053
- return existsSync46(path) ? statSync25(path).size : 0;
54098
+ return existsSync47(path) ? statSync26(path).size : 0;
54054
54099
  } catch {
54055
54100
  return 0;
54056
54101
  }
@@ -54062,7 +54107,7 @@ function sanitizeValue(value) {
54062
54107
  return sanitizeConfigValue(value);
54063
54108
  }
54064
54109
  function readConfig3(path) {
54065
- if (!existsSync46(path))
54110
+ if (!existsSync47(path))
54066
54111
  return { value: null };
54067
54112
  try {
54068
54113
  const raw = readFileSync29(path, "utf-8");
@@ -54122,46 +54167,36 @@ function parseHistorianDumpMeta(path) {
54122
54167
  return { error: error instanceof Error ? error.message : String(error) };
54123
54168
  }
54124
54169
  }
54170
+ function summarizeDumps(dir, files, limit) {
54171
+ const now = Date.now();
54172
+ return files.slice(0, limit).map((entry) => {
54173
+ const meta = parseHistorianDumpMeta(join37(dir, entry.name));
54174
+ const summary = {
54175
+ name: entry.name,
54176
+ ageMinutes: Math.round((now - entry.mtime) / 60000),
54177
+ sizeKb: entry.sizeKb
54178
+ };
54179
+ if ("error" in meta) {
54180
+ summary.parseError = meta.error;
54181
+ } else {
54182
+ summary.meta = meta;
54183
+ }
54184
+ return summary;
54185
+ });
54186
+ }
54125
54187
  function listDumpsInDir(dir, limit) {
54126
- if (!existsSync46(dir))
54127
- return { count: 0, recent: [] };
54128
- try {
54129
- const entries = readdirSync10(dir).filter((name) => name.endsWith(".xml")).map((name) => {
54130
- const stat = statSync25(join36(dir, name));
54131
- return {
54132
- name,
54133
- mtime: stat.mtimeMs,
54134
- sizeKb: Math.round(stat.size / 1024)
54135
- };
54136
- }).sort((a, b) => b.mtime - a.mtime);
54137
- const now = Date.now();
54138
- const recent = entries.slice(0, limit).map((entry) => {
54139
- const meta = parseHistorianDumpMeta(join36(dir, entry.name));
54140
- const summary = {
54141
- name: entry.name,
54142
- ageMinutes: Math.round((now - entry.mtime) / 60000),
54143
- sizeKb: entry.sizeKb
54144
- };
54145
- if ("error" in meta) {
54146
- summary.parseError = meta.error;
54147
- } else {
54148
- summary.meta = meta;
54149
- }
54150
- return summary;
54151
- });
54152
- return { count: entries.length, recent };
54153
- } catch {
54154
- return { count: 0, recent: [] };
54155
- }
54188
+ const files = scanHistorianDumpFiles(dir);
54189
+ return { count: files.length, recent: summarizeDumps(dir, files, limit) };
54156
54190
  }
54157
- function collectHistorianDumps(recentSessions) {
54191
+ function collectHistorianDumps(recentSessions, historianRoot = getMagicContextHistorianDir2("opencode")) {
54192
+ const sessionDirs = scanHistorianSessionDumpDirs(historianRoot);
54158
54193
  const buckets = new Map;
54159
54194
  for (const session of recentSessions) {
54160
54195
  const dir = session.directory;
54161
54196
  if (!dir)
54162
54197
  continue;
54163
- const projectHistorianDir = getProjectMagicContextHistorianDir(dir);
54164
- const listing = listDumpsInDir(projectHistorianDir, 5);
54198
+ const projectHistorianDir = getProjectHistorianDumpDir(dir);
54199
+ const listing = listDumpsInDir(projectHistorianDir, DUMPS_PER_BUCKET_LIMIT);
54165
54200
  const existing = buckets.get(dir);
54166
54201
  if (existing) {
54167
54202
  if (!existing.sessionIds.includes(session.sessionId)) {
@@ -54179,12 +54214,21 @@ function collectHistorianDumps(recentSessions) {
54179
54214
  recent: listing.recent
54180
54215
  });
54181
54216
  }
54182
- const legacyDir = getMagicContextHistorianDir2("opencode");
54183
- const legacyListing = listDumpsInDir(legacyDir, 5);
54217
+ const legacyListing = listDumpsInDir(historianRoot, DUMPS_PER_BUCKET_LIMIT);
54184
54218
  return {
54219
+ sessionDumps: {
54220
+ dir: historianRoot,
54221
+ count: sessionDirs.reduce((sum, session) => sum + session.files.length, 0),
54222
+ sessionCount: sessionDirs.length,
54223
+ sessions: sessionDirs.slice(0, SESSION_DUMP_BUCKET_LIMIT).map((session) => ({
54224
+ sessionId: session.sessionId,
54225
+ count: session.files.length,
54226
+ recent: summarizeDumps(session.dir, session.files, DUMPS_PER_BUCKET_LIMIT)
54227
+ }))
54228
+ },
54185
54229
  byProject: [...buckets.values()],
54186
54230
  legacyDumps: {
54187
- dir: legacyDir,
54231
+ dir: historianRoot,
54188
54232
  count: legacyListing.count,
54189
54233
  recent: legacyListing.recent
54190
54234
  }
@@ -54247,7 +54291,7 @@ function collectRecentSessionsFromDatabase(database) {
54247
54291
  });
54248
54292
  }
54249
54293
  async function collectDatabaseRows(path, read) {
54250
- if (!existsSync46(path))
54294
+ if (!existsSync47(path))
54251
54295
  return { available: false, reason: "path missing" };
54252
54296
  let backend;
54253
54297
  try {
@@ -54279,7 +54323,7 @@ async function collectRecentSessions(resolution, hostGeneration) {
54279
54323
  });
54280
54324
  }
54281
54325
  async function collectHistorianFailures(storageDirPath) {
54282
- return collectDatabaseRows(join36(storageDirPath, "context.db"), (db) => {
54326
+ return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54283
54327
  const rows = db.prepare("SELECT session_id, historian_failure_count, historian_last_error, historian_last_failure_at FROM session_meta WHERE historian_failure_count > 0 ORDER BY historian_last_failure_at DESC LIMIT 10").all();
54284
54328
  return rows.map((row) => {
54285
54329
  const sessionId = typeof row.session_id === "string" ? row.session_id : "<unknown>";
@@ -54292,7 +54336,7 @@ async function collectHistorianFailures(storageDirPath) {
54292
54336
  });
54293
54337
  }
54294
54338
  async function collectHistorianRuns(storageDirPath) {
54295
- return collectDatabaseRows(join36(storageDirPath, "context.db"), (db) => {
54339
+ return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54296
54340
  const aggRows = db.prepare(`SELECT session_id,
54297
54341
  COUNT(*) AS total,
54298
54342
  SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS success,
@@ -54347,7 +54391,7 @@ async function collectDiagnostics(options = {}) {
54347
54391
  const magicContextConfig = readConfig3(configPaths.magicContextConfig);
54348
54392
  const storageResolution = getStorageResolution();
54349
54393
  const storageDirPath = storageResolution.path;
54350
- const contextDbPath = join36(storageDirPath, "context.db");
54394
+ const contextDbPath = join37(storageDirPath, "context.db");
54351
54395
  let compactionEnabled = false;
54352
54396
  try {
54353
54397
  compactionEnabled = isCompactionEnabled(loadPluginConfig(process.cwd()));
@@ -54379,7 +54423,7 @@ async function collectDiagnostics(options = {}) {
54379
54423
  opencodeConfigHasPlugin: configHasPluginEntry(opencodeConfig.value),
54380
54424
  tuiConfigHasPlugin: configHasPluginEntry(tuiConfig.value),
54381
54425
  magicContextConfig: {
54382
- exists: existsSync46(configPaths.magicContextConfig),
54426
+ exists: existsSync47(configPaths.magicContextConfig),
54383
54427
  ...magicContextConfig.error ? { parseError: magicContextConfig.error } : {},
54384
54428
  flags: sanitizeValue(magicContextConfig.value ?? {}) ?? {}
54385
54429
  },
@@ -54387,7 +54431,7 @@ async function collectDiagnostics(options = {}) {
54387
54431
  storageDir: {
54388
54432
  path: storageDirPath,
54389
54433
  source: storageResolution.source,
54390
- exists: existsSync46(storageDirPath),
54434
+ exists: existsSync47(storageDirPath),
54391
54435
  contextDbSizeBytes: fileSize(contextDbPath)
54392
54436
  },
54393
54437
  openCodeDatabase: {
@@ -54458,6 +54502,12 @@ function renderDiagnosticsMarkdown(report) {
54458
54502
  ...openCodeInstallations.map((installation) => `| ${installation.active ? "[active]" : ""} | \`${sanitizeString(installation.path)}\` | ${installation.version} | ${installation.source} |`)
54459
54503
  ] : [];
54460
54504
  const historianDumps = {
54505
+ sessionDumps: {
54506
+ dir: sanitizeString(report.historianDumps.sessionDumps.dir),
54507
+ count: report.historianDumps.sessionDumps.count,
54508
+ sessionCount: report.historianDumps.sessionDumps.sessionCount,
54509
+ sessions: report.historianDumps.sessionDumps.sessions
54510
+ },
54461
54511
  byProject: report.historianDumps.byProject.map((bucket) => ({
54462
54512
  directory: sanitizeString(bucket.directory),
54463
54513
  primarySessionId: bucket.primarySessionId,
@@ -54522,7 +54572,7 @@ function renderDiagnosticsMarkdown(report) {
54522
54572
  "",
54523
54573
  "### Historian dumps",
54524
54574
  "(Metadata only — XML content is not included in this report.)",
54525
- "Dumps are stored per-project under `<project>/.cortexkit/magic-context/historian/`.",
54575
+ "`sessionDumps` lists the per-session directories under `<temp dir>/opencode/magic-context/historian/` that current plugins write to. `byProject` lists dumps that plugins up to 0.49.57 wrote under `<project>/.cortexkit/magic-context/historian/`, and `legacyDumps` those from plugins before 0.18.",
54526
54576
  "```json",
54527
54577
  JSON.stringify(historianDumps, null, 2),
54528
54578
  "```",
@@ -54550,7 +54600,7 @@ function renderDiagnosticsMarkdown(report) {
54550
54600
  ].join(`
54551
54601
  `);
54552
54602
  }
54553
- var import_comment_json10, RECENT_SESSION_GROUP_LIMIT = 5, CHILD_SESSIONS_PER_PARENT_LIMIT = 3;
54603
+ var import_comment_json10, SESSION_DUMP_BUCKET_LIMIT = 10, DUMPS_PER_BUCKET_LIMIT = 5, RECENT_SESSION_GROUP_LIMIT = 5, CHILD_SESSIONS_PER_PARENT_LIMIT = 3;
54554
54604
  var init_diagnostics_opencode = __esm(async () => {
54555
54605
  init_config();
54556
54606
  init_agent_disable();
@@ -54558,6 +54608,7 @@ var init_diagnostics_opencode = __esm(async () => {
54558
54608
  init_conflict_detector();
54559
54609
  init_data_path();
54560
54610
  init_opencode_db_path();
54611
+ init_historian_dump_dirs();
54561
54612
  init_log_lines();
54562
54613
  init_opencode_detect();
54563
54614
  init_opencode_helpers();
@@ -54661,9 +54712,9 @@ var init_embedding_local = __esm(async () => {
54661
54712
 
54662
54713
  // src/lib/embedding-runtime.ts
54663
54714
  import { spawnSync as spawnSync9 } from "node:child_process";
54664
- import { existsSync as existsSync47, readFileSync as readFileSync30 } from "node:fs";
54715
+ import { existsSync as existsSync48, readFileSync as readFileSync30 } from "node:fs";
54665
54716
  import { createRequire as createRequire5 } from "node:module";
54666
- import { dirname as dirname25, join as join37, sep as sep2 } from "node:path";
54717
+ import { dirname as dirname25, join as join38, sep as sep2 } from "node:path";
54667
54718
  function describeError(error) {
54668
54719
  const message = error instanceof Error ? error.message : String(error ?? "unknown error");
54669
54720
  const code = error?.code;
@@ -54805,11 +54856,11 @@ function expectedBinaryRelPath(platform, arch) {
54805
54856
  const supportedArch = arch === "x64" || arch === "arm64";
54806
54857
  if (!supportedPlatform || !supportedArch)
54807
54858
  return null;
54808
- return join37("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54859
+ return join38("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54809
54860
  }
54810
54861
  function onnxRuntimeNodeVersion(packageDir) {
54811
54862
  try {
54812
- const parsed = JSON.parse(readFileSync30(join37(packageDir, "package.json"), "utf8"));
54863
+ const parsed = JSON.parse(readFileSync30(join38(packageDir, "package.json"), "utf8"));
54813
54864
  return typeof parsed.version === "string" ? parsed.version : undefined;
54814
54865
  } catch {
54815
54866
  return;
@@ -54858,7 +54909,7 @@ function formatLocalEmbeddingRuntimeWasmSelected(status) {
54858
54909
  function requireNodeWasmBundle(probe, candidates) {
54859
54910
  if (probe.state === "failed")
54860
54911
  return probe;
54861
- const bundlePath = candidates.find((candidate) => existsSync47(candidate));
54912
+ const bundlePath = candidates.find((candidate) => existsSync48(candidate));
54862
54913
  return bundlePath ? probe : {
54863
54914
  state: "failed",
54864
54915
  reason: `functional Node WASM Transformers bundle is missing (checked ${candidates.join(", ")})`
@@ -54866,13 +54917,13 @@ function requireNodeWasmBundle(probe, candidates) {
54866
54917
  }
54867
54918
  function nodeWasmBundleCandidates(installRoot) {
54868
54919
  return [
54869
- join37(installRoot, "dist", "transformers-node-wasm.js"),
54870
- join37(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
54871
- join37(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
54920
+ join38(installRoot, "dist", "transformers-node-wasm.js"),
54921
+ join38(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
54922
+ join38(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
54872
54923
  ];
54873
54924
  }
54874
54925
  function probeWasmRuntimeAt(installRoot) {
54875
- const requireFn = createRequire5(join37(installRoot, "package.json"));
54926
+ const requireFn = createRequire5(join38(installRoot, "package.json"));
54876
54927
  return requireNodeWasmBundle(probeWasmRuntimeFromRequire(requireFn), nodeWasmBundleCandidates(installRoot));
54877
54928
  }
54878
54929
  function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
@@ -54881,9 +54932,9 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54881
54932
  const wasm = probeWasmRuntimeAt(installRoot);
54882
54933
  return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
54883
54934
  }
54884
- const packageDir = join37(installRoot, "node_modules", "onnxruntime-node");
54935
+ const packageDir = join38(installRoot, "node_modules", "onnxruntime-node");
54885
54936
  let native;
54886
- if (!existsSync47(join37(packageDir, "package.json"))) {
54937
+ if (!existsSync48(join38(packageDir, "package.json"))) {
54887
54938
  native = { state: "package-missing", packageDir };
54888
54939
  } else {
54889
54940
  const rel = expectedBinaryRelPath(platform, arch);
@@ -54893,8 +54944,8 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54893
54944
  binaryPath: packageDir
54894
54945
  };
54895
54946
  } else {
54896
- const binaryPath = join37(packageDir, rel);
54897
- native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
54947
+ const binaryPath = join38(packageDir, rel);
54948
+ native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
54898
54949
  state: "binary-missing",
54899
54950
  packageDir,
54900
54951
  expectedBinary: binaryPath,
@@ -54905,7 +54956,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54905
54956
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
54906
54957
  }
54907
54958
  function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
54908
- const existing = installRoots.filter((root) => existsSync47(root));
54959
+ const existing = installRoots.filter((root) => existsSync48(root));
54909
54960
  if (existing.length === 0) {
54910
54961
  return {
54911
54962
  state: "unknown",
@@ -54935,15 +54986,15 @@ function packageDirFromResolved(resolvedPath, packageName) {
54935
54986
  }
54936
54987
  function probeWasmRuntimeByResolution(pluginDir) {
54937
54988
  try {
54938
- const reqPlugin = createRequire5(join37(pluginDir, "package.json"));
54989
+ const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
54939
54990
  const direct = probeWasmRuntimeFromRequire(reqPlugin);
54940
54991
  let probe = direct;
54941
54992
  if (direct.state === "failed" && direct.reason.startsWith("onnxruntime-web is not resolvable")) {
54942
54993
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
54943
54994
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
54944
- probe = probeWasmRuntimeFromRequire(createRequire5(join37(tfDir, "package.json")));
54995
+ probe = probeWasmRuntimeFromRequire(createRequire5(join38(tfDir, "package.json")));
54945
54996
  }
54946
- return requireNodeWasmBundle(probe, [join37(pluginDir, "dist", "transformers-node-wasm.js")]);
54997
+ return requireNodeWasmBundle(probe, [join38(pluginDir, "dist", "transformers-node-wasm.js")]);
54947
54998
  } catch (error) {
54948
54999
  return {
54949
55000
  state: "failed",
@@ -54952,7 +55003,7 @@ function probeWasmRuntimeByResolution(pluginDir) {
54952
55003
  }
54953
55004
  }
54954
55005
  function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
54955
- if (!existsSync47(join37(pluginDir, "package.json"))) {
55006
+ if (!existsSync48(join38(pluginDir, "package.json"))) {
54956
55007
  return { state: "unknown", reason: "plugin package dir not found" };
54957
55008
  }
54958
55009
  const selectedRuntime = resolveLocalEmbeddingWorkerRuntime(runtimePreference, host);
@@ -54963,13 +55014,13 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54963
55014
  let onnxDir = null;
54964
55015
  let resolveError;
54965
55016
  try {
54966
- const reqPlugin = createRequire5(join37(pluginDir, "package.json"));
55017
+ const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
54967
55018
  try {
54968
55019
  onnxDir = packageDirFromResolved(reqPlugin.resolve("onnxruntime-node"), "onnxruntime-node");
54969
55020
  } catch {
54970
55021
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
54971
55022
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
54972
- const reqTf = createRequire5(join37(tfDir, "package.json"));
55023
+ const reqTf = createRequire5(join38(tfDir, "package.json"));
54973
55024
  onnxDir = packageDirFromResolved(reqTf.resolve("onnxruntime-node"), "onnxruntime-node");
54974
55025
  }
54975
55026
  } catch (error) {
@@ -54977,7 +55028,7 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54977
55028
  if (resolveError === "ERR_MODULE_NOT_FOUND" || resolveError === "MODULE_NOT_FOUND") {
54978
55029
  return withWasmFallback({
54979
55030
  state: "package-missing",
54980
- packageDir: join37(pluginDir, "node_modules", "onnxruntime-node")
55031
+ packageDir: join38(pluginDir, "node_modules", "onnxruntime-node")
54981
55032
  }, () => probeWasmRuntimeByResolution(pluginDir));
54982
55033
  }
54983
55034
  return {
@@ -54993,8 +55044,8 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54993
55044
  if (rel === null) {
54994
55045
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
54995
55046
  } else {
54996
- const binaryPath = join37(onnxDir, rel);
54997
- native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
55047
+ const binaryPath = join38(onnxDir, rel);
55048
+ native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
54998
55049
  state: "binary-missing",
54999
55050
  packageDir: onnxDir,
55000
55051
  expectedBinary: binaryPath,
@@ -55030,7 +55081,7 @@ var init_embedding_runtime = __esm(async () => {
55030
55081
 
55031
55082
  // src/lib/logs-opencode.ts
55032
55083
  import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "node:fs";
55033
- import { dirname as dirname26, join as join38 } from "node:path";
55084
+ import { dirname as dirname26, join as join39 } from "node:path";
55034
55085
  function formatTimestamp(date) {
55035
55086
  const pad = (value) => String(value).padStart(2, "0");
55036
55087
  return [
@@ -55121,11 +55172,11 @@ async function bundleIssueReport(report, description, title, sessionFilter = nul
55121
55172
  const bodyMarkdown = capBodyToGithubLimit(rawBodyMarkdown);
55122
55173
  const truncated = bodyMarkdown !== rawBodyMarkdown;
55123
55174
  const timestamp = formatTimestamp(new Date);
55124
- const path = options.outputPath ?? join38(process.cwd(), `magic-context-issue-${timestamp}.md`);
55175
+ const path = options.outputPath ?? join39(process.cwd(), `magic-context-issue-${timestamp}.md`);
55125
55176
  mkdirSync9(dirname26(path), { recursive: true });
55126
55177
  writeFileSync9(path, `${bodyMarkdown}
55127
55178
  `);
55128
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join38(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55179
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join39(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55129
55180
  if (fullPath)
55130
55181
  writeFileSync9(fullPath, `${rawBodyMarkdown}
55131
55182
  `);
@@ -55946,10 +55997,10 @@ function removeDeprecatedReasoningAge(config) {
55946
55997
 
55947
55998
  // src/commands/doctor-opencode.ts
55948
55999
  import { spawnSync as spawnSync10 } from "node:child_process";
55949
- import { existsSync as existsSync48, mkdtempSync as mkdtempSync4, readFileSync as readFileSync31, rmSync as rmSync9 } from "node:fs";
56000
+ import { existsSync as existsSync49, mkdtempSync as mkdtempSync4, readFileSync as readFileSync31, rmSync as rmSync9 } from "node:fs";
55950
56001
  import { createRequire as createRequire6 } from "node:module";
55951
56002
  import { homedir as homedir21, tmpdir as tmpdir4 } from "node:os";
55952
- import { dirname as dirname27, join as join39, resolve as resolve19 } from "node:path";
56003
+ import { dirname as dirname27, join as join40, resolve as resolve19 } from "node:path";
55953
56004
  function formatSharedDbRowCounts(db) {
55954
56005
  return SHARED_DB_ROW_COUNT_TABLES.map((table) => {
55955
56006
  try {
@@ -56020,7 +56071,7 @@ function checkConfiguredVariantCatalog(config, hostGeneration, warn, run = (args
56020
56071
  }
56021
56072
  if (models.length === 0)
56022
56073
  return;
56023
- const tempRoot = mkdtempSync4(join39(tmpdir4(), "magic-context-opencode-catalog-"));
56074
+ const tempRoot = mkdtempSync4(join40(tmpdir4(), "magic-context-opencode-catalog-"));
56024
56075
  try {
56025
56076
  const command = hostGeneration === "v2" ? ["api", "model.list", "--param", `directory=${projectDir}`] : ["models", "--verbose"];
56026
56077
  const guidance = `opencode ${command.join(" ")}`;
@@ -56196,7 +56247,7 @@ function getSelfVersion2() {
56196
56247
  function describeAutoUpdateStall(specifier, autoUpdateEnabled, storageDir = getMagicContextStorageDir()) {
56197
56248
  if (!autoUpdateEnabled || !isPinnedOpenCodePluginSpecifier(specifier))
56198
56249
  return null;
56199
- const state = readAutoUpdateCheckState(join39(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56250
+ const state = readAutoUpdateCheckState(join40(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56200
56251
  const owner = isUpdaterPinnedSpec(state, specifier) ? "updater" : "you";
56201
56252
  return `auto-update: stalled — config pinned to ${specifier} (by ${owner})`;
56202
56253
  }
@@ -56205,12 +56256,12 @@ function getUserNpmrcPath() {
56205
56256
  if (custom)
56206
56257
  return custom;
56207
56258
  const home = process.env.HOME?.trim();
56208
- return join39(home || homedir21(), ".npmrc");
56259
+ return join40(home || homedir21(), ".npmrc");
56209
56260
  }
56210
56261
  function collectNpmReleaseAgeWarnings() {
56211
56262
  const ageWarnings = [];
56212
56263
  const npmrcPath = getUserNpmrcPath();
56213
- if (!existsSync48(npmrcPath))
56264
+ if (!existsSync49(npmrcPath))
56214
56265
  return ageWarnings;
56215
56266
  try {
56216
56267
  const npmrc = readFileSync31(npmrcPath, "utf-8");
@@ -56402,7 +56453,7 @@ function checkLocalEmbeddingRuntimeForDoctor(installRoots, runtimePreference = "
56402
56453
  return { issues: 0 };
56403
56454
  }
56404
56455
  async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56405
- if (!existsSync48(magicContextConfigPath)) {
56456
+ if (!existsSync49(magicContextConfigPath)) {
56406
56457
  return checkLocalEmbeddingRuntimeForDoctor(installRoots);
56407
56458
  }
56408
56459
  let rawText;
@@ -56583,7 +56634,7 @@ async function runDoctor2(options = {}) {
56583
56634
  const v22Result = await runV22BackfillCommands({
56584
56635
  name: "OpenCode",
56585
56636
  openDatabase: (readonly = true) => {
56586
- const dbPath = join39(getMagicContextStorageDir(), "context.db");
56637
+ const dbPath = join40(getMagicContextStorageDir(), "context.db");
56587
56638
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
56588
56639
  return v22Db;
56589
56640
  },
@@ -56619,7 +56670,7 @@ async function runDoctor2(options = {}) {
56619
56670
  if (isMagicContextStorageOutsideEngram(storageDir)) {
56620
56671
  warn(`Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
56621
56672
  }
56622
- const authorityDbPath = join39(getMagicContextStorageDir(), "context.db");
56673
+ const authorityDbPath = join40(getMagicContextStorageDir(), "context.db");
56623
56674
  let authorityDb = null;
56624
56675
  try {
56625
56676
  authorityDb = openExistingContextDatabase(authorityDbPath, { readonly: true });
@@ -56794,7 +56845,7 @@ async function runDoctor2(options = {}) {
56794
56845
  pass(`OpenCode config: ${paths.opencodeConfig}`);
56795
56846
  }
56796
56847
  let autoUpdateEnabled = true;
56797
- if (existsSync48(paths.magicContextConfig)) {
56848
+ if (existsSync49(paths.magicContextConfig)) {
56798
56849
  pass(`Magic Context config: ${paths.magicContextConfig}`);
56799
56850
  try {
56800
56851
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
@@ -56832,7 +56883,7 @@ async function runDoctor2(options = {}) {
56832
56883
  log3.info(rerankConfigSummary());
56833
56884
  log3.info(" Run 'setup' to create one with model recommendations");
56834
56885
  }
56835
- if (existsSync48(paths.magicContextConfig)) {
56886
+ if (existsSync49(paths.magicContextConfig)) {
56836
56887
  try {
56837
56888
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
56838
56889
  if (!raw)
@@ -57065,7 +57116,7 @@ async function runDoctor2(options = {}) {
57065
57116
  pass("Added TUI sidebar plugin to tui.json");
57066
57117
  warn("Restart OpenCode to see the sidebar");
57067
57118
  fixed++;
57068
- } else if (existsSync48(paths.tuiConfig)) {
57119
+ } else if (existsSync49(paths.tuiConfig)) {
57069
57120
  try {
57070
57121
  const tuiRaw = readFileSync31(paths.tuiConfig, "utf-8");
57071
57122
  const tuiConfig = import_comment_json11.parse(tuiRaw);
@@ -57106,7 +57157,7 @@ async function runDoctor2(options = {}) {
57106
57157
  fail("Could not create or verify the TUI sidebar config");
57107
57158
  }
57108
57159
  }
57109
- if (existsSync48(paths.magicContextConfig)) {
57160
+ if (existsSync49(paths.magicContextConfig)) {
57110
57161
  try {
57111
57162
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
57112
57163
  if (!raw)
@@ -57125,7 +57176,7 @@ async function runDoctor2(options = {}) {
57125
57176
  embeddingHostConfig = import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8"));
57126
57177
  } catch {}
57127
57178
  const embeddingInstalls = getOpenCodeLoadedPluginInstallRoots(hostGeneration, embeddingHostConfig);
57128
- const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync48(root));
57179
+ const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync49(root));
57129
57180
  if (unusedInstalls.length > 0)
57130
57181
  log3.info(`Local embedding runtime: checked only the copy ${hostGeneration === "v2" ? "OpenCode 2" : "OpenCode 1"} loads; other installed copies (not loaded, not checked): ${unusedInstalls.join(", ")}`);
57131
57182
  const embeddingCheck = await checkEmbeddingConfig(paths.magicContextConfig, embeddingInstalls.loaded);
@@ -57137,9 +57188,9 @@ async function runDoctor2(options = {}) {
57137
57188
  else
57138
57189
  passCount++;
57139
57190
  const storage = getMagicContextStorageResolution();
57140
- const dbPath = join39(storage.path, "context.db");
57191
+ const dbPath = join40(storage.path, "context.db");
57141
57192
  log3.info(`Shared storage: ${storage.path} (source: ${storage.source})`);
57142
- if (!existsSync48(dbPath)) {
57193
+ if (!existsSync49(dbPath)) {
57143
57194
  log3.info(`Shared context DB not yet created at ${dbPath} (will be created on first run)`);
57144
57195
  } else {
57145
57196
  log3.info(`Shared context DB exists at ${dbPath}`);
@@ -57327,11 +57378,29 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
57327
57378
  }
57328
57379
  }
57329
57380
  const diagnostics = await collectDiagnostics();
57381
+ const sessionDumps = diagnostics.historianDumps.sessionDumps;
57382
+ if (sessionDumps.count > 0) {
57383
+ warn(`Historian debug dumps: ${sessionDumps.count} file(s) across ${sessionDumps.sessionCount} session(s) in ${sessionDumps.dir}`);
57384
+ for (const session of sessionDumps.sessions) {
57385
+ log3.info(` [${session.sessionId}] ${session.count} file(s)`);
57386
+ for (const dump of session.recent.slice(0, 3)) {
57387
+ const age = dump.ageMinutes;
57388
+ const ageStr = age < 60 ? `${age}m ago` : `${Math.round(age / 60)}h ago`;
57389
+ log3.info(` ${dump.name} (${ageStr})`);
57390
+ }
57391
+ if (session.count > 3) {
57392
+ log3.info(` ... and ${session.count - 3} more`);
57393
+ }
57394
+ }
57395
+ if (sessionDumps.sessionCount > sessionDumps.sessions.length) {
57396
+ log3.info(` ... and ${sessionDumps.sessionCount - sessionDumps.sessions.length} more session(s)`);
57397
+ }
57398
+ }
57330
57399
  const dumpBuckets = diagnostics.historianDumps.byProject;
57331
57400
  if (dumpBuckets.length > 0) {
57332
57401
  const totalCount = dumpBuckets.reduce((sum, b) => sum + b.count, 0);
57333
57402
  const sessionCount = dumpBuckets.length;
57334
- warn(`Historian debug dumps: ${totalCount} file(s) across ${sessionCount} project(s)`);
57403
+ warn(`Historian debug dumps from older plugins in project directories: ${totalCount} file(s) across ${sessionCount} project(s)`);
57335
57404
  for (const bucket of dumpBuckets) {
57336
57405
  log3.info(` [${bucket.directory}] ${bucket.count} file(s)`);
57337
57406
  for (const dump of bucket.recent.slice(0, 3)) {
@@ -57676,9 +57745,9 @@ var init_model_chain_health = __esm(() => {
57676
57745
  });
57677
57746
 
57678
57747
  // src/lib/diagnostics-pi.ts
57679
- import { existsSync as existsSync49, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync26 } from "node:fs";
57748
+ import { existsSync as existsSync50, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync27 } from "node:fs";
57680
57749
  import { createRequire as createRequire7 } from "node:module";
57681
- import { join as join40 } from "node:path";
57750
+ import { join as join41 } from "node:path";
57682
57751
  function getSelfVersion3() {
57683
57752
  const req = createRequire7(import.meta.url);
57684
57753
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -57693,7 +57762,7 @@ function getSelfVersion3() {
57693
57762
  }
57694
57763
  function fileSize2(path) {
57695
57764
  try {
57696
- return existsSync49(path) ? statSync26(path).size : 0;
57765
+ return existsSync50(path) ? statSync27(path).size : 0;
57697
57766
  } catch {
57698
57767
  return 0;
57699
57768
  }
@@ -57705,7 +57774,7 @@ function sanitizeValue2(value) {
57705
57774
  return sanitizeConfigValue(value);
57706
57775
  }
57707
57776
  function readJsonc(path) {
57708
- if (!existsSync49(path))
57777
+ if (!existsSync50(path))
57709
57778
  return { value: {} };
57710
57779
  try {
57711
57780
  return {
@@ -57725,7 +57794,7 @@ function readConfigDiagnostic(path) {
57725
57794
  const parsed = readJsonc(path);
57726
57795
  return {
57727
57796
  path,
57728
- exists: existsSync49(path),
57797
+ exists: existsSync50(path),
57729
57798
  ...parsed.parseError ? { parseError: parsed.parseError } : {},
57730
57799
  flags: sanitizeValue2(parsed.value)
57731
57800
  };
@@ -57743,7 +57812,7 @@ function reverseSlugToDirectory(slug) {
57743
57812
  }
57744
57813
  function collectPiRecentSessions() {
57745
57814
  const sessionsRoot = getPiSessionsRoot();
57746
- if (!existsSync49(sessionsRoot))
57815
+ if (!existsSync50(sessionsRoot))
57747
57816
  return [];
57748
57817
  try {
57749
57818
  const slugs = readdirSync11(sessionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
@@ -57752,7 +57821,7 @@ function collectPiRecentSessions() {
57752
57821
  const directory = reverseSlugToDirectory(slug);
57753
57822
  if (!directory)
57754
57823
  continue;
57755
- const slugDir = join40(sessionsRoot, slug);
57824
+ const slugDir = join41(sessionsRoot, slug);
57756
57825
  let files;
57757
57826
  try {
57758
57827
  files = readdirSync11(slugDir).filter((name) => name.endsWith(".jsonl"));
@@ -57761,7 +57830,7 @@ function collectPiRecentSessions() {
57761
57830
  }
57762
57831
  for (const file of files) {
57763
57832
  try {
57764
- const mtime = statSync26(join40(slugDir, file)).mtimeMs;
57833
+ const mtime = statSync27(join41(slugDir, file)).mtimeMs;
57765
57834
  const sessionId = file.replace(/\.jsonl$/, "");
57766
57835
  candidates.push({ sessionId, directory, mtime });
57767
57836
  } catch {}
@@ -57811,46 +57880,36 @@ function parseHistorianDumpMeta2(path) {
57811
57880
  return { error: error instanceof Error ? error.message : String(error) };
57812
57881
  }
57813
57882
  }
57883
+ function summarizeDumps2(dir, files, limit) {
57884
+ const now = Date.now();
57885
+ return files.slice(0, limit).map((entry) => {
57886
+ const meta = parseHistorianDumpMeta2(join41(dir, entry.name));
57887
+ const summary = {
57888
+ name: entry.name,
57889
+ ageMinutes: Math.round((now - entry.mtime) / 60000),
57890
+ sizeKb: entry.sizeKb
57891
+ };
57892
+ if ("error" in meta) {
57893
+ summary.parseError = meta.error;
57894
+ } else {
57895
+ summary.meta = meta;
57896
+ }
57897
+ return summary;
57898
+ });
57899
+ }
57814
57900
  function listDumpsInDir2(dir, limit) {
57815
- if (!existsSync49(dir))
57816
- return { count: 0, recent: [] };
57817
- try {
57818
- const entries = readdirSync11(dir).filter((name) => name.endsWith(".xml")).map((name) => {
57819
- const stat = statSync26(join40(dir, name));
57820
- return {
57821
- name,
57822
- mtime: stat.mtimeMs,
57823
- sizeKb: Math.round(stat.size / 1024)
57824
- };
57825
- }).sort((a, b) => b.mtime - a.mtime);
57826
- const now = Date.now();
57827
- const recent = entries.slice(0, limit).map((entry) => {
57828
- const meta = parseHistorianDumpMeta2(join40(dir, entry.name));
57829
- const summary = {
57830
- name: entry.name,
57831
- ageMinutes: Math.round((now - entry.mtime) / 60000),
57832
- sizeKb: entry.sizeKb
57833
- };
57834
- if ("error" in meta) {
57835
- summary.parseError = meta.error;
57836
- } else {
57837
- summary.meta = meta;
57838
- }
57839
- return summary;
57840
- });
57841
- return { count: entries.length, recent };
57842
- } catch {
57843
- return { count: 0, recent: [] };
57844
- }
57901
+ const files = scanHistorianDumpFiles(dir);
57902
+ return { count: files.length, recent: summarizeDumps2(dir, files, limit) };
57845
57903
  }
57846
- function collectPiHistorianDumps(recentSessions) {
57904
+ function collectPiHistorianDumps(recentSessions, historianRoot = getMagicContextHistorianDir2("pi")) {
57905
+ const sessionDirs = scanHistorianSessionDumpDirs(historianRoot);
57847
57906
  const buckets = new Map;
57848
57907
  for (const session of recentSessions) {
57849
57908
  const dir = session.directory;
57850
57909
  if (!dir)
57851
57910
  continue;
57852
- const projectHistorianDir = getProjectMagicContextHistorianDir(dir);
57853
- const listing = listDumpsInDir2(projectHistorianDir, 5);
57911
+ const projectHistorianDir = getProjectHistorianDumpDir(dir);
57912
+ const listing = listDumpsInDir2(projectHistorianDir, DUMPS_PER_BUCKET_LIMIT2);
57854
57913
  const existing = buckets.get(dir);
57855
57914
  if (existing) {
57856
57915
  if (!existing.sessionIds.includes(session.sessionId)) {
@@ -57868,12 +57927,21 @@ function collectPiHistorianDumps(recentSessions) {
57868
57927
  recent: listing.recent
57869
57928
  });
57870
57929
  }
57871
- const legacyDir = getMagicContextHistorianDir2("pi");
57872
- const legacyListing = listDumpsInDir2(legacyDir, 5);
57930
+ const legacyListing = listDumpsInDir2(historianRoot, DUMPS_PER_BUCKET_LIMIT2);
57873
57931
  return {
57932
+ sessionDumps: {
57933
+ dir: historianRoot,
57934
+ count: sessionDirs.reduce((sum, session) => sum + session.files.length, 0),
57935
+ sessionCount: sessionDirs.length,
57936
+ sessions: sessionDirs.slice(0, SESSION_DUMP_BUCKET_LIMIT2).map((session) => ({
57937
+ sessionId: session.sessionId,
57938
+ count: session.files.length,
57939
+ recent: summarizeDumps2(session.dir, session.files, DUMPS_PER_BUCKET_LIMIT2)
57940
+ }))
57941
+ },
57874
57942
  byProject: [...buckets.values()],
57875
57943
  legacyDumps: {
57876
- dir: legacyDir,
57944
+ dir: historianRoot,
57877
57945
  count: legacyListing.count,
57878
57946
  recent: legacyListing.recent
57879
57947
  }
@@ -57889,7 +57957,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57889
57957
  const loaded = loadPiConfig({ cwd });
57890
57958
  const storageResolution = getMagicContextStorageResolution();
57891
57959
  const storageDirPath = storageResolution.path;
57892
- const dbPath = join40(storageDirPath, "context.db");
57960
+ const dbPath = join41(storageDirPath, "context.db");
57893
57961
  const logFiles = inspectMagicContextLogs("pi");
57894
57962
  const primaryLog = logFiles.find((file) => file.exists) ?? logFiles[0];
57895
57963
  const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
@@ -57906,7 +57974,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57906
57974
  piVersion: pi ? getPiVersion(pi.path) : null,
57907
57975
  settings: {
57908
57976
  path: settingsPath,
57909
- exists: existsSync49(settingsPath),
57977
+ exists: existsSync50(settingsPath),
57910
57978
  ...settingsParsed.parseError ? { parseError: settingsParsed.parseError } : {},
57911
57979
  hasMagicContextPackage: hasPiMagicContextPackage(packages),
57912
57980
  packages: sanitizeValue2(packages)
@@ -57923,7 +57991,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57923
57991
  storageDir: {
57924
57992
  path: storageDirPath,
57925
57993
  source: storageResolution.source,
57926
- exists: existsSync49(storageDirPath),
57994
+ exists: existsSync50(storageDirPath),
57927
57995
  contextDbSizeBytes: fileSize2(dbPath)
57928
57996
  },
57929
57997
  conflicts: {
@@ -58015,12 +58083,13 @@ function renderDiagnosticsMarkdown2(report) {
58015
58083
  ].join(`
58016
58084
  `);
58017
58085
  }
58018
- var import_comment_json12;
58086
+ var import_comment_json12, SESSION_DUMP_BUCKET_LIMIT2 = 10, DUMPS_PER_BUCKET_LIMIT2 = 5;
58019
58087
  var init_diagnostics_pi = __esm(() => {
58020
58088
  init_migrate_config_location();
58021
58089
  init_compartment_parser();
58022
58090
  init_data_path();
58023
58091
  init_config2();
58092
+ init_historian_dump_dirs();
58024
58093
  init_log_lines();
58025
58094
  init_paths();
58026
58095
  init_pi_helpers();
@@ -58031,7 +58100,7 @@ var init_diagnostics_pi = __esm(() => {
58031
58100
 
58032
58101
  // src/lib/logs-pi.ts
58033
58102
  import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync10 } from "node:fs";
58034
- import { dirname as dirname28, join as join41 } from "node:path";
58103
+ import { dirname as dirname28, join as join42 } from "node:path";
58035
58104
  function formatTimestamp2(date) {
58036
58105
  const pad = (value) => String(value).padStart(2, "0");
58037
58106
  return [
@@ -58085,11 +58154,11 @@ async function bundleIssueReport2(report, description, title, options = {}) {
58085
58154
  const truncated = bodyMarkdown !== rawBodyMarkdown;
58086
58155
  const cwd = options.cwd ?? process.cwd();
58087
58156
  const timestamp = formatTimestamp2(options.now ?? new Date);
58088
- const path = options.outputPath ?? join41(cwd, `magic-context-pi-issue-${timestamp}.md`);
58157
+ const path = options.outputPath ?? join42(cwd, `magic-context-pi-issue-${timestamp}.md`);
58089
58158
  mkdirSync10(dirname28(path), { recursive: true });
58090
58159
  writeFileSync10(path, `${bodyMarkdown}
58091
58160
  `);
58092
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join41(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
58161
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join42(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
58093
58162
  if (fullPath)
58094
58163
  writeFileSync10(fullPath, `${rawBodyMarkdown}
58095
58164
  `);
@@ -58103,10 +58172,10 @@ var init_logs_pi = __esm(() => {
58103
58172
 
58104
58173
  // src/commands/doctor-pi.ts
58105
58174
  import { execFileSync as execFileSync9, spawnSync as spawnSync11 } from "node:child_process";
58106
- import { existsSync as existsSync50, readdirSync as readdirSync12, readFileSync as readFileSync33, rmSync as rmSync10, statSync as statSync27 } from "node:fs";
58175
+ import { existsSync as existsSync51, readdirSync as readdirSync12, readFileSync as readFileSync33, rmSync as rmSync10, statSync as statSync28 } from "node:fs";
58107
58176
  import { createRequire as createRequire8 } from "node:module";
58108
58177
  import { homedir as homedir22 } from "node:os";
58109
- import { isAbsolute as isAbsolute9, join as join42 } from "node:path";
58178
+ import { isAbsolute as isAbsolute9, join as join43 } from "node:path";
58110
58179
  function depsFrom(options) {
58111
58180
  return {
58112
58181
  ...DEFAULT_DEPS5,
@@ -58248,15 +58317,15 @@ function piPluginDirCandidates(packages, cwd) {
58248
58317
  if (resolved)
58249
58318
  dirs.push(resolved);
58250
58319
  }
58251
- dirs.push(join42(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58252
- dirs.push(join42(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58253
- return dirs.filter((dir) => existsSync50(join42(dir, "package.json")));
58320
+ dirs.push(join43(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58321
+ dirs.push(join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58322
+ return dirs.filter((dir) => existsSync51(join43(dir, "package.json")));
58254
58323
  }
58255
58324
  function projectConfigPath(cwd) {
58256
58325
  return resolveCortexKitProjectConfigPath(cwd);
58257
58326
  }
58258
58327
  function readConfigForEmbedding(path, isProjectConfig) {
58259
- if (!existsSync50(path))
58328
+ if (!existsSync51(path))
58260
58329
  return null;
58261
58330
  try {
58262
58331
  const raw = loadRawConfigFile({
@@ -58347,33 +58416,33 @@ function pinnedVersionFromPackageSpecifier(specifier) {
58347
58416
  }
58348
58417
  function cacheRoots(cwd) {
58349
58418
  const home = process.env.HOME?.trim();
58350
- const cacheHome = process.env.XDG_CACHE_HOME || join42(home || homedir22(), ".cache");
58419
+ const cacheHome = process.env.XDG_CACHE_HOME || join43(home || homedir22(), ".cache");
58351
58420
  const piCacheRoot = getPiCacheRoot();
58352
58421
  return [
58353
- join42(piCacheRoot, "extensions"),
58354
- join42(piCacheRoot, "packages"),
58355
- join42(cacheHome, "pi", "extensions"),
58356
- join42(cacheHome, "pi", "packages"),
58357
- join42(getPiAgentConfigDir(), "cache", "extensions"),
58358
- join42(getPiAgentConfigDir(), "npm", "node_modules", PACKAGE_NAME2),
58359
- join42(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2)
58422
+ join43(piCacheRoot, "extensions"),
58423
+ join43(piCacheRoot, "packages"),
58424
+ join43(cacheHome, "pi", "extensions"),
58425
+ join43(cacheHome, "pi", "packages"),
58426
+ join43(getPiAgentConfigDir(), "cache", "extensions"),
58427
+ join43(getPiAgentConfigDir(), "npm", "node_modules", PACKAGE_NAME2),
58428
+ join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2)
58360
58429
  ];
58361
58430
  }
58362
58431
  function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58363
58432
  const found = new Map;
58364
58433
  const visit = (path, depth) => {
58365
- if (depth < 0 || !existsSync50(path))
58434
+ if (depth < 0 || !existsSync51(path))
58366
58435
  return;
58367
58436
  let stat;
58368
58437
  try {
58369
- stat = statSync27(path);
58438
+ stat = statSync28(path);
58370
58439
  } catch {
58371
58440
  return;
58372
58441
  }
58373
58442
  if (!stat.isDirectory())
58374
58443
  return;
58375
- const packageJson = join42(path, "package.json");
58376
- if (existsSync50(packageJson)) {
58444
+ const packageJson = join43(path, "package.json");
58445
+ if (existsSync51(packageJson)) {
58377
58446
  try {
58378
58447
  const pkg = JSON.parse(readFileSync33(packageJson, "utf-8"));
58379
58448
  const name = typeof pkg.name === "string" ? pkg.name : "";
@@ -58395,7 +58464,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58395
58464
  return;
58396
58465
  }
58397
58466
  for (const entry of entries)
58398
- visit(join42(path, entry), depth - 1);
58467
+ visit(join43(path, entry), depth - 1);
58399
58468
  };
58400
58469
  for (const root of cacheRoots(cwd))
58401
58470
  visit(root, 5);
@@ -58456,7 +58525,7 @@ async function runHealthChecks2(options) {
58456
58525
  const settingsPath = getPiUserExtensionsPath();
58457
58526
  let packages = [];
58458
58527
  let piPluginInstalled = false;
58459
- if (!existsSync50(settingsPath)) {
58528
+ if (!existsSync51(settingsPath)) {
58460
58529
  if (pi) {
58461
58530
  add2(results, "info", `${piVersion ? `Pi ${piVersion}` : "Pi"} found; Magic Context is not installed there (run setup to add it)`);
58462
58531
  }
@@ -58498,7 +58567,7 @@ async function runHealthChecks2(options) {
58498
58567
  ["user", userConfigPath, true],
58499
58568
  ["project", projectPath, false]
58500
58569
  ]) {
58501
- if (!existsSync50(path)) {
58570
+ if (!existsSync51(path)) {
58502
58571
  if (required) {
58503
58572
  add2(results, "warn", `No ${label} magic-context.jsonc found at ${path}`);
58504
58573
  if (userConfigMigrationRefused) {
@@ -58545,12 +58614,12 @@ async function runHealthChecks2(options) {
58545
58614
  checkPiModelChains(results, pi, loadedConfig.config, options.deps);
58546
58615
  const storage = getMagicContextStorageResolution();
58547
58616
  const storageDir = storage.path;
58548
- const dbPath = join42(storageDir, "context.db");
58617
+ const dbPath = join43(storageDir, "context.db");
58549
58618
  if (isMagicContextStorageOutsideEngram(storageDir)) {
58550
58619
  add2(results, "warn", `Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
58551
58620
  }
58552
58621
  add2(results, "info", `Shared storage: ${storageDir} (source: ${storage.source})`);
58553
- const existedBeforeOpen = existsSync50(dbPath);
58622
+ const existedBeforeOpen = existsSync51(dbPath);
58554
58623
  if (existedBeforeOpen)
58555
58624
  add2(results, "pass", `Shared context DB exists at ${dbPath}`);
58556
58625
  else
@@ -58745,10 +58814,28 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
58745
58814
  }
58746
58815
  }
58747
58816
  const diagnosticsForDumps = await collectDiagnostics2(options.cwd);
58817
+ const sessionDumps = diagnosticsForDumps.historianDumps.sessionDumps;
58818
+ if (sessionDumps.count > 0) {
58819
+ add2(results, "warn", `Historian debug dumps: ${sessionDumps.count} file(s) across ${sessionDumps.sessionCount} session(s) in ${sessionDumps.dir}`);
58820
+ for (const session of sessionDumps.sessions) {
58821
+ add2(results, "info", ` [${session.sessionId}] ${session.count} file(s)`);
58822
+ for (const dump of session.recent.slice(0, 3)) {
58823
+ const age = dump.ageMinutes;
58824
+ const ageStr = age < 60 ? `${age}m ago` : `${Math.round(age / 60)}h ago`;
58825
+ add2(results, "info", ` ${dump.name} (${ageStr})`);
58826
+ }
58827
+ if (session.count > 3) {
58828
+ add2(results, "info", ` ... and ${session.count - 3} more`);
58829
+ }
58830
+ }
58831
+ if (sessionDumps.sessionCount > sessionDumps.sessions.length) {
58832
+ add2(results, "info", ` ... and ${sessionDumps.sessionCount - sessionDumps.sessions.length} more session(s)`);
58833
+ }
58834
+ }
58748
58835
  const dumpBuckets = diagnosticsForDumps.historianDumps.byProject;
58749
58836
  if (dumpBuckets.length > 0) {
58750
58837
  const totalCount = dumpBuckets.reduce((sum, b) => sum + b.count, 0);
58751
- add2(results, "warn", `Historian debug dumps: ${totalCount} file(s) across ${dumpBuckets.length} project(s)`);
58838
+ add2(results, "warn", `Historian debug dumps from older plugins in project directories: ${totalCount} file(s) across ${dumpBuckets.length} project(s)`);
58752
58839
  for (const bucket of dumpBuckets) {
58753
58840
  add2(results, "info", ` [${bucket.directory}] ${bucket.count} file(s)`);
58754
58841
  for (const dump of bucket.recent.slice(0, 3)) {
@@ -58807,7 +58894,7 @@ function repair2(plan, prompts) {
58807
58894
  }
58808
58895
  if (plan.writeUserConfig) {
58809
58896
  const configPath = getPiUserConfigPath();
58810
- if (!existsSync50(configPath)) {
58897
+ if (!existsSync51(configPath)) {
58811
58898
  try {
58812
58899
  writeDefaultMagicContextConfig(configPath);
58813
58900
  prompts.log.success(`Wrote default Magic Context config to ${configPath}`);
@@ -58861,7 +58948,7 @@ async function runIssueFlow3(options) {
58861
58948
  if (options.reportPath) {
58862
58949
  try {
58863
58950
  const report = await options.deps.collectDiagnostics(options.cwd);
58864
- const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join42(options.cwd, options.reportPath);
58951
+ const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join43(options.cwd, options.reportPath);
58865
58952
  const bundled = await bundleIssueReport2(report, "Generated non-interactively by `doctor --issue --report`.", "Magic Context diagnostic report", { cwd: options.cwd, now: options.deps.now(), outputPath });
58866
58953
  options.prompts.log.info(`Report written to ${bundled.path}`);
58867
58954
  return 0;
@@ -58945,7 +59032,7 @@ async function runDoctor3(options = {}) {
58945
59032
  const v22Result = await runV22BackfillCommands({
58946
59033
  name: "Pi",
58947
59034
  openDatabase: (readonly = true) => {
58948
- const dbPath = join42(getMagicContextStorageDir(), "context.db");
59035
+ const dbPath = join43(getMagicContextStorageDir(), "context.db");
58949
59036
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
58950
59037
  return v22Db;
58951
59038
  },
@@ -59063,8 +59150,8 @@ var init_doctor_pi = __esm(async () => {
59063
59150
  });
59064
59151
 
59065
59152
  // src/commands/doctor.ts
59066
- import { existsSync as existsSync51, rmSync as rmSync11 } from "node:fs";
59067
- import { join as join43 } from "node:path";
59153
+ import { existsSync as existsSync52, rmSync as rmSync11 } from "node:fs";
59154
+ import { join as join44 } from "node:path";
59068
59155
  async function runDoctor4(options) {
59069
59156
  if (options.clear)
59070
59157
  return runClear();
@@ -59082,7 +59169,7 @@ async function runDoctor4(options) {
59082
59169
  const result = await runV22BackfillCommands({
59083
59170
  name: "Magic Context",
59084
59171
  openDatabase: (readonly = true) => {
59085
- const dbPath = join43(getMagicContextStorageDir(), "context.db");
59172
+ const dbPath = join44(getMagicContextStorageDir(), "context.db");
59086
59173
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
59087
59174
  return v22Db;
59088
59175
  },
@@ -59102,7 +59189,7 @@ async function runDoctor4(options) {
59102
59189
  log3.warn(`Identity split check unavailable: ${error instanceof Error ? error.message : String(error)}`);
59103
59190
  }
59104
59191
  await init_migrate();
59105
- const sweepDbPath = join43(getMagicContextStorageDir(), "context.db");
59192
+ const sweepDbPath = join44(getMagicContextStorageDir(), "context.db");
59106
59193
  let sweepDb = null;
59107
59194
  try {
59108
59195
  sweepDb = openExistingContextDatabaseForMutation(sweepDbPath);
@@ -59219,7 +59306,7 @@ async function runClear() {
59219
59306
  failed += 1;
59220
59307
  continue;
59221
59308
  }
59222
- } else if (existsSync51(item.path)) {
59309
+ } else if (existsSync52(item.path)) {
59223
59310
  rmSync11(item.path, { recursive: true, force: true });
59224
59311
  }
59225
59312
  s.stop(`Cleared ${item.path}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/magic-context",
3
- "version": "0.49.57",
3
+ "version": "0.49.59",
4
4
  "description": "Unified CLI for Magic Context — setup, doctor, and migration across OpenCode, Pi, and OMP",
5
5
  "keywords": [
6
6
  "opencode",