@creator-notes/cnotes 0.112.0 → 0.113.1

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.
@@ -0,0 +1,270 @@
1
+ // GENERATED from lib/local-db in the repository root: do not edit here.
2
+ // Change the source and run `npm --prefix cli run sync:local-db`.
3
+ /**
4
+ * Keeps the local workspace database in step with the server (PLAN-6KP3
5
+ * step 4).
6
+ *
7
+ * The caller hands every head it receives to `onHead`: the page from its
8
+ * `localDb.syncHead` subscription, the CLI from one `POST /api/local-db`
9
+ * read. The first head of a session opens the member's file and reconciles
10
+ * every note id (which also fills an empty copy); later heads pull only
11
+ * notes written since the newest one the copy holds. Canvases whose
12
+ * `changedAt` or note count moved have their placements read again, and a
13
+ * judged dimension's answers are read again when notes of its type changed
14
+ * or a judgment landed since they were read.
15
+ *
16
+ * Heads that arrive while a pass runs are coalesced: the latest one runs next.
17
+ *
18
+ * The database holds ONE open file. A disposed sync (the page moved to
19
+ * another workspace) must never write again, or its rows land in whichever
20
+ * file the next sync opened: every database call goes through `call`, which
21
+ * refuses once disposed.
22
+ *
23
+ * Runtime-neutral: nothing here touches the DOM, Convex or Node. The `cnotes`
24
+ * CLI runs a copy of this file (cli/src/local-db/, kept in step by
25
+ * `npm --prefix cli run sync:local-db`).
26
+ */
27
+ import { localDbFileName } from "./protocol.js";
28
+ export const IDLE_STATUS = {
29
+ phase: "idle",
30
+ persistent: false,
31
+ counts: { notes: 0, canvases: 0, placements: 0, answers: 0, bytes: 0 },
32
+ copied: 0,
33
+ syncedAt: null,
34
+ lastPassMs: null,
35
+ firstPassMs: null,
36
+ error: null,
37
+ };
38
+ /** Thrown by a pass whose sync was disposed mid-flight; never reaches the status. */
39
+ export class SyncDisposedError extends Error {
40
+ constructor() {
41
+ super("The sync was disposed.");
42
+ this.name = "SyncDisposedError";
43
+ }
44
+ }
45
+ const ID_PAGE = 1000;
46
+ const CHANGED_PAGE = 200;
47
+ const FETCH_CHUNK = 200;
48
+ /**
49
+ * Canvases per `placements` call. A canvas can hold thousands of cards, list
50
+ * nodes and list items, and one Convex query reads at most 16,384 documents,
51
+ * so a small batch keeps a workspace of large canvases syncable.
52
+ */
53
+ const PLACEMENT_CHUNK = 5;
54
+ const ANSWER_PAGE = 500;
55
+ /** Parallel note fetches during a reconcile. */
56
+ const FETCH_PARALLEL = 4;
57
+ const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
58
+ const chunks = (items, size) => {
59
+ const out = [];
60
+ for (let i = 0; i < items.length; i += size)
61
+ out.push(items.slice(i, i + size));
62
+ return out;
63
+ };
64
+ const dimensionKey = (d) => `${d.type}\u0000${d.key}`;
65
+ export class WorkspaceSync {
66
+ source;
67
+ db;
68
+ workspaceId;
69
+ onStatus;
70
+ options;
71
+ opened = false;
72
+ /** False until a pass has compared every note id this session. */
73
+ reconciled = false;
74
+ forgetOnOpen = false;
75
+ newest = 0;
76
+ running = false;
77
+ nextHead = null;
78
+ disposed = false;
79
+ status = IDLE_STATUS;
80
+ constructor(source, db, workspaceId, onStatus, options = {}) {
81
+ this.source = source;
82
+ this.db = db;
83
+ this.workspaceId = workspaceId;
84
+ this.onStatus = onStatus;
85
+ this.options = options;
86
+ }
87
+ dispose() {
88
+ this.disposed = true;
89
+ }
90
+ /** Throw away this workspace's copy and sync it again from scratch. */
91
+ rebuild(head) {
92
+ this.opened = false;
93
+ this.reconciled = false;
94
+ this.forgetOnOpen = true;
95
+ return this.onHead(head);
96
+ }
97
+ onHead(head) {
98
+ this.nextHead = head;
99
+ if (this.running)
100
+ return Promise.resolve();
101
+ return this.drain();
102
+ }
103
+ async drain() {
104
+ this.running = true;
105
+ try {
106
+ while (this.nextHead && !this.disposed) {
107
+ const head = this.nextHead;
108
+ this.nextHead = null;
109
+ await this.pass(head);
110
+ }
111
+ }
112
+ finally {
113
+ this.running = false;
114
+ }
115
+ }
116
+ emit(patch) {
117
+ if (this.disposed)
118
+ return;
119
+ this.status = { ...this.status, ...patch };
120
+ this.onStatus(this.status);
121
+ }
122
+ /** Every database call: refused once disposed, so no row of this workspace reaches another's file. */
123
+ call(op, args) {
124
+ if (this.disposed)
125
+ return Promise.reject(new SyncDisposedError());
126
+ return this.db.call(op, args);
127
+ }
128
+ async open(head) {
129
+ this.emit({ phase: "opening", error: null });
130
+ if (this.forgetOnOpen) {
131
+ // A rebuild drops this workspace's files only; other workspaces' copies stay.
132
+ await this.call("forget", { workspaceId: this.workspaceId });
133
+ this.forgetOnOpen = false;
134
+ }
135
+ const opened = await this.call("open", {
136
+ fileName: localDbFileName(head.userId, this.workspaceId),
137
+ wipeFirst: this.options.wipePending?.() ?? false,
138
+ });
139
+ this.options.clearWipePending?.();
140
+ this.opened = true;
141
+ this.newest = opened.fresh ? 0 : opened.newestNoteUpdatedAt;
142
+ const every = this.options.reconcileEvery;
143
+ if (every !== undefined && !opened.fresh && Date.now() - opened.reconciledAt < every)
144
+ this.reconciled = true;
145
+ this.emit({ persistent: opened.persistent });
146
+ }
147
+ async pass(head) {
148
+ const start = now();
149
+ try {
150
+ if (!this.opened)
151
+ await this.open(head);
152
+ this.emit({ phase: "syncing", copied: 0 });
153
+ const full = !this.reconciled;
154
+ const { canvasesToRefresh, dimensionsToRefresh } = await this.call("applyHead", head);
155
+ const changedTypes = full ? await this.reconcile() : await this.pullChanged(head);
156
+ this.reconciled = true;
157
+ await this.pullPlacements(canvasesToRefresh);
158
+ await this.pullAnswers(head, full ? null : changedTypes, dimensionsToRefresh);
159
+ await this.call("setNewest", this.newest);
160
+ const counts = await this.call("counts", null);
161
+ const ms = now() - start;
162
+ this.emit({
163
+ phase: "ready",
164
+ counts,
165
+ syncedAt: Date.now(),
166
+ lastPassMs: ms,
167
+ firstPassMs: this.status.firstPassMs ?? ms,
168
+ error: null,
169
+ });
170
+ }
171
+ catch (err) {
172
+ if (err instanceof SyncDisposedError)
173
+ return;
174
+ this.emit({ phase: "error", error: err instanceof Error ? err.message : String(err) });
175
+ }
176
+ }
177
+ track(rows, types) {
178
+ let copied = this.status.copied;
179
+ for (const row of rows) {
180
+ this.newest = Math.max(this.newest, row.updatedAt ?? 0);
181
+ if (!row.removed) {
182
+ types.add(row.type);
183
+ copied += 1;
184
+ }
185
+ }
186
+ if (copied !== this.status.copied)
187
+ this.emit({ copied });
188
+ }
189
+ /** Every note id against the copy: drops what the server no longer holds, fetches what changed. */
190
+ async reconcile() {
191
+ const ids = [];
192
+ let cursor = null;
193
+ for (;;) {
194
+ const page = await this.source.noteIds(cursor, ID_PAGE);
195
+ ids.push(...page.page);
196
+ if (page.isDone)
197
+ break;
198
+ cursor = page.continueCursor;
199
+ }
200
+ for (const row of ids)
201
+ this.newest = Math.max(this.newest, row.updatedAt ?? 0);
202
+ const { toFetch } = await this.call("reconcile", ids);
203
+ await this.call("markReconciled", Date.now());
204
+ const types = new Set();
205
+ const batches = chunks(toFetch, FETCH_CHUNK);
206
+ for (const group of chunks(batches, FETCH_PARALLEL)) {
207
+ const results = await Promise.all(group.map((batch) => this.source.notesByIds(batch)));
208
+ for (const rows of results) {
209
+ this.track(rows, types);
210
+ await this.call("applyNotes", rows);
211
+ }
212
+ }
213
+ return types;
214
+ }
215
+ /**
216
+ * Notes written since the newest one the copy holds. The mark is inclusive
217
+ * (`gte` on the server): a note committed with the same millisecond
218
+ * `updatedAt` as the one the last pass ended on, after that pass read, must
219
+ * not be skipped. The boundary note is upserted again, which is idempotent.
220
+ */
221
+ async pullChanged(head) {
222
+ const types = new Set();
223
+ if (head.newestNoteUpdatedAt < this.newest)
224
+ return types;
225
+ const since = this.newest;
226
+ let cursor = null;
227
+ for (;;) {
228
+ const page = await this.source.notesChangedSince(since, cursor, CHANGED_PAGE);
229
+ this.track(page.page, types);
230
+ await this.call("applyNotes", page.page);
231
+ if (page.isDone)
232
+ break;
233
+ cursor = page.continueCursor;
234
+ }
235
+ return types;
236
+ }
237
+ async pullPlacements(canvasIds) {
238
+ for (const batch of chunks(canvasIds, PLACEMENT_CHUNK)) {
239
+ const rows = await this.source.placements(batch);
240
+ await this.call("applyPlacements", rows);
241
+ }
242
+ }
243
+ /**
244
+ * Every dimension on the first pass; afterwards, those whose type had notes
245
+ * change and those the head says gained a judgment since they were read.
246
+ */
247
+ async pullAnswers(head, changedTypes, toRefresh) {
248
+ const refresh = new Set(toRefresh.map(dimensionKey));
249
+ for (const dim of head.dimensions) {
250
+ if (changedTypes && !changedTypes.has(dim.type) && !refresh.has(dimensionKey(dim)))
251
+ continue;
252
+ let cursor = null;
253
+ let firstPage = true;
254
+ for (;;) {
255
+ const page = await this.source.dimensionAnswers(dim.supertagId, dim.key, cursor, ANSWER_PAGE);
256
+ await this.call("applyAnswers", {
257
+ type: dim.type,
258
+ key: dim.key,
259
+ rows: page.page,
260
+ firstPage,
261
+ answersAt: dim.newestAnswerAt,
262
+ });
263
+ firstPage = false;
264
+ if (page.isDone)
265
+ break;
266
+ cursor = page.continueCursor;
267
+ }
268
+ }
269
+ }
270
+ }
@@ -0,0 +1,8 @@
1
+ // GENERATED from lib/local-db in the repository root: do not edit here.
2
+ // Change the source and run `npm --prefix cli run sync:local-db`.
3
+ /**
4
+ * Shapes shared by the local workspace database's worker, sync loop and UI
5
+ * (experiment `workspaceQuery`). Server rows mirror convex/localDb.ts with ids
6
+ * as plain strings, so the worker never imports Convex.
7
+ */
8
+ export {};
@@ -35,6 +35,7 @@ import { attachRubricsToResults, loadRubricMap, rubricsForTypes, } from "./lib/r
35
35
  import { lintNarratedVerbMentions, lintPlainTextDisplayIds, lintPlainTextDisplayIdsBatch, hasGenericMention, fetchRelationshipTypeOptions, } from "./lib/mention-lint.js";
36
36
  import { DECISION_CARD_RULE } from "./lib/decision-citation.js";
37
37
  import { parseReviewRef } from "./lib/review-helpers.js";
38
+ import { runQuery } from "./commands/query.js";
38
39
  // ---------------------------------------------------------------------------
39
40
  // Environment
40
41
  // ---------------------------------------------------------------------------
@@ -155,6 +156,37 @@ server.tool("cnotes_notes_list", "List notes in the workspace. Returns metadata
155
156
  format: includeContent ? "markdown" : undefined,
156
157
  limit: String(limit ?? 20),
157
158
  })));
159
+ 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
+ text: z.string().optional().describe("Words that must all appear in the title or display id"),
161
+ types: z.array(z.string()).optional().describe("Note types, e.g. ['Decision','Insight']"),
162
+ canvases: z.array(z.string()).optional().describe("Canvases by CANVAS-<n> display id or name"),
163
+ tags: z.array(z.string()).optional(),
164
+ madeBy: z.array(z.enum(["human", "agent", "api", "import"])).optional().describe("How the notes were made"),
165
+ by: z.string().optional().describe("A member whose name contains this"),
166
+ groupBy: z
167
+ .string()
168
+ .optional()
169
+ .describe("type (default), canvas, tag, month, person, made-by, none, or '<Type>:<dimension>' for a judged dimension"),
170
+ limit: z.number().int().min(1).max(2000).optional().describe("Rows to return (default 100)"),
171
+ sql: z.string().optional().describe("One read-only SELECT against the copy instead of a filter; 'tables' lists the tables"),
172
+ rebuild: z.boolean().optional().describe("Drop the local copy and copy the workspace again"),
173
+ }, async ({ text, types, canvases, tags, madeBy, by, groupBy, limit, sql, rebuild }) => withErrorHandling(async () => {
174
+ const answer = await runQuery(api, workspaceId, text ? [text] : [], {
175
+ type: types?.join(","),
176
+ canvas: canvases?.join(","),
177
+ tag: tags?.join(","),
178
+ madeBy: madeBy?.join(","),
179
+ by,
180
+ groupBy,
181
+ limit: limit === undefined ? undefined : String(limit),
182
+ sql,
183
+ rebuild,
184
+ });
185
+ if (answer.kind === "notes")
186
+ return answer.json;
187
+ const { kind: _kind, ...rest } = answer;
188
+ return rest;
189
+ }));
158
190
  server.tool("cnotes_notes_get", "Get one or more notes by display ID (e.g. MEETING-12, PRD-3). Always returns an array, in input order, in a single round-trip. Pass one ID for one note, or many IDs to batch-fetch — never call this tool multiple times in parallel for different IDs. Set expand=true to also return the notes they link to (outgoing relationship rows and inline [[rel::ID]] / [[ID]] mentions) as { notes, linked, truncated, cap, omitted, notice }.", {
159
191
  ids: z
160
192
  .array(z.string())
package/dist/program.js CHANGED
@@ -15,6 +15,7 @@ import { registerRelationshipsCommands } from "./commands/relationships.js";
15
15
  import { registerDepsCommands } from "./commands/deps.js";
16
16
  import { registerGoalsCommands } from "./commands/goals.js";
17
17
  import { registerSearchCommands } from "./commands/search.js";
18
+ import { registerQueryCommands } from "./commands/query.js";
18
19
  import { registerTimelineCommands } from "./commands/timeline.js";
19
20
  import { registerReviewCommands } from "./commands/review.js";
20
21
  import { registerSharedCommands } from "./commands/shared.js";
@@ -119,6 +120,7 @@ Env vars:
119
120
  registerDepsCommands(program);
120
121
  registerGoalsCommands(program);
121
122
  registerSearchCommands(program);
123
+ registerQueryCommands(program);
122
124
  registerTimelineCommands(program);
123
125
  registerReviewCommands(program);
124
126
  registerSharedCommands(program);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creator-notes/cnotes",
3
- "version": "0.112.0",
3
+ "version": "0.113.1",
4
4
  "description": "CLI for CreatorNotes — create notes, build canvases, search knowledge from the terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,9 +24,10 @@
24
24
  "release:binaries": "node scripts/build-binaries.mjs --publish",
25
25
  "dev": "tsc --watch",
26
26
  "start": "node dist/cn.js",
27
- "test": "npm run build && node --experimental-transform-types --test \"src/**/*.test.ts\"",
27
+ "test": "npm run build && node scripts/sync-local-db.mjs --check && node --experimental-transform-types --test \"src/**/*.test.ts\"",
28
28
  "version": "node scripts/sync-plugin-version.mjs",
29
- "prepublishOnly": "npm run build"
29
+ "prepublishOnly": "npm run build",
30
+ "sync:local-db": "node scripts/sync-local-db.mjs"
30
31
  },
31
32
  "keywords": [
32
33
  "cli",
@@ -4,6 +4,7 @@ Focus plans, files and images, setup, theme, config, and sending feedback to the
4
4
 
5
5
  ## Contents
6
6
 
7
+ - [Query the workspace (`cnotes query`)](#query-the-workspace-cnotes-query)
7
8
  - [Focus plans (`cnotes focus`)](#focus-plans-cnotes-focus)
8
9
  - [Files (`cnotes files` / `cnotes f`)](#files-cnotes-files--cnotes-f)
9
10
  - [Init & MCP (`cnotes init` / `cnotes mcp`)](#init--mcp-cnotes-init--cnotes-mcp)
@@ -12,6 +13,27 @@ Focus plans, files and images, setup, theme, config, and sending feedback to the
12
13
  - [Feedback (`cnotes feedback`)](#feedback-cnotes-feedback)
13
14
  - [Closing the loop: submit feedback when you hit friction](#closing-the-loop-submit-feedback-when-you-hit-friction)
14
15
 
16
+ ## Query the workspace (`cnotes query`)
17
+
18
+ Workspace-wide questions over every note's metadata, answered from a local
19
+ SQLite copy in milliseconds instead of paged `notes list` reads. The first
20
+ call copies the workspace (a few seconds); later calls sync only what
21
+ changed. Never a note body: read those with `cnotes notes get`.
22
+
23
+ ```bash
24
+ cnotes query pricing --type Decision,Insight # words in the title; AND across fields
25
+ cnotes query --canvas CANVAS-12 --group-by tag # notes on one canvas, by tag
26
+ cnotes query --made-by agent --group-by month --json
27
+ cnotes query --group-by Risk:status # a judged dimension; `unjudged` is a group
28
+ cnotes query --sql "SELECT type, COUNT(*) AS n FROM notes GROUP BY type ORDER BY n DESC"
29
+ cnotes query --sql tables # the tables and their columns
30
+ ```
31
+
32
+ `--json` returns `{ total, groups, rows, sync, ms }`; rows carry `displayId`,
33
+ `title`, `type`, `updatedAt` and the group they fell in. `--sql` runs ONE
34
+ read-only SELECT (a write is refused). `--rebuild` drops the copy and copies
35
+ again. Needs Node.js 22.13 or newer.
36
+
15
37
  ## Focus plans (`cnotes focus`)
16
38
 
17
39
  Protected flow-state blocks, private to the user. The Focus calendar overlays