From 5441ee5788b2317076c4762d094b615a9e250e5b Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Thu, 26 Nov 2026 00:46:13 -0600 Subject: [PATCH 1/3] fix(server): the library's state folder is a plain folder, so state and pairings are never written through a link (ISSUE-33) A cloned library can carry a link (or a file) at .viewswitcher/, and the server wrote state.json, settings.json, devices.json and kit.json wherever it pointed. At startup, before anything reads or writes there, plainStateFolder (library/contain.ts) moves a link or a file aside, kept and named in the log, and the library makes a plain folder in its place. Links that arrive with the library are the case the containment rule defends (Decisions, 2026-11-26). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ1ZdpFyktLPZbQXJSh --- apps/server/src/library/contain.test.ts | 40 +++++++++++++++++++++++-- apps/server/src/library/contain.ts | 18 ++++++++++- apps/server/src/main.ts | 4 +++ 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/apps/server/src/library/contain.test.ts b/apps/server/src/library/contain.test.ts index e50bf72..6b742b2 100644 --- a/apps/server/src/library/contain.test.ts +++ b/apps/server/src/library/contain.test.ts @@ -1,9 +1,9 @@ // The library's one real-path rule (contain.ts), on a real folder with real links. import { afterAll, describe, expect, test } from "bun:test"; -import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { realLibraryPath, resolveInLibrary } from "./contain"; +import { plainStateFolder, realLibraryPath, resolveInLibrary } from "./contain"; const library = mkdtempSync(join(tmpdir(), "vs-contain-")); const outside = mkdtempSync(join(tmpdir(), "vs-contain-out-")); @@ -86,3 +86,39 @@ describe("a path that can't be read", () => { } }); }); + +describe("plainStateFolder", () => { + const lib = () => mkdtempSync(join(tmpdir(), "vs-state-")); + const at = new Date("2026-11-26T08:00:00.000Z"); + + test("a plain folder, or none yet, is left as it is", async () => { + const empty = lib(); + expect(await plainStateFolder(empty, at)).toBeNull(); + expect(existsSync(join(empty, ".viewswitcher"))).toBe(false); + const plain = lib(); + mkdirSync(join(plain, ".viewswitcher")); + writeFileSync(join(plain, ".viewswitcher", "state.json"), "{}"); + expect(await plainStateFolder(plain, at)).toBeNull(); + expect(readFileSync(join(plain, ".viewswitcher", "state.json"), "utf8")).toBe("{}"); + }); + + test("a link is moved aside, never followed: what it points at is untouched", async () => { + const root = lib(); + const elsewhere = mkdtempSync(join(tmpdir(), "vs-elsewhere-")); + writeFileSync(join(elsewhere, "keep.txt"), "mine"); + symlinkSync(elsewhere, join(root, ".viewswitcher")); + const aside = await plainStateFolder(root, at); + expect(aside).toBe(join(root, ".viewswitcher.moved-aside-2026-11-26T08-00-00-000Z")); + expect(lstatSync(aside!).isSymbolicLink()).toBe(true); // kept, as the link it was + expect(existsSync(join(root, ".viewswitcher"))).toBe(false); // the library makes a plain one next + expect(readFileSync(join(elsewhere, "keep.txt"), "utf8")).toBe("mine"); + }); + + test("a file where the folder should be is moved aside too", async () => { + const root = lib(); + writeFileSync(join(root, ".viewswitcher"), "not a folder"); + const aside = await plainStateFolder(root, at); + expect(readFileSync(aside!, "utf8")).toBe("not a folder"); + expect(existsSync(join(root, ".viewswitcher"))).toBe(false); + }); +}); diff --git a/apps/server/src/library/contain.ts b/apps/server/src/library/contain.ts index 8d76a40..d01b6d8 100644 --- a/apps/server/src/library/contain.ts +++ b/apps/server/src/library/contain.ts @@ -11,7 +11,7 @@ // // Paths still go through inside() and plainName() (paths.ts) first; this adds what the real files say. import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from "node:fs"; -import { type FileHandle, lstat, open, realpath } from "node:fs/promises"; +import { type FileHandle, lstat, open, realpath, rename } from "node:fs/promises"; import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"; import { inside, PathError } from "../paths"; @@ -118,6 +118,22 @@ async function plainStaging(dir: string): Promise { return at; } +/** + * The library's own state folder (/.viewswitcher: state.json, settings.json, devices.json, + * kit.json) as a plain folder, made so at startup before anything reads or writes it. A cloned library + * can carry a link (or a file) there; the switcher would write its state and pairings wherever it + * points. So a link or a file is moved aside, kept and named in the log, and the folder starts empty: + * never followed, never deleted. Returns where it was moved, or null when there was nothing to move. + */ +export async function plainStateFolder(libraryRoot: string, now = new Date()): Promise { + const at = join(libraryRoot, ".viewswitcher"); + const s = await lstat(at).catch(() => null); + if (!s || s.isDirectory()) return null; + const aside = `${at}.moved-aside-${now.toISOString().replace(/[:.]/g, "-")}`; + await rename(at, aside); + return aside; +} + /** * Where a library path really is (through links), as a library path, or the path itself when that * can't be told. Synchronous, for checks that must happen at one instant (the agents' on-air guard). diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index b604474..0f337c1 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -13,6 +13,7 @@ import { dispatcher, type SocketData } from "./http/dispatch"; import { pairPageResponse, routes, secure } from "./http/routes"; import { pairingOrder, thisMac } from "./lan"; import { appParent, watchParent } from "./parent-watch"; +import { plainStateFolder } from "./library/contain"; import { LibraryScanner } from "./library/scanner"; import { ensureLibrary } from "./library-kit"; import { createPlacer } from "./live/placement"; @@ -31,6 +32,9 @@ import { createSlotOrder } from "./slot-order"; import { startUsbBridge, usbAvailable } from "./usb-bridge"; // A new library gets the agent skill, CLAUDE.md, a git repo and a first org; an existing one is left as it is. +// The state folder must be a plain folder before anything writes state or pairings into it (contain.ts). +const movedAside = await plainStateFolder(config.library); +if (movedAside) console.error(`[library] .viewswitcher was a link or a file, so it was moved aside to ${movedAside} and a plain folder starts in its place`); const firstRun = await ensureLibrary(config.library, { kit: config.libraryKit, starter: config.starter }); if (firstRun.copied.length || firstRun.updated.length || firstRun.org) { const did = [ From a453ec766eace1c79be191ba31a04134fd0a8fc0 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Thu, 26 Nov 2026 00:51:20 -0600 Subject: [PATCH 2/3] fix(server): every state write and settings read heals a state folder that became a link, not just startup (ISSUE-33) Review of #34: .viewswitcher/ is gitignored, so a git pull whose upstream committed a link there replaces the local folder while the server runs, and the startup check alone missed it. - contain.ts plainFolder(dir): a link or a file at dir is moved aside (kept, logged); a rename that fails says what to do. plainStateFolder is that for /.viewswitcher. - writeAtomic({ plainParent }) runs it before each write: the on-air record, settings, the paired devices and kit.json pass it. The settings read runs it too, so the agents' guard never reads settings through a link (a failure there reads as the strictest setting). - The library kit's .gitignore ignores the moved-aside names. - atomic.test.ts: the swap after start, a plain write, and settings through a link. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ1ZdpFyktLPZbQXJSh --- apps/server/library-kit/library-gitignore | 1 + apps/server/src/atomic.test.ts | 46 +++++++++++++++++++++++ apps/server/src/atomic.ts | 8 +++- apps/server/src/library-kit.ts | 2 +- apps/server/src/library/contain.ts | 31 ++++++++++----- apps/server/src/live/store.ts | 2 +- apps/server/src/main.ts | 3 +- apps/server/src/pairing.ts | 2 +- apps/server/src/settings.ts | 5 ++- 9 files changed, 82 insertions(+), 18 deletions(-) create mode 100644 apps/server/src/atomic.test.ts diff --git a/apps/server/library-kit/library-gitignore b/apps/server/library-kit/library-gitignore index 8cadae9..e654e38 100644 --- a/apps/server/library-kit/library-gitignore +++ b/apps/server/library-kit/library-gitignore @@ -1,2 +1,3 @@ .viewswitcher/ +.viewswitcher.moved-aside-* .DS_Store diff --git a/apps/server/src/atomic.test.ts b/apps/server/src/atomic.test.ts new file mode 100644 index 0000000..57b1677 --- /dev/null +++ b/apps/server/src/atomic.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, test } from "bun:test"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { writeAtomic } from "./atomic"; +import { readSettings } from "./settings"; + +const scratch = (name: string) => mkdtempSync(join(tmpdir(), `vs-${name}-`)); + +describe("writeAtomic with plainParent", () => { + test("a state folder that became a link (a git pull) is moved aside, and the write lands in a plain folder", async () => { + const lib = scratch("lib"); + const elsewhere = scratch("elsewhere"); + mkdirSync(join(lib, ".viewswitcher")); + await writeAtomic(join(lib, ".viewswitcher", "state.json"), "{}", { plainParent: true }); + // The swap happens while the server runs: the plain folder is replaced by a link to another place. + const { rmSync } = await import("node:fs"); + rmSync(join(lib, ".viewswitcher"), { recursive: true }); + symlinkSync(elsewhere, join(lib, ".viewswitcher")); + + await writeAtomic(join(lib, ".viewswitcher", "devices.json"), "secret", { mode: 0o600, plainParent: true }); + expect(lstatSync(join(lib, ".viewswitcher")).isDirectory()).toBe(true); + expect(readFileSync(join(lib, ".viewswitcher", "devices.json"), "utf8")).toBe("secret"); + expect(readdirSync(elsewhere)).toEqual([]); // nothing was written through the link + expect(readdirSync(lib).some((n) => n.startsWith(".viewswitcher.moved-aside-"))).toBe(true); + }); + + test("without it, a plain write is unchanged", async () => { + const dir = scratch("plain"); + await writeAtomic(join(dir, "sub", "x.json"), "1"); + expect(readFileSync(join(dir, "sub", "x.json"), "utf8")).toBe("1"); + }); +}); + +describe("settings", () => { + test("settings that came in through a linked state folder are never read: it's moved aside first", async () => { + const lib = scratch("lib"); + const elsewhere = scratch("elsewhere"); + const { writeFileSync } = await import("node:fs"); + writeFileSync(join(elsewhere, "settings.json"), JSON.stringify({ agentOnAir: "always" })); + symlinkSync(elsewhere, join(lib, ".viewswitcher")); + // The moved-aside folder's "always" never counts: the fresh folder has no settings yet, so the default. + expect((await readSettings(lib)).agentOnAir).toBe("not-live"); + expect(existsSync(join(elsewhere, "settings.json"))).toBe(true); // left where it was + }); +}); diff --git a/apps/server/src/atomic.ts b/apps/server/src/atomic.ts index 93563d3..f083555 100644 --- a/apps/server/src/atomic.ts +++ b/apps/server/src/atomic.ts @@ -5,14 +5,18 @@ // still the version that was read; a new file that claims its name is an exclusive create instead.) import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; +import { plainFolder } from "./library/contain"; /** * Write `data` to a temp file beside `file`, then rename it over `file`. The temp name has a random * part, so two writes in flight never share (or rename) each other's half-written copy. `mode` * (devices.json's 0o600) is set on the copy before it takes the name, so the file is never readable - * by others, even for a moment. + * by others, even for a moment. With `plainParent` (the switcher's own state in .viewswitcher/), a + * link or a file where its folder should be is moved aside first (contain.ts plainFolder), so the + * write never goes through a link that appeared since the last one. */ -export async function writeAtomic(file: string, data: string | Uint8Array, { mode }: { mode?: number } = {}): Promise { +export async function writeAtomic(file: string, data: string | Uint8Array, { mode, plainParent }: { mode?: number; plainParent?: boolean } = {}): Promise { + if (plainParent) await plainFolder(dirname(file)); await mkdir(dirname(file), { recursive: true }); const tmp = `${file}.${crypto.randomUUID().slice(0, 8)}.tmp`; try { diff --git a/apps/server/src/library-kit.ts b/apps/server/src/library-kit.ts index ee601a3..1ab79b9 100644 --- a/apps/server/src/library-kit.ts +++ b/apps/server/src/library-kit.ts @@ -77,7 +77,7 @@ export async function ensureLibrary(root: string, { kit, starter, firstOrg = FIR written[to] = sha(text); } if (JSON.stringify(written) !== JSON.stringify(state.files ?? {})) { - await writeAtomic(statePath, JSON.stringify({ files: written }, null, 2) + "\n"); + await writeAtomic(statePath, JSON.stringify({ files: written }, null, 2) + "\n", { plainParent: true }); } if (fresh && !existsSync(join(root, ".git"))) result.git = await gitInit(root).catch(() => false); diff --git a/apps/server/src/library/contain.ts b/apps/server/src/library/contain.ts index d01b6d8..138ae40 100644 --- a/apps/server/src/library/contain.ts +++ b/apps/server/src/library/contain.ts @@ -119,21 +119,32 @@ async function plainStaging(dir: string): Promise { } /** - * The library's own state folder (/.viewswitcher: state.json, settings.json, devices.json, - * kit.json) as a plain folder, made so at startup before anything reads or writes it. A cloned library - * can carry a link (or a file) there; the switcher would write its state and pairings wherever it - * points. So a link or a file is moved aside, kept and named in the log, and the folder starts empty: - * never followed, never deleted. Returns where it was moved, or null when there was nothing to move. + * `dir` as a plain folder, or nothing there yet: a link or a file at `dir` is moved aside (kept, renamed + * `.moved-aside-