@cortexkit/opencode-magic-context 0.44.2 → 0.44.4

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 (116) hide show
  1. package/dist/{conflict-warning-hook-1msyvb51.js → conflict-warning-hook-hmpzxep6.js} +3 -3
  2. package/dist/{derive-budgets-gd2270s0.js → derive-budgets-ncwn1jk9.js} +4 -2
  3. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  4. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  5. package/dist/features/magic-context/dreamer/lease.d.ts +1 -1
  6. package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
  7. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  8. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  9. package/dist/features/magic-context/memory/embedding-openai.d.ts +1 -0
  10. package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
  11. package/dist/features/magic-context/memory/project-identity.d.ts +8 -4
  12. package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
  13. package/dist/features/magic-context/message-index-async.d.ts +1 -1
  14. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  15. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  16. package/dist/features/magic-context/session-project-storage.d.ts +5 -5
  17. package/dist/features/magic-context/session-project-storage.d.ts.map +1 -1
  18. package/dist/features/magic-context/storage-db.d.ts +6 -1
  19. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
  21. package/dist/features/magic-context/v22-deferred-backfill.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/compartment-render-epoch.d.ts +12 -1
  23. package/dist/hooks/magic-context/compartment-render-epoch.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -1
  25. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/compartment-runner-types.d.ts +1 -0
  28. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/derive-budgets.d.ts +4 -0
  30. package/dist/hooks/magic-context/derive-budgets.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/drop-stale-reduce-calls.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/event-resolvers.d.ts +7 -0
  33. package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/inject-compartments.d.ts +5 -0
  37. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/lkg-persist.d.ts +1 -4
  39. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
  41. package/dist/hooks/magic-context/producer-window-guard.d.ts +4 -1
  42. package/dist/hooks/magic-context/producer-window-guard.d.ts.map +1 -1
  43. package/dist/hooks/magic-context/read-session-chunk.d.ts +4 -2
  44. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/read-session-raw.d.ts +2 -2
  46. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  47. package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -0
  48. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/storage-busy-refusal.d.ts +6 -0
  50. package/dist/hooks/magic-context/storage-busy-refusal.d.ts.map +1 -1
  51. package/dist/hooks/magic-context/tokenizer-calibration.d.ts +1 -1
  52. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  53. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +1 -0
  54. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  55. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  56. package/dist/{index-r9vkp4n9.js → index-33q7s9y2.js} +1 -1
  57. package/dist/{index-egkfvhms.js → index-4an2p8qa.js} +80 -14
  58. package/dist/{index-18tjha8g.js → index-638hf49n.js} +1 -1
  59. package/dist/{index-gtzcmv90.js → index-mrc0twf3.js} +12 -6
  60. package/dist/{index-stb5fg12.js → index-msqr3x6m.js} +32 -2
  61. package/dist/{index-y5145x8k.js → index-n96ag4rk.js} +15 -1
  62. package/dist/{index-esxfcz5z.js → index-qm36k34q.js} +56 -13
  63. package/dist/{index-ttdn47aq.js → index-sqp1hz9v.js} +311 -82
  64. package/dist/{index-40s1xz22.js → index-wprsye9w.js} +1 -1
  65. package/dist/{index-3x9caerx.js → index-zx7pmr39.js} +3 -3
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +530 -250
  68. package/dist/plugin/dream-timer.d.ts.map +1 -1
  69. package/dist/plugin/embedding-bootstrap.d.ts.map +1 -1
  70. package/dist/plugin/messages-transform.d.ts.map +1 -1
  71. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  72. package/dist/{read-session-chunk-wmvgnd24.js → read-session-chunk-339hg90t.js} +3 -3
  73. package/dist/{recomp-orchestrator-rk40ff15.js → recomp-orchestrator-0ers6smx.js} +7 -7
  74. package/dist/{send-session-notification-6xsrcxnp.js → send-session-notification-04hvd54c.js} +2 -2
  75. package/dist/shared/rpc-utils.d.ts +7 -0
  76. package/dist/shared/rpc-utils.d.ts.map +1 -1
  77. package/dist/shared/run-token-log.d.ts +13 -0
  78. package/dist/shared/run-token-log.d.ts.map +1 -0
  79. package/dist/shared/sqlite.d.ts +7 -0
  80. package/dist/shared/sqlite.d.ts.map +1 -1
  81. package/dist/shared/transcript.d.ts +2 -0
  82. package/dist/shared/transcript.d.ts.map +1 -1
  83. package/dist/shared/user-answer.d.ts +4 -0
  84. package/dist/shared/user-answer.d.ts.map +1 -0
  85. package/dist/{transform-postprocess-phase-t7xgdhdf.js → transform-postprocess-phase-ttdkrm6r.js} +7 -7
  86. package/dist/v2/hidden-completion.d.ts +7 -1
  87. package/dist/v2/hidden-completion.d.ts.map +1 -1
  88. package/dist/v2/hooks/context.d.ts.map +1 -1
  89. package/dist/v2/hooks/hidden-terminal-error.d.ts +8 -0
  90. package/dist/v2/hooks/hidden-terminal-error.d.ts.map +1 -0
  91. package/dist/v2/hooks/payload.d.ts.map +1 -1
  92. package/dist/v2/hooks/store.d.ts +1 -1
  93. package/dist/v2/hooks/store.d.ts.map +1 -1
  94. package/dist/v2/hooks/tools.d.ts +1 -1
  95. package/dist/v2/hooks/tools.d.ts.map +1 -1
  96. package/dist/v2/server.js +916 -221
  97. package/dist/v2/store-reader.d.ts +2 -1
  98. package/dist/v2/store-reader.d.ts.map +1 -1
  99. package/dist/{wrapup-orchestrator-h8tr10c6.js → wrapup-orchestrator-x0jvvrqn.js} +8 -8
  100. package/package.json +1 -1
  101. package/src/config/latch-permanence-guard.test.ts +4 -0
  102. package/src/shared/data-path.test.ts +1 -1
  103. package/src/shared/models-dev-cache.test.ts +30 -1
  104. package/src/shared/rpc-utils.test.ts +27 -2
  105. package/src/shared/rpc-utils.ts +44 -15
  106. package/src/shared/run-token-log.test.ts +65 -0
  107. package/src/shared/run-token-log.ts +39 -0
  108. package/src/shared/sqlite-acquisition-routing.test.ts +19 -11
  109. package/src/shared/sqlite-pass-scope.test.ts +115 -144
  110. package/src/shared/sqlite.ts +123 -20
  111. package/src/shared/storage-busy.test.ts +34 -57
  112. package/src/shared/tag-transcript.ts +4 -1
  113. package/src/shared/transcript.ts +3 -0
  114. package/src/shared/user-answer.test.ts +40 -0
  115. package/src/shared/user-answer.ts +17 -0
  116. package/src/shared/write-transaction-attribution.test.ts +13 -11
@@ -1,3 +1,4 @@
1
+ import type { RawMessageOrdinalAnchor } from "../hooks/magic-context/read-session-raw";
1
2
  /** Compatibility export; shared/opencode-db-path.ts is the single filename authority. */
2
3
  export declare function sourceDatabaseFilename(channel: string, env?: NodeJS.ProcessEnv): string;
3
4
  /** GA data root resolved by the shared host-generation-aware resolver. */
@@ -103,7 +104,7 @@ export declare class V2StoreReader {
103
104
  * includes non-conversation rows, so the CTE maps the two ordinal boundaries
104
105
  * to seq values without hydrating any row outside the requested page.
105
106
  */
106
- messagePage(sessionID: string, afterOrdinal: number, limit: number, finalWatermark: number): StoreRow[];
107
+ messagePage(sessionID: string, afterOrdinal: number, limit: number, finalWatermark: number, after?: RawMessageOrdinalAnchor): StoreRow[];
107
108
  messageCount(sessionID: string): number;
108
109
  /**
109
110
  * One page of host sessions with the directory each was created in, in
@@ -1 +1 @@
1
- {"version":3,"file":"store-reader.d.ts","sourceRoot":"","sources":["../../src/v2/store-reader.ts"],"names":[],"mappings":"AAOA,yFAAyF;AACzF,wBAAgB,sBAAsB,CAClC,OAAO,EAAE,MAAM,EACf,GAAG,GAAE,MAAM,CAAC,UAAwB,GACrC,MAAM,CAER;AAED,0EAA0E;AAC1E,wBAAgB,cAAc,CAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,SAAW,EAClB,GAAG,GAAE,MAAM,CAAC,UAAwB,GACrC,MAAM,CAER;AAGD,MAAM,MAAM,WAAW,GACjB,gBAAgB,GAChB,gBAAgB,GAChB,mBAAmB,GACnB,MAAM,GACN,WAAW,GACX,QAAQ,GACR,OAAO,GACP,OAAO,GACP,WAAW,GACX,YAAY,GACZ,MAAM,CAAC;AAEb,eAAO,MAAM,iBAAiB,yEAOa,CAAC;AAI5C,eAAO,MAAM,mBAAmB,QAkBP,CAAC;AAC1B,MAAM,WAAW,WAAW;IACxB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,OAAO,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM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.js";
6
6
  import"./index-sd3egckz.js";
7
- import"./index-stb5fg12.js";
8
- import"./index-r9vkp4n9.js";
9
- import"./index-esxfcz5z.js";
10
- import"./index-y5145x8k.js";
11
- import"./index-egkfvhms.js";
7
+ import"./index-msqr3x6m.js";
8
+ import"./index-33q7s9y2.js";
9
+ import"./index-qm36k34q.js";
10
+ import"./index-n96ag4rk.js";
11
+ import"./index-4an2p8qa.js";
12
12
  import"./index-kr5qehbd.js";
13
13
  import"./index-jdxxq8cz.js";
14
14
  import"./index-kwe03yde.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-magic-context",
3
- "version": "0.44.2",
3
+ "version": "0.44.4",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -53,6 +53,10 @@ const KNOWN_SLOTS: Record<string, KnownSlot> = {
53
53
  classification: "VERDICT",
54
54
  reason: "Correct: circuit state expires and a half-open probe re-evaluates the endpoint.",
55
55
  },
56
+ "packages/plugin/src/features/magic-context/memory/project-identity.ts:homeProjectPermission": {
57
+ classification: "VERDICT",
58
+ reason: "Boot config publishes the home-project permission; the setter replaces it on another host initialization, while explicit resolution arguments override it.",
59
+ },
56
60
  "packages/plugin/src/features/magic-context/memory/project-identity.ts:directoryFallbackCache":
57
61
  {
58
62
  classification: "VERDICT",
@@ -29,7 +29,7 @@ const savedEnv = {
29
29
  describe("data-path", () => {
30
30
  beforeEach(() => {
31
31
  process.env.XDG_CACHE_HOME = undefined;
32
- process.env.XDG_DATA_HOME = undefined;
32
+ process.env.XDG_DATA_HOME = process.env.MAGIC_CONTEXT_TEST_DATA_DIR;
33
33
  delete process.env.MAGIC_CONTEXT_TEST_DATA_DIR;
34
34
  delete process.env.NODE_ENV;
35
35
  process.env.LOCALAPPDATA = undefined;
@@ -2,7 +2,14 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
2
  import { mkdtempSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { resolveKnownHistorianContextLimit } from "../hooks/magic-context/derive-budgets";
5
+ import {
6
+ resolveHistorianProducerLimits,
7
+ resolveKnownHistorianContextLimit,
8
+ } from "../hooks/magic-context/derive-budgets";
9
+ import {
10
+ historianProducerReserve,
11
+ producerInputTokenLimit,
12
+ } from "../hooks/magic-context/producer-window-guard";
6
13
  import {
7
14
  clearModelsDevCache,
8
15
  getModelsDevCacheState,
@@ -231,6 +238,28 @@ describe("models-dev-cache (SDK-only)", () => {
231
238
  expect(getSdkContextLimit("openai", "gpt-5.4-mini")).toBe(922000);
232
239
  });
233
240
 
241
+ test("issue 567: production resolver keeps input cap separate from context reserve", async () => {
242
+ await refreshModelLimitsFromApi(
243
+ makeClient([
244
+ {
245
+ id: "auth-provider",
246
+ models: {
247
+ model: { limit: { context: 400_000, input: 272_000, output: 128_000 } },
248
+ },
249
+ },
250
+ ]),
251
+ );
252
+ const resolved = getSdkContextLimit("auth-provider", "model", undefined, {
253
+ reservation: "none",
254
+ });
255
+ const limits = resolveHistorianProducerLimits("auth-provider/model");
256
+ const reserve = historianProducerReserve(limits.context, undefined, 128_000);
257
+ expect(resolved).toBe(272_000);
258
+ expect(limits).toEqual({ context: 400_000, input: 272_000 });
259
+ expect(reserve).toBe(100_000);
260
+ expect(producerInputTokenLimit(limits.context, reserve, limits.input)).toBe(263_840);
261
+ });
262
+
234
263
  test("explicit SDK-resolved config limit wins over a larger catalog or detected value", async () => {
235
264
  // OpenCode's config.providers() has already applied opencode.json over its
236
265
  // catalog. The cache must preserve that 120K effective value, and a later
@@ -12,6 +12,7 @@ import {
12
12
  inspectLivePiProcesses,
13
13
  isPidAlive,
14
14
  isPidIdentityPlausible,
15
+ parseTasklistOutput,
15
16
  type RpcPortFileRecord,
16
17
  readProcessProbeEvidence,
17
18
  } from "./rpc-utils";
@@ -441,7 +442,7 @@ describe("isPidAlive", () => {
441
442
  expect(calls).toEqual([
442
443
  {
443
444
  file: "tasklist",
444
- args: ["/FO", "CSV", "/FI", `PID eq ${PID}`],
445
+ args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${PID}`],
445
446
  stdio: ["ignore", "pipe", "pipe"],
446
447
  },
447
448
  ]);
@@ -623,7 +624,9 @@ describe("isPidIdentityPlausible", () => {
623
624
  });
624
625
 
625
626
  expect(isPidIdentityPlausible(record(0))).toBe("plausible");
626
- expect(calls).toEqual([{ file: "tasklist", args: ["/FO", "CSV", "/FI", `PID eq ${PID}`] }]);
627
+ expect(calls).toEqual([
628
+ { file: "tasklist", args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${PID}`] },
629
+ ]);
627
630
 
628
631
  calls.length = 0;
629
632
  expect(isPidIdentityPlausible(record(NOW_MS))).toBe("inconclusive");
@@ -639,3 +642,25 @@ describe("isPidIdentityPlausible", () => {
639
642
  ]);
640
643
  });
641
644
  });
645
+
646
+ test("Spanish tasklist no-match is not running", () => {
647
+ const output =
648
+ "INFORMACIÓN: no hay tareas ejecutándose que coincidan con los\ncriterios especificados.";
649
+ expect(parseTasklistOutput(output)).toEqual([]);
650
+ __setRpcIdentityTestHooks({ platform: "win32", execFileSync: psOutput(output) });
651
+ expect(isPidAlive(PID)).toBe("dead");
652
+ });
653
+
654
+ test("German tasklist no-match is not running", () => {
655
+ expect(
656
+ parseTasklistOutput(
657
+ "INFORMATION: Es werden keine Aufgaben mit den angegebenen Kriterien ausgeführt.",
658
+ ),
659
+ ).toEqual([]);
660
+ });
661
+
662
+ test("tasklist CSV live process is running", () => {
663
+ expect(parseTasklistOutput('"opencode.exe","1234","Console","1","10,000 K"')).toEqual([
664
+ { pid: 1234, command: "opencode.exe" },
665
+ ]);
666
+ });
@@ -121,8 +121,6 @@ const WINDOWS_CIM_PROBE_TIMEOUT_MS = 5_000;
121
121
  const WINDOWS_PROCESS_SNAPSHOT_TTL_MS = 2_000;
122
122
  const MAX_ANCESTOR_WALK_DEPTH = 16;
123
123
  const OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
124
- const TASKLIST_NO_TASKS_PATTERN =
125
- /^INFO:\s+No tasks are running which match the specified criteria\.?$/im;
126
124
  const WINDOWS_CIM_COMMAND =
127
125
  "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,CreationDate | ConvertTo-Json -Compress";
128
126
  const PI_HARNESS_ARC_MARKERS = [
@@ -270,34 +268,39 @@ function parseCsvLine(line: string): string[] | null {
270
268
  return fields;
271
269
  }
272
270
 
273
- function parseTasklistOutput(output: string): ProcessListEntry[] | null {
271
+ export function parseTasklistOutput(output: string): ProcessListEntry[] | null {
274
272
  const entries: ProcessListEntry[] = [];
275
- let sawHeader = false;
273
+
276
274
  for (const rawLine of output.split(/\r?\n/)) {
277
275
  const line = rawLine.trim();
278
276
  if (!line) continue;
279
- if (TASKLIST_NO_TASKS_PATTERN.test(line)) return [];
277
+
280
278
  const fields = parseCsvLine(line);
281
279
  if (!fields) continue;
282
280
  if (fields[1]?.trim().toLowerCase() === "pid") {
283
- sawHeader = true;
284
281
  continue;
285
282
  }
286
283
  const pid = Number(fields[1]);
287
284
  if (!Number.isInteger(pid) || pid <= 0 || !fields[0]) continue;
288
285
  entries.push({ pid, command: fields[0] });
289
286
  }
290
- return entries.length > 0 || sawHeader ? entries : null;
287
+ // Successful tasklist commands return localized prose when no PID matches.
288
+ // Only CSV PID fields are evidence of a live process; failures are caught by the caller.
289
+ return entries;
291
290
  }
292
291
 
293
292
  function readWindowsProcess(pid: number): { state: PidLiveness; command?: string } {
294
293
  try {
295
- const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/FI", `PID eq ${pid}`], {
296
- encoding: "utf8",
297
- timeout: PS_PROBE_TIMEOUT_MS,
298
- stdio: ["ignore", "pipe", "pipe"],
299
- windowsHide: true,
300
- });
294
+ const output = rpcIdentityExecFileSync(
295
+ "tasklist",
296
+ ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],
297
+ {
298
+ encoding: "utf8",
299
+ timeout: PS_PROBE_TIMEOUT_MS,
300
+ stdio: ["ignore", "pipe", "pipe"],
301
+ windowsHide: true,
302
+ },
303
+ );
301
304
  const entries = parseTasklistOutput(String(output));
302
305
  if (entries === null) return { state: "inconclusive" };
303
306
  const process = entries.find((entry) => entry.pid === pid);
@@ -632,7 +635,11 @@ function tryReadWindowsCimSnapshot(exec: typeof execFileSync): ProcessSnapshot |
632
635
 
633
636
  function tryReadWindowsTasklistSnapshot(): ProcessSnapshot | null {
634
637
  try {
635
- const output = execProcessList(rpcProcessListExecFileSync, "tasklist", ["/FO", "CSV"]);
638
+ const output = execProcessList(rpcProcessListExecFileSync, "tasklist", [
639
+ "/FO",
640
+ "CSV",
641
+ "/NH",
642
+ ]);
636
643
  const entries = parseTasklistOutput(output);
637
644
  if (entries === null) return null;
638
645
  const facts = entries.map((entry) => ({
@@ -921,7 +928,11 @@ export function inspectProcessesAsync(forceFresh = false): Promise<AsyncProcessI
921
928
  }
922
929
  if (!snapshot) {
923
930
  const entries = parseTasklistOutput(
924
- await asyncProcessExec("tasklist", ["/FO", "CSV"], PS_PROBE_TIMEOUT_MS),
931
+ await asyncProcessExec(
932
+ "tasklist",
933
+ ["/FO", "CSV", "/NH"],
934
+ PS_PROBE_TIMEOUT_MS,
935
+ ),
925
936
  );
926
937
  if (entries)
927
938
  snapshot = snapshotFromFacts(
@@ -986,3 +997,21 @@ export function inspectProcessesAsync(forceFresh = false): Promise<AsyncProcessI
986
997
  });
987
998
  return asyncInspection;
988
999
  }
1000
+
1001
+ /** Take one fresh Windows process snapshot with command time limits for synchronous callers. */
1002
+ export function inspectWindowsProcessesSync(): AsyncProcessInspection {
1003
+ const snapshot =
1004
+ tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
1005
+ const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
1006
+ return {
1007
+ pi: snapshot ? classifyLivePiSnapshot(snapshot) : { state: "unreadable", processIds: [] },
1008
+ ...(snapshot
1009
+ ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } }
1010
+ : {}),
1011
+ evidence: (pid) => ({
1012
+ startTime: byPid.get(pid)?.startTime ?? null,
1013
+ commandLine: byPid.get(pid)?.commandLine ?? byPid.get(pid)?.imageName ?? null,
1014
+ }),
1015
+ liveness: (pid) => (byPid.has(pid) ? "alive" : snapshot ? "dead" : "inconclusive"),
1016
+ };
1017
+ }
@@ -0,0 +1,65 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { runTokenLog } from "./run-token-log";
3
+
4
+ describe("run token log host usage", () => {
5
+ test("OpenCode assistant message tokens retain reasoning and cache", () => {
6
+ const message = {
7
+ info: {
8
+ finish: "length",
9
+ tokens: { input: 10, output: 50, reasoning: 48, cache: { read: 7, write: 0 } },
10
+ },
11
+ };
12
+ expect(runTokenLog(message.info.tokens, 64, message.info.finish)).toEqual({
13
+ input: 10,
14
+ output: 50,
15
+ reasoning: 48,
16
+ cache_read: 7,
17
+ cache_write: 0,
18
+ max_tokens: 64,
19
+ finish_reason: "length",
20
+ });
21
+ });
22
+
23
+ test("OpenCode hidden-completion usage preserves omitted reasoning as null", () => {
24
+ const row = {
25
+ data: {
26
+ finish: "stop",
27
+ tokens: { input: 20, output: 4, cache: { read: 0, write: 3 } },
28
+ },
29
+ };
30
+ expect(runTokenLog(row.data.tokens, undefined, row.data.finish)).toEqual({
31
+ input: 20,
32
+ output: 4,
33
+ reasoning: null,
34
+ cache_read: 0,
35
+ cache_write: 3,
36
+ max_tokens: null,
37
+ finish_reason: "stop",
38
+ });
39
+ });
40
+
41
+ test("Pi stdout usage and absent usage remain distinguishable", () => {
42
+ const message = {
43
+ stopReason: "length",
44
+ usage: { input: 3, output: 12, cacheRead: 2, cacheWrite: 0 },
45
+ };
46
+ expect(runTokenLog(message.usage, 12, message.stopReason)).toEqual({
47
+ input: 3,
48
+ output: 12,
49
+ reasoning: null,
50
+ cache_read: 2,
51
+ cache_write: 0,
52
+ max_tokens: 12,
53
+ finish_reason: "length",
54
+ });
55
+ expect(runTokenLog(undefined)).toEqual({
56
+ input: null,
57
+ output: null,
58
+ reasoning: null,
59
+ cache_read: null,
60
+ cache_write: null,
61
+ max_tokens: null,
62
+ finish_reason: null,
63
+ });
64
+ });
65
+ });
@@ -0,0 +1,39 @@
1
+ export interface RunTokenLog {
2
+ input: number | null;
3
+ output: number | null;
4
+ reasoning: number | null;
5
+ cache_read: number | null;
6
+ cache_write: number | null;
7
+ max_tokens: number | null;
8
+ finish_reason: string | null;
9
+ }
10
+
11
+ function count(value: unknown): number | null {
12
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
13
+ }
14
+
15
+ /** Keep provider omissions distinct from measured zero in diagnostic logs. */
16
+ export function runTokenLog(tokens: unknown, maxTokens?: number, finish?: unknown): RunTokenLog {
17
+ const usage = tokens && typeof tokens === "object" ? (tokens as Record<string, unknown>) : {};
18
+ const cache =
19
+ usage.cache && typeof usage.cache === "object"
20
+ ? (usage.cache as Record<string, unknown>)
21
+ : {};
22
+ return {
23
+ input: count(usage.input ?? usage.input_tokens),
24
+ output: count(usage.output ?? usage.output_tokens),
25
+ reasoning: count(usage.reasoning ?? usage.reasoning_tokens),
26
+ cache_read: count(
27
+ usage.cacheRead ?? usage.cache_read ?? usage.cached_input_tokens ?? cache.read,
28
+ ),
29
+ cache_write: count(
30
+ usage.cacheWrite ?? usage.cache_write ?? usage.cache_write_tokens ?? cache.write,
31
+ ),
32
+ max_tokens: count(maxTokens),
33
+ finish_reason: typeof finish === "string" ? finish : null,
34
+ };
35
+ }
36
+
37
+ export function formatRunTokenLog(tokens: RunTokenLog): string {
38
+ return `tokens=${JSON.stringify(tokens)}`;
39
+ }
@@ -1,8 +1,13 @@
1
- import { expect, spyOn, test } from "bun:test";
1
+ import { expect, test } from "bun:test";
2
2
  import { mkdtempSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { Database, withPrivilegedWriter, withSqliteTransformPass } from "./sqlite";
5
+ import {
6
+ Database,
7
+ withAsyncPrivilegedWriter,
8
+ withPrivilegedWriter,
9
+ withSqliteTransformPass,
10
+ } from "./sqlite";
6
11
  import { startSqliteWriteLocker } from "./sqlite-write-locker-test-support";
7
12
 
8
13
  for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
@@ -10,7 +15,9 @@ for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
10
15
  const dir = mkdtempSync(join(tmpdir(), "mc-routed-acquisition-"));
11
16
  const path = join(dir, "context.db");
12
17
  const db = new Database(path);
13
- db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; CREATE TABLE result(value TEXT)");
18
+ db.exec(
19
+ "PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; CREATE TABLE result(value TEXT); CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
20
+ );
14
21
  const locker = await startSqliteWriteLocker(path, 650);
15
22
  let calls = 0;
16
23
  const write = () => {
@@ -19,7 +26,8 @@ for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
19
26
  return "managed";
20
27
  };
21
28
  try {
22
- withSqliteTransformPass(() => {
29
+ await withSqliteTransformPass(async () => {
30
+ await withAsyncPrivilegedWriter(db, () => undefined);
23
31
  if (mode === "literal") {
24
32
  db.exec("BEGIN IMMEDIATE");
25
33
  write();
@@ -43,7 +51,9 @@ for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
43
51
 
44
52
  test("routed transactions preserve nesting, receiver, arguments and rollback without callback retries", () => {
45
53
  const db = new Database(":memory:");
46
- db.exec("CREATE TABLE result(value TEXT)");
54
+ db.exec(
55
+ "CREATE TABLE result(value TEXT); CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
56
+ );
47
57
  let calls = 0;
48
58
  const transaction = db.transaction(function (this: { prefix: string }, value: string) {
49
59
  calls++;
@@ -69,23 +79,21 @@ test("exhausted routed acquisition never enters the callback or multiplies privi
69
79
  const path = join(dir, "context.db");
70
80
  const blocker = new Database(path);
71
81
  const db = new Database(path);
72
- blocker.exec("PRAGMA journal_mode=WAL; CREATE TABLE result(value TEXT)");
82
+ blocker.exec(
83
+ "PRAGMA journal_mode=WAL; CREATE TABLE result(value TEXT); CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
84
+ );
73
85
  db.exec("PRAGMA busy_timeout=0");
74
86
  blocker.exec("BEGIN IMMEDIATE");
75
- const wait = spyOn(Atomics, "wait").mockReturnValue("timed-out");
76
87
  let callbacks = 0;
77
88
  try {
78
89
  for (const run of [
79
90
  () => db.transaction(() => callbacks++)(),
80
91
  () => withPrivilegedWriter(db, () => callbacks++),
81
92
  ]) {
82
- wait.mockClear();
83
- expect(() => withSqliteTransformPass(run)).toThrow("after 3 attempts");
84
- expect(wait).toHaveBeenCalledTimes(2);
93
+ expect(() => withSqliteTransformPass(run)).toThrow("acquisition remained busy");
85
94
  expect(callbacks).toBe(0);
86
95
  }
87
96
  } finally {
88
- wait.mockRestore();
89
97
  blocker.exec("ROLLBACK");
90
98
  blocker.close();
91
99
  db.close();