@lorekit/cli 1.21.0 → 1.22.0

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.
package/README.md CHANGED
@@ -224,13 +224,13 @@ stored by basename only) — so every scope is reconstructed verbatim. Lessons
224
224
  present in both tiers are counted once (project shadows home, the same merge
225
225
  `list` uses); archived lessons are excluded.
226
226
 
227
- **Remote enumeration is not possible, and `scopes` says so honestly.** The
228
- hosted MCP surface exposes no "list all scopes" tool every read tool
229
- (`memory.list` / `memory.search` / `memory.read`) *requires* a scope so a
230
- remote inventory can't be built. The Remote section is therefore always a short
231
- note (never a faked listing), degrading gracefully at exit 0, the same way
232
- `stats` omits a cap-usage figure. `--endpoint` / `--token` / `--store` behave as
233
- in `list`.
227
+ **Remote enumeration is exact too.** `RemoteStore.listScopes()` calls
228
+ `GET /memories/scopes`, which aggregates one `{ scope, count }` row per scope in
229
+ Postgres (never a truncatable `select('scope')` plus a client-side dedupe), so
230
+ the Remote section is a real inventory rendered through the same helpers as the
231
+ Offline one. A denied, unconfigured, unreachable, or erroring remote degrades to
232
+ a short, accurate note (network error / HTTP status never a faked listing) at
233
+ exit 0. `--endpoint` / `--token` / `--store` behave as in `list`.
234
234
 
235
235
  ### `lorekit diff`
236
236
 
package/bin/lorekit.mjs CHANGED
@@ -348,9 +348,10 @@ is a full inventory — it surfaces scopes anywhere in the store, regardless of
348
348
  current directory.
349
349
 
350
350
  Offline counts are exact: each scope is read from the memory files' frontmatter,
351
- not reverse-mapped from the directory layout. The Remote section is always a
352
- short note: the hosted MCP surface has no "list all scopes" tool (every read tool
353
- requires a scope), so a remote inventory isn't possible never an error (exit 0).
351
+ not reverse-mapped from the directory layout. Remote counts are exact too — they
352
+ come from \`GET /memories/scopes\`, which aggregates one row per scope server-side.
353
+ A denied, unconfigured, or unreachable remote degrades to a short, accurate note
354
+ rather than an error (exit 0).
354
355
 
355
356
  ${c.bold('Options')}
356
357
  -d, --dir <path> Target project root (default: current directory)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lorekit/cli",
3
- "version": "1.21.0",
3
+ "version": "1.22.0",
4
4
  "description": "Install the LoreKit shared-memory skill and run health checks for the LoreKit MCP server.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/mcp.mjs CHANGED
@@ -27,7 +27,11 @@ export function buildRemoteUrl(endpoint, token) {
27
27
  let idCounter = 0;
28
28
 
29
29
  // Returns { ok, httpStatus, result, error, networkError }.
30
- export async function mcpCall(endpoint, token, method, params = {}, { timeoutMs = 10000 } = {}) {
30
+ //
31
+ // `opts.traceparent` is an optional W3C traceparent header value (see
32
+ // src/telemetry.mjs `getActiveTraceparent`); when present it is forwarded so
33
+ // the server-side span joins the CLI's trace — same idiom as restFetch.
34
+ export async function mcpCall(endpoint, token, method, params = {}, { timeoutMs = 10000, traceparent } = {}) {
31
35
  const controller = new AbortController();
32
36
  const timer = setTimeout(() => controller.abort(), timeoutMs);
33
37
  try {
@@ -40,6 +44,7 @@ export async function mcpCall(endpoint, token, method, params = {}, { timeoutMs
40
44
  'content-type': 'application/json',
41
45
  accept: 'application/json, text/event-stream',
42
46
  ...(token ? { authorization: `Bearer ${token}` } : {}),
47
+ ...(traceparent ? { traceparent } : {}),
43
48
  },
44
49
  body: JSON.stringify({ jsonrpc: '2.0', id: ++idCounter, method, params }),
45
50
  signal: controller.signal,
package/src/scopes.mjs CHANGED
@@ -13,10 +13,12 @@
13
13
  // mapping the on-disk directory layout, which is lossy for `project::{name}`
14
14
  // (stored by basename only) — so every scope is reconstructed exactly.
15
15
  //
16
- // Remote enumeration is NOT possible: the hosted MCP surface exposes no "list
17
- // all scopes" tool every read tool (memory.list / search / read) REQUIRES a
18
- // scope so the Remote section is always an honest note (never faked), the same
19
- // way `stats` omits a cap-usage figure. It still degrades gracefully at exit 0.
16
+ // Remote enumeration is EXACT too: `RemoteStore.listScopes()` calls
17
+ // `GET /memories/scopes`, which aggregates one row per scope in Postgres (never
18
+ // a truncatable `select('scope')` + client-side dedupe), so both sections are
19
+ // real inventories rendered through the same pure helpers. A denied,
20
+ // unconfigured, unreachable, or erroring remote still degrades to a short,
21
+ // accurate note at exit 0 — never a throw.
20
22
  //
21
23
  // Graceful, read-only, human-facing (the bin wraps it in `traceCommand`).
22
24
  // `LOREKIT_DENY` suppresses a section; `--scope <s>` filters the inventory to
@@ -26,15 +28,9 @@ import process from 'node:process';
26
28
  import { resolveProjectRoot } from './config.mjs';
27
29
  import { resolveDenies } from './control.mjs';
28
30
  import { resolveStores, remoteUnavailableReason } from './stores.mjs';
29
- import { summarizeScopeInventory, filterScopeInventory } from './lessons-view.mjs';
31
+ import { summarizeScopeInventory, filterScopeInventory, describeError } from './lessons-view.mjs';
30
32
  import { log, heading, status, c } from './util.mjs';
31
33
 
32
- // The honest note the Remote section shows when it isn't denied/unconfigured:
33
- // the hosted MCP surface simply can't enumerate scopes. Exported so tests can
34
- // assert the exact wording rather than a fragile substring.
35
- export const REMOTE_SCOPES_UNSUPPORTED =
36
- 'remote scope enumeration is not supported by the hosted MCP surface (memory.list requires a scope)';
37
-
38
34
  export async function scopes(args) {
39
35
  const root = resolveProjectRoot(args.dir);
40
36
  const env = { ...process.env };
@@ -63,16 +59,21 @@ export async function scopes(args) {
63
59
  offlineSection = { available: true, ...summarizeScopeInventory(inventory) };
64
60
  }
65
61
 
66
- // Remote: never enumerable. A deny note, an unconfigured note, or the honest
67
- // "not supported" note all graceful (exit 0). Order matches the other
68
- // commands' precedence: deny first, then connectivity, then the capability.
62
+ // Remote: the hosted enumeration, via `GET /memories/scopes`. Precedence is
63
+ // unchanged from the other read commands deny first, then connectivity, then
64
+ // the call itself. A failed call degrades to the same bounded, non-PII
65
+ // `describeError` note a failed `list()` gets (network error / HTTP status),
66
+ // never a throw and never a faked inventory.
69
67
  let remoteSection;
70
68
  if (remoteDenied) {
71
69
  remoteSection = { available: false, reason: `disabled by deny constraint (${remoteDenied.source})` };
72
70
  } else if (!remote.usable()) {
73
71
  remoteSection = { available: false, reason: remoteUnavailableReason(connection) };
74
72
  } else {
75
- remoteSection = { available: false, reason: REMOTE_SCOPES_UNSUPPORTED };
73
+ const res = await remote.listScopes();
74
+ remoteSection = res.ok
75
+ ? { available: true, ...summarizeScopeInventory(filterScopeInventory(res.scopes, filter)) }
76
+ : { available: false, reason: describeError(res) };
76
77
  }
77
78
 
78
79
  if (args.json) {
@@ -89,15 +90,17 @@ export async function scopes(args) {
89
90
  log('');
90
91
  }
91
92
 
92
- // Bounded, non-PII telemetry extras (counts + a boolean) — never a scope
93
- // string, path, or token. `remote_available` is always false: the surface
94
- // can't enumerate, and saying so is the honest signal.
93
+ // Bounded, non-PII telemetry extras (counts + booleans) — never a scope
94
+ // string, path, or token. `remote_available` now reflects whether the hosted
95
+ // enumeration actually answered; the remote counts mirror the offline pair.
95
96
  return {
96
97
  exitCode: 0,
97
98
  'lorekit.cli.scopes.offline_scope_count': offlineSection.available ? offlineSection.scopes.length : 0,
98
99
  'lorekit.cli.scopes.offline_total': offlineSection.available ? offlineSection.total : 0,
99
100
  'lorekit.cli.scopes.filtered': Boolean(filter),
100
- 'lorekit.cli.scopes.remote_available': false,
101
+ 'lorekit.cli.scopes.remote_scope_count': remoteSection.available ? remoteSection.scopes.length : 0,
102
+ 'lorekit.cli.scopes.remote_total': remoteSection.available ? remoteSection.total : 0,
103
+ 'lorekit.cli.scopes.remote_available': remoteSection.available,
101
104
  };
102
105
  }
103
106
 
@@ -1,9 +1,12 @@
1
1
  // Remote store: wraps the LoreKit REST API `memory.*` endpoints behind the
2
- // common store contract. Memory operations use the REST API for lower overhead
3
- // and W3C traceparent propagation. Org operations remain on MCP because org
4
- // RPCs require a Supabase JWT session (auth.uid() via SECURITY DEFINER
5
- // functions), which is incompatible with the lk_* api_key tokens that CLI
6
- // users have. Zero-dependency.
2
+ // common store contract. EVERY memory operation goes over REST list, search,
3
+ // read, write, delete (soft-archive AND `?force=true` hard-delete) and the
4
+ // store-wide `listScopes()` enumeration for lower overhead and W3C
5
+ // traceparent propagation. MCP remains ONLY for the four `org.*` calls and the
6
+ // `ping` fallback: org RPCs require a Supabase JWT session (they resolve the
7
+ // actor via auth.uid() inside SECURITY DEFINER functions), which is
8
+ // incompatible with the lk_* api_key tokens that CLI users have.
9
+ // Zero-dependency.
7
10
  import { mcpCall, restFetch, mcpToRestBase } from '../mcp.mjs';
8
11
  import { getActiveTraceparent } from '../telemetry.mjs';
9
12
 
@@ -39,7 +42,7 @@ class RemoteStore {
39
42
 
40
43
  async _mcp(name, args) {
41
44
  if (!this.usable()) return { ok: false, unusable: true };
42
- return mcpCall(this.endpoint, this.token, 'tools/call', { name, arguments: args });
45
+ return mcpCall(this.endpoint, this.token, 'tools/call', { name, arguments: args }, { traceparent: this._tp() });
43
46
  }
44
47
 
45
48
  _mcpEntries(res) {
@@ -79,6 +82,8 @@ class RemoteStore {
79
82
  const p = new URLSearchParams();
80
83
  if (scope) p.set('scope', scope);
81
84
  if (key) p.set('key', key);
85
+ // scope+key is unique, so one row is all there can be — don't pull the default page of 50.
86
+ p.set('limit', '1');
82
87
  const res = await this._rest(`/memories?${p}`);
83
88
  if (!res.ok) return { ok: false, error: res.error, networkError: res.networkError };
84
89
  const entries = res.data?.entries ?? [];
@@ -99,14 +104,12 @@ class RemoteStore {
99
104
  return { ok: res.ok, error: res.error, networkError: res.networkError };
100
105
  }
101
106
 
107
+ // Natural-key DELETE. Without `force` the server soft-archives (stamps
108
+ // `archived_at`); `?force=true` hard-deletes the row outright — both forms of
109
+ // the same REST route (supabase/functions/memories/handlers/remove.ts).
102
110
  async delete({ scope, key, force = false } = {}) {
103
- if (force) {
104
- // Hard-delete requires MCP — REST only supports soft-archive (archived_at)
105
- const res = await this._mcp('memory.delete', { scope, key, force: true });
106
- return { ok: res.ok, error: res.error, networkError: res.networkError };
107
- }
108
- // Soft-archive via natural-key REST endpoint
109
111
  const p = new URLSearchParams({ scope, key });
112
+ if (force) p.set('force', 'true');
110
113
  const res = await this._rest(`/memories?${p}`, { method: 'DELETE' });
111
114
  return { ok: res.ok, error: res.error, networkError: res.networkError };
112
115
  }
@@ -155,12 +158,22 @@ class RemoteStore {
155
158
  return { ok: true, ...(payload ?? {}) };
156
159
  }
157
160
 
158
- // Store-wide scope enumeration is NOT possible against the hosted REST surface:
159
- // every read tool requires a scope, and there is no "list all scopes" endpoint.
160
- // Signal that honestly so the `scopes` command shows a clear note rather than
161
- // faking an inventory.
161
+ // Store-wide scope enumeration every distinct scope the caller can see with
162
+ // its count of active (non-archived, non-expired) memories. `GET
163
+ // /memories/scopes` aggregates in Postgres, so the answer is exact at any size
164
+ // (see supabase/functions/memories/handlers/scopes.ts).
165
+ //
166
+ // The `scopes` array is the SAME `[{ scope, count }]` inventory shape
167
+ // `LocalStore.listScopes()` returns, so `scopes.mjs` feeds both through the
168
+ // same pure `filterScopeInventory`/`summarizeScopeInventory` helpers. Ordering
169
+ // is not relied upon (the server sorts by scope asc; the view re-sorts by
170
+ // scope type). Failures use this store's standard `{ ok:false, error,
171
+ // networkError }` envelope so the caller can degrade gracefully.
162
172
  async listScopes() {
163
- return { ok: false, unsupported: true };
173
+ const res = await this._rest('/memories/scopes');
174
+ if (!res.ok) return { ok: false, error: res.error, networkError: res.networkError, unusable: res.unusable };
175
+ const scopes = Array.isArray(res.data?.scopes) ? res.data.scopes : [];
176
+ return { ok: true, scopes: scopes.map((s) => ({ scope: s.scope, count: Number(s.count) || 0 })) };
164
177
  }
165
178
 
166
179
  // Connectivity probe for doctor — a transport check, not a memory op.
@@ -171,11 +184,15 @@ class RemoteStore {
171
184
  ? `${this.restBase.replace(/\/functions\/v1$/, '')}/functions/v1/health`
172
185
  : null;
173
186
  if (healthUrl) {
187
+ const tp = this._tp();
174
188
  try {
175
- const res = await fetch(healthUrl, { signal: AbortSignal.timeout(5000) });
189
+ const res = await fetch(healthUrl, {
190
+ signal: AbortSignal.timeout(5000),
191
+ ...(tp ? { headers: { traceparent: tp } } : {}),
192
+ });
176
193
  return { ok: res.ok, httpStatus: res.status };
177
194
  } catch (e) { return { ok: false, networkError: String(e?.message ?? e) }; }
178
195
  }
179
- return mcpCall(this.endpoint, this.token, 'tools/list', {});
196
+ return mcpCall(this.endpoint, this.token, 'tools/list', {}, { traceparent: this._tp() });
180
197
  }
181
198
  }
package/src/telemetry.mjs CHANGED
@@ -41,19 +41,30 @@ const FLAG_ATTRS = ['global', 'project', 'deep', 'yes', 'force', 'no-hooks', 'js
41
41
  const OFF_VALUES = new Set(['0', 'off', 'false', 'no', 'disable', 'disabled']);
42
42
 
43
43
  // ── Active trace context (for traceparent propagation to REST calls) ──────────
44
- // Set at the start of each traced command run; used by RemoteStore to
45
- // forward the CLI span's trace identity to outgoing REST requests.
44
+ // Set at the start of EVERY traced command run including runs where export is
45
+ // disabled. Context propagation is deliberately decoupled from export: a user
46
+ // who opted out (or who simply has no OTLP endpoint configured) must still get
47
+ // correlated server-side traces, they just don't contribute a CLI span.
46
48
  let _activeTraceId = null;
47
49
  let _activeSpanId = null;
50
+ // Whether the current command's span will actually be exported. Drives the
51
+ // W3C `sampled` bit only — never whether the header is sent.
52
+ let _activeSampled = false;
48
53
 
49
54
  /**
50
- * Get the W3C traceparent for the currently-running CLI command, or null.
51
- * Called by RemoteStore to inject the header into REST fetches so CLI spans
52
- * are linked to REST API spans in Dash0.
55
+ * Get the W3C traceparent for the currently-running CLI command, or null when
56
+ * no command is running. Called by RemoteStore to inject the header into
57
+ * outgoing REST/MCP calls so the server span joins the CLI's trace.
58
+ *
59
+ * Flags are `01` when the CLI span is exported and `00` when it is not — the
60
+ * trace id is still carried either way, so the server can correlate. This
61
+ * mirrors `formatTraceparent` in `packages/mcp-core/src/trace-context.ts`
62
+ * (the CLI is zero-dep `.mjs` and cannot import the TS module); keep the two
63
+ * byte-consistent.
53
64
  */
54
65
  export function getActiveTraceparent() {
55
66
  if (!_activeTraceId || !_activeSpanId) return null;
56
- return `00-${_activeTraceId}-${_activeSpanId}-01`;
67
+ return `00-${_activeTraceId}-${_activeSpanId}-${_activeSampled ? '01' : '00'}`;
57
68
  }
58
69
 
59
70
  // ── Config resolution ─────────────────────────────────────────────────────────
@@ -313,18 +324,32 @@ export async function traceCommand(command, args, version, run) {
313
324
  config = { enabled: false };
314
325
  }
315
326
 
327
+ // Generate trace context BEFORE the export gate below, so outgoing REST/MCP
328
+ // calls can forward it as `traceparent` even when telemetry is disabled.
329
+ // Propagation is decoupled from export: a user with no OTLP endpoint (the
330
+ // common case — TELEMETRY_TOKEN is empty in git) still gets a single
331
+ // correlated server-side trace. The `sampled` bit is what reflects export.
332
+ // The same IDs are reused in exportInvocation() to link the CLI span to
333
+ // REST spans.
334
+ _activeTraceId = randHex(16);
335
+ _activeSpanId = randHex(8);
336
+ _activeSampled = Boolean(config.enabled);
337
+
316
338
  // Fast path: no export configured → run with zero telemetry overhead. Still
317
339
  // normalize the result to a numeric exit code: commands may resolve to an
318
340
  // { exitCode, ...extra } object (e.g. `doctor`), and only the instrumented
319
341
  // path below unwraps it. Returning `run()` raw would leak that object all the
320
342
  // way to `process.exit(obj)` in the bin entry → ERR_INVALID_ARG_TYPE crash
321
343
  // (exit 1) for every user without an OTLP endpoint configured.
322
- if (!config.enabled) return normalizeExitCode(await run());
323
-
324
- // Generate trace context before run() so REST calls can forward it as traceparent.
325
- // The same IDs are reused in exportInvocation() to link the CLI span to REST spans.
326
- _activeTraceId = randHex(16);
327
- _activeSpanId = randHex(8);
344
+ if (!config.enabled) {
345
+ try {
346
+ return normalizeExitCode(await run());
347
+ } finally {
348
+ _activeTraceId = null;
349
+ _activeSpanId = null;
350
+ _activeSampled = false;
351
+ }
352
+ }
328
353
 
329
354
  const startMs = Date.now();
330
355
  let exitCode = 0;
@@ -389,6 +414,7 @@ export async function traceCommand(command, args, version, run) {
389
414
  } finally {
390
415
  _activeTraceId = null;
391
416
  _activeSpanId = null;
417
+ _activeSampled = false;
392
418
  }
393
419
  }
394
420
  }