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

refactor: convert 3 long positional parameter lists to options objects (#2841)

[._.]/ Adam Eivy252e9588d2dd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ec0bf13319..0536f54e1f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -75,3 +75,4 @@
- **[issue-2846] Add a client `sleep(ms)` helper and rebuild `useLocalStorageBool` on `safeStorage`** — `client/src/utils/sleep.js` mirrors the server helper and replaces the three duplicated inline delays (`lazyWithReload`'s retry backoff, `staleChunkReload`'s purge race timeout, `voiceClient`'s decoder-tick wait). `useLocalStorageBool`/`useLocalStoragePersisted` now delegate their four hand-rolled `try/catch` storage helpers to `client/src/lib/safeStorage.js`, which gains a `safeWriteJsonStorage` that guards `JSON.stringify` alongside `setItem`. The JSON read keeps a private sentinel so a stored `null` still runs the caller's `parse` migration instead of collapsing into "missing".
- **[issue-2899] Fold the Creative Director / Music Video / Sprites `selectBackend()` dispatchers into `pgFileFacade`** — Creative Director, Music Video, and Sprites each memoized their own copy of the same file-vs-Postgres selector (already drifted: differing error text, differing test-mode predicate). A new `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` in `server/lib/pgFileFacade.js` wraps the existing `createPgFileFacade`/`resolvePgBackend` backbone for stores whose backends are whole modules rather than built objects, so the escape-hatch posture, the health-check → `ensureSchema` → one-time-migration bring-up, and the selection memoization live in one place. Public store surfaces are unchanged (`getProjectsBackendName()` still reports `'file'`/`'postgres'`), each store keeps its own requirement message, and Sprites keeps its stronger `isTestRunner()` test-mode signal via the new `isTestMode` hook — no gating semantics were weakened. The selector also exposes a `reset()` test seam matching the `_reset<X>Backend()` exports on the artists/tracks/albums/authors stores, which still hand-roll the same dispatcher and are tracked separately.
- **[issue-2842] Barrel-split `checkInfra`, `layeredIntelligence`, and `seriesAutopilot` by sub-domain** — the three remaining ~2.6k-line multi-domain server files each become a thin re-exporting barrel over a new same-named directory, mirroring the `arcPlanner.js` split (#1152). `server/lib/editorial/checkInfra.js` → `checkInfra/{externals,taxonomy,revealForeshadowing,craftStages,voiceCanon,structureStages,povAndNames,canonScaffolding,llmRunner,readability,rosterCast,sceneAnalysis,proseDensity,comic}.js`; `server/services/layeredIntelligence.js` → `layeredIntelligence/{constants,config,dedup,proposal,outcomes,awareness,gates,prompt,runCli,sources,semanticDedup,forgeFiler,jiraFiler,planFiler}.js`; `server/services/pipeline/seriesAutopilot.js` → `seriesAutopilot/{state,config,convergence,stepResolver,session,childRuns,editorialSteps,visualSteps,revisionSteps,dispatch,dryRun,orchestrator}.js`. No caller changes — every existing deep import still resolves through the barrel, and `seriesAutopilot`'s `__testing` bundle is reassembled from the split modules. Three new `*Barrel.test.js` suites pin the contract (every module export reachable through the barrel as the same object, no cross-module symbol collisions). The largest resulting module is 439 lines, down from 2,635.
+- **[issue-2841] Convert long positional parameter lists to options objects** — `appendIntervalOccurrences` (8 args) and its sibling `appendCronOccurrences` in `server/services/workflow.js`, `scaffoldVite` (7 args) and the equally-long `scaffoldPortOS` in `server/routes/`, and `createAgentRun` (6 args) in `server/services/agentRunTracking.js` now take a single destructured options object, matching the codebase's dominant convention and removing the "which of these five interchangeable numbers goes where" hazard at each call site. All call sites updated; `scaffold.test.js` gains two regression tests pinning the named-options dispatch shape. Behavior-preserving.
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
index 1ce85b50d2..d5342daec0 100644
--- a/server/routes/scaffold.js
+++ b/server/routes/scaffold.js
@@ -281,7 +281,7 @@ async function scaffoldApp(req, res) {
// Generate project files based on template
if (template === 'vite-react' || template === 'vite-express') {
- await scaffoldVite(repoPath, dirName, parentDir, template, uiPort, apiPort, addStep);
+ await scaffoldVite({ repoPath, dirName, parentDir, template, uiPort, apiPort, addStep });
} else if (template === 'express-api') {
await scaffoldExpress(repoPath, dirName, apiPort, addStep);
} else if (template === 'ios-native') {
@@ -289,7 +289,7 @@ async function scaffoldApp(req, res) {
} else if (template === 'xcode-multiplatform') {
await scaffoldXcode(repoPath, name, dirName, addStep);
} else if (template === 'portos-stack') {
- await scaffoldPortOS(repoPath, name, dirName, uiPort, apiPort, addStep);
+ await scaffoldPortOS({ repoPath, name, dirName, uiPort, apiPort, addStep });
}
// Create .env file
diff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.js
index 89fbd8bfe9..4dcbe28d7b 100644
--- a/server/routes/scaffold.test.js
+++ b/server/routes/scaffold.test.js
@@ -54,6 +54,8 @@ import { ensureDir } from '../lib/fileUtils.js';
import { writeFile } from 'fs/promises';
import { spawn, exec } from 'child_process';
import { createApp } from '../services/apps.js';
+import { scaffoldVite } from './scaffoldVite.js';
+import { scaffoldPortOS } from './scaffoldPortOS.js';
function makeApp() {
const app = express();
@@ -147,4 +149,40 @@ describe('POST /api/scaffold — request validation before filesystem mutation (
expect(ensureDir).toHaveBeenCalledWith('/tmp/workspace/my-app');
expect(createApp).toHaveBeenCalledTimes(1);
});
+
+ // The scaffolders take a single options object (#2841) — a positional call
+ // would silently pass `dirName` as `repoPath` and scaffold into the wrong tree.
+ it('dispatches to scaffoldVite with a named-options object', async () => {
+ const res = await request(app)
+ .post('/api/scaffold')
+ .send({ ...validBody, template: 'vite-express', uiPort: 3100, apiPort: 3101 });
+
+ expect(res.status).toBe(200);
+ expect(scaffoldVite).toHaveBeenCalledTimes(1);
+ expect(scaffoldVite).toHaveBeenCalledWith(expect.objectContaining({
+ repoPath: '/tmp/workspace/my-app',
+ dirName: 'my-app',
+ parentDir: '/tmp/workspace',
+ template: 'vite-express',
+ uiPort: 3100,
+ apiPort: 3101,
+ addStep: expect.any(Function)
+ }));
+ });
+
+ it('dispatches to scaffoldPortOS with a named-options object', async () => {
+ const res = await request(app)
+ .post('/api/scaffold')
+ .send({ ...validBody, template: 'portos-stack', uiPort: 3100, apiPort: 3101 });
+
+ expect(res.status).toBe(200);
+ expect(scaffoldPortOS).toHaveBeenCalledWith(expect.objectContaining({
+ repoPath: '/tmp/workspace/my-app',
+ name: 'My App',
+ dirName: 'my-app',
+ uiPort: 3100,
+ apiPort: 3101,
+ addStep: expect.any(Function)
+ }));
+ });
});
diff --git a/server/routes/scaffoldPortOS.js b/server/routes/scaffoldPortOS.js
index 975047c4a8..e9b6f8d87c 100644
--- a/server/routes/scaffoldPortOS.js
+++ b/server/routes/scaffoldPortOS.js
@@ -11,7 +11,7 @@ const CORS_SNIPPET = `app.use((req, res, next) => {
next();
});`;
-export async function scaffoldPortOS(repoPath, name, dirName, uiPort, apiPort, addStep) {
+export async function scaffoldPortOS({ repoPath, name, dirName, uiPort, apiPort, addStep }) {
const clientDir = join(repoPath, 'client');
const serverDir = join(repoPath, 'server');
const workflowsDir = join(repoPath, '.github/workflows');
diff --git a/server/routes/scaffoldVite.js b/server/routes/scaffoldVite.js
index a63c1658f2..f3f5d17f1d 100644
--- a/server/routes/scaffoldVite.js
+++ b/server/routes/scaffoldVite.js
@@ -14,7 +14,7 @@ const CORS_SNIPPET = `app.use((req, res, next) => {
next();
});`;
-export async function scaffoldVite(repoPath, dirName, parentDir, template, uiPort, apiPort, addStep) {
+export async function scaffoldVite({ repoPath, dirName, parentDir, template, uiPort, apiPort, addStep }) {
// Create using npm create vite
// Security: Use spawn with array args instead of execAsync to prevent shell injection
const { stderr } = await new Promise((resolve) => {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 1ac49a9ac4..8267008b31 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -393,7 +393,14 @@ async function runAgentSpawn(task) {
}
// Create run entry for usage tracking
- const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);
+ const { runId } = await createAgentRun({
+ agentId,
+ task,
+ model: selectedModel,
+ provider,
+ workspacePath,
+ appName: resolvedAppName
+ });
const executionMode = isTui ? 'tui' : useRunner ? 'runner' : 'direct';
// Register the agent with model info.
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 1ee145bf96..c94a2a0acf 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -17,7 +17,7 @@ const RUNS_DIR = PATHS.runs;
/**
* Create a run entry for usage tracking.
*/
-export async function createAgentRun(agentId, task, model, provider, workspacePath, appName) {
+export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName }) {
const runId = uuidv4();
const runDir = join(RUNS_DIR, runId);
diff --git a/server/services/workflow.js b/server/services/workflow.js
index 834893dcaa..1518ff7d54 100644
--- a/server/services/workflow.js
+++ b/server/services/workflow.js
@@ -308,7 +308,16 @@ export function projectWorkflowTimeline(nodes, { start, end, timezone = 'UTC' })
// When a due-now marker was emitted, start the projection strictly after
// startMs so a cron slot landing exactly on the current minute doesn't
// produce a duplicate occurrence id at the same instant.
- appendCronOccurrences(node, schedule.cronExpression, startMs, endMs, timezone, occurrences, 'launch', { skipStart: dueNow });
+ appendCronOccurrences({
+ node,
+ expression: schedule.cronExpression,
+ startMs,
+ endMs,
+ timezone,
+ target: occurrences,
+ kind: 'launch',
+ skipStart: dueNow
+ });
continue;
}
@@ -332,7 +341,7 @@ export function projectWorkflowTimeline(nodes, { start, end, timezone = 'UTC' })
};
}
-function appendCronOccurrences(node, expression, startMs, endMs, timezone, target, kind, { skipStart = false } = {}) {
+function appendCronOccurrences({ node, expression, startMs, endMs, timezone, target, kind, skipStart = false }) {
// parseCronToNextRun searches strictly after its cursor, so startMs - 60s
// makes a slot exactly at startMs eligible (unless the caller already
// emitted a due-now marker there — skipStart).
@@ -375,14 +384,31 @@ function projectPerpetual(node, startMs, endMs, timezone, occurrences, windows)
const recheckCron = node.schedule?.recheckCron;
if (recheckCron) {
- appendCronOccurrences(node, recheckCron, startMs, endMs, timezone, occurrences, 'recheck');
+ appendCronOccurrences({
+ node,
+ expression: recheckCron,
+ startMs,
+ endMs,
+ timezone,
+ target: occurrences,
+ kind: 'recheck'
+ });
return;
}
const nextRecheckMs = node.nextRunAt ? new Date(node.nextRunAt).getTime() : NaN;
const cadence = node.schedule?.recheckIntervalMs || DAY;
if (Number.isFinite(nextRecheckMs)) {
- appendIntervalOccurrences(node, nextRecheckMs, cadence, startMs, endMs, timezone, occurrences, 'recheck');
+ appendIntervalOccurrences({
+ node,
+ firstMs: nextRecheckMs,
+ cadence,
+ startMs,
+ endMs,
+ timezone,
+ target: occurrences,
+ kind: 'recheck'
+ });
}
}
@@ -412,7 +438,16 @@ function projectIntervalTask(node, startMs, endMs, timezone, occurrences) {
nextMs = Number.isFinite(lastRunMs) ? lastRunMs + cadence : startMs;
}
}
- appendIntervalOccurrences(node, nextMs, cadence, startMs, endMs, timezone, occurrences, 'launch');
+ appendIntervalOccurrences({
+ node,
+ firstMs: nextMs,
+ cadence,
+ startMs,
+ endMs,
+ timezone,
+ target: occurrences,
+ kind: 'launch'
+ });
}
function projectIntervalJob(node, startMs, endMs, timezone, occurrences) {
@@ -480,7 +515,7 @@ function isAllowedWeekday(node, atMs, timezone) {
return day >= 1 && day <= 5;
}
-function appendIntervalOccurrences(node, firstMs, cadence, startMs, endMs, timezone, target, kind) {
+function appendIntervalOccurrences({ node, firstMs, cadence, startMs, endMs, timezone, target, kind }) {
if (!Number.isFinite(firstMs) || !Number.isFinite(cadence) || cadence <= 0) return;
let nextMs = firstMs;
if (nextMs < startMs) nextMs += Math.ceil((startMs - nextMs) / cadence) * cadence;