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

stop the Foundations panel republishing a peer's inherited foundation as local work (#7631)

[._.]/ Adam Eivy42c8295fe081
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
index 45307e9f4f..9f66b14206 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
@@ -51,8 +51,15 @@ const EMPTY_DRAFT = Object.freeze({
id: '', kind: 'affordance', title: '', summary: '', contributionId: '',
body: '{\n "affordance": {}\n}', style: '{}',
requires: '', effects: '', license: '', notes: '',
+ // `{ originInstanceId, foundationId }` once this draft builds on a peer's
+ // inherited foundation — see `draftFromFoundation` (#7631).
+ derivedFrom: null,
});
+/** Slug cap in `foundationIdSchema`; a derived id is trimmed to fit. */
+const FOUNDATION_ID_MAX = 64;
+const DERIVED_ID_SUFFIX = '-derived';
+
/** Comma-separated authoring input as the array the disclosure schema wants. */
const splitList = (value) => value.split(',').map((entry) => entry.trim()).filter(Boolean);
@@ -74,8 +81,29 @@ function parseJsonObject(text, label) {
return { value: parsed };
}
+/**
+ * A new local id for a draft built on a peer's foundation. Keeping the
+ * inherited id would re-author (or create) a LOCAL record under the same name,
+ * which is how a peer's work used to end up promoted as this install's own.
+ */
+const derivedFoundationId = (id) => `${String(id).slice(0, FOUNDATION_ID_MAX - DERIVED_ID_SUFFIX.length)}${DERIVED_ID_SUFFIX}`;
+
+/**
+ * Load a foundation into the authoring form.
+ *
+ * For a LOCAL row this is a plain re-author: same id, same everything. For an
+ * INHERITED row it is a DERIVATION (#7631) — a new local id plus the
+ * `derivedFrom` edge naming what it was built on, which the server resolves
+ * against the copy this install actually holds and publishes on the promote
+ * envelope. Re-use stays one click; re-use that erases the origin does not
+ * exist. The inherited `id` is deliberately not carried over: the acceptance
+ * test for this change asserts exactly that.
+ */
const draftFromFoundation = (foundation) => ({
- id: foundation.id,
+ id: foundation.inheritance ? derivedFoundationId(foundation.id) : foundation.id,
+ derivedFrom: foundation.inheritance
+ ? { originInstanceId: foundation.inheritance.originInstanceId, foundationId: foundation.id }
+ : null,
kind: foundation.kind,
title: foundation.title,
summary: foundation.summary,
@@ -154,9 +182,26 @@ function InheritedFromBadge({ inheritance }) {
);
}
+/** This install's own work, built on a peer's foundation — the opposite claim
+ * to `InheritedFromBadge`'s, and the one that keeps attribution when somebody
+ * re-uses what a peer promoted (#7631). */
+function DerivedFromBadge({ derivedFrom }) {
+ if (!derivedFrom) 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={`Built on "${derivedFrom.foundationId}" from instance ${derivedFrom.originInstanceId}`}
+ >
+ <GitFork size={12} aria-hidden="true" />
+ Derived
+ </span>
+ );
+}
+
const LINEAGE_COPY = Object.freeze({
authored: (event) => `Authored (${event.authorKind || 'unknown'})`,
inherited: (event) => `Inherited from instance ${event.originInstanceId}`,
+ derived: (event) => `Derived from "${event.foundationId}" on 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',
@@ -260,6 +305,9 @@ export default function EidoverseFoundationsPanel() {
contributionId: draft.contributionId.trim(),
body: body.value,
style: style.value,
+ // Omitted rather than sent as `null` when absent: the field is optional
+ // on the input schema, and an explicit `null` is the same thing to it.
+ ...(draft.derivedFrom ? { derivedFrom: draft.derivedFrom } : {}),
disclosure: {
requires: splitList(draft.requires),
effects: splitList(draft.effects),
@@ -324,6 +372,7 @@ export default function EidoverseFoundationsPanel() {
<h4 className="font-medium text-white">{foundation.title}</h4>
<LayerBadge layer={foundation.layer} />
<InheritedFromBadge inheritance={foundation.inheritance} />
+ <DerivedFromBadge derivedFrom={foundation.derivedFrom} />
<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>
@@ -386,8 +435,15 @@ export default function EidoverseFoundationsPanel() {
</p>
<pre className="max-h-32 overflow-auto rounded-lg bg-port-bg p-3 text-xs text-gray-300">{JSON.stringify(foundation.style, null, 2)}</pre>
<button type="button" className={secondaryButton} onClick={() => setDraft(draftFromFoundation(foundation))}>
- Load into the form below
+ {foundation.inheritance ? 'Build on this in the form below' : 'Load into the form below'}
</button>
+ {foundation.inheritance && (
+ <p className="text-xs text-gray-500">
+ Loads a new local id and records a derivation edge back to instance{' '}
+ {foundation.inheritance.originInstanceId}, which travels with the foundation if you
+ promote it. Saving this body unchanged as your own work is refused.
+ </p>
+ )}
</div>
)}
</li>
@@ -403,6 +459,13 @@ export default function EidoverseFoundationsPanel() {
both described the previous body. A foundation already in the shared baseline returns to local when
you edit it, so the new body can be promoted in its turn.
</p>
+ {draft.derivedFrom && (
+ <p className="mt-3 rounded-lg border border-port-accent/40 bg-port-accent/5 p-3 text-sm text-gray-300" role="status">
+ Building on <code className="text-gray-200">{draft.derivedFrom.foundationId}</code> from instance{' '}
+ <code className="text-gray-200">{draft.derivedFrom.originInstanceId}</code>. Recording this keeps the
+ edge back to that install, and promoting it publishes the edge rather than your name alone.
+ </p>
+ )}
<form className="mt-4 space-y-3" onSubmit={submitDraft}>
<div className="grid gap-3 sm:grid-cols-2">
<div>
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
index 25d1389fb2..b36dd4967f 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
@@ -41,6 +41,21 @@ const foundation = (overrides = {}) => ({
...overrides,
});
+/** A local copy of a peer's promoted foundation, as the list endpoint serves it. */
+const inheritedFoundation = () => 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 },
+ ],
+});
+
const listing = (foundations, counts) => ({
foundations,
counts: counts || { vernacular: foundations.length, baseline: 0, candidates: 0 },
@@ -119,19 +134,7 @@ describe('the Eidoverse foundations promote panel', () => {
});
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 },
- ],
- });
+ const inherited = inheritedFoundation();
listEidoverseFoundations.mockResolvedValue(listing([inherited], { vernacular: 0, baseline: 1, candidates: 0, inherited: 1 }));
getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
await renderPanel();
@@ -143,4 +146,37 @@ describe('the Eidoverse foundations promote panel', () => {
fireEvent.click(screen.getByRole('button', { name: 'Details' }));
expect(screen.getByText(/Inherited from instance instance-origin-peer/)).toBeInTheDocument();
});
+
+ /**
+ * #7631: 'Load into the form below' sat OUTSIDE the guard that hides Promote
+ * and Run assay, and copied the inherited id verbatim. Saving the form then
+ * wrote a LOCAL record under that id with this install's own origin and no
+ * edge, which promoted and was served to peers as this install's own work.
+ */
+ it('turns re-use of an inherited foundation into a derivation instead of a copy under the peer\'s own id (#7631)', async () => {
+ listEidoverseFoundations.mockResolvedValue(listing([inheritedFoundation()], { vernacular: 0, baseline: 1, candidates: 0, inherited: 1 }));
+ getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ recordEidoverseFoundation.mockResolvedValue({ success: true });
+ await renderPanel();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Details' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Build on this in the form below' }));
+
+ // The inherited id is NOT reused: that id is what made the copy look like
+ // a re-author of this install's own foundation.
+ const idField = screen.getByLabelText('Id (lowercase slug)');
+ expect(idField.value).not.toBe('tide-beacon');
+ expect(idField.value).toBe('tide-beacon-derived');
+ expect(screen.getByText(/Building on/)).toBeInTheDocument();
+
+ await act(async () => { fireEvent.submit(idField.closest('form')); });
+
+ expect(recordEidoverseFoundation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'tide-beacon-derived',
+ derivedFrom: { originInstanceId: 'instance-origin-peer', foundationId: 'tide-beacon' },
+ }),
+ expect.anything(),
+ );
+ });
});
diff --git a/docs/API.md b/docs/API.md
index 8fca81a21b..055409f772 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -361,7 +361,7 @@ federate world records.
| 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, 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 |
+| POST | `/eidoverse/world/foundations` | Record (or re-author) a local vernacular foundation — the layer is never caller-supplied; a body copied from an inherited foundation is refused with 409 unless it carries a `derivedFrom: { originInstanceId, foundationId }` edge naming it |
| 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 |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 4481e3d5d6..d1a3b0a2d0 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 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 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. A write under that key is REFUSED, not applied, when the record already there was inherited from a different peer: the key is chosen by an origin the sender claims and hashes into its own fingerprint, so without that check a peer could replace this install's genuine copy of a third install's foundation (#7631). A record this install AUTHORED by building on an inherited one instead carries a `derivedFrom` edge (`{ originInstanceId, foundationId, fingerprint, derivedAt }`), which is the one provenance field that also rides the promote envelope — so a body copied from a peer is refused unless it says what it was derived from, and what it publishes is "derived from that install's X" rather than local authorship. 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`/`derivedFrom` 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/`.
- Eidoverse observation visit marker — `data/eidoverse/observation.json` (#7457). What this install's mind had already seen the last time it toured its own world: the foundation ids, opaque peer ids, per-district status, and already-failing controller ids observed at that moment, plus when. It exists so "what is new since I last looked" survives a WAKE BOUNDARY — the nearest in-memory equivalents do not (the world chat cursor lives in a ring buffer a restart empties; the peer sync's `lastOfferingListHash` is per-peer change detection for a background sweep). `file-primary` and **intentionally machine-local — never federated**: a marker records this install's own mind's behavior, which the [machine-local privacy ADR](decisions/2026-08-08-privacy-records-machine-local.md) keeps off the federation layer, and it holds no body, style, or record content. No `data.reference/` seed and no migration — an absent file IS the never-observed state every install starts from, and that state is deliberately distinct from an empty one: the first observation reports `firstObservation: true` rather than declaring a settled world new. A marker stamped by a NEWER PortOS degrades to that same never-observed state rather than being diffed against fields this build does not understand. 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.
diff --git a/server/lib/eidoverseFoundations.js b/server/lib/eidoverseFoundations.js
index e49a782032..bae1869207 100644
--- a/server/lib/eidoverseFoundations.js
+++ b/server/lib/eidoverseFoundations.js
@@ -79,8 +79,22 @@ export const EIDOVERSE_FOUNDATION_KINDS = Object.freeze(['schema', 'affordance',
/** Wire stamp on the promote envelope. The peer pull/inherit slice gates on
* this; it is deliberately separate from `PORTOS_SCHEMA_VERSIONS`, which
* versions STORAGE layouts for the record-sync transports this payload does
- * not ride. */
-export const EIDOVERSE_FOUNDATION_CANDIDATE_VERSION = 1;
+ * not ride.
+ *
+ * v2 added the `derived-from` edge (#7631), so an install that builds on a
+ * peer's foundation publishes "derived from A's X" instead of a byte-identical
+ * body stamped as its own work. */
+export const EIDOVERSE_FOUNDATION_CANDIDATE_VERSION = 2;
+
+/**
+ * Every envelope version this install can still READ. A v1 envelope predates
+ * the derivation edge and is otherwise byte-for-byte the shape it always was,
+ * so refusing it would strand every not-yet-upgraded peer's whole offering for
+ * a field that is absent by construction — and, because the fingerprint is
+ * hashed over the envelope AS SENT, a v1 payload still verifies unchanged.
+ * Only `EIDOVERSE_FOUNDATION_CANDIDATE_VERSION` is ever WRITTEN.
+ */
+export const EIDOVERSE_FOUNDATION_CANDIDATE_VERSIONS_ACCEPTED = Object.freeze([1, 2]);
/**
* Keys that are UNAMBIGUOUSLY cosmetic and so must never appear inside a
@@ -207,6 +221,46 @@ export const foundationInheritanceEdgeSchema = z.object({
inheritedAt: isoDateSchema,
}).strict();
+/**
+ * The second provenance-graph edge (#7631): "this install AUTHORED this
+ * foundation, building on the copy it holds of `foundationId` from origin
+ * `originInstanceId`."
+ *
+ * Deliberately a separate field from `inheritance` rather than a variant of
+ * it, because the two make opposite claims about who did the work. An
+ * `inherited` record is a peer's foundation this install merely stores and may
+ * never re-share; a `derived` record IS this install's own work and promotes
+ * normally — it just carries, and publishes, the edge back to what it was
+ * built from. That is what makes "build on a peer's foundation" a one-click
+ * path that keeps attribution instead of a one-click path that erases it.
+ *
+ * `fingerprint` is the ORIGIN's candidate digest, copied off the inherited
+ * record this install actually holds rather than from the caller's claim (see
+ * `resolveFoundationDerivation`): the edge then attests what was inherited,
+ * not what someone asserted. `derivedAt` is stamped when the edge is first
+ * recorded and carried across later re-authorings of the same body, the same
+ * way `provenance.createdAt` is.
+ */
+export const foundationDerivationEdgeSchema = z.object({
+ type: z.literal('derived-from'),
+ originInstanceId: instanceIdSchema,
+ foundationId: foundationIdSchema,
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/, 'must be a sha256 hex digest'),
+ derivedAt: isoDateSchema,
+}).strict();
+
+/**
+ * What an AUTHOR may claim — which inherited foundation this new body builds
+ * on, and nothing more. The digest and the timestamp are deliberately absent:
+ * both are stamped from this install's own ledger, so no caller (a route body,
+ * a mind tool, a hand-edited file) can mint a derivation edge pointing at a
+ * fingerprint or a moment this install never saw.
+ */
+export const foundationDerivationClaimSchema = z.object({
+ originInstanceId: instanceIdSchema,
+ foundationId: foundationIdSchema,
+}).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
@@ -248,6 +302,13 @@ export const eidoverseFoundationRecordSchema = z.object({
// 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),
+ // `null` on everything authored from nothing. Set on a record this install
+ // authored by building on a peer's inherited foundation (#7631), and copied
+ // onto a local copy of a peer's record whose own envelope carried one, so a
+ // third install reads the whole chain rather than just the last hop. Additive
+ // and nullable on a machine-local ledger, so no migration is owed — same
+ // argument as `inheritance` above.
+ derivedFrom: foundationDerivationEdgeSchema.nullable().default(null),
updatedAt: isoDateSchema,
}).strict();
@@ -262,12 +323,15 @@ export const eidoverseFoundationInputSchema = z.object({
style: foundationStyleSchema.default({}),
disclosure: foundationDisclosureSchema.default({}),
authorKind: authorKindSchema.default('user'),
+ // A CLAIM, not the edge: see `foundationDerivationClaimSchema`.
+ derivedFrom: foundationDerivationClaimSchema.nullable().default(null),
}).strict();
/** The promote envelope — the only shape authorized to cross to a peer. */
export const eidoverseFoundationCandidateSchema = z.object({
...foundationCoreShape,
- candidateVersion: z.literal(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION),
+ candidateVersion: z.union(EIDOVERSE_FOUNDATION_CANDIDATE_VERSIONS_ACCEPTED.map((version) => z.literal(version))),
+ derivedFrom: foundationDerivationEdgeSchema.nullable().default(null),
foundationId: foundationIdSchema,
provenance: foundationProvenanceSchema.extend({
packagedAt: isoDateSchema,
@@ -387,6 +451,95 @@ function withoutFingerprint(candidate) {
return rest;
}
+/**
+ * The scan input: the hash input, minus the derivation edge's digest as well.
+ * A `derived-from` edge carries the ORIGIN's candidate fingerprint, which is
+ * another 64 unbroken hex characters and so trips `scrubSecretTokens` exactly
+ * as the envelope's own digest would. It is excluded from the SCAN only — it
+ * stays in the hash input, because the edge is part of what the fingerprint
+ * has to cover for a receiver to detect a re-attributed envelope.
+ */
+function scannableCandidate(candidate) {
+ const rest = withoutFingerprint(candidate);
+ if (!rest.derivedFrom || typeof rest.derivedFrom !== 'object') return rest;
+ const { fingerprint: _edgeDigest, ...edge } = rest.derivedFrom;
+ return { ...rest, derivedFrom: edge };
+}
+
+/**
+ * A content address for a foundation `body` alone — the same canonicalization
+ * the candidate fingerprint uses, so key order and whitespace never decide
+ * whether two bodies are "the same work".
+ */
+export function foundationBodyDigest(body) {
+ return createHash('sha256').update(canonicalStringify(body ?? {})).digest('hex');
+}
+
+/**
+ * Resolve the `derived-from` edge an authored foundation carries — or the
+ * reason this install refuses to record the body as its own work (#7631).
+ *
+ * The guard this replaces tested `record.inheritance`, a field the authoring
+ * path clears unconditionally: loading a peer's foundation into the authoring
+ * form and saving it produced a local record stamped with THIS install's
+ * origin and no edge at all, which promoted and re-shared cleanly. So the
+ * check moved off the mutable flag and onto the bytes: a body that
+ * canonicalizes to one this install holds under an inherited key is refused
+ * unless the author says what it is derived from.
+ *
+ * A claim is resolved against the inherited records this install ACTUALLY
+ * holds, and the resulting edge is stamped from that record. A claim naming a
+ * foundation this install never inherited is refused rather than recorded,
+ * which is what keeps the edge an attestation of local ledger state instead of
+ * a free-text assertion that travels to peers.
+ *
+ * An existing edge survives a re-authoring the same way `provenance` does: a
+ * derivation that a later edit diverges from is still the thing this work grew
+ * out of, and dropping the edge on the first byte changed would make erasure
+ * the easy path all over again.
+ *
+ * Pure: the caller supplies the inherited records, the previous edge, and the
+ * clock.
+ *
+ * @param {object} options
+ * @param {{ originInstanceId: string, foundationId: string }|null} options.claim
+ * @param {object} options.body - the body being authored
+ * @param {Array<object>} options.inheritedRecords - ledger records carrying an `inheritance` edge
+ * @param {object|null} [options.existingEdge] - the edge the record being re-authored already carried
+ * @param {string} options.now
+ * @returns {{ edge: object|null, refusal: string|null }}
+ */
+export function resolveFoundationDerivation({ claim, body, inheritedRecords, existingEdge = null, now }) {
+ const held = (inheritedRecords || []).filter((entry) => entry?.inheritance && entry?.provenance);
+ let edge = existingEdge || null;
+
+ if (claim) {
+ const source = held.find((entry) => entry.provenance.originInstanceId === claim.originInstanceId && entry.id === claim.foundationId);
+ if (!source) {
+ return { edge: null, refusal: `no foundation inherited from install ${claim.originInstanceId} is recorded under "${claim.foundationId}" — a derivation edge names a foundation this install actually holds` };
+ }
+ const carried = edge && edge.originInstanceId === claim.originInstanceId && edge.foundationId === claim.foundationId;
+ edge = {
+ type: 'derived-from',
+ originInstanceId: claim.originInstanceId,
+ foundationId: claim.foundationId,
+ fingerprint: source.inheritance.fingerprint,
+ derivedAt: carried ? edge.derivedAt : now,
+ };
+ }
+
+ const digest = foundationBodyDigest(body);
+ const copied = held.find((entry) => foundationBodyDigest(entry.body) === digest);
+ if (copied && !(edge && edge.originInstanceId === copied.provenance.originInstanceId && edge.foundationId === copied.id)) {
+ return {
+ edge: null,
+ refusal: `this body is byte-for-byte the foundation "${copied.id}" inherited from install ${copied.provenance.originInstanceId} — record it as a derivation of that foundation rather than as this install's own work`,
+ };
+ }
+
+ return { edge, refusal: null };
+}
+
/**
* Package a local vernacular foundation into a promote candidate.
*
@@ -432,6 +585,11 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
disclosure: foundation.disclosure,
provenance: { ...foundation.provenance, packagedAt: now, portosVersion },
assay: foundation.assay,
+ // Published, not just remembered: a receiver that cannot see the edge has
+ // no way to tell this install's own work from a body it built on a peer's.
+ // Omitted rather than sent as `null` when there is none, so an undecorated
+ // v2 envelope hashes over exactly the fields a v1 one did.
+ ...(foundation.derivedFrom ? { derivedFrom: foundation.derivedFrom } : {}),
};
const candidate = { ...draft, fingerprint: foundationCandidateFingerprint(draft) };
@@ -466,10 +624,17 @@ export function verifyFoundationCandidate(candidate, { requiredDisturbances }) {
reasons.push('fingerprint does not match the candidate body — the payload was altered after packaging');
}
+ // A v1 envelope predates the derivation edge, so one that carries anyway is
+ // not an older peer — it is a payload assembled by hand. Refuse it rather
+ // than accept an edge under a version whose fingerprint never covered one.
+ if (envelope.candidateVersion === 1 && envelope.derivedFrom) {
+ reasons.push('a v1 promote envelope cannot carry a derived-from edge — the field was introduced at candidateVersion 2');
+ }
+
const assayRefusal = assayEvidenceRefusal(envelope.assay, requiredDisturbances, envelope.contributionId);
if (assayRefusal) reasons.push(assayRefusal);
- const findings = [...styleLeakFindings(envelope.body), ...federationSafetyFindings(withoutFingerprint(envelope))];
+ const findings = [...styleLeakFindings(envelope.body), ...federationSafetyFindings(scannableCandidate(envelope))];
for (const finding of findings) reasons.push(`${finding.path}: ${finding.detail} (${finding.code})`);
return { valid: reasons.length === 0, reasons, findings };
@@ -567,6 +732,11 @@ export function foundationFromInheritedCandidate({ candidate, requiredDisturbanc
assay: envelope.assay,
candidate: envelope,
promotedAt: null,
+ // Copied verbatim off the envelope (absent on a v1 one, which reads back
+ // as `null`): the origin told us its own work was derived from a third
+ // install's, and dropping that here would truncate the chain to the last
+ // hop on every install downstream of it.
+ derivedFrom: envelope.derivedFrom ?? null,
inheritance: {
type: 'inherited-from',
originInstanceId: envelope.provenance.originInstanceId,
@@ -617,6 +787,19 @@ export function foundationLineage(record) {
});
}
+ // Emitted alongside `authored` or `inherited` rather than instead of either:
+ // a derivation says what this work GREW OUT OF, which is a different fact
+ // from who authored the record and from which peer handed it over (#7631).
+ if (record.derivedFrom) {
+ events.push({
+ type: 'derived',
+ at: record.derivedFrom.derivedAt,
+ originInstanceId: record.derivedFrom.originInstanceId,
+ foundationId: record.derivedFrom.foundationId,
+ fingerprint: record.derivedFrom.fingerprint,
+ });
+ }
+
if (record.assay?.ranAt) {
events.push({ type: 'assayed', at: record.assay.ranAt, pass: record.assay.pass === true });
}
@@ -681,6 +864,7 @@ export function summarizeFoundation(record) {
? { originInstanceId: record.provenance.originInstanceId ?? null, authorKind: record.provenance.authorKind ?? null, createdAt: record.provenance.createdAt ?? null }
: null,
inheritance: record?.inheritance ?? null,
+ derivedFrom: record?.derivedFrom ?? null,
lineage: foundationLineage(record),
};
}
diff --git a/server/lib/eidoverseFoundations.test.js b/server/lib/eidoverseFoundations.test.js
index 61497b9b41..c59899596d 100644
--- a/server/lib/eidoverseFoundations.test.js
+++ b/server/lib/eidoverseFoundations.test.js
@@ -323,3 +323,59 @@ describe('foundation lineage (#7461)', () => {
expect(foundationLineage(undefined)).toEqual([]);
});
});
+
+/**
+ * #7631: the derivation edge is the one field on the envelope that carries
+ * another install's sha256. Two things about it can only be pinned here — the
+ * digest must stay INSIDE the content-addressed fingerprint yet OUTSIDE the
+ * credential scan (`scrubSecretTokens` treats 64 unbroken hex characters as a
+ * leaked secret, so a naive scan refuses every derived foundation ever
+ * promoted), and a v1 envelope must keep verifying byte-for-byte.
+ */
+describe('the derived-from edge on a promote envelope (#7631)', () => {
+ const derivedFrom = {
+ type: 'derived-from',
+ originInstanceId: 'instance-origin-peer',
+ foundationId: 'tide-beacon',
+ fingerprint: 'b'.repeat(64),
+ derivedAt: NOW,
+ };
+
+ it('packages and re-verifies a derived foundation instead of refusing its edge as a credential', () => {
+ // The scan reads the edge's digest as credential-shaped on its own; the
+ // packaging path has to exclude that ONE field from the scan without
+ // excluding it from the hash.
+ expect(federationSafetyFindings({ derivedFrom })).toHaveLength(1);
+
+ const result = packageRecord({ derivedFrom });
+
+ expect(result.outcome).toBe('packaged');
+ expect(result.candidate.candidateVersion).toBe(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION);
+ expect(result.candidate.derivedFrom).toEqual(derivedFrom);
+ expect(verifyFoundationCandidate(result.candidate, { requiredDisturbances: DISTURBANCES }).valid).toBe(true);
+ });
+
+ it('refuses a v1 envelope that carries an edge its version never hashed', () => {
+ const packaged = packageRecord({ derivedFrom }).candidate;
+ const backdated = { ...packaged, candidateVersion: 1 };
+ backdated.fingerprint = foundationCandidateFingerprint({ ...backdated, fingerprint: undefined });
+
+ const verified = verifyFoundationCandidate(backdated, { requiredDisturbances: DISTURBANCES });
+
+ expect(verified.valid).toBe(false);
+ expect(verified.reasons.join(' ')).toContain('candidateVersion 2');
+ });
+
+ it('carries an origin\'s own derivation edge onto the inheriting install, so the chain does not truncate to the last hop', () => {
+ const candidate = packageRecord({ derivedFrom }).candidate;
+
+ const inherited = foundationFromInheritedCandidate({
+ candidate, requiredDisturbances: DISTURBANCES, sourceInstanceId: 'instance-peer-relay',
+ localInstanceId: 'instance-this-install', now: '2026-03-05T00:00:00.000Z',
+ });
+
+ expect(inherited.outcome).toBe('inherited');
+ expect(inherited.foundation.derivedFrom).toEqual(derivedFrom);
+ expect(foundationLineage(inherited.foundation).map((event) => event.type)).toContain('derived');
+ });
+});
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index bdb075f205..a6f7f89432 100644
--- a/server/lib/persistentMindCapabilities.js
+++ b/server/lib/persistentMindCapabilities.js
@@ -157,7 +157,7 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([
'The server runs the agent-free resilience assay itself — the mind can ask for the check, never assert a passing verdict',
'The promote envelope carries the foundation\'s body and drops its style layer, so an inheriting peer keeps its own cosmetics',
'A candidate carrying machine identity, PII, or credential-shaped values is refused outright and never redacted and shipped',
- 'Promotion publishes only what this install authored; it cannot reach another install\'s foundations',
+ 'Promotion publishes only what this install authored; a body copied from an inherited foundation is refused unless it is recorded as a derivation, and the edge back to the origin travels with it',
],
}),
Object.freeze({
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index a863d5d721..6c98c6b02f 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -712,7 +712,13 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// 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,
+ //
+ // v2 (#7631): the envelope gained the `derived-from` edge, so both numbers
+ // moved together exactly as the note above requires. A v2 RECEIVER still
+ // accepts a v1 offering unchanged (the edge is absent by construction there),
+ // and a v1 receiver gently skips a v2 one rather than storing an envelope
+ // whose attribution it would read as plain local authorship.
+ eidoverseFoundations: 2,
// 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
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 8e150c46ef..4137c2e93b 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -370,7 +370,7 @@ const eidoverseTravelTools = [
const eidoverseFoundationTools = [
['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'],
['contributions', 'List the resilience-assay contributions registered on this install — the ids a foundation\'s `contributionId` may bind to before it is promotable.', z.object({}).strict(), ['manageEidoverse'], 'read'],
- ['record', 'Record (or re-author) a local vernacular foundation — a durable, promotable creative build (a `schema`, `affordance`, `controller`, or `district-template`). It always lands on this install\'s local `vernacular` layer; the layer is not accepted from you and nothing crosses to a peer until eidoverse.promote is called separately. Use eidoverse.creative-catalog for material/motif/layout ids and eidoverse.contributions for a valid `contributionId` first. `style` (palette, motif, aliases) stays local forever; a cosmetic key found inside `body` refuses the write instead of being silently dropped.', eidoverseFoundationInputSchema, ['manageEidoverse'], 'write'],
+ ['record', 'Record (or re-author) a local vernacular foundation — a durable, promotable creative build (a `schema`, `affordance`, `controller`, or `district-template`). It always lands on this install\'s local `vernacular` layer; the layer is not accepted from you and nothing crosses to a peer until eidoverse.promote is called separately. Use eidoverse.creative-catalog for material/motif/layout ids and eidoverse.contributions for a valid `contributionId` first. `style` (palette, motif, aliases) stays local forever; a cosmetic key found inside `body` refuses the write instead of being silently dropped. To build on a foundation this install inherited from a peer, pass `derivedFrom: { originInstanceId, foundationId }` naming it: an identical body with no such edge is refused rather than recorded as this install\'s own work.', eidoverseFoundationInputSchema, ['manageEidoverse'], 'write'],
['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 635c32b986..234e178609 100644
--- a/server/services/eidoverseFoundationLedger.js
+++ b/server/services/eidoverseFoundationLedger.js
@@ -13,6 +13,14 @@
* which lands directly at `baseline` and carries an `inherited-from` edge
* rather than this install's own authorship.
*
+ * Between the two sits DERIVATION (#7631): a record this install authored by
+ * building on an inherited copy. It is local work — it packages and promotes
+ * like any other — but it carries, and publishes, a `derived-from` edge back to
+ * the origin. `recordEidoverseFoundation()` refuses a body that matches an
+ * inherited one and names no such edge, which is what closed the path from
+ * 'load a peer's foundation into the authoring form' to 're-share it as this
+ * install's own work'.
+ *
* **The promote gate runs the agent-free assay; it never accepts a verdict.**
* `packageEidoverseFoundationCandidate()` resolves the foundation's declared
* contribution by ID through `eidoverseResilienceContributions.js`, replays it
@@ -45,8 +53,10 @@ import {
foundationLineage,
inheritedFoundationStorageKey,
packageFoundationCandidate,
+ resolveFoundationDerivation,
verifyFoundationCandidate,
} from '../lib/eidoverseFoundations.js';
+import { ServerError } from '../lib/errorHandler.js';
import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';
import { findContributionById } from './eidoverseResilienceContributions.js';
@@ -176,6 +186,22 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
return withLedgerLock(async () => {
const foundations = await readFoundations();
const existing = foundations[authored.id] || null;
+ // The republish guard (#7631). `inheritance` below is a field THIS path
+ // clears, so it could never have stopped a peer's foundation being saved
+ // back through the authoring surface and promoted as local work; the body
+ // itself is what gets checked, against every inherited copy this install
+ // holds. A refusal is thrown rather than returned because both callers —
+ // the route and the mind tool — treat this function's return value as the
+ // recorded foundation, and a verdict shape would make "refused" look like
+ // a saved record to anything that did not read the new field.
+ const derivation = resolveFoundationDerivation({
+ claim: authored.derivedFrom,
+ body: authored.body,
+ inheritedRecords: Object.values(foundations),
+ existingEdge: existing?.derivedFrom || null,
+ now,
+ });
+ if (derivation.refusal) throw new ServerError(derivation.refusal, { status: 409 });
const record = {
id: authored.id,
layer: DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
@@ -195,6 +221,7 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
// `inheritedFoundationStorageKey()`'s namespace, so it can never
// overwrite (or be confused with) a copy pulled from a peer.
inheritance: null,
+ derivedFrom: derivation.edge,
updatedAt: now,
};
foundations[authored.id] = record;
@@ -354,7 +381,30 @@ export async function recordEidoverseFoundationInheritance(candidate, { sourceIn
return withLedgerLock(async () => {
const foundations = await readFoundations();
- const key = inheritedFoundationStorageKey(built.foundation.provenance.originInstanceId, built.foundation.id);
+ const originInstanceId = built.foundation.provenance.originInstanceId;
+ const key = inheritedFoundationStorageKey(originInstanceId, built.foundation.id);
+ // The storage key is chosen by `provenance.originInstanceId` — a field the
+ // SENDER wrote and hashed into its own fingerprint, so re-fingerprinting an
+ // altered origin costs a forger nothing and `verifyFoundationCandidate()`
+ // (which only checks self-consistency) cannot see it. Without this check a
+ // peer offering an envelope that claims ANOTHER install's origin silently
+ // replaced this install's genuine copy of that install's foundation (#7631).
+ //
+ // Divergence is the whole signal: `listPromotedFoundationCandidates()`
+ // filters out inherited records, so no shipped install re-shares a
+ // foundation it did not author, and a genuine record under this key can
+ // therefore only ever have come from the origin itself. Re-offering from
+ // the SAME peer stays an ordinary update.
+ const held = foundations[key];
+ if (held?.inheritance && held.inheritance.sourceInstanceId !== sourceInstanceId) {
+ console.warn(`⚠️ Eidoverse foundation "${built.foundation.id}" attributed to origin ${originInstanceId} is already held from peer ${held.inheritance.sourceInstanceId} — refusing the copy offered by peer ${sourceInstanceId} rather than overwriting it`);
+ return {
+ outcome: 'refused',
+ foundation: null,
+ reasons: [`this install already holds "${built.foundation.id}" from origin ${originInstanceId} by way of peer ${held.inheritance.sourceInstanceId}; peer ${sourceInstanceId} offered a different copy under that same origin — refusing rather than overwriting the record already attributed to it`],
+ findings: [],
+ };
+ }
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 1c6d7dd891..79fbcc10b1 100644
--- a/server/services/eidoverseFoundationLedger.test.js
+++ b/server/services/eidoverseFoundationLedger.test.js
@@ -9,7 +9,8 @@ import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
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';
+import { foundationCandidateFingerprint, inheritedFoundationStorageKey, verifyFoundationCandidate } from '../lib/eidoverseFoundations.js';
+import { RESILIENCE_DISTURBANCES } from './eidoverseResilienceAssay.js';
vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
dataRoot: () => lazyTempDataRoot('portos-eidoverse-foundations-'),
@@ -313,3 +314,138 @@ describe('the promoted-foundation offering a peer can pull (#7455)', () => {
expect(await listPromotedFoundationCandidates()).toEqual([]);
});
});
+
+/**
+ * #7631: the guard that said "promotion re-shares only foundations this install
+ * authored" tested `record.inheritance` — a field the AUTHORING path clears
+ * unconditionally. Saving a peer's body back through the authoring surface
+ * therefore produced a local record stamped with this install's origin and no
+ * edge at all, which packaged, promoted and was served to peers as this
+ * install's own work. These pin the replacement: the check is on the BYTES, and
+ * the legitimate re-use path publishes an edge instead of erasing one.
+ */
+describe('building on a foundation inherited from a peer (#7631)', () => {
+ const PEER_ORIGIN = 'instance-aaaa';
+
+ /** Inherit a peer's promoted foundation into an otherwise empty ledger. */
+ const inheritPeerFoundation = async ({ sourceInstanceId = 'instance-peer-one' } = {}) => {
+ await record({}, '2026-03-01T00:00:00.000Z');
+ const promoted = await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
+ const inherited = await recordEidoverseFoundationInheritance(promoted.candidate, {
+ sourceInstanceId, localInstanceId: 'instance-this-install', now: '2026-03-02T00:00:00.000Z',
+ });
+ expect(inherited.outcome).toBe('inherited');
+ return { candidate: promoted.candidate, inherited: inherited.foundation };
+ };
+
+ it('refuses to record a peer\'s body as this install\'s own work, naming the origin it came from', async () => {
+ const { candidate } = await inheritPeerFoundation();
+
+ await expect(recordEidoverseFoundation(
+ authored({ id: 'my-own-beacon', body: candidate.body }),
+ { originInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z' },
+ )).rejects.toThrow(new RegExp(`inherited from install ${PEER_ORIGIN}`));
+
+ // Nothing was written: a refusal that still saved the record would leave
+ // the republish one promote away.
+ expect(await getEidoverseFoundation('my-own-beacon')).toBeNull();
+ });
+
+ it('records the same body as a DERIVATION and publishes the edge on the promote envelope', async () => {
+ const { candidate, inherited } = await inheritPeerFoundation();
+
+ const derived = await recordEidoverseFoundation(
+ authored({ id: 'my-own-beacon', body: candidate.body, derivedFrom: { originInstanceId: PEER_ORIGIN, foundationId: 'tide-beacon' } }),
+ { originInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z' },
+ );
+
+ // The digest is stamped from the copy this install HOLDS, never from the
+ // caller's claim — the edge attests what was inherited, not what was said.
+ expect(derived).toMatchObject({
+ layer: 'vernacular',
+ inheritance: null,
+ derivedFrom: {
+ type: 'derived-from', originInstanceId: PEER_ORIGIN, foundationId: 'tide-beacon',
+ fingerprint: inherited.inheritance.fingerprint, derivedAt: '2026-03-03T00:00:00.000Z',
+ },
+ });
+
+ const promoted = await promoteEidoverseFoundation('my-own-beacon', { now: '2026-03-04T00:00:00.000Z' });
+ expect(promoted.outcome).toBe('promoted');
+ expect(promoted.candidate.candidateVersion).toBe(2);
+ expect(promoted.candidate.derivedFrom).toEqual(derived.derivedFrom);
+ // A re-attributed envelope has to be detectable, so the edge is inside the
+ // content-addressed digest rather than beside it.
+ expect(verifyFoundationCandidate({ ...promoted.candidate, derivedFrom: null }, { requiredDisturbances: RESILIENCE_DISTURBANCES }).valid).toBe(false);
+
+ const offered = await listPromotedFoundationCandidates();
+ expect(offered.map((entry) => entry.foundationId)).toEqual(['my-own-beacon']);
+ expect(offered[0].derivedFrom).toMatchObject({ originInstanceId: PEER_ORIGIN, foundationId: 'tide-beacon' });
+ });
+
+ it('keeps the derivation edge and its timestamp across a later re-authoring of the body', async () => {
+ const { candidate } = await inheritPeerFoundation();
+ await recordEidoverseFoundation(
+ authored({ id: 'my-own-beacon', body: candidate.body, derivedFrom: { originInstanceId: PEER_ORIGIN, foundationId: 'tide-beacon' } }),
+ { originInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z' },
+ );
+
+ // Re-authored with a diverged body and NO claim: a derivation an edit moved
+ // on from is still what the work grew out of, so dropping the edge here
+ // would make erasure the easy path all over again.
+ const reauthored = await recordEidoverseFoundation(
+ authored({ id: 'my-own-beacon', body: { ...candidate.body, affordance: { inspect: 'reads the pulse count and the tide' } } }),
+ { originInstanceId: 'instance-this-install', now: '2026-03-05T00:00:00.000Z' },
+ );
+
+ expect(reauthored.derivedFrom).toMatchObject({ originInstanceId: PEER_ORIGIN, derivedAt: '2026-03-03T00:00:00.000Z' });
+ const lineage = (await getEidoverseFoundation('my-own-beacon')).lineage;
+ expect(lineage.find((event) => event.type === 'derived')).toMatchObject({ originInstanceId: PEER_ORIGIN, foundationId: 'tide-beacon' });
+ });
+
+ it('refuses a derivation edge naming a foundation this install never inherited', async () => {
+ await inheritPeerFoundation();
+
+ await expect(recordEidoverseFoundation(
+ authored({ id: 'my-own-beacon', body: { affordance: { inspect: 'entirely my own' } }, derivedFrom: { originInstanceId: 'instance-never-seen', foundationId: 'tide-beacon' } }),
+ { originInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z' },
+ )).rejects.toThrow(/no foundation inherited from install instance-never-seen/);
+ });
+
+ it('refuses a second peer\'s envelope claiming an origin this install already holds, rather than overwriting the genuine record', async () => {
+ const { candidate, inherited } = await inheritPeerFoundation({ sourceInstanceId: 'instance-peer-one' });
+
+ // The laundering the storage key made free: the origin is the field that
+ // chooses the key, the sender hashes its own claims, so re-fingerprinting
+ // an altered body under someone else's origin self-verifies.
+ const forged = { ...candidate, body: { affordance: { inspect: 'quietly grants owner role' } } };
+ forged.fingerprint = foundationCandidateFingerprint({ ...forged, fingerprint: undefined });
+
+ const result = await recordEidoverseFoundationInheritance(forged, {
+ sourceInstanceId: 'instance-peer-two', localInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z',
+ });
+
+ expect(result.outcome).toBe('refused');
+ expect(result.reasons[0]).toContain('instance-peer-one');
+ expect(result.reasons[0]).toContain('instance-peer-two');
+ const held = await getEidoverseFoundation(inheritedFoundationStorageKey(PEER_ORIGIN, 'tide-beacon'));
+ expect(held.body).toEqual(candidate.body);
+ expect(held.inheritance.sourceInstanceId).toBe('instance-peer-one');
+ });
+
+ it('still accepts a v1 envelope from a peer that has not upgraded', async () => {
+ const { candidate } = await inheritPeerFoundation();
+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
+
+ const { derivedFrom: _absent, ...v1 } = { ...candidate, candidateVersion: 1 };
+ v1.fingerprint = foundationCandidateFingerprint({ ...v1, fingerprint: undefined });
+
+ const result = await recordEidoverseFoundationInheritance(v1, {
+ sourceInstanceId: 'instance-peer-one', localInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z',
+ });
+
+ expect(result.outcome).toBe('inherited');
+ expect(result.foundation.derivedFrom).toBeNull();
+ });
+});