@creator-notes/cnotes 0.113.4 → 0.115.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.115.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
@@ -58,9 +58,18 @@ Examples:
58
58
  }
59
59
  }
60
60
  console.log("");
61
- console.log("Relationship slugs (free-form; these are conventions, not an enum):");
62
- for (const slug of STATIC_SCHEMA.relationships.common) {
63
- console.log(` - ${slug}`);
61
+ const { usage, counted, common } = schema.relationships;
62
+ if (usage && usage.length > 0) {
63
+ console.log("Relationship slugs this workspace writes, most-linked first (free-form; reuse before coining):");
64
+ outputTable(["SLUG", "LINKS"], usage.map((u) => [u.slug, String(u.links)]));
65
+ if (counted)
66
+ console.log(` (${counted})`);
67
+ }
68
+ else {
69
+ console.log("Relationship slugs (the server's built-ins; free-form, not an enum):");
70
+ for (const slug of common) {
71
+ console.log(` - ${slug}`);
72
+ }
64
73
  }
65
74
  console.log("");
66
75
  console.log("Cross-reference syntax inside markdown:");
@@ -57,6 +57,19 @@ function renderImagesSection(section) {
57
57
  ]);
58
58
  outputTable(["ID", "FILE", "SCORE", "SEEN"], rows);
59
59
  }
60
+ /**
61
+ * A flag `search semantic` shares with its parent. Commander hands a flag to
62
+ * the parent `search` wherever it appears on the line, so semantic's own copy
63
+ * only ever held its default: `--canvas` and `--limit` were dropped with exit
64
+ * 0. Take the value from whichever command actually parsed it.
65
+ */
66
+ function sharedFlag(cmd, key) {
67
+ for (const c of [cmd, cmd.parent]) {
68
+ if (c?.getOptionValueSource(key) === "cli")
69
+ return c.getOptionValue(key);
70
+ }
71
+ return cmd.getOptionValue(key);
72
+ }
60
73
  export function registerSearchCommands(program) {
61
74
  const search = program
62
75
  .command("search")
@@ -156,15 +169,16 @@ Examples:
156
169
  $ cnotes search semantic "user retention"
157
170
  $ cnotes search semantic "checkout flow" --canvas <canvasId> --limit 20 --json
158
171
  `)
159
- .action(async (query, opts) => {
172
+ .action(async (query, _opts, cmd) => {
160
173
  const cfg = resolveConfig(program.opts());
161
174
  const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
175
+ const canvas = sharedFlag(cmd, "canvas");
162
176
  try {
163
177
  const data = await api.post("/api/semantic-search", {
164
178
  query,
165
179
  workspaceId: cfg.workspaceId,
166
- limit: parseInt(opts.limit, 10),
167
- ...(opts.canvas ? { canvasId: opts.canvas } : {}),
180
+ limit: parseInt(sharedFlag(cmd, "limit") ?? "10", 10) || 10,
181
+ ...(canvas ? { canvasId: canvas } : {}),
168
182
  });
169
183
  const results = data.results || data;
170
184
  if (cfg.json) {
@@ -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
  /**
@@ -6,25 +6,41 @@
6
6
  * slugs, resource field shapes, exit codes, and env vars. One source of truth
7
7
  * so the CLI and MCP surfaces never drift.
8
8
  */
9
+ /**
10
+ * The server's built-in relationship slugs, spelled as it seeds them
11
+ * (lib/constants/relationship-types.ts; build-schema.test.ts keeps the two in
12
+ * step). The schema falls back to these only when the workspace's own ranking
13
+ * cannot be read or the workspace has no links yet. A hand-written list used to
14
+ * stand here and sent agents to near-twins of what workspaces write
15
+ * (derives_from beside derived-from, related beside related-to), which split
16
+ * their backlinks.
17
+ */
18
+ export const BUILT_IN_RELATIONSHIP_SLUGS = [
19
+ "references",
20
+ "blocks",
21
+ "contradicts",
22
+ "depends-on",
23
+ "derived-from",
24
+ "duplicates",
25
+ "extends",
26
+ "implements",
27
+ "invalidates",
28
+ "part-of",
29
+ "related-to",
30
+ "supersedes",
31
+ "validates",
32
+ ];
9
33
  export const STATIC_SCHEMA = {
10
34
  relationships: {
11
- note: "Relationship slugs are free-form strings. The values below are common conventions, not an enum — the server accepts any string.",
12
- common: [
13
- "references",
14
- "supports",
15
- "blocks",
16
- "derives_from",
17
- "contradicts",
18
- "triggers",
19
- "related",
20
- ],
35
+ note: "Relationship slugs are free-form strings, not an enum: the server accepts any string. `common` is this workspace's own vocabulary, most-linked first (`usage` has the counts); reuse one of these spellings before coining a near-twin.",
36
+ common: [...BUILT_IN_RELATIONSHIP_SLUGS],
21
37
  },
22
38
  syntax: {
23
39
  noteMention: "[NOTE-12: Title](relationship:<type>)",
24
40
  batchPlaceholder: "[@key: Title](relationship:<type>) — '@key' is replaced with the new display ID after batch create",
25
41
  rules: [
26
42
  "`: Title` after the ID is optional. The server stamps the linked note's current title onto the chip when it saves; `[[<type>::NOTE-12]]` is the same link in wiki form.",
27
- "Pick the relationship slug from the verb your own prose uses: 'blocks X' → relationship:blocks, 'depends on X' → relationship:depends-on. Slugs are free-form (unknown ones auto-create); `cnotes rel types` lists the workspace vocabulary — reuse before coining.",
43
+ "Pick the relationship slug from the verb your own prose uses: 'blocks X' → relationship:blocks, 'depends on X' → relationship:depends-on. Slugs are free-form (unknown ones auto-create); `relationships.common` is the workspace's vocabulary, most-linked first, and `cnotes rel types` lists every slug — reuse before coining.",
28
44
  "Reserve `references` for pure citations. A verb narrated in prose around a `references` chip is invisible to backlinks and `rel list` — create/version responses flag these as `mentionWarnings`; treat each as a retype instruction.",
29
45
  ],
30
46
  },
@@ -72,6 +88,8 @@ export const STATIC_SCHEMA = {
72
88
  "5": "conflict (state collision)",
73
89
  "6": "rate-limited",
74
90
  "7": "permission denied",
91
+ "8": "subscription required or billing lockout (the JSON error carries upgradeUrl)",
92
+ "9": "network: the server could not be reached or the connection dropped (the hint says whether a write may have landed)",
75
93
  },
76
94
  env: {
77
95
  CNOTES_SERVER: "Override server URL",
@@ -86,19 +104,43 @@ export const STATIC_SCHEMA = {
86
104
  CLAUDE_CODE_SESSION_ID: "Auto-detected by Claude Code; stamped as agentSession kind=claude-code",
87
105
  },
88
106
  agentRun: {
89
- note: "Wrap multi-step canvas mutations in an agent-run so they show up as one revertable unit in the UI history.",
107
+ note: "Open a run before writing: `cnotes operations begin` brackets everything that follows (notes and canvases) as one entry in History, and a note create with a key outside a run is refused (422 operation_required). `canvas agent-run wrap` brackets one command's canvas mutations.",
108
+ begin: "cnotes operations begin --prompt \"<intent>\" …writes… cnotes operations end",
90
109
  wrap: "cnotes canvas agent-run wrap --canvas <id> --prompt \"<intent>\" -- <command>",
91
110
  },
92
111
  };
112
+ /**
113
+ * The relationships block: the workspace's own ranking when it has one, the
114
+ * server's built-in spellings when it has no links yet or the ranking could
115
+ * not be read.
116
+ */
117
+ function relationshipsFrom(usage) {
118
+ const ranked = (usage?.types ?? []).filter((t) => t.name && t.links > 0);
119
+ if (ranked.length === 0) {
120
+ return {
121
+ ...STATIC_SCHEMA.relationships,
122
+ note: "Relationship slugs are free-form strings, not an enum: the server accepts any string. `common` is the server's built-in vocabulary, because this workspace's own could not be read or it has no links yet; `cnotes rel types` lists every slug. Reuse one of these spellings before coining a near-twin.",
123
+ };
124
+ }
125
+ return {
126
+ note: STATIC_SCHEMA.relationships.note,
127
+ common: ranked.map((t) => t.name),
128
+ usage: ranked.map((t) => ({ slug: t.name, links: t.links })),
129
+ counted: usage?.complete
130
+ ? `distinct links per slug across all ${usage.linksRead ?? 0} link rows in this workspace`
131
+ : `distinct links per slug among the newest ${usage?.linksRead ?? 0} link rows in this workspace`,
132
+ };
133
+ }
93
134
  /**
94
135
  * Build the full schema document. The static metadata (exit codes, syntax,
95
- * resource shapes) is always present; the dynamic bits (workspace + types)
96
- * are fetched and any failures are reported in `dynamicFetchErrors` so callers
97
- * never treat a partial schema as authoritative.
136
+ * resource shapes) is always present; the dynamic bits (workspace, types and
137
+ * the relationship vocabulary) are fetched and any failures are reported in
138
+ * `dynamicFetchErrors` so callers never treat a partial schema as
139
+ * authoritative.
98
140
  */
99
141
  export async function buildSchema(api, workspaceId) {
100
142
  const dynamicFetchErrors = [];
101
- const [workspaceData, supertags] = await Promise.all([
143
+ const [workspaceData, supertags, relationshipUsage] = await Promise.all([
102
144
  api
103
145
  .get(`/api/workspaces/${workspaceId}`)
104
146
  .catch((err) => {
@@ -117,6 +159,15 @@ export async function buildSchema(api, workspaceId) {
117
159
  });
118
160
  return [];
119
161
  }),
162
+ api
163
+ .get("/api/relationship-types/usage", { workspaceId })
164
+ .catch((err) => {
165
+ dynamicFetchErrors.push({
166
+ resource: "relationships",
167
+ error: err instanceof Error ? err.message : String(err),
168
+ });
169
+ return null;
170
+ }),
120
171
  ]);
121
172
  const workspaceRecord = workspaceData
122
173
  ? (workspaceData.workspace ??
@@ -147,5 +198,6 @@ export async function buildSchema(api, workspaceId) {
147
198
  types,
148
199
  ...(dynamicFetchErrors.length > 0 ? { dynamicFetchErrors } : {}),
149
200
  ...STATIC_SCHEMA,
201
+ relationships: relationshipsFrom(relationshipUsage),
150
202
  };
151
203
  }
@@ -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
+ }
@@ -12,8 +12,27 @@ export function setOutputMode(next) {
12
12
  /** Envelope keys that hold a response's rows, in the order we look for them. */
13
13
  const ROW_KEYS = ["results", "items", "comments", "plans", "drafts", "all", "keys"];
14
14
  /**
15
- * Find the rows in a response: the array itself, or the array inside a known
16
- * envelope key (`notes create` → results, `comments list` → comments, …).
15
+ * The sections of a sectioned envelope (`search` →
16
+ * `{ sections: { notes: { results }, canvases: { results } } }`), whose rows
17
+ * sit one level down. A section that failed carries `error` and no results.
18
+ */
19
+ function sectionsOf(data) {
20
+ if (!data || typeof data !== "object" || Array.isArray(data))
21
+ return null;
22
+ const sections = data.sections;
23
+ if (!sections || typeof sections !== "object" || Array.isArray(sections))
24
+ return null;
25
+ const values = Object.values(sections);
26
+ if (!values.every((s) => s && typeof s === "object" && !Array.isArray(s)))
27
+ return null;
28
+ if (!values.some((s) => Array.isArray(s.results)))
29
+ return null;
30
+ return sections;
31
+ }
32
+ /**
33
+ * Find the rows in a response: the array itself, the array inside a known
34
+ * envelope key (`notes create` → results, `comments list` → comments, …), or
35
+ * every section's results in order (`search`).
17
36
  */
18
37
  function findRows(data) {
19
38
  if (Array.isArray(data))
@@ -25,6 +44,10 @@ function findRows(data) {
25
44
  if (Array.isArray(rec[key]))
26
45
  return { rows: rec[key], key };
27
46
  }
47
+ const sections = sectionsOf(data);
48
+ if (sections) {
49
+ return { rows: Object.values(sections).flatMap((s) => (Array.isArray(s.results) ? s.results : [])) };
50
+ }
28
51
  return null;
29
52
  }
30
53
  /**
@@ -33,7 +56,8 @@ function findRows(data) {
33
56
  * just the keys they need (e.g. `--fields displayId,title`) instead of paying
34
57
  * for the full record in their context window. When none of the fields sit on
35
58
  * an envelope itself, they are applied to its rows instead, so
36
- * `notes create --fields key,displayId` trims `.results[]`.
59
+ * `notes create --fields key,displayId` trims `.results[]` and
60
+ * `search --fields displayId,title` trims each section's results.
37
61
  */
38
62
  export function projectFields(data, fields) {
39
63
  if (!fields || fields.length === 0)
@@ -53,6 +77,14 @@ export function projectFields(data, fields) {
53
77
  return data.map(pick);
54
78
  const found = findRows(data);
55
79
  const rec = data;
80
+ const sections = sectionsOf(data);
81
+ if (sections && rec && !fields.some((f) => f in rec)) {
82
+ const trimmed = {};
83
+ for (const [name, s] of Object.entries(sections)) {
84
+ trimmed[name] = Array.isArray(s.results) ? { ...s, results: s.results.map(pick) } : s;
85
+ }
86
+ return { ...rec, sections: trimmed };
87
+ }
56
88
  if (found?.key && rec && !fields.some((f) => f in rec)) {
57
89
  return { ...rec, [found.key]: found.rows.map(pick) };
58
90
  }
@@ -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/dist/program.js CHANGED
@@ -100,6 +100,7 @@ Examples:
100
100
  Exit codes:
101
101
  0 ok 1 generic 2 auth 3 validation
102
102
  4 not-found 5 conflict 6 rate-limit 7 permission
103
+ 8 subscription/billing 9 network
103
104
 
104
105
  Env vars:
105
106
  CNOTES_SERVER, CNOTES_TOKEN, CNOTES_WORKSPACE, CNOTES_JSON=1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creator-notes/cnotes",
3
- "version": "0.113.4",
3
+ "version": "0.115.0",
4
4
  "description": "CLI for CreatorNotes — create notes, build canvases, search knowledge from the terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -60,7 +60,7 @@ Other writes that belong together (notes on two canvases, a change that needs se
60
60
 
61
61
  1. **The exit code is the verdict.** `0` is success. Never decide success from the body, and never re-run a write because a key looked empty: a second `notes create` duplicates the batch.
62
62
  2. **Knowledge lives in typed notes.** Text cards, lists, section frames, edges and portals arrange and label; they are unversioned, unsearchable and uncitable. If a future reader needs to find, cite or trust it, it is a note. A text card holds at most three sentences (the orientation banner: four short lines).
63
- 3. **Name notes with titled, typed mentions.** `[NOTE-12: Title](relationship:<verb>)`, with the verb your sentence uses (`blocks`, `depends-on`, `answered-by`). A bare `NOTE-12` in prose creates no link and is a defect, in note bodies and on canvas cards. `references` is for pure citation only. Reuse the workspace's types (`cnotes rel types`) before coining one.
63
+ 3. **Name notes with titled, typed mentions.** `[NOTE-12: Title](relationship:<verb>)`, with the verb your sentence uses (`blocks`, `depends-on`, `answered-by`). A bare `NOTE-12` in prose creates no link and is a defect, in note bodies and on canvas cards. `references` is for pure citation only. Reuse the workspace's types (`cnotes schema` ranks them by use; `cnotes rel types` lists all) before coining one.
64
64
  4. **Edges are local to one canvas.** When an edge connects two notes, write the same relationship as a mention in a note body, or it exists nowhere off that canvas.
65
65
  5. **Place declaratively, edit in place.** Use `canvas place` / `canvas arrange`, never hand-computed x/y. Add to a section with `place --into SECTION-n` (or `--section` on a single add); tidy one with `arrange --section SECTION-n`. Change a text card with `canvas update-text` and a frame with `canvas update-section`. Deleting and re-adding mints new ids and drops edges and `[[SECTION-n]]` mentions.
66
66
  6. **Content changes are versions.** `cnotes versions create` changes a note's body (the `# h1` is its title); fetch the current body first and edit that, since people edit between sessions. `notes update` changes metadata only (type, tags, pin, archive).
@@ -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.
@@ -269,7 +269,7 @@ each note is judged again; a new label alone keeps them.
269
269
  > — from [[quotes::TRANSCRIPT-4@v5]] v5, 12 Oct 2026, 4:55 pm
270
270
  ```
271
271
  It is a hard copy: the version never changes, so the block never goes stale, and saving it records a `quotes` relationship pinned to v5. Say what the quote means in your own sentences around it.
272
- - **Reuse an existing relationship type before inventing one.** Run `cnotes rel types` (or read the list printed by `cnotes workspace current`) and pick the closest existing label. The type slot is free-form, so an unknown label is auto-created as a custom workspace type rather than dropped — but that means a typo or a needless synonym (`support` vs `supports`, `relates-to` vs `related-to`) silently pollutes the workspace's type vocabulary forever. Only coin a new type when nothing existing fits.
272
+ - **Reuse an existing relationship type before inventing one.** `cnotes schema` lists the workspace's slugs most-linked first (`cnotes rel types` lists every one); pick the closest existing label. The type slot is free-form, so an unknown label is auto-created as a custom workspace type rather than dropped — but that means a typo or a needless synonym (`support` vs `supports`, `relates-to` vs `related-to`) silently pollutes the workspace's type vocabulary forever. Only coin a new type when nothing existing fits.
273
273
  - Names are normalized to lowercase + hyphens, so `Depends On`, `depends on`, and `depends-on` all resolve to the same type. When `cnotes notes create` does create new types, it reports them (`+ created N new relationship types: …`) — treat that line as a prompt to double-check you didn't mean an existing one.
274
274
  - Common built-in types to reach for first:
275
275
  - `depends-on` / `blocks` — dependency ordering between notes