@bli-cockpit/telemetry-core 0.1.50 → 0.1.51

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.
@@ -121,6 +121,18 @@ export declare const MEMORY_DAEMON_UNIX_PATH_MAX = 100;
121
121
  * 1 MB is far above both and bounds a peer that never sends a newline.
122
122
  */
123
123
  export declare const MEMORY_DAEMON_MAX_LINE_BYTES = 1048576;
124
+ /**
125
+ * How long a proxied `http` request may run before the daemon gives up on
126
+ * Tower and answers `daemon_http_timeout` (BLI-10746).
127
+ *
128
+ * This is the DAEMON's own ceiling on the request it makes with its warm
129
+ * dispatcher, separate from `deadlineMs` a caller passes to
130
+ * `askMemoryDaemonHttp` (the whole round trip including the local socket).
131
+ * CLI reads today (`work list`, `docs list`, …) already carry a
132
+ * `READ_DEADLINE_MS` of their own well under this; the daemon's ceiling only
133
+ * has to sit under that, never define it.
134
+ */
135
+ export declare const MEMORY_DAEMON_HTTP_PROXY_TIMEOUT_MS = 8000;
124
136
  export interface MemoryDaemonEndpoint {
125
137
  /** Which kind of endpoint this platform gets. */
126
138
  kind: "unix" | "pipe";
@@ -122,6 +122,18 @@ export const MEMORY_DAEMON_UNIX_PATH_MAX = 100;
122
122
  * 1 MB is far above both and bounds a peer that never sends a newline.
123
123
  */
124
124
  export const MEMORY_DAEMON_MAX_LINE_BYTES = 1_048_576;
125
+ /**
126
+ * How long a proxied `http` request may run before the daemon gives up on
127
+ * Tower and answers `daemon_http_timeout` (BLI-10746).
128
+ *
129
+ * This is the DAEMON's own ceiling on the request it makes with its warm
130
+ * dispatcher, separate from `deadlineMs` a caller passes to
131
+ * `askMemoryDaemonHttp` (the whole round trip including the local socket).
132
+ * CLI reads today (`work list`, `docs list`, …) already carry a
133
+ * `READ_DEADLINE_MS` of their own well under this; the daemon's ceiling only
134
+ * has to sit under that, never define it.
135
+ */
136
+ export const MEMORY_DAEMON_HTTP_PROXY_TIMEOUT_MS = 8_000;
125
137
  /**
126
138
  * The one place the daemon's address is computed. Both packages call this;
127
139
  * nobody joins a socket path by hand.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * THE CLIENT HALF OF THE DAEMON'S `http` EVENT, NODE ONLY (BLI-10746).
3
+ *
4
+ * `memory-daemon-endpoint.ts` next door is imported by the dashboard as well
5
+ * as by two CLIs, so it stays pure path/string arithmetic — nothing in it
6
+ * ever opens a socket. This module is the part that does, and it lives
7
+ * behind this package's own `./node-daemon-http-client` export rather than
8
+ * the root one, so a browser/edge bundle that imports `@bli-cockpit/
9
+ * telemetry-core` never pulls in `node:net`.
10
+ *
11
+ * `@bli-cockpit/local-collector` (the CLI) and `@bli-cockpit/mcp` (the MCP
12
+ * server) both need to ask the SAME resident daemon
13
+ * (`@bli-cockpit/memory-mcp`'s `bli-memory-mcp daemon`) to proxy one HTTP
14
+ * request over its already-warm connection to Tower (BLI-10741 built that
15
+ * connection for recall; this reuses it for every other read). Neither
16
+ * package may casually depend on `@bli-cockpit/memory-mcp` for this — the MCP
17
+ * server does not depend on it at all today, and the packed CLI's dependency
18
+ * list is its own contract — so this module speaks the daemon's
19
+ * `memory-daemon.v1` wire format directly, using only the address and
20
+ * timing constants both sides already share from `memory-daemon-endpoint.ts`.
21
+ * The daemon's own request/answer parsing (`@bli-cockpit/memory-mcp`'s
22
+ * `daemon/protocol.ts`) reads and writes the exact same shape; the two are
23
+ * bound together by `daemon/http-proxy.test.ts` on the daemon's side and by
24
+ * this module's own tests here, the same "two independent envelopes, proven
25
+ * by tests on each side" shape `memory-daemon-probe.ts` already uses for
26
+ * `ping`.
27
+ *
28
+ * **The device token is NOT part of this contract.** The caller's own
29
+ * `authorization` header travels inside `request.headers` exactly as it
30
+ * would have gone out directly — the daemon only forwards bytes over a
31
+ * socket it already trusts (owner-only, same OS user), never inspects or
32
+ * caches the credential. A daemon that is absent, refuses, times out or
33
+ * answers something this client cannot parse is a NAMED reason, never a
34
+ * thrown exception: every caller's contract is "fall back to a direct
35
+ * request", and that only works if this never hangs or throws.
36
+ */
37
+ import net from "node:net";
38
+ /** What travels out: enough to replay one `fetch(url, init)` on the daemon's own dispatcher. */
39
+ export interface DaemonHttpProxyRequest {
40
+ method: string;
41
+ url: string;
42
+ headers: Record<string, string>;
43
+ /** Already-serialised, exactly what `fetch`'s `body` would have been. */
44
+ body?: string;
45
+ }
46
+ /** What comes back: enough to reconstruct the `Response` the caller expected. */
47
+ export interface DaemonHttpProxyAnswer {
48
+ status: number;
49
+ headers: Record<string, string>;
50
+ body: string;
51
+ }
52
+ export type AskMemoryDaemonHttpSettled = {
53
+ ok: true;
54
+ answer: DaemonHttpProxyAnswer;
55
+ } | {
56
+ ok: false;
57
+ reason: string;
58
+ };
59
+ export type AskMemoryDaemonHttpResult = AskMemoryDaemonHttpSettled & {
60
+ elapsedMs: number;
61
+ };
62
+ export interface AskMemoryDaemonHttpOptions {
63
+ /** The unix socket path or the Windows pipe name (`memoryDaemonEndpoint(...).address`). */
64
+ address: string;
65
+ request: DaemonHttpProxyRequest;
66
+ /** Bounds the connect alone. Defaults to the shared 50 ms. */
67
+ connectTimeoutMs?: number;
68
+ /** Bounds the whole ask, local socket plus the daemon's own outbound call. */
69
+ deadlineMs: number;
70
+ /** Test seam. Real callers use `net.createConnection`. */
71
+ connectImpl?: (address: string) => net.Socket;
72
+ now?: () => number;
73
+ }
74
+ /**
75
+ * Ask the daemon to proxy one HTTP request over its warm connection.
76
+ * Resolves once, always — never throws, never hangs, never holds the event
77
+ * loop open past its own timers (all `unref`'d, same discipline as
78
+ * `memory-daemon-probe.ts` and `@bli-cockpit/memory-mcp`'s `askDaemon`).
79
+ */
80
+ export declare function askMemoryDaemonHttp(options: AskMemoryDaemonHttpOptions): Promise<AskMemoryDaemonHttpResult>;
81
+ /** One JSON line, the same envelope every daemon event uses. */
82
+ export declare function encodeHttpProxyLine(request: DaemonHttpProxyRequest): string;
83
+ export type ParsedHttpProxyAnswer = {
84
+ ok: true;
85
+ answer: DaemonHttpProxyAnswer;
86
+ } | {
87
+ ok: false;
88
+ reason: string;
89
+ };
90
+ /** Reads one answer line. Any shape this client cannot trust is a named reason, never a guess. */
91
+ export declare function parseHttpProxyAnswerLine(line: string): ParsedHttpProxyAnswer;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * THE CLIENT HALF OF THE DAEMON'S `http` EVENT, NODE ONLY (BLI-10746).
3
+ *
4
+ * `memory-daemon-endpoint.ts` next door is imported by the dashboard as well
5
+ * as by two CLIs, so it stays pure path/string arithmetic — nothing in it
6
+ * ever opens a socket. This module is the part that does, and it lives
7
+ * behind this package's own `./node-daemon-http-client` export rather than
8
+ * the root one, so a browser/edge bundle that imports `@bli-cockpit/
9
+ * telemetry-core` never pulls in `node:net`.
10
+ *
11
+ * `@bli-cockpit/local-collector` (the CLI) and `@bli-cockpit/mcp` (the MCP
12
+ * server) both need to ask the SAME resident daemon
13
+ * (`@bli-cockpit/memory-mcp`'s `bli-memory-mcp daemon`) to proxy one HTTP
14
+ * request over its already-warm connection to Tower (BLI-10741 built that
15
+ * connection for recall; this reuses it for every other read). Neither
16
+ * package may casually depend on `@bli-cockpit/memory-mcp` for this — the MCP
17
+ * server does not depend on it at all today, and the packed CLI's dependency
18
+ * list is its own contract — so this module speaks the daemon's
19
+ * `memory-daemon.v1` wire format directly, using only the address and
20
+ * timing constants both sides already share from `memory-daemon-endpoint.ts`.
21
+ * The daemon's own request/answer parsing (`@bli-cockpit/memory-mcp`'s
22
+ * `daemon/protocol.ts`) reads and writes the exact same shape; the two are
23
+ * bound together by `daemon/http-proxy.test.ts` on the daemon's side and by
24
+ * this module's own tests here, the same "two independent envelopes, proven
25
+ * by tests on each side" shape `memory-daemon-probe.ts` already uses for
26
+ * `ping`.
27
+ *
28
+ * **The device token is NOT part of this contract.** The caller's own
29
+ * `authorization` header travels inside `request.headers` exactly as it
30
+ * would have gone out directly — the daemon only forwards bytes over a
31
+ * socket it already trusts (owner-only, same OS user), never inspects or
32
+ * caches the credential. A daemon that is absent, refuses, times out or
33
+ * answers something this client cannot parse is a NAMED reason, never a
34
+ * thrown exception: every caller's contract is "fall back to a direct
35
+ * request", and that only works if this never hangs or throws.
36
+ */
37
+ import net from "node:net";
38
+ import { MEMORY_DAEMON_CONNECT_TIMEOUT_MS, MEMORY_DAEMON_MAX_LINE_BYTES, MEMORY_DAEMON_PROTOCOL_VERSION, } from "./memory-daemon-endpoint.js";
39
+ /**
40
+ * Ask the daemon to proxy one HTTP request over its warm connection.
41
+ * Resolves once, always — never throws, never hangs, never holds the event
42
+ * loop open past its own timers (all `unref`'d, same discipline as
43
+ * `memory-daemon-probe.ts` and `@bli-cockpit/memory-mcp`'s `askDaemon`).
44
+ */
45
+ export function askMemoryDaemonHttp(options) {
46
+ const now = options.now ?? Date.now;
47
+ const started = now();
48
+ const connectTimeoutMs = options.connectTimeoutMs ?? MEMORY_DAEMON_CONNECT_TIMEOUT_MS;
49
+ const connect = options.connectImpl ?? ((address) => net.createConnection({ path: address }));
50
+ return new Promise((resolve) => {
51
+ let settled = false;
52
+ let buffered = "";
53
+ let socket;
54
+ const timers = [];
55
+ const finish = (result) => {
56
+ if (settled)
57
+ return;
58
+ settled = true;
59
+ for (const timer of timers)
60
+ clearTimeout(timer);
61
+ try {
62
+ socket?.destroy();
63
+ }
64
+ catch {
65
+ // Already gone.
66
+ }
67
+ resolve({ ...result, elapsedMs: now() - started });
68
+ };
69
+ const arm = (ms, reason) => {
70
+ const timer = setTimeout(() => finish({ ok: false, reason }), Math.max(1, ms));
71
+ timer.unref?.();
72
+ timers.push(timer);
73
+ };
74
+ let connectTimer;
75
+ try {
76
+ socket = connect(options.address);
77
+ }
78
+ catch (error) {
79
+ finish({ ok: false, reason: connectReason(error) });
80
+ return;
81
+ }
82
+ socket.setNoDelay?.(true);
83
+ arm(options.deadlineMs, "daemon_http_deadline");
84
+ connectTimer = setTimeout(() => finish({ ok: false, reason: "daemon_connect_timeout" }), Math.max(1, connectTimeoutMs));
85
+ connectTimer.unref?.();
86
+ timers.push(connectTimer);
87
+ socket.on("error", (error) => {
88
+ finish({ ok: false, reason: connectReason(error) });
89
+ });
90
+ socket.on("connect", () => {
91
+ clearTimeout(connectTimer);
92
+ socket.write(encodeHttpProxyLine(options.request));
93
+ });
94
+ socket.on("data", (chunk) => {
95
+ buffered += chunk.toString("utf8");
96
+ if (buffered.length > MEMORY_DAEMON_MAX_LINE_BYTES) {
97
+ finish({ ok: false, reason: "daemon_answer_too_large" });
98
+ return;
99
+ }
100
+ const newline = buffered.indexOf("\n");
101
+ if (newline === -1)
102
+ return;
103
+ const parsed = parseHttpProxyAnswerLine(buffered.slice(0, newline));
104
+ if (!parsed.ok) {
105
+ finish({ ok: false, reason: parsed.reason });
106
+ return;
107
+ }
108
+ finish({ ok: true, answer: parsed.answer });
109
+ });
110
+ socket.on("close", () => {
111
+ finish({ ok: false, reason: "daemon_closed_without_answer" });
112
+ });
113
+ });
114
+ }
115
+ /** One JSON line, the same envelope every daemon event uses. */
116
+ export function encodeHttpProxyLine(request) {
117
+ return `${JSON.stringify({
118
+ v: MEMORY_DAEMON_PROTOCOL_VERSION,
119
+ event: "http",
120
+ http: request,
121
+ })}\n`;
122
+ }
123
+ /** Reads one answer line. Any shape this client cannot trust is a named reason, never a guess. */
124
+ export function parseHttpProxyAnswerLine(line) {
125
+ let parsed;
126
+ try {
127
+ parsed = JSON.parse(line);
128
+ }
129
+ catch {
130
+ return { ok: false, reason: "daemon_answer_unparseable" };
131
+ }
132
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
133
+ return { ok: false, reason: "daemon_answer_not_an_object" };
134
+ }
135
+ const record = parsed;
136
+ if (record["ok"] !== true) {
137
+ const reason = record["reason"];
138
+ return { ok: false, reason: typeof reason === "string" ? reason : "daemon_refused" };
139
+ }
140
+ const http = record["http"];
141
+ if (!http || typeof http !== "object" || Array.isArray(http)) {
142
+ return { ok: false, reason: "daemon_answer_without_http" };
143
+ }
144
+ const httpRecord = http;
145
+ const status = httpRecord["status"];
146
+ const body = httpRecord["body"];
147
+ if (typeof status !== "number" || typeof body !== "string") {
148
+ return { ok: false, reason: "daemon_answer_http_malformed" };
149
+ }
150
+ const headers = {};
151
+ const rawHeaders = httpRecord["headers"];
152
+ if (rawHeaders && typeof rawHeaders === "object" && !Array.isArray(rawHeaders)) {
153
+ for (const [key, value] of Object.entries(rawHeaders)) {
154
+ if (typeof value === "string")
155
+ headers[key] = value;
156
+ }
157
+ }
158
+ return { ok: true, answer: { status, headers, body } };
159
+ }
160
+ /** The closed reason vocabulary for a failed connect. `errno` codes only, never an exception message. */
161
+ function connectReason(error) {
162
+ const code = error?.code;
163
+ if (code === "ENOENT" || code === "ECONNREFUSED")
164
+ return "daemon_absent";
165
+ if (code === "EACCES" || code === "EPERM")
166
+ return "daemon_forbidden";
167
+ if (code === "ETIMEDOUT")
168
+ return "daemon_connect_timeout";
169
+ return typeof code === "string" ? `daemon_socket_${code.toLowerCase()}` : "daemon_socket_error";
170
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * THE ON-DISK, PER-OPERATOR, STALE-WHILE-REVALIDATE READ CACHE (BLI-10746).
3
+ *
4
+ * Node only — file permissions and `node:fs`/`node:crypto` are not something
5
+ * a dashboard bundle needs — so this lives behind this package's own
6
+ * `./node-read-cache` export, the same isolation `./node-daemon-http-client`
7
+ * next door uses.
8
+ *
9
+ * `@bli-cockpit/local-collector` (the CLI) owns the actual stale-while-
10
+ * revalidate DECISION — when to serve cache, when a fresh call is required,
11
+ * when to kick off a background refresh — because that decision needs
12
+ * `--fresh`/`--allow-stale`/`--json`, which are CLI concepts this module
13
+ * knows nothing about. What lives HERE is the shared, dumb, provably-correct
14
+ * bottom half both the CLI (reading and writing) and `@bli-cockpit/mcp` (only
15
+ * ever invalidating, on its own writes) need to agree on byte-for-byte:
16
+ * where an entry lives on disk, how it is written so a reader never sees a
17
+ * half-written file, and how a whole surface is thrown away after a write.
18
+ * Two independent computations of the same cache path is exactly the
19
+ * BLI-2541 shape (a reader that "worked" against a path nothing ever wrote)
20
+ * this module exists to rule out.
21
+ *
22
+ * **Per-operator, never shared.** The device token is never stored — only
23
+ * its SHA-256, truncated, as a directory segment — but two different people
24
+ * pairing the same machine still get two different cache trees, so a shared
25
+ * intern laptop can never show one operator's Tower data to another.
26
+ *
27
+ * **Owner-only on disk.** Directories `0700`, files `0600`, same as every
28
+ * other collector state directory (`local-state-paths.ts`). No secret is
29
+ * ever written here — this stores API RESPONSE bodies, the same bodies the
30
+ * CLI already prints to a terminal — but the discipline is kept anyway.
31
+ */
32
+ /** The seven surfaces this ticket's cache covers. A write to any other path invalidates nothing (and is never asked to). */
33
+ export declare const READ_CACHE_SURFACES: readonly ["work", "docs", "cal", "mail", "msg", "settings", "memory"];
34
+ export type ReadCacheSurface = (typeof READ_CACHE_SURFACES)[number];
35
+ /** `/api/work/...` → `"work"`, and so on. `null` for anything this cache does not cover. */
36
+ export declare function readCacheSurfaceForPath(apiPath: string): ReadCacheSurface | null;
37
+ /** One entry, as it sits on disk. */
38
+ export interface ReadCacheEntry {
39
+ storedAt: number;
40
+ status: number;
41
+ body: unknown;
42
+ }
43
+ /** Never the raw token — a machine-scoping label only, never reversible in practice and never logged with its input. */
44
+ export declare function operatorScope(deviceToken: string): string;
45
+ /** One request, folded to a filename-safe key. Includes the body so `memory search`'s different queries never collide. */
46
+ export declare function readCacheKey(label: string, apiPath: string, body: unknown): string;
47
+ export declare function readCacheSurfaceDir(stateDir: string, deviceToken: string, surface: ReadCacheSurface): string;
48
+ export declare function readCacheEntryPath(stateDir: string, deviceToken: string, surface: ReadCacheSurface, key: string): string;
49
+ /**
50
+ * Reads one entry. Missing, corrupt, or an unreadable shape are all the same
51
+ * answer — `null`, a cache miss — never a thrown error: a cache is a
52
+ * performance optimisation, and a command that crashed because its cache
53
+ * file was half-written would be worse than no cache at all.
54
+ */
55
+ export declare function readReadCacheEntry(entryPath: string): ReadCacheEntry | null;
56
+ /**
57
+ * Writes one entry atomically: a temp file in the SAME directory (so the
58
+ * rename is on one filesystem, never a cross-device copy), then `rename`,
59
+ * which POSIX and NTFS both make an atomic replace. A reader mid-refresh
60
+ * therefore always sees either the old whole entry or the new whole entry,
61
+ * never a partial write.
62
+ */
63
+ export declare function writeReadCacheEntryAtomic(entryPath: string, entry: Omit<ReadCacheEntry, "storedAt"> & {
64
+ storedAt?: number;
65
+ }): void;
66
+ /**
67
+ * Throws away every cached read for one surface — the whole answer to "any
68
+ * write through the CLI or MCP invalidates the affected cache" (BLI-10746).
69
+ * Coarse on purpose: a write to `/api/work/issues/BLI-1` could in principle
70
+ * only stale one `work list` filter combination, but naming exactly which
71
+ * cached queries a given write affects is its own project, and "the next
72
+ * read of this surface is live" costs one extra request, never a wrong
73
+ * answer.
74
+ */
75
+ export declare function invalidateReadCacheSurface(stateDir: string, deviceToken: string, surface: ReadCacheSurface): {
76
+ ok: true;
77
+ removed: boolean;
78
+ } | {
79
+ ok: false;
80
+ reason: string;
81
+ };
@@ -0,0 +1,137 @@
1
+ /**
2
+ * THE ON-DISK, PER-OPERATOR, STALE-WHILE-REVALIDATE READ CACHE (BLI-10746).
3
+ *
4
+ * Node only — file permissions and `node:fs`/`node:crypto` are not something
5
+ * a dashboard bundle needs — so this lives behind this package's own
6
+ * `./node-read-cache` export, the same isolation `./node-daemon-http-client`
7
+ * next door uses.
8
+ *
9
+ * `@bli-cockpit/local-collector` (the CLI) owns the actual stale-while-
10
+ * revalidate DECISION — when to serve cache, when a fresh call is required,
11
+ * when to kick off a background refresh — because that decision needs
12
+ * `--fresh`/`--allow-stale`/`--json`, which are CLI concepts this module
13
+ * knows nothing about. What lives HERE is the shared, dumb, provably-correct
14
+ * bottom half both the CLI (reading and writing) and `@bli-cockpit/mcp` (only
15
+ * ever invalidating, on its own writes) need to agree on byte-for-byte:
16
+ * where an entry lives on disk, how it is written so a reader never sees a
17
+ * half-written file, and how a whole surface is thrown away after a write.
18
+ * Two independent computations of the same cache path is exactly the
19
+ * BLI-2541 shape (a reader that "worked" against a path nothing ever wrote)
20
+ * this module exists to rule out.
21
+ *
22
+ * **Per-operator, never shared.** The device token is never stored — only
23
+ * its SHA-256, truncated, as a directory segment — but two different people
24
+ * pairing the same machine still get two different cache trees, so a shared
25
+ * intern laptop can never show one operator's Tower data to another.
26
+ *
27
+ * **Owner-only on disk.** Directories `0700`, files `0600`, same as every
28
+ * other collector state directory (`local-state-paths.ts`). No secret is
29
+ * ever written here — this stores API RESPONSE bodies, the same bodies the
30
+ * CLI already prints to a terminal — but the discipline is kept anyway.
31
+ */
32
+ import crypto from "node:crypto";
33
+ import fs from "node:fs";
34
+ import path from "node:path";
35
+ /** The seven surfaces this ticket's cache covers. A write to any other path invalidates nothing (and is never asked to). */
36
+ export const READ_CACHE_SURFACES = [
37
+ "work",
38
+ "docs",
39
+ "cal",
40
+ "mail",
41
+ "msg",
42
+ "settings",
43
+ "memory",
44
+ ];
45
+ /** `/api/work/...` → `"work"`, and so on. `null` for anything this cache does not cover. */
46
+ export function readCacheSurfaceForPath(apiPath) {
47
+ const segment = apiPath.replace(/^\/+/, "").split("/")[1];
48
+ return READ_CACHE_SURFACES.includes(segment ?? "")
49
+ ? segment
50
+ : null;
51
+ }
52
+ /** Never the raw token — a machine-scoping label only, never reversible in practice and never logged with its input. */
53
+ export function operatorScope(deviceToken) {
54
+ return crypto.createHash("sha256").update(deviceToken).digest("hex").slice(0, 16);
55
+ }
56
+ /** One request, folded to a filename-safe key. Includes the body so `memory search`'s different queries never collide. */
57
+ export function readCacheKey(label, apiPath, body) {
58
+ const material = `${label}\n${apiPath}\n${body === undefined ? "" : JSON.stringify(body)}`;
59
+ return crypto.createHash("sha256").update(material).digest("hex").slice(0, 40);
60
+ }
61
+ export function readCacheSurfaceDir(stateDir, deviceToken, surface) {
62
+ return path.join(stateDir, "read-cache", operatorScope(deviceToken), surface);
63
+ }
64
+ export function readCacheEntryPath(stateDir, deviceToken, surface, key) {
65
+ return path.join(readCacheSurfaceDir(stateDir, deviceToken, surface), `${key}.json`);
66
+ }
67
+ /**
68
+ * Reads one entry. Missing, corrupt, or an unreadable shape are all the same
69
+ * answer — `null`, a cache miss — never a thrown error: a cache is a
70
+ * performance optimisation, and a command that crashed because its cache
71
+ * file was half-written would be worse than no cache at all.
72
+ */
73
+ export function readReadCacheEntry(entryPath) {
74
+ let raw;
75
+ try {
76
+ raw = fs.readFileSync(entryPath, "utf8");
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ try {
82
+ const parsed = JSON.parse(raw);
83
+ const storedAt = parsed["storedAt"];
84
+ const status = parsed["status"];
85
+ if (typeof storedAt !== "number" || typeof status !== "number" || !("body" in parsed)) {
86
+ return null;
87
+ }
88
+ return { storedAt, status, body: parsed["body"] };
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ /**
95
+ * Writes one entry atomically: a temp file in the SAME directory (so the
96
+ * rename is on one filesystem, never a cross-device copy), then `rename`,
97
+ * which POSIX and NTFS both make an atomic replace. A reader mid-refresh
98
+ * therefore always sees either the old whole entry or the new whole entry,
99
+ * never a partial write.
100
+ */
101
+ export function writeReadCacheEntryAtomic(entryPath, entry) {
102
+ const dir = path.dirname(entryPath);
103
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
104
+ const payload = { storedAt: entry.storedAt ?? Date.now(), status: entry.status, body: entry.body };
105
+ const tmpPath = path.join(dir, `.${path.basename(entryPath)}.${process.pid}.tmp`);
106
+ fs.writeFileSync(tmpPath, JSON.stringify(payload), { mode: 0o600 });
107
+ fs.renameSync(tmpPath, entryPath);
108
+ if (process.platform !== "win32") {
109
+ try {
110
+ fs.chmodSync(dir, 0o700);
111
+ }
112
+ catch {
113
+ // Best-effort tightening only; the mkdir mode above already asked for it.
114
+ }
115
+ }
116
+ }
117
+ /**
118
+ * Throws away every cached read for one surface — the whole answer to "any
119
+ * write through the CLI or MCP invalidates the affected cache" (BLI-10746).
120
+ * Coarse on purpose: a write to `/api/work/issues/BLI-1` could in principle
121
+ * only stale one `work list` filter combination, but naming exactly which
122
+ * cached queries a given write affects is its own project, and "the next
123
+ * read of this surface is live" costs one extra request, never a wrong
124
+ * answer.
125
+ */
126
+ export function invalidateReadCacheSurface(stateDir, deviceToken, surface) {
127
+ const dir = readCacheSurfaceDir(stateDir, deviceToken, surface);
128
+ try {
129
+ const existed = fs.existsSync(dir);
130
+ if (existed)
131
+ fs.rmSync(dir, { recursive: true, force: true });
132
+ return { ok: true, removed: existed };
133
+ }
134
+ catch (error) {
135
+ return { ok: false, reason: error instanceof Error ? error.name : "unknown" };
136
+ }
137
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.50",
3
+ "version": "0.1.51",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,6 +24,16 @@
24
24
  "types": "./dist/evidence-storage-encoding.d.ts",
25
25
  "import": "./dist/evidence-storage-encoding.js",
26
26
  "default": "./dist/evidence-storage-encoding.js"
27
+ },
28
+ "./node-daemon-http-client": {
29
+ "types": "./dist/node-daemon-http-client.d.ts",
30
+ "import": "./dist/node-daemon-http-client.js",
31
+ "default": "./dist/node-daemon-http-client.js"
32
+ },
33
+ "./node-read-cache": {
34
+ "types": "./dist/node-read-cache.d.ts",
35
+ "import": "./dist/node-read-cache.js",
36
+ "default": "./dist/node-read-cache.js"
27
37
  }
28
38
  },
29
39
  "publishConfig": {