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
fix: make all four Mind playbook phases reachable and gate Coordinate on measured peer contributions (#7630)
[._.]/ Adam Eivyd7337280d07c
diff --git a/docs/features/persistent-mind-continuous-play.md b/docs/features/persistent-mind-continuous-play.mdindex f7eeb1fb66..ad9b486d23 100644--- a/docs/features/persistent-mind-continuous-play.md+++ b/docs/features/persistent-mind-continuous-play.md@@ -13,16 +13,20 @@ Saving a playbook never starts inference. The Mind Context panel exposes the mod### Maturity-aware phases (#7458)-`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:+`continuous-play` no longer runs one fixed loop forever. Every wake, `resolvePersistentMindPlaybookPhase()` (`server/services/persistentMindPlaybookSignals.js`) reads the bounded Eidoverse world-signal projection the World Design recipe renders into districts (`buildEidoverseWorldSignals()`, `server/lib/eidoverseWorldSignals.js`) plus a non-committing observation report (`observeEidoverseWorld({ commit: false })`, `server/services/eidoverseObservationLedger.js`), reduces them to four 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 |+| **Explore** | Commons is sparse (fewer than 3 built signals, or signals unavailable) | Map affordances, reconnect presence, many small interactions |+| **Construct** | Commons has some shape (3–11 built signals) and nothing is broken or waiting | Densify districts — places, labels, structures, affordances |+| **Maintain** | Recent failure rate ≥ 25%, or the Commons is mature (12+ built signals) with no unread peer contributions | Repair broken projections, retire dead affordances, re-test foundations |+| **Coordinate** | The observation marker reports foundations inherited from a peer (or a new peer) since this mind last looked, that peer is reachable, 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.+**Density counts what a mind BUILT, not what PortOS ships** (#7630). The count sums apps, active agents, active tasks, peers, goals, memory categories, Jira groups, locally-authored foundations, and installed controllers. It deliberately excludes the install-constant scaffolding the same projection carries for the districts themselves — every registry feature (~15 rows whether enabled or not), the two fixed storage areas, and the single `operations`/`productivity`/`activity` summary rows. Those five put a floor of ~19 under the original count while the mature threshold was 16, so `explore` and `construct` were unreachable on every install and a brand-new one was told to steward a mature Commons. The districts still *show* features and storage; only this maturity signal stops counting them.++**`coordinate` measures unread contributions, not reachability.** It fires on `changes.newFoundations` entries that are *inherited* (a foundation this mind authored itself since the last look is not a peer waiting) plus `changes.newPeers`, with reachability kept as a necessary-but-insufficient precondition — you cannot visit a peer you cannot reach. A first observation has no marker to diff against, so it yields `null` ("not measured"), never a measured zero. The picker's observation read passes `commit: false`: advancing the visit marker here would consume the very trail the mind's own `eidoverse.observe` depends on.++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); construction outranks coordination below the maturity threshold, so a mind with a thin Commons keeps building rather than going visiting. The picker never reads a wall clock — it degrades to `explore` (the safe default) whenever a signal is unavailable rather than guessing.A failure rate only exists when work actually ran. `getTodayActivity()` reports `successRate: 0` for a day with zero completed agents, so the derivation requires a non-empty sample before trusting it: an idle day yields *no* failure signal (falling back to coarse health, then to `null`), never a fabricated 100%. Without that guard every wake before the day's first completed task would claim a 100% failure rate and force `maintain`, starving `construct` and `coordinate` entirely.diff --git a/server/lib/persistentMindPlaybook.js b/server/lib/persistentMindPlaybook.jsindex 52fe78133c..b3ad34ab89 100644--- a/server/lib/persistentMindPlaybook.js+++ b/server/lib/persistentMindPlaybook.js@@ -76,9 +76,9 @@ The Commons is established but something is broken, stale, or aging. Each wake,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)+ coordinate: `PLAYBOOK PHASE — Coordinate (new peer contributions since your last look)-Federated peers have activity worth your attention. Each wake, prefer this loop:+Since this mind last observed, foundations arrived from a federated peer, or a new peer joined. Nobody asked you to come — the signal is what changed in the ledger, not a message. Each wake, prefer this loop:1) Check eidoverse.status, then run eidoverse.observe FIRST: its peers section already shows which peers this install inherited foundations through, and foundations.inherited names those contributions. Read what a peer built before you go ask about it. Then, 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 — build on what a peer contributed, respond, and note anything worth bringing home. An inherited foundation keeps working without its author narrating it; chat is for what observation could not answer.diff --git a/server/lib/persistentMindPlaybook.test.js b/server/lib/persistentMindPlaybook.test.jsindex 56edbd3075..fabe4a5642 100644--- a/server/lib/persistentMindPlaybook.test.js+++ b/server/lib/persistentMindPlaybook.test.js@@ -57,6 +57,20 @@ describe('persistentMindPlaybook', () => {expect(composed.startsWith('Be concise.')).toBe(true);});+ // The regression #7630 names: the picker's peer signal was reachability,+ // and this template — the text the model actually reads — claimed "peers+ // waiting" with "activity worth your attention". A reachable peer with+ // nothing unread made that fabricated claim the steady state for every+ // mature install. The heading and opening sentence must claim only what+ // `peerContributionsUnread` measured: what ARRIVED since the last look.+ it('claims only the signal that selected it (#7630)', () => {+ const coordinate = PERSISTENT_MIND_PLAYBOOK_PHASE_INSTRUCTIONS.coordinate;+ const opening = coordinate.split('\n\n').slice(0, 2).join(' ');+ expect(opening).not.toMatch(/peers waiting|worth your attention/i);+ expect(opening).toMatch(/since (this mind|you) last (observed|looked)/i);+ expect(opening).toMatch(/arrived|new peer/i);+ });+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');diff --git a/server/lib/persistentMindPlaybookPhase.js b/server/lib/persistentMindPlaybookPhase.jsindex 3c477ff10b..91d80454c8 100644--- a/server/lib/persistentMindPlaybookPhase.js+++ b/server/lib/persistentMindPlaybookPhase.js@@ -8,9 +8,10 @@* 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`.+ * from `buildEidoverseWorldSignals()` and from an `observeEidoverseWorld()`+ * report (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([@@ -21,15 +22,31 @@ export const PERSISTENT_MIND_PLAYBOOK_PHASES = Object.freeze([]);/**- * 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.+ * Thresholds are counted in what a MIND BUILT, not in what PortOS ships.+ *+ * The count sums the genuinely-variable world populations (apps, active+ * agents, active tasks, peers, goals, memory categories, Jira groups) plus the+ * two durable Eidoverse populations a mind grows itself: locally-authored+ * foundations and installed controllers. It deliberately EXCLUDES the+ * install-constant scaffolding `buildEidoverseWorldSignals()` also projects —+ * `features` (one row per registry feature, enabled or not: a fixed ~15),+ * `storage` (always `database` + `filesystem`: a fixed 2), and the single+ * `operations` / `productivity` / `activity` summary rows (a fixed 3). Those+ * five sources put a floor of ~19 under the old count, which is above the old+ * `matureDistrictCount: 16` — so `explore` and `construct` were unreachable on+ * every install and a brand-new one was told to steward a mature Commons+ * (#7630). The districts still SHOW features and storage; only this maturity+ * signal stops counting them.+ *+ * Calibration on the recalibrated scale: a fresh install with nothing built+ * measures 0. One with a few apps, a task or two, and a handful of authored+ * foundations or an installed controller lands in the single digits. An+ * established Commons — authored foundations, armed controllers, goals, memory+ * categories, live work — clears the mature threshold comfortably.*/const THRESHOLDS = Object.freeze({- sparseDistrictCount: 4,- matureDistrictCount: 16,+ sparseDistrictCount: 3,+ matureDistrictCount: 12,highFailureRate: 0.25,});@@ -81,50 +98,109 @@ const healthFailureRate = (health) => {return null;};+/**+ * Foundations this install AUTHORED, excluding the copies it pulled from a+ * peer. A mind that inherited fifty foundations has a well-connected Commons,+ * not a densely-built one, and counting them here would let federation alone+ * carry an install to `maintain`. `inherited` is a documented subset of+ * `baseline` (see `listEidoverseFoundations`), so subtracting it is exact.+ */+function authoredFoundationCount(observation) {+ const counts = observation?.foundations?.counts;+ if (!counts || typeof counts !== 'object') return null;+ const vernacular = nonNegativeIntOrNull(counts.vernacular);+ const baseline = nonNegativeIntOrNull(counts.baseline);+ if (vernacular === null || baseline === null) return null;+ return Math.max(0, vernacular + baseline - (nonNegativeIntOrNull(counts.inherited) ?? 0));+}++/**+ * Peer contributions this mind has not looked at yet — the signal #7458's own+ * acceptance criteria named ("unread peer contributions") and never wired up.+ *+ * Three distinctions matter here:+ *+ * - A FIRST observation has no marker to diff against, so nothing was+ * measured and this is `null` ("unknown"), never a measured `0`. Reporting+ * zero there would be the same fabricated-signal defect in mirror image.+ * - Only INHERITED arrivals count. `changes.newFoundations` also lists+ * foundations this mind authored since its last look, and telling it a peer+ * is waiting because of its own work is exactly the claim #7630 removed.+ * The inherited row list is capped at the most recent 20, which by+ * construction covers every newly-inherited id.+ * - A new peer counts on its own: a federation link that did not exist last+ * wake is a contribution worth going to read.+ */+function derivePeerContributionsUnread(observation) {+ const changes = observation?.changes;+ if (!changes || typeof changes !== 'object' || changes.firstObservation === true) return null;+ const newFoundations = Array.isArray(changes.newFoundations) ? changes.newFoundations : null;+ const newPeers = Array.isArray(changes.newPeers) ? changes.newPeers : null;+ if (newFoundations === null && newPeers === null) return null;+ const inheritedIds = new Set((Array.isArray(observation?.foundations?.inherited) ? observation.foundations.inherited : [])+ .map((entry) => entry?.id)+ .filter(Boolean));+ const inheritedArrivals = (newFoundations ?? []).filter((id) => inheritedIds.has(id)).length;+ return inheritedArrivals + (newPeers?.length ?? 0);+}+/*** 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+ * `server/lib/eidoverseWorldSignals.js`) and, optionally, an+ * `observeEidoverseWorld()` report (see+ * `server/services/eidoverseObservationLedger.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, failureRateMeasured: false, peersReachable: null };- }+export function derivePersistentMindPlaybookPhaseSignals(worldSignals, observation = null) {+ const world = worldSignals && typeof worldSignals === 'object' ? worldSignals : null;// A failed source read arrives as `null`, not `[]`. Counting those as zero// would report a confidently empty Commons when the truth is that nothing// could be read, so an all-null projection degrades to `null` ("unknown")- // and only genuinely-present districts contribute to the count.- const districtEntries = [- worldSignals.apps, worldSignals.agents, worldSignals.tasks, worldSignals.features,- worldSignals.peers, worldSignals.activity, worldSignals.goals, worldSignals.memory,- worldSignals.storage, worldSignals.jira, worldSignals.operations,- ].filter((entries) => Array.isArray(entries));- const districtCount = districtEntries.length > 0- ? districtEntries.reduce((total, entries) => total + entries.length, 0)+ // and only genuinely-present populations contribute to the count.+ //+ // `features`, `storage`, `operations`, and the `productivity`/`activity`+ // summary rows are deliberately absent — see THRESHOLDS above.+ const populations = [+ world?.apps, world?.agents, world?.tasks,+ world?.peers, world?.goals, world?.memory, world?.jira,+ ]+ .filter((entries) => Array.isArray(entries))+ .map((entries) => entries.length);+ for (const built of [authoredFoundationCount(observation), nonNegativeIntOrNull(observation?.controllers?.counts?.total)]) {+ if (built !== null) populations.push(built);+ }+ const districtCount = populations.length > 0+ ? populations.reduce((total, count) => total + count, 0): null;- const productivity = Array.isArray(worldSignals.productivity) ? worldSignals.productivity[0] : null;+ const productivity = Array.isArray(world?.productivity) ? world.productivity[0] : null;// `??` (not `||`) so a measured zero-failure day stays 0 rather than// falling through to the coarse health signal.const measured = measuredFailureRate(productivity);- const failureRate = measured ?? healthFailureRate(worldSignals.health);+ const failureRate = measured ?? healthFailureRate(world?.health);// Peers this mind can actually travel to. This is NOT "peers with unread// contributions": a peer is only a travel destination when `listEidoverse// Destinations()` saw it `status === 'online'`, which `coarseStatus` maps to// `active` — so filtering the projection for a non-`steady` status was true- // for every travelable peer and measured nothing. Count reachability, say- // reachability, and let it rank below construction so one permanently-online- // peer cannot pin every wake to `coordinate`.- const peersReachable = Array.isArray(worldSignals.peers)- ? worldSignals.peers.filter((peer) => peer?.travelAvailable === true).length+ // for every travelable peer and measured nothing. Reachability is a+ // NECESSARY-BUT-INSUFFICIENT precondition for `coordinate` (you cannot visit+ // a peer you cannot reach); `peerContributionsUnread` is what makes it fire.+ const peersReachable = Array.isArray(world?.peers)+ ? world.peers.filter((peer) => peer?.travelAvailable === true).length: null;- return { districtCount, failureRate, failureRateMeasured: measured !== null, peersReachable };+ return {+ districtCount,+ failureRate,+ failureRateMeasured: measured !== null,+ peersReachable,+ peerContributionsUnread: derivePeerContributionsUnread(observation),+ };}/**@@ -136,23 +212,26 @@ export function derivePersistentMindPlaybookPhaseSignals(worldSignals) {* Priority, highest first: a still-sparse Commons always explores first; a* high recent failure rate (or an unhealthy install) outranks everything else,* because fixing what is broken comes before building or visiting; a Commons- * short of the maturity threshold keeps building; a mature Commons with a- * reachable peer goes visiting; an otherwise mature, peer-less Commons falls- * back to steady-state maintenance.+ * short of the maturity threshold keeps building; a mature Commons with unread+ * peer contributions it can actually reach goes visiting; an otherwise mature+ * Commons falls back to steady-state maintenance.*- * `coordinate` deliberately ranks BELOW `construct`. The peer signal measures- * reachability, not unread activity, so a single always-online peer would- * otherwise satisfy it on every wake and `construct` would never run.+ * `coordinate` requires BOTH halves of its claim to be measured: unread+ * contributions (what the phase tells the mind is waiting) and a reachable+ * peer (whether it can go). Reachability alone is not enough — one+ * always-online peer would otherwise satisfy it on every wake, and the+ * template would tell the mind peers are waiting when nothing was measured.*/export function selectPersistentMindPlaybookPhase(signals = {}) {const districtCount = nonNegativeIntOrNull(signals.districtCount);const failureRate = clampFractionOrNull(signals.failureRate);const peersReachable = nonNegativeIntOrNull(signals.peersReachable);+ const peerContributionsUnread = nonNegativeIntOrNull(signals.peerContributionsUnread);if (districtCount === null || districtCount < THRESHOLDS.sparseDistrictCount) {return {phase: 'explore',- reason: districtCount === null ? 'world signals unavailable' : `sparse Commons (${districtCount} live signal(s))`,+ reason: districtCount === null ? 'world signals unavailable' : `sparse Commons (${districtCount} built signal(s))`,};}if (failureRate !== null && failureRate >= THRESHOLDS.highFailureRate) {@@ -167,10 +246,13 @@ export function selectPersistentMindPlaybookPhase(signals = {}) {};}if (districtCount < THRESHOLDS.matureDistrictCount) {- return { phase: 'construct', reason: `${districtCount} live signal(s), room to densify before ${THRESHOLDS.matureDistrictCount}` };+ return { phase: 'construct', reason: `${districtCount} built signal(s), room to densify before ${THRESHOLDS.matureDistrictCount}` };}- if (peersReachable !== null && peersReachable > 0) {- return { phase: 'coordinate', reason: `${peersReachable} reachable peer(s) to visit` };+ if (peerContributionsUnread !== null && peerContributionsUnread > 0 && peersReachable !== null && peersReachable > 0) {+ return {+ phase: 'coordinate',+ reason: `${peerContributionsUnread} unread peer contribution(s), ${peersReachable} reachable peer(s)`,+ };}- return { phase: 'maintain', reason: `mature Commons (${districtCount} live signal(s)), steady-state upkeep` };+ return { phase: 'maintain', reason: `mature Commons (${districtCount} built signal(s)), steady-state upkeep` };}diff --git a/server/lib/persistentMindPlaybookPhase.test.js b/server/lib/persistentMindPlaybookPhase.test.jsindex fcab378325..f070632b35 100644--- a/server/lib/persistentMindPlaybookPhase.test.js+++ b/server/lib/persistentMindPlaybookPhase.test.js@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import { buildEidoverseWorldSignals, eidoversePeerId } from './eidoverseWorldSignals.js';+import { buildEidoverseObservation } from './eidoverseObservation.js';import {PERSISTENT_MIND_PLAYBOOK_PHASES,derivePersistentMindPlaybookPhaseSignals,@@ -14,17 +15,17 @@ describe('selectPersistentMindPlaybookPhase', () => {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');+ expect(selectPersistentMindPlaybookPhase({ districtCount: 2 }).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, peersReachable: 0 });+ const result = selectPersistentMindPlaybookPhase({ districtCount: 3, failureRate: 0, peersReachable: 0 });expect(result).toMatchObject({ phase: 'construct' });});- it('maintains when the recent failure rate crosses the threshold, even with peers reachable', () => {+ it('maintains when the recent failure rate crosses the threshold, even with unread peer contributions', () => {const result = selectPersistentMindPlaybookPhase({- districtCount: 10, failureRate: 0.25, failureRateMeasured: true, peersReachable: 3,+ districtCount: 20, failureRate: 0.25, failureRateMeasured: true, peersReachable: 3, peerContributionsUnread: 4,});expect(result).toMatchObject({ phase: 'maintain', reason: expect.stringContaining('25%') });});@@ -34,42 +35,68 @@ describe('selectPersistentMindPlaybookPhase', () => {// failure rate" would claim a rate on a day when zero work ran.it('never reports an unmeasured, health-derived rate as a percentage', () => {const result = selectPersistentMindPlaybookPhase({- districtCount: 10, failureRate: 0.5, failureRateMeasured: false, peersReachable: 0,+ districtCount: 20, failureRate: 0.5, failureRateMeasured: false, peersReachable: 0,});expect(result.phase).toBe('maintain');expect(result.reason).not.toMatch(/%/);expect(result.reason).toContain('health');});- // A reachable peer must not outrank construction: the peer signal measures- // reachability, so one always-online peer would otherwise pin every wake to- // `coordinate` and `construct` would never run.- it('keeps building below the mature threshold even with a reachable peer', () => {- const result = selectPersistentMindPlaybookPhase({ districtCount: 10, failureRate: 0.1, peersReachable: 1 });+ // Coordination must not outrank construction below the maturity threshold:+ // a mind with a thin Commons should keep building rather than go visiting.+ it('keeps building below the mature threshold even with unread peer contributions', () => {+ const result = selectPersistentMindPlaybookPhase({+ districtCount: 10, failureRate: 0.1, peersReachable: 1, peerContributionsUnread: 3,+ });expect(result).toMatchObject({ phase: 'construct' });});- it('coordinates once the Commons is mature and a peer is reachable', () => {- const result = selectPersistentMindPlaybookPhase({ districtCount: 16, failureRate: 0.1, peersReachable: 1 });- expect(result).toMatchObject({ phase: 'coordinate', reason: expect.stringContaining('reachable peer') });+ // The regression #7630 names: reachability alone selected `coordinate`, and+ // the template it selects tells the mind "peers have activity worth your+ // attention" — a claim nothing measured. One always-online peer made that+ // the steady state for every mature install.+ it('does not coordinate for a reachable peer with nothing unread', () => {+ expect(selectPersistentMindPlaybookPhase({+ districtCount: 20, failureRate: 0, peersReachable: 2, peerContributionsUnread: 0,+ })).toMatchObject({ phase: 'maintain' });+ // An unmeasured contribution count (first observation, failed read) is+ // likewise not a reason to claim a peer is waiting.+ expect(selectPersistentMindPlaybookPhase({+ districtCount: 20, failureRate: 0, peersReachable: 2, peerContributionsUnread: null,+ })).toMatchObject({ phase: 'maintain' });+ });++ // Reachability stays a necessary-but-insufficient precondition: a mind+ // cannot visit a peer it cannot travel to, however much arrived from it.+ it('does not coordinate with unread contributions from an unreachable peer', () => {+ expect(selectPersistentMindPlaybookPhase({+ districtCount: 20, failureRate: 0, peersReachable: 0, peerContributionsUnread: 3,+ })).toMatchObject({ phase: 'maintain' });+ });++ it('coordinates once the Commons is mature and unread contributions arrived from a reachable peer', () => {+ const result = selectPersistentMindPlaybookPhase({+ districtCount: 12, failureRate: 0.1, peersReachable: 1, peerContributionsUnread: 2,+ });+ expect(result).toMatchObject({ phase: 'coordinate', reason: expect.stringContaining('unread peer contribution') });});it('stays in construct just below the mature threshold once failures/peers are quiet', () => {- const result = selectPersistentMindPlaybookPhase({ districtCount: 15, failureRate: 0, peersReachable: 0 });+ const result = selectPersistentMindPlaybookPhase({ districtCount: 11, failureRate: 0, peersReachable: 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, peersReachable: 0 });+ const result = selectPersistentMindPlaybookPhase({ districtCount: 12, failureRate: 0, peersReachable: 0 });expect(result).toMatchObject({ phase: 'maintain', reason: expect.stringContaining('mature') });});it('always resolves to a documented phase', () => {const matrix = [{},- { districtCount: -5, failureRate: -1, peersReachable: -2 },+ { districtCount: -5, failureRate: -1, peersReachable: -2, peerContributionsUnread: -3 },{ districtCount: Number.NaN, failureRate: Number.NaN },- { districtCount: 100, failureRate: 0.9, peersReachable: 5 },+ { districtCount: 100, failureRate: 0.9, peersReachable: 5, peerContributionsUnread: 5 },];for (const signals of matrix) {expect(PERSISTENT_MIND_PLAYBOOK_PHASES).toContain(selectPersistentMindPlaybookPhase(signals).phase);@@ -84,26 +111,63 @@ describe('selectPersistentMindPlaybookPhase', () => {describe('derivePersistentMindPlaybookPhaseSignals', () => {it('returns null signals for a missing or malformed world-signals projection', () => {- const empty = { districtCount: null, failureRate: null, failureRateMeasured: false, peersReachable: null };+ const empty = {+ districtCount: null, failureRate: null, failureRateMeasured: false, peersReachable: null, peerContributionsUnread: null,+ };expect(derivePersistentMindPlaybookPhaseSignals(null)).toEqual(empty);expect(derivePersistentMindPlaybookPhaseSignals('not-an-object')).toEqual(empty);});- it('sums entities across every projected district array', () => {+ it('sums only the populations a mind grows, never the install-constant scaffolding', () => {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: [],+ // Install-constant scaffolding: ~15 feature rows whether enabled or not,+ // two fixed storage areas, and one summary row each for operations,+ // productivity, and activity. These put a floor of ~19 under the old+ // count and made explore/construct unreachable (#7630).+ features: [{ id: 'd' }, { id: 'e' }, { id: 'f' }],+ storage: [{ id: 'i' }, { id: 'j' }],operations: [{ id: 'k' }],+ productivity: [{ id: 'p' }],+ activity: [{ id: 'q' }],+ });+ expect(signals.districtCount).toBe(2 + 1 + 0 + 1 + 0);+ });++ it('adds locally-authored foundations and installed controllers, excluding inherited copies', () => {+ // A mind that inherited fifty foundations has a well-connected Commons,+ // not a densely-built one, so `inherited` (a subset of `baseline`) is+ // subtracted rather than counted as construction.+ const signals = derivePersistentMindPlaybookPhaseSignals({ apps: [{ id: 'a' }] }, {+ foundations: { counts: { vernacular: 3, baseline: 5, candidates: 1, inherited: 4 } },+ controllers: { counts: { total: 2, armed: 1, delivering: 0 } },+ });+ expect(signals.districtCount).toBe(1 + (3 + 5 - 4) + 2);+ });++ it('treats an unavailable observation as unknown rather than as zero built entities', () => {+ // A failed observation read must not report "this mind has authored+ // nothing" — that is the absent-vs-empty rule the density signal already+ // applies to the world projection.+ const withoutObservation = derivePersistentMindPlaybookPhaseSignals({ apps: [{ id: 'a' }] }, null);+ expect(withoutObservation.districtCount).toBe(1);+ expect(withoutObservation.peerContributionsUnread).toBeNull();++ const everythingUnavailable = derivePersistentMindPlaybookPhaseSignals({ apps: null, agents: null }, null);+ expect(everythingUnavailable.districtCount).toBeNull();++ // An observation alone still measures something, even with no projection.+ const observationOnly = derivePersistentMindPlaybookPhaseSignals(null, {+ foundations: { counts: { vernacular: 2, baseline: 0, candidates: 0, inherited: 0 } },+ controllers: { counts: { total: 0, armed: 0, delivering: 0 } },});- expect(signals.districtCount).toBe(2 + 1 + 0 + 1 + 0 + 3 + 0 + 1 + 2 + 0 + 1);+ expect(observationOnly.districtCount).toBe(2);});it('prefers today failed/succeeded counts over successRate when both are present', () => {@@ -187,41 +251,222 @@ describe('derivePersistentMindPlaybookPhaseSignals', () => {});expect(signals.peersReachable).toBe(3);});++ describe('peerContributionsUnread', () => {+ const observationWith = (changes, inheritedRows = []) => ({+ foundations: { counts: { vernacular: 0, baseline: 0, candidates: 0, inherited: 0 }, inherited: inheritedRows },+ changes,+ });++ it('is null on a first observation, which measured nothing to compare against', () => {+ const signals = derivePersistentMindPlaybookPhaseSignals({}, observationWith({+ firstObservation: true, newFoundations: [], newPeers: [],+ }));+ expect(signals.peerContributionsUnread).toBeNull();+ });++ it('is a measured zero when the marker diff ran and nothing arrived', () => {+ const signals = derivePersistentMindPlaybookPhaseSignals({}, observationWith({+ firstObservation: false, newFoundations: [], newPeers: [],+ }));+ expect(signals.peerContributionsUnread).toBe(0);+ });++ it('ignores foundations this mind authored itself since the last look', () => {+ // `changes.newFoundations` lists every foundation id absent from the+ // marker, including the mind's own work. Counting those would tell it a+ // peer is waiting because of something it built.+ const signals = derivePersistentMindPlaybookPhaseSignals({}, observationWith(+ { firstObservation: false, newFoundations: ['local:mine'], newPeers: [] },+ [{ id: 'peer:alpha:one' }],+ ));+ expect(signals.peerContributionsUnread).toBe(0);+ });++ it('counts newly inherited foundations and newly appeared peers', () => {+ const signals = derivePersistentMindPlaybookPhaseSignals({}, observationWith(+ { firstObservation: false, newFoundations: ['peer:alpha:one', 'local:mine'], newPeers: ['peer-digest'] },+ [{ id: 'peer:alpha:one' }],+ ));+ expect(signals.peerContributionsUnread).toBe(2);+ });++ it('is null when the observation carries no readable changes section', () => {+ expect(derivePersistentMindPlaybookPhaseSignals({}, { changes: null }).peerContributionsUnread).toBeNull();+ expect(derivePersistentMindPlaybookPhaseSignals({}, observationWith({ firstObservation: false }))+ .peerContributionsUnread).toBeNull();+ });+ });});-describe('contract with buildEidoverseWorldSignals()', () => {- // Reads a real projection (not a hand-built fixture matching this module's- // own assumptions) so a future shape change to eidoverseWorldSignals.js- // that silently breaks phase derivation fails here rather than only in- // production. See server/lib/eidoverseWorldSignals.js.- it('derives a sane, non-null signal set from a representative world-signals projection', () => {- const peerId = eidoversePeerId({ instanceId: 'fixture-peer' });- const worldSignals = buildEidoverseWorldSignals({- apps: [{ overallStatus: 'online', managed: true }, { overallStatus: 'stopped', managed: false }],- agents: [{ id: 'agent-1', status: 'running' }],- taskState: { tasks: [{ id: 'task-1', status: 'pending' }] },- cosStatus: { running: true, activeAgents: 1, pausedAgents: 0 },- review: { total: 2, cos: 1, alert: 0 },- featuresState: { features: [{ id: 'feature-a', enabled: true }] },- peers: [{ instanceId: 'fixture-peer', enabled: true, status: 'active' }],- backupState: { status: 'success', filesChanged: 3 },- notifications: { total: 4, unread: 1 },- character: { level: 3 },- voiceConfig: { enabled: false },- memory: { total: 100, used: 10 },- diskPercent: 40,- todayActivity: { stats: { completed: 5, succeeded: 4, failed: 1, successRate: 80 }, isRunning: false, isPaused: false },- velocity: { today: 5, todaySuccesses: 4, todayFailures: 1, velocity: 1.2, avgPerDay: 3, historicalDays: 30 },- activityCalendar: { weeks: [], summary: {} },- goalsData: { goals: [{ id: 'goal-1', status: 'active', progress: 40, milestones: [], todos: [] }] },- memoryGraph: { nodes: [{ id: 'n1', category: 'fact', importance: 1 }], edges: [] },- inboxCounts: { total: 1, needs_review: 0, classifying: 0 },- introspection: { db: { tables: ['t1'] }, fs: { domains: ['d1'], totalBytes: 10, totalFiles: 2 } },- jira: [],- destinations: new Set([peerId]),+/**+ * Calibration against the SHIPPED builders, not against hand-built signal+ * objects with the counts a test author chose.+ *+ * #7630's root cause is that every earlier fixture here was hand-written, so a+ * count the real builder could never produce (its floor was ~19, above the+ * old mature threshold of 16) passed a suite that pinned only the shape. These+ * cases run `buildEidoverseWorldSignals()` and `buildEidoverseObservation()`+ * and assert that all four phases are reachable from what they actually emit.+ */+describe('calibration against the shipped signal + observation builders', () => {+ const PEER_INSTANCE = 'fixture-peer-instance';+ const PEER_ID = eidoversePeerId({ instanceId: PEER_INSTANCE });++ // The install-constant scaffolding the old count summed: one row per+ // registry feature whether enabled or not (~15 on a shipped install).+ const registryFeatures = (count = 15) => Array.from({ length: count }, (_, index) => ({+ id: `feature-${index}`, enabled: index % 2 === 0,+ }));++ const worldSignalsFor = ({+ apps = [], agents = [], tasks = [], peers = [], goals = [], memoryNodes = [],+ features = registryFeatures(), destinations = new Set(),+ } = {}) => buildEidoverseWorldSignals({+ apps,+ agents,+ taskState: { tasks },+ cosStatus: { running: true, activeAgents: 0, pausedAgents: 0 },+ review: { total: 0, cos: 0, alert: 0 },+ featuresState: { features },+ peers,+ backupState: { status: 'success', filesChanged: 0 },+ notifications: { total: 0, unread: 0 },+ character: { level: 1 },+ voiceConfig: { enabled: false },+ memory: { total: 100, used: 10 },+ diskPercent: 30,+ todayActivity: { stats: { completed: 4, succeeded: 4, failed: 0, successRate: 100 }, isRunning: false, isPaused: false },+ activityCalendar: { weeks: [], summary: {} },+ goalsData: { goals },+ memoryGraph: { nodes: memoryNodes, edges: [] },+ inboxCounts: { total: 0, needs_review: 0, classifying: 0 },+ introspection: { db: { tables: [] }, fs: { domains: [], totalBytes: 0, totalFiles: 0 } },+ jira: [],+ destinations,+ });++ const authored = (id) => ({ id, kind: 'affordance', title: 'Local build', layer: 'vernacular' });+ const inheritedFrom = (id) => ({+ id,+ kind: 'affordance',+ title: 'Inherited build',+ layer: 'baseline',+ inheritance: {+ type: 'inherited-from',+ originInstanceId: PEER_INSTANCE,+ sourceInstanceId: PEER_INSTANCE,+ inheritedAt: '2026-09-17T10:00:00.000Z',+ },+ });++ const countsFor = (foundations) => ({+ vernacular: foundations.filter((entry) => entry.layer === 'vernacular').length,+ baseline: foundations.filter((entry) => entry.layer === 'baseline').length,+ candidates: 0,+ inherited: foundations.filter((entry) => entry.inheritance).length,+ });++ const observationFor = (worldSignals, { foundations = [], controllers = 0, marker = null } = {}) => buildEidoverseObservation({+ source: worldSignals,+ foundations,+ foundationCounts: countsFor(foundations),+ controllerInstalls: [],+ controllerCounts: { total: controllers, armed: controllers, delivering: 0 },+ marker,+ observedAt: '2026-09-18T09:00:00.000Z',+ });++ const phaseFor = (world, observationOptions) => {+ const { report } = observationFor(world, observationOptions);+ return selectPersistentMindPlaybookPhase(derivePersistentMindPlaybookPhaseSignals(world, report));+ };++ const emptyInstall = () => worldSignalsFor();+ const someBuilt = () => worldSignalsFor({+ apps: [{ overallStatus: 'online', managed: true }, { overallStatus: 'online', managed: true }],+ tasks: [{ id: 'task-1', status: 'pending' }],+ });+ const denseCommons = ({ peers = [], destinations = new Set() } = {}) => worldSignalsFor({+ apps: [1, 2, 3, 4].map(() => ({ overallStatus: 'online', managed: true })),+ agents: [{ id: 'agent-1', status: 'running' }, { id: 'agent-2', status: 'running' }],+ tasks: [1, 2, 3, 4, 5].map((n) => ({ id: `task-${n}`, status: 'pending' })),+ goals: [{ id: 'goal-1', status: 'active', progress: 10, milestones: [], todos: [] }],+ memoryNodes: [{ id: 'n1', category: 'fact', importance: 1 }, { id: 'n2', category: 'plan', importance: 1 }],+ peers,+ destinations,+ });++ it('reaches explore on a maximally-empty install', () => {+ // The defect: this install measured 19 and was told its Commons was mature.+ expect(phaseFor(emptyInstall())).toMatchObject({ phase: 'explore' });+ });++ it('reaches construct with a handful of authored foundations and a little live work', () => {+ const foundations = ['f-1', 'f-2', 'f-3'].map(authored);+ expect(phaseFor(someBuilt(), { foundations })).toMatchObject({ phase: 'construct' });+ });++ it('reaches maintain on a dense Commons with nothing unread', () => {+ const foundations = ['f-1', 'f-2', 'f-3', 'f-4', 'f-5', 'f-6'].map(authored);+ expect(phaseFor(denseCommons(), { foundations, controllers: 2 })).toMatchObject({ phase: 'maintain' });+ });++ it('reaches coordinate only once the marker reports a foundation inherited since the last look', () => {+ const peers = [{ instanceId: PEER_INSTANCE, enabled: true, status: 'active' }];+ const world = denseCommons({ peers, destinations: new Set([PEER_ID]) });+ const authoredSix = ['f-1', 'f-2', 'f-3', 'f-4', 'f-5', 'f-6'].map(authored);++ // A settled world: the mind has looked before and nothing arrived since.+ const settled = observationFor(world, { foundations: authoredSix, controllers: 2 });+ const steady = observationFor(world, { foundations: authoredSix, controllers: 2, marker: settled.marker });+ expect(selectPersistentMindPlaybookPhase(derivePersistentMindPlaybookPhaseSignals(world, steady.report)))+ .toMatchObject({ phase: 'maintain' });++ // The mind's OWN new foundation is not a peer waiting.+ const selfAuthored = observationFor(world, {+ foundations: [...authoredSix, authored('f-7')], controllers: 2, marker: settled.marker,+ });+ expect(selfAuthored.report.changes.newFoundations).toContain('f-7');+ expect(selectPersistentMindPlaybookPhase(derivePersistentMindPlaybookPhaseSignals(world, selfAuthored.report)))+ .toMatchObject({ phase: 'maintain' });++ // A foundation inherited from the peer is.+ const arrived = observationFor(world, {+ foundations: [...authoredSix, inheritedFrom('peer:alpha:one')], controllers: 2, marker: settled.marker,+ });+ expect(selectPersistentMindPlaybookPhase(derivePersistentMindPlaybookPhaseSignals(world, arrived.report)))+ .toMatchObject({ phase: 'coordinate' });+ });++ // The guard #7630's acceptance names: density must move with what a mind+ // built and stay still when PortOS scaffolding changes underneath it.+ it('responds to an authored foundation and ignores an instance-feature toggle', () => {+ const foundations = ['f-1', 'f-2', 'f-3'].map(authored);+ const baseline = derivePersistentMindPlaybookPhaseSignals(someBuilt(), observationFor(someBuilt(), { foundations }).report);++ const featuresChanged = worldSignalsFor({+ apps: [{ overallStatus: 'online', managed: true }, { overallStatus: 'online', managed: true }],+ tasks: [{ id: 'task-1', status: 'pending' }],+ // Every feature enabled, plus five more registry entries.+ features: registryFeatures(20).map((feature) => ({ ...feature, enabled: true })),});+ const afterToggle = derivePersistentMindPlaybookPhaseSignals(featuresChanged, observationFor(featuresChanged, { foundations }).report);+ expect(afterToggle.districtCount).toBe(baseline.districtCount);+ // The districts themselves still show features — only the maturity signal stops counting them.+ expect(featuresChanged.features).toHaveLength(20);++ const grown = ['f-1', 'f-2', 'f-3', 'f-4'].map(authored);+ const afterAuthoring = derivePersistentMindPlaybookPhaseSignals(someBuilt(), observationFor(someBuilt(), { foundations: grown }).report);+ expect(afterAuthoring.districtCount).toBe(baseline.districtCount + 1);+ });- const signals = derivePersistentMindPlaybookPhaseSignals(worldSignals);+ it('derives a sane, non-null signal set from a representative projection', () => {+ const world = denseCommons({+ peers: [{ instanceId: PEER_INSTANCE, enabled: true, status: 'active' }],+ destinations: new Set([PEER_ID]),+ });+ const signals = derivePersistentMindPlaybookPhaseSignals(world, observationFor(world).report);expect(signals.districtCount).toBeGreaterThan(0);expect(signals.failureRate).not.toBeNull();expect(signals.peersReachable).toBe(1);diff --git a/server/services/eidoverseObservationLedger.js b/server/services/eidoverseObservationLedger.jsindex a1383ed7d1..7c2b422b7b 100644--- a/server/services/eidoverseObservationLedger.js+++ b/server/services/eidoverseObservationLedger.js@@ -94,6 +94,12 @@ async function resolveDesign() {* this is not idempotent, and the tool is declared a `write` rather than a* read. Pass `{ commit: false }` to look without stamping.*+ * Pass a `source` when the caller has ALREADY collected the world-signal+ * projection this turn (the playbook phase picker does, #7630):+ * `collectEidoverseWorldSources()` fans out across ~20 service reads, and+ * collecting it twice in one wake doubles that for a projection already in+ * hand.+ ** Travel destinations are deliberately NOT collected here:* `collectEidoverseWorldSources()` already resolves them and folds the result* into `source.peers[].travelAvailable`, and `listEidoverseDestinations()`@@ -105,9 +111,9 @@ async function resolveDesign() {* still get to see its districts. `null` sections are reported as unavailable,* never as empty (`readSource` in the pure lib).*/-export async function observeEidoverseWorld({ signal, commit = true, now = () => new Date().toISOString() } = {}) {+export async function observeEidoverseWorld({ signal, commit = true, source: collectedSource = null, now = () => new Date().toISOString() } = {}) {const [source, ledger, controllers, design] = await Promise.all([- import('./eidoverseWorldSources.js')+ collectedSource ?? import('./eidoverseWorldSources.js').then((module) => module.collectEidoverseWorldSources({ signal })).catch(() => ({})),import('./eidoverseFoundationLedger.js')diff --git a/server/services/persistentMindPlaybookSignals.js b/server/services/persistentMindPlaybookSignals.jsindex a705e33632..e2836e9a89 100644--- a/server/services/persistentMindPlaybookSignals.js+++ b/server/services/persistentMindPlaybookSignals.js@@ -2,13 +2,15 @@* 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.+ * feeds it — the bounded Eidoverse world-signal projection the World Design+ * recipe renders into districts, plus the observation report that says what+ * arrived from a peer since this mind last looked.*- * `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.+ * Both collaborators are dynamically imported so a mind running in `default`+ * playbook mode (the common case) never pays for the ~20 parallel service+ * reads they perform; only an active `continuous-play` wake reaches this+ * module at all. The projection is collected once and handed to the+ * observation so the wake does not fan out across those reads twice.*/import {@@ -16,19 +18,38 @@ import {selectPersistentMindPlaybookPhase,} from '../lib/persistentMindPlaybookPhase.js';+/**+ * Degrade one signal read to `null` ("unknown") rather than parking the wake.+ * An abort is NOT a signal failure — the turn was interrupted, and swallowing+ * it here would let the wake continue against a world nobody read.+ */+const orNull = (what, signal) => (error) => {+ if (signal?.aborted) throw error;+ console.error(`❌ Persistent mind playbook phase ${what} unavailable: ${error.message}`);+ return null;+};+/*** 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.+ * signals. Never throws (except on abort): a signal read failure degrades to+ * the picker's `explore` default rather than parking the wake.+ *+ * `commit: false` on the observation is load-bearing. Observing normally+ * advances the visit marker, and the picker must not consume the "what is new+ * since I last looked" trail that the mind's own `eidoverse.observe` call —+ * and the very `coordinate` phase this resolves — depends on.*/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);+ .catch(orNull('signals', signal));+ const observation = await import('./eidoverseObservationLedger.js')+ .then(({ observeEidoverseWorld }) => observeEidoverseWorld({+ signal,+ commit: false,+ source: worldSignals ?? {},+ }))+ .catch(orNull('observation', signal));+ const signals = derivePersistentMindPlaybookPhaseSignals(worldSignals, observation);return { ...selectPersistentMindPlaybookPhase(signals), signals };}diff --git a/server/services/persistentMindPlaybookSignals.test.js b/server/services/persistentMindPlaybookSignals.test.jsindex 23002ce9f3..fec75a0130 100644--- a/server/services/persistentMindPlaybookSignals.test.js+++ b/server/services/persistentMindPlaybookSignals.test.js@@ -1,45 +1,145 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+/**+ * The live half of the continuous-play phase picker.+ *+ * These run the REAL `eidoverseObservationLedger` against a temp data root+ * (only the leaf service reads are mocked) because the contract that matters+ * here cannot be proved with a mocked ledger: the picker must read the visit+ * marker WITHOUT advancing it (#7630). Advancing it would consume the "what+ * arrived since I last looked" trail that the mind's own `eidoverse.observe`+ * — and the very `coordinate` phase this resolves — depends on, so every wake+ * would erase the evidence for the next one.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { eidoversePeerId } from '../lib/eidoverseWorldSignals.js';-const mock = vi.hoisted(() => ({ collectEidoverseWorldSources: vi.fn() }));+const dataRoot = () => lazyTempDataRoot('portos-playbook-phase-');-vi.mock('./eidoverseWorldSources.js', () => ({- collectEidoverseWorldSources: (...args) => mock.collectEidoverseWorldSources(...args),-}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot }));++const collectSources = vi.fn();+const listFoundations = vi.fn();+const listControllers = vi.fn();++vi.mock('./eidoverseWorldSources.js', () => ({ collectEidoverseWorldSources: (...args) => collectSources(...args) }));+vi.mock('./eidoverseFoundationLedger.js', () => ({ listEidoverseFoundations: (...args) => listFoundations(...args) }));+vi.mock('./eidoverseControllerRuntime.js', () => ({ listEidoverseControllers: (...args) => listControllers(...args) }));+vi.mock('./eidoverseWorld.js', () => ({ readEidoverseWorldRecipe: vi.fn().mockResolvedValue(null) }));+vi.mock('./eidoverseTravel.js', () => ({ listEidoverseDestinations: vi.fn().mockResolvedValue({ destinations: [] }) }));const { resolvePersistentMindPlaybookPhase } = await import('./persistentMindPlaybookSignals.js');+const { observeEidoverseWorld } = await import('./eidoverseObservationLedger.js');++const PEER_INSTANCE = 'fixture-peer-instance';+const PEER_ID = eidoversePeerId({ instanceId: PEER_INSTANCE });+const markerFile = () => join(dataRoot(), 'eidoverse', 'observation.json');++const authored = (id) => ({ id, kind: 'affordance', title: 'Local build', layer: 'vernacular' });+const inheritedFrom = (id) => ({+ id,+ kind: 'affordance',+ title: 'Inherited build',+ layer: 'baseline',+ inheritance: { type: 'inherited-from', originInstanceId: PEER_INSTANCE, sourceInstanceId: PEER_INSTANCE, inheritedAt: '2026-09-17T10:00:00.000Z' },+});++const setFoundations = (foundations) => listFoundations.mockResolvedValue({+ counts: {+ vernacular: foundations.filter((entry) => entry.layer === 'vernacular').length,+ baseline: foundations.filter((entry) => entry.layer === 'baseline').length,+ candidates: 0,+ inherited: foundations.filter((entry) => entry.inheritance).length,+ },+ foundations,+});++const denseWorld = () => ({+ apps: [1, 2, 3, 4].map((n) => ({ id: `app-${n}` })),+ agents: [{ id: 'agent-1' }, { id: 'agent-2' }],+ tasks: [1, 2, 3].map((n) => ({ id: `task-${n}` })),+ peers: [{ id: PEER_ID, label: 'Federated peer', status: 'active', enabled: true, fullSync: true, travelAvailable: true }],+ goals: [{ id: 'goal-1' }],+ memory: [{ id: 'fact' }],+ // Install-constant scaffolding the density signal must ignore.+ features: Array.from({ length: 15 }, (_, index) => ({ id: `feature-${index}`, enabled: index % 2 === 0 })),+ storage: [{ id: 'database' }, { id: 'filesystem' }],+ operations: [{ id: 'overview' }],+ activity: [{ id: 'activity' }],+ productivity: [{ succeededToday: 8, failedToday: 0 }],+});beforeEach(() => {vi.clearAllMocks();+ collectSources.mockResolvedValue(denseWorld());+ setFoundations([]);+ listControllers.mockResolvedValue({ counts: { total: 0, armed: 0, delivering: 0 }, installs: [] });});+afterAll(cleanupTempDataRoots);+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 }],+ it('collects the world projection once and hands it to the observation', async () => {+ // `collectEidoverseWorldSources()` fans out across ~20 service reads;+ // collecting it again inside the observation would double that per wake.+ await resolvePersistentMindPlaybookPhase();+ expect(collectSources).toHaveBeenCalledTimes(1);+ });++ it('never advances the visit marker the mind\'s own observation depends on', async () => {+ setFoundations([authored('f-1')]);+ // Seed a real marker the way a mind's own `eidoverse.observe` would.+ await observeEidoverseWorld({ now: () => '2026-09-18T08:00:00.000Z' });+ const before = readFileSync(markerFile(), 'utf8');++ await resolvePersistentMindPlaybookPhase();+ expect(readFileSync(markerFile(), 'utf8')).toBe(before);+ });++ it('reports a fresh install as explore rather than a mature Commons', async () => {+ collectSources.mockResolvedValue({+ apps: [], agents: [], tasks: [], peers: [], goals: [], memory: [], jira: [],+ features: Array.from({ length: 15 }, (_, index) => ({ id: `feature-${index}`, enabled: false })),+ storage: [{ id: 'database' }, { id: 'filesystem' }],+ operations: [{ id: 'overview' }],+ activity: [{ id: 'activity' }],+ productivity: [{ succeededToday: 0, failedToday: 0 }],});const result = await resolvePersistentMindPlaybookPhase();- expect(mock.collectEidoverseWorldSources).toHaveBeenCalledTimes(1);- // 5 live signals is below the maturity threshold, so a reachable peer does- // not preempt construction — see selectPersistentMindPlaybookPhase.- expect(result.phase).toBe('construct');- expect(result.signals).toMatchObject({ districtCount: 5, failureRate: 0, peersReachable: 1 });+ expect(result).toMatchObject({ phase: 'explore' });+ expect(result.signals.districtCount).toBe(0);+ });++ it('coordinates only when a foundation arrived from a reachable peer since the last look', async () => {+ setFoundations([authored('f-1'), authored('f-2'), authored('f-3'), authored('f-4')]);+ await observeEidoverseWorld({ now: () => '2026-09-18T08:00:00.000Z' });++ // Reachable peer, nothing new: the old picker called this "peers waiting".+ const quiet = await resolvePersistentMindPlaybookPhase();+ expect(quiet.signals.peersReachable).toBe(1);+ expect(quiet.signals.peerContributionsUnread).toBe(0);+ expect(quiet.phase).toBe('maintain');++ setFoundations([authored('f-1'), authored('f-2'), authored('f-3'), authored('f-4'), inheritedFrom('peer:alpha:one')]);+ const arrived = await resolvePersistentMindPlaybookPhase();+ expect(arrived.signals.peerContributionsUnread).toBe(1);+ expect(arrived.phase).toBe('coordinate');});it('degrades to the safe explore default when the signal read fails', async () => {- mock.collectEidoverseWorldSources.mockRejectedValue(new Error('world source unavailable'));+ collectSources.mockRejectedValue(new Error('world source unavailable'));+ listFoundations.mockRejectedValue(new Error('ledger unavailable'));+ listControllers.mockRejectedValue(new Error('controllers unavailable'));const result = await resolvePersistentMindPlaybookPhase();expect(result.phase).toBe('explore');- expect(result.signals).toEqual({ districtCount: null, failureRate: null, failureRateMeasured: false, peersReachable: null });+ expect(result.signals).toMatchObject({ districtCount: null, failureRate: null, peersReachable: 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'));+ collectSources.mockRejectedValue(new Error('turn interrupted'));await expect(resolvePersistentMindPlaybookPhase({ signal: controller.signal })).rejects.toThrow('turn interrupted');});});