@foldrun/core 22.1.0 → 22.2.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.
@@ -22,6 +22,16 @@ export declare function callSink(owner: object, ctx: Ctx): (part: CapturedCall)
22
22
  export declare function flushCalls(owner: object): Promise<void>;
23
23
  /** One recorded call, or null (not recorded). The row first, then the file. */
24
24
  export declare function readCapturedCallAsync(tenant: string, workspace: string, runId: string, callId: string): Promise<CapturedCall | null>;
25
+ /**
26
+ * One call from a run's folder into the store, whatever the switch says
27
+ * (FOL-126: the one-time copy of the runs written before calls went to the
28
+ * store, before the shared volume goes). "stored", "present" (already in the
29
+ * store), or "unavailable": the store is not set up here — never mistaken for
30
+ * present (Codex review).
31
+ */
32
+ export declare function backfillCall(tenant: string, workspace: string, runId: string, call: CapturedCall, opts?: {
33
+ dryRun?: boolean;
34
+ }): Promise<"stored" | "present" | "unavailable">;
25
35
  /** What the run-delete hook started and has not finished (tests, a process that is ending). */
26
36
  export declare function settleCalls(): Promise<void>;
27
37
  /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
@@ -179,6 +179,31 @@ export async function readCapturedCallAsync(tenant, workspace, runId, callId) {
179
179
  }
180
180
  return readCapturedCall(tenant, workspace, runId, callId);
181
181
  }
182
+ /**
183
+ * One call from a run's folder into the store, whatever the switch says
184
+ * (FOL-126: the one-time copy of the runs written before calls went to the
185
+ * store, before the shared volume goes). "stored", "present" (already in the
186
+ * store), or "unavailable": the store is not set up here — never mistaken for
187
+ * present (Codex review).
188
+ */
189
+ export async function backfillCall(tenant, workspace, runId, call, opts = {}) {
190
+ const deps = CALLS.backend;
191
+ const port = portFor(tenant, workspace);
192
+ if (!deps || !port)
193
+ return "unavailable";
194
+ if (!SAFE.test(runId) || !SAFE.test(call.id))
195
+ throw new Error(`not a call id: ${call.id}`);
196
+ if (await port.async.stepGet(tenant, workspace, runId, KIND, call.id))
197
+ return "present";
198
+ if (opts.dryRun)
199
+ return "stored"; // would be
200
+ const bytes = Buffer.from(JSON.stringify(call));
201
+ const sha = sha256Hex(bytes);
202
+ await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
203
+ await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes, { contentType: "application/json" });
204
+ await port.async.stepPut(tenant, workspace, runId, KIND, call.id, { sha, size: bytes.length });
205
+ return "stored";
206
+ }
182
207
  // ---------------------------------------------------------------- lifecycle
183
208
  /** What the run-delete hook started and has not finished (tests, a process that is ending). */
184
209
  export async function settleCalls() {
@@ -61,7 +61,9 @@ export const MODE_EXEC = 0o755;
61
61
  // tests/manifest.test.ts compares this list with WORKSPACE_DIRS and fails when
62
62
  // they differ — the failure is the prompt to decide which side the new folder
63
63
  // is on, and whether that needs manifest v2.
64
- export const AUTHORED_DIRS = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks"];
64
+ // "library": the account's shelf, kept as the scope "@library" whose folder is
65
+ // the account's (account AGENTS.md + library/**, FOL-126); no workspace has one.
66
+ export const AUTHORED_DIRS = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks", "library"];
65
67
  export const STATE_DIRS = ["state"];
66
68
  export const AUTHORED_ROOT_FILES = ["AGENTS.md", "project.md"];
67
69
  /** A conflict copy of a root file (conflictPath) is a root file too. */
@@ -26,7 +26,7 @@ export function mirrorOn() {
26
26
  return false;
27
27
  }
28
28
  }
29
- const SAFE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
29
+ const SAFE = /^(?:@library|[A-Za-z0-9][A-Za-z0-9_.-]{0,127})$/;
30
30
  export const mirrorBaseFile = (tenant, workspace) => SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
31
31
  export function readMirrorBase(tenant, workspace) {
32
32
  const f = mirrorBaseFile(tenant, workspace);
@@ -79,7 +79,8 @@ export function newRevisionId() {
79
79
  export function localRevisionStore(root = path.join(dataRoot(), ".revisions")) {
80
80
  const dirOf = (ws) => {
81
81
  assertSafeName(ws.tenant, "tenant");
82
- assertSafeName(ws.workspace, "workspace");
82
+ if (ws.workspace !== "@library")
83
+ assertSafeName(ws.workspace, "workspace"); // the account shelf's scope
83
84
  // The state head is a separate history in a subfolder of its own; the
84
85
  // workspace head's folder never lists it (seqs reads revs/ only).
85
86
  return scopeOf(ws) === "state" ? path.join(root, ws.tenant, ws.workspace, "state-head") : path.join(root, ws.tenant, ws.workspace);
@@ -39,6 +39,9 @@ export interface BlobCache {
39
39
  put(tenant: string, sha: string, bytes: Buffer): Promise<void>;
40
40
  }
41
41
  export declare function setBlobCache(c: BlobCache | null): void;
42
+ /** The account's AGENTS.md or library changed outside the journal (a route
43
+ * that writes the file itself): publish it, as any other change of a scope. */
44
+ export declare function noteAccountFilesChanged(tenant: string): void;
42
45
  /** One file a step wrote back to the workspace (run-container.ts
43
46
  * applyContainerChanges): `base` is the sha of the folder's copy before the
44
47
  * write (null: new file), `after` the bytes now on the folder. */
@@ -36,7 +36,7 @@ import path from "node:path";
36
36
  import crypto from "node:crypto";
37
37
  import { pipeline } from "node:stream/promises";
38
38
  import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle } from "./history.js";
39
- import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.js";
39
+ import { workspaceDir, accountDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.js";
40
40
  import { dataRoot } from "./paths.js";
41
41
  import { processState } from "./process-state.js";
42
42
  import { opsError, opsLog } from "./ops-log.js";
@@ -88,7 +88,7 @@ const entryStore = () => S.primary ?? legacyFiles;
88
88
  export function setRevisionBackend(deps, opts = {}) {
89
89
  // Every commit asks, inside the store's workspace lock, whether the folder is
90
90
  // still there: a delete or rename on another pod removes it under that lock.
91
- S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
91
+ S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(folderOf(ws.tenant, ws.workspace))) } : null;
92
92
  S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
93
93
  S.primary = opts.journalStore ?? null;
94
94
  S.retention = opts.stateRetention ?? null;
@@ -139,6 +139,17 @@ const restoring = S.restoring;
139
139
  const key = (tenant, workspace) => `${tenant}\0${workspace}`;
140
140
  const split = (k) => k.split("\0");
141
141
  const journalRoot = () => path.join(dataRoot(), ".revision-journal");
142
+ /** Where a scope's files are: a workspace's folder, or for the account shelf
143
+ * ("@library") the account's own — its AGENTS.md and library/ (FOL-126). */
144
+ function folderOf(tenant, workspace) {
145
+ return workspace === "@library" ? accountDir(tenant) : workspaceDir(tenant, workspace);
146
+ }
147
+ /** The account's AGENTS.md or library changed outside the journal (a route
148
+ * that writes the file itself): publish it, as any other change of a scope. */
149
+ export function noteAccountFilesChanged(tenant) {
150
+ if (S.backend && journalOn())
151
+ requestReconcile(tenant, "@library");
152
+ }
142
153
  /** Write the entry down, atomically. A store that refuses leaves the entry in
143
154
  * memory only (said once per failure), as the journal always was. */
144
155
  function persist(tenant, workspace, e) {
@@ -164,8 +175,8 @@ function forget(tenant, workspace, e) {
164
175
  /** Called by history.recordRevision for every change set. Synchronous and
165
176
  * cheap; the commit happens in the background (flushRevisions waits for it). */
166
177
  function journalChange(tenant, scope, files, meta) {
167
- if (!S.backend || scope === "@library")
168
- return; // the account shelf is not a workspace
178
+ if (!S.backend)
179
+ return;
169
180
  const k = key(tenant, scope);
170
181
  if (!safe(S.gate.journal)) {
171
182
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
@@ -174,7 +185,9 @@ function journalChange(tenant, scope, files, meta) {
174
185
  }
175
186
  // Only what the head needs: the new content. The old text is the writer's
176
187
  // history record, not the journal's (it can be a quarter megabyte a file).
177
- const slim = files.map((f) => ({ path: f.path, before: null, after: f.after }));
188
+ // The account shelf's paths are `<kind>/<file>` in its own history and
189
+ // `library/<kind>/<file>` in its revisions (its folder is the account's).
190
+ const slim = files.map((f) => ({ path: scope === "@library" ? `library/${f.path}` : f.path, before: null, after: f.after }));
178
191
  enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
179
192
  }
180
193
  function enqueue(tenant, scope, entry) {
@@ -304,7 +317,7 @@ async function drainOne(k) {
304
317
  const entry = q[0];
305
318
  // The workspace was deleted while this waited (or retried): nothing to
306
319
  // publish, and nothing for a later boot to replay.
307
- if (!fs.existsSync(workspaceDir(tenant, workspace))) {
320
+ if (!fs.existsSync(folderOf(tenant, workspace))) {
308
321
  q.shift();
309
322
  forget(tenant, workspace, entry);
310
323
  continue;
@@ -354,7 +367,7 @@ async function drainOne(k) {
354
367
  // journal was off for a while, a run wrote the folder directly) is brought
355
368
  // to it. After the entries, never before: replaying an older change over a
356
369
  // reconciled head would write it backwards.
357
- if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
370
+ if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(folderOf(tenant, workspace))) {
358
371
  verified.add(k);
359
372
  try {
360
373
  await reconcileNow(tenant, workspace, "reconcile");
@@ -860,7 +873,7 @@ export async function recoverJournal(opts = {}) {
860
873
  const k = key(tenant, workspace);
861
874
  const q = queues.get(k) ?? [];
862
875
  const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
863
- const gone = !fs.existsSync(workspaceDir(tenant, workspace));
876
+ const gone = !fs.existsSync(folderOf(tenant, workspace));
864
877
  const found = [];
865
878
  let names = [];
866
879
  try {
@@ -920,7 +933,9 @@ export async function reconcileAll(opts = {}) {
920
933
  if (S.orphanMarks)
921
934
  await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
922
935
  for (const tenant of opts.tenants ?? listTenants()) {
923
- for (const w of listWorkspaces(tenant)) {
936
+ // The account shelf too (account AGENTS.md + library/), as a scope of its own.
937
+ const shelf = ["AGENTS.md", "library"].some((n) => fs.existsSync(path.join(accountDir(tenant), n)));
938
+ for (const w of [...listWorkspaces(tenant), ...(shelf ? [{ name: "@library" }] : [])]) {
924
939
  const k = key(tenant, w.name);
925
940
  try {
926
941
  verified.add(k); // reconciled explicitly below, and counted
@@ -972,7 +987,7 @@ async function hashOf(abs, size) {
972
987
  * not be read. Null when the folder is not there.
973
988
  */
974
989
  async function scanFolder(tenant, workspace) {
975
- const dir = workspaceDir(tenant, workspace);
990
+ const dir = folderOf(tenant, workspace);
976
991
  if (!fs.existsSync(dir))
977
992
  return null;
978
993
  const found = [];
@@ -1074,7 +1089,7 @@ async function uploadLarge(deps, tenant, changes, onDisk, opId) {
1074
1089
  }
1075
1090
  function modeOf(tenant, workspace, rel) {
1076
1091
  try {
1077
- return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1092
+ return fs.statSync(path.join(folderOf(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1078
1093
  }
1079
1094
  catch {
1080
1095
  return MODE_FILE;
@@ -1309,7 +1324,7 @@ async function reconcileNow(tenant, workspace, by = "reconcile") {
1309
1324
  // head alone is someone else's change not copied here yet, never undone.
1310
1325
  const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1311
1326
  if (base)
1312
- ({ have, want } = threeWay(have, scan, base, workspaceDir(tenant, workspace)));
1327
+ ({ have, want } = threeWay(have, scan, base, folderOf(tenant, workspace)));
1313
1328
  // A path the scan could not take (unreadable now, a name the manifest
1314
1329
  // refuses) but the folder still holds is neither added nor removed here;
1315
1330
  // one that is gone from the folder is gone from the head.
@@ -1368,7 +1383,7 @@ async function afterPublish(deps, ws, changes, r) {
1368
1383
  const { tenant, workspace } = ws;
1369
1384
  const base = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
1370
1385
  const conflicted = new Set(r.conflicts.map((c) => c.path));
1371
- const dir = workspaceDir(tenant, workspace);
1386
+ const dir = folderOf(tenant, workspace);
1372
1387
  let head = null;
1373
1388
  for (const [p, c] of Object.entries(changes)) {
1374
1389
  if (!conflicted.has(p)) {
@@ -1484,7 +1499,7 @@ async function syncNow(tenant, workspace) {
1484
1499
  const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
1485
1500
  if (busy())
1486
1501
  return "skipped";
1487
- const dir = workspaceDir(tenant, workspace);
1502
+ const dir = folderOf(tenant, workspace);
1488
1503
  // A copy whose folder is gone (the disk was cleared, a hand rm) starts again
1489
1504
  // from the heads: with the old record kept, every file would read as deleted
1490
1505
  // here and the reconcile would publish those deletes (Codex review).
@@ -1499,9 +1514,17 @@ async function syncNow(tenant, workspace) {
1499
1514
  return "absent";
1500
1515
  if (busy())
1501
1516
  return "skipped";
1502
- fs.rmSync(dir, { recursive: true, force: true });
1517
+ if (workspace === "@library") {
1518
+ // The shelf's folder is the ACCOUNT's: only what the shelf owns goes —
1519
+ // never the account folder with every workspace in it (Codex review).
1520
+ fs.rmSync(path.join(dir, "AGENTS.md"), { force: true });
1521
+ fs.rmSync(path.join(dir, "library"), { recursive: true, force: true });
1522
+ }
1523
+ else
1524
+ fs.rmSync(dir, { recursive: true, force: true });
1503
1525
  dropMirrorBase(tenant, workspace);
1504
- notifyWorkspaceChanged(tenant, workspace, "delete");
1526
+ if (workspace !== "@library")
1527
+ notifyWorkspaceChanged(tenant, workspace, "delete");
1505
1528
  return "removed";
1506
1529
  }
1507
1530
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
@@ -1642,7 +1665,7 @@ async function syncNow(tenant, workspace) {
1642
1665
  finished = true;
1643
1666
  if (ownChanges)
1644
1667
  requestReconcile(tenant, workspace);
1645
- if (wrote)
1668
+ if (wrote && workspace !== "@library")
1646
1669
  notifyWorkspaceChanged(tenant, workspace, "write");
1647
1670
  return "synced";
1648
1671
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "22.1.0",
3
+ "version": "22.2.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",
@@ -189,6 +189,28 @@ export async function readCapturedCallAsync(tenant: string, workspace: string, r
189
189
  return readCapturedCall(tenant, workspace, runId, callId);
190
190
  }
191
191
 
192
+ /**
193
+ * One call from a run's folder into the store, whatever the switch says
194
+ * (FOL-126: the one-time copy of the runs written before calls went to the
195
+ * store, before the shared volume goes). "stored", "present" (already in the
196
+ * store), or "unavailable": the store is not set up here — never mistaken for
197
+ * present (Codex review).
198
+ */
199
+ export async function backfillCall(tenant: string, workspace: string, runId: string, call: CapturedCall, opts: { dryRun?: boolean } = {}): Promise<"stored" | "present" | "unavailable"> {
200
+ const deps = CALLS.backend;
201
+ const port = portFor(tenant, workspace);
202
+ if (!deps || !port) return "unavailable";
203
+ if (!SAFE.test(runId) || !SAFE.test(call.id)) throw new Error(`not a call id: ${call.id}`);
204
+ if (await port.async!.stepGet!(tenant, workspace, runId, KIND, call.id)) return "present";
205
+ if (opts.dryRun) return "stored"; // would be
206
+ const bytes = Buffer.from(JSON.stringify(call));
207
+ const sha = sha256Hex(bytes);
208
+ await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
209
+ await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes, { contentType: "application/json" });
210
+ await port.async!.stepPut!(tenant, workspace, runId, KIND, call.id, { sha, size: bytes.length });
211
+ return "stored";
212
+ }
213
+
192
214
  // ---------------------------------------------------------------- lifecycle
193
215
 
194
216
  /** What the run-delete hook started and has not finished (tests, a process that is ending). */
package/src/manifest.ts CHANGED
@@ -89,7 +89,9 @@ export type ManifestId = string;
89
89
  // tests/manifest.test.ts compares this list with WORKSPACE_DIRS and fails when
90
90
  // they differ — the failure is the prompt to decide which side the new folder
91
91
  // is on, and whether that needs manifest v2.
92
- export const AUTHORED_DIRS: readonly string[] = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks"];
92
+ // "library": the account's shelf, kept as the scope "@library" whose folder is
93
+ // the account's (account AGENTS.md + library/**, FOL-126); no workspace has one.
94
+ export const AUTHORED_DIRS: readonly string[] = ["agents", "flows", "evals", "skills", "memory", "knowledge", "tools", "scripts", "hooks", "library"];
93
95
  export const STATE_DIRS: readonly string[] = ["state"];
94
96
  export const AUTHORED_ROOT_FILES: readonly string[] = ["AGENTS.md", "project.md"];
95
97
  /** A conflict copy of a root file (conflictPath) is a root file too. */
@@ -39,7 +39,7 @@ export function mirrorOn(): boolean {
39
39
  }
40
40
  }
41
41
 
42
- const SAFE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
42
+ const SAFE = /^(?:@library|[A-Za-z0-9][A-Za-z0-9_.-]{0,127})$/;
43
43
  export const mirrorBaseFile = (tenant: string, workspace: string): string | null =>
44
44
  SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
45
45
 
@@ -249,7 +249,7 @@ export function newRevisionId(): string {
249
249
  export function localRevisionStore(root: string = path.join(dataRoot(), ".revisions")): RevisionStore {
250
250
  const dirOf = (ws: WorkspaceRef) => {
251
251
  assertSafeName(ws.tenant, "tenant");
252
- assertSafeName(ws.workspace, "workspace");
252
+ if (ws.workspace !== "@library") assertSafeName(ws.workspace, "workspace"); // the account shelf's scope
253
253
  // The state head is a separate history in a subfolder of its own; the
254
254
  // workspace head's folder never lists it (seqs reads revs/ only).
255
255
  return scopeOf(ws) === "state" ? path.join(root, ws.tenant, ws.workspace, "state-head") : path.join(root, ws.tenant, ws.workspace);
@@ -37,7 +37,7 @@ import path from "node:path";
37
37
  import crypto from "node:crypto";
38
38
  import { pipeline } from "node:stream/promises";
39
39
  import { registerJournal, registerRevisionView, registerWorkspaceGone, registerWorkspaceLifecycle, type RevisionView, type RevisionFile, type RevisionSummary, type Revision as HistoryRevision } from "./history.ts";
40
- import { workspaceDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.ts";
40
+ import { workspaceDir, accountDir, listTenants, listWorkspaces, readWorkspaceFile, assertEditablePath, isPlatformPath, notifyWorkspaceChanged } from "./store.ts";
41
41
  import { dataRoot } from "./paths.ts";
42
42
  import { processState } from "./process-state.ts";
43
43
  import { opsError, opsLog } from "./ops-log.ts";
@@ -134,7 +134,7 @@ const entryStore = (): JournalStore => S.primary ?? legacyFiles;
134
134
  export function setRevisionBackend(deps: Deps | null, opts: BackendOptions = {}): void {
135
135
  // Every commit asks, inside the store's workspace lock, whether the folder is
136
136
  // still there: a delete or rename on another pod removes it under that lock.
137
- S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(workspaceDir(ws.tenant, ws.workspace))) } : null;
137
+ S.backend = deps ? { ...deps, workspaceExists: deps.workspaceExists ?? ((ws) => fs.existsSync(folderOf(ws.tenant, ws.workspace))) } : null;
138
138
  S.gate = { journal: opts.journal ?? (() => false), read: opts.read ?? (() => false) };
139
139
  S.primary = opts.journalStore ?? null;
140
140
  S.retention = opts.stateRetention ?? null;
@@ -237,6 +237,18 @@ const split = (k: string): [string, string] => k.split("\0") as [string, string]
237
237
 
238
238
  const journalRoot = () => path.join(dataRoot(), ".revision-journal");
239
239
 
240
+ /** Where a scope's files are: a workspace's folder, or for the account shelf
241
+ * ("@library") the account's own — its AGENTS.md and library/ (FOL-126). */
242
+ function folderOf(tenant: string, workspace: string): string {
243
+ return workspace === "@library" ? accountDir(tenant) : workspaceDir(tenant, workspace);
244
+ }
245
+
246
+ /** The account's AGENTS.md or library changed outside the journal (a route
247
+ * that writes the file itself): publish it, as any other change of a scope. */
248
+ export function noteAccountFilesChanged(tenant: string): void {
249
+ if (S.backend && journalOn()) requestReconcile(tenant, "@library");
250
+ }
251
+
240
252
  /** Write the entry down, atomically. A store that refuses leaves the entry in
241
253
  * memory only (said once per failure), as the journal always was. */
242
254
  function persist(tenant: string, workspace: string, e: Entry): void {
@@ -261,7 +273,7 @@ function forget(tenant: string, workspace: string, e: Entry): void {
261
273
  /** Called by history.recordRevision for every change set. Synchronous and
262
274
  * cheap; the commit happens in the background (flushRevisions waits for it). */
263
275
  function journalChange(tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }): void {
264
- if (!S.backend || scope === "@library") return; // the account shelf is not a workspace
276
+ if (!S.backend) return;
265
277
  const k = key(tenant, scope);
266
278
  if (!safe(S.gate.journal)) {
267
279
  verified.delete(k); // a change the head will not see: reconcile before trusting it again
@@ -270,7 +282,9 @@ function journalChange(tenant: string, scope: string, files: RevisionFile[], met
270
282
  }
271
283
  // Only what the head needs: the new content. The old text is the writer's
272
284
  // history record, not the journal's (it can be a quarter megabyte a file).
273
- const slim = files.map((f) => ({ path: f.path, before: null, after: f.after }));
285
+ // The account shelf's paths are `<kind>/<file>` in its own history and
286
+ // `library/<kind>/<file>` in its revisions (its folder is the account's).
287
+ const slim = files.map((f) => ({ path: scope === "@library" ? `library/${f.path}` : f.path, before: null, after: f.after }));
274
288
  enqueue(tenant, scope, { id: crypto.randomBytes(12).toString("hex"), files: slim, by: meta.by, message: meta.message, at: meta.at, restoredFrom: restoring.get(k) });
275
289
  }
276
290
 
@@ -417,7 +431,7 @@ async function drainOne(k: string): Promise<void> {
417
431
  const entry = q[0];
418
432
  // The workspace was deleted while this waited (or retried): nothing to
419
433
  // publish, and nothing for a later boot to replay.
420
- if (!fs.existsSync(workspaceDir(tenant, workspace))) {
434
+ if (!fs.existsSync(folderOf(tenant, workspace))) {
421
435
  q.shift();
422
436
  forget(tenant, workspace, entry);
423
437
  continue;
@@ -463,7 +477,7 @@ async function drainOne(k: string): Promise<void> {
463
477
  // journal was off for a while, a run wrote the folder directly) is brought
464
478
  // to it. After the entries, never before: replaying an older change over a
465
479
  // reconciled head would write it backwards.
466
- if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(workspaceDir(tenant, workspace))) {
480
+ if (S.backend && (!q || !q.length) && (!verified.has(k) || marked.has(k)) && fs.existsSync(folderOf(tenant, workspace))) {
467
481
  verified.add(k);
468
482
  try {
469
483
  await reconcileNow(tenant, workspace, "reconcile");
@@ -954,7 +968,7 @@ export async function recoverJournal(opts: { minAgeMs?: number } = {}): Promise<
954
968
  const k = key(tenant, workspace);
955
969
  const q = queues.get(k) ?? [];
956
970
  const held = new Set(q.filter((e) => e.store === store).map((e) => e.handle));
957
- const gone = !fs.existsSync(workspaceDir(tenant, workspace));
971
+ const gone = !fs.existsSync(folderOf(tenant, workspace));
958
972
  const found: Entry[] = [];
959
973
  let names: { handle: string; ageMs: number }[] = [];
960
974
  try {
@@ -1006,7 +1020,9 @@ export async function reconcileAll(opts: { by?: string; tenants?: string[] } = {
1006
1020
  // workspace of the same name.
1007
1021
  if (S.orphanMarks) await cleanOrphanedHistory(S.orphanMarks, { graceMs: S.orphanGrace }).catch((err) => opsError("revisions.orphans_failed", err, {}, "warn"));
1008
1022
  for (const tenant of opts.tenants ?? listTenants()) {
1009
- for (const w of listWorkspaces(tenant)) {
1023
+ // The account shelf too (account AGENTS.md + library/), as a scope of its own.
1024
+ const shelf = ["AGENTS.md", "library"].some((n) => fs.existsSync(path.join(accountDir(tenant), n)));
1025
+ for (const w of [...listWorkspaces(tenant), ...(shelf ? [{ name: "@library" }] : [])]) {
1010
1026
  const k = key(tenant, w.name);
1011
1027
  try {
1012
1028
  verified.add(k); // reconciled explicitly below, and counted
@@ -1066,7 +1082,7 @@ async function hashOf(abs: string, size: number): Promise<string> {
1066
1082
  * not be read. Null when the folder is not there.
1067
1083
  */
1068
1084
  async function scanFolder(tenant: string, workspace: string): Promise<{ files: Map<string, FolderFile>; left: Set<string> } | null> {
1069
- const dir = workspaceDir(tenant, workspace);
1085
+ const dir = folderOf(tenant, workspace);
1070
1086
  if (!fs.existsSync(dir)) return null;
1071
1087
  const found: { rel: string; abs: string; st: fs.Stats }[] = [];
1072
1088
  const left = new Set<string>();
@@ -1151,7 +1167,7 @@ async function uploadLarge(deps: Deps, tenant: string, changes: Changes, onDisk:
1151
1167
 
1152
1168
  function modeOf(tenant: string, workspace: string, rel: string): number {
1153
1169
  try {
1154
- return fs.statSync(path.join(workspaceDir(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1170
+ return fs.statSync(path.join(folderOf(tenant, workspace), rel)).mode & 0o111 ? MODE_EXEC : MODE_FILE;
1155
1171
  } catch {
1156
1172
  return MODE_FILE;
1157
1173
  }
@@ -1371,7 +1387,7 @@ async function reconcileNow(tenant: string, workspace: string, by = "reconcile")
1371
1387
  // differs from the last sync is this pod's change. A difference from the
1372
1388
  // head alone is someone else's change not copied here yet, never undone.
1373
1389
  const base = mirrorOn() ? readMirrorBase(tenant, workspace) : null;
1374
- if (base) ({ have, want } = threeWay(have, scan, base, workspaceDir(tenant, workspace)));
1390
+ if (base) ({ have, want } = threeWay(have, scan, base, folderOf(tenant, workspace)));
1375
1391
  // A path the scan could not take (unreadable now, a name the manifest
1376
1392
  // refuses) but the folder still holds is neither added nor removed here;
1377
1393
  // one that is gone from the folder is gone from the head.
@@ -1423,7 +1439,7 @@ async function afterPublish(deps: Deps, ws: WorkspaceRef, changes: Changes, r: P
1423
1439
  const { tenant, workspace } = ws;
1424
1440
  const base: MirrorBase = readMirrorBase(tenant, workspace) ?? { workspaceHead: null, stateHead: null, files: {}, at: new Date().toISOString() };
1425
1441
  const conflicted = new Set(r.conflicts.map((c) => c.path));
1426
- const dir = workspaceDir(tenant, workspace);
1442
+ const dir = folderOf(tenant, workspace);
1427
1443
  let head: Record<string, ManifestEntry> | null = null;
1428
1444
  for (const [p, c] of Object.entries(changes)) {
1429
1445
  if (!conflicted.has(p)) {
@@ -1524,7 +1540,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1524
1540
  const k = key(tenant, workspace);
1525
1541
  const busy = () => (queues.get(k)?.length ?? 0) > 0 || repairing.has(k) || frozen.has(k);
1526
1542
  if (busy()) return "skipped";
1527
- const dir = workspaceDir(tenant, workspace);
1543
+ const dir = folderOf(tenant, workspace);
1528
1544
  // A copy whose folder is gone (the disk was cleared, a hand rm) starts again
1529
1545
  // from the heads: with the old record kept, every file would read as deleted
1530
1546
  // here and the reconcile would publish those deletes (Codex review).
@@ -1537,9 +1553,14 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1537
1553
  if (!heads.workspace && !heads.state) {
1538
1554
  if (!base) return "absent";
1539
1555
  if (busy()) return "skipped";
1540
- fs.rmSync(dir, { recursive: true, force: true });
1556
+ if (workspace === "@library") {
1557
+ // The shelf's folder is the ACCOUNT's: only what the shelf owns goes —
1558
+ // never the account folder with every workspace in it (Codex review).
1559
+ fs.rmSync(path.join(dir, "AGENTS.md"), { force: true });
1560
+ fs.rmSync(path.join(dir, "library"), { recursive: true, force: true });
1561
+ } else fs.rmSync(dir, { recursive: true, force: true });
1541
1562
  dropMirrorBase(tenant, workspace);
1542
- notifyWorkspaceChanged(tenant, workspace, "delete");
1563
+ if (workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "delete");
1543
1564
  return "removed";
1544
1565
  }
1545
1566
  const ids = { workspaceHead: heads.workspace?.id ?? null, stateHead: heads.state?.id ?? null };
@@ -1666,7 +1687,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
1666
1687
  writeMirrorBase(tenant, workspace, { ...(blocked ? { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null } : ids), files: next, at: new Date().toISOString() });
1667
1688
  finished = true;
1668
1689
  if (ownChanges) requestReconcile(tenant, workspace);
1669
- if (wrote) notifyWorkspaceChanged(tenant, workspace, "write");
1690
+ if (wrote && workspace !== "@library") notifyWorkspaceChanged(tenant, workspace, "write");
1670
1691
  return "synced";
1671
1692
  } finally {
1672
1693
  if (!finished && touched) writeMirrorBase(tenant, workspace, { workspaceHead: base?.workspaceHead ?? null, stateHead: base?.stateHead ?? null, files: progress, at: new Date().toISOString() });