@creator-notes/cnotes 0.115.0 → 0.117.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.115.0",
3
+ "version": "0.117.0",
4
4
  "description": "CreatorNotes CLI: create notes, build canvases, search knowledge from the terminal",
5
5
  "author": {
6
6
  "name": "CreatorNotes",
@@ -1033,6 +1033,10 @@ verb (Changes), or repeats the headline or the Why; nothing is saved, so
1033
1033
  rewrite the line and ask again. The runs you flagged with operations end
1034
1034
  --unsure are listed for the person as the ones to look at.
1035
1035
 
1036
+ If another open proposal you can see rewords one of the same notes, the ask
1037
+ prints it to stderr as "Overlaps: ...": compare the two (cnotes draft status
1038
+ <id>) and say in the ask which should land first, or fold one into the other.
1039
+
1036
1040
  If a check blocks when you ask, the ask is still made, so a person can help
1037
1041
  settle it. Each blocking check is printed to stderr, the person sees the
1038
1042
  proposal blocked, and nothing can be accepted until you fix it and ask again.
@@ -1060,6 +1064,11 @@ Examples:
1060
1064
  const blocking = asked.checks.findings.filter((f) => f.blocking);
1061
1065
  for (const f of blocking)
1062
1066
  console.error(`Blocking: ${f.message} ${f.fix}`);
1067
+ // Another open proposal rewords the same notes: say so whatever the
1068
+ // output mode, so the agent compares the two before the person decides.
1069
+ for (const f of asked.checks.findings.filter((f) => f.code === "proposal-overlap")) {
1070
+ console.error(`Overlaps: ${f.message} ${f.fix}`);
1071
+ }
1063
1072
  if (cfg.quiet) {
1064
1073
  console.log(inPlaceId);
1065
1074
  return;
@@ -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
  }
@@ -9,6 +9,7 @@ import { loadConfig, setActiveAgentRunId, registerAgentRun, unregisterAgentRun,
9
9
  import { resolveHostAgentSession } from "../lib/claude-session.js";
10
10
  import { allWorkspaceRubrics, loadRubricMap } from "../lib/rubrics.js";
11
11
  import { briefIsEmpty, loadSessionBrief, renderBrief } from "../lib/session-brief.js";
12
+ import { renderProposalsForCaller } from "../lib/waiting-proposals.js";
12
13
  /**
13
14
  * `cnotes operations` — workspace-scoped lifecycle for agentic batches.
14
15
  *
@@ -64,6 +65,12 @@ pointer, so neither agent can clobber or close the other's run.
64
65
 
65
66
  -q prints only the run id, without the rubrics and the brief.
66
67
 
68
+ Proposals: begin lists the open proposals asked of you in this workspace
69
+ (waitingOnYou) and your own not yet asked that reword a note another open
70
+ proposal also rewords (overlapping), each with its overlaps. Compare
71
+ overlapping proposals before either is accepted. Under -q these lines go to
72
+ stderr.
73
+
67
74
  --json includes typeRubrics: [{type, rubric}, ...] for every workspace type
68
75
  that has a validationPrompt. Read the ones you will author BEFORE notes create
69
76
  (or run cnotes types show <Type>). Post-write rubric echoes are too late to
@@ -150,7 +157,13 @@ start fresh, or --detached to open your own run alongside it.
150
157
  ]);
151
158
  const typeRubrics = allWorkspaceRubrics(rubricMap);
152
159
  reportHeadlineWarnings(readHeadlineWarnings(result));
160
+ // Proposals waiting on the caller, and the ones that overlap, reach
161
+ // the agent even under -q (on stderr), so it hears of another agent's
162
+ // work at the start of its own.
163
+ const proposalLines = renderProposalsForCaller(result);
153
164
  if (cfg.quiet) {
165
+ for (const line of proposalLines)
166
+ console.error(line);
154
167
  console.log(result.agentRunId);
155
168
  return;
156
169
  }
@@ -181,6 +194,11 @@ start fresh, or --detached to open your own run alongside it.
181
194
  if (typeRubrics.length > 0) {
182
195
  console.log(`${typeRubrics.length} type rubric${typeRubrics.length === 1 ? "" : "s"} in this workspace — read with \`cnotes types show <Type>\` BEFORE notes create (also in --json as typeRubrics).`);
183
196
  }
197
+ if (proposalLines.length > 0) {
198
+ console.log("");
199
+ for (const line of proposalLines)
200
+ console.log(line);
201
+ }
184
202
  if (brief && !briefIsEmpty(brief)) {
185
203
  console.log("");
186
204
  console.log("What the workspace already knows about this (read before acting):");
@@ -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);
@@ -89,7 +89,7 @@ export const STATIC_SCHEMA = {
89
89
  "6": "rate-limited",
90
90
  "7": "permission denied",
91
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)",
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)",
93
93
  },
94
94
  env: {
95
95
  CNOTES_SERVER: "Override server URL",
@@ -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
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What `operations begin` says about proposals in the workspace: the ones
3
+ * asked of the caller, and the caller's own that overlap another (V1 on
4
+ * CANVAS-461). Two agents rewording the same note in two proposals hear of
5
+ * each other here, at the start of their work, in output they already read.
6
+ */
7
+ function overlapText(overlaps) {
8
+ return overlaps.map((o) => `overlaps ${o.displayId} on ${o.notes.join(", ")}`).join("; ");
9
+ }
10
+ /** The lines to print, or none when nothing waits and nothing overlaps. */
11
+ export function renderProposalsForCaller(result) {
12
+ const waiting = result.waitingOnYou ?? [];
13
+ const overlapping = result.overlapping ?? [];
14
+ if (waiting.length === 0 && overlapping.length === 0)
15
+ return [];
16
+ const lines = [];
17
+ if (waiting.length > 0) {
18
+ lines.push("Waiting on you in this workspace:");
19
+ for (const p of waiting) {
20
+ const parts = [`${p.displayId} "${p.name}"`, `built by ${p.builtBy}`];
21
+ if (p.sentBack)
22
+ parts.push("sent back");
23
+ if (p.overlaps.length > 0)
24
+ parts.push(overlapText(p.overlaps));
25
+ lines.push(` ${parts.join(" · ")}`);
26
+ }
27
+ }
28
+ if (overlapping.length > 0) {
29
+ lines.push("Your proposals not yet asked that overlap another:");
30
+ for (const p of overlapping) {
31
+ lines.push(` ${p.displayId} "${p.name}" · ${overlapText(p.overlaps)}`);
32
+ }
33
+ }
34
+ const anyOverlap = overlapping.length > 0 || waiting.some((p) => p.overlaps.length > 0);
35
+ if (anyOverlap) {
36
+ lines.push("Overlapping proposals reword the same notes: compare them before either is accepted (`cnotes draft status <id>`), and say in the ask which should land first.");
37
+ }
38
+ return lines;
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creator-notes/cnotes",
3
- "version": "0.115.0",
3
+ "version": "0.117.0",
4
4
  "description": "CLI for CreatorNotes — create notes, build canvases, search knowledge from the terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,7 +17,7 @@ Every note and canvas you write is context: what the next reader, a teammate or
17
17
 
18
18
  1. **Confirm the workspace.** `cnotes workspace current` names it and lists its relationship types. `-w <id>` targets another one for a single command.
19
19
  2. **Read before you write.** Past sessions and teammates left context for this task. `cnotes brief "<task>"` returns the notes, canvases and recent changes most relevant to the task. Search notes and canvases separately (they are different corpora): `cnotes search semantic "<topic>"` and `cnotes canvas search "<topic>"`. `cnotes notes get <id> --expand` loads a note with the notes it rests on. Before changing a canvas, `cnotes canvas read <canvasId>`. A Decision or Guide you find may already settle what you were about to propose.
20
- 3. **Open a run.** `cnotes operations begin --prompt "<the change as a past-tense headline, e.g. Added a risks list to the Q1 roadmap>" --json`, as its own command; check its exit code before writing (a pipe hides it). `notes create` refuses to run without one. The response carries `typeRubrics` and the same brief; `-q` prints only the run id when you already have both. One canvas per run: end it and begin another before writing to a second canvas.
20
+ 3. **Open a run.** `cnotes operations begin --prompt "<the change as a past-tense headline, e.g. Added a risks list to the Q1 roadmap>" --json`, as its own command; check its exit code before writing (a pipe hides it). `notes create` refuses to run without one. The response carries `typeRubrics`, the same brief, and the proposals waiting on you with any that reword the same note as another (read those first, [references/drafts.md](references/drafts.md) step 8); `-q` prints only the run id, with the proposals on stderr. One canvas per run: end it and begin another before writing to a second canvas.
21
21
  4. **Write to the type's rubric.** Pick the type, run `cnotes types show <Type>`, and author to its rubric. Audience-facing prose (note bodies, banners, pre-reads) goes through [references/humanizer.md](references/humanizer.md) first; transcripts, quotes and other raw capture are stored verbatim.
22
22
  5. **Create notes in one batch.** `cnotes notes create --notes '[{"key":"A","type":"Insight","markdownFile":"./a.md"}, ...]'`. Each body starts with a `# h1` (the title). Cross-link inside the batch with `[@A: Title](relationship:<verb>)`. Detail: [references/notes.md](references/notes.md).
23
23
  6. **Grade what you wrote.** `cnotes quality <displayIds...> --fail-below 4`, then revise weak notes with `cnotes versions create <id> --description "<what changed>" --markdown-file <path>`.
@@ -199,6 +199,16 @@ the checkout that reaches it.
199
199
  reads "Waiting on <you>: ..." instead of a proposal to decide. Make the fix,
200
200
  then `draft ask` again and stop. A live save of a note with a proposed new
201
201
  text prints that the save puts the proposal out of date.
202
+ 8. **When another proposal rewords the same note,** you are told wherever you
203
+ look: `draft ask` prints "Overlaps: PROPOSAL-7 "Team price" also rewords
204
+ DECISION-1, built by you via Codex (Slack)." on stderr, `draft status`
205
+ lists it as a `proposal-overlap` warning, and `operations begin` lists it
206
+ under the proposals waiting on you. You only ever hear of a proposal you
207
+ could already see (yours, or one asked of you). It never blocks. Read the
208
+ other one (`cnotes draft status PROPOSAL-7`) and decide which of three
209
+ holds: they agree (say in your ask which should land first), yours
210
+ repeats it (fold what is new into the other or dismiss yours), or they
211
+ conflict (write a Question for the person naming both, with your lean).
202
212
 
203
213
  ## Deciding as someone's agent
204
214
 
@@ -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