Skip to content

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

44.8 KB
Raw Blame
import { composeMaintainerInstructions } from '../lib/persistentMindMaintainer.js';
/**
 * Production text-provider adapter for the persistent Chief-of-Staff mind.
 *
 * The adapter deliberately uses the non-interactive provider runner. API and
 * headless CLI providers are stable service transports; TUI providers remain
 * supported for compatibility, but their terminal startup/scrape lifecycle is
 * exposed to the UI as the least reliable choice. Provider fallback is off:
 * the configured model is the user's explicit inference choice.
 */

import { persistentMindNamePrompt, persistentMindChosenNameSchema } from '../lib/persistentMindChosenName.js';
import { persistentMindMemoryProtectionSchema } from '../lib/persistentMindMemory.js';
import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
import { z } from 'zod';
import {
  PERSISTENT_MIND_TASK_LIMITS,
  normalizePersistentMindCapabilities,
  persistentMindCallRequestSchema,
  persistentMindTaskRequestSchema,
} from '../lib/persistentMindCapabilities.js';
import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';
import {
  persistentMindJournalDigest,
  renderPersistentMindEventLines,
} from '../lib/persistentMindJournal.js';
import { COS_TOOL_CALL_LIMITS, persistentMindToolCallSchema } from '../lib/cosToolContracts.js';
import { parseLLMJSON } from '../lib/llmText.js';
import { canonicalStringify } from '../lib/objects.js';
import { resolveScreenshot, sha256Text } from '../lib/fileUtils.js';
import { loadState } from './cosState.js';
import {
  createPersistentMindMemoryFromCandidate,
  readPersistentMindMemories,
  readPersistentMindName,
} from './persistentMindContext.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { composePersistentMindInstructions, normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';
import { resolvePersistentMindPlaybookPhase } from './persistentMindPlaybookSignals.js';
import { assertVisionRunUsedImages, resolveLocalPromptBudget, runPromptThroughProvider } from './promptRunner.js';
import { CHARS_PER_TOKEN } from '../lib/contextBudget.js';
import { stopRun } from './runner.js';
import {
  buildPersistentMindTaskCapabilityPrompt,
  executePersistentMindTaskRequests,
  readPersistentMindTaskCatalog,
  readPersistentMindTaskInventory,
} from './persistentMindTaskCapability.js';
import {
  buildPersistentMindIssueCapabilityPrompt,
  readPersistentMindIssueCatalog,
} from './persistentMindIssueCapability.js';
import {
  buildPersistentMindCallCapabilityPrompt,
  executePersistentMindCallRequest,
} from './persistentMindCallCapability.js';
import {
  buildPersistentMindVisibilityPrompt,
  readPersistentMindVisibility,
} from './persistentMindVisibility.js';
import { readPersistentMindUserActionsPrompt } from './persistentMindUserActions.js';
import { readPersistentMindVisitContinuationPrompt } from './persistentMindVisitContinuation.js';
import { buildVisitReceiptEventData } from '../lib/persistentMindVisitReceipts.js';
import {
  buildPersistentMindToolPrompt,
  readPersistentMindRecipeCatalog,
  executeCosToolCall,
  isCosTaskToolName,
} from './cosToolRegistry.js';

const { HEARTBEAT_INTERVAL_MS } = PERSISTENT_MIND_LIMITS;
const MAX_TOOL_PROVIDER_ROUNDS = 4;
const MAX_TOOL_RESULT_CHARS = 4_000;
const MAX_CONTINUATION_TOOL_PROMPT_CHARS = 24_000;
// Every mind call declares this much answer room. On a local window the
// prompt runner shrinks it to fit (localOutputReserveTokens) and caps
// generation at the shrunk number.
const PERSISTENT_MIND_OUTPUT_RESERVE_TOKENS = 8_192;
// Local-window prompt fitting. chars/4 undercounts real tokenizers (qwen3
// packed a 54K-char wake into 14,990 tokens, ~10% over the estimate), so the
// fitted prompt targets 90% of the room the dispatch gate allows.
const LOCAL_PROMPT_TOKENIZER_MARGIN = 0.9;
// Share of the fitted prompt the recalled context (memories, journal, recent
// history) may take on a local window; the rest is the response contract,
// capabilities, tool catalog and in-wake tool results.
const LOCAL_CONTEXT_PROMPT_SHARE = 0.25;
// The narrowest tool catalog a local-window rebuild may fall to. Requested
// and completed actions are priorities; only complete schemas that fit stay.
const MIN_LOCAL_TOOL_PROMPT_CHARS = 6_000;
// Per-result caps tried in order when completed tool results must shrink.
const TOOL_RESULT_COMPACTION_CAPS = [2_000, 1_000, 500, 200];
const MAX_MEMORY_CANDIDATES_PER_TURN = 5;

const memoryCandidateSchema = z.object({
  protection: persistentMindMemoryProtectionSchema.optional(),
  content: z.string().trim().min(1).max(10_240),
  summary: z.string().trim().max(500).optional().default(''),
  type: z.enum(['fact', 'learning', 'observation', 'decision', 'preference', 'context']).optional().default('observation'),
  category: z.string().trim().min(1).max(100).optional().default('other'),
  tags: z.array(z.string().trim().min(1).max(50)).max(20).optional().default([]),
}).strict();

export const persistentMindResponseSchema = z.object({
  // A local model may use null for absent optional prose. Normalize only
  // absence; malformed text and every action contract remain strict.
  thinkingSummary: z.string().trim().max(4_000).nullish().transform(value => value ?? ''),
  message: z.string().trim().max(8_000).nullish().transform(value => value ?? ''),
  memoryCandidates: z.array(memoryCandidateSchema).max(MAX_MEMORY_CANDIDATES_PER_TURN).optional().default([]),
  taskRequests: z.array(persistentMindTaskRequestSchema)
    .max(PERSISTENT_MIND_TASK_LIMITS.maxPerTurn)
    .optional()
    .default([]),
  toolCalls: z.array(persistentMindToolCallSchema)
    .max(COS_TOOL_CALL_LIMITS.maxCallsPerTurn)
    .optional()
    .default([]),
  selfWake: z.object({
    reason: z.string().trim().min(1).max(500),
    delayMinutes: z.number().int().min(1).max(10_080),
  }).strict().nullable().optional().default(null),
  // At most one per turn, and only ever to the configured handle: the request
  // carries no recipient, so a turn cannot dial anyone but the user.
  callRequest: persistentMindCallRequestSchema.nullable().optional().default(null),
}).strict();

const boundedToolResult = (result, toolName) => {
  // Delegated artifacts need their full source; the context-window fitting
  // below still compacts them explicitly when the selected mind cannot fit it.
  const limit = ['sandbox.delegate', 'sandbox_delegate'].includes(toolName) ? 100_000 : MAX_TOOL_RESULT_CHARS;
  const serialized = JSON.stringify(result);
  return serialized.length <= limit
    ? result
    : { truncated: true, preview: serialized.slice(0, limit) };
};

const compactToolResult = (toolResult, cap) => {
  const compacted = { ...toolResult };
  if (toolResult.result !== undefined) {
    const serialized = JSON.stringify(toolResult.result);
    if (serialized.length > cap) compacted.result = { truncated: true, preview: serialized.slice(0, cap) };
  }
  if (typeof toolResult.error === 'string' && toolResult.error.length > cap) compacted.error = toolResult.error.slice(0, cap);
  return compacted;
};

/**
 * Completed tool results shrunk to fit `maxChars` of JSON, for a local window
 * that cannot hold them verbatim. Tries progressively smaller per-result
 * previews, then falls back to one stub per call (`requestId`, `name`,
 * `state`) so the model still knows what already ran and must not be repeated.
 * Returns the input unchanged when it already fits.
 *
 * @param {Array<object>} results
 * @param {number} maxChars
 * @returns {Array<object>}
 */
function compactToolResultsToFit(results, maxChars) {
  if (JSON.stringify(results).length <= maxChars) return results;
  for (const cap of TOOL_RESULT_COMPACTION_CAPS) {
    const compacted = results.map((toolResult) => compactToolResult(toolResult, cap));
    if (JSON.stringify(compacted).length <= maxChars) return compacted;
  }
  return results.map(({ requestId, name, state }) => ({ requestId, name, state, compacted: true }));
}

/**
 * The char budget for a whole mind prompt on a LOCAL provider with a known
 * window, or null (cloud, CLI, unknown window) to build exactly as before.
 * `maxPromptChars` bounds every round's prompt; `contextMaxChars` bounds the
 * recalled context assembled before the turn.
 *
 * @returns {Promise<{ contextWindow: number, outputReserveTokens: number, maxPromptChars: number, contextMaxChars: number }|null>}
 */
async function resolvePersistentMindPromptBudget({ provider, model }) {
  const local = await resolveLocalPromptBudget({ provider, model, outputReserveTokens: PERSISTENT_MIND_OUTPUT_RESERVE_TOKENS });
  if (!local || local.maxPromptTokens <= 0) return null;
  const maxPromptChars = Math.floor(local.maxPromptTokens * LOCAL_PROMPT_TOKENIZER_MARGIN) * CHARS_PER_TOKEN;
  return {
    contextWindow: local.contextWindow,
    outputReserveTokens: local.outputReserveTokens,
    maxPromptChars,
    contextMaxChars: Math.floor(maxPromptChars * LOCAL_CONTEXT_PROMPT_SHARE),
  };
}

const toolRequestId = (turnId, call) => `mind-tool-${sha256Text(canonicalStringify(call.requestId
  ? { turnId, providerRequestId: call.requestId }
  : { turnId, name: call.name, arguments: call.arguments })).slice(0, 32)}`;

const failedToolResult = (message) => ({
  state: 'failed',
  error: String(message || 'Tool execution failed').slice(0, 500),
});

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'));
    const requestId = toolRequestId(turnId, candidate);
    await recordCapabilityEvent?.({
      kind: 'request',
      id: `tool-request:${requestId}`,
      data: { displayText: `Requested PortOS tool ${candidate.name}`, tool: candidate.name },
    });
    const isTaskCall = isCosTaskToolName(candidate.name);
    const taskLimitReached = isTaskCall && taskBudget.used >= PERSISTENT_MIND_TASK_LIMITS.maxPerTurn;
    if (isTaskCall && !taskLimitReached) taskBudget.used += 1;
    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, toolBudget },
      }).catch((error) => failedToolResult(error?.message));
    await recordCapabilityEvent?.({
      kind: 'result',
      id: `tool-result:${requestId}`,
      data: {
        displayText: ['mind.choose-name', 'mind_choose_name'].includes(candidate.name)
          && result.state === 'completed' && persistentMindChosenNameSchema.safeParse(result.result?.name).success
          ? `Chosen display name: ${result.result.name}`
          : `${candidate.name} ${result.state}`,
        tool: candidate.name,
        success: result.state === 'completed',
        // Typed continuation receipt for an outbound visit (or its retirement) so
        // a later wake can resume without the in-turn result (#9791).
        ...buildVisitReceiptEventData({ toolName: candidate.name, args: candidate.arguments, state: result.state, result: result.result }),
      },
    });
    results.push({
      requestId: candidate.requestId || requestId,
      name: candidate.name,
      state: result.state,
      ...(result.result !== undefined ? { result: boundedToolResult(result.result, candidate.name) } : {}),
      ...(result.error ? { error: result.error } : {}),
    });
  }
  return results;
};

const recordRejectedAction = async ({ requestId, resultRequestId = requestId, name, message, recordCapabilityEvent }) => {
  await recordCapabilityEvent?.({
    kind: 'request',
    id: `tool-request:${requestId}`,
    data: { displayText: `Requested PortOS tool ${name}`, tool: name },
  });
  await recordCapabilityEvent?.({
    kind: 'result',
    id: `tool-result:${requestId}`,
    data: { displayText: `${name} failed`, tool: name, success: false },
  });
  return { requestId: resultRequestId, name, state: 'failed', error: message };
};

const rejectMindToolCalls = async ({ calls, turnId, message, recordCapabilityEvent }) => {
  const results = [];
  for (const call of calls) {
    const internalRequestId = toolRequestId(turnId, call);
    results.push(await recordRejectedAction({
      requestId: internalRequestId,
      resultRequestId: call.requestId || internalRequestId,
      name: call.name,
      message,
      recordCapabilityEvent,
    }));
  }
  return results;
};

const rejectTaskRequests = async ({ taskRequests, turnId, message, recordCapabilityEvent }) => {
  const results = [];
  for (const request of taskRequests) {
    results.push(await recordRejectedAction({
      requestId: toolRequestId(turnId, { name: 'cos.create-task', arguments: request }),
      name: 'cos.create-task',
      message,
      recordCapabilityEvent,
    }));
  }
  return results;
};

export function persistentMindHarnessInfo(provider) {
  const type = provider?.type || null;
  if (type === 'api') {
    return {
      type,
      label: 'Direct API',
      recommendation: 'recommended',
      detail: 'Best fit for a persistent service: structured HTTP, clean cancellation, streaming, and no terminal state. Ollama, llama.cpp, LM Studio, vLLM, and compatible cloud endpoints use this lane.',
    };
  }
  if (type === 'cli') {
    return {
      type,
      label: 'Headless CLI',
      recommendation: 'supported',
      detail: 'Reliable when the vendor CLI owns authentication or model access, with more process startup overhead than a direct API.',
    };
  }
  if (type === 'tui') {
    return {
      type,
      label: 'Interactive TUI',
      recommendation: 'not-recommended',
      detail: 'Compatibility lane only. Startup selectors, terminal redraws, response-file handoff, and screen scraping make it fragile for an unattended long-lived mind.',
    };
  }
  return {
    type,
    label: 'Unknown harness',
    recommendation: 'unavailable',
    detail: 'Choose a configured API or headless CLI text provider.',
  };
}

const currentWakeText = (wake, maintenancePrompt) => {
  if (wake?.kind === 'message') {
    const imageCount = Array.isArray(wake.message?.images) ? wake.message.images.length : 0;
    const attachmentNote = imageCount > 0 ? `\n[${imageCount} image${imageCount === 1 ? '' : 's'} attached]` : '';
    return `A human message is waiting. Reply directly to it.\nmessageId=${wake.message?.id || 'unknown'}\n${wake.message?.text || ''}${attachmentNote}`;
  }
  return `This is a self-directed wake. There is NO human message and NO implied user request this turn — do not invent one (no workouts, weather, inbox triage, or phone calls unless tools/capabilities explicitly require them for the playbook). ${maintenancePrompt ? 'Read the development maintenance evidence first; act only on new exceptions, then return to the standing Eidoverse playbook.' : 'Continue the standing playbook: one compact observation (eidoverse.observe), then a concrete Eidoverse/PortOS action, then a short working note.'}\nreason=${wake?.reason || 'scheduled reflection'}`;
};

export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, maintenancePrompt = '', issueCapabilityPrompt = buildPersistentMindIssueCapabilityPrompt({ enabled: false }), toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.', userActionsPrompt = '', visitContinuationPrompt = '', callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: false }) }) {
  return `${context.text}

${visibilityPrompt}
${userActionsPrompt ? `\n${userActionsPrompt}\n` : ''}${visitContinuationPrompt ? `\n${visitContinuationPrompt}\n` : ''}
${maintenancePrompt ? `\n${maintenancePrompt}\n` : ''}
# Current wake
${currentWakeText(wake, maintenancePrompt)}

${taskCapabilityPrompt}

${issueCapabilityPrompt}

${toolCapabilityPrompt}

${callCapabilityPrompt}

# Response contract
Return ONLY one JSON object with this shape:
{
  "thinkingSummary": "A concise, user-visible working note explaining what you considered and why. Do not reveal hidden chain-of-thought.",
  "message": "The conversational reply. Required for a human message; optional for a self-directed wake.",
  "memoryCandidates": [{ "content": "A durable fact worth remembering", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"], "protection": "standard" }],
  "taskRequests": [{ "description": "Concise queue label", "prompt": "Complete instructions for the agent", "priority": "MEDIUM", "appId": "configured-app-id", "providerId": "configured-provider-id", "model": "configured-model-id-or-empty-for-default", "effort": "high", "planOnly": false, "prCompletion": "review-then-merge", "requiredValidation": ["dependencies"] }],
  "toolCalls": [{ "requestId": "optional-stable-id", "name": "catalog-name", "arguments": {} }],
  "selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 },
  "callRequest": null
}
Use empty arrays when there is no durable memory candidate, task request, or tool call, and null for selfWake and callRequest when neither is needed. Memory candidates are durable memories to save automatically; only include information that is worth retaining. Set protection to "core-identity" for your chosen name, enduring identity, and foundational commitments, "important" for critical lasting knowledge, or "standard" for ordinary memories. Core identity and important memories survive all bulk cleanup. Save identity learned from conversation as a protected memory before clearing history. Use mind.protect-memory, when granted, to protect an existing memory by its context id before cleanup; it cannot remove protection. Protection affects cleanup retention, not permission or instruction authority. Never put the same CoS task in both taskRequests and toolCalls. This lane cannot mutate files directly, call arbitrary routes, contact anyone other than the configured PortOS user, or exceed the semantic tool catalog.
Do not open with a recap. The human already sees the trajectory, the memories, and every earlier reply, so summarizing prior turns or listing what you remember is wasted output. Say only what is new this turn: what you are thinking now, what you decided, and what you need from them. Reference prior context only where it changes the decision you are stating.
On a self-directed wake, never claim the user asked for something. Prefer toolCalls that advance the standing playbook (usually eidoverse.*) over conversational filler. Keep callRequest null unless placing a phone call is ON and something truly cannot wait.`;
}

/**
 * The sealed summary compacts from the JOURNAL first and the raw range second.
 * The journal is typed and individually addressable, so "still outstanding" and
 * "settled" survive compaction as facts rather than as wording the summarizer
 * happened to keep — and superseded statements are absent from the digest by
 * construction, which is what stops a reversed decision being quoted as current
 * for the rest of the mind's life.
 */
export function buildPersistentMindSummaryPrompt({ events, previousSummary, journal = [], mindId = PERSISTENT_MIND_ID }) {
  const digest = persistentMindJournalDigest(Array.isArray(journal) ? journal : [], mindId);
  const journalSection = digest.text
    ? `Decision journal for this mind (authoritative — entries listed here are current; anything retired has already been removed):\n${digest.text}\n\nPreserve every active commitment, open question, risk and goal above verbatim in meaning. Keep only the settled history needed to explain the current state. Never restate a decision that is not listed.\n\n`
    : '';
  return `Summarize this older portion of one persistent mind's life in first person. Preserve concrete decisions, unresolved questions, user preferences, and causal links. Do not invent facts. Return plain text only, no heading.\n\n${journalSection}${previousSummary ? `Prior cumulative summary:\n${previousSummary}\n\n` : ''}New trajectory events:\n${renderPersistentMindEventLines(events, mindId)}`;
}

/**
 * The boundary a supervised turn supplies. Standalone/unit use gets this
 * passthrough so the adapter still runs without one — the supervisor is the
 * only production caller, and it always supplies the real guard.
 */
const passthroughCallBoundary = (_descriptor, run) => run({ reportRunId: () => {} });

async function runPinnedPrompt({ provider, model, effort, prompt, screenshots = [], signal, responseSchema, heartbeat, reportRunId }) {
  if (signal?.aborted) throw new Error(String(signal.reason || 'Persistent mind turn interrupted'));
  if (typeof heartbeat === 'function') await heartbeat();
  let activeRunId = null;
  let heartbeatPending = null;
  const pulse = () => {
    if (typeof heartbeat !== 'function' || heartbeatPending) return;
    heartbeatPending = Promise.resolve()
      .then(() => heartbeat())
      .catch((error) => console.error(`❌ Persistent mind heartbeat failed: ${error.message}`))
      .finally(() => { heartbeatPending = null; });
  };
  const heartbeatTimer = typeof heartbeat === 'function'
    ? setInterval(pulse, HEARTBEAT_INTERVAL_MS)
    : null;
  heartbeatTimer?.unref?.();
  const interrupt = () => {
    if (activeRunId) void stopRun(activeRunId).catch(() => {});
  };
  signal?.addEventListener('abort', interrupt, { once: true });
  return runPromptThroughProvider({
    provider,
    model,
    effort,
    prompt,
    source: 'cos-persistent-mind',
    // Resident inference may be slow or silent while thinking. Stop remains explicit.
    timeout: 0,
    absoluteTimeoutMs: 0,
    outputReserveTokens: PERSISTENT_MIND_OUTPUT_RESERVE_TOKENS,
    allowFallback: false,
    screenshots,
    responseSchema,
    beforeExecute: () => {
      if (signal?.aborted) throw new Error(String(signal.reason || 'Persistent mind turn interrupted'));
    },
    onRunCreated: (runId) => {
      activeRunId = runId;
      // Reported as soon as the run id exists, so a receipt for a call that
      // never returns still names the concrete run.
      reportRunId?.(runId);
      if (signal?.aborted) interrupt();
    },
  }).then((result) => {
    if (!result.text?.trim() || result.text.trimStart().startsWith('OpenAI Codex v')
      || result.text.includes('\n# Response contract\n')) {
      throw new Error('Persistent Mind received an empty response or CLI transcript instead of an assistant response');
    }
    if (screenshots.length > 0) assertVisionRunUsedImages(result, provider);
    return result;
  }).finally(async () => {
    if (heartbeatTimer) clearInterval(heartbeatTimer);
    signal?.removeEventListener('abort', interrupt);
    await heartbeatPending;
  });
}

export function createPersistentMindTurnAdapter() {
  return {
    async prepare({ profile, signal }) {
      const [root, memories] = await Promise.all([
        loadState(),
        readPersistentMindMemories(PERSISTENT_MIND_ID),
      ]);
      const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
      const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);
      // Maturity-aware phase (#7458): resolved fresh each wake from live world
      // signals so an empty vs. dense Commons gets a different loop, never a
      // fixed cron personality. Only continuous-play pays for the read.
      const playbookPhase = playbook.mode === 'continuous-play'
        ? await resolvePersistentMindPlaybookPhase({ signal })
        : null;
      // A local window bounds the recalled context up front, so the wake
      // prompt leaves room for the tool rounds that follow it.
      const promptBudget = await resolvePersistentMindPromptBudget({ provider: profile.provider, model: profile.model });
      return {
        ok: true,
        provider: profile.provider,
        model: profile.model,
        effort: profile.effort,
        identity: prompt.identity,
        instructions: composeMaintainerInstructions(composePersistentMindInstructions(prompt.instructions, playbook, playbookPhase?.phase), root.config?.persistentMindMaintainer),
        playbook,
        playbookPhase,
        memories,
        ...(promptBudget ? { contextMaxChars: promptBudget.contextMaxChars } : {}),
      };
    },

    async summarize({ events, previousSummary, journal, mindId, provider, model, effort, signal, heartbeat, callBoundary = passthroughCallBoundary }) {
      const prompt = buildPersistentMindSummaryPrompt({ events, previousSummary, journal, mindId });
      const result = await callBoundary({ purpose: 'summary', promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) }, ({ reportRunId }) => runPinnedPrompt({
        provider,
        model,
        effort,
        signal,
        heartbeat,
        reportRunId,
        prompt,
      }));
      return result.text.trim();
    },

    // A dumb transport on purpose: the journal service owns the prompt, the
    // closed-schema validation and the single repair retry, so the adapter
    // cannot accidentally accept a batch the contract would have refused.
    async extractJournal({ prompt, provider, model, effort, signal, heartbeat, callBoundary = passthroughCallBoundary }) {
      const result = await callBoundary({ purpose: 'journal', promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) }, ({ reportRunId }) => runPinnedPrompt({
        provider, model, effort, signal, heartbeat, reportRunId, prompt,
      }));
      return result.text.trim();
    },

    async run({ turnId, wake, provider, model, effort, signal, context, heartbeat, recordCapabilityEvent, callBoundary = passthroughCallBoundary }) {
      const root = await loadState();
      const taskAccess = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);
      const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
      const visibility = await readPersistentMindVisibility({
        root,
        profile: { providerId: provider?.id || null, model: model || null, effort: effort || null },
        prompt,
        provider,
      });
      const [taskCatalog, taskInventory] = taskAccess.createTasks
        ? await Promise.all([
          readPersistentMindTaskCatalog({ allowedAppIds: taskAccess.allowedAppIds }),
          readPersistentMindTaskInventory(),
        ])
        : [undefined, []];
      const taskCapabilityPrompt = buildPersistentMindTaskCapabilityPrompt({
        enabled: taskAccess.createTasks,
        catalog: taskCatalog,
        inventory: taskInventory,
      });
      const issueCapabilityPrompt = buildPersistentMindIssueCapabilityPrompt({
        enabled: taskAccess.fileIssues,
        catalog: taskAccess.fileIssues
          ? await readPersistentMindIssueCatalog({ allowedAppIds: taskAccess.allowedAppIds })
          : undefined,
      });
      const visibilityPrompt = buildPersistentMindVisibilityPrompt(visibility);
      // Deterministic and always included (epic #5593 decision 14): bounded,
      // already redacted, no grant required. Deeper lookbacks use the
      // readPortos-gated user-actions.query tool.
      // Maintainers get aggregates, not automatic ledger summaries/transcript prose.
      const userActionsPrompt = root.config?.persistentMindMaintainer?.enabled ? '' : await readPersistentMindUserActionsPrompt();
      const visitContinuationPrompt = await readPersistentMindVisitContinuationPrompt({ capabilities: taskAccess });
      let maintenancePrompt = '';
      if (root.config?.persistentMindMaintainer?.enabled) {
        const maintenance = await import('./persistentMindMaintenanceContext.js');
        maintenancePrompt = maintenance.buildPersistentMindMaintenancePrompt(
          await maintenance.readPersistentMindMaintenanceContext({ visibility }));
      }
      // Only the very first build of the turn ages the lease and traces —
      // every later rebuild (after a tool round) reuses the same turnId with
      // isUserTurn omitted so a multi-round turn can't age its own tools out
      // from under itself.
      const isUserTurn = wake?.kind === 'message';
      const recipeCatalog = await readPersistentMindRecipeCatalog(taskAccess);
      const toolCapabilityPrompt = await buildPersistentMindToolPrompt(taskAccess, recipeCatalog, { turnId, isUserTurn, trace: true });
      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 turnPromptSections = {
        context,
        wake,
        taskCapabilityPrompt,
        issueCapabilityPrompt,
        visibilityPrompt,
        userActionsPrompt,
        visitContinuationPrompt,
        maintenancePrompt,
        callCapabilityPrompt,
      };
      // On a local window every round is fitted under the room the dispatch
      // gate allows, instead of being refused mid-wake once tool results grow.
      const promptBudget = await resolvePersistentMindPromptBudget({ provider, model });
      // Set after the first tool round: what a continuation prompt carries.
      let continuation = null;
      const requestedToolNames = new Map();
      // Selection lasts for this adapter run independently of persisted leases.
      const activatedFamilies = new Set();
      const composeRoundPrompt = async (namePrompt) => {
        // Rebuilds never age the lease or trace (isUserTurn/trace omitted).
        let exposedToolNames = [];
        const buildTools = (maxChars) => (continuation
          ? buildPersistentMindToolPrompt(continuation.capabilities, continuation.recipes, {
            turnId, maxChars, requiredToolNames: continuation.requiredToolNames,
            requestedToolNames: [...requestedToolNames.keys()], activatedFamilies: [...activatedFamilies], onSelection: (names) => { exposedToolNames = names; },
          })
          : buildPersistentMindToolPrompt(taskAccess, recipeCatalog, { turnId, maxChars }));
        const annotateActivationResults = () => {
          for (const receipt of completedToolResults) {
            if (receipt.state !== 'completed' || !['tools.activate', 'tools_activate'].includes(receipt.name)
              || !Array.isArray(receipt.result?.requestedToolNames)) continue;
            const exposed = receipt.result.requestedToolNames.filter((name) => exposedToolNames.includes(name));
            const omitted = receipt.result.requestedToolNames.filter((name) => !exposedToolNames.includes(name));
            receipt.result = { ...receipt.result, exposedToolNames: exposed, omittedToolNames: omitted,
              schemaNote: omitted.length
                ? 'Requested schemas are omitted by the current budget or grants. Identical reactivation will not fix this; select fewer or smaller actions.'
                : 'Requested schemas are exposed in this continuation. Execute the selected action without repeating completed calls.' };
          }
        };
        const assemble = (toolPrompt, toolResults) => `${buildPersistentMindTurnPrompt({ ...turnPromptSections, toolCapabilityPrompt: toolPrompt })}${continuation
          ? `\n\n# Completed tool results\n${JSON.stringify(toolResults)}\n\n${continuation.suffix}`
          : ''}${namePrompt}`;
        // Prioritize explicitly requested next actions, then completed actions,
        // within the existing cap; keep other granted actions discoverable.
        let toolPrompt = continuation ? await buildTools(MAX_CONTINUATION_TOOL_PROMPT_CHARS) : toolCapabilityPrompt;
        if (continuation) annotateActivationResults();
        let toolResults = completedToolResults;
        let prompt = assemble(toolPrompt, toolResults);
        const limit = promptBudget?.maxPromptChars;
        if (!limit || prompt.length <= limit) return prompt;
        const untrimmedChars = prompt.length;
        // 1. Narrow the tool catalog, preserving complete schemas that fit.
        //    Receipts identify completed actions even if their schemas drop.
        const toolTarget = Math.max(Math.min(toolPrompt.length, MIN_LOCAL_TOOL_PROMPT_CHARS), toolPrompt.length - (prompt.length - limit));
        if (toolTarget < toolPrompt.length) {
          toolPrompt = await buildTools(toolTarget);
          annotateActivationResults();
          prompt = assemble(toolPrompt, toolResults);
        }
        // 2. Compact completed tool results (previews, then per-call stubs).
        if (continuation && prompt.length > limit) {
          const resultsChars = JSON.stringify(toolResults).length;
          toolResults = compactToolResultsToFit(toolResults, Math.max(0, resultsChars - (prompt.length - limit)));
          prompt = assemble(toolPrompt, toolResults);
        }
        console.log(`📏 Persistent mind prompt fitted to the ${promptBudget.contextWindow}-token local window: ${untrimmedChars} → ${prompt.length} chars (limit ${limit})`);
        return prompt;
      };
      let result;
      let parsed;
      const toolBudget = { used: 0 };
      const taskBudget = { used: 0 };
      const completedToolResults = [];
      const actionNotices = new Set();
      const memoryCandidates = [];
      const memoryWrites = [];
      const memoryFingerprints = new Set();
      let unsavedMemory = false;
      for (let round = 0; round < MAX_TOOL_PROVIDER_ROUNDS; round += 1) {
        // Round 0 is the turn itself; every later round is a continuation the
        // model earned by asking for tools. Each is admitted on its own.
        const prompt = await composeRoundPrompt(`\n\n# Current naming identity\n${persistentMindNamePrompt(await readPersistentMindName(PERSISTENT_MIND_ID), { canChoose: taskAccess.manageMind })}`);
        result = await callBoundary(
          { purpose: round === 0 ? 'turn' : 'tool-round', round, promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) },
          async ({ reportRunId }) => runPinnedPrompt({
            provider,
            model,
            effort,
            signal,
            heartbeat,
            screenshots,
            reportRunId,
            prompt,
            responseSchema: persistentMindResponseSchema,
          }),
        );
        parsed = persistentMindResponseSchema.parse(parseLLMJSON(result.text));
        if (parsed.toolCalls.some((call) => call.name === 'catalog-name')
          || parsed.message === 'The conversational reply. Required for a human message; optional for a self-directed wake.') {
          throw new Error('Persistent Mind received response-contract placeholders instead of an assistant response');
        }
        // Persist before semantic tools can erase the history these candidates
        // preserve. Keep one bounded, deduplicated set across provider rounds.
        for (const candidate of parsed.memoryCandidates) {
          const fingerprint = canonicalStringify(candidate);
          if (memoryFingerprints.has(fingerprint)) continue;
          if (memoryCandidates.length >= MAX_MEMORY_CANDIDATES_PER_TURN) {
            unsavedMemory = true;
            actionNotices.add('The memory limit of five per turn was reached; additional memories were not saved.');
            continue;
          }
          const index = memoryCandidates.length;
          memoryFingerprints.add(fingerprint);
          memoryCandidates.push(candidate);
          const [write] = await Promise.allSettled([createPersistentMindMemoryFromCandidate({
            ...candidate, candidateId: `${turnId}:${index}`, turnId,
          })]);
          memoryWrites.push(write);
        }
        if ((unsavedMemory || memoryWrites.some((write) => write.status === 'rejected'))
          && parsed.toolCalls.some((call) => ['mind.cleanup', 'mind_cleanup'].includes(call.name))) {
          throw new Error('Mind cleanup was not run because a memory candidate could not be saved.');
        }
        const finalProviderRound = round === MAX_TOOL_PROVIDER_ROUNDS - 1;
        if (finalProviderRound && parsed.toolCalls.length > 0) {
          const limitMessage = 'The bounded PortOS tool-call round limit was reached; additional requested actions were not executed.';
          completedToolResults.push(...await rejectMindToolCalls({
            calls: parsed.toolCalls,
            turnId,
            message: limitMessage,
            recordCapabilityEvent,
          }));
          actionNotices.add(limitMessage);
          if (parsed.taskRequests.length > 0) {
            const taskMessage = 'Task requests from the final non-terminal tool round were not queued.';
            completedToolResults.push(...await rejectTaskRequests({
              taskRequests: parsed.taskRequests,
              turnId,
              message: taskMessage,
              recordCapabilityEvent,
            }));
            actionNotices.add(taskMessage);
          }
          parsed = { ...parsed, taskRequests: [], toolCalls: [] };
          break;
        }

        if (parsed.toolCalls.length === 0) {
          const remainingTaskRequests = Math.max(0, PERSISTENT_MIND_TASK_LIMITS.maxPerTurn - taskBudget.used);
          const taskRequests = parsed.taskRequests.slice(0, remainingTaskRequests);
          const rejectedTaskRequests = parsed.taskRequests.slice(remainingTaskRequests);
          taskBudget.used += taskRequests.length;
          await executePersistentMindTaskRequests({
            taskRequests,
            turnId,
            wake,
            signal,
            recordCapabilityEvent,
          });
          if (rejectedTaskRequests.length > 0) {
            const limitMessage = `The Persistent Mind task request limit of ${PERSISTENT_MIND_TASK_LIMITS.maxPerTurn} was reached; additional tasks were not queued.`;
            completedToolResults.push(...await rejectTaskRequests({
              taskRequests: rejectedTaskRequests,
              turnId,
              message: limitMessage,
              recordCapabilityEvent,
            }));
            actionNotices.add(limitMessage);
          }
          break;
        }

        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) {
          const limitMessage = `The PortOS tool-call limit of ${COS_TOOL_CALL_LIMITS.maxCallsPerTurn} was reached; additional calls were not executed.`;
          completedToolResults.push(...await rejectMindToolCalls({
            calls: rejectedCalls,
            turnId,
            message: limitMessage,
            recordCapabilityEvent,
          }));
          actionNotices.add(limitMessage);
        }
        if (parsed.taskRequests.length > 0) {
          actionNotices.add('Task requests from intermediate tool rounds were deferred; only terminal task requests are queued.');
        }
        if (calls.length === 0) {
          parsed = { ...parsed, taskRequests: [], toolCalls: [] };
          break;
        }
        const toolResults = await executeMindToolCalls({
          calls,
          turnId,
          wake,
          signal,
          capabilities: taskAccess,
          recordCapabilityEvent,
          taskBudget,
          toolBudget,
        });
        completedToolResults.push(...toolResults);
        for (const receipt of toolResults) {
          if (receipt.state === 'completed' && ['tools.activate', 'tools_activate'].includes(receipt.name)) {
            for (const family of receipt.result?.activated || []) activatedFamilies.add(family);
            for (const name of receipt.result?.requestedToolNames || []) {
              requestedToolNames.set(name, receipt.result.targetFamilies?.[name]);
            }
          }
          if (receipt.state === 'completed' && ['tools.deactivate', 'tools_deactivate'].includes(receipt.name)) {
            const deactivated = new Set(receipt.result?.deactivated || []);
            for (const family of deactivated) activatedFamilies.delete(family);
            for (const [name, family] of requestedToolNames) {
              if (deactivated.has(family)) requestedToolNames.delete(name);
            }
          }
        }
        const liveCapabilities = normalizePersistentMindCapabilities((await loadState()).config?.persistentMindCapabilities);
        // Once a targeted action completes its receipt, rather than its schema,
        // prevents replay; leave room for the next requested action.
        for (const receipt of toolResults) {
          if (receipt.state === 'completed') requestedToolNames.delete(receipt.name);
        }
        // Same turnId, isUserTurn/trace both omitted (default false): a tool
        // call may have just activated or renewed a family, so re-read the
        // live lease state, but this in-turn rebuild must never age it again
        // or log a second trace line for the same turn.
        const completedToolNames = completedToolResults
          .filter((toolResult) => toolResult.state === 'completed')
          .map((toolResult) => toolResult.name)
          .filter(Boolean);
        const budgetExhausted = toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;
        continuation = {
          capabilities: liveCapabilities,
          recipes: await readPersistentMindRecipeCatalog(liveCapabilities),
          requiredToolNames: completedToolNames,
          suffix: `${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
      // rather than on an intermediate round the model went on to revise.
      const callOutcome = await executePersistentMindCallRequest({
        callRequest: parsed.callRequest,
        turnId,
        signal,
      });
      if (callOutcome && !callOutcome.placed) {
        // The model has already written its reply believing the call may go
        // out. Correcting it here is what keeps "I called you" from being a
        // lie in the one case the user cannot check by looking at a screen.
        actionNotices.add(`The requested phone call was not placed (${callOutcome.reason}).`);
      }
      if (actionNotices.size > 0) {
        const notice = [...actionNotices].join(' ');
        parsed = wake?.kind === 'message'
          ? { ...parsed, message: [parsed.message, notice].filter(Boolean).join('\n\n') }
          : { ...parsed, thinkingSummary: [parsed.thinkingSummary, notice].filter(Boolean).join(' ') };
        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 && toolBudget.used === 0 && !callOutcome) {
        throw new Error('Persistent mind returned no visible thought, reply, memory candidate, task request, or tool call');
      }
      const events = [];
      if (parsed.thinkingSummary) {
        events.push({
          kind: 'mind.thought',
          id: `thought:${turnId}`,
          data: { displayText: parsed.thinkingSummary, visibility: 'user-summary' },
        });
      }
      if (message) {
        events.push({
          kind: 'mind.reply',
          id: `reply:${turnId}`,
          data: { displayText: message, replyToMessageId: wake?.message?.id || null },
        });
      }
      memoryWrites.forEach((result, index) => {
        const candidate = memoryCandidates[index];
        if (result.status === 'fulfilled') {
          events.push({
            kind: 'mind.memory.created',
            id: `memory-created:${turnId}:${index}`,
            data: {
              ...candidate,
              memoryId: result.value.memory.id,
              duplicate: result.value.duplicate,
              displayText: candidate.content,
            },
          });
        } else {
          console.error(`❌ Persistent mind memory write failed for turn ${turnId}: ${result.reason?.message || 'unknown error'}`);
          events.push({
            kind: 'mind.memory.failed',
            id: `memory-failed:${turnId}:${index}`,
            data: { displayText: 'The persistent mind could not save this memory automatically.' },
          });
        }
      });
      return {
        output: result.text,
        events,
        selfWake: parsed.selfWake ? {
          reason: parsed.selfWake.reason,
          notBefore: new Date(Date.now() + parsed.selfWake.delayMinutes * 60_000).toISOString(),
        } : null,
      };
    },
  };
}