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
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.jsonis 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 headlessagyrun) were launched asagy --print --dangerously-skip-permissionswith the prompt piped to stdin. But unlike the old Gemini CLI,agy --printtakes the prompt as the flag's value and does not read stdin — so the flag parser consumed--dangerously-skip-permissionsas 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--printvalue (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--printto 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_enqueueVideoJobwas rendering at the video worker's default 768×512 landscape box: the planner authored anaspectRatiostring the worker doesn't read, and the project's locked preset was never resolved into thewidth/heightthe 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 thecd-planprompt 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
completebut never promoted the rendered clip tofinalVideoId, 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.jsonbecame 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/healthendpoint 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
triggerfield, older runs read as scheduled). A paused or half-configured commission is still testable: the manual path deliberately skips only theenabledand cron-validity guards. NewrunCommissionNow()in the scheduler (sharedfireCommissioncore 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
needsAgentFeedbackpredicate + optimistichandleFeedbackChangeinAgentsTab.jsx;AgentCardnow 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(buildAvatarBiodeterministic +polishAvatarBioprovider path) and routesGET /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 (nowindow.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 serviceserver/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 libclient/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) andChordDiagramcomponent, 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/:appIdinstead 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 exposesaria-currentto 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 helperscityFocusCamera(framing math, unit-tested) andcityFocusState(route-param resolution, unit-tested); newCityFocusCamera(in-canvas controller) andCityFocusPanelcomponents.[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 goalcategory→ 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 realNAV_COMMANDSpath (test-enforced). A goal can pin its own feature areas via an optionalfeatureAreasoverride (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 inwidgetRegistry.jsxand 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/ legacyself.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 thechrome://flagshint. 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. Newllm.fastPathconfig (enabled/triggers/browserLlm/browser.{temperature,topK}); new client modulesbrowserLlm.js(Nano client) andvoiceFastPath.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
PageHeaderbar over an internalflex-1 overflow-autoscroll 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 narrowmax-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
SettingsTabsHeadersub-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 bespokefixed inset-0 bg-black/50overlays with norole="dialog", noaria-modal, no focus trap, and no Esc-to-close. They now render throughclient/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 expliciteffectiveTier(replacing the oldparticleDensity-as-quality proxy incityShowDetail/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
ServerErrorand delete the duplicatedmapServiceErrorcopies. Routes now speak one error model. A singlecreateServiceErrorMapper(statusMap, buildContext?)factory inserver/lib/errorHandler.jsreplaces the nine near-identical localmapServiceErrorbodies 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 domaincode → statusmap (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 throwServerErrorwith an explicitstatus/code, socosAgentRoutes.jsno longer string-matchesresult.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:
pauseAgentandkillAgentnow throwServerErrortoo. The prior pass left the agent-lifecyclepauseAgentandkillAgentreturning{ success: false, error }result shapes, so the pause and kill routes still string-matchedresult.errorinto a blanket 404. Both now throwServerError— 404NOT_FOUNDfor a missing/not-running agent (including a genuine runner-side 404 when the runner has restarted out of sync, whose HTTP statuscosRunnerClientnow preserves on the thrown error), 500AGENT_PAUSE_FAILED/AGENT_KILL_FAILEDfor a runner-RPC or persist failure (previously every runner failure was mis-reported as 404). Thepause/killroutes drop their result-shape checks and just return the success payload.killProcess's CoS-delegation path falls back to a rawkillvia.then(ok, err)so a now-throwingkillAgentstill degrades gracefully.terminateAgentintentionally stays result-shaped: its route is fire-and-forget (the lifecycle wrapper emitsagent:terminateand 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
useCityViewporthook 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 acityPaneURL 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 tabbedDrawer(size="sm", Performance/Audio/Visual/Explore, active tab deep-linked viauseDrawerTab'scityTabparam,TabPillsmobile dropdown), preserving the/city/settingsroute.[issue-2550] Add direct unit tests for
telegramClient, the telegram service, anderrorHandler.asyncHandler. Three previously under-covered modules gain colocated*.test.jssuites, all driven with an injected/mockfetch(no network):server/lib/telegramClient.test.jsnow covers the poll loop (getUpdates dispatch to matching/non-matchingonText+message/callback_querylisteners, offset advance,stopPollingabort, and non-ok retry via fake timers) and theapiCallmethods (getMe/sendMessagehappy path,reply_markupstring→object parse, non-ok throw); a newserver/services/telegram.test.jsexercises the token-bucket rate limiter (30-message cap thenRate limit exceeded) and unauthorized-chat rejection (message/command/callback_query paths) throughinit()with all deps mocked; andserver/lib/errorHandler.test.jsaddsasyncHandlercoverage (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.jsdequeueNextTaskand splitcosAgents.jsinto focused modules. The ~370-linedequeueNextTaskscheduler is now a thin orchestrator that threads a sharedctxthrough fivespawnDequeuePriorityN(ctx)tier helpers (mirroringevaluateTasks), with the pure per-cycle capacity tracker (createDequeueCapacity) and mission/idle tier-eligibility predicates extracted to a newserver/services/cosDequeue.js— so the scheduler and its unit tests exercise the same guards instead of a local replica. The ~1090-linecosAgents.jsis 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) — withcosAgents.jskept 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/appshandler's ~80 lines of inline PM2 enrichment (one read perpm2Home, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a newserver/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 fromroutes/apps/shared.jsso 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 largeroutes/imageGen.jsrender router intoroutes/imageGenSetup.js, with the setup-check cache and pip allowlist relocated toservices/imageGen/setup.js. Pure mechanical refactor — no behavior change.[issue-2531] Split the pipeline
issues.jsandvisualStages.jsmonoliths along CRUD/stage/sync seams. The ~1470-lineserver/services/pipeline/issues.jsis now a thin barrel overissuesShared.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), andissueSync.js(peer-sync LWW merge + tombstone GC). The ~1760-linevisualStages.jsis now a thin barrel overvisualStageHelpers.js(shared style/prompt composers + image-gen enqueue plumbing),covers.js(comic + volume front/back covers),comicPages.js(comic page renders + panel prompt refine), andstoryboards.js(scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (queueSeriesIssuesWrite) and the store'squeueTypeIndexWritemerge snapshot are preserved, and every existingfrom './issues.js'/from './visualStages.js'import path still resolves through the barrels.
Documentation
- [issue-2547] Align the dual
pm2pins and refresh thekokoro-jsdependency audit. The rootpackage.jsonpinnedpm2at7.0.3whileserver/package.jsonpinned7.0.1; both are now7.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 from1.2.0to its latest patch1.2.1and flagged maintenance watch indocs/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'ssynthesizePiper— sharing the same(text, cfg, signal) → { wav, latencyMs }contract, so dropping kokoro is a delete of the kokoro branch intts.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
.envvars and the bootCREATE INDEXlock window..env.examplenow 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), andHUGGINGFACE_TOKEN(the fourth HF-token alias read by the Hugging Face catalog client). Separately,ensureSchema()inserver/lib/db.jscreates 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 indocs/STORAGE.mdexplain when this bites (existing-install upgrades, not fresh installs) and why the fix for a future large-table index is aCONCURRENTLYdb-migration rather than changingensureSchema(). 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" (justgh repo sync) and "Ignore v…" are not hidden. Defense-in-depth on the server:POST /api/update/executehard-rejects with409 AGENTS_ACTIVEwhen 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 persistedstatus: 'running'can't spuriously block, and a paused agent (process already stopped) correctly doesn't.GET /api/update/statusreportsactiveCosAgents, 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 byupdate.test.jsandUpdateTab.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 runsTZ=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 rendercompletedTodayfromgetPostStats(), inherited the drift. The day boundary now threads your configured timezone (getUserTimezone/todayInTimezone, via a shareduserLocalToday()helper) through both sides: every writer that stamps a day (submitPostSession,submitTrainingEntry, memory-practicesubmitPractice, and MorseappendMorseRound) records a new record'sdatein your local day — derived from the same instant it stamps intotimestamp/startedAtso 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 (newuseUserTimezonehook +dayKeyInTimezoneutil) 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-stablestartedAt, and preserving a legacy practice entry's only instant intotimestampbefore rewritingdate), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server'sTZ=UTCruntime), 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 (newserver/services/voice/voiceOutput.js): each tab registers as a candidate on connect, and the tab you're actively looking at claims output — the client emitsvoice:output:claimon 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 owntoast.errorin 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). ThegetVoiceConfig/updateVoiceConfig/fetchPiperVoice, telegram,registerTool/updateTool/getToolsList, andgetDatabaseStatuswrappers gained a backward-compatible trailingoptionsparam 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.errorin a custom.catch/catchwhile its API call also routed through the auto-toastingrequest()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 inapiWritersRoom.js,apiUniverseBuilder.js,apiDigitalTwin.js,apiImageVideo.js,apiMediaJobs.js, andapiBrain.jsgained a backward-compatible trailingoptionsparam so callers can opt into silent. Pipeline toast sites are intentionally deferred (a concurrent PR is reworkingclient/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.errorin a custom.catch/catchwhile their API call also routed through the auto-toastingrequest()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 loaderPromise.alls in the Series, Issue, Manuscript Editor, Continuity Bible, Reverse Outline, Export, and Series Roadmap pages. Validation-only guards, SSE-frame toasts,useAsyncActioncallers, and already-silent sites are unchanged. The pipeline sites whoseapiPipeline.jswrappers still lack a request-options param (most stage-render/generate calls that spreadoptsinto 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-insightsfetch, 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 aninsightsRefreshKeyon every task-list mutation, which the banner watches (via a mount-skipping effect) torefetch()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'sfetchDatato 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-gitlabwork-detector runsgh/glab issue listwith an author filter (self→@me, orowner→the repo owner), and an empty filtered result was flattened to the reasonno-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:ownerresolves to an org (e.g. a GHE repo owned by a team), which is never an issue author, so the filter matches nothing; andself/@meis 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 newno-authored-issuesreason 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 reportsno-open-issues, and theanyfilter is unaffected (no wasted re-probe). New private helpercountOpenIssuesUnfiltered; covered byperpetualWork.test.jsanduseOnDemandTaskToast.test.jsx.claim-issue distinguishes the "owner filter matches an org" trap from a personal-username mismatch. Building on the fix above: when the
ownerauthor 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 distinctowner-is-orgreason 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.ownermode on a user-owned repo is unchanged. Covered byperpetualWork.test.jsanduseOnDemandTaskToast.test.jsx.Perpetual claim-issue stops spawning agents forever on a
[Epic]-titled issue. The perpetual work-detector recognized a tracking epic only by anepiclabel or a title ending in "(epic)" — but the common[Epic] …bracketed-prefix convention (an epic filed with noepiclabel) 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 wasneeds-input/blockedplus one[Epic]-prefixed umbrella.isActionableIssuenow recognizes a leading[epic]bracket orEpic:colon tag (case-insensitive,\b+terminator-guarded so[epicenter]and a bare "Epic rework" adjective don't match) via a new exportedtitleMarksEpichelper, 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 byperpetualWork.test.js(incl. a 7-issue convergence scenario) andtaskPromptDefaults.test.js.pr-watcher now works on GitHub Enterprise hosts and resolves "self" against the repo's actual host. The
pr-watchertask gated ongetOriginInfo().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 viagh api userwith 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 sharedhostToWorkTracker(the same rule the claim-issue router uses;gitlab.*still falls through as not-a-github-repo), the default-branch and PR-listghcalls pass a host-qualified--repo HOST/OWNER/REPOselector (enterprise-correct, and deterministic on a fork+upstream multi-remote checkout where cwd-based detection would ambiguously resolve to the parent), andgetSelfLogin(host)resolves identity with an explicit--hostnameand caches per host. Covered byprWatcher.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.
lazyWithReloadnow 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. NewimportWithRetryhelper 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.reloadOnceForStaleChunknow purges the SW'sportos-*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).fetchServerBuildIdre-fetches the shell withcache: 'no-store'and reads theportos-build-idmeta 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. NewpurgeOfflineCaches+fetchServerBuildIdhelpers 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 checkedscanNotesVaultsynchronously right afterawait waitFor(...)on the rendered vault id. That mock call is fired by a separateuseEffectkeyed 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 ownwaitFor, awaiting the async side-effect instead of sampling it. Test-only change (notest.retryor timeout inflation) — no runtime behavior change.[issue-2633] Direct
task:readyemits now claim against the right task file. The Creative Director bridge, the on-demanddequeueNextTask, andspawnPriority0OnDemandpublish task records with notaskType, so an internal (sys-*/cd-*/app-improve-*) task's claim/in_progressupdateTaskfell back to'user', targeted TASKS.md instead of COS-TASKS.md, missed the record, and returned a truthy{ error }object theif (!updateResult)check silently swallowed — leaving the task un-claimed while the agent spawned anyway.runAgentSpawnnow normalizestaskTypefrom the id viaisInternalTaskIdup 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 carrytaskType:'internal'but are never written to COS-TASKS.md) must still spawn as they did before, so only anullresult (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 throughreadState()→loadAll(), pulling every issue's fulldataJSONB — up to ~12MB of stagerunHistoryeach — into memory only to read the ids; it now sources the store'sSELECT idprojection, with the PG backend filtering tombstones via the mirroreddeletedcolumn (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 topoffset+limitby date and merges those heads, so a paged inbox readsaccounts × (offset+limit)messages into the merge instead of the full cross-account total (the exacttotalcount 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 barefetchwith no timeout, so a hungaccounts.spotify.comcould 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 sharedfetchWithTimeouthelper with a 15s cap. Separately, concurrentgetAccessToken()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-flightrefreshPromise(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 usesmin-h-[44px] min-w-[44px]centered around its icon (matching the sharedDrawercontrol sizing), and the bell's mobile hit area is bumped 40→44px (itssm:desktop shrink is unchanged). The notification panel also gainsmax-w-[calc(100vw-2rem)]so itsw-80width can't overflow a narrow mobile sidebar, and the ⌘K result rows get amin-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-80left rail and a magiccalc(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 frommd+, laid out on agridthat 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
endpointis a free-form URL, and model-refresh / API-run paths attached the paidAuthorization: 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 newendpointGuardnow 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 likedata/uploads-evil/string-matched) and the attachment/screenshot responses echoed the absolute on-diskpathback to the client, leaking the install layout / home-directory username segment. Containment now goes through a sharedisPathInsideDir()helper (anchoredresolvePath(dir) + sepprefix, matchingmakePathResolver), 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). Themoltbook-claim.mjsscript 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/navigateonly checked the host LITERAL withisSafeIngestUrl, 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 throughnavigateToUrlPinned— the same connect-time pin the catalog URL ingest uses — which verifies Chrome's own reportedremoteIPAddressfor 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 (noremoteIPAddresson WS events) — bounded by the single-user trust model and documented inbrowserService.ssrfPinRefusalReason. - [issue-2515] Restrict Layered Intelligence custom
cmdsources to allowlisted binaries (noshell: true). A customcmdsource ran its full command string throughshell: truewith 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 tosh).runShellCommandnow denies the shell by default: the command is parsed and checked against the sharedcommandSecuritybinary allowlist (rejecting shell metacharacters and non-allowlisted binaries), then spawned withshell: falseand parsed args. An operator who genuinely needs a pipeline can set the install-levelsettings.layeredIntelligence.trustShellSourcesopt-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.
refreshMessageandupdateMessageEvaluationsdid theirload → mutate → saveCacheoutside the per-accountsyncLocks, so a full-body refresh or an evaluation write racing a concurrent sync (or each other) could clobber the other's update on the shareddata/messages/cache/<accountId>.jsonfile. 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 — mirroringissueWriteTailinpipeline/issues.js. The existingsyncLocksboolean 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 acancelledflag. The global-search effect now mirrors thatcancelledguard so only the latest query's response applies. Separately,Security.jsx's device-change handler scheduledsetTimeout(startMedia, 100)with no clear on unmount or before rescheduling, so rapid device switches stacked multiplestartMedia()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'sDOMAIN_ICONSmap was missing acognitiveentry, yetDRILL_TO_DOMAINmaps every cognitive drill type (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) to thecognitivedomain — 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 toundefinedand blanked the run page with a minified React error. Added thecognitive: Brainicon and hardened the lookup to fall back toChevronRightfor any unmapped domain, so a future domain gap degrades gracefully instead of crashing. A regression test renders the transition for everyDRILL_TO_DOMAINtype. - [issue-2549] Enforce the Windows
.exebasename contract in the CoS Runner allowlist test. TheallowedCommands.test.jscase for a Windows absolute path (C:\\...\\claude.exe) ended onexpect(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.exepath (/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 expectstrueonwin32andfalseon POSIX (wherepath.basenamedoesn't split backslashes). Both new assertions were verified to fail against a broken implementation (dropping the.exestrip; forcingwin32basename 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.onhandlers without awaiting or catching,telegram.jsransetInterval(healthCheck)and a couple of sync-contextbot.sendMessage(...)calls without a.catch, andinstances.jsscheduledprobeAllPeers()fromsetTimeout/setIntervalwithout 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 arunHandlerwrapper 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.catchtheir promise. A vitest suite drives the client'sonTextandmessagepaths with a throwing handler and asserts nounhandledRejectionescapes. - [issue-2519] CoS handlers no longer flash a false-success toast after a failed API call. Several Chief of Staff actions (
handleForceEvaluateon 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 singletoast.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-toastingrequest()helper AND showed their owntoast.errorin.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 localcharGet/charPost/charPuthelpers are silent-by-default (every caller owns its own catch toast or theloadErrorbanner) 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/chordsprops 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. AuseEffectnow drops the hover identity wheneverdata/chordschange. - [issue-2513] Block loopback/metadata hosts in Layered Intelligence custom
httpsources.fetchHttpSourceused a barefetchwith only anhttp(s)scheme check, so a hand-edited config could point a custom source at127.0.0.1,169.254.169.254, ormetadata.google.internaland exfiltrate up to 8KB into the reasoner prompt. It now routes through the shared SSRF-guardedfetchPublicText(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 intopsql. The import now streams the dump throughspawn('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 oldsedstage stripped are filtered in-process. No user- or env-derived value ever reaches a shell string.
Changed
[issue-2528] Collapse the pipeline per-key
createFileWriteQueuefactory into one helper (DRY). Five pipeline stage stores (editorialScore.js,reverseOutline.js,perspectiveRewrite.js,manuscriptReview.js,continuityBible.js) each hand-rolled the sameconst 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 newcreateKeyedFileWriteQueue()inserver/lib/fileWriteQueue.js, a thin wrapper over the already-existing self-pruningcreateKeyCachedQueue— 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.jsgod-module into focused sibling modules behind a thin barrel. The ~2000-lineserver/services/universeBuilder.js(50+ exports mixing sanitizers, CRUD, peer-sync, and prompt compilation) was split along its natural seams intouniverseBuilder/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), anduniverseBuilder/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. ThecatalogDB.jssplit is tracked as remaining work under the same issue.[issue-2529] Split the
catalogDB.jsgod-module into focused sibling modules behind a thin barrel. The ~1900-lineserver/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 intocatalogDB/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), andcatalogDB/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
createKeyCachedQueuehelper (DRY). Five modules each hand-rolled the sameMap+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), andcollectionStore.js(per-record). Each now delegates toserver/lib/createKeyCachedQueue.js, andfileWriteQueue.js's id-keyedcreateRecordWriteQueue(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 reusescreateFileWriteQueue. 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
createPgFileFacadebackbone 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: theisFileBackend()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/Odb.js). Those now live once inserver/lib/pgFileFacade.jsasisFileBackend(),resolvePgBackend({ requirement, migrate?, loadDb, makePg }), andcreatePgFileFacade({ makeFile, makePg }); the two inline write-queue copies (createFileWriteQueue's id-keyed siblingcreateRecordWriteQueue) were folded intoserver/lib/fileWriteQueue.js. Each store keeps its own genuinely-differentmakeFile/makePgfactories 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/libcounterparts:sleep(youtubeSync.js,pipeline/seriesAutopilot.js) andpathExists(localLlm.js) now import fromfileUtils.js;database.js's inline color-onlystripAnsiuses the sharedansiStrip.js(full ANSI/control stripper);systemHealth.js's byte formatter andhuggingFaceCatalog.js's (via a thin wrapper that preserves itsnull-on-unknown-size fallback contract) now delegate tofileUtils.formatBytes; and the two hand-rolled SSE header blocks now use the canonicalSSE_HEADERS—ask.jskeeps its extrano-transformdirective on top of the shared set, andmediaJobQueue's terminal-event path gains the previously-missingX-Accel-Buffering: noso 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 parsedreq.bodywith hand-rolledArray.isArray/includeschecks. Each now has a named Zod schema (PortOS schemas inlib/validation.js, brain schema inbrainValidation.js, provider schemas inaiToolkit/validation.js) wired throughvalidateRequest, so invalid bodies return a consistent400 VALIDATION_ERRORwith per-fieldcontext.detailsinstead of ad-hoc messages. Port numbers are range-checked (andcountcoercion no longer silently accepts booleans/arrays), backend/target values are enum-checked, and provider create/update reuse the canonicalproviderSchema(.partial()on update). As part of wiringPUT /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 inheritedObject.prototypemember as an existing provider and be persisted as the active one.[issue-2525] Extract shared
migrationMarkerhelpers usingatomicWrite. Eleven boot-time migration/repair/reconcile scripts underserver/scripts/each hand-rolledmarkerExists/readMarker/writeMarkeron top ofreadFile(...).catch(() => null)and a non-atomicwriteFile(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 inserver/lib/migrationMarker.js(anchored underPATHS.data, built on the existingtryReadFile/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 (defaultcircleomitted for a clean/tribe) with a valid-tab fallback for stale/unknown values — matching the PromptManager convention. Separately, theStylePresetPickerstyle-preset<label>and the Loops "Interval"<label>had nohtmlFor/idpairing; both now associate with their control via auseId()-generated id so click-to-focus and screen readers work.[issue-2527] Route client localStorage and keyboard activation through the shared
safeStorage/a11yKeyboardhelpers. Several client sites bypassed the guardedsafeStoragehelpers with rawwindow.localStorage+ hand-rolledtry/catch(ortypeof windowguards), and several non-<button>clickables reimplemented the Enter/SpaceonKeyDownhandler inline. Storage reads/writes inSecurity.jsx,PipelineManuscriptEditor.jsx,voiceVisibility.js,MortalLoomBanner.jsx,WhileAwayWidget.jsx, andManuscriptReadAloud.jsxnow go throughsafeReadStorage/safeReadJsonStorage/safeWriteStorage/safeRemoveStorage; keyboard activation inIngredientPicker.jsx,ManuscriptReadAloud.jsx,EditorialHealthPanel.jsx,TribeCircleMap.jsx, andGenomeTab.jsxnow spreadsclickableProps(handler)(which suppliesrole/tabIndex/onKeyDownvia the sharedonActivateKeyDown). 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
useUniverseGalleryhook.UniverseBuilder.jsxinlined ~160 lines of gallery/preview plumbing — the filename→image-sidecar metadata map, thelistImageGallery()refetch effect (keyed onruns.length+ a per-job-completion bump), thepreviewItemsderivation across variations/composite sheets/style probes/canon+character-sheet refs (namespaced-key dedupe), and theusePreviewRoute/useMediaPreviewActions/useMediaAnnotationswiring. That cohesive concern now lives inclient/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,useShellSessionfor 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 viatitle(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 anaria-labelmatching theirtitle. The MessageDetail reply<textarea>(previously placeholder-only) gains anaria-label, and the Templates "Target Directory"<label>is now wired to its input viahtmlFor/idso 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
setTimeoutwas a locallet busyRetryTimerassigned inside an async.catch, so the effect's own cleanup (consumed on everysetQueue/setRunningQueueIdre-run before the timer was ever assigned) couldn't clear it — an unmount during the 1.5s backoff, or a newer dispatch, could still firesetRunningQueueIdon a torn-down component or steal a slot a newer item owned. The timer now lives on auseRef, is cleared by a dedicated unmount cleanup, and every deferredthen/catch/finally(and the timer callback) is gated by a per-dispatch generation token plus amountedRefso stale callbacks bail. Separately,FeatureAgentDetail'sgetFeatureAgent(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 amountedRefguard, 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 tobuildClaimWorkTask).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 theclaim-issue-jiraprompt assembly directly inserver/routes/cosTaskRoutes.js. That logic now lives inserver/services/cosTaskGenerator.jsas an exportedbuildJiraTicketTask(app, ticketKey)that returns{ ticketKey, prompt, taskMetadata }— besidebuildClaimWorkTask, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, anduseWorktree/openPRposture are byte-for-byte unchanged; new unit tests cover the extracted assembly.[issue-2539] Serialize
createCachedStoreandbackup.saveStatewrites; bound the rate-limit state maps.createCachedStorenow runs every write through an internal single-tailcreateFileWriteQueueand exposes amutate(fn)primitive that serializes the wholeload → modify → persistcycle, 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 racyload()+save()pair ontomutate().backup.saveStategained 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 boundedcreateBoundedStateMap({ maxSize, ttlMs })helper (server/lib/boundedStateMap.js) that lazily evicts idle (TTL) and least-recently-used (LRU) entries. (The idle pipelinewriteQueuespruning called for by the issue already shipped viacreateKeyedFileWriteQueue/createKeyCachedQueuein #2528/#2524.) Behavior is otherwise unchanged; new unit tests cover the serializedmutate, 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, butroutes/usage.js(GET/api/usage) andservices/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.providersvia theArray.isArray(result) ? result : (result?.providers || [])pattern already used injiraReports.js/loops.js. The two test suites mockedgetAllProvidersas a bare array (masking the bug); their mocks now return the real object shape, plus a newgetProviderQuotasregression test asserts the unwrap.[issue-2598] Add Antigravity + Grok subscription-usage adapters via headless TUI
/usagescrape. DevTools → Usage previously showed "not available" placeholders for theagy(Antigravity) andgrok(Grok Build) provider families, because neither CLI exposes quota in non-interactive--printmode (there/usageis treated as an LLM prompt — wrong data, and it burns tokens). Their real usage surface is an interactive slash command (/usagefor agy,/usage showfor grok), so a newserver/lib/tuiUsageScrape.js#scrapeTuiUsagedrives 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), andproviderUsage.jsparses 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 treatingWeekly 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
useShellSessionhook.pages/Shell.jsxinlined ~750 lines of xterm setup, the Socket.IOshell:*protocol, and the single-subscriber PTY attach/detach contract (thependingAttachRef {target,generation}guards,claim-vs-user-intent handling,userIdleRefpassive-idle gating,mountedRefdeferred-work guards, and URL sync). That cohesive concern now lives inclient/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.jsxandcomponents/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.jsxto fix a CI flake. The "paints the roll" testawaited the footer text (findByText(/3 notes · /)) then synchronously assertedexpect(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-controlsctx.clearRectassertion, which followed the fit/zoom button clicks) are now wrapped inwaitFor(...)so they wait for the draw deterministically. Audited the sibling songs canvas tests (PianoRoll,MidiPianoRoll,Metronome,RoundStack,PitchTuner,SingToScore,SongTraining,ReferenceAnalysis,SongRecordings): onlyMidiVisualizationgates its paint behind async data loading, so it was the only racy one —PianoRoll/MidiPianoRollassert after a synchronousrender()/pump()(no text-findBygap), and the rest have no canvas assertions. Test-only; each test keeps its own explicitgetContextmock.[issue-2541] Add a wall-clock timeout to the AI toolkit's API runner so a hung provider can't leak
activeRuns.runner.js#executeApiRunattached anAbortControllerbut armed no timer, so an upstream that opened the SSE stream then stalled (or never responded) held its controller inactiveRuns— 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.executeApiRunnow accepts an optionaltimeout(falling back toprovider.timeoutthen a 300s default, mirroringaiProvider/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 anERROR_CATEGORIES.TIMEOUTfailure — so a stalled fetch/stream, a provider that never responds, and even aensureProviderReadyhook that never reaches the fetch are all bounded, and the failure is recorded as a timeout instead of the raw AbortError'sUNKNOWN/HTTP 0. Both the Runs router andpromptRunnernow thread theireffectiveTimeoutinto 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 flipisRunActiveback to false and complete witherrorCategory: 'timeout'.[issue-2533] Split the ~990-line
server/routes/digital-twin.jsflat router into adigital-twin/sub-router directory (mirroring the apps/pipeline layout). The single multi-domain file is now an assembledindex.jsmounting thirteen domain sub-routers at the same/api/digital-twinbase —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, andevidence— with the sharedassertPersonaExistsguard extracted todigital-twin/shared.js. The route contract is byte-for-byte unchanged: all 73 endpoints keep their exact method+path, Zod validation, andServerErrorstatus mapping, and the order-sensitive pairs (/personas/activebefore/personas/:id;/taste/sectionsbefore/taste/:section/...) each live entirely within one file so mount order is irrelevant. The route test moved into the directory asdigital-twin/index.test.js(21 cases green). Completes the last remaining slice of #2533 (the imageGen setup, apps-list enrichment, andbuildJiraTicketTaskextractions 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 against100vh, which iOS Safari inflates by the retractable browser-chrome height — so each spilled under the chrome. New parametrizedmax-h-dvh-cap/min-h-dvh-cap/h-dvh-cap@utilityclasses inindex.csssize to100dvh(the visible dynamic viewport) with a100vhfallback gated behind@supports (height: 1dvh)— the two-declaration idiom.h-dvh-screenuses does not work once the value is wrapped invar()/min()/calc()(both declarations become valid-at-parse-time, so thedvhone wins the cascade then computes to invalid rather than restoring thevhline), so thevhvalue is the unconditional base and thedvhvalue overrides only where supported. A--dvh-capupper bound and--dvh-insetsubtracted 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 fixedmin-h-[180px]/190pxat base/sm/md and only switches to the dvh cap atlg:/xl:, where the original used a viewport unit. Behavior is byte-identical on engines that predatedvh; 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.jsre-implemented production logic — localunfixedSpawn/fixedSpawncopies of thespawningTasksdedup flow and arunCompletion/makeCompletionHarnesscopy of the completion try/finally — and never importedspawnAgentForTask/handleAgentCompletion, so they stayed green when production regressed. The two concurrency contracts those replicas modelled are now extracted intoserver/services/agentGuards.js:withSpawnDedupGuard(spawningTasks, taskId, fn)(acquire-before-first-await, hold across the whole spawn body incl. the runner-enqueue handoff, release infinally,SPAWN_DEDUP_SKIPon a concurrent duplicate) andwithMapEntryCleanup(map, key, fn)(delete therunnerAgentsentry infinallyeven when a completion step throws).spawnAgentForTasknow wrapsrunAgentSpawnin the former (dropping six inlinespawningTasks.deletesites), andhandleAgentCompletionwraps 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.jsalready drove the realcreateDequeueCapacity/isMissionTierEligible/isIdleTierEligibleexports after #2530, so it was left as-is. NewagentGuards.test.jsunit-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, thefrom-slate-900/80 to-slate-900/40gradients, andtext-slate-400— aslatesurface that ignored the active theme. Those now map tobg-port-card/hover:bg-port-border/text-port-text-muted(the collapse button'stext-gray-500 hover:text-whitealso becametext-port-text-muted hover:text-port-textso 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/#4a4a4afor the opaque, theme-derivedrgb(var(--port-text-muted))andrgb(var(--port-text))— colors that stay high-contrast against the already-tokenizedrgb(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 inLayout.jsx(four sites) andNotificationDropdown.jsxswappedbg-yellow-500 text-blackforbg-port-warning text-port-on-warning; the Dashboard server-health glow'sshadow-[0_0_8px_#22c55e]/#ef4444now referencergb(var(--port-success))/rgb(var(--port-error)). The Ambient full-screen idle display is intentionally left on its fixed deep-blackbg-[#050505](withtext-whitecontent) — 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-warningcontrast to WCAG AA in day themes. Twomode: 'day'themes paired an amber--port-warningwith 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) andblack-ice-terminal-day(#aa6e00 on white ≈ 4.25:1). Both now use black--port-on-warningat 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 newclient/src/themes/portosThemes.test.jscomputes 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 (
failureCountlived only in per-instance metadata; ROTATION types had no cadence gate at all, returningshouldRun: trueunconditionally). A new per-type failure ledger now lives on the schedule execution record (consecutiveFailures/lastFailureAt/lastErrorCategory, per app + global) — persisted alongsidelastRun, so it survives restarts as per-install runtime state (additive, backward-compatible, never synced).shouldRunTaskapplies 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-facingAGENT_WARNINGnotification 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-doneoutput is unparseable — previously recorded as a benign completed success, invisible to any failure accounting — now feeds a failure signal into the ledger via the pureresolveTypeFailureSignal(anunparseable-responsehook reason, or a thrown output hook, counts as a failure regardless of exit code; benign hook reasons likeno-proposal/duplicatedefer 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
paginateArrayhelper. The primary indexGETs for creativeDirector (/), storyBuilder (/), universeBuilder (/), moodBoard (/), videoTimeline (/projects), and loras (/) returned unbounded arrays. Each now opts into pagination the moment a client sendslimit/offset, mirroring thebrainCrudprecedent:isPaginationRequested(req.query)gates a bounded{ items, total, limit, offset }envelope (via the existingpaginateArrayinserver/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=1default-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 sharedpaginateArrayenvelope 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 passeslimit/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 localpaginationQueryFieldsfragment (limit/offsetas passthrough strings —parsePaginationdoes the parse+clamp) is spread intoprivacyVaultListQuerySchema,privacyOrgListQuerySchema,privacyBrokerListQuerySchema, andprivacyBrokerCaseListQuerySchemainprivacyValidation.js; the/orgshandler stripslimit/offsetbefore passing filters tolistOrgsso 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.categoryalone, but that category is produced by theanalyzeAgentFailureregex 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."analyzeAgentFailurenow stamps anoriginprovenance marker on every classification:'provider'/'runner'when the match carries a genuine structured signal (anAPI Error: NNNline, a Node error code likeECONNREFUSED, a provider token likeoverloaded_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: 429vs a barerate limit) gate the promotion through a per-patternstructuredMarkersub-pattern via the new pureresolvePatternOriginhelper. The exclusion gate inrecordTaskCompletion(server/services/taskLearning/metrics.js) now runs through a pureshouldDivertToEnvironmental(outcomeSuccess, category, origin)that additionally requiresorigin !== 'output-scan', so an output-scan false positive counts as a genuine failure while structured signals stay excluded. Back-compat is preserved: anerrorAnalysiswith noorigin(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.jsxis now a 9-line compatibility shell over the presentational editor, while draft hydration/persistence and canon-safe merges live inuseUniverseDraft, AI expansion/refinement lives inuseUniverseExpand, and bulk-render configuration plus per-entry job queues live inuseUniverseRender. 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
/songbookindex (filter by stage/instrument/tag/search, all URL-addressable) and/songbook/:idfull-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 underdata/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 puretabNotationlib (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-Am7classifies, renders, and transposes as one token) and Unicode accidentals (♯/♭ normalize to #/b on paste soF♯mtransposes 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".
getBranchesmarked a local branchmerged: truefromgit branch --mergedalone, butdeleteMergedBranches(correctly) skips branches checked out in a worktree —git branch -dcan'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.getBranchesnow also returns aworktreeflag (branch checked out in another worktree), the Git tab'slocalMergedCountcounts onlymerged && !worktreeso the button reflects what the server will actually delete, and locked branches render aworktreebadge next tomergedso the user sees why they linger. Server + client tests cover the count and badge.[issue-2654] Lift the CoS actionable-insights fetch into
ChiefOfStaff.fetchDataso the banner refreshes for the whole staleness class.ActionableInsightsBannerowned its own/cos/actionable-insightsfetch on a 60suseAutoRefetchpoll, 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 aninsightsRefreshKeycounter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched insideChiefOfStaff.fetchData'sPromise.alland passed down as aninsightsprop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path callsonRefreshup instead of owning arefetch(). The banner's counts refresh only throughfetchData: the 30s poll, task mutations (TasksTabonRefresh), the unblock-up path, and agent spawn/completion (which already callfetchData). There is deliberately no on-demand "refresh just the insights" path, because/cos/actionable-insightsruns a health check that auto-restarts errored PM2 processes (server/services/cosHealthMonitor.js) and re-emitscos:health:check— so refreshing from thecos:health:checksocket 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 nextfetchDatapoll (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 whosecos:health:checksocket emit can land beforefetchData's own (pre-check)getCosHealthread resolves,fetchDatakeeps whichever health check is newer bylastCheck(Date.parse-normalized), and preserves the last-good health when its own read fails — instead of blanking a fresher socket-delivered result. RetiresinsightsRefreshKey,refreshTasks's signal bump, the banner'srefreshKeyprop, itsdidMountRefskip-mount effect, and itsuseAutoRefetchself-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, guards asserting neither thecos:health:checksocket 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.ElementFlashModenow binds a windowkeydownlistener while a result is showing (input unmounted) that advances on Enter/Return, mirroring the "Next" button; thenext()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
CreativeCommissionentity: 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 aredb-primary(perdocs/STORAGE.md): one row per commission in the machine-localcreative_commissionsPostgreSQL table (full record indataJSONB, adapterserver/services/creativeCommissions/db.js, selected pg-vs-file exactly like universeBuilder so aNODE_ENV=test/MEMORY_BACKEND=fileinstall keeps a file escape hatch). Nosync_sequence/tombstone — deletes are hard deletes, mirroringtribe. They are deliberately not federated in Phase 1 — the same rationale asseriesAutopilotScheduler'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 newcommissionScheduler.js(modeled onseriesAutopilotScheduler) arms oneeventSchedulercron per enabled commission; on fire it re-reads the commission + creative-autonomy config, builds a CD directive from the brief via the purebuildCommissionDirective(which already folds a last-N feedback digest so Phase 2 only needs the rate surface), mints a directive-driven CD video project, and nudgesadvanceAfterPlanStepSettledso each plan step runs through the gateddispatchCreativeTool. 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 autonomyexecuteand the dailycosbudget before spawning anything — anoff/dry-runor over-budget install records askippedrun and generates nothing. Full REST CRUD at/api/creative-commission(Zod-validated create/update, DAILY/WEEKLY/CUSTOM schedules composed to cron with an authoritativeisValidCroncheck in the service,generationschema 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-commissionCreate-suite page: list + deep-linked create/edit Drawer (/creative-commission/:id,/new) with pause/resume, inline-confirm delete, and per-run history — registered inNAV_COMMANDS(⌘K + voice) and the sidebar. Phase 1 restrictstargetAbilitytovideo(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 thecreative_commissionsrow 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
CommissionFeedbackreaction against that specific run; the next scheduled fire'sbuildCommissionDirectivefolds 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'spromptUsed). Feedback lives inline on the commission record — Phase 1 reservedfeedback[]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). NewPOST /api/creative-commission/:id/feedback(Zod-validatedcommissionFeedbackSchema—runIdrequired 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 (newcreative_commissiontype, 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-uselessneeds_reviewitem 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,schedulestays 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 newassignment: { 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 omitsassignmentpreserves it while an explicit{ providerId: null, model: null }clears it back to the default. Zod-validated on create/update via the newcreativeCommissionAssignmentSchema. 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 toapior 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.
findViteConfigonly probed a hardcoded subdir allowlist (client/,frontend/,web/, …) plus each managed process'scwd. Apps that keep their Vite client elsewhere — e.g. anadmin/dir — and whose stored process records carry nocwdproduced a false "no vite.config was found" banner even though the config already setallowedHosts: trueand the Dev UI opened fine over Tailscale.findViteConfignow falls back to a bounded breadth-first scan of the repo (depth ≤3, skippingnode_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.adminalso 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