@creator-notes/cnotes 0.114.0 → 0.116.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.114.0",
3
+ "version": "0.116.0",
4
4
  "description": "CreatorNotes CLI: create notes, build canvases, search knowledge from the terminal",
5
5
  "author": {
6
6
  "name": "CreatorNotes",
@@ -1,6 +1,6 @@
1
- import { ApiClient } from "../lib/api-client.js";
1
+ import { ApiClient, resolveActiveAgentRun } from "../lib/api-client.js";
2
2
  import { resolveConfig } from "../lib/config.js";
3
- import { handleError, NotFoundError, ValidationError, EXIT_CODES } from "../lib/errors.js";
3
+ import { CliError, handleError, NotFoundError, ValidationError, EXIT_CODES } from "../lib/errors.js";
4
4
  import { parseJsonOption } from "../lib/fs-utils.js";
5
5
  import { outputJson, outputTable, outputQuiet, timeAgo, truncate } from "../lib/output.js";
6
6
  import { readHeadlineWarnings, reportHeadlineWarnings } from "../lib/headline-warnings.js";
@@ -9,7 +9,7 @@ import { formatNoteDimensionLines, parseDimensionFilter, readNoteDimensions } fr
9
9
  import { isLocalDbEnabled } from "../lib/auth-store.js";
10
10
  import { explainTruncation, listNotes, SERVER_LIST_CAP } from "../lib/notes-list.js";
11
11
  import { formatLinkedItemHeading, groupLinkedByRelation, parseExpandArgs, projectExpandPayload, renderExpandContentOnly, } from "../lib/expand-notes.js";
12
- import { resolveNoteBatchItems } from "../lib/note-batch.js";
12
+ import { noteBatchIdempotencyKey, resolveNoteBatchItems } from "../lib/note-batch.js";
13
13
  import { describeUnresolvedMentions, lintNarratedVerbMentions, lintPlainTextDisplayIdsBatch, hasGenericMention, fetchRelationshipTypeOptions, } from "../lib/mention-lint.js";
14
14
  import { attachRubricsToResults, loadRubricMap, rubricsForTypes, } from "../lib/rubrics.js";
15
15
  import { DECISION_CARD_RULE, } from "../lib/decision-citation.js";
@@ -562,6 +562,9 @@ Examples:
562
562
  " '{\"key\":\"A\",\"type\":\"Insight\",\"markdown\":\"# Solo note\"}'\n" +
563
563
  " '[{\"key\":\"BUG\",\"type\":\"Claim\",\"markdown\":\"# The bug\\nSee [@CHECK: Open check](relationship:references).\"},\n" +
564
564
  " {\"key\":\"CHECK\",\"type\":\"Question\",\"markdown\":\"# Open check\\n[@BUG: The bug](relationship:blocks)\"}]'")
565
+ .option("--idempotency-key <key>", "Same key + same batch = the same create: a resend returns the notes the first one made\n" +
566
+ " (alreadyExists: true) instead of writing them again. Default inside a run: the run id plus a\n" +
567
+ " hash of the batch. Pass the key a failed create printed to re-run it safely from another run.")
565
568
  .addHelpText("after", `
566
569
  Before you write:
567
570
  Read each target type's rubric first — author to it, don't discover it after save:
@@ -590,11 +593,13 @@ Output (--json):
590
593
  command that grades the new notes against those rubrics; run it and revise
591
594
  anything below 4 before ending the operation. Read results with:
592
595
  cnotes notes create --json --notes '…' | jq -r '.results[] | "\\(.displayId) \\(.type)"'
593
- Success is the exit code (0). Do NOT re-run on a missing key; a re-run
594
- duplicates the batch. A non-zero exit prints { error, code, exitCode, hint }
595
- on stderr. An uncited Decision sets "hint" on that result (the displayId to
596
- re-version), lists the same line in the top-level "hints" array, and prints
597
- the same line on stderr. It is a reminder, not an error.
596
+ Success is the exit code (0). Inside a run, the same batch run again returns
597
+ the notes it made (alreadyExists: true), not a copy: the CLI sends an
598
+ idempotency key, the run id plus a hash of the batch. A non-zero exit prints
599
+ { error, code, exitCode, hint } on stderr. An uncited Decision sets "hint" on
600
+ that result (the displayId to re-version), lists the same line in the
601
+ top-level "hints" array, and prints the same line on stderr. It is a
602
+ reminder, not an error.
598
603
  `)
599
604
  .action(async (opts) => {
600
605
  const cfg = resolveConfig(program.opts());
@@ -611,6 +616,17 @@ Output (--json):
611
616
  throw new ValidationError("--notes must contain at least one item (object or non-empty array)");
612
617
  }
613
618
  const notes = resolveNoteBatchItems(items);
619
+ // The idempotency key: the same batch sent again in the same run gets
620
+ // the first notes back instead of a second copy. Outside a run none is
621
+ // derived: the server refuses a CLI create with no run (422
622
+ // operation_required), so nothing could be created twice, and a key
623
+ // from the batch alone would merge two deliberate identical creates.
624
+ const explicitKey = opts.idempotencyKey === undefined ? undefined : String(opts.idempotencyKey).trim();
625
+ if (explicitKey === "") {
626
+ throw new ValidationError("--idempotency-key cannot be empty");
627
+ }
628
+ const run = resolveActiveAgentRun(cfg.serverUrl);
629
+ const idempotencyKey = explicitKey ?? (run ? noteBatchIdempotencyKey(run.agentRunId, cfg.workspaceId, notes) : undefined);
614
630
  // Narrated-verb lint (warn-only, computed pre-send): prose like
615
631
  // "Blocks [[CLAIM-6G2]]" files a plain `references` edge the graph
616
632
  // can't distinguish from a citation. Never blocks the write — types
@@ -659,16 +675,37 @@ Output (--json):
659
675
  `The notes were still created. To link them, save a fixed body: ` +
660
676
  `cnotes versions create <displayId> --markdown-file <fixed.md> --minor`);
661
677
  };
662
- const data = await api.post("/api/notes/bulk", {
663
- action: "bulkCreate",
664
- workspaceId: cfg.workspaceId,
665
- notes,
666
- });
678
+ let data;
679
+ try {
680
+ data = await api.post("/api/notes/bulk", {
681
+ action: "bulkCreate",
682
+ workspaceId: cfg.workspaceId,
683
+ notes,
684
+ ...(idempotencyKey ? { idempotencyKey } : {}),
685
+ });
686
+ }
687
+ catch (error) {
688
+ // The send went out and failed before an answer (a reset, a timeout,
689
+ // a 5xx): the notes may exist. The key is what makes a re-run safe.
690
+ if (error instanceof CliError && error.mayHaveCommitted && idempotencyKey) {
691
+ error.idempotencyKey = idempotencyKey;
692
+ error.hint =
693
+ `The notes may have been created. Re-run with --idempotency-key ${idempotencyKey}: ` +
694
+ "if they were created you get them back, if not they are created once. " +
695
+ "(In the same run, the same command sends this key anyway.)";
696
+ }
697
+ throw error;
698
+ }
699
+ const alreadyExists = data.alreadyExists === true;
700
+ if (alreadyExists) {
701
+ console.error("That idempotency key already created these notes — returning them, not a copy.");
702
+ }
667
703
  // Fail-loud safety net: the notes were created, but if any mention
668
704
  // didn't resolve server-side the graph is silently under-built. Surface
669
705
  // it on stderr and set a non-zero exit so callers can't sail past it.
670
- // The notes already exist — fix forward with `versions create`, never
671
- // re-run create (it duplicates the batch).
706
+ // The notes already exist — fix forward with `versions create`; a
707
+ // re-run of the same create returns these same notes (or, without a
708
+ // key, writes them twice) and fixes nothing.
672
709
  const emitUnresolved = () => {
673
710
  const report = describeUnresolvedMentions(data.unresolvedMentions);
674
711
  if (!report)
@@ -677,7 +714,7 @@ Output (--json):
677
714
  console.error(`\n⚠ Some relationship mentions did not resolve. The ${created.length} note(s) ` +
678
715
  `were CREATED but carry broken links:\n${report}\n` +
679
716
  `Fix forward: cnotes versions create <id> --markdown-file <fixed.md>. ` +
680
- `Do NOT re-run create — it would duplicate the batch.`);
717
+ `Re-running this create cannot fix them.`);
681
718
  process.exitCode = EXIT_CODES.VALIDATION;
682
719
  };
683
720
  // The server sets `hint` on a Decision whose create wrote no typed
@@ -735,7 +772,9 @@ Output (--json):
735
772
  const relCount = data.relationshipsCreated || 0;
736
773
  const newTypes = (data.relationshipTypesCreated || []);
737
774
  const noun = results.length === 1 ? "note" : "notes";
738
- console.log(`Created ${results.length} ${noun} (${relCount} relationships)`);
775
+ console.log(alreadyExists
776
+ ? `Already created ${results.length} ${noun} (${relCount} relationships); nothing new was written`
777
+ : `Created ${results.length} ${noun} (${relCount} relationships)`);
739
778
  if (newTypes.length > 0) {
740
779
  console.log(` + created ${newTypes.length} new relationship type${newTypes.length === 1 ? "" : "s"}: ${newTypes.join(", ")}`);
741
780
  }
@@ -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) {
@@ -11,6 +11,17 @@ function isRetryable(status) {
11
11
  function sleep(ms) {
12
12
  return new Promise((resolve) => setTimeout(resolve, ms));
13
13
  }
14
+ /** Reads sent as POST: nothing they do can commit, so a failure says so. */
15
+ const READ_POSTS = new Set(["/api/local-db", "/api/semantic-search"]);
16
+ /**
17
+ * Whether a failed request could have written something, which decides
18
+ * whether its error says the write "may have committed" (errors.ts).
19
+ */
20
+ function isWriteRequest(method, url) {
21
+ if (!method || method === "GET" || method === "HEAD")
22
+ return false;
23
+ return !(method === "POST" && READ_POSTS.has(new URL(url).pathname));
24
+ }
14
25
  /**
15
26
  * Resolve the agent-run to attach to writes against `serverUrl`, in precedence
16
27
  * order:
@@ -193,7 +204,8 @@ export class ApiClient {
193
204
  // A transport failure here (DNS/TCP/TLS) surfaces from fetch as a bare
194
205
  // "fetch failed". Wrap it so the caller sees which host failed and why,
195
206
  // instead of an opaque message that reads like a backend/auth problem.
196
- throw asCliError(this.serverUrl, lastError || new Error("Request failed after retries"));
207
+ // A write that failed after it was sent is marked as possibly committed.
208
+ throw asCliError(this.serverUrl, lastError || new Error("Request failed after retries"), { write: isWriteRequest(init.method, url) });
197
209
  }
198
210
  /**
199
211
  * Read an error-response body for ApiError. Non-JSON bodies (an HTML 502
@@ -244,7 +256,7 @@ export class ApiClient {
244
256
  });
245
257
  if (!res.ok) {
246
258
  const respBody = await this.errorBody(res);
247
- throw new ApiError(res.status, respBody);
259
+ throw new ApiError(res.status, respBody, { write: isWriteRequest("POST", url.toString()) });
248
260
  }
249
261
  // The local copy's sync is a read sent as POST; anything else may have written.
250
262
  if (path !== "/api/local-db")
@@ -273,7 +285,7 @@ export class ApiClient {
273
285
  }, buildFormData);
274
286
  if (!res.ok) {
275
287
  const respBody = await this.errorBody(res);
276
- throw new ApiError(res.status, respBody);
288
+ throw new ApiError(res.status, respBody, { write: true });
277
289
  }
278
290
  markLocalWrite();
279
291
  return res.json();
@@ -287,7 +299,7 @@ export class ApiClient {
287
299
  });
288
300
  if (!res.ok) {
289
301
  const respBody = await this.errorBody(res);
290
- throw new ApiError(res.status, respBody);
302
+ throw new ApiError(res.status, respBody, { write: true });
291
303
  }
292
304
  markLocalWrite();
293
305
  return this.parseJsonSafe(res);
@@ -307,7 +319,7 @@ export class ApiClient {
307
319
  });
308
320
  if (!res.ok) {
309
321
  const respBody = await this.errorBody(res);
310
- throw new ApiError(res.status, respBody);
322
+ throw new ApiError(res.status, respBody, { write: true });
311
323
  }
312
324
  markLocalWrite();
313
325
  return this.parseJsonSafe(res);
@@ -321,7 +333,7 @@ export class ApiClient {
321
333
  });
322
334
  if (!res.ok) {
323
335
  const body = await this.errorBody(res);
324
- throw new ApiError(res.status, body);
336
+ throw new ApiError(res.status, body, { write: true });
325
337
  }
326
338
  markLocalWrite();
327
339
  return this.parseJsonSafe(res);
@@ -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 after a write was sent (the JSON error then carries mayHaveCommitted: true; re-run a notes create with the idempotencyKey it prints)",
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
  }
@@ -15,10 +15,12 @@
15
15
  * a lapsed trial or a failed payment). Distinct from 7 so an agent can
16
16
  * branch on billing without confusing it with an editor-permission denial.
17
17
  * The JSON error carries `upgradeUrl`.
18
- * 9 network (the request never reached the server — DNS/TCP/TLS failed).
19
- * Distinct from 1 so an agent can tell "I can't reach the host" (transient,
20
- * retry / check connectivity) apart from a malformed command. The JSON
21
- * error carries the low-level `cause` code (e.g. "ENOTFOUND").
18
+ * 9 network (no HTTP answer: DNS/TCP/TLS failed, or the connection dropped
19
+ * or timed out). Distinct from 1 so an agent can tell "I can't reach the
20
+ * host" (transient, retry / check connectivity) apart from a malformed
21
+ * command. The JSON error carries the low-level `cause` code (e.g.
22
+ * "ENOTFOUND"). A write that failed after it was sent carries
23
+ * `mayHaveCommitted: true` (see {@link failedBeforeSend}).
22
24
  */
23
25
  export const EXIT_CODES = {
24
26
  OK: 0,
@@ -42,6 +44,18 @@ export class CliError extends Error {
42
44
  * server body's `details`.
43
45
  */
44
46
  details;
47
+ /**
48
+ * True when a write failed after the request was sent (a reset, a timeout,
49
+ * a 5xx), so the server may have committed it. Surfaced in --json so an
50
+ * agent checks before running the write again instead of assuming nothing
51
+ * happened.
52
+ */
53
+ mayHaveCommitted;
54
+ /**
55
+ * The idempotency key the failed write sent. Sending the same write with it
56
+ * again returns what the first send made instead of a second copy.
57
+ */
58
+ idempotencyKey;
45
59
  constructor(message, exitCode = EXIT_CODES.GENERIC, hint, details) {
46
60
  super(message);
47
61
  this.exitCode = exitCode;
@@ -94,7 +108,12 @@ export class ApiError extends CliError {
94
108
  * why it was refused, not just on the status.
95
109
  */
96
110
  reason;
97
- constructor(status, body) {
111
+ /**
112
+ * @param opts.write The request was a write. A 5xx answering a write may
113
+ * come after the write committed (a later step failed, a proxy timed out),
114
+ * so it is marked {@link CliError.mayHaveCommitted} and hinted as such.
115
+ */
116
+ constructor(status, body, opts = {}) {
98
117
  const baseMsg = body.error || `API error: HTTP ${status}`;
99
118
  const fieldLines = formatFieldErrors(body.details);
100
119
  const msg = fieldLines.length > 0
@@ -109,6 +128,7 @@ export class ApiError extends CliError {
109
128
  : exitCodeForStatus(status);
110
129
  const resource = typeof body.resource === "string" ? body.resource : undefined;
111
130
  const reason = refusalReason(body, baseMsg);
131
+ const mayHaveCommitted = opts.write === true && status >= 500;
112
132
  const hint = typeof body.hint === "string"
113
133
  ? body.hint
114
134
  : serverCode === "billing_blocked"
@@ -117,11 +137,15 @@ export class ApiError extends CliError {
117
137
  ? "This workspace is on the free plan. Run `cnotes upgrade` to start a free 7-day Pro trial (no card), then retry."
118
138
  : reason !== undefined && Object.hasOwn(REASON_HINTS, reason)
119
139
  ? REASON_HINTS[reason]
120
- : hintForStatus(status, baseMsg, resource);
140
+ : mayHaveCommitted
141
+ ? WRITE_FAILED_AFTER_SEND_HINT
142
+ : hintForStatus(status, baseMsg, resource);
121
143
  super(msg, exitCode, hint);
122
144
  this.status = status;
123
145
  this.body = body;
124
146
  this.name = "ApiError";
147
+ if (mayHaveCommitted)
148
+ this.mayHaveCommitted = true;
125
149
  this.serverCode = serverCode;
126
150
  if (reason !== undefined)
127
151
  this.reason = reason;
@@ -164,6 +188,9 @@ const REASON_HINTS = {
164
188
  // Undoing a merge reverses a person's decision, so it is theirs to make.
165
189
  human_undo_required: "Ask the person who approved it: Undo is on the merge row in History, in the browser.",
166
190
  shared_write_from_draft: undefined,
191
+ // Review requests and note batches: the same key with a different body.
192
+ // Re-fetching changes nothing; the key is what has to change.
193
+ idempotency_key_reused: "That idempotency key already went with a different body. Use a new key for this one; to get the earlier result back, send exactly what was sent with that key.",
167
194
  // "CANVAS-390 is the live board. Your copy in this draft is CANVAS-412.
168
195
  // Nothing changed." The sentence is the remedy; "re-fetch and retry" would
169
196
  // send the agent back at the live board.
@@ -184,12 +211,22 @@ const REASON_HINTS = {
184
211
  export class NetworkError extends CliError {
185
212
  /** Low-level cause code when resolvable (e.g. "ENOTFOUND", "ECONNREFUSED"). */
186
213
  code;
187
- constructor(serverUrl, cause) {
214
+ /**
215
+ * @param opts.write The request was a write. Unless the failure provably
216
+ * came before the send ({@link failedBeforeSend}), the server may have
217
+ * committed it, and the error says so instead of "never reached".
218
+ */
219
+ constructor(serverUrl, cause, opts = {}) {
188
220
  const code = extractErrorCode(cause);
189
- const summary = code ? networkCodeSummary(code) : "DNS/connection failed";
190
- super(`Could not reach ${serverUrl}: ${summary}`, EXIT_CODES.NETWORK, networkHint(code));
221
+ const summary = code ? networkCodeSummary(code) : "connection failed";
222
+ const beforeSend = failedBeforeSend(cause);
223
+ super(beforeSend
224
+ ? `Could not reach ${serverUrl}: ${summary}`
225
+ : `Lost the connection to ${serverUrl} before it answered: ${summary}`, EXIT_CODES.NETWORK, networkHint(code, beforeSend, opts.write === true));
191
226
  this.name = "NetworkError";
192
227
  this.code = code;
228
+ if (opts.write === true && !beforeSend)
229
+ this.mayHaveCommitted = true;
193
230
  // Preserve the original error so callers can inspect the full chain.
194
231
  this.cause = cause;
195
232
  }
@@ -259,6 +296,31 @@ export function isPermanentNetworkError(err) {
259
296
  export function isRefusedBeforeSend(err) {
260
297
  return extractErrorCode(err) === "EAI_AGAIN";
261
298
  }
299
+ /**
300
+ * Failures that provably happened before any byte of the request was sent:
301
+ * the name did not resolve, no connection was made, or the TLS handshake was
302
+ * refused. Only these may say "the request never reached the server". A
303
+ * reset, a timeout after connecting, a socket error or a failure with no code
304
+ * may have come after the server received the request.
305
+ */
306
+ const BEFORE_SEND_CODES = new Set([
307
+ "ENOTFOUND",
308
+ "EAI_AGAIN",
309
+ "EAI_FAIL",
310
+ "ECONNREFUSED",
311
+ "EHOSTUNREACH",
312
+ "ENETUNREACH",
313
+ "ERR_INVALID_URL",
314
+ "UND_ERR_CONNECT_TIMEOUT",
315
+ ]);
316
+ export function failedBeforeSend(err) {
317
+ const code = extractErrorCode(err);
318
+ if (!code)
319
+ return false;
320
+ return BEFORE_SEND_CODES.has(code) || isTlsCode(code);
321
+ }
322
+ /** What a write that failed after it was sent should tell the caller. */
323
+ const WRITE_FAILED_AFTER_SEND_HINT = "The write was answered with a server error, and it may have committed before the failure. Check what is there before running it again.";
262
324
  /**
263
325
  * True when an error means the request failed at the transport layer rather
264
326
  * than returning an HTTP status. Node fetch raises `TypeError: fetch failed`
@@ -295,23 +357,29 @@ function networkCodeSummary(code) {
295
357
  return `connection failed (${code})`;
296
358
  }
297
359
  }
298
- function networkHint(code) {
360
+ function networkHint(code, beforeSend, write) {
299
361
  if (code && isTlsCode(code)) {
300
362
  return "TLS verification failed. Check the system clock and CA certificates, or whether a proxy is intercepting HTTPS.";
301
363
  }
302
364
  // The common case in agent sandboxes: outbound network is blocked entirely,
303
365
  // so DNS or connect fails for every host. Point there first.
304
- return "The request never reached the server. Check connectivity and DNS; in a sandboxed shell, confirm outbound network access is enabled.";
366
+ if (beforeSend) {
367
+ return "The request never reached the server. Check connectivity and DNS; in a sandboxed shell, confirm outbound network access is enabled.";
368
+ }
369
+ if (write) {
370
+ return "The connection dropped after the write was sent, so the write may have committed. Check what is there before running it again.";
371
+ }
372
+ return "The connection dropped before the server answered. Check connectivity and run it again; a read changes nothing.";
305
373
  }
306
374
  /**
307
375
  * Normalize a thrown error for surfacing: transport failures become a typed
308
376
  * {@link NetworkError} (naming the host + cause); everything else passes
309
377
  * through untouched. Call at the fetch boundary, where the server URL is known.
310
378
  */
311
- export function asCliError(serverUrl, err) {
379
+ export function asCliError(serverUrl, err, opts = {}) {
312
380
  if (isNetworkError(err)) {
313
381
  const cause = err instanceof Error ? err : new Error(String(err));
314
- return new NetworkError(serverUrl, cause);
382
+ return new NetworkError(serverUrl, cause, opts);
315
383
  }
316
384
  return err;
317
385
  }
@@ -448,6 +516,10 @@ export function handleError(error, json) {
448
516
  };
449
517
  if (error.hint)
450
518
  payload.hint = error.hint;
519
+ if (error.mayHaveCommitted)
520
+ payload.mayHaveCommitted = true;
521
+ if (error.idempotencyKey)
522
+ payload.idempotencyKey = error.idempotencyKey;
451
523
  // Structured details attached client-side (e.g. local batch validation).
452
524
  // ApiError's server-body details below take precedence when both exist.
453
525
  if (error.details !== undefined)
@@ -1,6 +1,27 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { ValidationError } from "./errors.js";
2
3
  import { readFileSafe } from "./fs-utils.js";
3
4
  import { lintMentionMarkdown } from "./mention-lint.js";
5
+ /** The run id shown in a derived key is cut here, so the key fits the server's 200 characters. */
6
+ const KEY_RUN_ID_CHARS = 100;
7
+ /**
8
+ * The idempotency key `notes create` sends inside a run: the run id plus a
9
+ * SHA-256 of the workspace and the batch as sent (markdownFile already read).
10
+ * The same batch run again in the same run sends the same key, so the server
11
+ * returns the notes the first send made instead of writing them twice
12
+ * (convex/lib/noteBatchReplay.ts). Another run, or any change to the batch,
13
+ * gives another key and creates. The hash covers the whole run id; only the
14
+ * readable copy in front of it is cut.
15
+ */
16
+ export function noteBatchIdempotencyKey(agentRunId, workspaceId, notes) {
17
+ const canonical = JSON.stringify([
18
+ agentRunId,
19
+ workspaceId,
20
+ notes.map((n) => [n.key, n.type, n.markdown, n.tags ?? [], n.changeDescription ?? null]),
21
+ ]);
22
+ const hash = createHash("sha256").update(canonical).digest("hex");
23
+ return `notes-create:${agentRunId.slice(0, KEY_RUN_ID_CHARS)}:${hash}`;
24
+ }
4
25
  /**
5
26
  * Resolve and check a batch of notes before anything is sent: `notes create
6
27
  * --notes` and the `notes` array of a `canvas place` spec. Reads markdownFile
@@ -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
  }
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.114.0",
3
+ "version": "0.116.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).
@@ -119,6 +119,7 @@ cnotes notes create --notes '[
119
119
  # later writes one. Human-typed editor text only gets the token filled.
120
120
  # On validation failure the response lists every bad item by index + key + field
121
121
  # (and `details.items` in --json mode), so you can fix the whole batch in one shot.
122
+ # Same batch again in the same run returns the first notes (alreadyExists: true), not a copy; after a reset or 5xx (`mayHaveCommitted: true`) re-run with the printed `--idempotency-key`.
122
123
  # Each .results[] item carries .type + .rubric — keep them when filtering JSON.
123
124
  # Where the deployment turns the rubric check on, each item also carries
124
125
  # .quality: {level 1-4, label, missing[], nextStep, unsure}. `missing` quotes the
@@ -269,7 +270,7 @@ each note is judged again; a new label alone keeps them.
269
270
  > — from [[quotes::TRANSCRIPT-4@v5]] v5, 12 Oct 2026, 4:55 pm
270
271
  ```
271
272
  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.
273
+ - **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
274
  - 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
275
  - Common built-in types to reach for first:
275
276
  - `depends-on` / `blocks` — dependency ordering between notes