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

record cross-instance foundation provenance and inheritance edges (#7461)

[._.]/ Adam Eivye5f271822362
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
index d87d7cdeee..752f5c4121 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useId, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router';
-import { Globe2, Home, ShieldCheck } from 'lucide-react';
+import { GitFork, Globe2, Home, ShieldCheck } from 'lucide-react';
import {
getEidoverseContributions,
listEidoverseFoundations,
@@ -8,6 +8,7 @@ import {
promoteEidoverseFoundation,
recordEidoverseFoundation,
} from '../../services/api';
+import { formatDateShort, timeAgo } from '../../utils/formatters';
/**
* The promote surface for Eidoverse world foundations (#7455).
@@ -124,6 +125,46 @@ function Verdict({ verdict }) {
);
}
+/** A short, non-collapsible label for who's opaque instance/author identity a
+ * lineage event carries — never a display name (#7461: provenance is
+ * instance-id + coarse author kind only). */
+function InheritedFromBadge({ inheritance }) {
+ if (!inheritance) return null;
+ return (
+ <span
+ className="inline-flex items-center gap-1 rounded-full border border-port-border bg-port-bg px-2 py-0.5 text-xs text-gray-400"
+ title={`Pulled from instance ${inheritance.sourceInstanceId}, originally authored on ${inheritance.originInstanceId}`}
+ >
+ <GitFork size={12} aria-hidden="true" />
+ Inherited
+ </span>
+ );
+}
+
+const LINEAGE_COPY = Object.freeze({
+ authored: (event) => `Authored (${event.authorKind || 'unknown'})`,
+ inherited: (event) => `Inherited from instance ${event.originInstanceId}`,
+ assayed: (event) => (event.pass ? 'Agent-free assay passed' : 'Agent-free assay failed'),
+ packaged: () => 'Promote candidate packaged',
+ promoted: () => 'Promoted to the shared baseline',
+});
+
+/** Proposal → commit → promote(/inherit), oldest first — a read-only
+ * projection the server derives on every read; nothing here is stored. */
+function LineageTimeline({ lineage }) {
+ if (!lineage?.length) return null;
+ return (
+ <ol className="space-y-1 text-xs text-gray-400">
+ {lineage.map((event) => (
+ <li key={`${event.type}-${event.at}`} className="flex flex-wrap items-baseline gap-x-2">
+ <span className="text-gray-300">{(LINEAGE_COPY[event.type] || (() => event.type))(event)}</span>
+ <span className="text-gray-500" title={formatDateShort(event.at)}>{timeAgo(event.at)}</span>
+ </li>
+ ))}
+ </ol>
+ );
+}
+
export default function EidoverseFoundationsPanel() {
const [searchParams, setSearchParams] = useSearchParams();
const openId = searchParams.get('foundation');
@@ -268,6 +309,7 @@ export default function EidoverseFoundationsPanel() {
<div className="flex flex-wrap items-center gap-2">
<h4 className="font-medium text-white">{foundation.title}</h4>
<LayerBadge layer={foundation.layer} />
+ <InheritedFromBadge inheritance={foundation.inheritance} />
<span className="rounded-full border border-port-border px-2 py-0.5 text-xs text-gray-400">{foundation.kind}</span>
</div>
<p className="mt-1 text-sm text-gray-400">{foundation.summary}</p>
@@ -277,34 +319,52 @@ export default function EidoverseFoundationsPanel() {
{foundation.assay ? (foundation.assay.pass ? ' · assay passed' : ' · assay failed') : ' · assay not run'}
</p>
</div>
- <div className="flex flex-wrap gap-2">
- <button
- type="button"
- className={secondaryButton}
- disabled={busyId === foundation.id}
- onClick={() => runGate(foundation.id, packageEidoverseFoundationCandidate)}
- >
- {busyId === foundation.id ? 'Running assay…' : 'Run assay'}
- </button>
- <button
- type="button"
- className={primaryButton}
- disabled={busyId === foundation.id || foundation.layer === 'baseline'}
- title={foundation.layer === 'baseline' ? 'Already offered to the shared baseline' : 'Run every gate and publish to the shared baseline'}
- onClick={() => runGate(foundation.id, promoteEidoverseFoundation)}
- >
- Promote
- </button>
+ {/* A local copy of a peer's foundation is never packaged or promoted
+ from here — it is already the origin's candidate, and promoting
+ it would re-share another install's work as this one's own. */}
+ {!foundation.inheritance && (
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ className={secondaryButton}
+ disabled={busyId === foundation.id}
+ onClick={() => runGate(foundation.id, packageEidoverseFoundationCandidate)}
+ >
+ {busyId === foundation.id ? 'Running assay…' : 'Run assay'}
+ </button>
+ <button
+ type="button"
+ className={primaryButton}
+ disabled={busyId === foundation.id || foundation.layer === 'baseline'}
+ title={foundation.layer === 'baseline' ? 'Already offered to the shared baseline' : 'Run every gate and publish to the shared baseline'}
+ onClick={() => runGate(foundation.id, promoteEidoverseFoundation)}
+ >
+ Promote
+ </button>
+ <button type="button" className={secondaryButton} onClick={() => openFoundation(expanded ? '' : foundation.id)}>
+ {expanded ? 'Hide' : 'Details'}
+ </button>
+ </div>
+ )}
+ {foundation.inheritance && (
<button type="button" className={secondaryButton} onClick={() => openFoundation(expanded ? '' : foundation.id)}>
{expanded ? 'Hide' : 'Details'}
</button>
- </div>
+ )}
</div>
<Verdict verdict={verdicts[foundation.id]} />
{expanded && (
<div className="mt-3 space-y-2 border-t border-port-border pt-3 text-sm">
+ <div>
+ <p className="text-gray-400">
+ Provenance
+ {foundation.provenance?.authorKind && ` — authored by a ${foundation.provenance.authorKind}`}
+ {foundation.provenance?.originInstanceId && ` on instance ${foundation.provenance.originInstanceId}`}:
+ </p>
+ <LineageTimeline lineage={foundation.lineage} />
+ </div>
<p className="text-gray-400">
Promotable substance (<code>body</code>) — the only part a peer receives:
</p>
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
index 1a917c624a..25d1389fb2 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
@@ -117,4 +117,30 @@ describe('the Eidoverse foundations promote panel', () => {
expect(screen.getByText(/registers no replayable contribution/)).toBeInTheDocument();
});
+
+ it('marks a local copy of a peer foundation as Inherited and hides the promote/run-assay actions a re-share would need (#7461)', async () => {
+ const inherited = foundation({
+ layer: 'baseline',
+ provenance: { originInstanceId: 'instance-origin-peer', authorKind: 'mind', createdAt: '2026-03-01T00:00:00.000Z' },
+ inheritance: {
+ type: 'inherited-from', originInstanceId: 'instance-origin-peer', foundationId: 'tide-beacon',
+ fingerprint: 'a'.repeat(64), packagedAt: '2026-03-01T01:00:00.000Z',
+ sourceInstanceId: 'instance-relay-peer', inheritedAt: '2026-03-04T05:06:07.000Z',
+ },
+ lineage: [
+ { type: 'inherited', at: '2026-03-04T05:06:07.000Z', originInstanceId: 'instance-origin-peer', sourceInstanceId: 'instance-relay-peer' },
+ { type: 'assayed', at: '2026-03-01T00:30:00.000Z', pass: true },
+ ],
+ });
+ listEidoverseFoundations.mockResolvedValue(listing([inherited], { vernacular: 0, baseline: 1, candidates: 0, inherited: 1 }));
+ getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ await renderPanel();
+
+ expect(screen.getByText('Inherited')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Promote' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Run assay' })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Details' }));
+ expect(screen.getByText(/Inherited from instance instance-origin-peer/)).toBeInTheDocument();
+ });
});
diff --git a/docs/API.md b/docs/API.md
index d878d2aef3..87152c9447 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -358,9 +358,9 @@ federate world records.
| POST | `/eidoverse/world/project` | Project current PortOS resources into the world using the saved recipe |
| POST | `/eidoverse/world/augment` | Apply bounded, allowlisted world construction/role operations |
| POST | `/eidoverse/world/say` | Send a bounded message as the PortOS CoS presence |
-| GET | `/eidoverse/world/foundations` | Local foundation ledger: ownership layer, provenance, and packaged promote candidates |
+| GET | `/eidoverse/world/foundations` | Local foundation ledger: ownership layer, provenance, derived lineage, any inheritance edge, and packaged promote candidates |
| POST | `/eidoverse/world/foundations` | Record (or re-author) a local vernacular foundation — the layer is never caller-supplied |
-| GET | `/eidoverse/world/foundations/:id` | One foundation record |
+| GET | `/eidoverse/world/foundations/:id` | One foundation record, with its derived provenance lineage |
| POST | `/eidoverse/world/foundations/:id/candidate` | Run the agent-free resilience assay and package a promote candidate; a refusal returns 200 with its reasons |
| POST | `/eidoverse/world/foundations/:id/promote` | Re-package and publish a foundation into this install's shared baseline population; a refusal returns 200 with its reasons and moves nothing |
| GET | `/eidoverse/world/contributions` | The resilience-assay contribution ids a foundation may bind itself to |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 41d0ce933e..53348cf61e 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). The install-local record of every durable world foundation this instance authored: its ownership layer (`vernacular` by default, `baseline` once promoted), 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. `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. No `data.reference/` seed and no migration — an absent file IS the empty ledger every install starts from, so a seed would only put shipped defaults where a user's foundations belong. 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 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/`.
- 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).
- Manual maintenance runs — `data/cos/maintenance-runs.json`. A capped list of the Schedule tab's "Run maintenance now" records: the app, the pinned provider/model/effort, the ladder's steps, the per-step completion ledger and the current hold reason. `ephemeral-file` and machine-local like the burn plan (its steps name task types and managed apps that only exist here); deleting it only forgets progress — a run in flight would have to be started again. See [Quota Burn → Maintenance sequence](./QUOTA-BURN.md#maintenance-sequence).
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index f5cedda02c..ac73dedb39 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -779,6 +779,45 @@ Both tools return summaries (`summarizeFoundation`) rather than whole records:
the local style layer and the packaged envelope have no business riding into a
prompt.
-What is still to come is the receiving side — peer pull/inherit — and the
-envelope's own `candidateVersion` is what that will gate on. Until it lands,
-`baseline` means "this install offers this foundation"; nothing pulls it yet.
+### Provenance graph and inheritance edges (#7461)
+
+Every foundation carries queryable provenance: who authored it (an opaque
+instance id + coarse `authorKind` — `mind` / `cos` / `user`, never a display
+name) and its ordered lineage. `foundationLineage()`
+(`server/lib/eidoverseFoundations.js`) derives that lineage — `authored` →
+`assayed` → `packaged` → `promoted`, or `inherited` → `assayed` for a local
+copy of a peer's — from fields the record already persists, so it costs no
+extra storage and a ledger written before this existed still projects
+correctly. `GET /api/eidoverse/world/foundations` and `.../foundations/:id`
+return it on every entry, and the mind tools' `summarizeFoundation()`
+projection carries `provenance`, `inheritance`, and `lineage` too — the same
+identity fields a candidate envelope was already authorized to carry, now
+surfaced consistently everywhere a foundation is read.
+
+**`recordEidoverseFoundationInheritance()`** (`eidoverseFoundationLedger.js`)
+is the accept-side of a peer pull: given an already-verified candidate
+envelope, the peer this install pulled it FROM, and this install's own
+instance id, it re-runs the exact gate a peer runs on a candidate it was
+handed — schema, content-addressed fingerprint, the embedded assay evidence,
+and federation safety — and, on a pass, stores a `baseline` local copy
+carrying an `inherited-from` edge (origin instance, source instance, the
+envelope's fingerprint, and when it was pulled). It refuses a self-referential
+pull (a peer handing back a foundation this install itself originated) and
+never re-runs the resilience assay itself — replaying a peer's controller code
+on the receiving install is exactly what the assay harness exists to keep off
+every OTHER install.
+
+The inherited copy is stored under `peer:<originInstanceId>:<foundationId>` —
+deliberately disjoint from any id a local author could ever write — so it can
+never shadow, collide with, or erase a same-id local vernacular foundation;
+both simply coexist in the listing. An inherited foundation can never be
+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.
diff --git a/server/lib/eidoverseFoundations.js b/server/lib/eidoverseFoundations.js
index a6cdeeaae6..70ecba2392 100644
--- a/server/lib/eidoverseFoundations.js
+++ b/server/lib/eidoverseFoundations.js
@@ -177,6 +177,36 @@ const foundationAssayEvidenceSchema = z.object({
reasons: z.array(z.string().trim().min(1).max(400)).max(FOUNDATION_LIMITS.findingsMax).default([]),
}).strict();
+/** Opaque PortOS federation instance id — never a hostname, never a tailnet name. */
+const instanceIdSchema = z.string().trim().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/, 'must be an opaque instance id');
+
+/**
+ * The one provenance-graph edge PortOS records today: "this install's local
+ * copy of `foundationId` is a pull of the candidate a peer packaged, from
+ * origin `originInstanceId` by way of `sourceInstanceId`." (#7461)
+ *
+ * `sourceInstanceId` and `originInstanceId` are DELIBERATELY separate fields
+ * rather than one: a foundation can be re-shared through more than one hop, so
+ * the peer this install pulled FROM is not always the install that authored
+ * it. Both are opaque instance ids already authorized to travel with a promote
+ * envelope — nothing here widens what crosses the federation layer, it only
+ * remembers, locally, an edge between two envelopes this install already saw.
+ *
+ * `fingerprint` + `packagedAt` are copied from the candidate this edge was
+ * built from, so the edge stays meaningful even if the local copy's `candidate`
+ * field is ever dropped (the pattern the ledger already uses for a
+ * re-authored `baseline` foundation losing its packaged envelope).
+ */
+export const foundationInheritanceEdgeSchema = z.object({
+ type: z.literal('inherited-from'),
+ originInstanceId: instanceIdSchema,
+ foundationId: foundationIdSchema,
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/, 'must be a sha256 hex digest'),
+ packagedAt: isoDateSchema,
+ sourceInstanceId: instanceIdSchema,
+ inheritedAt: isoDateSchema,
+}).strict();
+
/**
* The fields a foundation carries in every one of its three shapes — the local
* record, what a caller may author, and the promote envelope. Declared once so
@@ -211,6 +241,13 @@ export const eidoverseFoundationRecordSchema = z.object({
// `promotedAt` to a timestamp yet, so a reader should not take a `baseline`
// count of zero as evidence about anything.
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
+ // `foundationFromInheritedCandidate()`. Absent entirely on a record written
+ // before this field existed, which reads back as `null` through this same
+ // default — an additive nullable field on the machine-local ledger, so no
+ // migration is owed (`docs/STORAGE.md`'s entry for `foundations.json`).
+ inheritance: foundationInheritanceEdgeSchema.nullable().default(null),
updatedAt: isoDateSchema,
}).strict();
@@ -373,6 +410,13 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
// packaging side and the receiving side share one definition of valid.
const reasons = [
layerPromoteRefusal(foundation.layer),
+ // An inherited record is already `baseline`, so the layer check above
+ // does not catch it — and its own reason ("already part of the shared
+ // baseline") would be misleading here: this install never promoted it,
+ // it pulled a local copy of a foundation ANOTHER install promoted.
+ // Promotion publishes only what this install authored (#7461); it must
+ // never become a relay that re-shares a peer's foundation as its own.
+ foundation.inheritance ? `inherited from another install (${foundation.inheritance.originInstanceId}) — promotion re-shares only foundations this install authored` : null,
assayEvidenceRefusal(foundation.assay, requiredDisturbances, foundation.contributionId),
].filter(Boolean);
if (reasons.length > 0) return refused(reasons);
@@ -431,6 +475,158 @@ export function verifyFoundationCandidate(candidate, { requiredDisturbances }) {
return { valid: reasons.length === 0, reasons, findings };
}
+// ---------------------------------------------------------------------------
+// Provenance graph (#7461)
+// ---------------------------------------------------------------------------
+
+/**
+ * The ledger key an inherited foundation is stored under — deliberately
+ * disjoint from any id `recordEidoverseFoundation()` can ever author, so
+ * pulling a peer's foundation never touches, shadows, or can collide with a
+ * local vernacular foundation that happens to share the same foundation id.
+ * `foundationIdSchema` is a plain lowercase slug with no colon, which is what
+ * makes this namespace collision-proof rather than merely unlikely.
+ */
+export function inheritedFoundationStorageKey(originInstanceId, foundationId) {
+ return `peer:${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.
+ *
+ * The candidate is re-verified through the EXACT gate a peer runs on one it
+ * was handed (`verifyFoundationCandidate`): schema, the content-addressed
+ * fingerprint, the assay evidence already embedded in the envelope, and
+ * federation safety (machine identity, PII, credentials). A payload handed
+ * over by a peer is untrusted input, so this never trusts "it was already
+ * promoted, so it must be clean" — a candidate that fails is refused outright,
+ * never stored redacted. 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 here is exactly what the
+ * assay harness exists to keep off every OTHER install.
+ *
+ * `style` is never part of the envelope, so the local copy always starts with
+ * an empty one — it looks like this install's own Commons only once someone
+ * here deliberately re-styles it, same as any other baseline foundation.
+ *
+ * Refuses (never throws) a self-referential pull — a peer handing back a
+ * foundation this install itself originated: "inherited from myself" is not
+ * a provenance edge, it is a loop.
+ *
+ * @param {object} options
+ * @param {object} options.candidate - a promote envelope, as received from a peer
+ * @param {string[]} options.requiredDisturbances
+ * @param {string} options.sourceInstanceId - the peer this install pulled FROM
+ * @param {string} options.localInstanceId - this install's own federation id
+ * @param {string} options.now - ISO timestamp supplied by the caller
+ * @returns {{ outcome: 'inherited'|'refused', foundation: object|null, reasons: string[], findings: Array }}
+ */
+export function foundationFromInheritedCandidate({ candidate, requiredDisturbances, sourceInstanceId, localInstanceId, now }) {
+ const inheritanceRefused = (reasons, findings = []) => ({ outcome: 'refused', foundation: null, reasons, findings });
+
+ if (!localInstanceId) return inheritanceRefused(['this install has no federation identity yet — inheritance cannot check for a self-referential pull']);
+
+ const verified = verifyFoundationCandidate(candidate, { requiredDisturbances });
+ if (!verified.valid) return inheritanceRefused(verified.reasons, verified.findings);
+
+ const envelope = candidate;
+ if (envelope.provenance.originInstanceId === localInstanceId) {
+ return inheritanceRefused(['this candidate originated on this install — inheritance applies to another install\'s foundation, not a copy of your own']);
+ }
+
+ const draft = {
+ id: envelope.foundationId,
+ layer: 'baseline',
+ kind: envelope.kind,
+ title: envelope.title,
+ summary: envelope.summary,
+ contributionId: envelope.contributionId,
+ body: envelope.body,
+ style: {},
+ provenance: {
+ originInstanceId: envelope.provenance.originInstanceId,
+ authorKind: envelope.provenance.authorKind,
+ createdAt: envelope.provenance.createdAt,
+ },
+ disclosure: envelope.disclosure,
+ assay: envelope.assay,
+ candidate: envelope,
+ promotedAt: null,
+ inheritance: {
+ type: 'inherited-from',
+ originInstanceId: envelope.provenance.originInstanceId,
+ foundationId: envelope.foundationId,
+ fingerprint: envelope.fingerprint,
+ packagedAt: envelope.provenance.packagedAt,
+ sourceInstanceId,
+ inheritedAt: now,
+ },
+ updatedAt: now,
+ };
+
+ const parsed = eidoverseFoundationRecordSchema.safeParse(draft);
+ if (!parsed.success) return { outcome: 'refused', foundation: null, reasons: issueReasons(parsed.error), findings: [] };
+
+ return { outcome: 'inherited', foundation: parsed.data, reasons: [], findings: [] };
+}
+
+/**
+ * Proposal → commit → promote — and, for a local copy of a peer's, → inherit
+ * — as an ORDERED, read-only projection over fields the record already
+ * persists. No new storage: a ledger written before this function existed
+ * still projects a correct lineage the instant it is read, which is what lets
+ * `docs/STORAGE.md`'s "no migration owed" hold for this change too.
+ *
+ * @param {object|null} record
+ * @returns {Array<{ type: string, at: string, [key: string]: unknown }>}
+ */
+export function foundationLineage(record) {
+ if (!record) return [];
+ const events = [];
+
+ if (record.inheritance) {
+ events.push({
+ type: 'inherited',
+ at: record.inheritance.inheritedAt,
+ originInstanceId: record.inheritance.originInstanceId,
+ foundationId: record.inheritance.foundationId,
+ sourceInstanceId: record.inheritance.sourceInstanceId,
+ fingerprint: record.inheritance.fingerprint,
+ });
+ } else if (record.provenance?.createdAt) {
+ events.push({
+ type: 'authored',
+ at: record.provenance.createdAt,
+ authorKind: record.provenance.authorKind ?? null,
+ originInstanceId: record.provenance.originInstanceId ?? null,
+ });
+ }
+
+ if (record.assay?.ranAt) {
+ events.push({ type: 'assayed', at: record.assay.ranAt, pass: record.assay.pass === true });
+ }
+
+ // Skipped on an inherited record: its `candidate` is the envelope it was
+ // BUILT from, so `packaged` would just restate the `inherited` event above
+ // under a different name.
+ if (!record.inheritance && record.candidate?.provenance?.packagedAt) {
+ events.push({ type: 'packaged', at: record.candidate.provenance.packagedAt, fingerprint: record.candidate.fingerprint ?? null });
+ }
+
+ // An inherited record's `promotedAt` is always `null` (see the schema
+ // comment) — this install never promoted it, it pulled a copy.
+ if (!record.inheritance && record.promotedAt) {
+ events.push({ type: 'promoted', at: record.promotedAt });
+ }
+
+ return events.sort((a, b) => String(a.at).localeCompare(String(b.at)));
+}
+
// ---------------------------------------------------------------------------
// Projection
// ---------------------------------------------------------------------------
@@ -445,6 +641,15 @@ export function verifyFoundationCandidate(candidate, { requiredDisturbances }) {
* candidate currently exists, which is exactly what "can I promote this, and if
* not why" needs. `style` is omitted rather than trimmed: a mind that never
* sees the cosmetics cannot narrate them into a promote body.
+ *
+ * `provenance`, `inheritance`, and `lineage` (#7461) are the provenance-graph
+ * projection: who authored this (an opaque instance id and coarse author
+ * kind — never a display name, per the provenance-privacy note on
+ * `foundationProvenanceSchema`), whether it is a local copy of a PEER's
+ * foundation, and the ordered proposal → commit → promote/inherit timeline.
+ * All three are already either stored on the record or cheaply derived from
+ * it, so surfacing them here costs a mind nothing it was not already paying
+ * for through the full-record GET routes.
*/
export function summarizeFoundation(record) {
return {
@@ -462,5 +667,10 @@ export function summarizeFoundation(record) {
assayPass: record?.assay ? record.assay.pass === true : null,
assayReasons: record?.assay?.reasons?.slice(0, 5) ?? [],
promoteRefusal: layerPromoteRefusal(record?.layer),
+ provenance: record?.provenance
+ ? { originInstanceId: record.provenance.originInstanceId ?? null, authorKind: record.provenance.authorKind ?? null, createdAt: record.provenance.createdAt ?? null }
+ : null,
+ inheritance: record?.inheritance ?? null,
+ lineage: foundationLineage(record),
};
}
diff --git a/server/lib/eidoverseFoundations.test.js b/server/lib/eidoverseFoundations.test.js
index 5ac5b303f2..0dca11be9e 100644
--- a/server/lib/eidoverseFoundations.test.js
+++ b/server/lib/eidoverseFoundations.test.js
@@ -10,6 +10,9 @@ import {
EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,
assayEvidenceFromVerdict,
foundationCandidateFingerprint,
+ foundationFromInheritedCandidate,
+ foundationLineage,
+ inheritedFoundationStorageKey,
layerPromoteRefusal,
packageFoundationCandidate,
styleLeakFindings,
@@ -113,6 +116,19 @@ describe('packaging a promote candidate', () => {
expect(packageRecord({ assay: passingAssay('some-other-build') }).reasons[0])
.toMatch(/ran against "some-other-build"/);
});
+
+ it('refuses to re-promote an inherited foundation as though this install authored it', () => {
+ const result = packageRecord({
+ layer: 'baseline',
+ inheritance: {
+ type: 'inherited-from', originInstanceId: 'instance-peer-origin', foundationId: 'tide-beacon',
+ fingerprint: 'a'.repeat(64), packagedAt: NOW, sourceInstanceId: 'instance-peer-origin', inheritedAt: NOW,
+ },
+ });
+
+ expect(result.outcome).toBe('refused');
+ expect(result.reasons.join(' ')).toContain('inherited from another install');
+ });
});
describe('verifying a candidate a peer was handed', () => {
@@ -168,3 +184,130 @@ describe('style-leak scanning', () => {
expect(findings.map((finding) => finding.path)).toEqual(['controller.motif', 'affordance.render.palette']);
});
});
+
+describe('inheriting a foundation from a peer (#7461)', () => {
+ const LOCAL_INSTANCE_ID = 'instance-local-0001';
+ const SOURCE_INSTANCE_ID = 'instance-peer-relay';
+
+ it('builds a baseline local copy with an inherited-from edge, style dropped, own authorship never claimed', () => {
+ const { candidate } = packageRecord();
+
+ const result = foundationFromInheritedCandidate({
+ candidate, requiredDisturbances: DISTURBANCES, sourceInstanceId: SOURCE_INSTANCE_ID, localInstanceId: LOCAL_INSTANCE_ID, now: NOW,
+ });
+
+ expect(result.outcome).toBe('inherited');
+ expect(result.foundation).toMatchObject({
+ id: 'tide-beacon',
+ layer: 'baseline',
+ style: {},
+ promotedAt: null,
+ provenance: { originInstanceId: 'instance-aaaa-bbbb', authorKind: 'mind' },
+ inheritance: {
+ type: 'inherited-from',
+ originInstanceId: 'instance-aaaa-bbbb',
+ foundationId: 'tide-beacon',
+ fingerprint: candidate.fingerprint,
+ sourceInstanceId: SOURCE_INSTANCE_ID,
+ inheritedAt: NOW,
+ },
+ });
+ });
+
+ it('refuses a self-referential pull instead of recording a loop', () => {
+ const { candidate } = packageRecord();
+
+ const result = foundationFromInheritedCandidate({
+ candidate, requiredDisturbances: DISTURBANCES, sourceInstanceId: SOURCE_INSTANCE_ID, localInstanceId: 'instance-aaaa-bbbb', now: NOW,
+ });
+
+ expect(result.outcome).toBe('refused');
+ expect(result.foundation).toBeNull();
+ expect(result.reasons.join(' ')).toContain('originated on this install');
+ });
+
+ it('refuses a candidate altered after packaging, exactly as a peer running verifyFoundationCandidate would', () => {
+ const { candidate } = packageRecord();
+ const tampered = { ...candidate, body: { ...candidate.body, affordance: { inspect: 'quietly grants owner role' } } };
+
+ const result = foundationFromInheritedCandidate({
+ candidate: tampered, requiredDisturbances: DISTURBANCES, sourceInstanceId: SOURCE_INSTANCE_ID, localInstanceId: LOCAL_INSTANCE_ID, now: NOW,
+ });
+
+ expect(result.outcome).toBe('refused');
+ expect(result.foundation).toBeNull();
+ expect(result.reasons.join(' ')).toContain('altered after packaging');
+ });
+
+ it('refuses PII/machine-identity smuggled into the body even when the fingerprint is internally consistent', () => {
+ // Bypass probe: `packageFoundationCandidate` would never emit this
+ // envelope (packaging itself refuses the leak), so hand-build the shape
+ // an untrusted or buggy peer might send — self-fingerprinted so schema
+ // AND digest both pass — to prove the RECEIVING side's privacy scan
+ // catches it independently of whether the sender's own gate did.
+ const draft = {
+ candidateVersion: EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,
+ foundationId: 'tide-beacon',
+ kind: 'controller',
+ title: 'Tide Beacon',
+ summary: 'A beacon that keeps pulsing between mind wakes.',
+ contributionId: 'beacon-relay-demo',
+ body: { affordance: { inspect: 'reads the pulse count' }, notes: 'built against 192.0.2.10 by [email protected]' },
+ disclosure: { requires: [], effects: [], license: null, notes: null },
+ provenance: { originInstanceId: 'instance-aaaa-bbbb', authorKind: 'mind', createdAt: NOW, packagedAt: NOW, portosVersion: '9.9.9' },
+ assay: passingAssay(),
+ };
+ const forged = { ...draft, fingerprint: foundationCandidateFingerprint(draft) };
+ expect(verifyFoundationCandidate(forged, { requiredDisturbances: DISTURBANCES }).valid).toBe(false); // sanity: a peer would refuse it too
+
+ const result = foundationFromInheritedCandidate({
+ candidate: forged, requiredDisturbances: DISTURBANCES, sourceInstanceId: SOURCE_INSTANCE_ID, localInstanceId: LOCAL_INSTANCE_ID, now: NOW,
+ });
+
+ expect(result.outcome).toBe('refused');
+ expect(result.foundation).toBeNull();
+ expect(result.findings.map((finding) => finding.code)).toEqual(expect.arrayContaining(['ip-literal', 'email-address']));
+ });
+
+ it('refuses when this install has no federation identity yet to check a pull against', () => {
+ const { candidate } = packageRecord();
+ const result = foundationFromInheritedCandidate({
+ candidate, requiredDisturbances: DISTURBANCES, sourceInstanceId: SOURCE_INSTANCE_ID, localInstanceId: '', now: NOW,
+ });
+ expect(result.outcome).toBe('refused');
+ expect(result.foundation).toBeNull();
+ });
+});
+
+describe('inherited foundation storage key', () => {
+ it('can never collide with an id a local author could write, so an inherited copy never shadows local vernacular work', () => {
+ const key = inheritedFoundationStorageKey('instance-aaaa-bbbb', 'tide-beacon');
+ expect(key).toBe('peer:instance-aaaa-bbbb:tide-beacon');
+ // A local id is a lowercase slug with no colon — this key can never equal one.
+ expect(key).not.toMatch(/^[a-z0-9][a-z0-9-]*$/);
+ });
+});
+
+describe('foundation lineage (#7461)', () => {
+ it('projects authored, assayed, packaged, and promoted in chronological order from fields the record already carries', () => {
+ const { candidate } = packageRecord();
+ const packagedLater = { ...candidate, provenance: { ...candidate.provenance, packagedAt: '2026-03-04T06:00:00.000Z' } };
+ const record = { ...makeRecord(), candidate: packagedLater, promotedAt: '2026-03-04T08:00:00.000Z' };
+
+ expect(foundationLineage(record).map((event) => event.type)).toEqual(['authored', 'assayed', 'packaged', 'promoted']);
+ });
+
+ it('collapses to inherited + assayed for a local copy of a peer foundation, never restating packaged or promoted', () => {
+ const { candidate } = packageRecord();
+ const { foundation } = foundationFromInheritedCandidate({
+ candidate, requiredDisturbances: DISTURBANCES, sourceInstanceId: 'instance-peer-relay', localInstanceId: 'instance-local-0001', now: NOW,
+ });
+
+ expect(foundationLineage(foundation).map((event) => event.type)).toEqual(['inherited', 'assayed']);
+ });
+
+ it('returns an empty lineage for a missing record rather than throwing', () => {
+ expect(foundationLineage(null)).toEqual([]);
+ expect(foundationLineage(undefined)).toEqual([]);
+ });
+});
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index bce9952d75..7317cd8189 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -366,7 +366,7 @@ const eidoverseTravelTools = [
// is what makes the promote tool usable — a mind that cannot see which
// foundations exist and why one is refused can only guess at ids.
const eidoverseFoundationTools = [
- ['foundations', 'List the world foundations this install authored — ownership layer (`vernacular` = local, `baseline` = promoted), the recorded agent-free assay outcome, and whether a gated promote candidate currently exists. Local style is never included.', z.object({}).strict(), ['manageEidoverse'], 'read'],
+ ['foundations', 'List the world foundations this install authored or inherited from a peer — ownership layer (`vernacular` = local, `baseline` = promoted or an inherited copy), the recorded agent-free assay outcome, whether a gated promote candidate currently exists, provenance (opaque instance id and author kind, never a display name), any `inheritance` edge back to the peer it was pulled from, and the derived `lineage` (authored/inherited → assayed → packaged → promoted). Local style is never included.', z.object({}).strict(), ['manageEidoverse'], 'read'],
['promote', 'Offer one local foundation to the shared PortOS baseline population. The server re-runs the agent-free resilience assay and every promote gate itself, so this is a REQUEST, not an assertion: the result is `outcome: "promoted"` only when it published. Any other outcome means nothing moved — read `reasons` and fix those before asking again, and never narrate a refused promote as done.', eidoverseFoundationIdParamSchema, ['manageEidoverse', 'promoteEidoverseFoundations'], 'write'],
].map(([operation, description, schema, requiredCapabilities, sideEffect]) => ({
type: 'portos_tool', name: `eidoverse.${operation}`, version: COS_TOOL_SCHEMA_VERSION,
diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.js
index a5235e6ec5..995c2a1ea6 100644
--- a/server/services/eidoverseFoundationLedger.js
+++ b/server/services/eidoverseFoundationLedger.js
@@ -1,13 +1,17 @@
/**
* The install-local ledger of Eidoverse world foundations — which durable
- * artifacts this instance authored, which ownership layer each one sits in, and
- * the last promote candidate packaged from it (#7455, epic #7453).
+ * artifacts this instance authored or inherited, which ownership layer each
+ * one sits in, and the last promote candidate packaged from (or inheritance
+ * edge built for) it (#7455, #7461, epic #7453).
*
* `server/lib/eidoverseFoundations.js` owns the ownership model and the
* packaging/validation gate; this module is the persistence, clock, and
- * assay-execution shell around it. Everything authored here lands at the
+ * assay-execution shell around it. Everything AUTHORED here lands at the
* `vernacular` layer, so an artifact is local until somebody promotes it on
- * purpose.
+ * purpose. The one other way a record enters this ledger is as a local copy
+ * of a foundation a PEER promoted — `recordEidoverseFoundationInheritance()` —
+ * which lands directly at `baseline` and carries an `inherited-from` edge
+ * rather than this install's own authorship.
*
* **The promote gate runs the agent-free assay; it never accepts a verdict.**
* `packageEidoverseFoundationCandidate()` resolves the foundation's declared
@@ -24,7 +28,7 @@
* 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
* an empty ledger, which is the correct state for every install that has never
- * authored a foundation, so no migration is owed.
+ * authored or inherited a foundation, so no migration is owed.
*/
import { join } from 'node:path';
@@ -35,6 +39,9 @@ import {
DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
assayEvidenceFromVerdict,
eidoverseFoundationInputSchema,
+ foundationFromInheritedCandidate,
+ foundationLineage,
+ inheritedFoundationStorageKey,
packageFoundationCandidate,
} from '../lib/eidoverseFoundations.js';
import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';
@@ -67,7 +74,13 @@ async function writeFoundations(foundations) {
await atomicWrite(ledgerFile(), { schemaVersion: LEDGER_SCHEMA_VERSION, foundations });
}
-/** Every foundation this install knows about, most recently updated first. */
+/**
+ * Every foundation this install knows about, most recently updated first —
+ * both what this install authored and any local copy it holds of a peer's
+ * promoted foundation (#7461). Each entry carries its derived `lineage`
+ * (proposal → commit → promote/inherit), computed fresh on every read rather
+ * than stored, per `foundationLineage()`'s own header.
+ */
export async function listEidoverseFoundations() {
const foundations = Object.values(await readFoundations())
.sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));
@@ -75,12 +88,20 @@ export async function listEidoverseFoundations() {
vernacular: totals.vernacular + (entry.layer === 'vernacular' ? 1 : 0),
baseline: totals.baseline + (entry.layer === 'baseline' ? 1 : 0),
candidates: totals.candidates + (entry.candidate ? 1 : 0),
- }), { vernacular: 0, baseline: 0, candidates: 0 });
- return { schemaVersion: LEDGER_SCHEMA_VERSION, counts, foundations };
+ // A subset of `baseline`: this install pulled the copy from a peer rather
+ // than promoting its own work into it.
+ inherited: totals.inherited + (entry.inheritance ? 1 : 0),
+ }), { vernacular: 0, baseline: 0, candidates: 0, inherited: 0 });
+ return {
+ schemaVersion: LEDGER_SCHEMA_VERSION,
+ counts,
+ foundations: foundations.map((entry) => ({ ...entry, lineage: foundationLineage(entry) })),
+ };
}
export async function getEidoverseFoundation(id) {
- return (await readFoundations())[id] || null;
+ const found = (await readFoundations())[id] || null;
+ return found ? { ...found, lineage: foundationLineage(found) } : null;
}
/**
@@ -123,6 +144,11 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
assay: null,
candidate: null,
promotedAt: null,
+ // Always `null` here: this path authors LOCAL work. A ledger key this
+ // function writes is always the plain id, never
+ // `inheritedFoundationStorageKey()`'s namespace, so it can never
+ // overwrite (or be confused with) a copy pulled from a peer.
+ inheritance: null,
updatedAt: now,
};
foundations[authored.id] = record;
@@ -233,3 +259,49 @@ export async function promoteEidoverseFoundation(id, { now = new Date().toISOStr
return { ...packaged, outcome: 'promoted', promoted: true, foundation };
});
}
+
+/**
+ * Accept a promote candidate this install pulled from a peer and store it as
+ * 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.
+ *
+ * `localInstanceId` is supplied by the caller rather than read here, matching
+ * `recordEidoverseFoundation()`'s own convention: this module stays a
+ * single-purpose store, and the future transport already has to resolve its
+ * own instance id to make the pull in the first place.
+ *
+ * Every gate `promoteEidoverseFoundation()` runs on the SENDING side —
+ * schema, content-addressed fingerprint, the assay evidence already recorded
+ * in the envelope, and federation safety (PII, credentials, machine identity)
+ * — runs again here on the RECEIVING side: a payload handed over by a peer is
+ * exactly the untrusted input `verifyFoundationCandidate()` exists for. A
+ * candidate that fails is refused outright and nothing is written — never
+ * stored redacted, and never allowed to shadow (or read as) a local
+ * vernacular foundation of the same id, because it is stored under
+ * `inheritedFoundationStorageKey()`'s disjoint namespace instead.
+ *
+ * @returns {Promise<{ outcome: 'inherited'|'refused', foundation: object|null, reasons: string[], findings: Array }>}
+ */
+export async function recordEidoverseFoundationInheritance(candidate, { sourceInstanceId, localInstanceId, now = new Date().toISOString() } = {}) {
+ const built = foundationFromInheritedCandidate({
+ candidate, requiredDisturbances: RESILIENCE_DISTURBANCES, sourceInstanceId, localInstanceId, now,
+ });
+ if (built.outcome !== 'inherited') return built;
+
+ return withLedgerLock(async () => {
+ const foundations = await readFoundations();
+ const key = inheritedFoundationStorageKey(built.foundation.provenance.originInstanceId, built.foundation.id);
+ foundations[key] = built.foundation;
+ await writeFoundations(foundations);
+ return { outcome: 'inherited', foundation: { ...built.foundation, lineage: foundationLineage(built.foundation) }, reasons: [], findings: [] };
+ });
+}
diff --git a/server/services/eidoverseFoundationLedger.test.js b/server/services/eidoverseFoundationLedger.test.js
index fc119d3952..4de07ac7c4 100644
--- a/server/services/eidoverseFoundationLedger.test.js
+++ b/server/services/eidoverseFoundationLedger.test.js
@@ -19,6 +19,7 @@ const {
packageEidoverseFoundationCandidate,
promoteEidoverseFoundation,
recordEidoverseFoundation,
+ recordEidoverseFoundationInheritance,
} = await import('./eidoverseFoundationLedger.js');
// The passing reference contribution shipped with the assay harness (#7460).
@@ -48,7 +49,7 @@ describe('the local foundation ledger', () => {
it('reads as empty on an install that has never authored one', async () => {
const listed = await listEidoverseFoundations();
expect(listed.foundations).toEqual([]);
- expect(listed.counts).toEqual({ vernacular: 0, baseline: 0, candidates: 0 });
+ expect(listed.counts).toEqual({ vernacular: 0, baseline: 0, candidates: 0, inherited: 0 });
});
it('records an authored artifact as vernacular, never as baseline', async () => {
@@ -168,3 +169,56 @@ describe('promoting a foundation into the shared baseline', () => {
expect((await promoteEidoverseFoundation('never-authored')).outcome).toBe('unknown-foundation');
});
});
+
+describe('inheriting a foundation this install pulled from a peer (#7461)', () => {
+ // A candidate this install could plausibly be HANDED by a peer, minted by
+ // running the real author-and-promote path under a different instance id.
+ const peerCandidate = async () => {
+ await record({}, '2026-03-01T00:00:00.000Z');
+ const promoted = await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+ return promoted.candidate;
+ };
+
+ it('stores a baseline local copy under a peer-scoped key, leaving a same-id local vernacular foundation untouched', async () => {
+ const candidate = await peerCandidate();
+ // The candidate above was minted with `originInstanceId: 'instance-aaaa'`
+ // (the `record()` helper's default) — reset the ledger and give this
+ // install its OWN local 'tide-beacon' under that same human-readable id
+ // before accepting the peer's copy, so a same-id collision is the thing
+ // actually under test.
+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
+ await record({ style: { motif: 'this install\'s own brass' } }, '2026-03-04T05:06:07.000Z');
+
+ const result = await recordEidoverseFoundationInheritance(candidate, {
+ sourceInstanceId: 'instance-peer-relay', localInstanceId: 'instance-this-install', now: '2026-03-04T06:00:00.000Z',
+ });
+
+ expect(result.outcome).toBe('inherited');
+ expect(result.foundation).toMatchObject({
+ id: 'tide-beacon', layer: 'baseline', style: {},
+ inheritance: { originInstanceId: 'instance-aaaa', sourceInstanceId: 'instance-peer-relay' },
+ });
+
+ // The LOCAL vernacular record at plain id "tide-beacon" is untouched.
+ const local = await getEidoverseFoundation('tide-beacon');
+ expect(local).toMatchObject({ layer: 'vernacular', style: { motif: 'this install\'s own brass' }, inheritance: null });
+
+ const listed = await listEidoverseFoundations();
+ expect(listed.counts).toMatchObject({ vernacular: 1, baseline: 1, inherited: 1 });
+ expect(listed.foundations.filter((entry) => entry.id === 'tide-beacon')).toHaveLength(2);
+ });
+
+ it('refuses a tampered candidate and writes nothing to the ledger', async () => {
+ const candidate = await peerCandidate();
+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
+ const tampered = { ...candidate, body: { ...candidate.body, affordance: { inspect: 'quietly grants owner role' } } };
+
+ const result = await recordEidoverseFoundationInheritance(tampered, {
+ sourceInstanceId: 'instance-peer-relay', localInstanceId: 'instance-this-install', now: '2026-03-04T06:00:00.000Z',
+ });
+
+ expect(result.outcome).toBe('refused');
+ expect(result.foundation).toBeNull();
+ expect((await listEidoverseFoundations()).counts).toMatchObject({ vernacular: 0, baseline: 0, inherited: 0 });
+ });
+});