@creator-notes/cnotes 0.111.1 → 0.113.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +15 -0
- package/dist/commands/auth-keys.js +88 -4
- package/dist/commands/query.js +233 -0
- package/dist/lib/auth-store.js +4 -0
- package/dist/lib/local-db-store.js +200 -0
- package/dist/local-db/apply.js +166 -0
- package/dist/local-db/ops.js +102 -0
- package/dist/local-db/protocol.js +10 -0
- package/dist/local-db/query.js +184 -0
- package/dist/local-db/schema.js +83 -0
- package/dist/local-db/sync.js +270 -0
- package/dist/local-db/types.js +8 -0
- package/dist/mcp-server.js +32 -0
- package/dist/program.js +2 -0
- package/package.json +4 -3
- package/skills/cnotes/references/more-commands.md +22 -0
- package/skills/cnotes/references/operations.md +9 -0
package/README.md
CHANGED
|
@@ -50,6 +50,7 @@ cnotes search semantic "onboarding flow"
|
|
|
50
50
|
| `cnotes draft open\|status\|propose\|edits\|ask\|checkout\|dismiss` | | Private drafts: build many notes and canvases out of sight, propose edits to shared notes, and branch a shared board (`open --from-canvas CANVAS-n`) to rework your own copy of it. Run `status` until no check blocks, then `ask --reviewer <person>` and stop: only that person accepts it, in the browser; no key can merge it |
|
|
51
51
|
| `cnotes focus plan\|list\|cancel` | | Plan protected focus blocks; `--canvas` + `--target` land a block on the exact card it works on |
|
|
52
52
|
| `cnotes search semantic` | `cnotes s` | Semantic search across notes |
|
|
53
|
+
| `cnotes query` | `cnotes q` | Filter, group or run a SELECT over every note's metadata from a local SQLite copy of the workspace, synced on each call |
|
|
53
54
|
| `cnotes timeline` | `cnotes tl` | Recent activity feed |
|
|
54
55
|
| `cnotes relationships list` | `cnotes rel` | Note relationships |
|
|
55
56
|
| `cnotes types list\|create\|update` | `cnotes t` | Manage note types (supertags) |
|
|
@@ -326,6 +327,20 @@ mkdir -p .claude/skills/cnotes
|
|
|
326
327
|
cp $(npm root -g)/@creator-notes/cnotes/skills/cnotes/SKILL.md .claude/skills/cnotes/SKILL.md
|
|
327
328
|
```
|
|
328
329
|
|
|
330
|
+
## Query the local copy (`cnotes query`)
|
|
331
|
+
|
|
332
|
+
`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 in milliseconds. The web app's Query panel uses the same copy format, so the two never disagree.
|
|
333
|
+
|
|
334
|
+
```bash
|
|
335
|
+
cnotes query pricing --type Decision,Insight # words in the title, AND across fields
|
|
336
|
+
cnotes query --canvas CANVAS-12 --group-by tag # notes on one canvas, grouped by tag
|
|
337
|
+
cnotes query --made-by agent --group-by month # what agents wrote, by month
|
|
338
|
+
cnotes query --sql "SELECT type, COUNT(*) AS n FROM notes GROUP BY type ORDER BY n DESC"
|
|
339
|
+
cnotes query --rebuild # drop this workspace's copy and copy it again
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
`--group-by` takes `type`, `canvas`, `tag`, `month`, `person`, `made-by`, `none`, or `<Type>:<dimension>` for a judged dimension. `--sql` runs one read-only SELECT (`--sql tables` prints the tables). Needs Node.js 22.13 or newer.
|
|
343
|
+
|
|
329
344
|
## Scripting
|
|
330
345
|
|
|
331
346
|
```bash
|
|
@@ -1,11 +1,93 @@
|
|
|
1
1
|
import { ApiClient } from "../lib/api-client.js";
|
|
2
|
+
import { BRAND } from "../lib/brand.js";
|
|
2
3
|
import { resolveBaseConfig } from "../lib/config.js";
|
|
3
4
|
import { handleError, ValidationError } from "../lib/errors.js";
|
|
4
|
-
import { outputJson } from "../lib/output.js";
|
|
5
|
+
import { outputJson, outputQuiet } from "../lib/output.js";
|
|
6
|
+
const MINUTE_MS = 60_000;
|
|
7
|
+
const LIFETIME_UNIT_MS = { m: MINUTE_MS, h: 60 * MINUTE_MS, d: 24 * 60 * MINUTE_MS };
|
|
8
|
+
/** `--expires 30m | 2h | 1d` in milliseconds, within the server's 1 minute to 24 hours. */
|
|
9
|
+
export function parseKeyLifetime(value) {
|
|
10
|
+
const match = /^(\d+)\s*([mhd])$/i.exec(value.trim());
|
|
11
|
+
if (!match) {
|
|
12
|
+
throw new ValidationError(`--expires takes a lifetime like 30m, 2h or 1d, not "${value}".`);
|
|
13
|
+
}
|
|
14
|
+
const ms = Number(match[1]) * LIFETIME_UNIT_MS[match[2].toLowerCase()];
|
|
15
|
+
if (ms < MINUTE_MS || ms > LIFETIME_UNIT_MS.d) {
|
|
16
|
+
throw new ValidationError("A child key lives between 1 minute and 24 hours (--expires 1m to 24h).");
|
|
17
|
+
}
|
|
18
|
+
return ms;
|
|
19
|
+
}
|
|
20
|
+
/** The environment that hands a child key to the agent it was minted for. */
|
|
21
|
+
export function childKeyEnv(child, serverUrl) {
|
|
22
|
+
const server = serverUrl && serverUrl !== BRAND.url ? `CNOTES_SERVER=${serverUrl} ` : "";
|
|
23
|
+
return `${server}CNOTES_TOKEN=${child.key} CNOTES_WORKSPACE=${child.workspaceId}`;
|
|
24
|
+
}
|
|
25
|
+
function describeKey(k, now) {
|
|
26
|
+
const tags = [];
|
|
27
|
+
if (k.source === "child")
|
|
28
|
+
tags.push(`child of ${k.parentKeyId ?? "a revoked key"}`);
|
|
29
|
+
if (k.source === "oauth")
|
|
30
|
+
tags.push("connector");
|
|
31
|
+
if (k.workspaceId)
|
|
32
|
+
tags.push(`pinned to ${k.workspaceId}`);
|
|
33
|
+
if (k.expiresAt && k.expiresAt < now)
|
|
34
|
+
tags.push("expired");
|
|
35
|
+
return tags.length ? ` (${tags.join(", ")})` : "";
|
|
36
|
+
}
|
|
5
37
|
export function registerAuthKeysCommands(auth, program) {
|
|
6
38
|
const keys = auth
|
|
7
39
|
.command("keys")
|
|
8
|
-
.description("
|
|
40
|
+
.description("Create child keys for agents you start, and list and revoke CLI API keys");
|
|
41
|
+
keys
|
|
42
|
+
.command("create")
|
|
43
|
+
.description("Mint a key for one agent you are about to start: named, pinned to one workspace, expiring within 24 hours")
|
|
44
|
+
.requiredOption("--name <name>", 'Who the key is for, as History should show it (e.g. "Seat 3 · Notion PM")')
|
|
45
|
+
.option("--expires <lifetime>", "How long it lives: 30m, 2h (the default) or up to 24h")
|
|
46
|
+
.addHelpText("after", `
|
|
47
|
+
The key is pinned to the workspace -w names (else your current one), acts with
|
|
48
|
+
your role there, and is shown once. Every run the agent opens is labelled with
|
|
49
|
+
its name in History. Revoking your own key revokes every child it minted.
|
|
50
|
+
Only a key from \`cnotes auth login\` can mint; a child or a connector token cannot.
|
|
51
|
+
|
|
52
|
+
Examples:
|
|
53
|
+
$ cnotes auth keys create --name "Seat 3 · Notion PM" --expires 90m
|
|
54
|
+
$ CHILD=$(cnotes auth keys create --name "Verifier · undo" -q) # just the key
|
|
55
|
+
$ CNOTES_TOKEN=$CHILD CNOTES_WORKSPACE=<workspaceId> cnotes notes list`)
|
|
56
|
+
.action(async (opts) => {
|
|
57
|
+
const json = program.opts().json ?? false;
|
|
58
|
+
try {
|
|
59
|
+
const cfg = resolveBaseConfig(program.opts());
|
|
60
|
+
if (!cfg.token)
|
|
61
|
+
throw new ValidationError("Not authenticated. Run `cnotes auth login` first.");
|
|
62
|
+
if (!cfg.workspaceId) {
|
|
63
|
+
throw new ValidationError("No workspace to pin the key to.", "Pass -w <workspaceId> or run `cnotes workspace use`.");
|
|
64
|
+
}
|
|
65
|
+
const ttlMs = opts.expires !== undefined ? parseKeyLifetime(opts.expires) : undefined;
|
|
66
|
+
const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
|
|
67
|
+
const child = await api.post("/api/auth/cli-keys", {
|
|
68
|
+
name: opts.name,
|
|
69
|
+
workspaceId: cfg.workspaceId,
|
|
70
|
+
...(ttlMs !== undefined ? { ttlMs } : {}),
|
|
71
|
+
});
|
|
72
|
+
if (program.opts().quiet) {
|
|
73
|
+
outputQuiet(child.key);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (json) {
|
|
77
|
+
outputJson({ ...child, env: childKeyEnv(child, cfg.serverUrl) });
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
console.log(`Child key "${child.name}", pinned to ${child.workspaceId}, expires ${new Date(child.expiresAt).toISOString()}.`);
|
|
81
|
+
console.log("Shown once. Hand it to that agent only:");
|
|
82
|
+
console.log("");
|
|
83
|
+
console.log(` ${childKeyEnv(child, cfg.serverUrl)} cnotes ...`);
|
|
84
|
+
console.log("");
|
|
85
|
+
console.log(`Revoke just this one with: cnotes auth keys revoke ${child.keyId}`);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
handleError(error, json);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
9
91
|
keys
|
|
10
92
|
.command("list")
|
|
11
93
|
.description("List CLI API keys (metadata only — not the secret values)")
|
|
@@ -27,6 +109,7 @@ export function registerAuthKeysCommands(auth, program) {
|
|
|
27
109
|
return;
|
|
28
110
|
}
|
|
29
111
|
console.log("CLI API keys:");
|
|
112
|
+
const now = Date.now();
|
|
30
113
|
for (const k of rows) {
|
|
31
114
|
const last = k.lastUsedAt
|
|
32
115
|
? new Date(k.lastUsedAt).toISOString()
|
|
@@ -34,7 +117,7 @@ export function registerAuthKeysCommands(auth, program) {
|
|
|
34
117
|
const exp = k.expiresAt
|
|
35
118
|
? new Date(k.expiresAt).toISOString()
|
|
36
119
|
: "never";
|
|
37
|
-
console.log(` ${k.id} ${k.name}`);
|
|
120
|
+
console.log(` ${k.id} ${k.name}${describeKey(k, now)}`);
|
|
38
121
|
console.log(` created: ${new Date(k.createdAt).toISOString()} last used: ${last} expires: ${exp}`);
|
|
39
122
|
}
|
|
40
123
|
}
|
|
@@ -58,7 +141,8 @@ export function registerAuthKeysCommands(auth, program) {
|
|
|
58
141
|
outputJson(result);
|
|
59
142
|
}
|
|
60
143
|
else {
|
|
61
|
-
|
|
144
|
+
const children = result.childrenRevoked ?? 0;
|
|
145
|
+
console.log(`Revoked CLI API key ${keyId}${children ? `, and the ${children} child key${children === 1 ? "" : "s"} it minted` : ""}`);
|
|
62
146
|
}
|
|
63
147
|
}
|
|
64
148
|
catch (error) {
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { ApiClient } from "../lib/api-client.js";
|
|
2
|
+
import { resolveConfig } from "../lib/config.js";
|
|
3
|
+
import { ValidationError, handleError } from "../lib/errors.js";
|
|
4
|
+
import { outputJson, timeAgo, truncate } from "../lib/output.js";
|
|
5
|
+
import { openLocalCopy } from "../lib/local-db-store.js";
|
|
6
|
+
import { SCHEMA_HINT } from "../local-db/schema.js";
|
|
7
|
+
import { UNJUDGED } from "../local-db/query.js";
|
|
8
|
+
const GROUPS = {
|
|
9
|
+
type: "type",
|
|
10
|
+
canvas: "canvas",
|
|
11
|
+
tag: "tag",
|
|
12
|
+
month: "month",
|
|
13
|
+
person: "author",
|
|
14
|
+
author: "author",
|
|
15
|
+
"made-by": "source",
|
|
16
|
+
source: "source",
|
|
17
|
+
none: "none",
|
|
18
|
+
};
|
|
19
|
+
const SOURCES = new Set(["human", "agent", "import", "api"]);
|
|
20
|
+
const list = (value) => value
|
|
21
|
+
?.split(",")
|
|
22
|
+
.map((v) => v.trim())
|
|
23
|
+
.filter(Boolean);
|
|
24
|
+
/** A canvas by display id (CANVAS-12), by name, or by Convex id. */
|
|
25
|
+
function resolveCanvas(ref, head) {
|
|
26
|
+
const lower = ref.toLowerCase();
|
|
27
|
+
const hit = head.canvases.find((c) => c.id === ref || c.displayId?.toLowerCase() === lower || c.name.toLowerCase() === lower);
|
|
28
|
+
if (!hit) {
|
|
29
|
+
throw new ValidationError(`No canvas "${ref}" in this workspace.`, "Pass a CANVAS-<n> display id or the canvas name; `cnotes canvas list` shows both.");
|
|
30
|
+
}
|
|
31
|
+
return hit.id;
|
|
32
|
+
}
|
|
33
|
+
/** Members whose name contains the text, case-insensitively. */
|
|
34
|
+
function resolveAuthors(text, head) {
|
|
35
|
+
const lower = text.toLowerCase();
|
|
36
|
+
const ids = head.members.filter((m) => (m.name ?? "").toLowerCase().includes(lower)).map((m) => m.userId);
|
|
37
|
+
if (ids.length === 0)
|
|
38
|
+
throw new ValidationError(`No member named "${text}" in this workspace.`);
|
|
39
|
+
return ids;
|
|
40
|
+
}
|
|
41
|
+
/** Turn the command's words and flags into the shared filter and grouping. */
|
|
42
|
+
export function parseQuery(words, opts, head) {
|
|
43
|
+
const filter = {};
|
|
44
|
+
const text = words.join(" ").trim();
|
|
45
|
+
if (text)
|
|
46
|
+
filter.text = text;
|
|
47
|
+
const types = list(opts.type);
|
|
48
|
+
if (types?.length)
|
|
49
|
+
filter.types = types;
|
|
50
|
+
const canvases = list(opts.canvas);
|
|
51
|
+
if (canvases?.length)
|
|
52
|
+
filter.canvasIds = canvases.map((c) => resolveCanvas(c, head));
|
|
53
|
+
const tags = list(opts.tag);
|
|
54
|
+
if (tags?.length)
|
|
55
|
+
filter.tags = tags;
|
|
56
|
+
const sources = list(opts.madeBy);
|
|
57
|
+
if (sources?.length) {
|
|
58
|
+
const bad = sources.find((s) => !SOURCES.has(s));
|
|
59
|
+
if (bad)
|
|
60
|
+
throw new ValidationError(`--made-by takes human, agent, api or import, not "${bad}".`);
|
|
61
|
+
filter.sources = sources;
|
|
62
|
+
}
|
|
63
|
+
if (opts.by)
|
|
64
|
+
filter.authors = resolveAuthors(opts.by, head);
|
|
65
|
+
const groupBy = parseGroupBy(opts.groupBy, head);
|
|
66
|
+
const limit = opts.limit ? parseInt(opts.limit, 10) : 100;
|
|
67
|
+
if (!Number.isFinite(limit) || limit < 1)
|
|
68
|
+
throw new ValidationError("--limit must be a positive number.");
|
|
69
|
+
return { filter, groupBy, limit };
|
|
70
|
+
}
|
|
71
|
+
export function parseGroupBy(value, head) {
|
|
72
|
+
if (!value)
|
|
73
|
+
return "type";
|
|
74
|
+
const known = GROUPS[value.toLowerCase()];
|
|
75
|
+
if (known)
|
|
76
|
+
return known;
|
|
77
|
+
// "<Type>:<dimension>" names a judged dimension, by its key or its label.
|
|
78
|
+
const [type, dim] = value.split(":");
|
|
79
|
+
const match = head.dimensions.find((d) => d.type.toLowerCase() === type?.toLowerCase() && (d.key.toLowerCase() === dim?.toLowerCase() || d.label.toLowerCase() === dim?.toLowerCase()));
|
|
80
|
+
if (match)
|
|
81
|
+
return `dimension:${match.type}:${match.key}`;
|
|
82
|
+
const choices = [...Object.keys(GROUPS).filter((k) => k !== "author" && k !== "source"), ...head.dimensions.map((d) => `${d.type}:${d.key}`)];
|
|
83
|
+
throw new ValidationError(`Unknown --group-by "${value}".`, `One of: ${choices.join(", ")}.`);
|
|
84
|
+
}
|
|
85
|
+
/** The JSON shape `--json` prints. */
|
|
86
|
+
export function toJsonResult(result, head, status) {
|
|
87
|
+
const canvasNames = new Map(head.canvases.map((c) => [c.id, c.displayId ?? c.name]));
|
|
88
|
+
return {
|
|
89
|
+
total: result.total,
|
|
90
|
+
groups: result.groups.map((g) => ({ value: g.value, label: g.label, count: g.count })),
|
|
91
|
+
rows: result.rows.map((r) => ({
|
|
92
|
+
id: r.id,
|
|
93
|
+
displayId: r.display_id,
|
|
94
|
+
title: r.title,
|
|
95
|
+
type: r.type,
|
|
96
|
+
updatedAt: r.updated_at,
|
|
97
|
+
group: r.group_label,
|
|
98
|
+
})),
|
|
99
|
+
shown: result.rows.length,
|
|
100
|
+
ms: Math.round(result.ms * 10) / 10,
|
|
101
|
+
sync: syncSummary(status),
|
|
102
|
+
canvases: Object.fromEntries(canvasNames),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export function syncSummary(status) {
|
|
106
|
+
return {
|
|
107
|
+
notes: status.counts.notes,
|
|
108
|
+
canvases: status.counts.canvases,
|
|
109
|
+
bytes: status.counts.bytes,
|
|
110
|
+
firstCopy: status.firstPassMs != null && status.firstPassMs === status.lastPassMs,
|
|
111
|
+
ms: status.lastPassMs == null ? null : Math.round(status.lastPassMs),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Lines for the terminal: a heading per group, then `ID title when` rows. */
|
|
115
|
+
export function renderResult(result, groupBy) {
|
|
116
|
+
const lines = [];
|
|
117
|
+
if (result.total === 0)
|
|
118
|
+
return ["No notes match."];
|
|
119
|
+
let current = null;
|
|
120
|
+
for (const row of result.rows) {
|
|
121
|
+
if (groupBy !== "none" && row.group_key !== current) {
|
|
122
|
+
current = row.group_key;
|
|
123
|
+
const count = result.groups.find((g) => `${g.value}` === row.group_key)?.count ?? 0;
|
|
124
|
+
if (lines.length)
|
|
125
|
+
lines.push("");
|
|
126
|
+
lines.push(`${row.group_label} (${count})`);
|
|
127
|
+
}
|
|
128
|
+
const when = row.updated_at ? timeAgo(row.updated_at) : "";
|
|
129
|
+
lines.push(` ${row.display_id.padEnd(16)} ${truncate(row.title || "Untitled", 60).padEnd(60)} ${when}`);
|
|
130
|
+
}
|
|
131
|
+
const shown = new Set(result.rows.map((r) => r.id)).size;
|
|
132
|
+
lines.push("");
|
|
133
|
+
lines.push(`${result.total} ${result.total === 1 ? "note" : "notes"}` +
|
|
134
|
+
(shown < result.total ? ` · showing ${shown}; raise --limit for more` : "") +
|
|
135
|
+
` · ${result.ms < 10 ? result.ms.toFixed(1) : Math.round(result.ms)} ms`);
|
|
136
|
+
return lines;
|
|
137
|
+
}
|
|
138
|
+
export function renderSql(out) {
|
|
139
|
+
const lines = [];
|
|
140
|
+
if (out.columns.length === 0)
|
|
141
|
+
return ["No rows."];
|
|
142
|
+
const widths = out.columns.map((c, i) => Math.max(c.length, ...out.rows.map((r) => String(r[i] ?? "").length)));
|
|
143
|
+
lines.push(out.columns.map((c, i) => c.padEnd(widths[i])).join(" "));
|
|
144
|
+
lines.push(widths.map((w) => "-".repeat(w)).join(" "));
|
|
145
|
+
for (const row of out.rows)
|
|
146
|
+
lines.push(row.map((cell, i) => String(cell ?? "").padEnd(widths[i])).join(" "));
|
|
147
|
+
lines.push("");
|
|
148
|
+
lines.push(`${out.rows.length}${out.truncated ? "+" : ""} rows · ${out.ms < 10 ? out.ms.toFixed(1) : Math.round(out.ms)} ms`);
|
|
149
|
+
return lines;
|
|
150
|
+
}
|
|
151
|
+
const SQL_MAX_ROWS = 500;
|
|
152
|
+
/** Everything `cnotes query` and the MCP tool share: sync, ask, shape the answer. */
|
|
153
|
+
export async function runQuery(api, workspaceId, words, opts, directory) {
|
|
154
|
+
const opened = await openLocalCopy({ api, workspaceId, rebuild: opts.rebuild, directory });
|
|
155
|
+
try {
|
|
156
|
+
if (opts.sql !== undefined) {
|
|
157
|
+
if (opts.sql.trim().toLowerCase() === "tables") {
|
|
158
|
+
return { kind: "tables", tables: SCHEMA_HINT, sync: syncSummary(opened.status) };
|
|
159
|
+
}
|
|
160
|
+
const out = opened.store.db.sql({ sql: opts.sql, maxRows: SQL_MAX_ROWS });
|
|
161
|
+
return { kind: "sql", ...out, sync: syncSummary(opened.status) };
|
|
162
|
+
}
|
|
163
|
+
const { filter, groupBy, limit } = parseQuery(words, opts, opened.head);
|
|
164
|
+
const result = opened.store.db.query({ filter, groupBy, limit });
|
|
165
|
+
return { kind: "notes", result, groupBy, json: toJsonResult(result, opened.head, opened.status) };
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
opened.store.close();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
export function registerQueryCommands(program) {
|
|
172
|
+
program
|
|
173
|
+
.command("query")
|
|
174
|
+
.alias("q")
|
|
175
|
+
.description("Filter, group or run a SELECT over every note's metadata, from a local copy of the workspace")
|
|
176
|
+
.argument("[words...]", "Words that must all appear in the title or display id")
|
|
177
|
+
.option("--type <types>", "Note types, comma-separated (Decision,Insight)")
|
|
178
|
+
.option("--canvas <refs>", "Canvases by CANVAS-<n> or name, comma-separated")
|
|
179
|
+
.option("--tag <tags>", "Tags, comma-separated")
|
|
180
|
+
.option("--made-by <sources>", "human, agent, api or import, comma-separated")
|
|
181
|
+
.option("--by <name>", "Notes made by a member whose name contains this")
|
|
182
|
+
.option("--group-by <field>", "type (default), canvas, tag, month, person, made-by, none, or <Type>:<dimension>")
|
|
183
|
+
.option("--limit <n>", "Rows to return (default 100)")
|
|
184
|
+
.option("--sql <select>", "Run one read-only SELECT against the copy; `tables` lists the tables")
|
|
185
|
+
.option("--rebuild", "Drop this workspace's copy and copy it again")
|
|
186
|
+
.addHelpText("after", `
|
|
187
|
+
The copy holds every note's metadata (title, type, tags, canvases, who made it,
|
|
188
|
+
judged answers), never a note body. The first call copies the workspace; later
|
|
189
|
+
calls sync only what changed, then answer in milliseconds.
|
|
190
|
+
|
|
191
|
+
Examples:
|
|
192
|
+
$ cnotes query pricing --type Decision,Insight
|
|
193
|
+
$ cnotes query --canvas CANVAS-12 --group-by tag
|
|
194
|
+
$ cnotes query --made-by agent --group-by month --json
|
|
195
|
+
$ cnotes query --group-by Risk:status # the state '${UNJUDGED}' is a group too
|
|
196
|
+
$ cnotes query --sql "SELECT type, COUNT(*) AS n FROM notes GROUP BY type ORDER BY n DESC"
|
|
197
|
+
$ cnotes query --sql tables
|
|
198
|
+
`)
|
|
199
|
+
.action(async (words, opts) => {
|
|
200
|
+
const cfg = resolveConfig(program.opts());
|
|
201
|
+
const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
|
|
202
|
+
try {
|
|
203
|
+
const answer = await runQuery(api, cfg.workspaceId, words, opts);
|
|
204
|
+
if (answer.kind === "tables") {
|
|
205
|
+
if (cfg.json)
|
|
206
|
+
outputJson({ tables: answer.tables, sync: answer.sync }, cfg.fields);
|
|
207
|
+
else
|
|
208
|
+
for (const line of answer.tables)
|
|
209
|
+
console.log(line);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (answer.kind === "sql") {
|
|
213
|
+
if (cfg.json) {
|
|
214
|
+
const { kind: _kind, ...rest } = answer;
|
|
215
|
+
outputJson(rest, cfg.fields);
|
|
216
|
+
}
|
|
217
|
+
else
|
|
218
|
+
for (const line of renderSql(answer))
|
|
219
|
+
console.log(line);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (cfg.json) {
|
|
223
|
+
outputJson(answer.json, cfg.fields);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
for (const line of renderResult(answer.result, answer.groupBy))
|
|
227
|
+
console.log(line);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
handleError(error, cfg.json);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
package/dist/lib/auth-store.js
CHANGED
|
@@ -7,6 +7,10 @@ import { BRAND } from "./brand.js";
|
|
|
7
7
|
// multi-profile setups). Unset in normal use, which is the homedir default.
|
|
8
8
|
const CONFIG_DIR = process.env.CNOTES_CONFIG_DIR || join(homedir(), BRAND.configDir);
|
|
9
9
|
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
10
|
+
/** The directory everything the CLI keeps on disk lives under (config, local workspace copies). */
|
|
11
|
+
export function getConfigDir() {
|
|
12
|
+
return CONFIG_DIR;
|
|
13
|
+
}
|
|
10
14
|
/**
|
|
11
15
|
* One-time migration of the pre-rename config dir (`~/.creatornotes`) to the
|
|
12
16
|
* current one (`~/.cnotes`). Best-effort and idempotent: it only acts when the
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The CLI's local copy of a workspace's note metadata: the same SQLite
|
|
11
|
+
* database the web app's Query panel keeps (src/local-db/, copied from
|
|
12
|
+
* lib/local-db/), held in a file under the config directory and filled
|
|
13
|
+
* through `POST /api/local-db` with the caller's key.
|
|
14
|
+
*
|
|
15
|
+
* The web app runs the database in a worker over SQLite-wasm; here it is
|
|
16
|
+
* `node:sqlite` (or `bun:sqlite` in the compiled binary) in-process, so a
|
|
17
|
+
* "call" is a direct function call. Everything else (schema, sync loop, query
|
|
18
|
+
* builder) is the shared code.
|
|
19
|
+
*/
|
|
20
|
+
import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import { getConfigDir } from "./auth-store.js";
|
|
23
|
+
import { CliError, NotFoundError } from "./errors.js";
|
|
24
|
+
import { createLocalDbOps, openCopy } from "../local-db/ops.js";
|
|
25
|
+
import { workspaceFilePrefix } from "../local-db/protocol.js";
|
|
26
|
+
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
|
+
}
|
|
31
|
+
export const NODE_SQLITE_HINT = "cnotes query keeps the workspace copy in node:sqlite, which needs Node.js 22.13 or newer. " +
|
|
32
|
+
"Upgrade Node (https://nodejs.org), or use the cnotes binary, which carries its own runtime.";
|
|
33
|
+
async function loadDatabase() {
|
|
34
|
+
try {
|
|
35
|
+
const mod = (await import(__rewriteRelativeImportExtension("node:sqlite")));
|
|
36
|
+
return mod.DatabaseSync;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Not Node 22.13+, or the module is behind a flag.
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const mod = (await import(__rewriteRelativeImportExtension("bun:sqlite")));
|
|
43
|
+
return mod.Database;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
throw new CliError(NODE_SQLITE_HINT);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** The handle the shared code needs, over one open database. */
|
|
50
|
+
function wrap(handle) {
|
|
51
|
+
return {
|
|
52
|
+
run: (sql, params = []) => {
|
|
53
|
+
if (params.length)
|
|
54
|
+
handle.prepare(sql).run(...params);
|
|
55
|
+
else
|
|
56
|
+
handle.exec(sql);
|
|
57
|
+
},
|
|
58
|
+
all: (sql, params = []) => handle.prepare(sql).all(...params),
|
|
59
|
+
transaction: (fn) => {
|
|
60
|
+
handle.exec("BEGIN");
|
|
61
|
+
try {
|
|
62
|
+
const result = fn();
|
|
63
|
+
handle.exec("COMMIT");
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
handle.exec("ROLLBACK");
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
rows: (sql, params = []) => {
|
|
72
|
+
// query_only makes SQLite itself refuse any write, whatever the text says.
|
|
73
|
+
handle.exec("PRAGMA query_only = 1");
|
|
74
|
+
try {
|
|
75
|
+
const stmt = handle.prepare(sql);
|
|
76
|
+
const columns = stmt.columns ? stmt.columns().map((c) => c.name) : (stmt.columnNames ?? []);
|
|
77
|
+
const objects = stmt.all(...params);
|
|
78
|
+
const names = columns.length ? columns : Object.keys(objects[0] ?? {});
|
|
79
|
+
return { columns: names, rows: objects.map((o) => names.map((c) => o[c] ?? null)) };
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
handle.exec("PRAGMA query_only = 0");
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// The database as the sync loop sees it: an open file plus the shared ops.
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
export class LocalCopyStore {
|
|
91
|
+
Database;
|
|
92
|
+
directory;
|
|
93
|
+
handle = null;
|
|
94
|
+
ops = null;
|
|
95
|
+
openPath = null;
|
|
96
|
+
constructor(Database, directory) {
|
|
97
|
+
this.Database = Database;
|
|
98
|
+
this.directory = directory;
|
|
99
|
+
}
|
|
100
|
+
/** Query, facets and SQL over the open copy; throws until a sync has opened it. */
|
|
101
|
+
get db() {
|
|
102
|
+
if (!this.ops)
|
|
103
|
+
throw new CliError("The local copy is not open yet.");
|
|
104
|
+
return this.ops;
|
|
105
|
+
}
|
|
106
|
+
get path() {
|
|
107
|
+
return this.openPath;
|
|
108
|
+
}
|
|
109
|
+
close() {
|
|
110
|
+
this.handle?.close();
|
|
111
|
+
this.handle = null;
|
|
112
|
+
this.ops = null;
|
|
113
|
+
this.openPath = null;
|
|
114
|
+
}
|
|
115
|
+
async call(op, args) {
|
|
116
|
+
switch (op) {
|
|
117
|
+
case "open": {
|
|
118
|
+
const { fileName, wipeFirst } = args;
|
|
119
|
+
this.close();
|
|
120
|
+
if (wipeFirst)
|
|
121
|
+
this.wipeAll();
|
|
122
|
+
mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
123
|
+
// The shared name is an OPFS path with a leading slash.
|
|
124
|
+
const path = join(this.directory, fileName.replace(/^\//, ""));
|
|
125
|
+
this.handle = new this.Database(path);
|
|
126
|
+
this.openPath = path;
|
|
127
|
+
const db = wrap(this.handle);
|
|
128
|
+
this.ops = createLocalDbOps(db);
|
|
129
|
+
return openCopy(db, true);
|
|
130
|
+
}
|
|
131
|
+
case "forget": {
|
|
132
|
+
const { workspaceId } = args;
|
|
133
|
+
const prefix = workspaceFilePrefix(workspaceId).replace(/^\//, "");
|
|
134
|
+
if (this.openPath && this.openPath.includes(prefix))
|
|
135
|
+
this.close();
|
|
136
|
+
this.removeFiles((name) => name.startsWith(prefix));
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
case "wipe":
|
|
140
|
+
this.close();
|
|
141
|
+
this.wipeAll();
|
|
142
|
+
return null;
|
|
143
|
+
default: {
|
|
144
|
+
const handler = this.db[op];
|
|
145
|
+
return handler(args);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
wipeAll() {
|
|
150
|
+
this.removeFiles(() => true);
|
|
151
|
+
}
|
|
152
|
+
removeFiles(match) {
|
|
153
|
+
if (!existsSync(this.directory))
|
|
154
|
+
return;
|
|
155
|
+
for (const name of readdirSync(this.directory)) {
|
|
156
|
+
if (match(name))
|
|
157
|
+
rmSync(join(this.directory, name), { force: true });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export function restSyncSource(api, workspaceId) {
|
|
162
|
+
const call = (body) => api.post("/api/local-db", { workspaceId, ...body });
|
|
163
|
+
return {
|
|
164
|
+
noteIds: (cursor, numItems) => call({ op: "noteIds", cursor, numItems }),
|
|
165
|
+
notesChangedSince: (since, cursor, numItems) => call({ op: "changedSince", since, cursor, numItems }),
|
|
166
|
+
notesByIds: (ids) => call({ op: "notesByIds", ids }),
|
|
167
|
+
placements: (canvasIds) => call({ op: "placements", canvasIds }),
|
|
168
|
+
dimensionAnswers: (supertagId, dimensionKey, cursor, numItems) => call({ op: "answers", supertagId, dimensionKey, cursor, numItems }),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
export function fetchSyncHead(api, workspaceId) {
|
|
172
|
+
return api.post("/api/local-db", { op: "head", workspaceId });
|
|
173
|
+
}
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// One call: open the copy, bring it up to date, hand it back.
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
/** Inside this window a call pulls only what changed; past it, every note id is compared again. */
|
|
178
|
+
export const RECONCILE_EVERY_MS = 60 * 60 * 1000;
|
|
179
|
+
export async function openLocalCopy(options) {
|
|
180
|
+
const Database = await loadDatabase();
|
|
181
|
+
const directory = options.directory ?? localDbDirectory();
|
|
182
|
+
const store = new LocalCopyStore(Database, directory);
|
|
183
|
+
const head = await fetchSyncHead(options.api, options.workspaceId);
|
|
184
|
+
if (!head) {
|
|
185
|
+
// Not a member any more, or the key is pinned to another workspace: the copy goes too.
|
|
186
|
+
await store.call("forget", { workspaceId: options.workspaceId });
|
|
187
|
+
throw new NotFoundError("This workspace is not readable with your key.", "Run `cnotes workspace list` to see the workspaces your key reaches.");
|
|
188
|
+
}
|
|
189
|
+
let status = IDLE_STATUS;
|
|
190
|
+
const sync = new WorkspaceSync(restSyncSource(options.api, options.workspaceId), store, options.workspaceId, (s) => {
|
|
191
|
+
status = s;
|
|
192
|
+
options.onStatus?.(s);
|
|
193
|
+
}, { reconcileEvery: RECONCILE_EVERY_MS });
|
|
194
|
+
await (options.rebuild ? sync.rebuild(head) : sync.onHead(head));
|
|
195
|
+
if (status.phase === "error") {
|
|
196
|
+
store.close();
|
|
197
|
+
throw new CliError(`The local copy could not be synced: ${status.error ?? "unknown error"}`);
|
|
198
|
+
}
|
|
199
|
+
return { store, head, status };
|
|
200
|
+
}
|