@cortexkit/pi-magic-context 0.49.83 → 0.49.85

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 (32) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +5 -4
  3. package/dist/{embedding-backfill-yh10bmx5.js → embedding-backfill-7a01ns95.js} +6 -5
  4. package/dist/embedding-worker.js +14 -27
  5. package/dist/{index-e0zdn1p3.js → index-53fgdt6n.js} +1 -1
  6. package/dist/{index-47g3pgzk.js → index-7v0z62ek.js} +6 -6
  7. package/dist/{index-xz5b9t4g.js → index-7yz95h83.js} +38 -736
  8. package/dist/index-8x8wtn3t.js +1083 -0
  9. package/dist/{index-hna2sxy8.js → index-94z1xzmr.js} +3 -3
  10. package/dist/{index-qz43gkqe.js → index-bjr11ay6.js} +24 -26
  11. package/dist/{index-qky62xze.js → index-ddfjg278.js} +23 -0
  12. package/dist/{index-gdy08gn6.js → index-ex9te7tc.js} +1 -1
  13. package/dist/{index-wtqv3vha.js → index-fd57gfnn.js} +4 -4
  14. package/dist/{index-nmmge3j6.js → index-gbc29ysq.js} +1 -1
  15. package/dist/{index-txcs0vnj.js → index-rqdjb6j3.js} +461 -273
  16. package/dist/{index-k8xz22jc.js → index-sqp84q6s.js} +1 -1
  17. package/dist/{index-y573dt51.js → index-ty0tvxhm.js} +43 -20
  18. package/dist/{index-3g1wy4z9.js → index-wy6h2wn2.js} +22 -10
  19. package/dist/index.js +61 -57
  20. package/dist/migration-worker.js +5 -4
  21. package/dist/{project-embedding-registry-3sss39rx.js → project-embedding-registry-agkd7egh.js} +7 -4
  22. package/dist/raw-ordinal-warmup-worker.js +2 -2
  23. package/dist/{render-9xgp0jka.js → render-rphfegr8.js} +7 -6
  24. package/dist/{search-archive-wr38qtkw.js → search-archive-7p43e77j.js} +1 -1
  25. package/dist/{search-dh4ryftv.js → search-pwafh0v5.js} +9 -8
  26. package/dist/{store-xg9ez6jn.js → store-ekaexkvc.js} +5 -2
  27. package/dist/{store-reader-8j41p18c.js → store-reader-vwphd51b.js} +1 -1
  28. package/dist/subagent-entry.js +17 -17
  29. package/dist/tag-snapshot-worker-pi.js +5 -4
  30. package/dist/{v2-archive-reader-8m9mw6sv.js → v2-archive-reader-qc4c9wrp.js} +1 -1
  31. package/package.json +1 -1
  32. package/dist/index-81nthk8j.js +0 -193
@@ -1,14 +1,3 @@
1
- import {
2
- getHarness2,
3
- harnessOwnsOpenCodeStore2
4
- } from "./index-0h2mkab2.js";
5
- import {
6
- getMagicContextStorageDir,
7
- getLegacyOpenCodeMagicContextStorageDir,
8
- importPluginModule,
9
- writeForwardedLogLine2,
10
- log2
11
- } from "./index-tm11k42a.js";
12
1
  import {
13
2
  inRootAsyncContext2,
14
3
  registerSlowWriteReporter2,
@@ -24,7 +13,35 @@ import {
24
13
  } from "./index-2qtx0q6h.js";
25
14
  import {
26
15
  scheduleAfterBootQuiet
27
- } from "./index-hna2sxy8.js";
16
+ } from "./index-94z1xzmr.js";
17
+ import {
18
+ getHarness2,
19
+ harnessOwnsOpenCodeStore2
20
+ } from "./index-0h2mkab2.js";
21
+ import {
22
+ getMagicContextStorageDir,
23
+ getLegacyOpenCodeMagicContextStorageDir,
24
+ importPluginModule,
25
+ writeForwardedLogLine2,
26
+ log2
27
+ } from "./index-tm11k42a.js";
28
+ import {
29
+ isOwnRpcServerRecord,
30
+ isPidAlive,
31
+ readProcessProbeEvidence,
32
+ classifyProcessKind,
33
+ isPidIdentityPlausible,
34
+ inspectLivePiProcesses,
35
+ parseRpcPortFile,
36
+ inspectProcessesAsync,
37
+ inspectWindowsProcessesSync,
38
+ shouldEnforcePrivateStoragePermissions,
39
+ ensureStorageDirectorySync,
40
+ writeStorageFileSync,
41
+ copyStorageFileSync,
42
+ copyStorageTreeSync,
43
+ tightenStorageTreeSync
44
+ } from "./index-8x8wtn3t.js";
28
45
  import {
29
46
  configureContextDatabasePragmas2
30
47
  } from "./index-fapenpch.js";
@@ -46,7 +63,7 @@ import {
46
63
  hasPendingMigrations,
47
64
  getMainThreadMigrationBodyCount,
48
65
  runMigrations
49
- } from "./index-e0zdn1p3.js";
66
+ } from "./index-53fgdt6n.js";
50
67
  import {
51
68
  setDatabase,
52
69
  loadToolDefinitionMeasurements,
@@ -64,721 +81,6 @@ import {
64
81
  import {
65
82
  logSlowWriteTransaction
66
83
  } from "./index-1ts77n1b.js";
67
- import {
68
- shouldEnforcePrivateStoragePermissions,
69
- ensureStorageDirectorySync,
70
- writeStorageFileSync,
71
- copyStorageFileSync,
72
- copyStorageTreeSync,
73
- tightenStorageTreeSync
74
- } from "./index-81nthk8j.js";
75
-
76
- // ../plugin/src/shared/rpc-utils.ts
77
- import { execFile, execFileSync } from "node:child_process";
78
- import { readFileSync } from "node:fs";
79
-
80
- // ../plugin/src/shared/pi-executable.ts
81
- var PI_IMAGE_NAMES = new Set(["pi", "pi.cmd", "omp", "oh-my-pi"]);
82
- function piHarnessKindFromExecutable(value) {
83
- const executable = (value ?? "").trim().replace(/^['"]|['"]$/g, "").replaceAll("\\", "/").split("/").at(-1)?.toLowerCase().replace(/\.(?:exe|cmd)$/, "");
84
- if (!executable || !PI_IMAGE_NAMES.has(executable))
85
- return;
86
- return executable === "pi" ? "pi" : "omp";
87
- }
88
-
89
- // ../plugin/src/shared/rpc-utils.ts
90
- var ownRpcServerInstanceIds = new Set;
91
- function isOwnRpcServerRecord(record) {
92
- return record.pid === process.pid && record.instance_id !== undefined && ownRpcServerInstanceIds.has(record.instance_id);
93
- }
94
- function isPidAlive(pid) {
95
- if (!Number.isInteger(pid) || pid <= 0)
96
- return "dead";
97
- if (rpcIdentityPlatform === "win32")
98
- return readWindowsProcess(pid).state;
99
- try {
100
- rpcIdentityProcessKill(pid, 0);
101
- return "alive";
102
- } catch (error) {
103
- return error.code === "ESRCH" ? "dead" : "inconclusive";
104
- }
105
- }
106
- var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
107
- var LINUX_CLOCK_TICKS_PER_SECOND = 100;
108
- var PS_PROBE_TIMEOUT_MS = 1000;
109
- var WINDOWS_CIM_PROBE_TIMEOUT_MS = 5000;
110
- var WINDOWS_PROCESS_SNAPSHOT_TTL_MS = 2000;
111
- var MAX_ANCESTOR_WALK_DEPTH = 16;
112
- var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
113
- 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";
114
- var PROCESS_LIST_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
115
- var PI_HARNESS_ARC_MARKERS = [
116
- "pi-coding-agent",
117
- "oh-my-pi",
118
- "@oh-my-pi",
119
- "cljs/dist",
120
- "dist/bundle/cli"
121
- ];
122
- var rpcIdentityReadFileSync = readFileSync;
123
- var rpcIdentityExecFileSync = execFileSync;
124
- var rpcIdentityProcessKill = process.kill;
125
- var rpcProcessListExecFileSync = execFileSync;
126
- var rpcIdentityPlatform = process.platform;
127
- var rpcIdentityNowMs = () => Date.now();
128
- function parseLinuxProcessStartTime(statContent, uptimeContent) {
129
- const closingCommandName = statContent.lastIndexOf(")");
130
- if (closingCommandName < 0)
131
- return null;
132
- const statFields = statContent.slice(closingCommandName + 1).trim().split(/\s+/);
133
- const startTimeTicks = Number(statFields[19]);
134
- const uptimeSeconds = Number(uptimeContent.trim().split(/\s+/)[0]);
135
- if (!Number.isFinite(startTimeTicks) || startTimeTicks < 0 || !Number.isFinite(uptimeSeconds) || uptimeSeconds < 0) {
136
- return null;
137
- }
138
- const processStartTime = rpcIdentityNowMs() - uptimeSeconds * 1000 + startTimeTicks / LINUX_CLOCK_TICKS_PER_SECOND * 1000;
139
- return Number.isFinite(processStartTime) ? processStartTime : null;
140
- }
141
- function readLinuxProcessStartTime(pid) {
142
- try {
143
- const statContent = String(rpcIdentityReadFileSync(`/proc/${pid}/stat`, "utf8"));
144
- const uptimeContent = String(rpcIdentityReadFileSync("/proc/uptime", "utf8"));
145
- return parseLinuxProcessStartTime(statContent, uptimeContent);
146
- } catch {
147
- return null;
148
- }
149
- }
150
- function readPsProcessStartTime(pid) {
151
- try {
152
- const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
153
- encoding: "utf8",
154
- timeout: PS_PROBE_TIMEOUT_MS,
155
- stdio: ["ignore", "pipe", "pipe"],
156
- windowsHide: true
157
- });
158
- const processStartTime = Date.parse(String(output).trim());
159
- return Number.isFinite(processStartTime) ? processStartTime : null;
160
- } catch {
161
- return null;
162
- }
163
- }
164
- function readProcessStartTime(pid) {
165
- if (!Number.isInteger(pid) || pid <= 0)
166
- return null;
167
- return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? readWindowsProcessStartTime(pid) : readPsProcessStartTime(pid);
168
- }
169
- function readProcessProbeEvidence(pid) {
170
- return {
171
- startTime: readProcessStartTime(pid),
172
- commandLine: readProcessCommand(pid)
173
- };
174
- }
175
- function readCachedWindowsImageName(pid) {
176
- return rpcIdentityPlatform === "win32" ? windowsProcessFactsCache?.get(pid)?.imageName ?? null : null;
177
- }
178
- var windowsProcessFactsCache = null;
179
- var windowsProcessSnapshotCache = null;
180
- function rememberWindowsProcessFacts(facts) {
181
- windowsProcessFactsCache = new Map(facts.map((fact) => [fact.pid, fact]));
182
- }
183
- function parseCsvLine(line) {
184
- const fields = [];
185
- let field = "";
186
- let quoted = false;
187
- for (let index = 0;index < line.length; index += 1) {
188
- const character = line[index];
189
- if (character === '"') {
190
- if (quoted && line[index + 1] === '"') {
191
- field += '"';
192
- index += 1;
193
- } else {
194
- quoted = !quoted;
195
- }
196
- } else if (character === "," && !quoted) {
197
- fields.push(field);
198
- field = "";
199
- } else {
200
- field += character;
201
- }
202
- }
203
- if (quoted)
204
- return null;
205
- fields.push(field);
206
- return fields;
207
- }
208
- function parseTasklistOutput(output) {
209
- const entries = [];
210
- for (const rawLine of output.split(/\r?\n/)) {
211
- const line = rawLine.trim();
212
- if (!line)
213
- continue;
214
- const fields = parseCsvLine(line);
215
- if (!fields)
216
- continue;
217
- if (fields[1]?.trim().toLowerCase() === "pid") {
218
- continue;
219
- }
220
- const pid = Number(fields[1]);
221
- if (!Number.isInteger(pid) || pid <= 0 || !fields[0])
222
- continue;
223
- entries.push({ pid, command: fields[0] });
224
- }
225
- return entries;
226
- }
227
- function readWindowsProcess(pid) {
228
- try {
229
- const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], {
230
- encoding: "utf8",
231
- timeout: PS_PROBE_TIMEOUT_MS,
232
- stdio: ["ignore", "pipe", "pipe"],
233
- windowsHide: true
234
- });
235
- const entries = parseTasklistOutput(String(output));
236
- if (entries === null)
237
- return { state: "inconclusive" };
238
- const process2 = entries.find((entry) => entry.pid === pid);
239
- return process2 ? { state: "alive", command: process2.command } : { state: "dead" };
240
- } catch {
241
- return { state: "inconclusive" };
242
- }
243
- }
244
- function readWindowsProcessStartTime(pid) {
245
- const cached = windowsProcessFactsCache?.get(pid);
246
- if (cached)
247
- return cached.startTime;
248
- const snapshot = tryReadWindowsCimSnapshot(rpcIdentityExecFileSync);
249
- if (!snapshot)
250
- return null;
251
- rememberWindowsProcessFacts(snapshot.facts);
252
- return windowsProcessFactsCache?.get(pid)?.startTime ?? null;
253
- }
254
- function readLinuxProcessCommand(pid) {
255
- try {
256
- return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
257
- } catch {
258
- return null;
259
- }
260
- }
261
- function readPsProcessCommand(pid) {
262
- try {
263
- const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "command="], {
264
- encoding: "utf8",
265
- timeout: PS_PROBE_TIMEOUT_MS,
266
- stdio: ["ignore", "pipe", "pipe"],
267
- windowsHide: true
268
- });
269
- return String(output);
270
- } catch {
271
- return null;
272
- }
273
- }
274
- function readProcessCommand(pid) {
275
- if (!Number.isInteger(pid) || pid <= 0)
276
- return null;
277
- if (rpcIdentityPlatform === "linux")
278
- return readLinuxProcessCommand(pid);
279
- if (rpcIdentityPlatform === "win32") {
280
- const cached = windowsProcessFactsCache?.get(pid);
281
- if (cached?.commandLine)
282
- return cached.commandLine;
283
- return readWindowsProcess(pid).command ?? null;
284
- }
285
- return readPsProcessCommand(pid);
286
- }
287
- function executableName(token) {
288
- return (token ?? "").replace(/^['"]|['"]$/g, "").split("/").at(-1) ?? "";
289
- }
290
- function commandTokens(command) {
291
- return command.toLowerCase().replaceAll("\\", "/").replaceAll("\x00", " ").split(/\s+/).map((token) => token.replace(/^['"]|['"]$/g, "")).filter(Boolean);
292
- }
293
- function commandHasOpenCodeExecutable(tokens) {
294
- return tokens.findIndex((token) => {
295
- const executable = executableName(token).replace(/\.(?:exe|cmd)$/, "");
296
- return executable === "opencode" || executable.endsWith("/opencode");
297
- });
298
- }
299
- function commandHasPiExecutable(tokens) {
300
- for (let index = 0;index < tokens.length; index += 1) {
301
- const executable = executableName(tokens[index]).replace(/\.(?:exe|cmd)$/, "");
302
- if (piHarnessKindFromExecutable(executable) !== undefined)
303
- return true;
304
- if (["node", "bun", "deno"].includes(executable)) {
305
- const script = executableName(tokens[index + 1]).replace(/\.(?:exe|cmd)$/, "");
306
- if (["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script) || tokens[index + 1]?.includes("pi-coding-agent")) {
307
- return true;
308
- }
309
- }
310
- }
311
- return false;
312
- }
313
- function classifyProcessKind(command) {
314
- if (!command)
315
- return "process";
316
- const tokens = commandTokens(command);
317
- const openCodeIndex = commandHasOpenCodeExecutable(tokens);
318
- if (openCodeIndex >= 0) {
319
- const args = tokens.slice(openCodeIndex + 1);
320
- if (args.some((token) => token === "serve" || token === "--serve" || token.startsWith("--serve="))) {
321
- return "OpenCode server";
322
- }
323
- return "OpenCode instance (TUI/CLI)";
324
- }
325
- return commandHasPiExecutable(tokens) ? "Pi" : "process";
326
- }
327
- function commandLooksLikeOpenCode(command) {
328
- const normalized = command.toLowerCase();
329
- return OPEN_CODE_COMMAND_MARKERS.some((marker) => normalized.includes(marker));
330
- }
331
- var RPC_HOST_PROCESS_MARKERS = [
332
- "opencode",
333
- "openchamber",
334
- "ck-mc",
335
- "magic-context",
336
- "cortexkit",
337
- "electron",
338
- "node",
339
- "bun",
340
- "deno",
341
- "pi-coding-agent",
342
- "oh-my-pi"
343
- ];
344
- function processCannotBeRpcHost(evidence) {
345
- const texts = [evidence.imageName, evidence.commandLine].filter((text) => typeof text === "string" && text.trim().length > 0);
346
- if (texts.length === 0)
347
- return false;
348
- for (const text of texts) {
349
- const normalized = text.toLowerCase();
350
- if (RPC_HOST_PROCESS_MARKERS.some((marker) => normalized.includes(marker)))
351
- return false;
352
- const tokens = commandTokens(text);
353
- if (commandHasPiExecutable(tokens))
354
- return false;
355
- if (tokens.some((token) => piHarnessKindFromExecutable(token) !== undefined))
356
- return false;
357
- }
358
- return true;
359
- }
360
- function isPidIdentityPlausible(record, evidence) {
361
- if (!Number.isInteger(record.pid) || record.pid <= 0)
362
- return "implausible";
363
- if (Number.isFinite(record.started_at) && record.started_at > 0) {
364
- const processStartTime = evidence ? evidence.startTime : readProcessStartTime(record.pid);
365
- if (processStartTime !== null) {
366
- return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS ? "plausible" : "implausible";
367
- }
368
- const identity = evidence ?? {
369
- commandLine: readProcessCommand(record.pid),
370
- imageName: readCachedWindowsImageName(record.pid)
371
- };
372
- return processCannotBeRpcHost(identity) ? "implausible" : "inconclusive";
373
- }
374
- const command = evidence ? evidence.commandLine : rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(record.pid).command ?? null : readPsProcessCommand(record.pid);
375
- if (command === null)
376
- return "inconclusive";
377
- if (commandLooksLikeOpenCode(command))
378
- return "plausible";
379
- return processCannotBeRpcHost({ commandLine: command, imageName: evidence?.imageName }) ? "implausible" : "inconclusive";
380
- }
381
- function commandLooksLikePiImage(command) {
382
- const tokens = commandTokens(command);
383
- const first = executableName(tokens[0]).replace(/\.(?:exe|cmd)$/, "");
384
- return PI_IMAGE_NAMES.has(first);
385
- }
386
- function commandHasPiHarnessArc(command) {
387
- const normalized = command.trim().toLowerCase().replaceAll("\\", "/").replaceAll("\x00", " ");
388
- if (!normalized)
389
- return false;
390
- const tokens = commandTokens(command);
391
- if (tokens.length === 0)
392
- return false;
393
- const hasArc = PI_HARNESS_ARC_MARKERS.some((marker) => normalized.includes(marker));
394
- const first = executableName(tokens[0]).replace(/\.(?:exe|cmd)$/, "");
395
- if (hasArc && ["pi", "omp", "oh-my-pi", "node", "bun", "deno", "cmd"].includes(first)) {
396
- return true;
397
- }
398
- if (hasArc && PI_HARNESS_ARC_MARKERS.some((marker) => tokens[0].includes(marker))) {
399
- return true;
400
- }
401
- if (["node", "bun", "deno"].includes(first)) {
402
- const script = executableName(tokens[1]).replace(/\.(?:exe|cmd)$/, "");
403
- if (["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script))
404
- return true;
405
- if (hasArc)
406
- return true;
407
- }
408
- return false;
409
- }
410
- function execProcessList(exec, file, args, timeout = PS_PROBE_TIMEOUT_MS) {
411
- return String(exec(file, [...args], {
412
- encoding: "utf8",
413
- timeout,
414
- maxBuffer: PROCESS_LIST_MAX_BUFFER_BYTES,
415
- stdio: ["ignore", "pipe", "pipe"],
416
- windowsHide: true
417
- }));
418
- }
419
- function parseWindowsCreationDate(value) {
420
- if (value !== null && typeof value === "object" && "value" in value) {
421
- return parseWindowsCreationDate(value.value);
422
- }
423
- if (typeof value === "number" && Number.isFinite(value)) {
424
- return value > 1000000000000 ? value : value * 1000;
425
- }
426
- if (typeof value !== "string")
427
- return null;
428
- const trimmed = value.trim();
429
- if (!trimmed)
430
- return null;
431
- const wmi = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/.exec(trimmed);
432
- if (wmi) {
433
- 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);
434
- if (!Number.isFinite(utcMs))
435
- return null;
436
- const offsetMinutes = Number(wmi[9]);
437
- const sign = wmi[8] === "+" ? 1 : -1;
438
- return utcMs - sign * offsetMinutes * 60000;
439
- }
440
- const dotNet = /^\/Date\((-?\d+)\)\/$/.exec(trimmed);
441
- if (dotNet) {
442
- const milliseconds = Number(dotNet[1]);
443
- return Number.isFinite(milliseconds) ? milliseconds : null;
444
- }
445
- const parsed = Date.parse(trimmed);
446
- return Number.isFinite(parsed) ? parsed : null;
447
- }
448
- function parseWindowsCimOutput(output) {
449
- const trimmed = output.trim();
450
- if (!trimmed)
451
- return null;
452
- const bracket = trimmed.indexOf("[");
453
- const brace = trimmed.indexOf("{");
454
- const start = Math.min(bracket === -1 ? Number.POSITIVE_INFINITY : bracket, brace === -1 ? Number.POSITIVE_INFINITY : brace);
455
- if (!Number.isFinite(start))
456
- return null;
457
- let parsed;
458
- try {
459
- parsed = JSON.parse(trimmed.slice(start));
460
- } catch {
461
- return null;
462
- }
463
- if (parsed == null)
464
- return null;
465
- const rows = Array.isArray(parsed) ? parsed : [parsed];
466
- const facts = [];
467
- for (const row of rows) {
468
- if (!row || typeof row !== "object")
469
- continue;
470
- const record = row;
471
- const pid = Number(record.ProcessId);
472
- if (!Number.isInteger(pid) || pid <= 0)
473
- continue;
474
- const parentRaw = record.ParentProcessId;
475
- const parentPid = parentRaw == null || parentRaw === "" ? Number.NaN : Number(parentRaw);
476
- const commandLine = typeof record.CommandLine === "string" ? record.CommandLine : null;
477
- facts.push({
478
- pid,
479
- parentPid: Number.isInteger(parentPid) && parentPid > 0 ? parentPid : null,
480
- commandLine,
481
- imageName: typeof record.Name === "string" ? record.Name : commandLine ? executableName(commandTokens(commandLine)[0]) : null,
482
- startTime: parseWindowsCreationDate(record.CreationDate)
483
- });
484
- }
485
- return facts.length > 0 ? facts : null;
486
- }
487
- function snapshotFromFacts(facts, source) {
488
- const parentByPid = new Map;
489
- for (const fact of facts) {
490
- if (fact.parentPid != null)
491
- parentByPid.set(fact.pid, fact.parentPid);
492
- }
493
- return { facts, parentByPid, source };
494
- }
495
- function tryReadWindowsCimSnapshot(exec) {
496
- try {
497
- const output = execProcessList(exec, "powershell", ["-NoProfile", "-Command", WINDOWS_CIM_COMMAND], WINDOWS_CIM_PROBE_TIMEOUT_MS);
498
- const facts = parseWindowsCimOutput(output);
499
- return facts ? snapshotFromFacts(facts, "cim") : null;
500
- } catch {
501
- return null;
502
- }
503
- }
504
- function tryReadWindowsTasklistSnapshot() {
505
- try {
506
- const output = execProcessList(rpcProcessListExecFileSync, "tasklist", [
507
- "/FO",
508
- "CSV",
509
- "/NH"
510
- ]);
511
- const entries = parseTasklistOutput(output);
512
- if (entries === null)
513
- return null;
514
- const facts = entries.map((entry) => ({
515
- pid: entry.pid,
516
- parentPid: null,
517
- commandLine: null,
518
- imageName: entry.command,
519
- startTime: null
520
- }));
521
- return snapshotFromFacts(facts, "tasklist");
522
- } catch {
523
- return null;
524
- }
525
- }
526
- function readPosixProcessSnapshot() {
527
- const output = execProcessList(rpcProcessListExecFileSync, "ps", ["-axo", "pid=,command="]);
528
- const facts = [];
529
- for (const line of output.split(/\r?\n/)) {
530
- const match = /^\s*(\d+)\s+(.+)$/.exec(line);
531
- if (!match)
532
- continue;
533
- const pid = Number(match[1]);
534
- if (!Number.isInteger(pid) || pid <= 0)
535
- continue;
536
- facts.push({
537
- pid,
538
- parentPid: null,
539
- commandLine: match[2],
540
- imageName: executableName(commandTokens(match[2])[0]),
541
- startTime: null
542
- });
543
- }
544
- return snapshotFromFacts(facts, "ps");
545
- }
546
- function readPosixParentPid(pid) {
547
- try {
548
- const output = execProcessList(rpcProcessListExecFileSync, "ps", [
549
- "-o",
550
- "ppid=",
551
- "-p",
552
- String(pid)
553
- ]);
554
- const match = /^\s*(\d+)\s*$/.exec(output);
555
- if (!match)
556
- return null;
557
- const ppid = Number(match[1]);
558
- return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
559
- } catch {
560
- return null;
561
- }
562
- }
563
- function collectAncestorPids(selfPid, parentByPid, probeParents = true) {
564
- const ancestors = new Set;
565
- let current = selfPid;
566
- for (let depth = 0;depth < MAX_ANCESTOR_WALK_DEPTH; depth += 1) {
567
- let ppid = null;
568
- if (parentByPid.has(current)) {
569
- ppid = parentByPid.get(current) ?? null;
570
- } else if (rpcIdentityPlatform !== "win32" && probeParents) {
571
- ppid = readPosixParentPid(current);
572
- if (ppid == null && current === process.pid && process.ppid > 0) {
573
- ppid = process.ppid;
574
- }
575
- } else if (current === process.pid && process.ppid > 0) {
576
- ppid = process.ppid;
577
- } else {
578
- break;
579
- }
580
- if (ppid == null || ppid <= 0 || ppid === current || ancestors.has(ppid))
581
- break;
582
- ancestors.add(ppid);
583
- current = ppid;
584
- }
585
- return ancestors;
586
- }
587
- function classifyLivePiSnapshot(snapshot, probeParents = true) {
588
- const ancestors = collectAncestorPids(process.pid, snapshot.parentByPid, probeParents);
589
- const processIds = new Set;
590
- const inconclusivePids = new Set;
591
- const skippedAncestorPids = [];
592
- for (const fact of snapshot.facts) {
593
- if (fact.pid === process.pid)
594
- continue;
595
- const command = fact.commandLine ?? fact.imageName ?? "";
596
- const looksLikeHarness = commandHasPiHarnessArc(command) || commandLooksLikePiImage(command);
597
- if (!looksLikeHarness)
598
- continue;
599
- if (ancestors.has(fact.pid)) {
600
- skippedAncestorPids.push(fact.pid);
601
- log2(`[magic-context] Pi process scan: skipping ancestor PID ${fact.pid} (session launcher shim)`);
602
- continue;
603
- }
604
- if (commandHasPiHarnessArc(command)) {
605
- processIds.add(fact.pid);
606
- continue;
607
- }
608
- inconclusivePids.add(fact.pid);
609
- log2(`[magic-context] Pi process scan: PID ${fact.pid} command line is ambiguous (image-name or missing Pi/OMP arc); treating as inconclusive`);
610
- }
611
- skippedAncestorPids.sort((left, right) => left - right);
612
- const verified = [...processIds].sort((left, right) => left - right);
613
- const inconclusive = [...inconclusivePids].sort((left, right) => left - right);
614
- if (verified.length === 0 && inconclusive.length > 0) {
615
- return {
616
- state: "inconclusive",
617
- processIds: [],
618
- inconclusivePids: inconclusive,
619
- ...skippedAncestorPids.length > 0 ? { skippedAncestorPids } : {}
620
- };
621
- }
622
- return {
623
- state: "known",
624
- processIds: verified,
625
- ...inconclusive.length > 0 ? { inconclusivePids: inconclusive } : {},
626
- ...skippedAncestorPids.length > 0 ? { skippedAncestorPids } : {}
627
- };
628
- }
629
- function inspectLivePiProcesses() {
630
- if (false) {}
631
- try {
632
- if (rpcIdentityPlatform === "win32") {
633
- const now = rpcIdentityNowMs();
634
- const cached = windowsProcessSnapshotCache;
635
- const snapshot = cached && now >= cached.at && now - cached.at < WINDOWS_PROCESS_SNAPSHOT_TTL_MS ? cached.snapshot : tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
636
- if (!snapshot) {
637
- return {
638
- state: "unreadable",
639
- processIds: [],
640
- error: "process list unavailable"
641
- };
642
- }
643
- if (snapshot !== cached?.snapshot)
644
- windowsProcessSnapshotCache = { snapshot, at: now };
645
- rememberWindowsProcessFacts(snapshot.facts);
646
- return classifyLivePiSnapshot(snapshot);
647
- }
648
- return classifyLivePiSnapshot(readPosixProcessSnapshot());
649
- } catch (error) {
650
- return {
651
- state: "unreadable",
652
- processIds: [],
653
- error: error instanceof Error ? error.message : String(error)
654
- };
655
- }
656
- }
657
- function parseRpcPortFile(content, fallbackPid = 0) {
658
- const trimmed = content.trim();
659
- if (!trimmed)
660
- return null;
661
- if (trimmed.startsWith("{")) {
662
- try {
663
- const parsed = JSON.parse(trimmed);
664
- const port = Number(parsed.port);
665
- const pid = Number(parsed.pid);
666
- const startedAt = Number(parsed.started_at);
667
- if (!isValidPort(port) || !Number.isInteger(pid) || pid <= 0)
668
- return null;
669
- return {
670
- port,
671
- pid,
672
- started_at: Number.isFinite(startedAt) ? startedAt : 0,
673
- kind: typeof parsed.kind === "string" ? parsed.kind : undefined,
674
- harness: typeof parsed.harness === "string" ? parsed.harness : undefined,
675
- token: typeof parsed.token === "string" ? parsed.token : undefined,
676
- instance_id: typeof parsed.instance_id === "string" ? parsed.instance_id : undefined
677
- };
678
- } catch {
679
- return null;
680
- }
681
- }
682
- const port = Number.parseInt(trimmed, 10);
683
- if (!isValidPort(port))
684
- return null;
685
- return { port, pid: fallbackPid, started_at: 0 };
686
- }
687
- function isValidPort(port) {
688
- return Number.isInteger(port) && port > 0 && port <= 65535;
689
- }
690
- function snapshotEvidence(fact) {
691
- return {
692
- startTime: fact?.startTime ?? null,
693
- commandLine: fact?.commandLine ?? fact?.imageName ?? null,
694
- ...fact?.imageName ? { imageName: fact.imageName } : {}
695
- };
696
- }
697
- function execProcessListAsync(file, args, timeout) {
698
- return new Promise((resolve, reject) => {
699
- execFile(file, args, { encoding: "utf8", timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
700
- if (error)
701
- reject(error);
702
- else
703
- resolve(stdout);
704
- });
705
- });
706
- }
707
- var asyncProcessExec = execProcessListAsync;
708
- var asyncInspection;
709
- var asyncInspectionExpires = 0;
710
- var lastAsyncSnapshot = null;
711
- function inspectProcessesAsync(forceFresh = false) {
712
- if (!forceFresh && asyncInspection && rpcIdentityNowMs() < asyncInspectionExpires)
713
- return asyncInspection;
714
- asyncInspectionExpires = Number.POSITIVE_INFINITY;
715
- asyncInspection = (async () => {
716
- let snapshot = null;
717
- try {
718
- if (rpcIdentityPlatform === "win32") {
719
- try {
720
- const output = await asyncProcessExec("powershell", ["-NoProfile", "-Command", WINDOWS_CIM_COMMAND], WINDOWS_CIM_PROBE_TIMEOUT_MS);
721
- const facts = parseWindowsCimOutput(output);
722
- if (facts)
723
- snapshot = snapshotFromFacts(facts, "cim");
724
- } catch {}
725
- if (!snapshot) {
726
- const entries = parseTasklistOutput(await asyncProcessExec("tasklist", ["/FO", "CSV", "/NH"], PS_PROBE_TIMEOUT_MS));
727
- if (entries)
728
- snapshot = snapshotFromFacts(entries.map(({ pid, command }) => ({
729
- pid,
730
- parentPid: null,
731
- commandLine: null,
732
- imageName: command,
733
- startTime: null
734
- })), "tasklist");
735
- }
736
- } else {
737
- const output = await asyncProcessExec("ps", ["-axo", "pid=,ppid=,lstart=,command="], PS_PROBE_TIMEOUT_MS);
738
- const facts = [];
739
- for (const line of output.split(/\r?\n/)) {
740
- const match = /^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.+)$/.exec(line);
741
- if (!match)
742
- continue;
743
- const startTime = Date.parse(match[3]);
744
- facts.push({
745
- pid: Number(match[1]),
746
- parentPid: Number(match[2]),
747
- commandLine: match[4],
748
- imageName: null,
749
- startTime: Number.isFinite(startTime) ? startTime : null
750
- });
751
- }
752
- snapshot = facts.length > 0 ? snapshotFromFacts(facts, "ps") : null;
753
- }
754
- } catch {}
755
- const fresh = snapshot !== null;
756
- if (snapshot)
757
- lastAsyncSnapshot = snapshot;
758
- else
759
- snapshot = lastAsyncSnapshot;
760
- const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
761
- return {
762
- pi: snapshot ? classifyLivePiSnapshot(snapshot, false) : { state: "unreadable", processIds: [] },
763
- ...fresh && snapshot ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } } : {},
764
- evidence: (pid) => snapshotEvidence(byPid.get(pid)),
765
- liveness: (pid) => byPid.has(pid) ? "alive" : fresh ? "dead" : "inconclusive"
766
- };
767
- })().finally(() => {
768
- asyncInspectionExpires = rpcIdentityNowMs() + WINDOWS_PROCESS_SNAPSHOT_TTL_MS;
769
- });
770
- return asyncInspection;
771
- }
772
- function inspectWindowsProcessesSync() {
773
- const snapshot = tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
774
- const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
775
- return {
776
- pi: snapshot ? classifyLivePiSnapshot(snapshot) : { state: "unreadable", processIds: [] },
777
- ...snapshot ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } } : {},
778
- evidence: (pid) => snapshotEvidence(byPid.get(pid)),
779
- liveness: (pid) => byPid.has(pid) ? "alive" : snapshot ? "dead" : "inconclusive"
780
- };
781
- }
782
84
 
783
85
  // ../plugin/src/features/magic-context/context-store-uuid.ts
784
86
  import { randomUUID } from "node:crypto";
@@ -803,7 +105,7 @@ function ensureContextStoreUuid(db) {
803
105
  import {
804
106
  existsSync as existsSync2,
805
107
  readdirSync,
806
- readFileSync as readFileSync2,
108
+ readFileSync,
807
109
  rmdirSync,
808
110
  statSync,
809
111
  unlinkSync
@@ -1352,8 +654,8 @@ var BOOT_SQLITE_BUSY_TIMEOUT_MS = 5000;
1352
654
  function ensureSecureStorageDir(dir) {
1353
655
  ensureStorageDirectorySync(dir);
1354
656
  }
1355
- function tightenStorageTree(dir) {
1356
- const { failures } = tightenStorageTreeSync(dir);
657
+ function tightenStorageTree(dbPath) {
658
+ const { failures } = tightenStorageTreeSync(dirname(dbPath), dbPath);
1357
659
  log2(`[magic-context] storage permission tightening failures=${failures}`);
1358
660
  }
1359
661
  function resolveBootBusyTimeoutMs(value) {
@@ -1468,7 +770,7 @@ function unreadableDiscovery(path, arm) {
1468
770
  var RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
1469
771
  var defaultRpcDiscoveryFs = {
1470
772
  readdirSync: (path, options) => options?.withFileTypes ? readdirSync(path, { withFileTypes: true }) : readdirSync(path),
1471
- readFileSync: (path, encoding) => String(readFileSync2(path, encoding)),
773
+ readFileSync: (path, encoding) => String(readFileSync(path, encoding)),
1472
774
  statSync: (path) => ({ mtimeMs: statSync(path).mtimeMs }),
1473
775
  unlinkSync: (path) => unlinkSync(path),
1474
776
  rmdirSync: (path) => rmdirSync(path)
@@ -1813,7 +1115,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1813
1115
  }
1814
1116
  setDatabase(db);
1815
1117
  loadToolDefinitionMeasurements(db);
1816
- tightenStorageTree(dirname(dbPath));
1118
+ tightenStorageTree(dbPath);
1817
1119
  databases.set(dbPath, db);
1818
1120
  pathByDatabase.set(db, dbPath);
1819
1121
  persistenceByDatabase.set(db, true);
@@ -3113,7 +2415,7 @@ function openDatabase(dbPathOrOptions) {
3113
2415
  migrateLegacyStorageIfNeeded(dbPath, dbDir);
3114
2416
  }
3115
2417
  ensureSecureStorageDir(dbDir);
3116
- tightenStorageTree(dbDir);
2418
+ tightenStorageTree(dbPath);
3117
2419
  if (!existsSync2(dbPath) && shouldEnforcePrivateStoragePermissions()) {
3118
2420
  try {
3119
2421
  writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
@@ -3210,7 +2512,7 @@ async function openDatabaseAsync(dbPathOrOptions) {
3210
2512
  if (!explicitDbPath)
3211
2513
  migrateLegacyStorageIfNeeded(dbPath, dbDir);
3212
2514
  ensureSecureStorageDir(dbDir);
3213
- tightenStorageTree(dbDir);
2515
+ tightenStorageTree(dbPath);
3214
2516
  if (!existsSync2(dbPath) && shouldEnforcePrivateStoragePermissions()) {
3215
2517
  try {
3216
2518
  writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
@@ -3308,4 +2610,4 @@ function closeDatabase() {
3308
2610
  return Promise.all(pendingDatabaseCloses).then(() => {});
3309
2611
  }
3310
2612
 
3311
- export { piHarnessKindFromExecutable, isPidAlive, readProcessStartTime, getErrorMessage, describeError, startBootDeadline, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, enforceSchemaFence, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, closeDatabase };
2613
+ export { getErrorMessage, describeError, startBootDeadline, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, enforceSchemaFence, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, closeDatabase };