@cortexkit/magic-context 0.49.57 → 0.49.60

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 +283 -181
  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
  }
@@ -2530,7 +2527,11 @@ var init_models_dev_cache = __esm(() => {
2530
2527
  init_logger();
2531
2528
  init_storage_permissions();
2532
2529
  init_window_geometry();
2533
- SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set(["google", "google-antigravity"]);
2530
+ SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set([
2531
+ "google",
2532
+ "google-antigravity",
2533
+ "antigravity-cli"
2534
+ ]);
2534
2535
  reserveClampLogSeen = new Set;
2535
2536
  });
2536
2537
 
@@ -16005,6 +16006,9 @@ function getMagicContextLogPath2(harness) {
16005
16006
  function getMagicContextHistorianDir2(harness) {
16006
16007
  return getMagicContextHistorianDir(harness);
16007
16008
  }
16009
+ function getProjectHistorianDumpDir(directory) {
16010
+ return join7(getProjectMagicContextDir(directory), "historian");
16011
+ }
16008
16012
  function getOpenCodePluginCacheDir() {
16009
16013
  const xdg = process.env.XDG_CACHE_HOME || join7(homedir7(), ".cache");
16010
16014
  return join7(xdg, "opencode", "packages");
@@ -48391,6 +48395,7 @@ var init_issue_log_templates_generated = __esm(() => {
48391
48395
  "WARN: execute_threshold clamped \x01% → \x01% for \x01 (capped against the output-reserved safe window; 10% remains for mid-turn growth before the absolute 95% wall)\x022m",
48392
48396
  "history boundary unresolved: compartment end \x01 is not in the active host branch and no older compartment end is in the host store; nothing to re-anchor on\x020i",
48393
48397
  "compartment trigger: cheap-skip at \x01% (below proactive floor \x01%) — live-tail upper bound \x01 < triggerBudget \x01; no size trigger possible, skipped full raw read",
48398
+ "pi history cut not placed: boundary \x01 is not among the \x01 context messages and \x01; first message without a branch position: \x01; nothing was cut at this boundary\x020i",
48394
48399
  "[magic-context] transform produced an assistant-terminated request (input was user-terminated); providers without prefill support will reject it. tail=[\x01]",
48395
48400
  "Magic Context compacted history, but Pi's native compaction marker is waiting for a resolvable kept entry. It will retry on the next materializing pass.",
48396
48401
  "[magic-context] compaction-marker: flip-off cleanup RETAINED lineage at boundary \x01 — a surviving tail_start_id references a row the deletion would remove\x020i",
@@ -48403,6 +48408,7 @@ var init_issue_log_templates_generated = __esm(() => {
48403
48408
  "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Refusing to compact a Magic Context hidden-agent session this instance did not register)",
48404
48409
  "[backfill] OpenCode DB not found at \x01 — marking all unbackfilled sessions as skipped. Lazy adoption (defense-in-depth) handles legacy rows at runtime.\x020p",
48405
48410
  "[dreamer] storage unavailable; skipping \x01 (the cache schema is newer than this binary supports — restart/upgrade OpenCode/Pi/Magic Context to recover)",
48411
+ "[magic-context] host overflow check unavailable: @earendil-works/pi-ai has no isContextOverflow export; using Magic Context's overflow patterns only",
48406
48412
  "[magic-context] local embedding pooling metadata for \x01 is not available: \x01; using legacy mean pooling and retrying during a later background bootstrap\x020m",
48407
48413
  "transform: unknown provider usage; using saved provider reading for priced pass inputTokens=\x01 percentage=\x01 countPercentage=\x01 sizedPlan=clears_reasoning",
48408
48414
  "transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=[\x01]",
@@ -48463,6 +48469,7 @@ var init_issue_log_templates_generated = __esm(() => {
48463
48469
  "[dreamer] no OpenCode 2 session in \x01 to parent a timer-started dream run; tasks that need a child session are skipped until one exists\x020p",
48464
48470
  "v2 payload: left out \x01 emptied messages and \x01 empty text parts, because Anthropic rejects an empty text block (logged once per session)",
48465
48471
  "prefix trim: boundary \x01; pass=priced; no in-pass trim applied (Refusing an unregistered prompt on a Magic Context hidden-run session)",
48472
+ "[magic-context] host overflow check unavailable: @earendil-works/pi-ai did not load (\x01); using Magic Context's overflow patterns only",
48466
48473
  'recomp partial code=\x01 reason="chunk could not be represented safely: chunk omits raw message \x01 while still claiming coverage through \x01"',
48467
48474
  "transform: no provider usage reading; the execute decision reads the local count of the last served request percentage=\x01 inputTokens=\x01",
48468
48475
  "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Refusing an unregistered prompt on a Magic Context hidden-run session)",
@@ -48470,6 +48477,7 @@ var init_issue_log_templates_generated = __esm(() => {
48470
48477
  "[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
48478
  "system prompt hash changed: \x01 → \x01 (len=\x01), adopting on the request whose messages are already final; presetChanged=unknown elements=[\x01]",
48472
48479
  "[magic-context] host stall profiler enabled: threshold \x01ms, sample interval \x01ms, clock calibration unavailable, setup \x01ms, reports in \x01",
48480
+ "prefix trim: boundary \x01; pass=priced; no in-pass trim applied (Refusing a prompt that names more than one Magic Context hidden run)",
48473
48481
  "compaction-marker drain: refusing ordinal \x01 because prefix trim through \x01 was not proven; preserving deferred history refresh signal\x021i",
48474
48482
  "[magic-context] conflict-detector: resolved v2 config carried no explicit compaction.auto (\x01); falling back to file-based detection",
48475
48483
  "[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 +48485,7 @@ var init_issue_log_templates_generated = __esm(() => {
48477
48485
  "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
48486
  "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
48487
  "rust compaction-marker admission deferred: reason=output_fit fit=\x01 estimated=\x01 trusted=\x01 proxy_tokens=unavailable proxy_bytes=\x01 limit=\x01",
48488
+ "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Refusing a prompt that names more than one Magic Context hidden run)",
48480
48489
  "prefix trim: boundary \x01; pass=priced; no in-pass trim applied (Hidden child history does not contain this run's registered marker)",
48481
48490
  "[magic-context] boot phase 'hooks' exceeded the whole-server \x01ms budget; host startup will continue with Magic Context fail-closed",
48482
48491
  "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Hidden child history does not contain this run's registered marker)",
@@ -48634,6 +48643,7 @@ var init_issue_log_templates_generated = __esm(() => {
48634
48643
  "compartment injection entering degraded mode: boundary \x01 not in visible messages (consecutive degraded passes: \x01)\x021s",
48635
48644
  "auto-search: decision outcome=timeout lanes=\x01 nearMisses=\x01 threshold=\x01 pool=\x01 rows=\x01 workerStarted=\x01 peek=\x01 elapsedMs=\x01",
48636
48645
  "[auto-update-checker] Explicit @latest leaves the active package unpinned; OpenCode may delete it mid-session.",
48646
+ "[magic-context] session_before_compact: host compacting for overflow; provider-overflow recovery already-armed",
48637
48647
  "compartment trigger: force_band skipped — no protected head meets summary admission after emergency tail scale",
48638
48648
  "historian: refusing to publish over a stale protected-tail snapshot (was: \x01); ending the run without publishing",
48639
48649
  "ERROR: compaction marker disabled: incompatible host binding harness=\x01 arity=\x01 getEntry=\x01; leaving marker pending",
@@ -48718,6 +48728,7 @@ var init_issue_log_templates_generated = __esm(() => {
48718
48728
  "historian no-op: protectedTailStart=\x01 eligibleEnd=\x01 <= offset=\x01 — nothing to compact; boundaryDiagnostics=\x01",
48719
48729
  "historian unanchored promotion skipped: reason=\x01 facts=\x01 user_observations=\x01 primers=\x01 events_publishable=\x01/\x01",
48720
48730
  "tag identity fold guards could not be written; duplicates that need one are served unmerged this pass: \x01",
48731
+ "[magic-context] session_before_compact: host compacting for overflow; provider-overflow recovery armed",
48721
48732
  "latest-turn thinking recovery: rejection not bound, no pass in this process built the rejected request",
48722
48733
  'recomp partial code=\x01 reason="remaining messages \x01-\x01 were too few or all noise to form a historian chunk"',
48723
48734
  "[magic-context] buildAllowOnlyPermission: allow-list UNDEFINED for \x01 — registering deny-all (defensive)",
@@ -48807,6 +48818,7 @@ var init_issue_log_templates_generated = __esm(() => {
48807
48818
  "historian publish stage: stage=dangling-boundary-check status=started elapsed=0.0ms compartments=\x01",
48808
48819
  "Pi compaction-marker clear: reason=active-branch-retired endMessageId=\x01 ordinal=\x01 firstKeptEntryId=\x01\x020i",
48809
48820
  "v2 refusal: interrupting the turn before the provider request arm=blocking-transform-error cause=\x01",
48821
+ "Oh My Pi spawned session (agent kind sub) has compartments from its source session: kept primary",
48810
48822
  "[dreamer] verify safety refusal: memory_id=\x01 verdict=archive reason=directive-shaped-project-rule",
48811
48823
  "[dreamer] map-memories: all \x01 path(s) for memory \x01 were rejected; recording host_rejected_fallback",
48812
48824
  "transform: model switch \x01 -> \x01/\x01 reset — percentage=\x01% tokens=\x01 — clearing stale model-specific state\x020s,1m,2m",
@@ -48992,6 +49004,7 @@ var init_issue_log_templates_generated = __esm(() => {
48992
49004
  "mc-module: historian firing for \x01: await_timeout_ms=\x01 attempt_budget_ms=\x01 firing_budget_ms=\x01\x020s",
48993
49005
  "v2 context omitted a content part the host would reject: type=<missing> message=\x01 reason=\x01",
48994
49006
  "v2 refusal: interrupting the turn before the provider request arm=compaction-fold cause=\x01",
49007
+ "[magic-context] host overflow check: using isContextOverflow from @earendil-works/pi-ai",
48995
49008
  "[magic-context] protected_tags is deprecated and ignored; use protected_tokens instead.",
48996
49009
  "ERROR [tail-hygiene-last-writer-check-failed]: structural production guard failed open:",
48997
49010
  "historian: cleared stale compartmentInProgress flag on first context pass after restart",
@@ -49078,6 +49091,7 @@ var init_issue_log_templates_generated = __esm(() => {
49078
49091
  "[dreamer] primers: embedding unavailable; falling back to normalized-text clusters: \x01",
49079
49092
  "[magic-context] project identity resolution failed for \x01; using directory fallback \x01: \x01\x020p,1p",
49080
49093
  "compaction-marker drain: stale-skip (compartment-removed) for ordinal \x01 endMessageId=\x01\x021i",
49094
+ "compartment injection failed; replaying the last good request or refusing the turn: \x01",
49081
49095
  "historian publish stage: stage=publish-txn status=completed elapsed=\x01ms compartments=\x01",
49082
49096
  "transform scheduler: percentage=\x01% inputTokens=\x01 cacheTtl=\x01 lastResponseTime=\x01 decision=\x01",
49083
49097
  "[magic-context] conflict-warning: could not find active session for Desktop warning",
@@ -49164,9 +49178,12 @@ var init_issue_log_templates_generated = __esm(() => {
49164
49178
  "historian publish stage: stage=validate status=completed elapsed=\x01ms compartments=\x01",
49165
49179
  "mc-pass-stage session=\x01 stage=historian_inline_wait event=end outcome=\x01 elapsed_ms=\x01\x020s",
49166
49180
  "transform: over-window first-pass check could not estimate the incoming history: \x01",
49181
+ "ctx_reduce served record failed after the request was decided; serving the pass:",
49167
49182
  "final wire usage capture failed after the request was decided; serving the pass:",
49168
49183
  "Pi publication commit_failed reason=envelope_unreadable; serving managed context",
49169
49184
  "Pi publication commit_failed reason=number_write_failed; serving managed context",
49185
+ "request tool list changed: ctx_reduce added; tag prefixes return on this rebuild",
49186
+ "request tool list changed: ctx_reduce removed; tag prefixes stop on this rebuild",
49170
49187
  "transform refused degraded pass site=merged-reasoning-strip-persistence-failure:",
49171
49188
  "model changed (\x01/\x01 -> \x01/\x01), clearing historian failure state and reasoning watermark\x020m,1m,2m,3m",
49172
49189
  "prompt_surface.guidance_override_path (\x01) is not a file; using built-in guidance.\x020p",
@@ -49413,6 +49430,7 @@ var init_issue_log_templates_generated = __esm(() => {
49413
49430
  "mc-module: pending_rewrite ambiguous after boundary-present recovery for \x01",
49414
49431
  "mc-pass-stage session=\x01 stage=historian_inline_wait event=begin budget_ms=\x01\x020s",
49415
49432
  "proven input floor \x01 has no recorded model; dropped instead of applied to \x01\x021m",
49433
+ "raw_fallback_over_context_limit tokens=\x01 limit=\x01 proxy_bytes=\x01 proxy_tokens=\x01",
49416
49434
  "rust compaction-marker drain: retryable failure; pending target retained \x01",
49417
49435
  "tag identity repair without last-served evidence: session=\x01 kept=\x01 removed=\x01\x020s",
49418
49436
  "todowrite permission read failed; retaining the last successful verdict: \x01",
@@ -49658,6 +49676,7 @@ var init_issue_log_templates_generated = __esm(() => {
49658
49676
  "channel2 terminal-run intent clear failed; leaving lease to heal:",
49659
49677
  "compaction-off render changed the head: stripping signed thinking",
49660
49678
  "historian publish stage: stage=parse status=started elapsed=0.0ms",
49679
+ "Oh My Pi spawned session (agent kind sub): recorded as a subagent",
49661
49680
  "transform refused degraded pass site=m0-m1-injection-degradation:",
49662
49681
  "transform refused degraded pass site=overflow-state-read-failure:",
49663
49682
  "transform refused degraded pass site=tagging-persistence-failure:",
@@ -49760,6 +49779,7 @@ var init_issue_log_templates_generated = __esm(() => {
49760
49779
  "agent_end: returning synchronously (background work continues)",
49761
49780
  "historian failure notice skipped after session context cleared",
49762
49781
  "Last-good certificate remains dirty after publication failure:",
49782
+ "raw_fallback_refused completeness=partial messages=unpriceable",
49763
49783
  "rust refusal recovery expired before the module became healthy",
49764
49784
  "system delivery acknowledgement failed (keeping pending work):",
49765
49785
  "transform: cannot force-start compartment agent without client",
@@ -49791,6 +49811,7 @@ var init_issue_log_templates_generated = __esm(() => {
49791
49811
  "[message-index] pending Rust session cleanup: cleared=\x01 failed=\x01\x021s",
49792
49812
  "event message.removed: stripped placeholder ids unchanged for \x01\x020i",
49793
49813
  "mc-module: need_full_sync session=\x01 reason=\x01 after=\x01 fingerprint=\x01",
49814
+ "overflow detected: source=\x01 reportedLimit=\x01 provenance=\x01 pattern=\x01",
49794
49815
  "protected token floor snapshot: floor=\x01 provenance=\x01 usableSoft=\x01",
49795
49816
  "[auto-update-checker] Auto-update disabled, notification only",
49796
49817
  "[magic-context] failed to close cached OpenCode read-only DB:",
@@ -49869,6 +49890,7 @@ var init_issue_log_templates_generated = __esm(() => {
49869
49890
  "pending operations no-op: source=\x01 total=\x01 persisted=\x01 reasons=\x01",
49870
49891
  "Subagent temperature sent for \x01: host model metadata says no \x01\x020m",
49871
49892
  "WARN: [auto-update-checker] Background update check failed: \x01",
49893
+ "WARN: session_before_compact: overflow recovery arm failed: \x01",
49872
49894
  "[dreamer] evaluate-smart-notes: skipped (wake plane active)",
49873
49895
  "[magic-context] embedding batch returned invalid dimensions",
49874
49896
  "compartment agent: failed to remove historian response dump",
@@ -49876,6 +49898,7 @@ var init_issue_log_templates_generated = __esm(() => {
49876
49898
  "historian publish skipped: missing compartment lease holder",
49877
49899
  "outgoing fit: fits-or-unknown; attempting emergency reclaim",
49878
49900
  "transform refused degraded pass site=image-strip-exception:",
49901
+ "WARN: session_before_compact: overflow recovery arm failed:",
49879
49902
  "[ctx_search] rerank fallback (\x01); retaining original ranking",
49880
49903
  "Subagent temperature sent for \x01: host model metadata says no\x020m",
49881
49904
  "injected \x01 compartments + \x01 facts + \x01 memories into message[0]",
@@ -50076,7 +50099,6 @@ var init_issue_log_templates_generated = __esm(() => {
50076
50099
  "exact ordinal read failed; the historian start waits: \x01",
50077
50100
  "historian state snapshot failed; using safe defaults: \x01",
50078
50101
  "OMP provider images trimmed: planned=\x01 actual=\x01 trimmed=\x01",
50079
- "overflow detected: reportedLimit=\x01 provenance=\x01 pattern=\x01",
50080
50102
  "overflow unknown-usage recovery: inputTokens=\x01 retryMs=\x01",
50081
50103
  "protected-tail migration seed fell back to ordinal 1: \x01",
50082
50104
  "recomp post-publish step=\x01 failed; publication stands: \x01",
@@ -50531,7 +50553,6 @@ var init_issue_log_templates_generated = __esm(() => {
50531
50553
  "[search] off-thread message search failed: \x01",
50532
50554
  "aft-incremental total_ms=\x01 tier_tokenize_ms=\x01",
50533
50555
  "channel1 nudge injection failed (ignored): \x01",
50534
- "compartment injection failed (continuing): \x01",
50535
50556
  "event completion clock persistence failed: \x01",
50536
50557
  "heuristic cleanup stage: stage=\x01 elapsed=\x01ms \x01",
50537
50558
  "historian failure: subagent run failed (\x01): \x01",
@@ -50544,6 +50565,7 @@ var init_issue_log_templates_generated = __esm(() => {
50544
50565
  "pi m[0] HARD fold firing: reason=\x01 mismatch=\x01",
50545
50566
  "processed-image strip failed (continuing): \x01",
50546
50567
  "project registration after publish failed: \x01",
50568
+ "raw_fallback_refused count=unusable tokens=\x01",
50547
50569
  "reasoning removal: drop mode write failed: \x01",
50548
50570
  "rust memory sync trigger failed (ignored): \x01",
50549
50571
  "v2 host fold: optional capture unavailable \x01",
@@ -50763,6 +50785,7 @@ var init_issue_log_templates_generated = __esm(() => {
50763
50785
  "[migrations] migration worker ready: \x01\x020p",
50764
50786
  "collectMessageEntryIdsStrict failed: \x01",
50765
50787
  "compartment agent: finalizer failed: \x01",
50788
+ "ctx_reduce served record unreadable: \x01",
50766
50789
  "dreamer token budget: finalize fired \x01",
50767
50790
  "event session.error handling failed: \x01",
50768
50791
  "host checkpoint head: changed=\x01 proof=\x01",
@@ -50779,6 +50802,8 @@ var init_issue_log_templates_generated = __esm(() => {
50779
50802
  "WARN: shutdown: dreamer drain threw: \x01",
50780
50803
  "[dreamer] scheduled task run failed:",
50781
50804
  "compartment agent: finalizer failed:",
50805
+ "ctx_reduce served record not written",
50806
+ "ctx_reduce served record unreadable:",
50782
50807
  "dreamer token budget: finalize fired",
50783
50808
  "event session.error handling failed:",
50784
50809
  "lkg wrapper replay fit check failed:",
@@ -53975,10 +54000,45 @@ var init_tui_config = __esm(() => {
53975
54000
  PLUGIN_ENTRY = `${PLUGIN_NAME2}@latest`;
53976
54001
  });
53977
54002
 
54003
+ // src/lib/historian-dump-dirs.ts
54004
+ import { existsSync as existsSync46, readdirSync as readdirSync10, statSync as statSync25 } from "node:fs";
54005
+ import { join as join36 } from "node:path";
54006
+ function scanHistorianDumpFiles(dir) {
54007
+ if (!existsSync46(dir))
54008
+ return [];
54009
+ try {
54010
+ return readdirSync10(dir).filter((name) => name.endsWith(".xml")).map((name) => {
54011
+ const stat = statSync25(join36(dir, name));
54012
+ return { name, mtime: stat.mtimeMs, sizeKb: Math.round(stat.size / 1024) };
54013
+ }).sort((a, b) => b.mtime - a.mtime);
54014
+ } catch {
54015
+ return [];
54016
+ }
54017
+ }
54018
+ function scanHistorianSessionDumpDirs(root) {
54019
+ if (!existsSync46(root))
54020
+ return [];
54021
+ const sessions = [];
54022
+ try {
54023
+ for (const entry of readdirSync10(root, { withFileTypes: true })) {
54024
+ if (!entry.isDirectory())
54025
+ continue;
54026
+ const dir = join36(root, entry.name);
54027
+ const files = scanHistorianDumpFiles(dir);
54028
+ if (files.length > 0)
54029
+ sessions.push({ sessionId: entry.name, dir, files });
54030
+ }
54031
+ } catch {
54032
+ return [];
54033
+ }
54034
+ return sessions.sort((a, b) => (b.files[0]?.mtime ?? 0) - (a.files[0]?.mtime ?? 0));
54035
+ }
54036
+ var init_historian_dump_dirs = () => {};
54037
+
53978
54038
  // src/lib/diagnostics-opencode.ts
53979
- import { existsSync as existsSync46, readdirSync as readdirSync10, readFileSync as readFileSync29, statSync as statSync25 } from "node:fs";
54039
+ import { existsSync as existsSync47, readFileSync as readFileSync29, statSync as statSync26 } from "node:fs";
53980
54040
  import { createRequire as createRequire4 } from "node:module";
53981
- import { join as join36 } from "node:path";
54041
+ import { join as join37 } from "node:path";
53982
54042
  function getSelfVersion() {
53983
54043
  const require2 = createRequire4(import.meta.url);
53984
54044
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -54002,7 +54062,7 @@ function readLegacyCachedVersion(root) {
54002
54062
  function collectOpenCodePluginCacheReport(hostGeneration, opencodeConfig, npmVersions = {}) {
54003
54063
  const installs = [];
54004
54064
  for (const root of getOpenCodePluginCacheRoots()) {
54005
- if (!existsSync46(root))
54065
+ if (!existsSync47(root))
54006
54066
  continue;
54007
54067
  const spec = root.endsWith("@latest") ? "latest" : "(bare)";
54008
54068
  installs.push({
@@ -54050,7 +54110,7 @@ function getStorageResolution() {
54050
54110
  }
54051
54111
  function fileSize(path) {
54052
54112
  try {
54053
- return existsSync46(path) ? statSync25(path).size : 0;
54113
+ return existsSync47(path) ? statSync26(path).size : 0;
54054
54114
  } catch {
54055
54115
  return 0;
54056
54116
  }
@@ -54062,7 +54122,7 @@ function sanitizeValue(value) {
54062
54122
  return sanitizeConfigValue(value);
54063
54123
  }
54064
54124
  function readConfig3(path) {
54065
- if (!existsSync46(path))
54125
+ if (!existsSync47(path))
54066
54126
  return { value: null };
54067
54127
  try {
54068
54128
  const raw = readFileSync29(path, "utf-8");
@@ -54122,46 +54182,36 @@ function parseHistorianDumpMeta(path) {
54122
54182
  return { error: error instanceof Error ? error.message : String(error) };
54123
54183
  }
54124
54184
  }
54185
+ function summarizeDumps(dir, files, limit) {
54186
+ const now = Date.now();
54187
+ return files.slice(0, limit).map((entry) => {
54188
+ const meta = parseHistorianDumpMeta(join37(dir, entry.name));
54189
+ const summary = {
54190
+ name: entry.name,
54191
+ ageMinutes: Math.round((now - entry.mtime) / 60000),
54192
+ sizeKb: entry.sizeKb
54193
+ };
54194
+ if ("error" in meta) {
54195
+ summary.parseError = meta.error;
54196
+ } else {
54197
+ summary.meta = meta;
54198
+ }
54199
+ return summary;
54200
+ });
54201
+ }
54125
54202
  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
- }
54203
+ const files = scanHistorianDumpFiles(dir);
54204
+ return { count: files.length, recent: summarizeDumps(dir, files, limit) };
54156
54205
  }
54157
- function collectHistorianDumps(recentSessions) {
54206
+ function collectHistorianDumps(recentSessions, historianRoot = getMagicContextHistorianDir2("opencode")) {
54207
+ const sessionDirs = scanHistorianSessionDumpDirs(historianRoot);
54158
54208
  const buckets = new Map;
54159
54209
  for (const session of recentSessions) {
54160
54210
  const dir = session.directory;
54161
54211
  if (!dir)
54162
54212
  continue;
54163
- const projectHistorianDir = getProjectMagicContextHistorianDir(dir);
54164
- const listing = listDumpsInDir(projectHistorianDir, 5);
54213
+ const projectHistorianDir = getProjectHistorianDumpDir(dir);
54214
+ const listing = listDumpsInDir(projectHistorianDir, DUMPS_PER_BUCKET_LIMIT);
54165
54215
  const existing = buckets.get(dir);
54166
54216
  if (existing) {
54167
54217
  if (!existing.sessionIds.includes(session.sessionId)) {
@@ -54179,12 +54229,21 @@ function collectHistorianDumps(recentSessions) {
54179
54229
  recent: listing.recent
54180
54230
  });
54181
54231
  }
54182
- const legacyDir = getMagicContextHistorianDir2("opencode");
54183
- const legacyListing = listDumpsInDir(legacyDir, 5);
54232
+ const legacyListing = listDumpsInDir(historianRoot, DUMPS_PER_BUCKET_LIMIT);
54184
54233
  return {
54234
+ sessionDumps: {
54235
+ dir: historianRoot,
54236
+ count: sessionDirs.reduce((sum, session) => sum + session.files.length, 0),
54237
+ sessionCount: sessionDirs.length,
54238
+ sessions: sessionDirs.slice(0, SESSION_DUMP_BUCKET_LIMIT).map((session) => ({
54239
+ sessionId: session.sessionId,
54240
+ count: session.files.length,
54241
+ recent: summarizeDumps(session.dir, session.files, DUMPS_PER_BUCKET_LIMIT)
54242
+ }))
54243
+ },
54185
54244
  byProject: [...buckets.values()],
54186
54245
  legacyDumps: {
54187
- dir: legacyDir,
54246
+ dir: historianRoot,
54188
54247
  count: legacyListing.count,
54189
54248
  recent: legacyListing.recent
54190
54249
  }
@@ -54247,7 +54306,7 @@ function collectRecentSessionsFromDatabase(database) {
54247
54306
  });
54248
54307
  }
54249
54308
  async function collectDatabaseRows(path, read) {
54250
- if (!existsSync46(path))
54309
+ if (!existsSync47(path))
54251
54310
  return { available: false, reason: "path missing" };
54252
54311
  let backend;
54253
54312
  try {
@@ -54279,7 +54338,7 @@ async function collectRecentSessions(resolution, hostGeneration) {
54279
54338
  });
54280
54339
  }
54281
54340
  async function collectHistorianFailures(storageDirPath) {
54282
- return collectDatabaseRows(join36(storageDirPath, "context.db"), (db) => {
54341
+ return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54283
54342
  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
54343
  return rows.map((row) => {
54285
54344
  const sessionId = typeof row.session_id === "string" ? row.session_id : "<unknown>";
@@ -54292,7 +54351,7 @@ async function collectHistorianFailures(storageDirPath) {
54292
54351
  });
54293
54352
  }
54294
54353
  async function collectHistorianRuns(storageDirPath) {
54295
- return collectDatabaseRows(join36(storageDirPath, "context.db"), (db) => {
54354
+ return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54296
54355
  const aggRows = db.prepare(`SELECT session_id,
54297
54356
  COUNT(*) AS total,
54298
54357
  SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS success,
@@ -54347,7 +54406,7 @@ async function collectDiagnostics(options = {}) {
54347
54406
  const magicContextConfig = readConfig3(configPaths.magicContextConfig);
54348
54407
  const storageResolution = getStorageResolution();
54349
54408
  const storageDirPath = storageResolution.path;
54350
- const contextDbPath = join36(storageDirPath, "context.db");
54409
+ const contextDbPath = join37(storageDirPath, "context.db");
54351
54410
  let compactionEnabled = false;
54352
54411
  try {
54353
54412
  compactionEnabled = isCompactionEnabled(loadPluginConfig(process.cwd()));
@@ -54379,7 +54438,7 @@ async function collectDiagnostics(options = {}) {
54379
54438
  opencodeConfigHasPlugin: configHasPluginEntry(opencodeConfig.value),
54380
54439
  tuiConfigHasPlugin: configHasPluginEntry(tuiConfig.value),
54381
54440
  magicContextConfig: {
54382
- exists: existsSync46(configPaths.magicContextConfig),
54441
+ exists: existsSync47(configPaths.magicContextConfig),
54383
54442
  ...magicContextConfig.error ? { parseError: magicContextConfig.error } : {},
54384
54443
  flags: sanitizeValue(magicContextConfig.value ?? {}) ?? {}
54385
54444
  },
@@ -54387,7 +54446,7 @@ async function collectDiagnostics(options = {}) {
54387
54446
  storageDir: {
54388
54447
  path: storageDirPath,
54389
54448
  source: storageResolution.source,
54390
- exists: existsSync46(storageDirPath),
54449
+ exists: existsSync47(storageDirPath),
54391
54450
  contextDbSizeBytes: fileSize(contextDbPath)
54392
54451
  },
54393
54452
  openCodeDatabase: {
@@ -54458,6 +54517,12 @@ function renderDiagnosticsMarkdown(report) {
54458
54517
  ...openCodeInstallations.map((installation) => `| ${installation.active ? "[active]" : ""} | \`${sanitizeString(installation.path)}\` | ${installation.version} | ${installation.source} |`)
54459
54518
  ] : [];
54460
54519
  const historianDumps = {
54520
+ sessionDumps: {
54521
+ dir: sanitizeString(report.historianDumps.sessionDumps.dir),
54522
+ count: report.historianDumps.sessionDumps.count,
54523
+ sessionCount: report.historianDumps.sessionDumps.sessionCount,
54524
+ sessions: report.historianDumps.sessionDumps.sessions
54525
+ },
54461
54526
  byProject: report.historianDumps.byProject.map((bucket) => ({
54462
54527
  directory: sanitizeString(bucket.directory),
54463
54528
  primarySessionId: bucket.primarySessionId,
@@ -54522,7 +54587,7 @@ function renderDiagnosticsMarkdown(report) {
54522
54587
  "",
54523
54588
  "### Historian dumps",
54524
54589
  "(Metadata only — XML content is not included in this report.)",
54525
- "Dumps are stored per-project under `<project>/.cortexkit/magic-context/historian/`.",
54590
+ "`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
54591
  "```json",
54527
54592
  JSON.stringify(historianDumps, null, 2),
54528
54593
  "```",
@@ -54550,7 +54615,7 @@ function renderDiagnosticsMarkdown(report) {
54550
54615
  ].join(`
54551
54616
  `);
54552
54617
  }
54553
- var import_comment_json10, RECENT_SESSION_GROUP_LIMIT = 5, CHILD_SESSIONS_PER_PARENT_LIMIT = 3;
54618
+ 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
54619
  var init_diagnostics_opencode = __esm(async () => {
54555
54620
  init_config();
54556
54621
  init_agent_disable();
@@ -54558,6 +54623,7 @@ var init_diagnostics_opencode = __esm(async () => {
54558
54623
  init_conflict_detector();
54559
54624
  init_data_path();
54560
54625
  init_opencode_db_path();
54626
+ init_historian_dump_dirs();
54561
54627
  init_log_lines();
54562
54628
  init_opencode_detect();
54563
54629
  init_opencode_helpers();
@@ -54661,9 +54727,9 @@ var init_embedding_local = __esm(async () => {
54661
54727
 
54662
54728
  // src/lib/embedding-runtime.ts
54663
54729
  import { spawnSync as spawnSync9 } from "node:child_process";
54664
- import { existsSync as existsSync47, readFileSync as readFileSync30 } from "node:fs";
54730
+ import { existsSync as existsSync48, readFileSync as readFileSync30 } from "node:fs";
54665
54731
  import { createRequire as createRequire5 } from "node:module";
54666
- import { dirname as dirname25, join as join37, sep as sep2 } from "node:path";
54732
+ import { dirname as dirname25, join as join38, sep as sep2 } from "node:path";
54667
54733
  function describeError(error) {
54668
54734
  const message = error instanceof Error ? error.message : String(error ?? "unknown error");
54669
54735
  const code = error?.code;
@@ -54805,11 +54871,11 @@ function expectedBinaryRelPath(platform, arch) {
54805
54871
  const supportedArch = arch === "x64" || arch === "arm64";
54806
54872
  if (!supportedPlatform || !supportedArch)
54807
54873
  return null;
54808
- return join37("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54874
+ return join38("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54809
54875
  }
54810
54876
  function onnxRuntimeNodeVersion(packageDir) {
54811
54877
  try {
54812
- const parsed = JSON.parse(readFileSync30(join37(packageDir, "package.json"), "utf8"));
54878
+ const parsed = JSON.parse(readFileSync30(join38(packageDir, "package.json"), "utf8"));
54813
54879
  return typeof parsed.version === "string" ? parsed.version : undefined;
54814
54880
  } catch {
54815
54881
  return;
@@ -54858,7 +54924,7 @@ function formatLocalEmbeddingRuntimeWasmSelected(status) {
54858
54924
  function requireNodeWasmBundle(probe, candidates) {
54859
54925
  if (probe.state === "failed")
54860
54926
  return probe;
54861
- const bundlePath = candidates.find((candidate) => existsSync47(candidate));
54927
+ const bundlePath = candidates.find((candidate) => existsSync48(candidate));
54862
54928
  return bundlePath ? probe : {
54863
54929
  state: "failed",
54864
54930
  reason: `functional Node WASM Transformers bundle is missing (checked ${candidates.join(", ")})`
@@ -54866,13 +54932,13 @@ function requireNodeWasmBundle(probe, candidates) {
54866
54932
  }
54867
54933
  function nodeWasmBundleCandidates(installRoot) {
54868
54934
  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")
54935
+ join38(installRoot, "dist", "transformers-node-wasm.js"),
54936
+ join38(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
54937
+ join38(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
54872
54938
  ];
54873
54939
  }
54874
54940
  function probeWasmRuntimeAt(installRoot) {
54875
- const requireFn = createRequire5(join37(installRoot, "package.json"));
54941
+ const requireFn = createRequire5(join38(installRoot, "package.json"));
54876
54942
  return requireNodeWasmBundle(probeWasmRuntimeFromRequire(requireFn), nodeWasmBundleCandidates(installRoot));
54877
54943
  }
54878
54944
  function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
@@ -54881,9 +54947,9 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54881
54947
  const wasm = probeWasmRuntimeAt(installRoot);
54882
54948
  return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
54883
54949
  }
54884
- const packageDir = join37(installRoot, "node_modules", "onnxruntime-node");
54950
+ const packageDir = join38(installRoot, "node_modules", "onnxruntime-node");
54885
54951
  let native;
54886
- if (!existsSync47(join37(packageDir, "package.json"))) {
54952
+ if (!existsSync48(join38(packageDir, "package.json"))) {
54887
54953
  native = { state: "package-missing", packageDir };
54888
54954
  } else {
54889
54955
  const rel = expectedBinaryRelPath(platform, arch);
@@ -54893,8 +54959,8 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54893
54959
  binaryPath: packageDir
54894
54960
  };
54895
54961
  } else {
54896
- const binaryPath = join37(packageDir, rel);
54897
- native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
54962
+ const binaryPath = join38(packageDir, rel);
54963
+ native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
54898
54964
  state: "binary-missing",
54899
54965
  packageDir,
54900
54966
  expectedBinary: binaryPath,
@@ -54905,7 +54971,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54905
54971
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
54906
54972
  }
54907
54973
  function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
54908
- const existing = installRoots.filter((root) => existsSync47(root));
54974
+ const existing = installRoots.filter((root) => existsSync48(root));
54909
54975
  if (existing.length === 0) {
54910
54976
  return {
54911
54977
  state: "unknown",
@@ -54935,15 +55001,15 @@ function packageDirFromResolved(resolvedPath, packageName) {
54935
55001
  }
54936
55002
  function probeWasmRuntimeByResolution(pluginDir) {
54937
55003
  try {
54938
- const reqPlugin = createRequire5(join37(pluginDir, "package.json"));
55004
+ const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
54939
55005
  const direct = probeWasmRuntimeFromRequire(reqPlugin);
54940
55006
  let probe = direct;
54941
55007
  if (direct.state === "failed" && direct.reason.startsWith("onnxruntime-web is not resolvable")) {
54942
55008
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
54943
55009
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
54944
- probe = probeWasmRuntimeFromRequire(createRequire5(join37(tfDir, "package.json")));
55010
+ probe = probeWasmRuntimeFromRequire(createRequire5(join38(tfDir, "package.json")));
54945
55011
  }
54946
- return requireNodeWasmBundle(probe, [join37(pluginDir, "dist", "transformers-node-wasm.js")]);
55012
+ return requireNodeWasmBundle(probe, [join38(pluginDir, "dist", "transformers-node-wasm.js")]);
54947
55013
  } catch (error) {
54948
55014
  return {
54949
55015
  state: "failed",
@@ -54952,7 +55018,7 @@ function probeWasmRuntimeByResolution(pluginDir) {
54952
55018
  }
54953
55019
  }
54954
55020
  function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
54955
- if (!existsSync47(join37(pluginDir, "package.json"))) {
55021
+ if (!existsSync48(join38(pluginDir, "package.json"))) {
54956
55022
  return { state: "unknown", reason: "plugin package dir not found" };
54957
55023
  }
54958
55024
  const selectedRuntime = resolveLocalEmbeddingWorkerRuntime(runtimePreference, host);
@@ -54963,13 +55029,13 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54963
55029
  let onnxDir = null;
54964
55030
  let resolveError;
54965
55031
  try {
54966
- const reqPlugin = createRequire5(join37(pluginDir, "package.json"));
55032
+ const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
54967
55033
  try {
54968
55034
  onnxDir = packageDirFromResolved(reqPlugin.resolve("onnxruntime-node"), "onnxruntime-node");
54969
55035
  } catch {
54970
55036
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
54971
55037
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
54972
- const reqTf = createRequire5(join37(tfDir, "package.json"));
55038
+ const reqTf = createRequire5(join38(tfDir, "package.json"));
54973
55039
  onnxDir = packageDirFromResolved(reqTf.resolve("onnxruntime-node"), "onnxruntime-node");
54974
55040
  }
54975
55041
  } catch (error) {
@@ -54977,7 +55043,7 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54977
55043
  if (resolveError === "ERR_MODULE_NOT_FOUND" || resolveError === "MODULE_NOT_FOUND") {
54978
55044
  return withWasmFallback({
54979
55045
  state: "package-missing",
54980
- packageDir: join37(pluginDir, "node_modules", "onnxruntime-node")
55046
+ packageDir: join38(pluginDir, "node_modules", "onnxruntime-node")
54981
55047
  }, () => probeWasmRuntimeByResolution(pluginDir));
54982
55048
  }
54983
55049
  return {
@@ -54993,8 +55059,8 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54993
55059
  if (rel === null) {
54994
55060
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
54995
55061
  } else {
54996
- const binaryPath = join37(onnxDir, rel);
54997
- native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
55062
+ const binaryPath = join38(onnxDir, rel);
55063
+ native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
54998
55064
  state: "binary-missing",
54999
55065
  packageDir: onnxDir,
55000
55066
  expectedBinary: binaryPath,
@@ -55030,7 +55096,7 @@ var init_embedding_runtime = __esm(async () => {
55030
55096
 
55031
55097
  // src/lib/logs-opencode.ts
55032
55098
  import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "node:fs";
55033
- import { dirname as dirname26, join as join38 } from "node:path";
55099
+ import { dirname as dirname26, join as join39 } from "node:path";
55034
55100
  function formatTimestamp(date) {
55035
55101
  const pad = (value) => String(value).padStart(2, "0");
55036
55102
  return [
@@ -55121,11 +55187,11 @@ async function bundleIssueReport(report, description, title, sessionFilter = nul
55121
55187
  const bodyMarkdown = capBodyToGithubLimit(rawBodyMarkdown);
55122
55188
  const truncated = bodyMarkdown !== rawBodyMarkdown;
55123
55189
  const timestamp = formatTimestamp(new Date);
55124
- const path = options.outputPath ?? join38(process.cwd(), `magic-context-issue-${timestamp}.md`);
55190
+ const path = options.outputPath ?? join39(process.cwd(), `magic-context-issue-${timestamp}.md`);
55125
55191
  mkdirSync9(dirname26(path), { recursive: true });
55126
55192
  writeFileSync9(path, `${bodyMarkdown}
55127
55193
  `);
55128
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join38(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55194
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join39(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55129
55195
  if (fullPath)
55130
55196
  writeFileSync9(fullPath, `${rawBodyMarkdown}
55131
55197
  `);
@@ -55946,10 +56012,10 @@ function removeDeprecatedReasoningAge(config) {
55946
56012
 
55947
56013
  // src/commands/doctor-opencode.ts
55948
56014
  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";
56015
+ import { existsSync as existsSync49, mkdtempSync as mkdtempSync4, readFileSync as readFileSync31, rmSync as rmSync9 } from "node:fs";
55950
56016
  import { createRequire as createRequire6 } from "node:module";
55951
56017
  import { homedir as homedir21, tmpdir as tmpdir4 } from "node:os";
55952
- import { dirname as dirname27, join as join39, resolve as resolve19 } from "node:path";
56018
+ import { dirname as dirname27, join as join40, resolve as resolve19 } from "node:path";
55953
56019
  function formatSharedDbRowCounts(db) {
55954
56020
  return SHARED_DB_ROW_COUNT_TABLES.map((table) => {
55955
56021
  try {
@@ -56020,7 +56086,7 @@ function checkConfiguredVariantCatalog(config, hostGeneration, warn, run = (args
56020
56086
  }
56021
56087
  if (models.length === 0)
56022
56088
  return;
56023
- const tempRoot = mkdtempSync4(join39(tmpdir4(), "magic-context-opencode-catalog-"));
56089
+ const tempRoot = mkdtempSync4(join40(tmpdir4(), "magic-context-opencode-catalog-"));
56024
56090
  try {
56025
56091
  const command = hostGeneration === "v2" ? ["api", "model.list", "--param", `directory=${projectDir}`] : ["models", "--verbose"];
56026
56092
  const guidance = `opencode ${command.join(" ")}`;
@@ -56196,7 +56262,7 @@ function getSelfVersion2() {
56196
56262
  function describeAutoUpdateStall(specifier, autoUpdateEnabled, storageDir = getMagicContextStorageDir()) {
56197
56263
  if (!autoUpdateEnabled || !isPinnedOpenCodePluginSpecifier(specifier))
56198
56264
  return null;
56199
- const state = readAutoUpdateCheckState(join39(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56265
+ const state = readAutoUpdateCheckState(join40(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56200
56266
  const owner = isUpdaterPinnedSpec(state, specifier) ? "updater" : "you";
56201
56267
  return `auto-update: stalled — config pinned to ${specifier} (by ${owner})`;
56202
56268
  }
@@ -56205,12 +56271,12 @@ function getUserNpmrcPath() {
56205
56271
  if (custom)
56206
56272
  return custom;
56207
56273
  const home = process.env.HOME?.trim();
56208
- return join39(home || homedir21(), ".npmrc");
56274
+ return join40(home || homedir21(), ".npmrc");
56209
56275
  }
56210
56276
  function collectNpmReleaseAgeWarnings() {
56211
56277
  const ageWarnings = [];
56212
56278
  const npmrcPath = getUserNpmrcPath();
56213
- if (!existsSync48(npmrcPath))
56279
+ if (!existsSync49(npmrcPath))
56214
56280
  return ageWarnings;
56215
56281
  try {
56216
56282
  const npmrc = readFileSync31(npmrcPath, "utf-8");
@@ -56402,7 +56468,7 @@ function checkLocalEmbeddingRuntimeForDoctor(installRoots, runtimePreference = "
56402
56468
  return { issues: 0 };
56403
56469
  }
56404
56470
  async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56405
- if (!existsSync48(magicContextConfigPath)) {
56471
+ if (!existsSync49(magicContextConfigPath)) {
56406
56472
  return checkLocalEmbeddingRuntimeForDoctor(installRoots);
56407
56473
  }
56408
56474
  let rawText;
@@ -56583,7 +56649,7 @@ async function runDoctor2(options = {}) {
56583
56649
  const v22Result = await runV22BackfillCommands({
56584
56650
  name: "OpenCode",
56585
56651
  openDatabase: (readonly = true) => {
56586
- const dbPath = join39(getMagicContextStorageDir(), "context.db");
56652
+ const dbPath = join40(getMagicContextStorageDir(), "context.db");
56587
56653
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
56588
56654
  return v22Db;
56589
56655
  },
@@ -56619,7 +56685,7 @@ async function runDoctor2(options = {}) {
56619
56685
  if (isMagicContextStorageOutsideEngram(storageDir)) {
56620
56686
  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
56687
  }
56622
- const authorityDbPath = join39(getMagicContextStorageDir(), "context.db");
56688
+ const authorityDbPath = join40(getMagicContextStorageDir(), "context.db");
56623
56689
  let authorityDb = null;
56624
56690
  try {
56625
56691
  authorityDb = openExistingContextDatabase(authorityDbPath, { readonly: true });
@@ -56794,7 +56860,7 @@ async function runDoctor2(options = {}) {
56794
56860
  pass(`OpenCode config: ${paths.opencodeConfig}`);
56795
56861
  }
56796
56862
  let autoUpdateEnabled = true;
56797
- if (existsSync48(paths.magicContextConfig)) {
56863
+ if (existsSync49(paths.magicContextConfig)) {
56798
56864
  pass(`Magic Context config: ${paths.magicContextConfig}`);
56799
56865
  try {
56800
56866
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
@@ -56832,7 +56898,7 @@ async function runDoctor2(options = {}) {
56832
56898
  log3.info(rerankConfigSummary());
56833
56899
  log3.info(" Run 'setup' to create one with model recommendations");
56834
56900
  }
56835
- if (existsSync48(paths.magicContextConfig)) {
56901
+ if (existsSync49(paths.magicContextConfig)) {
56836
56902
  try {
56837
56903
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
56838
56904
  if (!raw)
@@ -57065,7 +57131,7 @@ async function runDoctor2(options = {}) {
57065
57131
  pass("Added TUI sidebar plugin to tui.json");
57066
57132
  warn("Restart OpenCode to see the sidebar");
57067
57133
  fixed++;
57068
- } else if (existsSync48(paths.tuiConfig)) {
57134
+ } else if (existsSync49(paths.tuiConfig)) {
57069
57135
  try {
57070
57136
  const tuiRaw = readFileSync31(paths.tuiConfig, "utf-8");
57071
57137
  const tuiConfig = import_comment_json11.parse(tuiRaw);
@@ -57106,7 +57172,7 @@ async function runDoctor2(options = {}) {
57106
57172
  fail("Could not create or verify the TUI sidebar config");
57107
57173
  }
57108
57174
  }
57109
- if (existsSync48(paths.magicContextConfig)) {
57175
+ if (existsSync49(paths.magicContextConfig)) {
57110
57176
  try {
57111
57177
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
57112
57178
  if (!raw)
@@ -57125,7 +57191,7 @@ async function runDoctor2(options = {}) {
57125
57191
  embeddingHostConfig = import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8"));
57126
57192
  } catch {}
57127
57193
  const embeddingInstalls = getOpenCodeLoadedPluginInstallRoots(hostGeneration, embeddingHostConfig);
57128
- const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync48(root));
57194
+ const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync49(root));
57129
57195
  if (unusedInstalls.length > 0)
57130
57196
  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
57197
  const embeddingCheck = await checkEmbeddingConfig(paths.magicContextConfig, embeddingInstalls.loaded);
@@ -57137,9 +57203,9 @@ async function runDoctor2(options = {}) {
57137
57203
  else
57138
57204
  passCount++;
57139
57205
  const storage = getMagicContextStorageResolution();
57140
- const dbPath = join39(storage.path, "context.db");
57206
+ const dbPath = join40(storage.path, "context.db");
57141
57207
  log3.info(`Shared storage: ${storage.path} (source: ${storage.source})`);
57142
- if (!existsSync48(dbPath)) {
57208
+ if (!existsSync49(dbPath)) {
57143
57209
  log3.info(`Shared context DB not yet created at ${dbPath} (will be created on first run)`);
57144
57210
  } else {
57145
57211
  log3.info(`Shared context DB exists at ${dbPath}`);
@@ -57327,11 +57393,29 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
57327
57393
  }
57328
57394
  }
57329
57395
  const diagnostics = await collectDiagnostics();
57396
+ const sessionDumps = diagnostics.historianDumps.sessionDumps;
57397
+ if (sessionDumps.count > 0) {
57398
+ warn(`Historian debug dumps: ${sessionDumps.count} file(s) across ${sessionDumps.sessionCount} session(s) in ${sessionDumps.dir}`);
57399
+ for (const session of sessionDumps.sessions) {
57400
+ log3.info(` [${session.sessionId}] ${session.count} file(s)`);
57401
+ for (const dump of session.recent.slice(0, 3)) {
57402
+ const age = dump.ageMinutes;
57403
+ const ageStr = age < 60 ? `${age}m ago` : `${Math.round(age / 60)}h ago`;
57404
+ log3.info(` ${dump.name} (${ageStr})`);
57405
+ }
57406
+ if (session.count > 3) {
57407
+ log3.info(` ... and ${session.count - 3} more`);
57408
+ }
57409
+ }
57410
+ if (sessionDumps.sessionCount > sessionDumps.sessions.length) {
57411
+ log3.info(` ... and ${sessionDumps.sessionCount - sessionDumps.sessions.length} more session(s)`);
57412
+ }
57413
+ }
57330
57414
  const dumpBuckets = diagnostics.historianDumps.byProject;
57331
57415
  if (dumpBuckets.length > 0) {
57332
57416
  const totalCount = dumpBuckets.reduce((sum, b) => sum + b.count, 0);
57333
57417
  const sessionCount = dumpBuckets.length;
57334
- warn(`Historian debug dumps: ${totalCount} file(s) across ${sessionCount} project(s)`);
57418
+ warn(`Historian debug dumps from older plugins in project directories: ${totalCount} file(s) across ${sessionCount} project(s)`);
57335
57419
  for (const bucket of dumpBuckets) {
57336
57420
  log3.info(` [${bucket.directory}] ${bucket.count} file(s)`);
57337
57421
  for (const dump of bucket.recent.slice(0, 3)) {
@@ -57676,9 +57760,9 @@ var init_model_chain_health = __esm(() => {
57676
57760
  });
57677
57761
 
57678
57762
  // src/lib/diagnostics-pi.ts
57679
- import { existsSync as existsSync49, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync26 } from "node:fs";
57763
+ import { existsSync as existsSync50, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync27 } from "node:fs";
57680
57764
  import { createRequire as createRequire7 } from "node:module";
57681
- import { join as join40 } from "node:path";
57765
+ import { join as join41 } from "node:path";
57682
57766
  function getSelfVersion3() {
57683
57767
  const req = createRequire7(import.meta.url);
57684
57768
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -57693,7 +57777,7 @@ function getSelfVersion3() {
57693
57777
  }
57694
57778
  function fileSize2(path) {
57695
57779
  try {
57696
- return existsSync49(path) ? statSync26(path).size : 0;
57780
+ return existsSync50(path) ? statSync27(path).size : 0;
57697
57781
  } catch {
57698
57782
  return 0;
57699
57783
  }
@@ -57705,7 +57789,7 @@ function sanitizeValue2(value) {
57705
57789
  return sanitizeConfigValue(value);
57706
57790
  }
57707
57791
  function readJsonc(path) {
57708
- if (!existsSync49(path))
57792
+ if (!existsSync50(path))
57709
57793
  return { value: {} };
57710
57794
  try {
57711
57795
  return {
@@ -57725,7 +57809,7 @@ function readConfigDiagnostic(path) {
57725
57809
  const parsed = readJsonc(path);
57726
57810
  return {
57727
57811
  path,
57728
- exists: existsSync49(path),
57812
+ exists: existsSync50(path),
57729
57813
  ...parsed.parseError ? { parseError: parsed.parseError } : {},
57730
57814
  flags: sanitizeValue2(parsed.value)
57731
57815
  };
@@ -57743,7 +57827,7 @@ function reverseSlugToDirectory(slug) {
57743
57827
  }
57744
57828
  function collectPiRecentSessions() {
57745
57829
  const sessionsRoot = getPiSessionsRoot();
57746
- if (!existsSync49(sessionsRoot))
57830
+ if (!existsSync50(sessionsRoot))
57747
57831
  return [];
57748
57832
  try {
57749
57833
  const slugs = readdirSync11(sessionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
@@ -57752,7 +57836,7 @@ function collectPiRecentSessions() {
57752
57836
  const directory = reverseSlugToDirectory(slug);
57753
57837
  if (!directory)
57754
57838
  continue;
57755
- const slugDir = join40(sessionsRoot, slug);
57839
+ const slugDir = join41(sessionsRoot, slug);
57756
57840
  let files;
57757
57841
  try {
57758
57842
  files = readdirSync11(slugDir).filter((name) => name.endsWith(".jsonl"));
@@ -57761,7 +57845,7 @@ function collectPiRecentSessions() {
57761
57845
  }
57762
57846
  for (const file of files) {
57763
57847
  try {
57764
- const mtime = statSync26(join40(slugDir, file)).mtimeMs;
57848
+ const mtime = statSync27(join41(slugDir, file)).mtimeMs;
57765
57849
  const sessionId = file.replace(/\.jsonl$/, "");
57766
57850
  candidates.push({ sessionId, directory, mtime });
57767
57851
  } catch {}
@@ -57811,46 +57895,36 @@ function parseHistorianDumpMeta2(path) {
57811
57895
  return { error: error instanceof Error ? error.message : String(error) };
57812
57896
  }
57813
57897
  }
57898
+ function summarizeDumps2(dir, files, limit) {
57899
+ const now = Date.now();
57900
+ return files.slice(0, limit).map((entry) => {
57901
+ const meta = parseHistorianDumpMeta2(join41(dir, entry.name));
57902
+ const summary = {
57903
+ name: entry.name,
57904
+ ageMinutes: Math.round((now - entry.mtime) / 60000),
57905
+ sizeKb: entry.sizeKb
57906
+ };
57907
+ if ("error" in meta) {
57908
+ summary.parseError = meta.error;
57909
+ } else {
57910
+ summary.meta = meta;
57911
+ }
57912
+ return summary;
57913
+ });
57914
+ }
57814
57915
  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
- }
57916
+ const files = scanHistorianDumpFiles(dir);
57917
+ return { count: files.length, recent: summarizeDumps2(dir, files, limit) };
57845
57918
  }
57846
- function collectPiHistorianDumps(recentSessions) {
57919
+ function collectPiHistorianDumps(recentSessions, historianRoot = getMagicContextHistorianDir2("pi")) {
57920
+ const sessionDirs = scanHistorianSessionDumpDirs(historianRoot);
57847
57921
  const buckets = new Map;
57848
57922
  for (const session of recentSessions) {
57849
57923
  const dir = session.directory;
57850
57924
  if (!dir)
57851
57925
  continue;
57852
- const projectHistorianDir = getProjectMagicContextHistorianDir(dir);
57853
- const listing = listDumpsInDir2(projectHistorianDir, 5);
57926
+ const projectHistorianDir = getProjectHistorianDumpDir(dir);
57927
+ const listing = listDumpsInDir2(projectHistorianDir, DUMPS_PER_BUCKET_LIMIT2);
57854
57928
  const existing = buckets.get(dir);
57855
57929
  if (existing) {
57856
57930
  if (!existing.sessionIds.includes(session.sessionId)) {
@@ -57868,12 +57942,21 @@ function collectPiHistorianDumps(recentSessions) {
57868
57942
  recent: listing.recent
57869
57943
  });
57870
57944
  }
57871
- const legacyDir = getMagicContextHistorianDir2("pi");
57872
- const legacyListing = listDumpsInDir2(legacyDir, 5);
57945
+ const legacyListing = listDumpsInDir2(historianRoot, DUMPS_PER_BUCKET_LIMIT2);
57873
57946
  return {
57947
+ sessionDumps: {
57948
+ dir: historianRoot,
57949
+ count: sessionDirs.reduce((sum, session) => sum + session.files.length, 0),
57950
+ sessionCount: sessionDirs.length,
57951
+ sessions: sessionDirs.slice(0, SESSION_DUMP_BUCKET_LIMIT2).map((session) => ({
57952
+ sessionId: session.sessionId,
57953
+ count: session.files.length,
57954
+ recent: summarizeDumps2(session.dir, session.files, DUMPS_PER_BUCKET_LIMIT2)
57955
+ }))
57956
+ },
57874
57957
  byProject: [...buckets.values()],
57875
57958
  legacyDumps: {
57876
- dir: legacyDir,
57959
+ dir: historianRoot,
57877
57960
  count: legacyListing.count,
57878
57961
  recent: legacyListing.recent
57879
57962
  }
@@ -57889,7 +57972,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57889
57972
  const loaded = loadPiConfig({ cwd });
57890
57973
  const storageResolution = getMagicContextStorageResolution();
57891
57974
  const storageDirPath = storageResolution.path;
57892
- const dbPath = join40(storageDirPath, "context.db");
57975
+ const dbPath = join41(storageDirPath, "context.db");
57893
57976
  const logFiles = inspectMagicContextLogs("pi");
57894
57977
  const primaryLog = logFiles.find((file) => file.exists) ?? logFiles[0];
57895
57978
  const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
@@ -57906,7 +57989,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57906
57989
  piVersion: pi ? getPiVersion(pi.path) : null,
57907
57990
  settings: {
57908
57991
  path: settingsPath,
57909
- exists: existsSync49(settingsPath),
57992
+ exists: existsSync50(settingsPath),
57910
57993
  ...settingsParsed.parseError ? { parseError: settingsParsed.parseError } : {},
57911
57994
  hasMagicContextPackage: hasPiMagicContextPackage(packages),
57912
57995
  packages: sanitizeValue2(packages)
@@ -57923,7 +58006,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57923
58006
  storageDir: {
57924
58007
  path: storageDirPath,
57925
58008
  source: storageResolution.source,
57926
- exists: existsSync49(storageDirPath),
58009
+ exists: existsSync50(storageDirPath),
57927
58010
  contextDbSizeBytes: fileSize2(dbPath)
57928
58011
  },
57929
58012
  conflicts: {
@@ -58015,12 +58098,13 @@ function renderDiagnosticsMarkdown2(report) {
58015
58098
  ].join(`
58016
58099
  `);
58017
58100
  }
58018
- var import_comment_json12;
58101
+ var import_comment_json12, SESSION_DUMP_BUCKET_LIMIT2 = 10, DUMPS_PER_BUCKET_LIMIT2 = 5;
58019
58102
  var init_diagnostics_pi = __esm(() => {
58020
58103
  init_migrate_config_location();
58021
58104
  init_compartment_parser();
58022
58105
  init_data_path();
58023
58106
  init_config2();
58107
+ init_historian_dump_dirs();
58024
58108
  init_log_lines();
58025
58109
  init_paths();
58026
58110
  init_pi_helpers();
@@ -58031,7 +58115,7 @@ var init_diagnostics_pi = __esm(() => {
58031
58115
 
58032
58116
  // src/lib/logs-pi.ts
58033
58117
  import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync10 } from "node:fs";
58034
- import { dirname as dirname28, join as join41 } from "node:path";
58118
+ import { dirname as dirname28, join as join42 } from "node:path";
58035
58119
  function formatTimestamp2(date) {
58036
58120
  const pad = (value) => String(value).padStart(2, "0");
58037
58121
  return [
@@ -58085,11 +58169,11 @@ async function bundleIssueReport2(report, description, title, options = {}) {
58085
58169
  const truncated = bodyMarkdown !== rawBodyMarkdown;
58086
58170
  const cwd = options.cwd ?? process.cwd();
58087
58171
  const timestamp = formatTimestamp2(options.now ?? new Date);
58088
- const path = options.outputPath ?? join41(cwd, `magic-context-pi-issue-${timestamp}.md`);
58172
+ const path = options.outputPath ?? join42(cwd, `magic-context-pi-issue-${timestamp}.md`);
58089
58173
  mkdirSync10(dirname28(path), { recursive: true });
58090
58174
  writeFileSync10(path, `${bodyMarkdown}
58091
58175
  `);
58092
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join41(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
58176
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join42(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
58093
58177
  if (fullPath)
58094
58178
  writeFileSync10(fullPath, `${rawBodyMarkdown}
58095
58179
  `);
@@ -58103,10 +58187,10 @@ var init_logs_pi = __esm(() => {
58103
58187
 
58104
58188
  // src/commands/doctor-pi.ts
58105
58189
  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";
58190
+ import { existsSync as existsSync51, readdirSync as readdirSync12, readFileSync as readFileSync33, rmSync as rmSync10, statSync as statSync28 } from "node:fs";
58107
58191
  import { createRequire as createRequire8 } from "node:module";
58108
58192
  import { homedir as homedir22 } from "node:os";
58109
- import { isAbsolute as isAbsolute9, join as join42 } from "node:path";
58193
+ import { isAbsolute as isAbsolute9, join as join43 } from "node:path";
58110
58194
  function depsFrom(options) {
58111
58195
  return {
58112
58196
  ...DEFAULT_DEPS5,
@@ -58248,15 +58332,15 @@ function piPluginDirCandidates(packages, cwd) {
58248
58332
  if (resolved)
58249
58333
  dirs.push(resolved);
58250
58334
  }
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")));
58335
+ dirs.push(join43(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58336
+ dirs.push(join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58337
+ return dirs.filter((dir) => existsSync51(join43(dir, "package.json")));
58254
58338
  }
58255
58339
  function projectConfigPath(cwd) {
58256
58340
  return resolveCortexKitProjectConfigPath(cwd);
58257
58341
  }
58258
58342
  function readConfigForEmbedding(path, isProjectConfig) {
58259
- if (!existsSync50(path))
58343
+ if (!existsSync51(path))
58260
58344
  return null;
58261
58345
  try {
58262
58346
  const raw = loadRawConfigFile({
@@ -58347,33 +58431,33 @@ function pinnedVersionFromPackageSpecifier(specifier) {
58347
58431
  }
58348
58432
  function cacheRoots(cwd) {
58349
58433
  const home = process.env.HOME?.trim();
58350
- const cacheHome = process.env.XDG_CACHE_HOME || join42(home || homedir22(), ".cache");
58434
+ const cacheHome = process.env.XDG_CACHE_HOME || join43(home || homedir22(), ".cache");
58351
58435
  const piCacheRoot = getPiCacheRoot();
58352
58436
  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)
58437
+ join43(piCacheRoot, "extensions"),
58438
+ join43(piCacheRoot, "packages"),
58439
+ join43(cacheHome, "pi", "extensions"),
58440
+ join43(cacheHome, "pi", "packages"),
58441
+ join43(getPiAgentConfigDir(), "cache", "extensions"),
58442
+ join43(getPiAgentConfigDir(), "npm", "node_modules", PACKAGE_NAME2),
58443
+ join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2)
58360
58444
  ];
58361
58445
  }
58362
58446
  function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58363
58447
  const found = new Map;
58364
58448
  const visit = (path, depth) => {
58365
- if (depth < 0 || !existsSync50(path))
58449
+ if (depth < 0 || !existsSync51(path))
58366
58450
  return;
58367
58451
  let stat;
58368
58452
  try {
58369
- stat = statSync27(path);
58453
+ stat = statSync28(path);
58370
58454
  } catch {
58371
58455
  return;
58372
58456
  }
58373
58457
  if (!stat.isDirectory())
58374
58458
  return;
58375
- const packageJson = join42(path, "package.json");
58376
- if (existsSync50(packageJson)) {
58459
+ const packageJson = join43(path, "package.json");
58460
+ if (existsSync51(packageJson)) {
58377
58461
  try {
58378
58462
  const pkg = JSON.parse(readFileSync33(packageJson, "utf-8"));
58379
58463
  const name = typeof pkg.name === "string" ? pkg.name : "";
@@ -58395,7 +58479,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58395
58479
  return;
58396
58480
  }
58397
58481
  for (const entry of entries)
58398
- visit(join42(path, entry), depth - 1);
58482
+ visit(join43(path, entry), depth - 1);
58399
58483
  };
58400
58484
  for (const root of cacheRoots(cwd))
58401
58485
  visit(root, 5);
@@ -58456,7 +58540,7 @@ async function runHealthChecks2(options) {
58456
58540
  const settingsPath = getPiUserExtensionsPath();
58457
58541
  let packages = [];
58458
58542
  let piPluginInstalled = false;
58459
- if (!existsSync50(settingsPath)) {
58543
+ if (!existsSync51(settingsPath)) {
58460
58544
  if (pi) {
58461
58545
  add2(results, "info", `${piVersion ? `Pi ${piVersion}` : "Pi"} found; Magic Context is not installed there (run setup to add it)`);
58462
58546
  }
@@ -58498,7 +58582,7 @@ async function runHealthChecks2(options) {
58498
58582
  ["user", userConfigPath, true],
58499
58583
  ["project", projectPath, false]
58500
58584
  ]) {
58501
- if (!existsSync50(path)) {
58585
+ if (!existsSync51(path)) {
58502
58586
  if (required) {
58503
58587
  add2(results, "warn", `No ${label} magic-context.jsonc found at ${path}`);
58504
58588
  if (userConfigMigrationRefused) {
@@ -58545,12 +58629,12 @@ async function runHealthChecks2(options) {
58545
58629
  checkPiModelChains(results, pi, loadedConfig.config, options.deps);
58546
58630
  const storage = getMagicContextStorageResolution();
58547
58631
  const storageDir = storage.path;
58548
- const dbPath = join42(storageDir, "context.db");
58632
+ const dbPath = join43(storageDir, "context.db");
58549
58633
  if (isMagicContextStorageOutsideEngram(storageDir)) {
58550
58634
  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
58635
  }
58552
58636
  add2(results, "info", `Shared storage: ${storageDir} (source: ${storage.source})`);
58553
- const existedBeforeOpen = existsSync50(dbPath);
58637
+ const existedBeforeOpen = existsSync51(dbPath);
58554
58638
  if (existedBeforeOpen)
58555
58639
  add2(results, "pass", `Shared context DB exists at ${dbPath}`);
58556
58640
  else
@@ -58745,10 +58829,28 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
58745
58829
  }
58746
58830
  }
58747
58831
  const diagnosticsForDumps = await collectDiagnostics2(options.cwd);
58832
+ const sessionDumps = diagnosticsForDumps.historianDumps.sessionDumps;
58833
+ if (sessionDumps.count > 0) {
58834
+ add2(results, "warn", `Historian debug dumps: ${sessionDumps.count} file(s) across ${sessionDumps.sessionCount} session(s) in ${sessionDumps.dir}`);
58835
+ for (const session of sessionDumps.sessions) {
58836
+ add2(results, "info", ` [${session.sessionId}] ${session.count} file(s)`);
58837
+ for (const dump of session.recent.slice(0, 3)) {
58838
+ const age = dump.ageMinutes;
58839
+ const ageStr = age < 60 ? `${age}m ago` : `${Math.round(age / 60)}h ago`;
58840
+ add2(results, "info", ` ${dump.name} (${ageStr})`);
58841
+ }
58842
+ if (session.count > 3) {
58843
+ add2(results, "info", ` ... and ${session.count - 3} more`);
58844
+ }
58845
+ }
58846
+ if (sessionDumps.sessionCount > sessionDumps.sessions.length) {
58847
+ add2(results, "info", ` ... and ${sessionDumps.sessionCount - sessionDumps.sessions.length} more session(s)`);
58848
+ }
58849
+ }
58748
58850
  const dumpBuckets = diagnosticsForDumps.historianDumps.byProject;
58749
58851
  if (dumpBuckets.length > 0) {
58750
58852
  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)`);
58853
+ add2(results, "warn", `Historian debug dumps from older plugins in project directories: ${totalCount} file(s) across ${dumpBuckets.length} project(s)`);
58752
58854
  for (const bucket of dumpBuckets) {
58753
58855
  add2(results, "info", ` [${bucket.directory}] ${bucket.count} file(s)`);
58754
58856
  for (const dump of bucket.recent.slice(0, 3)) {
@@ -58807,7 +58909,7 @@ function repair2(plan, prompts) {
58807
58909
  }
58808
58910
  if (plan.writeUserConfig) {
58809
58911
  const configPath = getPiUserConfigPath();
58810
- if (!existsSync50(configPath)) {
58912
+ if (!existsSync51(configPath)) {
58811
58913
  try {
58812
58914
  writeDefaultMagicContextConfig(configPath);
58813
58915
  prompts.log.success(`Wrote default Magic Context config to ${configPath}`);
@@ -58861,7 +58963,7 @@ async function runIssueFlow3(options) {
58861
58963
  if (options.reportPath) {
58862
58964
  try {
58863
58965
  const report = await options.deps.collectDiagnostics(options.cwd);
58864
- const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join42(options.cwd, options.reportPath);
58966
+ const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join43(options.cwd, options.reportPath);
58865
58967
  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
58968
  options.prompts.log.info(`Report written to ${bundled.path}`);
58867
58969
  return 0;
@@ -58945,7 +59047,7 @@ async function runDoctor3(options = {}) {
58945
59047
  const v22Result = await runV22BackfillCommands({
58946
59048
  name: "Pi",
58947
59049
  openDatabase: (readonly = true) => {
58948
- const dbPath = join42(getMagicContextStorageDir(), "context.db");
59050
+ const dbPath = join43(getMagicContextStorageDir(), "context.db");
58949
59051
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
58950
59052
  return v22Db;
58951
59053
  },
@@ -59063,8 +59165,8 @@ var init_doctor_pi = __esm(async () => {
59063
59165
  });
59064
59166
 
59065
59167
  // src/commands/doctor.ts
59066
- import { existsSync as existsSync51, rmSync as rmSync11 } from "node:fs";
59067
- import { join as join43 } from "node:path";
59168
+ import { existsSync as existsSync52, rmSync as rmSync11 } from "node:fs";
59169
+ import { join as join44 } from "node:path";
59068
59170
  async function runDoctor4(options) {
59069
59171
  if (options.clear)
59070
59172
  return runClear();
@@ -59082,7 +59184,7 @@ async function runDoctor4(options) {
59082
59184
  const result = await runV22BackfillCommands({
59083
59185
  name: "Magic Context",
59084
59186
  openDatabase: (readonly = true) => {
59085
- const dbPath = join43(getMagicContextStorageDir(), "context.db");
59187
+ const dbPath = join44(getMagicContextStorageDir(), "context.db");
59086
59188
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
59087
59189
  return v22Db;
59088
59190
  },
@@ -59102,7 +59204,7 @@ async function runDoctor4(options) {
59102
59204
  log3.warn(`Identity split check unavailable: ${error instanceof Error ? error.message : String(error)}`);
59103
59205
  }
59104
59206
  await init_migrate();
59105
- const sweepDbPath = join43(getMagicContextStorageDir(), "context.db");
59207
+ const sweepDbPath = join44(getMagicContextStorageDir(), "context.db");
59106
59208
  let sweepDb = null;
59107
59209
  try {
59108
59210
  sweepDb = openExistingContextDatabaseForMutation(sweepDbPath);
@@ -59219,7 +59321,7 @@ async function runClear() {
59219
59321
  failed += 1;
59220
59322
  continue;
59221
59323
  }
59222
- } else if (existsSync51(item.path)) {
59324
+ } else if (existsSync52(item.path)) {
59223
59325
  rmSync11(item.path, { recursive: true, force: true });
59224
59326
  }
59225
59327
  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.60",
4
4
  "description": "Unified CLI for Magic Context — setup, doctor, and migration across OpenCode, Pi, and OMP",
5
5
  "keywords": [
6
6
  "opencode",