Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: save and restore versioned Mind read recipes (#7194)
[._.]/ Adam Eivy60baf65f188f
diff --git a/client/src/components/cos/PersistentMindRecipeLibrary.jsx b/client/src/components/cos/PersistentMindRecipeLibrary.jsxnew file mode 100644index 0000000000..6fdd012b8d--- /dev/null+++ b/client/src/components/cos/PersistentMindRecipeLibrary.jsx@@ -0,0 +1,182 @@+import { useCallback, useEffect, useId, useRef, useState } from 'react';+import { useSearchParams } from 'react-router';+import * as api from '../../services/api';+import Banner from '../ui/Banner';+import { formatDateShort } from '../../utils/formatters';++const EXAMPLE = {+ schemaVersion: 1,+ name: 'recipe.project-checkin',+ purpose: 'Collect matching Brain notes and current goals.',+ parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'], additionalProperties: false },+ steps: [+ { id: 'search', tool: 'brain.search', arguments: { query: { input: 'query' } } },+ { id: 'goals', tool: 'goals.list', arguments: {} },+ ],+ outputs: { matches: { step: 'search', path: [] }, goals: { step: 'goals', path: [] } },+};+const buttonClass = 'min-h-10 rounded border border-port-border px-3 text-sm text-port-text hover:border-port-accent disabled:opacity-50';++function RecipeEditor({ id, onChanged, onSelect }) {+ const inputId = useId();+ const [detail, setDetail] = useState(null);+ const [text, setText] = useState(id === 'new' ? JSON.stringify(EXAMPLE, null, 2) : '');+ const [loading, setLoading] = useState(id !== 'new');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState(null);+ const [validation, setValidation] = useState(null);+ const [reload, setReload] = useState(0);+ const active = useRef(false);+ const recipe = detail?.recipe;+ const dirty = recipe && text !== JSON.stringify(recipe.definition, null, 2);++ useEffect(() => {+ active.current = true;+ let cancelled = false;+ if (id !== 'new') {+ setLoading(true);+ setError(null);+ setValidation(null);+ api.getMindRecipe(id, { silent: true }).then((response) => {+ if (cancelled) return;+ setDetail(response);+ setText(JSON.stringify(response.recipe.definition, null, 2));+ }).catch((failure) => {+ if (!cancelled) setError(failure.status === 404 ? 'Recipe not found. Select another recipe or create one.' : failure.message);+ }).finally(() => { if (!cancelled) setLoading(false); });+ }+ return () => { cancelled = true; active.current = false; };+ }, [id, reload]);++ const run = (operation) => {+ setBusy(true);+ setError(null);+ setValidation(null);+ Promise.resolve().then(operation).catch((failure) => {+ if (!active.current) return;+ const location = [failure.context?.field, failure.context?.step && `step ${failure.context.step}`].filter(Boolean).join(' · ');+ const details = Array.isArray(failure.context?.details)+ ? failure.context.details.slice(0, 3).map((entry) => `${Array.isArray(entry.path) ? entry.path.join('.') : entry.path || 'definition'}: ${entry.message}`).join('; ')+ : '';+ setError(`${location ? `${location}: ` : ''}${failure.message}${details ? ` — ${details}` : ''}${failure.status === 409 ? ' Reload the saved revision before trying again; copy your draft first.' : ''}`);+ }).finally(() => { if (active.current) setBusy(false); });+ };++ const apply = (saved) => {+ if (!active.current) return;+ onChanged(saved);+ setDetail((current) => ({+ recipe: saved,+ versions: [{ revision: saved.activeRevision, definition: saved.definition, author: 'user', createdAt: saved.updatedAt }, ...(current?.versions || [])],+ }));+ setText(JSON.stringify(saved.definition, null, 2));+ if (id === 'new') onSelect(saved.id);+ };++ const save = () => run(async () => {+ const definition = JSON.parse(text);+ const saved = recipe+ ? await api.updateMindRecipe(id, { expectedRevision: recipe.activeRevision, definition }, { silent: true })+ : await api.createMindRecipe(definition, { silent: true });+ apply(saved);+ });+ const validate = () => run(async () => {+ const result = await api.validateMindRecipe(JSON.parse(text), { silent: true });+ if (active.current) setValidation(result);+ });++ if (loading) return <p role="status" className="text-sm text-port-text-muted">Loading recipe…</p>;+ return (+ <div className="min-w-0 space-y-3 rounded border border-port-border p-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="font-semibold text-port-text">{id === 'new' ? 'New recipe' : recipe?.name || 'Recipe unavailable'}</h3>+ {recipe && <span className="text-xs text-port-text-muted">Revision {recipe.activeRevision} · {recipe.archived ? 'Archived' : recipe.available === false ? 'Unavailable' : 'Saved'}</span>}+ <button type="button" className={buttonClass} onClick={() => onSelect(null)}>Close editor</button>+ </div>+ {error && <Banner tone="error" title="Recipe could not be completed">{error}</Banner>}+ {id !== 'new' && <button type="button" className={buttonClass} disabled={busy} onClick={() => setReload((value) => value + 1)}>Reload saved revision</button>}+ {(recipe || id === 'new') && <>+ <label htmlFor={inputId} className="block text-sm text-port-text">Recipe definition (JSON)</label>+ <textarea id={inputId} value={text} disabled={busy} onChange={(event) => { setText(event.target.value); setValidation(null); }} spellCheck={false} rows={18} className="w-full rounded border border-port-border bg-port-bg p-3 font-mono text-xs text-port-text disabled:opacity-50" />+ <p className="text-xs text-port-text-muted">Use a recipe.* name and closed object parameters (additionalProperties: false). Each step calls a supported read tool. Arguments bind a literal, an input parameter, or an earlier step output; output paths are arrays of field names or index strings. No scripts, expressions, or nested recipes.</p>+ {dirty && <p className="text-xs text-port-text-muted">Unsaved edits. Save a revision or reload the saved definition before archiving or restoring history.</p>}+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={validate} disabled={busy} className={buttonClass}>Validate definition</button>+ <button type="button" onClick={save} disabled={busy || recipe?.archived} className={buttonClass}>{id === 'new' ? 'Save recipe' : 'Save new revision'}</button>+ {recipe && !recipe.archived && <button type="button" disabled={busy || dirty} className={buttonClass} onClick={() => run(async () => apply(await api.archiveMindRecipe(id, recipe.activeRevision, { silent: true })))}>Archive recipe</button>}+ </div>+ {busy && <p role="status" className="text-xs text-port-text-muted">Working…</p>}+ {validation && <div role="status" className="space-y-1 text-sm text-port-success">+ <p>Definition valid. Validation does not run tools.</p>+ {(validation.runtimeChecks || []).map((check, index) => <p key={`${check.field}-${index}`} className="text-xs text-port-text-muted">{check.field}{check.step ? ` · step ${check.step}` : ''}: {check.message}</p>)}+ </div>}+ {recipe?.archived && <p className="text-xs text-port-text-muted">Restore a revision below to make this recipe active again.</p>}+ {detail?.versions?.length > 0 && <section aria-label="Revision history" className="space-y-2">+ <h4 className="text-sm font-semibold text-port-text">Revision history</h4>+ {detail.versions.map((version) => <div key={version.revision} className="rounded border border-port-border p-2">+ <details>+ <summary className="cursor-pointer text-sm text-port-text">Revision {version.revision} · {version.author}{version.createdAt ? ` · ${formatDateShort(version.createdAt)}` : ''}</summary>+ <pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs text-port-text-muted">{JSON.stringify(version.definition, null, 2)}</pre>+ </details>+ <button type="button" disabled={busy || dirty || (!recipe.archived && version.revision === recipe.activeRevision)} className={`${buttonClass} mt-2`} onClick={() => run(async () => apply(await api.restoreMindRecipe(id, { expectedRevision: recipe.activeRevision, revision: version.revision }, { silent: true })))}>Restore revision {version.revision}</button>+ </div>)}+ </section>}+ </>}+ </div>+ );+}++export default function PersistentMindRecipeLibrary() {+ const [searchParams, setSearchParams] = useSearchParams();+ // Tools already lives in a URL-driven Mind panel; preserve that panel and its other parameters.+ const selected = searchParams.get('recipe');+ const [recipes, setRecipes] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [reload, setReload] = useState(0);+ const version = useRef(0);+ useEffect(() => {+ const request = ++version.current;+ setLoading(true);+ api.getMindRecipes({ silent: true }).then((result) => {+ if (request !== version.current) return;+ // Revisions only advance (including archive/restore), so a read started+ // before a local save must not replace that newer row or lose other rows.+ setRecipes((current) => {+ const merged = new Map((result.recipes || []).map((recipe) => [recipe.id, recipe]));+ for (const recipe of current) {+ if (!merged.has(recipe.id) || merged.get(recipe.id).activeRevision < recipe.activeRevision) merged.set(recipe.id, recipe);+ }+ return [...merged.values()];+ });+ setError(null);+ }).catch((failure) => { if (request === version.current) setError(failure.message); })+ .finally(() => { if (request === version.current) setLoading(false); });+ return () => { version.current += 1; };+ }, [reload]);+ const onChanged = useCallback((recipe) => {+ setRecipes((current) => current.some((entry) => entry.id === recipe.id) ? current.map((entry) => entry.id === recipe.id ? recipe : entry) : [recipe, ...current]);+ }, []);+ const onSelect = (id) => setSearchParams((current) => {+ const next = new URLSearchParams(current);+ if (id) next.set('recipe', id);+ else next.delete('recipe');+ return next;+ });+ return <section aria-label="Saved tool recipes" className="space-y-3 rounded border border-port-border bg-port-card p-4">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-base font-semibold text-port-text">Saved tool recipes</h2>+ <button type="button" className={buttonClass} onClick={() => onSelect('new')}>New recipe</button>+ </div>+ <p className="text-sm text-port-text-muted">Manage reusable read definitions and their history with Mind grants off. Saved recipes are not yet callable by the Mind. Nothing executes when you save or validate.</p>+ {error && <Banner tone="error" title="Recipe library unavailable">{error} <button type="button" className={buttonClass} onClick={() => setReload((value) => value + 1)}>Retry library</button></Banner>}+ {loading ? <p role="status" className="text-sm text-port-text-muted">Loading recipes…</p> : !recipes.length && !error ? <p className="text-sm text-port-text-muted">No saved recipes. Create one from the editable example.</p> : null}+ <ul className="space-y-2">+ {recipes.map((recipe) => <li key={recipe.id} className="flex flex-wrap items-center justify-between gap-2 rounded border border-port-border p-2">+ <button type="button" onClick={() => onSelect(recipe.id)} className="min-h-10 break-all text-left text-sm text-port-accent hover:underline" aria-current={selected === recipe.id ? 'true' : undefined}>{recipe.name}</button>+ <span className="text-xs text-port-text-muted">Revision {recipe.activeRevision} · {recipe.archived ? 'Archived' : recipe.available === false ? 'Unavailable' : 'Saved'}</span>+ </li>)}+ </ul>+ {selected && <RecipeEditor key={selected} id={selected} onChanged={onChanged} onSelect={onSelect} />}+ </section>;+}diff --git a/client/src/components/cos/PersistentMindRecipeLibrary.test.jsx b/client/src/components/cos/PersistentMindRecipeLibrary.test.jsxnew file mode 100644index 0000000000..42d77cda3e--- /dev/null+++ b/client/src/components/cos/PersistentMindRecipeLibrary.test.jsx@@ -0,0 +1,140 @@+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { MemoryRouter, useLocation, useNavigate } from 'react-router';+import PersistentMindRecipeLibrary from './PersistentMindRecipeLibrary';++const api = vi.hoisted(() => ({+ getMindRecipes: vi.fn(), getMindRecipe: vi.fn(), createMindRecipe: vi.fn(),+ updateMindRecipe: vi.fn(), validateMindRecipe: vi.fn(), archiveMindRecipe: vi.fn(), restoreMindRecipe: vi.fn(),+}));+vi.mock('../../services/api', () => api);+const definition = { schemaVersion: 1, name: 'recipe.project-checkin', purpose: 'Project summary', parameters: { type: 'object', properties: {}, additionalProperties: false }, steps: [{ id: 'goals', tool: 'goals.list', arguments: {} }], outputs: { goals: { step: 'goals', path: [] } } };+const recipe = (overrides = {}) => ({ id: 'first', name: definition.name, activeRevision: 1, definition, archived: false, available: true, updatedAt: '2026-09-12T00:00:00Z', ...overrides });+const detail = (entry) => ({ recipe: entry, versions: [{ revision: entry.activeRevision, definition: entry.definition, author: 'user', createdAt: entry.updatedAt }] });+function TestPage() {+ const location = useLocation();+ const navigate = useNavigate();+ return <><output data-testid="location">{location.search}</output><button type="button" onClick={() => navigate('/cos/mind?panel=tools&recipe=second')}>Navigate to second</button><PersistentMindRecipeLibrary /></>;+}+const renderPage = (search = '?panel=tools') => render(<MemoryRouter initialEntries={[`/cos/mind${search}`]}><TestPage /></MemoryRouter>);+const deferred = () => { let resolve; const promise = new Promise((yes) => { resolve = yes; }); return { promise, resolve }; };++beforeEach(() => {+ vi.resetAllMocks();+ api.getMindRecipes.mockResolvedValue({ recipes: [] });+ api.getMindRecipe.mockImplementation(async (id) => detail(recipe({ id, name: id === 'second' ? 'recipe.second' : definition.name })));+ api.validateMindRecipe.mockResolvedValue({ valid: true, runtimeChecks: [{ field: 'steps.0.arguments', step: 'goals', message: 'Output bindings are checked at invocation.' }] });+ api.createMindRecipe.mockResolvedValue(recipe());+});++describe('PersistentMindRecipeLibrary', () => {+ it('creates from an editable example, validates without execution, and preserves the panel link', async () => {+ const user = userEvent.setup();+ renderPage();+ expect(await screen.findByText(/No saved recipes/)).toBeInTheDocument();+ expect(screen.getByText(/with Mind grants off/)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'New recipe' }));+ expect(JSON.parse(screen.getByLabelText('Recipe definition (JSON)').value).name).toBe('recipe.project-checkin');+ await user.click(screen.getByRole('button', { name: 'Validate definition' }));+ expect(await screen.findByText('Definition valid. Validation does not run tools.')).toBeInTheDocument();+ expect(screen.getByText(/Output bindings are checked at invocation/)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Save recipe' }));+ expect(await screen.findByRole('button', { name: definition.name })).toBeInTheDocument();+ expect(screen.getByTestId('location')).toHaveTextContent('?panel=tools&recipe=first');+ expect(api.getMindRecipes).toHaveBeenCalledTimes(1);+ expect(api.createMindRecipe).toHaveBeenCalledWith(expect.objectContaining({ schemaVersion: 1, name: definition.name }), { silent: true });+ });++ it('preserves invalid drafts and revision conflicts, and saves the expected revision', async () => {+ const user = userEvent.setup();+ renderPage('?panel=tools&recipe=first');+ const editor = await screen.findByLabelText('Recipe definition (JSON)');+ fireEvent.change(editor, { target: { value: '{bad' } });+ await user.click(screen.getByRole('button', { name: 'Save new revision' }));+ expect(await screen.findByText('Recipe could not be completed')).toBeInTheDocument();+ expect(api.updateMindRecipe).not.toHaveBeenCalled();+ const changed = { ...definition, purpose: 'Updated purpose' };+ fireEvent.change(editor, { target: { value: JSON.stringify(changed) } });+ api.validateMindRecipe.mockRejectedValueOnce(Object.assign(new Error('Read tool is unavailable'), { context: { field: 'steps.0.tool', step: 'goals' } }));+ await user.click(screen.getByRole('button', { name: 'Validate definition' }));+ expect(await screen.findByText(/steps.0.tool · step goals: Read tool is unavailable/)).toBeInTheDocument();+ expect(editor).toHaveValue(JSON.stringify(changed));+ api.validateMindRecipe.mockRejectedValueOnce(Object.assign(new Error('Validation failed'), { context: { details: [{ path: ['definition', 'parameters', 'additionalProperties'], message: 'Must be false' }] } }));+ await user.click(screen.getByRole('button', { name: 'Validate definition' }));+ expect(await screen.findByText(/definition.parameters.additionalProperties: Must be false/)).toBeInTheDocument();+ api.updateMindRecipe.mockRejectedValueOnce(Object.assign(new Error('Revision conflict'), { status: 409 }));+ await user.click(screen.getByRole('button', { name: 'Save new revision' }));+ expect(await screen.findByText(/copy your draft first/)).toBeInTheDocument();+ expect(editor).toHaveValue(JSON.stringify(changed));+ expect(api.updateMindRecipe).toHaveBeenCalledWith('first', { expectedRevision: 1, definition: changed }, { silent: true });+ api.updateMindRecipe.mockResolvedValueOnce(recipe({ definition: changed, activeRevision: 2 }));+ await user.click(screen.getByRole('button', { name: 'Save new revision' }));+ expect(await screen.findByText(/Revision 2 · user/)).toBeInTheDocument();+ });++ it('archives and restores history as a new revision with immediate list updates', async () => {+ const user = userEvent.setup();+ api.getMindRecipes.mockResolvedValue({ recipes: [recipe()] });+ api.archiveMindRecipe.mockResolvedValue(recipe({ archived: true, available: false, activeRevision: 2 }));+ api.restoreMindRecipe.mockResolvedValue(recipe({ activeRevision: 3 }));+ renderPage('?panel=tools&recipe=first');+ await user.click(await screen.findByRole('button', { name: 'Archive recipe' }));+ expect(await screen.findByText(/Restore a revision below/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Save new revision' })).toBeDisabled();+ expect(api.archiveMindRecipe).toHaveBeenCalledWith('first', 1, { silent: true });+ await user.click(screen.getByRole('button', { name: 'Restore revision 1' }));+ expect(await screen.findByText(/Revision 3 · user/)).toBeInTheDocument();+ expect(api.restoreMindRecipe).toHaveBeenCalledWith('first', { expectedRevision: 2, revision: 1 }, { silent: true });+ expect(screen.getByRole('button', { name: 'Save new revision' })).toBeEnabled();+ expect(within(screen.getByRole('list')).getByText('Revision 3 · Saved')).toBeInTheDocument();+ expect(api.getMindRecipes).toHaveBeenCalledTimes(1);+ });++ it('ignores stale detail and save responses when the URL selection changes', async () => {+ const user = userEvent.setup();+ const lateDetail = deferred();+ api.getMindRecipe.mockImplementationOnce(() => lateDetail.promise);+ renderPage('?panel=tools&recipe=first');+ await user.click(screen.getByRole('button', { name: 'Navigate to second' }));+ const editor = await screen.findByLabelText('Recipe definition (JSON)');+ await act(async () => lateDetail.resolve(detail(recipe())));+ expect(screen.getByRole('heading', { name: 'recipe.second' })).toBeInTheDocument();+ const lateSave = deferred();+ api.updateMindRecipe.mockReturnValueOnce(lateSave.promise);+ await user.click(screen.getByRole('button', { name: 'Save new revision' }));+ expect(editor).toBeDisabled();+ await user.click(screen.getByRole('button', { name: 'Close editor' }));+ await user.click(screen.getByRole('button', { name: 'New recipe' }));+ await act(async () => lateSave.resolve(recipe({ id: 'second', activeRevision: 2 })));+ expect(screen.getByRole('heading', { name: 'New recipe' })).toBeInTheDocument();+ expect(screen.getByTestId('location')).toHaveTextContent('recipe=new');+ expect(screen.queryByText(/Revision 2 · user/)).not.toBeInTheDocument();+ });++ it('keeps newer saved rows and unrelated recipes when an earlier library read finishes', async () => {+ const user = userEvent.setup();+ const lateList = deferred();+ api.getMindRecipes.mockReturnValueOnce(lateList.promise);+ api.archiveMindRecipe.mockResolvedValue(recipe({ activeRevision: 2, archived: true }));+ renderPage('?panel=tools&recipe=first');+ await user.click(await screen.findByRole('button', { name: 'Archive recipe' }));+ await screen.findByText(/Restore a revision below/);+ await act(async () => lateList.resolve({ recipes: [recipe(), recipe({ id: 'second', name: 'recipe.second' })] }));+ const list = within(screen.getByRole('list'));+ expect(list.getByText('Revision 2 · Archived')).toBeInTheDocument();+ expect(list.getByRole('button', { name: 'recipe.second' })).toBeInTheDocument();+ });++ it('shows lookup failures and retries instead of treating them as an empty library', async () => {+ const user = userEvent.setup();+ api.getMindRecipes.mockRejectedValueOnce(new Error('Database unavailable'));+ api.getMindRecipe.mockRejectedValueOnce(Object.assign(new Error('Missing'), { status: 404 }));+ renderPage('?panel=tools&recipe=missing');+ expect(await screen.findByText(/Recipe not found/)).toBeInTheDocument();+ expect(screen.getByText(/Database unavailable/)).toBeInTheDocument();+ expect(screen.queryByText(/No saved recipes/)).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Retry library' }));+ await waitFor(() => expect(screen.getByText(/No saved recipes/)).toBeInTheDocument());+ });+});diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsxindex 5c36be2b26..ba54470f3a 100644--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@ -3,9 +3,10 @@ import * as api from '../../services/api';import toast from '../ui/Toast';const normalizeCapabilities = (value) => ({- schemaVersion: 8,+ schemaVersion: 9,createTasks: value?.createTasks === true,manageMind: value?.manageMind === true,+ manageToolRecipes: value?.manageToolRecipes === true,manageEidoverse: value?.manageEidoverse === true,visitEidoversePeers: value?.visitEidoversePeers === true,callUser: value?.callUser === true,@@ -20,6 +21,11 @@ const normalizeCapabilities = (value) => ({});const OPTIONS = [+ {+ key: 'manageToolRecipes',+ label: 'Allow mind to manage saved tool recipes',+ hint: 'Definition authority only; underlying reads still require bounded PortOS read access. Mind authoring and invocation arrive in a later phase. You can manage the library below with this grant off.',+ },{key: 'readPortos',label: 'Allow bounded PortOS reads',@@ -77,7 +83,7 @@ export default function PersistentMindTaskAccessControls({useEffect(() => {if (!saving) setDraft(normalizeCapabilities(capabilities));- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.manageEidoverse, capabilities?.visitEidoversePeers, capabilities?.callUser, capabilities?.adjustLocalContext, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.manageToolRecipes, capabilities?.manageEidoverse, capabilities?.visitEidoversePeers, capabilities?.callUser, capabilities?.adjustLocalContext, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);const save = async (key, enabled) => {const previous = draft;diff --git a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsxindex 02bb4ac544..87361e0109 100644--- a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx+++ b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx@@ -67,6 +67,7 @@ export default function PersistentMindTaskModelAllowlistControls({const next = {schemaVersion: 3,createTasks: capabilities?.createTasks === true,+ manageToolRecipes: capabilities?.manageToolRecipes === true,readPortos: capabilities?.readPortos === true,writePortos: capabilities?.writePortos === true,taskModelAllowlist: deduped,diff --git a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsx b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsxindex 5f6dc10a43..02c4d31bc2 100644--- a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsx+++ b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsx@@ -31,6 +31,7 @@ describe('PersistentMindTaskModelAllowlistControls', () => {persistentMindCapabilities: {schemaVersion: 3,createTasks: true,+ manageToolRecipes: false,readPortos: false,writePortos: false,taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }],diff --git a/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsx b/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsxindex e2175a1561..a9e10b7cb1 100644--- a/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsx+++ b/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsx@@ -19,6 +19,7 @@ const api = vi.hoisted(() => ({updateCosConfig: vi.fn(),getPersistentMindContext: vi.fn(),getPersistentMindTools: vi.fn(),+ getMindRecipes: vi.fn().mockResolvedValue({ recipes: [] }),getPersistentMindRuntime: vi.fn(),getPersistentMindVisibility: vi.fn(),createPersistentMindMemory: vi.fn(),diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex 8977a046c3..3af970aef5 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -21,6 +21,7 @@ const api = vi.hoisted(() => ({updateCosConfig: vi.fn(),getPersistentMindContext: vi.fn(),getPersistentMindTools: vi.fn(),+ getMindRecipes: vi.fn().mockResolvedValue({ recipes: [] }),getPersistentMindRuntime: vi.fn(),getPersistentMindVisibility: vi.fn(),createPersistentMindMemory: vi.fn(),@@ -406,7 +407,7 @@ describe('MindTab', () => {await user.click(taskAccess);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 8, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(screen.getAllByText(/code review then merge/i).length).toBeGreaterThan(0);diff --git a/client/src/pages/PersistentMindTools.jsx b/client/src/pages/PersistentMindTools.jsxindex 16196a1082..0af9c3c9fb 100644--- a/client/src/pages/PersistentMindTools.jsx+++ b/client/src/pages/PersistentMindTools.jsx@@ -4,6 +4,7 @@ import { Link } from 'react-router';import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';import Banner from '../components/ui/Banner';+import PersistentMindRecipeLibrary from '../components/cos/PersistentMindRecipeLibrary';import PersistentMindTaskAccessControls from '../components/cos/PersistentMindTaskAccessControls';import PersistentMindTaskModelAllowlistControls from '../components/cos/PersistentMindTaskModelAllowlistControls';@@ -70,6 +71,7 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChanreturn (<div className="space-y-4">+ <PersistentMindRecipeLibrary />{error && <Banner tone="error" title="Tools unavailable">{error}. The last loaded state is preserved; retry when the connection recovers.</Banner>}{loading && !data ? (diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsxindex 83ba7e1150..feaf2f22f4 100644--- a/client/src/pages/PersistentMindTools.test.jsx+++ b/client/src/pages/PersistentMindTools.test.jsx@@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({getPersistentMindTools: vi.fn(),+ getMindRecipes: vi.fn().mockResolvedValue({ recipes: [] }),getProviders: vi.fn(),updateCosConfig: vi.fn(),}));@@ -48,6 +49,22 @@ describe('PersistentMindTools', () => {api.updateCosConfig.mockResolvedValue({ success: true });});+ it('allows user recipe management with its separate Mind grant off and preserves the grant on later saves', async () => {+ const user = userEvent.setup();+ renderPage();+ const grant = await screen.findByRole('checkbox', { name: 'Allow mind to manage saved tool recipes' });+ expect(grant).not.toBeChecked();+ expect(screen.getByRole('button', { name: 'New recipe' })).toBeEnabled();+ await user.click(grant);+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({+ persistentMindCapabilities: expect.objectContaining({ schemaVersion: 9, manageToolRecipes: true, readPortos: false }),+ }, { silent: true }));+ await user.click(screen.getByRole('checkbox', { name: 'Allow bounded PortOS reads' }));+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenLastCalledWith({+ persistentMindCapabilities: expect.objectContaining({ manageToolRecipes: true, readPortos: true }),+ }, { silent: true }));+ });+it('updates executable tool access after changing a grant', async () => {api.getPersistentMindTools.mockResolvedValue(response({ semanticTools: [{name: 'eidoverse.augment', description: 'Build a private world', granted: false,@@ -65,7 +82,7 @@ describe('PersistentMindTools', () => {expect(toggle).not.toBeChecked();await userEvent.setup().click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({- persistentMindCapabilities: expect.objectContaining({ schemaVersion: 8, visitEidoversePeers: true, manageEidoverse: false }),+ persistentMindCapabilities: expect.objectContaining({ schemaVersion: 9, visitEidoversePeers: true, manageEidoverse: false }),}, { silent: true }));});@@ -96,7 +113,7 @@ describe('PersistentMindTools', () => {await user.click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 8, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(await screen.findByText(/persistent-mind capabilities granted/)).toHaveTextContent('1 of 1');@@ -116,9 +133,10 @@ describe('PersistentMindTools', () => {await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 8,+ schemaVersion: 9,createTasks: false,manageMind: true,+ manageToolRecipes: false,manageEidoverse: false,visitEidoversePeers: false,callUser: false,@@ -153,9 +171,10 @@ describe('PersistentMindTools', () => {await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 8,+ schemaVersion: 9,createTasks: true,manageMind: false,+ manageToolRecipes: false,manageEidoverse: false,visitEidoversePeers: false,callUser: false,@@ -219,9 +238,10 @@ describe('PersistentMindTools', () => {await user.click(callToggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 8,+ schemaVersion: 9,createTasks: false,manageMind: false,+ manageToolRecipes: false,manageEidoverse: false,visitEidoversePeers: false,callUser: true,diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 396d92237c..e66f0efe6a 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -41,7 +41,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart) + local open actions (editor, folder, Xcode) + `getAppIssues` (open GitHub/GitLab issues for the Issues tab). || `apiWorkspaceContexts.js` | Per-project working-context save/restore (branch, shells, tasks). || `apiAccounts.js` | Platform accounts. |-| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, the CoS task schedule (intervals, on-demand triggers, manual maintenance runs via `getMaintenanceRuns`/`startMaintenanceRun`/`stopMaintenanceRun`), and persistent-mind conversation, lifecycle, context, and runtime-telemetry calls. |+| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, the CoS task schedule (intervals, on-demand triggers, manual maintenance runs via `getMaintenanceRuns`/`startMaintenanceRun`/`stopMaintenanceRun`), and persistent-mind conversation, lifecycle, context, runtime-telemetry calls, and versioned tool recipe library CRUD, validation, archive, and restore calls. || `apiCommands.js` | CLI command dispatch. || `apiDashboard.js` | Dashboard state. || `apiDatabase.js` | Database introspection. |diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 0d861f6d56..5f12907695 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -57,6 +57,23 @@ export const cancelPersistentMindThinkingRequest = (options = {}) =>request('/cos/mind/thinking-request', { method: 'DELETE', ...options });export const getPersistentMindContext = (options = {}) => request('/cos/mind/context', options);export const getPersistentMindTools = (options = {}) => request('/cos/mind/tools', options);+export const getMindRecipes = (options = {}) => request('/cos/mind/recipes', options);+export const getMindRecipe = (id, options = {}) => request(`/cos/mind/recipes/${encodeURIComponent(id)}`, options);+export const createMindRecipe = (definition, options = {}) => request('/cos/mind/recipes', {+ method: 'POST', body: JSON.stringify({ definition }), ...options,+});+export const updateMindRecipe = (id, body, options = {}) => request(`/cos/mind/recipes/${encodeURIComponent(id)}`, {+ method: 'PUT', body: JSON.stringify(body), ...options,+});+export const validateMindRecipe = (definition, options = {}) => request('/cos/mind/recipes/validate', {+ method: 'POST', body: JSON.stringify({ definition }), ...options,+});+export const archiveMindRecipe = (id, expectedRevision, options = {}) => request(`/cos/mind/recipes/${encodeURIComponent(id)}/archive`, {+ method: 'POST', body: JSON.stringify({ expectedRevision }), ...options,+});+export const restoreMindRecipe = (id, body, options = {}) => request(`/cos/mind/recipes/${encodeURIComponent(id)}/restore`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});export const getCosToolCatalog = ({ scope = 'all', format = 'portos', intent, ...options } = {}) => {const params = new URLSearchParams({ scope, format });if (intent) params.set('intent', intent);diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 57ef1ea2bf..b9d08f0031 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -21,6 +21,8 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](## `db-primary` — app-native relational records+- `mind_tool_recipes` / `mind_tool_recipe_versions` — machine-local authored read-tool definitions, stable IDs, active revision/archive metadata, and immutable revisions linked by recipe ID (#7194). No execution output is stored; no definitions or literals enter federation/status payloads. PostgreSQL backup covers both tables. Migration 381 registers schema-only installation; empty installs receive no user recipe seed. Unknown future definitions are retained but unavailable.+**Definition.** Records that PortOS itself authors and relates: they have foreign keys, statuses, audit trails, search/vector indexes, and federated sync cursors/tombstones. The DB is the source of truth; there is no meaningful file representation of the record.**When to use.** The record participates in relationships (`series.universeId`, `issue.seriesId`, catalog refs), needs cross-record queries ("everything related to this universe"), needs full-text or vector search, or needs per-table sequence cursors for peer sync.diff --git a/scripts/migrations/381-mind-tool-recipes.js b/scripts/migrations/381-mind-tool-recipes.jsnew file mode 100644index 0000000000..95b582d47d--- /dev/null+++ b/scripts/migrations/381-mind-tool-recipes.js@@ -0,0 +1,8 @@+/** Recipe definitions are db-primary. Idempotent DDL runs through ensureSchema+ * at boot and ships in init-db.sql for fresh installs. No user data is seeded. */+export default {+ async up() {+ console.log('📚 Mind recipe definition and revision tables are installed by ensureSchema at boot');+ return { success: true };+ },+};diff --git a/server/lib/README.md b/server/lib/README.mdindex a540e45a69..aca5082e4f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -640,3 +640,5 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `voiceEngines.js` | Shared TTS engine IDs, display metadata, supported-engine set, persisted configuration keys, and retired TTS config migration. || `auditQuality.js` | Category discovery strategies, assessment prompt and strict schema, sentinel parsing, and freshness-aware app quality aggregation with deterministic latest-per-category selection across peers. |++| `mindToolRecipes.js` | Closed recipe schemas, current semantic-contract validation, and safe JSON field binding resolution. |diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex d81c03b702..d3800624a6 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -52,3 +52,5 @@ init-db.sql, each with a one-line reason.`ensureSchemaImpl()` calls these two builders and runs each list through`pool.query` in order.++| `mindToolRecipes.js` | `mindToolRecipesDdl`: machine-local recipe definitions and immutable revisions. |diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex ed39f8bc93..d40ba1e45c 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -30,6 +30,7 @@ import { loraDdl } from './lora.js';import { privacyDdl } from './privacy.js';import { stackerNewsDdl } from './stackerNews.js';import { xDdl } from './x.js';+import { mindToolRecipesDdl } from './mindToolRecipes.js';import { beeperDdl } from './beeper.js';import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';@@ -53,6 +54,7 @@ export {stackerNewsDdl,xDdl,beeperDdl,+ mindToolRecipesDdl,auditDdl,auditedTables,buildAuditTriggers,@@ -92,6 +94,7 @@ export function buildCatalogDdl() {...stackerNewsDdl,...xDdl,...beeperDdl,+ ...mindToolRecipesDdl,...auditDdl,...buildAuditTriggers(),];diff --git a/server/lib/db/schema/mindToolRecipes.js b/server/lib/db/schema/mindToolRecipes.jsnew file mode 100644index 0000000000..3fb0a6fa37--- /dev/null+++ b/server/lib/db/schema/mindToolRecipes.js@@ -0,0 +1,20 @@+// Machine-local authored definitions only; never execution outputs or federation data.+export const mindToolRecipesDdl = [+ `CREATE TABLE IF NOT EXISTS mind_tool_recipes (+ id UUID PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ active_revision INTEGER NOT NULL CHECK (active_revision > 0),+ archived BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )`,+ `CREATE TABLE IF NOT EXISTS mind_tool_recipe_versions (+ recipe_id UUID NOT NULL REFERENCES mind_tool_recipes (id) ON DELETE CASCADE,+ revision INTEGER NOT NULL CHECK (revision > 0),+ definition JSONB NOT NULL,+ author TEXT NOT NULL CHECK (author IN ('user', 'mind')),+ archived BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (recipe_id, revision)+ )`,+];diff --git a/server/lib/index.js b/server/lib/index.jsindex 3bee132887..3551336513 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -623,3 +623,5 @@ export * as voiceEcho from './voiceEcho.js';export * from './voiceEngines.js';export * from './auditQuality.js';++export * from './mindToolRecipes.js';diff --git a/server/lib/mindToolRecipes.js b/server/lib/mindToolRecipes.jsnew file mode 100644index 0000000000..7c9a911b16--- /dev/null+++ b/server/lib/mindToolRecipes.js@@ -0,0 +1,171 @@+/** Closed, non-executable recipe definitions. No tools or providers run here. */+import { z } from 'zod';+import { ServerError } from './errorHandler.js';++export const MIND_TOOL_RECIPE_SCHEMA_VERSION = 1;+const key = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/)+ .refine((value) => !['constructor', 'prototype', '__proto__'].includes(value), 'reserved field');+const fields = (schema) => z.record(key, schema).refine((value) => Object.keys(value).length <= 30, 'at most 30 fields');+const primitiveMatches = (value, type) => type === 'null' ? value === null+ : type === 'integer' ? Number.isInteger(value)+ : typeof value === type;+const parameter = z.lazy(() => z.object({+ type: z.enum(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null']),+ description: z.string().max(500).optional(),+ properties: fields(parameter).optional(),+ required: z.array(key).max(30).optional(),+ additionalProperties: z.literal(false).optional(),+ items: parameter.optional(),+ enum: z.array(z.union([z.string().max(2000), z.number().finite(), z.boolean(), z.null()])).min(1).max(30).optional(),+}).strict().superRefine((value, ctx) => {+ if (value.type === 'object') {+ if (!value.properties || value.additionalProperties !== false) ctx.addIssue({ code: 'custom', message: 'objects require properties and additionalProperties: false' });+ for (const name of value.required || []) if (!Object.hasOwn(value.properties || {}, name)) ctx.addIssue({ code: 'custom', path: ['required'], message: 'required field must exist in properties' });+ } else if (value.properties || value.required || value.additionalProperties !== undefined) ctx.addIssue({ code: 'custom', message: 'object keywords require object type' });+ if (value.enum?.some((entry) => !primitiveMatches(entry, value.type))) ctx.addIssue({ code: 'custom', path: ['enum'], message: 'enum values must match the declared primitive type' });+ if ((value.type === 'array') !== !!value.items) ctx.addIssue({ code: 'custom', path: ['items'], message: 'only arrays require an items schema' });+}));+const path = z.array(z.string().regex(/^(?:[A-Za-z][A-Za-z0-9_-]{0,63}|0|[1-9][0-9]{0,5})$/)+ .refine((value) => !['constructor', 'prototype', '__proto__'].includes(value), 'reserved field')).max(8);+export const mindToolRecipeBindingSchema = z.union([+ z.object({ literal: z.json() }).strict(),+ z.object({ input: key }).strict(),+ z.object({ step: key, path }).strict(),+]);+const definition = z.object({+ schemaVersion: z.literal(MIND_TOOL_RECIPE_SCHEMA_VERSION),+ name: z.string().regex(/^recipe\.[a-z][a-z0-9-]{0,63}$/),+ purpose: z.string().trim().min(1).max(1000),+ parameters: parameter.refine((value) => value.type === 'object', 'parameters must be a closed object'),+ steps: z.array(z.object({ id: key, tool: z.string().min(1).max(100), arguments: fields(mindToolRecipeBindingSchema) }).strict()).min(1).max(5),+ outputs: fields(mindToolRecipeBindingSchema).refine((value) => Object.keys(value).length > 0, 'at least one output binding'),+}).strict();+// Bound recursive parsing before Zod descends into authored JSON.+const boundedJson = z.unknown().superRefine((value, ctx) => {+ const queue = [[value, 0]];+ let nodes = 0;+ let chars = 0;+ while (queue.length) {+ const [item, depth] = queue.pop();+ if (typeof item === 'string') chars += item.length;+ if (++nodes > 4000 || depth > 16 || chars > 64000) {+ ctx.addIssue({ code: 'custom', message: 'definition exceeds depth or size limit' });+ return;+ }+ if (item && typeof item === 'object') queue.push(...Object.values(item).map((child) => [child, depth + 1]));+ else if (typeof item === 'string' && item.length > 12000) {+ ctx.addIssue({ code: 'custom', message: 'definition value exceeds size limit' });+ return;+ }+ }+});+export const mindToolRecipeDefinitionSchema = boundedJson.pipe(definition);+export const mindToolRecipeSaveSchema = z.object({ definition: mindToolRecipeDefinitionSchema }).strict();+export const mindToolRecipeRevisionSchema = z.object({ expectedRevision: z.number().int().positive() }).strict();+export const mindToolRecipeUpdateSchema = mindToolRecipeRevisionSchema.extend({ definition: mindToolRecipeDefinitionSchema });+export const mindToolRecipeRestoreSchema = mindToolRecipeRevisionSchema.extend({ revision: z.number().int().positive() });++const fail = (field, message, step) => {+ throw new ServerError(`${field}: ${message}`, { status: 400, code: 'RECIPE_VALIDATION_ERROR', context: { field, ...(step ? { step } : {}) } });+};+const parseDefinition = (candidate) => {+ const parsed = mindToolRecipeDefinitionSchema.safeParse(candidate);+ if (!parsed.success) {+ const issue = parsed.error.issues[0];+ fail(issue.path.join('.') || 'definition', issue.message);+ }+ return parsed.data;+};+const compatibleType = (source, target) => {+ if (!target.type || !source.type) return true;+ const targets = Array.isArray(target.type) ? target.type : [target.type];+ const sources = Array.isArray(source.type) ? source.type : [source.type];+ return sources.some((type) => targets.includes(type) || (type === 'integer' && targets.includes('number')));+};+const checkBindingType = (source, target, field, step) => {+ if (!compatibleType(source, target)) fail(field, 'binding type does not match target argument contract', step);+ if (source.enum && target.enum && !source.enum.some((value) => target.enum.includes(value))) fail(field, 'binding enum cannot satisfy target argument contract', step);+ if (source.type === 'array' && target.type === 'array' && source.items && target.items) checkBindingType(source.items, target.items, field, step);+ if (source.type === 'object' && target.type === 'object') {+ for (const required of target.required || []) {+ if (!Object.hasOwn(source.properties || {}, required) && source.additionalProperties === false) fail(field, 'binding object lacks a required target field', step);+ }+ for (const [name, schema] of Object.entries(source.properties || {})) {+ if (target.properties?.[name]) checkBindingType(schema, target.properties[name], field, step);+ else if (target.additionalProperties === false && (source.required || []).includes(name)) fail(field, 'binding object contains a required field outside the target contract', step);+ }+ }+};+const walkOutput = (schema, segments, field, step, runtimeChecks) => {+ let current = schema;+ for (const segment of segments) {+ if (current?.type === 'array' && /^\d+$/.test(segment)) current = current.items;+ else if (Object.hasOwn(current?.properties || {}, segment)) current = current.properties[segment];+ else if (current?.additionalProperties === true || !current?.type) {+ runtimeChecks.push({ field, step, message: 'Open output: binding presence and type must be checked at invocation' });+ return null;+ } else fail(field, 'output field is not declared by this tool', step);+ }+ return current;+};++/** Validate against the current catalog without reading any private tool result. */+export function validateMindToolRecipe(candidate, catalog) {+ const value = parseDefinition(candidate);+ const runtimeChecks = [];+ const names = new Set(catalog.flatMap((tool) => [tool.name, tool.providerName, ...(tool.aliases || [])]));+ if (names.has(value.name)) fail('name', 'name collides with a shipped tool');+ const earlier = new Map();+ const inspectBinding = (binding, target, field, step) => {+ let source;+ if (Object.hasOwn(binding, 'literal')) {+ if (target && !z.fromJSONSchema(target).safeParse(binding.literal).success) fail(field, 'literal does not match target argument contract', step);+ return;+ }+ if (binding.input) {+ source = value.parameters.properties[binding.input];+ if (!source) fail(field, 'input field is not declared', step);+ if (!(value.parameters.required || []).includes(binding.input)) runtimeChecks.push({ field, step, message: 'Optional input binding must be present at invocation' });+ } else {+ const tool = earlier.get(binding.step);+ if (!tool) fail(field, 'step reference must name an earlier step', step);+ source = walkOutput(tool.output_schema, binding.path, field, step, runtimeChecks);+ }+ if (!target || !source) return;+ checkBindingType(source, target, field, step);+ // Constraints and optional output properties need the actual value even+ // when their top-level types agree. Never promise static certainty here.+ runtimeChecks.push({ field, step, message: 'Validate bound value against the target contract at invocation' });+ };+ for (const [index, step] of value.steps.entries()) {+ const field = `steps.${index}`;+ if (earlier.has(step.id)) fail(`${field}.id`, 'step ids must be unique', step.id);+ const tool = catalog.find((entry) => entry.name === step.tool);+ if (!tool || tool.policy.sideEffect !== 'read' || !tool.policy.scopes.includes('mind') || tool.name.startsWith('recipe.')) fail(`${field}.tool`, 'select a current canonical read tool in mind scope', step.id);+ const contract = tool.input_schema;+ for (const required of contract.required || []) if (!Object.hasOwn(step.arguments, required)) fail(`${field}.arguments.${required}`, 'required argument is missing', step.id);+ for (const [name, binding] of Object.entries(step.arguments)) {+ if (!Object.hasOwn(contract.properties || {}, name)) fail(`${field}.arguments.${name}`, 'unknown tool argument', step.id);+ inspectBinding(binding, contract.properties[name], `${field}.arguments.${name}`, step.id);+ }+ earlier.set(step.id, tool);+ }+ for (const [name, binding] of Object.entries(value.outputs)) inspectBinding(binding, null, `outputs.${name}`);+ return { valid: true, definition: value, runtimeChecks };+}++/** Phase 2 can use this at invocation; it never executes a tool itself. */+export function resolveMindToolRecipeBinding(binding, inputs, results, field = 'binding') {+ if (Object.hasOwn(binding, 'literal')) return structuredClone(binding.literal);+ if (binding.input) {+ if (!Object.hasOwn(inputs, binding.input)) fail(field, 'input binding is missing');+ return inputs[binding.input];+ }+ if (!Object.hasOwn(results, binding.step)) fail(field, 'step result is missing', binding.step);+ let value = results[binding.step];+ for (const segment of binding.path) {+ if (value === null || typeof value !== 'object' || !Object.hasOwn(value, segment)) fail(field, 'output binding is missing', binding.step);+ value = value[segment];+ }+ return value;+}diff --git a/server/lib/mindToolRecipes.test.js b/server/lib/mindToolRecipes.test.jsnew file mode 100644index 0000000000..8c7bd2dec1--- /dev/null+++ b/server/lib/mindToolRecipes.test.js@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';+import { mindToolRecipeDefinitionSchema, validateMindToolRecipe, resolveMindToolRecipeBinding } from './mindToolRecipes.js';+import { createDefaultPersistentMindCapabilities, mergePersistentMindCapabilities, persistentMindCapabilitiesSchema } from './persistentMindCapabilities.js';++const tool = (name, properties = {}, required = [], output = { type: 'object', additionalProperties: true }) => ({+ name, aliases: [`alias_${name}`], policy: { scopes: ['mind'], sideEffect: 'read' },+ input_schema: { type: 'object', properties, required, additionalProperties: false }, output_schema: output,+});+const catalog = [tool('brain.search', { query: { type: 'string' } }, ['query']), tool('goals.list', { limit: { type: 'integer' } })];+const recipe = () => ({ schemaVersion: 1, name: 'recipe.checkin', purpose: 'Find project notes and goals',+ parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'], additionalProperties: false },+ steps: [{ id: 'search', tool: 'brain.search', arguments: { query: { input: 'query' } } }, { id: 'goals', tool: 'goals.list', arguments: {} }],+ outputs: { notes: { step: 'search', path: ['entries'] }, goals: { step: 'goals', path: [] } },+});++describe('closed, governed recipe definition boundary', () => {+ it('validates the library without claiming static certainty for open tool outputs', () => {+ const result = validateMindToolRecipe(recipe(), catalog);+ expect(result.valid).toBe(true);+ expect(result.runtimeChecks).toContainEqual(expect.objectContaining({ field: 'outputs.notes', message: expect.stringContaining('Open output') }));+ });++ it.each([+ ['arbitrary code', (value) => { value.steps[0].code = 'process.exit()'; }],+ ['dynamic tools', (value) => { value.steps[0].tool = { input: 'query' }; }],+ ['expression binding', (value) => { value.steps[0].arguments.query = { expression: 'query + 1' }; }],+ ['enum with wrong primitive type', (value) => { value.parameters.properties.query.enum = [3]; }],+ ['open parameters', (value) => { value.parameters.additionalProperties = true; }],+ ['nested recipes', (value) => { value.steps[0].tool = 'recipe.other'; }],+ ['forward reference', (value) => { value.steps[0].arguments.query = { step: 'goals', path: ['title'] }; }],+ ['bad literal', (value) => { value.steps[0].arguments.query = { literal: 3 }; }],+ ['unknown input', (value) => { value.steps[0].arguments.query = { input: 'missing' }; }],+ ['unknown argument', (value) => { value.steps[0].arguments.url = { literal: 'https://invalid.example' }; }],+ ['future version', (value) => { value.schemaVersion = 2; }],+ ['duplicate step', (value) => { value.steps[1].id = 'search'; }],+ ['six steps', (value) => { value.steps = Array.from({ length: 6 }, (_, i) => ({ id: `step${i}`, tool: 'goals.list', arguments: {} })); }],+ ])('rejects %s', (_name, change) => {+ const value = recipe(); change(value);+ expect(() => validateMindToolRecipe(value, catalog)).toThrow();+ });++ it('rejects declared output and input type mismatches, writes, wrong scope and name collisions', () => {+ const value = recipe();+ value.steps[1].arguments.limit = { input: 'query' };+ expect(() => validateMindToolRecipe(value, catalog)).toThrow('binding type');+ value.parameters.properties.query = { type: 'object', properties: { tag: { type: 'integer' } }, required: ['tag'], additionalProperties: false };+ expect(() => validateMindToolRecipe(value, [tool('brain.search', { query: { type: 'object', properties: { tag: { type: 'string' } }, required: ['tag'], additionalProperties: false } }, ['query']), catalog[1]])).toThrow('binding type');+ value.parameters.properties.query = { type: 'string' };+ value.steps[1].arguments = {};+ expect(() => validateMindToolRecipe(value, [catalog[0], { ...catalog[1], policy: { scopes: ['mind'], sideEffect: 'write' } }])).toThrow('read tool');+ expect(() => validateMindToolRecipe(value, [catalog[0], { ...catalog[1], policy: { scopes: ['voice'], sideEffect: 'read' } }])).toThrow('mind scope');+ expect(() => validateMindToolRecipe(value, [...catalog, { name: 'shipped', aliases: [value.name] }])).toThrow('collides');+ expect(() => validateMindToolRecipe(value, [tool('brain.search', { query: { type: 'string' } }, ['query'], { type: 'object', properties: {}, additionalProperties: false }), catalog[1]])).toThrow('output field');+ });++ it('bounds recursive authored data before parsing and forbids prototype traversal', () => {+ const value = recipe();+ let literal = {};+ for (let i = 0; i < 25; i++) literal = { child: literal };+ value.outputs.value = { literal };+ expect(mindToolRecipeDefinitionSchema.safeParse(value).success).toBe(false);+ value.outputs.value = { step: 'search', path: ['constructor'] };+ expect(mindToolRecipeDefinitionSchema.safeParse(value).success).toBe(false);+ });++ it('resolves only own JSON fields and rejects missing open-output bindings without exposing results', () => {+ const results = { search: { entries: [{ title: 'private result' }] } };+ expect(resolveMindToolRecipeBinding({ step: 'search', path: ['entries', '0', 'title'] }, {}, results)).toBe('private result');+ expect(() => resolveMindToolRecipeBinding({ step: 'search', path: ['absent'] }, {}, results, 'outputs.notes')).toThrow('outputs.notes: output binding is missing');+ expect(() => resolveMindToolRecipeBinding({ input: 'query' }, {}, results)).toThrow('input binding is missing');+ });++ it('defaults the definition grant off and preserves it across old capability updates', () => {+ expect(createDefaultPersistentMindCapabilities().manageToolRecipes).toBe(false);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8, readPortos: true }).success).toBe(true);+ expect(mergePersistentMindCapabilities({ manageToolRecipes: true }, { schemaVersion: 3, readPortos: false })).toMatchObject({ schemaVersion: 9, manageToolRecipes: true, readPortos: false });+ });+});diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex c845b404a2..110bbf397b 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -14,12 +14,12 @@ import {portosSemanticToolGrantsSchema,} from './cosToolContracts.js';-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 8;+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 9;// Every wire version this server still accepts on input. Installs upgrade on// their own schedule, so a browser bundle (or a route caller) pinned at an// older version must keep being able to toggle the grants it already knows// about; normalization always writes the current version forward.-const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8]);+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8, 9]);export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({MAX_ENTRIES: 200,@@ -55,6 +55,12 @@ export const PERSISTENT_MIND_CALL_LIMITS = Object.freeze({// agents. Keep this catalog beside the capability schema so the API and the UI// describe the same grants instead of maintaining a second client-only list.export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([+ Object.freeze({+ id: 'mind.manage-tool-recipes', capability: 'manageToolRecipes',+ name: 'Manage saved tool recipes', kind: 'definition-management', defaultEnabled: false,+ description: 'Authorize Mind definition changes only. Saved recipes are not yet Mind-callable; model exposure is disabled in this phase.',+ guardrails: ['User library management remains available with this grant off', 'Invoking underlying reads still requires readPortos and each tool grant', 'Versioned, machine-local definitions only; no execution results in history'],+ }),Object.freeze({id: 'mind.request-thinking-preset', capability: 'chooseThinkingPreset',name: 'Request a local thinking preset', kind: 'semantic-tools', defaultEnabled: false,@@ -207,6 +213,7 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.e.optional(),createTasks: z.boolean().optional(),manageMind: z.boolean().optional(),+ manageToolRecipes: z.boolean().optional(),callUser: z.boolean().optional(),chooseThinkingPreset: z.boolean().optional(),adjustLocalContext: z.boolean().optional(),@@ -276,6 +283,7 @@ export function createDefaultPersistentMindCapabilities() {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: false,manageMind: false,+ manageToolRecipes: false,manageEidoverse: false,visitEidoversePeers: false,callUser: false,@@ -335,6 +343,7 @@ export function normalizePersistentMindCapabilities(raw) {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: source.createTasks === true,manageMind: source.manageMind === true,+ manageToolRecipes: source.manageToolRecipes === true,callUser: source.callUser === true,chooseThinkingPreset: source.chooseThinkingPreset === true,adjustLocalContext: source.adjustLocalContext === true,diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsindex daac0a6314..00e4b963e8 100644--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@ -15,6 +15,7 @@ import {describe('persistent mind capabilities', () => {it('describes every persistent-mind grant from the capability contract', () => {expect(PERSISTENT_MIND_TOOL_CATALOG).toEqual([+ expect.objectContaining({ capability: 'manageToolRecipes', defaultEnabled: false }),expect.objectContaining({ capability: 'chooseThinkingPreset', defaultEnabled: false }),expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', defaultEnabled: false }),expect.objectContaining({ id: 'portos.read', capability: 'readPortos', defaultEnabled: false }),@@ -50,10 +51,10 @@ describe('persistent mind capabilities', () => {expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 3, callUser: true }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 5 }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8 }).success).toBe(true);- expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 9 }).success).toBe(false);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 10 }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))- .toMatchObject({ schemaVersion: 8, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false });+ .toMatchObject({ schemaVersion: 9, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false });expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex a9cc8fea7c..c29dbea391 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -1,3 +1,4 @@+import mindToolRecipeRoutes from './mindToolRecipeRoutes.js';import { persistentMindMemoryProtectionSchema } from '../lib/persistentMindMemory.js';import { getPersistentMindThinkingRequestCatalog, cancelPersistentMindThinkingRequest } from '../services/persistentMindThinkingRequests.js';/** Persistent Chief-of-Staff mind conversation and lifecycle routes. */@@ -65,6 +66,7 @@ import {} from '../services/persistentMindSupervisor.js';const router = Router();+router.use('/mind/recipes', mindToolRecipeRoutes);const idempotencyId = z.string().trim().min(1).max(200);const eventId = z.string().trim().min(1).max(128);diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex bf1ac8e318..85fc2d5b3b 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -213,7 +213,7 @@ describe('persistent mind routes', () => {thinkingInterface: 'text',wakeIntervalMinutes: 30,},- capabilities: { schemaVersion: 8, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ capabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },harness: { type: 'api', recommendation: 'recommended' },imageCapability: { status: 'unknown' },autonomyMode: 'execute',@@ -307,8 +307,8 @@ describe('persistent mind routes', () => {expect.objectContaining({ name: 'eidoverse.status', granted: false, input_schema: expect.any(Object) }),expect.objectContaining({ name: 'cos.create-task', granted: true }),]),- schemaVersion: 8,- capabilities: { schemaVersion: 8, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ schemaVersion: 9,+ capabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),tools: expect.arrayContaining([expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),diff --git a/server/routes/mindToolRecipeRoutes.js b/server/routes/mindToolRecipeRoutes.jsnew file mode 100644index 0000000000..5c925f71b6--- /dev/null+++ b/server/routes/mindToolRecipeRoutes.js@@ -0,0 +1,48 @@+/** User-owned library management follows the existing Mind settings auth gate.+ * No manageToolRecipes grant is required for the human's own HTTP edits. */+import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ mindToolRecipeSaveSchema, mindToolRecipeUpdateSchema,+ mindToolRecipeRevisionSchema, mindToolRecipeRestoreSchema,+} from '../lib/mindToolRecipes.js';++const router = Router();+const recipeIdSchema = z.object({ recipeId: z.uuid() });+const service = () => import('../services/mindToolRecipes.js');+const id = (req) => validateRequest(recipeIdSchema, req.params).recipeId;++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await (await service()).listRecipes());+}));+router.post('/validate', asyncHandler(async (req, res) => {+ const { definition } = validateRequest(mindToolRecipeSaveSchema, req.body);+ const { valid, runtimeChecks } = await (await service()).validateRecipe(definition);+ res.json({ valid, runtimeChecks });+}));+router.post('/', asyncHandler(async (req, res) => {+ const { definition } = validateRequest(mindToolRecipeSaveSchema, req.body);+ res.status(201).json(await (await service()).createRecipe(definition));+}));+router.get('/:recipeId', asyncHandler(async (req, res) => {+ const recipeId = id(req);+ res.json(await (await service()).getRecipe(recipeId));+}));+router.put('/:recipeId', asyncHandler(async (req, res) => {+ const recipeId = id(req);+ const body = validateRequest(mindToolRecipeUpdateSchema, req.body);+ res.json(await (await service()).updateRecipe(recipeId, body));+}));+router.post('/:recipeId/archive', asyncHandler(async (req, res) => {+ const recipeId = id(req);+ const body = validateRequest(mindToolRecipeRevisionSchema, req.body);+ res.json(await (await service()).archiveRecipe(recipeId, body));+}));+router.post('/:recipeId/restore', asyncHandler(async (req, res) => {+ const recipeId = id(req);+ const body = validateRequest(mindToolRecipeRestoreSchema, req.body);+ res.json(await (await service()).restoreRecipe(recipeId, body));+}));+export default router;diff --git a/server/routes/mindToolRecipes.db.test.js b/server/routes/mindToolRecipes.db.test.jsnew file mode 100644index 0000000000..b0255de978--- /dev/null+++ b/server/routes/mindToolRecipes.db.test.js@@ -0,0 +1,98 @@+/** Route-to-Postgres library recovery contract. Runs only against portos_test. */+import { afterAll, describe, expect, it } from 'vitest';+import { randomUUID } from 'node:crypto';+import express from 'express';+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import recipeRoutes from './mindToolRecipeRoutes.js';++const health = await checkHealth().catch((error) => ({ connected: false, error: error.message }));+const ready = requireDbOrSkip('routes/mindToolRecipes.db.test', health.connected, health.error);+if (ready) await ensureSchema();+const ids = [];+afterAll(async () => {+ if (ready && ids.length) await query('DELETE FROM mind_tool_recipes WHERE id = ANY($1::uuid[])', [ids]);+ await close();+});+const app = express();+app.use(express.json());+app.use('/recipes', recipeRoutes);+app.use(errorMiddleware);+const get = (path = '') => request(app).get(`/recipes${path}`);+const post = (path, body) => request(app).post(`/recipes${path}`).send(body);+const put = (path, body) => request(app).put(`/recipes${path}`).send(body);+const definition = () => ({+ schemaVersion: 1, name: `recipe.test-${randomUUID()}`, purpose: 'Project check-in',+ parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'], additionalProperties: false },+ steps: [{ id: 'notes', tool: 'brain.search', arguments: { query: { input: 'query' } } }, { id: 'goals', tool: 'goals.list', arguments: {} }],+ outputs: { notes: { step: 'notes', path: ['entries'] }, goals: { step: 'goals', path: [] } },+});+const create = async () => {+ const saved = await post('', { definition: definition() });+ expect(saved.status).toBe(201);+ ids.push(saved.body.id);+ return saved.body;+};++describe.skipIf(!ready)('Mind recipe library over HTTP and PostgreSQL', () => {+ it('reloads, rejects bad/forward/stale edits, archives and restores with immutable history', async () => {+ const saved = await create();+ expect(saved).toMatchObject({ activeRevision: 1, archived: false, mindCallable: false });+ expect((await get()).body.recipes).toContainEqual(expect.objectContaining({ id: saved.id }));+ const bad = structuredClone(saved.definition);+ bad.steps[0].arguments.query = { literal: 25 };+ const rejected = await put(`/${saved.id}`, { expectedRevision: 1, definition: bad });+ expect(rejected.status).toBe(400);+ expect(rejected.body.context).toMatchObject({ field: 'steps.0.arguments.query', step: 'notes' });+ bad.steps[0].arguments.query = { step: 'goals', path: ['title'] };+ expect((await put(`/${saved.id}`, { expectedRevision: 1, definition: bad })).status).toBe(400);+ expect((await get(`/${saved.id}`)).body).toMatchObject({ recipe: { activeRevision: 1, definition: saved.definition }, versions: [{ revision: 1, author: 'user' }] });+ const edited = { ...saved.definition, purpose: 'Updated project check-in' };+ expect((await put(`/${saved.id}`, { expectedRevision: 1, definition: edited })).body.activeRevision).toBe(2);+ expect((await put(`/${saved.id}`, { expectedRevision: 1, definition: saved.definition })).status).toBe(409);+ expect((await post(`/${saved.id}/archive`, { expectedRevision: 2 })).body).toMatchObject({ activeRevision: 3, archived: true, available: false });+ expect((await post(`/${saved.id}/restore`, { expectedRevision: 2, revision: 1 })).status).toBe(409);+ expect((await post(`/${saved.id}/restore`, { expectedRevision: 3, revision: 1 })).body).toMatchObject({ activeRevision: 4, archived: false, definition: saved.definition });+ const history = (await get(`/${saved.id}`)).body.versions;+ expect(history.map(({ revision }) => revision)).toEqual([4, 3, 2, 1]);+ expect(history[3].definition).toEqual(saved.definition);+ expect(history.every((entry) => Object.keys(entry).sort().join(',') === 'archived,author,createdAt,definition,revision')).toBe(true);+ });++ it('validates without persisting and preserves future definitions without granting execution', async () => {+ const value = definition();+ expect((await post('/validate', { definition: value })).body.valid).toBe(true);+ expect((await get()).body.recipes.some((item) => item.name === value.name)).toBe(false);+ const saved = await create();+ const future = { ...saved.definition, schemaVersion: 99, futureField: { preserved: true } };+ await query('UPDATE mind_tool_recipe_versions SET definition = $1 WHERE recipe_id = $2 AND revision = 1', [future, saved.id]);+ expect((await get(`/${saved.id}`)).body.recipe).toMatchObject({ available: false, mindCallable: false, definition: future });+ expect((await put(`/${saved.id}`, { expectedRevision: 1, definition: saved.definition })).status).toBe(409);+ expect((await get(`/${saved.id}`)).body.versions[0].definition).toEqual(future);+ });++ it('revalidates a restored historical definition before appending a revision', async () => {+ const saved = await create();+ const edited = { ...saved.definition, purpose: 'Current valid definition' };+ expect((await put(`/${saved.id}`, { expectedRevision: 1, definition: edited })).status).toBe(200);+ // Simulate a historical target contract retired by an upgrade.+ const retired = structuredClone(saved.definition);+ retired.steps[0].tool = 'retired.search';+ await query('UPDATE mind_tool_recipe_versions SET definition = $1 WHERE recipe_id = $2 AND revision = 1', [retired, saved.id]);+ expect((await post(`/${saved.id}/restore`, { expectedRevision: 2, revision: 1 })).status).toBe(400);+ const detail = (await get(`/${saved.id}`)).body;+ expect(detail.recipe).toMatchObject({ activeRevision: 2, definition: edited });+ expect(detail.versions).toHaveLength(2);+ });++ it('rejects malformed requests and colliding recipe names without overwriting either record', async () => {+ expect((await post('', { definition: definition(), author: 'mind' })).status).toBe(400);+ expect((await get('/not-a-uuid')).status).toBe(400);+ const saved = await create();+ expect((await post('', { definition: saved.definition })).status).toBe(409);+ expect((await put(`/${saved.id}`, { definition: saved.definition })).status).toBe(400);+ expect((await get(`/${saved.id}`)).body.recipe.activeRevision).toBe(1);+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex acee4b5892..ba6dc44391 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -2050,3 +2050,22 @@ CREATE TABLE IF NOT EXISTS app_quality_measurements ();CREATE INDEX IF NOT EXISTS idx_app_quality_history ON app_quality_measurements (app_id, assessed_at DESC);++-- Machine-local Mind recipe library (#7194).+CREATE TABLE IF NOT EXISTS mind_tool_recipes (+ id UUID PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ active_revision INTEGER NOT NULL CHECK (active_revision > 0),+ archived BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ );+CREATE TABLE IF NOT EXISTS mind_tool_recipe_versions (+ recipe_id UUID NOT NULL REFERENCES mind_tool_recipes (id) ON DELETE CASCADE,+ revision INTEGER NOT NULL CHECK (revision > 0),+ definition JSONB NOT NULL,+ author TEXT NOT NULL CHECK (author IN ('user', 'mind')),+ archived BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (recipe_id, revision)+ );diff --git a/server/services/mindToolRecipes.js b/server/services/mindToolRecipes.jsnew file mode 100644index 0000000000..503f275c93--- /dev/null+++ b/server/services/mindToolRecipes.js@@ -0,0 +1,111 @@+/** db-primary, machine-local recipe library; deliberately no model exposure. */+import { randomUUID } from 'node:crypto';+import { query, withTransaction, ensureSchema } from '../lib/db.js';+import { ServerError } from '../lib/errorHandler.js';+import { MIND_TOOL_RECIPE_SCHEMA_VERSION, validateMindToolRecipe } from '../lib/mindToolRecipes.js';++const catalog = async () => {+ const { getCosToolCatalog } = await import('./cosToolRegistry.js');+ return getCosToolCatalog({ scope: 'all' }).tools;+};+export const validateRecipe = async (definition) => validateMindToolRecipe(definition, await catalog());+const project = (row) => ({+ id: row.id, name: row.name, activeRevision: row.active_revision,+ archived: row.archived, definition: row.definition,+ available: !row.archived && row.definition?.schemaVersion === MIND_TOOL_RECIPE_SCHEMA_VERSION,+ mindCallable: false,+ createdAt: row.created_at, updatedAt: row.updated_at,+});+const select = `SELECT r.*, v.definition FROM mind_tool_recipes r+ JOIN mind_tool_recipe_versions v ON v.recipe_id = r.id AND v.revision = r.active_revision`;+const notFound = () => new ServerError('Recipe not found', { status: 404, code: 'RECIPE_NOT_FOUND' });+const conflict = () => new ServerError('Recipe changed. Reload before saving or restoring.', { status: 409, code: 'RECIPE_REVISION_CONFLICT' });+const load = async (client, id) => {+ const { rows } = await client.query(`${select} WHERE r.id = $1`, [id]);+ if (!rows[0]) throw notFound();+ return rows[0];+};+const assertRevision = (row, expectedRevision) => {+ if (row.active_revision !== expectedRevision) throw conflict();+};+const assertEditable = (row) => {+ if (row.definition?.schemaVersion !== MIND_TOOL_RECIPE_SCHEMA_VERSION) throw new ServerError('This definition version requires a newer PortOS. It has been preserved.', { status: 409, code: 'RECIPE_VERSION_UNSUPPORTED' });+};+const assertNameFree = async (client, name, id) => {+ const { rows } = await client.query('SELECT id FROM mind_tool_recipes WHERE name = $1 AND id <> $2', [name, id]);+ if (rows.length) throw new ServerError('name: another recipe already uses this name', { status: 409, code: 'RECIPE_NAME_CONFLICT', context: { field: 'name' } });+};+const append = async (client, row, definition, archived) => {+ await assertNameFree(client, definition.name, row.id);+ const revision = row.active_revision + 1;+ const result = await client.query(`UPDATE mind_tool_recipes SET name = $1, active_revision = $2, archived = $3, updated_at = NOW()+ WHERE id = $4 AND active_revision = $5 RETURNING id`, [definition.name, revision, archived, row.id, row.active_revision]);+ if (!result.rowCount) throw conflict();+ await client.query(`INSERT INTO mind_tool_recipe_versions (recipe_id, revision, definition, author, archived)+ VALUES ($1, $2, $3, 'user', $4)`, [row.id, revision, definition, archived]);+ return project(await load(client, row.id));+};++export async function listRecipes() {+ await ensureSchema();+ const { rows } = await query(`${select} ORDER BY r.updated_at DESC, r.id`);+ return { recipes: rows.map(project) };+}++export async function getRecipe(id) {+ await ensureSchema();+ const row = await load({ query }, id);+ const { rows } = await query(`SELECT revision, definition, author, archived, created_at+ FROM mind_tool_recipe_versions WHERE recipe_id = $1 ORDER BY revision DESC`, [id]);+ return { recipe: project(row), versions: rows.map((version) => ({+ revision: version.revision, definition: version.definition, author: version.author,+ archived: version.archived, createdAt: version.created_at,+ })) };+}++export async function createRecipe(candidate) {+ const { definition } = await validateRecipe(candidate);+ await ensureSchema();+ return withTransaction(async (client) => {+ const id = randomUUID();+ await assertNameFree(client, definition.name, id);+ await client.query('INSERT INTO mind_tool_recipes (id, name, active_revision) VALUES ($1, $2, 1)', [id, definition.name]);+ await client.query(`INSERT INTO mind_tool_recipe_versions (recipe_id, revision, definition, author)+ VALUES ($1, 1, $2, 'user')`, [id, definition]);+ return project(await load(client, id));+ });+}++export async function updateRecipe(id, { definition: candidate, expectedRevision }) {+ const { definition } = await validateRecipe(candidate);+ await ensureSchema();+ return withTransaction(async (client) => {+ const row = await load(client, id);+ assertRevision(row, expectedRevision);+ assertEditable(row);+ return append(client, row, definition, row.archived);+ });+}++export async function archiveRecipe(id, { expectedRevision }) {+ await ensureSchema();+ return withTransaction(async (client) => {+ const row = await load(client, id);+ assertRevision(row, expectedRevision);+ if (row.archived) return project(row);+ return append(client, row, row.definition, true);+ });+}++export async function restoreRecipe(id, { revision, expectedRevision }) {+ await ensureSchema();+ return withTransaction(async (client) => {+ const row = await load(client, id);+ assertRevision(row, expectedRevision);+ assertEditable(row);+ const { rows } = await client.query('SELECT definition FROM mind_tool_recipe_versions WHERE recipe_id = $1 AND revision = $2', [id, revision]);+ if (!rows[0]) throw notFound();+ const { definition } = await validateRecipe(rows[0].definition);+ return append(client, row, definition, false);+ });+}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 10ebf2daf3..d6818e3eaf 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -40,6 +40,7 @@ export const DB_TEST_INCLUDE = ['services/creativeDirector/projectsDB.test.js','services/musicVideo/projectsDB.test.js','routes/catalog.test.js',+ 'routes/mindToolRecipes.db.test.js','scripts/run-db-migrations.test.js',];