@creator-notes/cnotes 0.110.1 → 0.111.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "creator-notes-cli",
3
- "version": "0.110.1",
3
+ "version": "0.111.1",
4
4
  "description": "CreatorNotes CLI: create notes, build canvases, search knowledge from the terminal",
5
5
  "author": {
6
6
  "name": "CreatorNotes",
@@ -21,6 +21,7 @@ import { registerCanvasMilestoneCommands } from "./canvas-milestone.js";
21
21
  import { DISPLAY_ID_CORE } from "../lib/display-id.js";
22
22
  import { resolveNoteBatchItems } from "../lib/note-batch.js";
23
23
  import { describeUnresolvedMentions } from "../lib/mention-lint.js";
24
+ import { setIntentPreflight } from "../lib/intent-run.js";
24
25
  /** A node handle the agent reads off `canvas read`: NOTE-12, SECTION-7, … */
25
26
  const NODE_DISPLAY_REF_RE = new RegExp(String.raw `^${DISPLAY_ID_CORE}$`);
26
27
  /**
@@ -114,6 +115,188 @@ function warnLayoutListMisuse(node) {
114
115
  for (const value of Object.values(n))
115
116
  warnLayoutListMisuse(value);
116
117
  }
118
+ function hasLayoutSpec(opts) {
119
+ return Boolean(opts.spec || opts.specInline || opts.specStdin);
120
+ }
121
+ /**
122
+ * Read a layout document from --spec / --spec-inline / --spec-stdin and split
123
+ * off its `notes` array, which goes to the server beside the layout. The notes
124
+ * are checked here exactly as `notes create` checks them.
125
+ */
126
+ async function readLayoutSpec(opts, { silent = false } = {}) {
127
+ let raw;
128
+ if (opts.spec) {
129
+ raw = readFileSafe(opts.spec);
130
+ }
131
+ else if (opts.specInline) {
132
+ raw = opts.specInline;
133
+ }
134
+ else if (opts.specStdin) {
135
+ raw = await new Promise((resolve, reject) => {
136
+ const chunks = [];
137
+ process.stdin.on("data", (c) => chunks.push(c));
138
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
139
+ process.stdin.on("error", reject);
140
+ });
141
+ }
142
+ else {
143
+ throw new ValidationError("One of --spec, --spec-inline, or --spec-stdin is required");
144
+ }
145
+ let doc;
146
+ try {
147
+ doc = JSON.parse(raw);
148
+ }
149
+ catch (e) {
150
+ throw new ValidationError(`Layout spec is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
151
+ }
152
+ // --placement overrides whatever the spec carries (or sets it if absent).
153
+ if (opts.placement !== undefined) {
154
+ const allowed = ["auto", "append", "exact"];
155
+ if (!allowed.includes(opts.placement)) {
156
+ throw new ValidationError(`--placement must be one of ${allowed.join(", ")} (got "${opts.placement}")`);
157
+ }
158
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc)) {
159
+ throw new ValidationError("Layout spec must be a JSON object to apply --placement");
160
+ }
161
+ doc.placement = opts.placement;
162
+ }
163
+ if (!silent)
164
+ warnLayoutListMisuse(doc);
165
+ let notes;
166
+ if (doc && typeof doc === "object" && !Array.isArray(doc) && "notes" in doc) {
167
+ const { notes: rawNotes, ...layout } = doc;
168
+ if (!Array.isArray(rawNotes) || rawNotes.length === 0) {
169
+ throw new ValidationError('"notes" must be a non-empty array of {key, type, markdown|markdownFile}');
170
+ }
171
+ notes = resolveNoteBatchItems(rawNotes);
172
+ doc = layout;
173
+ }
174
+ return { doc, ...(notes ? { notes } : {}) };
175
+ }
176
+ /**
177
+ * Report the notes a placeLayout call created: headline warnings, hints, and
178
+ * mentions that did not resolve (which sets a validation exit code). Returns
179
+ * the created rows.
180
+ */
181
+ function reportPlacedNotes(data) {
182
+ // The notes exist once the call returns, even when placing failed:
183
+ // never re-run a spec with notes to retry, it duplicates them.
184
+ const createdNotes = data.notes;
185
+ const createdRows = (createdNotes?.results || []);
186
+ if (createdNotes) {
187
+ for (const row of createdRows) {
188
+ reportHeadlineWarnings(readHeadlineWarnings(row), typeof row.displayId === "string" ? row.displayId : undefined);
189
+ if (typeof row.hint === "string" && row.hint.trim())
190
+ console.error(`Hint: ${row.hint.trim()}`);
191
+ }
192
+ const unresolved = describeUnresolvedMentions(createdNotes.unresolvedMentions);
193
+ if (unresolved) {
194
+ console.error(`\n⚠ Some relationship mentions did not resolve. The ${createdRows.length} note(s) ` +
195
+ `were CREATED but carry broken links:\n${unresolved}\n` +
196
+ `Fix forward: cnotes versions create <id> --markdown-file <fixed.md>. ` +
197
+ `Do NOT re-run place — it would duplicate the notes.`);
198
+ process.exitCode = EXIT_CODES.VALIDATION;
199
+ }
200
+ }
201
+ return createdRows;
202
+ }
203
+ /**
204
+ * The server answers 207 with per-item results. Partial failure keeps exit 0
205
+ * (the caller inspects items[].error, the documented contract), but when EVERY
206
+ * item and edge failed, nothing was placed and exiting 0 would report success
207
+ * to an agent that keys on the exit code.
208
+ */
209
+ function placedNothing(data) {
210
+ const allItems = (data.items || []);
211
+ const allEdges = (data.edges || []);
212
+ return (!data.dryRun &&
213
+ allItems.length + allEdges.length > 0 &&
214
+ allItems.every((r) => !r.id || r.error) &&
215
+ allEdges.every((e) => !e.id || e.error));
216
+ }
217
+ function reportNothingPlacedJson() {
218
+ console.error(JSON.stringify({
219
+ error: "placeLayout placed nothing: every item and edge failed",
220
+ code: "PlaceFailed",
221
+ exitCode: EXIT_CODES.GENERIC,
222
+ hint: "Inspect items[].error and edges[].error in the response above; fix the failing refs and retry.",
223
+ }));
224
+ }
225
+ /** The human summary of a (non-dry-run) placeLayout result. */
226
+ function printPlaceSummary(data, createdRows) {
227
+ const items = (data.items || []);
228
+ const edges = (data.edges || []);
229
+ const bbox = data.bbox;
230
+ if (createdRows.length > 0) {
231
+ console.log(`Created ${createdRows.length} note${createdRows.length === 1 ? "" : "s"}: ` +
232
+ createdRows.map((r) => `${r.key} → ${r.displayId}`).join(", "));
233
+ }
234
+ const placed = items.filter((r) => r.id && !r.error).length;
235
+ const failed = items.filter((r) => !r.id || r.error).length;
236
+ const edgesAdded = edges.filter((e) => e.id && !e.error).length;
237
+ const edgesFailed = edges.filter((e) => !e.id || e.error).length;
238
+ console.log(`Placed ${placed} items${failed > 0 ? ` (${failed} failed)` : ""}, ` +
239
+ `${edgesAdded} edges${edgesFailed > 0 ? ` (${edgesFailed} failed)` : ""}`);
240
+ if (bbox?.width && bbox?.height) {
241
+ console.log(`Layout bounding box: ${Math.round(bbox.width)} × ${Math.round(bbox.height)}px`);
242
+ }
243
+ const arranged = (data.arrangedSections || []);
244
+ for (const a of arranged) {
245
+ if (a.error)
246
+ console.log(` ✗ section ${a.displayId ?? a.sectionId} could not arrange itself: ${a.error}`);
247
+ else
248
+ console.log(` Arranged ${a.displayId} (${a.width} × ${a.height}px); it keeps itself laid out`);
249
+ }
250
+ // Surface item-level errors so the user doesn't have to re-run with --json
251
+ for (const item of items) {
252
+ if (item.error)
253
+ console.log(` ✗ item[${item.index}] (${item.type}): ${item.error}`);
254
+ }
255
+ for (const edge of edges) {
256
+ if (edge.error)
257
+ console.log(` ✗ edge ${edge.from} → ${edge.to}: ${edge.error}`);
258
+ }
259
+ if (placedNothing(data)) {
260
+ console.error("Error: nothing was placed — every item and edge failed (see above).");
261
+ }
262
+ }
263
+ function printCreatedCanvas(cfg, name, data, createdRows) {
264
+ const canvas = data.canvas ?? {};
265
+ const canvasId = String(canvas.id || canvas._id || "");
266
+ const url = canvasId ? canvasUrl(cfg.serverUrl, cfg.workspaceId, canvasId) : "";
267
+ if (cfg.quiet) {
268
+ outputQuiet(canvasId);
269
+ return;
270
+ }
271
+ if (cfg.json) {
272
+ // Inject the ready-to-surface web link (server-side has no reliable
273
+ // public origin; the CLI knows which server it's talking to).
274
+ if (url)
275
+ canvas.url = url;
276
+ // Also surface id/displayId/url at the TOP level, not just under
277
+ // `.canvas`. A scripter naturally reaches for `jq -r '.id'`; when the
278
+ // id only lived at `.canvas.id` that returned a silent `null` and the
279
+ // next command placed onto "null" without erroring. Additive — the
280
+ // `.canvas` object is unchanged, so existing readers keep working.
281
+ outputJson({
282
+ ...data,
283
+ id: canvasId || null,
284
+ displayId: canvas.displayId ?? null,
285
+ ...(url ? { url } : {}),
286
+ });
287
+ return;
288
+ }
289
+ console.log(`Created canvas: ${name}`);
290
+ // Lead with the display id — the memorable, immutable handle to cite
291
+ // to the user — then the raw id and a click-through link.
292
+ if (canvas.displayId)
293
+ console.log(`Ref: ${canvas.displayId}`);
294
+ console.log(`ID: ${canvasId || "(unknown)"}`);
295
+ if (data.layout)
296
+ printPlaceSummary(data.layout, createdRows);
297
+ if (url)
298
+ console.log(`Link: ${url}`);
299
+ }
117
300
  /**
118
301
  * Human-readable line(s) for the server's ripple report — the band of content
119
302
  * below a growing frame that shifted down with it (or didn't, and why).
@@ -811,16 +994,32 @@ Examples:
811
994
  handleError(error, cfg.json);
812
995
  }
813
996
  });
814
- canvas
997
+ const canvasCreate = canvas
815
998
  .command("create")
816
999
  .description("Create a new canvas. Write --goal first, for a reader; the server rejects a goal without a \"Done when\" sentence.")
817
1000
  .argument("<name>", "Canvas name (separate parts with ·, e.g. \"Path to Revenue · Funding strategy\")")
818
1001
  .option("--goal <text>", CANVAS_GOAL_DESCRIPTION)
819
1002
  .option("--audience <text>", "Target audience — who this canvas is meant to serve or inform, and what they do with it")
1003
+ .option("--spec <path>", "Lay out the new canvas in the same call: a `canvas place` layout document (notes, root, edges) in a JSON file")
1004
+ .option("--spec-stdin", "Read the layout document from stdin")
1005
+ .option("--spec-inline <json>", "Pass the layout document inline as a JSON string (short specs only)")
1006
+ .option("--placement <mode>", "Where the layout lands on the new canvas: auto (default), append, or exact (honor the spec's origin verbatim). Overrides any placement in the spec.")
1007
+ .addHelpText("after", `
1008
+ A new canvas and its first layout in one call: --spec takes the same document as
1009
+ \`canvas place\`, new notes included, and the server places it onto the canvas it
1010
+ just made; the placement comes back under \`layout\`. New notes need a run, so
1011
+ pair it with --intent:
1012
+ $ cnotes canvas create "Q1 · Roadmap" --goal "<goal>" --audience "<who>" \\
1013
+ --spec ./layout.json --intent "Built the Q1 roadmap canvas"
1014
+ The spec is checked before the canvas exists, and a layout the server refuses
1015
+ removes the canvas again, so a failed create leaves nothing behind: fix the
1016
+ spec and run the same command again.
1017
+ `)
820
1018
  .action(async (name, opts) => {
821
1019
  const cfg = resolveConfig(program.opts());
822
1020
  const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
823
1021
  try {
1022
+ const layout = hasLayoutSpec(opts) ? await readLayoutSpec(opts) : undefined;
824
1023
  const body = {
825
1024
  workspaceId: cfg.workspaceId,
826
1025
  title: name,
@@ -829,48 +1028,35 @@ Examples:
829
1028
  body.goal = opts.goal;
830
1029
  if (opts.audience !== undefined)
831
1030
  body.targetAudience = opts.audience;
832
- const data = await api.post("/api/canvas", body);
833
- const canvas = data.canvas ?? {};
834
- const canvasId = String(canvas.id || canvas._id || "");
835
- const url = canvasId
836
- ? canvasUrl(cfg.serverUrl, cfg.workspaceId, canvasId)
837
- : "";
838
- if (cfg.quiet) {
839
- outputQuiet(canvasId);
840
- return;
841
- }
842
- if (cfg.json) {
843
- // Inject the ready-to-surface web link (server-side has no reliable
844
- // public origin; the CLI knows which server it's talking to).
845
- if (url)
846
- canvas.url = url;
847
- // Also surface id/displayId/url at the TOP level, not just under
848
- // `.canvas`. A scripter naturally reaches for `jq -r '.id'`; when the
849
- // id only lived at `.canvas.id` that returned a silent `null` and the
850
- // next command placed onto "null" without erroring. Additive — the
851
- // `.canvas` object is unchanged, so existing readers keep working.
852
- outputJson({
853
- ...data,
854
- id: canvasId || null,
855
- displayId: canvas.displayId ?? null,
856
- ...(url ? { url } : {}),
857
- });
858
- }
859
- else {
860
- console.log(`Created canvas: ${name}`);
861
- // Lead with the display id — the memorable, immutable handle to cite
862
- // to the user — then the raw id and a click-through link.
863
- if (canvas.displayId)
864
- console.log(`Ref: ${canvas.displayId}`);
865
- console.log(`ID: ${canvasId || "(unknown)"}`);
866
- if (url)
867
- console.log(`Link: ${url}`);
1031
+ // The spec travels with the create: the server checks it before the
1032
+ // canvas exists and places it under the same run as the create.
1033
+ if (layout) {
1034
+ body.doc = layout.doc;
1035
+ if (layout.notes)
1036
+ body.notes = layout.notes;
868
1037
  }
1038
+ const data = await api.post("/api/canvas", body);
1039
+ const createdRows = data.layout ? reportPlacedNotes(data.layout) : [];
1040
+ const nothingPlaced = data.layout ? placedNothing(data.layout) : false;
1041
+ if (nothingPlaced)
1042
+ process.exitCode = EXIT_CODES.GENERIC;
1043
+ printCreatedCanvas(cfg, name, data, createdRows);
1044
+ if (cfg.json && nothingPlaced)
1045
+ reportNothingPlacedJson();
869
1046
  }
870
1047
  catch (error) {
871
1048
  handleError(error, cfg.json);
872
1049
  }
873
1050
  });
1051
+ // Under --intent the run opens before the command runs. A spec that cannot
1052
+ // be read is refused here first, so the call opens no run and creates
1053
+ // nothing. A spec on stdin cannot be read twice, so it is checked by the
1054
+ // command itself, after the run has opened.
1055
+ setIntentPreflight(canvasCreate, async (opts) => {
1056
+ const specOpts = opts;
1057
+ if (specOpts.spec || specOpts.specInline)
1058
+ await readLayoutSpec(specOpts, { silent: true });
1059
+ });
874
1060
  canvas
875
1061
  .command("update")
876
1062
  .description("Update canvas metadata (title, goal, audience). A goal is rejected without a \"Done when\" sentence.")
@@ -1716,55 +1902,7 @@ Placement (relative to nodes already on the canvas):
1716
1902
  const cfg = resolveConfig(program.opts());
1717
1903
  const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
1718
1904
  try {
1719
- let raw;
1720
- if (opts.spec) {
1721
- raw = readFileSafe(opts.spec);
1722
- }
1723
- else if (opts.specInline) {
1724
- raw = opts.specInline;
1725
- }
1726
- else if (opts.specStdin) {
1727
- raw = await new Promise((resolve, reject) => {
1728
- const chunks = [];
1729
- process.stdin.on("data", (c) => chunks.push(c));
1730
- process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
1731
- process.stdin.on("error", reject);
1732
- });
1733
- }
1734
- else {
1735
- throw new ValidationError("One of --spec, --spec-inline, or --spec-stdin is required");
1736
- }
1737
- let doc;
1738
- try {
1739
- doc = JSON.parse(raw);
1740
- }
1741
- catch (e) {
1742
- throw new ValidationError(`Layout spec is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
1743
- }
1744
- // --placement overrides whatever the spec carries (or sets it if absent).
1745
- if (opts.placement !== undefined) {
1746
- const allowed = ["auto", "append", "exact"];
1747
- if (!allowed.includes(opts.placement)) {
1748
- throw new ValidationError(`--placement must be one of ${allowed.join(", ")} (got "${opts.placement}")`);
1749
- }
1750
- if (doc === null || typeof doc !== "object" || Array.isArray(doc)) {
1751
- throw new ValidationError("Layout spec must be a JSON object to apply --placement");
1752
- }
1753
- doc.placement = opts.placement;
1754
- }
1755
- warnLayoutListMisuse(doc);
1756
- // New notes ride in the spec's own `notes` array (the `notes create`
1757
- // batch shape), checked here exactly as `notes create` checks them,
1758
- // and go to the server beside the layout document.
1759
- let notes;
1760
- if (doc && typeof doc === "object" && !Array.isArray(doc) && "notes" in doc) {
1761
- const { notes: rawNotes, ...layout } = doc;
1762
- if (!Array.isArray(rawNotes) || rawNotes.length === 0) {
1763
- throw new ValidationError('"notes" must be a non-empty array of {key, type, markdown|markdownFile}');
1764
- }
1765
- notes = resolveNoteBatchItems(rawNotes);
1766
- doc = layout;
1767
- }
1905
+ const { doc, notes } = await readLayoutSpec(opts);
1768
1906
  const data = await api.post(canvasActionPath(canvasId, cfg.workspaceId), {
1769
1907
  action: "placeLayout",
1770
1908
  doc,
@@ -1772,60 +1910,27 @@ Placement (relative to nodes already on the canvas):
1772
1910
  ...(opts.into ? { intoSection: opts.into } : {}),
1773
1911
  ...(opts.dryRun ? { dryRun: true } : {}),
1774
1912
  });
1775
- // The notes exist once the call returns, even when placing failed:
1776
- // never re-run a spec with notes to retry, it duplicates them.
1777
- const createdNotes = data.notes;
1778
- const createdRows = (createdNotes?.results || []);
1779
- if (createdNotes) {
1780
- for (const row of createdRows) {
1781
- reportHeadlineWarnings(readHeadlineWarnings(row), typeof row.displayId === "string" ? row.displayId : undefined);
1782
- if (typeof row.hint === "string" && row.hint.trim())
1783
- console.error(`Hint: ${row.hint.trim()}`);
1784
- }
1785
- const unresolved = describeUnresolvedMentions(createdNotes.unresolvedMentions);
1786
- if (unresolved) {
1787
- console.error(`\n⚠ Some relationship mentions did not resolve. The ${createdRows.length} note(s) ` +
1788
- `were CREATED but carry broken links:\n${unresolved}\n` +
1789
- `Fix forward: cnotes versions create <id> --markdown-file <fixed.md>. ` +
1790
- `Do NOT re-run place — it would duplicate the notes.`);
1791
- process.exitCode = EXIT_CODES.VALIDATION;
1792
- }
1793
- }
1913
+ const createdRows = reportPlacedNotes(data);
1794
1914
  // No canvas was mutated on a dry run, so don't surface a "here's what I
1795
1915
  // built" link for it.
1796
1916
  const link = opts.dryRun
1797
1917
  ? null
1798
1918
  : await resolveCanvasLink(api, cfg, canvasId);
1799
- // The server answers 207 with per-item results. Partial failure keeps
1800
- // exit 0 (the caller inspects items[].error — documented contract),
1801
- // but when EVERY item and edge failed, nothing was placed and exiting
1802
- // 0 would report success to an agent that keys on the exit code.
1803
- const allItems = (data.items || []);
1804
- const allEdges = (data.edges || []);
1805
- const nothingPlaced = !data.dryRun &&
1806
- allItems.length + allEdges.length > 0 &&
1807
- allItems.every((r) => !r.id || r.error) &&
1808
- allEdges.every((e) => !e.id || e.error);
1919
+ const nothingPlaced = placedNothing(data);
1809
1920
  if (nothingPlaced)
1810
1921
  process.exitCode = EXIT_CODES.GENERIC;
1811
1922
  if (cfg.json) {
1812
1923
  if (link)
1813
1924
  data.url = link;
1814
1925
  outputJson(data);
1815
- if (nothingPlaced) {
1816
- console.error(JSON.stringify({
1817
- error: "placeLayout placed nothing: every item and edge failed",
1818
- code: "PlaceFailed",
1819
- exitCode: EXIT_CODES.GENERIC,
1820
- hint: "Inspect items[].error and edges[].error in the response above; fix the failing refs and retry.",
1821
- }));
1822
- }
1926
+ if (nothingPlaced)
1927
+ reportNothingPlacedJson();
1823
1928
  }
1824
1929
  else {
1825
- const items = (data.items || []);
1826
- const edges = (data.edges || []);
1827
- const bbox = data.bbox;
1828
1930
  if (data.dryRun) {
1931
+ const items = (data.items || []);
1932
+ const edges = (data.edges || []);
1933
+ const bbox = data.bbox;
1829
1934
  console.log(`[dry run] Would place ${items.length} item${items.length === 1 ? "" : "s"} ` +
1830
1935
  `and ${edges.length} edge${edges.length === 1 ? "" : "s"} (no changes made).`);
1831
1936
  if (bbox?.width && bbox?.height) {
@@ -1833,38 +1938,7 @@ Placement (relative to nodes already on the canvas):
1833
1938
  }
1834
1939
  return;
1835
1940
  }
1836
- if (createdRows.length > 0) {
1837
- console.log(`Created ${createdRows.length} note${createdRows.length === 1 ? "" : "s"}: ` +
1838
- createdRows.map((r) => `${r.key} → ${r.displayId}`).join(", "));
1839
- }
1840
- const placed = items.filter((r) => r.id && !r.error).length;
1841
- const failed = items.filter((r) => !r.id || r.error).length;
1842
- const edgesAdded = edges.filter((e) => e.id && !e.error).length;
1843
- const edgesFailed = edges.filter((e) => !e.id || e.error).length;
1844
- console.log(`Placed ${placed} items${failed > 0 ? ` (${failed} failed)` : ""}, ` +
1845
- `${edgesAdded} edges${edgesFailed > 0 ? ` (${edgesFailed} failed)` : ""}`);
1846
- if (bbox?.width && bbox?.height) {
1847
- console.log(`Layout bounding box: ${Math.round(bbox.width)} × ${Math.round(bbox.height)}px`);
1848
- }
1849
- const arranged = (data.arrangedSections || []);
1850
- for (const a of arranged) {
1851
- if (a.error)
1852
- console.log(` ✗ section ${a.displayId ?? a.sectionId} could not arrange itself: ${a.error}`);
1853
- else
1854
- console.log(` Arranged ${a.displayId} (${a.width} × ${a.height}px); it keeps itself laid out`);
1855
- }
1856
- // Surface item-level errors so the user doesn't have to re-run with --json
1857
- for (const item of items) {
1858
- if (item.error)
1859
- console.log(` ✗ item[${item.index}] (${item.type}): ${item.error}`);
1860
- }
1861
- for (const edge of edges) {
1862
- if (edge.error)
1863
- console.log(` ✗ edge ${edge.from} → ${edge.to}: ${edge.error}`);
1864
- }
1865
- if (nothingPlaced) {
1866
- console.error("Error: nothing was placed — every item and edge failed (see above).");
1867
- }
1941
+ printPlaceSummary(data, createdRows);
1868
1942
  if (link)
1869
1943
  console.log(`Link: ${link}`);
1870
1944
  }
@@ -48,6 +48,20 @@ export function applyIntentOptions(program) {
48
48
  export function intentBracketFor(cmd) {
49
49
  return brackets.get(cmd);
50
50
  }
51
+ const preflights = new WeakMap();
52
+ /**
53
+ * A check intent-runner runs in the parent BEFORE it opens the run: local
54
+ * input the command would refuse anyway (a spec file that is not JSON, a
55
+ * markdown file that does not exist) fails here first, so the call opens no
56
+ * run and leaves no empty one behind. It must read nothing the child needs to
57
+ * read again (stdin), and print nothing the child will print.
58
+ */
59
+ export function setIntentPreflight(cmd, preflight) {
60
+ preflights.set(cmd, preflight);
61
+ }
62
+ export function intentPreflightFor(cmd) {
63
+ return preflights.get(cmd);
64
+ }
51
65
  /**
52
66
  * What `--intent` should do for this invocation. A canvas bracket needs the
53
67
  * canvas the command names; without one it falls back to a workspace run.
@@ -6,7 +6,7 @@ import { resolveHostAgentSession } from "./claude-session.js";
6
6
  import { readHeadlineWarnings, reportHeadlineWarnings } from "./headline-warnings.js";
7
7
  import { canvasActionPath } from "./canvas-paths.js";
8
8
  import { handleError } from "./errors.js";
9
- import { decideIntentRun, intentBracketFor, INTENT_CHILD_ENV } from "./intent-run.js";
9
+ import { decideIntentRun, intentBracketFor, intentPreflightFor, INTENT_CHILD_ENV } from "./intent-run.js";
10
10
  /**
11
11
  * Root preAction hook: when the command carries `--intent`, open a run, re-run
12
12
  * this same command line as a child with the run in its environment, close the
@@ -23,13 +23,19 @@ export async function runUnderIntent(program, actionCommand) {
23
23
  const intent = actionCommand.opts().intent;
24
24
  if (!bracket || !intent)
25
25
  return;
26
+ // The child runs the command itself, with the run in its environment; it
27
+ // needs nothing from here, not even the config (which the command resolves,
28
+ // and which a parse-only harness with no credentials does not have).
29
+ const isChild = process.env[INTENT_CHILD_ENV] === "1";
30
+ if (isChild)
31
+ return;
26
32
  const cfg = resolveConfig(program.opts());
27
33
  const decision = decideIntentRun({
28
34
  intent,
29
35
  bracket,
30
36
  canvasRef: actionCommand.processedArgs[0],
31
37
  attachedRunId: resolveActiveAgentRun(cfg.serverUrl)?.agentRunId,
32
- isChild: process.env[INTENT_CHILD_ENV] === "1",
38
+ isChild,
33
39
  });
34
40
  if (decision.kind === "none")
35
41
  return;
@@ -37,6 +43,16 @@ export async function runUnderIntent(program, actionCommand) {
37
43
  console.error(`# joined the open run ${decision.agentRunId}; --intent is not its headline`);
38
44
  return;
39
45
  }
46
+ // Input the command would refuse is refused here, before a run exists.
47
+ const preflight = intentPreflightFor(actionCommand);
48
+ if (preflight) {
49
+ try {
50
+ await preflight(actionCommand.opts());
51
+ }
52
+ catch (error) {
53
+ handleError(error, cfg.json);
54
+ }
55
+ }
40
56
  const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
41
57
  const agentSession = await resolveHostAgentSession();
42
58
  const canvasPath = decision.canvasRef ? canvasActionPath(decision.canvasRef, cfg.workspaceId) : null;
@@ -408,13 +408,52 @@ server.tool("cnotes_canvas_read_section", "Read ONE section frame of a canvas: e
408
408
  const read = await api.get("/api/canvas/read", { section, workspaceId });
409
409
  return read.result;
410
410
  }));
411
- server.tool("cnotes_canvas_create", "Create a new canvas. Goal and target audience are required — every canvas must declare the result it exists to produce and who it serves. Write the goal FIRST, for a reader: a result sentence, then a \"Done when\" sentence (the server rejects a goal without one).", {
411
+ /** The layout document `cnotes_canvas_place` takes, shared with `cnotes_canvas_create`. */
412
+ const layoutDocArg = z
413
+ .object({
414
+ root: z
415
+ .unknown()
416
+ .describe("Root LayoutNode. kind is one of: 'stack' (items flow along one axis, like CSS flexbox: {kind:'stack', axis:'vertical'|'horizontal', gap?, align?:'start'|'center'|'end', items:[LayoutNode...]}), 'grid' (N columns, items wrap to new rows: {kind:'grid', columns:<n>, gap?, items:[...]}), 'anchor' (place a sub-tree relative to an EXISTING canvas node: {kind:'anchor', to:'<displayId or node id>', direction:'right'|'left'|'above'|'below' — exactly these four, NOT top/bottom/up/down, gap?, child:LayoutNode}), 'section' (a named frame that sizes itself around its content: {kind:'section', name:'<title>', key?, child:LayoutNode}), or 'item' (a leaf — one per visible thing, NO x/y: {kind:'item', type:'note'|'richtext'|'list'|'canvas'|'section', key?, ...type-specific fields}). gap accepts a preset 'tight'|'medium'|'spacious' or a raw pixel number (default 'medium')."),
417
+ edges: z
418
+ .array(z.unknown())
419
+ .optional()
420
+ .describe("Edges between placed/existing nodes: [{from, to, label?}]. Endpoints resolve in priority order: '@<key>' of an item placed in this call, the noteId of a note placed in this call (e.g. 'NOTE-7'), or the displayId/convex id of a node already on the canvas."),
421
+ origin: z
422
+ .object({ x: z.number(), y: z.number() })
423
+ .optional()
424
+ .describe("Top-left corner of the whole layout. Omit it and placement 'auto'/'append' pick a safe spot for you."),
425
+ placement: z
426
+ .enum(["auto", "append", "exact"])
427
+ .optional()
428
+ .describe("Where the layout lands vs existing content: 'auto' (default, collision-aware — drops into a clear band below existing nodes and slides down to de-collide), 'append' (always below everything), 'exact' (honor origin verbatim, pixel-perfect templates only)."),
429
+ })
430
+ .passthrough()
431
+ .describe("Layout document { root, edges?, origin?, placement? }. Describe STRUCTURE via the four node kinds (stack / grid / anchor / item, plus section frames) — the server resolves pixels. The schema is strict server-side: an unknown or typo'd key anywhere in the doc is rejected with the offending path named.");
432
+ /** New notes a layout creates and places in the same call. */
433
+ const layoutNotesArg = z
434
+ .array(z.object({
435
+ key: z.string(),
436
+ type: z.string(),
437
+ markdown: z.string(),
438
+ tags: z.array(z.string()).optional(),
439
+ changeDescription: z.string().optional(),
440
+ }))
441
+ .min(1)
442
+ .describe("Notes to create and place in this call (cnotes_notes_create item shape); a note leaf places one with noteId '@<key>'");
443
+ server.tool("cnotes_canvas_create", "Create a new canvas. Goal and target audience are required — every canvas must declare the result it exists to produce and who it serves. Write the goal FIRST, for a reader: a result sentence, then a \"Done when\" sentence (the server rejects a goal without one).\n\nLAY IT OUT IN THE SAME CALL: pass `doc` (and `notes`), exactly as cnotes_canvas_place takes them, and the server places the layout onto the new canvas before it answers, under `layout` in the result. One call replaces create then place. New notes need an open run, as cnotes_notes_create does. A layout the server refuses creates nothing: fix the doc and call this again.", {
412
444
  name: z.string().describe("Canvas name"),
413
445
  goal: z.string().describe(`${CANVAS_GOAL_DESCRIPTION} Required.`),
414
446
  targetAudience: z.string().describe("Target audience — who this canvas is meant to serve or inform, and what they do with it. Required."),
415
- }, async ({ name, goal, targetAudience }) => {
416
- return withErrorHandling(() => api.post("/api/canvas", { workspaceId, title: name, goal, targetAudience }));
417
- });
447
+ doc: layoutDocArg.optional(),
448
+ notes: layoutNotesArg.optional(),
449
+ }, async ({ name, goal, targetAudience, doc, notes }) => withErrorHandling(() => api.post("/api/canvas", {
450
+ workspaceId,
451
+ title: name,
452
+ goal,
453
+ targetAudience,
454
+ ...(doc ? { doc } : {}),
455
+ ...(notes ? { notes } : {}),
456
+ })));
418
457
  server.tool("cnotes_canvas_update", "Update canvas metadata: title, goal, and/or target audience. Use this to set or fix the goal a board is scoped to (cnotes_canvas_read shows the current one under the title). The goal follows the same two-sentence shape as on create and is rejected without a \"Done when\" sentence.", {
419
458
  canvasId: z.string().describe("Canvas ID"),
420
459
  title: z.string().optional().describe("New canvas title"),
@@ -612,41 +651,12 @@ server.tool("cnotes_canvas_bulk_add", "LOW-LEVEL: add items at raw x/y that YOU
612
651
  }));
613
652
  server.tool("cnotes_canvas_place", "Place items on a canvas using a DECLARATIVE LAYOUT (no x/y math). The server measures every item, packs them with no overlaps, and inserts them in a single batch. PREFER THIS over cnotes_canvas_bulk_add whenever you can express the layout as stacks/grids/anchors — which is almost always. The agent should describe STRUCTURE (rows, columns, what's near what), not pixel coordinates.\n\nELEMENT CHOICE: default content to typed NOTES (the only versioned, searchable tier agents can read back); richtext = the Text element, card-sized framing only (a heading is just content '# Title', untinted), section = a named region frame, list = member notes behind a one-line frame, edges connect notes only.\n\nThe call is best-effort, NOT atomic: per-item failures are reported in the response (HTTP 207) but the items that succeeded stay on the canvas. Always inspect `items[].error` and `edges[].error` in the response.\n\nThe `doc` argument is a layout document:\n { root: <LayoutNode>, edges?: [{from, to, label?}], origin?: {x, y} }\n\n<LayoutNode> is one of:\n • { kind: 'stack', axis: 'vertical'|'horizontal', gap?: 'tight'|'medium'|'spacious'|<px>, align?: 'start'|'center'|'end', items: [<LayoutNode>...] }\n • { kind: 'grid', columns: <n>, gap?: ..., items: [<LayoutNode>...] }\n • { kind: 'anchor', to: '<displayId or canvas node id>', direction: 'right'|'left'|'above'|'below', gap?: ..., child: <LayoutNode> }\n • { kind: 'item', type: 'note'|'richtext'|'list'|'canvas'|'section', key?: '<name>', ...item-specific fields }\n\nLeaf item shapes (no x/y!):\n note: { kind:'item', type:'note', noteId:'NOTE-3', key?:'a' }\n richtext: { kind:'item', type:'richtext', content:'# Markdown OK', size?:'small'|'medium'|'large', colorHex?:'<role hex>' } // the Text element: card-sized framing only; a heading is just content '# Title' with no colorHex; colorHex is a ROLE tint (#3B82F6 evidence · #22C55E commitment · #EC4899 insight · #F59E0B warning · #EF4444 danger · #8B5CF6 people — anything else snaps to the nearest), default untinted; plain markdown, NO [NOTE-X](relationship:...) mention syntax (corrupts the card); knowledge worth keeping = a note\n list: { kind:'item', type:'list', description:'One-line frame — first paragraph becomes the title', noteIds?:['NOTE-1','NOTE-2'], viewMode?:'list'|'grid' } // description is REQUIRED and is a frame, never the content: N distinct things = N notes in noteIds\n canvas: { kind:'item', type:'canvas', linkedCanvasId:'<id>' }\n\nEdges reference endpoints by, in priority order: `@<key>` (any item with a `key` placed in the same call), the original noteId/displayId of a note placed in this call (e.g. 'NOTE-7'), or the displayId / convex id of a node already on the canvas.\n\nNEW NOTES IN THE SAME CALL: pass `notes` (the cnotes_notes_create item shape) and place each with a note leaf whose noteId is '@<key>'. Bodies cross-link with [@<key>: Title](relationship:<verb>); edges and anchors say '@<key>'. One call replaces notes_create then place, inside the same open operation. The notes are created only if the layout solves, and come back under `notes`.\n\nExample (a SWOT-like quadrant):\n {\n root: {\n kind:'stack', axis:'vertical', gap:'spacious',\n items:[\n { kind:'stack', axis:'horizontal', gap:'spacious', items:[\n { kind:'grid', columns:2, items:[\n { kind:'item', type:'note', noteId:'STR-1' },\n { kind:'item', type:'note', noteId:'STR-2' },\n ]},\n { kind:'grid', columns:2, items:[\n { kind:'item', type:'note', noteId:'WEAK-1' },\n ]},\n ]},\n { kind:'stack', axis:'horizontal', gap:'spacious', items:[ /* opportunities + threats */ ]},\n ],\n },\n }", {
614
653
  canvasId: z.string().describe("Canvas ID"),
615
- doc: z
616
- .object({
617
- root: z
618
- .unknown()
619
- .describe("Root LayoutNode. kind is one of: 'stack' (items flow along one axis, like CSS flexbox: {kind:'stack', axis:'vertical'|'horizontal', gap?, align?:'start'|'center'|'end', items:[LayoutNode...]}), 'grid' (N columns, items wrap to new rows: {kind:'grid', columns:<n>, gap?, items:[...]}), 'anchor' (place a sub-tree relative to an EXISTING canvas node: {kind:'anchor', to:'<displayId or node id>', direction:'right'|'left'|'above'|'below' — exactly these four, NOT top/bottom/up/down, gap?, child:LayoutNode}), 'section' (a named frame that sizes itself around its content: {kind:'section', name:'<title>', key?, child:LayoutNode}), or 'item' (a leaf — one per visible thing, NO x/y: {kind:'item', type:'note'|'richtext'|'list'|'canvas'|'section', key?, ...type-specific fields}). gap accepts a preset 'tight'|'medium'|'spacious' or a raw pixel number (default 'medium')."),
620
- edges: z
621
- .array(z.unknown())
622
- .optional()
623
- .describe("Edges between placed/existing nodes: [{from, to, label?}]. Endpoints resolve in priority order: '@<key>' of an item placed in this call, the noteId of a note placed in this call (e.g. 'NOTE-7'), or the displayId/convex id of a node already on the canvas."),
624
- origin: z
625
- .object({ x: z.number(), y: z.number() })
626
- .optional()
627
- .describe("Top-left corner of the whole layout. Omit it and placement 'auto'/'append' pick a safe spot for you."),
628
- placement: z
629
- .enum(["auto", "append", "exact"])
630
- .optional()
631
- .describe("Where the layout lands vs existing content: 'auto' (default, collision-aware — drops into a clear band below existing nodes and slides down to de-collide), 'append' (always below everything), 'exact' (honor origin verbatim, pixel-perfect templates only)."),
632
- })
633
- .passthrough()
634
- .describe("Layout document { root, edges?, origin?, placement? }. Describe STRUCTURE via the four node kinds (stack / grid / anchor / item, plus section frames) — the server resolves pixels. The schema is strict server-side: an unknown or typo'd key anywhere in the doc is rejected with the offending path named."),
654
+ doc: layoutDocArg,
635
655
  intoSection: z
636
656
  .string()
637
657
  .optional()
638
658
  .describe("SECTION-<n> to put the items INTO: appended to its layout (end of its shortest column, or the next grid cell); the section re-arranges and resizes. A section container in the doc creates an ARRANGED section that keeps its cards laid out until a card is moved by hand; add to it later with intoSection, never by aiming origin inside the frame. The doc may not contain sections when intoSection is set."),
639
- notes: z
640
- .array(z.object({
641
- key: z.string(),
642
- type: z.string(),
643
- markdown: z.string(),
644
- tags: z.array(z.string()).optional(),
645
- changeDescription: z.string().optional(),
646
- }))
647
- .min(1)
648
- .optional()
649
- .describe("Notes to create and place in this call (cnotes_notes_create item shape); a note leaf places one with noteId '@<key>'"),
659
+ notes: layoutNotesArg.optional(),
650
660
  }, async ({ canvasId, doc, intoSection, notes }) => withErrorHandling(() => api.post(`/api/canvas/${encodeURIComponent(canvasId)}?workspaceId=${encodeURIComponent(workspaceId)}`, {
651
661
  action: "placeLayout",
652
662
  doc,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creator-notes/cnotes",
3
- "version": "0.110.1",
3
+ "version": "0.111.1",
4
4
  "description": "CLI for CreatorNotes — create notes, build canvases, search knowledge from the terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@inquirer/prompts": "^8.3.2",
61
- "@modelcontextprotocol/sdk": "^1.12.0",
61
+ "@modelcontextprotocol/sdk": "^1.32.2",
62
62
  "commander": "^12.1.0",
63
63
  "open": "^10.1.0",
64
64
  "update-notifier": "^5.1.0",
@@ -21,7 +21,7 @@ Every note and canvas you write is context: what the next reader, a teammate or
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>`.
24
- 7. **Lay out the canvas.** `cnotes canvas place <canvasId> --spec layout.json` packs items without overlap. A spec can carry the notes too (see the fast path below), which folds steps 5 and 7 into one call. Read [references/canvas-elements.md](references/canvas-elements.md) before choosing elements and [references/canvas-layout.md](references/canvas-layout.md) before writing the spec.
24
+ 7. **Lay out the canvas.** `cnotes canvas place <canvasId> --spec layout.json` packs items without overlap. A spec can carry the notes too (see the fast path below), which folds steps 5 and 7 into one call. For a new canvas, `canvas create --spec` takes the same spec, so creating the canvas, its notes and its layout is one call. Read [references/canvas-elements.md](references/canvas-elements.md) before choosing elements and [references/canvas-layout.md](references/canvas-layout.md) before writing the spec.
25
25
  8. **Read it back.** `cnotes canvas read <canvasId>`: every claim must appear in a note with a display ID, and the banner must make sense to someone who was not in the session. A write that touches no canvas gets the same test: `cnotes notes get <id> --expand` on what you wrote, read as the next session will, without this conversation.
26
26
  9. **Close the run.** `cnotes operations end`.
27
27
  10. **Link the result.** End your reply with the canvas link (see [Surfacing the canvas link](#surfacing-the-canvas-link)).
@@ -46,7 +46,15 @@ Adding cards, filling or tidying a section, linking two cards or removing one ta
46
46
  Other single changes take the same flag: `cnotes canvas arrange <canvasId> --section SECTION-7 --intent "Tidied the Risks section"`, `cnotes canvas bulk-remove <canvasId> --nodes '["NOTE-4"]' --intent "Removed the duplicate risk card"`.
47
47
  3. **Link the canvas** from the `Link:` line, in the same reply.
48
48
 
49
- Several writes that belong together (a new canvas and its first layout, notes on two canvases) still go in one `operations begin`/`end` run, so the timeline shows one change. Open [references/canvas-layout.md](references/canvas-layout.md) only when the layout needs anchors, origins or several sections; the rules above and step 7 below cover the rest.
49
+ ## Fast path: a new canvas
50
+
51
+ A new canvas with its notes and layout is one write. Read first, in parallel (`cnotes brief`, `cnotes canvas search`, `cnotes types show <Type>` for each type), then create the canvas and place the spec in the same command:
52
+
53
+ `cnotes canvas create "Q1 · Roadmap" --goal "<goal>" --audience "<who>" --spec spec.json --intent "Built the Q1 roadmap canvas"`
54
+
55
+ The spec is the same document `canvas place` takes, `notes` array included, and the result carries the placement under `layout`. The spec is checked before the canvas exists, and a layout the server refuses removes the canvas again, so a bad file, a missing run or a refused layout creates nothing: fix the spec and run the same command again.
56
+
57
+ Other writes that belong together (notes on two canvases, a change that needs several kinds of command) still go in one `operations begin`/`end` run, so the timeline shows one change. Open [references/canvas-layout.md](references/canvas-layout.md) only when the layout needs anchors, origins or several sections; the rules above and step 7 below cover the rest.
50
58
 
51
59
  ## Rules that hold on every task
52
60
 
@@ -63,6 +63,9 @@ cnotes canvas digest <canvasId>
63
63
  # NAMING: separate parts with the interpunct · (U+00B7, MIDDLE DOT, not a bullet •),
64
64
  # never an em or en dash: "Path to Revenue · Funding strategy".
65
65
  cnotes canvas create "<name>" --goal "<text>" [--audience "<text>"] # prints Ref (CANVAS-N) + Link; end your reply with them
66
+ cnotes canvas create "<name>" --goal "<text>" --audience "<text>" --spec spec.json --intent "<headline>"
67
+ # the canvas AND its first layout in one call: --spec is the `canvas place` document, notes included;
68
+ # the placement comes back under `layout`. A refused layout creates nothing: fix the spec, run it again.
66
69
  # --goal is not optional in practice. Write it FIRST, for a reader, in two short sentences:
67
70
  # <Decide | Rank | Agree | Show | Plan | Record> <the object>. Done when <what is visibly true on the board>.
68
71
  # e.g. "Decide which phone-section bugs ship in the next PR. Done when every card is in a PR or marked won't fix."