@foldrun/core 14.3.4 → 14.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -159,9 +159,12 @@ export async function decideApproval(tenant, workspace, runId, d) {
159
159
  d = { ...d, actor: check.approver ? { email: check.approver, role: null } : null };
160
160
  }
161
161
  assertMayDecide(tenant, workspace, run, d);
162
+ // With no step named, a decision is for the gates waiting on a person: a
163
+ // `wait: event` step waits on its event, and is approved by its payload or
164
+ // rejected by name (5 Nov 2026: an unnamed reject failed it too).
162
165
  const waiting = run.steps
163
166
  .map((s, i) => ({ s, i }))
164
- .filter(({ s, i }) => s.status === "awaiting-approval" && (d.step === undefined || d.step === i) && (allowed === null || allowed.includes(i)));
167
+ .filter(({ s, i }) => s.status === "awaiting-approval" && (d.step === undefined ? s.waitFor !== "event" : d.step === i) && (allowed === null || allowed.includes(i)));
165
168
  if (waiting.length === 0)
166
169
  throw new ApprovalError("nothing is awaiting approval", 409);
167
170
  const note = typeof d.note === "string" ? d.note.trim() : "";
@@ -88,3 +88,34 @@ export interface LibraryUse {
88
88
  relation: "use" | "shadowed";
89
89
  }
90
90
  export declare function libraryUsage(tenant: string, kind: LibraryKind, name: string): LibraryUse[];
91
+ /** The workspace folders "Move to shared" applies to: the library's kinds
92
+ * but hooks, whose run.mjs is code a shared hook is made for on purpose. */
93
+ export declare const SHAREABLE_KINDS: readonly ["skills", "tools", "scripts", "knowledge", "memory"];
94
+ /**
95
+ * Move a workspace's skill, tool, script, knowledge or memory file into the
96
+ * account library — the dashboard's and `foldrun source share`'s "Move to
97
+ * shared", done here in one call (5 Nov 2026). Done by the client it copied
98
+ * one file and deleted the folder (a skill's other files were lost), and a
99
+ * folder tool's path was flattened.
100
+ *
101
+ * A skill or folder tool moves as its whole folder; anything else names one
102
+ * file. Everything is checked before anything is written: a file the library
103
+ * cannot hold (an image, a binary), one too large, broken frontmatter, or a
104
+ * library file already at a path (unless `overwrite`) refuses the move and
105
+ * nothing changes. Then every file is copied and the original deleted, in
106
+ * one synchronous step. `dryRun` answers what would move.
107
+ */
108
+ export declare function moveToLibrary(tenant: string, workspace: string, rel: string, opts?: {
109
+ overwrite?: boolean;
110
+ dryRun?: boolean;
111
+ by?: string;
112
+ }): {
113
+ kind: LibraryKind;
114
+ unit: string;
115
+ files: {
116
+ from: string;
117
+ to: string;
118
+ replaces: boolean;
119
+ }[];
120
+ moved: boolean;
121
+ };
@@ -17,7 +17,7 @@ import { dataRoot, singleWorkspace, singleAccountRoot, MAX_EDITABLE_FILE } from
17
17
  import matter from "./matter.js";
18
18
  import { KINDS } from "./kinds.js";
19
19
  import { recordRevision, registerTreeReader } from "./history.js";
20
- import { assertSafeName, assertCanonicalCase, buildMemoryIndex, parseToolDef, readToolDir, syncBundleFor, listWorkspaces, listAgents, workspaceDir, } from "./store.js";
20
+ import { assertSafeName, assertCanonicalCase, buildMemoryIndex, parseToolDef, readToolDir, syncBundleFor, listWorkspaces, listAgents, workspaceDir, deleteWorkspacePath, assertDeletable, } from "./store.js";
21
21
  // Same order as the workspace nav and asset pages — one list, one order.
22
22
  // Order matters and is asserted: it is the order every noun list in the
23
23
  // product uses. Tools then scripts, because a script is material a tool
@@ -348,3 +348,195 @@ registerTreeReader((tenant, scope) => {
348
348
  }
349
349
  return out;
350
350
  });
351
+ /** The workspace folders "Move to shared" applies to: the library's kinds
352
+ * but hooks, whose run.mjs is code a shared hook is made for on purpose. */
353
+ export const SHAREABLE_KINDS = ["skills", "tools", "scripts", "knowledge", "memory"];
354
+ const refusal = (message, status) => Object.assign(new Error(message), { status });
355
+ /**
356
+ * Move a workspace's skill, tool, script, knowledge or memory file into the
357
+ * account library — the dashboard's and `foldrun source share`'s "Move to
358
+ * shared", done here in one call (5 Nov 2026). Done by the client it copied
359
+ * one file and deleted the folder (a skill's other files were lost), and a
360
+ * folder tool's path was flattened.
361
+ *
362
+ * A skill or folder tool moves as its whole folder; anything else names one
363
+ * file. Everything is checked before anything is written: a file the library
364
+ * cannot hold (an image, a binary), one too large, broken frontmatter, or a
365
+ * library file already at a path (unless `overwrite`) refuses the move and
366
+ * nothing changes. Then every file is copied and the original deleted, in
367
+ * one synchronous step. `dryRun` answers what would move.
368
+ */
369
+ export function moveToLibrary(tenant, workspace, rel, opts = {}) {
370
+ const clean = path.normalize(String(rel ?? "")).replaceAll("\\", "/").replace(/^(\.\/)+/, "").replace(/\/+$/, "");
371
+ if (!clean || clean === "." || clean.startsWith("..") || path.isAbsolute(clean))
372
+ throw refusal(`illegal path: ${rel}`, 400);
373
+ const [kind, ...rest] = clean.split("/");
374
+ if (kind === "hooks")
375
+ throw refusal("a hook is a folder whose run.mjs goes with it — make a shared one with `foldrun hook add <name> --library`", 400);
376
+ if (!SHAREABLE_KINDS.includes(kind) || !rest.length) {
377
+ throw refusal(`"${rel}" is not under ${SHAREABLE_KINDS.join("/, ")}/ — only those move to the shared library`, 400);
378
+ }
379
+ const dir = workspaceDir(tenant, workspace);
380
+ const folderKind = kind === "skills" || kind === "tools";
381
+ // skills/x/SKILL.md or tools/x/tool.md names its folder: the folder is the unit.
382
+ const unit = folderKind && rest.length >= 2 ? `${kind}/${rest[0]}` : clean;
383
+ const full = path.join(dir, unit);
384
+ let stat;
385
+ try {
386
+ stat = fs.lstatSync(full);
387
+ }
388
+ catch {
389
+ throw refusal(`no ${unit} in ${workspace}`, 404);
390
+ }
391
+ if (stat.isSymbolicLink())
392
+ throw refusal(`${unit} is a link — move what it points at instead`, 400);
393
+ if (stat.isDirectory() && !(folderKind && unit.split("/").length === 2)) {
394
+ throw refusal(`${unit} is a folder — name a file in it (only a skill or a folder tool moves as a folder)`, 400);
395
+ }
396
+ const realDir = fs.realpathSync(dir);
397
+ if (!fs.realpathSync(full).startsWith(realDir + path.sep))
398
+ throw refusal(`illegal path: ${rel}`, 400);
399
+ // The original is deleted last, so ask now whether that delete would go
400
+ // through: a file the workspace cannot do without (knowledge/index.md, a
401
+ // memory log) or a folder that is not a whole unit is refused before the
402
+ // library is touched.
403
+ try {
404
+ const d = assertDeletable(tenant, workspace, unit);
405
+ if (stat.isDirectory() !== d.folder)
406
+ throw new Error(`${unit} cannot be moved as one thing`);
407
+ }
408
+ catch (err) {
409
+ throw refusal(`${err.message} — nothing was moved`, 409);
410
+ }
411
+ const members = stat.isDirectory()
412
+ ? fs.readdirSync(full, { recursive: true })
413
+ .map((e) => path.join(full, String(e)))
414
+ .filter((e) => {
415
+ const st = fs.lstatSync(e);
416
+ if (st.isSymbolicLink())
417
+ throw refusal(`${path.relative(dir, e)} is a link — the library holds files, not links; nothing was moved`, 409);
418
+ return st.isFile();
419
+ })
420
+ .map((e) => path.relative(dir, e).split(path.sep).join("/"))
421
+ .sort()
422
+ : [unit];
423
+ if (!members.length)
424
+ throw refusal(`${unit} is empty — nothing to move`, 400);
425
+ const files = [];
426
+ const cannot = [];
427
+ for (const from of members) {
428
+ const to = from.slice(kind.length + 1);
429
+ try {
430
+ assertLibraryPath(kind, to);
431
+ }
432
+ catch {
433
+ cannot.push(from);
434
+ continue;
435
+ }
436
+ // Text in the library's sense: an allowed extension AND bytes that are
437
+ // UTF-8, or reading it as text would change it and the original goes.
438
+ const bytes = fs.readFileSync(path.join(dir, from));
439
+ const content = bytes.toString("utf8");
440
+ if (!Buffer.from(content, "utf8").equals(bytes)) {
441
+ cannot.push(from);
442
+ continue;
443
+ }
444
+ if (content.length > MAX_EDITABLE_FILE)
445
+ throw refusal(`${from} is too large for the library (over ${Math.round(MAX_EDITABLE_FILE / 1024)} KB); nothing was moved`, 409);
446
+ if (to.endsWith(".md")) {
447
+ try {
448
+ matter(content);
449
+ }
450
+ catch {
451
+ throw refusal(`${from} has frontmatter that does not parse; fix it first — nothing was moved`, 409);
452
+ }
453
+ }
454
+ files.push({ from, to, replaces: libraryFileExists(tenant, kind, to), content });
455
+ }
456
+ if (cannot.length) {
457
+ throw refusal(`${unit} holds files the shared library cannot hold (${cannot.join(", ")}) — only text files go there; nothing was moved`, 409);
458
+ }
459
+ // A file already where one of these needs a folder (or a folder where one
460
+ // needs a file) would stop the copy halfway: refuse it now.
461
+ // And no link anywhere on the library side: a write through one could land
462
+ // back in the workspace, and the delete after it would take the only copy.
463
+ const shelf = libraryDir(tenant, kind);
464
+ const linked = (p) => {
465
+ try {
466
+ return fs.lstatSync(p).isSymbolicLink();
467
+ }
468
+ catch {
469
+ return false;
470
+ }
471
+ };
472
+ for (const up of [path.dirname(shelf), shelf]) {
473
+ if (linked(up))
474
+ throw refusal(`the library's ${kind} shelf is a link — nothing was moved`, 409);
475
+ }
476
+ for (const f of files) {
477
+ const parts = f.to.split("/");
478
+ for (let i = 1; i <= parts.length; i++) {
479
+ const at = path.join(shelf, ...parts.slice(0, i));
480
+ if (linked(at))
481
+ throw refusal(`the library has a link at ${kind}/${parts.slice(0, i).join("/")} — nothing was moved`, 409);
482
+ if (i < parts.length && fs.existsSync(at) && !fs.statSync(at).isDirectory())
483
+ throw refusal(`the library has a file at ${kind}/${parts.slice(0, i).join("/")}, where ${kind}/${f.to} needs a folder — nothing was moved`, 409);
484
+ if (i === parts.length && fs.existsSync(at) && fs.statSync(at).isDirectory())
485
+ throw refusal(`the library has a folder at ${kind}/${f.to} — nothing was moved`, 409);
486
+ }
487
+ // The bundle files a write keeps beside it (syncBundleFor) are written too.
488
+ for (const keeper of ["index.md", "log.md"]) {
489
+ const at = path.join(shelf, path.dirname(f.to), keeper);
490
+ if (linked(at))
491
+ throw refusal(`the library has a link at ${kind}/${path.join(path.dirname(f.to), keeper)} — nothing was moved`, 409);
492
+ }
493
+ }
494
+ const taken = files.filter((f) => f.replaces);
495
+ const answer = { kind: kind, unit, files: files.map(({ from, to, replaces }) => ({ from, to, replaces })) };
496
+ if (taken.length && !opts.overwrite && !opts.dryRun) {
497
+ throw refusal(`the library already has ${taken.map((f) => `${kind}/${f.to}`).join(", ")} — nothing was moved; overwrite replaces ${taken.length === 1 ? "it" : "them"}`, 409);
498
+ }
499
+ if (opts.dryRun)
500
+ return { ...answer, moved: false };
501
+ // Copy, then delete; if anything fails on the way, put the library back
502
+ // as it was (each undo is a revision too), so a move is all or nothing.
503
+ const done = [];
504
+ try {
505
+ for (const f of files) {
506
+ // On the undo list before the write: a writer that fails after the
507
+ // file landed (its chmod, index or revision) is undone too.
508
+ done.push({ to: f.to, before: f.replaces ? readLibraryFile(tenant, kind, f.to) : null });
509
+ writeLibraryFile(tenant, kind, f.to, f.content, { by: opts.by, message: `moved from ${workspace}/${f.from}` });
510
+ }
511
+ }
512
+ catch (err) {
513
+ undo(err);
514
+ }
515
+ try {
516
+ deleteWorkspacePath(tenant, workspace, unit, { by: opts.by, message: `moved ${unit} to the shared library` });
517
+ }
518
+ catch (err) {
519
+ // Gone already, even in part (the delete landed, or stopped halfway, or
520
+ // its bookkeeping failed): the library copy is now the only whole one —
521
+ // keep it, and say so. Undo only while every original is still there.
522
+ if (!members.every((m) => fs.existsSync(path.join(dir, m)))) {
523
+ throw refusal(`moved ${unit} to the shared library, but recording it in ${workspace}'s history failed — ${err.message}`, 500);
524
+ }
525
+ undo(err);
526
+ }
527
+ return { ...answer, moved: true };
528
+ function undo(err) {
529
+ for (const d of done.reverse()) {
530
+ try {
531
+ if (d.before === null)
532
+ deleteLibraryPath(tenant, kind, d.to, { by: opts.by, message: "move to shared undone" });
533
+ else
534
+ writeLibraryFile(tenant, kind, d.to, d.before, { by: opts.by, message: "move to shared undone" });
535
+ }
536
+ catch {
537
+ // best effort: the error below says the move failed
538
+ }
539
+ }
540
+ throw refusal(`could not move ${unit} — ${err.message}; the library was put back and ${unit} is still in ${workspace}`, err.status ?? 500);
541
+ }
542
+ }
@@ -925,6 +925,17 @@ export declare function syncBundleFor(file: string, change?: "Creation" | "Updat
925
925
  */
926
926
  export declare function anchoredReason(rel: string): string | null;
927
927
  export declare function renameWorkspaceFile(tenant: string, workspace: string, from: string, to: string, meta?: ChangeMeta): void;
928
+ /**
929
+ * What deleteWorkspacePath(rel) would delete, or the refusal it would throw —
930
+ * without deleting anything. A whole-folder unit (an agent, a skill, a folder
931
+ * tool) is `folder: true`. For a caller that must know a delete will go
932
+ * through before it changes something else (moveToLibrary: the library is
933
+ * written first, the original deleted after).
934
+ */
935
+ export declare function assertDeletable(tenant: string, workspace: string, rel: string): {
936
+ norm: string;
937
+ folder: boolean;
938
+ };
928
939
  export declare function deleteWorkspacePath(tenant: string, workspace: string, rel: string, meta?: ChangeMeta): void;
929
940
  export declare function deleteWorkspace(tenant: string, workspace: string): void;
930
941
  /**
package/dist/src/store.js CHANGED
@@ -2604,7 +2604,14 @@ function deletionsUnder(dir, norm) {
2604
2604
  after: null,
2605
2605
  }));
2606
2606
  }
2607
- export function deleteWorkspacePath(tenant, workspace, rel, meta = {}) {
2607
+ /**
2608
+ * What deleteWorkspacePath(rel) would delete, or the refusal it would throw —
2609
+ * without deleting anything. A whole-folder unit (an agent, a skill, a folder
2610
+ * tool) is `folder: true`. For a caller that must know a delete will go
2611
+ * through before it changes something else (moveToLibrary: the library is
2612
+ * written first, the original deleted after).
2613
+ */
2614
+ export function assertDeletable(tenant, workspace, rel) {
2608
2615
  const norm = path.normalize(rel).replaceAll("\\", "/");
2609
2616
  if (norm.startsWith("..") || path.isAbsolute(norm))
2610
2617
  throw new Error(`illegal path: ${rel}`);
@@ -2634,13 +2641,22 @@ export function deleteWorkspacePath(tenant, workspace, rel, meta = {}) {
2634
2641
  // The last part may be a link — rmSync removes the link, not what it
2635
2642
  // names — but a linked folder ABOVE it would delete outside.
2636
2643
  assertLandsInside(dir, path.join(dir, norm), norm, false);
2644
+ return { norm, folder: true };
2645
+ }
2646
+ const p = path.join(dir, assertEditablePath(norm));
2647
+ assertLandsInside(dir, p, norm, false);
2648
+ return { norm, folder: false };
2649
+ }
2650
+ export function deleteWorkspacePath(tenant, workspace, rel, meta = {}) {
2651
+ const { norm, folder } = assertDeletable(tenant, workspace, rel);
2652
+ const dir = workspaceDir(tenant, workspace);
2653
+ if (folder) {
2637
2654
  const gone = deletionsUnder(dir, norm);
2638
2655
  fs.rmSync(path.join(dir, norm), { recursive: true, force: true });
2639
2656
  recordRevision(tenant, workspace, gone, { message: `deleted ${norm}/`, ...meta });
2640
2657
  return;
2641
2658
  }
2642
- const p = path.join(dir, assertEditablePath(norm));
2643
- assertLandsInside(dir, p, norm, false);
2659
+ const p = path.join(dir, norm);
2644
2660
  const gone = deletionsUnder(dir, norm);
2645
2661
  fs.rmSync(p, { force: true });
2646
2662
  recordRevision(tenant, workspace, gone, meta);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "14.3.4",
3
+ "version": "14.4.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/approvals.ts CHANGED
@@ -232,9 +232,12 @@ export async function decideApproval(
232
232
  }
233
233
  assertMayDecide(tenant, workspace, run, d);
234
234
 
235
+ // With no step named, a decision is for the gates waiting on a person: a
236
+ // `wait: event` step waits on its event, and is approved by its payload or
237
+ // rejected by name (5 Nov 2026: an unnamed reject failed it too).
235
238
  const waiting = run.steps
236
239
  .map((s, i) => ({ s, i }))
237
- .filter(({ s, i }) => s.status === "awaiting-approval" && (d.step === undefined || d.step === i) && (allowed === null || allowed.includes(i)));
240
+ .filter(({ s, i }) => s.status === "awaiting-approval" && (d.step === undefined ? s.waitFor !== "event" : d.step === i) && (allowed === null || allowed.includes(i)));
238
241
  if (waiting.length === 0) throw new ApprovalError("nothing is awaiting approval", 409);
239
242
 
240
243
  const note = typeof d.note === "string" ? d.note.trim() : "";
package/src/library.ts CHANGED
@@ -28,6 +28,8 @@ import {
28
28
  listWorkspaces,
29
29
  listAgents,
30
30
  workspaceDir,
31
+ deleteWorkspacePath,
32
+ assertDeletable,
31
33
  type ToolDef,
32
34
  } from "./store.ts";
33
35
 
@@ -438,3 +440,183 @@ registerTreeReader((tenant, scope) => {
438
440
  });
439
441
 
440
442
 
443
+
444
+
445
+ /** The workspace folders "Move to shared" applies to: the library's kinds
446
+ * but hooks, whose run.mjs is code a shared hook is made for on purpose. */
447
+ export const SHAREABLE_KINDS = ["skills", "tools", "scripts", "knowledge", "memory"] as const;
448
+
449
+ const refusal = (message: string, status: number) => Object.assign(new Error(message), { status });
450
+
451
+ /**
452
+ * Move a workspace's skill, tool, script, knowledge or memory file into the
453
+ * account library — the dashboard's and `foldrun source share`'s "Move to
454
+ * shared", done here in one call (5 Nov 2026). Done by the client it copied
455
+ * one file and deleted the folder (a skill's other files were lost), and a
456
+ * folder tool's path was flattened.
457
+ *
458
+ * A skill or folder tool moves as its whole folder; anything else names one
459
+ * file. Everything is checked before anything is written: a file the library
460
+ * cannot hold (an image, a binary), one too large, broken frontmatter, or a
461
+ * library file already at a path (unless `overwrite`) refuses the move and
462
+ * nothing changes. Then every file is copied and the original deleted, in
463
+ * one synchronous step. `dryRun` answers what would move.
464
+ */
465
+ export function moveToLibrary(
466
+ tenant: string,
467
+ workspace: string,
468
+ rel: string,
469
+ opts: { overwrite?: boolean; dryRun?: boolean; by?: string } = {},
470
+ ): { kind: LibraryKind; unit: string; files: { from: string; to: string; replaces: boolean }[]; moved: boolean } {
471
+ const clean = path.normalize(String(rel ?? "")).replaceAll("\\", "/").replace(/^(\.\/)+/, "").replace(/\/+$/, "");
472
+ if (!clean || clean === "." || clean.startsWith("..") || path.isAbsolute(clean)) throw refusal(`illegal path: ${rel}`, 400);
473
+ const [kind, ...rest] = clean.split("/");
474
+ if (kind === "hooks") throw refusal("a hook is a folder whose run.mjs goes with it — make a shared one with `foldrun hook add <name> --library`", 400);
475
+ if (!(SHAREABLE_KINDS as readonly string[]).includes(kind) || !rest.length) {
476
+ throw refusal(`"${rel}" is not under ${SHAREABLE_KINDS.join("/, ")}/ — only those move to the shared library`, 400);
477
+ }
478
+ const dir = workspaceDir(tenant, workspace);
479
+ const folderKind = kind === "skills" || kind === "tools";
480
+ // skills/x/SKILL.md or tools/x/tool.md names its folder: the folder is the unit.
481
+ const unit = folderKind && rest.length >= 2 ? `${kind}/${rest[0]}` : clean;
482
+ const full = path.join(dir, unit);
483
+ let stat: fs.Stats;
484
+ try {
485
+ stat = fs.lstatSync(full);
486
+ } catch {
487
+ throw refusal(`no ${unit} in ${workspace}`, 404);
488
+ }
489
+ if (stat.isSymbolicLink()) throw refusal(`${unit} is a link — move what it points at instead`, 400);
490
+ if (stat.isDirectory() && !(folderKind && unit.split("/").length === 2)) {
491
+ throw refusal(`${unit} is a folder — name a file in it (only a skill or a folder tool moves as a folder)`, 400);
492
+ }
493
+ const realDir = fs.realpathSync(dir);
494
+ if (!fs.realpathSync(full).startsWith(realDir + path.sep)) throw refusal(`illegal path: ${rel}`, 400);
495
+ // The original is deleted last, so ask now whether that delete would go
496
+ // through: a file the workspace cannot do without (knowledge/index.md, a
497
+ // memory log) or a folder that is not a whole unit is refused before the
498
+ // library is touched.
499
+ try {
500
+ const d = assertDeletable(tenant, workspace, unit);
501
+ if (stat.isDirectory() !== d.folder) throw new Error(`${unit} cannot be moved as one thing`);
502
+ } catch (err) {
503
+ throw refusal(`${(err as Error).message} — nothing was moved`, 409);
504
+ }
505
+
506
+ const members: string[] = stat.isDirectory()
507
+ ? (fs.readdirSync(full, { recursive: true }) as string[])
508
+ .map((e) => path.join(full, String(e)))
509
+ .filter((e) => {
510
+ const st = fs.lstatSync(e);
511
+ if (st.isSymbolicLink()) throw refusal(`${path.relative(dir, e)} is a link — the library holds files, not links; nothing was moved`, 409);
512
+ return st.isFile();
513
+ })
514
+ .map((e) => path.relative(dir, e).split(path.sep).join("/"))
515
+ .sort()
516
+ : [unit];
517
+ if (!members.length) throw refusal(`${unit} is empty — nothing to move`, 400);
518
+
519
+ const files: { from: string; to: string; replaces: boolean; content: string }[] = [];
520
+ const cannot: string[] = [];
521
+ for (const from of members) {
522
+ const to = from.slice(kind.length + 1);
523
+ try {
524
+ assertLibraryPath(kind as LibraryKind, to);
525
+ } catch {
526
+ cannot.push(from);
527
+ continue;
528
+ }
529
+ // Text in the library's sense: an allowed extension AND bytes that are
530
+ // UTF-8, or reading it as text would change it and the original goes.
531
+ const bytes = fs.readFileSync(path.join(dir, from));
532
+ const content = bytes.toString("utf8");
533
+ if (!Buffer.from(content, "utf8").equals(bytes)) {
534
+ cannot.push(from);
535
+ continue;
536
+ }
537
+ if (content.length > MAX_EDITABLE_FILE) throw refusal(`${from} is too large for the library (over ${Math.round(MAX_EDITABLE_FILE / 1024)} KB); nothing was moved`, 409);
538
+ if (to.endsWith(".md")) {
539
+ try {
540
+ matter(content);
541
+ } catch {
542
+ throw refusal(`${from} has frontmatter that does not parse; fix it first — nothing was moved`, 409);
543
+ }
544
+ }
545
+ files.push({ from, to, replaces: libraryFileExists(tenant, kind as LibraryKind, to), content });
546
+ }
547
+ if (cannot.length) {
548
+ throw refusal(`${unit} holds files the shared library cannot hold (${cannot.join(", ")}) — only text files go there; nothing was moved`, 409);
549
+ }
550
+ // A file already where one of these needs a folder (or a folder where one
551
+ // needs a file) would stop the copy halfway: refuse it now.
552
+ // And no link anywhere on the library side: a write through one could land
553
+ // back in the workspace, and the delete after it would take the only copy.
554
+ const shelf = libraryDir(tenant, kind as LibraryKind);
555
+ const linked = (p: string) => {
556
+ try {
557
+ return fs.lstatSync(p).isSymbolicLink();
558
+ } catch {
559
+ return false;
560
+ }
561
+ };
562
+ for (const up of [path.dirname(shelf), shelf]) {
563
+ if (linked(up)) throw refusal(`the library's ${kind} shelf is a link — nothing was moved`, 409);
564
+ }
565
+ for (const f of files) {
566
+ const parts = f.to.split("/");
567
+ for (let i = 1; i <= parts.length; i++) {
568
+ const at = path.join(shelf, ...parts.slice(0, i));
569
+ if (linked(at)) throw refusal(`the library has a link at ${kind}/${parts.slice(0, i).join("/")} — nothing was moved`, 409);
570
+ if (i < parts.length && fs.existsSync(at) && !fs.statSync(at).isDirectory()) throw refusal(`the library has a file at ${kind}/${parts.slice(0, i).join("/")}, where ${kind}/${f.to} needs a folder — nothing was moved`, 409);
571
+ if (i === parts.length && fs.existsSync(at) && fs.statSync(at).isDirectory()) throw refusal(`the library has a folder at ${kind}/${f.to} — nothing was moved`, 409);
572
+ }
573
+ // The bundle files a write keeps beside it (syncBundleFor) are written too.
574
+ for (const keeper of ["index.md", "log.md"]) {
575
+ const at = path.join(shelf, path.dirname(f.to), keeper);
576
+ if (linked(at)) throw refusal(`the library has a link at ${kind}/${path.join(path.dirname(f.to), keeper)} — nothing was moved`, 409);
577
+ }
578
+ }
579
+ const taken = files.filter((f) => f.replaces);
580
+ const answer = { kind: kind as LibraryKind, unit, files: files.map(({ from, to, replaces }) => ({ from, to, replaces })) };
581
+ if (taken.length && !opts.overwrite && !opts.dryRun) {
582
+ throw refusal(`the library already has ${taken.map((f) => `${kind}/${f.to}`).join(", ")} — nothing was moved; overwrite replaces ${taken.length === 1 ? "it" : "them"}`, 409);
583
+ }
584
+ if (opts.dryRun) return { ...answer, moved: false };
585
+ // Copy, then delete; if anything fails on the way, put the library back
586
+ // as it was (each undo is a revision too), so a move is all or nothing.
587
+ const done: { to: string; before: string | null }[] = [];
588
+ try {
589
+ for (const f of files) {
590
+ // On the undo list before the write: a writer that fails after the
591
+ // file landed (its chmod, index or revision) is undone too.
592
+ done.push({ to: f.to, before: f.replaces ? readLibraryFile(tenant, kind as LibraryKind, f.to) : null });
593
+ writeLibraryFile(tenant, kind as LibraryKind, f.to, f.content, { by: opts.by, message: `moved from ${workspace}/${f.from}` });
594
+ }
595
+ } catch (err) {
596
+ undo(err);
597
+ }
598
+ try {
599
+ deleteWorkspacePath(tenant, workspace, unit, { by: opts.by, message: `moved ${unit} to the shared library` });
600
+ } catch (err) {
601
+ // Gone already, even in part (the delete landed, or stopped halfway, or
602
+ // its bookkeeping failed): the library copy is now the only whole one —
603
+ // keep it, and say so. Undo only while every original is still there.
604
+ if (!members.every((m) => fs.existsSync(path.join(dir, m)))) {
605
+ throw refusal(`moved ${unit} to the shared library, but recording it in ${workspace}'s history failed — ${(err as Error).message}`, 500);
606
+ }
607
+ undo(err);
608
+ }
609
+ return { ...answer, moved: true };
610
+
611
+ function undo(err: unknown): never {
612
+ for (const d of done.reverse()) {
613
+ try {
614
+ if (d.before === null) deleteLibraryPath(tenant, kind as LibraryKind, d.to, { by: opts.by, message: "move to shared undone" });
615
+ else writeLibraryFile(tenant, kind as LibraryKind, d.to, d.before, { by: opts.by, message: "move to shared undone" });
616
+ } catch {
617
+ // best effort: the error below says the move failed
618
+ }
619
+ }
620
+ throw refusal(`could not move ${unit} — ${(err as Error).message}; the library was put back and ${unit} is still in ${workspace}`, (err as { status?: number }).status ?? 500);
621
+ }
622
+ }
package/src/store.ts CHANGED
@@ -3104,7 +3104,14 @@ function deletionsUnder(dir: string, norm: string): RevisionFile[] {
3104
3104
  }));
3105
3105
  }
3106
3106
 
3107
- export function deleteWorkspacePath(tenant: string, workspace: string, rel: string, meta: ChangeMeta = {}) {
3107
+ /**
3108
+ * What deleteWorkspacePath(rel) would delete, or the refusal it would throw —
3109
+ * without deleting anything. A whole-folder unit (an agent, a skill, a folder
3110
+ * tool) is `folder: true`. For a caller that must know a delete will go
3111
+ * through before it changes something else (moveToLibrary: the library is
3112
+ * written first, the original deleted after).
3113
+ */
3114
+ export function assertDeletable(tenant: string, workspace: string, rel: string): { norm: string; folder: boolean } {
3108
3115
  const norm = path.normalize(rel).replaceAll("\\", "/");
3109
3116
  if (norm.startsWith("..") || path.isAbsolute(norm)) throw new Error(`illegal path: ${rel}`);
3110
3117
  const dir = workspaceDir(tenant, workspace);
@@ -3133,13 +3140,23 @@ export function deleteWorkspacePath(tenant: string, workspace: string, rel: stri
3133
3140
  // The last part may be a link — rmSync removes the link, not what it
3134
3141
  // names — but a linked folder ABOVE it would delete outside.
3135
3142
  assertLandsInside(dir, path.join(dir, norm), norm, false);
3143
+ return { norm, folder: true };
3144
+ }
3145
+ const p = path.join(dir, assertEditablePath(norm));
3146
+ assertLandsInside(dir, p, norm, false);
3147
+ return { norm, folder: false };
3148
+ }
3149
+
3150
+ export function deleteWorkspacePath(tenant: string, workspace: string, rel: string, meta: ChangeMeta = {}) {
3151
+ const { norm, folder } = assertDeletable(tenant, workspace, rel);
3152
+ const dir = workspaceDir(tenant, workspace);
3153
+ if (folder) {
3136
3154
  const gone = deletionsUnder(dir, norm);
3137
3155
  fs.rmSync(path.join(dir, norm), { recursive: true, force: true });
3138
3156
  recordRevision(tenant, workspace, gone, { message: `deleted ${norm}/`, ...meta });
3139
3157
  return;
3140
3158
  }
3141
- const p = path.join(dir, assertEditablePath(norm));
3142
- assertLandsInside(dir, p, norm, false);
3159
+ const p = path.join(dir, norm);
3143
3160
  const gone = deletionsUnder(dir, norm);
3144
3161
  fs.rmSync(p, { force: true });
3145
3162
  recordRevision(tenant, workspace, gone, meta);