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: guard and account every Persistent Mind provider call, not just the turn (#6284)
[._.]/ Adam Eivyb97cc6664c85
diff --git a/server/lib/README.md b/server/lib/README.mdindex af3b0f80e9..d6503bab87 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -54,7 +54,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). || `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |-| `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |+| `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, bounded strictly-allowlisted per-provider-call execution receipts (route, run id, elapsed time, outcome, usage that stays `unknown` rather than zero) with their safe public projection, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. || `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. || `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. || `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. |diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.jsindex 01a07f8168..300c33d5aa 100644--- a/server/lib/persistentMindTrajectory.js+++ b/server/lib/persistentMindTrajectory.js@@ -3,8 +3,8 @@** The machine-local run-event ledger owns persistence and ordering. This module* owns the mind-specific vocabulary, cursor shape, replay projection, rollup- * record validation, and bounded context rendering so restart replay and live- * reads use the same deterministic rules.+ * record validation, per-provider-call execution receipts, and bounded context+ * rendering so restart replay and live reads use the same deterministic rules.*/import { z } from 'zod';@@ -18,6 +18,12 @@ export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze(['mind.annotation.accepted','mind.wake','mind.model.request',+ // One bounded receipt per PROVIDER CALL — the context summary, the turn, and+ // each tool round are separate attempts with their own run id, elapsed time,+ // outcome and usage provenance. `mind.model.result` still marks the turn's+ // overall answer. Older builds fold this kind as a no-op, so adding it is not+ // an envelope change.+ 'mind.model.call','mind.model.result','mind.thought','mind.reply',@@ -54,6 +60,10 @@ export const PERSISTENT_MIND_TRAJECTORY_LIMITS = Object.freeze({maxStoredRollups: 100,maxProjectedTurns: 100,maxProjectedInputs: 200,+ // A turn is capped at one summary call plus MAX_TOOL_PROVIDER_ROUNDS provider+ // rounds, so this holds every receipt a healthy turn can produce with room for+ // the denied/failed attempts a contested one adds.+ maxProjectedCallsPerTurn: 12,});export const persistentMindRollupSchema = z.object({@@ -162,6 +172,10 @@ export function projectPersistentMind(events, mindId = PERSISTENT_MIND_ID) {providerId: null,model: null,effort: null,+ thinkingPresetId: null,+ // Empty for a turn from before per-call receipts existed, and for one+ // that never reached a provider. Absent telemetry stays absent.+ calls: [],eventCount: 0,});}@@ -205,6 +219,19 @@ export function projectPersistentMind(events, mindId = PERSISTENT_MIND_ID) {turn.providerId = event.data?.providerId || turn.providerId;turn.model = event.data?.model || turn.model;turn.effort = event.data?.effort || turn.effort;+ turn.thinkingPresetId = event.data?.thinkingPresetId || turn.thinkingPresetId;+ }+ break;+ case 'mind.model.call':+ if (turn) {+ // The receipt names the route the call ACTUALLY ran on, so it wins+ // over the request event's announced route.+ turn.providerId = event.data?.providerId || turn.providerId;+ turn.model = event.data?.model || turn.model;+ turn.effort = event.data?.effort || turn.effort;+ turn.thinkingPresetId = event.data?.thinkingPresetId || turn.thinkingPresetId;+ turn.calls = [...turn.calls, publicPersistentMindCallReceipt(event)]+ .slice(-PERSISTENT_MIND_TRAJECTORY_LIMITS.maxProjectedCallsPerTurn);}break;case 'mind.paused':@@ -280,7 +307,7 @@ const renderEventLine = (event) => {if (event.turnId) parts.push(`turn=${event.turnId}`);const text = displayText(event);if (text !== null) parts.push(JSON.stringify(text));- for (const key of ['providerId', 'model', 'effort', 'capability', 'status']) {+ for (const key of ['providerId', 'model', 'effort', 'capability', 'status', 'purpose', 'outcome']) {const value = event.data?.[key];if (typeof value === 'string' && value) parts.push(`${key}=${value}`);}@@ -436,3 +463,271 @@ export function assemblePersistentMindContext({instructionsChars: instructionsText.length,};}++// ---------------------------------------------------------------------------+// Per-call execution receipts+// ---------------------------------------------------------------------------++/**+ * A turn is not one provider call: the optional context summary is one, the+ * turn itself is another, and every tool round after it is another again. These+ * are the vocabulary and SHAPE of what each of those attempts is allowed to+ * write into the machine-local trajectory — the same job `buildPersistentMindRollup`+ * does for a sealed summary range.+ *+ * A receipt is built from named fields only and parsed through a `.strict()`+ * schema, so a caller cannot widen it by handing over a provider record, a+ * prompt, a response, or a hidden reasoning trace — an unknown key throws at the+ * call site rather than reaching the ledger. That matters because the inputs are+ * the live provider object and a raw error message.+ *+ * Missing telemetry is `unknown`, never zero. A provider that reports nothing+ * and a provider that genuinely used zero tokens are different facts, and+ * collapsing them would make the ledger claim a free call.+ */+export const PERSISTENT_MIND_CALL_PURPOSES = Object.freeze(['summary', 'turn', 'tool-round']);++export const PERSISTENT_MIND_CALL_OUTCOMES = Object.freeze(['completed', 'failed', 'denied', 'interrupted']);++export const PERSISTENT_MIND_CALL_USAGE_STATES = Object.freeze(['reported', 'unknown']);++export const PERSISTENT_MIND_CALL_RECEIPT_LIMITS = Object.freeze({+ idChars: 128,+ modelChars: 200,+ effortChars: 32,+ labelChars: 120,+ // The ledger scrubs and bounds ordinary strings at RUN_EVENT_LIMITS.maxStringChars+ // (200). Building a longer reason would only be truncated on write, so the two+ // bounds are kept equal and the stored receipt matches the built one.+ reasonChars: 200,+ displayChars: 300,+ maxRound: 64,+});++// Distinct from `bounded` above, which yields '' for a missing rollup field.+// A receipt field that was never present must serialize as null: '' would read+// as an empty provider id or model rather than as absent.+const nullableBounded = (value, max) => {+ const text = typeof value === 'string' ? value.trim() : '';+ return text ? text.slice(0, max) : null;+};++// A token count or price is only real when the provider reported a finite,+// non-negative number. Anything else — absent, NaN, a string, a negative — is+// unknown, and must not be coerced into 0.+const reportedNumber = (value) => (+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null+);++const firstReported = (...values) => {+ for (const value of values) {+ const reported = reportedNumber(value);+ if (reported !== null) return reported;+ }+ return null;+};++const usageSchema = z.object({+ state: z.enum(PERSISTENT_MIND_CALL_USAGE_STATES),+ source: z.enum(['provider-reported', 'unavailable']),+ inputTokens: z.number().nonnegative().nullable(),+ outputTokens: z.number().nonnegative().nullable(),+ totalTokens: z.number().nonnegative().nullable(),+ costUsd: z.number().nonnegative().nullable(),+}).strict();++export const persistentMindCallReceiptSchema = z.object({+ schemaVersion: z.literal(1),+ purpose: z.enum(PERSISTENT_MIND_CALL_PURPOSES),+ round: z.number().int().nonnegative().max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.maxRound).nullable(),+ turnId: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ runId: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars).nullable(),+ providerId: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars).nullable(),+ providerType: z.enum(['api', 'cli', 'tui']).nullable(),+ model: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.modelChars).nullable(),+ effort: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.effortChars).nullable(),+ thinkingPresetId: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars).nullable(),+ thinkingPresetLabel: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.labelChars).nullable(),+ temporaryRoute: z.boolean(),+ elapsedMs: z.number().int().nonnegative().nullable(),+ outcome: z.enum(PERSISTENT_MIND_CALL_OUTCOMES),+ reason: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.reasonChars).nullable(),+ usage: usageSchema,+ displayText: z.string().min(1).max(PERSISTENT_MIND_CALL_RECEIPT_LIMITS.displayChars),+}).strict();++/**+ * Normalize whatever a provider result carried into an explicit usage record.+ *+ * @param {*} raw - a provider `usage` block, or nothing at all+ * @returns {{state: string, source: string, inputTokens: number|null,+ * outputTokens: number|null, totalTokens: number|null, costUsd: number|null}}+ */+export function normalizePersistentMindCallUsage(raw) {+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ const inputTokens = firstReported(source.inputTokens, source.input_tokens, source.promptTokens, source.prompt_tokens);+ const outputTokens = firstReported(source.outputTokens, source.output_tokens, source.completionTokens, source.completion_tokens);+ const reportedTotal = firstReported(source.totalTokens, source.total_tokens);+ const totalTokens = reportedTotal ?? (+ inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null+ );+ // Only explicitly-denominated fields: a bare `cost` could be cents, and a+ // misread price is worse than an unknown one.+ const costUsd = firstReported(source.costUsd, source.cost_usd);+ const reported = [inputTokens, outputTokens, reportedTotal, costUsd].some((value) => value !== null);+ return {+ state: reported ? 'reported' : 'unknown',+ source: reported ? 'provider-reported' : 'unavailable',+ inputTokens,+ outputTokens,+ totalTokens: reported ? totalTokens : null,+ costUsd,+ };+}++/**+ * A refusal thrown by the per-call boundary — the call NEVER reached a+ * provider. It lives here rather than in the guard because several readers must+ * tell it apart from a provider failure without importing the guard's own+ * dependency graph: a refused summary must leave its range UNATTEMPTED, while a+ * summarizer that really ran and failed seals a failed rollup.+ */+export function buildPersistentMindCallDenial({ reason, status, requiresResubmission = false }) {+ return Object.assign(new Error(reason), {+ persistentMindCallDenied: true,+ deniedStatus: status,+ requiresResubmission: requiresResubmission === true,+ });+}++/** Was this thrown by the boundary refusing a call, rather than by the call? */+export function isPersistentMindCallDenial(error) {+ return error?.persistentMindCallDenied === true;+}++const receiptDisplayText = ({ purpose, round, providerId, model, outcome, elapsedMs, usage }) => {+ const route = [providerId || 'unknown-provider', model || 'default-model'].join('/');+ const roundLabel = round === null ? '' : ` round ${round}`;+ const elapsed = elapsedMs === null ? 'elapsed unknown' : `${elapsedMs}ms`;+ const tokens = usage.state === 'reported' && usage.totalTokens !== null+ ? `${usage.totalTokens} tokens`+ : 'usage unknown';+ return `${purpose}${roundLabel} on ${route} — ${outcome} (${elapsed}, ${tokens})`+ .slice(0, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.displayChars);+};++/**+ * Build one validated receipt for a provider call attempt.+ *+ * Every field is read by name. `route` is a plain descriptor, never the live+ * provider record — passing a provider object here would only contribute its+ * `id`/`type`, and any extra key fails the strict parse.+ *+ * @param {object} input+ * @param {string} input.turnId+ * @param {string} [input.purpose] - one of PERSISTENT_MIND_CALL_PURPOSES+ * @param {number} [input.round] - provider round within the turn, when it has one+ * @param {string} [input.runId] - the concrete run id the provider call created+ * @param {object} [input.route] - { providerId, providerType, model, effort,+ * thinkingPresetId, thinkingPresetLabel, temporary }+ * @param {number} [input.elapsedMs] - wall time of the attempt; null when it never started+ * @param {string} input.outcome - one of PERSISTENT_MIND_CALL_OUTCOMES+ * @param {string} [input.reason] - denial/failure reason+ * @param {*} [input.usage] - raw provider usage block, if any+ * @returns {object} validated receipt payload+ */+export function buildPersistentMindCallReceipt({+ turnId,+ purpose,+ round = null,+ runId = null,+ route = {},+ elapsedMs = null,+ outcome,+ reason = null,+ usage = null,+} = {}) {+ const usageRecord = normalizePersistentMindCallUsage(usage);+ const providerType = route.providerType === 'api' || route.providerType === 'cli' || route.providerType === 'tui'+ ? route.providerType+ : null;+ const core = {+ schemaVersion: 1,+ purpose,+ round: Number.isSafeInteger(round) && round >= 0 ? round : null,+ turnId: nullableBounded(turnId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ runId: nullableBounded(runId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ providerId: nullableBounded(route.providerId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ providerType,+ model: nullableBounded(route.model, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.modelChars),+ effort: nullableBounded(route.effort, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.effortChars),+ thinkingPresetId: nullableBounded(route.thinkingPresetId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ thinkingPresetLabel: nullableBounded(route.thinkingPresetLabel, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.labelChars),+ temporaryRoute: route.temporary === true,+ elapsedMs: Number.isFinite(elapsedMs) && elapsedMs >= 0 ? Math.round(elapsedMs) : null,+ outcome,+ reason: nullableBounded(reason, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.reasonChars),+ usage: usageRecord,+ };+ return persistentMindCallReceiptSchema.parse({+ ...core,+ displayText: receiptDisplayText(core),+ });+}++/**+ * Project one stored receipt into the safe public shape the Mind history+ * endpoint serves. Reads named fields only, so a ledger line written by a newer+ * build cannot smuggle an unknown key through the projection.+ */+export function publicPersistentMindCallReceipt(event) {+ const data = event?.data && typeof event.data === 'object' ? event.data : {};+ const usage = normalizePersistentMindCallUsage(data.usage);+ return {+ eventId: typeof event?.eventId === 'string' ? event.eventId : null,+ at: typeof event?.at === 'string' ? event.at : null,+ purpose: PERSISTENT_MIND_CALL_PURPOSES.includes(data.purpose) ? data.purpose : null,+ round: Number.isSafeInteger(data.round) ? data.round : null,+ runId: nullableBounded(data.runId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ providerId: nullableBounded(data.providerId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ model: nullableBounded(data.model, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.modelChars),+ effort: nullableBounded(data.effort, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.effortChars),+ thinkingPresetId: nullableBounded(data.thinkingPresetId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ thinkingPresetLabel: nullableBounded(data.thinkingPresetLabel, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.labelChars),+ temporaryRoute: data.temporaryRoute === true,+ elapsedMs: Number.isSafeInteger(data.elapsedMs) && data.elapsedMs >= 0 ? data.elapsedMs : null,+ outcome: PERSISTENT_MIND_CALL_OUTCOMES.includes(data.outcome) ? data.outcome : null,+ reason: nullableBounded(data.reason, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.reasonChars),+ usage,+ };+}++/**+ * The per-turn execution summary the Mind history endpoint serves.+ *+ * Deliberately narrower than the full replay projection: turn identity, the+ * route the turn actually ran on, and its receipts. No message bodies, no+ * annotations, no free-form model text — a caller asking "what did this turn+ * spend, on what, and how did it end" gets exactly that.+ *+ * Turns with no receipts are omitted rather than served as empty rows: a turn+ * from before per-call receipts existed has unknown telemetry, and an empty+ * `calls` array would read as "it made no provider calls".+ */+export function publicPersistentMindTurnExecutions(projection, limit = 25) {+ const turns = Array.isArray(projection?.turns) ? projection.turns : [];+ return turns+ .filter((turn) => Array.isArray(turn?.calls) && turn.calls.length > 0)+ .slice(-Math.max(1, limit))+ .map((turn) => ({+ turnId: nullableBounded(turn.id, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ status: nullableBounded(turn.status, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.effortChars),+ startedAt: typeof turn.startedAt === 'string' ? turn.startedAt : null,+ completedAt: typeof turn.completedAt === 'string' ? turn.completedAt : null,+ providerId: nullableBounded(turn.providerId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ model: nullableBounded(turn.model, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.modelChars),+ effort: nullableBounded(turn.effort, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.effortChars),+ thinkingPresetId: nullableBounded(turn.thinkingPresetId, PERSISTENT_MIND_CALL_RECEIPT_LIMITS.idChars),+ calls: turn.calls,+ }));+}diff --git a/server/lib/persistentMindTrajectory.test.js b/server/lib/persistentMindTrajectory.test.jsindex 9fad72d4e6..41c1f5cfc2 100644--- a/server/lib/persistentMindTrajectory.test.js+++ b/server/lib/persistentMindTrajectory.test.js@@ -6,6 +6,10 @@ import {parsePersistentMindCursor,persistentMindEventCursor,projectPersistentMind,+ buildPersistentMindCallReceipt,+ normalizePersistentMindCallUsage,+ publicPersistentMindCallReceipt,+ publicPersistentMindTurnExecutions,} from './persistentMindTrajectory.js';const event = ({@@ -148,3 +152,248 @@ describe('assemblePersistentMindContext', () => {.toBe('stale');});});++describe('per-call execution receipts in the replay projection', () => {+ const receipt = (sequence, overrides) => event({+ eventId: `call-${sequence}`,+ sequence,+ kind: 'mind.model.call',+ turnId: 'turn-1',+ data: {+ schemaVersion: 1,+ purpose: 'turn',+ round: 0,+ turnId: 'turn-1',+ runId: `run-${sequence}`,+ providerId: 'example-api',+ providerType: 'api',+ model: 'example-model',+ effort: 'high',+ thinkingPresetId: 'preset-deep',+ thinkingPresetLabel: 'Deep think',+ temporaryRoute: true,+ elapsedMs: 120,+ outcome: 'completed',+ reason: null,+ usage: { state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null },+ displayText: 'turn round 0 on example-api/example-model — completed (120ms, usage unknown)',+ ...overrides,+ },+ });++ it('attaches each receipt to its turn with the route the call actually ran on', () => {+ const projection = projectPersistentMind([+ event({ eventId: 'wake-1', sequence: 1, kind: 'mind.wake', turnId: 'turn-1' }),+ receipt(2),+ receipt(3, { purpose: 'tool-round', round: 1, outcome: 'failed', reason: 'provider stream ended' }),+ event({ eventId: 'done-1', sequence: 4, kind: 'mind.turn.completed', turnId: 'turn-1' }),+ ]);+ const [turn] = projection.turns;+ expect(turn).toMatchObject({+ id: 'turn-1',+ status: 'completed',+ providerId: 'example-api',+ model: 'example-model',+ effort: 'high',+ thinkingPresetId: 'preset-deep',+ });+ expect(turn.calls.map((call) => [call.purpose, call.outcome, call.runId])).toEqual([+ ['turn', 'completed', 'run-2'],+ ['tool-round', 'failed', 'run-3'],+ ]);+ expect(turn.calls[0]).toMatchObject({ elapsedMs: 120, temporaryRoute: true, thinkingPresetLabel: 'Deep think' });+ expect(turn.calls[0].usage).toMatchObject({ state: 'unknown', totalTokens: null });+ });++ it('leaves a turn recorded before receipts existed with no telemetry rather than zeroes', () => {+ const projection = projectPersistentMind([+ event({ eventId: 'wake-old', sequence: 1, kind: 'mind.wake', turnId: 'turn-old' }),+ event({+ eventId: 'request-old',+ sequence: 2,+ kind: 'mind.model.request',+ turnId: 'turn-old',+ data: { providerId: 'example-api', model: 'example-model', effort: 'high' },+ }),+ event({ eventId: 'done-old', sequence: 3, kind: 'mind.turn.completed', turnId: 'turn-old' }),+ ]);+ expect(projection.turns[0]).toMatchObject({+ status: 'completed',+ providerId: 'example-api',+ calls: [],+ thinkingPresetId: null,+ });+ });+});++const route = {+ providerId: 'example-api',+ providerType: 'api',+ model: 'example-model',+ effort: 'high',+ thinkingPresetId: 'preset-deep',+ thinkingPresetLabel: 'Deep think',+ temporary: true,+};++describe('normalizePersistentMindCallUsage', () => {+ it('reports absent telemetry as unknown rather than zero', () => {+ for (const raw of [undefined, null, {}, [], 'nope', { inputTokens: 'many' }, { costUsd: NaN }]) {+ expect(normalizePersistentMindCallUsage(raw)).toEqual({+ state: 'unknown',+ source: 'unavailable',+ inputTokens: null,+ outputTokens: null,+ totalTokens: null,+ costUsd: null,+ });+ }+ });++ it('keeps a genuinely reported zero distinct from missing telemetry', () => {+ expect(normalizePersistentMindCallUsage({ inputTokens: 0, outputTokens: 0 })).toMatchObject({+ state: 'reported',+ source: 'provider-reported',+ inputTokens: 0,+ outputTokens: 0,+ totalTokens: 0,+ });+ });++ it('derives a total only when both halves were reported, and prefers a reported total', () => {+ expect(normalizePersistentMindCallUsage({ input_tokens: 120, output_tokens: 30 }).totalTokens).toBe(150);+ expect(normalizePersistentMindCallUsage({ inputTokens: 120 }).totalTokens).toBeNull();+ expect(normalizePersistentMindCallUsage({ inputTokens: 1, outputTokens: 1, totalTokens: 9 }).totalTokens).toBe(9);+ });++ it('treats a cost-only report as reported usage with unknown token counts', () => {+ expect(normalizePersistentMindCallUsage({ costUsd: 0.42 })).toMatchObject({+ state: 'reported',+ costUsd: 0.42,+ inputTokens: null,+ totalTokens: null,+ });+ });+});++describe('buildPersistentMindCallReceipt', () => {+ it('records the actual route, run id, elapsed time and outcome of one attempt', () => {+ const receipt = buildPersistentMindCallReceipt({+ turnId: 'mind-turn-1',+ purpose: 'tool-round',+ round: 2,+ runId: 'run-7',+ route,+ elapsedMs: 1234.6,+ outcome: 'completed',+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ expect(receipt).toMatchObject({+ schemaVersion: 1,+ purpose: 'tool-round',+ round: 2,+ turnId: 'mind-turn-1',+ runId: 'run-7',+ providerId: 'example-api',+ providerType: 'api',+ model: 'example-model',+ effort: 'high',+ thinkingPresetId: 'preset-deep',+ thinkingPresetLabel: 'Deep think',+ temporaryRoute: true,+ elapsedMs: 1235,+ outcome: 'completed',+ reason: null,+ });+ expect(receipt.displayText).toContain('example-api/example-model');+ });++ it('leaves elapsed time null for a call that never started', () => {+ const receipt = buildPersistentMindCallReceipt({+ turnId: 'mind-turn-1',+ purpose: 'summary',+ route,+ outcome: 'denied',+ reason: 'CoS actions budget exhausted',+ });+ expect(receipt.elapsedMs).toBeNull();+ expect(receipt.runId).toBeNull();+ expect(receipt.usage.state).toBe('unknown');+ expect(receipt.displayText).toContain('elapsed unknown');+ });++ it('cannot carry provider configuration, prompts, or hidden reasoning', () => {+ const receipt = buildPersistentMindCallReceipt({+ turnId: 'mind-turn-1',+ purpose: 'turn',+ round: 0,+ route: {+ ...route,+ apiKey: 'sk-secret-value',+ endpoint: 'https://provider.example.com/v1',+ headers: { authorization: 'Bearer sk-secret-value' },+ },+ elapsedMs: 5,+ outcome: 'completed',+ usage: { inputTokens: 3, apiKey: 'sk-secret-value', reasoning: 'hidden chain of thought' },+ });+ const serialized = JSON.stringify(receipt);+ expect(serialized).not.toContain('sk-secret-value');+ expect(serialized).not.toContain('provider.example.com');+ expect(serialized).not.toContain('hidden chain of thought');+ expect(Object.keys(receipt).sort()).toEqual([+ 'displayText', 'effort', 'elapsedMs', 'model', 'outcome', 'providerId', 'providerType',+ 'purpose', 'reason', 'round', 'runId', 'schemaVersion', 'temporaryRoute', 'thinkingPresetId',+ 'thinkingPresetLabel', 'turnId', 'usage',+ ]);+ expect(Object.keys(receipt.usage).sort()).toEqual([+ 'costUsd', 'inputTokens', 'outputTokens', 'source', 'state', 'totalTokens',+ ]);+ });++ it('refuses an unknown outcome or purpose rather than storing it', () => {+ expect(() => buildPersistentMindCallReceipt({+ turnId: 'mind-turn-1', purpose: 'turn', route, outcome: 'maybe',+ })).toThrow();+ expect(() => buildPersistentMindCallReceipt({+ turnId: 'mind-turn-1', purpose: 'gossip', route, outcome: 'completed',+ })).toThrow();+ });+});++describe('publicPersistentMindCallReceipt', () => {+ it('projects only allowlisted fields from a stored event', () => {+ const projected = publicPersistentMindCallReceipt({+ eventId: 'mind-model-call:mind-turn-1:0',+ at: '2026-01-01T00:00:00.000Z',+ data: {+ purpose: 'turn',+ round: 0,+ runId: 'run-7',+ providerId: 'example-api',+ model: 'example-model',+ effort: 'high',+ thinkingPresetId: 'preset-deep',+ thinkingPresetLabel: 'Deep think',+ temporaryRoute: true,+ elapsedMs: 90,+ outcome: 'completed',+ usage: { inputTokens: 10, outputTokens: 2 },+ // A newer build's extra key, and something that must never be served.+ futureField: 'ignored',+ apiKey: 'sk-secret-value',+ },+ });+ expect(JSON.stringify(projected)).not.toContain('sk-secret-value');+ expect(projected).toMatchObject({ purpose: 'turn', runId: 'run-7', elapsedMs: 90, outcome: 'completed' });+ expect(projected.usage).toMatchObject({ state: 'reported', totalTokens: 12 });+ expect(Object.keys(projected)).not.toContain('futureField');+ });++ it('reads an unrecognized purpose/outcome as null instead of passing it through', () => {+ const projected = publicPersistentMindCallReceipt({ data: { purpose: 'gossip', outcome: 'maybe' } });+ expect(projected.purpose).toBeNull();+ expect(projected.outcome).toBeNull();+ expect(projected.usage.state).toBe('unknown');+ });+});diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 5407b21602..761bea9981 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -26,6 +26,7 @@ import {} from '../lib/persistentMindThinkingPresets.js';import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { publicPersistentMindState } from '../lib/persistentMindPublic.js';+import { publicPersistentMindTurnExecutions } from '../lib/persistentMindTrajectory.js';import { validateRequest } from '../lib/validation.js';import { readPersistentMindEvents, readPersistentMindHistory } from '../services/agentRunEventLog.js';import { loadState } from '../services/cosState.js';@@ -187,9 +188,13 @@ router.get('/mind', asyncHandler(async (req, res) => {const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);const provider = profile.providerId ? await getProviderById(profile.providerId) : null;const imageCapability = await resolvePersistentMindImageCapability({ provider, model: profile.model });- const { snapshot: _snapshot, ...publicHistory } = history;+ // The full replay projection carries message bodies; only the per-turn+ // execution receipts (route, run ids, elapsed time, outcome, usage) are safe+ // to serve, and they are what answers 'what did this turn actually spend'.+ const { snapshot, ...publicHistory } = history;res.json({...publicHistory,+ turnExecutions: publicPersistentMindTurnExecutions(snapshot),state: publicPersistentMindState(state),profile: {enabled: profile.enabled,diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex f01d99fe8c..ddcd4d897c 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -196,6 +196,62 @@ describe('persistent mind routes', () => {expect(JSON.stringify(res.body)).not.toContain('secret-value');});+ it('exposes per-call execution receipts for completed and failed turns without their message bodies', async () => {+ mocks.readPersistentMindEvents.mockResolvedValue({+ events: [], cursor: null, gap: false, hasMore: false,+ snapshot: {+ messages: [{ messageId: 'private', text: 'must not leak' }],+ turns: [+ // A turn from before receipts existed contributes no row at all.+ { id: 'turn-old', status: 'completed', providerId: 'demo', model: 'demo-model', calls: [] },+ {+ id: 'turn-temp',+ status: 'failed',+ startedAt: '2026-08-27T12:00:00.000Z',+ completedAt: '2026-08-27T12:00:05.000Z',+ providerId: 'demo-alt',+ model: 'alt-model',+ effort: 'max',+ thinkingPresetId: 'preset-deep',+ calls: [+ {+ purpose: 'turn', round: 0, runId: 'run-1', providerId: 'demo-alt', model: 'alt-model',+ effort: 'max', thinkingPresetId: 'preset-deep', thinkingPresetLabel: 'Deep think',+ temporaryRoute: true, elapsedMs: 900, outcome: 'completed',+ usage: { state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null },+ },+ {+ purpose: 'tool-round', round: 1, runId: null, providerId: 'demo-alt', model: 'alt-model',+ effort: 'max', thinkingPresetId: 'preset-deep', thinkingPresetLabel: 'Deep think',+ temporaryRoute: true, elapsedMs: null, outcome: 'denied', reason: 'CoS actions budget exhausted',+ usage: { state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null },+ },+ ],+ },+ ],+ },+ });++ const res = await get('/mind');+ expect(res.status).toBe(200);+ expect(res.body.turnExecutions).toHaveLength(1);+ expect(res.body.turnExecutions[0]).toMatchObject({+ turnId: 'turn-temp',+ status: 'failed',+ providerId: 'demo-alt',+ model: 'alt-model',+ effort: 'max',+ thinkingPresetId: 'preset-deep',+ });+ expect(res.body.turnExecutions[0].calls.map((call) => [call.purpose, call.outcome, call.elapsedMs])).toEqual([+ ['turn', 'completed', 900],+ ['tool-round', 'denied', null],+ ]);+ expect(res.body.turnExecutions[0].calls[0].usage).toMatchObject({ state: 'unknown', totalTokens: null });+ expect(res.body).not.toHaveProperty('snapshot');+ expect(JSON.stringify(res.body)).not.toContain('must not leak');+ });+it('exposes the editable prompt, owned memories, derived rollups, and exact context preview', async () => {const res = await get('/mind/context');expect(res.status).toBe(200);diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex f1ed449605..9e07873ed1 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -261,7 +261,14 @@ export function buildPersistentMindSummaryPrompt({ events, previousSummary }) {return `Summarize this older portion of one persistent mind's life in first person. Preserve concrete decisions, unresolved questions, user preferences, and causal links. Do not invent facts. Return plain text only, no heading.\n\n${previousSummary ? `Prior cumulative summary:\n${previousSummary}\n\n` : ''}New trajectory events:\n${summaryEventLines(events)}`;}-async function runPinnedPrompt({ provider, model, effort, prompt, screenshots = [], signal, responseSchema, heartbeat }) {+/**+ * 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;@@ -292,6 +299,9 @@ async function runPinnedPrompt({ provider, model, effort, prompt, screenshots =responseSchema,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) => {@@ -323,19 +333,20 @@ export function createPersistentMindTurnAdapter() {};},- async summarize({ events, previousSummary, provider, model, effort, signal, heartbeat }) {- const result = await runPinnedPrompt({+ async summarize({ events, previousSummary, provider, model, effort, signal, heartbeat, callBoundary = passthroughCallBoundary }) {+ const result = await callBoundary({ purpose: 'summary' }, ({ reportRunId }) => runPinnedPrompt({provider,model,effort,signal,heartbeat,+ reportRunId,prompt: buildPersistentMindSummaryPrompt({ events, previousSummary }),- });+ }));return result.text.trim();},- async run({ turnId, wake, provider, model, effort, signal, context, heartbeat, recordCapabilityEvent }) {+ 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);@@ -385,16 +396,22 @@ export function createPersistentMindTurnAdapter() {const completedToolResults = [];const actionNotices = new Set();for (let round = 0; round < MAX_TOOL_PROVIDER_ROUNDS; round += 1) {- result = await runPinnedPrompt({- provider,- model,- effort,- signal,- heartbeat,- screenshots,- prompt: providerPrompt,- responseSchema: persistentMindResponseSchema,- });+ // 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.+ result = await callBoundary(+ { purpose: round === 0 ? 'turn' : 'tool-round', round },+ ({ reportRunId }) => runPinnedPrompt({+ provider,+ model,+ effort,+ signal,+ heartbeat,+ screenshots,+ reportRunId,+ prompt: providerPrompt,+ responseSchema: persistentMindResponseSchema,+ }),+ );parsed = persistentMindResponseSchema.parse(parseLLMJSON(result.text));const finalProviderRound = round === MAX_TOOL_PROVIDER_ROUNDS - 1;if (finalProviderRound && parsed.toolCalls.length > 0) {diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex 5760cee51e..b81b876a0f 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -512,6 +512,98 @@ describe('persistent mind adapter', () => {}});+ it('admits the summary and every tool round through the per-call boundary', async () => {+ mock.root.config.persistentMindCapabilities = { readPortos: true };+ mock.runPrompt+ .mockResolvedValueOnce({ text: 'An earlier stretch of my life.' })+ .mockResolvedValueOnce({ text: JSON.stringify({+ thinkingSummary: 'I need the catalog result.',+ toolCalls: [{ name: 'catalog.search', arguments: { query: 'example' } }],+ }) })+ .mockResolvedValueOnce({ text: JSON.stringify({+ thinkingSummary: 'I used the catalog result.',+ message: 'I found one match.',+ toolCalls: [],+ }) });+ const admitted = [];+ const callBoundary = vi.fn(async (descriptor, run) => {+ admitted.push(descriptor);+ return run({ reportRunId: () => {} });+ });+ const adapter = createPersistentMindTurnAdapter();++ await adapter.summarize({+ events: [{ id: 'event-1', kind: 'mind.reply' }],+ previousSummary: null,+ ...profile,+ signal: new AbortController().signal,+ callBoundary,+ });+ await adapter.run({+ turnId: 'turn-boundary',+ wake: { kind: 'message', message: { id: 'message-boundary', text: 'Find the example.' } },+ ...profile,+ signal: new AbortController().signal,+ context: { text: '# Context' },+ recordCapabilityEvent: vi.fn(async () => true),+ callBoundary,+ });++ expect(admitted).toEqual([+ { purpose: 'summary' },+ { purpose: 'turn', round: 0 },+ { purpose: 'tool-round', round: 1 },+ ]);+ expect(mock.runPrompt).toHaveBeenCalledTimes(3);+ });++ it('starts no further provider call once the boundary denies a later round', async () => {+ mock.root.config.persistentMindCapabilities = { readPortos: true };+ mock.runPrompt.mockResolvedValue({ text: JSON.stringify({+ thinkingSummary: 'Still working.',+ toolCalls: [{ name: 'catalog.search', arguments: { query: 'example' } }],+ }) });+ const callBoundary = vi.fn(async (descriptor, run) => {+ if (descriptor.round > 0) throw Object.assign(new Error('CoS actions budget exhausted'), { persistentMindCallDenied: true });+ return run({ reportRunId: () => {} });+ });++ await expect(createPersistentMindTurnAdapter().run({+ turnId: 'turn-denied',+ wake: { kind: 'message', message: { id: 'message-denied', text: 'Keep searching.' } },+ ...profile,+ signal: new AbortController().signal,+ context: { text: '# Context' },+ recordCapabilityEvent: vi.fn(async () => true),+ callBoundary,+ })).rejects.toThrow('CoS actions budget exhausted');++ // The first round ran and its tool executed; the denial stopped the second+ // round before the provider was reached again.+ expect(mock.runPrompt).toHaveBeenCalledTimes(1);+ expect(mock.executeToolCall).toHaveBeenCalledTimes(1);+ });++ it('reports the concrete run id to the boundary as soon as the provider creates it', async () => {+ mock.runPrompt.mockImplementation(async ({ onRunCreated }) => {+ onRunCreated?.('run-42');+ throw new Error('provider stream ended without a response');+ });+ const reported = [];+ const callBoundary = vi.fn((_descriptor, run) => run({ reportRunId: (id) => reported.push(id) }));++ await expect(createPersistentMindTurnAdapter().run({+ turnId: 'turn-runid',+ wake: { kind: 'message', message: { id: 'message-runid', text: 'Hello.' } },+ ...profile,+ signal: new AbortController().signal,+ context: { text: '# Context' },+ recordCapabilityEvent: vi.fn(async () => true),+ callBoundary,+ })).rejects.toThrow('provider stream ended without a response');+ expect(reported).toEqual(['run-42']);+ });+it('makes the provider harness tradeoff explicit', () => {expect(persistentMindHarnessInfo({ type: 'api' }).recommendation).toBe('recommended');expect(persistentMindHarnessInfo({ type: 'cli' }).recommendation).toBe('supported');diff --git a/server/services/persistentMindCallGuard.js b/server/services/persistentMindCallGuard.jsnew file mode 100644index 0000000000..4b058a9043--- /dev/null+++ b/server/services/persistentMindCallGuard.js@@ -0,0 +1,208 @@+/**+ * The per-call boundary every persistent-mind provider call passes through.+ *+ * The supervisor admits a TURN: one global slot, one action reservation, one+ * local-endpoint slot, one budget check. But a turn is not one provider call —+ * the optional context summary is one, the turn itself is another, and each+ * tool round after it is another again. Checking admission once and accounting+ * one action for that whole span meant a mind could keep spending after the+ * budget was exhausted, after its preset was revoked, or after the user stopped+ * it, and the ledger only ever heard about it once.+ *+ * So this module re-checks the things that can change WHILE a turn runs — the+ * live exact route, provider availability/authorization, mind lifecycle,+ * capability grants, remaining budget — immediately before each call, and+ * accounts every attempt that actually started, failures included.+ *+ * It deliberately acquires NOTHING. The turn already holds the global slot, the+ * action reservation, and the endpoint slot; taking nested ones here would+ * deadlock a turn against its own admission. This boundary only ever refuses.+ */++import { getDomainMode } from '../lib/domainAutonomy.js';+import { canonicalStringify } from '../lib/objects.js';+import { normalizePersistentMindState } from '../lib/persistentMind.js';+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';+import { buildPersistentMindCallDenial, buildPersistentMindCallReceipt } from '../lib/persistentMindTrajectory.js';+import { loadState } from './cosState.js';+import { appendMindEvent } from './agentRunEventLog.js';+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';+import { resolvePersistentMindProfile, resolvePersistentMindThinkingSession } from './persistentMindProfile.js';++/** Mind status a denial should park the turn under, by cause. */+const DENIAL_STATUS = Object.freeze({+ interrupted: 'interrupted',+ budget: 'waiting',+ authorization: 'degraded',+});++const denial = (reason, status, extra = {}) => ({ ok: false, reason, status, ...extra });++/**+ * The comparable fingerprint of the mind's capability grants.+ *+ * Any change — widening or narrowing — ends the turn's remaining calls. The+ * turn's prompt, its tool catalog, and its already-executed rounds were all+ * built against the snapshot, so continuing on a different grant set would run+ * the second half of a turn under authority the first half never described.+ */+export function persistentMindCapabilityGrantFingerprint(rawCapabilities) {+ return canonicalStringify(normalizePersistentMindCapabilities(rawCapabilities)) ?? '';+}++/**+ * Decide whether one more provider call may start on this turn.+ *+ * Ordered cheapest-and-most-decisive first: an aborted turn or a stopped mind+ * short-circuits before any provider registry or budget read.+ *+ * @param {object} input+ * @param {string} input.turnId - the turn that must still be the active one+ * @param {object} input.route - { providerId, model, effort } pinned at admission+ * @param {string} [input.thinkingPresetId] - set for a temporary thinking session+ * @param {object} [input.thinkingSelection] - the ACCEPTED preset snapshot (#6283);+ * never re-derived from the mutable preset id+ * @param {string} [input.capabilityFingerprint] - snapshot from turn admission+ * @param {AbortSignal} [input.signal]+ * @returns {Promise<{ok: boolean, reason?: string, status?: string, requiresResubmission?: boolean}>}+ */+export async function evaluatePersistentMindCallAdmission({+ turnId,+ route,+ thinkingPresetId = null,+ thinkingSelection = null,+ capabilityFingerprint = null,+ signal,+} = {}) {+ if (signal?.aborted) {+ return denial(String(signal.reason || 'Persistent mind turn interrupted'), DENIAL_STATUS.interrupted);+ }++ const root = await loadState();+ if (root?.paused) return denial('PortOS autonomy was paused during the turn', DENIAL_STATUS.interrupted);+ if (getDomainMode(root?.config, 'cos') !== 'execute') {+ return denial('CoS autonomy left execute mode during the turn', DENIAL_STATUS.interrupted);+ }++ const mind = normalizePersistentMindState(root?.persistentMind);+ if (!mind.enabled || !mind.started) return denial('Persistent mind was stopped during the turn', DENIAL_STATUS.interrupted);+ if (mind.status === 'paused') return denial('Persistent mind was paused during the turn', DENIAL_STATUS.interrupted);+ if (mind.activeTurn?.id !== turnId) return denial('Persistent mind turn is no longer the active turn', DENIAL_STATUS.interrupted);++ if (capabilityFingerprint !== null+ && persistentMindCapabilityGrantFingerprint(root?.config?.persistentMindCapabilities) !== capabilityFingerprint) {+ return denial('Persistent mind capability grants changed during the turn', DENIAL_STATUS.authorization);+ }++ // Provider availability/authorization and preset lifecycle both resolve here:+ // the same exact-or-refuse resolvers the supervisor admitted the turn with.+ const resolved = thinkingPresetId+ ? await resolvePersistentMindThinkingSession({ presetId: thinkingPresetId, selection: thinkingSelection, config: root?.config })+ : await resolvePersistentMindProfile(root?.config?.persistentMindProfile);+ if (!resolved.ok) {+ return denial(resolved.error, DENIAL_STATUS.authorization, { requiresResubmission: resolved.requiresResubmission === true });+ }+ if ((resolved.provider?.id || null) !== (route?.providerId || null)+ || (resolved.model || null) !== (route?.model || null)+ || (resolved.effort || null) !== (route?.effort || null)) {+ return denial('Persistent mind route changed during the turn', DENIAL_STATUS.authorization);+ }++ // Fail closed: an unreadable ledger must not read as unlimited budget.+ let budget;+ try {+ budget = await getDomainBudgetStatus('cos');+ } catch (error) {+ return denial(`Persistent mind budget check failed: ${error?.message || 'unknown error'}`, DENIAL_STATUS.budget);+ }+ if (!budget.withinBudget) {+ return denial(`CoS ${budget.exceeded || 'daily'} budget exhausted`, DENIAL_STATUS.budget);+ }++ return { ok: true };+}++/**+ * Build the per-turn boundary the supervisor hands to the adapter.+ *+ * `call({ purpose, round }, run)` re-checks admission, runs `run`, times it,+ * accounts it against the domain ledger, and writes one bounded receipt to the+ * trajectory — for completed, failed, interrupted AND denied attempts. `run`+ * receives `{ reportRunId }` so the receipt names the concrete provider run id+ * even when the call throws before returning one.+ *+ * @returns {{call: Function, accountedCalls: () => number}}+ */+export function createPersistentMindCallBoundary({+ mindId,+ turnId,+ route,+ thinkingPresetId = null,+ thinkingSelection = null,+ capabilityFingerprint = null,+ signal,+ now = () => Date.now(),+ evaluate = evaluatePersistentMindCallAdmission,+ appendEvent = appendMindEvent,+ recordUsage = recordDomainUsage,+} = {}) {+ let receiptIndex = 0;+ let accountedCalls = 0;++ const writeReceipt = async (fields) => {+ const index = receiptIndex;+ receiptIndex += 1;+ const receipt = buildPersistentMindCallReceipt({ turnId, route, ...fields });+ await appendEvent({+ kind: 'mind.model.call',+ mindId,+ turnId,+ eventId: `mind-model-call:${turnId}:${index}`,+ data: receipt,+ });+ return receipt;+ };++ const account = async (elapsedMs) => {+ accountedCalls += 1;+ await recordUsage('cos', { actions: 1, ms: elapsedMs }).catch((error) => {+ console.error(`❌ Failed to record persistent mind call usage: ${error.message}`);+ });+ };++ const call = async ({ purpose, round = null } = {}, run) => {+ const admission = await evaluate({ turnId, route, thinkingPresetId, thinkingSelection, capabilityFingerprint, signal });+ if (!admission.ok) {+ await writeReceipt({ purpose, round, outcome: 'denied', reason: admission.reason });+ throw buildPersistentMindCallDenial(admission);+ }+ let runId = null;+ const reportRunId = (id) => { if (typeof id === 'string' && id) runId = id; };+ const startedAt = now();+ try {+ const result = await run({ reportRunId });+ const elapsedMs = Math.max(0, now() - startedAt);+ reportRunId(result?.runId);+ await account(elapsedMs);+ await writeReceipt({ purpose, round, runId, elapsedMs, outcome: 'completed', usage: result?.usage });+ return result;+ } catch (error) {+ const elapsedMs = Math.max(0, now() - startedAt);+ // The attempt reached the provider, so it is accounted even though it+ // produced nothing — an uncertain spend is still a spend, and never a+ // reason to silently retry.+ await account(elapsedMs);+ await writeReceipt({+ purpose,+ round,+ runId,+ elapsedMs,+ outcome: signal?.aborted ? 'interrupted' : 'failed',+ reason: error?.message,+ });+ throw error;+ }+ };++ return { call, accountedCalls: () => accountedCalls };+}diff --git a/server/services/persistentMindCallGuard.test.js b/server/services/persistentMindCallGuard.test.jsnew file mode 100644index 0000000000..41153b889e--- /dev/null+++ b/server/services/persistentMindCallGuard.test.js@@ -0,0 +1,290 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mock = vi.hoisted(() => ({+ root: null,+ budget: { withinBudget: true, exceeded: null },+ budgetError: null,+ profile: null,+ thinkingSession: null,+ appendMindEvent: vi.fn(async () => ({ appended: true })),+ recordDomainUsage: vi.fn(async () => {}),+}));++vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mock.root) }));+vi.mock('./agentRunEventLog.js', () => ({ appendMindEvent: (...args) => mock.appendMindEvent(...args) }));+vi.mock('./domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn(async () => {+ if (mock.budgetError) throw mock.budgetError;+ return mock.budget;+ }),+ recordDomainUsage: (...args) => mock.recordDomainUsage(...args),+}));+vi.mock('./persistentMindProfile.js', () => ({+ resolvePersistentMindProfile: vi.fn(async () => mock.profile),+ resolvePersistentMindThinkingSession: vi.fn(async () => mock.thinkingSession),+}));++const {+ createPersistentMindCallBoundary,+ evaluatePersistentMindCallAdmission,+ persistentMindCapabilityGrantFingerprint,+} = await import('./persistentMindCallGuard.js');+const { isPersistentMindCallDenial } = await import('../lib/persistentMindTrajectory.js');++const TURN_ID = 'mind-turn-1';+const route = { providerId: 'example-api', providerType: 'api', model: 'example-model', effort: 'high' };++const makeRoot = () => ({+ paused: false,+ config: {+ domainAutonomy: { cos: 'execute' },+ persistentMindProfile: { enabled: true, providerId: 'example-api', model: 'example-model', effort: 'high' },+ persistentMindCapabilities: { createTasks: true, readPortos: true },+ },+ persistentMind: {+ enabled: true,+ started: true,+ status: 'thinking',+ activeTurn: {+ id: TURN_ID,+ wake: { id: 'wake-1', kind: 'self', reason: 'scheduled reflection', sourceTurnId: 'mind-turn-0' },+ startedAt: '2026-01-01T00:00:00.000Z',+ },+ },+});++const receipts = () => mock.appendMindEvent.mock.calls+ .filter(([event]) => event.kind === 'mind.model.call')+ .map(([event]) => event);++const boundary = (overrides = {}) => createPersistentMindCallBoundary({+ mindId: 'cos-persistent-mind',+ turnId: TURN_ID,+ route,+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ mock.root = makeRoot();+ mock.budget = { withinBudget: true, exceeded: null };+ mock.budgetError = null;+ mock.profile = { ok: true, provider: { id: 'example-api' }, model: 'example-model', effort: 'high' };+ mock.thinkingSession = { ok: true, provider: { id: 'example-api' }, model: 'example-model', effort: 'high' };+});++describe('evaluatePersistentMindCallAdmission', () => {+ it('admits a call while route, lifecycle, grants and budget all still hold', async () => {+ await expect(evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route })).resolves.toEqual({ ok: true });+ });++ it.each([+ ['the mind was stopped', (root) => { root.persistentMind.started = false; }, 'interrupted'],+ ['the mind was paused', (root) => { root.persistentMind.status = 'paused'; }, 'interrupted'],+ ['the turn is no longer active', (root) => { root.persistentMind.activeTurn = { id: 'other-turn' }; }, 'interrupted'],+ ['PortOS autonomy was paused', (root) => { root.paused = true; }, 'interrupted'],+ ['CoS left execute mode', (root) => { root.config.domainAutonomy.cos = 'dry-run'; }, 'interrupted'],+ ])('denies the next call when %s', async (_label, mutate, status) => {+ mutate(mock.root);+ const admission = await evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route });+ expect(admission.ok).toBe(false);+ expect(admission.status).toBe(status);+ });++ it('denies when the exhausted budget is only reached mid-turn', async () => {+ mock.budget = { withinBudget: false, exceeded: 'actions' };+ const admission = await evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route });+ expect(admission).toMatchObject({ ok: false, status: 'waiting', reason: 'CoS actions budget exhausted' });+ });++ it('fails closed when the budget ledger cannot be read', async () => {+ mock.budgetError = new Error('ledger unreadable');+ const admission = await evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route });+ expect(admission).toMatchObject({ ok: false, status: 'waiting' });+ expect(admission.reason).toContain('ledger unreadable');+ });++ it('denies when the provider became unavailable or the route moved', async () => {+ mock.profile = { ok: false, error: 'Pinned provider "example-api" is unavailable' };+ await expect(evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route })).resolves.toMatchObject({+ ok: false,+ status: 'degraded',+ reason: 'Pinned provider "example-api" is unavailable',+ });++ mock.profile = { ok: true, provider: { id: 'example-api' }, model: 'other-model', effort: 'high' };+ await expect(evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route })).resolves.toMatchObject({+ ok: false,+ reason: 'Persistent mind route changed during the turn',+ });+ });++ it('revalidates a temporary session against its accepted snapshot, not the mutable preset id', async () => {+ mock.thinkingSession = {+ ok: false,+ requiresResubmission: true,+ error: 'Temporary thinking preset changed after acceptance; send a new message to authorize its new route',+ };+ const accepted = { id: 'preset-deep', providerId: 'example-api', model: 'example-model', effort: 'high' };+ const admission = await evaluatePersistentMindCallAdmission({+ turnId: TURN_ID,+ route,+ thinkingPresetId: 'preset-deep',+ thinkingSelection: accepted,+ });+ expect(admission).toMatchObject({ ok: false, status: 'degraded', requiresResubmission: true });++ const { resolvePersistentMindThinkingSession } = await import('./persistentMindProfile.js');+ expect(resolvePersistentMindThinkingSession).toHaveBeenCalledWith(+ expect.objectContaining({ presetId: 'preset-deep', selection: accepted }),+ );+ });++ it('denies once the capability grants differ from the turn snapshot', async () => {+ const fingerprint = persistentMindCapabilityGrantFingerprint(mock.root.config.persistentMindCapabilities);+ await expect(evaluatePersistentMindCallAdmission({+ turnId: TURN_ID, route, capabilityFingerprint: fingerprint,+ })).resolves.toEqual({ ok: true });++ mock.root.config.persistentMindCapabilities = { createTasks: true };+ await expect(evaluatePersistentMindCallAdmission({+ turnId: TURN_ID, route, capabilityFingerprint: fingerprint,+ })).resolves.toMatchObject({+ ok: false,+ status: 'degraded',+ reason: 'Persistent mind capability grants changed during the turn',+ });+ });++ it('short-circuits an aborted turn before reading any provider or budget state', async () => {+ const controller = new AbortController();+ controller.abort('Persistent mind turn interrupted');+ const admission = await evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route, signal: controller.signal });+ expect(admission).toMatchObject({ ok: false, status: 'interrupted' });+ const { resolvePersistentMindProfile } = await import('./persistentMindProfile.js');+ expect(resolvePersistentMindProfile).not.toHaveBeenCalled();+ });+});++describe('createPersistentMindCallBoundary', () => {+ it('accounts each admitted call once and writes a receipt naming the run it created', async () => {+ let clock = 1_000;+ const { call, accountedCalls } = boundary({ now: () => clock });+ const result = await call({ purpose: 'turn', round: 0 }, async ({ reportRunId }) => {+ reportRunId('run-7');+ clock += 250;+ return { text: '{}', runId: 'run-7', usage: { inputTokens: 12, outputTokens: 4 } };+ });++ expect(result.runId).toBe('run-7');+ expect(accountedCalls()).toBe(1);+ expect(mock.recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1, ms: 250 });+ expect(receipts()).toHaveLength(1);+ expect(receipts()[0]).toMatchObject({+ kind: 'mind.model.call',+ turnId: TURN_ID,+ eventId: `mind-model-call:${TURN_ID}:0`,+ });+ expect(receipts()[0].data).toMatchObject({+ purpose: 'turn',+ round: 0,+ runId: 'run-7',+ providerId: 'example-api',+ model: 'example-model',+ effort: 'high',+ elapsedMs: 250,+ outcome: 'completed',+ });+ expect(receipts()[0].data.usage).toMatchObject({ state: 'reported', totalTokens: 16 });+ });++ it('records unknown usage rather than zero when the provider reported none', async () => {+ const { call } = boundary();+ await call({ purpose: 'summary' }, async () => ({ text: 'summary', runId: 'run-1' }));+ expect(receipts()[0].data.usage).toEqual({+ state: 'unknown',+ source: 'unavailable',+ inputTokens: null,+ outputTokens: null,+ totalTokens: null,+ costUsd: null,+ });+ });++ it('never starts a denied call, and does not charge the ledger for one', async () => {+ mock.budget = { withinBudget: false, exceeded: 'minutes' };+ const run = vi.fn();+ const { call, accountedCalls } = boundary();+ await expect(call({ purpose: 'tool-round', round: 1 }, run)).rejects.toMatchObject({+ message: 'CoS minutes budget exhausted',+ deniedStatus: 'waiting',+ });++ expect(run).not.toHaveBeenCalled();+ expect(mock.recordDomainUsage).not.toHaveBeenCalled();+ expect(accountedCalls()).toBe(0);+ expect(receipts()[0].data).toMatchObject({+ purpose: 'tool-round',+ round: 1,+ outcome: 'denied',+ reason: 'CoS minutes budget exhausted',+ elapsedMs: null,+ runId: null,+ });+ });++ it('marks a boundary refusal so a caller can tell it from a provider failure', async () => {+ mock.profile = { ok: false, error: 'Pinned provider "example-api" is unavailable' };+ const { call } = boundary();+ const denial = await call({ purpose: 'turn', round: 0 }, async () => ({})).catch((error) => error);+ expect(isPersistentMindCallDenial(denial)).toBe(true);+ expect(isPersistentMindCallDenial(new Error('provider exploded'))).toBe(false);+ });++ it('propagates a revoked temporary route as requiring resubmission', async () => {+ mock.thinkingSession = { ok: false, requiresResubmission: true, error: 'Temporary thinking preset "Deep" is no longer available' };+ const { call } = boundary({ thinkingPresetId: 'preset-deep', thinkingSelection: { id: 'preset-deep' } });+ const denial = await call({ purpose: 'turn', round: 0 }, async () => ({})).catch((error) => error);+ expect(denial.requiresResubmission).toBe(true);+ expect(denial.deniedStatus).toBe('degraded');+ });++ it('accounts a failed attempt and records the run it had already created', async () => {+ let clock = 0;+ const { call, accountedCalls } = boundary({ now: () => clock });+ await expect(call({ purpose: 'turn', round: 0 }, async ({ reportRunId }) => {+ reportRunId('run-9');+ clock += 40;+ throw new Error('provider stream ended without a response');+ })).rejects.toThrow('provider stream ended without a response');++ expect(accountedCalls()).toBe(1);+ expect(mock.recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1, ms: 40 });+ expect(receipts()[0].data).toMatchObject({+ runId: 'run-9',+ elapsedMs: 40,+ outcome: 'failed',+ reason: 'provider stream ended without a response',+ });+ });++ it('reports an aborted attempt as interrupted rather than failed', async () => {+ const controller = new AbortController();+ const { call } = boundary({ signal: controller.signal });+ await expect(call({ purpose: 'turn', round: 0 }, async () => {+ controller.abort('Persistent mind turn interrupted');+ throw new Error('Persistent mind turn interrupted');+ })).rejects.toThrow('Persistent mind turn interrupted');+ expect(receipts()[0].data.outcome).toBe('interrupted');+ });++ it('gives every attempt in one turn its own receipt id', async () => {+ const { call } = boundary();+ await call({ purpose: 'turn', round: 0 }, async () => ({ runId: 'run-1' }));+ await call({ purpose: 'tool-round', round: 1 }, async () => ({ runId: 'run-2' }));+ expect(receipts().map((event) => event.eventId)).toEqual([+ `mind-model-call:${TURN_ID}:0`,+ `mind-model-call:${TURN_ID}:1`,+ ]);+ });+});diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.jsindex 01bb39c816..1dae837d5a 100644--- a/server/services/persistentMindContext.js+++ b/server/services/persistentMindContext.js@@ -22,6 +22,7 @@ import {PERSISTENT_MIND_TRAJECTORY_LIMITS,assemblePersistentMindContext,buildPersistentMindRollup,+ isPersistentMindCallDenial,isStoredPersistentMindRollup,} from '../lib/persistentMindTrajectory.js';import {@@ -138,13 +139,23 @@ const latestReadyRollup = (rollups, promptVersion) => rollups.sort((a, b) => a.source.toSequence - b.source.toSequence).at(-1) || null;+// `attempted: false` means the summarizer never reached a provider — the+// per-call boundary refused it (budget, authorization, lifecycle). Sealing a+// FAILED rollup for that range would be a lie AND permanent: the range id is+// deterministic, so `alreadyAttempted` would stop every later turn from+// retrying, and a transient refusal would silently cost the mind that stretch+// of its life forever.const summaryOutcome = (summarize, input) => Promise.resolve().then(() => summarize(input)).then((summary) => typeof summary === 'string' && summary.trim()- ? { ok: true, summary }- : { ok: false, error: 'Persistent mind summarizer returned no summary text' },- (error) => ({ ok: false, error: String(error?.message || error || 'Persistent mind summary failed').slice(0, 500) })+ ? { ok: true, attempted: true, summary }+ : { ok: false, attempted: true, error: 'Persistent mind summarizer returned no summary text' },+ (error) => ({+ ok: false,+ attempted: !isPersistentMindCallDenial(error),+ error: String(error?.message || error || 'Persistent mind summary failed').slice(0, 500),+ }));/**@@ -211,40 +222,44 @@ export async function preparePersistentMindContext({previousProvenance: previous?.provenance ?? null,promptVersion,});- const rollup = await recordPersistentMindRollup({- id: rollupId,- mindId,- status: outcome.ok ? 'ready' : 'failed',- summary: outcome.ok ? outcome.summary : null,- error: outcome.ok ? null : outcome.error,- source,- providerId,- model,- promptVersion,- });- await appendMindEvent({- kind: 'mind.summary',- mindId,- // Keyed on the rollup's own createdAt (unique per attempt), not just- // rollup.id: a forceSummary retry reuses the same rollup id, and the- // shared ledger dedupes mind events by eventId regardless of age — an- // id derived from rollup.id alone would make a successful retry's- // event silently drop, leaving the replayed trajectory stuck showing- // the earlier failed attempt forever.- eventId: `mind-summary-${sha256Text(`${rollup.id}:${rollup.provenance.createdAt}`).slice(0, 32)}`,- data: {- rollupId: rollup.id,- status: rollup.status,- fromSequence: source.fromSequence,- toSequence: source.toSequence,+ // A refused call never reached a provider, so the range stays+ // unattempted and a later turn can still seal it.+ if (outcome.attempted) {+ const rollup = await recordPersistentMindRollup({+ id: rollupId,+ mindId,+ status: outcome.ok ? 'ready' : 'failed',+ summary: outcome.ok ? outcome.summary : null,+ error: outcome.ok ? null : outcome.error,+ source,providerId,model,promptVersion,- summaryText: rollup.summary,- error: rollup.error,- },- });- rollups = await readPersistentMindRollups(mindId);+ });+ await appendMindEvent({+ kind: 'mind.summary',+ mindId,+ // Keyed on the rollup's own createdAt (unique per attempt), not just+ // rollup.id: a forceSummary retry reuses the same rollup id, and the+ // shared ledger dedupes mind events by eventId regardless of age — an+ // id derived from rollup.id alone would make a successful retry's+ // event silently drop, leaving the replayed trajectory stuck showing+ // the earlier failed attempt forever.+ eventId: `mind-summary-${sha256Text(`${rollup.id}:${rollup.provenance.createdAt}`).slice(0, 32)}`,+ data: {+ rollupId: rollup.id,+ status: rollup.status,+ fromSequence: source.fromSequence,+ toSequence: source.toSequence,+ providerId,+ model,+ promptVersion,+ summaryText: rollup.summary,+ error: rollup.error,+ },+ });+ rollups = await readPersistentMindRollups(mindId);+ }}}}diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.jsindex e56a249b80..3847aec481 100644--- a/server/services/persistentMindContext.test.js+++ b/server/services/persistentMindContext.test.js@@ -41,6 +41,7 @@ const {promotePersistentMindMemory,readPersistentMindRollups,} = await import('./persistentMindContext.js');+const { buildPersistentMindCallDenial } = await import('../lib/persistentMindTrajectory.js');const ROLLUPS = join(CONTEXT_DIR, 'persistent-mind-rollups.json');@@ -122,6 +123,25 @@ describe('persistent mind rollups', () => {expect(rollup).toMatchObject({ status: 'failed', summary: null, error: 'summary provider unavailable' });});+ it('leaves the range unattempted when the per-call boundary refuses the summary', async () => {+ mock.history = [event(1), event(2), event(3)];+ const summarize = vi.fn(async () => {+ throw buildPersistentMindCallDenial({ reason: 'CoS actions budget exhausted', status: 'waiting' });+ });++ const first = await preparePersistentMindContext({ recentEventLimit: 1, summarize });+ const second = await preparePersistentMindContext({ recentEventLimit: 1, summarize });++ // No rollup was sealed, so the next turn still retries the same range —+ // a refused call never reached a provider and never summarized anything.+ expect(await readPersistentMindRollups()).toEqual([]);+ expect(summarize).toHaveBeenCalledTimes(2);+ expect(first.summaryState).toBe('unavailable');+ expect(second.summaryState).toBe('unavailable');+ expect(mock.appendMindEvent).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'mind.summary' }));+ expect(mock.history).toHaveLength(3);+ });+it('rejects an empty or whitespace-only summary as a failed attempt', async () => {mock.history = [event(1), event(2), event(3)];const summarize = vi.fn(async () => ' ');diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex 8e5cc5d0cd..3e75b7fe4a 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -13,6 +13,7 @@ import { randomUUID } from 'crypto';import { mkdir, readFile, readdir, stat } from 'fs/promises';import { join } from 'path';import { getDomainMode } from '../lib/domainAutonomy.js';+import { isPersistentMindCallDenial } from '../lib/persistentMindTrajectory.js';import {PERSISTENT_MIND_LIMITS,PERSISTENT_MIND_IMAGE_EXTENSIONS,@@ -47,6 +48,10 @@ import { schedule, cancel } from './eventScheduler.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissionReservations.js';+import {+ createPersistentMindCallBoundary,+ persistentMindCapabilityGrantFingerprint,+} from './persistentMindCallGuard.js';import { appendMindEvent } from './agentRunEventLog.js';import { preparePersistentMindContext } from './persistentMindContext.js';import { resolvePersistentMindProfile, resolvePersistentMindThinkingSession } from './persistentMindProfile.js';@@ -900,6 +905,7 @@ async function runOnePersistentMindTurn() {activeAbortController = controller;let release = () => {};let runStartedAt = null;+ let callBoundary = null;try {// The route is resolved before an adapter can run. This is a read-only// catalog/status check: no alternate provider, model pull, or generation@@ -971,11 +977,12 @@ async function runOnePersistentMindTurn() {if (!await turnCanContinue(turn.id, generation, controller.signal)) return;// Preparation and slot admission may wait. A preset revoked during those// waits must be refused before even a context-summary call can begin.+ const admissionRoot = await loadState();if (thinkingPresetId) {const admissionProfile = await resolvePersistentMindThinkingSession({presetId: thinkingPresetId,selection: turn.wake.message.thinkingPreset,- config: (await loadState()).config,+ config: admissionRoot.config,});if (!await turnCanContinue(turn.id, generation, controller.signal)) return;if (!admissionProfile.ok) {@@ -983,10 +990,36 @@ async function runOnePersistentMindTurn() {return;}}- // One accounted provider span covers both optional context summarization- // and the turn itself. A local adapter must not bypass endpoint capacity- // merely because its first inference happens while context is prepared.+ // The span opens BEFORE context preparation, so a local adapter cannot+ // bypass endpoint capacity merely because its first inference happens+ // while context is assembled.+ //+ // The turn keeps the ONE global slot, action reservation and endpoint slot+ // it was admitted with; the boundary below acquires nothing further. What+ // it does is re-check — before the summary call, before the turn call, and+ // before every tool round — that the route, authorization, lifecycle,+ // grants and remaining budget still permit one more provider call, and+ // account each attempt (failures included) against the domain ledger.runStartedAt = Date.now();+ callBoundary = createPersistentMindCallBoundary({+ mindId: mind.mindId,+ turnId: turn.id,+ route: {+ providerId: prepared.provider.id,+ providerType: prepared.provider.type || null,+ model: prepared.model || null,+ effort: prepared.effort || null,+ thinkingPresetId,+ thinkingPresetLabel: profile.presetLabel || null,+ temporary: profile.temporary === true,+ },+ thinkingPresetId,+ // The ACCEPTED preset snapshot the message carries (#6283) — never the+ // mutable preset id, which the user can repoint mid-turn.+ thinkingSelection: thinkingPresetId ? turn.wake.message.thinkingPreset : null,+ capabilityFingerprint: persistentMindCapabilityGrantFingerprint(admissionRoot.config?.persistentMindCapabilities),+ signal: controller.signal,+ });const context = await preparePersistentMindContext({mindId: mind.mindId,identity: prepared.identity ?? turnAdapter.identity ?? 'One supervised persistent Chief of Staff mind.',@@ -1002,6 +1035,7 @@ async function runOnePersistentMindTurn() {effort: prepared.effort || null,signal: controller.signal,heartbeat: () => heartbeat(turn.id, generation),+ callBoundary: callBoundary.call,}): null,});@@ -1031,6 +1065,7 @@ async function runOnePersistentMindTurn() {signal: controller.signal,heartbeat: () => heartbeat(turn.id, generation),context,+ callBoundary: callBoundary.call,recordCapabilityEvent: ({ kind, id, data } = {}) => {const eventKind = kind === 'result' ? 'mind.capability.result' : 'mind.capability.request';const capabilityId = typeof id === 'string' && id ? id : randomUUID();@@ -1076,15 +1111,27 @@ async function runOnePersistentMindTurn() {}, generation);} catch (error) {if (generation === runtimeGeneration) {+ const denied = isPersistentMindCallDenial(error);const message = controller.signal.aborted? String(controller.signal.reason || 'Persistent mind turn interrupted'): errorMessage(error);- await parkActiveTurn(turn.id, message, 'interrupted', { consumedAttempt: runStartedAt != null });- emitLog('warn', `Persistent mind turn interrupted: ${message}`, { turnId: turn.id });+ // A refusal already named its own cause and the status it belongs+ // under; only a revoked temporary route retires the wake, exactly as+ // the pre-turn resolution does.+ await parkActiveTurn(turn.id, message, (denied && error.deniedStatus) || 'interrupted', {+ consumedAttempt: runStartedAt != null,+ retireWake: denied && error.requiresResubmission === true,+ });+ emitLog('warn', `Persistent mind turn ${denied ? 'refused a further provider call' : 'interrupted'}: ${message}`, { turnId: turn.id });}} finally {release();- if (runStartedAt != null) {+ // The boundary accounts every provider call it admitted, so the turn adds+ // nothing on top — that would double-count the span it already recorded.+ // A turn that opened the span and never reached a provider still costs one+ // action, or a turn that always aborts just before its first call would+ // retry against the budget for free.+ if (runStartedAt != null && (callBoundary?.accountedCalls() ?? 0) === 0) {await recordDomainUsage('cos', { actions: 1, ms: Date.now() - runStartedAt }).catch((error) => {console.error(`❌ Failed to record persistent mind usage: ${error.message}`);});diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex eb7032e965..6e0db748a9 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -1063,4 +1063,141 @@ describe('persistent mind supervisor', () => {expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['plain-1']);expect(mock.root.persistentMind.recentMessageIds).toEqual([]);});++ describe('per-call provider boundary', () => {+ const mindCallReceipts = () => mock.appendMindEvent.mock.calls+ .map(([event]) => event)+ .filter((event) => event.kind === 'mind.model.call');++ it('admits and accounts each provider call of a turn instead of the whole span', async () => {+ mock.prepareContext.mockImplementationOnce(async ({ summarize }) => {+ await summarize({ events: [], previousSummary: null });+ return { text: 'bounded context', chars: 15, summaryState: 'ready' };+ });+ const summarize = vi.fn(async ({ callBoundary }) => {+ await callBoundary({ purpose: 'summary' }, async ({ reportRunId }) => {+ reportRunId('run-summary');+ return { text: 'An earlier stretch of my life.', runId: 'run-summary' };+ });+ return 'An earlier stretch of my life.';+ });+ const run = vi.fn(async ({ callBoundary }) => {+ for (const round of [0, 1]) {+ await callBoundary({ purpose: round === 0 ? 'turn' : 'tool-round', round }, async ({ reportRunId }) => {+ reportRunId(`run-${round}`);+ return { text: '{}', runId: `run-${round}`, usage: { inputTokens: 10, outputTokens: 2 } };+ });+ }+ return {};+ });+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run, summarize });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-calls', text: 'Do the work.' });+ await supervisor.drainPersistentMind();++ expect(summarize).toHaveBeenCalledTimes(1);+ // Three calls, three accounted actions — and no extra action for the turn+ // itself, which would double-count the span the receipts already cover.+ expect(mock.recordUsage).toHaveBeenCalledTimes(3);+ expect(mock.recordUsage.mock.calls.every(([domain, delta]) => domain === 'cos' && delta.actions === 1)).toBe(true);+ expect(mindCallReceipts().map((event) => event.data.purpose)).toEqual(['summary', 'turn', 'tool-round']);+ expect(mindCallReceipts().map((event) => event.data.runId)).toEqual(['run-summary', 'run-0', 'run-1']);+ expect(mindCallReceipts()[1].data).toMatchObject({+ providerId: 'example-cloud',+ model: 'example-model',+ effort: 'high',+ outcome: 'completed',+ temporaryRoute: false,+ });+ expect(mindCallReceipts()[1].data.elapsedMs).toBeGreaterThanOrEqual(0);+ expect(mindCallReceipts()[1].data.usage).toMatchObject({ state: 'reported', totalTokens: 12 });+ expect(mock.root.persistentMind.status).toBe('idle');+ });++ it('denies a later round when the budget empties mid-turn and parks the turn as waiting', async () => {+ const run = vi.fn(async ({ callBoundary }) => {+ await callBoundary({ purpose: 'turn', round: 0 }, async () => ({ text: '{}', runId: 'run-0' }));+ mock.budget = { withinBudget: false, exceeded: 'actions' };+ await callBoundary({ purpose: 'tool-round', round: 1 }, async () => {+ throw new Error('this second provider call must never start');+ });+ return {};+ });+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-budget', text: 'Keep going.' });+ await supervisor.drainPersistentMind();++ expect(mock.recordUsage).toHaveBeenCalledTimes(1);+ expect(mindCallReceipts().map((event) => event.data.outcome)).toEqual(['completed', 'denied']);+ expect(mindCallReceipts()[1].data.reason).toBe('CoS actions budget exhausted');+ expect(mock.root.persistentMind).toMatchObject({+ status: 'waiting',+ pauseReason: 'CoS actions budget exhausted',+ });+ });++ it('records a failed attempt and still leaves its route and elapsed time readable', async () => {+ const run = vi.fn(async ({ callBoundary }) => callBoundary(+ { purpose: 'turn', round: 0 },+ async ({ reportRunId }) => {+ reportRunId('run-0');+ throw new Error('provider stream ended without a response');+ },+ ));+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-failed', text: 'Try this.' });+ await supervisor.drainPersistentMind();++ expect(mock.recordUsage).toHaveBeenCalledTimes(1);+ expect(mindCallReceipts()[0].data).toMatchObject({+ outcome: 'failed',+ runId: 'run-0',+ providerId: 'example-cloud',+ model: 'example-model',+ reason: 'provider stream ended without a response',+ });+ expect(mindCallReceipts()[0].data.usage.state).toBe('unknown');+ expect(mock.root.persistentMind.status).toBe('interrupted');+ });++ it('refuses the next call and retires the wake when a temporary preset is revoked mid-turn', async () => {+ withDeepPreset();+ const run = vi.fn(async ({ callBoundary }) => {+ await callBoundary({ purpose: 'turn', round: 0 }, async () => ({ text: '{}', runId: 'run-0' }));+ mock.thinkingSession = {+ ok: false,+ requiresResubmission: true,+ error: 'Temporary thinking preset "Deep pass" is no longer available',+ };+ await callBoundary({ purpose: 'tool-round', round: 1 }, async () => {+ throw new Error('this second provider call must never start');+ });+ return {};+ });+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-revoked', text: 'Deep pass please.', thinkingPresetId: 'deep' });+ await supervisor.drainPersistentMind();++ const receipts = mindCallReceipts();+ expect(receipts.map((event) => event.data.outcome)).toEqual(['completed', 'denied']);+ expect(receipts[0].data).toMatchObject({+ providerId: 'example-alt',+ model: 'alt-model',+ effort: 'max',+ thinkingPresetId: 'deep',+ temporaryRoute: true,+ });+ expect(mock.root.persistentMind.status).toBe('degraded');+ // A spent temporary session is never replayed automatically.+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);+ expect(mock.root.persistentMind.recentMessageIds).toContain('message-revoked');+ });+ });});