Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: make the persistent mind observable and conversational

Adam Eivy18d49a0abab7
diff --git a/client/src/components/cos/PersistentMindContextPanel.jsx b/client/src/components/cos/PersistentMindContextPanel.jsx
new file mode 100644
index 0000000000..5c89d2ad8b
--- /dev/null
+++ b/client/src/components/cos/PersistentMindContextPanel.jsx
@@ -0,0 +1,226 @@
+import { useCallback, useEffect, useId, useState } from 'react';
+import { Brain, Database, Eye, Plus, RefreshCw, Save } from 'lucide-react';
+import * as api from '../../services/api';
+import BrailleSpinner from '../BrailleSpinner';
+import Banner from '../ui/Banner';
+
+const EMPTY_MEMORY = {
+ content: '', summary: '', type: 'observation', category: 'other', tags: [], importance: 0.5,
+};
+
+const promptDraft = (data) => ({
+ schemaVersion: data?.prompt?.schemaVersion || 1,
+ identity: data?.prompt?.identity || '',
+ instructions: data?.prompt?.instructions || '',
+});
+
+const harnessTone = (recommendation) => recommendation === 'recommended'
+ ? 'success'
+ : recommendation === 'not-recommended' ? 'warning' : 'info';
+
+export default function PersistentMindContextPanel() {
+ const [data, setData] = useState(null);
+ const [draft, setDraft] = useState(() => promptDraft(null));
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ return api.getPersistentMindContext({ silent: true })
+ .then((next) => {
+ setData(next);
+ setDraft(promptDraft(next));
+ })
+ .catch((nextError) => setError(nextError?.message || 'Could not load the mind context'))
+ .finally(() => setLoading(false));
+ }, []);
+
+ useEffect(() => { void load(); }, [load]);
+
+ const savePrompt = async () => {
+ if (saving) return;
+ setSaving(true);
+ setError(null);
+ await api.updateCosConfig({ persistentMindPrompt: draft }, { silent: true })
+ .then(() => load())
+ .catch((nextError) => setError(nextError?.message || 'Could not save the prompt'))
+ .finally(() => setSaving(false));
+ };
+
+ if (loading && !data) return <div className="flex justify-center p-10"><BrailleSpinner text="Loading mind context" /></div>;
+
+ return (
+ <div className="space-y-4">
+ {error && <Banner tone="error" title="Context unavailable">{error}</Banner>}
+
+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-architecture-heading">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h3 id="mind-architecture-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text">
+ <Brain size={17} aria-hidden="true" /> How one wake works
+ </h3>
+ <p className="mt-1 text-xs text-port-text-muted">Every visible result is appended to the machine-local trajectory; the next wake receives a bounded projection of that same record.</p>
+ </div>
+ <button type="button" onClick={() => load()} disabled={loading} className="flex items-center gap-2 rounded border border-port-border px-3 py-1.5 text-xs text-port-text disabled:opacity-50">
+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} aria-hidden="true" /> Refresh
+ </button>
+ </div>
+ <div className="mt-3 grid gap-2 text-xs sm:grid-cols-4">
+ {[
+ ['1 · Observe', 'Messages, annotations, and scheduled self-wakes enter one FIFO stream.'],
+ ['2 · Assemble', 'Identity, instructions, curated memories, rollups, and recent events fill a bounded context.'],
+ ['3 · Think', 'The exact pinned provider returns a visible working note, reply, memory proposals, and optional follow-up.'],
+ ['4 · Persist', 'The append-only trajectory becomes the source for chat, inspection, replay, and later context.'],
+ ].map(([title, body]) => (
+ <div key={title} className="rounded border border-port-border bg-port-bg/40 p-3">
+ <p className="font-semibold text-port-text">{title}</p>
+ <p className="mt-1 text-port-text-muted">{body}</p>
+ </div>
+ ))}
+ </div>
+ </section>
+
+ {data?.harness && (
+ <Banner tone={harnessTone(data.harness.recommendation)} title={`${data.harness.label} · ${data.harness.recommendation}`}>
+ {data.harness.detail}
+ </Banner>
+ )}
+
+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-prompt-heading">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h3 id="mind-prompt-heading" className="text-sm font-semibold text-port-text">Identity and operating prompt</h3>
+ <p className="mt-1 text-xs text-port-text-muted">These are injected verbatim on every wake. Saving changes context only; it never starts inference.</p>
+ </div>
+ <button type="button" onClick={savePrompt} disabled={saving || !data} className="flex items-center gap-2 rounded bg-port-accent px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50">
+ <Save size={14} aria-hidden="true" /> {saving ? 'Saving…' : 'Save prompt'}
+ </button>
+ </div>
+ <div className="mt-3 grid gap-3 lg:grid-cols-2">
+ <label className="text-xs font-medium text-port-text" htmlFor="persistent-mind-identity">
+ Identity
+ <textarea id="persistent-mind-identity" rows={7} maxLength={4000} value={draft.identity} onChange={(event) => setDraft((current) => ({ ...current, identity: event.target.value }))} className="mt-1 w-full resize-y rounded border border-port-border bg-port-bg px-3 py-2 text-sm font-normal text-port-text" />
+ </label>
+ <label className="text-xs font-medium text-port-text" htmlFor="persistent-mind-instructions">
+ Operating instructions
+ <textarea id="persistent-mind-instructions" rows={7} maxLength={12000} value={draft.instructions} onChange={(event) => setDraft((current) => ({ ...current, instructions: event.target.value }))} className="mt-1 w-full resize-y rounded border border-port-border bg-port-bg px-3 py-2 text-sm font-normal text-port-text" />
+ </label>
+ </div>
+ </section>
+
+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-memory-heading">
+ <div>
+ <h3 id="mind-memory-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text"><Database size={16} aria-hidden="true" /> Curated memories</h3>
+ <p className="mt-1 text-xs text-port-text-muted">Only memories explicitly promoted or added here enter the mind context. Model proposals stay in the conversation until you promote them.</p>
+ </div>
+ <MemoryCreator onCreated={load} />
+ <div className="mt-3 space-y-2">
+ {(data?.memories || []).length === 0 ? (
+ <p className="rounded border border-dashed border-port-border p-4 text-center text-xs text-port-text-muted">No curated memories yet.</p>
+ ) : (data.memories || []).map((memory) => <MemoryEditor key={memory.id} memory={memory} onSaved={load} />)}
+ </div>
+ </section>
+
+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-preview-heading">
+ <h3 id="mind-preview-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text"><Eye size={16} aria-hidden="true" /> Effective context preview</h3>
+ <p className="mt-1 text-xs text-port-text-muted">
+ This is the actual bounded text projection used on the next wake: {data?.preview?.chars || 0} characters, about {data?.preview?.approximateTokens || 0} tokens, summary cache {data?.preview?.summaryState || 'unknown'}.
+ </p>
+ <pre className="mt-3 max-h-[34rem] overflow-auto whitespace-pre-wrap break-words rounded border border-port-border bg-port-bg p-3 text-xs text-port-text">{data?.preview?.text || 'No context available.'}</pre>
+ <details className="mt-3 rounded border border-port-border p-3">
+ <summary className="cursor-pointer text-xs font-semibold text-port-text">Derived rollups ({data?.rollups?.length || 0})</summary>
+ <p className="mt-2 text-xs text-port-text-muted">Rollups are read-only cached projections with provider/model provenance. Edit the source conversation or curated memories, not derived history.</p>
+ <div className="mt-2 space-y-2">
+ {(data?.rollups || []).map((rollup) => (
+ <div key={rollup.id} className="rounded bg-port-bg/50 p-2 text-xs">
+ <p className="font-mono text-port-text-muted">events {rollup.source.fromSequence}–{rollup.source.toSequence} · {rollup.provenance.providerId || 'unknown'}/{rollup.provenance.model || 'default'} · prompt v{rollup.provenance.promptVersion}</p>
+ <p className="mt-1 whitespace-pre-wrap text-port-text">{rollup.summary || rollup.error || rollup.status}</p>
+ </div>
+ ))}
+ </div>
+ </details>
+ </section>
+ </div>
+ );
+}
+
+function MemoryCreator({ onCreated }) {
+ const id = useId();
+ const [draft, setDraft] = useState(EMPTY_MEMORY);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(null);
+ const create = async (event) => {
+ event.preventDefault();
+ if (!draft.content.trim() || saving) return;
+ setSaving(true);
+ setError(null);
+ await api.createPersistentMindMemory({
+ ...draft,
+ content: draft.content.trim(),
+ summary: draft.summary.trim() || undefined,
+ }, { silent: true })
+ .then(() => {
+ setDraft({ ...EMPTY_MEMORY });
+ return onCreated();
+ })
+ .catch((nextError) => setError(nextError?.message || 'Could not add the memory'))
+ .finally(() => setSaving(false));
+ };
+ return (
+ <form onSubmit={create} className="mt-3 rounded border border-port-border bg-port-bg/30 p-3">
+ <label htmlFor={`${id}-content`} className="text-xs font-medium text-port-text">Add a durable memory</label>
+ <div className="mt-1 flex flex-col gap-2 sm:flex-row">
+ <input id={`${id}-content`} value={draft.content} maxLength={10240} onChange={(event) => setDraft((current) => ({ ...current, content: event.target.value }))} placeholder="A stable fact, preference, decision, or context…" className="min-w-0 flex-1 rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text" />
+ <button type="submit" disabled={saving || !draft.content.trim()} className="flex items-center justify-center gap-2 rounded border border-port-accent px-3 py-2 text-xs font-medium text-port-accent disabled:opacity-50"><Plus size={14} aria-hidden="true" /> {saving ? 'Adding…' : 'Add memory'}</button>
+ </div>
+ {error && <p role="alert" className="mt-2 text-xs text-port-error">{error}</p>}
+ </form>
+ );
+}
+
+function MemoryEditor({ memory, onSaved }) {
+ const id = useId();
+ const [draft, setDraft] = useState({
+ content: memory.content || '',
+ summary: memory.summary || '',
+ type: memory.type || 'observation',
+ category: memory.category || 'other',
+ tags: (memory.tags || []).join(', '),
+ importance: memory.importance ?? 0.5,
+ });
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(null);
+ const save = async (event) => {
+ event.preventDefault();
+ setSaving(true);
+ setError(null);
+ await api.updatePersistentMindMemory(memory.id, {
+ ...draft,
+ summary: draft.summary.trim(),
+ tags: draft.tags.split(',').map((tag) => tag.trim()).filter(Boolean),
+ importance: Number(draft.importance),
+ }, { silent: true })
+ .then(() => onSaved())
+ .catch((nextError) => setError(nextError?.message || 'Could not save the memory'))
+ .finally(() => setSaving(false));
+ };
+ return (
+ <details className="rounded border border-port-border p-3">
+ <summary className="cursor-pointer text-sm text-port-text"><span className="font-medium">{memory.summary || memory.content}</span> <span className="text-xs text-port-text-muted">· {memory.type}/{memory.category}</span></summary>
+ <form onSubmit={save} className="mt-3 grid gap-3">
+ <label htmlFor={`${id}-content`} className="text-xs font-medium text-port-text">Content<textarea id={`${id}-content`} rows={4} required maxLength={10240} value={draft.content} onChange={(event) => setDraft((current) => ({ ...current, content: event.target.value }))} className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm font-normal text-port-text" /></label>
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ <label htmlFor={`${id}-summary`} className="text-xs font-medium text-port-text">Summary<input id={`${id}-summary`} maxLength={500} value={draft.summary} onChange={(event) => setDraft((current) => ({ ...current, summary: event.target.value }))} className="mt-1 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 font-normal" /></label>
+ <label htmlFor={`${id}-type`} className="text-xs font-medium text-port-text">Type<select id={`${id}-type`} value={draft.type} onChange={(event) => setDraft((current) => ({ ...current, type: event.target.value }))} className="mt-1 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 font-normal">{['fact', 'learning', 'observation', 'decision', 'preference', 'context'].map((type) => <option key={type}>{type}</option>)}</select></label>
+ <label htmlFor={`${id}-category`} className="text-xs font-medium text-port-text">Category<input id={`${id}-category`} maxLength={100} value={draft.category} onChange={(event) => setDraft((current) => ({ ...current, category: event.target.value }))} className="mt-1 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 font-normal" /></label>
+ <label htmlFor={`${id}-importance`} className="text-xs font-medium text-port-text">Importance<input id={`${id}-importance`} type="number" min="0" max="1" step="0.1" value={draft.importance} onChange={(event) => setDraft((current) => ({ ...current, importance: event.target.value }))} className="mt-1 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 font-normal" /></label>
+ </div>
+ <label htmlFor={`${id}-tags`} className="text-xs font-medium text-port-text">Tags, comma-separated<input id={`${id}-tags`} value={draft.tags} onChange={(event) => setDraft((current) => ({ ...current, tags: event.target.value }))} className="mt-1 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 font-normal" /></label>
+ {error && <p role="alert" className="text-xs text-port-error">{error}</p>}
+ <div className="flex justify-end"><button type="submit" disabled={saving || !draft.content.trim()} className="flex items-center gap-2 rounded bg-port-accent px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50"><Save size={14} aria-hidden="true" /> {saving ? 'Saving…' : 'Save memory'}</button></div>
+ </form>
+ </details>
+ );
+}
diff --git a/client/src/components/cos/PersistentMindProfileControls.jsx b/client/src/components/cos/PersistentMindProfileControls.jsx
index a748446352..1c9c83f941 100644
--- a/client/src/components/cos/PersistentMindProfileControls.jsx
+++ b/client/src/components/cos/PersistentMindProfileControls.jsx
@@ -39,6 +39,14 @@ export default function PersistentMindProfileControls({
const draftRef = useRef(draft);
const publishedProfileRef = useRef(draft);
const pendingSavesRef = useRef(0);
+ const selectedProvider = providers.find((provider) => provider.id === draft.providerId) || null;
+ const harness = selectedProvider?.type === 'api'
+ ? { label: 'Direct API · recommended', tone: 'border-port-success/30 bg-port-success/10 text-port-success', detail: 'Best reliability for an always-on mind: structured HTTP, clean cancellation, and no terminal state. Ollama, llama.cpp, LM Studio, vLLM, and compatible cloud endpoints use this lane.' }
+ : selectedProvider?.type === 'cli'
+ ? { label: 'Headless CLI · supported', tone: 'border-port-accent/30 bg-port-accent/10 text-port-accent', detail: 'A good option when the vendor CLI owns authentication or model access, with more startup overhead than a direct API.' }
+ : selectedProvider?.type === 'tui'
+ ? { label: 'Interactive TUI · not recommended', tone: 'border-port-warning/30 bg-port-warning/10 text-port-warning', detail: 'Compatibility lane only. Startup prompts, terminal redraws, and screen scraping are fragile for unattended persistent work.' }
+ : null;
// The provider hook memoizes its setters in production, but simple host-page
// test mocks may return fresh functions every render. This effect describes
@@ -155,6 +163,12 @@ export default function PersistentMindProfileControls({
}}
onEffortChange={(effort) => save({ effort })}
/>
+ {harness && (
+ <div className={`rounded border px-3 py-2 text-xs ${harness.tone}`}>
+ <p className="font-semibold">{harness.label}</p>
+ <p className="mt-0.5">{harness.detail}</p>
+ </div>
+ )}
<p className="text-xs text-port-text-muted">
Thinking effort appears when the selected provider and model support it. File-changing work remains an explicit typed CoS task; an unavailable or invalid pin pauses the mind instead of falling back.
</p>
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index b458a43d47..dd10d46a48 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -1,17 +1,25 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
-import { Check, CirclePause, CirclePlay, MessageCircle, RefreshCw, Square, Upload } from 'lucide-react';
+import { Brain, Check, CirclePause, CirclePlay, MessageCircle, RefreshCw, Settings2, Square, Upload } from 'lucide-react';
import { useSocket } from '../../../hooks/useSocket';
import { uuidv4 } from '../../../lib/uuid.js';
import * as api from '../../../services/api';
import { formatDateTime } from '../../../utils/formatters';
import BrailleSpinner from '../../BrailleSpinner';
import Banner from '../../ui/Banner';
+import TabPills from '../../ui/TabPills';
+import PersistentMindContextPanel from '../PersistentMindContextPanel';
import PersistentMindProfileControls from '../PersistentMindProfileControls';
const PAGE_LIMIT = 200;
const MAX_BACKFILL_PAGES = 5;
const MAX_VISIBLE_EVENTS = PAGE_LIMIT * MAX_BACKFILL_PAGES;
+const MIND_VIEWS = new Set(['conversation', 'context', 'setup']);
+const MIND_TABS = [
+ { id: 'conversation', label: 'Conversation', icon: MessageCircle },
+ { id: 'context', label: 'Context & memory', icon: Brain },
+ { id: 'setup', label: 'Provider & lifecycle', icon: Settings2 },
+];
const EVENT_LABELS = {
'mind.message.accepted': 'User input',
@@ -19,6 +27,9 @@ const EVENT_LABELS = {
'mind.summary': 'Mind summary',
'mind.model.result': 'Mind summary',
'mind.turn.completed': 'Mind summary',
+ 'mind.thought': 'Working note',
+ 'mind.reply': 'Chief of Staff',
+ 'mind.memory.candidate': 'Memory proposal',
'mind.capability.request': 'Action request',
'mind.capability.result': 'Action outcome',
'mind.memory.promoted': 'Memory promoted',
@@ -53,6 +64,7 @@ const mintId = (prefix) => `${prefix}-${uuidv4()}`;
export default function MindTab() {
const [searchParams, setSearchParams] = useSearchParams();
const selectedEventId = searchParams.get('event');
+ const activeView = MIND_VIEWS.has(searchParams.get('view')) ? searchParams.get('view') : 'conversation';
const socket = useSocket();
const [events, setEvents] = useState(null);
const [mind, setMind] = useState(null);
@@ -68,6 +80,7 @@ export default function MindTab() {
const [eventActionPending, setEventActionPending] = useState(null);
const [lifecycleError, setLifecycleError] = useState(null);
const [profileSaving, setProfileSaving] = useState(false);
+ const [showActivity, setShowActivity] = useState(false);
const cursorRef = useRef(null);
const loadPendingRef = useRef(false);
const deferredLoadRef = useRef(false);
@@ -236,6 +249,15 @@ export default function MindTab() {
const selectedEvent = events?.find((event) => event.eventId === selectedEventId) || null;
const isPaused = state?.status === 'paused';
const profileReady = Boolean(mind?.profile?.enabled && mind.profile.providerId && mind.profile.model);
+ const visibleEvents = (events || []).filter((event) => showActivity || ![
+ 'mind.wake', 'mind.model.request', 'mind.model.result', 'mind.turn.completed',
+ ].includes(event.kind));
+ const changeView = (view) => setSearchParams((current) => {
+ const next = new URLSearchParams(current);
+ if (view === 'conversation') next.delete('view');
+ else next.set('view', view);
+ return next;
+ });
return (
<section aria-labelledby="mind-heading" className="space-y-4">
@@ -257,129 +279,129 @@ export default function MindTab() {
</div>
</header>
- <section aria-labelledby="mind-profile-heading" className="rounded border border-port-border bg-port-card p-4">
- <div className="mb-3">
- <h3 id="mind-profile-heading" className="text-sm font-semibold text-port-text">AI profile</h3>
- <p className="mt-1 text-xs text-port-text-muted">
- Choose the provider, model, and model effort here before starting the persistent mind. Changes apply to its next wake.
- </p>
- </div>
- <PersistentMindProfileControls
- profile={mind?.profile}
- disabled={!mind}
- onSaved={(profile) => setMind((current) => current ? { ...current, profile } : current)}
- onSavingChange={setProfileSaving}
- />
- {!state?.started && (
- <div className="mt-4 flex flex-col gap-2 border-t border-port-border pt-4 sm:flex-row sm:items-center sm:justify-between">
- <p className="text-xs text-port-text-muted">
- {profileSaving
- ? 'Saving the AI profile…'
- : profileReady
- ? 'The saved AI profile is ready.'
- : 'Enable the profile and select both an AI provider and model to start.'}
- </p>
- <ActionButton
- label="Start persistent mind"
- icon={CirclePlay}
- pending={lifecyclePending === 'start'}
- disabled={loading || profileSaving || !profileReady}
- onClick={() => runLifecycle('start')}
- />
- </div>
- )}
- </section>
+ <TabPills tabs={MIND_TABS} activeTab={activeView} onChange={changeView} variant="pills" mobileDropdown mobileSelectId="persistent-mind-view" ariaLabel="Persistent mind view" />
{gap && <Banner tone="warning" title="History gap detected">The saved cursor is no longer retained. The visible trace was reloaded from the newest bounded snapshot.</Banner>}
{truncated && <Banner tone="info" title="Showing recent history">The initial trace shows the newest {PAGE_LIMIT} events; older retained events are not shown.</Banner>}
{loadError && <Banner tone="error" title="Conversation unavailable">{loadError}. Existing messages are preserved; retry when the connection recovers.</Banner>}
{lifecycleError && <Banner tone="error" title="Action failed">{lifecycleError}</Banner>}
- <div data-testid="mind-layout" className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(18rem,0.42fr)]">
- <div className="min-w-0 rounded border border-port-border bg-port-card">
- <div className="border-b border-port-border px-4 py-3 text-sm text-port-text-muted">
- Status: <span className="font-medium text-port-text">{state?.status || 'unknown'}</span>
- {state?.pauseReason ? ` · ${state.pauseReason}` : ''}
- {state?.failureCount > 0 ? ` · ${state.failureCount} failed wake${state.failureCount === 1 ? '' : 's'}` : ''}
- {state?.nextEligibleWakeAt ? ` · retry after ${formatDateTime(state.nextEligibleWakeAt)}` : ''}
- {state?.lastError ? ` · ${state.lastError}` : ''}
+ {activeView === 'setup' && (
+ <section aria-labelledby="mind-profile-heading" className="rounded border border-port-border bg-port-card p-4">
+ <div className="mb-3">
+ <h3 id="mind-profile-heading" className="text-sm font-semibold text-port-text">AI profile</h3>
+ <p className="mt-1 text-xs text-port-text-muted">Pin the provider, model, and effort used on every wake. Changes apply to the next wake and never silently fall back to another model.</p>
</div>
- {loading && events === null ? (
- <div className="flex justify-center p-10"><BrailleSpinner text="Loading mind history" /></div>
- ) : events?.length === 0 && !loadError ? (
- <p className="p-8 text-center text-sm text-port-text-muted">No conversation yet. Add a message or idea below.</p>
- ) : (
- <ol className="max-h-[52vh] space-y-2 overflow-y-auto p-3" aria-label="Persistent mind conversation">
- {(events || []).map((event) => {
- const selected = event.eventId === selectedEventId;
- const textValue = eventText(event);
- return (
- <li key={event.eventId}>
- <button
- type="button"
- onClick={() => setSearchParams((current) => {
- const next = new URLSearchParams(current);
- next.set('event', event.eventId);
- return next;
- })}
- aria-current={selected ? 'true' : undefined}
- className={`w-full rounded border p-3 text-left ${selected ? 'border-port-accent bg-port-accent/10' : 'border-port-border hover:bg-port-border/20'}`}
- >
- <span className="flex flex-wrap items-center justify-between gap-2">
- <span className="text-xs font-semibold uppercase tracking-wide text-port-accent">{eventLabel(event.kind)}</span>
- <time className="text-xs text-port-text-muted" dateTime={event.at}>{formatDateTime(event.at)}</time>
- </span>
- <span className="mt-1 block whitespace-pre-wrap break-words text-sm text-port-text">{textValue || event.kind}</span>
- {event.turnId && <span className="mt-1 block truncate font-mono text-[11px] text-port-text-muted">turn {event.turnId}</span>}
- </button>
- </li>
- );
- })}
- </ol>
+ <PersistentMindProfileControls
+ profile={mind?.profile}
+ disabled={!mind}
+ onSaved={(profile) => setMind((current) => current ? { ...current, profile } : current)}
+ onSavingChange={setProfileSaving}
+ />
+ {!state?.started && (
+ <div className="mt-4 flex flex-col gap-2 border-t border-port-border pt-4 sm:flex-row sm:items-center sm:justify-between">
+ <p className="text-xs text-port-text-muted">{profileSaving ? 'Saving the AI profile…' : profileReady ? 'The saved AI profile is ready.' : 'Enable the profile and select both an AI provider and model to start.'}</p>
+ <ActionButton label="Start persistent mind" icon={CirclePlay} pending={lifecyclePending === 'start'} disabled={loading || profileSaving || !profileReady} onClick={() => runLifecycle('start')} />
+ </div>
)}
- </div>
+ </section>
+ )}
- <aside className="space-y-3 rounded border border-port-border bg-port-card p-4" aria-label="Selected mind event">
- <h3 className="text-sm font-semibold text-port-text">Selected event</h3>
- {selectedEvent ? (
- <>
- <p className="break-all font-mono text-xs text-port-text-muted">{selectedEvent.eventId}</p>
- <p className="text-sm text-port-text">{eventLabel(selectedEvent.kind)}</p>
- {selectedEvent.kind === 'mind.capability.request' && (
- <div className="flex flex-wrap gap-2">
- <ActionButton label="Acknowledge" icon={Check} pending={eventActionPending === selectedEvent.eventId} onClick={() => acknowledge(selectedEvent)} />
- </div>
- )}
- {['mind.summary', 'mind.model.result', 'mind.turn.completed'].includes(selectedEvent.kind) && (
- <ActionButton label="Promote" icon={Upload} pending={eventActionPending === selectedEvent.eventId} disabled={!eventText(selectedEvent)} onClick={() => promote(selectedEvent)} />
+ {activeView === 'context' && <PersistentMindContextPanel />}
+
+ {activeView === 'conversation' && (
+ <>
+ <div data-testid="mind-layout" className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(18rem,0.42fr)]">
+ <div className="min-w-0 rounded border border-port-border bg-port-card">
+ <div className="flex flex-wrap items-center justify-between gap-2 border-b border-port-border px-4 py-3 text-sm text-port-text-muted">
+ <span>
+ Status: <span className="font-medium text-port-text">{state?.status || 'unknown'}</span>
+ {state?.pauseReason ? ` · ${state.pauseReason}` : ''}
+ {state?.queuedMessageCount > 0 ? ` · ${state.queuedMessageCount} queued` : ''}
+ {state?.failureCount > 0 ? ` · ${state.failureCount} failed wake${state.failureCount === 1 ? '' : 's'}` : ''}
+ {state?.nextEligibleWakeAt ? ` · retry after ${formatDateTime(state.nextEligibleWakeAt)}` : ''}
+ {state?.lastError ? ` · ${state.lastError}` : ''}
+ </span>
+ <label htmlFor="mind-show-activity" className="flex items-center gap-2 text-xs">
+ <input id="mind-show-activity" type="checkbox" checked={showActivity} onChange={(event) => setShowActivity(event.target.checked)} className="accent-port-accent" /> Show run activity
+ </label>
+ </div>
+ {loading && events === null ? (
+ <div className="flex justify-center p-10"><BrailleSpinner text="Loading mind history" /></div>
+ ) : visibleEvents.length === 0 && !loadError ? (
+ <p className="p-8 text-center text-sm text-port-text-muted">No conversation yet. Add a message below, or start the mind from Provider & lifecycle.</p>
+ ) : (
+ <ol className="max-h-[62vh] space-y-3 overflow-y-auto p-3" aria-label="Persistent mind conversation">
+ {visibleEvents.map((event) => {
+ const selected = event.eventId === selectedEventId;
+ const textValue = eventText(event);
+ const assistant = event.kind === 'mind.reply';
+ const thought = event.kind === 'mind.thought';
+ return (
+ <li key={event.eventId} className={assistant ? 'flex justify-end' : ''}>
+ <button
+ type="button"
+ onClick={() => setSearchParams((current) => {
+ const next = new URLSearchParams(current);
+ next.set('event', event.eventId);
+ return next;
+ })}
+ aria-current={selected ? 'true' : undefined}
+ className={`${assistant ? 'max-w-[88%] border-port-accent/50 bg-port-accent/10' : 'w-full'} rounded border p-3 text-left ${thought ? 'border-dashed border-port-accent/40 bg-port-bg/40' : ''} ${selected ? 'ring-1 ring-port-accent' : 'hover:bg-port-border/20'} ${!assistant && !thought ? 'border-port-border' : ''}`}
+ >
+ <span className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-xs font-semibold uppercase tracking-wide text-port-accent">{eventLabel(event.kind)}</span>
+ <time className="text-xs text-port-text-muted" dateTime={event.at}>{formatDateTime(event.at)}</time>
+ </span>
+ <span className="mt-1 block whitespace-pre-wrap break-words text-sm text-port-text">{textValue || event.kind}</span>
+ {event.turnId && <span className="mt-1 block truncate font-mono text-[11px] text-port-text-muted">turn {event.turnId}</span>}
+ </button>
+ </li>
+ );
+ })}
+ </ol>
)}
- </>
- ) : <p className="text-sm text-port-text-muted">Choose an event to keep the selection in the URL and attach an annotation.</p>}
- </aside>
- </div>
+ </div>
- <form onSubmit={submit} className="rounded border border-port-border bg-port-card p-4">
- <div className="grid gap-3 sm:grid-cols-[12rem_minmax(0,1fr)]">
- <div>
- <label htmlFor="mind-input-kind" className="mb-1 block text-sm font-medium text-port-text">Input type</label>
- <select id="mind-input-kind" value={kind} onChange={(event) => changeKind(event.target.value)} className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text">
- <option value="message">Instruction / message</option>
- <option value="annotation">Comment / idea</option>
- </select>
- </div>
- <div>
- <label htmlFor="mind-input-text" className="mb-1 block text-sm font-medium text-port-text">{kind === 'message' ? 'Message' : 'Comment or idea'}</label>
- <textarea id="mind-input-text" value={text} onChange={(event) => changeText(event.target.value)} maxLength={8000} rows={3} className="w-full resize-y rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text" placeholder={kind === 'message' ? 'What should the mind consider on its next eligible wake?' : 'Add context without turning it into an immediate task.'} />
+ <aside className="space-y-3 rounded border border-port-border bg-port-card p-4" aria-label="Selected mind event">
+ <h3 className="text-sm font-semibold text-port-text">Selected event</h3>
+ {selectedEvent ? (
+ <>
+ <p className="break-all font-mono text-xs text-port-text-muted">{selectedEvent.eventId}</p>
+ <p className="text-sm text-port-text">{eventLabel(selectedEvent.kind)}</p>
+ <p className="text-xs text-port-text-muted">Sequence {selectedEvent.sequence}{selectedEvent.turnId ? ` · turn ${selectedEvent.turnId}` : ''}</p>
+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border border-port-border bg-port-bg p-2 text-[11px] text-port-text-muted">{JSON.stringify(selectedEvent.data || {}, null, 2)}</pre>
+ {selectedEvent.kind === 'mind.capability.request' && <ActionButton label="Acknowledge" icon={Check} pending={eventActionPending === selectedEvent.eventId} onClick={() => acknowledge(selectedEvent)} />}
+ {['mind.summary', 'mind.reply', 'mind.thought', 'mind.memory.candidate'].includes(selectedEvent.kind) && (
+ <ActionButton label="Promote to memory" icon={Upload} pending={eventActionPending === selectedEvent.eventId} disabled={!eventText(selectedEvent)} onClick={() => promote(selectedEvent)} />
+ )}
+ </>
+ ) : <p className="text-sm text-port-text-muted">Choose an item to inspect its safe event payload, keep it selected in the URL, attach an annotation, or promote it to memory.</p>}
+ </aside>
</div>
- </div>
- {kind === 'annotation' && selectedEventId && <p className="mt-2 text-xs text-port-text-muted">Attached to selected event {selectedEventId}</p>}
- {submitError && <p role="alert" className="mt-2 text-sm text-port-error">{submitError} — Retry uses the same id, so it will not duplicate the input.</p>}
- <div className="mt-3 flex justify-end">
- <button type="submit" disabled={!text.trim() || submitting} className="rounded bg-port-accent px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50">
- {submitting ? 'Submitting…' : submitError ? 'Retry' : 'Submit'}
- </button>
- </div>
- </form>
+
+ <form onSubmit={submit} className="rounded border border-port-border bg-port-card p-4">
+ <div className="grid gap-3 sm:grid-cols-[12rem_minmax(0,1fr)]">
+ <div>
+ <label htmlFor="mind-input-kind" className="mb-1 block text-sm font-medium text-port-text">Input type</label>
+ <select id="mind-input-kind" value={kind} onChange={(event) => changeKind(event.target.value)} className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text">
+ <option value="message">Message</option>
+ <option value="annotation">Comment / idea</option>
+ </select>
+ </div>
+ <div>
+ <label htmlFor="mind-input-text" className="mb-1 block text-sm font-medium text-port-text">{kind === 'message' ? 'Message' : 'Comment or idea'}</label>
+ <textarea id="mind-input-text" value={text} onChange={(event) => changeText(event.target.value)} maxLength={8000} rows={3} className="w-full resize-y rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text" placeholder={kind === 'message' ? 'Write directly into the persistent conversation…' : 'Add context without requesting an immediate reply.'} />
+ </div>
+ </div>
+ {kind === 'annotation' && selectedEventId && <p className="mt-2 text-xs text-port-text-muted">Attached to selected event {selectedEventId}</p>}
+ {submitError && <p role="alert" className="mt-2 text-sm text-port-error">{submitError} — Retry uses the same id, so it will not duplicate the input.</p>}
+ <div className="mt-3 flex justify-end">
+ <button type="submit" disabled={!text.trim() || submitting} className="rounded bg-port-accent px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50">{submitting ? 'Sending…' : submitError ? 'Retry' : kind === 'message' ? 'Send message' : 'Add annotation'}</button>
+ </div>
+ </form>
+ </>
+ )}
</section>
);
}
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 7d340f27fc..1973579bf8 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -16,6 +16,9 @@ const api = vi.hoisted(() => ({
promotePersistentMindEvent: vi.fn(),
getProviders: vi.fn(),
updateCosConfig: vi.fn(),
+ getPersistentMindContext: vi.fn(),
+ createPersistentMindMemory: vi.fn(),
+ updatePersistentMindMemory: vi.fn(),
}));
const socket = vi.hoisted(() => {
@@ -89,6 +92,15 @@ describe('MindTab', () => {
}],
});
api.updateCosConfig.mockResolvedValue({ success: true });
+ api.getPersistentMindContext.mockResolvedValue({
+ prompt: { schemaVersion: 1, identity: 'Resident mind', instructions: 'Stay grounded.' },
+ preview: { text: '# Effective context', chars: 19, approximateTokens: 5, summaryState: 'empty' },
+ memories: [],
+ rollups: [],
+ harness: { type: 'api', label: 'Direct API', recommendation: 'recommended', detail: 'Structured and reliable.' },
+ });
+ api.createPersistentMindMemory.mockResolvedValue({ success: true });
+ api.updatePersistentMindMemory.mockResolvedValue({ success: true });
});
it('restores the selected event from the URL and uses a responsive single DOM tree', async () => {
@@ -107,7 +119,7 @@ describe('MindTab', () => {
expect(await screen.findByText('Conversation unavailable')).toBeInTheDocument();
expect(screen.queryByText(/No conversation yet/)).not.toBeInTheDocument();
- expect(screen.getByRole('checkbox', { name: 'Enable persistent mind profile' })).toBeDisabled();
+ expect(screen.getByRole('tab', { name: 'Provider & lifecycle' })).toBeInTheDocument();
});
it('deduplicates a socket-triggered cursor backfill', async () => {
@@ -156,7 +168,7 @@ describe('MindTab', () => {
profile: { enabled: true, providerId: 'codex', model: 'gpt-5', effort: 'high', thinkingInterface: 'text' },
}));
api.updateCosConfig.mockImplementation(() => new Promise((resolve) => { finishSave = resolve; }));
- renderTab();
+ renderTab('/cos/mind?view=setup');
expect(await screen.findByRole('heading', { name: 'AI profile' })).toBeInTheDocument();
await waitFor(() => expect(screen.getByLabelText('AI provider')).toHaveValue('codex'));
@@ -190,7 +202,7 @@ describe('MindTab', () => {
await screen.findByText('Review the next bounded slice.');
await user.type(screen.getByLabelText('Message'), 'Keep this queued.');
- await user.click(screen.getByRole('button', { name: 'Submit' }));
+ await user.click(screen.getByRole('button', { name: 'Send message' }));
expect(await screen.findByRole('alert')).toHaveTextContent(/Retry uses the same id/);
expect(screen.getByLabelText('Message')).toHaveValue('Keep this queued.');
@@ -206,12 +218,12 @@ describe('MindTab', () => {
renderTab();
await screen.findByText('Review the next bounded slice.');
await user.type(screen.getByLabelText('Message'), 'Original text');
- await user.click(screen.getByRole('button', { name: 'Submit' }));
+ await user.click(screen.getByRole('button', { name: 'Send message' }));
await screen.findByRole('alert');
const firstId = api.sendPersistentMindMessage.mock.calls[0][0].id;
await user.type(screen.getByLabelText('Message'), ' updated');
- await user.click(screen.getByRole('button', { name: 'Submit' }));
+ await user.click(screen.getByRole('button', { name: 'Send message' }));
await waitFor(() => expect(api.sendPersistentMindMessage).toHaveBeenCalledTimes(2));
expect(api.sendPersistentMindMessage.mock.calls[1][0].id).not.toBe(firstId);
});
@@ -223,7 +235,26 @@ describe('MindTab', () => {
})] }));
renderTab();
+ await userEvent.setup().click(await screen.findByRole('checkbox', { name: 'Show run activity' }));
expect(await screen.findByText('A synthesized summary.')).toBeInTheDocument();
expect(screen.queryByText(/not-rendered|5000|prompt/i)).not.toBeInTheDocument();
});
+
+ it('renders user-visible working notes and replies in the conversation', async () => {
+ api.getPersistentMind.mockResolvedValue(response({ events: [
+ event({ eventId: 'thought-1', kind: 'mind.thought', sequence: 2, data: { displayText: 'I connected this with the prior decision.' } }),
+ event({ eventId: 'reply-1', kind: 'mind.reply', sequence: 3, data: { displayText: 'Here is the recommendation.' } }),
+ ] }));
+ renderTab();
+ expect(await screen.findByText('I connected this with the prior decision.')).toBeInTheDocument();
+ expect(screen.getByText('Here is the recommendation.')).toBeInTheDocument();
+ });
+
+ it('loads the editable effective context from the URL-backed context view', async () => {
+ renderTab('/cos/mind?view=context');
+ expect(await screen.findByRole('heading', { name: 'Identity and operating prompt' })).toBeInTheDocument();
+ expect(screen.getByLabelText('Identity')).toHaveValue('Resident mind');
+ expect(screen.getByText('# Effective context')).toBeInTheDocument();
+ expect(api.getPersistentMindContext).toHaveBeenCalledWith({ silent: true });
+ });
});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index a5cce9f115..f031d30c68 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -65,6 +65,7 @@ export const repairRunRecords = (body = {}, options = {}) =>
// timed-out request cannot duplicate a message or annotation.
export const getPersistentMind = (filters = {}, options = {}) =>
request(`/cos/mind${runEventQuery(filters)}`, options);
+export const getPersistentMindContext = (options = {}) => request('/cos/mind/context', options);
export const sendPersistentMindMessage = (body, options = {}) =>
request('/cos/mind/messages', { method: 'POST', body: JSON.stringify(body), ...options });
export const addPersistentMindAnnotation = (body, options = {}) =>
@@ -83,6 +84,12 @@ export const promotePersistentMindEvent = (eventId, body, options = {}) =>
request(`/cos/mind/events/${encodeURIComponent(eventId)}/promote`, {
method: 'POST', body: JSON.stringify(body), ...options,
});
+export const createPersistentMindMemory = (body, options = {}) => request('/cos/mind/memories', {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const updatePersistentMindMemory = (memoryId, body, options = {}) => request(`/cos/mind/memories/${encodeURIComponent(memoryId)}`, {
+ method: 'PUT', body: JSON.stringify(body), ...options,
+});
// Chief of Staff
export const getCosStatus = () => request('/cos');
diff --git a/client/src/services/apiMemory.js b/client/src/services/apiMemory.js
index 5c6425e6b8..51af7f346b 100644
--- a/client/src/services/apiMemory.js
+++ b/client/src/services/apiMemory.js
@@ -8,6 +8,7 @@ export const getMemories = (options = {}) => {
if (options.tags) params.set('tags', options.tags.join(','));
if (options.status) params.set('status', options.status);
if (options.appId) params.set('appId', options.appId);
+ if (options.sourceAgentId) params.set('sourceAgentId', options.sourceAgentId);
if (options.limit) params.set('limit', options.limit);
if (options.offset) params.set('offset', options.offset);
if (options.sortBy) params.set('sortBy', options.sortBy);
diff --git a/scripts/migrations/302-persistent-mind-prompt.js b/scripts/migrations/302-persistent-mind-prompt.js
new file mode 100644
index 0000000000..560f2b9726
--- /dev/null
+++ b/scripts/migrations/302-persistent-mind-prompt.js
@@ -0,0 +1,33 @@
+/** Add the editable persistent-mind identity and operating prompt. */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';
+import { createDefaultPersistentMindPrompt } from '../../server/lib/persistentMindPrompt.js';
+
+export default {
+ async up({ rootDir }) {
+ const statePath = join(rootDir, 'data', 'cos', 'state.json');
+ const raw = await readFile(statePath, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (raw == null) return { updated: 0, reason: 'no-state' };
+
+ const state = safeJSONParse(raw, null, { logError: false });
+ if (!state || typeof state !== 'object' || Array.isArray(state)) {
+ return { updated: 0, reason: 'invalid-state' };
+ }
+ state.config = state.config && typeof state.config === 'object' && !Array.isArray(state.config)
+ ? state.config
+ : {};
+ if (Object.hasOwn(state.config, 'persistentMindPrompt')) {
+ return { updated: 0, reason: 'already-applied' };
+ }
+
+ state.config.persistentMindPrompt = createDefaultPersistentMindPrompt();
+ await atomicWrite(statePath, state);
+ console.log('🧠 migration 302: added editable persistent mind prompt');
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/302-persistent-mind-prompt.test.js b/scripts/migrations/302-persistent-mind-prompt.test.js
new file mode 100644
index 0000000000..c1a8b5b0b9
--- /dev/null
+++ b/scripts/migrations/302-persistent-mind-prompt.test.js
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './302-persistent-mind-prompt.js';
+
+let rootDir;
+
+afterEach(async () => {
+ if (rootDir) await rm(rootDir, { recursive: true, force: true });
+ rootDir = null;
+});
+
+describe('migration 302', () => {
+ it('adds defaults without overwriting an existing prompt', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-prompt-'));
+ const cosDir = join(rootDir, 'data', 'cos');
+ await mkdir(cosDir, { recursive: true });
+ const statePath = join(cosDir, 'state.json');
+ await writeFile(statePath, JSON.stringify({ config: { autoStart: false } }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+ const state = JSON.parse(await readFile(statePath, 'utf8'));
+ expect(state.config.persistentMindPrompt.identity).toContain('Chief of Staff');
+
+ state.config.persistentMindPrompt.identity = 'Custom identity';
+ await writeFile(statePath, JSON.stringify(state));
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ expect(JSON.parse(await readFile(statePath, 'utf8')).config.persistentMindPrompt.identity).toBe('Custom identity');
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index a99e18e003..c4fb5451d0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -43,6 +43,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, bounded exponential backoff, watchdog staleness, and next-wake projection. |
| `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |
| `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface), its strict API schema, and safe partial-update merge that clears model/effort on a provider switch. |
+| `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. |
| `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields and queue count, drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. |
| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 6f507851a7..af8d44b4c1 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -311,6 +311,7 @@ export function createRunnerService(config = {}) {
effort = null,
requestCapabilities = null,
screenshots = [],
+ allowFallback = true,
} = options;
if (!providerService) {
@@ -330,6 +331,10 @@ export function createRunnerService(config = {}) {
});
if (providerStatusService && !providerStatusService.isAvailable(providerId)) {
+ if (!allowFallback) {
+ const status = providerStatusService.getStatus(providerId) || {};
+ throw new Error(`Provider ${providerId} is unavailable (${status.reason || 'unknown'}) and fallback is disabled`);
+ }
const allProviders = await providerService.getAllProviders();
const providersMap = {};
for (const p of allProviders.providers) {
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 177d3eda82..923107c67c 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -52,6 +52,30 @@ describe('AI Toolkit runner service', () => {
);
});
+ it('refuses proactive fallback when an exact provider is required', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const primary = { id: 'primary', name: 'Primary', type: 'api', enabled: true };
+ const providerService = {
+ getAllProviders: vi.fn().mockResolvedValue({ providers: [primary] }),
+ getProviderById: vi.fn().mockResolvedValue(primary),
+ };
+ const providerStatusService = {
+ isAvailable: vi.fn().mockReturnValue(false),
+ getFallbackProvider: vi.fn(),
+ getStatus: vi.fn().mockReturnValue({ reason: 'rate-limit' }),
+ };
+ const runner = createRunnerService({ dataDir, providerService, providerStatusService });
+
+ await expect(runner.createRun({
+ providerId: primary.id,
+ prompt: 'stay pinned',
+ allowFallback: false,
+ })).rejects.toThrow('fallback is disabled');
+ expect(providerStatusService.getFallbackProvider).not.toHaveBeenCalled();
+ expect(providerService.getAllProviders).not.toHaveBeenCalled();
+ });
+
it('derives request capabilities for direct and pre-created runs', async () => {
const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
tempDirs.push(dataDir);
diff --git a/server/lib/creativeLatitude.js b/server/lib/creativeLatitude.js
index 4ba49125c0..c54e21a134 100644
--- a/server/lib/creativeLatitude.js
+++ b/server/lib/creativeLatitude.js
@@ -127,6 +127,7 @@ export const OPERATIONAL_RUN_SOURCES = Object.freeze([
'activity-digest',
'agent-personality-generation',
'ai-app-detect',
+ 'cos-persistent-mind',
'digital-twin',
'goal-scorecard',
'jira-title',
diff --git a/server/lib/index.js b/server/lib/index.js
index b74783bd4c..e0ee397cce 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -218,6 +218,7 @@ export * from './agentRunReconcile.js';
export * from './persistentMind.js';
export * from './persistentMindTrajectory.js';
export * from './persistentMindProfile.js';
+export * from './persistentMindPrompt.js';
export * from './persistentMindPublic.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
diff --git a/server/lib/memoryQuery.js b/server/lib/memoryQuery.js
index bcf1e6676c..b56537a36a 100644
--- a/server/lib/memoryQuery.js
+++ b/server/lib/memoryQuery.js
@@ -25,7 +25,8 @@ export function projectIndexMeta(memory) {
importance: memory.importance,
createdAt: memory.createdAt,
status: memory.status,
- sourceAppId: memory.sourceAppId
+ sourceAppId: memory.sourceAppId,
+ sourceAgentId: memory.sourceAgentId,
};
}
@@ -63,6 +64,10 @@ export function filterMemoryIndex(memories, options = {}) {
filtered = filtered.filter(m => m.sourceAppId === options.appId);
}
+ if (options.sourceAgentId) {
+ filtered = filtered.filter(m => m.sourceAgentId === options.sourceAgentId);
+ }
+
return filtered;
}
diff --git a/server/lib/memoryQuery.test.js b/server/lib/memoryQuery.test.js
index e402841a11..1a78a32cae 100644
--- a/server/lib/memoryQuery.test.js
+++ b/server/lib/memoryQuery.test.js
@@ -14,23 +14,23 @@ describe('projectIndexMeta', () => {
const memory = {
id: 'm1', type: 'fact', category: 'work', tags: ['a'], summary: 's',
importance: 0.7, createdAt: '2024-01-01T00:00:00Z', status: 'active',
- sourceAppId: 'brain',
+ sourceAppId: 'brain', sourceAgentId: 'agent-1',
// fields that must NOT leak into the index entry
content: 'long content', embedding: [1, 2, 3], confidence: 0.9, accessCount: 5
};
expect(projectIndexMeta(memory)).toEqual({
id: 'm1', type: 'fact', category: 'work', tags: ['a'], summary: 's',
importance: 0.7, createdAt: '2024-01-01T00:00:00Z', status: 'active',
- sourceAppId: 'brain'
+ sourceAppId: 'brain', sourceAgentId: 'agent-1'
});
});
});
describe('filterMemoryIndex', () => {
const memories = [
- { id: '1', type: 'fact', category: 'work', tags: ['x'], status: 'active', sourceAppId: 'brain' },
- { id: '2', type: 'note', category: 'home', tags: ['y'], status: 'active', sourceAppId: 'app1' },
- { id: '3', type: 'fact', category: 'work', tags: ['x', 'z'], status: 'archived', sourceAppId: 'app1' }
+ { id: '1', type: 'fact', category: 'work', tags: ['x'], status: 'active', sourceAppId: 'brain', sourceAgentId: 'mind-1' },
+ { id: '2', type: 'note', category: 'home', tags: ['y'], status: 'active', sourceAppId: 'app1', sourceAgentId: 'mind-2' },
+ { id: '3', type: 'fact', category: 'work', tags: ['x', 'z'], status: 'archived', sourceAppId: 'app1', sourceAgentId: 'mind-1' }
];
it('defaults to active status', () => {
@@ -57,6 +57,10 @@ describe('filterMemoryIndex', () => {
expect(filterMemoryIndex(memories, { appId: 'app1' }).map(m => m.id)).toEqual(['2']);
});
+ it('filters by the owning source agent', () => {
+ expect(filterMemoryIndex(memories, { sourceAgentId: 'mind-1' }).map(m => m.id)).toEqual(['1']);
+ });
+
it('excludes brain entries with __not_brain sentinel', () => {
expect(filterMemoryIndex(memories, { appId: '__not_brain' }).map(m => m.id)).toEqual(['2']);
});
diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.js
index df3c56858c..3db5770833 100644
--- a/server/lib/memoryValidation.js
+++ b/server/lib/memoryValidation.js
@@ -146,6 +146,7 @@ export const memoryListSchema = z.object({
tags: csvList(z.array(z.string().max(50)).optional()),
status: emptyToUndefined(memoryStatusEnum.optional().default('active')),
appId: emptyToUndefined(z.string().max(100).optional()),
+ sourceAgentId: emptyToUndefined(z.string().max(128).optional()),
limit: numeric(z.number().int().min(1).max(500).optional().default(50)),
offset: numeric(z.number().int().min(0).optional().default(0)),
sortBy: emptyToUndefined(z.enum(['createdAt', 'updatedAt', 'importance', 'accessCount']).optional().default('createdAt')),
diff --git a/server/lib/memoryValidation.test.js b/server/lib/memoryValidation.test.js
index d253274715..59ca411ff2 100644
--- a/server/lib/memoryValidation.test.js
+++ b/server/lib/memoryValidation.test.js
@@ -407,6 +407,12 @@ describe('memoryValidation.js', () => {
expect(result.success).toBe(true);
expect(result.data.appId).toBe('__not_brain');
});
+
+ it('should accept a sourceAgentId filter', () => {
+ const result = memoryListSchema.safeParse({ sourceAgentId: 'cos-persistent-mind' });
+ expect(result.success).toBe(true);
+ expect(result.data.sourceAgentId).toBe('cos-persistent-mind');
+ });
});
describe('memoryExtractSchema', () => {
diff --git a/server/lib/persistentMindPrompt.js b/server/lib/persistentMindPrompt.js
new file mode 100644
index 0000000000..f990271a42
--- /dev/null
+++ b/server/lib/persistentMindPrompt.js
@@ -0,0 +1,54 @@
+/**
+ * Editable identity and operating prompt for the persistent Chief-of-Staff mind.
+ *
+ * This is durable configuration, not lifecycle consent. Reading or saving it
+ * never starts the mind or calls a provider.
+ */
+
+import { z } from 'zod';
+
+export const PERSISTENT_MIND_PROMPT_SCHEMA_VERSION = 1;
+
+export const PERSISTENT_MIND_PROMPT_LIMITS = Object.freeze({
+ identityChars: 4_000,
+ instructionsChars: 12_000,
+});
+
+export const DEFAULT_PERSISTENT_MIND_IDENTITY = `I am the resident Chief of Staff mind for this PortOS install. I am one continuous, machine-local conversational presence. I preserve continuity across wakes, distinguish facts from hypotheses, and treat the human's messages and annotations as part of one shared trajectory.`;
+
+export const DEFAULT_PERSISTENT_MIND_INSTRUCTIONS = `Keep the conversation useful, candid, and concise. Connect new messages to relevant prior context and curated memories. A self-directed wake should produce a concrete observation, question, or next line of inquiry rather than filler. Never claim that an action happened unless the trajectory records its outcome. File-changing work, external communication, purchases, and other consequential actions remain explicit typed CoS tasks; this mind may propose them but must not perform them from this reasoning loop. Return a short user-visible working note instead of hidden chain-of-thought.`;
+
+export const persistentMindPromptSchema = z.object({
+ schemaVersion: z.literal(PERSISTENT_MIND_PROMPT_SCHEMA_VERSION).optional(),
+ identity: z.string().max(PERSISTENT_MIND_PROMPT_LIMITS.identityChars).optional(),
+ instructions: z.string().max(PERSISTENT_MIND_PROMPT_LIMITS.instructionsChars).optional(),
+}).strict();
+
+export function createDefaultPersistentMindPrompt() {
+ return {
+ schemaVersion: PERSISTENT_MIND_PROMPT_SCHEMA_VERSION,
+ identity: DEFAULT_PERSISTENT_MIND_IDENTITY,
+ instructions: DEFAULT_PERSISTENT_MIND_INSTRUCTIONS,
+ };
+}
+
+const boundedText = (value, fallback, max) => (
+ typeof value === 'string' ? value.trim().slice(0, max) : fallback
+);
+
+/** Missing fields inherit defaults; an explicitly empty string remains empty. */
+export function normalizePersistentMindPrompt(raw) {
+ const defaults = createDefaultPersistentMindPrompt();
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ return {
+ schemaVersion: PERSISTENT_MIND_PROMPT_SCHEMA_VERSION,
+ identity: boundedText(source.identity, defaults.identity, PERSISTENT_MIND_PROMPT_LIMITS.identityChars),
+ instructions: boundedText(source.instructions, defaults.instructions, PERSISTENT_MIND_PROMPT_LIMITS.instructionsChars),
+ };
+}
+
+export function mergePersistentMindPrompt(previous, update) {
+ const prior = normalizePersistentMindPrompt(previous);
+ const patch = update && typeof update === 'object' && !Array.isArray(update) ? update : {};
+ return normalizePersistentMindPrompt({ ...prior, ...patch });
+}
diff --git a/server/lib/persistentMindPrompt.test.js b/server/lib/persistentMindPrompt.test.js
new file mode 100644
index 0000000000..5c10a7428e
--- /dev/null
+++ b/server/lib/persistentMindPrompt.test.js
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createDefaultPersistentMindPrompt,
+ mergePersistentMindPrompt,
+ normalizePersistentMindPrompt,
+ persistentMindPromptSchema,
+} from './persistentMindPrompt.js';
+
+describe('persistent mind prompt', () => {
+ it('ships a useful default without enabling any runtime work', () => {
+ expect(createDefaultPersistentMindPrompt()).toMatchObject({
+ schemaVersion: 1,
+ identity: expect.stringContaining('Chief of Staff'),
+ instructions: expect.stringContaining('user-visible working note'),
+ });
+ });
+
+ it('preserves intentional clears while defaulting absent fields', () => {
+ expect(normalizePersistentMindPrompt({ identity: '' })).toMatchObject({
+ identity: '',
+ instructions: expect.stringContaining('Keep the conversation useful'),
+ });
+ });
+
+ it('merges partial edits and rejects unknown API fields', () => {
+ const prior = { identity: 'Example identity', instructions: 'Existing instructions' };
+ expect(mergePersistentMindPrompt(prior, { instructions: 'Updated' })).toMatchObject({
+ identity: 'Example identity', instructions: 'Updated',
+ });
+ expect(persistentMindPromptSchema.safeParse({ identity: 'ok', extra: true }).success).toBe(false);
+ });
+});
diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.js
index e82ab5cb73..4859975ec2 100644
--- a/server/lib/persistentMindTrajectory.js
+++ b/server/lib/persistentMindTrajectory.js
@@ -18,6 +18,9 @@ export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze([
'mind.wake',
'mind.model.request',
'mind.model.result',
+ 'mind.thought',
+ 'mind.reply',
+ 'mind.memory.candidate',
'mind.capability.request',
'mind.capability.result',
'mind.summary',
@@ -33,8 +36,10 @@ export const PERSISTENT_MIND_TRAJECTORY_LIMITS = Object.freeze({
defaultPageSize: 100,
maxPageSize: 500,
recentContextEvents: 60,
- maxContextChars: 16_000,
+ maxContextChars: 32_000,
maxIdentityChars: 2_000,
+ maxInstructionsChars: 8_000,
+ maxMemoriesChars: 8_000,
maxSummaryChars: 6_000,
maxStoredRollups: 100,
maxProjectedTurns: 100,
@@ -280,6 +285,8 @@ const renderEventLine = (event) => {
export function assemblePersistentMindContext({
mindId = PERSISTENT_MIND_ID,
identity = '',
+ instructions = '',
+ memories = [],
events = [],
rollups = [],
maxChars = PERSISTENT_MIND_TRAJECTORY_LIMITS.maxContextChars,
@@ -336,7 +343,30 @@ export function assemblePersistentMindContext({
typeof identity === 'string' ? identity : JSON.stringify(identity),
PERSISTENT_MIND_TRAJECTORY_LIMITS.maxIdentityChars
);
- const prefix = `# Persistent mind identity\nmindId=${mindId}${identityText ? `\n${identityText}` : ''}`;
+ const instructionsText = bounded(
+ typeof instructions === 'string' ? instructions : JSON.stringify(instructions),
+ PERSISTENT_MIND_TRAJECTORY_LIMITS.maxInstructionsChars
+ );
+ const memoryLines = (Array.isArray(memories) ? memories : [])
+ .filter((memory) => memory && typeof memory === 'object')
+ .map((memory) => {
+ const content = typeof memory.content === 'string' && memory.content.trim()
+ ? memory.content.trim()
+ : typeof memory.summary === 'string' ? memory.summary.trim() : '';
+ if (!content) return null;
+ const label = [memory.type, memory.category].filter(Boolean).join('/') || 'memory';
+ return `- [${label}; id=${memory.id || 'unknown'}] ${content}`;
+ })
+ .filter(Boolean);
+ const memoryText = bounded(
+ memoryLines.join('\n'),
+ PERSISTENT_MIND_TRAJECTORY_LIMITS.maxMemoriesChars
+ );
+ const prefix = [
+ `# Persistent mind identity\nmindId=${mindId}${identityText ? `\n${identityText}` : ''}`,
+ `# Operating instructions\n${instructionsText || '(none)'}`,
+ `# Curated memories\n${memoryText || '(none)'}`,
+ ].join('\n\n');
const summaryLines = effectiveReadyRollups
.map((rollup) => `[events ${rollup.source.fromSequence}-${rollup.source.toSequence}; ${rollup.provenance.providerId || 'unknown'}/${rollup.provenance.model || 'default'}; prompt v${rollup.provenance.promptVersion}]\n${rollup.summary}`);
const omittedStarts = [selectedRollups[0]?.source.fromSequence, older[0]?.sequence].filter(Number.isSafeInteger);
@@ -391,5 +421,8 @@ export function assemblePersistentMindContext({
toEventId: older.at(-1)?.eventId ?? selectedRollups.at(-1)?.source.toEventId ?? null,
} : null,
recentEventCount: recentLines.length,
+ memoryCount: memoryLines.length,
+ identityChars: identityText.length,
+ instructionsChars: instructionsText.length,
};
}
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 055021b24e..6d8ed8fcbd 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -11,14 +11,22 @@ import {
parsePersistentMindCursor,
} from '../lib/persistentMindTrajectory.js';
import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
import { validateRequest } from '../lib/validation.js';
import { readPersistentMindEvents, readPersistentMindHistory } from '../services/agentRunEventLog.js';
import { loadState } from '../services/cosState.js';
import {
appendPersistentMindAnnotation,
+ createPersistentMindMemory,
+ preparePersistentMindContext,
promotePersistentMindMemory,
+ readPersistentMindMemories,
+ readPersistentMindRollups,
+ updatePersistentMindMemory,
} from '../services/persistentMindContext.js';
+import { getProviderById } from '../services/providers.js';
+import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';
import {
enqueuePersistentMindMessage,
getPersistentMindState,
@@ -57,6 +65,27 @@ const promotionSchema = z.object({
category: z.string().trim().min(1).max(100).optional(),
tags: z.array(z.string().trim().min(1).max(100)).max(20).optional(),
}).strict();
+const memoryType = z.enum(['fact', 'learning', 'observation', 'decision', 'preference', 'context']);
+const memoryFields = {
+ content: z.string().trim().min(1).max(10_240),
+ summary: z.string().trim().max(500).optional(),
+ type: memoryType,
+ category: z.string().trim().min(1).max(100),
+ tags: z.array(z.string().trim().min(1).max(50)).max(20),
+ importance: z.number().min(0).max(1),
+};
+const memoryInputSchema = z.object({
+ ...memoryFields,
+ type: memoryFields.type.optional().default('observation'),
+ category: memoryFields.category.optional().default('other'),
+ tags: memoryFields.tags.optional().default([]),
+ importance: memoryFields.importance.optional().default(0.5),
+}).strict();
+const memoryUpdateSchema = z.object(memoryFields).partial().strict().refine(
+ (value) => Object.keys(value).length > 0,
+ 'At least one memory field is required'
+);
+const memoryParamsSchema = z.object({ memoryId: z.string().trim().min(1).max(128) }).strict();
const requireSuccess = (result) => {
if (result?.success === false) {
@@ -80,6 +109,7 @@ router.get('/mind', asyncHandler(async (req, res) => {
loadState(),
]);
const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const provider = profile.providerId ? await getProviderById(profile.providerId) : null;
const { snapshot: _snapshot, ...publicHistory } = history;
res.json({
...publicHistory,
@@ -91,10 +121,49 @@ router.get('/mind', asyncHandler(async (req, res) => {
effort: profile.effort || null,
thinkingInterface: profile.thinkingInterface,
},
+ harness: persistentMindHarnessInfo(provider),
autonomyMode: getDomainMode(root.config, 'cos'),
});
}));
+router.get('/mind/context', asyncHandler(async (_req, res) => {
+ const root = await loadState();
+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const [memories, rollups, provider] = await Promise.all([
+ readPersistentMindMemories(PERSISTENT_MIND_ID),
+ readPersistentMindRollups(PERSISTENT_MIND_ID),
+ profile.providerId ? getProviderById(profile.providerId) : null,
+ ]);
+ const preview = await preparePersistentMindContext({
+ mindId: PERSISTENT_MIND_ID,
+ identity: prompt.identity,
+ instructions: prompt.instructions,
+ memories,
+ });
+ res.json({
+ prompt,
+ preview,
+ memories,
+ rollups,
+ harness: persistentMindHarnessInfo(provider),
+ });
+}));
+
+router.post('/mind/memories', asyncHandler(async (req, res) => {
+ const input = validateRequest(memoryInputSchema, req.body);
+ const memory = await createPersistentMindMemory(input);
+ res.status(201).json({ success: true, memory });
+}));
+
+router.put('/mind/memories/:memoryId', asyncHandler(async (req, res) => {
+ const { memoryId } = validateRequest(memoryParamsSchema, req.params);
+ const updates = validateRequest(memoryUpdateSchema, req.body);
+ const memory = await updatePersistentMindMemory(memoryId, updates);
+ if (!memory) throw new ServerError('Persistent mind memory not found', { status: 404, code: 'NOT_FOUND' });
+ res.json({ success: true, memory });
+}));
+
router.post('/mind/messages', asyncHandler(async (req, res) => {
const input = validateRequest(messageSchema, req.body);
res.status(202).json(requireSuccess(await enqueuePersistentMindMessage(input)));
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index f2d6651657..0d7c3b8f88 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -10,7 +10,13 @@ const mocks = vi.hoisted(() => ({
getPersistentMindState: vi.fn(),
enqueuePersistentMindMessage: vi.fn(),
appendPersistentMindAnnotation: vi.fn(),
+ createPersistentMindMemory: vi.fn(),
+ preparePersistentMindContext: vi.fn(),
promotePersistentMindMemory: vi.fn(),
+ readPersistentMindMemories: vi.fn(),
+ readPersistentMindRollups: vi.fn(),
+ updatePersistentMindMemory: vi.fn(),
+ getProviderById: vi.fn(),
startPersistentMind: vi.fn(),
pausePersistentMind: vi.fn(),
resumePersistentMind: vi.fn(),
@@ -24,7 +30,21 @@ vi.mock('../services/agentRunEventLog.js', () => ({
vi.mock('../services/cosState.js', () => ({ loadState: mocks.loadState }));
vi.mock('../services/persistentMindContext.js', () => ({
appendPersistentMindAnnotation: mocks.appendPersistentMindAnnotation,
+ createPersistentMindMemory: mocks.createPersistentMindMemory,
+ preparePersistentMindContext: mocks.preparePersistentMindContext,
promotePersistentMindMemory: mocks.promotePersistentMindMemory,
+ readPersistentMindMemories: mocks.readPersistentMindMemories,
+ readPersistentMindRollups: mocks.readPersistentMindRollups,
+ updatePersistentMindMemory: mocks.updatePersistentMindMemory,
+}));
+vi.mock('../services/providers.js', () => ({ getProviderById: mocks.getProviderById }));
+vi.mock('../services/persistentMindAdapter.js', () => ({
+ persistentMindHarnessInfo: (provider) => ({
+ type: provider?.type || null,
+ label: provider?.type === 'api' ? 'Direct API' : 'Headless CLI',
+ recommendation: provider?.type === 'api' ? 'recommended' : 'supported',
+ detail: 'Structured provider harness.',
+ }),
}));
vi.mock('../services/persistentMindSupervisor.js', () => ({
getPersistentMindState: mocks.getPersistentMindState,
@@ -47,6 +67,7 @@ const app = () => {
const get = (path) => request(app()).get(`/api/cos${path}`);
const post = (path, body) => request(app()).post(`/api/cos${path}`).send(body);
+const put = (path, body) => request(app()).put(`/api/cos${path}`).send(body);
describe('persistent mind routes', () => {
beforeEach(() => {
@@ -58,7 +79,17 @@ describe('persistent mind routes', () => {
activeTurn: null, lastCompletedTurnId: null, lastCompletedAt: null, nextEligibleWakeAt: null,
failureCount: 0, pauseReason: null, lastError: 'provider failed with \"apiKey\": \"secret-value\"',
});
- mocks.loadState.mockResolvedValue({ config: { domainAutonomy: { cos: 'execute' }, persistentMindProfile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high' } } });
+ mocks.loadState.mockResolvedValue({ config: {
+ domainAutonomy: { cos: 'execute' },
+ persistentMindProfile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high' },
+ persistentMindPrompt: { schemaVersion: 1, identity: 'Resident mind', instructions: 'Stay grounded.' },
+ } });
+ mocks.getProviderById.mockResolvedValue({ id: 'demo', type: 'api' });
+ mocks.readPersistentMindMemories.mockResolvedValue([{ id: 'memory-1', content: 'A durable fact', sourceAgentId: 'cos-persistent-mind' }]);
+ mocks.readPersistentMindRollups.mockResolvedValue([]);
+ mocks.preparePersistentMindContext.mockResolvedValue({ text: '# Context', chars: 9, approximateTokens: 3, summaryState: 'empty' });
+ mocks.createPersistentMindMemory.mockResolvedValue({ id: 'memory-2', content: 'A new fact', sourceAgentId: 'cos-persistent-mind' });
+ mocks.updatePersistentMindMemory.mockResolvedValue({ id: 'memory-1', content: 'An edited fact', sourceAgentId: 'cos-persistent-mind' });
mocks.enqueuePersistentMindMessage.mockResolvedValue({ success: true, duplicate: false, messageId: 'message-1' });
mocks.appendPersistentMindAnnotation.mockResolvedValue({ appended: true, duplicate: false });
mocks.promotePersistentMindMemory.mockResolvedValue({ success: true, memory: { id: 'memory-1' } });
@@ -75,6 +106,7 @@ describe('persistent mind routes', () => {
expect(res.body).toMatchObject({
events: [], gap: false, state: { status: 'idle' },
profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text' },
+ harness: { type: 'api', recommendation: 'recommended' },
autonomyMode: 'execute',
});
expect(res.body.profile).not.toHaveProperty('credential');
@@ -84,6 +116,42 @@ describe('persistent mind routes', () => {
expect(JSON.stringify(res.body)).not.toContain('secret-value');
});
+ it('exposes the editable prompt, owned memories, derived rollups, and exact context preview', async () => {
+ const res = await get('/mind/context');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ prompt: { identity: 'Resident mind', instructions: 'Stay grounded.' },
+ preview: { text: '# Context', summaryState: 'empty' },
+ memories: [{ id: 'memory-1', content: 'A durable fact' }],
+ rollups: [],
+ harness: { type: 'api', recommendation: 'recommended' },
+ });
+ expect(mocks.preparePersistentMindContext).toHaveBeenCalledWith(expect.objectContaining({
+ mindId: 'cos-persistent-mind',
+ identity: 'Resident mind',
+ instructions: 'Stay grounded.',
+ memories: expect.any(Array),
+ }));
+ });
+
+ it('creates and edits only validated persistent-mind memories', async () => {
+ const created = await post('/mind/memories', { content: 'A new fact' });
+ expect(created.status).toBe(201);
+ expect(mocks.createPersistentMindMemory).toHaveBeenCalledWith({
+ content: 'A new fact', type: 'observation', category: 'other', tags: [], importance: 0.5,
+ });
+
+ const updated = await put('/mind/memories/memory-1', { content: 'An edited fact' });
+ expect(updated.status).toBe(200);
+ expect(mocks.updatePersistentMindMemory).toHaveBeenCalledWith('memory-1', { content: 'An edited fact' });
+ expect((await put('/mind/memories/memory-1', {})).status).toBe(400);
+ });
+
+ it('returns not found when an edited memory is not owned by this mind', async () => {
+ mocks.updatePersistentMindMemory.mockResolvedValue(null);
+ expect((await put('/mind/memories/foreign', { content: 'No access' })).status).toBe(404);
+ });
+
it('rejects malformed cursors, oversized pages, and unknown query fields', async () => {
expect((await get('/mind?cursor=broken')).status).toBe(400);
expect((await get('/mind?limit=501')).status).toBe(400);
diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.js
index b9a1bec0fa..af5fd60682 100644
--- a/server/routes/cosStatusRoutes.js
+++ b/server/routes/cosStatusRoutes.js
@@ -13,6 +13,7 @@ import { z } from 'zod';
import { DOMAIN_IDS, DOMAIN_MODES } from '../lib/domainAutonomy.js';
import { BUDGET_LIMIT_FIELDS } from '../lib/domainBudgets.js';
import { persistentMindProfileSchema } from '../lib/persistentMindProfile.js';
+import { persistentMindPromptSchema } from '../lib/persistentMindPrompt.js';
const router = Router();
@@ -53,6 +54,7 @@ export const cosConfigSchema = z.object({
// A durable reasoning route for the persistent mind. It is separate from
// `alwaysOn`: saving or enabling this profile never starts background work.
persistentMindProfile: persistentMindProfileSchema.optional(),
+ persistentMindPrompt: persistentMindPromptSchema.optional(),
// Per-domain autonomy guardrails (#711): partial map of domainId → mode.
// Partial is fine — updateConfig() merges it over the stored map.
domainAutonomy: z.object(
diff --git a/server/services/cos.js b/server/services/cos.js
index b29e61ca30..29ae4db7ee 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -36,6 +36,7 @@ import { getUserTimezone } from './userTimezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';
import { mergePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { mergePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { pendingCosActionReservations } from './cosAdmissionReservations.js';
// Dependency-free leaf holding the shared agent maps + the runner-mode flag,
@@ -157,7 +158,10 @@ import {
shutdownPersistentMindSupervisor,
handlePersistentMindGlobalPause,
handlePersistentMindGlobalResume,
+ registerPersistentMindTurnAdapter,
+ unregisterPersistentMindTurnAdapter,
} from './persistentMindSupervisor.js';
+import { createPersistentMindTurnAdapter } from './persistentMindAdapter.js';
export {
getPersistentMindState,
@@ -222,6 +226,7 @@ export async function updateConfig(updates) {
// domain) must merge field-by-field over the rest, not replace the map.
const priorDomainBudgets = state.config.domainBudgets;
const priorPersistentMindProfile = state.config.persistentMindProfile;
+ const priorPersistentMindPrompt = state.config.persistentMindPrompt;
state.config = { ...state.config, ...updates };
if (updates.domainAutonomy !== undefined) {
state.config.domainAutonomy = normalizeDomainAutonomy({
@@ -242,6 +247,12 @@ export async function updateConfig(updates) {
updates.persistentMindProfile,
);
}
+ if (updates.persistentMindPrompt !== undefined) {
+ state.config.persistentMindPrompt = mergePersistentMindPrompt(
+ priorPersistentMindPrompt,
+ updates.persistentMindPrompt,
+ );
+ }
await saveState(state);
return state.config;
});
@@ -458,6 +469,7 @@ export async function start() {
emitLog('info', 'Running initial task evaluation...');
await evaluateTasks({ initialStartup: true });
await runHealthCheck();
+ await registerPersistentMindTurnAdapter(createPersistentMindTurnAdapter());
await initializePersistentMindSupervisor();
cosEvents.emit('status', { running: true });
@@ -489,6 +501,7 @@ export async function stop() {
}
await shutdownPersistentMindSupervisor();
+ unregisterPersistentMindTurnAdapter();
// Cancel all scheduled events
cancelEvent('cos-health-check');
diff --git a/server/services/cosState.js b/server/services/cosState.js
index b9140ab072..596905f327 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -13,6 +13,7 @@ import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js
import { normalizeDomainBudgets } from '../lib/domainBudgets.js';
import { createDefaultPersistentMindState, normalizePersistentMindState } from '../lib/persistentMind.js';
import { createDefaultPersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { createDefaultPersistentMindPrompt, normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';
export const STATE_FILE = join(PATHS.cos, 'state.json');
@@ -66,6 +67,7 @@ export const DEFAULT_CONFIG = {
// Persisting a profile is not consent to wake the mind. Fresh and upgraded
// installs stay disabled until the user explicitly starts it.
persistentMindProfile: createDefaultPersistentMindProfile(),
+ persistentMindPrompt: createDefaultPersistentMindPrompt(),
// Per-domain autonomy guardrails (#711). Each domain is off | dry-run | execute.
// Default is `execute` for every domain, reproducing pre-#711 behavior so no
// migration is needed — an install with no stored value reads `execute`.
@@ -227,6 +229,7 @@ export async function loadState() {
...DEFAULT_CONFIG,
...persistedConfig,
persistentMindProfile: normalizePersistentMindProfile(persistedConfig.persistentMindProfile),
+ persistentMindPrompt: normalizePersistentMindPrompt(persistedConfig.persistentMindPrompt),
},
stats: { ...DEFAULT_STATE.stats, ...state.stats },
persistentMind: normalizePersistentMindState(state.persistentMind),
diff --git a/server/services/memoryDB.js b/server/services/memoryDB.js
index 74cbf9d7e5..20ca5240ab 100644
--- a/server/services/memoryDB.js
+++ b/server/services/memoryDB.js
@@ -55,7 +55,8 @@ function rowToMeta(row) {
importance: row.importance,
createdAt: row.created_at.toISOString(),
status: row.status,
- sourceAppId: row.source_app_id
+ sourceAppId: row.source_app_id,
+ sourceAgentId: row.source_agent_id,
};
}
@@ -215,6 +216,12 @@ function buildMemoryFilterWhere(options = {}) {
params.push(options.appId);
}
+
+ if (options.sourceAgentId) {
+ conditions.push(`source_agent_id = $${paramIdx++}`);
+ params.push(options.sourceAgentId);
+ }
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
return { where, params };
}
@@ -248,7 +255,7 @@ export async function getMemories(options = {}) {
const limit = options.limit || 50;
const dataResult = await query(
- `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id
+ `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id, source_agent_id
FROM memories ${where}
ORDER BY ${sortBy} ${sortOrder}
LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
new file mode 100644
index 0000000000..4b3693e52d
--- /dev/null
+++ b/server/services/persistentMindAdapter.js
@@ -0,0 +1,202 @@
+/**
+ * Production text-provider adapter for the persistent Chief-of-Staff mind.
+ *
+ * The adapter deliberately uses the non-interactive provider runner. API and
+ * headless CLI providers are stable service transports; TUI providers remain
+ * supported for compatibility, but their terminal startup/scrape lifecycle is
+ * exposed to the UI as the least reliable choice. Provider fallback is off:
+ * the configured model is part of this mind's identity.
+ */
+
+import { z } from 'zod';
+import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';
+import { parseLLMJSON } from '../lib/llmText.js';
+import { loadState } from './cosState.js';
+import { readPersistentMindMemories } from './persistentMindContext.js';
+import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
+import { runPromptThroughProvider } from './promptRunner.js';
+import { stopRun } from './runner.js';
+
+const memoryCandidateSchema = z.object({
+ content: z.string().trim().min(1).max(10_240),
+ summary: z.string().trim().max(500).optional().default(''),
+ type: z.enum(['fact', 'learning', 'observation', 'decision', 'preference', 'context']).optional().default('observation'),
+ category: z.string().trim().min(1).max(100).optional().default('other'),
+ tags: z.array(z.string().trim().min(1).max(50)).max(20).optional().default([]),
+}).strict();
+
+export const persistentMindResponseSchema = z.object({
+ thinkingSummary: z.string().trim().max(4_000).optional().default(''),
+ message: z.string().trim().max(8_000).optional().default(''),
+ memoryCandidates: z.array(memoryCandidateSchema).max(5).optional().default([]),
+ selfWake: z.object({
+ reason: z.string().trim().min(1).max(500),
+ delayMinutes: z.number().int().min(1).max(10_080),
+ }).strict().nullable().optional().default(null),
+}).strict();
+
+export function persistentMindHarnessInfo(provider) {
+ const type = provider?.type || null;
+ if (type === 'api') {
+ return {
+ type,
+ label: 'Direct API',
+ recommendation: 'recommended',
+ detail: 'Best fit for a persistent service: structured HTTP, clean cancellation, streaming, and no terminal state. Ollama, llama.cpp, LM Studio, vLLM, and compatible cloud endpoints use this lane.',
+ };
+ }
+ if (type === 'cli') {
+ return {
+ type,
+ label: 'Headless CLI',
+ recommendation: 'supported',
+ detail: 'Reliable when the vendor CLI owns authentication or model access, with more process startup overhead than a direct API.',
+ };
+ }
+ if (type === 'tui') {
+ return {
+ type,
+ label: 'Interactive TUI',
+ recommendation: 'not-recommended',
+ detail: 'Compatibility lane only. Startup selectors, terminal redraws, response-file handoff, and screen scraping make it fragile for an unattended long-lived mind.',
+ };
+ }
+ return {
+ type,
+ label: 'Unknown harness',
+ recommendation: 'unavailable',
+ detail: 'Choose a configured API or headless CLI text provider.',
+ };
+}
+
+const currentWakeText = (wake) => {
+ if (wake?.kind === 'message') {
+ return `A human message is waiting. Reply directly to it.\nmessageId=${wake.message?.id || 'unknown'}\n${wake.message?.text || ''}`;
+ }
+ return `This is a self-directed wake. Continue one worthwhile thread from the trajectory.\nreason=${wake?.reason || 'scheduled reflection'}`;
+};
+
+export function buildPersistentMindTurnPrompt({ context, wake }) {
+ return `${context.text}
+
+# Current wake
+${currentWakeText(wake)}
+
+# Response contract
+Return ONLY one JSON object with this shape:
+{
+ "thinkingSummary": "A concise, user-visible working note explaining what you considered and why. Do not reveal hidden chain-of-thought.",
+ "message": "The conversational reply. Required for a human message; optional for a self-directed wake.",
+ "memoryCandidates": [{ "content": "A durable fact worth proposing", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"] }],
+ "selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 }
+}
+Use an empty array when there is no durable memory candidate and null when no earlier follow-up is needed. Memory candidates are proposals only; a human decides whether to promote them. This lane cannot mutate files, call tools, contact people, or perform external actions.`;
+}
+
+const summaryEventLines = (events) => (Array.isArray(events) ? events : []).map((event) => {
+ const text = event?.data?.displayText || event?.data?.summaryText || event?.kind;
+ return `[${event?.sequence ?? '?'}] ${event?.kind}: ${text}`;
+}).join('\n');
+
+export function buildPersistentMindSummaryPrompt({ events, previousSummary }) {
+ return `Summarize this older portion of one persistent mind's life in first person. Preserve concrete decisions, unresolved questions, user preferences, and causal links. Do not invent facts. Return plain text only, no heading.\n\n${previousSummary ? `Prior cumulative summary:\n${previousSummary}\n\n` : ''}New trajectory events:\n${summaryEventLines(events)}`;
+}
+
+async function runPinnedPrompt({ provider, model, effort, prompt, signal, responseSchema }) {
+ if (signal?.aborted) throw new Error(String(signal.reason || 'Persistent mind turn interrupted'));
+ let activeRunId = null;
+ const interrupt = () => {
+ if (activeRunId) void stopRun(activeRunId).catch(() => {});
+ };
+ signal?.addEventListener('abort', interrupt, { once: true });
+ return runPromptThroughProvider({
+ provider,
+ model,
+ effort,
+ prompt,
+ source: 'cos-persistent-mind',
+ allowFallback: false,
+ responseSchema,
+ onRunCreated: (runId) => {
+ activeRunId = runId;
+ if (signal?.aborted) interrupt();
+ },
+ }).finally(() => signal?.removeEventListener('abort', interrupt));
+}
+
+export function createPersistentMindTurnAdapter() {
+ return {
+ async prepare({ profile }) {
+ const [root, memories] = await Promise.all([
+ loadState(),
+ readPersistentMindMemories(PERSISTENT_MIND_ID),
+ ]);
+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ return {
+ ok: true,
+ provider: profile.provider,
+ model: profile.model,
+ effort: profile.effort,
+ identity: prompt.identity,
+ instructions: prompt.instructions,
+ memories,
+ };
+ },
+
+ async summarize({ events, previousSummary, provider, model, effort, signal }) {
+ const result = await runPinnedPrompt({
+ provider,
+ model,
+ effort,
+ signal,
+ prompt: buildPersistentMindSummaryPrompt({ events, previousSummary }),
+ });
+ return result.text.trim();
+ },
+
+ async run({ turnId, wake, provider, model, effort, signal, context, heartbeat }) {
+ await heartbeat();
+ const result = await runPinnedPrompt({
+ provider,
+ model,
+ effort,
+ signal,
+ prompt: buildPersistentMindTurnPrompt({ context, wake }),
+ responseSchema: persistentMindResponseSchema,
+ });
+ const parsed = persistentMindResponseSchema.parse(parseLLMJSON(result.text));
+ const message = parsed.message || (wake?.kind === 'message' ? parsed.thinkingSummary : '');
+ if (!parsed.thinkingSummary && !message && parsed.memoryCandidates.length === 0) {
+ throw new Error('Persistent mind returned no visible thought, reply, or memory candidate');
+ }
+ const events = [];
+ if (parsed.thinkingSummary) {
+ events.push({
+ kind: 'mind.thought',
+ id: `thought:${turnId}`,
+ data: { displayText: parsed.thinkingSummary, visibility: 'user-summary' },
+ });
+ }
+ if (message) {
+ events.push({
+ kind: 'mind.reply',
+ id: `reply:${turnId}`,
+ data: { displayText: message, replyToMessageId: wake?.message?.id || null },
+ });
+ }
+ parsed.memoryCandidates.forEach((candidate, index) => events.push({
+ kind: 'mind.memory.candidate',
+ id: `memory-candidate:${turnId}:${index}`,
+ data: { ...candidate, displayText: candidate.content },
+ }));
+ return {
+ output: result.text,
+ events,
+ selfWake: parsed.selfWake ? {
+ reason: parsed.selfWake.reason,
+ notBefore: new Date(Date.now() + parsed.selfWake.delayMinutes * 60_000).toISOString(),
+ } : null,
+ };
+ },
+ };
+}
diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.js
new file mode 100644
index 0000000000..5b14c219b5
--- /dev/null
+++ b/server/services/persistentMindAdapter.test.js
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({
+ root: { config: { persistentMindPrompt: { identity: 'Example identity', instructions: 'Example instructions' } } },
+ memories: [{ id: 'memory-1', type: 'fact', content: 'A durable fact.', sourceAgentId: 'cos-persistent-mind', status: 'active' }],
+ runPrompt: vi.fn(),
+ stopRun: vi.fn(),
+}));
+
+vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mock.root) }));
+vi.mock('./persistentMindContext.js', () => ({ readPersistentMindMemories: vi.fn(async () => mock.memories) }));
+vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: (...args) => mock.runPrompt(...args) }));
+vi.mock('./runner.js', () => ({ stopRun: (...args) => mock.stopRun(...args) }));
+
+const { createPersistentMindTurnAdapter, persistentMindHarnessInfo } = await import('./persistentMindAdapter.js');
+
+const profile = { provider: { id: 'example-api', type: 'api' }, model: 'example-model', effort: 'high' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.runPrompt.mockResolvedValue({ text: JSON.stringify({
+ thinkingSummary: 'I connected the new request to the durable fact.',
+ message: 'Here is the answer.',
+ memoryCandidates: [{ content: 'Remember this.', type: 'fact', category: 'other', tags: [] }],
+ selfWake: null,
+ }) });
+});
+
+describe('persistent mind adapter', () => {
+ it('prepares editable prompt and curated memory context without inference', async () => {
+ const prepared = await createPersistentMindTurnAdapter().prepare({ profile });
+ expect(prepared).toMatchObject({
+ provider: profile.provider,
+ identity: 'Example identity',
+ instructions: 'Example instructions',
+ memories: mock.memories,
+ });
+ expect(mock.runPrompt).not.toHaveBeenCalled();
+ });
+
+ it('runs the exact pinned non-interactive profile and returns visible trajectory events', async () => {
+ const heartbeat = vi.fn(async () => true);
+ const result = await createPersistentMindTurnAdapter().run({
+ turnId: 'turn-1',
+ wake: { kind: 'message', message: { id: 'message-1', text: 'Hello' } },
+ ...profile,
+ signal: new AbortController().signal,
+ context: { text: '# Context' },
+ heartbeat,
+ });
+
+ expect(mock.runPrompt).toHaveBeenCalledWith(expect.objectContaining({
+ provider: profile.provider,
+ model: 'example-model',
+ effort: 'high',
+ source: 'cos-persistent-mind',
+ allowFallback: false,
+ }));
+ expect(heartbeat).toHaveBeenCalled();
+ expect(result.events.map((event) => event.kind)).toEqual([
+ 'mind.thought', 'mind.reply', 'mind.memory.candidate',
+ ]);
+ });
+
+ it('makes the provider harness tradeoff explicit', () => {
+ expect(persistentMindHarnessInfo({ type: 'api' }).recommendation).toBe('recommended');
+ expect(persistentMindHarnessInfo({ type: 'cli' }).recommendation).toBe('supported');
+ expect(persistentMindHarnessInfo({ type: 'tui' }).recommendation).toBe('not-recommended');
+ });
+});
diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.js
index 07758e7822..06930aa113 100644
--- a/server/services/persistentMindContext.js
+++ b/server/services/persistentMindContext.js
@@ -55,6 +55,19 @@ export async function readPersistentMindRollups(mindId = PERSISTENT_MIND_ID) {
.sort((a, b) => a.source.fromSequence - b.source.fromSequence);
}
+/** Full active memories explicitly owned by this mind, newest importance first. */
+export async function readPersistentMindMemories(mindId = PERSISTENT_MIND_ID) {
+ const result = await memoryBackend.getMemories({
+ status: 'active',
+ sourceAgentId: mindId,
+ sortBy: 'importance',
+ sortOrder: 'desc',
+ limit: 100,
+ });
+ const details = await Promise.all((result.memories || []).map((memory) => memoryBackend.peekMemory(memory.id)));
+ return details.filter((memory) => memory?.status === 'active' && memory.sourceAgentId === mindId);
+}
+
export function recordPersistentMindRollup(input) {
const rollup = buildPersistentMindRollup(input);
return queueRollupWrite(async () => {
@@ -100,6 +113,8 @@ const summaryOutcome = (summarize, input) => Promise.resolve()
export async function preparePersistentMindContext({
mindId = PERSISTENT_MIND_ID,
identity = '',
+ instructions = '',
+ memories = [],
maxChars,
recentEventLimit = PERSISTENT_MIND_TRAJECTORY_LIMITS.recentContextEvents,
promptVersion = PERSISTENT_MIND_ROLLUP_PROMPT_VERSION,
@@ -108,8 +123,11 @@ export async function preparePersistentMindContext({
summarize = null,
forceSummary = false,
} = {}) {
- const history = await readPersistentMindHistory(mindId);
- let rollups = await readPersistentMindRollups(mindId);
+ const [history, initialRollups] = await Promise.all([
+ readPersistentMindHistory(mindId),
+ readPersistentMindRollups(mindId),
+ ]);
+ let rollups = initialRollups;
const older = history.slice(0, Math.max(0, history.length - Math.max(1, recentEventLimit)));
let coverageGap = null;
@@ -193,6 +211,8 @@ export async function preparePersistentMindContext({
return assemblePersistentMindContext({
mindId,
identity,
+ instructions,
+ memories,
events: history,
rollups,
maxChars,
@@ -202,6 +222,20 @@ export async function preparePersistentMindContext({
});
}
+export function createPersistentMindMemory({ mindId = PERSISTENT_MIND_ID, ...input } = {}) {
+ return memoryBackend.createMemory({
+ ...input,
+ sourceAgentId: mindId,
+ status: 'active',
+ });
+}
+
+export async function updatePersistentMindMemory(memoryId, updates, mindId = PERSISTENT_MIND_ID) {
+ const existing = await memoryBackend.peekMemory(memoryId);
+ if (!existing || existing.sourceAgentId !== mindId) return null;
+ return memoryBackend.updateMemory(memoryId, updates);
+}
+
/** Add an attributable comment/idea to the trajectory. */
export function appendPersistentMindAnnotation({
id,
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index dd3192e553..4611bb8528 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -499,7 +499,9 @@ async function runOnePersistentMindTurn() {
runStartedAt = Date.now();
const context = await preparePersistentMindContext({
mindId: mind.mindId,
- identity: turnAdapter.identity || 'One supervised persistent Chief of Staff mind.',
+ identity: prepared.identity ?? turnAdapter.identity ?? 'One supervised persistent Chief of Staff mind.',
+ instructions: prepared.instructions || '',
+ memories: Array.isArray(prepared.memories) ? prepared.memories : [],
providerId: prepared.provider.id,
model: prepared.model || null,
summarize: typeof turnAdapter.summarize === 'function'
@@ -549,6 +551,15 @@ async function runOnePersistentMindTurn() {
});
},
});
+ for (const event of Array.isArray(result?.events) ? result.events : []) {
+ await appendMindEvent({
+ kind: event.kind,
+ mindId: mind.mindId,
+ turnId: turn.id,
+ eventId: `mind-${event.id}`,
+ data: event.data,
+ });
+ }
await appendMindEvent({
kind: 'mind.model.result',
mindId: mind.mindId,
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index f583402bbf..40fd6833f8 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -542,6 +542,9 @@ export function assertVisionRunUsedImages(result, requestedProvider) {
* must pass this — without it, the CLI/TUI spawn lands in PortOS's own
* cwd and the analysis runs against the wrong files. No-op for API
* providers (no spawn).
+ * @param {boolean} [args.allowFallback=true] — set false when provider/model
+ * identity is part of the feature contract. Disables proactive provider
+ * substitution and every model/provider retry tier after the first attempt.
* @param {*} [args.responseSchema] — the caller's declared response schema
* (issue #2350). A Zod-style schema (`.safeParse`/`.parse`) or a bare
* predicate `(parsedValue) => boolean`. When set, the runner enables Tier-2
@@ -653,6 +656,10 @@ export async function runPromptThroughProvider(rawArgs) {
throw stripFallbackContext(firstError);
}
+ if (rawArgs.allowFallback === false) {
+ throw stripFallbackContext(firstError);
+ }
+
{
// Only retry when the failure came from the execution layer (annotated
// by safeReject with effectiveProvider) or is a synthetic schema/type
@@ -1142,6 +1149,7 @@ async function executeProviderRunOnce({
cwd: cwdOverride,
screenshots = [],
outputReserveTokens,
+ allowFallback = true,
}) {
// Resolve the model that'll actually run BEFORE creating the run record
// so the record reflects reality. resolveEffectiveModel handles both
@@ -1178,6 +1186,7 @@ async function executeProviderRunOnce({
workspacePath: effectiveCwd,
effort,
requestCapabilities: buildRequestCapabilities({ prompt, screenshots, outputReserveTokens }),
+ allowFallback,
});
runId = runResult.runId;
if (runResult.provider && runResult.provider.id !== provider.id) {
diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.js
index e64b5c6d8a..bea2be984a 100644
--- a/server/services/promptRunner.test.js
+++ b/server/services/promptRunner.test.js
@@ -784,6 +784,25 @@ describe('promptRunner — retry-with-fallback', () => {
return { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider };
}
+ it('keeps an exact provider pin and skips every fallback tier when disabled', async () => {
+ const status = mockToolkitWithFallback();
+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => {
+ onComplete({ success: false, error: 'Pinned provider failed' });
+ });
+
+ await expect(runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ allowFallback: false,
+ })).rejects.toThrow('Pinned provider failed');
+
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({ allowFallback: false }));
+ expect(status.markUnavailable).not.toHaveBeenCalled();
+ expect(status.getFallbackProvider).not.toHaveBeenCalled();
+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();
+ });
+
it('does not retry, bench, or escalate a canceled TUI run', async () => {
const status = mockToolkitWithFallback();
const primaryTui = tuiProvider({ id: 'primary-tui', name: 'Primary TUI', defaultModel: 'primary-model' });