@creator-notes/cnotes 0.113.4 → 0.114.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "creator-notes-cli",
3
- "version": "0.113.4",
3
+ "version": "0.114.0",
4
4
  "description": "CreatorNotes CLI: create notes, build canvases, search knowledge from the terminal",
5
5
  "author": {
6
6
  "name": "CreatorNotes",
package/README.md CHANGED
@@ -332,7 +332,9 @@ cp $(npm root -g)/@creator-notes/cnotes/skills/cnotes/SKILL.md .claude/skills/cn
332
332
 
333
333
  `cnotes query` keeps a SQLite copy of the workspace's note metadata (titles, types, tags, canvases, who made each note, judged answers; never a note body) under `~/.cnotes/local-db/`, syncs what changed since the last call, and answers from the copy. The query itself runs in milliseconds; each call first reads the workspace head and what changed, a second or two on a 5,000-note workspace, and the first copy takes about a minute at that size. The web app's Query panel uses the same copy format, so the two never disagree.
334
334
 
335
- A copy on disk is the person's decision, as it is in the web app: it is off until `cnotes config set-local-db on` (or `CNOTES_LOCAL_DB=on` in the environment). Until then `cnotes query`, and the `cnotes_query` MCP tool, refuse and say so. `set-local-db off` deletes every copy; `cnotes query --forget` deletes one workspace's.
335
+ A copy on disk is the person's decision, as it is in the web app: it is off until `cnotes config set-local-db on` (or `CNOTES_LOCAL_DB=on` in the environment), which copies the current workspace right away. Until then `cnotes query`, and the `cnotes_query` MCP tool, refuse and say so. `set-local-db off` deletes every copy; `cnotes query --forget` deletes one workspace's.
336
+
337
+ With the copy on, `cnotes notes list` and the `cnotes_notes_list` MCP tool answer type, tag, title-text, pin and no-canvas lists from it as well, in the same row shape, counting every note. A list within 30 seconds of a sync, with no write from this machine since, reads only the file; otherwise it syncs first, so a note you just wrote is always there. Dimension filters ask the server, and so does any list when the copy cannot answer (no copy of that workspace yet, a copy from another cnotes version). One stderr line says which answered: `From the local copy, synced 12 s ago.` or `From the server: <why>.`
336
338
 
337
339
  ```bash
338
340
  cnotes query pricing --type Decision,Insight # words in the title, AND across fields
@@ -1,9 +1,51 @@
1
1
  import { isLocalDbEnabled, loadConfig, setCurrentServer, setLocalDb } from "../lib/auth-store.js";
2
- import { forgetLocalCopies } from "../lib/local-db-store.js";
2
+ import { ApiClient } from "../lib/api-client.js";
3
+ import { resolveConfig } from "../lib/config.js";
4
+ import { forgetLocalCopies, openLocalCopy } from "../lib/local-db-store.js";
3
5
  import { ValidationError } from "../lib/errors.js";
4
6
  import { validateServerUrl, unofficialServerWarning } from "../lib/server-url.js";
5
7
  import { handleError } from "../lib/errors.js";
6
8
  import { outputJson } from "../lib/output.js";
9
+ /** The first copy of the selected workspace, with progress on stderr; null when there is none to make or it failed. */
10
+ async function copyCurrentWorkspace(program, json) {
11
+ let resolved;
12
+ try {
13
+ resolved = resolveConfig(program.opts());
14
+ }
15
+ catch {
16
+ return null; // Not signed in or no workspace yet: the first `cnotes query` after that copies it.
17
+ }
18
+ const api = new ApiClient(resolved.serverUrl, resolved.token, resolved.workspaceId);
19
+ const started = Date.now();
20
+ if (!json)
21
+ console.error("Copying the current workspace now (about a minute for 5,000 notes)...");
22
+ let shown = 0;
23
+ try {
24
+ const opened = await openLocalCopy({
25
+ api,
26
+ workspaceId: resolved.workspaceId,
27
+ enabled: true,
28
+ onStatus: (status) => {
29
+ if (json || status.copied - shown < 500)
30
+ return;
31
+ shown = status.copied;
32
+ console.error(` ${shown} notes copied`);
33
+ },
34
+ });
35
+ const notes = opened.status.counts.notes;
36
+ opened.store.close();
37
+ const ms = Date.now() - started;
38
+ if (!json)
39
+ console.error(`Copied ${notes} notes in ${Math.round(ms / 1000)} s.`);
40
+ return { notes, ms };
41
+ }
42
+ catch (error) {
43
+ if (!json) {
44
+ console.error(`The copy could not be made now (${error instanceof Error ? error.message : String(error)}); the next \`cnotes query\` makes it.`);
45
+ }
46
+ return null;
47
+ }
48
+ }
7
49
  export function registerConfigCommands(program) {
8
50
  const config = program
9
51
  .command("config")
@@ -54,7 +96,7 @@ export function registerConfigCommands(program) {
54
96
  });
55
97
  config
56
98
  .command("set-local-db")
57
- .description("Allow (on) or refuse (off) a local copy of workspace note metadata on this machine; off deletes every copy")
99
+ .description("Allow (on) or refuse (off) a local copy of workspace note metadata on this machine; on copies the current workspace now, off deletes every copy")
58
100
  .argument("<on|off>", "on or off")
59
101
  .action(async (value) => {
60
102
  const json = program.opts().json ?? false;
@@ -65,11 +107,18 @@ export function registerConfigCommands(program) {
65
107
  const cfg = loadConfig();
66
108
  setLocalDb(cfg, setting);
67
109
  const forgot = setting === "off" ? forgetLocalCopies(null) : 0;
68
- if (json) {
69
- outputJson({ localDb: setting, forgot });
110
+ if (setting === "on") {
111
+ if (!json) {
112
+ console.log("Local copies allowed. `notes list` and `cnotes query` answer from each workspace's note metadata (never a body), kept under the cnotes config directory.");
113
+ }
114
+ // Copy the current workspace now, so no later list waits a minute
115
+ // for it. The setting stands even when this fails.
116
+ const copied = await copyCurrentWorkspace(program, json);
117
+ if (json)
118
+ outputJson({ localDb: setting, forgot, copied });
70
119
  }
71
- else if (setting === "on") {
72
- console.log("Local copies allowed. `cnotes query` keeps each workspace's note metadata (never a body) under the cnotes config directory.");
120
+ else if (json) {
121
+ outputJson({ localDb: setting, forgot });
73
122
  }
74
123
  else {
75
124
  console.log(`Local copies refused${forgot ? `; deleted ${forgot} file${forgot === 1 ? "" : "s"}` : ""}.`);
@@ -6,6 +6,8 @@ import { outputJson, outputTable, outputQuiet, timeAgo, truncate } from "../lib/
6
6
  import { readHeadlineWarnings, reportHeadlineWarnings } from "../lib/headline-warnings.js";
7
7
  import { resolveNoteId } from "../lib/resolve-note.js";
8
8
  import { formatNoteDimensionLines, parseDimensionFilter, readNoteDimensions } from "../lib/note-dimensions.js";
9
+ import { isLocalDbEnabled } from "../lib/auth-store.js";
10
+ import { explainTruncation, listNotes, SERVER_LIST_CAP } from "../lib/notes-list.js";
9
11
  import { formatLinkedItemHeading, groupLinkedByRelation, parseExpandArgs, projectExpandPayload, renderExpandContentOnly, } from "../lib/expand-notes.js";
10
12
  import { resolveNoteBatchItems } from "../lib/note-batch.js";
11
13
  import { describeUnresolvedMentions, lintNarratedVerbMentions, lintPlainTextDisplayIdsBatch, hasGenericMention, fetchRelationshipTypeOptions, } from "../lib/mention-lint.js";
@@ -19,8 +21,8 @@ export function registerNotesCommands(program) {
19
21
  notes
20
22
  .command("list")
21
23
  .description("List notes in the current workspace")
22
- .option("--search <query>", "Full-text search")
23
- .option("--type <type>", "Filter by note type")
24
+ .option("--search <text>", "Text in the title or display id (for words inside notes, use `cnotes search`)")
25
+ .option("--type <type>", "Filter by note type (comma-separated for several)")
24
26
  .option("--tags <tags>", "Filter by tags (comma-separated)")
25
27
  .option("--pinned", "Only show pinned notes")
26
28
  .option("--no-canvas", "Only notes that are on no canvas at all, at most 500 per list (combines with --type, --tags, --limit)")
@@ -41,6 +43,11 @@ Dimensions are readings from live links, declared per type: a Question is
41
43
  answered when a link joins it to its answer ([QUESTION-12: Title](relationship:answers)
42
44
  on that note, or answered-by on the Question). Write that link whenever a note
43
45
  settles a Question. \`notes get\` prints each dimension under the title.
46
+
47
+ With the local copy on (cnotes config set-local-db on), --type, --tags,
48
+ --search, --pinned and --no-canvas are answered from it and count every note;
49
+ dimension filters ask the server. stderr says which answered. To count or
50
+ group notes, use \`cnotes query\`.
44
51
  `)
45
52
  .action(async (opts) => {
46
53
  const cfg = resolveConfig(program.opts());
@@ -79,56 +86,35 @@ settles a Question. \`notes get\` prints each dimension under the title.
79
86
  else if (opts.answered) {
80
87
  dimension = ["answered", "answered"];
81
88
  }
82
- const params = {
83
- workspaceId: cfg.workspaceId,
84
- notOnCanvas: notOnCanvas ? "true" : undefined,
85
- // The server applies the limit for this scan, so ask for what will show.
86
- limit: notOnCanvas ? String(parseInt(opts.limit, 10) || 20) : undefined,
89
+ const limit = parseInt(opts.limit, 10) || 20;
90
+ const answer = await listNotes(api, cfg.workspaceId, {
87
91
  search: opts.search,
88
- types: shortcuts > 0 ? "Question" : opts.type,
89
- dimension: dimension?.[0],
90
- state: dimension?.[1],
91
- waitsOnMe: opts.needsMe ? "true" : undefined,
92
- tags: opts.tags,
93
- onlyPinned: opts.pinned ? "true" : undefined,
94
- excludeDrafts: "true",
95
- excludeContent: "true",
96
- };
97
- let truncated = null;
98
- const notesList = await api.get("/api/notes", params, (headers) => {
99
- truncated = headers.get("X-Cnotes-Truncated");
100
- });
101
- // stderr, so --json stdout stays valid JSON. A --no-canvas list is
102
- // often counted, and a silently short list reads as "that's all".
103
- if (truncated === "limit") {
104
- console.error("Stopped at 500 notes, the most one --no-canvas list returns. Narrow it with --type or --tags to see the rest.");
105
- }
106
- else if (truncated === "scan") {
107
- console.error("Stopped early: more notes on no canvas may exist. Narrow the list with --type or --tags to see them.");
108
- }
109
- else if (truncated === "dimension-limit") {
110
- console.error("Checked 500 notes, the most one list reads; others of this type were not checked. Narrow it with --tags to see the rest.");
111
- }
112
- else if (truncated === "dimension-links") {
113
- console.error("Some notes have more links than one read covers, so a match may be missing. Check a note with `cnotes notes get`.");
114
- }
115
- // The server caps results (and ignores `limit` when a search/type
116
- // filter is active), so apply the requested limit here. This also
117
- // fixes the JSON path, which previously emitted the entire result
118
- // set regardless of --limit.
119
- const limit = parseInt(opts.limit, 10);
120
- const all = Array.isArray(notesList) ? notesList : [];
92
+ types: shortcuts > 0 ? ["Question"] : opts.type ? String(opts.type).split(",").map((t) => t.trim()).filter(Boolean) : undefined,
93
+ tags: opts.tags ? String(opts.tags).split(",").map((t) => t.trim()).filter(Boolean) : undefined,
94
+ pinned: !!opts.pinned,
95
+ notOnCanvas,
96
+ dimension,
97
+ waitsOnMe: !!opts.needsMe,
98
+ }, { limit });
99
+ // stderr, so --json stdout stays valid JSON: which source answered,
100
+ // and why a list may be short. A short list must never read as "that's all".
101
+ if (answer.route)
102
+ console.error(answer.route);
103
+ const partial = explainTruncation(answer.truncated, isLocalDbEnabled());
104
+ if (partial)
105
+ console.error(partial);
106
+ const all = answer.notes;
107
+ // The server returns at most 500 rows; past that the count is a floor.
108
+ const total = answer.from === "server" && answer.total >= SERVER_LIST_CAP ? `${answer.total}+` : String(answer.total);
121
109
  if (cfg.json) {
122
110
  const shown = all.slice(0, limit);
123
- if (all.length > shown.length) {
124
- // stderr keeps stdout valid JSON while still signalling to the
125
- // caller (often an agent) that the list was truncated.
126
- console.error(`Showing ${shown.length} of ${all.length} — raise --limit to see more.`);
111
+ if (answer.total > shown.length) {
112
+ console.error(`Showing ${shown.length} of ${total}. Raise --limit to see more.`);
127
113
  }
128
114
  outputJson(shown, cfg.fields);
129
115
  return;
130
116
  }
131
- await displayNotesList(all, limit, cfg, api, "notes found — select to view:");
117
+ await displayNotesList(all, limit, cfg, api, "notes found — select to view:", { total, count: answer.total });
132
118
  }
133
119
  catch (error) {
134
120
  handleError(error, cfg.json);
@@ -949,7 +935,9 @@ Examples:
949
935
  /**
950
936
  * Display a list of notes with interactive selection or plain table.
951
937
  */
952
- async function displayNotesList(notesList, limit, cfg, api, message) {
938
+ async function displayNotesList(notesList, limit, cfg, api, message,
939
+ /** How many matched, when the rows given are fewer (a list from the local copy). */
940
+ matched) {
953
941
  const sliced = Array.isArray(notesList) ? notesList.slice(0, limit) : [];
954
942
  if (sliced.length === 0) {
955
943
  console.log("No notes found.");
@@ -980,8 +968,9 @@ async function displayNotesList(notesList, limit, cfg, api, message) {
980
968
  n.updatedAt ? timeAgo(n.updatedAt) : "",
981
969
  ]);
982
970
  outputTable(["ID", "TITLE", "UPDATED"], rows);
983
- if (notesList.length > sliced.length) {
984
- console.log(`\nShowing ${sliced.length} of ${notesList.length} — raise --limit to see more.`);
971
+ const count = matched?.count ?? notesList.length;
972
+ if (count > sliced.length) {
973
+ console.log(`\nShowing ${sliced.length} of ${matched?.total ?? notesList.length}. Raise --limit to see more.`);
985
974
  }
986
975
  }
987
976
  /**
@@ -197,7 +197,8 @@ milliseconds.
197
197
 
198
198
  A copy on this machine is the person's decision: it is off until
199
199
  \`cnotes config set-local-db on\` (or CNOTES_LOCAL_DB=on). \`set-local-db off\`
200
- deletes every copy; --forget deletes this workspace's.
200
+ deletes every copy; --forget deletes this workspace's. With the copy on,
201
+ \`cnotes notes list\` answers from it too.
201
202
 
202
203
  Examples:
203
204
  $ cnotes query pricing --type Decision,Insight
@@ -2,6 +2,7 @@ import { ApiError, asCliError, CliError, EXIT_CODES, isPermanentNetworkError, is
2
2
  import { loadConfig, getActiveAgentRunId, getServerConfig } from "./auth-store.js";
3
3
  import { inPlaceProposalId, resolveProposal } from "./config.js";
4
4
  import { detectAgentClient } from "./agent-client.js";
5
+ import { markLocalWrite } from "./local-write-mark.js";
5
6
  const MAX_RETRIES = 3;
6
7
  const RETRY_BASE_MS = 1000;
7
8
  function isRetryable(status) {
@@ -245,6 +246,9 @@ export class ApiClient {
245
246
  const respBody = await this.errorBody(res);
246
247
  throw new ApiError(res.status, respBody);
247
248
  }
249
+ // The local copy's sync is a read sent as POST; anything else may have written.
250
+ if (path !== "/api/local-db")
251
+ markLocalWrite();
248
252
  return this.parseJsonSafe(res);
249
253
  }
250
254
  async postFormData(path, buildFormData) {
@@ -271,6 +275,7 @@ export class ApiClient {
271
275
  const respBody = await this.errorBody(res);
272
276
  throw new ApiError(res.status, respBody);
273
277
  }
278
+ markLocalWrite();
274
279
  return res.json();
275
280
  }
276
281
  async put(path, body) {
@@ -284,6 +289,7 @@ export class ApiClient {
284
289
  const respBody = await this.errorBody(res);
285
290
  throw new ApiError(res.status, respBody);
286
291
  }
292
+ markLocalWrite();
287
293
  return this.parseJsonSafe(res);
288
294
  }
289
295
  async patch(path, body, params) {
@@ -303,6 +309,7 @@ export class ApiClient {
303
309
  const respBody = await this.errorBody(res);
304
310
  throw new ApiError(res.status, respBody);
305
311
  }
312
+ markLocalWrite();
306
313
  return this.parseJsonSafe(res);
307
314
  }
308
315
  async delete(path, body) {
@@ -316,6 +323,7 @@ export class ApiClient {
316
323
  const body = await this.errorBody(res);
317
324
  throw new ApiError(res.status, body);
318
325
  }
326
+ markLocalWrite();
319
327
  return this.parseJsonSafe(res);
320
328
  }
321
329
  /**
@@ -19,15 +19,15 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
19
19
  */
20
20
  import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
21
21
  import { join } from "node:path";
22
- import { getConfigDir, isLocalDbEnabled } from "./auth-store.js";
22
+ import { isLocalDbEnabled } from "./auth-store.js";
23
23
  import { CliError, NotFoundError } from "./errors.js";
24
+ import { lastLocalWriteAt, localDbDirectory } from "./local-write-mark.js";
25
+ import { getMeta, readPinnedNoteIds, setMeta } from "../local-db/apply.js";
24
26
  import { createLocalDbOps, openCopy } from "../local-db/ops.js";
25
- import { workspaceFilePrefix } from "../local-db/protocol.js";
27
+ import { localDbFileName, workspaceFilePrefix } from "../local-db/protocol.js";
28
+ import { SCHEMA_VERSION } from "../local-db/schema.js";
26
29
  import { IDLE_STATUS, WorkspaceSync } from "../local-db/sync.js";
27
- /** Where the copies live: one file per member per workspace. */
28
- export function localDbDirectory() {
29
- return join(getConfigDir(), "local-db");
30
- }
30
+ export { localDbDirectory };
31
31
  export const LOCAL_DB_OFF_MESSAGE = "A local copy of this workspace is not allowed on this machine yet.";
32
32
  export const LOCAL_DB_OFF_HINT = "cnotes query keeps the workspace's note metadata (titles, types, tags, canvases, who made each note, judged answers; never a note body) " +
33
33
  "in a SQLite file under the cnotes config directory. If the person agrees, they run `cnotes config set-local-db on`; " +
@@ -95,6 +95,7 @@ export class LocalCopyStore {
95
95
  Database;
96
96
  directory;
97
97
  handle = null;
98
+ sqlDb = null;
98
99
  ops = null;
99
100
  openPath = null;
100
101
  /** True when the last open created the tables, so this call copied the workspace from nothing. */
@@ -112,9 +113,16 @@ export class LocalCopyStore {
112
113
  get path() {
113
114
  return this.openPath;
114
115
  }
116
+ /** The open file as SQL, for reads the shared ops do not cover (`notes list`). */
117
+ get sql() {
118
+ if (!this.sqlDb)
119
+ throw new CliError("The local copy is not open yet.");
120
+ return this.sqlDb;
121
+ }
115
122
  close() {
116
123
  this.handle?.close();
117
124
  this.handle = null;
125
+ this.sqlDb = null;
118
126
  this.ops = null;
119
127
  this.openPath = null;
120
128
  }
@@ -131,6 +139,7 @@ export class LocalCopyStore {
131
139
  this.handle = new this.Database(path);
132
140
  this.openPath = path;
133
141
  const db = wrap(this.handle);
142
+ this.sqlDb = db;
134
143
  this.ops = createLocalDbOps(db);
135
144
  const opened = openCopy(db, true);
136
145
  this.fresh = opened.fresh;
@@ -198,13 +207,53 @@ export function forgetLocalCopies(workspaceId, directory = localDbDirectory()) {
198
207
  }
199
208
  return removed;
200
209
  }
210
+ /**
211
+ * Why a list cannot be answered from the copy without making one: `none` when
212
+ * this member has no copy of the workspace, `schema` when this cnotes version
213
+ * reads a newer layout and the copy must be made again. Either way a first
214
+ * copy takes about a minute for 5,000 notes, too long to hide inside a list.
215
+ */
216
+ export class NoLocalCopyError extends CliError {
217
+ reason;
218
+ constructor(reason) {
219
+ super(reason === "none" ? "There is no local copy of this workspace yet." : "The local copy must be made again for this cnotes version.");
220
+ this.reason = reason;
221
+ }
222
+ }
223
+ /** When this CLI last brought the copy up to date: the time it asked for the head, so a write after that is never counted as synced. */
224
+ const CLI_SYNCED_KEY = "cli_synced_at";
225
+ /** This workspace's copies on disk, one per member who used it here. */
226
+ export function localCopyFiles(workspaceId, directory = localDbDirectory()) {
227
+ if (!existsSync(directory))
228
+ return [];
229
+ const prefix = workspaceFilePrefix(workspaceId).replace(/^\//, "");
230
+ return readdirSync(directory).filter((name) => name.startsWith(prefix) && name.endsWith(".sqlite3"));
231
+ }
232
+ /** The layout version a copy was written with, read without touching it (opening through the store would drop a stale layout). */
233
+ function copySchemaVersion(Database, path) {
234
+ const handle = new Database(path);
235
+ try {
236
+ return Number(handle.prepare("PRAGMA user_version").all()[0]?.user_version ?? 0);
237
+ }
238
+ finally {
239
+ handle.close();
240
+ }
241
+ }
201
242
  export async function openLocalCopy(options) {
202
243
  if (!(options.enabled ?? isLocalDbEnabled()))
203
244
  throw new CliError(LOCAL_DB_OFF_MESSAGE, undefined, LOCAL_DB_OFF_HINT);
204
245
  const Database = await loadDatabase();
205
246
  const directory = options.directory ?? localDbDirectory();
206
247
  const store = new LocalCopyStore(Database, directory);
248
+ const askedAt = Date.now();
207
249
  const head = await fetchSyncHead(options.api, options.workspaceId);
250
+ if (head && options.onlyIfCopied) {
251
+ const path = join(directory, localDbFileName(head.userId, options.workspaceId).replace(/^\//, ""));
252
+ if (!existsSync(path))
253
+ throw new NoLocalCopyError("none");
254
+ if (copySchemaVersion(Database, path) !== SCHEMA_VERSION)
255
+ throw new NoLocalCopyError("schema");
256
+ }
208
257
  if (!head) {
209
258
  // Not a member any more, or the key is pinned to another workspace: the copy goes too.
210
259
  await store.call("forget", { workspaceId: options.workspaceId });
@@ -220,5 +269,42 @@ export async function openLocalCopy(options) {
220
269
  store.close();
221
270
  throw new CliError(`The local copy could not be synced: ${status.error ?? "unknown error"}`);
222
271
  }
272
+ setMeta(store.sql, CLI_SYNCED_KEY, String(askedAt));
223
273
  return { store, head, status };
224
274
  }
275
+ /** How long a sync stays good for a list when nothing was written from this machine since. */
276
+ export const LIST_MAX_AGE_MS = 30_000;
277
+ /**
278
+ * The copy for `notes list`: answered from the file with no server call when
279
+ * it was synced within `maxAgeMs` and nothing was written from this machine
280
+ * since, otherwise synced first (a head read and what changed). Never makes a
281
+ * copy from nothing: NoLocalCopyError, and the caller asks the server.
282
+ */
283
+ export async function openLocalCopyForList(options) {
284
+ if (!(options.enabled ?? isLocalDbEnabled()))
285
+ throw new CliError(LOCAL_DB_OFF_MESSAGE, undefined, LOCAL_DB_OFF_HINT);
286
+ const directory = options.directory ?? localDbDirectory();
287
+ const files = localCopyFiles(options.workspaceId, directory);
288
+ if (files.length === 0)
289
+ throw new NoLocalCopyError("none");
290
+ const Database = await loadDatabase();
291
+ // One member's copy: try it without asking the server anything.
292
+ if (files.length === 1 && copySchemaVersion(Database, join(directory, files[0])) === SCHEMA_VERSION) {
293
+ const store = new LocalCopyStore(Database, directory);
294
+ await store.call("open", { fileName: files[0], wipeFirst: false });
295
+ const syncedAt = Number(getMeta(store.sql, CLI_SYNCED_KEY) ?? 0);
296
+ const pinnedNoteIds = readPinnedNoteIds(store.sql);
297
+ const fresh = Date.now() - syncedAt < (options.maxAgeMs ?? LIST_MAX_AGE_MS) && lastLocalWriteAt(directory) < syncedAt;
298
+ if (fresh && pinnedNoteIds)
299
+ return { store, syncedAt, synced: false, pinnedNoteIds };
300
+ store.close();
301
+ }
302
+ const opened = await openLocalCopy({ api: options.api, workspaceId: options.workspaceId, directory, enabled: true, onlyIfCopied: true });
303
+ const pinnedNoteIds = readPinnedNoteIds(opened.store.sql);
304
+ if (!pinnedNoteIds) {
305
+ // A server older than the pins in the head: a list from here would mark every note unpinned.
306
+ opened.store.close();
307
+ throw new CliError("The server did not send pins with the copy.");
308
+ }
309
+ return { store: opened.store, syncedAt: Number(getMeta(opened.store.sql, CLI_SYNCED_KEY) ?? 0), synced: true, pinnedNoteIds };
310
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * When this machine last wrote to CreatorNotes, so a list answered from the
3
+ * local copy always shows the caller's own writes (read-your-writes): every
4
+ * successful write through ApiClient stamps the time, and a copy synced
5
+ * before the stamp is synced again before it answers. One stamp for every
6
+ * workspace and process on the machine; a stamp too many only costs a sync.
7
+ *
8
+ * Kept apart from local-db-store.ts, which loads the shared SQLite code: the
9
+ * ApiClient imports this on every call.
10
+ */
11
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { getConfigDir } from "./auth-store.js";
14
+ /** Where the copies live: one file per member per workspace. */
15
+ export function localDbDirectory() {
16
+ return join(getConfigDir(), "local-db");
17
+ }
18
+ const MARK = "last-write";
19
+ /** Stamp a write. Only where copies exist, and never fails the write it follows. */
20
+ export function markLocalWrite(directory = localDbDirectory(), at = Date.now()) {
21
+ try {
22
+ if (existsSync(directory))
23
+ writeFileSync(join(directory, MARK), String(at), { mode: 0o600 });
24
+ }
25
+ catch {
26
+ // A copy that cannot be marked is synced on its next stale read anyway.
27
+ }
28
+ }
29
+ /** Epoch ms of the last write from this machine, 0 when none was stamped. */
30
+ export function lastLocalWriteAt(directory = localDbDirectory()) {
31
+ try {
32
+ return Number(readFileSync(join(directory, MARK), "utf8")) || 0;
33
+ }
34
+ catch {
35
+ return 0;
36
+ }
37
+ }
@@ -0,0 +1,152 @@
1
+ import { isLocalDbEnabled } from "./auth-store.js";
2
+ /** The most rows one server list returns (GET /api/notes MAX_RESULTS_CAP). */
3
+ export const SERVER_LIST_CAP = 500;
4
+ const FIRST_COPY = "about a minute for 5,000 notes";
5
+ /** Why the copy cannot answer this filter, or null when it can. */
6
+ export function localListBlocker(filter) {
7
+ if (filter.dimension || filter.waitsOnMe) {
8
+ return "--open, --answered, --needs-me and --dimension read links the local copy does not hold";
9
+ }
10
+ return null;
11
+ }
12
+ /** Why a server list may be short (X-Cnotes-Truncated), as one line for stderr; null when it is whole. */
13
+ export function explainTruncation(truncated, localCopyOn) {
14
+ const widen = localCopyOn ? "" : " A local copy checks every note: ask the person about `cnotes config set-local-db on`.";
15
+ switch (truncated) {
16
+ case null:
17
+ return null;
18
+ case "limit":
19
+ return "Stopped at 500 notes, the most one --no-canvas list returns. Narrow it with --type or --tags to see the rest.";
20
+ case "scan":
21
+ return "Stopped early: more notes on no canvas may exist. Narrow the list with --type or --tags to see them.";
22
+ case "dimension-limit":
23
+ return "Checked 500 notes, the most one list reads; others of this type were not checked. Narrow it with --tags to see the rest.";
24
+ case "dimension-links":
25
+ return "Some notes have more links than one read covers, so a match may be missing. Check a note with `cnotes notes get`.";
26
+ case "window":
27
+ return `Checked only the most recently changed notes (up to 1,500), so older matches are missing. Filter by type to check every note of a type.${widen}`;
28
+ case "type-window":
29
+ return `This type has more notes than one list reads, so older ones may be missing.${widen}`;
30
+ default:
31
+ return `The server says this list may be incomplete (${truncated}).`;
32
+ }
33
+ }
34
+ const toIso = (ms) => (typeof ms === "number" ? new Date(ms).toISOString() : undefined);
35
+ /**
36
+ * The filter over the copy, as GET /api/notes answers it: the newest-changed
37
+ * first (a tie, as from one batch, newest-created first, the order the
38
+ * server's index reads), a tag list matching any tag, text matching the title
39
+ * or display id.
40
+ */
41
+ export function listFromCopy(db, filter, options) {
42
+ const where = [];
43
+ const params = [];
44
+ if (filter.types?.length) {
45
+ where.push(`n.type IN (${filter.types.map(() => "?").join(", ")})`);
46
+ params.push(...filter.types);
47
+ }
48
+ if (filter.tags?.length) {
49
+ where.push(`EXISTS (SELECT 1 FROM note_tags t WHERE t.note_id = n.id AND t.tag IN (${filter.tags.map(() => "?").join(", ")}))`);
50
+ params.push(...filter.tags);
51
+ }
52
+ if (filter.search) {
53
+ const text = filter.search.toLowerCase();
54
+ where.push("(instr(lower(coalesce(n.title, '')), ?) > 0 OR instr(lower(n.display_id), ?) > 0)");
55
+ params.push(text, text);
56
+ }
57
+ if (filter.notOnCanvas)
58
+ where.push("NOT EXISTS (SELECT 1 FROM placements p WHERE p.note_id = n.id)");
59
+ if (filter.pinned) {
60
+ where.push("n.id IN (SELECT value FROM json_each(?))");
61
+ params.push(JSON.stringify([...options.pinnedNoteIds]));
62
+ }
63
+ const clause = where.length ? `WHERE ${where.join(" AND ")}` : "";
64
+ const total = Number(db.all(`SELECT COUNT(*) AS n FROM notes n ${clause}`, params)[0]?.n ?? 0);
65
+ const rows = db.all(`SELECT n.id, n.display_id, n.title, n.type, n.created_by, n.source, n.created_at, n.updated_at,
66
+ (SELECT json_group_array(t.tag) FROM note_tags t WHERE t.note_id = n.id) AS tags
67
+ FROM notes n ${clause}
68
+ ORDER BY COALESCE(n.updated_at, n.created_at, 0) DESC, n.created_at DESC, n.display_id DESC
69
+ LIMIT ?`, [...params, options.limit]);
70
+ const notes = rows.map((r) => ({
71
+ id: r.id,
72
+ convexId: r.id,
73
+ displayId: r.display_id,
74
+ type: r.type,
75
+ title: r.title,
76
+ updatedAt: toIso(r.updated_at),
77
+ createdAt: toIso(r.created_at),
78
+ userId: r.created_by,
79
+ createdBySource: r.source ?? "human",
80
+ isArchived: false,
81
+ archivedAt: null,
82
+ isPinned: options.pinnedNoteIds.has(r.id),
83
+ isDraft: false,
84
+ workspaceId: options.workspaceId,
85
+ tags: JSON.parse(r.tags || "[]"),
86
+ }));
87
+ return { notes, total };
88
+ }
89
+ /** The server's answer, through GET /api/notes. */
90
+ async function listFromServer(api, workspaceId, filter, limit) {
91
+ const filtered = !!(filter.search || filter.types?.length || filter.tags?.length || filter.notOnCanvas || filter.pinned || filter.dimension || filter.waitsOnMe);
92
+ const params = {
93
+ workspaceId,
94
+ notOnCanvas: filter.notOnCanvas ? "true" : undefined,
95
+ // A filtered list comes back whole (up to 500) so the count is real; a
96
+ // plain one is the newest `limit`. --no-canvas scans until `limit` matches.
97
+ limit: filter.notOnCanvas || !filtered ? String(Math.min(limit, SERVER_LIST_CAP)) : undefined,
98
+ search: filter.search,
99
+ types: filter.types?.join(","),
100
+ dimension: filter.dimension?.[0],
101
+ state: filter.dimension?.[1],
102
+ waitsOnMe: filter.waitsOnMe ? "true" : undefined,
103
+ tags: filter.tags?.join(","),
104
+ onlyPinned: filter.pinned ? "true" : undefined,
105
+ excludeDrafts: "true",
106
+ excludeContent: "true",
107
+ };
108
+ let truncated = null;
109
+ const rows = await api.get("/api/notes", params, (headers) => {
110
+ truncated = headers.get("X-Cnotes-Truncated");
111
+ });
112
+ const notes = Array.isArray(rows) ? rows : [];
113
+ return { notes, total: notes.length, truncated };
114
+ }
115
+ export async function listNotes(api, workspaceId, filter, options) {
116
+ const enabled = options.enabled ?? isLocalDbEnabled();
117
+ const server = async (why) => ({
118
+ ...(await listFromServer(api, workspaceId, filter, options.limit)),
119
+ route: why === null ? null : `From the server: ${why}.`,
120
+ from: "server",
121
+ });
122
+ if (!enabled)
123
+ return server(null);
124
+ const blocked = localListBlocker(filter);
125
+ if (blocked)
126
+ return server(blocked);
127
+ // Loaded only with the copy on: the shared SQLite code is not free to import.
128
+ const { NoLocalCopyError, openLocalCopyForList } = await import("./local-db-store.js");
129
+ let copy;
130
+ try {
131
+ copy = await openLocalCopyForList({ api, workspaceId, directory: options.directory, enabled: true, maxAgeMs: options.maxAgeMs });
132
+ }
133
+ catch (err) {
134
+ if (err instanceof NoLocalCopyError) {
135
+ return server(err.reason === "none"
136
+ ? `there is no local copy of this workspace yet; \`cnotes query\` makes one (${FIRST_COPY})`
137
+ : `this cnotes version needs the local copy made again; \`cnotes query\` does it (${FIRST_COPY})`);
138
+ }
139
+ return server(`the local copy could not answer (${err instanceof Error ? err.message : String(err)})`);
140
+ }
141
+ try {
142
+ const { notes, total } = listFromCopy(copy.store.sql, filter, { workspaceId, pinnedNoteIds: copy.pinnedNoteIds, limit: options.limit });
143
+ const age = copy.synced ? "just now" : `${Math.max(0, Math.round((Date.now() - copy.syncedAt) / 1000))} s ago`;
144
+ return { notes, total, truncated: null, route: `From the local copy, synced ${age}.`, from: "local" };
145
+ }
146
+ catch (err) {
147
+ return server(`the local copy could not answer (${err instanceof Error ? err.message : String(err)})`);
148
+ }
149
+ finally {
150
+ copy.store.close();
151
+ }
152
+ }
@@ -82,9 +82,27 @@ export function applyHead(db, head) {
82
82
  db.run("DELETE FROM placements WHERE canvas_id = ?", [id]);
83
83
  clearLayout(db, id);
84
84
  }
85
+ if (head.pinnedNoteIds)
86
+ setMeta(db, PINNED_KEY, JSON.stringify(head.pinnedNoteIds));
87
+ else
88
+ db.run("DELETE FROM meta WHERE key = ?", [PINNED_KEY]);
85
89
  });
86
90
  return { canvasesToRefresh, dimensionsToRefresh };
87
91
  }
92
+ const PINNED_KEY = "pinned_note_ids";
93
+ /** The caller's pinned note ids from the last head, or null when that head did not carry them. */
94
+ export function readPinnedNoteIds(db) {
95
+ const raw = getMeta(db, PINNED_KEY);
96
+ if (raw === null)
97
+ return null;
98
+ try {
99
+ const ids = JSON.parse(raw);
100
+ return Array.isArray(ids) ? new Set(ids.map(String)) : null;
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
88
106
  function clearLayout(db, canvasId) {
89
107
  db.run("DELETE FROM layout_nodes WHERE canvas_id = ?", [canvasId]);
90
108
  db.run("DELETE FROM layout_edges WHERE canvas_id = ?", [canvasId]);
@@ -36,6 +36,8 @@ import { lintNarratedVerbMentions, lintPlainTextDisplayIds, lintPlainTextDisplay
36
36
  import { DECISION_CARD_RULE } from "./lib/decision-citation.js";
37
37
  import { parseReviewRef } from "./lib/review-helpers.js";
38
38
  import { runQuery } from "./commands/query.js";
39
+ import { isLocalDbEnabled } from "./lib/auth-store.js";
40
+ import { explainTruncation, listNotes, SERVER_LIST_CAP } from "./lib/notes-list.js";
39
41
  // ---------------------------------------------------------------------------
40
42
  // Environment
41
43
  // ---------------------------------------------------------------------------
@@ -138,24 +140,51 @@ server.resource("types", "cnotes://types", async () => ({
138
140
  // ---------------------------------------------------------------------------
139
141
  // Notes tools
140
142
  // ---------------------------------------------------------------------------
141
- server.tool("cnotes_notes_list", "List notes in the workspace. Returns metadata by default. Set includeContent=true to include full note content (useful to avoid multiple cnotes_notes_get calls).", {
142
- search: z.string().optional().describe("Full-text search query"),
143
- type: z.string().optional().describe("Filter by note type (e.g. Meeting, PRD)"),
143
+ server.tool("cnotes_notes_list", "List notes in the workspace, most recently changed first. Returns metadata by default; set includeContent=true for full content (saves cnotes_notes_get calls). " +
144
+ "With the local copy on, a list without content counts every note. A second text block says how many matched, which source answered, and whether the list may be short. " +
145
+ "To count or group notes, use cnotes_query.", {
146
+ search: z.string().optional().describe("Text in the title or display id (for words inside notes, use cnotes_search)"),
147
+ type: z.string().optional().describe("Filter by note type (e.g. Meeting, PRD); comma-separated for several"),
144
148
  tags: z.string().optional().describe("Filter by tags (comma-separated)"),
145
149
  pinned: z.boolean().optional().describe("Only show pinned notes"),
146
150
  limit: z.number().optional().default(20).describe("Max results"),
147
151
  includeContent: z.boolean().optional().default(false).describe("Include full note content in results"),
148
- }, async ({ search, type, tags, pinned, limit, includeContent }) => withErrorHandling(() => api.get("/api/notes", {
149
- workspaceId,
150
- search,
151
- types: type,
152
- tags,
153
- onlyPinned: pinned ? "true" : undefined,
154
- excludeDrafts: "true",
155
- excludeContent: includeContent ? undefined : "true",
156
- format: includeContent ? "markdown" : undefined,
157
- limit: String(limit ?? 20),
158
- })));
152
+ }, async ({ search, type, tags, pinned, limit, includeContent }) => {
153
+ const max = limit ?? 20;
154
+ if (includeContent) {
155
+ return withErrorHandling(async () => {
156
+ const rows = await api.get("/api/notes", {
157
+ workspaceId,
158
+ search,
159
+ types: type,
160
+ tags,
161
+ onlyPinned: pinned ? "true" : undefined,
162
+ excludeDrafts: "true",
163
+ format: "markdown",
164
+ limit: String(max),
165
+ });
166
+ return (Array.isArray(rows) ? rows : []).slice(0, max);
167
+ });
168
+ }
169
+ const split = (value) => value?.split(",").map((v) => v.trim()).filter(Boolean);
170
+ let answer;
171
+ try {
172
+ answer = await listNotes(api, workspaceId, { search, types: split(type), tags: split(tags), pinned: !!pinned }, { limit: max });
173
+ }
174
+ catch (e) {
175
+ return withErrorHandling(async () => {
176
+ throw e;
177
+ });
178
+ }
179
+ const shown = answer.notes.slice(0, max);
180
+ const total = answer.from === "server" && answer.total >= SERVER_LIST_CAP ? `${answer.total}+` : String(answer.total);
181
+ const notes = [
182
+ answer.route,
183
+ answer.total > shown.length ? `Showing ${shown.length} of ${total}. Raise limit to see more.` : `${shown.length} matched.`,
184
+ explainTruncation(answer.truncated, isLocalDbEnabled()),
185
+ ].filter((line) => !!line);
186
+ return { content: [...ok(shown).content, { type: "text", text: notes.join("\n") }] };
187
+ });
159
188
  server.tool("cnotes_query", "Ask a workspace-wide question over every note's metadata (title, type, tags, canvases, who made it, judged answers; never a body) and get the answer in milliseconds from a local copy of the workspace that syncs on each call. Filters AND across fields and OR within one. Use it to count, group or list notes across the whole workspace; use cnotes_notes_get for a note's content.", {
160
189
  text: z.string().optional().describe("Words that must all appear in the title or display id"),
161
190
  types: z.array(z.string()).optional().describe("Note types, e.g. ['Decision','Insight']"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creator-notes/cnotes",
3
- "version": "0.113.4",
3
+ "version": "0.114.0",
4
4
  "description": "CLI for CreatorNotes — create notes, build canvases, search knowledge from the terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -102,6 +102,7 @@ Every command follows one contract.
102
102
 
103
103
  - **Reads return data; writes return an envelope.** `notes list/get/search` emit a bare array (one note is `.[0]`). `notes create` returns `{ results, relationshipsCreated, rubrics?, hints? }`; read new notes from `results`. `canvas create` returns `{ canvas: { id, displayId, url } }` with `id`, `displayId` and `url` mirrored at the top level.
104
104
  - **Errors go to stderr** as `{ error, code, exitCode, hint }`. The `hint` names the command that fixes it; read it before retrying.
105
+ - **`notes list` says on stderr which source answered and whether the list may be short.** With the local copy on, type, tag, text, pin and no-canvas lists come from it, count every note, and include your own writes; read `Showing N of M` as the real count. A line saying older matches may be missing means exactly that: narrow the list or relay the hint, never report it as the whole. Counting or grouping is `cnotes query` ([references/more-commands.md](references/more-commands.md)).
105
106
  - **`cnotes auth status` and `cnotes whoami` exit 2 when no token is stored.** That means signed out. Exit 0 means a token is present. Do not treat exit 2 from status as a broken install.
106
107
  - **No `jq` needed.** `cnotes notes list --type Decision -q`, `cnotes notes create --notes '[...]' -q --fields key,displayId`, `CANVAS=$(cnotes canvas create "<name>" -q)`. Use a JSON parser only for nested values these flags cannot reach.
107
108
 
@@ -35,7 +35,15 @@ cnotes query --sql tables # the tables and their colu
35
35
  read-only SELECT (a write is refused). `--rebuild` drops the copy and copies
36
36
  again; `--forget` deletes this workspace's copy. Needs Node.js 22.13 or newer.
37
37
 
38
- The copy is off until the PERSON allows it: `cnotes config set-local-db on`.
38
+ With the copy on, `cnotes notes list` answers type, tag, text, pin and
39
+ no-canvas lists from it too, with no extra step: inside 30 s of a sync and with
40
+ no write from this machine since, it reads only the file; otherwise it syncs
41
+ first, so your own writes always show. Dimension filters (`--open`,
42
+ `--answered`, `--needs-me`) ask the server. stderr says which answered:
43
+ `From the local copy, synced 12 s ago.` or `From the server: <why>.`
44
+
45
+ The copy is off until the PERSON allows it: `cnotes config set-local-db on`
46
+ (which copies the current workspace right away).
39
47
  If `cnotes query` refuses with that hint, tell the user what the copy holds
40
48
  (metadata, never a body) and ask them to run it; do not work around it with
41
49
  `notes list`. `set-local-db off` deletes every copy on the machine.