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: let the Mind save and reuse governed read recipes (#7195)
[._.]/ Adam Eivy6707677afb59
diff --git a/client/src/components/cos/PersistentMindRecipeLibrary.jsx b/client/src/components/cos/PersistentMindRecipeLibrary.jsxindex f764b5eb56..5b1f290031 100644--- a/client/src/components/cos/PersistentMindRecipeLibrary.jsx+++ b/client/src/components/cos/PersistentMindRecipeLibrary.jsx@@ -179,7 +179,7 @@ export default function PersistentMindRecipeLibrary() {<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>+ <p className="text-sm text-port-text-muted">Manage reusable read definitions and their history with Mind grants off. The Mind can reuse recipes when recipe management and every underlying read grant are enabled. Nothing executes when you save or validate.</p>{error && <Banner tone="error" title="Recipe library unavailable">{error} <button type="button" className={buttonClass} onClick={load}>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">diff --git a/server/lib/mindToolRecipes.js b/server/lib/mindToolRecipes.jsindex 75251b1839..fb2fcb363a 100644--- a/server/lib/mindToolRecipes.js+++ b/server/lib/mindToolRecipes.js@@ -141,7 +141,7 @@ export function validateMindToolRecipe(candidate, catalog) {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);+ if (!tool || tool.policy.sideEffect !== 'read' || !tool.policy.scopes.includes('mind') || (tool.name.startsWith('recipe.') || tool.name.startsWith('mind.recipes.'))) 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)) {diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex 110bbf397b..d581139968 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -58,7 +58,7 @@ 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.',+ description: 'Authorize Mind recipe definition changes and reuse of saved reads, subject to every underlying read grant and the shared turn budget.',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({diff --git a/server/routes/mindToolRecipes.db.test.js b/server/routes/mindToolRecipes.db.test.jsindex b0255de978..cb029d3d2c 100644--- a/server/routes/mindToolRecipes.db.test.js+++ b/server/routes/mindToolRecipes.db.test.js@@ -7,6 +7,7 @@ import { requireDbOrSkip } from '../lib/dbTestGate.js';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';import recipeRoutes from './mindToolRecipeRoutes.js';+import { createRecipe, updateRecipe, archiveRecipe, restoreRecipe, getRecipe, getRecipeByName, listRecipes } from '../services/mindToolRecipes.js';const health = await checkHealth().catch((error) => ({ connected: false, error: error.message }));const ready = requireDbOrSkip('routes/mindToolRecipes.db.test', health.connected, health.error);@@ -61,6 +62,18 @@ describe.skipIf(!ready)('Mind recipe library over HTTP and PostgreSQL', () => {expect(history.every((entry) => Object.keys(entry).sort().join(',') === 'archived,author,createdAt,definition,revision')).toBe(true);});+ it('persists Mind authorship across definition changes and pages only definition history', async () => {+ const saved = await createRecipe(definition(), { author: 'mind' }); ids.push(saved.id);+ expect(await getRecipeByName(saved.name)).toMatchObject({ id: saved.id, activeRevision: 1 });+ await updateRecipe(saved.id, { definition: { ...saved.definition, purpose: 'Revised check-in' }, expectedRevision: 1 }, { author: 'mind' });+ await archiveRecipe(saved.id, { expectedRevision: 2 }, { author: 'mind' });+ await restoreRecipe(saved.id, { expectedRevision: 3, revision: 1 }, { author: 'mind' });+ const page = await getRecipe(saved.id, { limit: 2, offset: 1 });+ expect(page.versions.map(({ revision, author }) => ({ revision, author }))).toEqual([{ revision: 3, author: 'mind' }, { revision: 2, author: 'mind' }]);+ expect((await listRecipes({ limit: 1, offset: 0 })).recipes).toHaveLength(1);+ expect(page.recipe.definition).toEqual(saved.definition);+ });+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);diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 391ebd606d..bd58744dfb 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -31,6 +31,8 @@ import { dispatchTool, getToolSpecs, getToolSpecsForIntent } from './voice/toolsimport { executePersistentMindTaskRequests } from './persistentMindTaskCapability.js';import { cleanupPersistentMind } from './persistentMindMaintenance.js';+import { recipeManagementTools, resolveMindRecipeInvocation, readMindRecipeTools, currentMindAuthority, executeRecipeManagement, executeRecipe } from './mindToolRecipeRuntime.js';+const MAX_CALL_RESULTS = 500;const MAX_IDEMPOTENCY_TOMBSTONES = 10_000;const IDEMPOTENCY_RETENTION_MS = 24 * 60 * 60 * 1_000;@@ -337,13 +339,14 @@ const localContextTools = (() => {},];})();-const toolCatalog = (intent) => [...thinkingTools, ...localContextTools, taskTool, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];+const toolCatalog = (intent) => [...recipeManagementTools, ...thinkingTools, ...localContextTools, taskTool, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];const toolCalls = new Map();const toolCallFingerprints = new Map();const normalizeToolCapabilities = (raw) => ({...normalizePortosSemanticToolGrants(raw),createTasks: raw?.createTasks === true,+ manageToolRecipes: raw?.manageToolRecipes === true,manageMind: raw?.manageMind === true,chooseThinkingPreset: raw?.chooseThinkingPreset === true,adjustLocalContext: raw?.adjustLocalContext === true,@@ -365,9 +368,9 @@ const publicTool = (tool, { scope, capabilities }) => ({: tool.policy.requiredCapabilities.every((capability) => capabilities[capability] === true),});-export const getCosToolCatalog = ({ scope = 'all', intent, capabilities } = {}) => {+export const getCosToolCatalog = ({ scope = 'all', intent, capabilities, recipes = [] } = {}) => {const grants = normalizeToolCapabilities(capabilities);- const tools = toolCatalog(intent)+ const tools = [...toolCatalog(intent), ...(scope === 'mind' ? recipes : [])].filter((tool) => scope === 'all' || tool.policy.scopes.includes(scope)).map((tool) => publicTool(tool, { scope, capabilities: grants }));return {@@ -409,8 +412,8 @@ export const formatCosToolCatalog = (catalog, format = 'portos') => {return { type: `${format}_tool_catalog`, schemaVersion: catalog.schemaVersion, scope: catalog.scope, tools };};-export const buildPersistentMindToolPrompt = (capabilities) => {- const catalog = getCosToolCatalog({ scope: 'mind', capabilities });+export const buildPersistentMindToolPrompt = (capabilities, recipes = []) => {+ const catalog = getCosToolCatalog({ scope: 'mind', capabilities, recipes });const tools = catalog.tools.filter((tool) => tool.granted).map((tool) => ({name: tool.name,description: tool.description,@@ -429,6 +432,8 @@ ${JSON.stringify(tools)}Calls without requestId are coalesced by canonical tool name and arguments within this turn. Supply distinct requestId values only when two intentionally identical actions must both run.`;};+export const readPersistentMindRecipeCatalog = (capabilities) => readMindRecipeTools(capabilities, getCosToolCatalog({ scope: 'mind' }).tools);+const resolveTool = (name) => toolCatalog().find((tool) =>tool.name === name || tool.providerName === name || tool.aliases.includes(name));@@ -466,7 +471,9 @@ const validateArguments = (tool, args) => {return parsed.data;};-const executeAdapter = async (tool, args, context) => {+const executeAdapter = async (tool, args, context, authority) => {+ if (tool.adapter.kind === 'recipe-management') return executeRecipeManagement(tool, args, context);+ if (tool.adapter.kind === 'recipe') return executeRecipe(tool, args, context, authority);if (tool.adapter.kind.startsWith('thinking-')) {const { getPersistentMindThinkingRequestCatalog, requestPersistentMindThinkingPreset } = await import('./persistentMindThinkingRequests.js');return tool.adapter.kind === 'thinking-catalog'@@ -604,11 +611,20 @@ const normalizeAdapterResult = ({ parsedCall, tool, result }) => {export const executeCosToolCall = async ({ call, authority, context = {} }) => {const parsedCall = cosToolCallSchema.parse(call);- const tool = resolveTool(parsedCall.name);+ let tool = resolveTool(parsedCall.name);+ if (parsedCall.name.startsWith('recipe.')) {+ if (authority?.scope !== 'mind') throw new ServerError('Recipes require mind scope', { status: 403, code: 'TOOL_SCOPE_DENIED' });+ authority = await currentMindAuthority(authority);+ if (authority.capabilities.manageToolRecipes !== true) throw new ServerError('Recipe access is not granted', { status: 403, code: 'TOOL_CAPABILITY_DENIED' });+ const { getRecipeByName } = await import('./mindToolRecipes.js');+ tool = await resolveMindRecipeInvocation(await getRecipeByName(parsedCall.name), getCosToolCatalog({ scope: 'mind' }).tools);+ } else if (tool?.adapter.kind === 'recipe-management' && authority?.scope === 'mind') {+ authority = await currentMindAuthority(authority);+ }if (!tool) throw new ServerError(`Unknown tool '${parsedCall.name}'`, { status: 404, code: 'TOOL_NOT_FOUND' });validateAuthority(tool, authority);const args = validateArguments(tool, parsedCall.arguments);- const fingerprint = sha256Text(canonicalStringify({ name: tool.name, arguments: args, scope: authority?.scope || 'ui' }));+ const fingerprint = sha256Text(canonicalStringify({ name: tool.name, arguments: args, scope: authority?.scope || 'ui', ...(tool.adapter.kind === 'recipe' ? { recipeId: tool.adapter.recipe.id, revision: tool.adapter.recipe.activeRevision } : {}) }));pruneToolCallFingerprints();const existing = toolCalls.get(parsedCall.requestId);if (existing) {@@ -627,7 +643,7 @@ export const executeCosToolCall = async ({ call, authority, context = {} }) => {}const promise = Promise.resolve()- .then(() => executeAdapter(tool, args, { ...context, requestId: parsedCall.requestId }))+ .then(() => executeAdapter(tool, args, { ...context, requestId: parsedCall.requestId }, authority)).then((result) => normalizeAdapterResult({ parsedCall, tool, result }),(error) => ({diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex 25cf7de221..5880742afb 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -110,6 +110,7 @@ describe('cosToolRegistry', () => {it('exports a compact canonical catalog and provider translations', () => {const catalog = getCosToolCatalog({ scope: 'mind', capabilities: { readPortos: true } });expect(catalog.tools.map((tool) => tool.name)).toEqual([+ 'mind.recipes.create', 'mind.recipes.list', 'mind.recipes.read', 'mind.recipes.update', 'mind.recipes.archive', 'mind.recipes.restore','mind.thinking-presets','mind.request-thinking-preset','mind.local-context',diff --git a/server/services/mindToolRecipeRuntime.js b/server/services/mindToolRecipeRuntime.jsnew file mode 100644index 0000000000..7bdfeb0a17--- /dev/null+++ b/server/services/mindToolRecipeRuntime.js@@ -0,0 +1,121 @@+/** Mind-only recipe catalog and bounded orchestration over semantic reads. */+import { z } from 'zod';+import { COS_TOOL_SCHEMA_VERSION, COS_TOOL_CALL_LIMITS, providerToolName } from '../lib/cosToolContracts.js';+import { validateMindToolRecipe, resolveMindToolRecipeBinding } from '../lib/mindToolRecipes.js';+import { zodToOpenApiSchema } from '../lib/apiContractSchemas.js';+import { ServerError } from '../lib/errorHandler.js';+import { sha256Text } from '../lib/fileUtils.js';++const page = { limit: z.number().int().min(1).max(20).optional().default(10), offset: z.number().int().min(0).max(100000).optional().default(0) };+const id = z.string().uuid();+const revision = z.number().int().positive();+const managementSchemas = {+ create: z.object({ definition: z.json() }).strict(),+ list: z.object(page).strict(),+ read: z.object({ id, ...page }).strict(),+ update: z.object({ id, definition: z.json(), expectedRevision: revision }).strict(),+ archive: z.object({ id, expectedRevision: revision }).strict(),+ restore: z.object({ id, revision, expectedRevision: revision }).strict(),+};+const descriptor = (name, description, input_schema, adapter, requiredCapabilities, sideEffect = 'read') => ({+ type: 'portos_tool', name, version: COS_TOOL_SCHEMA_VERSION, providerName: providerToolName(name), aliases: [],+ description, input_schema, output_schema: { type: 'object', additionalProperties: true },+ policy: { scopes: ['mind'], requiredCapabilities, sideEffect, idempotent: true, async: false, confirmation: 'capability-grant' },+ adapter,+});+export const recipeManagementTools = Object.entries(managementSchemas).map(([operation, schema]) => descriptor(+ `mind.recipes.${operation}`, `${operation} saved read-tool recipe definitions. Read/list return paged definitions/history only. Create/update require schemaVersion:1, recipe.* name, purpose, closed parameters, 1-5 steps with {id,tool,arguments}, and outputs. Bindings are {literal:value}, {input:parameter}, or {step:id,path:[field]}.`,+ zodToOpenApiSchema(schema), { kind: 'recipe-management', operation }, ['manageToolRecipes'], ['list', 'read'].includes(operation) ? 'read' : 'write',+));++export const recipeTool = (recipe, primitives) => {+ if (recipe.archived) throw new ServerError('Recipe is archived. Restore a revision before calling it.', { code: 'RECIPE_ARCHIVED', status: 409 });+ const { definition } = validateMindToolRecipe(recipe.definition, primitives);+ const required = [...new Set(['manageToolRecipes', ...definition.steps.flatMap((step) => primitives.find((tool) => tool.name === step.tool).policy.requiredCapabilities)])];+ return descriptor(definition.name, definition.purpose.slice(0, 280), definition.parameters,+ { kind: 'recipe', recipe: { id: recipe.id, activeRevision: recipe.activeRevision, definition } }, required);+};++// Even an incompatible revision gets a replay fingerprint and structured failure.+// A repair must never silently reinterpret the same invocation requestId.+export const resolveMindRecipeInvocation = (recipe, primitives) => Promise.resolve()+ .then(() => recipeTool(recipe, primitives))+ .catch((error) => descriptor(recipe.name, 'Unavailable saved recipe', { type: 'object', additionalProperties: true },+ { kind: 'recipe', recipe, validationError: { message: error.message, step: error.context?.step || 'definition' } }, ['manageToolRecipes']));++export async function readMindRecipeTools(capabilities, primitives) {+ if (capabilities?.manageToolRecipes !== true) return [];+ const { listRecipes } = await import('./mindToolRecipes.js');+ const { recipes } = await listRecipes({ limit: 20 });+ const checked = await Promise.allSettled(recipes.map(async (recipe) => recipeTool(recipe, primitives)));+ let chars = 0;+ return checked.flatMap((entry) => {+ if (entry.status !== 'fulfilled' || !entry.value.policy.requiredCapabilities.every((key) => capabilities[key] === true)) return [];+ const size = JSON.stringify(entry.value.input_schema).length + entry.value.description.length;+ if (chars + size > 24000) return [];+ chars += size;+ return [entry.value];+ });+}++export async function currentMindAuthority(authority) {+ const { loadState } = await import('./cosState.js');+ const root = await loadState();+ return { ...authority, capabilities: root.config?.persistentMindCapabilities || {} };+}++export async function executeRecipeManagement(tool, args, context) {+ const recipes = await import('./mindToolRecipes.js');+ const { operation } = tool.adapter;+ const parsed = managementSchemas[operation].parse(args);+ if (operation === 'list') return recipes.listRecipes(parsed);+ if (operation === 'read') return recipes.getRecipe(parsed.id, parsed);+ const result = operation === 'create' ? await recipes.createRecipe(parsed.definition, { author: 'mind' })+ : await recipes[`${operation}Recipe`](parsed.id, parsed, { author: 'mind' });+ await context.recordCapabilityEvent?.({ kind: 'result', id: `recipe-definition:${context.requestId}`, data: {+ displayText: `Recipe definition ${operation} completed`, recipeId: result.id, revision: result.activeRevision, operation,+ } });+ return result;+}++export async function executeRecipe(tool, inputs, context, authority) {+ const { executeCosToolCall, getCosToolCatalog } = await import('./cosToolRegistry.js');+ const { id: recipeId, activeRevision: revision, definition } = tool.adapter.recipe;+ const results = {};+ const outcomes = [];+ let failingStep = tool.adapter.validationError?.step || null;+ const run = async () => {+ if (tool.adapter.validationError) throw new Error(tool.adapter.validationError.message);+ for (const step of definition.steps) {+ failingStep = step.id;+ if (context.signal?.aborted) throw new Error('Recipe interrupted by turn cancellation');+ const liveAuthority = await currentMindAuthority(authority);+ if (context.signal?.aborted) throw new Error('Recipe interrupted by turn cancellation');+ if (!liveAuthority.capabilities.manageToolRecipes) throw new Error('Recipe management grant was revoked; remaining steps were stopped');+ validateMindToolRecipe(definition, getCosToolCatalog({ scope: 'mind' }).tools);+ if (!context.toolBudget || context.toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn) throw new Error('Shared turn tool-call budget exhausted; remaining steps were stopped');+ context.toolBudget.used += 1;+ const args = Object.fromEntries(Object.entries(step.arguments).map(([key, binding]) => [key, resolveMindToolRecipeBinding(binding, inputs, results, `steps.${step.id}.${key}`)]));+ const requestId = `recipe-${sha256Text(`${context.requestId}:${recipeId}:${revision}:${step.id}`).slice(0, 48)}`;+ const outcome = await executeCosToolCall({ call: { requestId, name: step.tool, arguments: args }, authority: liveAuthority, context });+ outcomes.push({ step: step.id, state: outcome.state });+ await context.recordCapabilityEvent?.({ kind: 'result', id: `recipe-step:${requestId}`, data: {+ displayText: `Recipe step ${step.id} ${outcome.state}`, recipeId, revision, step: step.id, success: outcome.state === 'completed',+ } });+ if (outcome.state !== 'completed') throw new Error(outcome.error || 'Read tool failed');+ results[step.id] = outcome.result;+ }+ failingStep = 'outputs';+ const outputs = Object.fromEntries(Object.entries(definition.outputs).map(([key, binding]) => [key, resolveMindToolRecipeBinding(binding, inputs, results, `outputs.${key}`)]));+ return { ok: true, state: 'completed', recipeId, revision, outcomes, outputs };+ };+ return run().catch(async (error) => {+ const state = context.signal?.aborted ? 'aborted' : outcomes.some((outcome) => outcome.state === 'completed') ? 'partial' : 'failed';+ await context.recordCapabilityEvent?.({ kind: 'result', id: `recipe-failure:${context.requestId}`, data: {+ displayText: `Recipe ${state} at ${failingStep}`, recipeId, revision, step: failingStep, state, success: false,+ } });+ return { ok: false, state, recipeId, revision, failingStep, outcomes, error: String(error.message).slice(0, 500),+ guidance: 'Read the current definition and grants; repair or restore if needed. Use a new requestId only for an intentional retry.',+ };+ });+}diff --git a/server/services/mindToolRecipeRuntime.test.js b/server/services/mindToolRecipeRuntime.test.jsnew file mode 100644index 0000000000..e34596130d--- /dev/null+++ b/server/services/mindToolRecipeRuntime.test.js@@ -0,0 +1,141 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { randomUUID } from 'node:crypto';+const mock = vi.hoisted(() => ({ capabilities: {}, recipes: [], dispatch: vi.fn(), runPrompt: vi.fn(), mutations: [] }));+vi.mock('./cosState.js', () => ({ loadState: async () => ({ config: { persistentMindCapabilities: mock.capabilities } }) }));+vi.mock('./voice/tools.js', () => ({+ getToolSpecs: () => [{ function: { name: 'brain_search', description: 'Search records.', parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } } }],+ getToolSpecsForIntent: () => ({ specs: [] }),+ dispatchTool: (...args) => mock.dispatch(...args),+}));+vi.mock('./persistentMindMaintenance.js', () => ({ cleanupPersistentMind: vi.fn() }));+vi.mock('./persistentMindTaskCapability.js', () => ({+ executePersistentMindTaskRequests: vi.fn(async () => []), buildPersistentMindTaskCapabilityPrompt: () => '',+ readPersistentMindTaskCatalog: vi.fn(), readPersistentMindTaskInventory: vi.fn(),+}));+vi.mock('./persistentMindContext.js', () => ({+ createPersistentMindMemoryFromCandidate: vi.fn(), readPersistentMindMemories: vi.fn(async () => []), readPersistentMindName: vi.fn(async () => null),+}));+vi.mock('./persistentMindVisibility.js', () => ({ readPersistentMindVisibility: vi.fn(async () => ({})), buildPersistentMindVisibilityPrompt: () => '' }));+vi.mock('./persistentMindUserActions.js', () => ({ readPersistentMindUserActionsPrompt: vi.fn(async () => '') }));+vi.mock('./persistentMindCallCapability.js', () => ({ buildPersistentMindCallCapabilityPrompt: () => '', executePersistentMindCallRequest: vi.fn(async () => null) }));+vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: (...args) => mock.runPrompt(...args), assertVisionRunUsedImages: (_, provider) => provider }));+vi.mock('./runner.js', () => ({ stopRun: vi.fn() }));+vi.mock('./mindToolRecipes.js', async () => {+ const { validateMindToolRecipe } = await import('../lib/mindToolRecipes.js');+ const validate = async (candidate) => validateMindToolRecipe(candidate, (await import('./cosToolRegistry.js')).getCosToolCatalog().tools).definition;+ return {+ listRecipes: async () => ({ recipes: structuredClone(mock.recipes) }),+ getRecipeByName: async (name) => structuredClone(mock.recipes.find((recipe) => recipe.name === name)),+ getRecipe: async (id, options) => ({ recipe: mock.recipes.find((recipe) => recipe.id === id), versions: mock.mutations.slice(options.offset, options.offset + options.limit) }),+ createRecipe: async (candidate, options) => {+ const definition = await validate(candidate);+ const recipe = { id: randomUUID(), name: definition.name, definition, activeRevision: 1, archived: false };+ mock.recipes.push(recipe); mock.mutations.push({ ...structuredClone(recipe), author: options.author }); return recipe;+ },+ updateRecipe: async (id, args) => {+ const definition = await validate(args.definition);+ const recipe = mock.recipes.find((row) => row.id === id);+ Object.assign(recipe, { definition, activeRevision: recipe.activeRevision + 1 }); return recipe;+ },+ restoreRecipe: async (id) => {+ const recipe = mock.recipes.find((row) => row.id === id);+ Object.assign(recipe, { definition: structuredClone(mock.mutations[0].definition), activeRevision: recipe.activeRevision + 1 }); return recipe;+ },+ };+});+import { executeCosToolCall, readPersistentMindRecipeCatalog, getCosToolCatalog, __testing } from './cosToolRegistry.js';+import { createPersistentMindTurnAdapter } from './persistentMindAdapter.js';+const definition = (steps = 2) => ({+ schemaVersion: 1, name: 'recipe.project-check', purpose: 'Read a project check-in',+ parameters: { type: 'object', properties: { project: { type: 'string' } }, required: ['project'], additionalProperties: false },+ steps: Array.from({ length: steps }, (_, index) => ({ id: `read${index}`, tool: 'brain.search', arguments: { query: { input: 'project' } } })),+ outputs: { summary: { step: `read${steps - 1}`, path: ['summary'] } },+});+const authority = () => ({ scope: 'mind', capabilities: mock.capabilities });+const call = (name, args = {}, context = {}, requestId = randomUUID()) => executeCosToolCall({ call: { name, arguments: args, requestId }, authority: authority(), context });+const save = () => call('mind.recipes.create', { definition: definition() });+beforeEach(() => {+ vi.clearAllMocks(); mock.capabilities = { manageToolRecipes: true, readPortos: true }; mock.recipes = []; mock.mutations = [];+ __testing.toolCalls.clear(); __testing.toolCallFingerprints.clear(); mock.dispatch.mockResolvedValue({ summary: 'Synthetic private result' });+});+it('creates, discovers and runs a two-read recipe on the next continuation, then reuses it on a later wake', async () => {+ mock.runPrompt.mockResolvedValueOnce({ text: JSON.stringify({ toolCalls: [{ name: 'mind.recipes.create', arguments: { definition: definition() } }] }) })+ .mockResolvedValueOnce({ text: JSON.stringify({ toolCalls: [{ name: 'recipe.project-check', arguments: { project: 'Example' } }] }) })+ .mockResolvedValue({ text: JSON.stringify({ message: 'Check complete.' }) });+ const events = [];+ const adapter = createPersistentMindTurnAdapter();+ const options = { provider: { id: 'fixture', type: 'api' }, model: 'fixture-model', turnId: 'wake1', wake: { kind: 'self' }, context: { text: '' }, recordCapabilityEvent: (event) => events.push(event) };+ await adapter.run(options);+ expect(mock.dispatch).toHaveBeenCalledTimes(2);+ expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('"name":"recipe.project-check"');+ expect(mock.runPrompt.mock.calls[2][0].prompt).toContain('Synthetic private result');+ expect(mock.runPrompt.mock.calls.every(([args]) => args.model === 'fixture-model')).toBe(true);+ expect(JSON.stringify(events)).not.toContain('Synthetic private result');+ expect(events.filter((event) => event.id.startsWith('recipe-step:'))).toHaveLength(2);+ expect(mock.mutations[0].author).toBe('mind');+ mock.runPrompt.mockResolvedValueOnce({ text: JSON.stringify({ toolCalls: [{ name: 'recipe.project-check', arguments: { project: 'Example' } }] }) });+ await adapter.run({ ...options, turnId: 'wake2' });+ expect(mock.dispatch).toHaveBeenCalledTimes(4);+});+it('cannot multiply the adapter turn budget through a five-step wrapper or later calls', async () => {+ await call('mind.recipes.create', { definition: definition(5) });+ mock.runPrompt.mockResolvedValueOnce({ text: JSON.stringify({ toolCalls: [+ { name: 'recipe.project-check', arguments: { project: 'Example' } },+ { name: 'brain.search', arguments: { query: 'Must not execute' } },+ ] }) }).mockResolvedValue({ text: JSON.stringify({ message: 'Partial check.' }) });+ await createPersistentMindTurnAdapter().run({ provider: { id: 'fixture', type: 'api' }, model: 'fixture-model', turnId: 'budget-wake', wake: { kind: 'self' }, context: { text: '' } });+ expect(mock.dispatch).toHaveBeenCalledTimes(4);+ expect(mock.dispatch.mock.calls.every(([, args]) => args.query === 'Example')).toBe(true);+ expect(mock.runPrompt).toHaveBeenCalledTimes(2);+ expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('budget is exhausted');+ expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('"state":"partial"');+});+it('stops after revocation, removes discovery, and keeps already completed reads marked partial', async () => {+ await save();+ mock.dispatch.mockImplementationOnce(async () => { mock.capabilities.readPortos = false; return { summary: 'Private' }; });+ const result = await call('recipe.project-check', { project: 'Example' }, { toolBudget: { used: 1 } });+ expect(result).toMatchObject({ state: 'failed', result: { state: 'partial', revision: 1, failingStep: 'read1' } });+ expect(mock.dispatch).toHaveBeenCalledTimes(1);+ expect(await readPersistentMindRecipeCatalog(mock.capabilities)).toEqual([]);+});+it('charges children to the shared turn budget and reports cancellation and missing fields', async () => {+ await call('mind.recipes.create', { definition: definition(5) });+ const budget = { used: 1 };+ expect(await call('recipe.project-check', { project: 'Example' }, { toolBudget: budget })).toMatchObject({ result: { state: 'partial', failingStep: 'read4' } });+ expect(budget.used).toBe(5); expect(mock.dispatch).toHaveBeenCalledTimes(4);+ const controller = new AbortController(); controller.abort();+ expect(await call('recipe.project-check', { project: 'Example' }, { signal: controller.signal, toolBudget: { used: 1 } })).toMatchObject({ result: { state: 'aborted' } });+ mock.recipes[0].definition = definition(); mock.dispatch.mockResolvedValue({});+ expect(await call('recipe.project-check', { project: 'Example' }, { toolBudget: { used: 1 } })).toMatchObject({ result: { state: 'partial', failingStep: 'outputs', error: expect.stringContaining('missing') } });+});+it('retains the valid definition on invalid edits and binds invocation replay to the pinned revision', async () => {+ const saved = await save(); const id = saved.result.id;+ const invalid = definition(); invalid.steps[0].tool = 'brain.capture';+ expect(await call('mind.recipes.update', { id, definition: invalid, expectedRevision: 1 })).toMatchObject({ state: 'failed' });+ const context = { toolBudget: { used: 1 } }; const invocation = randomUUID();+ expect(await call('recipe.project-check', { project: 'Example' }, context, invocation)).toMatchObject({ state: 'completed', result: { revision: 1 } });+ expect(await call('recipe.project-check', { project: 'Example' }, context, invocation)).toMatchObject({ duplicate: true });+ expect(await call('mind.recipes.restore', { id, revision: 1, expectedRevision: 1 })).toMatchObject({ result: { activeRevision: 2 } });+ await expect(call('recipe.project-check', { project: 'Example' }, context, invocation)).rejects.toMatchObject({ code: 'TOOL_IDEMPOTENCY_CONFLICT' });+ expect(mock.dispatch).toHaveBeenCalledTimes(2);+});+it('denies management without an explicit live grant or outside mind scope and pages history', async () => {+ const saved = await save();+ expect(await call('mind.recipes.read', { id: saved.result.id, limit: 1, offset: 1 })).toMatchObject({ result: { versions: [] } });+ for (const scope of ['ui', 'agent', 'voice']) await expect(executeCosToolCall({ call: { name: 'mind.recipes.list', requestId: randomUUID() }, authority: { scope, authenticated: true, capabilities: mock.capabilities } })).rejects.toMatchObject({ code: 'TOOL_SCOPE_DENIED' });+ mock.capabilities.manageToolRecipes = false;+ await expect(call('mind.recipes.list')).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });+ expect(getCosToolCatalog({ scope: 'mind', capabilities: mock.capabilities }).tools.filter((tool) => tool.name.startsWith('mind.recipes.')).every((tool) => !tool.granted)).toBe(true);+});++it('returns structured incompatible-definition failures and requires a new invocation after repair', async () => {+ await save();+ mock.recipes[0].definition.steps[0].tool = 'retired.search';+ const invocation = randomUUID();+ const failed = await call('recipe.project-check', { project: 'Example' }, { toolBudget: { used: 1 } }, invocation);+ expect(failed).toMatchObject({ state: 'failed', result: { recipeId: mock.recipes[0].id, revision: 1, failingStep: 'read0', guidance: expect.stringContaining('repair') } });+ expect(await readPersistentMindRecipeCatalog(mock.capabilities)).toEqual([]);+ mock.recipes[0].definition = definition(); mock.recipes[0].activeRevision += 1;+ await expect(call('recipe.project-check', { project: 'Example' }, { toolBudget: { used: 1 } }, invocation)).rejects.toMatchObject({ code: 'TOOL_IDEMPOTENCY_CONFLICT' });+ expect(mock.dispatch).not.toHaveBeenCalled();+});diff --git a/server/services/mindToolRecipes.js b/server/services/mindToolRecipes.jsindex 503f275c93..239a9cf4ee 100644--- a/server/services/mindToolRecipes.js+++ b/server/services/mindToolRecipes.js@@ -1,4 +1,4 @@-/** db-primary, machine-local recipe library; deliberately no model exposure. */+/** db-primary, machine-local recipe library; definitions and revisions, never private tool results. */import { randomUUID } from 'node:crypto';import { query, withTransaction, ensureSchema } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';@@ -35,35 +35,35 @@ 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) => {+const append = async (client, row, definition, archived, author = 'user') => {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]);+ VALUES ($1, $2, $3, $4, $5)`, [row.id, revision, definition, author, archived]);return project(await load(client, row.id));};-export async function listRecipes() {+export async function listRecipes({ limit, offset = 0 } = {}) {await ensureSchema();- const { rows } = await query(`${select} ORDER BY r.updated_at DESC, r.id`);+ const { rows } = await query(`${select} ORDER BY r.updated_at DESC, r.id${limit === undefined ? '' : ' LIMIT $1 OFFSET $2'}`, limit === undefined ? [] : [limit, offset]);return { recipes: rows.map(project) };}-export async function getRecipe(id) {+export async function getRecipe(id, { limit, offset = 0 } = {}) {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]);+ FROM mind_tool_recipe_versions WHERE recipe_id = $1 ORDER BY revision DESC${limit === undefined ? '' : ' LIMIT $2 OFFSET $3'}`, limit === undefined ? [id] : [id, limit, offset]);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) {+export async function createRecipe(candidate, { author = 'user' } = {}) {const { definition } = await validateRecipe(candidate);await ensureSchema();return withTransaction(async (client) => {@@ -71,33 +71,33 @@ export async function createRecipe(candidate) {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]);+ VALUES ($1, 1, $2, $3)`, [id, definition, author]);return project(await load(client, id));});}-export async function updateRecipe(id, { definition: candidate, expectedRevision }) {+export async function updateRecipe(id, { definition: candidate, expectedRevision }, { author = 'user' } = {}) {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);+ return append(client, row, definition, row.archived, author);});}-export async function archiveRecipe(id, { expectedRevision }) {+export async function archiveRecipe(id, { expectedRevision }, { author = 'user' } = {}) {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);+ return append(client, row, row.definition, true, author);});}-export async function restoreRecipe(id, { revision, expectedRevision }) {+export async function restoreRecipe(id, { revision, expectedRevision }, { author = 'user' } = {}) {await ensureSchema();return withTransaction(async (client) => {const row = await load(client, id);@@ -106,6 +106,13 @@ export async function restoreRecipe(id, { revision, expectedRevision }) {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);+ return append(client, row, definition, false, author);});}++export async function getRecipeByName(name) {+ await ensureSchema();+ const { rows } = await query(`${select} WHERE r.name = $1`, [name]);+ if (!rows[0]) throw notFound();+ return project(rows[0]);+}diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex 3e7f2cae7f..d9b14826cb 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -49,6 +49,7 @@ import {import { readPersistentMindUserActionsPrompt } from './persistentMindUserActions.js';import {buildPersistentMindToolPrompt,+ readPersistentMindRecipeCatalog,executeCosToolCall,isCosTaskToolName,} from './cosToolRegistry.js';@@ -104,7 +105,7 @@ const failedToolResult = (message) => ({error: String(message || 'Tool execution failed').slice(0, 500),});-const executeMindToolCalls = async ({ calls, turnId, wake, signal, capabilities, recordCapabilityEvent, taskBudget }) => {+const executeMindToolCalls = async ({ calls, turnId, wake, signal, capabilities, recordCapabilityEvent, taskBudget, toolBudget }) => {const results = [];for (const candidate of calls) {if (signal?.aborted) throw new Error(String(signal.reason || 'Persistent mind turn interrupted'));@@ -117,12 +118,16 @@ const executeMindToolCalls = async ({ calls, turnId, wake, signal, capabilities,const isTaskCall = isCosTaskToolName(candidate.name);const taskLimitReached = isTaskCall && taskBudget.used >= PERSISTENT_MIND_TASK_LIMITS.maxPerTurn;if (isTaskCall && !taskLimitReached) taskBudget.used += 1;- const result = taskLimitReached+ const toolLimitReached = toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn;+ if (!toolLimitReached) toolBudget.used += 1;+ const result = toolLimitReached+ ? failedToolResult(`The PortOS tool-call limit of ${COS_TOOL_CALL_LIMITS.maxCallsPerTurn} was reached`)+ : taskLimitReached? failedToolResult(`Persistent Mind task request limit of ${PERSISTENT_MIND_TASK_LIMITS.maxPerTurn} was reached for this turn`): await executeCosToolCall({call: { ...candidate, requestId },authority: { scope: 'mind', capabilities },- context: { turnId, wake, signal, recordCapabilityEvent },+ context: { turnId, wake, signal, recordCapabilityEvent, toolBudget },}).catch((error) => failedToolResult(error?.message));await recordCapabilityEvent?.({kind: 'result',@@ -387,14 +392,14 @@ export function createPersistentMindTurnAdapter() {// already redacted, no grant required. Deeper lookbacks use the// readPortos-gated user-actions.query tool.const userActionsPrompt = await readPersistentMindUserActionsPrompt();- const toolCapabilityPrompt = buildPersistentMindToolPrompt(taskAccess);+ const toolCapabilityPrompt = buildPersistentMindToolPrompt(taskAccess, await readPersistentMindRecipeCatalog(taskAccess));const callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: taskAccess.callUser });const screenshots = (Array.isArray(wake?.message?.images) ? wake.message.images : []).map((image) => {const path = resolveScreenshot(image?.filename);if (!path) throw new Error('A Persistent Mind image attachment no longer resolves under the screenshots directory');return path;});- const basePrompt = buildPersistentMindTurnPrompt({+ let basePrompt = buildPersistentMindTurnPrompt({context,wake,taskCapabilityPrompt,@@ -406,7 +411,7 @@ export function createPersistentMindTurnAdapter() {let providerPrompt = basePrompt;let result;let parsed;- let toolCallCount = 0;+ const toolBudget = { used: 0 };const taskBudget = { used: 0 };const completedToolResults = [];const actionNotices = new Set();@@ -507,7 +512,7 @@ export function createPersistentMindTurnAdapter() {break;}- const remaining = Math.max(0, COS_TOOL_CALL_LIMITS.maxCallsPerTurn - toolCallCount);+ const remaining = Math.max(0, COS_TOOL_CALL_LIMITS.maxCallsPerTurn - toolBudget.used);const calls = parsed.toolCalls.slice(0, remaining);const rejectedCalls = parsed.toolCalls.slice(remaining);if (rejectedCalls.length > 0) {@@ -535,10 +540,14 @@ export function createPersistentMindTurnAdapter() {capabilities: taskAccess,recordCapabilityEvent,taskBudget,+ toolBudget,});completedToolResults.push(...toolResults);- toolCallCount += calls.length;- const budgetExhausted = toolCallCount >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;+ const liveCapabilities = normalizePersistentMindCapabilities((await loadState()).config?.persistentMindCapabilities);+ basePrompt = buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, visibilityPrompt, userActionsPrompt, callCapabilityPrompt,+ toolCapabilityPrompt: buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities)),+ });+ const budgetExhausted = toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;providerPrompt = `${basePrompt}\n\n# Completed tool results\n${JSON.stringify(completedToolResults)}\n\n${parsed.taskRequests.length > 0 ? 'Task requests from this intermediate round were not queued. Include only the final desired taskRequests in a terminal response with toolCalls: [].\n' : ''}${budgetExhausted ? 'The tool-call budget is exhausted. Return a final response with toolCalls: [] and do not repeat completed actions.' : 'Use these results to continue. Do not repeat a completed requestId.'}`;}// After the tool rounds, so a call is placed on the turn's final answer@@ -562,7 +571,7 @@ export function createPersistentMindTurnAdapter() {result = { ...result, text: JSON.stringify(parsed) };}const message = parsed.message || (wake?.kind === 'message' ? parsed.thinkingSummary : '');- if (!parsed.thinkingSummary && !message && memoryCandidates.length === 0 && parsed.taskRequests.length === 0 && toolCallCount === 0 && !callOutcome) {+ if (!parsed.thinkingSummary && !message && memoryCandidates.length === 0 && parsed.taskRequests.length === 0 && toolBudget.used === 0 && !callOutcome) {throw new Error('Persistent mind returned no visible thought, reply, memory candidate, task request, or tool call');}const events = [];diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex ee00604f0a..096f68d92e 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -53,6 +53,7 @@ vi.mock('./persistentMindCallCapability.js', () => ({executePersistentMindCallRequest: (...args) => mock.executeCallRequest(...args),}));vi.mock('./cosToolRegistry.js', () => ({+ readPersistentMindRecipeCatalog: vi.fn(async () => []),buildPersistentMindToolPrompt: ({ readPortos, writePortos }) => `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}`,executeCosToolCall: (...args) => mock.executeToolCall(...args),isCosTaskToolName: (name) => name === 'cos.create-task' || name === 'cos_create_task',