Skip to content

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

feat: wire the peer pull/inherit transport for promoted Eidoverse foundations (#7455)

[._.]/ Adam Eivyb52f222b4d75
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
index 9e9dd8831e..45307e9f4f 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
@@ -182,7 +182,7 @@ export default function EidoverseFoundationsPanel() {
const [searchParams, setSearchParams] = useSearchParams();
const openId = searchParams.get('foundation');
const [foundations, setFoundations] = useState([]);
- const [counts, setCounts] = useState({ vernacular: 0, baseline: 0, candidates: 0 });
+ const [counts, setCounts] = useState({ vernacular: 0, baseline: 0, candidates: 0, inherited: 0 });
const [contributions, setContributions] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
@@ -195,7 +195,7 @@ export default function EidoverseFoundationsPanel() {
const applyListing = useCallback((listing) => {
setFoundations(listing.foundations || []);
- setCounts(listing.counts || { vernacular: 0, baseline: 0, candidates: 0 });
+ setCounts(listing.counts || { vernacular: 0, baseline: 0, candidates: 0, inherited: 0 });
}, []);
useEffect(() => {
@@ -300,6 +300,7 @@ export default function EidoverseFoundationsPanel() {
</p>
<p className="mt-3 text-sm text-gray-400">
{counts.vernacular} local · {counts.baseline} in the shared baseline · {counts.candidates} packaged
+ {counts.inherited > 0 && ` · ${counts.inherited} inherited from peers`}
</p>
</section>
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index c69e3f63a8..9ff7d02758 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -68,7 +68,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.
- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.
- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, explicit display aliases keyed by opaque resource identity (never backfilled from records), user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. Guest travel sessions and live chat cursors are ephemeral transport state held only in memory; they are not a new record store or sync category. Explicit guest conversation follows the [guest-chat ADR](decisions/2026-09-05-eidoverse-guest-chat.md). PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.
-- Eidoverse world foundations ledger — `data/eidoverse/foundations.json` (#7455, #7461). The install-local record of every durable world foundation this instance authored OR inherited: its ownership layer (`vernacular` by default, `baseline` once promoted or inherited), the promotable `body`, the vernacular `style` layer that never leaves, provenance (opaque instance id + author kind), the last agent-free resilience verdict, and the last packaged promote candidate. A record this install pulled from a peer additionally carries an `inheritance` edge (`{ originInstanceId, foundationId, fingerprint, sourceInstanceId, inheritedAt }`) and is stored under a `peer:<originInstanceId>:<foundationId>` key disjoint from any locally-authored id, so it can never shadow or collide with a same-id local vernacular foundation. The proposal → commit → promote/inherit lineage is not stored — `foundationLineage()` derives it on every read from fields the record already carries. `file-primary` and **intentionally machine-local — never federated**: the only thing authorized to leave the install is a packaged candidate envelope, and only through an explicit promote (out) or an already-verified candidate handed to `recordEidoverseFoundationInheritance()` (in) — the peer pull/inherit wire transport itself is the still-open remainder of #7455, so nothing calls the inherit path in this install yet. No `data.reference/` seed and no migration — an absent file IS the empty ledger every install starts from, and the `inheritance`/`lineage` additions are additive/nullable so an older file on disk reads back unchanged. Backed up with the rest of `data/eidoverse/`.
+- Eidoverse world foundations ledger — `data/eidoverse/foundations.json` (#7455, #7461). The install-local record of every durable world foundation this instance authored OR inherited: its ownership layer (`vernacular` by default, `baseline` once promoted or inherited), the promotable `body`, the vernacular `style` layer that never leaves, provenance (opaque instance id + author kind), the last agent-free resilience verdict, and the last packaged promote candidate. A record this install pulled from a peer additionally carries an `inheritance` edge (`{ originInstanceId, foundationId, fingerprint, sourceInstanceId, inheritedAt }`) and is stored under a `peer:<originInstanceId>:<foundationId>` key disjoint from any locally-authored id, so it can never shadow or collide with a same-id local vernacular foundation. The proposal → commit → promote/inherit lineage is not stored — `foundationLineage()` derives it on every read from fields the record already carries. `file-primary` and **intentionally machine-local — never federated**: the only thing authorized to leave the install is a packaged candidate envelope, and only for a foundation somebody explicitly promoted. `services/sharing/peerEidoverseFoundationSync.js` is the transport: it serves those envelopes (and only those — never a record, so never the `style` layer) at `GET /api/peer-sync/eidoverse-foundations` to registered outbound-enabled peers, and pulls a full-sync peer's offering into `recordEidoverseFoundationInheritance()`, which re-runs the whole accept-side gate and writes nothing on a refusal. Version-gated as `PORTOS_SCHEMA_VERSIONS.eidoverseFoundations`. No `data.reference/` seed and no migration — an absent file IS the empty ledger every install starts from, and the `inheritance`/`lineage` additions are additive/nullable so an older file on disk reads back unchanged. Backed up with the rest of `data/eidoverse/`.
- Eidoverse executable world controllers — `data/eidoverse/controllers.json` (#7456). The install-local set of controllers attached to this instance's private world: which shipped controller each install names (by REGISTRY ID — never a module path, so an install can never become an import), its bounded config, its cadence, whether it is armed, whether its effects are allowed to reach the world, and the durable state the controller advances one step per supervised tick. `file-primary` and **intentionally machine-local — never federated**: an install names this world's own entities and carries its author's intent, which the [machine-local privacy ADR](decisions/2026-08-08-privacy-records-machine-local.md) keeps off the federation layer; a controller is shared with a peer only as the BODY of a promoted foundation, which carries no install. No `data.reference/` seed and no migration — an absent file IS the empty set every install starts from. Backed up with the rest of `data/eidoverse/`.
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + an ordered list of steps, each a REFERENCE to a scheduled task (`data/cos/task-schedule.json` or the app job store) plus its per-invocation overrides. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and a step's scheduled-task reference names task types and managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index 7ab79aa58a..77036392fa 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -840,12 +840,58 @@ re-promoted from this install (`packageFoundationCandidate` refuses it by
name): promotion publishes only what this install itself authored, never a
relay of another install's work.
-**What is still to come is the wire transport** — the peer pull/inherit
-protocol itself, tracked as the remainder of #7455. `recordEidoverseFoundationInheritance()`
-is written and tested as the function that transport will call once it
-exists; nothing in this install invokes it yet, so `baseline` in practice
-still means "this install offered this foundation" until a transport starts
-calling it.
+### The peer pull/inherit transport (#7455)
+
+`server/services/sharing/peerEidoverseFoundationSync.js` is the wire between
+the two gates above. It owns no policy of its own — which foundations an
+install offers is `listPromotedFoundationCandidates()` in the ledger, and
+which it accepts is `recordEidoverseFoundationInheritance()`. It owns the
+payload wrapper, the version gate, the caps and the sweep.
+
+**Outbound.** `GET /api/peer-sync/eidoverse-foundations` advertises
+`{ schemaVersion, listHash, candidates: [...] }`. The offering is exactly the
+foundations this install PROMOTED and AUTHORED:
+
+- `layer === 'baseline'` — a merely *packaged* candidate is a dry run ("would
+ this pass?"), not a publication, and is never served.
+- `!inheritance` — `baseline` also covers a local copy of a peer's foundation,
+ so an inherited record is excluded rather than relayed. That matches the
+ ledger's existing refusal to re-package an inherited record: a peer that
+ wants a third install's foundation pulls it from the install that authored it.
+- the stored envelope must still pass `verifyFoundationCandidate()`.
+ `foundations.json` is a file a human can edit, and refuse-never-redact
+ applies outbound as well as inbound, so a candidate that no longer passes is
+ withheld from the offering and logged.
+
+Unlike the older peer-pull routes, this one does not ride the warn-first
+authorization ramp: it passes `alwaysEnforce`, so only a registered,
+outbound-enabled peer ever reads it. The ramp exists so a peer mid-upgrade
+does not lose sync it already had, and a brand-new endpoint has no such
+history to protect.
+
+**Inbound.** `syncEidoverseFoundationsFromPeer()` runs for peers the user
+flagged `fullSync`, on the same 60-second sweep as the media-library,
+CoS-history and CoS-task sweeps (`services/sharing/index.js`). It byte-caps
+the response, validates the wrapper, gently skips a sender whose
+`schemaVersion` is ahead of local (the ledger has no re-fetch path that would
+correct a mis-applied envelope later), short-circuits on an unchanged
+`listHash`, and hands every remaining candidate to
+`recordEidoverseFoundationInheritance()` — which re-runs the *entire*
+accept-side gate and writes nothing on a refusal. A candidate whose
+fingerprint this install already holds is skipped, so the periodic forced
+re-pull (there so a local deletion self-heals) never rewrites `inheritedAt`
+on an unchanged copy.
+
+Both directions are gated on the `eidoverse` instance feature: an install with
+Eidoverse turned off neither offers nor accumulates.
+
+**Compatibility.** `PORTOS_SCHEMA_VERSIONS.eidoverseFoundations` (v1) is the
+transport contract, registered in `NON_RECORD_SCHEMA_CATEGORIES` because this
+is a receiver-pull category with no push to gate — a foundation is not a
+peer-subscribable record kind. It is deliberately separate from the envelope's
+own `candidateVersion`, which pins one envelope's shape and is hashed into its
+fingerprint: a change to the envelope bumps both, a change to the wrapper or
+the caps bumps only the category.
### Creative toolkit for minds (#7459)
diff --git a/server/lib/eidoverseFoundations.js b/server/lib/eidoverseFoundations.js
index d8e14ec9e1..e49a782032 100644
--- a/server/lib/eidoverseFoundations.js
+++ b/server/lib/eidoverseFoundations.js
@@ -236,10 +236,10 @@ export const eidoverseFoundationRecordSchema = z.object({
// a stored envelope from a newer install must not make the whole record
// unreadable — the promote path re-verifies the envelope it actually uses.
candidate: z.unknown().optional(),
- // Forward-declared storage slots, written by the promote-to-baseline step
- // that follows this slice: nothing here ever sets `layer` to `baseline` or
- // `promotedAt` to a timestamp yet, so a reader should not take a `baseline`
- // count of zero as evidence about anything.
+ // Set by `promoteEidoverseFoundation()` alongside `layer: 'baseline'`, and
+ // cleared when the body is re-authored. `null` on everything this install has
+ // only packaged (a dry run) and on every inherited copy, which carries the
+ // ORIGIN's `packagedAt` on its inheritance edge instead.
promotedAt: isoDateSchema.nullable().default(null),
// `null` for everything this install authored (the overwhelming majority of
// records). Set only on a LOCAL COPY of a peer's promoted foundation — see
@@ -494,11 +494,10 @@ export function inheritedFoundationStorageKey(originInstanceId, foundationId) {
/**
* Build a local ledger record for a foundation candidate this install pulled
- * from a peer. This is the function a future peer pull/inherit TRANSPORT
- * calls — that transport does not exist yet (it is the still-open remainder
- * of #7455); `recordEidoverseFoundationInheritance()` in
- * `services/eidoverseFoundationLedger.js` is the only caller today, and only
- * from tests, until the transport lands.
+ * from a peer. `recordEidoverseFoundationInheritance()` in
+ * `services/eidoverseFoundationLedger.js` is the only caller; the peer
+ * pull/inherit transport that drives it is
+ * `services/sharing/peerEidoverseFoundationSync.js` (#7455).
*
* The candidate is re-verified through the EXACT gate a peer runs on one it
* was handed (`verifyFoundationCandidate`): schema, the content-addressed
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index 77dd7b40a7..c4c7d349e0 100644
--- a/server/lib/peerSyncValidation.js
+++ b/server/lib/peerSyncValidation.js
@@ -416,6 +416,30 @@ export const peerCosTasksSchema = z.object({
tasks: z.array(peerCosTaskEntrySchema).max(50_000),
}).strict();
+/**
+ * The Eidoverse foundation offering a peer advertises (#7455).
+ *
+ * Deliberately shallow on `candidates`: the envelope's real shape lives in
+ * `eidoverseFoundationCandidateSchema` (lib/eidoverseFoundations.js), and the
+ * receiver runs that — with the content-addressed fingerprint check, the assay
+ * evidence gate and the federation-safety scan — on EVERY candidate before it
+ * stores one. Re-declaring the envelope here would be a second copy of a
+ * contract that must not drift, and would also drag the whole Eidoverse
+ * foundation module into `validation.js`'s import closure, which nearly every
+ * server suite reaches. This schema's job is only to bound the TRANSPORT: a
+ * well-formed wrapper, a capped candidate count, and objects rather than
+ * scalars, so one malformed entry can't take the whole sweep down before the
+ * real gate ever runs.
+ */
+export const peerEidoverseFoundationsSchema = z.object({
+ schemaVersion: z.number().int().min(0).max(1_000_000),
+ listHash: hex64,
+ // A foundation body caps at 16 KiB, so 500 envelopes stay well inside the
+ // byte cap the receiver enforces on the response. Far beyond any realistic
+ // promoted population — the sender logs and truncates at the same number.
+ candidates: z.array(z.record(z.string().min(1).max(64), z.unknown())).max(500),
+}).strict();
+
export const peerPullMetadataSchema = z.object({
// Backfill tries every online peer; no per-peer scoping field today.
// .trim() so a stray-whitespace filename (' a.png ') normalizes to the real
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index a38ae6c73c..a863d5d721 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -688,6 +688,31 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v9 = strict large-input PR review fallback pins and complete linked issue
// evidence. Older peers may clip that evidence or substitute a smaller model.
cosTasks: 9,
+ // v1 = the Eidoverse foundation promote-candidate envelope (#7455, epic
+ // #7453) — the ONE Eidoverse artifact the machine-local privacy ADR
+ // authorizes to cross the federation layer. A sender advertises its promoted
+ // `baseline` foundations at GET /api/peer-sync/eidoverse-foundations; a
+ // receiver pulls, re-runs the full accept-side gate per envelope
+ // (`verifyFoundationCandidate`), and stores each acceptance under a
+ // `peer:<originInstanceId>:<foundationId>` ledger key.
+ //
+ // Receiver-pull like `mediaLibrary`/`cosHistory`/`cosTasks`, so it rides
+ // NON_RECORD_SCHEMA_CATEGORIES below and has no RECORD_KIND_SCHEMA_CATEGORIES
+ // entry: there is no push to gate. The receiver GENTLY SKIPS a sender ahead of
+ // its local version rather than 409-ing, because the envelope carries a body
+ // whose vocabulary is still being written (#7456) — a v1 receiver that applied
+ // a v2 envelope would store a foundation it cannot interpret, and the ledger
+ // has no re-fetch path that would later correct it.
+ //
+ // The envelope ALSO carries its own `candidateVersion` literal
+ // (EIDOVERSE_FOUNDATION_CANDIDATE_VERSION in lib/eidoverseFoundations.js),
+ // which the two prior slices added before any transport existed. The two are
+ // deliberately separate: `candidateVersion` pins ONE envelope's shape and is
+ // hashed into its content-addressed fingerprint, while this category gates the
+ // TRANSPORT payload (its wrapper, its caps, and which foundations an install
+ // offers). A change to either must bump its own number; a change to the
+ // envelope shape bumps both, because the wrapper's contents changed too.
+ eidoverseFoundations: 1,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
@@ -764,6 +789,12 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
* claim-aware per-task merge (see syncCosTasksFromPeer) — no push to gate, so
* no RECORD_KIND_SCHEMA_CATEGORIES entry.
*
+ * - `eidoverseFoundations` (#7455): the promoted Eidoverse foundation candidates
+ * an install advertises at GET /api/peer-sync/eidoverse-foundations. Same
+ * receiver-pull shape as `cosTasks` (see syncEidoverseFoundationsFromPeer) —
+ * no push to gate, so no RECORD_KIND_SCHEMA_CATEGORIES entry. A foundation is
+ * not a peer-subscribable record kind and never rides the record pipeline.
+ *
* `appQuality`: numeric-only local evidence at GET /api/apps/quality-federation,
* validated against its exact wire version by collectAppQuality; never written or pushed.
*
@@ -771,7 +802,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
* leave its push transfers ungated (silent cross-install corruption). Only
* genuinely non-push categories belong.
*/
-export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks', 'appQuality']));
+export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks', 'appQuality', 'eidoverseFoundations']));
/**
* Lazy-read the current PortOS version from the ROOT package.json so a
diff --git a/server/routes/peerSync.js b/server/routes/peerSync.js
index 2187d9897e..503c7b17b0 100644
--- a/server/routes/peerSync.js
+++ b/server/routes/peerSync.js
@@ -53,6 +53,7 @@ import {
buildMediaLibraryManifest,
buildCosHistoryManifest,
buildCosTasksPayload,
+ buildEidoverseFoundationOffering,
ERR_NOT_FOUND,
ERR_VALIDATION,
ERR_SCHEMA_VERSION_AHEAD,
@@ -206,6 +207,27 @@ router.get('/cos-tasks', asyncHandler(async (req, res) => {
res.json(await buildCosTasksPayload());
}));
+// --- GET /eidoverse-foundations --- advertise the Eidoverse foundations this
+// instance has PROMOTED (#7455) so a full-sync peer can pull and inherit them.
+//
+// Returns `{ schemaVersion, listHash, candidates: [<promote envelope>, …] }`.
+// The envelope is the one Eidoverse artifact the machine-local privacy ADR
+// authorizes to cross, and it has no `style` layer by construction, so an
+// inheriting peer gets the substance and keeps its own cosmetics. The receiver
+// re-runs the whole accept-side gate on every envelope before it stores one.
+//
+// `alwaysEnforce` — unlike the older pull routes, this one does NOT ride the
+// warn-first authorization ramp. That ramp exists so a peer mid-upgrade doesn't
+// lose creative-work sync it already had; a brand-new endpoint has no such
+// history to protect, so only a registered, outbound-enabled peer ever gets
+// this install's promoted bodies. The manifests aren't scoped to one record
+// kind (a foundation is not a peer-subscribable record), so like them it gates
+// on `peerAllowsOutbound` alone — see peerPullAuthorization.js.
+router.get('/eidoverse-foundations', asyncHandler(async (req, res) => {
+ await authorizePeerPull(req, { route: 'eidoverse-foundations', alwaysEnforce: true });
+ res.json(await buildEidoverseFoundationOffering());
+}));
+
// --- GET /cos-agent-archive --- stream ONE completed-agent archive file so a
// full-sync peer can receiver-pull it (#1650). Archives are nested
// (<date>/<agentId>/<file>), so unlike media bytes they are NOT served by a
diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.js
index 83a536d022..d9c160db38 100644
--- a/server/routes/peerSync.test.js
+++ b/server/routes/peerSync.test.js
@@ -15,6 +15,7 @@ vi.mock('../services/sharing/peerSync.js', () => ({
buildMediaLibraryManifest: vi.fn(),
buildCosHistoryManifest: vi.fn(),
buildCosTasksPayload: vi.fn(),
+ buildEidoverseFoundationOffering: vi.fn(),
ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',
ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',
ERR_SCHEMA_VERSION_AHEAD: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',
@@ -648,6 +649,34 @@ describe('peer-sync routes', () => {
});
});
+ describe('GET /api/peer-sync/eidoverse-foundations (#7455)', () => {
+ const offering = {
+ schemaVersion: 1,
+ listHash: 'a'.repeat(64),
+ candidates: [{ candidateVersion: 1, foundationId: 'tide-beacon', fingerprint: 'b'.repeat(64) }],
+ };
+
+ it('200 with the promoted-foundation offering', async () => {
+ svc.buildEidoverseFoundationOffering.mockResolvedValue(offering);
+ const res = await request(buildApp()).get('/api/peer-sync/eidoverse-foundations');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(offering);
+ });
+
+ it('does NOT ride the warn-first authorization ramp — a new endpoint has no upgrade history to protect', async () => {
+ svc.buildEidoverseFoundationOffering.mockResolvedValue(offering);
+ await request(buildApp()).get('/api/peer-sync/eidoverse-foundations');
+ // Without `alwaysEnforce`, an unregistered caller on the tailnet would be
+ // SERVED this install's promoted bodies until the user found and flipped
+ // `federation.strictPullAuthorization` — which defaults off.
+ expect(authorizePeerPull).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ route: 'eidoverse-foundations', alwaysEnforce: true }),
+ );
+ expect(vi.mocked(authorizePeerPull).mock.calls[0][1].recordKind).toBeUndefined();
+ });
+ });
+
describe('GET /api/peer-sync/cos-agent-archive (#1650)', () => {
let tmp;
let originalCos;
@@ -871,6 +900,7 @@ describe('peer-sync routes', () => {
['/api/peer-sync/library-manifest', 'buildMediaLibraryManifest'],
['/api/peer-sync/cos-history-manifest', 'buildCosHistoryManifest'],
['/api/peer-sync/cos-tasks', 'buildCosTasksPayload'],
+ ['/api/peer-sync/eidoverse-foundations', 'buildEidoverseFoundationOffering'],
])('403s %s without building the payload when the gate rejects', async (path, fn) => {
vi.mocked(authorizePeerPull).mockRejectedValue(
Object.assign(new Error('peer not authorized for this record'), { status: 403, code: 'PEER_PULL_FORBIDDEN' })
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 5c8453908d..1502cf8332 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1181,6 +1181,13 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
// gated by syncCosTasksFromPeer's gentle skip-if-ahead; declared non-record
// in NON_RECORD_SCHEMA_CATEGORIES.
'cosTasks',
+ // Promoted Eidoverse foundations (#7455) → its own receiver-pull endpoint
+ // (GET /api/peer-sync/eidoverse-foundations), NOT the file-snapshot
+ // transfer — the ledger is machine-local and only the promote envelope
+ // ever crosses. Versioned for that envelope's transport wrapper and gated
+ // by syncEidoverseFoundationsFromPeer's gentle skip-if-ahead; declared
+ // non-record in NON_RECORD_SCHEMA_CATEGORIES.
+ 'eidoverseFoundations',
]);
const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());
for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {
diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.js
index e6b5057e7a..635c32b986 100644
--- a/server/services/eidoverseFoundationLedger.js
+++ b/server/services/eidoverseFoundationLedger.js
@@ -25,8 +25,10 @@
* Storage is `data/eidoverse/foundations.json` — `file-primary` and MACHINE
* LOCAL, the same class as `portos-world.json` beside it (`docs/STORAGE.md`).
* PortOS never federates this file: the only thing authorized to leave the
- * install is a packaged candidate envelope, and even that leaves only through
- * an explicit promote. There is no `data.reference/` seed — an absent file is
+ * install is a packaged candidate envelope, and even that leaves only once
+ * somebody promotes the foundation — `listPromotedFoundationCandidates()`
+ * below is the whole of what a peer can ever read
+ * (`services/sharing/peerEidoverseFoundationSync.js`). There is no `data.reference/` seed — an absent file is
* an empty ledger, which is the correct state for every install that has never
* authored or inherited a foundation, so no migration is owed.
*/
@@ -43,6 +45,7 @@ import {
foundationLineage,
inheritedFoundationStorageKey,
packageFoundationCandidate,
+ verifyFoundationCandidate,
} from '../lib/eidoverseFoundations.js';
import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';
import { findContributionById } from './eidoverseResilienceContributions.js';
@@ -99,6 +102,49 @@ export async function listEidoverseFoundations() {
};
}
+/**
+ * The promote envelopes this install OFFERS to its federated peers (#7455) —
+ * the read behind `GET /api/peer-sync/eidoverse-foundations`.
+ *
+ * Three filters, each load-bearing:
+ *
+ * - `layer === 'baseline'` — only what somebody deliberately promoted. A
+ * `vernacular` record may carry a packaged candidate (packaging is the step
+ * BEFORE promoting); packaging is "show me whether this would pass", not
+ * "publish this", and serving those would turn a dry run into a broadcast.
+ * - `!inheritance` — `baseline` covers BOTH what this install promoted and a
+ * local copy of a peer's, so offering every `baseline` record would re-share
+ * another install's work. That matches `packageEidoverseFoundationCandidate`,
+ * which already refuses an inherited record ("promotion re-shares only
+ * foundations this install authored"): a peer that wants a third install's
+ * foundation pulls it from the install that authored it.
+ * - the candidate still VERIFIES — the envelope was gated when it was
+ * promoted, but `foundations.json` is a file a human can edit and a partial
+ * hand-edit is exactly how a machine name or a local path would end up
+ * inside a body that was clean when it was packaged. Refuse-never-redact
+ * applies outbound as well as inbound, so a candidate that no longer passes
+ * is dropped from the offering (and logged) rather than served.
+ *
+ * Returns the envelopes only — never the ledger records, which carry the
+ * `style` layer that is not authorized to leave this install.
+ */
+export async function listPromotedFoundationCandidates() {
+ const offerable = Object.values(await readFoundations())
+ .filter((entry) => entry?.layer === 'baseline' && !entry.inheritance && entry.candidate);
+ const candidates = [];
+ for (const entry of offerable) {
+ const verified = verifyFoundationCandidate(entry.candidate, { requiredDisturbances: RESILIENCE_DISTURBANCES });
+ if (!verified.valid) {
+ console.warn(`⚠️ Eidoverse foundation "${entry.id}" is promoted but its stored candidate no longer passes the promote gate — withholding it from the peer offering (${verified.reasons.length} reason(s))`);
+ continue;
+ }
+ candidates.push(entry.candidate);
+ }
+ // Fingerprint order: content-addressed, so the offering (and the listHash a
+ // receiver short-circuits on) is stable across ledger read order.
+ return candidates.sort((a, b) => String(a.fingerprint).localeCompare(String(b.fingerprint)));
+}
+
export async function getEidoverseFoundation(id) {
const found = (await readFoundations())[id] || null;
return found ? { ...found, lineage: foundationLineage(found) } : null;
@@ -233,11 +279,12 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
* fingerprint — is re-run against the body as it stands right now. A refusal is
* a RESULT with its reasons, exactly as packaging is; nothing moves layer.
*
- * What `baseline` means today is "this install offers this foundation to the
- * shared population": the receiving side (a peer pulling and inheriting it) is
- * still to come, and when it lands this flag is the set it serves from. The
- * promoted record keeps its `style` locally — only the candidate envelope,
- * which has no style layer at all, is ever authorized to cross.
+ * `baseline` means "this install offers this foundation to the shared
+ * population", and it is literally the set served from:
+ * `listPromotedFoundationCandidates()` reads it for the peer-facing offering
+ * at `GET /api/peer-sync/eidoverse-foundations`. The promoted record keeps its
+ * `style` locally — only the candidate envelope, which has no style layer at
+ * all, is ever authorized to cross.
*
* @returns {Promise<{ outcome: 'promoted'|'refused'|'unknown-foundation', promoted: boolean, foundation: object|null, candidate: object|null, assay: object|null, reasons: string[], findings: Array }>}
*/
@@ -275,14 +322,12 @@ export async function promoteEidoverseFoundation(id, { now = new Date().toISOStr
* a local baseline copy, carrying an `inherited-from` edge back to its origin
* (#7461).
*
- * This is the function a future transport calls — it is written now so the
- * provenance model, storage and safety gate exist end to end, but nothing in
- * this install invokes it yet: the peer pull/inherit wire protocol is the
- * still-open remainder of #7455. A transport that has fetched and can vouch
- * for `sourceInstanceId` (the peer it pulled FROM — see
- * `foundationFromInheritedCandidate()` for why that can differ from the
- * candidate's own `originInstanceId` on a re-shared foundation) is the only
- * intended caller.
+ * The caller is the pull/inherit transport in
+ * `services/sharing/peerEidoverseFoundationSync.js` (#7455), which has fetched
+ * the envelope from a full-sync peer and can vouch for `sourceInstanceId` —
+ * the peer it pulled FROM, which differs from the candidate's own
+ * `originInstanceId` on a foundation re-shared through more than one hop (see
+ * `foundationFromInheritedCandidate()`).
*
* `localInstanceId` is supplied by the caller rather than read here, matching
* `recordEidoverseFoundation()`'s own convention: this module stays a
diff --git a/server/services/eidoverseFoundationLedger.test.js b/server/services/eidoverseFoundationLedger.test.js
index 8c7206896a..1c6d7dd891 100644
--- a/server/services/eidoverseFoundationLedger.test.js
+++ b/server/services/eidoverseFoundationLedger.test.js
@@ -6,7 +6,8 @@
* the verdict that vouched for the previous one.
*/
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { rmSync } from 'node:fs';
+import { readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
import { inheritedFoundationStorageKey } from '../lib/eidoverseFoundations.js';
@@ -21,6 +22,7 @@ const {
promoteEidoverseFoundation,
recordEidoverseFoundation,
recordEidoverseFoundationInheritance,
+ listPromotedFoundationCandidates,
} = await import('./eidoverseFoundationLedger.js');
// The passing reference contribution shipped with the assay harness (#7460).
@@ -247,3 +249,67 @@ describe('inheriting a foundation this install pulled from a peer (#7461)', () =
expect(after).toMatchObject({ assay: before.assay, updatedAt: before.updatedAt, layer: 'baseline' });
});
});
+
+describe('the promoted-foundation offering a peer can pull (#7455)', () => {
+ const ledgerPath = () => join(lazyTempDataRoot('portos-eidoverse-foundations-'), 'eidoverse', 'foundations.json');
+ const readLedger = () => JSON.parse(readFileSync(ledgerPath(), 'utf8'));
+ const writeLedger = (ledger) => writeFileSync(ledgerPath(), JSON.stringify(ledger));
+
+ it('offers only what this install both promoted and authored', async () => {
+ // Promoted + authored here → offered.
+ await record({}, '2026-03-01T00:00:00.000Z');
+ await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+ const peerEnvelope = (await getEidoverseFoundation('tide-beacon')).candidate;
+
+ // Packaged but NOT promoted → a dry run, never broadcast.
+ await record({ id: 'dry-run', title: 'Dry Run' }, '2026-03-02T00:00:00.000Z');
+ await packageEidoverseFoundationCandidate('dry-run', { now: '2026-03-02T01:00:00.000Z' });
+ expect((await getEidoverseFoundation('dry-run')).candidate).toBeTruthy();
+
+ // A peer's foundation this install inherited → `baseline`, but not ours to
+ // relay. Re-minted under a different origin so it is genuinely foreign.
+ const foreign = { ...peerEnvelope };
+ const inherited = await recordEidoverseFoundationInheritance(foreign, {
+ sourceInstanceId: 'instance-peer-relay', localInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z',
+ });
+ expect(inherited.outcome).toBe('inherited');
+
+ const offered = await listPromotedFoundationCandidates();
+ expect(offered.map((candidate) => candidate.foundationId)).toEqual(['tide-beacon']);
+ // One entry, not two: the inherited copy carries the SAME foundationId and
+ // fingerprint, so a filter that only checked `layer === 'baseline'` would
+ // pass this assertion's id check while re-sharing another install's work.
+ expect((await listEidoverseFoundations()).counts).toMatchObject({ baseline: 2, inherited: 1 });
+ });
+
+ it('serves the envelope only — never the ledger record, so the local style layer cannot ride along', async () => {
+ await record({ style: { motif: 'weathered brass', palette: ['#332211'] } }, '2026-03-01T00:00:00.000Z');
+ await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+
+ const [offered] = await listPromotedFoundationCandidates();
+ expect(offered).toBeTruthy();
+ expect(Object.keys(offered)).not.toContain('style');
+ // Nor any other record-only key that would leak local state or let a
+ // receiver mistake an envelope for a record.
+ for (const recordOnlyKey of ['style', 'id', 'layer', 'promotedAt', 'inheritance', 'updatedAt', 'candidate']) {
+ expect(offered[recordOnlyKey]).toBeUndefined();
+ }
+ expect(JSON.stringify(offered)).not.toContain('weathered brass');
+ });
+
+ it('withholds a promoted foundation whose stored envelope no longer passes the gate', async () => {
+ await record({}, '2026-03-01T00:00:00.000Z');
+ await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+ expect(await listPromotedFoundationCandidates()).toHaveLength(1);
+
+ // Hand-edit the ledger the way a person with an editor could: the record
+ // still says `baseline`, but the envelope's body no longer matches the
+ // fingerprint it was promoted under. Trusting the `promotedAt` stamp
+ // instead of re-verifying would serve unvouched bytes to every peer.
+ const ledger = readLedger();
+ ledger.foundations['tide-beacon'].candidate.body = { affordance: { inspect: 'quietly grants owner role' } };
+ writeLedger(ledger);
+
+ expect(await listPromotedFoundationCandidates()).toEqual([]);
+ });
+});
diff --git a/server/services/sharing/eidoverseFoundationsSync.test.js b/server/services/sharing/eidoverseFoundationsSync.test.js
new file mode 100644
index 0000000000..a2d92999d5
--- /dev/null
+++ b/server/services/sharing/eidoverseFoundationsSync.test.js
@@ -0,0 +1,243 @@
+/**
+ * The Eidoverse foundation pull/inherit transport (#7455).
+ *
+ * The two gates this wire connects are tested where they live — the send-side
+ * offering filter in `eidoverseFoundationLedger.test.js`, the accept-side gate
+ * in `eidoverseFoundations.test.js`. What only this suite can catch is the
+ * TRANSPORT's own contract: that a version-ahead peer is skipped instead of
+ * mis-applied, that the sweep is idempotent rather than rewriting the ledger
+ * every tick, that the accept gate is handed the right two instance ids (the
+ * only thing that lets it recognize a self-referential pull), and that a
+ * refusal is counted rather than thrown.
+ *
+ * The ledger is mocked so the transport is observable AND can never touch the
+ * real `data/eidoverse/foundations.json`; the module reaches it through a
+ * dynamic import, which vitest's mock registry covers.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('../instances.js', () => ({
+ DEFAULT_SYNC_CATEGORIES: {},
+ getPeers: vi.fn().mockResolvedValue([]),
+ resolveEffectiveCategories: vi.fn(() => ({})),
+}));
+vi.mock('../instanceIdentity.js', () => ({
+ UNKNOWN_INSTANCE_ID: 'unknown',
+ getInstanceId: vi.fn().mockResolvedValue('instance-local'),
+}));
+vi.mock('../instanceFeatures.js', () => ({ isInstanceFeatureEnabled: vi.fn().mockResolvedValue(true) }));
+vi.mock('../../lib/peerHttpClient.js', () => ({ peerFetch: vi.fn() }));
+vi.mock('../eidoverseFoundationLedger.js', () => ({
+ listPromotedFoundationCandidates: vi.fn().mockResolvedValue([]),
+ listEidoverseFoundations: vi.fn().mockResolvedValue({ foundations: [] }),
+ recordEidoverseFoundationInheritance: vi.fn().mockResolvedValue({ outcome: 'inherited', foundation: {}, reasons: [], findings: [] }),
+}));
+
+import {
+ __resetEidoverseFoundationSweepForTests,
+ buildEidoverseFoundationOffering,
+ syncEidoverseFoundationsFromPeer,
+ syncEidoverseFoundationsWithAllPeers,
+} from './peerEidoverseFoundationSync.js';
+import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';
+import { FORCE_REVALIDATE_EVERY } from './peerSyncShared.js';
+import { getPeers } from '../instances.js';
+import { getInstanceId } from '../instanceIdentity.js';
+import { isInstanceFeatureEnabled } from '../instanceFeatures.js';
+import { peerFetch } from '../../lib/peerHttpClient.js';
+import {
+ listEidoverseFoundations,
+ listPromotedFoundationCandidates,
+ recordEidoverseFoundationInheritance,
+} from '../eidoverseFoundationLedger.js';
+
+const PEER = { instanceId: 'instance-peer', name: 'Workshop', address: '192.0.2.10', port: 5555, fullSync: true, enabled: true };
+
+const fingerprint = (seed) => seed.repeat(64).slice(0, 64);
+
+// Shaped like a real promote envelope, but only the fields the TRANSPORT reads
+// matter here — the envelope's own contract is the accept gate's to enforce,
+// and mocking the ledger is precisely what keeps this suite from re-testing it.
+const candidate = (id, seed = 'a') => ({
+ candidateVersion: 1,
+ foundationId: id,
+ kind: 'controller',
+ title: id,
+ summary: `${id} summary`,
+ contributionId: 'beacon-relay-demo',
+ body: { schema: { pulses: 'integer' } },
+ disclosure: { requires: [], effects: [], license: null, notes: null },
+ provenance: {
+ originInstanceId: 'instance-peer', authorKind: 'mind',
+ createdAt: '2026-03-01T00:00:00.000Z', packagedAt: '2026-03-01T01:00:00.000Z', portosVersion: '9.9.9',
+ },
+ assay: {
+ harness: 'eidoverse-resilience-assay', contributionId: 'beacon-relay-demo', pass: true,
+ disturbances: ['author-absent'], ranAt: '2026-03-01T00:30:00.000Z', reasons: [],
+ },
+ fingerprint: fingerprint(seed),
+});
+
+const offering = (candidates, overrides = {}) => ({
+ ok: true,
+ headers: { get: () => null },
+ json: async () => ({
+ schemaVersion: PORTOS_SCHEMA_VERSIONS.eidoverseFoundations,
+ // A hex64 the receiver only compares for equality; the sender's real one is
+ // derived from the fingerprints.
+ listHash: fingerprint('f'),
+ candidates,
+ ...overrides,
+ }),
+});
+
+beforeEach(() => {
+ __resetEidoverseFoundationSweepForTests();
+ vi.mocked(peerFetch).mockReset();
+ vi.mocked(getPeers).mockResolvedValue([PEER]);
+ vi.mocked(getInstanceId).mockResolvedValue('instance-local');
+ vi.mocked(isInstanceFeatureEnabled).mockResolvedValue(true);
+ vi.mocked(listPromotedFoundationCandidates).mockReset().mockResolvedValue([]);
+ vi.mocked(listEidoverseFoundations).mockReset().mockResolvedValue({ foundations: [] });
+ vi.mocked(recordEidoverseFoundationInheritance).mockReset()
+ .mockResolvedValue({ outcome: 'inherited', foundation: {}, reasons: [], findings: [] });
+});
+
+describe('the offering this install advertises', () => {
+ it('stamps the wire version and a content-addressed listHash over the promoted envelopes', async () => {
+ vi.mocked(listPromotedFoundationCandidates).mockResolvedValue([candidate('tide-beacon', 'a'), candidate('lamp-post', 'b')]);
+
+ const payload = await buildEidoverseFoundationOffering();
+
+ expect(payload.schemaVersion).toBe(PORTOS_SCHEMA_VERSIONS.eidoverseFoundations);
+ expect(payload.candidates.map((c) => c.foundationId)).toEqual(['tide-beacon', 'lamp-post']);
+ expect(payload.listHash).toMatch(/^[a-f0-9]{64}$/);
+
+ // Content-addressed: the SAME envelopes hash the same, a different set does
+ // not. Without this the receiver's unchanged short-circuit would either
+ // never fire or would hide a genuine change.
+ const again = await buildEidoverseFoundationOffering();
+ expect(again.listHash).toBe(payload.listHash);
+ vi.mocked(listPromotedFoundationCandidates).mockResolvedValue([candidate('tide-beacon', 'a')]);
+ expect((await buildEidoverseFoundationOffering()).listHash).not.toBe(payload.listHash);
+ });
+
+ it('advertises nothing while the Eidoverse feature is off, without reading the ledger', async () => {
+ vi.mocked(isInstanceFeatureEnabled).mockResolvedValue(false);
+ vi.mocked(listPromotedFoundationCandidates).mockResolvedValue([candidate('tide-beacon')]);
+
+ expect((await buildEidoverseFoundationOffering()).candidates).toEqual([]);
+ expect(listPromotedFoundationCandidates).not.toHaveBeenCalled();
+ });
+});
+
+describe('pulling a peer offering', () => {
+ it('hands each candidate to the accept gate with the peer it came FROM and this install id', async () => {
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('tide-beacon')]));
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 1, refused: 0 });
+ // Both ids, separately: `sourceInstanceId` is the hop, `localInstanceId` is
+ // what lets the gate refuse a foundation this install itself originated.
+ // Collapsing them (or passing the candidate's own origin) would silently
+ // disarm both self-referential checks.
+ expect(recordEidoverseFoundationInheritance).toHaveBeenCalledWith(
+ expect.objectContaining({ foundationId: 'tide-beacon' }),
+ { sourceInstanceId: 'instance-peer', localInstanceId: 'instance-local' },
+ );
+ expect(peerFetch).toHaveBeenCalledWith(
+ expect.stringContaining('/api/peer-sync/eidoverse-foundations'), expect.anything(), PEER,
+ );
+ });
+
+ it('counts a refusal instead of failing the sweep, and applies the rest', async () => {
+ vi.mocked(recordEidoverseFoundationInheritance)
+ .mockResolvedValueOnce({ outcome: 'refused', foundation: null, reasons: ['fingerprint does not match'], findings: [] })
+ .mockResolvedValueOnce({ outcome: 'inherited', foundation: {}, reasons: [], findings: [] });
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('tampered', 'a'), candidate('sound', 'b')]));
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 1, refused: 1 });
+ });
+
+ it('skips a sender whose schemaVersion is ahead rather than storing a shape it cannot read', async () => {
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('from-the-future')], {
+ schemaVersion: PORTOS_SCHEMA_VERSIONS.eidoverseFoundations + 1,
+ }));
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toEqual({ inherited: 0, skipped: 'schema-ahead' });
+ expect(recordEidoverseFoundationInheritance).not.toHaveBeenCalled();
+ });
+
+ it('short-circuits an unchanged offering, then force-revalidates so a local deletion self-heals', async () => {
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('tide-beacon')]));
+ await syncEidoverseFoundationsFromPeer(PEER);
+ // Held locally from here on, so a re-pull has nothing to apply.
+ vi.mocked(listEidoverseFoundations).mockResolvedValue({
+ foundations: [{ inheritance: { fingerprint: fingerprint('a') } }],
+ });
+
+ for (let i = 1; i < FORCE_REVALIDATE_EVERY; i += 1) {
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toEqual({ inherited: 0, skipped: 'unchanged' });
+ }
+ // The forced tick falls through to a real apply pass rather than skipping.
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 0, refused: 0 });
+ expect(vi.mocked(listEidoverseFoundations)).toHaveBeenCalled();
+ });
+
+ it('does not re-apply a candidate this install already holds at the same fingerprint', async () => {
+ vi.mocked(listEidoverseFoundations).mockResolvedValue({
+ foundations: [{ inheritance: { fingerprint: fingerprint('a') } }, { inheritance: null }],
+ });
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('tide-beacon', 'a'), candidate('lamp-post', 'b')]));
+
+ // Re-applying would rewrite `inheritedAt`/`updatedAt` on an unchanged copy
+ // every forced re-pull and churn the ledger for nothing.
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 1, refused: 0 });
+ expect(recordEidoverseFoundationInheritance).toHaveBeenCalledTimes(1);
+ expect(recordEidoverseFoundationInheritance).toHaveBeenCalledWith(
+ expect.objectContaining({ foundationId: 'lamp-post' }), expect.anything(),
+ );
+ });
+
+ it('rejects a malformed wrapper before any candidate reaches the gate', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, headers: { get: () => null }, json: async () => ({ candidates: 'not-an-array' }) });
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toEqual({ inherited: 0, skipped: 'invalid' });
+ expect(recordEidoverseFoundationInheritance).not.toHaveBeenCalled();
+ });
+
+ it('refuses an over-cap response on the declared content length', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true, headers: { get: () => String(64 * 1024 * 1024) }, json: async () => ({}),
+ });
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toEqual({ inherited: 0, skipped: 'too-large' });
+ });
+
+ it('never pulls for a peer the user did not flag full-sync, or while Eidoverse is off', async () => {
+ expect(await syncEidoverseFoundationsFromPeer({ ...PEER, fullSync: false })).toEqual({ inherited: 0, skipped: 'not-fullsync' });
+ vi.mocked(isInstanceFeatureEnabled).mockResolvedValue(false);
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toEqual({ inherited: 0, skipped: 'feature-disabled' });
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('skips an install with no federation identity instead of minting one in the background', async () => {
+ vi.mocked(getInstanceId).mockResolvedValue('unknown');
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toEqual({ inherited: 0, skipped: 'no-local-identity' });
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('sweeps only enabled full-sync peers', async () => {
+ vi.mocked(getPeers).mockResolvedValue([
+ PEER,
+ { ...PEER, instanceId: 'instance-disabled', enabled: false },
+ { ...PEER, instanceId: 'instance-partial', fullSync: false },
+ ]);
+ vi.mocked(peerFetch).mockResolvedValue(offering([]));
+
+ await syncEidoverseFoundationsWithAllPeers();
+
+ expect(peerFetch).toHaveBeenCalledTimes(1);
+ expect(peerFetch).toHaveBeenCalledWith(expect.any(String), expect.anything(), PEER);
+ });
+});
diff --git a/server/services/sharing/index.js b/server/services/sharing/index.js
index 274e18b13b..bbd8157eb4 100644
--- a/server/services/sharing/index.js
+++ b/server/services/sharing/index.js
@@ -12,7 +12,7 @@ import { join } from 'path';
import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';
import { sharingEvents } from './importer.js';
import { installSubscriptionListener } from './subscriptions.js';
-import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers, syncCosHistoryWithAllPeers, syncCosTasksWithAllPeers } from './peerSync.js';
+import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers, syncCosHistoryWithAllPeers, syncCosTasksWithAllPeers, syncEidoverseFoundationsWithAllPeers } from './peerSync.js';
import { hasSubscriptionAdapter } from './recordEvents.js';
import { initAnnotationsSync } from './annotationsSync.js';
@@ -54,6 +54,13 @@ function startMediaLibrarySweep() {
syncCosTasksWithAllPeers().catch((err) => {
console.error(`❌ sharing: cos-tasks sweep failed: ${err.message}`);
});
+ // Promoted Eidoverse foundations (#7455) — the pull/inherit half of the
+ // shared baseline. Same cadence; the receiver short-circuits on an
+ // unchanged content-addressed listHash, so the steady-state tick is one
+ // cheap fetch per full-sync peer. Separate catch keeps it isolated.
+ syncEidoverseFoundationsWithAllPeers().catch((err) => {
+ console.error(`❌ sharing: eidoverse-foundations sweep failed: ${err.message}`);
+ });
} catch (err) {
console.error(`❌ sharing: full-sync sweep threw synchronously: ${err.message}`);
}
diff --git a/server/services/sharing/peerEidoverseFoundationSync.js b/server/services/sharing/peerEidoverseFoundationSync.js
new file mode 100644
index 0000000000..a185e0e24d
--- /dev/null
+++ b/server/services/sharing/peerEidoverseFoundationSync.js
@@ -0,0 +1,266 @@
+/**
+ * Federated peer-sync — Eidoverse foundation pull/inherit transport (#7455,
+ * provenance edges #7461, epic #7453).
+ *
+ * "Fork locally, contribute foundations globally" needs a wire. The two gates
+ * already existed and were already tested; nothing connected them:
+ *
+ * - `verifyFoundationCandidate()` (lib/eidoverseFoundations.js) — the gate a
+ * sender runs on its own envelope and a receiver runs on one it was handed.
+ * - `recordEidoverseFoundationInheritance()` (services/eidoverseFoundationLedger.js)
+ * — the accept side, which re-runs that whole gate on receipt, refuses a
+ * self-referential pull, and stores the acceptance under a
+ * `peer:<originInstanceId>:<foundationId>` key disjoint from local ids.
+ *
+ * This module is that wire, and nothing more. It owns no policy about WHICH
+ * foundations an install offers (that is `listPromotedFoundationCandidates()`
+ * in the ledger) and no policy about which it accepts (that is the accept-side
+ * gate). It owns the payload wrapper, the version gate, the caps, and the
+ * sweep.
+ *
+ * Shape mirrors the `cos-tasks` receiver-pull sweep (peerCosSync.js), the
+ * closest existing precedent: the sender advertises at
+ * `GET /api/peer-sync/eidoverse-foundations`; a receiver (only for peers it
+ * flags `fullSync`) fetches it, byte-caps it, validates the wrapper,
+ * version-gates it, short-circuits on an unchanged content-addressed
+ * `listHash`, and applies per candidate. Every guard RETURNS rather than
+ * throws — a sweep is best-effort and idempotent.
+ *
+ * **What crosses.** Only the promote envelope, which has no `style` layer by
+ * construction: an inheriting peer gets the substance and keeps its own
+ * cosmetics. The machine-local privacy ADR authorizes exactly this one
+ * Eidoverse artifact to cross, and the federation-safety scan REFUSES a
+ * payload carrying machine identity, PII or credentials rather than redacting
+ * it — on both sides, because a peer's payload is untrusted input and this
+ * install's own ledger is a file a human can edit.
+ */
+import { createHash } from 'crypto';
+import { isPlainObject } from '../../lib/objects.js';
+import { isStr } from '../../lib/textUtils.js';
+import { peerBaseUrl } from '../../lib/peerUrl.js';
+import { peerFetch } from '../../lib/peerHttpClient.js';
+import { withAbortTimeout } from '../../lib/abortTimeout.js';
+import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';
+import { peerEidoverseFoundationsSchema } from '../../lib/validation.js';
+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';
+import { getPeers } from '../instances.js';
+import { FORCE_REVALIDATE_EVERY } from './peerSyncShared.js';
+
+/**
+ * A foundation body caps at 16 KiB, so the offering cap keeps the whole payload
+ * comfortably inside the byte cap even at the entry cap. Both are generous
+ * against any realistic promoted population; the sender truncates at the entry
+ * cap and the receiver rejects an over-cap response on its content-length check.
+ */
+const OFFERING_ENTRY_CAP = 500;
+const OFFERING_MAX_BYTES = 16 * 1024 * 1024;
+
+/**
+ * Deliberately NOT `ASSET_PULL_TIMEOUT_MS`: that constant is sized for
+ * streaming media bytes, and importing it would drag `peerSyncAssets.js` — and
+ * with it the authors/artists/albums/tracks/creative-director/mood-board/
+ * writers-room graph — into this module's closure for one number. An offering
+ * is a small capped JSON document; a peer that cannot produce one in 30s is
+ * unreachable for this purpose.
+ */
+const OFFERING_PULL_TIMEOUT_MS = 30_000;
+
+/**
+ * The Eidoverse feature and the foundation ledger both sit behind dynamic
+ * imports: this module is in `peerSync.js`'s static import chain (the sweep
+ * driver and the route both reach it), and the Eidoverse graph — the assay
+ * harness, the contribution registry, the controller runtime — has no business
+ * being instantiated in the ~hundreds of suites that reach peer-sync for
+ * unrelated reasons. Mirrors `buildCosTasksPayload`'s import of `cosTaskStore`.
+ * A failed import degrades to "offer nothing / inherit nothing" rather than
+ * taking the sweep down.
+ */
+const ledger = () => import('../eidoverseFoundationLedger.js').catch(() => null);
+const eidoverseEnabled = async () => {
+ const mod = await import('../instanceFeatures.js').catch(() => null);
+ return (await mod?.isInstanceFeatureEnabled?.('eidoverse').catch(() => false)) === true;
+};
+
+const peerLabel = (peer) => peer.name || peer.instanceId;
+
+/** Content-address the offering so a receiver can short-circuit an unchanged
+ * one. Each envelope already carries a sha256 of its own body, and the list is
+ * sorted by it, so hashing the fingerprints alone is both sufficient and
+ * order-independent. */
+const offeringListHash = (candidates) => createHash('sha256')
+ .update(candidates.map((candidate) => String(candidate.fingerprint)).join('\n'))
+ .digest('hex');
+
+/**
+ * Build the foundation offering this instance advertises to peers.
+ *
+ * Empty (not an error) when the Eidoverse feature is off: an install that
+ * turned the feature off is not participating in the shared baseline, in
+ * either direction. Also empty when the ledger module can't load.
+ *
+ * @returns {Promise<{ schemaVersion:number, listHash:string, candidates:Array }>}
+ */
+export async function buildEidoverseFoundationOffering() {
+ const offering = (candidates) => ({
+ schemaVersion: PORTOS_SCHEMA_VERSIONS.eidoverseFoundations,
+ listHash: offeringListHash(candidates),
+ candidates,
+ });
+ if (!(await eidoverseEnabled())) return offering([]);
+ const mod = await ledger();
+ if (!mod?.listPromotedFoundationCandidates) return offering([]);
+ const candidates = await mod.listPromotedFoundationCandidates();
+ if (candidates.length > OFFERING_ENTRY_CAP) {
+ console.log(`⚠️ peerSync: eidoverse-foundations offering hit the ${OFFERING_ENTRY_CAP}-entry cap — truncating`);
+ return offering(candidates.slice(0, OFFERING_ENTRY_CAP));
+ }
+ return offering(candidates);
+}
+
+// Receiver-side bookkeeping — mirrors the cos-tasks sweep.
+const lastOfferingListHash = new Map(); // peerInstanceId → listHash
+const offeringUnchangedSkips = new Map(); // peerInstanceId → count
+const offeringSweepInFlight = new Set(); // peerInstanceId
+
+/** Test-support: forget the per-peer short-circuit state. */
+export function __resetEidoverseFoundationSweepForTests() {
+ lastOfferingListHash.clear();
+ offeringUnchangedSkips.clear();
+ offeringSweepInFlight.clear();
+}
+
+/**
+ * Pull ONE full-sync peer's foundation offering and inherit what passes the
+ * accept-side gate. Best-effort + idempotent; no-op for a non-full-sync peer.
+ *
+ * Every candidate goes through `recordEidoverseFoundationInheritance()`, which
+ * re-runs the ENTIRE gate — envelope schema, content-addressed fingerprint,
+ * the embedded assay evidence, and the federation-safety scan — and refuses
+ * (writing nothing) on any failure. Nothing here re-runs the resilience assay
+ * or executes the contribution: that ran on the author's install, and
+ * replaying arbitrary controller code pulled from a peer is exactly what the
+ * agent-free harness exists to keep off every OTHER install.
+ *
+ * A candidate whose fingerprint this install already holds is skipped rather
+ * than re-applied, so the periodic forced re-pull (which exists so a LOCAL
+ * deletion self-heals) doesn't rewrite `inheritedAt` on every unchanged copy
+ * and churn the ledger.
+ *
+ * @param {object} peer a peer entry from getPeers()
+ * @returns {Promise<{ inherited:number, refused?:number, skipped?:string }>}
+ */
+export async function syncEidoverseFoundationsFromPeer(peer) {
+ if (!isPlainObject(peer) || peer.fullSync !== true || !isStr(peer.instanceId)) {
+ return { inherited: 0, skipped: 'not-fullsync' };
+ }
+ // Claimed synchronously, BEFORE the first await: a re-entrancy guard taken
+ // after one would let two sweep ticks past it and double-apply an offering.
+ if (offeringSweepInFlight.has(peer.instanceId)) return { inherited: 0, skipped: 'in-flight' };
+ offeringSweepInFlight.add(peer.instanceId);
+ try {
+ if (!(await eidoverseEnabled())) return { inherited: 0, skipped: 'feature-disabled' };
+ // `getInstanceId`, not `ensureInstanceId`: a background sweep must not mint
+ // this install's durable federation identity as a side effect. Without one
+ // the accept-side gate cannot check for a self-referential pull anyway, so
+ // there is nothing useful to do.
+ const localInstanceId = await getInstanceId().catch(() => null);
+ if (!isStr(localInstanceId) || localInstanceId === UNKNOWN_INSTANCE_ID) {
+ return { inherited: 0, skipped: 'no-local-identity' };
+ }
+ const url = `${peerBaseUrl(peer)}/api/peer-sync/eidoverse-foundations`;
+ const res = await withAbortTimeout(OFFERING_PULL_TIMEOUT_MS, (signal) =>
+ peerFetch(url, { signal, maxBytes: OFFERING_MAX_BYTES }, peer))
+ .catch(() => null);
+ if (!res || !res.ok) return { inherited: 0, skipped: 'unreachable' };
+ const declaredLen = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(declaredLen) && declaredLen > OFFERING_MAX_BYTES) {
+ console.log(`⚠️ peerSync: eidoverse-foundations offering from ${peerLabel(peer)} too large (${declaredLen} > ${OFFERING_MAX_BYTES}) — skipping`);
+ return { inherited: 0, skipped: 'too-large' };
+ }
+ const parsed = peerEidoverseFoundationsSchema.safeParse(await res.json().catch(() => null));
+ if (!parsed.success) {
+ console.log(`⚠️ peerSync: eidoverse-foundations offering from ${peerLabel(peer)} failed validation — skipping`);
+ return { inherited: 0, skipped: 'invalid' };
+ }
+ const payload = parsed.data;
+ // Schema gate — GENTLE skip, not a rejection: wait for the local PortOS to
+ // upgrade rather than store a foundation shape it cannot interpret. The
+ // ledger has no re-fetch path that would correct a mis-applied envelope
+ // later, so "apply now, fix on upgrade" is not available here.
+ if (payload.schemaVersion > PORTOS_SCHEMA_VERSIONS.eidoverseFoundations) {
+ console.log(`⏸️ peerSync: ${peerLabel(peer)} eidoverse-foundations offering is schema v${payload.schemaVersion} > local v${PORTOS_SCHEMA_VERSIONS.eidoverseFoundations} — skipping until this instance updates`);
+ return { inherited: 0, skipped: 'schema-ahead' };
+ }
+ // Unchanged short-circuit with a periodic forced re-pull, so a LOCAL loss
+ // (a hand-deleted ledger entry) self-heals even while the peer's offering
+ // stays put.
+ if (lastOfferingListHash.get(peer.instanceId) === payload.listHash) {
+ const skips = (offeringUnchangedSkips.get(peer.instanceId) || 0) + 1;
+ if (skips < FORCE_REVALIDATE_EVERY) {
+ offeringUnchangedSkips.set(peer.instanceId, skips);
+ return { inherited: 0, skipped: 'unchanged' };
+ }
+ offeringUnchangedSkips.set(peer.instanceId, 0); // forced re-pull — fall through
+ }
+ const applied = await applyOffering(payload.candidates, { peer, localInstanceId });
+ // Only remember the offering once it was actually applied: recording the
+ // hash after a `ledger-unavailable` pass would short-circuit the next
+ // FORCE_REVALIDATE_EVERY ticks on work that never happened.
+ if (!applied.skipped) lastOfferingListHash.set(peer.instanceId, payload.listHash);
+ if (applied.inherited > 0) {
+ console.log(`📥 peerSync: eidoverse-foundations sweep from ${peerLabel(peer)} — inherited ${applied.inherited} foundation(s)`);
+ }
+ if (applied.refused > 0) {
+ console.log(`⚠️ peerSync: eidoverse-foundations sweep from ${peerLabel(peer)} — refused ${applied.refused} candidate(s) at the accept-side gate`);
+ }
+ return applied;
+ } finally {
+ offeringSweepInFlight.delete(peer.instanceId);
+ }
+}
+
+/**
+ * Hand each candidate to the accept-side gate, skipping the ones this install
+ * already holds at the same content-addressed fingerprint.
+ *
+ * Sequential on purpose: `recordEidoverseFoundationInheritance` serializes on
+ * the ledger's own mutex, so a `Promise.all` here would buy nothing but a
+ * deeper queue and a less readable failure.
+ */
+async function applyOffering(candidates, { peer, localInstanceId }) {
+ const mod = await ledger();
+ if (!mod?.recordEidoverseFoundationInheritance || !mod?.listEidoverseFoundations) {
+ return { inherited: 0, refused: 0, skipped: 'ledger-unavailable' };
+ }
+ const held = new Set((await mod.listEidoverseFoundations()).foundations
+ .filter((entry) => entry.inheritance)
+ .map((entry) => entry.inheritance.fingerprint));
+ let inherited = 0;
+ let refused = 0;
+ for (const candidate of candidates) {
+ if (held.has(candidate.fingerprint)) continue;
+ const result = await mod.recordEidoverseFoundationInheritance(candidate, {
+ sourceInstanceId: peer.instanceId,
+ localInstanceId,
+ }).catch((err) => {
+ console.log(`⚠️ peerSync: eidoverse-foundations inherit from ${peerLabel(peer)} failed: ${err.message}`);
+ return null;
+ });
+ if (result?.outcome === 'inherited') inherited += 1;
+ else refused += 1;
+ }
+ return { inherited, refused };
+}
+
+/**
+ * Periodic driver: pull the foundation offering from every full-sync peer.
+ * Each peer's sweep is independent + best-effort.
+ */
+export async function syncEidoverseFoundationsWithAllPeers() {
+ const peers = await getPeers().catch(() => []);
+ for (const peer of peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId))) {
+ await syncEidoverseFoundationsFromPeer(peer).catch((err) => {
+ console.log(`⚠️ peerSync: eidoverse-foundations sweep for ${peerLabel(peer)} failed: ${err.message}`);
+ });
+ }
+}
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index c3c50670b6..5af9d08a3c 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -11,6 +11,7 @@
* - `peerSyncReceive.js` — receiver-side push handler
* - `peerMediaLibrarySync.js` — standalone media-library sync
* - `peerCosSync.js` — CoS history + tasks sync
+ * - `peerEidoverseFoundationSync.js` — Eidoverse foundation pull/inherit (#7455)
*
* Their public surface is re-exported below so existing importers
* (routes/peerSync.js, sharing/index.js, dataSync, the test suite, …) keep
@@ -111,6 +112,12 @@ export {
syncCosTasksFromPeer,
syncCosTasksWithAllPeers,
} from './peerCosSync.js';
+export {
+ buildEidoverseFoundationOffering,
+ syncEidoverseFoundationsFromPeer,
+ syncEidoverseFoundationsWithAllPeers,
+ __resetEidoverseFoundationSweepForTests,
+} from './peerEidoverseFoundationSync.js';
/**