@cortexkit/pi-magic-context 0.49.25 → 0.49.27

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