@coderook/cli 0.46.8 → 0.46.9

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.
@@ -2,7 +2,7 @@
2
2
  "name": "coderook",
3
3
  "displayName": "CodeRook",
4
4
  "description": "Save, browse and restore whole-snapshot versions of a project on CodeRook, with cbx or plain git, from Claude Code.",
5
- "version": "0.46.8",
5
+ "version": "0.46.9",
6
6
  "author": {
7
7
  "name": "ACCA Gaming Productions",
8
8
  "url": "https://coderook.com"
package/README.md CHANGED
@@ -784,6 +784,10 @@ is reachable, and who this machine is signed in as.
784
784
  `0` on success, `1` on failure. Every command prints why it failed on standard
785
785
  error, so a script can branch on the status and log the reason.
786
786
 
787
+ `cbx submit` and `cbx workspace save` exit `3` when the save was kept as a
788
+ merge (`M-n`) instead of landing on the line, because somebody changed the same
789
+ lines first. Nothing is lost: settle it with `cbx merge M-n`.
790
+
787
791
  ## Source and licence
788
792
 
789
793
  The `cbx` command line and the CBX engine it is built on are open source under
@@ -23,6 +23,7 @@ const node_stream_1 = require("node:stream");
23
23
  const node_zlib_1 = require("node:zlib");
24
24
  const node_path_1 = __importDefault(require("node:path"));
25
25
  const safe_path_js_1 = require("../shared/safe_path.js");
26
+ const chunking_js_1 = require("../shared/chunking.js");
26
27
  const identify_js_1 = require("./identify.js");
27
28
  const faults_js_1 = require("./faults.js");
28
29
  const retry_js_1 = require("./retry.js");
@@ -692,7 +693,59 @@ class Downloader {
692
693
  can say it happened.
693
694
  */
694
695
  recoveredFromGzip = [];
695
- async fetchInto(repositoryId, versionId, file, target, halt) {
696
+ /** Pieces of large files taken from the copy already in the folder rather than downloaded. */
697
+ piecesReused = 0;
698
+ /**
699
+ * Where each piece of `pieces` already sits in `localCopy`, by digest.
700
+ *
701
+ * Pieces are cut by content, so the parts of a large file a change did not
702
+ * touch cut into the same pieces again. Cutting the copy already in the
703
+ * folder the way the upload did finds them, and only the rest is fetched:
704
+ * a 1 MB edit inside a 1.2 GB file made every catch-up download all 1.2 GB
705
+ * again (2026-11-11 agent exercise, about 250 s each). Which profile the
706
+ * upload used is not in the listing, so the one whose target size is
707
+ * nearest the pieces' own median is taken; a wrong guess finds nothing and
708
+ * costs one read of the local file.
709
+ */
710
+ async localPieces(localCopy, pieces) {
711
+ const found = await (0, promises_1.stat)(localCopy).catch(() => null);
712
+ if (!found?.isFile() || pieces.length < 2)
713
+ return null;
714
+ const total = pieces.reduce((sum, piece) => sum + piece.sourceSize, 0);
715
+ const sizes = pieces.map((piece) => piece.sourceSize).sort((left, right) => left - right);
716
+ const median = sizes[sizes.length >> 1] ?? 0;
717
+ const candidates = [(0, chunking_js_1.microchunkProfileForFileSize)(total), (0, chunking_js_1.profileForFileSize)(total)].filter((one) => one !== null);
718
+ if (!candidates.length)
719
+ return null;
720
+ const profile = candidates.reduce((best, one) => Math.abs(one.targetSize - median) < Math.abs(best.targetSize - median) ? one : best);
721
+ const wanted = new Set(pieces.map((piece) => piece.sha256).filter(Boolean));
722
+ const where = new Map();
723
+ const note = (bytes, offset) => {
724
+ const digest = (0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex");
725
+ if (wanted.has(digest) && !where.has(digest))
726
+ where.set(digest, { offset, length: bytes.length });
727
+ };
728
+ let pending = Buffer.alloc(0);
729
+ let pendingAt = 0;
730
+ for await (const block of (0, node_fs_1.createReadStream)(localCopy, { highWaterMark: 8 * 1024 * 1024 })) {
731
+ this.check();
732
+ const incoming = Buffer.from(block);
733
+ pending = pending.length ? Buffer.concat([pending, incoming]) : incoming;
734
+ let from = 0;
735
+ for (const cut of (0, chunking_js_1.cutPoints)(pending, profile)) {
736
+ note(pending.subarray(from, cut), pendingAt + from);
737
+ from = cut;
738
+ }
739
+ pendingAt += from;
740
+ pending = Buffer.from(pending.subarray(from));
741
+ }
742
+ if (pending.length)
743
+ note(pending, pendingAt);
744
+ return where.size ? where : null;
745
+ }
746
+ async fetchInto(repositoryId, versionId, file, target, halt,
747
+ /* The copy of this file already in the folder, whose unchanged pieces need not be fetched. */
748
+ localCopy) {
696
749
  /*
697
750
  A sealed file is read whole, by path, whatever shape it is stored in.
698
751
 
@@ -731,11 +784,40 @@ class Downloader {
731
784
  a 1.25 GB restore came down at 2.6 MB/s (2026-11-11).
732
785
  */
733
786
  const AHEAD = 4;
787
+ const onDisk = localCopy ? await this.localPieces(localCopy, pieces).catch(() => null) : null;
788
+ const reuse = async (piece) => {
789
+ const place = onDisk?.get(piece.sha256);
790
+ if (!place || !localCopy)
791
+ return null;
792
+ const handle = await (0, promises_1.open)(localCopy, "r");
793
+ try {
794
+ const body = Buffer.alloc(place.length);
795
+ const { bytesRead } = await handle.read(body, 0, place.length, place.offset);
796
+ if (bytesRead !== place.length)
797
+ return null;
798
+ /* Checked like a download: a file changed since it was cut is fetched instead. */
799
+ if ((0, node_crypto_1.createHash)("sha256").update(body).digest("hex") !== piece.sha256)
800
+ return null;
801
+ return { body, headers: new Headers() };
802
+ }
803
+ finally {
804
+ await handle.close();
805
+ }
806
+ };
807
+ const counted = () => {
808
+ this.piecesReused += 1;
809
+ };
734
810
  const source = (async function* () {
735
811
  const asked = [];
736
812
  const ask = (at) => {
737
813
  const piece = pieces[at];
738
- const reply = fetchPiece(`/v1/repositories/${repositoryId}/objects/${piece.objectId}`, `${file.path} (piece ${at + 1} of ${pieces.length})`);
814
+ const reply = reuse(piece).then((local) => {
815
+ if (local) {
816
+ counted();
817
+ return local;
818
+ }
819
+ return fetchPiece(`/v1/repositories/${repositoryId}/objects/${piece.objectId}`, `${file.path} (piece ${at + 1} of ${pieces.length})`);
820
+ });
739
821
  /* Awaited in turn below; this only stops an early stop leaving it unhandled. */
740
822
  reply.catch(() => undefined);
741
823
  asked[at] = reply;
@@ -931,12 +1013,24 @@ class Downloader {
931
1013
  14,125 files each spent twenty minutes re-downloading 306 MB apiece).
932
1014
  */
933
1015
  const kept = new Set();
1016
+ /*
1017
+ Files the version left alone that are gone from the folder: deleted
1018
+ here and not saved yet. Catching up put them back, which turned an
1019
+ unsaved rename into a copy (Opus55-1, 2026-11-11). They stay deleted,
1020
+ and the record still names them, so status shows the deletion waiting
1021
+ to be saved.
1022
+ */
1023
+ const deletedHere = new Set();
934
1024
  if (mode === "reconcile" && held) {
935
1025
  for (const file of files) {
936
1026
  if (!file.sha256 || held[file.path] !== file.sha256)
937
1027
  continue;
938
- if (!(await exists((0, safe_path_js_1.inside)(destination, file.path))))
1028
+ if (!(await exists((0, safe_path_js_1.inside)(destination, file.path)))) {
1029
+ deletedHere.add(file.path);
1030
+ kept.add(file.path);
1031
+ manifest[file.path] = file.sha256;
939
1032
  continue;
1033
+ }
940
1034
  kept.add(file.path);
941
1035
  manifest[file.path] = file.sha256;
942
1036
  written += 1;
@@ -1056,7 +1150,9 @@ class Downloader {
1056
1150
  const restoreFile = async (file) => {
1057
1151
  const full = (0, safe_path_js_1.inside)(staging, file.path);
1058
1152
  await (0, promises_1.mkdir)(node_path_1.default.dirname(full), { recursive: true });
1059
- const digest = await this.fetchInto(repositoryId, versionId, file, full, halt.signal);
1153
+ /* A file in pieces can take its unchanged pieces from the copy already here. */
1154
+ const localCopy = file.chunks?.length ? (0, safe_path_js_1.inside)(destination, file.path) : undefined;
1155
+ const digest = await this.fetchInto(repositoryId, versionId, file, full, halt.signal, localCopy);
1060
1156
  /*
1061
1157
  The whole file's digest, checked after every piece has already been
1062
1158
  checked individually. Both are needed: the pieces catch a corrupt or
@@ -1275,7 +1371,15 @@ class Downloader {
1275
1371
  percent: 100,
1276
1372
  });
1277
1373
  /* How many were already here and left alone, so a caller can say nothing was fetched. */
1278
- return { files: written, bytes, manifest, unchanged: kept.size, placedFiles: placedRecord, removed: removedHere };
1374
+ return {
1375
+ files: written,
1376
+ bytes,
1377
+ manifest,
1378
+ unchanged: kept.size - deletedHere.size,
1379
+ placedFiles: placedRecord,
1380
+ removed: removedHere,
1381
+ leftDeleted: deletedHere.size,
1382
+ };
1279
1383
  }
1280
1384
  catch (error) {
1281
1385
  await (0, promises_1.rm)(staging, { recursive: true, force: true });
@@ -1433,6 +1433,7 @@ class Uploader {
1433
1433
  storedBytes: completed.version.storedSize ?? storedBytes,
1434
1434
  sentBytes: progress.transferred,
1435
1435
  sentFiles: uploaded.length - progress.alreadyOnAccount,
1436
+ repackedFiles: this.foldPaths.size,
1436
1437
  reusedFiles: reused.length,
1437
1438
  /** Selected, but the service already held the content. */
1438
1439
  alreadyStoredFiles: progress.alreadyOnAccount,
@@ -15,6 +15,7 @@
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.linesOf = linesOf;
17
17
  exports.diffLines = diffLines;
18
+ exports.diffLinesWithin = diffLinesWithin;
18
19
  exports.foldUnchanged = foldUnchanged;
19
20
  exports.conflictDraft = conflictDraft;
20
21
  exports.hasConflictMarkers = hasConflictMarkers;
@@ -57,8 +58,67 @@ function linesOf(text) {
57
58
  * make.
58
59
  */
59
60
  function diffLines(target, candidate) {
61
+ return diffLinesWithin(target, candidate, Number.POSITIVE_INFINITY);
62
+ }
63
+ /*
64
+ Past this many cells the table is not built: the middle is compared by the
65
+ shortest edit instead, whose cost follows the number of changed lines.
66
+ */
67
+ const MOST_TABLE_CELLS = 4_000_000;
68
+ /**
69
+ * `diffLines`, giving up (null) only when more than `maxEdits` lines differ.
70
+ *
71
+ * Lines both sides share at the start and the end are matched first: a longest
72
+ * common subsequence can always keep them, so the answer is the same and only
73
+ * the changed middle is compared. That middle goes through the exact table when
74
+ * it is small, and otherwise through the shortest edit (Myers), which is exact
75
+ * too and costs memory in the number of changes rather than in lines squared.
76
+ * `cbx diff` refused any file over 4,000 lines before, so a one-line change to
77
+ * the 4,937-line cli.ts could not be reviewed at all (2026-11-11).
78
+ */
79
+ function diffLinesWithin(target, candidate, maxEdits) {
60
80
  const left = linesOf(target);
61
81
  const right = linesOf(candidate);
82
+ let head = 0;
83
+ while (head < left.length && head < right.length && left[head] === right[head])
84
+ head += 1;
85
+ let tail = 0;
86
+ while (tail < left.length - head &&
87
+ tail < right.length - head &&
88
+ left[left.length - 1 - tail] === right[right.length - 1 - tail])
89
+ tail += 1;
90
+ const middleLeft = left.slice(head, left.length - tail);
91
+ const middleRight = right.slice(head, right.length - tail);
92
+ const middle = (middleLeft.length + 1) * (middleRight.length + 1) <= MOST_TABLE_CELLS
93
+ ? byTable(middleLeft, middleRight)
94
+ : shortestEdit(middleLeft, middleRight, maxEdits);
95
+ if (!middle)
96
+ return null;
97
+ if (middle.filter((line) => line.side !== "same").length > maxEdits)
98
+ return null;
99
+ const out = [];
100
+ for (let at = 0; at < head; at += 1) {
101
+ out.push({ side: "same", targetLine: at + 1, candidateLine: at + 1, text: left[at] });
102
+ }
103
+ for (const line of middle) {
104
+ out.push({
105
+ ...line,
106
+ targetLine: line.targetLine === null ? null : line.targetLine + head,
107
+ candidateLine: line.candidateLine === null ? null : line.candidateLine + head,
108
+ });
109
+ }
110
+ for (let at = tail; at > 0; at -= 1) {
111
+ out.push({
112
+ side: "same",
113
+ targetLine: left.length - at + 1,
114
+ candidateLine: right.length - at + 1,
115
+ text: left[left.length - at],
116
+ });
117
+ }
118
+ return out;
119
+ }
120
+ /** The exact table walk, for a middle small enough to tabulate. */
121
+ function byTable(left, right) {
62
122
  const table = commonRuns(left, right);
63
123
  const out = [];
64
124
  let a = 0;
@@ -103,6 +163,82 @@ function diffLines(target, candidate) {
103
163
  }
104
164
  return out;
105
165
  }
166
+ /**
167
+ * Myers' shortest edit between two line lists, or null past `maxEdits`.
168
+ *
169
+ * Each round d keeps only the furthest point reached on each diagonal, so the
170
+ * memory kept for walking back is about d squared over two entries rather than
171
+ * one per pair of lines.
172
+ */
173
+ function shortestEdit(left, right, maxEdits) {
174
+ const n = left.length;
175
+ const m = right.length;
176
+ const limit = Math.min(n + m, Number.isFinite(maxEdits) ? maxEdits : n + m);
177
+ const trace = [];
178
+ const at = (row, d, k) => row[k + d];
179
+ let done = false;
180
+ for (let d = 0; d <= limit && !done; d += 1) {
181
+ const previous = trace[d - 1];
182
+ const row = new Int32Array(2 * d + 1);
183
+ for (let k = -d; k <= d; k += 2) {
184
+ let x;
185
+ if (d === 0)
186
+ x = 0;
187
+ else if (k === -d || (k !== d && at(previous, d - 1, k - 1) < at(previous, d - 1, k + 1))) {
188
+ x = at(previous, d - 1, k + 1);
189
+ }
190
+ else {
191
+ x = at(previous, d - 1, k - 1) + 1;
192
+ }
193
+ let y = x - k;
194
+ while (x < n && y < m && left[x] === right[y]) {
195
+ x += 1;
196
+ y += 1;
197
+ }
198
+ row[k + d] = x;
199
+ if (x >= n && y >= m) {
200
+ done = true;
201
+ break;
202
+ }
203
+ }
204
+ trace.push(row);
205
+ }
206
+ if (!done)
207
+ return null;
208
+ const out = [];
209
+ let x = n;
210
+ let y = m;
211
+ for (let d = trace.length - 1; d >= 0; d -= 1) {
212
+ const k = x - y;
213
+ if (d === 0) {
214
+ while (x > 0 && y > 0) {
215
+ out.push({ side: "same", targetLine: x, candidateLine: y, text: left[x - 1] });
216
+ x -= 1;
217
+ y -= 1;
218
+ }
219
+ break;
220
+ }
221
+ const previous = trace[d - 1];
222
+ const down = k === -d || (k !== d && at(previous, d - 1, k - 1) < at(previous, d - 1, k + 1));
223
+ const fromK = down ? k + 1 : k - 1;
224
+ const fromX = at(previous, d - 1, fromK);
225
+ const fromY = fromX - fromK;
226
+ const startX = down ? fromX : fromX + 1;
227
+ const startY = down ? fromY + 1 : fromY;
228
+ while (x > startX && y > startY) {
229
+ out.push({ side: "same", targetLine: x, candidateLine: y, text: left[x - 1] });
230
+ x -= 1;
231
+ y -= 1;
232
+ }
233
+ if (down)
234
+ out.push({ side: "candidate", targetLine: null, candidateLine: fromY + 1, text: right[fromY] });
235
+ else
236
+ out.push({ side: "target", targetLine: fromX + 1, candidateLine: null, text: left[fromX] });
237
+ x = fromX;
238
+ y = fromY;
239
+ }
240
+ return out.reverse();
241
+ }
106
242
  function foldUnchanged(lines, context = 3) {
107
243
  const interesting = new Set();
108
244
  lines.forEach((line, index) => {
@@ -1575,7 +1575,11 @@ The connection failed: ${text}`));
1575
1575
  }
1576
1576
  console.log(`\nRun ${accent(`cbx merge ${result.mergeTrack.reference}`)} to decide,` +
1577
1577
  ` or ${accent("cbx merges")} to see everything waiting.`);
1578
- return 0;
1578
+ /*
1579
+ 3, not 0: the work is kept, but the line did not move. Scripts and agents
1580
+ read 0 as saved and carried on (2026-11-11 agent exercise).
1581
+ */
1582
+ return 3;
1579
1583
  }
1580
1584
  /*
1581
1585
  The version exists on the account. Stopping before the line below is the
@@ -1630,8 +1634,16 @@ The connection failed: ${text}`));
1630
1634
  ` nothing was sent again.`);
1631
1635
  return 0;
1632
1636
  }
1637
+ /*
1638
+ Files sent again only to be gathered into one pack are counted apart: "sent
1639
+ 64 files" for a one-line change read as 63 files nobody touched having
1640
+ changed (GrokBot3, 2026-11-11).
1641
+ */
1642
+ const repacked = Math.min(result.repackedFiles ?? 0, result.sentFiles);
1643
+ const changedSent = result.sentFiles - repacked;
1633
1644
  console.log(`Saved ${accent(`v${result.sequence}`)} · sent ${bytes(result.sentBytes)} in ` +
1634
- `${result.sentFiles} file${result.sentFiles === 1 ? "" : "s"}` +
1645
+ `${changedSent} file${changedSent === 1 ? "" : "s"}` +
1646
+ (repacked ? ` (and re-packed ${repacked} unchanged small file${repacked === 1 ? "" : "s"} together)` : "") +
1635
1647
  /*
1636
1648
  Three different things, kept apart. Sent is what crossed the wire.
1637
1649
  Already on the account is content the service turned out to have, which
@@ -1642,13 +1654,24 @@ The connection failed: ${text}`));
1642
1654
  ? `, ${result.alreadyStoredFiles} already on the account`
1643
1655
  : "") +
1644
1656
  (result.reusedFiles ? `, ${result.reusedFiles} unchanged` : "") +
1657
+ /* What --sync removed, which the line used not to mention at all (GrokBot3, v145). */
1658
+ (hasFlag(parsed, "sync") && files.some((file) => file.deleted)
1659
+ ? `, ${files.filter((file) => file.deleted).length} removed`
1660
+ : "") +
1645
1661
  /*
1646
1662
  "version holds" was the old fused vocabulary. `cbx submit` makes a
1647
1663
  save; a save becomes a version when somebody names it, which is what
1648
1664
  `cbx release` does. Saying "version" here promised something this
1649
1665
  command does not do.
1650
1666
  */
1651
- ` · the save holds ${bytes(result.sourceBytes)}`);
1667
+ /*
1668
+ Both sizes, named: "holds 2.9 MB" beside 858 KB in cbx versions read as
1669
+ a contradiction. One is the files' size, the other what storage keeps.
1670
+ */
1671
+ ` · the save holds ${bytes(result.sourceBytes)}` +
1672
+ (result.storedBytes && result.storedBytes < result.sourceBytes
1673
+ ? ` (${bytes(result.storedBytes)} stored)`
1674
+ : ""));
1652
1675
  noteKeptDeletions(folder, baseline, hasFlag(parsed, "sync"), seen);
1653
1676
  noteGitRoute(folder, link?.slug ?? adopt?.slug ?? (0, folder_match_js_1.slugFor)(flagText(parsed, "name") ?? node_path_1.default.basename(folder)));
1654
1677
  /*
@@ -2074,6 +2097,11 @@ trackName) {
2074
2097
  else {
2075
2098
  console.log(`${accent(`v${latest.sequence}`)} · ${fileCount(result.files)} · ${bytes(result.bytes)} into ${destination}`);
2076
2099
  }
2100
+ const leftDeleted = result.leftDeleted ?? 0;
2101
+ if (leftDeleted) {
2102
+ console.log(dim(`${fileCount(leftDeleted)} you deleted here and have not saved ${leftDeleted === 1 ? "was" : "were"} left deleted; ` +
2103
+ `cbx submit --sync saves the deletion, cbx get --replace brings ${leftDeleted === 1 ? "it" : "them"} back.`));
2104
+ }
2077
2105
  return 0;
2078
2106
  }
2079
2107
  /**
@@ -2661,7 +2689,10 @@ const SPECS = [
2661
2689
  "into it, --new starts a separate one.\n\n" +
2662
2690
  "A save is not a version. Nobody outside the project can see one until\n" +
2663
2691
  "it is named, which is what `cbx release` does — so submitting is as\n" +
2664
- "cheap and as private as you want it to be.",
2692
+ "cheap and as private as you want it to be.\n\n" +
2693
+ "Exits 0 when the save is on the line, 3 when it is kept as a merge\n" +
2694
+ "because somebody changed the same lines (cbx merges lists it), and\n" +
2695
+ "1 when it failed.",
2665
2696
  options: [
2666
2697
  { flags: "-m, --message <text>", description: "what changed, in a sentence" },
2667
2698
  { flags: "-n, --dry-run", description: "show what would be sent, send nothing" },
@@ -3083,9 +3114,9 @@ const SPECS = [
3083
3114
  name: "workspace",
3084
3115
  group: "Workspaces",
3085
3116
  summary: "edit, save and run a private project remotely without a checkout",
3086
- usage: "workspace | workspace <usage|open|list|show|read|files|search|diff|patch|put|starter|review|reviewers|save|run|logs|cancel|deploy|preview|handoff|close|recipe|assign|assignments|unassign|checkout|say|thread|mute|unmute> <project> [workspace] [job] | workspace put <project> <workspace> <path…> | workspace push [folder] | workspace watch [project] [workspace]",
3117
+ usage: "workspace | workspace <usage|open|list|show|read|files|search|diff|patch|put|starter|review|reviewers|save|run|logs|cancel|deploy|preview|handoff|close|reopen|recipe|assign|assignments|unassign|checkout|say|thread|mute|unmute> <project> [workspace] [job] | workspace put <project> <workspace> <path…> | workspace push [folder] | workspace watch [project] [workspace]",
3087
3118
  brief: "workspace <action> <project>",
3088
- detail: "Works on CodeRook's durable remote draft, never the current local folder. Use --data-file for structured edits or recipe configuration. Mutations need the reviewed --revision and a unique --key; reuse the same key and request when retrying. Recipes reference existing project workflows. Usage reads the shared workspace credits and separate PR allowance without a draft ID. put copies files from this folder into a draft: text as text, images, fonts and other binary files as bytes (up to 1 MiB each), a file that is gone here is removed there, and each file must still be the version the draft holds, so a teammate's edit is never overwritten. starter reads this folder (package.json scripts, Cargo.toml, go.mod, Python) and suggests one check recipe per package so drafts have something to run; --apply adds them, never replacing a recipe that exists. review shows who must OK a draft before it is saved or deployed; --ok or --changes -m gives your verdict on the current revision, and counts only from the reviewer's own sign-in or token, never a name given with --as. reviewers lists the project's rules, and an administrator sets them with --data-file. Saving and deploying are separate operations. Run on its own at a terminal, it lists your open workspaces with their unread messages: choose one to see its changes and what is being discussed, and reply, save, run checks, hand it over or close it with one key. say and thread post to and read a workspace's discussion as JSON; a machine signed in to your account can name itself with --as (or CBX_NAME) so its messages and unread count are its own. watch prints each new message, each message addressed to you (@your name, or the name given with --as) and each new saved version as it happens, until stopped; --json gives one JSON object per line for a program.",
3119
+ detail: "Works on CodeRook's durable remote draft, never the current local folder. Use --data-file for structured edits or recipe configuration. Mutations need the reviewed --revision and a unique --key; reuse the same key and request when retrying. Recipes reference existing project workflows. Usage reads the shared workspace credits and separate PR allowance without a draft ID. put copies files from this folder into a draft: text as text, images, fonts and other binary files as bytes (up to 1 MiB each), a file that is gone here is removed there, and each file must still be the version the draft holds, so a teammate's edit is never overwritten. starter reads this folder (package.json scripts, Cargo.toml, go.mod, Python) and suggests one check recipe per package so drafts have something to run; --apply adds them, never replacing a recipe that exists. review shows who must OK a draft before it is saved or deployed; --ok or --changes -m gives your verdict on the current revision, and counts only from the reviewer's own sign-in or token, never a name given with --as. reviewers lists the project's rules, and an administrator sets them with --data-file. Saving and deploying are separate operations. close refuses a draft with edits that were never saved unless --unsaved is given (the edits are kept, not thrown away); reopen opens a closed draft again, edits and all. Run on its own at a terminal, it lists your open workspaces with their unread messages: choose one to see its changes and what is being discussed, and reply, save, run checks, hand it over or close it with one key. say and thread post to and read a workspace's discussion as JSON; a machine signed in to your account can name itself with --as (or CBX_NAME) so its messages and unread count are its own. watch prints each new message, each message addressed to you (@your name, or the name given with --as) and each new saved version as it happens, until stopped; --json gives one JSON object per line for a program.",
3089
3120
  options: [
3090
3121
  { flags: "--data-file <path>", description: "read an operation's JSON from this local file" },
3091
3122
  { flags: "--name <name>", description: "name a new workspace" },
@@ -3103,6 +3134,7 @@ const SPECS = [
3103
3134
  { flags: "--version <id>", description: "saved workspace version to deploy" },
3104
3135
  { flags: "-m, --message <text>", description: "describe the version being saved" },
3105
3136
  { flags: "--note <text>", description: "task context for another computer/assistant" },
3137
+ { flags: "--unsaved", description: "close: close a draft whose edits were never saved; they are kept and come back with reopen" },
3106
3138
  { flags: "--days <number>", description: "assign: how long the handed-over token lasts (1-90, default 14)" },
3107
3139
  { flags: "--save", description: "push: save the draft after sending the changes" },
3108
3140
  { flags: "--dry-run", description: "push: list what would be sent, send nothing" },
@@ -3118,7 +3150,7 @@ const SPECS = [
3118
3150
  { flags: "--interval <seconds>", description: "watch: how often to look (default 20, at least 5)" },
3119
3151
  ],
3120
3152
  examples: ["cbx workspace open my-project --name \"Laptop work\" --key laptop-open-001", "cbx workspace list my-project", "cbx workspace assign my-project <draft> --name Laptop", "cbx workspace checkout my-project <draft>", "cbx workspace push --save -m \"Fix the export dialog\"", "cbx workspace", "cbx workspace say my-project <draft> -m \"Tests updated\" --as GrokBot", "cbx workspace thread my-project <draft> --unread", "cbx workspace watch my-project --as GrokBot --json", "cbx workspace put my-project <draft> website/app/page.tsx website/public/og.png", "cbx workspace starter my-project --apply", "cbx workspace review my-project <draft> --ok -m \"Matches the concept\""],
3121
- arguments: { "[job]": "a job's name inside a run, for logs and cancel" },
3153
+ arguments: { "[job]": "the run's id (cbx workspace run prints it), for logs and cancel" },
3122
3154
  run: workspace_command_js_1.commandWorkspace,
3123
3155
  },
3124
3156
  {
@@ -30,17 +30,11 @@ const project_commands_js_1 = require("./project_commands.js");
30
30
  const merge_diff_js_1 = require("../../cbx/src/shared/merge_diff.js");
31
31
  const worktree_js_1 = require("../../cbx/src/core/worktree.js");
32
32
  /*
33
- Built rather than typed, so the escape character never sits literally in the
34
- source. The other command files spell theirs out; this reads the same on a
35
- terminal and survives being copied through a tool that eats control bytes.
33
+ The shared colours: only at a terminal, never with NO_COLOR. This file had its
34
+ own always-on copy, so cbx diff piped or under NO_COLOR=1 came back full of
35
+ escape codes (2026-11-11 agent exercise).
36
36
  */
37
- const ESC = String.fromCharCode(27);
38
- const paint = (code) => (value) => `${ESC}[${code}m${value}${ESC}[0m`;
39
- const dim = paint("2");
40
- const bold = paint("1");
41
- const red = paint("31");
42
- const green = paint("32");
43
- const accent = paint("33");
37
+ const colour_js_1 = require("./colour.js");
44
38
  /*
45
39
  The line comparison builds a table of one side's lines against the other's,
46
40
  which is exact and quadratic. On a conflicted file — what it was written for
@@ -49,35 +43,39 @@ const accent = paint("33");
49
43
  changed without its lines. Saying so beats both wedging the terminal and
50
44
  printing a heuristic diff that quietly invents a change.
51
45
  */
52
- const MOST_LINES_COMPARED = 4_000;
46
+ /*
47
+ More changed lines than this in one file are summarised rather than listed.
48
+ Files of any length are compared: only the changed part costs anything
49
+ (diffLinesWithin). It refused any file over 4,000 lines before.
50
+ */
51
+ const MOST_LINES_SHOWN = 4_000;
53
52
  /** How a change reads at a glance. */
54
53
  const MARK = {
55
- added: green("+"),
56
- removed: red("-"),
57
- changed: accent("~"),
54
+ added: (0, colour_js_1.green)("+"),
55
+ removed: (0, colour_js_1.red)("-"),
56
+ changed: (0, colour_js_1.accent)("~"),
58
57
  };
59
58
  /** Print one file's lines, folded to the interesting parts. */
60
59
  function printHunks(before, after, context) {
61
- const left = (0, merge_diff_js_1.linesOf)(before);
62
- const right = (0, merge_diff_js_1.linesOf)(after);
63
- if (left.length > MOST_LINES_COMPARED || right.length > MOST_LINES_COMPARED) {
64
- console.log(dim(` ${Math.max(left.length, right.length).toLocaleString()} lines — ` +
65
- `too large to compare line by line`));
60
+ const compared = (0, merge_diff_js_1.diffLinesWithin)(before, after, MOST_LINES_SHOWN);
61
+ if (!compared) {
62
+ const longest = Math.max((0, merge_diff_js_1.linesOf)(before).length, (0, merge_diff_js_1.linesOf)(after).length);
63
+ console.log((0, colour_js_1.dim)(` more than ${MOST_LINES_SHOWN.toLocaleString()} lines changed in ${longest.toLocaleString()} — too many to list`));
66
64
  return;
67
65
  }
68
- for (const chunk of (0, merge_diff_js_1.foldUnchanged)((0, merge_diff_js_1.diffLines)(before, after), context)) {
66
+ for (const chunk of (0, merge_diff_js_1.foldUnchanged)(compared, context)) {
69
67
  if (chunk.kind === "gap") {
70
- console.log(dim(` ... ${chunk.skipped} unchanged`));
68
+ console.log((0, colour_js_1.dim)(` ... ${chunk.skipped} unchanged`));
71
69
  continue;
72
70
  }
73
71
  for (const line of chunk.lines) {
74
72
  const at = String(line.candidateLine ?? line.targetLine ?? "").padStart(5);
75
73
  if (line.side === "same")
76
- console.log(dim(`${at} ${line.text}`));
74
+ console.log((0, colour_js_1.dim)(`${at} ${line.text}`));
77
75
  else if (line.side === "candidate")
78
- console.log(`${dim(at)} ${green("+")} ${green(line.text)}`);
76
+ console.log(`${(0, colour_js_1.dim)(at)} ${(0, colour_js_1.green)("+")} ${(0, colour_js_1.green)(line.text)}`);
79
77
  else
80
- console.log(`${dim(at)} ${red("-")} ${red(line.text)}`);
78
+ console.log(`${(0, colour_js_1.dim)(at)} ${(0, colour_js_1.red)("-")} ${(0, colour_js_1.red)(line.text)}`);
81
79
  }
82
80
  }
83
81
  }
@@ -119,13 +117,13 @@ async function commandDiff(parsed) {
119
117
  const from = versionBy(list, first);
120
118
  const to = versionBy(list, second);
121
119
  if (!from || !to) {
122
- console.error(red(`No such version: ${from ? second : first}`));
120
+ console.error((0, colour_js_1.red)(`No such version: ${from ? second : first}`));
123
121
  return 1;
124
122
  }
125
123
  const changes = (await (0, api_js_1.compareVersions)(project.id, from.id, to.id))
126
124
  .filter((change) => !only || change.path.includes(String(only)))
127
125
  .sort((left, right) => left.path.localeCompare(right.path));
128
- console.log(`${bold(project.slug)} ${dim(`v${from.sequence} -> v${to.sequence}`)}`);
126
+ console.log(`${(0, colour_js_1.bold)(project.slug)} ${(0, colour_js_1.dim)(`v${from.sequence} -> v${to.sequence}`)}`);
129
127
  if (!changes.length) {
130
128
  console.log("Nothing differs between them.");
131
129
  return 0;
@@ -139,13 +137,13 @@ async function commandDiff(parsed) {
139
137
  (0, api_js_1.fileTextAt)(project.id, to.id, change.path),
140
138
  ]);
141
139
  if (before === null || after === null) {
142
- console.log(dim(" not text"));
140
+ console.log((0, colour_js_1.dim)(" not text"));
143
141
  continue;
144
142
  }
145
143
  printHunks(before, after, context);
146
144
  }
147
145
  const many = changes.length === 1 ? "" : "s";
148
- console.log(dim(`\n${changes.length} file${many} differ${many ? "" : "s"}`));
146
+ console.log((0, colour_js_1.dim)(`\n${changes.length} file${many} differ${many ? "" : "s"}`));
149
147
  return 0;
150
148
  }
151
149
  /*
@@ -155,14 +153,14 @@ async function commandDiff(parsed) {
155
153
  */
156
154
  const link = await (0, config_js_1.readLink)(node_process_1.default.cwd());
157
155
  if (!link) {
158
- console.error(red("This folder is not linked to a project, so there is no local side."));
156
+ console.error((0, colour_js_1.red)("This folder is not linked to a project, so there is no local side."));
159
157
  return 1;
160
158
  }
161
159
  const against = first
162
160
  ? versionBy(list, first)
163
161
  : { id: link.baseVersionId ?? list[0].id, sequence: link.sequence };
164
162
  if (!against) {
165
- console.error(red(`No such version: ${first}`));
163
+ console.error((0, colour_js_1.red)(`No such version: ${first}`));
166
164
  return 1;
167
165
  }
168
166
  const folder = node_process_1.default.cwd();
@@ -181,7 +179,7 @@ async function commandDiff(parsed) {
181
179
  const changed = (await (0, worktree_js_1.changedFiles)(folder, rules, new Map(Object.entries(saved)), "synchronize"))
182
180
  .filter((one) => !only || one.path.includes(String(only)))
183
181
  .sort((left, right) => left.path.localeCompare(right.path));
184
- console.log(`${bold(node_path_1.default.basename(folder))} ${dim(`this folder -> v${against.sequence}`)}`);
182
+ console.log(`${(0, colour_js_1.bold)(node_path_1.default.basename(folder))} ${(0, colour_js_1.dim)(`this folder -> v${against.sequence}`)}`);
185
183
  let differing = 0;
186
184
  for (const one of changed) {
187
185
  const wasSaved = Object.prototype.hasOwnProperty.call(saved, one.path);
@@ -195,7 +193,7 @@ async function commandDiff(parsed) {
195
193
  if (nameOnly || kind !== "changed")
196
194
  continue;
197
195
  if (one.binary) {
198
- console.log(dim(" not text"));
196
+ console.log((0, colour_js_1.dim)(" not text"));
199
197
  continue;
200
198
  }
201
199
  const [before, after] = await Promise.all([
@@ -203,7 +201,7 @@ async function commandDiff(parsed) {
203
201
  (0, promises_1.readFile)(node_path_1.default.join(folder, one.path), "utf8").catch(() => null),
204
202
  ]);
205
203
  if (before === null || after === null || !isText(after)) {
206
- console.log(dim(" not text"));
204
+ console.log((0, colour_js_1.dim)(" not text"));
207
205
  continue;
208
206
  }
209
207
  printHunks(before, after, context);
@@ -213,6 +211,6 @@ async function commandDiff(parsed) {
213
211
  return 0;
214
212
  }
215
213
  const many = differing === 1 ? "" : "s";
216
- console.log(dim(`\n${differing} file${many} differ${many ? "" : "s"}`));
214
+ console.log((0, colour_js_1.dim)(`\n${differing} file${many} differ${many ? "" : "s"}`));
217
215
  return 0;
218
216
  }
@@ -6,7 +6,9 @@ exports.short = exports.accent = exports.green = exports.red = exports.bold = ex
6
6
  * can print exactly what the full commands print without loading them.
7
7
  */
8
8
  const ESC = String.fromCharCode(27);
9
- const paint = (code) => (value) => `${ESC}[${code}m${value}${ESC}[0m`;
9
+ /* Only at a terminal and never with NO_COLOR, the same rule as colour.ts. */
10
+ const colour = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
11
+ const paint = (code) => (value) => (colour ? `${ESC}[${code}m${value}${ESC}[0m` : value);
10
12
  exports.dim = paint("2");
11
13
  exports.bold = paint("1");
12
14
  exports.red = paint("31");
@@ -31,12 +31,8 @@ const node_process_1 = __importDefault(require("node:process"));
31
31
  const download_js_1 = require("../../cbx/src/core/download.js");
32
32
  const safe_path_js_1 = require("../../cbx/src/shared/safe_path.js");
33
33
  const config_js_1 = require("./config.js");
34
- const ESC = String.fromCharCode(27);
35
- const paint = (code) => (value) => `${ESC}[${code}m${value}${ESC}[0m`;
36
- const dim = paint("2");
37
- const red = paint("31");
38
- const green = paint("32");
39
- const accent = paint("33");
34
+ /* The shared colours: only at a terminal, never with NO_COLOR. */
35
+ const colour_js_1 = require("./colour.js");
40
36
  const plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
41
37
  async function digestOfFile(full) {
42
38
  try {
@@ -78,10 +74,10 @@ function projectPath(root, cwd, typed) {
78
74
  async function commandRemoteRestore(parsed) {
79
75
  const found = await linkedRoot(node_process_1.default.cwd());
80
76
  if (!found) {
81
- console.error(red("No history here."));
82
- console.error(dim(" This folder is not linked to a CodeRook project and has no local history. ") +
83
- accent("cbx link <project>") + dim(" connects it; ") + accent("cbx init") +
84
- dim(" starts a history on this machine."));
77
+ console.error((0, colour_js_1.red)("No history here."));
78
+ console.error((0, colour_js_1.dim)(" This folder is not linked to a CodeRook project and has no local history. ") +
79
+ (0, colour_js_1.accent)("cbx link <project>") + (0, colour_js_1.dim)(" connects it; ") + (0, colour_js_1.accent)("cbx init") +
80
+ (0, colour_js_1.dim)(" starts a history on this machine."));
85
81
  return 1;
86
82
  }
87
83
  const { root, link } = found;
@@ -90,7 +86,7 @@ async function commandRemoteRestore(parsed) {
90
86
  for (const typed of parsed.positional) {
91
87
  const one = projectPath(root, node_process_1.default.cwd(), typed);
92
88
  if (one === null) {
93
- console.error(red(`${typed} is outside the project folder (${root}).`));
89
+ console.error((0, colour_js_1.red)(`${typed} is outside the project folder (${root}).`));
94
90
  return 1;
95
91
  }
96
92
  wanted.push(one);
@@ -105,7 +101,7 @@ async function commandRemoteRestore(parsed) {
105
101
  ? versions.find((one) => one.sequence === Number(sequence[1]))
106
102
  : versions.find((one) => one.id.startsWith(from.trim()));
107
103
  if (!version) {
108
- console.error(red(`No version ${from} in ${link.slug}.`) + dim(" cbx versions lists them."));
104
+ console.error((0, colour_js_1.red)(`No version ${from} in ${link.slug}.`) + (0, colour_js_1.dim)(" cbx versions lists them."));
109
105
  return 1;
110
106
  }
111
107
  }
@@ -115,14 +111,14 @@ async function commandRemoteRestore(parsed) {
115
111
  versions.find((one) => one.id === base) ??
116
112
  versions.find((one) => one.sequence === link.sequence);
117
113
  if (!version) {
118
- console.error(red("This folder's saved version could not be found.") +
119
- dim(" Name one with --from vN."));
114
+ console.error((0, colour_js_1.red)("This folder's saved version could not be found.") +
115
+ (0, colour_js_1.dim)(" Name one with --from vN."));
120
116
  return 1;
121
117
  }
122
118
  }
123
119
  const files = selectFiles(await downloader.files(link.repositoryId, version.id), wanted);
124
120
  if (!files.length) {
125
- console.error(red(`v${version.sequence} holds nothing at ${wanted.join(", ") || "the project root"}.`));
121
+ console.error((0, colour_js_1.red)(`v${version.sequence} holds nothing at ${wanted.join(", ") || "the project root"}.`));
126
122
  return 1;
127
123
  }
128
124
  const toWrite = [];
@@ -130,7 +126,7 @@ async function commandRemoteRestore(parsed) {
130
126
  for (const file of files) {
131
127
  const unsafe = (0, safe_path_js_1.whyUnsafe)(file.path);
132
128
  if (unsafe) {
133
- console.error(red(`Skipped ${JSON.stringify(file.path)}: ${unsafe}.`));
129
+ console.error((0, colour_js_1.red)(`Skipped ${JSON.stringify(file.path)}: ${unsafe}.`));
134
130
  continue;
135
131
  }
136
132
  const here = await digestOfFile(node_path_1.default.join(root, ...file.path.split("/")));
@@ -147,28 +143,28 @@ async function commandRemoteRestore(parsed) {
147
143
  toWrite.push(file);
148
144
  }
149
145
  if (edited.length) {
150
- console.error(red(`${plural(edited.length, "file")} here ${edited.length === 1 ? "has" : "have"} ` +
146
+ console.error((0, colour_js_1.red)(`${plural(edited.length, "file")} here ${edited.length === 1 ? "has" : "have"} ` +
151
147
  `unsaved changes that restoring would overwrite:`));
152
148
  for (const one of edited.slice(0, 20))
153
149
  console.error(` ${one}`);
154
150
  if (edited.length > 20)
155
- console.error(dim(` …and ${edited.length - 20} more`));
156
- console.error(`\nAdd ${accent("--force")} to discard them, or save them first with ${accent("cbx submit")}.`);
151
+ console.error((0, colour_js_1.dim)(` …and ${edited.length - 20} more`));
152
+ console.error(`\nAdd ${(0, colour_js_1.accent)("--force")} to discard them, or save them first with ${(0, colour_js_1.accent)("cbx submit")}.`);
157
153
  return 1;
158
154
  }
159
155
  if (!toWrite.length) {
160
- console.log(`Already matches ${accent(`v${version.sequence}`)}; nothing to put back.`);
156
+ console.log(`Already matches ${(0, colour_js_1.accent)(`v${version.sequence}`)}; nothing to put back.`);
161
157
  return 0;
162
158
  }
163
159
  for (const file of toWrite) {
164
160
  await downloader.fileTo(link.repositoryId, version.id, file, node_path_1.default.join(root, ...file.path.split("/")));
165
161
  }
166
- console.log(`Put back ${plural(toWrite.length, "file")} from ${accent(`v${version.sequence}`)}: ` +
162
+ console.log(`Put back ${plural(toWrite.length, "file")} from ${(0, colour_js_1.accent)(`v${version.sequence}`)}: ` +
167
163
  `${version.message.split("\n")[0]}`);
168
164
  for (const file of toWrite.slice(0, 20))
169
- console.log(` ${green("restored")} ${file.path}`);
165
+ console.log(` ${(0, colour_js_1.green)("restored")} ${file.path}`);
170
166
  if (toWrite.length > 20)
171
- console.log(dim(` …and ${toWrite.length - 20} more`));
172
- console.log(dim("The folder's link has not moved. cbx submit saves the folder as it is now."));
167
+ console.log((0, colour_js_1.dim)(` …and ${toWrite.length - 20} more`));
168
+ console.log((0, colour_js_1.dim)("The folder's link has not moved. cbx submit saves the folder as it is now."));
173
169
  return 0;
174
170
  }
@@ -164,13 +164,16 @@ async function commandWorkspace(parsed) {
164
164
  body = {};
165
165
  }
166
166
  }
167
- else if (operation === "handoff" || operation === "close") {
167
+ else if (operation === "handoff" || operation === "close" || operation === "reopen") {
168
168
  method = "PATCH";
169
169
  body = {
170
170
  ...data,
171
171
  expectedRevision: revision,
172
172
  note: flag("note") ?? data.note,
173
173
  ...(operation === "close" ? { archived: true } : {}),
174
+ /* Closing a draft with unsaved edits needs this: the service refuses otherwise. The edits are kept for reopen. */
175
+ ...(operation === "close" && parsed.flags.has("unsaved") ? { unsaved: true } : {}),
176
+ ...(operation === "reopen" ? { archived: false } : {}),
174
177
  };
175
178
  }
176
179
  else if (operation !== "show")
@@ -197,6 +200,16 @@ async function commandWorkspace(parsed) {
197
200
  throw error;
198
201
  }
199
202
  console.log(JSON.stringify(result, null, 2));
203
+ /*
204
+ A save kept as a merge did not reach the line. It exited 0 with only JSON
205
+ to say otherwise, so a script or agent read it as saved (2026-11-11, M-1).
206
+ Exit 3 means exactly that, the same as cbx submit.
207
+ */
208
+ const kept = operation === "save" ? result?.mergeTrack : null;
209
+ if (kept?.reference) {
210
+ say(`Kept as ${kept.reference}, not saved to the line: somebody changed the same lines. Run cbx merge ${kept.reference} to decide.`);
211
+ return 3;
212
+ }
200
213
  return 0;
201
214
  }
202
215
  const say = (line) => process.stderr.write(line + "\n");
@@ -88,13 +88,41 @@ async function commandWorkspacePut(parsed, root, workspace) {
88
88
  const draft = `${root}/workspaces/${encodeURIComponent(workspace)}`;
89
89
  const wanted = [...new Set(paths.map((p) => projectPath(folder, p)))];
90
90
  /* The hashes the draft holds now; the listing pages 500 at a time, so stop once every wanted path is found. */
91
+ /*
92
+ Asked path by path first. Paging never stopped early for a new file, which
93
+ no page names: a put into a 20,000-file draft made about 41 requests and
94
+ took 22-24 s (2026-11-11 agent exercise). The listing is still the way for
95
+ many paths, and for a service that does not answer meta=1.
96
+ */
91
97
  const held = new Map();
92
- for (let offset = 0; offset !== null && held.size < wanted.length;) {
93
- const page = await (0, api_js_1.callApi)(`${draft}/files?offset=${offset}`);
94
- for (const f of page.files)
95
- if (wanted.includes(f.path))
96
- held.set(f.path, f.sha256);
97
- offset = page.nextOffset;
98
+ let pageThrough = wanted.length > 32;
99
+ if (!pageThrough) {
100
+ for (const path of wanted) {
101
+ try {
102
+ const one = await (0, api_js_1.callApi)(`${draft}/files?path=${encodeURIComponent(path)}&meta=1`);
103
+ if (typeof one.sha256 !== "string") {
104
+ pageThrough = true;
105
+ break;
106
+ }
107
+ held.set(path, one.sha256);
108
+ }
109
+ catch (error) {
110
+ if (error instanceof api_js_1.ServiceError && error.code === "workspace_file_missing")
111
+ continue;
112
+ pageThrough = true;
113
+ break;
114
+ }
115
+ }
116
+ }
117
+ if (pageThrough) {
118
+ held.clear();
119
+ for (let offset = 0; offset !== null && held.size < wanted.length;) {
120
+ const page = await (0, api_js_1.callApi)(`${draft}/files?offset=${offset}`);
121
+ for (const f of page.files)
122
+ if (wanted.includes(f.path))
123
+ held.set(f.path, f.sha256);
124
+ offset = page.nextOffset;
125
+ }
98
126
  }
99
127
  const changes = [];
100
128
  const unchanged = [];
@@ -7,9 +7,11 @@ exports.commandWorkspaceReviewers = commandWorkspaceReviewers;
7
7
  * cbx workspace review <project> <workspace> --ok [-m "…"] | --changes -m "…"
8
8
  * cbx workspace reviewers <project> [--data-file rules.json]
9
9
  *
10
- * The CLI side of the review gate (backend workspace_reviews.ts). A review
11
- * counts only from the reviewer's own sign-in or token, so --as is refused
12
- * here before the service refuses it, with the reason.
10
+ * The CLI side of the review gate (backend workspace_reviews.ts). Where the
11
+ * project names reviewers, a review counts only from the reviewer's own
12
+ * sign-in or token, and the service refuses a name given with --as. Where it
13
+ * names none, any member's review, a named machine's included, is kept as
14
+ * advisory: shown, and waited on by nobody.
13
15
  */
14
16
  const promises_1 = require("node:fs/promises");
15
17
  const api_js_1 = require("./api.js");
@@ -25,6 +27,11 @@ const flag = (parsed, ...names) => {
25
27
  /** One line per reviewer: a word for where it stands, never only a colour. */
26
28
  function describeReviewer(s, revision) {
27
29
  const when = [s.beforeSave && "save", s.beforeDeploy && "deploy"].filter(Boolean).join(" + ");
30
+ if (s.advisory) {
31
+ const said = s.state === "ok" ? (0, colour_js_1.green)("OK ") : s.state === "changes" ? (0, colour_js_1.red)("changes ") : "outdated ";
32
+ const on = s.state === "outdated" ? `on revision ${s.revision}, draft is at ${revision}` : `on revision ${s.revision}`;
33
+ return `${said}${(0, colour_js_1.bold)(s.label)} ${(0, colour_js_1.dim)(`advisory, ${on}`)}${s.note ? ` ${s.note}` : ""}`;
34
+ }
28
35
  if (!s.applies)
29
36
  return `${(0, colour_js_1.dim)("not needed")} ${s.label} ${(0, colour_js_1.dim)(`(no changes in its paths)`)}`;
30
37
  const word = s.state === "ok"
@@ -42,8 +49,9 @@ function describeReviewer(s, revision) {
42
49
  return `${word}${(0, colour_js_1.bold)(s.label)} ${(0, colour_js_1.dim)(`before ${when}`)}${detail ? ` ${detail}` : ""}`;
43
50
  }
44
51
  async function commandWorkspaceReview(parsed, root, workspace) {
45
- if (parsed.flags.has("as") || process.env.CBX_NAME)
46
- throw new Error("A review counts only from the reviewer's own sign-in or token; run it without --as or CBX_NAME.");
52
+ /* Passed on: the service keeps it as advisory where no reviewers are named, and refuses it where they are. */
53
+ const asValue = parsed.flags.get("as");
54
+ const named = typeof asValue === "string" ? asValue : process.env.CBX_NAME || undefined;
47
55
  const ok = parsed.flags.has("ok");
48
56
  const changes = parsed.flags.has("changes");
49
57
  const draft = `${root}/workspaces/${encodeURIComponent(workspace)}`;
@@ -54,7 +62,7 @@ async function commandWorkspaceReview(parsed, root, workspace) {
54
62
  if (parsed.flags.has("json"))
55
63
  console.log(JSON.stringify({ revision: shown.workspace.revision, review }, null, 2));
56
64
  else if (!review.length)
57
- console.log("This project names no reviewers. An administrator sets them with cbx workspace reviewers.");
65
+ console.log("This project names no reviewers, so nothing waits on a review; any review given is kept as advisory. An administrator names reviewers with cbx workspace reviewers.");
58
66
  else
59
67
  for (const s of review)
60
68
  console.log(describeReviewer(s, shown.workspace.revision));
@@ -68,7 +76,7 @@ async function commandWorkspaceReview(parsed, root, workspace) {
68
76
  : (await (0, api_js_1.callApi)(draft)).workspace.revision;
69
77
  const out = await (0, api_js_1.callApi)(`${draft}/reviews`, {
70
78
  method: "POST",
71
- body: { verdict: ok ? "ok" : "changes", note, expectedRevision: revision },
79
+ body: { verdict: ok ? "ok" : "changes", note, expectedRevision: revision, ...(named ? { as: named } : {}) },
72
80
  });
73
81
  if (parsed.flags.has("json"))
74
82
  console.log(JSON.stringify(out, null, 2));
@@ -21,6 +21,54 @@ const promises_1 = require("node:fs/promises");
21
21
  const node_path_1 = require("node:path");
22
22
  const api_js_1 = require("./api.js");
23
23
  const colour_js_1 = require("./colour.js");
24
+ /*
25
+ Installs Rust where the runner has none; CodeRook's hosted runner does not ship
26
+ it. Nor a C compiler, which most crates' build scripts link with ("linker `cc`
27
+ not found", 2026-11-11), so gcc comes too when cc is missing.
28
+ */
29
+ const CARGO = "command -v cc >/dev/null 2>&1 || { S=; [ \"$(id -u)\" = 0 ] || S=sudo; $S apt-get update -qq && $S apt-get install -y -qq --no-install-recommends gcc libc6-dev; }; " +
30
+ "command -v cargo >/dev/null 2>&1 || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal; }; " +
31
+ '. "$HOME/.cargo/env" 2>/dev/null; cargo test';
32
+ /** Sibling folders a package reaches with ../, from its tsconfig and file: dependencies. */
33
+ function siblingsOf(directory, seen) {
34
+ if (!directory)
35
+ return [];
36
+ const at = (name) => `${directory}/${name}`;
37
+ const found = new Set();
38
+ const add = (relative) => {
39
+ const parts = [...directory.split("/"), ...relative.split("/")];
40
+ const out = [];
41
+ for (const part of parts) {
42
+ if (!part || part === ".")
43
+ continue;
44
+ if (part === "..")
45
+ out.pop();
46
+ else
47
+ out.push(part);
48
+ }
49
+ const top = out.join("/");
50
+ if (top && top !== directory && !top.startsWith(`${directory}/`))
51
+ found.add(top);
52
+ };
53
+ const text = seen.get(at("tsconfig.json")) ?? "";
54
+ for (const match of text.matchAll(/"((?:\.\.\/)+[A-Za-z0-9_.-]+)/g))
55
+ add(match[1]);
56
+ try {
57
+ const pkg = JSON.parse(seen.get(at("package.json")) ?? "{}");
58
+ for (const group of ["dependencies", "devDependencies", "optionalDependencies"]) {
59
+ for (const value of Object.values(pkg[group] ?? {})) {
60
+ const local = /^file:((?:\.\.\/)+[A-Za-z0-9_.-]+)/.exec(String(value));
61
+ if (local)
62
+ add(local[1]);
63
+ }
64
+ }
65
+ }
66
+ catch {
67
+ /* A package.json that does not parse already produced no starter. */
68
+ }
69
+ return [...found].sort();
70
+ }
71
+ const pathsFor = (directory, extra = []) => directory ? [`${directory}/`, ...extra.map((one) => `${one}/`)] : [];
24
72
  const SKIP = new Set(["node_modules", ".git", ".coderook", ".rook", "dist", "build", "target", ".venv", "venv", "vendor", ".next"]);
25
73
  const slug = (directory) => (directory.split("/").pop() || "project").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "project";
26
74
  function nodeStarter(directory, seen) {
@@ -50,6 +98,7 @@ function nodeStarter(directory, seen) {
50
98
  directory,
51
99
  command: [install, ...steps.map((s) => `${run} ${s}`)].join(" && "),
52
100
  because: `package.json scripts: ${steps.join(", ")}`,
101
+ includePaths: pathsFor(directory, siblingsOf(directory, seen)),
53
102
  };
54
103
  }
55
104
  /** The starters a folder's files suggest, one per recognised package. */
@@ -66,12 +115,12 @@ function detectStarters(seen) {
66
115
  if (node)
67
116
  out.push(node);
68
117
  else if (seen.has(at("Cargo.toml")))
69
- out.push({ recipe: `${slug(directory)}-check`, workflow: `Draft check · ${directory || "project"}`, directory, command: "cargo test", because: "Cargo.toml" });
118
+ out.push({ recipe: `${slug(directory)}-check`, workflow: `Draft check · ${directory || "project"}`, directory, command: CARGO, because: "Cargo.toml (Rust is installed on the runner if missing)", includePaths: pathsFor(directory) });
70
119
  else if (seen.has(at("go.mod")))
71
- out.push({ recipe: `${slug(directory)}-check`, workflow: `Draft check · ${directory || "project"}`, directory, command: "go vet ./... && go test ./...", because: "go.mod" });
120
+ out.push({ recipe: `${slug(directory)}-check`, workflow: `Draft check · ${directory || "project"}`, directory, command: "go vet ./... && go test ./...", because: "go.mod", includePaths: pathsFor(directory) });
72
121
  else if (seen.has(at("pyproject.toml")) || seen.has(at("requirements.txt"))) {
73
122
  const install = seen.has(at("requirements.txt")) ? "python -m pip install -r requirements.txt" : "python -m pip install -e .";
74
- out.push({ recipe: `${slug(directory)}-check`, workflow: `Draft check · ${directory || "project"}`, directory, command: `${install} && python -m pytest`, because: seen.has(at("pyproject.toml")) ? "pyproject.toml" : "requirements.txt" });
123
+ out.push({ recipe: `${slug(directory)}-check`, workflow: `Draft check · ${directory || "project"}`, directory, command: `${install} && python -m pytest`, because: seen.has(at("pyproject.toml")) ? "pyproject.toml" : "requirements.txt", includePaths: pathsFor(directory) });
75
124
  }
76
125
  }
77
126
  /* Two folders with the same last name ("app/web", "site/web") keep apart by their full path. */
@@ -83,7 +132,9 @@ function detectStarters(seen) {
83
132
  s.recipe = `${s.directory.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "project"}-check`;
84
133
  return out;
85
134
  }
86
- const MARKERS = new Set(["package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "Cargo.toml", "go.mod", "pyproject.toml", "requirements.txt"]);
135
+ const MARKERS = new Set(["package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "Cargo.toml", "go.mod", "pyproject.toml", "requirements.txt", "tsconfig.json"]);
136
+ /* Read for what they say, not only noticed. */
137
+ const READ = new Set(["package.json", "tsconfig.json"]);
87
138
  /** The marker files in a folder, two levels deep, skipping dependencies and build output. */
88
139
  async function scan(root) {
89
140
  const seen = new Map();
@@ -96,7 +147,7 @@ async function scan(root) {
96
147
  await walk(path, depth + 1);
97
148
  }
98
149
  else if (MARKERS.has(entry.name)) {
99
- seen.set(path, entry.name === "package.json" ? await (0, promises_1.readFile)((0, node_path_1.join)(root, ...path.split("/")), "utf8") : "");
150
+ seen.set(path, READ.has(entry.name) ? await (0, promises_1.readFile)((0, node_path_1.join)(root, ...path.split("/")), "utf8") : "");
100
151
  }
101
152
  }
102
153
  };
@@ -126,8 +177,11 @@ async function commandWorkspaceStarter(parsed, root) {
126
177
  for (const s of starters) {
127
178
  const kept = taken.has(s.recipe);
128
179
  console.log(`${kept ? (0, colour_js_1.dim)("exists ") : (0, colour_js_1.green)("new ")} ${(0, colour_js_1.bold)(s.recipe)} ${(0, colour_js_1.dim)(`in ${s.directory || "."}`)}`);
129
- if (!kept)
180
+ if (!kept) {
130
181
  console.log(` ${s.command}\n ${(0, colour_js_1.dim)(s.because)}`);
182
+ if (s.includePaths.length > 1)
183
+ console.log(` ${(0, colour_js_1.dim)(`also sends ${s.includePaths.slice(1).join(", ")} (it builds from them)`)}`);
184
+ }
131
185
  }
132
186
  console.log(fresh.length
133
187
  ? (0, colour_js_1.dim)(`\nNothing was created. Add ${fresh.length === 1 ? "it" : "them"} with `) + (0, colour_js_1.accent)("--apply") + (0, colour_js_1.dim)("; drafts then run them with cbx workspace run <project> <draft> --recipe <name>.")
@@ -150,7 +204,7 @@ async function commandWorkspaceStarter(parsed, root) {
150
204
  }
151
205
  await (0, api_js_1.callApi)(`${root}/workspace-recipes/${encodeURIComponent(s.recipe)}`, {
152
206
  method: "PUT",
153
- body: { kind: "check", workflowId, includePaths: s.directory ? [`${s.directory}/`] : [] },
207
+ body: { kind: "check", workflowId, includePaths: s.includePaths },
154
208
  });
155
209
  made.push(s.recipe);
156
210
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coderook/cli",
3
- "version": "0.46.8",
3
+ "version": "0.46.9",
4
4
  "description": "The command line for CodeRook (coderook.com): version control and project hosting for projects of any size. Every save is a compressed snapshot, private or public, never used to train AI.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://coderook.com",
@@ -44,7 +44,7 @@
44
44
  "test:matrix": "node test/state-matrix.mjs",
45
45
  "test:attempt": "node test/attempt-identity.mjs",
46
46
  "test:get": "node test/get-safety.mjs",
47
- "test:live": "node test/e2e.mjs --allow-production && node test/state-matrix.mjs --allow-production && node test/get-safety.mjs --allow-production && node test/get-track.mjs --allow-production && node test/get-protects-edits.mjs --allow-production && node test/upgrade-migration.mjs --allow-production && node test/fault-get.mjs --allow-production && node test/rename-sync.mjs --allow-production && node test/version-floor.mjs --allow-production && node test/fault-submit.mjs --allow-production && node test/race-attempts.mjs --allow-production && node test/attempt-identity.mjs --allow-production",
47
+ "test:live": "node test/e2e.mjs --allow-production && node test/state-matrix.mjs --allow-production && node test/get-safety.mjs --allow-production && node test/get-track.mjs --allow-production && node test/get-protects-edits.mjs --allow-production && node test/upgrade-migration.mjs --allow-production && node test/fault-get.mjs --allow-production && node test/rename-sync.mjs --allow-production && node test/exercise-fixes.mjs --allow-production && node test/version-floor.mjs --allow-production && node test/fault-submit.mjs --allow-production && node test/race-attempts.mjs --allow-production && node test/attempt-identity.mjs --allow-production",
48
48
  "test:getedits": "node test/get-protects-edits.mjs",
49
49
  "test:upgrade": "node test/upgrade-migration.mjs",
50
50
  "test:faultget": "node test/fault-get.mjs",