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
move FableLoom and POST vocabularies below validation, and guard the layering
[._.]/ Adam Eivy2b0577cc9097
diff --git a/server/lib/README.md b/server/lib/README.mdindex a0ffa716ec..20060bfaae 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -28,6 +28,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. || `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). || `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets), kept below both validation and generation services so schemas never import orchestration modules. |+| `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |+| `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. |+| `postDrillTypes.js` | MeatSpace POST drill vocabularies (`CACHEABLE_TYPES`, `COGNITIVE_DRILL_TYPES`), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator). || `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. || `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |diff --git a/server/lib/fableLoomFormats.js b/server/lib/fableLoomFormats.jsnew file mode 100644index 0000000000..e345f69c4c--- /dev/null+++ b/server/lib/fableLoomFormats.js@@ -0,0 +1,48 @@+/**+ * FableLoom scene formats — how a loom's scene text is WRITTEN, and therefore+ * how every generative stage is told to write it.+ *+ * A loom is either narrated prose (second-person interactive fiction) or a+ * teleplay (sluglines, action lines, character cues). The choice is one field+ * on the record, and each stage that produces scene text renders the matching+ * contract into its prompt — so the format lives here once rather than as+ * three near-duplicate paragraphs across the templates.+ *+ * A leaf module (no imports): the validation schemas, the sanitizer, and the+ * weave service all read from it without pulling in the service graph.+ */++export const LOOM_FORMATS = Object.freeze(['prose', 'teleplay']);+export const LOOM_FORMAT_DEFAULT = 'prose';++export const isLoomFormat = (value) => LOOM_FORMATS.includes(value);++/** Normalize a stored/incoming format, falling back to the default. */+export const asLoomFormat = (value) => (isLoomFormat(value) ? value : LOOM_FORMAT_DEFAULT);++// What each stage is told about the `prose` field it generates. Written as+// prompt bullets: the templates render them under their own heading.+const SCENE_CONTRACTS = Object.freeze({+ prose: [+ "Each scene's `prose` is 100–250 words of second-person present-tense narration that ends at a decision point (except endings, which resolve).",+ 'Write flowing narrative paragraphs — no sluglines, no character cues, no screenplay formatting.',+ ].join('\n'),+ teleplay: [+ "Each scene's `prose` is a teleplay fragment in standard screenplay format, 120–250 words, ending at a decision point (except endings, which resolve).",+ 'Open with a slugline in caps (`INT. HOLDING CELL - NIGHT`). Action lines are present tense, third person, no camera directions.',+ 'Character cues are ALL CAPS on their own line above the dialogue; parentheticals go on their own line in lowercase. Introduce a character with their name in caps the first time they appear in an action line.',+ 'Use `\\n` line breaks between every slugline, action block, cue, and dialogue block — the text is rendered as written.',+ ].join('\n'),+});++// How the narrator answers a reader mid-scene, in the loom's format.+const NARRATION_CONTRACTS = Object.freeze({+ prose: '1–3 short paragraphs of second-person present-tense prose.',+ teleplay: 'a short teleplay fragment — action lines in present tense, plus a character cue and dialogue when someone speaks. No slugline unless the location changes.',+});++export const sceneFormatContract = (format) => SCENE_CONTRACTS[asLoomFormat(format)];+export const narrationFormatContract = (format) => NARRATION_CONTRACTS[asLoomFormat(format)];++/** Human label for the format, used in prompts and error copy. */+export const loomFormatLabel = (format) => (asLoomFormat(format) === 'teleplay' ? 'teleplay / screenplay' : 'narrated prose');diff --git a/server/lib/fableLoomLimits.js b/server/lib/fableLoomLimits.jsnew file mode 100644index 0000000000..35f47e9876--- /dev/null+++ b/server/lib/fableLoomLimits.js@@ -0,0 +1,27 @@+/**+ * FableLoom record caps — the single source of truth shared by the sanitizer+ * (`records.js`, enforcement) and the route schemas+ * (`server/lib/fableLoomValidation.js`, door check). A leaf module so the lib+ * barrel doesn't transitively load the universe/series service graph.+ */++export const LOOM_LIMITS = Object.freeze({+ NAME_MAX: 200,+ LOGLINE_MAX: 500,+ PREMISE_MAX: 20000,+ STYLE_NOTES_MAX: 4000,+ REF_ID_MAX: 64,+ EPISODES_MAX: 100,+ EPISODE_TITLE_MAX: 300,+ SYNOPSIS_MAX: 4000,+ NODES_MAX: 200,+ NODE_TITLE_MAX: 300,+ PROSE_MAX: 20000,+ IMAGE_PROMPT_MAX: 2000,+ ENDING_LABEL_MAX: 200,+ TRANSITIONS_MAX: 12,+ INTENT_MAX: 120,+ TRIGGER_MAX: 160,+ TRIGGERS_MAX: 8,+ TRANSITION_DESC_MAX: 500,+});diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex 0c680275aa..751ce0e2dc 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -6,8 +6,8 @@*/import { z } from 'zod';-import { LOOM_LIMITS } from '../services/fableLoom/limits.js';-import { LOOM_FORMATS } from '../services/fableLoom/formats.js';+import { LOOM_LIMITS } from './fableLoomLimits.js';+import { LOOM_FORMATS } from './fableLoomFormats.js';import { llmRoutePinSchema } from './llmRoutePin.js';const name = z.string().trim().min(1).max(LOOM_LIMITS.NAME_MAX);diff --git a/server/lib/index.js b/server/lib/index.jsindex 4a060f2609..77e54fd6d4 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -79,6 +79,8 @@ export * from './creativeLatitude.js';// discovery surface reaches EDITORIAL_CHECKS + the lookup helpers.export * as editorial from './editorial/index.js';export * from './fableLoomGraph.js';+export * from './fableLoomLimits.js';+export * from './fableLoomFormats.js';export * from './sceneExtractor.js';export * from './scenePrompt.js';export * from './proseExportSettings.js';@@ -349,6 +351,7 @@ export * from './markdownText.js';export * from './renderSlot.js';export * from './renderTargets.js';export * from './generationModes.js';+export * from './postDrillTypes.js';export * from './telegramClient.js';export * from './tempPathGuard.js';export * from './textUtils.js';diff --git a/server/lib/layering.test.js b/server/lib/layering.test.jsnew file mode 100644index 0000000000..06e6ad3be7--- /dev/null+++ b/server/lib/layering.test.js@@ -0,0 +1,97 @@+/**+ * Layering guard: `server/lib/` sits BELOW `server/services/`.+ *+ * lib is the pure/reusable tier — validation schemas, formatters, vocabularies.+ * services is domain orchestration. A lib module that imports upward inverts+ * that contract, and the cost is real, not theoretical: `lib/postValidation.js`+ * is loaded by every POST route, and it used to reach `services/+ * meatspacePostDrillCache.js` for a four-string array — dragging in the LLM+ * drill generator behind it.+ *+ * Burn-down, like the a11y control-name guard: the allowlist only shrinks.+ * Fixing a module means deleting its row, and the stale-entry test below fails+ * if you name one without deleting it. Tracked in #4901.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const LIB_ROOT = dirname(fileURLToPath(import.meta.url));++// Modules that still import upward into services. Each row is a real layering+// inversion awaiting its slice of #4901 — NOT a permanent exemption. Fix the+// module, delete the row. Never add a row for new code.+const PREEXISTING_LIB_TO_SERVICES_ALLOWLIST = new Set([+ 'aiProvider.js',+ 'assetMounts.js',+ 'createSettingsGatedSyncScheduler.js',+ 'creativeDirectorPrompts.js',+ 'hfDownload.js',+ 'hfToken.js',+ 'promptRunner.js',+ 'spriteValidation.js',+ 'stageRunner.js',+ 'timezone.js',+ 'tuiPromptRunner.js',+]);++// Permanently exempt — NOT burn-down rows. Both reach into services through a+// DYNAMIC import for a documented structural reason, and turning either into a+// static import is the bug, not the fix:+// * peerHttpClient.js — `services/instances.js` imports THIS module, so a+// static import back would close an evaluation-order cycle.+// * settingsTestUtil.js — a test-only helper; suites `vi.resetModules()`+// between builds, so it must resolve the live module per call.+// Listed separately from the allowlist so nobody "burns them down" by making+// them static.+const DYNAMIC_IMPORT_EXEMPT = new Set([+ 'peerHttpClient.js',+ 'settingsTestUtil.js',+]);++// `aiToolkit/` is a vendored, self-contained toolkit (see its AGENTS.md) and is+// scanned by its own rules, not this one.+const SKIP_DIRS = new Set(['aiToolkit', 'node_modules']);++function libSourceFiles(dir = LIB_ROOT, prefix = '') {+ const out = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.isDirectory()) {+ if (SKIP_DIRS.has(entry.name)) continue;+ out.push(...libSourceFiles(join(dir, entry.name), `${prefix}${entry.name}/`));+ } else if (entry.name.endsWith('.js') && !entry.name.endsWith('.test.js')) {+ out.push({ rel: `${prefix}${entry.name}`, abs: join(dir, entry.name) });+ }+ }+ return out;+}++// Matches `from '../services/x.js'` / `from '../../services/x.js'` in both+// static imports and dynamic `import(...)`, ignoring commented-out lines.+const UPWARD_IMPORT = /from\s+['"](?:\.\.\/)+services\/|import\s*\(\s*['"](?:\.\.\/)+services\//;++const offenders = () => libSourceFiles()+ .filter(({ rel }) => !DYNAMIC_IMPORT_EXEMPT.has(rel))+ .filter(({ abs }) => UPWARD_IMPORT.test(readFileSync(abs, 'utf8')))+ .map(({ rel }) => rel);++describe('server/lib layering', () => {+ it('has no lib -> services imports outside the burn-down allowlist', () => {+ const unlisted = offenders().filter((f) => !PREEXISTING_LIB_TO_SERVICES_ALLOWLIST.has(f));+ expect(+ unlisted,+ `server/lib modules importing upward into services — move the dependency below, or promote the module into services (#4901):\n${unlisted.join('\n')}`,+ ).toEqual([]);+ });++ it('keeps no stale entries in PREEXISTING_LIB_TO_SERVICES_ALLOWLIST (#4901)', () => {+ const current = new Set(offenders());+ const stale = [...PREEXISTING_LIB_TO_SERVICES_ALLOWLIST].filter((f) => !current.has(f));+ expect(+ stale,+ `allowlist rows whose module no longer imports services — delete them so the burn-down stays honest:\n${stale.join('\n')}`,+ ).toEqual([]);+ });+});diff --git a/server/lib/postDrillTypes.js b/server/lib/postDrillTypes.jsnew file mode 100644index 0000000000..7241c4eb51--- /dev/null+++ b/server/lib/postDrillTypes.js@@ -0,0 +1,34 @@+/**+ * MeatSpace POST drill-type vocabulary.+ *+ * These two lists sit below both validation and the POST services so a route+ * schema can enumerate a drill type without importing service-layer+ * orchestration (issue #4901). That mattered more than the layering nit:+ * `CACHEABLE_TYPES` used to live in `services/meatspacePostDrillCache.js`,+ * which imports the LLM drill generator — so `lib/postValidation.js`, loaded on+ * every POST route, transitively pulled in the LLM path just to know four+ * strings.+ *+ * A leaf module (no imports). The service modules re-export both lists, so+ * existing deep imports keep working.+ */++// Wordplay drills the cache can pre-generate and hold. A subset of the LLM+// drill types — the ones cheap and deterministic enough to prime ahead of use.+export const CACHEABLE_TYPES = Object.freeze([+ 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist',+]);++// Non-LLM cognitive drills, each backed by a generator in+// `services/meatspacePostCognitive.js`.+export const COGNITIVE_DRILL_TYPES = Object.freeze([+ 'n-back',+ 'digit-span',+ 'stroop',+ 'schulte-table',+ 'mental-rotation',+ 'reaction-time',+ 'task-switching',+ 'go-no-go',+ 'flanker',+]);diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 36a8f005c3..eb1d40a07d 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -1,6 +1,5 @@import { z } from 'zod';-import { CACHEABLE_TYPES } from '../services/meatspacePostDrillCache.js';-import { COGNITIVE_DRILL_TYPES } from '../services/meatspacePostCognitive.js';+import { CACHEABLE_TYPES, COGNITIVE_DRILL_TYPES } from './postDrillTypes.js';import { TOPIC_IDS } from './postTopics.js';import { HHMM_STRICT_RE } from './timezone.js';import { POST_LLM_MAX_SEMANTIC_CANDIDATES, postLlmEvaluationSchema } from './postLlmContracts.js';diff --git a/server/services/fableLoom/formats.js b/server/services/fableLoom/formats.jsindex e345f69c4c..fad5b0e5f0 100644--- a/server/services/fableLoom/formats.js+++ b/server/services/fableLoom/formats.js@@ -1,48 +1,16 @@/**- * FableLoom scene formats — how a loom's scene text is WRITTEN, and therefore- * how every generative stage is told to write it.- *- * A loom is either narrated prose (second-person interactive fiction) or a- * teleplay (sluglines, action lines, character cues). The choice is one field- * on the record, and each stage that produces scene text renders the matching- * contract into its prompt — so the format lives here once rather than as- * three near-duplicate paragraphs across the templates.- *- * A leaf module (no imports): the validation schemas, the sanitizer, and the- * weave service all read from it without pulling in the service graph.+ * Re-export shim. The format vocabulary and its prompt contracts moved to+ * `server/lib/fableLoomFormats.js` so `lib/fableLoomValidation.js` can read them+ * without importing upward into services (issue #4901). They were always a leaf+ * module; only the address changed. Existing deep imports keep working.*/-export const LOOM_FORMATS = Object.freeze(['prose', 'teleplay']);-export const LOOM_FORMAT_DEFAULT = 'prose';--export const isLoomFormat = (value) => LOOM_FORMATS.includes(value);--/** Normalize a stored/incoming format, falling back to the default. */-export const asLoomFormat = (value) => (isLoomFormat(value) ? value : LOOM_FORMAT_DEFAULT);--// What each stage is told about the `prose` field it generates. Written as-// prompt bullets: the templates render them under their own heading.-const SCENE_CONTRACTS = Object.freeze({- prose: [- "Each scene's `prose` is 100–250 words of second-person present-tense narration that ends at a decision point (except endings, which resolve).",- 'Write flowing narrative paragraphs — no sluglines, no character cues, no screenplay formatting.',- ].join('\n'),- teleplay: [- "Each scene's `prose` is a teleplay fragment in standard screenplay format, 120–250 words, ending at a decision point (except endings, which resolve).",- 'Open with a slugline in caps (`INT. HOLDING CELL - NIGHT`). Action lines are present tense, third person, no camera directions.',- 'Character cues are ALL CAPS on their own line above the dialogue; parentheticals go on their own line in lowercase. Introduce a character with their name in caps the first time they appear in an action line.',- 'Use `\\n` line breaks between every slugline, action block, cue, and dialogue block — the text is rendered as written.',- ].join('\n'),-});--// How the narrator answers a reader mid-scene, in the loom's format.-const NARRATION_CONTRACTS = Object.freeze({- prose: '1–3 short paragraphs of second-person present-tense prose.',- teleplay: 'a short teleplay fragment — action lines in present tense, plus a character cue and dialogue when someone speaks. No slugline unless the location changes.',-});--export const sceneFormatContract = (format) => SCENE_CONTRACTS[asLoomFormat(format)];-export const narrationFormatContract = (format) => NARRATION_CONTRACTS[asLoomFormat(format)];--/** Human label for the format, used in prompts and error copy. */-export const loomFormatLabel = (format) => (asLoomFormat(format) === 'teleplay' ? 'teleplay / screenplay' : 'narrated prose');+export {+ LOOM_FORMATS,+ LOOM_FORMAT_DEFAULT,+ isLoomFormat,+ asLoomFormat,+ sceneFormatContract,+ narrationFormatContract,+ loomFormatLabel,+} from '../../lib/fableLoomFormats.js';diff --git a/server/services/fableLoom/limits.js b/server/services/fableLoom/limits.jsindex 35f47e9876..f4ec7a3523 100644--- a/server/services/fableLoom/limits.js+++ b/server/services/fableLoom/limits.js@@ -1,27 +1,8 @@/**- * FableLoom record caps — the single source of truth shared by the sanitizer- * (`records.js`, enforcement) and the route schemas- * (`server/lib/fableLoomValidation.js`, door check). A leaf module so the lib- * barrel doesn't transitively load the universe/series service graph.+ * Re-export shim. The caps themselves moved to `server/lib/fableLoomLimits.js`+ * so `lib/fableLoomValidation.js` can read them without importing upward into+ * services (issue #4901). They were always a leaf module; only the address+ * changed. Existing deep imports from inside the service keep working.*/-export const LOOM_LIMITS = Object.freeze({- NAME_MAX: 200,- LOGLINE_MAX: 500,- PREMISE_MAX: 20000,- STYLE_NOTES_MAX: 4000,- REF_ID_MAX: 64,- EPISODES_MAX: 100,- EPISODE_TITLE_MAX: 300,- SYNOPSIS_MAX: 4000,- NODES_MAX: 200,- NODE_TITLE_MAX: 300,- PROSE_MAX: 20000,- IMAGE_PROMPT_MAX: 2000,- ENDING_LABEL_MAX: 200,- TRANSITIONS_MAX: 12,- INTENT_MAX: 120,- TRIGGER_MAX: 160,- TRIGGERS_MAX: 8,- TRANSITION_DESC_MAX: 500,-});+export { LOOM_LIMITS } from '../../lib/fableLoomLimits.js';diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.jsindex 0996a5873f..79272ea7a1 100644--- a/server/services/meatspacePostCognitive.js+++ b/server/services/meatspacePostCognitive.js@@ -23,17 +23,10 @@ import { shuffle } from '../lib/arrayUtils.js';// Coarse module tag stored on scored cognitive tasks, so stats read as// `byDrill['cognitive:<type>']` (parallel to `mental-math:<type>`).export const COGNITIVE_MODULE = 'cognitive';-export const COGNITIVE_DRILL_TYPES = [- 'n-back',- 'digit-span',- 'stroop',- 'schulte-table',- 'mental-rotation',- 'reaction-time',- 'task-switching',- 'go-no-go',- 'flanker',-];+// Moved to lib so route validation can enumerate the types without importing+// this module — issue #4901.+export { COGNITIVE_DRILL_TYPES } from '../lib/postDrillTypes.js';+import { COGNITIVE_DRILL_TYPES } from '../lib/postDrillTypes.js';const NBACK_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.jsindex 07de2b5020..555cc03bac 100644--- a/server/services/meatspacePostDrillCache.js+++ b/server/services/meatspacePostDrillCache.js@@ -18,9 +18,10 @@ const MIN_PER_TYPE = 3;const MAX_PER_TYPE = 10;// Only cache LLM-generated drill types used in wordplay training-export const CACHEABLE_TYPES = [- 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist',-];+// Moved to lib so route validation can enumerate the types without importing+// this module (and, through it, the LLM drill generator) — issue #4901.+export { CACHEABLE_TYPES } from '../lib/postDrillTypes.js';+import { CACHEABLE_TYPES } from '../lib/postDrillTypes.js';let cache = {}; // { type: [drill, drill, ...] }let replenishing = new Map(); // type -> Promise (in-flight replenishment)