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

120 KB
Raw Blame

Release v2.31.0

Released: 2026-07-16

Highlights

  • Autonomous Creation Engine (Creative Commissions). A standing creative brief that fires on a schedule and drives the Creative Director unattended — "every night at 2am, make me something surreal." Rate each run 👍/👎 and your reactions steer the next one; pick which AI provider/model processes it; and a ⚡ "Run Now" button tests a commission outside its schedule.
  • Creative Director reliability. Antigravity (agy) agents now actually receive their brief (a flag-parsing bug had them ignoring it), commissioned videos honor the project's locked aspect ratio, and a finished video commission now promotes its rendered clip to the project's final video instead of looking like it did nothing.
  • Digital Twin gets a face and a mirror. A new Avatar Bio tab assembles a copy-ready persona for live-avatar platforms (HeyGen, Tavus, ElevenLabs), built deterministically with no LLM call. A new Personality tab runs models through an introspective self-evaluation and scores how well their posture aligns with your twin.
  • SongBook. A new Brain repertoire for guitar tabs, chord sheets, and sheet music — learning-stage tracking, an Ultimate-Guitar-style autoscroll play view, non-destructive transpose, and per-instrument (guitar/ukulele/piano) chord voicings with tappable diagrams. Songs federate across machines.
  • Daily Driver + POST. A self-dismissing dashboard card sequences your day (POST → per-goal next actions) with no boot-time LLM calls; POST cognitive drills get first-run how-to cards; and every POST streak/day boundary is now computed in your timezone instead of the server's UTC day.
  • Holistic "Review this series." One panel runs every read-only series check at once — foundation, editorial, health, canon — into a single verdict with each finding deep-linked to where it'd be fixed, optionally driving the autopilot revision cycle.
  • CyberCity. URL-addressable building focus mode (fly-to camera, deep-linkable), an adaptive render budget with an Auto quality mode and a frameloop that pauses on hidden tabs, and a responsive mobile HUD that keeps the scene visible.
  • Smarter, self-healing automation. Task learning now weighs recent runs (so a fixed task type recovers fast), excludes provider outages from a type's success rate, dedups investigations per failure cause, and applies consecutive-failure backoff with auto-park + notification. Layered Intelligence stops re-proposing finished work.
  • Lower-latency voice. An opt-in fast-resolution cascade handles navigation and simple turns client-side (including on-device Gemini Nano) before the server LLM, and proactive speech now plays on a single designated tab instead of every open device at once.
  • Companion-app foundation. The public health endpoint now reports the instance name, whether a password is required, and the scheme — enough for a native companion app to list and label instances across your tailnet — with a documented native-client API contract.
  • Security hardening. SSRF / API-key-exfiltration guards on custom AI provider endpoints and browser navigation, shell-injection removed from the DB-sync import and Layered Intelligence custom sources, fail-closed auth when settings.json is corrupt, and tightened upload-path containment.
  • Reliability & accessibility. Lazy route chunks retry before failing on flaky mobile networks, above-the-fold mobile touch targets hit 44px, warning surfaces meet WCAG AA in day themes, and a broad sweep removes double error toasts across the app.
  • Infrastructure. Large god-modules (universeBuilder, catalogDB, the digital-twin router, cosAgents, the pipeline stores) decomposed behind thin barrels with shared write-queue / SSRF / pagination helpers, plus new Antigravity + Grok subscription-usage adapters in DevTools.

Creative Director

  • Antigravity (agy) agents now actually receive their task — CD plan/treatment agents (and every other headless agy run) were launched as agy --print --dangerously-skip-permissions with the prompt piped to stdin. But unlike the old Gemini CLI, agy --print takes the prompt as the flag's value and does not read stdin — so the flag parser consumed --dangerously-skip-permissions as the "prompt," the real 23KB brief was ignored, and the agent dutifully researched the flag name and asked for clarification (while permission auto-approval silently never took effect). The prompt is now delivered as the --print value (agy --dangerously-skip-permissions --print "<prompt>") across all six spawn paths (runner, direct, "Run Prompt", ask, vision, cos-runner). The interactive TUI path was never affected (it pastes the prompt, no --print to swallow the flag).

  • Commissioned videos now honor the project's locked aspect ratio — a scheduled Creative Commission (e.g. a daily 9:16 clip) whose plan renders through media_enqueueVideoJob was rendering at the video worker's default 768×512 landscape box: the planner authored an aspectRatio string the worker doesn't read, and the project's locked preset was never resolved into the width/height the renderer actually consumes. The server now deterministically forces every directive-plan video render onto the project's locked aspect/quality/duration preset (the planner keeps ownership of prompt/style), and the cd-plan prompt documents the locked settings so the plan preview stays honest.

  • A completed video commission no longer looks like it "did nothing" — the directive-plan flow marked the project complete but never promoted the rendered clip to finalVideoId, so the Creative Director overview showed "Final video: not yet rendered" even though the render had landed in the media library. Plan completion now promotes the last rendered video to the project's final video (and backfills it on re-entry for already-complete projects).

  • [issue-2620] Layered Intelligence stops re-proposing finished work — completed plan items stay recognized as done, and proposal outcomes now distinguish merged, rejected, and abandoned instead of counting every closed issue as merged.

  • [issue-2617] Task learning forgives fixed problems — scheduling, model-routing, and self-diagnostics decisions now weigh recent runs instead of lifetime totals, so a task type recovers as soon as it starts succeeding again.

  • [issue-2619] Self-heal cleanup after a fixed failure storm — a health-tick reaper now auto-expires stale failure-blocked tasks (older than 14 days) and investigation tasks whose origin is gone/completed via a federation-safe status flip (never deletion); resetting a task type's learning now also purges its stale failure-signature samples and correlation-window rows; failure signatures are age-windowed (30 days) so an outage-era sample stops steering routing; and a poor-lifetime task type whose recent window is clean is now auto-rehabilitated even while it keeps running (not just when idle).

  • [issue-2615] One investigation per failure cause, not one per failure — repeated agent failures now dedupe into a single investigation task, with an hourly cap and no investigations-of-investigations.

  • [issue-2618] Provider outages no longer count against task learning — rate-limit, auth, billing, and startup failures are tracked separately instead of denting a task type's success rate, so an outage can't get a healthy task skipped or demoted.

  • [issue-2621] Feature brainstorming remembers rejected ideas — the feature-ideas task now checks REJECTED.md and previously closed-unmerged proposals before suggesting, so declined ideas stop coming back.

  • [issue-2614] Failing scheduled tasks no longer pile up duplicates — a task blocked by repeated failures now counts as "already queued," so the same improvement task isn't re-created every cycle. Explicit retries (an on-demand Run, a manual job trigger, a Creative Director re-generate, or a repeated voice dispatch) revive the blocked task with a fresh retry budget instead of silently doing nothing, and the CoS log names the blocking task whenever it suppresses new work.

Security

  • [issue-2684] A corrupt settings file can no longer silently disable your password. Previously, if settings.json became unreadable or malformed, PortOS read it as "no settings" and treated the password gate as off — leaving the API open. The auth check now tells a genuinely absent settings file (a fresh install, correctly password-free) apart from one that exists but can't be read, and fails closed in the latter case: protected routes require a password and the health endpoint reports auth as required, until the file is readable again. The state self-heals on the next clean read with no restart.

Companion app

  • [issue-2678] Instance identity is discoverable before you sign in. The public GET /api/system/health endpoint now also reports the instance's display name, whether a password is required, and the scheme (http/https) it serves — so a native companion app can list, label, and decide whether to prompt for a password across your tailnet without a credential or a second request. Ships with a documented native-client API contract (docs/COMPANION_APP_API.md, linked from the API reference) covering discovery, auth, instance management, quick actions, daily-log, and POST progress.

Added

  • Creative Commissions "Run Now" test button. Each commission card gains a ⚡ button that fires the commission immediately, outside its schedule, so you can verify a standing brief actually works without waiting for the next cron tick. The manual fire runs the exact same gated path as a scheduled tick — autonomy-mode and budget gates included — so the outcome (started / skipped + reason / failed) is an honest preview of what the schedule will do; the toast reports it, and the run lands in the drawer's run history tagged with a manual badge (runs now persist a trigger field, older runs read as scheduled). A paused or half-configured commission is still testable: the manual path deliberately skips only the enabled and cron-validity guards. New runCommissionNow() in the scheduler (shared fireCommission core with the cron handler) + POST /api/creative-commission/:id/run, unit-tested at the store, scheduler, and route layers.

  • Durable agent feedback queue for CoS agents. Completion notifications already accept a quick rating, but once a notification expired there was no way to find completed runs still awaiting feedback. The Agents tab's completed-agents list gains a Needs feedback filter (with a live count) that surfaces only unrated, non-system runs, and rating one now updates the list in place — the run drops out of the queue immediately without a full refetch. New needsAgentFeedback predicate + optimistic handleFeedbackChange in AgentsTab.jsx; AgentCard now hands the updated agent record back to its parent on submit. Unit-tested.

  • Digital Twin → Avatar Bio: copy-ready persona for live avatars. A new Avatar Bio tab (reachable via ⌘K and voice) assembles a concise three-part persona — Who I Am / How I Speak / What I Know — sized for live-avatar platforms (HeyGen, Tavus, Simli, ElevenLabs conversational agents) whose persona/knowledge fields want a tight blurb, not the full soul-document dump that Export produces. The bio is built deterministically from your existing twin data (SOUL/COMMUNICATION/PERSONALITY/COGNITIVE/TECHNICAL/CREATIVE/VALUES docs + stored voice traits + goals) with graceful per-section fallbacks, so it renders instantly on tab load with no LLM call (never trips the no-cold-bootstrap policy). A length toggle (Blurb / Persona / Knowledge) tunes verbosity; each section and the combined bio have their own Copy button. An optional Refine with AI action rewrites the draft into first-person prose via a chosen provider, preserving every fact and inventing nothing. When no numeric voice profile has been generated yet, a nudge banner links to the Personality and Voice tabs so the "How I Speak" section can be enriched with cadence and verbal markers. New service server/services/digital-twin-avatar-bio.js (buildAvatarBio deterministic + polishAvatarBio provider path) and routes GET /api/digital-twin/avatar-bio + POST /api/digital-twin/avatar-bio/polish, unit-tested.

  • [issue-2664] Holistic "Review this series" flow. The series detail page gains a Review this series panel (above Autonomous mode) that runs every read-only check at once — the foundation judge (world/characters/arc/craft quality), the full editorial-checks pass, editorial health + readiness, and canon descriptive-integrity — and composes them into a single verdict (ready / issues) with signal chips (Foundation, Health, Canon) and every finding grouped by the issue it'd be patched at, each deep-linked to that section and to a per-finding Fix here in the manuscript editor. An optional free-text note ("Volume 1 looks complete but nothing develops") is routed by an LLM to the best issue/section and seeded as an anchored finding, so your own observation lands where it can be fixed. When issues are found, an inline confirm (no window.confirm) asks whether the story is good to move forward — Looks good dismisses, Fix these issues drives the existing Series Autopilot revision cycle (reusing the CoS-domain autonomy gate + budget + SSE — no second orchestrator) to patch findings at their anchors. The review performs no manuscript writes (safe to run repeatedly) and streams progress over SSE; with the CoS auto-run domain off it degrades gracefully — review still works read-only and each finding is fixable by hand. New service server/services/pipeline/seriesReview.js + POST/GET /api/pipeline/series/:id/review, both unit-tested.

  • [issue-2656] SongBook per-instrument view with chord voicings. The song viewer's play mode gains a Guitar/Ukulele/Piano toggle (URL-addressable via ?view=, defaulting to the song's own instrument — bass/voice/other render guitar shapes) that swaps how chords are visualized without touching the record. Every chord token in the sheet is now tappable/keyboard-accessible and opens a viewport-clamped popover with the voicing for the active instrument: an SVG fretbox (nut, finger dots, open/muted markers, and a fret-window label for barre shapes) for guitar and ukulele, or spelled note chips (letter-accurate — the 3rd of E is G#, never Ab) for piano. Slash chords voice the base chord and show the bass separately; unknown chords degrade to "no diagram" without crashing. A collapsible "Chords used" strip above the sheet shows a mini diagram for each unique chord in first-appearance order, diagrams follow the transpose control's chord names, and guitar-specific tab staffs collapse to a one-line note (with an inline "show" expand) in the ukulele/piano views. New pure lib client/src/lib/chordShapes.js (curated first-position guitar shapes + movable E-/A-form barre templates, an exact lowest-position search for ukulele GCEA, interval math for piano) and ChordDiagram component, both unit-tested.

  • [issue-2593] URL-addressable building focus mode in City. Clicking a building, minimap marker, or search match now focuses it in place at /city/apps/:appId instead of leaving City for /apps/:id — the camera flies to frame the whole borough (aspect- and HUD-safe-area aware, guarded against intersecting geometry) and the Intel pane is replaced (never overlapped) by a building-detail panel showing status, a process summary with unhealthy processes, and the app's active agents, plus an explicit Open app action to the real detail page and a Close back to the overview. The focused borough is visually distinguished (accent selection ring + expanded hologram) and its minimap dot exposes aria-current to assistive tech. Because the selection lives in the URL, reload/deep-link restores it once positions load, and browser back/forward moves between focused buildings and the overview; stale/deleted ids get an inline "building not found" fallback with a return-to-overview action. Entering Photo, History, or Drop In while focused deterministically clears focus first. On compact viewports the details render as the responsive HUD bottom sheet. New pure helpers cityFocusCamera (framing math, unit-tested) and cityFocusState (route-param resolution, unit-tested); new CityFocusCamera (in-canvas controller) and CityFocusPanel components.

  • [issue-2610] LLM personality self-profile testing with digital-twin alignment scoring. New Digital Twin → Personality tab (also reachable via ⌘K and voice): pick one or more provider/models and run a single-prompt deep introspective self-evaluation that returns a structured personality profile — agreeableness, humor, error aversion, self-censorship, conciseness, dogmatism, sycophancy, creativity, formality, empathy — each scored 0–100% with the model's own rationale, plus a plain-language summary. An optional follow-up check scores how well that posture aligns with your twin's analyzed traits (Big Five, communication profile, values), with per-dimension notes; it's skipped with a clear message when the twin has no analyzed traits yet. Results render on a radar chart, persist as capped local history (survives restart, delete per entry), and any 2+ past runs can be overlaid on one radar with a side-by-side score table to compare models or track one model over time. The scorer provider/model, history cap, and default alignment toggle are configurable in the tab's Options; both prompts are editable stage templates like any other. Calls fire only from the explicit Run action — never at boot or in the background.

  • [issue-2666] Daily Driver dashboard card. A self-dismissing card that, on the first visit of the local day, sequences you through your daily POST → a concrete next-action for each active goal → (with no goals) a "Define your goals" nudge — composing existing signals, never firing an LLM call on first visit or boot. The card renders the POST row (done-today/streak or the top "up next" recommendation, deep-linking to /post/launcher), then one row per active goal carrying that goal's mapped feature deep-links (health → Daily POST / Body Health, creative → Writers Room / Universes / Series Pipeline, legacy → Autobiography / Legacy Bundle / Sharing, etc.) plus its latest check-in recommendation, and a one-click "Check in on all goals." A new deterministic, LLM-free goal category → PortOS feature-area map lives in one module mirrored byte-for-byte between server and client (server/lib/goalFeatureMap.js ↔ client/src/lib/goalFeatureMap.js), with every deep-link sourced from a real NAV_COMMANDS path (test-enforced). A goal can pin its own feature areas via an optional featureAreas override (validated on create and update, falling back to the category default when absent). A timezone-correct per-day first-visit + "handled" signal (server/services/dailyDriver.js, GET/POST /api/daily-driver) gates the widget — it self-hides for the rest of the day once handled or dismissed, reserving no dashboard space. Registered in widgetRegistry.jsx and pinned to the top of the Morning Review layout.

  • First-run tutorial for POST cognitive drills. The timed, stimulus-driven cognitive drills (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) start flashing a stimulus the instant they mount, which is disorienting the first time you meet one. Each drill type now shows a one-time how-to card — a plain-language goal, numbered steps, and the controls — the first time it's encountered, and holds the drill (and its timers) until you tap Start drill. The card is config-aware (it names the n-back lag, the digit-span direction, and the reaction-time mode), then never shows again for that type (tracked per type in localStorage). Non-timed drills (math/memory, LLM/verbal) are self-explanatory and are not gated.

  • Voice fast-resolution cascade (lower CoS latency, opt-in). The voice Chief of Staff can now triage each spoken/typed turn through fast client-side tiers before the (slow) server LLM: tier 1 triggers resolve navigation commands ("go to tasks", "open the daily log") instantly in the browser with no LLM; tier 2 runs Chrome's on-device Gemini Nano (Prompt API — window.LanguageModel / legacy self.ai.languageModel) for simple/conversational turns, entirely local and private; tier 3 is the existing server pipeline (recommend Ollama), which still handles every tool/action turn, personal-data retrieval, dictation, and confirmations. Off by default (existing installs keep all-server behavior); enable under Settings → Voice → Fast resolution, which also shows a live on-device-model availability pill with the chrome://flags hint. Applies to Web-Speech STT and typed input (whisper/hands-free audio turns stay server-driven); trigger/Nano replies are spoken through the configured TTS and keep barge-in + echo-suppression working. New llm.fastPath config (enabled/triggers/browserLlm/browser.{temperature,topK}); new client modules browserLlm.js (Nano client) and voiceFastPath.js (routing decision). Nothing runs a model the user hasn't triggered (no cold-bootstrap).

Changed

  • Consistent Brain sub-page layout, and Insights moves to Identity. The standalone Brain sub-pages that hand-rolled their own headers now share the standard full-bleed layout every other section uses — a full-width bordered PageHeader bar over an internal flex-1 overflow-auto scroll region. SongBook (/songbook), its Import page (/songbook/import), Timeline (/timeline), and Rapid Reader (/rapid-reader) previously either stripped the header's border/padding, centered a narrow max-w-* column under the sidebar padding, or (Rapid Reader) rendered a bespoke <h1> — so navigating between Brain pages produced visual jitter. They're all routed through the full-width <main> now and own their scroll, matching Brain/Wiki/Tribe/Insights. Separately, Insights — cross-domain intelligence over your genome, health data, and taste/identity — is reclassified from Brain into the Identity sidebar group (alongside Digital Twin, Character, and Privacy), where it belongs; its route stays /insights/* and the nav-manifest entries (⌘K + voice navigation) move with it.

  • OpenClaw moves from Brain into Settings. The OpenClaw operator chat surface now lives under the Settings sidebar group instead of Brain, and its page adopts the standard Settings layout — a "Settings" header plus the shared SettingsTabsHeader sub-nav — so you can hop between OpenClaw and the other Settings sections (Providers, Prompts, Local LLMs, …) without returning to the sidebar. The route stays /openclaw; the nav manifest entry (and thus ⌘K / voice navigation) reclassifies it under Settings.

  • Accessibility: route the last hand-rolled confirmation modals through the shared <Modal>. The DataDog and JIRA "Delete instance?" dialogs, the GitHub archive/unarchive confirmation, and the PromptManager "Create Stage" / "Delete Stage" dialogs were bespoke fixed inset-0 bg-black/50 overlays with no role="dialog", no aria-modal, no focus trap, and no Esc-to-close. They now render through client/src/components/ui/Modal.jsx, gaining the shared dialog semantics — labelled headings (aria-labelledby), focus trap with focus restoration, the Esc stack, and backdrop-click dismissal — with the long "Create Stage" form opting out of backdrop-dismiss so an accidental click can't discard typed state. No visual change.

  • [issue-2592] Add an adaptive render budget and visibility-aware frameloop to CyberCity. City gains an Auto quality mode (City Settings → Performance): new installs default to Auto starting at High, while existing saved settings load as Manual and keep their preset (adaptation never touches a chosen fixed preset, and never rewrites localStorage). A pure state machine, client/src/utils/cityRenderBudget.js, watches p75 frame time over 2s rolling windows — ignoring the startup warm-up and frame gaps above 250ms — and steps the effective detail tier down after two windows above 25ms, up after five below 18ms, with a 10s cooldown and never more than one tier per decision (the 18–25ms dead band is the anti-oscillation gap); sustained sub-cutoff frames still downshift via a synthetic pressure window. The runtime effective tier is separate from persisted settings and drives reflections, particle density, DPR, interior-window shaders, and set dressing via an explicit effectiveTier (replacing the old particleDensity-as-quality proxy in cityShowDetail/cityShowInteriorWindows). The live City frameloop now pauses while the tab is hidden (frameloop="never") and resumes with a fresh warm-up when visible again — Photo mode keeps its demand loop and capture behavior untouched. The Performance tab shows the effective tier (AUTO · HIGH) plus a local-only diagnostics readout (tier, FPS, p75) that is never persisted or transmitted, and disables the Auto-controlled Reflections/Particle-density fields. New unit tests cover downshift, recovery, cooldown, ignored samples (warm-up/gap), sustained slowness, storage compatibility, Manual mode, and visibility transitions.

  • [issue-2534] Unify service errors on ServerError and delete the duplicated mapServiceError copies. Routes now speak one error model. A single createServiceErrorMapper(statusMap, buildContext?) factory in server/lib/errorHandler.js replaces the nine near-identical local mapServiceError bodies that had accreted across the pipeline / builder / media routers (pipeline/shared.js, storyBuilder.js, universeBuilder.js, importer.js, dashboardLayouts.js, conflictJournal.js, mediaSketches.js, mediaCollections.js, mediaAnnotations.js) — each now just wires its own domain code → status map (and optional diagnostic-context builder) through the shared factory. Separately, the CoS agent service functions that returned result-shaped { error } payloads (getAgentPrompt, deleteAgent, submitAgentFeedback, sendBtwToAgent) now throw ServerError with an explicit status/code, so cosAgentRoutes.js no longer string-matches result.error === 'Agent not found' to guess 404-vs-400 — the errors bubble straight to the centralized middleware and every route returns the same { error, code, timestamp, context? } envelope. No client-visible behavior change (the same statuses/codes are preserved). Pure architecture refactor.

  • [issue-2534] Finish the CoS agent error unification: pauseAgent and killAgent now throw ServerError too. The prior pass left the agent-lifecycle pauseAgent and killAgent returning { success: false, error } result shapes, so the pause and kill routes still string-matched result.error into a blanket 404. Both now throw ServerError — 404 NOT_FOUND for a missing/not-running agent (including a genuine runner-side 404 when the runner has restarted out of sync, whose HTTP status cosRunnerClient now preserves on the thrown error), 500 AGENT_PAUSE_FAILED / AGENT_KILL_FAILED for a runner-RPC or persist failure (previously every runner failure was mis-reported as 404). The pause/kill routes drop their result-shape checks and just return the success payload. killProcess's CoS-delegation path falls back to a raw kill via .then(ok, err) so a now-throwing killAgent still degrades gracefully. terminateAgent intentionally stays result-shaped: its route is fire-and-forget (the lifecycle wrapper emits agent:terminate and returns before termination runs), and its other callers (the event handler, killAllAgents' bulk sweep) inspect the result rather than a thrown error. Behavior-preserving apart from the more-correct 500 (not 404) on kill infra failures.

  • [issue-2591] Responsive City HUD + City settings on the shared Drawer. The CyberCity HUD now adapts to the viewport instead of stacking every desktop panel on top of the 3D scene at phone width. A new useCityViewport hook brackets the window into desktop (≥1024, unchanged cockpit), compact (640–1023) and phone (<640); below desktop the HUD collapses to a small clock/health chip, a status chip and a bottom dock of 44×44 launchers, keeping ≥70% of the scene unobscured on load. Secondary surfaces (vitals, attention, timeline, activity, map, filter, legend) open as ONE mutually-exclusive disclosure sheet driven by a cityPane URL param, so only one shows at a time and the open one is deep-linkable, reload-safe and restored by browser back/forward (the desktop Intel pane's active tab reads the same param). City settings moved off the bespoke bottom-right scroller onto the shared tabbed Drawer (size="sm", Performance/Audio/Visual/Explore, active tab deep-linked via useDrawerTab's cityTab param, TabPills mobile dropdown), preserving the /city/settings route.

  • [issue-2550] Add direct unit tests for telegramClient, the telegram service, and errorHandler.asyncHandler. Three previously under-covered modules gain colocated *.test.js suites, all driven with an injected/mock fetch (no network): server/lib/telegramClient.test.js now covers the poll loop (getUpdates dispatch to matching/non-matching onText + message/callback_query listeners, offset advance, stopPolling abort, and non-ok retry via fake timers) and the apiCall methods (getMe/sendMessage happy path, reply_markup string→object parse, non-ok throw); a new server/services/telegram.test.js exercises the token-bucket rate limiter (30-message cap then Rate limit exceeded) and unauthorized-chat rejection (message/command/callback_query paths) through init() with all deps mocked; and server/lib/errorHandler.test.js adds asyncHandler coverage (thrown ServerError → status+body+emit, plain Error → 500 normalization, success no-op, and the no-io path). Test-only change — no runtime behavior change.

  • [issue-2530] Decompose cos.js dequeueNextTask and split cosAgents.js into focused modules. The ~370-line dequeueNextTask scheduler is now a thin orchestrator that threads a shared ctx through five spawnDequeuePriorityN(ctx) tier helpers (mirroring evaluateTasks), with the pure per-cycle capacity tracker (createDequeueCapacity) and mission/idle tier-eligibility predicates extracted to a new server/services/cosDequeue.js — so the scheduler and its unit tests exercise the same guards instead of a local replica. The ~1090-line cosAgents.js is split into focused siblings — cosAgentIndex.js (date-bucket index / migration / prune / archive layout), cosAgentLifecycle.js (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), cosAgentFeedback.js (feedback capture + classifier), cosAgentArchive.js (state-eviction sweeps) — with cosAgents.js kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.

  • [issue-2533] Thin the apps-list route and split the imageGen setup routes into their own module. The GET /api/apps handler's ~80 lines of inline PM2 enrichment (one read per pm2Home, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a new server/services/appListEnrichment.js (enrichAppsWithPm2Status(apps)), so the route just fetches the raw records and responds; the pure port/status helpers (deriveUiPort/deriveAppPorts/computeOverallStatus) live there too and are re-exported from routes/apps/shared.js so the detail/lifecycle routes keep one shared implementation. The /api/image-gen/setup/* handlers (python probe/venv bootstrap, FLUX.2 install/status, HuggingFace-token store, pip installer) split out of the large routes/imageGen.js render router into routes/imageGenSetup.js, with the setup-check cache and pip allowlist relocated to services/imageGen/setup.js. Pure mechanical refactor — no behavior change.

  • [issue-2531] Split the pipeline issues.js and visualStages.js monoliths along CRUD/stage/sync seams. The ~1470-line server/services/pipeline/issues.js is now a thin barrel over issuesShared.js (store facade + per-series write queue + record sanitizers + renumberInline), issueCrud.js (create/read/list/update/delete + numbering/reassign), issueStages.js (per-stage merge/history/restore), and issueSync.js (peer-sync LWW merge + tombstone GC). The ~1760-line visualStages.js is now a thin barrel over visualStageHelpers.js (shared style/prompt composers + image-gen enqueue plumbing), covers.js (comic + volume front/back covers), comicPages.js (comic page renders + panel prompt refine), and storyboards.js (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (queueSeriesIssuesWrite) and the store's queueTypeIndexWrite merge snapshot are preserved, and every existing from './issues.js' / from './visualStages.js' import path still resolves through the barrels.

Documentation

  • [issue-2547] Align the dual pm2 pins and refresh the kokoro-js dependency audit. The root package.json pinned pm2 at 7.0.3 while server/package.json pinned 7.0.1; both are now 7.0.3 (the higher pin, already reflected in the committed root lockfile — server lockfiles are gitignored, so no lockfile churn). kokoro-js (the only pure-JS in-process TTS path) is bumped from 1.2.0 to its latest patch 1.2.1 and flagged maintenance watch in docs/DEPS.md — no upstream publish since ~May 2025 — with an already-implemented Piper escape hatch documented for if it's dropped later (Piper is already a peer TTS backend — tts-piper.js's synthesizePiper — sharing the same (text, cfg, signal) → { wav, latencyMs } contract, so dropping kokoro is a delete of the kokoro branch in tts.js, not a rewrite). docs/DEPS.md's last-audited note is refreshed to 2026-07-14. Config/docs only — no runtime behavior change (API-compatible patch bump).
  • [issue-2546] Document missing .env vars and the boot CREATE INDEX lock window. .env.example now carries commented entries with purpose notes for four vars the server actually reads but never documented: PUBLIC_HOST (public hostname baked into Google/Spotify OAuth redirect URIs), SPOTIFY_REDIRECT_URI (verbatim Spotify redirect override), CODEX_HOME (Codex CLI home scanned for provider-usage stats), and HUGGINGFACE_TOKEN (the fourth HF-token alias read by the Hugging Face catalog client). Separately, ensureSchema() in server/lib/db.js creates every index (incl. the HNSW vector index) non-CONCURRENTLY, so the first apply on a large pre-existing table takes a write-blocking lock at boot; a comment there and a new Boot schema upgrades & the CREATE INDEX lock window section in docs/STORAGE.md explain when this bites (existing-install upgrades, not fresh installs) and why the fix for a future large-table index is a CONCURRENTLY db-migration rather than changing ensureSchema(). Docs-only — no runtime behavior change.

Fixed

  • Updating/reconciling no longer severs a live CoS agent. The update page's "Update Now", "Reconcile Now", and every fork update variant run update.sh, which pm2-restarts PortOS — killing any CoS agent mid-task (each agent's PTY/child process is a child of the server process). The Update tab now suppresses the "Install out of sync" reconcile prompt and the restart-triggering update buttons while agents are running, showing a "Update paused — CoS agents running" notice that clears automatically once the last agent finishes (the tab polls status every 4s while agents are live). Safe, non-restarting actions stay available — "Sync Fork Only" (just gh repo sync) and "Ignore v…" are not hidden. Defense-in-depth on the server: POST /api/update/execute hard-rejects with 409 AGENTS_ACTIVE when agents exist, so a race, a stale client, or a direct API call can't restart out from under a running agent — and it re-checks once more after acquiring the update lock (releasing it on abort) so an agent that goes live during the git/fork work still blocks the restart. The active-agent signal counts the in-memory live-process maps (direct + runner spawns) plus in-flight spawns (spawningTasks) — a just-launched agent whose child process exists but isn't yet registered in a process map would otherwise be invisible to a plain live-process check and still get severed. A stale persisted status: 'running' can't spuriously block, and a paused agent (process already stopped) correctly doesn't. GET /api/update/status reports activeCosAgents, and the tab keeps a light status poll running whenever an update/reconcile surface is on screen, so an agent that starts (from a schedule or another tab) suppresses the buttons promptly rather than leaving one that 409s on click. Covered by update.test.js and UpdateTab.test.jsx.

  • [issue-2681] POST daily status now uses your timezone, not the server's UTC day. completedToday, todayScore, and the POST streaks in the MeatSpace POST service derived the day boundary from the server's UTC day (the process runs TZ=UTC), so for anyone outside UTC a POST completed the previous local evening could read as "done today," or a just-completed local-day POST could read as incomplete — and the Daily Post widget and the Daily Driver card (#2666), which both render completedToday from getPostStats(), inherited the drift. The day boundary now threads your configured timezone (getUserTimezone/todayInTimezone, via a shared userLocalToday() helper) through both sides: every writer that stamps a day (submitPostSession, submitTrainingEntry, memory-practice submitPractice, and Morse appendMorseRound) records a new record's date in your local day — derived from the same instant it stamps into timestamp/startedAt so a midnight boundary can't split the two — and every reader (getPostStats/getPostProgress/getUnifiedActivityStreak/getTrainingStats/getMorseProgress, plus the mastery-window cutoffs) derives "today" in your local day, mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. All window cutoffs use DST-safe day math off the local today. The POST launcher's "completed today"/today's-minutes and the history range floor also derive their day key in your configured timezone (new useUserTimezone hook + dayKeyInTimezone util) so the client agrees with the server instead of computing "today" in UTC. A one-time migration (192-post-dates-to-local-timezone) re-derives existing session, training-log, and Morse-round day-strings from each record's stored UTC timestamp in your timezone (preferring the retry-stable startedAt, and preserving a legacy practice entry's only instant into timestamp before rewriting date), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server's TZ=UTC runtime), making it a no-op for UTC/unconfigured installs.

  • Proactive voice speech no longer plays on every open tab/device at once. Server-initiated voice lines (reminders, briefings, task-completion alerts) were broadcast with io.emit('voice:speak', …), so every browser tab and every device connected to the instance spoke the same line simultaneously. Proactive audio is now routed to a single designated recipient tab, mirroring the shell's single-attached-socket pattern (new server/services/voice/voiceOutput.js): each tab registers as a candidate on connect, and the tab you're actively looking at claims output — the client emits voice:output:claim on focus, on becoming visible, and on reconnect-while-visible. When the recipient tab disconnects, output is promoted to the tab you focused most recently so audio always has exactly one home. Per-turn TTS (voice:tts:audio) was already single-socket and is unaffected. The voice widget shows a speaker / muted control so you can see which tab is the speaker and click to move it to the current tab. (Scope: dedup is per-instance — every client of one PortOS instance; it does not coordinate proactive lines independently fired by separate federated peers.)

  • [issue-2567] Stop double error toasts across the Settings tabs and the JIRA integration page. Several Settings surfaces routed a request through the auto-toasting request() helper AND showed their own toast.error in a custom catch, so a failure stacked two toasts. Every such call now passes { silent: true } so the caller's catch is the single error layer — covering VoiceTab (config load/save, Piper voice download), ImageGenTab (settings/tools load, save, tool register/update, test render), TelegramTab (settings load, method/config/test/disconnect, forward-types), BackupTab (settings load + save), DatabaseTab (status load), EmbeddingsTab (save), MortalLoomTab and CaptionModelPicker (save), and the JIRA instances page (load/save/delete/test — mirroring the DataDog fix from #2520). Loaders and callers without a custom toast are unchanged (single default-helper layer preserved). The getVoiceConfig/updateVoiceConfig/fetchPiperVoice, telegram, registerTool/updateTool/getToolsList, and getDatabaseStatus wrappers gained a backward-compatible trailing options param so callers can opt into silent. Follow-up sweep of the remaining pipeline/writers-room/universe/media/etc. areas is tracked in #2669.

  • [issue-2669] Stop double error toasts across the writers-room, universe, digital-twin, media, and brain areas. Continues the #2567 sweep into the non-settings feature areas: every caller that showed its own toast.error in a custom .catch/catch while its API call also routed through the auto-toasting request() helper now passes { silent: true }, so a failure surfaces one toast instead of two stacked ones. Covered across writers-room (folders/works/characters/objects/places CRUD, exercises, polish, drafts, analysis, promote-to-pipeline), universe canon + universeBuilder (extract/differentiate/refine/expand, lock toggles, world/reference-sheet renders, draft save + expand/refine auto-saves), digital-twin (confidence, enrichment lists, autobiography, writing-style/import/assessment analysis, taste + behavioral feedback, soul tests/documents), media/image/video (collections, timeline projects, media jobs queue, gallery hide/clean/upscale/stitch, image-gen cancel + submit, annotations, last-frame extract), and brain (links, daily log, brain graph). Loaders and callers without a custom toast are unchanged (single default-helper layer preserved). Wrappers in apiWritersRoom.js, apiUniverseBuilder.js, apiDigitalTwin.js, apiImageVideo.js, apiMediaJobs.js, and apiBrain.js gained a backward-compatible trailing options param so callers can opt into silent. Pipeline toast sites are intentionally deferred (a concurrent PR is reworking client/src/**/pipeline/**) and remain tracked in #2669, along with the other still-unswept areas (apps, cos, messages, meatspace, sharing, music/songs, privacy, calendar, and misc pages).

  • [issue-2669] Stop double error toasts across the Series Pipeline area. Continues the #2567/#2669 sweep into the pipeline stages, arc canvas, and Pipeline* pages: callers that showed their own toast.error in a custom .catch/catch while their API call also routed through the auto-toasting request() helper now pass { silent: true }, so a failure surfaces one toast instead of two. Covers the sites whose api wrappers already thread a trailing request-options arg — series/issue PATCH saves (LLM picker, theme chips, arc save, issue reassign, comic-page/storyboard persist, cover-script persist, page delete), universe-character refine and image-gen renders from the Nouns stage, series title-logo generation, and the loader Promise.alls in the Series, Issue, Manuscript Editor, Continuity Bible, Reverse Outline, Export, and Series Roadmap pages. Validation-only guards, SSE-frame toasts, useAsyncAction callers, and already-silent sites are unchanged. The pipeline sites whose apiPipeline.js wrappers still lack a request-options param (most stage-render/generate calls that spread opts into the request body) are tracked as a follow-up batch in #2669.

  • Deleting a blocked CoS task now clears the "N blocked tasks" alert bar immediately. On the Chief of Staff → Tasks page, the ActionableInsightsBanner (which owns its own /cos/actionable-insights fetch, decoupled from the task list) kept showing a stale blocked-tasks alert after a blocked task was deleted, until its 60s poll fired or the user manually dismissed it. The page now bumps an insightsRefreshKey on every task-list mutation, which the banner watches (via a mount-skipping effect) to refetch() its server-derived insights — so a delete (or any task mutation through the tasks list) re-derives the banner right away. Follow-up #2654 tracks lifting the insights fetch into the page's fetchData to also cover socket/health-driven staleness.

  • claim-issue no longer reports "no open issues" when an author filter is hiding a full queue. The perpetual claim-issue / claim-issue-gitlab work-detector runs gh/glab issue list with an author filter (self→@me, or owner→the repo owner), and an empty filtered result was flattened to the reason no-open-issues — so a repo with open issues that simply don't match the filter parked for a full recheck cadence claiming there was nothing to do. The two failure modes this hid: owner resolves to an org (e.g. a GHE repo owned by a team), which is never an issue author, so the filter matches nothing; and self/@me is the wrong identity when the forge session differs from whoever filed the issues. The detector now re-probes without the author filter when the filtered list is empty, and if open issues exist it parks with a new no-authored-issues reason carrying the real open count. The on-demand "Run" toast now says "open issues exist, but none match the author filter — set it to "any" (0 of N open)" instead of the misleading "no open issues", pointing the user at the fix. A genuinely empty repo still reports no-open-issues, and the any filter is unaffected (no wasted re-probe). New private helper countOpenIssuesUnfiltered; covered by perpetualWork.test.js and useOnDemandTaskToast.test.jsx.

  • claim-issue distinguishes the "owner filter matches an org" trap from a personal-username mismatch. Building on the fix above: when the owner author filter resolves to an organization login (the common case for team/enterprise repos), --author <org> can only ever match zero issues — an org is never an issue author. The detector now recognizes an org owner up front (gh repo view --json owner,isInOrganization), skips the guaranteed-empty query entirely, and parks with a distinct owner-is-org reason carrying the real open count. The toast now reads "the "owner" filter matches an org, which can't author issues — set it to "self" or "any" (0 of N open)" instead of the generic "set it to any", so the user isn't left thinking their own username is mismatched. owner mode on a user-owned repo is unchanged. Covered by perpetualWork.test.js and useOnDemandTaskToast.test.jsx.

  • Perpetual claim-issue stops spawning agents forever on a [Epic]-titled issue. The perpetual work-detector recognized a tracking epic only by an epic label or a title ending in "(epic)" — but the common [Epic] … bracketed-prefix convention (an epic filed with no epic label) slipped through, so the detector reported it actionable, cleared the park, and spawned a swarm/claim agent that read the issue, correctly skipped it as an epic, and shipped nothing. Because a perpetual completion skips the cooldown, that re-fired back-to-back — an overnight run churned hundreds of no-op agents on a queue where every remaining issue was needs-input/blocked plus one [Epic]-prefixed umbrella. isActionableIssue now recognizes a leading [epic] bracket or Epic: colon tag (case-insensitive, \b+terminator-guarded so [epicenter] and a bare "Epic rework" adjective don't match) via a new exported titleMarksEpic helper, so the drain converges and parks as it should. The claim-issue and claim-issue-gitlab prompts' Phase 1 epic rule was updated to name the [epic] prefix too (versions bumped to 6 / 5, outgoing defaults preserved for cross-install auto-upgrade), keeping the detector and the agent's skip criteria in lockstep. Covered by perpetualWork.test.js (incl. a 7-issue convergence scenario) and taskPromptDefaults.test.js.

  • pr-watcher now works on GitHub Enterprise hosts and resolves "self" against the repo's actual host. The pr-watcher task gated on getOriginInfo().isGithub, which is github.com-only, so it silently no-op'd (not-a-github-repo) on self-hosted GitHub Enterprise (github.*) repos. Worse, its self/others author gate resolved the operator login via gh api user with no --hostname — which always targets github.com regardless of the repo — and cached one login process-wide, so on an enterprise repo it compared PR authors against the wrong identity (a user is commonly a different login per host). The gate now classifies GitHub-family hosts via the shared hostToWorkTracker (the same rule the claim-issue router uses; gitlab.* still falls through as not-a-github-repo), the default-branch and PR-list gh calls pass a host-qualified --repo HOST/OWNER/REPO selector (enterprise-correct, and deterministic on a fork+upstream multi-remote checkout where cwd-based detection would ambiguously resolve to the parent), and getSelfLogin(host) resolves identity with an explicit --hostname and caches per host. Covered by prWatcher.test.js.

  • Retry lazy route chunks before failing on flaky mobile networks. Lazy-loaded pages fetch their JS chunk on demand, and on a weak cellular/Wi-Fi link that fetch can fail on a transient blip ("Importing a module script failed" on Safari, "Failed to fetch dynamically imported module" on Chrome) even though the chunk still exists — a page reload can't fix a network hiccup, so once the one-shot stale-chunk reload was spent for a build, the next blip stranded the user on the error screen. lazyWithReload now retries the dynamic import twice with a short backoff before treating the failure as terminal, so a transient mobile-network failure recovers silently without a jarring reload; a genuinely stale chunk (renamed by a rebuild) still 404s on each quick retry and falls through to the existing reload-once path. New importWithRetry helper with unit coverage.

  • Clear the offline (service-worker) cache before the stale-chunk recovery reload. When a genuinely stale chunk (renamed by a rebuild) triggered the one-shot reload, the reload could be served the old bundle right back — the service worker serves /assets/* cache-first, and on a flaky mobile link its network-first navigation falls back to the cached (old) app shell. That re-loaded the very code that just 404'd and burned the build-scoped reload guard, so the user stayed stuck on "Importing a module script failed" even after the reload and even on the latest build. reloadOnceForStaleChunk now purges the SW's portos-* caches (app shell + hashed asset chunks) via the page-side Cache Storage API before reloading, so the recovery reload is guaranteed to boot fresh code; the purge is bounded by a 1.5s timeout so a hung/disabled Cache Storage still reloads. The purge is gated on a build-id check: a flaky/offline network produces the same import-error messages as a stale chunk, and purging on a transient failure would destroy the valid current-build offline shell (if the link drops again during the recovery reload, the SW has no fallback and the user lands on the browser's connection-error page). fetchServerBuildId re-fetches the shell with cache: 'no-store' and reads the portos-build-id meta the server stamps into it — the caches are dropped only when the server confirms a different build; unreachable, non-ok, same-build, and unstamped responses all keep the caches so the reload can boot the SW's cached shell. New purgeOfflineCaches + fetchServerBuildId helpers with unit coverage (staleChunkReload.test.js).

  • [issue-2643] De-flake the Wiki vault-default test under full-suite load. Wiki.test.jsx's "defaults to the first vault" (and the sibling "restores the selected vault") assertions checked scanNotesVault synchronously right after await waitFor(...) on the rendered vault id. That mock call is fired by a separate useEffect keyed on the selected vault, so the committed overview render can land before the passive effect flushes — reliably true in isolation, but on a CPU-saturated full client run the bare assertion raced ahead of the effect and failed (expected vi.fn() to be called with arguments). The two mock-call assertions now sit inside their own waitFor, awaiting the async side-effect instead of sampling it. Test-only change (no test.retry or timeout inflation) — no runtime behavior change.

  • [issue-2633] Direct task:ready emits now claim against the right task file. The Creative Director bridge, the on-demand dequeueNextTask, and spawnPriority0OnDemand publish task records with no taskType, so an internal (sys-*/cd-*/app-improve-*) task's claim/in_progress updateTask fell back to 'user', targeted TASKS.md instead of COS-TASKS.md, missed the record, and returned a truthy { error } object the if (!updateResult) check silently swallowed — leaving the task un-claimed while the agent spawned anyway. runAgentSpawn now normalizes taskType from the id via isInternalTaskId up front (mirroring the completion path), so a correctly-routed internal task's claim lands in COS-TASKS.md. The in_progress-claim miss is now warn-logged so it's no longer silent — but it stays non-fatal: legitimately-unpersisted autonomous emits (Priority 3 mission and Priority 4 idle-review tasks carry taskType:'internal' but are never written to COS-TASKS.md) must still spawn as they did before, so only a null result (updateTask threw) aborts the spawn.

  • [issue-2540] Stop full-JSONB table loads for pipeline issue id sweeps and bound the multi-account message inbox aggregate. listIssueIds (the conflict-journal orphan-base-hash sweep + tombstone GC) went through readState() → loadAll(), pulling every issue's full data JSONB — up to ~12MB of stage runHistory each — into memory only to read the ids; it now sources the store's SELECT id projection, with the PG backend filtering tombstones via the mirrored deleted column (listIds({ includeDeleted })) so the whole-record load is skipped entirely for the default live sweep. Separately, messageSync.getMessages's multi-account inbox spread every message from every account into one array and globally sorted it before slicing a page; it now bounds each account's contribution to the top offset+limit by date and merges those heads, so a paged inbox reads accounts × (offset+limit) messages into the merge instead of the full cross-account total (the exact total count is preserved).

  • [issue-2538] Bound Spotify auth and privacy-broker fetches, and single-flight token refresh. The Spotify token endpoint (spotifyAuth.js) and the BADBOOL / CA-registry broker fetchers (privacyBrokers.js) used bare fetch with no timeout, so a hung accounts.spotify.com could stall an OAuth callback or a history-sync refresh — and a broker source that never responded could hang a user-triggered refresh — indefinitely. All three now go through the shared fetchWithTimeout helper with a 15s cap. Separately, concurrent getAccessToken() callers that all found the token expired each POSTed their own refresh, and since Spotify rotates the grant the losers persisted a stale token (last-write-wins); refreshes now share one in-flight refreshPromise (single-flight), so the grant is rotated exactly once and the guard is released on settle so a failed refresh can retry.

  • [issue-2552] Enlarge above-the-fold mobile touch targets to 44px. The GoalDetailPanel close button (p-1 + a 16px icon, ~24px) and the notification bell (40px min) were below the 44×44 touch-target minimum the shell's other chrome controls already meet. The close button now uses min-h-[44px] min-w-[44px] centered around its icon (matching the shared Drawer control sizing), and the bell's mobile hit area is bumped 40→44px (its sm: desktop shrink is unchanged). The notification panel also gains max-w-[calc(100vw-2rem)] so its w-80 width can't overflow a narrow mobile sidebar, and the ⌘K result rows get a min-h-[44px] so each is comfortably tappable.

  • [issue-2544] Wiki vault selection now lives in the URL. The selected Obsidian vault was local useState, so a reload, shared link, ⌘K jump, or voice nav always landed you back on the first vault. The vault is now encoded as a ?vault=<id> search param (the tab route param is preserved when switching tabs), selection is driven from the URL, and a stale/deleted vault id renders a "Vault not found" fallback with a one-click "Show default vault" recovery.

  • POST Digit Span: the form no longer jumps up as digits flash on and off. During the show phase the visible-digit slot collapsed to zero height in the blank gaps between digits, so the container (padding + min-h) oscillated and the recall form/progress bar below shifted up on every flash. The slot now reserves its line box with a non-breaking space in the gaps, keeping the layout steady while digits flash.

  • [issue-2551] Wiki Browse is now a responsive list/detail instead of a fixed two-pane. The Browse tab always rendered a horizontal two-pane layout with a fixed w-80 left rail and a magic calc(100dvh - 220px) height, so on a phone the folder tree consumed the whole viewport and the note pane was unreachable. It now mirrors the Brain Notes list/detail pattern: a single column on mobile that hides the tree once a note is opened (with a back control to return) and shows both panes from md+, laid out on a grid that fills its flex parent (min-h-0) rather than the fixed viewport-offset height, so a wrapped header no longer clips it.

Security

  • [issue-2514] Harden AI provider custom endpoints against SSRF / API-key exfiltration. A provider's endpoint is a free-form URL, and model-refresh / API-run paths attached the paid Authorization: Bearer <apiKey> and fetched that host with no host checks — a hostile or mistyped endpoint could receive the user's paid LLM key and prompts, or be pointed at a cloud-metadata service (169.254.169.254). A new endpointGuard now gates every secret-bearing request: loopback/LAN (Tailscale) and known paid-provider hosts are allowed, cloud-metadata hosts are always blocked, and any other host requires the new per-provider Allow custom endpoint opt-in. Keyless local-LLM calls (Ollama/LM Studio) are unaffected.
  • [issue-2518] Harden upload path containment and stop leaking absolute FS paths. The upload/attachment/screenshot routes guarded writes with a bare resolvedPath.startsWith(DIR) (no trailing separator, so a sibling like data/uploads-evil/ string-matched) and the attachment/screenshot responses echoed the absolute on-disk path back to the client, leaking the install layout / home-directory username segment. Containment now goes through a shared isPathInsideDir() helper (anchored resolvePath(dir) + sep prefix, matching makePathResolver), responses return only API-relative URLs (/api/screenshots/<file>), and the CoS prompt builder resolves those refs back to absolute paths at render time (legacy absolute values pass through unchanged). The moltbook-claim.mjs script now logs only the token length + short prefix instead of the full bearer token.
  • [issue-2517] Revalidate the browser navigate URL by resolved IP and by Chrome's actual per-hop connect address. POST /api/browser/navigate only checked the host LITERAL with isSafeIngestUrl, so a hostname whose A record rebinds to loopback/link-local/cloud-metadata, or a post-navigate redirect the CDP browser silently follows to a blocked host, slipped past. The route now adds a DNS-resolve pre-check (assertPublicHttpUrl) that refuses a hostname resolving to a blocked address before any tab is opened, and drives the navigation through navigateToUrlPinned — the same connect-time pin the catalog URL ingest uses — which verifies Chrome's own reported remoteIPAddress for the initial nav, every HTTP redirect, and any client-side navigation in the settle window, tearing the tab down and failing closed on a blocked hop. LAN/Tailscale hosts stay intentionally allowed. Residual: a WebSocket to a hostname that DNS-rebinds to a private IP can't be pinned via CDP interception (no remoteIPAddress on WS events) — bounded by the single-user trust model and documented in browserService.ssrfPinRefusalReason.
  • [issue-2515] Restrict Layered Intelligence custom cmd sources to allowlisted binaries (no shell: true). A custom cmd source ran its full command string through shell: true with only a length/timeout cap, so any config-write path (hand edit, hostile sync payload) gained persistent, unattended RCE on the LI schedule (; rm -rf ~, $(curl … | sh), pipes to sh). runShellCommand now denies the shell by default: the command is parsed and checked against the shared commandSecurity binary allowlist (rejecting shell metacharacters and non-allowlisted binaries), then spawned with shell: false and parsed args. An operator who genuinely needs a pipeline can set the install-level settings.layeredIntelligence.trustShellSources opt-in (off by default) to restore full-shell behavior for that install only.

Fixed

  • [issue-2537] Serialize message-cache mutators under a per-account write lock. refreshMessage and updateMessageEvaluations did their load → mutate → saveCache outside the per-account syncLocks, so a full-body refresh or an evaluation write racing a concurrent sync (or each other) could clobber the other's update on the shared data/messages/cache/<accountId>.json file. All three cache mutators (syncAccount, refreshMessage, updateMessageEvaluations) now route their write region through one per-account tail (createKeyCachedQueue), so each awaits the previous and re-reads the freshest persisted state before merging — mirroring issueWriteTail in pipeline/issues.js. The existing syncLocks boolean still rejects a duplicate in-flight sync with 409. Regression tests assert two concurrent mutators both persist.
  • [issue-2543] Cancel stale ⌘K global search responses and clear the Security device-change restart timer. The command palette's global search(query) effect debounced the request but had no in-flight guard, so a slow response for an older query could resolve after the user typed on and overwrite the newer query's results (or flip the loading spinner off prematurely) — the sibling catalog-search effect already used a cancelled flag. The global-search effect now mirrors that cancelled guard so only the latest query's response applies. Separately, Security.jsx's device-change handler scheduled setTimeout(startMedia, 100) with no clear on unmount or before rescheduling, so rapid device switches stacked multiple startMedia() calls and a navigation-away could fire the restart into an unmounted component; the timer id is now held in a ref, cleared before each reschedule, and cleared in an unmount cleanup effect. A regression test asserts a stale search response can't clobber the current query's results.
  • POST session run page crashed (React error #130) when transitioning into a cognitive drill. DrillTransition.jsx's DOMAIN_ICONS map was missing a cognitive entry, yet DRILL_TO_DOMAIN maps every cognitive drill type (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) to the cognitive domain — so finishing a drill whose successor was a cognitive drill (e.g. a Doubling Chain followed by a cognitive drill) resolved the transition-card icon to undefined and blanked the run page with a minified React error. Added the cognitive: Brain icon and hardened the lookup to fall back to ChevronRight for any unmapped domain, so a future domain gap degrades gracefully instead of crashing. A regression test renders the transition for every DRILL_TO_DOMAIN type.
  • [issue-2549] Enforce the Windows .exe basename contract in the CoS Runner allowlist test. The allowedCommands.test.js case for a Windows absolute path (C:\\...\\claude.exe) ended on expect(typeof result).toBe('boolean'), which passes for any boolean — so on POSIX CI the Windows path handling was never actually asserted and a regression would go unnoticed. It's replaced with concrete assertions: a POSIX-style .exe path (/opt/tools/claude.exe) that exercises the basename-then-strip logic deterministically on every OS (allowed), a matching rejection for a non-allowlisted .exe (/opt/tools/bash.exe), and a per-platform assertion for the real backslash form that expects true on win32 and false on POSIX (where path.basename doesn't split backslashes). Both new assertions were verified to fail against a broken implementation (dropping the .exe strip; forcing win32 basename on POSIX). Test-only change — no runtime behavior change.
  • [issue-2536] Catch unhandled rejections from Telegram handlers and health/probe timers. Several async boundaries were fire-and-forget: the Telegram client dispatched onText/emitter.on handlers without awaiting or catching, telegram.js ran setInterval(healthCheck) and a couple of sync-context bot.sendMessage(...) calls without a .catch, and instances.js scheduled probeAllPeers() from setTimeout/setInterval without one — so a rejected handler or a failed fs/network read leaked an unhandled promise rejection (process-killing on Node ≥15). The client now routes every handler invocation through a runHandler wrapper that logs a single emoji-prefixed line on rejection; the health-check interval and both probe timers wrap their async callback in .catch; and the /start, /help, and unauthorized-notice sends now await or .catch their promise. A vitest suite drives the client's onText and message paths with a throwing handler and asserts no unhandledRejection escapes.
  • [issue-2519] CoS handlers no longer flash a false-success toast after a failed API call. Several Chief of Staff actions (handleForceEvaluate on the CoS page, the Tasks tab "Run Now" button, and the Config tab's Save + autonomy-level change) .catch-swallowed the request rejection and then unconditionally toasted success and mutated optimistic UI — so a network/server error still read as "done." Each now awaits inside try/catch and only toasts success / advances state after the request resolves: a failed Save keeps the editor open, and a failed autonomy-level change reverts the optimistic form params. Errors surface via a single toast.error (the calls already pass { silent: true }).
  • [issue-2520] Pass { silent: true } on client API calls that own a custom error toast. Several call sites routed a request through the auto-toasting request() helper AND showed their own toast.error in .catch, so a failure surfaced two stacked toasts. The music managers (Artists/Albums/Tracks load + create/update/delete), MusicVideo (list/create/delete/analyze/plan/add-scene/delete-scene/reorder), and DataDog (load/save/delete/test) now pass { silent: true } on those calls; CharacterSheet's local charGet/charPost/charPut helpers are silent-by-default (every caller owns its own catch toast or the loadError banner) with an opt-out. Each failing action now shows a single toast.
  • [issue-2510] MidiPianoRoll: clear the stale hover overlay when the transcription data changes. The piano-roll kept its hovered note/chord identity (objects from the previous parse) when the data/chords props swapped on a mounted instance, so a re-transcription or Retry while a hover was active and the pointer sat still would keep stroking the old note at coordinates mapped into the new file until the next pointer move or Escape. A useEffect now drops the hover identity whenever data/chords change.
  • [issue-2513] Block loopback/metadata hosts in Layered Intelligence custom http sources. fetchHttpSource used a bare fetch with only an http(s) scheme check, so a hand-edited config could point a custom source at 127.0.0.1, 169.254.169.254, or metadata.google.internal and exfiltrate up to 8KB into the reasoner prompt. It now routes through the shared SSRF-guarded fetchPublicText (default posture): loopback, link-local, and cloud-metadata hosts are blocked and redirects are revalidated, while LAN/Tailscale hosts stay intentionally allowed for this single-user tool.
  • [issue-2516] Database sync: remove shell interpolation from the dump import. The active→inactive backend sync built a bash -c "sed … \"${dumpFile}\" | psql … -U ${pgUser} -d ${pgDb}" string that interpolated the dump path, port, user, and database name into a shell command — any shell metacharacter in those values (env-derived or surfacing from the export pipeline) was injectable into psql. The import now streams the dump through spawn('psql', argv) with no shell: the dump is read and piped to psql's stdin, and the pg17-only directives (\restrict/\unrestrict/SET transaction_timeout) the old sed stage stripped are filtered in-process. No user- or env-derived value ever reaches a shell string.

Changed

  • [issue-2528] Collapse the pipeline per-key createFileWriteQueue factory into one helper (DRY). Five pipeline stage stores (editorialScore.js, reverseOutline.js, perspectiveRewrite.js, manuscriptReview.js, continuityBible.js) each hand-rolled the same const map = new Map(); if (!map.get(key)) map.set(key, createFileWriteQueue()) get-or-create factory to serialize per-series/per-issue writes against a shared JSON state file. Each now uses a new createKeyedFileWriteQueue() in server/lib/fileWriteQueue.js, a thin wrapper over the already-existing self-pruning createKeyCachedQueue — so the tail Map no longer grows unbounded (idle keys evict on settle) and the five copies collapse to one line apiece. Key normalization (falsy/non-string → shared '__unknown__' tail) and observable write ordering are unchanged; all existing stage suites stay green.

  • [issue-2529] Split the universeBuilder.js god-module into focused sibling modules behind a thin barrel. The ~2000-line server/services/universeBuilder.js (50+ exports mixing sanitizers, CRUD, peer-sync, and prompt compilation) was split along its natural seams into universeBuilder/sanitize.js (constants + record-shape sanitizers), universeBuilder/storeFacade.js (shared synchronous store getter), universeBuilder/crud.js (read/list/get, create/update/delete, runs, render-history mutations), universeBuilder/sync.js (peer-sync merge + tombstone GC), and universeBuilder/compile.js (prompt compilation). The original path is now a 20-line barrel that re-exports the full public surface, so all 94 existing importers keep working unchanged. Pure structural refactor — no behavior change; every existing suite (including the DB-backed tests) stays green. The catalogDB.js split is tracked as remaining work under the same issue.

  • [issue-2529] Split the catalogDB.js god-module into focused sibling modules behind a thin barrel. The ~1900-line server/services/catalogDB.js (65 exports mixing row-mappers, scrap/ingredient/tag/media CRUD, refs & relations, peer-sync, and export/facets) was split along its natural seams into catalogDB/shared.js (row→object mappers, id-minters, the bible-payload sanitizer, revision constants, and the cross-seam HOMING SQL fragments — the acyclic leaf), catalogDB/scraps.js (scrap CRUD + chunking), catalogDB/ingredients.js (ingredient CRUD, revisions, FTS/vector/hybrid search), catalogDB/refs.js (source links, external refs, relations, role maps), catalogDB/media.js (media attachments + integrity surface), catalogDB/tags.js (tag taxonomy/normalization), catalogDB/sync.js (peer-sync change feeds + upserts), and catalogDB/facets.js (export slice / sync bundle / stats / facets). The original path is now a thin barrel that re-exports the identical 65-export public surface, so all existing importers keep working unchanged. Module graph is acyclic (shared ← every seam; ingredients ← tags; facets ← {refs, media}). Pure structural refactor — no behavior change; the full server suite stays green.

  • [issue-2524] Route per-key write tails through the shared createKeyCachedQueue helper (DRY). Five modules each hand-rolled the same Map + prev.then(fn, fn) + .catch-silence + self-pruning tail to serialize read-modify-write cycles per key: pipeline/issues.js (per-series), loraTraining/db.js (per-run), instances.js (per-peer reciprocal sync), worktreeManager.js (per-repo worktree create), and collectionStore.js (per-record). Each now delegates to server/lib/createKeyCachedQueue.js, and fileWriteQueue.js's id-keyed createRecordWriteQueue (already used by the pipeline series/issues and story-builder store facades) is now a thin validator wrapper over the same helper, so all per-key write serialization funnels through one implementation. collectionStore.js's single-tail type-index queue likewise reuses createFileWriteQueue. Each site keeps its own key derivation (series-id normalization, macOS realpath resolution) and the fixed reciprocal-sync work body; silence/eviction semantics and observable write ordering are unchanged, and existing write-order tests still pass.

  • [issue-2523] Extract a shared createPgFileFacade backbone for the six PG/file store dispatchers. The pipeline series/issues, story-builder, universe-builder, catalog-user-types, and writers-room stores each re-implemented the same three pieces: the isFileBackend() escape-hatch predicate, the promise-memoized lazy backend selection (so concurrent first calls don't run the migration twice), and the PG bring-up sequence (health-check → ensureSchema → one-time file→DB migration → import the leaf-I/O db.js). Those now live once in server/lib/pgFileFacade.js as isFileBackend(), resolvePgBackend({ requirement, migrate?, loadDb, makePg }), and createPgFileFacade({ makeFile, makePg }); the two inline write-queue copies (createFileWriteQueue's id-keyed sibling createRecordWriteQueue) were folded into server/lib/fileWriteQueue.js. Each store keeps its own genuinely-different makeFile/makePg factories and public surface; behavior is preserved on both the PostgreSQL and file/test backends. New unit tests cover the shared helpers.

  • [issue-2526] Reuse shared helpers instead of local reimplementations (DRY). Swapped duplicated one-off implementations for their existing server/lib counterparts: sleep (youtubeSync.js, pipeline/seriesAutopilot.js) and pathExists (localLlm.js) now import from fileUtils.js; database.js's inline color-only stripAnsi uses the shared ansiStrip.js (full ANSI/control stripper); systemHealth.js's byte formatter and huggingFaceCatalog.js's (via a thin wrapper that preserves its null-on-unknown-size fallback contract) now delegate to fileUtils.formatBytes; and the two hand-rolled SSE header blocks now use the canonical SSE_HEADERS — ask.js keeps its extra no-transform directive on top of the shared set, and mediaJobQueue's terminal-event path gains the previously-missing X-Accel-Buffering: no so it matches the live-stream path.

  • [issue-2521] Validate the remaining ad-hoc route bodies with Zod validateRequest. The ports (/check, /allocate), database (switch/start/stop/destroy/export), brain digest/review run, telegram (method/config/test/forward-types), and AI-toolkit provider (POST/PUT/PUT active) routes parsed req.body with hand-rolled Array.isArray/includes checks. Each now has a named Zod schema (PortOS schemas in lib/validation.js, brain schema in brainValidation.js, provider schemas in aiToolkit/validation.js) wired through validateRequest, so invalid bodies return a consistent 400 VALIDATION_ERROR with per-field context.details instead of ad-hoc messages. Port numbers are range-checked (and count coercion no longer silently accepts booleans/arrays), backend/target values are enum-checked, and provider create/update reuse the canonical providerSchema (.partial() on update). As part of wiring PUT /api/providers/active, the toolkit providers map is now null-prototyped on load so a crafted id (__proto__, constructor, toString) can no longer resolve an inherited Object.prototype member as an existing provider and be persisted as the active one.

  • [issue-2525] Extract shared migrationMarker helpers using atomicWrite. Eleven boot-time migration/repair/reconcile scripts under server/scripts/ each hand-rolled markerExists/readMarker/writeMarker on top of readFile(...).catch(() => null) and a non-atomic writeFile(JSON.stringify(...)), so a crash mid-write could leave a truncated marker a later boot misreads as "not applied." The three helpers now live once in server/lib/migrationMarker.js (anchored under PATHS.data, built on the existing tryReadFile/atomicWrite/safeJSONParse), are barrel- and README-cataloged, and carry their own unit test. Marker filenames, gate semantics, and payloads are unchanged; the write path is now atomic (temp file + rename).

  • [issue-2522] Deep-link Tribe tabs and fix form label associations. The Tribe page's active section (Circle / Map / Care Queue / Focus) lived in local useState, so a section couldn't be shared, bookmarked, or survive a reload. It now reads from a ?tab= URL search param (default circle omitted for a clean /tribe) with a valid-tab fallback for stale/unknown values — matching the PromptManager convention. Separately, the StylePresetPicker style-preset <label> and the Loops "Interval" <label> had no htmlFor/id pairing; both now associate with their control via a useId()-generated id so click-to-focus and screen readers work.

  • [issue-2527] Route client localStorage and keyboard activation through the shared safeStorage/a11yKeyboard helpers. Several client sites bypassed the guarded safeStorage helpers with raw window.localStorage + hand-rolled try/catch (or typeof window guards), and several non-<button> clickables reimplemented the Enter/Space onKeyDown handler inline. Storage reads/writes in Security.jsx, PipelineManuscriptEditor.jsx, voiceVisibility.js, MortalLoomBanner.jsx, WhileAwayWidget.jsx, and ManuscriptReadAloud.jsx now go through safeReadStorage/safeReadJsonStorage/safeWriteStorage/safeRemoveStorage; keyboard activation in IngredientPicker.jsx, ManuscriptReadAloud.jsx, EditorialHealthPanel.jsx, TribeCircleMap.jsx, and GenomeTab.jsx now spreads clickableProps(handler) (which supplies role/tabIndex/onKeyDown via the shared onActivateKeyDown). Behavior is preserved — same storage keys, same JSON-parse fallbacks and corrupt-entry cleanup, same Enter/Space activation.

  • [issue-2532] Extract the Universe Builder's page-level lightbox into a useUniverseGallery hook. UniverseBuilder.jsx inlined ~160 lines of gallery/preview plumbing — the filename→image-sidecar metadata map, the listImageGallery() refetch effect (keyed on runs.length + a per-job-completion bump), the previewItems derivation across variations/composite sheets/style probes/canon+character-sheet refs (namespaced-key dedupe), and the usePreviewRoute/useMediaPreviewActions/useMediaAnnotations wiring. That cohesive concern now lives in client/src/hooks/useUniverseGallery.js (takes { draft, runsLength }, returns { previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }), thinning the page shell toward the WritersRoom pattern. Pure structural refactor — behavior identical, no route-contract change; the UniverseBuilder page suite and hooks barrel test stay green. Further hook/panel extractions (draft/expand/canon/bulk-render for UniverseBuilder, useShellSession for Shell) remain.

  • [issue-2545] Add aria-labels to icon-only controls and fix Templates/MessageDetail form labels. Several icon-only buttons exposed their purpose only via title (unreliable for screen readers): the MessageDetail toolbar (Reply, voice-mode toggle, AI Reply, Refresh, Archive, Delete), MusicVideo scene move-up/move-down/delete, MediaCard hide/delete, the MediaJobsQueue per-job cancel, Review's edit save/cancel, and DuplicateGroup rename now carry an aria-label matching their title. The MessageDetail reply <textarea> (previously placeholder-only) gains an aria-label, and the Templates "Target Directory" <label> is now wired to its input via htmlFor/id so click-to-focus and screen readers work. Accessibility attributes only — no behavior or styling change.

  • [issue-2542] Fix VideoGen busy-retry timer cleanup and FeatureAgentDetail load race. The VideoGen queue worker's BUSY-backoff setTimeout was a local let busyRetryTimer assigned inside an async .catch, so the effect's own cleanup (consumed on every setQueue/setRunningQueueId re-run before the timer was ever assigned) couldn't clear it — an unmount during the 1.5s backoff, or a newer dispatch, could still fire setRunningQueueId on a torn-down component or steal a slot a newer item owned. The timer now lives on a useRef, is cleared by a dedicated unmount cleanup, and every deferred then/catch/finally (and the timer callback) is gated by a per-dispatch generation token plus a mountedRef so stale callbacks bail. Separately, FeatureAgentDetail's getFeatureAgent(id) load had no stale guard, so an A→B navigation whose A response resolved late could paint the wrong agent; the load is now sequence-tokened (late/stale results ignored) with a mountedRef guard, and an A→B switch clears to the spinner immediately instead of flashing the previous agent.

  • [issue-2533] Extract JIRA-ticket claim assembly out of the route into buildJiraTicketTask (next to buildClaimWorkTask). POST /api/cos/tasks/jira-ticket (the sprint-board per-card play button) inlined its reviewer-CSV resolution (resolveClaimReviewersCsv), the target-ticket constraint block (buildTargetTicketBlock), and the claim-issue-jira prompt assembly directly in server/routes/cosTaskRoutes.js. That logic now lives in server/services/cosTaskGenerator.js as an exported buildJiraTicketTask(app, ticketKey) that returns { ticketKey, prompt, taskMetadata } — beside buildClaimWorkTask, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, and useWorktree/openPR posture are byte-for-byte unchanged; new unit tests cover the extracted assembly.

  • [issue-2539] Serialize createCachedStore and backup.saveState writes; bound the rate-limit state maps. createCachedStore now runs every write through an internal single-tail createFileWriteQueue and exposes a mutate(fn) primitive that serializes the whole load → modify → persist cycle, so two concurrent read-modify-write paths can no longer clobber each other; the feeds, social-accounts, platform-accounts, agent-personalities, and automation-scheduler services were migrated off the racy load() + save() pair onto mutate(). backup.saveState gained the same promise-tail so a run completing while the scheduler stamps a status can't lose fields. The moltbook/moltworld rate-limiters, which kept one in-memory state entry per API key / agent id forever, now store it in a new bounded createBoundedStateMap({ maxSize, ttlMs }) helper (server/lib/boundedStateMap.js) that lazily evicts idle (TTL) and least-recently-used (LRU) entries. (The idle pipeline writeQueues pruning called for by the issue already shipped via createKeyedFileWriteQueue/createKeyCachedQueue in #2528/#2524.) Behavior is otherwise unchanged; new unit tests cover the serialized mutate, the bounded map, and the rate-limiter.

  • Fix the DevTools → Usage page crashing with "(providers || []).map/filter is not a function". services/providers.getAllProviders() returns the wrapped { activeProvider, providers } object, but routes/usage.js (GET /api/usage) and services/providerUsage.js#getProviderQuotas (GET /api/usage/providers) passed that object straight into .map/.filter, throwing on every request so the Usage page showed "Couldn't read provider usage." / "No usage data available." Both call sites now unwrap .providers via the Array.isArray(result) ? result : (result?.providers || []) pattern already used in jiraReports.js/loops.js. The two test suites mocked getAllProviders as a bare array (masking the bug); their mocks now return the real object shape, plus a new getProviderQuotas regression test asserts the unwrap.

  • [issue-2598] Add Antigravity + Grok subscription-usage adapters via headless TUI /usage scrape. DevTools → Usage previously showed "not available" placeholders for the agy (Antigravity) and grok (Grok Build) provider families, because neither CLI exposes quota in non-interactive --print mode (there /usage is treated as an LLM prompt — wrong data, and it burns tokens). Their real usage surface is an interactive slash command (/usage for agy, /usage show for grok), so a new server/lib/tuiUsageScrape.js#scrapeTuiUsage drives the TUI in a sandbox PTY (a fixed dir under the OS temp dir — never the user's project — trusted once via a primer Enter, output-idle-gated capture, hard-timeout backstop), and providerUsage.js parses the rendered panel into the common quota shape. Antigravity reports one card per model group (e.g. Gemini, Claude/GPT) with weekly + 5-hour meters and reset times, treating its bar percentage as remaining; Grok reports a single weekly meter treating Weekly limit: N% as used. Both scrapes are 0-token (the slash command renders synchronously, no LLM turn), user-triggered only, and cached 5 min with single-flight (each scrape costs ~12s). Parse failures degrade to a soft "no quota data" warning card rather than erroring the page. New unit tests cover both parsers, the relative-reset→ISO conversion, and the fetch/cache wiring.

  • [issue-2532] Extract the Shell page's socket/session/terminal lifecycle into a useShellSession hook. pages/Shell.jsx inlined ~750 lines of xterm setup, the Socket.IO shell:* protocol, and the single-subscriber PTY attach/detach contract (the pendingAttachRef {target,generation} guards, claim-vs-user-intent handling, userIdleRef passive-idle gating, mountedRef deferred-work guards, and URL sync). That cohesive concern now lives in client/src/hooks/useShellSession.js — which documents the full attach/detach contract at the top of the file — and the route drops to a thin presentational shell (header, quick-commands, terminal container) plus two extracted panels, components/shell/TerminalHotKeys.jsx and components/shell/ShellSessionTabs.jsx. Pure structural refactor toward the WritersRoom pattern — behavior identical, generation guards preserved byte-for-byte, no route-contract change; lint, the hooks barrel test, and the client build stay green.

  • [issue-2580] Await the canvas draw assertions in MidiVisualization.test.jsx to fix a CI flake. The "paints the roll" test awaited the footer text (findByText(/3 notes · /)) then synchronously asserted expect(ctx.fill).toHaveBeenCalled(), but the roll paints in the <MidiPianoRoll> child a tick after the footer text commits — so CI intermittently landed the paint one tick late and the assertion failed. That draw assertion (and the zoom-controls ctx.clearRect assertion, which followed the fit/zoom button clicks) are now wrapped in waitFor(...) so they wait for the draw deterministically. Audited the sibling songs canvas tests (PianoRoll, MidiPianoRoll, Metronome, RoundStack, PitchTuner, SingToScore, SongTraining, ReferenceAnalysis, SongRecordings): only MidiVisualization gates its paint behind async data loading, so it was the only racy one — PianoRoll/MidiPianoRoll assert after a synchronous render()/pump() (no text-findBy gap), and the rest have no canvas assertions. Test-only; each test keeps its own explicit getContext mock.

  • [issue-2541] Add a wall-clock timeout to the AI toolkit's API runner so a hung provider can't leak activeRuns. runner.js#executeApiRun attached an AbortController but armed no timer, so an upstream that opened the SSE stream then stalled (or never responded) held its controller in activeRuns — and thus the run slot — indefinitely; the CLI path (executeCliRun) already had an internal timeout, and the Runs-router path invoked the API runner with no outer guard. executeApiRun now accepts an optional timeout (falling back to provider.timeout then a 300s default, mirroring aiProvider/askService) and arms it before the fetch. A single-settlement gate (markSettled()) guarantees exactly one of {timer, response paths} finalizes the run: on timeout the timer aborts the fetch/reader AND independently finalizes the run as an ERROR_CATEGORIES.TIMEOUT failure — so a stalled fetch/stream, a provider that never responds, and even a ensureProviderReady hook that never reaches the fetch are all bounded, and the failure is recorded as a timeout instead of the raw AbortError's UNKNOWN/HTTP 0. Both the Runs router and promptRunner now thread their effectiveTimeout into the API call (parity with the CLI/TUI branches), so a per-call override — e.g. the importer's long stage timeout — governs the ceiling instead of being cut short by the provider/default fallback; promptRunner's own timer is demoted to a delayed backstop so the runner's timeout wins classification. The non-2xx error-body read now runs with the abort timer still armed (a provider that sends error headers then stalls the body is cancelled, not hung), and the success-path finalization-failure fallback rebuilds metadata from the stored record so run identity survives a write error. New unit tests prove both a hung stream and a hung readiness hook flip isRunActive back to false and complete with errorCategory: 'timeout'.

  • [issue-2533] Split the ~990-line server/routes/digital-twin.js flat router into a digital-twin/ sub-router directory (mirroring the apps/pipeline layout). The single multi-domain file is now an assembled index.js mounting thirteen domain sub-routers at the same /api/digital-twin base — status, documents, tests (behavioral/values-alignment/adversarial/multi-turn suites + generate), enrichment, export, settings, personas, analysis (validate/writing-style/identity-image/traits/confidence/gaps/assessment), import, feedback, taste, snapshots, and evidence — with the shared assertPersonaExists guard extracted to digital-twin/shared.js. The route contract is byte-for-byte unchanged: all 73 endpoints keep their exact method+path, Zod validation, and ServerError status mapping, and the order-sensitive pairs (/personas/active before /personas/:id; /taste/sections before /taste/:section/...) each live entirely within one file so mount order is irrelevant. The route test moved into the directory as digital-twin/index.test.js (21 cases green). Completes the last remaining slice of #2533 (the imageGen setup, apps-list enrichment, and buildJiraTicketTask extractions shipped earlier in #2600/#2589).

  • [issue-2553] Size four viewport-height surfaces with 100dvh (vh fallback) so iOS Safari chrome no longer clips them. MediaLightbox's fullscreen image (max-h-[100vh]), the CollectionPicker popover (min(360px, calc(100vh - 16px))), the Layout sidebar flyout (calc(100vh - 16px)), and the ChiefOfStaff avatar panel/canvas caps (min(460px|620px, calc(100vh - 1rem))) all measured against 100vh, which iOS Safari inflates by the retractable browser-chrome height — so each spilled under the chrome. New parametrized max-h-dvh-cap/min-h-dvh-cap/h-dvh-cap @utility classes in index.css size to 100dvh (the visible dynamic viewport) with a 100vh fallback gated behind @supports (height: 1dvh) — the two-declaration idiom .h-dvh-screen uses does not work once the value is wrapped in var()/min()/calc() (both declarations become valid-at-parse-time, so the dvh one wins the cascade then computes to invalid rather than restoring the vh line), so the vh value is the unconditional base and the dvh value overrides only where supported. A --dvh-cap upper bound and --dvh-inset subtracted margin (set per-surface, and per-breakpoint via arbitrary-property utilities for the responsive CoS caps) let one utility serve the plain, capped, and inset variants; the CoS panel keeps its fixed min-h-[180px]/190px at base/sm/md and only switches to the dvh cap at lg:/xl:, where the original used a viewport unit. Behavior is byte-identical on engines that predate dvh; on iOS Safari the surfaces now stay within the visible viewport.

  • [issue-2548] Replace the vacuous agentLifecycle spawn/completion replica tests with imports of real guard helpers. agentLifecycle.test.js re-implemented production logic — local unfixedSpawn/fixedSpawn copies of the spawningTasks dedup flow and a runCompletion/makeCompletionHarness copy of the completion try/finally — and never imported spawnAgentForTask/handleAgentCompletion, so they stayed green when production regressed. The two concurrency contracts those replicas modelled are now extracted into server/services/agentGuards.js: withSpawnDedupGuard(spawningTasks, taskId, fn) (acquire-before-first-await, hold across the whole spawn body incl. the runner-enqueue handoff, release in finally, SPAWN_DEDUP_SKIP on a concurrent duplicate) and withMapEntryCleanup(map, key, fn) (delete the runnerAgents entry in finally even when a completion step throws). spawnAgentForTask now wraps runAgentSpawn in the former (dropping six inline spawningTasks.delete sites), and handleAgentCompletion wraps its body in the latter — so the tests drive the exact code production runs. The late-delete race that spawned a second agent for the same task id is now a behavioral test against the real guard, not a hand-copied one; the remaining source-scan tests were trimmed to non-negotiable orderings (the handedOff pre-spawn/post-handoff split, the #1563 claim/register ordering, the #989 marker release, the #2243 runner env merge) plus two wiring guards that pin the delegation. cos.test.js already drove the real createDequeueCapacity/isMissionTierEligible/isIdleTierEligible exports after #2530, so it was left as-is. New agentGuards.test.js unit-tests both helpers in isolation.

  • [issue-2554] Align CoS chrome and scrollbar colors with port design tokens. The Chief of Staff panel chrome hardcoded bg-slate-900/60, hover:bg-slate-800/80, the from-slate-900/80 to-slate-900/40 gradients, and text-slate-400 — a slate surface that ignored the active theme. Those now map to bg-port-card/hover:bg-port-border/text-port-text-muted (the collapse button's text-gray-500 hover:text-white also became text-port-text-muted hover:text-port-text so its icon stays legible in light themes), so the panel restyles with the selected theme. The global ::-webkit-scrollbar-thumb (and its :hover) dropped their hardcoded #3a3a3a/#4a4a4a for the opaque, theme-derived rgb(var(--port-text-muted)) and rgb(var(--port-text)) — colors that stay high-contrast against the already-tokenized rgb(var(--port-card)) track in both dark and light themes (an alpha-over-track blend would wash out on light cards, so the opaque muted-text token is used). The unread-count badges in Layout.jsx (four sites) and NotificationDropdown.jsx swapped bg-yellow-500 text-black for bg-port-warning text-port-on-warning; the Dashboard server-health glow's shadow-[0_0_8px_#22c55e]/#ef4444 now reference rgb(var(--port-success))/rgb(var(--port-error)). The Ambient full-screen idle display is intentionally left on its fixed deep-black bg-[#050505] (with text-white content) — it is a theme-independent ambient/OLED surface, and making the backdrop theme-following would strand its non-tokenized white clock and translucent panels invisibly on light themes. Visual-only token swaps — no logic or layout change; the retokenized surfaces now follow the active theme instead of a fixed palette.

  • [issue-2626] Raise bg-port-warning / text-port-on-warning contrast to WCAG AA in day themes. Two mode: 'day' themes paired an amber --port-warning with white --port-on-warning, dropping the ~180 warning surfaces (buttons, chips, unread-count badges) below the 4.5:1 AA threshold for small text — lumen-glass-day (#ca8a04 on white ≈ 2.94:1) and black-ice-terminal-day (#aa6e00 on white ≈ 4.25:1). Both now use black --port-on-warning at the theme-token layer (0 0 0), lifting them to ~7.15:1 and ~4.94:1 respectively; the other two amber day themes (classic-noon, blueprint-ops-day) already cleared AA at ~5.02:1 on white and were left unchanged. A new client/src/themes/portosThemes.test.js computes the WCAG contrast ratio for the warning pair of every theme and asserts ≥4.5:1, so a future theme can't regress the pairing.

  • [issue-2616] Add type-level consecutive-failure backoff with auto-park + notification; count unparseable agent output as failure. The agent engine had no failure memory at the task-type level, so a permanently-broken scheduled type (or one whose instances all fail) re-queued on schedule forever — burning provider quota with no backoff, auto-disable, or notification (failureCount lived only in per-instance metadata; ROTATION types had no cadence gate at all, returning shouldRun: true unconditionally). A new per-type failure ledger now lives on the schedule execution record (consecutiveFailures/lastFailureAt/lastErrorCategory, per app + global) — persisted alongside lastRun, so it survives restarts as per-install runtime state (additive, backward-compatible, never synced). shouldRunTask applies an escalating failure cooldown (2^n × base, capped at a day) to all cadence types including ROTATION, so a failing type slows down instead of re-queuing every tick; after 5 consecutive failures the type auto-parks (indefinitely, for every cadence type) and fires a user-facing AGENT_WARNING notification naming the type, app, and last error category. A success resets the counter and lifts the park; a manual "Run now" or a config change (updateTaskInterval) clears the ledger to unpark. Separately, an LLM run that exits 0 but whose .agent-done output is unparseable — previously recorded as a benign completed success, invisible to any failure accounting — now feeds a failure signal into the ledger via the pure resolveTypeFailureSignal (an unparseable-response hook reason, or a thrown output hook, counts as a failure regardless of exit code; benign hook reasons like no-proposal/duplicate defer to the exit code). The existing per-instance retry ladder (MAX_TASK_RETRIES/MAX_TOTAL_SPAWNS) is unchanged. New unit tests cover the backoff math, ledger increment/reset/auto-park/notify/unpark, the ROTATION cooldown/park gates, and the unparseable-as-failure decision.

  • [issue-2535] Paginate the creative-catalog + media list endpoints with the shared paginateArray helper. The primary index GETs for creativeDirector (/), storyBuilder (/), universeBuilder (/), moodBoard (/), videoTimeline (/projects), and loras (/) returned unbounded arrays. Each now opts into pagination the moment a client sends limit/offset, mirroring the brainCrud precedent: isPaginationRequested(req.query) gates a bounded { items, total, limit, offset } envelope (via the existing paginateArray in server/lib/validation.js, defaultLimit: 50, maxLimit: 500), while a request with no pagination params still returns the full array byte-for-byte — so every current client (none of which pass those params to these routes) is unaffected and no client change is required. New route tests assert both the default array and the paginated envelope for each domain (moodBoard gains its first route test). Refs #2535 — CoS tasks (the ?full=1 default-paginated slice) already shipped; privacy vault/orgs/changes/brokers and digital-twin documents remain.

  • [issue-2535] Paginate the remaining privacy + digital-twin list endpoints, completing the sweep. The last unbounded index GETs flagged by #2535 — privacy /vault, /orgs, /changes, /brokers, /broker-cases, and digital-twin /documents — now opt into the shared paginateArray envelope exactly like the creative-catalog routes shipped in #2636: isPaginationRequested(req.query) gates a bounded { items, total, limit, offset } response (defaultLimit: 50, maxLimit: 500) the moment a client passes limit/offset, while a param-less request returns the full array byte-for-byte, so no client change is required. Because the four privacy list-query schemas are .strict() (they'd reject unknown keys), a local paginationQueryFields fragment (limit/offset as passthrough strings — parsePagination does the parse+clamp) is spread into privacyVaultListQuerySchema, privacyOrgListQuerySchema, privacyBrokerListQuerySchema, and privacyBrokerCaseListQuerySchema in privacyValidation.js; the /orgs handler strips limit/offset before passing filters to listOrgs so pagination never leaks into the service query. New route tests cover the vault/orgs/changes/broker-cases envelopes (filters preserved) and the digital-twin documents envelope. This closes the remaining slice of #2535 (the CoS-tasks default-paginated shape and the creative-catalog/media routes shipped previously).

  • [issue-2642] Require provider/runner provenance before excluding environmental failures from task learning. Environmental-failure exclusion previously trusted errorAnalysis.category alone, but that category is produced by the analyzeAgentFailure regex sweep over the failed agent's output tail — so ordinary task output could be misclassified as an infra category (e.g. a failing test whose tail prints "rate limit" tripping the unscoped /rate.?limit/) and the run would be silently diverted out of the learning aggregates as an "outage." analyzeAgentFailure now stamps an origin provenance marker on every classification: 'provider'/'runner' when the match carries a genuine structured signal (an API Error: NNN line, a Node error code like ECONNREFUSED, a provider token like overloaded_error/not_found_error, or the structural startup-failure), and 'output-scan' when it comes only from a loose keyword alternative. Mixed patterns (e.g. API Error: 429 vs a bare rate limit) gate the promotion through a per-pattern structuredMarker sub-pattern via the new pure resolvePatternOrigin helper. The exclusion gate in recordTaskCompletion (server/services/taskLearning/metrics.js) now runs through a pure shouldDivertToEnvironmental(outcomeSuccess, category, origin) that additionally requires origin !== 'output-scan', so an output-scan false positive counts as a genuine failure while structured signals stay excluded. Back-compat is preserved: an errorAnalysis with no origin (older records / federated peers) keeps the category-only behavior, and the routing-side signature filter is unchanged (it already fails safe). New unit tests cover the provenance stamping across the classifiers and all three acceptance cases in the gate.

  • [issue-2532] Finish thinning the Universe Builder route into focused feature lifecycles. pages/UniverseBuilder.jsx is now a 9-line compatibility shell over the presentational editor, while draft hydration/persistence and canon-safe merges live in useUniverseDraft, AI expansion/refinement lives in useUniverseExpand, and bulk-render configuration plus per-entry job queues live in useUniverseRender. The existing Bible/Cast/Places/Objects panels moved out of the route module with their behavior and named exports preserved. New hook tests cover hydration, dirty saves, deletion-wins canon merges, locked expansion rows, all-trunk render selection, and backend guards; the full client suite remains green.

  • SongBook — a Brain repertoire for guitar tabs, chord sheets, and sheet music with learning-stage tracking and an autoscrolling play view. New /songbook index (filter by stage/instrument/tag/search, all URL-addressable) and /songbook/:id full-bleed viewer: tab/chord/ChordPro content renders with highlighted chord tokens, section headers, and horizontally-scrollable tab staffs; an Ultimate-Guitar-style autoscroll (play/pause, speed slider, keyboard shortcuts, screen wake-lock) paces long charts, with non-destructive transpose and font-size controls persisted per song. Each song tracks a learning stage (new → learning → learned → memorized) flippable from the card or viewer. Songs import by paste (auto-cleanup of HTML remnants + format detection) or by URL — a server-side SSRF-guarded fetch with an Ultimate Guitar extractor and generic <pre>/plain-text fallbacks returns an editable draft, never auto-saving. Sheet-music/MIDI/image attachments upload per song: metadata (name, size, SHA-256) lives in the synced record while bytes stay machine-local under data/brain/songbook/ (peers show "not on this machine"). Songs are a first-class Brain entity type (data/brain/songs.json), so they federate across machines with LWW sync, tombstone deletes, and reconcile coverage automatically — and they're reachable from ⌘K and voice nav (nav.brain.songbook). New pure tabNotation lib (line classification, ChordPro, transpose with column preservation, paste normalization) with extensive unit tests. Ships three public-domain seed songs — "House of the Rising Sun" arranged for guitar, piano, and ukulele — seeded into existing installs by migration 190 (never overwriting a user-edited, synced, or deleted copy). The parser also handles dash-joined chord changes (Am-Am7 classifies, renders, and transposes as one token) and Unicode accidentals (♯/♭ normalize to #/b on paste so F♯m transposes correctly).

  • Fix the app-manager Git tab's "Clean N merged" button counting worktree-locked branches, so cleanup deleted zero and toasted "No merged branches to clean up". getBranches marked a local branch merged: true from git branch --merged alone, but deleteMergedBranches (correctly) skips branches checked out in a worktree — git branch -d can't delete them. On any install with active CoS-agent/claim worktrees, those merged-but-locked branches inflated the button's count while yielding no deletions. getBranches now also returns a worktree flag (branch checked out in another worktree), the Git tab's localMergedCount counts only merged && !worktree so the button reflects what the server will actually delete, and locked branches render a worktree badge next to merged so the user sees why they linger. Server + client tests cover the count and badge.

  • [issue-2654] Lift the CoS actionable-insights fetch into ChiefOfStaff.fetchData so the banner refreshes for the whole staleness class. ActionableInsightsBanner owned its own /cos/actionable-insights fetch on a 60s useAutoRefetch poll, decoupled from the parent's 30s task poll, so its server-derived counts (blocked, approvals, "N health issues") lagged any parent-owned data change until that poll. A prior fix bridged only the TasksTab mutation path via an insightsRefreshKey counter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched inside ChiefOfStaff.fetchData's Promise.all and passed down as an insights prop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path calls onRefresh up instead of owning a refetch(). The banner's counts refresh only through fetchData: the 30s poll, task mutations (TasksTab onRefresh), the unblock-up path, and agent spawn/completion (which already call fetchData). There is deliberately no on-demand "refresh just the insights" path, because /cos/actionable-insights runs a health check that auto-restarts errored PM2 processes (server/services/cosHealthMonitor.js) and re-emits cos:health:check — so refreshing from the cos:health:check socket handler would loop, and refreshing from the manual "Run Check" button would fire a second process-restart ~1s after the button's own check. Daemon/manual health changes therefore refresh the banner on the next fetchData poll (a 2× improvement over the retired 60s self-poll, and the cadence skew is gone). A failed/transient insights fetch (null) preserves the last-good array; a legitimately-empty [] clears the banner. Because that same insights call triggers a fresh server health check whose cos:health:check socket emit can land before fetchData's own (pre-check) getCosHealth read resolves, fetchData keeps whichever health check is newer by lastCheck (Date.parse-normalized), and preserves the last-good health when its own read fails — instead of blanking a fresher socket-delivered result. Retires insightsRefreshKey, refreshTasks's signal bump, the banner's refreshKey prop, its didMountRef skip-mount effect, and its useAutoRefetch self-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, guards asserting neither the cos:health:check socket handler nor the manual button re-fetches insights (no loop, no second restart), and the stale/failed-read health-overwrite guards.

  • Fix Element Flash: pressing Enter/Return after answering now advances to the next question. In the Element Flash recall test (ElementsSong.jsx), the Enter-to-submit handler lived only on the answer <input>, which unmounts once the result is shown — so a second Enter did nothing and the user had to click "Next" to continue. ElementFlashMode now binds a window keydown listener while a result is showing (input unmounted) that advances on Enter/Return, mirroring the "Next" button; the next() handler was hoisted above the completion early-return so the effect can reference it without breaking hook order. The listener ignores auto-repeat (e.repeat) and any Enter that a focused control or open overlay already owns (e.target.closest('button, a, input, textarea, select, [role="dialog"], [role="menu"], [contenteditable]')) — so a keyboard user tabbed to the Back/Next button doesn't double-advance, and an Enter meant for the command palette doesn't leak through to the quiz. Tests drive answer → Enter (submit) → Enter (advance) asserting the counter increments, and pin that an Enter fired from the focused Next button is not hijacked by the window listener.

  • [issue-2657] Autonomous Creation Engine (Phase 1) — schedule the Creative Director with a recurring, feedback-ready creative brief. New first-class CreativeCommission entity: a standing brief ({ name, enabled, targetAbility, brief, schedule, generation }) that fires on a cron cadence and drives the existing Creative Director directive pipeline unattended — "every night at 2am, make me something surreal." Commissions are db-primary (per docs/STORAGE.md): one row per commission in the machine-local creative_commissions PostgreSQL table (full record in data JSONB, adapter server/services/creativeCommissions/db.js, selected pg-vs-file exactly like universeBuilder so a NODE_ENV=test/MEMORY_BACKEND=file install keeps a file escape hatch). No sync_sequence/tombstone — deletes are hard deletes, mirroring tribe. They are deliberately not federated in Phase 1 — the same rationale as seriesAutopilotScheduler's settings-based schedules, since a schedule that synced across peers would double-run on every machine (federation with a per-peer "home" gate is Phase 2). A new commissionScheduler.js (modeled on seriesAutopilotScheduler) arms one eventScheduler cron per enabled commission; on fire it re-reads the commission + creative-autonomy config, builds a CD directive from the brief via the pure buildCommissionDirective (which already folds a last-N feedback digest so Phase 2 only needs the rate surface), mints a directive-driven CD video project, and nudges advanceAfterPlanStepSettled so each plan step runs through the gated dispatchCreativeTool. Cold-bootstrap compliant per the AI Provider Usage Policy: boot only arms crons (nothing fires until a cadence elapses), and every fire gates on creative autonomy execute and the daily cos budget before spawning anything — an off/dry-run or over-budget install records a skipped run and generates nothing. Full REST CRUD at /api/creative-commission (Zod-validated create/update, DAILY/WEEKLY/CUSTOM schedules composed to cron with an authoritative isValidCron check in the service, generation schema with no object-level default so an empty PATCH still 400s the "at least one field" refine), a scheduler re-sync after every mutation, and a new /creative-commission Create-suite page: list + deep-linked create/edit Drawer (/creative-commission/:id, /new) with pause/resume, inline-confirm delete, and per-run history — registered in NAV_COMMANDS (⌘K + voice) and the sidebar. Phase 1 restricts targetAbility to video (the enum widens with the ability adapter in Phase 3/4) so a user can't create a commission that silently never runs. Refs #2657 — Phases 2–5 (feedback loop, all-ability adapter, music tool, genre taxonomy) remain. New unit + route + PG-adapter tests cover cron composition, the feedback digest, the store CRUD/sanitizer, the autonomy/budget gates, the no-boot-generation guarantee, the route contract, and the creative_commissions row round-trip (verbatim readback / upsert with created_at preserved / list order / hard delete). Scheduler-vs-request writes serialize on the facade's shared per-id write queue (createRecordWriteQueue), identical to universeBuilder/storyBuilder.

  • [issue-2657] Autonomous Creation Engine (Phase 2) — the taste feedback loop closes. Each commission run's output is now rateable, and your reactions steer the next run. A new per-run rate/annotate control in the Creative Commissions run history (👍/👎 + an optional note like "less horror, more Magritte", keyboard-accessible, mobile-responsive, reactive) records a CommissionFeedback reaction against that specific run; the next scheduled fire's buildCommissionDirective folds the last N reactions (a configurable feedback window, now editable in the drawer — 0 disables conditioning) into the directive's goal as a "Recent likes / Recent dislikes — steer toward the likes, away from the dislikes" digest, so the run visibly drifts toward what you actually like (the digest shows up in the run's promptUsed). Feedback lives inline on the commission record — Phase 1 reserved feedback[] for exactly this, so no schema/table change was needed; reactions are deep-sanitized (a 👍/👎 or non-zero score is required, numeric ratings preserved verbatim, capped at 100) and upserted by run (re-rating a run replaces its prior reaction rather than stacking a contradictory second one) on the same shared per-id write queue as run-recording so a rating submitted mid-fire can't clobber a run append. The composed directive goal is length-clamped (per-note + overall) so a large feedback window can't push it past the Creative Director's 5000-char goal limit on the scheduler path (which skips the route's input validation). New POST /api/creative-commission/:id/feedback (Zod-validated commissionFeedbackSchema — runId required and verified against the record's runs, a zero rating rejected as meaningless, → 400/404 on bad input/unknown id) returns the full updated commission for reactive state; the edit drawer preserves unsaved field edits when a rating lands (the form re-syncs only on a genuine target change, not on every in-place record update). When a commission fires it also surfaces the run as a low-priority, machine-local notification (new creative_commission type, deep-linked to the commission) worded to reflect that the piece is being created — "rate the result once it lands." Surfacing stays notification-only for now: the brain inbox is federated (inbox ∈ BRAIN_ENTITY_TYPES), so a reminder there would propagate a peer-useless needs_review item pointing at a machine-local commission — brain-inbox surfacing (and completion-triggered surfacing) rejoin once commissions themselves federate. Commissions stay machine-local as in Phase 1 — since feedback lives on the never-federated commission it is also machine-local; the split-record federation the epic sketches (feedback federates, schedule stays per-machine to avoid double-runs) is genuinely larger and tracked as follow-up. Refs #2657 — Phases 3–5 (all-ability adapter, music tool, genre taxonomy) remain. New/updated unit + route tests cover the feedback sanitizer, submitCommissionFeedback (upsert-by-run / runId verification / NOT_FOUND / the full loop where a reaction folds into the next directive), the goal clamp, the feedback route contract, the notification-only surfacing helper (deep link + no federated-inbox write + best-effort resilience), and the scheduler surfacing a successful fire but not a skipped one.

  • [issue-2657] Creative Commissions now show — and let you choose — which AI processes them. A commission used to silently inherit the install's default Creative Director AI Assignment, so it wasn't clear what provider/model would write each run's treatment and production plan. The edit drawer gains an AI provider & model picker (the shared ProviderModelSelector, filtered to agent-harness CLI/TUI providers since an API-type provider injected into a CoS agent task trips the harness-boundary guard), and the list card shows the chosen processor at a glance (an unset pin reads "Install default AI"; the picker's default option names the actual active provider so "default" is never opaque). The choice is stored as a new assignment: { providerId, model } on the commission record (additive; providerId: null = inherit the default, preserving prior behavior); at fire time the scheduler fans that single pin onto both CD cognitive stages (modelOverrides.{treatment,plan}) so the run is processed by the provider/model you picked. Evaluation is deliberately left inheriting the default — it's a vision API call, not a CoS agent, and pinning it to a CLI/TUI provider would trip the same harness boundary. A provider-less model is dropped by the sanitizer (the runtime keys on the provider first) so the stored pin can never dangle, and a PATCH that omits assignment preserves it while an explicit { providerId: null, model: null } clears it back to the default. Zod-validated on create/update via the new creativeCommissionAssignmentSchema. The scheduler also guards the pin at fire time: treatment/plan run as CoS agent tasks that only accept an enabled agent-harness (cli/tui) provider, so a pin slipped past the UI (a direct REST write, or a provider whose type later changed to api or that the user disabled after pinning) is dropped and the run falls back to the default CD assignment instead of stalling at the harness boundary or launching through a disabled provider. New unit tests cover the sanitizer normalization/trim/provider-less-drop, the update replace-and-clear + preserve-on-omit semantics, the scheduler fanning the pin onto both stages (and omitting the model when only a provider is chosen), and the fire-time guard dropping api/removed/disabled pins.

  • Fix the Dev-UI "Vite host will be blocked" warning firing for apps whose vite config lives in an unlisted subdir. findViteConfig only probed a hardcoded subdir allowlist (client/, frontend/, web/, …) plus each managed process's cwd. Apps that keep their Vite client elsewhere — e.g. an admin/ dir — and whose stored process records carry no cwd produced a false "no vite.config was found" banner even though the config already set allowedHosts: true and the Dev UI opened fine over Tailscale. findViteConfig now falls back to a bounded breadth-first scan of the repo (depth ≤3, skipping node_modules/.git/build/vendor dirs, shallowest match wins) when the fast-path subdirs miss, so a config in any reasonable location is detected and the host-allow check reflects reality. admin also added to the fast-path list. New tests cover root, unlisted-subdir (admin/), nested, node_modules-ignore, and the end-to-end host-allowed status.

Full Changelog

Full Diff: https://github.com/atomantic/PortOS/compare/v2.30.0...v2.31.0