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
Pick maturity-aware continuous-play phases from live Eidoverse signals (#7458)
[._.]/ Adam Eivyf5437a1b2dc8
diff --git a/docs/features/persistent-mind-continuous-play.md b/docs/features/persistent-mind-continuous-play.mdindex cc64e026cf..2a3dc2f84c 100644--- a/docs/features/persistent-mind-continuous-play.md+++ b/docs/features/persistent-mind-continuous-play.md@@ -9,14 +9,22 @@ PortOS minds can opt into a first-class **operating playbook** stored on CoS con| `mode` | `default` (operator prompt only) or `continuous-play` || `customInstructions` | Optional extra notes appended after the mode template |-When `mode` is `continuous-play`, every wake merges the product template into operating instructions:+Saving a playbook never starts inference. The Mind Context panel exposes the mode selector; `PUT /api/cos/config` accepts `persistentMindPlaybook`. `GET /api/cos/mind/context` returns `playbook` + `playbookCatalog` + `playbookPhase` and previews composed instructions.-1. **Explore** the Eidoverse / Commons with many small interactions-2. **Interact** (say / augment / project / peers / PortOS tools)-3. **Reflect** with concrete improvement ideas-4. **Invent / improve** via the smallest safe PortOS-side step or typed CoS task+### Maturity-aware phases (#7458)-Saving a playbook never starts inference. The Mind Context panel exposes the mode selector; `PUT /api/cos/config` accepts `persistentMindPlaybook`. `GET /api/cos/mind/context` returns `playbook` + `playbookCatalog` and previews composed instructions.+`continuous-play` no longer runs one fixed loop forever. Every wake, `resolvePersistentMindPlaybookPhase()` (`server/services/persistentMindPlaybookSignals.js`) reads the same bounded Eidoverse world-signal projection the World Design V2 recipe renders into districts (`buildEidoverseWorldSignals()`, `server/lib/eidoverseWorldSignals.js`), reduces it to three numbers, and the pure picker in `server/lib/persistentMindPlaybookPhase.js` (`selectPersistentMindPlaybookPhase`) chooses one of four phases:++| Phase | When | Loop emphasis |+|-------|------|----------------|+| **Explore** | Commons is sparse (fewer than 4 live world-signal entities, or signals unavailable) | Map affordances, reconnect presence, many small interactions |+| **Construct** | Commons has some shape (4–15 live signals) and nothing is broken or waiting | Densify districts — places, labels, structures, affordances |+| **Maintain** | Recent failure rate ≥ 25%, or the Commons is mature (16+ signals) with no peer activity | Repair broken projections, retire dead affordances, re-test foundations |+| **Coordinate** | A federated peer is reporting new (non-steady) activity and failures are below threshold | Visit peers, read/respond to their contributions, steward the shared baseline |++Priority order when signals conflict: a still-sparse Commons always explores first; a high failure rate outranks a peer visit (fix what is broken before going visiting); an active peer outranks routine construction. The picker never reads a wall clock — it degrades to `explore` (the safe default) whenever a signal is unavailable rather than guessing.++Each phase template ends by naming itself (e.g. `Phase: Construct`) so the mind states its current phase in the wake's user-visible working note — how Helm and other minds can see which phase produced a given wake. `GET /api/cos/mind/context` also resolves the phase for preview (best-effort; a signal-read failure there falls back to the general loop rather than failing the request).## Mind-adjustable `numCtx`diff --git a/server/lib/README.md b/server/lib/README.mdindex f299c6056b..4fb2f04d18 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -67,6 +67,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `persistentMindMemory.js` | Persistent Mind memory protection schema, durable tag encoding, public projection, and protected-first context ordering. || `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. || `persistentMindPlaybook.js` | Continuous-play / explore→interact→reflect→invent Persistent Mind operating modes and prompt framing. Pure. |+| `persistentMindPlaybookPhase.js` | Maturity-aware continuous-play phase picker (explore/construct/maintain/coordinate) from bounded Eidoverse world signals — density, recent failure rate, active peers. Pure. || `mindLocalContextClamp.js` | RAM/GPU safety ceilings for mind-driven local `numCtx` adjustments (CPU-only tiers, free-RAM + PortOS headroom). Pure. || `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. || `persistentMindThinkingPresets.js` | Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 4c2e347bcd..1dbc29bb8b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -319,6 +319,7 @@ export * from './persistentMindProfile.js';export * from './persistentMindMemory.js';export * from './persistentMindPrompt.js';export * from './persistentMindPlaybook.js';+export * from './persistentMindPlaybookPhase.js';export * from './mindLocalContextClamp.js';export * from './persistentMindPublic.js';export * from './persistentMindThinkingPresets.js';diff --git a/server/lib/persistentMindPlaybook.js b/server/lib/persistentMindPlaybook.jsindex de8e161794..13d454b1e7 100644--- a/server/lib/persistentMindPlaybook.js+++ b/server/lib/persistentMindPlaybook.js@@ -9,6 +9,7 @@*/import { z } from 'zod';+import { PERSISTENT_MIND_PLAYBOOK_PHASES } from './persistentMindPlaybookPhase.js';export const PERSISTENT_MIND_PLAYBOOK_SCHEMA_VERSION = 1;@@ -36,6 +37,56 @@ Each wake, prefer this loop over idle chatter:Self-directed wakes must produce a concrete observation, question, or next step — not filler.`;+/**+ * Maturity-aware phase templates (issue #7458). Chosen each wake from world+ * signals by `resolvePersistentMindPlaybookPhase()` (see+ * `server/services/persistentMindPlaybookSignals.js`) rather than a fixed+ * cron personality — an empty Commons and a dense one need different wakes.+ * Each block ends by naming its own phase so the mind states it in the+ * working note, making the current phase visible to Helm and other minds.+ */+export const PERSISTENT_MIND_PLAYBOOK_PHASE_INSTRUCTIONS = Object.freeze({+ explore: `PLAYBOOK PHASE — Explore (sparse Commons)++The Commons is still mostly empty. Each wake, prefer this loop:++1) Check eidoverse.status; reconnect presence if disconnected.+2) Move through the world and map what already exists — places, peers, projections, affordances.+3) Prefer many small concrete interactions (eidoverse.say, eidoverse.augment) over one abstract plan.++End with a short user-visible working note starting "Phase: Explore" — what you found, and 1–3 smallest-first ideas for what to build next.`,++ construct: `PLAYBOOK PHASE — Construct (Commons taking shape)++The Commons has some structure but is not yet dense. Each wake, prefer this loop:++1) Check eidoverse.status, then densify: add places, labels, structures, resource projection, and gentle affordances where the world is thin.+2) Favor PortOS-side work; do not fork the Eidoverse runtime.+3) File a typed CoS task for anything file-changing or consequential; never claim side effects that did not happen.++End with a short user-visible working note starting "Phase: Construct" — what you built, what is still thin, and 1–3 smallest-first next steps.`,++ maintain: `PLAYBOOK PHASE — Maintain (Commons needs upkeep)++The Commons is established but something is broken, stale, or aging. Each wake, prefer this loop:++1) Check eidoverse.status, then look for what is broken, stale, or orphaned — failed projections, dead affordances, stalled tasks.+2) Repair or retire what no longer serves the world before adding anything new; re-test what you already built.+3) File a typed CoS task for anything file-changing or consequential.++End with a short user-visible working note starting "Phase: Maintain" — what you repaired or retired, and what still needs attention.`,++ coordinate: `PLAYBOOK PHASE — Coordinate (peers waiting)++Federated peers have activity worth your attention. Each wake, prefer this loop:++1) Check eidoverse.status; when visitEidoversePeers is granted, review eidoverse.destinations and visit a peer with new activity (eidoverse.visit, eidoverse.visit-chat, then eidoverse.leave).+2) Favor stewarding the shared baseline over solo construction this wake — read what a peer contributed, respond, and note anything worth bringing home.+3) Package the smallest safe follow-up as a typed CoS task rather than acting outside your granted tools.++End with a short user-visible working note starting "Phase: Coordinate" — who or what you coordinated with, and 1–3 smallest-first follow-ups.`,+});+export const persistentMindPlaybookSchema = z.object({schemaVersion: z.literal(PERSISTENT_MIND_PLAYBOOK_SCHEMA_VERSION).optional(),mode: z.enum(PERSISTENT_MIND_PLAYBOOK_MODES).optional(),@@ -79,12 +130,20 @@ export function mergePersistentMindPlaybook(previous, update) {/*** Resolve the instruction block for the active playbook mode.* `default` contributes nothing (operator prompt alone drives the mind).+ *+ * `phase` (one of `PERSISTENT_MIND_PLAYBOOK_PHASES`, e.g. from+ * `resolvePersistentMindPlaybookPhase()`) selects the maturity-aware+ * template for `continuous-play`. Omitting it (a preview with no live world+ * signals, or an unrecognized value) falls back to the general+ * explore→interact→reflect→invent loop.*/-export function playbookInstructionBlock(playbook) {+export function playbookInstructionBlock(playbook, phase) {const normalized = normalizePersistentMindPlaybook(playbook);const parts = [];if (normalized.mode === 'continuous-play') {- parts.push(CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS);+ parts.push(PERSISTENT_MIND_PLAYBOOK_PHASES.includes(phase)+ ? PERSISTENT_MIND_PLAYBOOK_PHASE_INSTRUCTIONS[phase]+ : CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS);}if (normalized.customInstructions) {parts.push(normalized.customInstructions);@@ -96,9 +155,9 @@ export function playbookInstructionBlock(playbook) {* Merge operator instructions with the active playbook template.* Playbook text is appended so the operator prompt remains primary voice.*/-export function composePersistentMindInstructions(operatorInstructions, playbook) {+export function composePersistentMindInstructions(operatorInstructions, playbook, phase) {const base = typeof operatorInstructions === 'string' ? operatorInstructions.trim() : '';- const block = playbookInstructionBlock(playbook);+ const block = playbookInstructionBlock(playbook, phase);if (!block) return base;if (!base) return block;return `${base}\n\n${block}`;diff --git a/server/lib/persistentMindPlaybook.test.js b/server/lib/persistentMindPlaybook.test.jsindex cf2f0c449d..e494b978d5 100644--- a/server/lib/persistentMindPlaybook.test.js+++ b/server/lib/persistentMindPlaybook.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS,+ PERSISTENT_MIND_PLAYBOOK_PHASE_INSTRUCTIONS,composePersistentMindInstructions,createDefaultPersistentMindPlaybook,mergePersistentMindPlaybook,@@ -32,4 +33,30 @@ describe('persistentMindPlaybook', () => {expect(composed.startsWith('Be concise.')).toBe(true);expect(composed).toContain('Continuous play');});++ it('selects the maturity-aware phase template when a valid phase is supplied (#7458)', () => {+ const construct = playbookInstructionBlock({ mode: 'continuous-play' }, 'construct');+ expect(construct).toBe(PERSISTENT_MIND_PLAYBOOK_PHASE_INSTRUCTIONS.construct);+ expect(construct).toContain('PLAYBOOK PHASE — Construct');+ expect(construct).toContain('Phase: Construct');+ expect(construct).not.toBe(CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS);++ for (const phase of ['explore', 'construct', 'maintain', 'coordinate']) {+ const block = playbookInstructionBlock({ mode: 'continuous-play' }, phase);+ expect(block).toBe(PERSISTENT_MIND_PLAYBOOK_PHASE_INSTRUCTIONS[phase]);+ }++ // An unrecognized/omitted phase keeps the general loop rather than throwing.+ expect(playbookInstructionBlock({ mode: 'continuous-play' }, 'not-a-real-phase')).toBe(CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS);++ const composed = composePersistentMindInstructions('Be concise.', { mode: 'continuous-play' }, 'coordinate');+ expect(composed).toContain('PLAYBOOK PHASE — Coordinate');+ expect(composed.startsWith('Be concise.')).toBe(true);+ });++ it('appends custom instructions after the phase template, not instead of it', () => {+ const block = playbookInstructionBlock({ mode: 'continuous-play', customInstructions: 'Prefer the northern district.' }, 'maintain');+ expect(block).toContain('PLAYBOOK PHASE — Maintain');+ expect(block.endsWith('Prefer the northern district.')).toBe(true);+ });});diff --git a/server/lib/persistentMindPlaybookPhase.js b/server/lib/persistentMindPlaybookPhase.jsnew file mode 100644index 0000000000..0c978bdbe2--- /dev/null+++ b/server/lib/persistentMindPlaybookPhase.js@@ -0,0 +1,128 @@+/**+ * Maturity-aware phase picker for the Persistent Mind continuous-play+ * playbook (issue #7458). SwarmWorld-style minds drift among explore,+ * construct, maintain, and coordinate as the shared Eidoverse Commons+ * matures, rather than running one fixed explore→invent loop forever. This+ * module picks the active phase from bounded world signals — never from a+ * wall-clock or fixed cron personality — so a sparse Commons gets more+ * exploring and a dense, aging one gets more maintenance and coordination.+ *+ * Pure and side-effect-free: it takes the numeric signals already reduced+ * from `buildEidoverseWorldSignals()` (see `derivePersistentMindPlaybookPhaseSignals`)+ * and returns a phase plus a short human-readable reason. Live signal+ * gathering (I/O) lives in `server/services/persistentMindPlaybookSignals.js`.+ */++export const PERSISTENT_MIND_PLAYBOOK_PHASES = Object.freeze([+ 'explore',+ 'construct',+ 'maintain',+ 'coordinate',+]);++/**+ * Thresholds are counted in live world-signal entities — one per projected+ * district landmark/aggregate from `buildEidoverseWorldSignals()` (apps,+ * agents, tasks, enabled features, peers, activity days, goals, memory+ * categories, storage areas, Jira groups, operations) — the same population+ * the Eidoverse World Design V2 recipe places across its eight districts.+ */+const THRESHOLDS = Object.freeze({+ sparseDistrictCount: 4,+ matureDistrictCount: 16,+ highFailureRate: 0.25,+});++const nonNegativeIntOrNull = (value) => {+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;+ return Math.max(0, Math.round(value));+};++const clampFractionOrNull = (value) => {+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;+ return Math.max(0, Math.min(1, value));+};++const arrayLength = (value) => (Array.isArray(value) ? value.length : 0);++const healthFailureRate = (health) => {+ if (!health || typeof health.status !== 'string') return null;+ if (health.status === 'error') return 1;+ if (health.status === 'attention') return 0.5;+ if (health.status === 'healthy') return 0;+ return null;+};++/**+ * Reduce a `buildEidoverseWorldSignals()` projection (see+ * `server/lib/eidoverseWorldSignals.js`) to the bounded numbers the phase+ * picker needs. Every field degrades to `null` ("unknown") rather than a+ * guessed zero when the source signal was unavailable, so the picker can+ * fall back to the safe `explore` phase instead of reading absence as+ * emptiness.+ */+export function derivePersistentMindPlaybookPhaseSignals(worldSignals) {+ if (!worldSignals || typeof worldSignals !== 'object') {+ return { districtCount: null, failureRate: null, peersWithActivity: null };+ }++ const districtCount = [+ worldSignals.apps, worldSignals.agents, worldSignals.tasks, worldSignals.features,+ worldSignals.peers, worldSignals.activity, worldSignals.goals, worldSignals.memory,+ worldSignals.storage, worldSignals.jira, worldSignals.operations,+ ].reduce((total, entries) => total + arrayLength(entries), 0);++ const productivity = Array.isArray(worldSignals.productivity) ? worldSignals.productivity[0] : null;+ const succeeded = nonNegativeIntOrNull(productivity?.succeededToday);+ const failed = nonNegativeIntOrNull(productivity?.failedToday);+ const totalToday = succeeded !== null && failed !== null ? succeeded + failed : null;+ const failureRate = totalToday !== null && totalToday > 0+ ? failed / totalToday+ : (typeof productivity?.successRate === 'number'+ ? clampFractionOrNull(1 - productivity.successRate / 100)+ : healthFailureRate(worldSignals.health));++ // "Unread peer contributions" approximated as federated peers currently+ // reporting non-steady status (active/attention/error — something changed+ // since the last look) that this mind can actually travel to.+ const peersWithActivity = Array.isArray(worldSignals.peers)+ ? worldSignals.peers.filter((peer) => peer?.travelAvailable === true && peer?.status && peer.status !== 'steady').length+ : null;++ return { districtCount, failureRate, peersWithActivity };+}++/**+ * Pick the active playbook phase from bounded signals. Never throws: an+ * absent or malformed signal set degrades to `explore`, the safe default for+ * a mind that cannot yet see the world it would otherwise+ * construct/maintain/coordinate in.+ *+ * Priority, highest first: a still-sparse Commons always explores first; a+ * high recent failure rate outranks a peer visit (fix what is broken before+ * going visiting); an active peer outranks routine construction; a Commons+ * short of the maturity threshold keeps building; a mature, healthy,+ * peer-quiet Commons falls back to steady-state maintenance.+ */+export function selectPersistentMindPlaybookPhase(signals = {}) {+ const districtCount = nonNegativeIntOrNull(signals.districtCount);+ const failureRate = clampFractionOrNull(signals.failureRate);+ const peersWithActivity = nonNegativeIntOrNull(signals.peersWithActivity);++ if (districtCount === null || districtCount < THRESHOLDS.sparseDistrictCount) {+ return {+ phase: 'explore',+ reason: districtCount === null ? 'world signals unavailable' : `sparse Commons (${districtCount} live signal(s))`,+ };+ }+ if (failureRate !== null && failureRate >= THRESHOLDS.highFailureRate) {+ return { phase: 'maintain', reason: `${Math.round(failureRate * 100)}% recent failure rate` };+ }+ if (peersWithActivity !== null && peersWithActivity > 0) {+ return { phase: 'coordinate', reason: `${peersWithActivity} peer(s) with new activity to visit` };+ }+ if (districtCount < THRESHOLDS.matureDistrictCount) {+ return { phase: 'construct', reason: `${districtCount} live signal(s), room to densify before ${THRESHOLDS.matureDistrictCount}` };+ }+ return { phase: 'maintain', reason: `mature Commons (${districtCount} live signal(s)), steady-state upkeep` };+}diff --git a/server/lib/persistentMindPlaybookPhase.test.js b/server/lib/persistentMindPlaybookPhase.test.jsnew file mode 100644index 0000000000..32b0bf44e2--- /dev/null+++ b/server/lib/persistentMindPlaybookPhase.test.js@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest';+import {+ PERSISTENT_MIND_PLAYBOOK_PHASES,+ derivePersistentMindPlaybookPhaseSignals,+ selectPersistentMindPlaybookPhase,+} from './persistentMindPlaybookPhase.js';++describe('selectPersistentMindPlaybookPhase', () => {+ it('explores when signals are entirely unavailable', () => {+ expect(selectPersistentMindPlaybookPhase()).toMatchObject({ phase: 'explore', reason: expect.stringContaining('unavailable') });+ expect(selectPersistentMindPlaybookPhase({ districtCount: null })).toMatchObject({ phase: 'explore' });+ });++ it('explores a Commons at and just below the sparse threshold', () => {+ expect(selectPersistentMindPlaybookPhase({ districtCount: 0 }).phase).toBe('explore');+ expect(selectPersistentMindPlaybookPhase({ districtCount: 3 }).phase).toBe('explore');+ });++ it('constructs once the Commons clears the sparse threshold with no failures or peer activity', () => {+ const result = selectPersistentMindPlaybookPhase({ districtCount: 4, failureRate: 0, peersWithActivity: 0 });+ expect(result).toMatchObject({ phase: 'construct' });+ });++ it('maintains when the recent failure rate crosses the threshold, even with peer activity waiting', () => {+ const result = selectPersistentMindPlaybookPhase({ districtCount: 10, failureRate: 0.25, peersWithActivity: 3 });+ expect(result).toMatchObject({ phase: 'maintain', reason: expect.stringContaining('25%') });+ });++ it('coordinates when a peer has new activity and failures are below threshold', () => {+ const result = selectPersistentMindPlaybookPhase({ districtCount: 10, failureRate: 0.1, peersWithActivity: 1 });+ expect(result).toMatchObject({ phase: 'coordinate' });+ });++ it('stays in construct just below the mature threshold once failures/peers are quiet', () => {+ const result = selectPersistentMindPlaybookPhase({ districtCount: 15, failureRate: 0, peersWithActivity: 0 });+ expect(result).toMatchObject({ phase: 'construct' });+ });++ it('falls back to maintain for a mature, healthy, peer-quiet Commons', () => {+ const result = selectPersistentMindPlaybookPhase({ districtCount: 16, failureRate: 0, peersWithActivity: 0 });+ expect(result).toMatchObject({ phase: 'maintain', reason: expect.stringContaining('mature') });+ });++ it('always resolves to a documented phase', () => {+ const matrix = [+ {},+ { districtCount: -5, failureRate: -1, peersWithActivity: -2 },+ { districtCount: Number.NaN, failureRate: Number.NaN },+ { districtCount: 100, failureRate: 0.9, peersWithActivity: 5 },+ ];+ for (const signals of matrix) {+ expect(PERSISTENT_MIND_PLAYBOOK_PHASES).toContain(selectPersistentMindPlaybookPhase(signals).phase);+ }+ });++ it('treats a negative/NaN failure rate as absent rather than throwing', () => {+ expect(() => selectPersistentMindPlaybookPhase({ districtCount: 10, failureRate: Number.NaN })).not.toThrow();+ expect(selectPersistentMindPlaybookPhase({ districtCount: 10, failureRate: -1 }).phase).toBe('construct');+ });+});++describe('derivePersistentMindPlaybookPhaseSignals', () => {+ it('returns null signals for a missing or malformed world-signals projection', () => {+ expect(derivePersistentMindPlaybookPhaseSignals(null)).toEqual({ districtCount: null, failureRate: null, peersWithActivity: null });+ expect(derivePersistentMindPlaybookPhaseSignals('not-an-object')).toEqual({ districtCount: null, failureRate: null, peersWithActivity: null });+ });++ it('sums entities across every projected district array', () => {+ const signals = derivePersistentMindPlaybookPhaseSignals({+ apps: [{ id: 'a' }, { id: 'b' }],+ agents: [{ id: 'c' }],+ tasks: null,+ features: [{ id: 'd' }],+ peers: [],+ activity: [{ id: 'e' }, { id: 'f' }, { id: 'g' }],+ goals: undefined,+ memory: [{ id: 'h' }],+ storage: [{ id: 'i' }, { id: 'j' }],+ jira: [],+ operations: [{ id: 'k' }],+ });+ expect(signals.districtCount).toBe(2 + 1 + 0 + 1 + 0 + 3 + 0 + 1 + 2 + 0 + 1);+ });++ it('prefers today failed/succeeded counts over successRate when both are present', () => {+ const signals = derivePersistentMindPlaybookPhaseSignals({+ productivity: [{ succeededToday: 3, failedToday: 1, successRate: 99 }],+ });+ expect(signals.failureRate).toBeCloseTo(0.25);+ });++ it('falls back to successRate, then to health status, when today counts are unavailable', () => {+ const viaSuccessRate = derivePersistentMindPlaybookPhaseSignals({ productivity: [{ successRate: 80 }] });+ expect(viaSuccessRate.failureRate).toBeCloseTo(0.2);++ const viaHealthError = derivePersistentMindPlaybookPhaseSignals({ health: { status: 'error' } });+ expect(viaHealthError.failureRate).toBe(1);+ const viaHealthAttention = derivePersistentMindPlaybookPhaseSignals({ health: { status: 'attention' } });+ expect(viaHealthAttention.failureRate).toBe(0.5);+ const viaHealthHealthy = derivePersistentMindPlaybookPhaseSignals({ health: { status: 'healthy' } });+ expect(viaHealthHealthy.failureRate).toBe(0);++ expect(derivePersistentMindPlaybookPhaseSignals({}).failureRate).toBeNull();+ });++ it('counts only travelable peers reporting non-steady status as active', () => {+ const signals = derivePersistentMindPlaybookPhaseSignals({+ peers: [+ { travelAvailable: true, status: 'active' },+ { travelAvailable: true, status: 'steady' },+ { travelAvailable: false, status: 'attention' },+ { travelAvailable: true, status: 'error' },+ ],+ });+ expect(signals.peersWithActivity).toBe(2);+ });+});diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex ae876d70af..71f1b305a6 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -29,6 +29,7 @@ import {} from '../lib/persistentMindThinkingPresets.js';import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { composePersistentMindInstructions, normalizePersistentMindPlaybook, PERSISTENT_MIND_PLAYBOOK_CATALOG } from '../lib/persistentMindPlaybook.js';+import { resolvePersistentMindPlaybookPhase } from '../services/persistentMindPlaybookSignals.js';import { publicPersistentMindState } from '../lib/persistentMindPublic.js';import { publicPersistentMindTurnExecutions } from '../lib/persistentMindTrajectory.js';import { validateRequest } from '../lib/validation.js';@@ -234,20 +235,25 @@ router.get('/mind/context', asyncHandler(async (_req, res) => {const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);- const [memories, rollups, provider] = await Promise.all([+ const [memories, rollups, provider, playbookPhase] = await Promise.all([readPersistentMindMemories(PERSISTENT_MIND_ID),readPersistentMindRollups(PERSISTENT_MIND_ID),profile.providerId ? getProviderById(profile.providerId) : null,+ // Preview only: the next real wake resolves this itself. Computed here+ // too so the Mind Context panel can show the phase a continuous-play+ // wake would currently pick (#7458).+ playbook.mode === 'continuous-play' ? resolvePersistentMindPlaybookPhase() : null,]);const preview = await preparePersistentMindContext({mindId: PERSISTENT_MIND_ID,identity: prompt.identity,- instructions: composePersistentMindInstructions(prompt.instructions, playbook),+ instructions: composePersistentMindInstructions(prompt.instructions, playbook, playbookPhase?.phase),memories,});res.json({prompt,playbook,+ playbookPhase,playbookCatalog: PERSISTENT_MIND_PLAYBOOK_CATALOG,preview,memories,diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex 3695d9fbd8..07f512cf84 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -31,6 +31,7 @@ import {} from './persistentMindContext.js';import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { composePersistentMindInstructions, normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';+import { resolvePersistentMindPlaybookPhase } from './persistentMindPlaybookSignals.js';import { assertVisionRunUsedImages, runPromptThroughProvider } from './promptRunner.js';import { stopRun } from './runner.js';import {@@ -342,21 +343,28 @@ async function runPinnedPrompt({ provider, model, effort, prompt, screenshots =export function createPersistentMindTurnAdapter() {return {- async prepare({ profile }) {+ 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;return {ok: true,provider: profile.provider,model: profile.model,effort: profile.effort,identity: prompt.identity,- instructions: composePersistentMindInstructions(prompt.instructions, playbook),+ instructions: composePersistentMindInstructions(prompt.instructions, playbook, playbookPhase?.phase),playbook,+ playbookPhase,memories,};},diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex 096f68d92e..176c99e94f 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -13,6 +13,7 @@ const mock = vi.hoisted(() => ({executeToolCall: vi.fn(),readVisibility: vi.fn(),executeCallRequest: vi.fn(),+ resolvePlaybookPhase: vi.fn(),createPersistentMindMemoryFromCandidate: vi.fn(async ({ candidateId, ...candidate }) => ({success: true,duplicate: false,@@ -52,6 +53,9 @@ vi.mock('./persistentMindCallCapability.js', () => ({buildPersistentMindCallCapabilityPrompt: ({ enabled }) => `Call access: ${enabled ? 'ON' : 'OFF'}`,executePersistentMindCallRequest: (...args) => mock.executeCallRequest(...args),}));+vi.mock('./persistentMindPlaybookSignals.js', () => ({+ resolvePersistentMindPlaybookPhase: (...args) => mock.resolvePlaybookPhase(...args),+}));vi.mock('./cosToolRegistry.js', () => ({readPersistentMindRecipeCatalog: vi.fn(async () => []),buildPersistentMindToolPrompt: ({ readPortos, writePortos }) => `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}`,@@ -73,6 +77,7 @@ beforeEach(() => {mock.executeTaskRequests.mockResolvedValue([]);mock.executeCallRequest.mockResolvedValue(null);mock.executeToolCall.mockResolvedValue({ state: 'completed', result: { ok: true, count: 1 } });+ mock.resolvePlaybookPhase.mockResolvedValue({ phase: 'construct', reason: 'test default', signals: {} });mock.assertVision.mockImplementation((result, provider) => result?.provider || provider);mock.runPrompt.mockResolvedValue({ text: JSON.stringify({thinkingSummary: 'I connected the new request to the durable fact.',@@ -141,6 +146,18 @@ describe('persistent mind adapter', () => {memories: mock.memories,});expect(mock.runPrompt).not.toHaveBeenCalled();+ expect(mock.resolvePlaybookPhase).not.toHaveBeenCalled();+ expect(prepared.playbookPhase).toBeNull();+ });++ it('resolves a maturity-aware phase and wires it into instructions only for continuous-play (#7458)', async () => {+ mock.root.config.persistentMindPlaybook = { mode: 'continuous-play' };+ mock.resolvePlaybookPhase.mockResolvedValue({ phase: 'coordinate', reason: '2 peer(s) with new activity to visit', signals: { districtCount: 20, failureRate: 0, peersWithActivity: 2 } });+ const prepared = await createPersistentMindTurnAdapter().prepare({ profile });+ expect(mock.resolvePlaybookPhase).toHaveBeenCalledTimes(1);+ expect(prepared.playbookPhase).toMatchObject({ phase: 'coordinate' });+ expect(prepared.instructions).toContain('PLAYBOOK PHASE — Coordinate');+ delete mock.root.config.persistentMindPlaybook;});it('runs the exact pinned non-interactive profile and returns visible trajectory events', async () => {diff --git a/server/services/persistentMindPlaybookSignals.js b/server/services/persistentMindPlaybookSignals.jsnew file mode 100644index 0000000000..a705e33632--- /dev/null+++ b/server/services/persistentMindPlaybookSignals.js@@ -0,0 +1,34 @@+/**+ * Live-signal gathering for the Persistent Mind continuous-play playbook+ * phase (issue #7458). The pure picker lives in+ * `../lib/persistentMindPlaybookPhase.js`; this module owns the I/O that+ * feeds it — reading the same bounded Eidoverse world-signal projection the+ * World Design V2 recipe renders into districts.+ *+ * `collectEidoverseWorldSources` is dynamically imported so a mind running+ * in `default` playbook mode (the common case) never pays for the ~20+ * parallel service reads it performs; only an active `continuous-play` wake+ * reaches this module at all.+ */++import {+ derivePersistentMindPlaybookPhaseSignals,+ selectPersistentMindPlaybookPhase,+} from '../lib/persistentMindPlaybookPhase.js';++/**+ * Resolve the current continuous-play phase from live PortOS/Eidoverse world+ * signals. Never throws: a signal read failure degrades to the picker's+ * `explore` default rather than parking the wake.+ */+export async function resolvePersistentMindPlaybookPhase({ signal } = {}) {+ const worldSignals = await import('./eidoverseWorldSources.js')+ .then(({ collectEidoverseWorldSources }) => collectEidoverseWorldSources({ signal }))+ .catch((error) => {+ if (signal?.aborted) throw error;+ console.error(`❌ Persistent mind playbook phase signals unavailable: ${error.message}`);+ return null;+ });+ const signals = derivePersistentMindPlaybookPhaseSignals(worldSignals);+ return { ...selectPersistentMindPlaybookPhase(signals), signals };+}diff --git a/server/services/persistentMindPlaybookSignals.test.js b/server/services/persistentMindPlaybookSignals.test.jsnew file mode 100644index 0000000000..262e9aacdd--- /dev/null+++ b/server/services/persistentMindPlaybookSignals.test.js@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mock = vi.hoisted(() => ({ collectEidoverseWorldSources: vi.fn() }));++vi.mock('./eidoverseWorldSources.js', () => ({+ collectEidoverseWorldSources: (...args) => mock.collectEidoverseWorldSources(...args),+}));++const { resolvePersistentMindPlaybookPhase } = await import('./persistentMindPlaybookSignals.js');++beforeEach(() => {+ vi.clearAllMocks();+});++describe('resolvePersistentMindPlaybookPhase', () => {+ it('derives a phase from a live world-signals projection', async () => {+ mock.collectEidoverseWorldSources.mockResolvedValue({+ apps: [{ id: 'a' }, { id: 'b' }],+ agents: [{ id: 'c' }],+ features: [{ id: 'd' }],+ peers: [{ travelAvailable: true, status: 'active' }],+ productivity: [{ succeededToday: 8, failedToday: 0 }],+ });+ const result = await resolvePersistentMindPlaybookPhase();+ expect(mock.collectEidoverseWorldSources).toHaveBeenCalledTimes(1);+ expect(result.phase).toBe('coordinate');+ expect(result.signals).toMatchObject({ districtCount: 5, failureRate: 0, peersWithActivity: 1 });+ });++ it('degrades to the safe explore default when the signal read fails', async () => {+ mock.collectEidoverseWorldSources.mockRejectedValue(new Error('world source unavailable'));+ const result = await resolvePersistentMindPlaybookPhase();+ expect(result.phase).toBe('explore');+ expect(result.signals).toEqual({ districtCount: null, failureRate: null, peersWithActivity: null });+ });++ it('propagates an abort rather than swallowing it as a signal failure', async () => {+ const controller = new AbortController();+ controller.abort(new Error('turn interrupted'));+ mock.collectEidoverseWorldSources.mockRejectedValue(new Error('turn interrupted'));+ await expect(resolvePersistentMindPlaybookPhase({ signal: controller.signal })).rejects.toThrow('turn interrupted');+ });+});