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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: drop 21 exported-but-unwired Zod schemas and guard against new ones (#5730)
Adam Eivy6fa099bd9dfc
diff --git a/server/lib/agentValidation.js b/server/lib/agentValidation.jsindex 89cdc6bc4c..91875ffdf5 100644--- a/server/lib/agentValidation.js+++ b/server/lib/agentValidation.js@@ -97,8 +97,6 @@ export const platformAccountSchema = z.object({platformData: z.record(z.unknown()).optional().default({})});-export const platformAccountUpdateSchema = partialWithoutDefaults(platformAccountSchema);-// Account registration (when creating new Moltbook account)export const accountRegistrationSchema = z.object({agentId: z.string().min(1),@@ -317,7 +315,9 @@ export const moltworldQueueAddSchema = z.object({// FEATURE AGENT SCHEMAS// =============================================================================-export const featureAgentStatusSchema = z.enum(['draft', 'active', 'paused', 'completed', 'error']);+// A feature agent's `status` is server-owned — stamped by the start/pause/+// complete routes, never accepted from a request body — so it has no request+// schema (#5730).export const featureAgentScheduleModeSchema = z.enum(['continuous', 'interval']);export const featureAgentAutonomySchema = z.enum(['standby', 'assistant', 'manager', 'yolo']);export const featureAgentPrioritySchema = z.enum(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']);diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 68206d216c..e45fa01cbb 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -140,17 +140,6 @@ export const adminRecordSchema = z.object({updatedAt: z.string().datetime()});-// Memory Record schema (journal entries, daily notes, personal memories)-export const memoryRecordSchema = z.object({- id: z.string().guid(),- title: z.string().min(1).max(200),- content: z.string().max(10000).optional().default(''),- mood: z.string().max(50).optional(),- tags: z.array(z.string().max(50)).optional().default([]),- createdAt: z.string().datetime(),- updatedAt: z.string().datetime()-});-// Meta/Settings schemaexport const brainSettingsSchema = z.object({version: z.number().int().positive().default(1),@@ -164,29 +153,6 @@ export const brainSettingsSchema = z.object({lastWeeklyReview: z.string().datetime().optional()});-// Digest Record schema-export const digestRecordSchema = z.object({- id: z.string().guid(),- generatedAt: z.string().datetime(),- digestText: z.string().max(2000),- topActions: z.array(z.string().max(200)).max(3),- stuckThing: z.string().max(200),- smallWin: z.string().max(200),- ai: aiConfigSchema.optional()-});--// Weekly Review Record schema-export const reviewRecordSchema = z.object({- id: z.string().guid(),- generatedAt: z.string().datetime(),- reviewText: z.string().max(3000),- whatHappened: z.array(z.string().max(200)).max(5),- biggestOpenLoops: z.array(z.string().max(200)).max(3),- suggestedActionsNextWeek: z.array(z.string().max(200)).max(3),- recurringTheme: z.string().max(500),- ai: aiConfigSchema.optional()-});-// --- Input schemas for API endpoints ---// Opt-in post-clone agent actions for a captured repository URL. Keys derive@@ -557,17 +523,6 @@ export const bucketColorEnum = z.enum(['accent', 'success', 'warning', 'error', 'purple', 'pink', 'cyan', 'slate']);-// Bucket Record schema-export const bucketRecordSchema = z.object({- id: z.string().guid(),- name: z.string().min(1).max(100),- color: bucketColorEnum.default('accent'),- icon: z.string().max(50).optional().default(''),- order: z.number().int().default(0),- createdAt: z.string().datetime(),- updatedAt: z.string().datetime()-});-// Create Bucket input schemaexport const bucketInputSchema = z.object({name: z.string().min(1).max(100),diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex 432ca92a9d..db6c9a4564 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -21,15 +21,6 @@ export const documentCategoryEnum = z.enum(['creative' // Aesthetic preferences, creative interests]);-// Test result enum-export const testResultEnum = z.enum(['passed', 'partial', 'failed', 'pending']);--// Values-alignment result enum (M34 P6)-export const valuesTestResultEnum = z.enum(['aligned', 'partial', 'misaligned', 'pending']);--// Adversarial-boundary result enum (M34 P6) — did the twin hold the line?-export const adversarialTestResultEnum = z.enum(['held', 'partial', 'breached', 'pending']);-// Export format enum// 'claude_md' is the pre-#4852 alias of 'agents_md' — kept so a persisted// preference on an existing install still validates.@@ -145,18 +136,6 @@ export const multiTurnTestHistoryEntrySchema = z.object({timestamp: z.string().datetime()});-// Individual test result schema-export const testResultSchema = z.object({- testId: z.number().int().min(1),- testName: z.string(),- prompt: z.string(),- expectedBehavior: z.string(),- failureSignals: z.string(),- response: z.string().optional(),- result: testResultEnum,- reasoning: z.string().optional()-});-// Enrichment progress schemaexport const enrichmentProgressSchema = z.object({completedCategories: z.array(enrichmentCategoryEnum).default([]),@@ -549,44 +528,6 @@ export const importSourceEnum = z.enum(['ical']);-// Goodreads book entry (parsed from CSV)-export const goodreadsBookSchema = z.object({- title: z.string(),- author: z.string().optional(),- rating: z.number().min(0).max(5).optional(),- dateRead: z.string().optional(),- shelves: z.array(z.string()).optional(),- review: z.string().optional()-});--// Spotify track/artist entry (parsed from JSON export)-export const spotifyEntrySchema = z.object({- trackName: z.string().optional(),- artistName: z.string(),- albumName: z.string().optional(),- playCount: z.number().int().optional(),- msPlayed: z.number().int().optional()-});--// Letterboxd film entry-export const letterboxdFilmSchema = z.object({- title: z.string(),- year: z.number().int().optional(),- rating: z.number().min(0).max(5).optional(),- watchedDate: z.string().optional(),- review: z.string().optional(),- tags: z.array(z.string()).optional()-});--// Calendar event for pattern analysis-export const calendarEventSchema = z.object({- summary: z.string(),- start: z.string(),- end: z.string().optional(),- recurring: z.boolean().optional(),- categories: z.array(z.string()).optional()-});-// Import data input (raw data to parse)export const importDataInputSchema = z.object({source: importSourceEnum,@@ -604,28 +545,6 @@ export const analyzeAssessmentInputSchema = z.object({model: z.string().min(1)});-// Import analysis result-export const importAnalysisResultSchema = z.object({- source: importSourceEnum,- itemCount: z.number().int(),- insights: z.object({- patterns: z.array(z.string()).optional(),- preferences: z.array(z.string()).optional(),- personalityInferences: z.object({- bigFive: bigFiveSchema.partial().optional(),- values: z.array(z.string()).optional(),- interests: z.array(z.string()).optional()- }).optional()- }),- suggestedDocuments: z.array(z.object({- filename: z.string(),- title: z.string(),- category: documentCategoryEnum,- content: z.string()- })).optional(),- rawSummary: z.string().optional()-});-// --- Taste Questionnaire Schemas ---export const tasteSectionEnum = z.enum([diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex f2f4042762..1a3899a8f3 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -591,17 +591,10 @@ export const writersRoomObjectUpdateSchema = z.object({notes: wrObjectTextField.optional(),}).strict();-// Generic bible-entry schemas — re-exports of the writers-room schemas under-// kind-neutral names so the Pipeline routes share the same validation-// surface and funnel through the canonical sanitizer in storyBible.js.-// `placeBibleCreateSchema` is the un-refined ZodObject (not the refined-// `writersRoomPlaceCreateSchema`) so Pipeline can `.extend()` it.-export const characterBibleCreateSchema = writersRoomCharacterCreateSchema;-export const characterBibleUpdateSchema = writersRoomCharacterUpdateSchema;-export const placeBibleCreateSchema = writersRoomPlaceCreateObject;-export const placeBibleUpdateSchema = writersRoomPlaceUpdateSchema;-export const objectBibleCreateSchema = writersRoomObjectCreateSchema;-export const objectBibleUpdateSchema = writersRoomObjectUpdateSchema;+// Every story-bible route validates through the `writersRoom*` schemas above;+// there are no kind-neutral `*Bible*Schema` aliases beside them (#5730). If a+// Pipeline route needs one, add it next to that caller —+// `writersRoomPlaceCreateObject` is the un-refined ZodObject to `.extend()`.// =============================================================================// PROMPT STAGE CONFIG (server/routes/prompts.js PUT /:stage body)diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 35ec11d240..ed8c017620 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -126,37 +126,6 @@ export const datadogSearchErrorsRequestSchema = z.object({}).optional()),});-// Reference-repo entry. Each app can list upstream repos it watches for-// clean-room reimplementation;-// the `reference-watch` scheduled task fetches each one, finds commits since-// `lastReviewedSha`, and appends slug-tagged `[ref-watch-…]` checklist items-// to the app's PLAN.md for `/claim` / `plan-task` to pick up. `notes` is the-// free-text "what we use from this repo" field — fed into the review prompt-// so the agent knows which features in our app are load-bearing for the watch.-export const referenceRepoSchema = z.object({- id: z.string().min(1).max(64),- name: z.string().min(1).max(120),- // Either a clonable URL (https://github.com/owner/repo or scp-style- // user@host:owner/repo.git) or a local filesystem path. The service- // detects remote URLs by matching `scheme://` or scp-style- // `user@host:path` (see isLocalPath in services/referenceRepos.js);- // anything else is treated as a local path.- repoUrl: z.string().min(1).max(500),- branch: z.string().max(120).optional().default('main'),- // 40-char hex SHA (case-insensitive), or null (no review yet). Validating- // hex here rather than just length means a bogus PATCH like 'g'.repeat(40)- // fails fast at the API instead of producing confusing git failures later.- lastReviewedSha: z.string().regex(/^[0-9a-f]{40}$/i, 'must be a 40-char hex SHA').nullable().optional(),- lastCheckedAt: z.string().datetime().nullable().optional(),- notes: z.string().max(4000).optional().default(''),- // Last action's outcome — used by the UI to highlight refs needing- // attention. 'needs-clone' means the managed clone hasn't been- // initialized yet (first run will populate it).- status: z.enum(['ok', 'checking', 'error', 'needs-clone']).optional().default('needs-clone'),- lastError: z.string().max(2000).nullable().optional(),- createdAt: z.string().datetime().optional()-});-// App schema for registration/update// Workspace Context (#902) — the only input is an app id (the apps-registry// key, or the fixed 'portos-default' baseline). Mirrors the apps-registry id@@ -333,6 +302,20 @@ export const appSchema = z.object({// fails validation rather than slipping through and producing confusing// git failures downstream — matches the project convention used elsewhere// in this file.+// Reference-repo entry. Each app can list upstream repos it watches for+// clean-room reimplementation; the `reference-watch` scheduled task fetches+// each one, finds commits since `lastReviewedSha`, and appends slug-tagged+// `[ref-watch-…]` checklist items to the app's PLAN.md for `/claim` /+// `plan-task` to pick up. `notes` is the free-text "what we use from this+// repo" field — fed into the review prompt so the agent knows which features+// in our app are load-bearing for the watch. `repoUrl` is either a clonable+// URL (https://github.com/owner/repo or scp-style user@host:owner/repo.git)+// or a local filesystem path; the service detects remote URLs by matching+// `scheme://` or scp-style `user@host:path` (see isLocalPath in+// services/referenceRepos.js) and treats anything else as a local path.+// The persisted record's server-owned fields (id, status, lastError,+// lastCheckedAt, lastKnownGoodSnapshot, createdAt) are stamped by+// services/referenceRepos.js and never accepted from a request body.export const referenceRepoCreateSchema = z.object({name: z.string().trim().min(1).max(120),repoUrl: z.string().trim().min(1).max(500),diff --git a/server/lib/validationSplit.test.js b/server/lib/validationSplit.test.jsindex c7404fbc54..242abc8ee6 100644--- a/server/lib/validationSplit.test.js+++ b/server/lib/validationSplit.test.js@@ -1,4 +1,8 @@import { describe, it, expect } from 'vitest';+import { execSync } from 'node:child_process';+import { readdirSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';import * as validation from './validation.js';import * as peerSyncValidation from './peerSyncValidation.js';import * as creativeDirectorValidation from './creativeDirectorValidation.js';@@ -108,3 +112,87 @@ describe('validation.js transitional re-exports (issues #1151, #1831)', () => {}});});++// Issue #5730: `server/AGENTS.md` requires that *all* inputs be validated —+// "an exported-but-unwired sub-schema creates false confidence". A Zod schema+// exported from a validation module but referenced nowhere else in the repo+// reads at review time as "this payload is validated" when nothing validates+// it. This guard is the enforcement: a schema either runs on some input, or it+// does not exist.+describe('exported validation schemas are wired (#5730)', () => {+ // Compat aliases and other deliberately-unwired exports. Adding a name here+ // is a reviewed decision, not a way to silence the guard — say why.+ const INTENTIONALLY_UNWIRED = new Set([+ // Alias of digitalTwinMetaSchema kept for backwards compatibility with+ // installs/forks that import the pre-rename name. Compat surface is not+ // removed on unused-ness grounds.+ 'digitalTwinValidation.js:soulMetaSchema',+ ]);++ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+ const libDir = path.join(repoRoot, 'server/lib');+ const BARREL = 'server/lib/index.js';+ const IDENTIFIER = /[A-Za-z_$][A-Za-z0-9_$]*/g;+ const EXPORTED_SCHEMA = /export\s+const\s+([A-Za-z0-9_$]+(?:Schema|Enum))\b/g;++ const moduleFiles = readdirSync(libDir)+ .filter((f) => (f.endsWith('Validation.js') || f === 'validation.js') && !f.endsWith('.test.js'))+ .sort();++ it('has validation modules to scan', () => {+ expect(moduleFiles.length).toBeGreaterThan(20);+ });++ it('every exported *Schema/*Enum is referenced outside its own declaration', () => {+ const tracked = execSync('git ls-files -z "*.js" "*.jsx" "*.mjs"', {+ cwd: repoRoot, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,+ }).split('\0').filter(Boolean);++ // One pass over the tree builds the identifier index. Per-module counts are+ // kept (not just presence) so a schema's own `export const` line can be+ // discounted; every other file only needs presence. The barrel is skipped+ // entirely — it re-exports wholesale and would mark everything "used".+ const moduleCounts = new Map(); // 'server/lib/x.js' -> Map(identifier -> count)+ const externalIdentifiers = new Set();+ for (const rel of tracked) {+ if (rel === BARREL) continue;+ const isModule = rel.startsWith('server/lib/')+ && moduleFiles.includes(rel.slice('server/lib/'.length));+ const tokens = readFileSync(path.join(repoRoot, rel), 'utf8').match(IDENTIFIER) || [];+ if (isModule) {+ const counts = new Map();+ for (const token of tokens) counts.set(token, (counts.get(token) || 0) + 1);+ moduleCounts.set(rel, counts);+ } else {+ for (const token of tokens) externalIdentifiers.add(token);+ }+ }++ const unwired = [];+ for (const file of moduleFiles) {+ const rel = `server/lib/${file}`;+ const source = readFileSync(path.join(repoRoot, rel), 'utf8');+ for (const match of source.matchAll(EXPORTED_SCHEMA)) {+ const name = match[1];+ if (INTENTIONALLY_UNWIRED.has(`${file}:${name}`)) continue;+ if (externalIdentifiers.has(name)) continue;+ // > 1 means the module composes it into a sibling schema beyond the+ // single occurrence on its own `export const` line.+ if ((moduleCounts.get(rel)?.get(name) || 0) > 1) continue;+ if ([...moduleCounts].some(([other, counts]) => other !== rel && counts.has(name))) continue;+ unwired.push(`${file}:${name}`);+ }+ }++ expect(unwired, 'exported but never referenced — wire these into the route/schema that should use them, delete them, or add a justified INTENTIONALLY_UNWIRED entry').toEqual([]);+ });++ it('every INTENTIONALLY_UNWIRED entry still names a real export', () => {+ const missing = [...INTENTIONALLY_UNWIRED].filter((entry) => {+ const [file, name] = entry.split(':');+ if (!moduleFiles.includes(file)) return true;+ return !new RegExp(`export\\s+const\\s+${name}\\b`).test(readFileSync(path.join(libDir, file), 'utf8'));+ });+ expect(missing, 'stale allowlist entries — the export was renamed or removed').toEqual([]);+ });+});