Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Schedule the steps only you can take as Actions tasks with reminders
Claude017960677cb8
diff --git a/.claude/skills/portos-api/SKILL.md b/.claude/skills/portos-api/SKILL.mdindex 499cc22320..f1a5b6ae9c 100644--- a/.claude/skills/portos-api/SKILL.md+++ b/.claude/skills/portos-api/SKILL.md@@ -13,9 +13,12 @@ node scripts/portos-api.js task "<what the agent should do>" --app <app-id> --prnode scripts/portos-api.js get /api/cos/tasksnode scripts/portos-api.js post /api/image-gen/generate '{"prompt":"..."}'node scripts/portos-api.js post /api/music-video/autonomous @brief.json+node scripts/portos-api.js post /api/human-actions/plans @plan.json # schedule steps the user must takenode scripts/portos-api.js get /api/api-docs/catalog.json # discover endpoints```+- When the user has to do something by hand later (post, reply, upload, sign), schedule it with `POST /api/human-actions/plans` instead of only saying so in chat: each step gets a due time with a UTC offset, explicit `instructions`, and the exact text to paste in `content`. It lands in Review Hub › Actions and notifies them when due. Reuse the same `planKey` to replace a plan. Shape: [docs/API.md › Human Actions](../../../docs/API.md#human-actions).+- Credential order: `PORTOS_API_TOKEN` (set inside PortOS-spawned agents), then `~/.portos/agent-key.json` (the agent API key).- `whoami` answering `"authenticated": false`, or a `401 AUTH_REQUIRED`, means no key is available: ask the user to turn on **Settings > Security > Agent API key**. Never ask for, store, or type the instance password.- Never print the token or paste it into a commit, PR, issue, or chat.diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsxindex 51d14827d9..ce8d781ce8 100644--- a/client/src/components/NotificationDropdown.jsx+++ b/client/src/components/NotificationDropdown.jsx@@ -1,7 +1,7 @@import { useState, useRef, useEffect } from 'react';import { createPortal } from 'react-dom';import { useNavigate } from 'react-router';-import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Film, Sparkles } from 'lucide-react';+import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Film, Sparkles, AlarmClock } from 'lucide-react';import { timeAgo, formatCount } from '../utils/formatters';import { useActionQueue } from '../hooks/useActionQueue';import ActionQueuePreview from './ActionQueuePreview';@@ -55,6 +55,11 @@ const NOTIFICATION_TYPE_CONFIG = {icon: Film,color: 'text-orange-400',bgColor: 'bg-orange-500/20'+ },+ action_due: {+ icon: AlarmClock,+ color: 'text-port-accent',+ bgColor: 'bg-port-accent/20'}};diff --git a/client/src/components/brain/ThreadPasteBlocks.jsx b/client/src/components/brain/ThreadPasteBlocks.jsxnew file mode 100644index 0000000000..c888d288ff--- /dev/null+++ b/client/src/components/brain/ThreadPasteBlocks.jsx@@ -0,0 +1,56 @@+import { Copy } from 'lucide-react';+import { copyToClipboard } from '../../lib/clipboard.js';++// A fenced block in thread notes, optionally preceded by a `**Label**` line —+// the shape a scheduled human action writes its ready-to-paste text in+// (server/lib/humanActions.js buildHumanActionNotes). The closing fence must be+// at least as long as the opening one, so a block holding ``` survives.+const BLOCK_RE = /(?:^\*\*(.+?)\*\*\n)?^(`{3,})[^\n]*\n([\s\S]*?)\n\2`*$/gm;++export function pasteBlocks(notes) {+ if (typeof notes !== 'string' || !notes.includes('```')) return [];+ return [...notes.matchAll(BLOCK_RE)]+ .map(([, label, , text], i) => ({ label: label?.trim() || `Text ${i + 1}`, text }))+ .filter((block) => block.text.trim());+}++// A scheduled step's numbered instructions: the list before its first heading.+export function stepLines(notes) {+ if (typeof notes !== 'string') return [];+ const head = notes.split(/^## /m)[0];+ return [...head.matchAll(/^\d+\.\s+(.+)$/gm)].map(([, line]) => line.trim());+}++/**+ * A scheduled human action's steps, then the text it asks you to paste, each+ * with its own Copy button, so the moment a reminder fires everything is one+ * tap away. Paste blocks show on any thread; the steps only on a scheduled+ * action (tag `human-action`), where the notes are known to start with them.+ */+export default function ThreadPasteBlocks({ notes, tags }) {+ const blocks = pasteBlocks(notes);+ const steps = Array.isArray(tags) && tags.includes('human-action') ? stepLines(notes) : [];+ if (!blocks.length && !steps.length) return null;+ return (+ <section aria-label="Ready to paste" className="space-y-2 rounded border border-port-border bg-port-bg p-2">+ {steps.length > 0 && (+ <ol className="list-decimal space-y-1 pl-5 text-sm text-gray-200">+ {steps.map((line, i) => <li key={i} className="break-words">{line}</li>)}+ </ol>+ )}+ {blocks.length > 0 && <h4 className="text-xs font-medium text-gray-300">Ready to paste</h4>}+ {blocks.map((block, i) => (+ <div key={i} className="space-y-1">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs text-gray-400 min-w-0 break-words">{block.label}</span>+ <button type="button" onClick={() => copyToClipboard(block.text, `Copied: ${block.label}`)}+ className="inline-flex items-center gap-1 rounded border border-port-border px-2 py-1 text-xs text-port-accent min-h-[44px] sm:min-h-0">+ <Copy size={12} /> Copy+ </button>+ </div>+ <p className="whitespace-pre-wrap break-words text-sm text-gray-200">{block.text}</p>+ </div>+ ))}+ </section>+ );+}diff --git a/client/src/components/brain/tabs/ThreadsTab.jsx b/client/src/components/brain/tabs/ThreadsTab.jsxindex 079eeeb567..dff4fb46df 100644--- a/client/src/components/brain/tabs/ThreadsTab.jsx+++ b/client/src/components/brain/tabs/ThreadsTab.jsx@@ -23,6 +23,7 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';import toast from '../../ui/Toast';import ThreadRefChip from '../ThreadRefChip';import ThreadSourceClosedAction from '../ThreadSourceClosedAction';+import ThreadPasteBlocks from '../ThreadPasteBlocks';import { THREAD_REF_KIND_IDS, threadRefLabel } from '../../../lib/threadRefKinds.js';import {THREAD_STATUSES, THREAD_PRIORITIES, THREAD_ACTIVE_STATUSES,@@ -82,7 +83,20 @@ const toDraft = (thread) => ({notes: thread.notes ?? '',});-const draftToPatch = (draft) => ({+// The form edits a calendar day, but a scheduled step is due at a time of day+// (its reminder fires then). An unchanged day keeps the stored instant, and a+// moved day keeps its local time, so saving any other field never resets the+// due time to midnight.+const pad2 = (n) => String(n).padStart(2, '0');+function dueAtPatch(draftDay, stored) {+ if (!draftDay) return null;+ const prev = typeof stored === 'string' && Number.isFinite(Date.parse(stored)) ? new Date(stored) : null;+ if (prev && localDateKey(prev) === draftDay) return stored;+ const time = prev ? `${pad2(prev.getHours())}:${pad2(prev.getMinutes())}` : '00:00';+ return new Date(`${draftDay}T${time}:00`).toISOString();+}++const draftToPatch = (draft, stored = {}) => ({title: draft.title.trim(),status: draft.status,priority: draft.priority,@@ -90,7 +104,7 @@ const draftToPatch = (draft) => ({nextAction: draft.nextAction,waitingOn: draft.waitingOn,// Explicit null clears a stored date (absent would preserve it).- dueAt: draft.dueAt ? new Date(`${draft.dueAt}T00:00:00`).toISOString() : null,+ dueAt: dueAtPatch(draft.dueAt, stored.dueAt),tags: tagsToArray(draft.tags),notes: draft.notes,});@@ -312,7 +326,7 @@ export default function ThreadsTab() {setDrawerTab('details');return null;}- const updated = await api.updateThread(record.id, draftToPatch(draft), { silent: true });+ const updated = await api.updateThread(record.id, draftToPatch(draft, record), { silent: true });// A PUT answers with the bare record; keep the hydrated refs we already hold.const full = { ...record, ...updated };adoptRecord(full);@@ -469,6 +483,7 @@ export default function ThreadsTab() {{drawerTab === 'details' && (<div className="space-y-3">+ <ThreadPasteBlocks notes={record.notes} tags={record.tags} /><FormField label="Title"><input value={draft.title} onChange={(e) => patchDraft({ title: e.target.value })} className={inputClass} maxLength={200} /></FormField>diff --git a/client/src/components/brain/tabs/ThreadsTab.test.jsx b/client/src/components/brain/tabs/ThreadsTab.test.jsxindex 84b7de3f0b..b7c6b5e217 100644--- a/client/src/components/brain/tabs/ThreadsTab.test.jsx+++ b/client/src/components/brain/tabs/ThreadsTab.test.jsx@@ -235,6 +235,26 @@ describe('ThreadsTab', () => {expect(api.getThread).toHaveBeenCalledTimes(1);});+ it('shows a scheduled step with copyable text and keeps its due time when another field is saved', async () => {+ const DUE = '2026-10-07T16:30:00.000Z';+ const step = {+ id: 'act', title: 'Post the clip', status: 'open', tags: ['human-action', 'plan:promo-example'], refs: [], dueAt: DUE,+ notes: 'Part of **Promote "Example Song"**.\n\n1. Open X.\n2. Attach the clip.\n\n## Ready to paste\n\n**X post**\n````text\nNot a person. ```\n````',+ };+ api.getThread.mockResolvedValue({ ...step, resolvedRefs: [] });+ api.updateThread.mockImplementation(async (id, patch) => ({ ...step, ...patch, resolvedRefs: [] }));+ renderTab('/brain/threads?thread=act');+ const card = await screen.findByRole('region', { name: 'Ready to paste' });+ expect(within(card).getByText('Attach the clip.')).toBeTruthy();+ expect(within(card).getByText('X post')).toBeTruthy();+ expect(within(card).getByText('Not a person. ```')).toBeTruthy();+ expect(within(card).getByRole('button', { name: /Copy/ })).toBeTruthy();++ fireEvent.change(screen.getByDisplayValue('Post the clip'), { target: { value: 'Post the opening clip' } });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save' })); });+ expect(api.updateThread).toHaveBeenCalledWith('act', expect.objectContaining({ title: 'Post the opening clip', dueAt: DUE }), { silent: true });+ });+it('is the component the Brain page renders for its threads tab', () => {const clientSrc = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');const brainPage = readFileSync(join(clientSrc, 'pages', 'Brain.jsx'), 'utf8');diff --git a/client/src/components/musicVideo/PromotionPlanPanel.jsx b/client/src/components/musicVideo/PromotionPlanPanel.jsxnew file mode 100644index 0000000000..2c1beb2f33--- /dev/null+++ b/client/src/components/musicVideo/PromotionPlanPanel.jsx@@ -0,0 +1,101 @@+import { useEffect, useState } from 'react';+import { Link } from 'react-router';+import { CalendarClock, Sparkles } from 'lucide-react';+import useProviderModels from '../../hooks/useProviderModels.js';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import { getMusicVideoPromotionPlan, planMusicVideoPromotion } from '../../services/apiMusicVideo.js';+import { formatWeekdayTime } from '../../utils/formatters.js';++const inputCls = 'w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';+const DAY_CHOICES = [3, 7, 14];++/**+ * Promotion plan: one provider call, asked for here, turns the release into a+ * few dated steps only the artist can take (post a clip, answer replies, join+ * the conversations their audience is having), each with explicit+ * instructions and the exact text to paste. The steps land in Review Hub ›+ * Actions and send a notification when due; PortOS never posts anything.+ */+export default function PromotionPlanPanel({ project }) {+ const projectId = project?.id;+ const [steps, setSteps] = useState(null);+ const [goal, setGoal] = useState('');+ const [audience, setAudience] = useState('');+ const [days, setDays] = useState(7);+ const [planning, setPlanning] = useState(false);+ const {+ providers, selectedProviderId, selectedModel, availableModels, setSelectedProviderId, setSelectedModel,+ } = useProviderModels({ allowDefault: true, silent: true });++ useEffect(() => {+ if (!projectId) return undefined;+ let active = true;+ setSteps(null);+ getMusicVideoPromotionPlan(projectId, { silent: true })+ .then((res) => { if (active) setSteps(res?.steps || []); })+ .catch(() => { if (active) setSteps([]); });+ return () => { active = false; };+ }, [projectId]);++ const plan = () => {+ setPlanning(true);+ planMusicVideoPromotion(projectId, {+ ...(selectedProviderId ? { providerId: selectedProviderId } : {}),+ ...(selectedModel ? { model: selectedModel } : {}),+ ...(goal.trim() ? { goal: goal.trim() } : {}),+ ...(audience.trim() ? { audience: audience.trim() } : {}),+ days,+ })+ .then((res) => { if (res?.created) setSteps(res.created); })+ .catch(() => {})+ .finally(() => setPlanning(false));+ };++ const idFor = (name) => `mv-promo-${name}`;+ return (+ <section aria-label="Promotion plan" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">+ <h3 className="text-sm font-medium flex items-center gap-1.5"><CalendarClock size={14} /> Promotion plan</h3>+ <p className="text-port-text-muted">Schedules the steps only you can take, with the text ready to paste. Each one shows up in <Link to="/review" className="text-port-accent underline">Actions</Link> and notifies you when it's time. Planning again replaces the open steps.</p>+ <div className="grid gap-2 sm:grid-cols-2">+ <label htmlFor={idFor('goal')} className="space-y-1">+ <span className="text-port-text-muted">What you want (optional)</span>+ <input id={idFor('goal')} value={goal} maxLength={1500} onChange={(e) => setGoal(e.target.value)}+ placeholder="More people seeing it, more followers" className={inputCls} />+ </label>+ <label htmlFor={idFor('audience')} className="space-y-1">+ <span className="text-port-text-muted">Who to reach (optional)</span>+ <input id={idFor('audience')} value={audience} maxLength={1000} onChange={(e) => setAudience(e.target.value)}+ placeholder="People into AI consciousness" className={inputCls} />+ </label>+ </div>+ <div className="flex flex-wrap items-end gap-2">+ <label htmlFor={idFor('days')} className="space-y-1">+ <span className="block text-port-text-muted">Over</span>+ <select id={idFor('days')} value={days} onChange={(e) => setDays(Number(e.target.value))} className={inputCls}>+ {DAY_CHOICES.map((n) => <option key={n} value={n}>{n} days</option>)}+ </select>+ </label>+ {providers.length > 0 && (+ <ProviderModelSelector providers={providers} selectedProviderId={selectedProviderId} selectedModel={selectedModel}+ availableModels={availableModels} onProviderChange={setSelectedProviderId} onModelChange={setSelectedModel}+ label="Planner" compact alwaysShowModel modelDisabled={availableModels.length === 0}+ emptyProviderOption="Active provider (default)" emptyModelOption="Default model" disabled={planning} />+ )}+ <button type="button" onClick={plan} disabled={planning || !projectId}+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">+ <Sparkles size={13} /> {planning ? 'Planning…' : (steps?.length ? 'Plan again' : 'Plan promotion')}+ </button>+ </div>+ {steps?.length > 0 && (+ <ol aria-label="Scheduled steps" className="space-y-1">+ {steps.map((step) => (+ <li key={step.id} className="flex flex-wrap items-baseline gap-x-2">+ <span className="text-port-text-muted whitespace-nowrap">{formatWeekdayTime(step.dueAt)}</span>+ <Link to={`/brain/threads?thread=${encodeURIComponent(step.id)}`} className="text-port-accent underline min-w-0 break-words">{step.title}</Link>+ </li>+ ))}+ </ol>+ )}+ </section>+ );+}diff --git a/client/src/components/musicVideo/PromotionPlanPanel.test.jsx b/client/src/components/musicVideo/PromotionPlanPanel.test.jsxnew file mode 100644index 0000000000..80b32bdf3d--- /dev/null+++ b/client/src/components/musicVideo/PromotionPlanPanel.test.jsx@@ -0,0 +1,42 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [], setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn() }),+}));+vi.mock('../../services/apiMusicVideo.js', () => ({+ getMusicVideoPromotionPlan: vi.fn(),+ planMusicVideoPromotion: vi.fn(),+}));++import { getMusicVideoPromotionPlan, planMusicVideoPromotion } from '../../services/apiMusicVideo.js';+import PromotionPlanPanel from './PromotionPlanPanel.jsx';++const renderPanel = () => render(<MemoryRouter><PromotionPlanPanel project={{ id: 'mv-1' }} /></MemoryRouter>);++describe('PromotionPlanPanel', () => {+ beforeEach(() => vi.clearAllMocks());++ it('plans with the artist\'s words and lists the scheduled steps as links to their Actions tasks', async () => {+ getMusicVideoPromotionPlan.mockResolvedValue({ steps: [] });+ planMusicVideoPromotion.mockResolvedValue({ created: [{ id: 't1', title: 'Post the opening clip', dueAt: '2026-10-07T16:30:00.000Z' }] });+ renderPanel();+ expect(await screen.findByRole('button', { name: /Plan promotion/ })).toBeTruthy();++ fireEvent.change(screen.getByLabelText('Who to reach (optional)'), { target: { value: 'People into AI consciousness' } });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Plan promotion/ })); });++ expect(planMusicVideoPromotion).toHaveBeenCalledWith('mv-1', { audience: 'People into AI consciousness', days: 7 });+ const link = await screen.findByRole('link', { name: 'Post the opening clip' });+ expect(link).toHaveAttribute('href', '/brain/threads?thread=t1');+ expect(screen.getByRole('button', { name: /Plan again/ })).toBeTruthy();+ });++ it('shows the steps already scheduled for the release', async () => {+ getMusicVideoPromotionPlan.mockResolvedValue({ steps: [{ id: 't9', title: 'Answer replies', dueAt: '2026-10-07T16:30:00.000Z' }] });+ renderPanel();+ expect(await screen.findByRole('link', { name: 'Answer replies' })).toBeTruthy();+ expect(getMusicVideoPromotionPlan).toHaveBeenCalledWith('mv-1', { silent: true });+ });+});diff --git a/client/src/components/musicVideo/stages/PublishStage.jsx b/client/src/components/musicVideo/stages/PublishStage.jsxindex 6a692cbb90..8760e3e8b3 100644--- a/client/src/components/musicVideo/stages/PublishStage.jsx+++ b/client/src/components/musicVideo/stages/PublishStage.jsx@@ -1,12 +1,14 @@import PublishKitPanel from '../PublishKitPanel.jsx';import PublishPostingPanel from '../PublishPostingPanel.jsx';import PublishPlatformsPanel from '../PublishPlatformsPanel.jsx';+import PromotionPlanPanel from '../PromotionPlanPanel.jsx';/*** Publish: the release kit made from the final render (encodes, thumbnails,* captions, chapters), the per-platform copy (#9281), and posting it through* the PortOS Browser with a review before every post (#9282), only to the- * platforms the director turned on (#9287).+ * platforms the director turned on (#9287), then a promotion plan of dated+ * steps for the director with reminders.*/export default function PublishStage({ board }) {const { project, locked, publishKit, publishing } = board;@@ -15,6 +17,7 @@ export default function PublishStage({ board }) {{publishing && <PublishPlatformsPanel publishing={publishing} />}<PublishKitPanel project={project} publishKit={publishKit} enabledTargets={publishing?.enabledTargets} />{publishing && <PublishPostingPanel project={project} publishing={publishing} />}+ <PromotionPlanPanel project={project} /></fieldset>);}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex f6db0f49bc..12cceb9993 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -244,6 +244,10 @@ export const cancelMusicVideoPublishKit = (jobId, options = {}) =>request(`/music-video/publish-kit/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });export const draftMusicVideoPublishCopy = (id, body, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/copy`, { method: 'POST', body: JSON.stringify(body || {}), ...options });+export const getMusicVideoPromotionPlan = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish/promotion-plan`, options);+export const planMusicVideoPromotion = (id, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish/promotion-plan`, { method: 'POST', body: JSON.stringify(body || {}), ...options });export const updateMusicVideoPublishCopy = (id, patch, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/copy`, { method: 'PATCH', body: JSON.stringify(patch || {}), ...options });export const selectMusicVideoPublishThumbnail = (id, filename, options = {}) =>diff --git a/docs/API.md b/docs/API.mdindex fb547b2177..8c0c92803e 100644--- a/docs/API.md+++ b/docs/API.md@@ -561,6 +561,21 @@ settings controls and source-closed UI prompts are tracked separately in #7664.| GET | `/agents/activity/run-events/reconcile` | Where the ledger and the durable run records disagree (filters: `runId`, `limit`) — read-only || POST | `/agents/activity/run-events/reconcile` | Close the run records the ledger proves are finished; reports what it closed |+### Human Actions++Steps only the person can take (press Post, answer replies, upload a file), scheduled for a time.+Each step becomes a Brain thread tagged `human-action` and `plan:<planKey>`, so it appears in+Review Hub › Actions on its day, and an `action_due` notification fires at its due time on the+machine that created it. Planning the same `planKey` again archives that plan's open steps and+leaves finished ones alone. Agents outside PortOS call these with `node scripts/portos-api.js`.++| Method | Endpoint | Description |+|--------|----------|-------------|+| GET | `/human-actions` | List open steps, soonest first (`?planKey=`, `?includeDone=true`) |+| POST | `/human-actions/plans` | Schedule `{ planKey, title, steps: [{ title, dueAt, instructions[], content[{label,text}], links[{label,url}], priority }] }` (`dueAt` needs a UTC offset) |+| GET | `/music-video/:id/publish/promotion-plan` | A music video's open promotion steps |+| POST | `/music-video/:id/publish/promotion-plan` | Plan its promotion with one provider call `{ goal?, audience?, days?, providerId?, model? }` and schedule the steps |+### Notifications| Method | Endpoint | Description |@@ -732,6 +747,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/data` | Data manager/sync || `/api/datadog`, `/api/jira`, `/api/github`, `/api/telegram` | External integrations || `/api/health` | Apple Health metrics, ingest, and XML import |+| `/api/human-actions` | Scheduled steps only the human can take, as Brain threads with reminders ([Human Actions](#human-actions)) || `/api/insights` | Cross-domain insights || `/api/instances`, `/api/sync`, `/api/peer-sync`, `/api/sharing` | Federation / peer sync (see [COMPANION_APP_API.md](./COMPANION_APP_API.md)) || `/api/federation/media/v1` | Authenticated queued peer audio provider (see [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.md)) |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 35db9dd9fe..130fe577b9 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -128,7 +128,7 @@ therefore starts conservatively if it contains a hold or outstanding operations.- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).-- Brain threads (the bullet journal of open loops, #7664) — `data/brain/threads/{uuid}/index.json`, one more member of `BRAIN_ENTITY_TYPES`. A *thread* is one tracked topic or commitment (status, priority, next action, due date, tags, markdown notes) plus a bounded `refs` array (≤100) of `{ kind, id, label }` tuples pointing at the PortOS records and external items that belong to it — vocabulary and routes in `server/lib/threadRefKinds.js`, existence/title lookups in `server/services/threadRefs.js`. `file-primary` rather than `db-primary` *against* this doc's default for related records, because Brain is an established file-primary domain whose federation, tombstone, parity and reconcile pipeline is all keyed off `BRAIN_ENTITY_TYPES`: splitting one Brain record kind into Postgres would fork the domain across two backends and require re-implementing every one of those paths. The refs are a bounded per-record array, not a join needing an index, and search is served by the existing `brainSearchIndex` projection. **Federated like every other Brain entity type** — the user's own open loops crossing to the user's own machines on the established Brain channel, the same posture as `ideas` and `projects`; the machine-local carve-out `idealoomLists.js` uses does NOT apply, because a bullet journal that exists only on one laptop is useless. `source`, `externalState` and `closedAt` are server-managed (no key in the write schemas, so Zod strips a client copy). No `schemaVersions.js` bump and no store migration: brain is intentionally ungated there and `collectionStore` creates its directory lazily. Empty `data.reference/brain/threads.json` seed. Adapters: `server/services/brainStorage.js` (records) and `server/routes/brainThreads.js` (API).+- Brain threads (the bullet journal of open loops, #7664) — `data/brain/threads/{uuid}/index.json`, one more member of `BRAIN_ENTITY_TYPES`. A *thread* is one tracked topic or commitment (status, priority, next action, due date, tags, markdown notes) plus a bounded `refs` array (≤100) of `{ kind, id, label }` tuples pointing at the PortOS records and external items that belong to it — vocabulary and routes in `server/lib/threadRefKinds.js`, existence/title lookups in `server/services/threadRefs.js`. `file-primary` rather than `db-primary` *against* this doc's default for related records, because Brain is an established file-primary domain whose federation, tombstone, parity and reconcile pipeline is all keyed off `BRAIN_ENTITY_TYPES`: splitting one Brain record kind into Postgres would fork the domain across two backends and require re-implementing every one of those paths. The refs are a bounded per-record array, not a join needing an index, and search is served by the existing `brainSearchIndex` projection. **Federated like every other Brain entity type** — the user's own open loops crossing to the user's own machines on the established Brain channel, the same posture as `ideas` and `projects`; the machine-local carve-out `idealoomLists.js` uses does NOT apply, because a bullet journal that exists only on one laptop is useless. `source`, `externalState`, `closedAt` and `remindedFor` (the `dueAt` a scheduled human action's reminder was sent for, `server/services/humanActionReminders.js`) are server-managed (no key in the write schemas, so Zod strips a client copy). No `schemaVersions.js` bump and no store migration: brain is intentionally ungated there and `collectionStore` creates its directory lazily. Empty `data.reference/brain/threads.json` seed. Adapters: `server/services/brainStorage.js` (records) and `server/routes/brainThreads.js` (API).- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's `fits` verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.- Tailcat peer forwards — `data/tailcat-forwards.json`. `file-primary`, **intentionally machine-local — never federated**: each row stores the bearer `tc…` address needed to restart `tailcat forward` after a PortOS reboot or to retry one that failed to start, plus the local/remote port mapping, the optional peer Basic credential, and the last (redacted) startup error. A row is written *before* the forward is attempted, so a failed add stays retryable instead of discarding the operator's pasted capability. The capability must not cross the wire, reach an API response, or appear in logs in full — `listTailcatForwards()` returns only the redacted form (see [features/tailcat-peers.md](./features/tailcat-peers.md)). No sync cursor or tombstone. Adapter: `server/services/tailcatPeer.js`.- Tailcat serve — `data/tailcat-serve.json`. `file-primary`, **intentionally machine-local — never federated**: enabled flag, status, local remote-ingress port (`5565`, migrated from the legacy main API port), key name (`portos-api`), last (redacted) startup error, and the listen `tc…` address needed to restore `tailcat serve` after reboot and to offer Copy in the Instances UI. Adapter: `server/services/tailcatServe.js`. See [features/tailcat-peers.md](./features/tailcat-peers.md).diff --git a/server/index.js b/server/index.jsindex c78846a092..bcf5f4513d 100644--- a/server/index.js+++ b/server/index.js@@ -146,6 +146,7 @@ import creativeCommissionRoutes from './routes/creativeCommissions.js';import gamesRoutes from './routes/games.js';import fableLoomRoutes from './routes/fableLoom.js';import musicVideoRoutes from './routes/musicVideo.js';+import humanActionRoutes from './routes/humanActions.js';import spriteRoutes from './routes/sprites.js';import moodBoardRoutes from './routes/moodBoard.js';import deckRoutes from './routes/decks.js';@@ -420,6 +421,7 @@ app.use('/api/sync', dataSyncRoutes);app.use('/api/meatspace', meatspaceRoutes);app.use('/api/mortalloom', mortallomRoutes);app.use('/api/review', reviewRoutes);+app.use('/api/human-actions', humanActionRoutes);app.use('/api/github', githubRoutes);app.use('/api/settings', settingsRoutes);app.use('/api/telegram', telegramRoutes);@@ -567,6 +569,9 @@ if (!isSmokeBoot()) {// Event-driven notifications for parked Music Video runs (#10156); zero provider calls.import('./services/musicVideo/attentionNotifier.js').then(({ initMusicVideoAttentionNotifier }) => initMusicVideoAttentionNotifier()).catch((err) => console.error(`❌ Music video attention notifier could not start: ${err.message}`));+ // Reminders for scheduled human action steps (Brain threads); zero provider calls.+ import('./services/humanActionReminders.js').then(({ initHumanActionReminders }) => initHumanActionReminders())+ .catch((err) => console.error(`❌ Human action reminders could not start: ${err.message}`));import('./services/fleetLlmHost.js').then(({ startFleetLlmHost }) => startFleetLlmHost()).catch(() => console.error('❌ Dedicated model host listener could not start; open AI Providers → Model host setup.'));// Local file scan only (no provider calls); keeps the federated Claude Codediff --git a/server/lib/README.md b/server/lib/README.mdindex 38ec7f066a..23a67df83f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -149,6 +149,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `telegramValidation.js` | Telegram bot config + test schemas. || `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. **`createReplayBuffer({ maxBytes })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. || `brainThreads.js` | Brain THREAD rules (#7664) — the pure half of the bullet journal (a *thread* is a tracked open loop, never a message thread): `THREAD_STATUSES` / `THREAD_PRIORITIES` / `THREAD_TERMINAL_STATUSES` / `THREAD_ACTIVE_STATUSES`, `isTerminalThreadStatus`, `isThreadOverdue(thread, now)` (never true once finished), `threadNextLine` (the row's "Waiting on X" / next-action line) and the list comparator `compareThreads` (pinned, soonest-due, most recently touched, id — NaN-safe for two undated threads). `brainValidation.js` builds its enums from the arrays, `routes/brainThreads.js` sorts with the comparator, and `client/src/lib/brainThreads.js` re-exports the whole module so the tab, the widget and the server agree. |+| `humanActions.js` | Scheduled human action steps — the pure half: `humanActionPlanSchema` (a plan of dated steps with explicit `instructions`, ready-to-paste `content` and `links`), `humanActionThreadFields` (a step as the Brain thread it is stored as, tagged `human-action` + `plan:<key>`), `buildHumanActionNotes`, and `humanActionReminderDecision` (fire / arm / nothing for one thread, keyed on `remindedFor`). || `threadRefKinds.js` | Brain THREAD ref vocabulary + route table (#7664) — the one `(kind, id)` → label/URL registry in the repo. A *thread* is a tracked topic or commitment (an open loop), never a message thread. `THREAD_REF_KINDS` is the frozen row-per-kind table (brain records, catalog scraps/ingredients, the five app-native creative kinds, goals/apps/messages/CoS tasks, and the external GitHub/GitLab/JIRA/URL kinds); `threadRefUrl(kind, id, context)` builds the deep link and `threadRefLabel(kind)` the chip text, both degrading to `null`/the raw kind for a kind this build does not know so a peer-sourced ref never throws. `isSafeExternalUrl` scheme-guards an external id before it can become an href. Pure (no zod, no db, no services) and re-exported by `client/src/lib/threadRefKinds.js`, which is how `pages/CatalogIngredient.jsx` renders its inbound-ref chips through the same table. Existence/title lookups live in `services/threadRefs.js`; a drift guard fails CI when a kind here has no resolver there. |## Story & narrativediff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex b8857e80e8..d955cae79e 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -811,7 +811,9 @@ export const songAttachmentUploadSchema = z.object({// in the write schemas below, so Zod's unknown-key stripping drops a// client-supplied value. `source` records where an auto-discovered thread came// from, `externalState` what the tracker last said, and `closedAt` is stamped by-// the route when the status enters a terminal state.+// the route when the status enters a terminal state. `remindedFor` is the+// `dueAt` a scheduled human action's reminder was sent for+// (services/humanActionReminders.js), so a restart never repeats it.// Vocabularies live in the pure leaf (`lib/brainThreads.js`) so the client// renders its pickers from the same arrays these enums validate against.diff --git a/server/lib/humanActions.js b/server/lib/humanActions.jsnew file mode 100644index 0000000000..b038d91dd2--- /dev/null+++ b/server/lib/humanActions.js@@ -0,0 +1,121 @@+/**+ * Human action plans — the pure half.+ *+ * A *human action* is a step only the person can take (press Post, reply to+ * people, upload a file), scheduled for a time and carried as a Brain thread so+ * it shows up in Review Hub › Actions and the Open Threads widget like any other+ * commitment. This module owns the request shape, how a step becomes a thread's+ * next action + markdown notes, and when a step's reminder should fire. The+ * service (`services/humanActions.js`) writes the threads; the reminder clock+ * (`services/humanActionReminders.js`) fires one notification per due step.+ */++import { z } from 'zod';+import { THREAD_PRIORITIES, isTerminalThreadStatus } from './brainThreads.js';++export const HUMAN_ACTION_TAG = 'human-action';+export const HUMAN_ACTION_SOURCE = 'human-action';+export const HUMAN_ACTION_PLAN_TAG_PREFIX = 'plan:';++// A step that came due while the server was down still gets its reminder when+// it boots, but not one from last month: past this, the row in Actions is the+// reminder.+export const HUMAN_ACTION_CATCH_UP_MS = 24 * 60 * 60 * 1000;++const planKey = z.string().trim().min(1).max(40)+ .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'planKey must be a lowercase dash slug');++export const humanActionStepSchema = z.object({+ title: z.string().trim().min(1).max(200),+ // When the person should do it. An offset is required so "18:00" is never+ // silently read as UTC.+ dueAt: z.string().datetime({ offset: true }),+ // Explicit, ordered instructions. The first is the thread's next action.+ instructions: z.array(z.string().trim().min(1).max(500)).min(1).max(20),+ // Ready-to-paste text (a caption, a reply), each with a label saying where it goes.+ content: z.array(z.object({+ label: z.string().trim().min(1).max(100),+ text: z.string().trim().min(1).max(5000),+ }).strict()).max(10).optional().default([]),+ links: z.array(z.object({+ label: z.string().trim().max(200).optional().default(''),+ url: z.string().trim().url().max(2000).regex(/^https?:\/\//i, 'links must be http(s)'),+ }).strict()).max(10).optional().default([]),+ priority: z.enum(THREAD_PRIORITIES).optional().default('normal'),+}).strict();++export const humanActionPlanSchema = z.object({+ // Stable id for the plan, so planning again replaces its open steps instead+ // of stacking a second copy of every reminder.+ planKey,+ title: z.string().trim().min(1).max(120),+ steps: z.array(humanActionStepSchema).min(1).max(30),+}).strict();++export const humanActionPlanTag = (key) => `${HUMAN_ACTION_PLAN_TAG_PREFIX}${key}`;++/** A fence longer than any backtick run in `text`, so pasted code can't close it early. */+function fenceFor(text) {+ const longest = Math.max(0, ...(String(text).match(/`+/g) || []).map((run) => run.length));+ return '`'.repeat(Math.max(3, longest + 1));+}++/**+ * The thread notes for one step: numbered instructions, then each piece of+ * ready-to-paste content in its own fenced block (the Threads drawer offers a+ * Copy button per block), then links.+ */+export function buildHumanActionNotes(step, { planTitle = '' } = {}) {+ const parts = [];+ if (planTitle) parts.push(`Part of **${planTitle}**.`);+ parts.push(step.instructions.map((line, i) => `${i + 1}. ${line}`).join('\n'));+ if (step.content?.length) {+ parts.push('## Ready to paste');+ for (const { label, text } of step.content) {+ const fence = fenceFor(text);+ parts.push(`**${label}**\n${fence}text\n${text}\n${fence}`);+ }+ }+ if (step.links?.length) {+ parts.push('## Links');+ parts.push(step.links.map(({ label, url }) => `- [${label || url}](${url})`).join('\n'));+ }+ return parts.join('\n\n');+}++/** The Brain thread a step becomes (the writable fields; the service adds `source`). */+export function humanActionThreadFields(step, plan) {+ return {+ title: step.title,+ status: 'open',+ priority: step.priority || 'normal',+ nextAction: step.instructions[0].slice(0, 500),+ notes: buildHumanActionNotes(step, { planTitle: plan.title }).slice(0, 20000),+ dueAt: new Date(step.dueAt).toISOString(),+ tags: [HUMAN_ACTION_TAG, humanActionPlanTag(plan.planKey)],+ pinned: false,+ waitingOn: '',+ refs: (step.links || []).map(({ label, url }) => ({ kind: 'url', id: url, label: (label || url).slice(0, 300) })),+ };+}++export const isHumanActionThread = (thread) => Array.isArray(thread?.tags) && thread.tags.includes(HUMAN_ACTION_TAG);++/**+ * What the reminder clock should do with one thread right now:+ * - `null` — nothing (not a human action, finished, undated, already reminded+ * for this due time, or due too long ago to be worth a ping)+ * - `{ fire: true }` — due now (or came due recently while PortOS was down)+ * - `{ delayMs }` — arm a timer for the due time+ *+ * `remindedFor` holds the `dueAt` a reminder was sent for, so moving the due+ * time re-arms it while a restart never repeats it.+ */+export function humanActionReminderDecision(thread, now = Date.now()) {+ if (!isHumanActionThread(thread) || isTerminalThreadStatus(thread.status) || thread.status === 'someday') return null;+ const due = Date.parse(thread.dueAt);+ if (!Number.isFinite(due)) return null;+ if (thread.remindedFor === thread.dueAt) return null;+ if (due > now) return { delayMs: due - now };+ return now - due <= HUMAN_ACTION_CATCH_UP_MS ? { fire: true } : null;+}diff --git a/server/lib/humanActions.test.js b/server/lib/humanActions.test.jsnew file mode 100644index 0000000000..a798a1f942--- /dev/null+++ b/server/lib/humanActions.test.js@@ -0,0 +1,73 @@+import { describe, it, expect } from 'vitest';+import {+ HUMAN_ACTION_CATCH_UP_MS,+ humanActionPlanSchema,+ humanActionReminderDecision,+ humanActionThreadFields,+} from './humanActions.js';++const NOW = Date.parse('2026-10-06T18:00:00.000Z');+const plan = humanActionPlanSchema.parse({+ planKey: 'promo-example',+ title: 'Promote "Example Song"',+ steps: [{+ title: 'Post the opening clip on X',+ dueAt: '2026-10-07T10:00:00-07:00',+ instructions: ['Open X and start a new post.', 'Attach clip 0:12–0:35.'],+ content: [{ label: 'Post text', text: 'Code in a caption: ```js\nx()\n```' }],+ links: [{ label: 'Full video', url: 'https://example.com/watch' }],+ priority: 'high',+ }],+});++describe('humanActionPlanSchema', () => {+ it('refuses a due time without an offset, so a local time is never read as UTC', () => {+ const bad = { ...plan, steps: [{ ...plan.steps[0], dueAt: '2026-10-07T10:00:00' }] };+ expect(humanActionPlanSchema.safeParse(bad).success).toBe(false);+ });++ it('refuses a non-http link', () => {+ const bad = { ...plan, steps: [{ ...plan.steps[0], links: [{ url: 'javascript:alert(1)' }] }] };+ expect(humanActionPlanSchema.safeParse(bad).success).toBe(false);+ });+});++describe('humanActionThreadFields', () => {+ it('stores the step as a tagged thread whose notes keep pasted fences intact', () => {+ const fields = humanActionThreadFields(plan.steps[0], plan);+ expect(fields).toMatchObject({+ title: 'Post the opening clip on X',+ status: 'open',+ priority: 'high',+ nextAction: 'Open X and start a new post.',+ dueAt: '2026-10-07T17:00:00.000Z',+ tags: ['human-action', 'plan:promo-example'],+ refs: [{ kind: 'url', id: 'https://example.com/watch', label: 'Full video' }],+ });+ expect(fields.notes).toContain('1. Open X and start a new post.\n2. Attach clip 0:12–0:35.');+ // The pasted text holds a ``` run, so its block is fenced with four.+ expect(fields.notes).toContain('**Post text**\n````text\nCode in a caption: ```js\nx()\n```\n````');+ });+});++describe('humanActionReminderDecision', () => {+ const thread = (overrides = {}) => ({ status: 'open', tags: ['human-action'], dueAt: '2026-10-06T19:00:00.000Z', ...overrides });++ it('arms a timer for a future step and fires one that is due', () => {+ expect(humanActionReminderDecision(thread(), NOW)).toEqual({ delayMs: 60 * 60 * 1000 });+ expect(humanActionReminderDecision(thread({ dueAt: '2026-10-06T17:59:00.000Z' }), NOW)).toEqual({ fire: true });+ });++ it('never repeats a reminder for the same due time, but re-arms a moved one', () => {+ expect(humanActionReminderDecision(thread({ remindedFor: '2026-10-06T19:00:00.000Z' }), NOW)).toBeNull();+ expect(humanActionReminderDecision(thread({ remindedFor: '2026-10-06T12:00:00.000Z' }), NOW)).toEqual({ delayMs: 60 * 60 * 1000 });+ });++ it('skips finished, parked, untagged and long-overdue threads', () => {+ expect(humanActionReminderDecision(thread({ status: 'done' }), NOW)).toBeNull();+ expect(humanActionReminderDecision(thread({ status: 'someday' }), NOW)).toBeNull();+ expect(humanActionReminderDecision(thread({ tags: ['ops'] }), NOW)).toBeNull();+ const stale = new Date(NOW - HUMAN_ACTION_CATCH_UP_MS - 1).toISOString();+ expect(humanActionReminderDecision(thread({ dueAt: stale }), NOW)).toBeNull();+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex a033ad2a1b..07597112d7 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -32,6 +32,7 @@ export * as agentContextValidation from './agentContextValidation.js';export * as appleHealthValidation from './appleHealthValidation.js';export * as brainValidation from './brainValidation.js';export * from './brainThreads.js';+export * from './humanActions.js';export * as catalogValidation from './catalogValidation.js';export * as characterAugmentValidation from './characterAugmentValidation.js';export * as characterEvolutionValidation from './characterEvolutionValidation.js';diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex bde9d3d376..afcc0ef882 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -690,6 +690,14 @@ export const musicVideoPublishCopyDraftSchema = z.object({// The director agreed to replace posts written or edited by hand since the last draft.replaceEdited: z.boolean().optional(),}).strict();+// Plan the promotion as scheduled steps for the artist (Review Hub › Actions).+export const musicVideoPromotionPlanSchema = z.object({+ providerId: z.string().max(200).nullable().optional(),+ model: z.string().max(200).nullable().optional(),+ goal: z.string().trim().max(1500).optional(),+ audience: z.string().trim().max(1000).optional(),+ days: z.number().int().min(1).max(30).optional(),+}).strict();export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().min(1).max(300) }).strict();// Release cover art: a source (a kit thumbnail or a gallery image) composeddiff --git a/server/lib/notificationTypes.js b/server/lib/notificationTypes.jsindex d2b2555cfa..70f6dc91ea 100644--- a/server/lib/notificationTypes.js+++ b/server/lib/notificationTypes.js@@ -11,7 +11,8 @@ export const NOTIFICATION_CATALOG = {AUTOPILOT_PAUSED: { key: 'autopilot_paused', label: 'Autopilot Paused' },DAILY_POST_REMINDER: { key: 'daily_post_reminder', label: 'POST Reminders' },CREATIVE_COMMISSION: { key: 'creative_commission', label: 'Creative Commissions' },- MUSIC_VIDEO_ATTENTION: { key: 'music_video_attention', label: 'Music Video Attention' }+ MUSIC_VIDEO_ATTENTION: { key: 'music_video_attention', label: 'Music Video Attention' },+ ACTION_DUE: { key: 'action_due', label: 'Scheduled Actions Due' }};export const NOTIFICATION_TYPES = Object.fromEntries(diff --git a/server/routes/humanActions.js b/server/routes/humanActions.jsnew file mode 100644index 0000000000..6c5f46baed--- /dev/null+++ b/server/routes/humanActions.js@@ -0,0 +1,34 @@+/**+ * Human action plans — schedule steps only the person can take as Brain+ * threads with reminders (see services/humanActions.js).+ *+ * Mounted at /api/human-actions. Agents call POST /plans (via+ * `node scripts/portos-api.js`) to hand the person a dated, explicit step with+ * its ready-to-paste text instead of a chat message they'll lose.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { humanActionPlanSchema } from '../lib/humanActions.js';+import { listHumanActions, scheduleHumanActionPlan } from '../services/humanActions.js';++const router = Router();++const listQuerySchema = z.object({+ planKey: z.string().trim().min(1).max(40).optional(),+ includeDone: z.enum(['true', 'false']).optional(),+}).strict();++router.get('/', asyncHandler(async (req, res) => {+ const { planKey, includeDone } = validateRequest(listQuerySchema, req.query);+ res.json({ actions: await listHumanActions({ planKey: planKey || null, includeDone: includeDone === 'true' }) });+}));++router.post('/plans', asyncHandler(async (req, res) => {+ const plan = validateRequest(humanActionPlanSchema, req.body ?? {});+ res.status(201).json(await scheduleHumanActionPlan(plan));+}));++export default router;diff --git a/server/routes/humanActions.test.js b/server/routes/humanActions.test.jsnew file mode 100644index 0000000000..c470d2f117--- /dev/null+++ b/server/routes/humanActions.test.js@@ -0,0 +1,70 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// An in-memory thread store behind the brainStorage calls the service makes.+const store = new Map();+vi.mock('../services/brainStorage.js', () => ({+ getThreads: vi.fn(async () => [...store.values()]),+ createThread: vi.fn(async (data) => {+ const record = { id: `t${store.size + 1}`, ...data };+ store.set(record.id, record);+ return record;+ }),+ updateWith: vi.fn(async (_type, id, fn) => {+ const updates = await fn({ ...store.get(id) });+ if (updates) store.set(id, { ...store.get(id), ...updates });+ return store.get(id);+ }),+}));++import humanActionRoutes from './humanActions.js';++const app = express();+app.use(express.json());+app.use('/api/human-actions', humanActionRoutes);+app.use(errorMiddleware);++const step = (title, dueAt) => ({ title, dueAt, instructions: [`Do ${title}`], content: [{ label: 'Post text', text: 'Hello.' }] });+const planBody = (steps) => ({ planKey: 'promo-example', title: 'Promote "Example Song"', steps });++describe('/api/human-actions', () => {+ beforeEach(() => store.clear());++ it('schedules a plan as open, tagged threads, soonest first', async () => {+ const res = await request(app).post('/api/human-actions/plans').send(planBody([+ step('Second', '2026-10-08T18:00:00Z'),+ step('First', '2026-10-07T18:00:00-07:00'),+ ]));+ expect(res.status).toBe(201);+ expect(res.body.created.map((t) => t.title)).toEqual(['First', 'Second']);+ expect(res.body.created[0]).toMatchObject({+ status: 'open', source: 'human-action', nextAction: 'Do First', dueAt: '2026-10-08T01:00:00.000Z',+ tags: ['human-action', 'plan:promo-example'],+ });++ const list = await request(app).get('/api/human-actions?planKey=promo-example');+ expect(list.body.actions.map((t) => t.title)).toEqual(['First', 'Second']);+ });++ it('planning again archives the open steps and leaves finished ones alone', async () => {+ await request(app).post('/api/human-actions/plans').send(planBody([step('Old', '2026-10-07T18:00:00Z'), step('Done', '2026-10-07T19:00:00Z')]));+ store.set('t2', { ...store.get('t2'), status: 'done' });++ const res = await request(app).post('/api/human-actions/plans').send(planBody([step('New', '2026-10-09T18:00:00Z')]));+ expect(res.body.replaced).toBe(1);+ expect(store.get('t1').status).toBe('archived');+ expect(store.get('t2').status).toBe('done');+ const list = await request(app).get('/api/human-actions?planKey=promo-example&includeDone=true');+ expect(list.body.actions.map((t) => t.title)).toEqual(['Old', 'Done', 'New']);+ });++ it('refuses a step with no instructions or a due time without an offset', async () => {+ const noSteps = await request(app).post('/api/human-actions/plans').send(planBody([{ ...step('X', '2026-10-07T18:00:00Z'), instructions: [] }]));+ expect(noSteps.status).toBe(400);+ const naive = await request(app).post('/api/human-actions/plans').send(planBody([step('X', '2026-10-07T18:00:00')]));+ expect(naive.status).toBe(400);+ expect(store.size).toBe(0);+ });+});diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 805d619a15..1aebe58f1b 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -45,6 +45,7 @@ import {musicVideoSocialCutsQuerySchema,musicVideoPublishCopyPatchSchema,musicVideoPublishCopyDraftSchema,+ musicVideoPromotionPlanSchema,musicVideoPublishThumbnailSchema,musicVideoCoverArtComposeSchema,musicVideoCoverArtGenerateSchema,@@ -921,6 +922,19 @@ router.post('/:id/publish-kit/copy', asyncHandler(async (req, res) => {res.json({ project });}));+// The release's scheduled promotion steps (open ones), soonest first.+router.get('/:id/publish/promotion-plan', asyncHandler(async (req, res) => {+ const { promotionPlanSteps } = await import('../services/musicVideo/promotionPlan.js');+ res.json(await promotionPlanSteps(req.params.id));+}));++// Turn the release into dated steps only the artist can take, with reminders.+router.post('/:id/publish/promotion-plan', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoPromotionPlanSchema, req.body || {});+ const { planMusicVideoPromotion } = await import('../services/musicVideo/promotionPlan.js');+ res.status(201).json(await planMusicVideoPromotion(req.params.id, input));+}));+router.patch('/:id/publish-kit/copy', asyncHandler(async (req, res) => {const patch = validateRequest(musicVideoPublishCopyPatchSchema, req.body || {});const { project } = await updatePublishKitCopy(req.params.id, patch);diff --git a/server/services/humanActionReminders.js b/server/services/humanActionReminders.jsnew file mode 100644index 0000000000..c566aa5146--- /dev/null+++ b/server/services/humanActionReminders.js@@ -0,0 +1,134 @@+/**+ * Human action reminders — one notification when a scheduled step comes due.+ *+ * Arms a one-shot `eventScheduler` timer per open `human-action` thread, re-arms+ * on every thread write (a moved due time, a finished step, a peer-sync apply)+ * and fires `ACTION_DUE` through the normal notification store, which fans out+ * to the bell, Telegram forwarding and voice. The thread records the due time it+ * was reminded for (`remindedFor`), so a restart never repeats a reminder and a+ * step that came due while the server was down is caught up at boot.+ *+ * Only the machine that created a step reminds for it: threads federate to the+ * user's other machines, and each one pinging for the same step would be noise.+ *+ * Deterministic: no provider calls. Started from boot, never by import side+ * effect, so a test that loads the services never writes the notification store.+ */++import * as brainStorage from './brainStorage.js';+import { brainEvents } from './brainStorage.js';+import * as eventScheduler from './eventScheduler.js';+import { addNotification, NOTIFICATION_TYPES } from './notifications.js';+import { humanActionReminderDecision } from '../lib/humanActions.js';++const EVENT_PREFIX = 'human-action-due:';++// threadId → the dueAt its armed timer is for, so a write that leaves the due+// time alone doesn't cancel and re-arm (and re-log) the same timer.+const armed = new Map();+let instanceId = null;+let reconcileTail = Promise.resolve();+let started = false;++const threadLink = (id) => `/brain/threads?thread=${encodeURIComponent(id)}`;++function disarm(id) {+ armed.delete(id);+ eventScheduler.cancel(`${EVENT_PREFIX}${id}`);+}++/** Send the reminder for one thread if it is still due and not yet reminded. */+export async function fireHumanActionReminder(threadId, deps = {}) {+ const storage = deps.storage || brainStorage;+ const notify = deps.addNotification || addNotification;+ const now = deps.now ? deps.now() : Date.now();+ armed.delete(threadId);+ let reminded = null;+ // Stamp first, under the record's write queue, so two fires (a timer and a+ // boot catch-up) can't both notify.+ await storage.updateWith('threads', threadId, (fresh) => {+ if (humanActionReminderDecision(fresh, now)?.fire !== true) return null;+ reminded = fresh;+ return { remindedFor: fresh.dueAt };+ });+ if (!reminded) return false;+ await notify({+ type: NOTIFICATION_TYPES.ACTION_DUE,+ title: `Time to: ${reminded.title}`,+ description: reminded.nextAction || 'Open the step for its instructions.',+ priority: ['high', 'urgent'].includes(reminded.priority) ? 'high' : 'medium',+ link: threadLink(threadId),+ metadata: { threadId, dueAt: reminded.dueAt },+ });+ console.log(`⏰ Human action due: ${reminded.title}`);+ return true;+}++/** Arm, re-arm, disarm or fire for every human action thread this machine created. */+export async function reconcileHumanActionReminders(deps = {}) {+ const storage = deps.storage || brainStorage;+ const scheduler = deps.scheduler || eventScheduler;+ const now = deps.now ? deps.now() : Date.now();+ const origin = deps.instanceId ?? instanceId;+ const threads = (await storage.getThreads()) || [];+ const keep = new Set();+ const dueNow = [];+ for (const thread of threads) {+ if (origin && thread.originInstanceId && thread.originInstanceId !== origin) continue;+ const decision = humanActionReminderDecision(thread, now);+ if (!decision) continue;+ if (decision.fire) { dueNow.push(thread.id); continue; }+ keep.add(thread.id);+ if (armed.get(thread.id) === thread.dueAt) continue;+ armed.set(thread.id, thread.dueAt);+ scheduler.schedule({+ id: `${EVENT_PREFIX}${thread.id}`,+ type: 'once',+ delayMs: decision.delayMs,+ metadata: { description: `Reminder: ${thread.title}`, threadId: thread.id },+ handler: () => fireHumanActionReminder(thread.id, deps).catch((err) => {+ console.error(`❌ Human action reminder failed for ${thread.id}: ${err.message}`);+ }),+ });+ }+ for (const id of [...armed.keys()]) {+ if (!keep.has(id)) {+ armed.delete(id);+ scheduler.cancel(`${EVENT_PREFIX}${id}`);+ }+ }+ for (const id of dueNow) await fireHumanActionReminder(id, deps);+ return { armed: keep.size, fired: dueNow.length };+}++// Writes arrive in bursts (a whole plan at once), so chain reconciles: each one+// reads the freshest records after the previous one settles.+function queueReconcile() {+ reconcileTail = reconcileTail+ .then(() => reconcileHumanActionReminders())+ .catch((err) => console.error(`❌ Human action reminders could not reconcile: ${err.message}`));+ return reconcileTail;+}++const onThreadEvent = () => { queueReconcile(); };+const onRecordChanged = ({ type } = {}) => { if (type === 'threads') queueReconcile(); };++export async function initHumanActionReminders() {+ if (started) return;+ started = true;+ const { getInstanceId } = await import('./instanceIdentity.js');+ instanceId = await getInstanceId().catch(() => null);+ brainEvents.on('threads:upserted', onThreadEvent);+ brainEvents.on('threads:deleted', onThreadEvent);+ brainEvents.on('record:changed', onRecordChanged);+ const { armed: count, fired } = await queueReconcile() || {};+ console.log(`⏰ Human action reminders ready${count ? ` (${count} armed)` : ''}${fired ? `, ${fired} caught up` : ''}`);+}++export function stopHumanActionReminders() {+ brainEvents.off('threads:upserted', onThreadEvent);+ brainEvents.off('threads:deleted', onThreadEvent);+ brainEvents.off('record:changed', onRecordChanged);+ for (const id of [...armed.keys()]) disarm(id);+ started = false;+}diff --git a/server/services/humanActionReminders.test.js b/server/services/humanActionReminders.test.jsnew file mode 100644index 0000000000..bf3a9bcb74--- /dev/null+++ b/server/services/humanActionReminders.test.js@@ -0,0 +1,97 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./brainStorage.js', () => ({ brainEvents: { on: vi.fn(), off: vi.fn() }, getThreads: vi.fn(), updateWith: vi.fn() }));+vi.mock('./eventScheduler.js', () => ({ schedule: vi.fn(), cancel: vi.fn() }));+vi.mock('./notifications.js', () => ({ addNotification: vi.fn(), NOTIFICATION_TYPES: { ACTION_DUE: 'action_due' } }));++import { fireHumanActionReminder, reconcileHumanActionReminders, stopHumanActionReminders } from './humanActionReminders.js';++const NOW = Date.parse('2026-10-06T18:00:00.000Z');+const ME = 'instance-a';++// A thread store with updateWith's contract: writes to one record queue+// behind each other, fn sees the fresh record, its partial is merged in, and+// null leaves the record alone.+function fakeStore(threads) {+ const byId = new Map(threads.map((t) => [t.id, { ...t }]));+ let tail = Promise.resolve();+ const write = async (id, fn) => {+ const fresh = byId.get(id);+ if (!fresh) return null;+ const updates = await fn({ ...fresh });+ if (!updates) return null;+ byId.set(id, { ...fresh, ...updates });+ return byId.get(id);+ };+ return {+ byId,+ getThreads: vi.fn(async () => [...byId.values()]),+ updateWith: vi.fn((_type, id, fn) => {+ const result = tail.then(() => write(id, fn));+ tail = result.catch(() => {});+ return result;+ }),+ };+}++const step = (overrides = {}) => ({+ id: 'step-1', title: 'Post the clip', status: 'open', priority: 'high', nextAction: 'Open X',+ tags: ['human-action'], originInstanceId: ME, dueAt: '2026-10-06T19:00:00.000Z', ...overrides,+});++const depsFor = (storage) => ({+ storage,+ scheduler: { schedule: vi.fn(), cancel: vi.fn() },+ addNotification: vi.fn(async () => ({})),+ now: () => NOW,+ instanceId: ME,+});++describe('human action reminders', () => {+ beforeEach(() => stopHumanActionReminders());++ it('arms future steps, catches up a due one once, and skips steps another machine created', async () => {+ const storage = fakeStore([+ step(),+ step({ id: 'due', title: 'Answer replies', dueAt: '2026-10-06T17:30:00.000Z', priority: 'normal' }),+ step({ id: 'peer', originInstanceId: 'instance-b', dueAt: '2026-10-06T17:30:00.000Z' }),+ ]);+ const deps = depsFor(storage);++ expect(await reconcileHumanActionReminders(deps)).toEqual({ armed: 1, fired: 1 });+ expect(deps.scheduler.schedule).toHaveBeenCalledWith(expect.objectContaining({ id: 'human-action-due:step-1', type: 'once', delayMs: 60 * 60 * 1000 }));+ expect(deps.addNotification).toHaveBeenCalledTimes(1);+ expect(deps.addNotification).toHaveBeenCalledWith(expect.objectContaining({+ type: 'action_due', title: 'Time to: Answer replies', priority: 'medium', link: '/brain/threads?thread=due',+ }));+ expect(storage.byId.get('due').remindedFor).toBe('2026-10-06T17:30:00.000Z');++ // A restart (or the write the stamp itself triggers) neither repeats the+ // reminder nor re-arms the unchanged timer.+ expect(await reconcileHumanActionReminders(deps)).toEqual({ armed: 1, fired: 0 });+ expect(deps.addNotification).toHaveBeenCalledTimes(1);+ expect(deps.scheduler.schedule).toHaveBeenCalledTimes(1);+ });++ it('disarms a step that was finished and re-arms one whose due time moved', async () => {+ const storage = fakeStore([step()]);+ const deps = depsFor(storage);+ await reconcileHumanActionReminders(deps);++ storage.byId.set('step-1', { ...storage.byId.get('step-1'), dueAt: '2026-10-06T20:00:00.000Z' });+ await reconcileHumanActionReminders(deps);+ expect(deps.scheduler.schedule).toHaveBeenLastCalledWith(expect.objectContaining({ delayMs: 2 * 60 * 60 * 1000 }));++ storage.byId.set('step-1', { ...storage.byId.get('step-1'), status: 'done' });+ await reconcileHumanActionReminders(deps);+ expect(deps.scheduler.cancel).toHaveBeenCalledWith('human-action-due:step-1');+ });++ it('notifies once when the timer and a catch-up fire for the same step', async () => {+ const storage = fakeStore([step({ dueAt: '2026-10-06T17:59:00.000Z' })]);+ const deps = depsFor(storage);+ const fired = await Promise.all([fireHumanActionReminder('step-1', deps), fireHumanActionReminder('step-1', deps)]);+ expect(fired.filter(Boolean)).toHaveLength(1);+ expect(deps.addNotification).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/humanActions.js b/server/services/humanActions.jsnew file mode 100644index 0000000000..57d85e58da--- /dev/null+++ b/server/services/humanActions.js@@ -0,0 +1,64 @@+/**+ * Human action plans — scheduled steps only the person can take.+ *+ * Each step is written as a Brain thread tagged `human-action` (and+ * `plan:<planKey>`), so it lands in Review Hub › Actions on its day and in the+ * Open Threads widget with no new UI. The step's instructions and its+ * ready-to-paste content live in the thread's next action + notes; the+ * reminder clock (`humanActionReminders.js`) notifies when it comes due.+ *+ * Planning the same `planKey` again replaces that plan's steps that are still+ * open, and leaves the ones the person already finished alone.+ */++import * as brainStorage from './brainStorage.js';+import {+ HUMAN_ACTION_SOURCE,+ humanActionPlanTag,+ humanActionThreadFields,+ isHumanActionThread,+} from '../lib/humanActions.js';+import { isTerminalThreadStatus } from '../lib/brainThreads.js';++/**+ * Write a validated plan (see `humanActionPlanSchema`) as Brain threads.+ * Returns `{ planKey, created: [thread], replaced: number }`.+ */+export async function scheduleHumanActionPlan(plan) {+ const tag = humanActionPlanTag(plan.planKey);+ const existing = (await brainStorage.getThreads()) || [];+ const stale = existing.filter((thread) => isHumanActionThread(thread)+ && thread.tags.includes(tag)+ && !isTerminalThreadStatus(thread.status));+ // Archive rather than delete: a replaced step stays in History, so nothing+ // the person was looking at vanishes without a trace.+ const closedAt = new Date().toISOString();+ for (const thread of stale) {+ await brainStorage.updateWith('threads', thread.id, (fresh) => (isTerminalThreadStatus(fresh.status)+ ? null+ : { status: 'archived', closedAt }));+ }+ const steps = [...plan.steps].sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt));+ const created = [];+ for (const step of steps) {+ created.push(await brainStorage.createThread({+ ...humanActionThreadFields(step, plan),+ source: HUMAN_ACTION_SOURCE,+ externalState: 'unknown',+ closedAt: null,+ }));+ }+ console.log(`🗓️ Human action plan "${plan.title}": ${created.length} step(s) scheduled, ${stale.length} replaced`);+ return { planKey: plan.planKey, created, replaced: stale.length };+}++/** Human action threads, soonest due first. `includeDone` adds finished ones. */+export async function listHumanActions({ planKey = null, includeDone = false } = {}) {+ const threads = (await brainStorage.getThreads()) || [];+ const tag = planKey ? humanActionPlanTag(planKey) : null;+ return threads+ .filter((thread) => isHumanActionThread(thread)+ && (!tag || thread.tags.includes(tag))+ && (includeDone || !isTerminalThreadStatus(thread.status)))+ .sort((a, b) => (Date.parse(a.dueAt) || Infinity) - (Date.parse(b.dueAt) || Infinity));+}diff --git a/server/services/musicVideo/promotionPlan.js b/server/services/musicVideo/promotionPlan.jsnew file mode 100644index 0000000000..b299734e33--- /dev/null+++ b/server/services/musicVideo/promotionPlan.js@@ -0,0 +1,47 @@+/**+ * Music Video — plan the promotion as scheduled human action steps.+ *+ * One provider call the artist asked for (the Publish stage's "Plan promotion"+ * button) turns the release into a few dated steps only they can take — post a+ * clip, answer replies, join the conversations their audience is having — each+ * with explicit instructions and the exact text to paste. The steps become+ * Brain threads with reminders (services/humanActions.js), so they appear in+ * Review Hub › Actions and ping when due. PortOS never posts anything itself.+ */+import { ServerError } from '../../lib/errorHandler.js';+import { humanActionPlanSchema } from '../../lib/humanActions.js';+import { getProject } from './projects.js';+import { suggestSocialCuts } from './socialCuts.js';+import { buildPromotionPlanPrompt, parsePromotionPlan, postedLinks, promotionPlanKey } from './promotionPlanText.js';++const planError = (status, code, message) => new ServerError(message, { status, code });++export async function planMusicVideoPromotion(projectId, { providerId = null, model = null, goal = '', audience = '', days = 7 } = {}, deps = {}) {+ const project = await (deps.getProject || getProject)(projectId);+ if (!project) throw planError(404, 'NOT_FOUND', 'Project not found');+ const timezone = deps.timezone || await (await import('../userTimezone.js')).getUserTimezone();+ const cuts = suggestSocialCuts(project, { count: 4, minSec: 15, maxSec: 40 });+ const { resolveProviderAndModel, runPromptThroughProvider } = deps.runner || await import('../promptRunner.js');+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ if (!provider) throw planError(503, 'NO_PROVIDER', 'No AI provider is available to plan the promotion');+ const prompt = buildPromotionPlanPrompt(project, { goal, audience, days, cuts, timezone });+ const { text } = await runPromptThroughProvider({ provider, model: selectedModel, prompt, source: 'music-video-promotion-plan' });+ const steps = parsePromotionPlan(text, { days, timezone, now: deps.now ? deps.now() : Date.now(), allowedLinks: Object.values(postedLinks(project)) });+ if (!steps) throw planError(502, 'PROMOTION_PLAN_UNPARSEABLE', 'The plan came back without usable steps — try again or another model');+ const plan = humanActionPlanSchema.parse({+ planKey: promotionPlanKey(project.id || projectId),+ title: `Promote "${project.name || 'the music video'}"`.slice(0, 120),+ steps,+ });+ const { scheduleHumanActionPlan } = deps.humanActions || await import('../humanActions.js');+ return scheduleHumanActionPlan(plan);+}++/** The project's open promotion steps, soonest first: `{ planKey, steps }`. */+export async function promotionPlanSteps(projectId, deps = {}) {+ const project = await (deps.getProject || getProject)(projectId);+ if (!project) throw planError(404, 'NOT_FOUND', 'Project not found');+ const planKey = promotionPlanKey(project.id || projectId);+ const { listHumanActions } = deps.humanActions || await import('../humanActions.js');+ return { planKey, steps: await listHumanActions({ planKey }) };+}diff --git a/server/services/musicVideo/promotionPlan.test.js b/server/services/musicVideo/promotionPlan.test.jsnew file mode 100644index 0000000000..3c110e2781--- /dev/null+++ b/server/services/musicVideo/promotionPlan.test.js@@ -0,0 +1,87 @@+import { describe, it, expect, vi } from 'vitest';+import { planMusicVideoPromotion } from './promotionPlan.js';+import { buildPromotionPlanPrompt, promotionPlanKey, promotionStepDueAt } from './promotionPlanText.js';++// 2026-10-06 11:00 in Los Angeles.+const NOW = Date.parse('2026-10-06T18:00:00.000Z');+const TZ = 'America/Los_Angeles';++const project = {+ id: 'mv-1234abcd-0000',+ name: 'Example Song',+ lyricCues: [{ text: 'This voice is not a person', startSec: 12 }, { text: 'Neither is yours', startSec: 15.5 }],+ publishKit: {+ posts: { x: { url: 'https://x.example.com/status/1' }, youtube: { url: 'https://video.example.com/watch?v=1' } },+ copy: { x: { hook: 'A song about minds.' } },+ },+};++const reply = JSON.stringify({ steps: [+ {+ title: 'Post the opening clip on X', day: 1, time: '09:30', priority: 'high',+ instructions: ['Cut 0:12–0:35 from the vertical cut.', 'Quote-post your video post with it.'],+ content: [{ label: 'X post', text: 'This voice is not a person.' }],+ links: [{ label: 'Your post', url: 'https://x.example.com/status/1' }, { label: 'Made up', url: 'https://invented.example.com' }],+ },+ { title: 'Answer replies', day: 0, time: '08:00', instructions: ['Reply to everyone who answered.'] },+ { title: 'No instructions', day: 2, time: '10:00', instructions: [] },+ { title: 'Far day', day: 99, time: '25:99', instructions: ['Check in.'] },+] });++const deps = () => ({+ getProject: vi.fn(async () => project),+ timezone: TZ,+ now: () => NOW,+ runner: {+ resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'p' }, selectedModel: 'm' })),+ runPromptThroughProvider: vi.fn(async () => ({ text: reply })),+ },+ humanActions: { scheduleHumanActionPlan: vi.fn(async (plan) => ({ planKey: plan.planKey, created: plan.steps, replaced: 0 })) },+});++describe('planMusicVideoPromotion', () => {+ it('turns one provider reply into a dated human action plan with only real links', async () => {+ const d = deps();+ await planMusicVideoPromotion(project.id, { goal: 'More followers', audience: 'People into AI consciousness', days: 7 }, d);++ const call = d.runner.runPromptThroughProvider.mock.calls[0][0];+ expect(call.source).toBe('music-video-promotion-plan');+ expect(call.prompt).toContain('People into AI consciousness');+ expect(call.prompt).toContain('- x: https://x.example.com/status/1');+ expect(call.prompt).toContain('0:12 This voice is not a person');++ const plan = d.humanActions.scheduleHumanActionPlan.mock.calls[0][0];+ expect(plan.planKey).toBe('promo-mv-1234abcd-0000');+ expect(plan.title).toBe('Promote "Example Song"');+ expect(plan.steps.map((s) => s.title)).toEqual(['Post the opening clip on X', 'Answer replies', 'Far day']);+ // Tomorrow 09:30 Los Angeles; an invented link is dropped.+ expect(plan.steps[0]).toMatchObject({ dueAt: '2026-10-07T16:30:00.000Z', priority: 'high', links: [{ label: 'Your post', url: 'https://x.example.com/status/1' }] });+ // Today 08:00 has already passed, so it is due in a few minutes rather than in the past.+ expect(plan.steps[1].dueAt).toBe('2026-10-06T18:05:00.000Z');+ // Day clamps to the last day of the window; a malformed time falls back to 18:00.+ expect(plan.steps[2].dueAt).toBe('2026-10-13T01:00:00.000Z');+ });++ it('reports an unusable reply instead of scheduling nothing', async () => {+ const d = deps();+ d.runner.runPromptThroughProvider.mockResolvedValue({ text: 'Sorry, no plan.' });+ await expect(planMusicVideoPromotion(project.id, {}, d)).rejects.toMatchObject({ code: 'PROMOTION_PLAN_UNPARSEABLE' });+ expect(d.humanActions.scheduleHumanActionPlan).not.toHaveBeenCalled();+ });+});++describe('promotion plan text', () => {+ it('keeps plan keys inside the tag limit', () => {+ expect(promotionPlanKey('mv-f507dc16-26a8-40c4-b905-c61536bbb3d6').length).toBeLessThanOrEqual(40);+ expect(promotionPlanKey('mv-f507dc16-26a8-40c4-b905-c61536bbb3d6')).toMatch(/^[a-z0-9]+(-[a-z0-9]+)*$/);+ });++ it('places a step across a DST change at its local time', () => {+ // 2026-11-01 is the US fall-back day; 18:00 local is 02:00Z the next day (PST, UTC-8).+ expect(promotionStepDueAt(0, '18:00', TZ, Date.parse('2026-11-01T17:00:00.000Z'))).toBe('2026-11-02T02:00:00.000Z');+ });++ it('says nothing has been posted when nothing has', () => {+ expect(buildPromotionPlanPrompt({ name: 'X' }, { timezone: TZ })).toContain('Nothing has been posted yet.');+ });+});diff --git a/server/services/musicVideo/promotionPlanText.js b/server/services/musicVideo/promotionPlanText.jsnew file mode 100644index 0000000000..0207b2c7be--- /dev/null+++ b/server/services/musicVideo/promotionPlanText.js@@ -0,0 +1,128 @@+/**+ * Music Video — promotion plan prompt + parser. Pure: project in, prompt out;+ * model reply in, human action steps out (see lib/humanActions.js).+ *+ * The plan is a short run of dated steps only the artist can take (post a+ * clip, answer replies, join a conversation), each with explicit instructions+ * and the exact text to paste, so the artist never has to remember or decide+ * on the day. PortOS never posts: every step ends with the artist pressing Post.+ */+import { extractJson } from '../../lib/jsonExtract.js';+import { fenceBlock } from '../../lib/promptFencing.js';+import { anchorLocalMidnightUtc, nextLocalTime, parseHHMM, todayInTimezone } from '../../lib/timezone.js';++export const PROMOTION_PLAN_MAX_STEPS = 20;++const finite = (n) => (typeof n === 'number' && Number.isFinite(n) ? n : null);+const str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : '');+const clock = (sec) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`;++/** Planning the same project again replaces its open steps. */+export const promotionPlanKey = (projectId) => `promo-${String(projectId).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`.slice(0, 40).replace(/-+$/, '');++function timedLyrics(project) {+ return (project?.lyricCues || [])+ .filter((c) => c && typeof c.text === 'string' && c.text.trim() && finite(c.startSec) != null)+ .sort((a, b) => a.startSec - b.startSec)+ .map((c) => `${clock(c.startSec)} ${c.text.trim()}`)+ .join('\n');+}++/** The posted links as `{ platform: url }`, http(s) only. */+export function postedLinks(project) {+ const posts = project?.publishKit?.posts && typeof project.publishKit.posts === 'object' ? project.publishKit.posts : {};+ return Object.fromEntries(Object.entries(posts)+ .map(([platform, post]) => [platform, typeof post?.url === 'string' ? post.url.trim() : ''])+ .filter(([, url]) => /^https?:\/\//i.test(url)));+}++/**+ * The plan prompt. `goal` and `audience` are the artist's own words; `cuts`+ * are suggested clip windows (`{ startSec, endSec, label }`); `days` bounds the+ * schedule. Only given facts may be claimed.+ */+export function buildPromotionPlanPrompt(project, { goal = '', audience = '', days = 7, cuts = [], timezone = 'UTC' } = {}) {+ const links = postedLinks(project);+ const copy = project?.publishKit?.copy && typeof project.publishKit.copy === 'object' ? project.publishKit.copy : {};+ const facts = [+ project?.name ? `Song title: ${project.name}` : null,+ `Artist's timezone: ${timezone}`,+ Object.keys(links).length ? `Already posted:\n${Object.entries(links).map(([p, url]) => `- ${p}: ${url}`).join('\n')}` : 'Nothing has been posted yet.',+ cuts.length ? `Suggested clip windows from the video:\n${cuts.map((c) => `- ${clock(c.startSec)}–${clock(c.endSec)}${c.label ? ` (${c.label})` : ''}`).join('\n')}` : null,+ ].filter(Boolean).join('\n\n');+ const copyText = Object.entries(copy)+ .map(([platform, fields]) => `${platform}: ${Object.values(fields || {}).filter((v) => typeof v === 'string' && v.trim()).join(' / ')}`)+ .filter((line) => line.length > 3)+ .join('\n');+ return [+ `Plan the next ${days} days of promotion for a music video the artist made, as a short list of dated steps ONLY THE ARTIST can do by hand (nobody posts for them). The aim is more of the right people seeing it, without looking like spam or getting the account downranked.`,+ 'How the platforms reward attention (use this):',+ [+ '- Conversation counts most: replies, and the artist answering them quickly. Plan short sessions answering replies.',+ '- Reach beyond followers comes from taking part in conversations the target audience is already having: thoughtful replies with an opinion, no link and no video.',+ '- Short hook clips (15–40 s) as NEW posts, each quote-posting or linking the full video, one every day or two. Never the same clip or caption twice.',+ '- Links in a main X post cut its reach: keep links in a reply under the post.',+ '- Avoid: link-dropping in other people\'s replies, tagging people who are not involved, hashtag stacks, deleting and reposting, engagement pods, asking for likes.',+ ].join('\n'),+ 'Style: few words. Every post or reply the artist pastes is a sentence or two at most, first person, plain, no emoji, no hashtags, no hype. Use ONLY the facts given; never invent links, numbers or events.',+ goal ? fenceBlock('What the artist wants', goal, 1500) : '',+ audience ? fenceBlock('Who they want to reach', audience, 1000) : '',+ facts,+ copyText ? fenceBlock('Copy already written for this release', copyText, 3000) : '',+ timedLyrics(project) ? fenceBlock('Timed lyrics (pick hook lines for clips from these)', timedLyrics(project), 4000) : '',+ `Return ONLY a JSON object: {"steps":[{"title":"…","day":0,"time":"18:00","priority":"normal","instructions":["…"],"content":[{"label":"…","text":"…"}],"links":[{"label":"…","url":"…"}]}]}`,+ [+ `- At most ${PROMOTION_PLAN_MAX_STEPS} steps. "day" is 0–${days - 1} (0 is today), "time" is local HH:MM, chosen for when the audience is online.`,+ '- "title": what to do, in a few words (e.g. "Post the opening clip on X").',+ '- "instructions": explicit, numbered-ready steps a person can follow without thinking: which clip (with its timestamps), where to tap, what to paste, what to check. 2–6 short lines.',+ '- "content": every piece of text to paste, exactly as it should be posted, each labelled with where it goes. Empty only for steps with nothing to paste.',+ '- "links": only links from "Already posted"; empty otherwise.',+ '- "priority": "high" for the steps that matter most, else "normal".',+ ].join('\n'),+ ].filter(Boolean).join('\n\n');+}++/** Local `day` (0 = today) at `time` HH:MM in `timezone`, as an ISO instant; never in the past. */+export function promotionStepDueAt(day, time, timezone, now = Date.now()) {+ const today = todayInTimezone(timezone, new Date(now));+ const [y, m, d] = today.split('-').map(Number);+ const target = new Date(Date.UTC(y, m - 1, d + day)).toISOString().slice(0, 10);+ const midnight = anchorLocalMidnightUtc(target, timezone);+ const minutes = parseHHMM(time) ?? 18 * 60;+ const due = Number.isFinite(midnight) ? nextLocalTime(midnight, Math.floor(minutes / 60), minutes % 60, timezone) : now;+ // A slot that already passed today becomes "in a few minutes".+ return new Date(Math.max(due, now + 5 * 60_000)).toISOString();+}++/**+ * The model's reply as human action steps (`humanActionStepSchema` shape), or+ * null when unusable. Links the model was not given are dropped.+ */+export function parsePromotionPlan(text, { days = 7, timezone = 'UTC', now = Date.now(), allowedLinks = [] } = {}) {+ const { value } = extractJson(text, { blockType: 'object' });+ const raw = Array.isArray(value?.steps) ? value.steps : null;+ if (!raw) return null;+ const allowed = new Set(allowedLinks);+ const steps = raw.slice(0, PROMOTION_PLAN_MAX_STEPS).flatMap((step) => {+ if (!step || typeof step !== 'object') return [];+ const title = str(step.title, 200);+ const instructions = (Array.isArray(step.instructions) ? step.instructions : []).map((l) => str(l, 500)).filter(Boolean).slice(0, 20);+ if (!title || !instructions.length) return [];+ const day = Math.min(Math.max(Math.round(Number(step.day) || 0), 0), days - 1);+ return [{+ title,+ dueAt: promotionStepDueAt(day, typeof step.time === 'string' ? step.time : '', timezone, now),+ instructions,+ content: (Array.isArray(step.content) ? step.content : [])+ .map((c) => ({ label: str(c?.label, 100), text: str(c?.text, 5000) }))+ .filter((c) => c.label && c.text)+ .slice(0, 10),+ links: (Array.isArray(step.links) ? step.links : [])+ .map((l) => ({ label: str(l?.label, 200), url: str(l?.url, 2000) }))+ .filter((l) => allowed.has(l.url))+ .slice(0, 10),+ priority: ['high', 'urgent'].includes(step.priority) ? 'high' : 'normal',+ }];+ });+ return steps.length ? steps : null;+}