@cortexkit/pi-magic-context 0.49.0 → 0.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/{embedding-backfill-b71dvfs8.js → embedding-backfill-scywarbn.js} +7 -7
  3. package/dist/embedding-worker-process.js +29 -0
  4. package/dist/embedding-worker.js +5 -5
  5. package/dist/index-0j0zqb4t.js +712 -0
  6. package/dist/{index-hwqb3s7f.js → index-0rasmwm8.js} +5 -5
  7. package/dist/{index-bejpsj10.js → index-27jh224p.js} +1 -1
  8. package/dist/{index-ehybv5nr.js → index-28vnkyy7.js} +1129 -2990
  9. package/dist/{index-r024r8da.js → index-4gfq5t09.js} +16 -1
  10. package/dist/{index-vf38qhee.js → index-81nthk8j.js} +44 -1
  11. package/dist/{index-yzcjxnt2.js → index-b2anqqad.js} +422 -6
  12. package/dist/{index-1evzceyw.js → index-cyrnv16r.js} +314 -1072
  13. package/dist/index-fqb1bddn.js +4947 -0
  14. package/dist/{index-041ex0cj.js → index-g7hndmqm.js} +20 -34
  15. package/dist/index-gc2749rx.js +1168 -0
  16. package/dist/{index-t7xfqtg6.js → index-p5zesr4e.js} +22 -718
  17. package/dist/{index-yarjn32j.js → index-r874cgmv.js} +38 -36
  18. package/dist/{index-3mgf68pn.js → index-rd53pk0h.js} +1 -1
  19. package/dist/{index-904reqtg.js → index-rdtgp48t.js} +6 -4
  20. package/dist/index.js +1159 -1126
  21. package/dist/{message-index-bounded-qz5dz2se.js → message-index-bounded-110sb4fm.js} +6 -5
  22. package/dist/migration-worker.js +6 -5
  23. package/dist/{project-embedding-registry-ky7wrkr1.js → project-embedding-registry-64t0mw8y.js} +6 -6
  24. package/dist/raw-ordinal-warmup-worker.js +1 -1
  25. package/dist/{read-session-chunk-24sd89tf.js → read-session-chunk-rvmc25n5.js} +3 -2
  26. package/dist/{search-jbh28nwy.js → search-7z3w8pmz.js} +15 -14
  27. package/dist/subagent-entry.js +17 -16
  28. package/package.json +3 -3
  29. package/dist/index-3rea6zd9.js +0 -2396
  30. package/dist/index-bgmv2kaf.js +0 -290
  31. /package/dist/{index-5prbx026.js → index-2pp04pmg.js} +0 -0
@@ -6,9 +6,6 @@ import {
6
6
  writeForwardedLogLine2,
7
7
  log2
8
8
  } from "./index-x3dcnxh0.js";
9
- import {
10
- harnessOwnsOpenCodeStore2
11
- } from "./index-0h2mkab2.js";
12
9
  import {
13
10
  registerSlowWriteReporter2,
14
11
  registerSqliteDiagnosticSink2,
@@ -19,12 +16,26 @@ import {
19
16
  isTransientSqliteError2,
20
17
  withPrivilegedWriter2
21
18
  } from "./index-3cgbv47m.js";
19
+ import {
20
+ harnessOwnsOpenCodeStore2
21
+ } from "./index-0h2mkab2.js";
22
+ import {
23
+ isOwnRpcServerRecord,
24
+ isPidAlive,
25
+ readProcessProbeEvidence,
26
+ classifyProcessKind,
27
+ isPidIdentityPlausible,
28
+ inspectLivePiProcesses,
29
+ parseRpcPortFile,
30
+ inspectProcessesAsync,
31
+ inspectWindowsProcessesSync
32
+ } from "./index-0j0zqb4t.js";
22
33
  import {
23
34
  configureContextDatabasePragmas2
24
35
  } from "./index-fapenpch.js";
25
36
  import {
26
37
  startMessageFtsRowidMapBackfill
27
- } from "./index-r024r8da.js";
38
+ } from "./index-4gfq5t09.js";
28
39
  import {
29
40
  LKG_SLOT_CHUNKS_DDL,
30
41
  SESSION_REPLAY_DECISIONS_DDL,
@@ -34,7 +45,7 @@ import {
34
45
  hasPendingMigrations,
35
46
  getMainThreadMigrationBodyCount,
36
47
  runMigrations
37
- } from "./index-3mgf68pn.js";
48
+ } from "./index-rd53pk0h.js";
38
49
  import {
39
50
  closeQuietly,
40
51
  ensureColumn,
@@ -50,7 +61,7 @@ import {
50
61
  import {
51
62
  bootQuietRemainingMs,
52
63
  scheduleAfterBootQuiet
53
- } from "./index-041ex0cj.js";
64
+ } from "./index-g7hndmqm.js";
54
65
  import {
55
66
  logSlowWriteTransaction
56
67
  } from "./index-0vrkp1jq.js";
@@ -61,7 +72,7 @@ import {
61
72
  copyStorageFileSync,
62
73
  copyStorageTreeSync,
63
74
  tightenStorageTreeSync
64
- } from "./index-vf38qhee.js";
75
+ } from "./index-81nthk8j.js";
65
76
 
66
77
  // ../plugin/src/features/magic-context/fail-closed-block.ts
67
78
  var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
@@ -287,713 +298,6 @@ function createFailClosedController(options) {
287
298
  };
288
299
  }
289
300
 
290
- // ../plugin/src/shared/rpc-utils.ts
291
- import { execFile, execFileSync } from "node:child_process";
292
- import { readFileSync } from "node:fs";
293
-
294
- // ../plugin/src/shared/pi-executable.ts
295
- var PI_IMAGE_NAMES = new Set(["pi", "pi.cmd", "omp", "oh-my-pi"]);
296
- function piHarnessKindFromExecutable(value) {
297
- const executable = (value ?? "").trim().replace(/^['"]|['"]$/g, "").replaceAll("\\", "/").split("/").at(-1)?.toLowerCase().replace(/\.(?:exe|cmd)$/, "");
298
- if (!executable || !PI_IMAGE_NAMES.has(executable))
299
- return;
300
- return executable === "pi" ? "pi" : "omp";
301
- }
302
-
303
- // ../plugin/src/shared/rpc-utils.ts
304
- var ownRpcServerInstanceIds = new Set;
305
- function isOwnRpcServerRecord(record) {
306
- return record.pid === process.pid && record.instance_id !== undefined && ownRpcServerInstanceIds.has(record.instance_id);
307
- }
308
- function isPidAlive(pid) {
309
- if (!Number.isInteger(pid) || pid <= 0)
310
- return "dead";
311
- if (rpcIdentityPlatform === "win32")
312
- return readWindowsProcess(pid).state;
313
- try {
314
- rpcIdentityProcessKill(pid, 0);
315
- return "alive";
316
- } catch (error) {
317
- return error.code === "ESRCH" ? "dead" : "inconclusive";
318
- }
319
- }
320
- var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
321
- var LINUX_CLOCK_TICKS_PER_SECOND = 100;
322
- var PS_PROBE_TIMEOUT_MS = 1000;
323
- var WINDOWS_CIM_PROBE_TIMEOUT_MS = 5000;
324
- var WINDOWS_PROCESS_SNAPSHOT_TTL_MS = 2000;
325
- var MAX_ANCESTOR_WALK_DEPTH = 16;
326
- var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
327
- var WINDOWS_CIM_COMMAND = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='CreationDate';Expression={if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }}} | ConvertTo-Json -Compress";
328
- var PROCESS_LIST_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
329
- var PI_HARNESS_ARC_MARKERS = [
330
- "pi-coding-agent",
331
- "oh-my-pi",
332
- "@oh-my-pi",
333
- "cljs/dist",
334
- "dist/bundle/cli"
335
- ];
336
- var rpcIdentityReadFileSync = readFileSync;
337
- var rpcIdentityExecFileSync = execFileSync;
338
- var rpcIdentityProcessKill = process.kill;
339
- var rpcProcessListExecFileSync = execFileSync;
340
- var rpcIdentityPlatform = process.platform;
341
- var rpcIdentityNowMs = () => Date.now();
342
- function parseLinuxProcessStartTime(statContent, uptimeContent) {
343
- const closingCommandName = statContent.lastIndexOf(")");
344
- if (closingCommandName < 0)
345
- return null;
346
- const statFields = statContent.slice(closingCommandName + 1).trim().split(/\s+/);
347
- const startTimeTicks = Number(statFields[19]);
348
- const uptimeSeconds = Number(uptimeContent.trim().split(/\s+/)[0]);
349
- if (!Number.isFinite(startTimeTicks) || startTimeTicks < 0 || !Number.isFinite(uptimeSeconds) || uptimeSeconds < 0) {
350
- return null;
351
- }
352
- const processStartTime = rpcIdentityNowMs() - uptimeSeconds * 1000 + startTimeTicks / LINUX_CLOCK_TICKS_PER_SECOND * 1000;
353
- return Number.isFinite(processStartTime) ? processStartTime : null;
354
- }
355
- function readLinuxProcessStartTime(pid) {
356
- try {
357
- const statContent = String(rpcIdentityReadFileSync(`/proc/${pid}/stat`, "utf8"));
358
- const uptimeContent = String(rpcIdentityReadFileSync("/proc/uptime", "utf8"));
359
- return parseLinuxProcessStartTime(statContent, uptimeContent);
360
- } catch {
361
- return null;
362
- }
363
- }
364
- function readPsProcessStartTime(pid) {
365
- try {
366
- const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
367
- encoding: "utf8",
368
- timeout: PS_PROBE_TIMEOUT_MS,
369
- stdio: ["ignore", "pipe", "pipe"],
370
- windowsHide: true
371
- });
372
- const processStartTime = Date.parse(String(output).trim());
373
- return Number.isFinite(processStartTime) ? processStartTime : null;
374
- } catch {
375
- return null;
376
- }
377
- }
378
- function readProcessStartTime(pid) {
379
- if (!Number.isInteger(pid) || pid <= 0)
380
- return null;
381
- return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? readWindowsProcessStartTime(pid) : readPsProcessStartTime(pid);
382
- }
383
- function readProcessProbeEvidence(pid) {
384
- return {
385
- startTime: readProcessStartTime(pid),
386
- commandLine: readProcessCommand(pid)
387
- };
388
- }
389
- function readCachedWindowsImageName(pid) {
390
- return rpcIdentityPlatform === "win32" ? windowsProcessFactsCache?.get(pid)?.imageName ?? null : null;
391
- }
392
- var windowsProcessFactsCache = null;
393
- var windowsProcessSnapshotCache = null;
394
- function rememberWindowsProcessFacts(facts) {
395
- windowsProcessFactsCache = new Map(facts.map((fact) => [fact.pid, fact]));
396
- }
397
- function parseCsvLine(line) {
398
- const fields = [];
399
- let field = "";
400
- let quoted = false;
401
- for (let index = 0;index < line.length; index += 1) {
402
- const character = line[index];
403
- if (character === '"') {
404
- if (quoted && line[index + 1] === '"') {
405
- field += '"';
406
- index += 1;
407
- } else {
408
- quoted = !quoted;
409
- }
410
- } else if (character === "," && !quoted) {
411
- fields.push(field);
412
- field = "";
413
- } else {
414
- field += character;
415
- }
416
- }
417
- if (quoted)
418
- return null;
419
- fields.push(field);
420
- return fields;
421
- }
422
- function parseTasklistOutput(output) {
423
- const entries = [];
424
- for (const rawLine of output.split(/\r?\n/)) {
425
- const line = rawLine.trim();
426
- if (!line)
427
- continue;
428
- const fields = parseCsvLine(line);
429
- if (!fields)
430
- continue;
431
- if (fields[1]?.trim().toLowerCase() === "pid") {
432
- continue;
433
- }
434
- const pid = Number(fields[1]);
435
- if (!Number.isInteger(pid) || pid <= 0 || !fields[0])
436
- continue;
437
- entries.push({ pid, command: fields[0] });
438
- }
439
- return entries;
440
- }
441
- function readWindowsProcess(pid) {
442
- try {
443
- const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], {
444
- encoding: "utf8",
445
- timeout: PS_PROBE_TIMEOUT_MS,
446
- stdio: ["ignore", "pipe", "pipe"],
447
- windowsHide: true
448
- });
449
- const entries = parseTasklistOutput(String(output));
450
- if (entries === null)
451
- return { state: "inconclusive" };
452
- const process2 = entries.find((entry) => entry.pid === pid);
453
- return process2 ? { state: "alive", command: process2.command } : { state: "dead" };
454
- } catch {
455
- return { state: "inconclusive" };
456
- }
457
- }
458
- function readWindowsProcessStartTime(pid) {
459
- const cached = windowsProcessFactsCache?.get(pid);
460
- if (cached)
461
- return cached.startTime;
462
- const snapshot = tryReadWindowsCimSnapshot(rpcIdentityExecFileSync);
463
- if (!snapshot)
464
- return null;
465
- rememberWindowsProcessFacts(snapshot.facts);
466
- return windowsProcessFactsCache?.get(pid)?.startTime ?? null;
467
- }
468
- function readLinuxProcessCommand(pid) {
469
- try {
470
- return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
471
- } catch {
472
- return null;
473
- }
474
- }
475
- function readPsProcessCommand(pid) {
476
- try {
477
- const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "command="], {
478
- encoding: "utf8",
479
- timeout: PS_PROBE_TIMEOUT_MS,
480
- stdio: ["ignore", "pipe", "pipe"],
481
- windowsHide: true
482
- });
483
- return String(output);
484
- } catch {
485
- return null;
486
- }
487
- }
488
- function readProcessCommand(pid) {
489
- if (!Number.isInteger(pid) || pid <= 0)
490
- return null;
491
- if (rpcIdentityPlatform === "linux")
492
- return readLinuxProcessCommand(pid);
493
- if (rpcIdentityPlatform === "win32") {
494
- const cached = windowsProcessFactsCache?.get(pid);
495
- if (cached?.commandLine)
496
- return cached.commandLine;
497
- return readWindowsProcess(pid).command ?? null;
498
- }
499
- return readPsProcessCommand(pid);
500
- }
501
- function executableName(token) {
502
- return (token ?? "").replace(/^['"]|['"]$/g, "").split("/").at(-1) ?? "";
503
- }
504
- function commandTokens(command) {
505
- return command.toLowerCase().replaceAll("\\", "/").replaceAll("\x00", " ").split(/\s+/).map((token) => token.replace(/^['"]|['"]$/g, "")).filter(Boolean);
506
- }
507
- function commandHasOpenCodeExecutable(tokens) {
508
- return tokens.findIndex((token) => {
509
- const executable = executableName(token).replace(/\.(?:exe|cmd)$/, "");
510
- return executable === "opencode" || executable.endsWith("/opencode");
511
- });
512
- }
513
- function commandHasPiExecutable(tokens) {
514
- for (let index = 0;index < tokens.length; index += 1) {
515
- const executable = executableName(tokens[index]).replace(/\.(?:exe|cmd)$/, "");
516
- if (piHarnessKindFromExecutable(executable) !== undefined)
517
- return true;
518
- if (["node", "bun", "deno"].includes(executable)) {
519
- const script = executableName(tokens[index + 1]).replace(/\.(?:exe|cmd)$/, "");
520
- if (["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script) || tokens[index + 1]?.includes("pi-coding-agent")) {
521
- return true;
522
- }
523
- }
524
- }
525
- return false;
526
- }
527
- function classifyProcessKind(command) {
528
- if (!command)
529
- return "process";
530
- const tokens = commandTokens(command);
531
- const openCodeIndex = commandHasOpenCodeExecutable(tokens);
532
- if (openCodeIndex >= 0) {
533
- const args = tokens.slice(openCodeIndex + 1);
534
- if (args.some((token) => token === "serve" || token === "--serve" || token.startsWith("--serve="))) {
535
- return "OpenCode server";
536
- }
537
- return "OpenCode instance (TUI/CLI)";
538
- }
539
- return commandHasPiExecutable(tokens) ? "Pi" : "process";
540
- }
541
- function commandLooksLikeOpenCode(command) {
542
- const normalized = command.toLowerCase();
543
- return OPEN_CODE_COMMAND_MARKERS.some((marker) => normalized.includes(marker));
544
- }
545
- var RPC_HOST_PROCESS_MARKERS = [
546
- "opencode",
547
- "openchamber",
548
- "ck-mc",
549
- "magic-context",
550
- "cortexkit",
551
- "electron",
552
- "node",
553
- "bun",
554
- "deno",
555
- "pi-coding-agent",
556
- "oh-my-pi"
557
- ];
558
- function processCannotBeRpcHost(evidence) {
559
- const texts = [evidence.imageName, evidence.commandLine].filter((text) => typeof text === "string" && text.trim().length > 0);
560
- if (texts.length === 0)
561
- return false;
562
- for (const text of texts) {
563
- const normalized = text.toLowerCase();
564
- if (RPC_HOST_PROCESS_MARKERS.some((marker) => normalized.includes(marker)))
565
- return false;
566
- const tokens = commandTokens(text);
567
- if (commandHasPiExecutable(tokens))
568
- return false;
569
- if (tokens.some((token) => piHarnessKindFromExecutable(token) !== undefined))
570
- return false;
571
- }
572
- return true;
573
- }
574
- function isPidIdentityPlausible(record, evidence) {
575
- if (!Number.isInteger(record.pid) || record.pid <= 0)
576
- return "implausible";
577
- if (Number.isFinite(record.started_at) && record.started_at > 0) {
578
- const processStartTime = evidence ? evidence.startTime : readProcessStartTime(record.pid);
579
- if (processStartTime !== null) {
580
- return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS ? "plausible" : "implausible";
581
- }
582
- const identity = evidence ?? {
583
- commandLine: readProcessCommand(record.pid),
584
- imageName: readCachedWindowsImageName(record.pid)
585
- };
586
- return processCannotBeRpcHost(identity) ? "implausible" : "inconclusive";
587
- }
588
- const command = evidence ? evidence.commandLine : rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(record.pid).command ?? null : readPsProcessCommand(record.pid);
589
- if (command === null)
590
- return "inconclusive";
591
- if (commandLooksLikeOpenCode(command))
592
- return "plausible";
593
- return processCannotBeRpcHost({ commandLine: command, imageName: evidence?.imageName }) ? "implausible" : "inconclusive";
594
- }
595
- function commandLooksLikePiImage(command) {
596
- const tokens = commandTokens(command);
597
- const first = executableName(tokens[0]).replace(/\.(?:exe|cmd)$/, "");
598
- return PI_IMAGE_NAMES.has(first);
599
- }
600
- function commandHasPiHarnessArc(command) {
601
- const normalized = command.trim().toLowerCase().replaceAll("\\", "/").replaceAll("\x00", " ");
602
- if (!normalized)
603
- return false;
604
- const tokens = commandTokens(command);
605
- if (tokens.length === 0)
606
- return false;
607
- const hasArc = PI_HARNESS_ARC_MARKERS.some((marker) => normalized.includes(marker));
608
- const first = executableName(tokens[0]).replace(/\.(?:exe|cmd)$/, "");
609
- if (hasArc && ["pi", "omp", "oh-my-pi", "node", "bun", "deno", "cmd"].includes(first)) {
610
- return true;
611
- }
612
- if (hasArc && PI_HARNESS_ARC_MARKERS.some((marker) => tokens[0].includes(marker))) {
613
- return true;
614
- }
615
- if (["node", "bun", "deno"].includes(first)) {
616
- const script = executableName(tokens[1]).replace(/\.(?:exe|cmd)$/, "");
617
- if (["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script))
618
- return true;
619
- if (hasArc)
620
- return true;
621
- }
622
- return false;
623
- }
624
- function execProcessList(exec, file, args, timeout = PS_PROBE_TIMEOUT_MS) {
625
- return String(exec(file, [...args], {
626
- encoding: "utf8",
627
- timeout,
628
- maxBuffer: PROCESS_LIST_MAX_BUFFER_BYTES,
629
- stdio: ["ignore", "pipe", "pipe"],
630
- windowsHide: true
631
- }));
632
- }
633
- function parseWindowsCreationDate(value) {
634
- if (value !== null && typeof value === "object" && "value" in value) {
635
- return parseWindowsCreationDate(value.value);
636
- }
637
- if (typeof value === "number" && Number.isFinite(value)) {
638
- return value > 1000000000000 ? value : value * 1000;
639
- }
640
- if (typeof value !== "string")
641
- return null;
642
- const trimmed = value.trim();
643
- if (!trimmed)
644
- return null;
645
- const wmi = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/.exec(trimmed);
646
- if (wmi) {
647
- const utcMs = Date.UTC(Number(wmi[1]), Number(wmi[2]) - 1, Number(wmi[3]), Number(wmi[4]), Number(wmi[5]), Number(wmi[6]), Number(wmi[7]) / 1000);
648
- if (!Number.isFinite(utcMs))
649
- return null;
650
- const offsetMinutes = Number(wmi[9]);
651
- const sign = wmi[8] === "+" ? 1 : -1;
652
- return utcMs - sign * offsetMinutes * 60000;
653
- }
654
- const dotNet = /^\/Date\((-?\d+)\)\/$/.exec(trimmed);
655
- if (dotNet) {
656
- const milliseconds = Number(dotNet[1]);
657
- return Number.isFinite(milliseconds) ? milliseconds : null;
658
- }
659
- const parsed = Date.parse(trimmed);
660
- return Number.isFinite(parsed) ? parsed : null;
661
- }
662
- function parseWindowsCimOutput(output) {
663
- const trimmed = output.trim();
664
- if (!trimmed)
665
- return null;
666
- const bracket = trimmed.indexOf("[");
667
- const brace = trimmed.indexOf("{");
668
- const start = Math.min(bracket === -1 ? Number.POSITIVE_INFINITY : bracket, brace === -1 ? Number.POSITIVE_INFINITY : brace);
669
- if (!Number.isFinite(start))
670
- return null;
671
- let parsed;
672
- try {
673
- parsed = JSON.parse(trimmed.slice(start));
674
- } catch {
675
- return null;
676
- }
677
- if (parsed == null)
678
- return null;
679
- const rows = Array.isArray(parsed) ? parsed : [parsed];
680
- const facts = [];
681
- for (const row of rows) {
682
- if (!row || typeof row !== "object")
683
- continue;
684
- const record = row;
685
- const pid = Number(record.ProcessId);
686
- if (!Number.isInteger(pid) || pid <= 0)
687
- continue;
688
- const parentRaw = record.ParentProcessId;
689
- const parentPid = parentRaw == null || parentRaw === "" ? Number.NaN : Number(parentRaw);
690
- const commandLine = typeof record.CommandLine === "string" ? record.CommandLine : null;
691
- facts.push({
692
- pid,
693
- parentPid: Number.isInteger(parentPid) && parentPid > 0 ? parentPid : null,
694
- commandLine,
695
- imageName: typeof record.Name === "string" ? record.Name : commandLine ? executableName(commandTokens(commandLine)[0]) : null,
696
- startTime: parseWindowsCreationDate(record.CreationDate)
697
- });
698
- }
699
- return facts.length > 0 ? facts : null;
700
- }
701
- function snapshotFromFacts(facts, source) {
702
- const parentByPid = new Map;
703
- for (const fact of facts) {
704
- if (fact.parentPid != null)
705
- parentByPid.set(fact.pid, fact.parentPid);
706
- }
707
- return { facts, parentByPid, source };
708
- }
709
- function tryReadWindowsCimSnapshot(exec) {
710
- try {
711
- const output = execProcessList(exec, "powershell", ["-NoProfile", "-Command", WINDOWS_CIM_COMMAND], WINDOWS_CIM_PROBE_TIMEOUT_MS);
712
- const facts = parseWindowsCimOutput(output);
713
- return facts ? snapshotFromFacts(facts, "cim") : null;
714
- } catch {
715
- return null;
716
- }
717
- }
718
- function tryReadWindowsTasklistSnapshot() {
719
- try {
720
- const output = execProcessList(rpcProcessListExecFileSync, "tasklist", [
721
- "/FO",
722
- "CSV",
723
- "/NH"
724
- ]);
725
- const entries = parseTasklistOutput(output);
726
- if (entries === null)
727
- return null;
728
- const facts = entries.map((entry) => ({
729
- pid: entry.pid,
730
- parentPid: null,
731
- commandLine: null,
732
- imageName: entry.command,
733
- startTime: null
734
- }));
735
- return snapshotFromFacts(facts, "tasklist");
736
- } catch {
737
- return null;
738
- }
739
- }
740
- function readPosixProcessSnapshot() {
741
- const output = execProcessList(rpcProcessListExecFileSync, "ps", ["-axo", "pid=,command="]);
742
- const facts = [];
743
- for (const line of output.split(/\r?\n/)) {
744
- const match = /^\s*(\d+)\s+(.+)$/.exec(line);
745
- if (!match)
746
- continue;
747
- const pid = Number(match[1]);
748
- if (!Number.isInteger(pid) || pid <= 0)
749
- continue;
750
- facts.push({
751
- pid,
752
- parentPid: null,
753
- commandLine: match[2],
754
- imageName: executableName(commandTokens(match[2])[0]),
755
- startTime: null
756
- });
757
- }
758
- return snapshotFromFacts(facts, "ps");
759
- }
760
- function readPosixParentPid(pid) {
761
- try {
762
- const output = execProcessList(rpcProcessListExecFileSync, "ps", [
763
- "-o",
764
- "ppid=",
765
- "-p",
766
- String(pid)
767
- ]);
768
- const match = /^\s*(\d+)\s*$/.exec(output);
769
- if (!match)
770
- return null;
771
- const ppid = Number(match[1]);
772
- return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
773
- } catch {
774
- return null;
775
- }
776
- }
777
- function collectAncestorPids(selfPid, parentByPid, probeParents = true) {
778
- const ancestors = new Set;
779
- let current = selfPid;
780
- for (let depth = 0;depth < MAX_ANCESTOR_WALK_DEPTH; depth += 1) {
781
- let ppid = null;
782
- if (parentByPid.has(current)) {
783
- ppid = parentByPid.get(current) ?? null;
784
- } else if (rpcIdentityPlatform !== "win32" && probeParents) {
785
- ppid = readPosixParentPid(current);
786
- if (ppid == null && current === process.pid && process.ppid > 0) {
787
- ppid = process.ppid;
788
- }
789
- } else if (current === process.pid && process.ppid > 0) {
790
- ppid = process.ppid;
791
- } else {
792
- break;
793
- }
794
- if (ppid == null || ppid <= 0 || ppid === current || ancestors.has(ppid))
795
- break;
796
- ancestors.add(ppid);
797
- current = ppid;
798
- }
799
- return ancestors;
800
- }
801
- function classifyLivePiSnapshot(snapshot, probeParents = true) {
802
- const ancestors = collectAncestorPids(process.pid, snapshot.parentByPid, probeParents);
803
- const processIds = new Set;
804
- const inconclusivePids = new Set;
805
- const skippedAncestorPids = [];
806
- for (const fact of snapshot.facts) {
807
- if (fact.pid === process.pid)
808
- continue;
809
- const command = fact.commandLine ?? fact.imageName ?? "";
810
- const looksLikeHarness = commandHasPiHarnessArc(command) || commandLooksLikePiImage(command);
811
- if (!looksLikeHarness)
812
- continue;
813
- if (ancestors.has(fact.pid)) {
814
- skippedAncestorPids.push(fact.pid);
815
- log2(`[magic-context] Pi process scan: skipping ancestor PID ${fact.pid} (session launcher shim)`);
816
- continue;
817
- }
818
- if (commandHasPiHarnessArc(command)) {
819
- processIds.add(fact.pid);
820
- continue;
821
- }
822
- inconclusivePids.add(fact.pid);
823
- log2(`[magic-context] Pi process scan: PID ${fact.pid} command line is ambiguous (image-name or missing Pi/OMP arc); treating as inconclusive`);
824
- }
825
- skippedAncestorPids.sort((left, right) => left - right);
826
- const verified = [...processIds].sort((left, right) => left - right);
827
- const inconclusive = [...inconclusivePids].sort((left, right) => left - right);
828
- if (verified.length === 0 && inconclusive.length > 0) {
829
- return {
830
- state: "inconclusive",
831
- processIds: [],
832
- inconclusivePids: inconclusive,
833
- ...skippedAncestorPids.length > 0 ? { skippedAncestorPids } : {}
834
- };
835
- }
836
- return {
837
- state: "known",
838
- processIds: verified,
839
- ...inconclusive.length > 0 ? { inconclusivePids: inconclusive } : {},
840
- ...skippedAncestorPids.length > 0 ? { skippedAncestorPids } : {}
841
- };
842
- }
843
- function inspectLivePiProcesses() {
844
- if (false) {}
845
- try {
846
- if (rpcIdentityPlatform === "win32") {
847
- const now = rpcIdentityNowMs();
848
- const cached = windowsProcessSnapshotCache;
849
- const snapshot = cached && now >= cached.at && now - cached.at < WINDOWS_PROCESS_SNAPSHOT_TTL_MS ? cached.snapshot : tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
850
- if (!snapshot) {
851
- return {
852
- state: "unreadable",
853
- processIds: [],
854
- error: "process list unavailable"
855
- };
856
- }
857
- if (snapshot !== cached?.snapshot)
858
- windowsProcessSnapshotCache = { snapshot, at: now };
859
- rememberWindowsProcessFacts(snapshot.facts);
860
- return classifyLivePiSnapshot(snapshot);
861
- }
862
- return classifyLivePiSnapshot(readPosixProcessSnapshot());
863
- } catch (error) {
864
- return {
865
- state: "unreadable",
866
- processIds: [],
867
- error: error instanceof Error ? error.message : String(error)
868
- };
869
- }
870
- }
871
- function parseRpcPortFile(content, fallbackPid = 0) {
872
- const trimmed = content.trim();
873
- if (!trimmed)
874
- return null;
875
- if (trimmed.startsWith("{")) {
876
- try {
877
- const parsed = JSON.parse(trimmed);
878
- const port = Number(parsed.port);
879
- const pid = Number(parsed.pid);
880
- const startedAt = Number(parsed.started_at);
881
- if (!isValidPort(port) || !Number.isInteger(pid) || pid <= 0)
882
- return null;
883
- return {
884
- port,
885
- pid,
886
- started_at: Number.isFinite(startedAt) ? startedAt : 0,
887
- kind: typeof parsed.kind === "string" ? parsed.kind : undefined,
888
- harness: typeof parsed.harness === "string" ? parsed.harness : undefined,
889
- token: typeof parsed.token === "string" ? parsed.token : undefined,
890
- instance_id: typeof parsed.instance_id === "string" ? parsed.instance_id : undefined
891
- };
892
- } catch {
893
- return null;
894
- }
895
- }
896
- const port = Number.parseInt(trimmed, 10);
897
- if (!isValidPort(port))
898
- return null;
899
- return { port, pid: fallbackPid, started_at: 0 };
900
- }
901
- function isValidPort(port) {
902
- return Number.isInteger(port) && port > 0 && port <= 65535;
903
- }
904
- function snapshotEvidence(fact) {
905
- return {
906
- startTime: fact?.startTime ?? null,
907
- commandLine: fact?.commandLine ?? fact?.imageName ?? null,
908
- ...fact?.imageName ? { imageName: fact.imageName } : {}
909
- };
910
- }
911
- function execProcessListAsync(file, args, timeout) {
912
- return new Promise((resolve, reject) => {
913
- execFile(file, args, { encoding: "utf8", timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
914
- if (error)
915
- reject(error);
916
- else
917
- resolve(stdout);
918
- });
919
- });
920
- }
921
- var asyncProcessExec = execProcessListAsync;
922
- var asyncInspection;
923
- var asyncInspectionExpires = 0;
924
- var lastAsyncSnapshot = null;
925
- function inspectProcessesAsync(forceFresh = false) {
926
- if (!forceFresh && asyncInspection && rpcIdentityNowMs() < asyncInspectionExpires)
927
- return asyncInspection;
928
- asyncInspectionExpires = Number.POSITIVE_INFINITY;
929
- asyncInspection = (async () => {
930
- let snapshot = null;
931
- try {
932
- if (rpcIdentityPlatform === "win32") {
933
- try {
934
- const output = await asyncProcessExec("powershell", ["-NoProfile", "-Command", WINDOWS_CIM_COMMAND], WINDOWS_CIM_PROBE_TIMEOUT_MS);
935
- const facts = parseWindowsCimOutput(output);
936
- if (facts)
937
- snapshot = snapshotFromFacts(facts, "cim");
938
- } catch {}
939
- if (!snapshot) {
940
- const entries = parseTasklistOutput(await asyncProcessExec("tasklist", ["/FO", "CSV", "/NH"], PS_PROBE_TIMEOUT_MS));
941
- if (entries)
942
- snapshot = snapshotFromFacts(entries.map(({ pid, command }) => ({
943
- pid,
944
- parentPid: null,
945
- commandLine: null,
946
- imageName: command,
947
- startTime: null
948
- })), "tasklist");
949
- }
950
- } else {
951
- const output = await asyncProcessExec("ps", ["-axo", "pid=,ppid=,lstart=,command="], PS_PROBE_TIMEOUT_MS);
952
- const facts = [];
953
- for (const line of output.split(/\r?\n/)) {
954
- const match = /^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.+)$/.exec(line);
955
- if (!match)
956
- continue;
957
- const startTime = Date.parse(match[3]);
958
- facts.push({
959
- pid: Number(match[1]),
960
- parentPid: Number(match[2]),
961
- commandLine: match[4],
962
- imageName: null,
963
- startTime: Number.isFinite(startTime) ? startTime : null
964
- });
965
- }
966
- snapshot = facts.length > 0 ? snapshotFromFacts(facts, "ps") : null;
967
- }
968
- } catch {}
969
- const fresh = snapshot !== null;
970
- if (snapshot)
971
- lastAsyncSnapshot = snapshot;
972
- else
973
- snapshot = lastAsyncSnapshot;
974
- const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
975
- return {
976
- pi: snapshot ? classifyLivePiSnapshot(snapshot, false) : { state: "unreadable", processIds: [] },
977
- ...fresh && snapshot ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } } : {},
978
- evidence: (pid) => snapshotEvidence(byPid.get(pid)),
979
- liveness: (pid) => byPid.has(pid) ? "alive" : fresh ? "dead" : "inconclusive"
980
- };
981
- })().finally(() => {
982
- asyncInspectionExpires = rpcIdentityNowMs() + WINDOWS_PROCESS_SNAPSHOT_TTL_MS;
983
- });
984
- return asyncInspection;
985
- }
986
- function inspectWindowsProcessesSync() {
987
- const snapshot = tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
988
- const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
989
- return {
990
- pi: snapshot ? classifyLivePiSnapshot(snapshot) : { state: "unreadable", processIds: [] },
991
- ...snapshot ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } } : {},
992
- evidence: (pid) => snapshotEvidence(byPid.get(pid)),
993
- liveness: (pid) => byPid.has(pid) ? "alive" : snapshot ? "dead" : "inconclusive"
994
- };
995
- }
996
-
997
301
  // ../plugin/src/features/magic-context/context-store-uuid.ts
998
302
  import { randomUUID } from "node:crypto";
999
303
  function getContextStoreUuid(db) {
@@ -1017,7 +321,7 @@ function ensureContextStoreUuid(db) {
1017
321
  import {
1018
322
  existsSync as existsSync2,
1019
323
  readdirSync,
1020
- readFileSync as readFileSync2,
324
+ readFileSync,
1021
325
  rmdirSync,
1022
326
  statSync,
1023
327
  unlinkSync
@@ -1670,7 +974,7 @@ function unreadableDiscovery(path, arm) {
1670
974
  var RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
1671
975
  var defaultRpcDiscoveryFs = {
1672
976
  readdirSync: (path, options) => options?.withFileTypes ? readdirSync(path, { withFileTypes: true }) : readdirSync(path),
1673
- readFileSync: (path, encoding) => String(readFileSync2(path, encoding)),
977
+ readFileSync: (path, encoding) => String(readFileSync(path, encoding)),
1674
978
  statSync: (path) => ({ mtimeMs: statSync(path).mtimeMs }),
1675
979
  unlinkSync: (path) => unlinkSync(path),
1676
980
  rmdirSync: (path) => rmdirSync(path)
@@ -1983,7 +1287,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1983
1287
  startMessageFtsRowidMapBackfill(db).then(async () => {
1984
1288
  if (!readsOpenCodeStore)
1985
1289
  return;
1986
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-24sd89tf.js"));
1290
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-rvmc25n5.js"));
1987
1291
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-05ppypkz.js"));
1988
1292
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
1989
1293
  readPage: readRawSessionMessagePage
@@ -3477,4 +2781,4 @@ function closeDatabase() {
3477
2781
  }
3478
2782
  }
3479
2783
 
3480
- export { FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, piHarnessKindFromExecutable, isPidAlive, getErrorMessage, describeError, startBootDeadline, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, closeDatabase };
2784
+ export { FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, getErrorMessage, describeError, startBootDeadline, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, closeDatabase };