Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): restore cos-runner constants + loops.js atomicWrite

[._.]/ Adam Eivy55417416175b
diff --git a/.changelog/v2.20.0.md b/.changelog/v2.20.0.md
index ff25e9ecb2..ad1646ca8a 100644
--- a/.changelog/v2.20.0.md
+++ b/.changelog/v2.20.0.md
@@ -22,6 +22,10 @@ Released: 2026-06-11
- **Every built-in song gets the layered player + piano-roll view, not just 500 Miles** — the Songs editor's Staff↔Piano (Synthesia-style falling-note) toggle and the multi-part MIDI player only appeared once a song had two or more sheet-music parts, and only "500 Miles" shipped a harmony stack — so the four built-in rounds (Hey Ho Nobody Home, Ah Poor Bird, Rose Rose Rose Red, Zum Gali Gali) showed a bare staff with no piano view. Two changes fix it: (1) the sheet-music card now routes *every* song with notation through the layered player, so a single-part song still gets the piano view (its redundant per-part "Layers" checkbox row and staff-picker pills are hidden when there's only one part); and (2) each built-in round now ships a **canonic voice stack** — the round sung against itself, with each voice entering a fixed number of bars late. The voices are *derived* from the melody (whole-bar rests prepended), so they can't drift from the tune, and a migration backfills them onto installs that seeded the rounds before they carried a voice stack (existing user/AI-derived parts are never clobbered). Also fixes song-card titles getting truncated to "Hey H…" / "Ah P…" — the title now claims its row and the artist moved to the metadata line. (`client/src/pages/SongEditor.jsx`, `client/src/pages/Songs.jsx`, `server/services/songs.js`, `scripts/migrations/086-seed-round-harmony-parts.js`)
+- **The standalone CoS agent runner boots again** — extracting the command allowlist into its own module (`server/cos-runner/allowedCommands.js`) also dropped the adjacent `ROOT_DIR`/`AGENTS_DIR`/`RUNS_DIR`/`PORT`/`HOST` constant definitions, which the runner still references throughout — including `server.listen(PORT, HOST, …)`. Starting the `portos-cos` PM2 process threw a `ReferenceError` before it could listen, so all CoS agent spawning and devtools runs were unavailable. The five constants are restored (a verbatim re-add of the working definitions), with a comment marking why they must stay alongside the now-extracted allowlist. (`server/cos-runner/index.js`)
+
+- **Loop iterations persist their results again** — the same `fileUtils` import refactor that fixed the backup-manifest crash (below) left one more bare `writeFile` behind: `loops.js` `onComplete` wrote each iteration's output file with `writeFile`, which is no longer imported. Because the throw is a synchronous `ReferenceError` (before `.catch()` can attach), it skipped past the `updatePersistedLoop` call right after it — so every completed loop iteration failed to persist its output file, `lastRun`, `iterationCount`, and `lastExitCode`. The write now goes through the already-imported `atomicWrite`, and a success-path regression test pins that the iteration completes without the swallowed-throw log and reaches the output write. (`server/services/loops.js`)
+
- **Backups no longer fail at the manifest step** — every `POST /api/backup/run` completed the rsync mirror and the `pg_dump`, then crashed with `writeFile is not defined` while writing the snapshot's `manifest.json` (the write used a bare `writeFile` that was never imported). The manifest now writes through the already-imported `atomicWrite` helper, and `generateManifest` gained end-to-end test coverage so a missing import can't silently reappear. (`server/services/backup.js`)
- **Uploaded init/reference images stop duplicating into the gallery on every render** — an uploaded init image (i2i / edit renders) was staged into `data/images`, the very directory the gallery enumerates, so each render dropped a fresh `init-<uuid>.png` copy there and it surfaced as a duplicate "(no prompt)" card alongside the actual output. Init uploads now stage into `data/image-refs` (the sibling dir multi-reference uploads already use — served statically but excluded from the gallery listing), and the Codex i2i path re-anchors through `resolveImageInputPath` so it still finds them. A migration relocates the orphaned staged-upload files prior renders already left in the gallery (moved, not deleted, so they stay reachable as inputs). (`server/services/imageGen/prepareParams.js`, `server/services/imageGen/codex.js`, `scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.js`)
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 167dbac448..fde4d78268 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -22,6 +22,17 @@ import { loadState, saveState, withState } from './runnerState.js';
import { getProcessStats, checkProcessRunning } from './processStats.js';
import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';
+// Path + listen constants. These lived adjacent to the command allowlist before
+// it was extracted to ./allowedCommands.js; they must stay here — they're
+// referenced throughout (RUNS_DIR/AGENTS_DIR/ROOT_DIR for spawn cwd + dirs, and
+// server.listen(PORT, HOST)) and dropping them crashes the runner on boot.
+const ROOT_DIR = PATHS.root;
+const AGENTS_DIR = PATHS.cosAgents;
+const RUNS_DIR = PATHS.runs;
+
+const PORT = process.env.PORT || 5558;
+const HOST = process.env.HOST || '127.0.0.1';
+
// Active agent processes (in memory)
const activeAgents = new Map();
diff --git a/server/services/loops.js b/server/services/loops.js
index c3c9da2840..ca48ee36f0 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -137,7 +137,10 @@ async function executeIteration(loop) {
loopEvents.emit('iteration:complete', { id, ...iterResult });
const outputPath = join(LOOPS_OUTPUT_DIR, `${id}-${iterationNum}.txt`);
- await writeFile(outputPath, result).catch(() => {});
+ // atomicWrite (not a bare writeFile, which is no longer imported) — a bare
+ // writeFile here throws ReferenceError synchronously, before .catch() can
+ // attach, skipping updatePersistedLoop so lastRun/iterationCount never persist.
+ await atomicWrite(outputPath, result).catch(() => {});
await updatePersistedLoop(id, {
lastRun: Date.now(),
diff --git a/server/services/loops.test.js b/server/services/loops.test.js
index 880be47876..c0a6e135b2 100644
--- a/server/services/loops.test.js
+++ b/server/services/loops.test.js
@@ -341,6 +341,47 @@ describe('loops.js', () => {
});
});
+ // ===========================================================================
+ // successful-completion persistence (regression: onComplete called a bare
+ // `writeFile` that was no longer imported — a ReferenceError thrown inside
+ // the success branch was swallowed by the wrapper but skipped the
+ // updatePersistedLoop call after it, so lastRun/iterationCount never landed)
+ // ===========================================================================
+ describe('successful iteration persistence', () => {
+ it('completes the success branch without throwing and writes the iteration output', async () => {
+ const loop = await createLoop({
+ prompt: 'success test',
+ interval: '30s',
+ runImmediately: false,
+ });
+ const savedBefore = atomicWrite.mock.calls[0][1];
+ readFile.mockResolvedValue(JSON.stringify(savedBefore));
+
+ const completes = [];
+ loopEvents.on('iteration:complete', (data) => completes.push(data));
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ atomicWrite.mockClear();
+
+ await triggerLoop(loop.id);
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+
+ // The success branch must NOT log its swallowed-throw message — that only
+ // fires if onComplete threw (the bare-writeFile ReferenceError regression).
+ expect(consoleSpy).not.toHaveBeenCalledWith(
+ expect.stringContaining('onComplete (success branch) threw')
+ );
+ expect(completes.length).toBeGreaterThan(0);
+ // onComplete reached its output write (line that previously crashed).
+ const wroteOutput = atomicWrite.mock.calls.some(
+ ([p]) => typeof p === 'string' && p.includes(`${loop.id}-`) && p.endsWith('.txt')
+ );
+ expect(wroteOutput).toBe(true);
+
+ loopEvents.removeAllListeners('iteration:complete');
+ consoleSpy.mockRestore();
+ });
+ });
+
// ===========================================================================
// provider-fallback branch (#1155 regression)
// ===========================================================================