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

let a promoted Eidoverse foundation be withdrawn, and propagate the retraction to peers (#7632)

[._.]/ Adam Eivy051f8723f6c0
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
index 9f66b14206..5703d6f1d4 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
@@ -7,6 +7,7 @@ import {
packageEidoverseFoundationCandidate,
promoteEidoverseFoundation,
recordEidoverseFoundation,
+ withdrawEidoverseFoundation,
} from '../../services/api';
import { formatDateShort, timeAgo } from '../../utils/formatters';
@@ -149,6 +150,8 @@ function LayerBadge({ layer }) {
const VERDICT_HEADLINES = Object.freeze({
promoted: 'Promoted to the shared baseline.',
packaged: 'Every gate passed — promote candidate packaged.',
+ withdrawn: 'Withdrawn — peers that inherited this drop their copy on the next sync.',
+ 'not-promoted': 'Nothing to retract — this was never promoted.',
});
function Verdict({ verdict }) {
@@ -406,6 +409,21 @@ export default function EidoverseFoundationsPanel() {
>
Promote
</button>
+ {/* Withdrawal (#7632) — the direction promotion never
+ had. Only a promoted record can be retracted, so the
+ button appears with the `baseline` layer rather than
+ sitting disabled beside every local draft. */}
+ {foundation.layer === 'baseline' && (
+ <button
+ type="button"
+ className={secondaryButton}
+ disabled={busyId === foundation.id}
+ title="Retract this from the shared baseline — peers that inherited it drop their copy on the next sweep"
+ onClick={() => runGate(foundation.id, withdrawEidoverseFoundation)}
+ >
+ Withdraw
+ </button>
+ )}
</>
)}
<button type="button" className={secondaryButton} onClick={() => openFoundation(expanded ? '' : foundation.id)}>
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
index b36dd4967f..fea3db0b03 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
@@ -15,6 +15,7 @@ vi.mock('../../services/api', () => ({
recordEidoverseFoundation: vi.fn(),
packageEidoverseFoundationCandidate: vi.fn(),
promoteEidoverseFoundation: vi.fn(),
+ withdrawEidoverseFoundation: vi.fn(),
}));
import {
@@ -22,6 +23,7 @@ import {
listEidoverseFoundations,
promoteEidoverseFoundation,
recordEidoverseFoundation,
+ withdrawEidoverseFoundation,
} from '../../services/api';
import EidoverseFoundationsPanel from './EidoverseFoundationsPanel';
@@ -107,6 +109,34 @@ describe('the Eidoverse foundations promote panel', () => {
expect(screen.getByRole('button', { name: 'Promote' })).toBeDisabled();
});
+ // #7632 — the panel is where an author actually retracts, so a Withdraw
+ // reachable only by curl would leave the feature unusable.
+ it('offers Withdraw only once a foundation is promoted, and reports the retraction as a pass', async () => {
+ const promoted = foundation({ layer: 'baseline', promotedAt: '2026-03-04T06:00:00.000Z' });
+ listEidoverseFoundations
+ .mockResolvedValueOnce(listing([promoted], { vernacular: 0, baseline: 1, candidates: 1 }))
+ .mockResolvedValue(listing([foundation()]));
+ getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ withdrawEidoverseFoundation.mockResolvedValue({ outcome: 'withdrawn', foundation: foundation(), reasons: [] });
+ await renderPanel();
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Withdraw' })); });
+
+ // A withdrawal answers 200 like every other gate, so without its own
+ // headline a success would render as "Refused — nothing moved."
+ expect(screen.getByRole('status')).toHaveTextContent(/Withdrawn/);
+ expect(withdrawEidoverseFoundation).toHaveBeenCalledWith('tide-beacon', expect.anything());
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Withdraw' })).toBeNull());
+ });
+
+ it('never offers Withdraw for an inherited copy — this install never published it', async () => {
+ listEidoverseFoundations.mockResolvedValue(listing([inheritedFoundation()], { vernacular: 0, baseline: 1, candidates: 0, inherited: 1 }));
+ getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ await renderPanel();
+
+ expect(screen.queryByRole('button', { name: 'Withdraw' })).toBeNull();
+ });
+
it('refuses to submit an unparseable body instead of sending it to the promote gate', async () => {
listEidoverseFoundations.mockResolvedValue(listing([]));
getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 9aa68d4c93..343e61b496 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -134,6 +134,13 @@ export const promoteEidoverseFoundation = (id, options = {}) => request(`/eidove
method: 'POST',
...options,
});
+// Withdrawal (#7632) — retract a promoted foundation so peers that inherited it
+// DROP their copy. Like promote, a refusal ("this is an inherited copy", "it was
+// never promoted") is a 200 carrying `outcome` + `reasons`.
+export const withdrawEidoverseFoundation = (id, options = {}) => request(`/eidoverse/world/foundations/${encodeURIComponent(id)}/withdraw`, {
+ method: 'POST',
+ ...options,
+});
// Eidoverse world controllers — the install/arm/retire surface beside the
// `eidoverse.controllers` mind-tool group (#7456, #7488). An install/arm
diff --git a/docs/API.md b/docs/API.md
index 055409f772..511a3a6356 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -365,6 +365,8 @@ federate world records.
| 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 |
+| POST | `/eidoverse/world/foundations/:id/withdraw` | Retract a promoted foundation: de-promotes it and tombstones the published fingerprint so peers that inherited it drop their copy on the next sweep; a refusal returns 200 with its reasons |
+| DELETE | `/eidoverse/world/foundations/:id` | Delete a record — `?originInstanceId=` addresses an inherited copy, a bare id this install's own work. A promoted local record is withdrawn first, so no peer's copy is orphaned |
| GET | `/eidoverse/world/contributions` | The resilience-assay contribution ids a foundation may bind itself to |
### Legacy OpenWorld / CyberCity
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index e3be619399..821df723d2 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -772,6 +772,33 @@ Re-authoring a promoted foundation returns it to `vernacular` and clears
keeping the stamp would also be a dead end, since the gate refuses to package a
`baseline` foundation.
+**Withdrawing retracts a publication, and it reaches the peers that pulled it
+(#7632).** `POST /api/eidoverse/world/foundations/:id/withdraw` de-promotes the
+record — `vernacular`, `promotedAt` and `candidate` cleared, the body kept — and
+records a **tombstone** for the fingerprint it had published. That tombstone
+rides the peer offering, and a receiving install *deletes* its inherited copy
+rather than merely ceasing to re-pull it. Re-authoring a promoted foundation
+tombstones the replaced envelope for the same reason: it retracts a published
+body, and before this it did so silently. Promotion used to be one-way, so a
+foundation carrying something its author regretted — a personal detail the
+regex-shaped federation-safety scan cannot recognize, a wrong attribution, a
+body that turned out to be harmful — stayed on every install that had pulled it,
+for good.
+
+`DELETE /api/eidoverse/world/foundations/:id` removes a record outright, and
+**withdraws it first if it was promoted** — so the most natural gesture an
+author makes cannot orphan a peer's copy beyond recall. `?originInstanceId=`
+addresses an INHERITED copy; a bare id always means this install's own work,
+because the two id spaces legitimately overlap.
+
+**What withdrawal does not promise.** A peer running a PortOS older than the
+`tombstones` wrapper key (schema v3) gently skips the whole offering and keeps
+its copy, saying so in its log. That is unavoidable by construction — retraction
+is best-effort across versions, never a guarantee — and it is the right failure
+mode: the old peer degrades to the previous add-only behavior instead of acting
+on a wrapper it cannot fully read. Deleting a record whose tombstone has already
+aged out of the capped list is likewise final.
+
**Where the user does this.** Eidoverse > World controls > **Foundations**
(`client/src/components/eidoverse/EidoverseFoundationsPanel.jsx`) lists every
foundation with its ownership-layer badge, records or re-authors one, runs the
@@ -849,8 +876,8 @@ which it accepts is `recordEidoverseFoundationInheritance()`. It owns the
payload wrapper, the version gate, the caps and the sweep.
**Outbound.** `GET /api/peer-sync/eidoverse-foundations` advertises
-`{ schemaVersion, listHash, candidates: [...] }`. The offering is exactly the
-foundations this install PROMOTED and AUTHORED:
+`{ schemaVersion, listHash, candidates: [...], tombstones: [...] }`. The
+`candidates` are exactly the foundations this install PROMOTED and AUTHORED:
- `layer === 'baseline'` — a merely *packaged* candidate is a dry run ("would
this pass?"), not a publication, and is never served.
@@ -862,6 +889,18 @@ foundations this install PROMOTED and AUTHORED:
`foundations.json` is a file a human can edit, and refuse-never-redact
applies outbound as well as inbound, so a candidate that no longer passes is
withheld from the offering and logged.
+- the fingerprint must not be tombstoned. Promoting clears a fingerprint's
+ tombstone, so the two lists cannot normally disagree; a hand-edited ledger can
+ make them, and an offering that both published and retracted one fingerprint
+ would resolve differently on every receiver. The retraction wins.
+
+`tombstones` is `[{ fingerprint, deletedAt }]` — a content-addressed name and an
+instant, never any of the body. It caps on its **own** budget, never against
+`OFFERING_ENTRY_CAP`: sharing one cap would let a large promoted population
+silently truncate the retractions, which is the one trade this must never make.
+Both lists feed the `listHash`, so a withdrawal with no other change still
+breaks a receiver's unchanged short-circuit instead of waiting for the next
+forced re-pull.
Unlike the older peer-pull routes, this one does not ride the warn-first
authorization ramp: it passes `alwaysEnforce`, so only a registered,
@@ -882,16 +921,33 @@ fingerprint this install already holds is skipped, so the periodic forced
re-pull (there so a local deletion self-heals) never rewrites `inheritedAt`
on an unchanged copy.
+The sweep applies the peer's **retractions first**, before it reads what this
+install holds: a fingerprint the same offering re-publishes is then re-verified
+through the whole accept-side gate on its way back in, rather than surviving in
+place unchecked. A retraction authorizes dropping only a record this install
+pulled from *that same peer* (`inheritance.sourceInstanceId`) — a fingerprint is
+public inside the federation the moment it is offered, so it identifies a record
+but authorizes nothing, and without the scope any registered peer could retract
+a third install's work by naming it. A tombstone for a fingerprint this install
+does not hold is a silent no-op. Peer tombstones are not persisted: this install
+never re-offers an inherited record, and the sender keeps advertising the
+tombstone while its candidate stays absent, so storing them would only let a
+peer crowd out this install's own retractions.
+
Both directions are gated on the `eidoverse` instance feature: an install with
Eidoverse turned off neither offers nor accumulates.
-**Compatibility.** `PORTOS_SCHEMA_VERSIONS.eidoverseFoundations` (v1) is the
+**Compatibility.** `PORTOS_SCHEMA_VERSIONS.eidoverseFoundations` (v3) is the
transport contract, registered in `NON_RECORD_SCHEMA_CATEGORIES` because this
is a receiver-pull category with no push to gate — a foundation is not a
peer-subscribable record kind. It is deliberately separate from the envelope's
own `candidateVersion`, which pins one envelope's shape and is hashed into its
fingerprint: a change to the envelope bumps both, a change to the wrapper or
-the caps bumps only the category.
+the caps bumps only the category. v3 (#7632) added `tombstones` to the wrapper
+and moved only the category, because a tombstone names a candidate by the
+fingerprint it already had and no envelope field changed. A v2 sender omits the
+key and a v3 receiver reads that as "nothing to retract"; a v2 **receiver**
+gently skips a v3 offering and therefore keeps a copy it should have dropped.
### Creative toolkit for minds (#7459, wired end-to-end in #7627)
diff --git a/server/lib/eidoverseFoundations.js b/server/lib/eidoverseFoundations.js
index bae1869207..1c12642bc5 100644
--- a/server/lib/eidoverseFoundations.js
+++ b/server/lib/eidoverseFoundations.js
@@ -314,6 +314,22 @@ export const eidoverseFoundationRecordSchema = z.object({
export const eidoverseFoundationIdParamSchema = z.object({ id: foundationIdSchema }).strict();
+/**
+ * Addressing ANY record in the ledger, local or inherited (#7632).
+ *
+ * A bare id reaches only locally-authored work, because a local vernacular
+ * foundation and an inherited copy can legitimately share the same
+ * human-readable id — which is exactly why the inherited one lives under
+ * `inheritedFoundationStorageKey()`'s disjoint namespace. Naming the origin
+ * disambiguates them. The caller supplies `{ id, originInstanceId }` rather
+ * than the raw `peer:<origin>:<id>` key so the storage grammar stays inside
+ * the ledger module, where the one function that mints it lives.
+ */
+export const eidoverseFoundationTargetSchema = z.object({
+ id: foundationIdSchema,
+ originInstanceId: instanceIdSchema.nullable().optional().default(null),
+}).strict();
+
/** What a caller (route, mind tool, test) may author. Layer is NOT accepted:
* a new local artifact is `vernacular` by construction, and moving to
* `baseline` is what the promote path is for. */
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index c4c7d349e0..54f9a3725b 100644
--- a/server/lib/peerSyncValidation.js
+++ b/server/lib/peerSyncValidation.js
@@ -438,6 +438,16 @@ export const peerEidoverseFoundationsSchema = z.object({
// byte cap the receiver enforces on the response. Far beyond any realistic
// promoted population — the sender logs and truncates at the same number.
candidates: z.array(z.record(z.string().min(1).max(64), z.unknown())).max(500),
+ // Withdrawals (#7632). Unlike `candidates` this IS declared in full, because
+ // there is no second gate downstream: a tombstone is two scalars the receiver
+ // acts on directly by DELETING a held record, so the shape has to be pinned
+ // where it arrives. `.default([])` keeps a pre-#7632 sender — which omits the
+ // key entirely — parsing as "nothing to retract" rather than failing the
+ // whole wrapper and stalling its candidates too.
+ tombstones: z.array(z.object({
+ fingerprint: hex64,
+ deletedAt: z.string().datetime(),
+ }).strict()).max(500).default([]),
}).strict();
export const peerPullMetadataSchema = z.object({
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 6c98c6b02f..4edb3da115 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -718,7 +718,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// 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,
+ //
+ // v3 (#7632): the WRAPPER gained `tombstones` — withdrawal, so a promoted
+ // foundation can be recalled from the installs that pulled it. `candidateVersion`
+ // does NOT move with it: a tombstone names a candidate by the fingerprint it
+ // already had, and no envelope field changed. A v2 sender simply omits the
+ // key and a v3 receiver reads that as "nothing to retract"; a v2 RECEIVER
+ // gently skips a v3 offering and therefore keeps a copy it should have
+ // dropped — the degradation is deliberate and documented in
+ // `docs/features/eidoverse.md`, because the alternative (a receiver acting on
+ // a wrapper it cannot fully read) is worse, and a retraction that reaches
+ // nobody is still better than one that corrupts.
+ eidoverseFoundations: 3,
// 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/routes/eidoverseWorldRoutes.js b/server/routes/eidoverseWorldRoutes.js
index 2814b348d5..4147ae46a4 100644
--- a/server/routes/eidoverseWorldRoutes.js
+++ b/server/routes/eidoverseWorldRoutes.js
@@ -14,18 +14,24 @@ import {
eidoverseWorldSaySchema,
validateRequest,
} from '../lib/validation.js';
-import { eidoverseFoundationIdParamSchema, eidoverseFoundationInputSchema } from '../lib/eidoverseFoundations.js';
+import {
+ eidoverseFoundationIdParamSchema,
+ eidoverseFoundationInputSchema,
+ eidoverseFoundationTargetSchema,
+} from '../lib/eidoverseFoundations.js';
import {
eidoverseControllerArmSchema,
eidoverseControllerIdParamSchema,
eidoverseControllerInstallSchema,
} from '../lib/eidoverseControllers.js';
import {
+ deleteEidoverseFoundation,
getEidoverseFoundation,
listEidoverseFoundations,
packageEidoverseFoundationCandidate,
promoteEidoverseFoundation,
recordEidoverseFoundation,
+ withdrawEidoverseFoundation,
} from '../services/eidoverseFoundationLedger.js';
import { listRegisteredContributionIds } from '../services/eidoverseResilienceContributions.js';
import { describeControllerDefinitions } from '../services/eidoverseControllerRegistry.js';
@@ -148,6 +154,36 @@ router.post('/foundations/:id/promote', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/eidoverse/world/foundations/:id/withdraw — retract a promoted
+// foundation from the shared population (#7632). The record drops back to
+// `vernacular` and its published fingerprint is tombstoned, so peers that
+// already inherited it DROP their copy on the next sweep rather than merely
+// ceasing to re-pull it. The body is kept; deleting the local work is the
+// separate DELETE below. Like the promote gate, a refusal ("this is an
+// inherited copy", "it was never promoted") is a 200 carrying its reasons.
+router.post('/foundations/:id/withdraw', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(eidoverseFoundationIdParamSchema, req.params || {});
+ const result = await withdrawEidoverseFoundation(id);
+ if (result.outcome === 'unknown-foundation') throw new ServerError('Foundation not found', { status: 404 });
+ res.json(result);
+}));
+
+// DELETE /api/eidoverse/world/foundations/:id — delete a record from this
+// install's ledger. `?originInstanceId=` addresses an INHERITED copy, which a
+// bare id cannot reach (it shares its id space with local work, on purpose);
+// without it the id means this install's own foundation. Deleting a promoted
+// local record WITHDRAWS it first, so the most natural gesture an author makes
+// ("remove this") can never orphan a peer's copy beyond recall.
+router.delete('/foundations/:id', asyncHandler(async (req, res) => {
+ const { id, originInstanceId } = validateRequest(eidoverseFoundationTargetSchema, {
+ id: req.params.id,
+ ...(req.query?.originInstanceId === undefined ? {} : { originInstanceId: req.query.originInstanceId }),
+ });
+ const result = await deleteEidoverseFoundation(id, { originInstanceId });
+ if (result.outcome === 'unknown-foundation') throw new ServerError('Foundation not found', { status: 404 });
+ res.json({ success: true, ...result });
+}));
+
// GET /api/eidoverse/world/foundations/:id — one foundation record, looked
// up by its plain (locally-authored) id. An inherited local copy of a peer's
// foundation lives under a separate `peer:<originInstanceId>:<foundationId>`
diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.js
index 9bd7e2dba3..7c00f46869 100644
--- a/server/routes/eidoverseWorldRoutes.test.js
+++ b/server/routes/eidoverseWorldRoutes.test.js
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
listContributions: vi.fn(),
recordFoundation: vi.fn(),
getFoundation: vi.fn(),
+ withdrawFoundation: vi.fn(),
+ deleteFoundation: vi.fn(),
ensurePresence: vi.fn(),
getProjectionStatus: vi.fn(),
getStatus: vi.fn(),
@@ -40,6 +42,8 @@ vi.mock('../services/eidoverseFoundationLedger.js', () => ({
packageEidoverseFoundationCandidate: mocks.packageCandidate,
promoteEidoverseFoundation: mocks.promoteFoundation,
recordEidoverseFoundation: mocks.recordFoundation,
+ withdrawEidoverseFoundation: mocks.withdrawFoundation,
+ deleteEidoverseFoundation: mocks.deleteFoundation,
}));
vi.mock('../services/eidoverseResilienceContributions.js', () => ({
@@ -251,6 +255,46 @@ it('reports a promote refusal as a verdict and never moves the layer itself', as
expect(mocks.promoteFoundation).toHaveBeenCalledWith('tide-beacon');
});
+ // #7632 — withdrawal and deletion, the directions promotion never had.
+ it('reports a withdrawal as a verdict and delegates the decision whole', async () => {
+ mocks.withdrawFoundation.mockResolvedValue({
+ outcome: 'withdrawn', foundation: { id: 'tide-beacon', layer: 'vernacular', promotedAt: null }, reasons: [],
+ });
+
+ const response = await request(makeApp()).post('/api/eidoverse/world/foundations/tide-beacon/withdraw');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ outcome: 'withdrawn', foundation: { layer: 'vernacular' } });
+ expect(mocks.withdrawFoundation).toHaveBeenCalledWith('tide-beacon');
+ });
+
+ it('reports a refused withdrawal as a 200 verdict, and an unknown id as a 404', async () => {
+ mocks.withdrawFoundation.mockResolvedValueOnce({ outcome: 'refused', foundation: null, reasons: ['inherited copy'] });
+ expect((await request(makeApp()).post('/api/eidoverse/world/foundations/tide-beacon/withdraw')).status).toBe(200);
+
+ mocks.withdrawFoundation.mockResolvedValueOnce({ outcome: 'unknown-foundation', foundation: null, reasons: ['no foundation'] });
+ expect((await request(makeApp()).post('/api/eidoverse/world/foundations/tide-beacon/withdraw')).status).toBe(404);
+ });
+
+ it('deletes a local record by bare id and an inherited copy by its origin', async () => {
+ mocks.deleteFoundation.mockResolvedValue({ outcome: 'deleted', foundation: { id: 'tide-beacon' }, withdrawn: true });
+
+ expect((await request(makeApp()).delete('/api/eidoverse/world/foundations/tide-beacon')).status).toBe(200);
+ // A bare id means LOCAL work; the inherited copy needs its origin named,
+ // because the two id spaces legitimately overlap.
+ expect(mocks.deleteFoundation).toHaveBeenLastCalledWith('tide-beacon', { originInstanceId: null });
+
+ await request(makeApp()).delete('/api/eidoverse/world/foundations/tide-beacon?originInstanceId=instance-aaaa');
+ expect(mocks.deleteFoundation).toHaveBeenLastCalledWith('tide-beacon', { originInstanceId: 'instance-aaaa' });
+ });
+
+ it('rejects a malformed origin before it can be assembled into a storage key', async () => {
+ const res = await request(makeApp()).delete('/api/eidoverse/world/foundations/tide-beacon?originInstanceId=not%20an%20id');
+
+ expect(res.status).toBe(400);
+ expect(mocks.deleteFoundation).not.toHaveBeenCalled();
+ });
+
it('serves the registered assay contributions on their own path, where no foundation id can shadow them', async () => {
mocks.listContributions.mockResolvedValue(['beacon-relay-demo']);
mocks.getFoundation.mockResolvedValue(null);
diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.js
index 372d1cf291..3753daeabc 100644
--- a/server/services/eidoverseFoundationLedger.js
+++ b/server/services/eidoverseFoundationLedger.js
@@ -39,6 +39,18 @@
* (`services/sharing/peerEidoverseFoundationSync.js`). There is no `data.reference/` seed — an absent file is
* an empty ledger, which is the correct state for every install that has never
* authored or inherited a foundation, so no migration is owed.
+ *
+ * **Withdrawal is a first-class act, and it propagates (#7632).** Promotion used
+ * to be one-way: a peer that pulled a foundation kept that copy forever, because
+ * the offering only ever ADDED and the sweep converged upward toward the
+ * sender's list. Re-authoring already de-promoted a record locally, which
+ * silently dropped it from the offering and left every receiver holding a
+ * `baseline` copy of bytes the author had retracted. `withdrawEidoverseFoundation()`
+ * below makes that retraction explicit and records a TOMBSTONE — keyed on the
+ * candidate's content-addressed fingerprint, the one identifier that means the
+ * same thing on every install — which rides the offering beside the candidates
+ * so a receiver DROPS the copy instead of merely ceasing to re-pull it.
+ * `applyEidoverseFoundationTombstones()` is that receiving half.
*/
import { join } from 'node:path';
@@ -58,12 +70,49 @@ import {
} from '../lib/eidoverseFoundations.js';
import { ServerError } from '../lib/errorHandler.js';
import { generateDistrictTemplatePlacement } from '../lib/eidoverseCreativeToolkit.js';
+import {
+ clearTombstone,
+ normalizeTombstones,
+ recordTombstone,
+ tombstoneTimestamp,
+} from '../lib/tombstones.js';
import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';
import { findContributionById } from './eidoverseResilienceContributions.js';
-/** Storage-layout version stamped on `data/eidoverse/foundations.json`. */
+/**
+ * Storage-layout version stamped on `data/eidoverse/foundations.json`.
+ *
+ * Still 1 with the `tombstones` list added (#7632): the key is ADDITIVE and
+ * compatible in both directions — a PortOS that predates it ignores the key,
+ * and this one reads a file without it as an empty tombstone list, which is
+ * exactly right for an install that has never withdrawn anything. Bumping
+ * would advertise an incompatibility that does not exist. The one asymmetry
+ * worth naming: an older PortOS that WRITES this file back drops the
+ * tombstones, so a downgrade-then-upgrade loses pending retractions that had
+ * not yet reached a peer. That is a lost withdrawal, not a corrupted ledger,
+ * and re-withdrawing the record records it again.
+ */
const LEDGER_SCHEMA_VERSION = 1;
+/**
+ * Tombstones are keyed on the promote candidate's `fingerprint`, NOT on the
+ * foundation id. The id is local and two installs can legitimately carry the
+ * same one; the fingerprint is a sha256 over the canonicalized envelope, so it
+ * names one specific published body and means the same thing everywhere. It is
+ * also exactly what the receiver already stores on its inherited copy
+ * (`inheritance.fingerprint`), so a match needs no extra index.
+ */
+const TOMBSTONE_KEY_FIELD = 'fingerprint';
+
+/**
+ * Capped independently of `OFFERING_ENTRY_CAP` in the transport, and far above
+ * any realistic withdrawal history. A retraction must never be displaced to
+ * make room for a publication — the whole point is that it outranks one.
+ */
+const TOMBSTONE_LIMIT = 200;
+
+const tombstoneOptions = { keyField: TOMBSTONE_KEY_FIELD, limit: TOMBSTONE_LIMIT };
+
// Read through `PATHS` per call, NOT `dataPath()`: a suite redirects the data
// root by proxying this module's `fileUtils` import, and `dataPath()` resolves
// against `paths.js`'s own `PATHS` binding, which that proxy never sees — so
@@ -79,13 +128,33 @@ const withLedgerLock = createMutex();
* user's ledger with an empty one. `strict: true` throws on unreadable bytes,
* while a genuinely ABSENT file still reads as the empty ledger it is.
*/
-async function readFoundations() {
+async function readLedger() {
const raw = await readJSONFile(ledgerFile(), null, { allowArray: false, strict: true });
- return raw && typeof raw === 'object' && raw.foundations && typeof raw.foundations === 'object' ? { ...raw.foundations } : {};
+ const stored = raw && typeof raw === 'object' ? raw : {};
+ return {
+ foundations: stored.foundations && typeof stored.foundations === 'object' ? { ...stored.foundations } : {},
+ // Normalized on READ as well as write: this list is the one part of the
+ // ledger a peer's offering also writes, and `foundations.json` is a file a
+ // human can edit. An entry without a usable key or stamp could never win a
+ // comparison anyway, so dropping it here keeps every downstream reader from
+ // having to re-check the shape.
+ tombstones: normalizeTombstones(stored.tombstones, TOMBSTONE_KEY_FIELD),
+ };
}
-async function writeFoundations(foundations) {
- await atomicWrite(ledgerFile(), { schemaVersion: LEDGER_SCHEMA_VERSION, foundations });
+/** The foundations map alone, for the read-only paths that never write back. */
+const readFoundations = async () => (await readLedger()).foundations;
+
+// Both halves always written together: a `writeFoundations(foundations)` that
+// defaulted the tombstones would erase every pending retraction on the next
+// ordinary authoring write, which is precisely the silent-loss shape #7632
+// exists to close.
+async function writeLedger({ foundations, tombstones }) {
+ await atomicWrite(ledgerFile(), {
+ schemaVersion: LEDGER_SCHEMA_VERSION,
+ foundations,
+ tombstones: normalizeTombstones(tombstones, TOMBSTONE_KEY_FIELD),
+ });
}
/**
@@ -140,10 +209,21 @@ export async function listEidoverseFoundations() {
* `style` layer that is not authorized to leave this install.
*/
export async function listPromotedFoundationCandidates() {
- const offerable = Object.values(await readFoundations())
+ const { foundations, tombstones } = await readLedger();
+ const offerable = Object.values(foundations)
.filter((entry) => entry?.layer === 'baseline' && !entry.inheritance && entry.candidate);
const candidates = [];
for (const entry of offerable) {
+ // A fourth filter (#7632), and a backstop rather than a live path: promoting
+ // clears the fingerprint's tombstone, so the two lists cannot normally
+ // disagree. A hand-edited ledger can make them disagree, and an offering
+ // that both published and retracted one fingerprint would resolve
+ // differently on every receiver depending on which list it applied first.
+ // The retraction wins, because refuse-never-redact runs outbound too.
+ if (tombstoneTimestamp(tombstones, entry.candidate.fingerprint, TOMBSTONE_KEY_FIELD) !== null) {
+ console.warn(`⚠️ Eidoverse foundation "${entry.id}" is promoted but its candidate is withdrawn — withholding it from the peer offering`);
+ continue;
+ }
const verified = verifyFoundationCandidate(entry.candidate, { requiredDisturbances: RESILIENCE_DISTURBANCES });
if (!verified.valid) {
console.warn(`⚠️ Eidoverse foundation "${entry.id}" is promoted but its stored candidate no longer passes the promote gate — withholding it from the peer offering (${verified.reasons.length} reason(s))`);
@@ -207,7 +287,7 @@ function deriveDistrictTemplateBody(authored) {
export async function recordEidoverseFoundation(input, { originInstanceId, now = new Date().toISOString() } = {}) {
const authored = eidoverseFoundationInputSchema.parse(input);
return withLedgerLock(async () => {
- const foundations = await readFoundations();
+ const { foundations, tombstones } = await readLedger();
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
@@ -255,11 +335,32 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
updatedAt: now,
};
foundations[authored.id] = record;
- await writeFoundations(foundations);
+ // Re-authoring a PROMOTED foundation is a retraction of the published body,
+ // and it is the one the issue that prompted #7632 opens with: the record
+ // silently dropped back to `vernacular`, left the offering, and every peer
+ // that had pulled it kept a `baseline` copy of bytes this install no longer
+ // has. The candidate being replaced is what those peers hold, so tombstone
+ // its fingerprint — the new body publishes under a new one when (and if)
+ // somebody promotes it.
+ await writeLedger({ foundations, tombstones: tombstoneForReplacedCandidate(tombstones, existing, now) });
return record;
});
}
+/**
+ * Tombstone the candidate a write is about to replace, but ONLY when that
+ * candidate was actually published. A merely PACKAGED candidate on a
+ * `vernacular` record never left the install — `listPromotedFoundationCandidates()`
+ * refuses to serve one — so tombstoning it would broadcast a retraction for a
+ * fingerprint no peer could ever hold, burning a tombstone slot for nothing.
+ */
+const wasPublished = (entry) => entry?.layer === 'baseline' && !entry.inheritance && typeof entry.candidate?.fingerprint === 'string';
+
+function tombstoneForReplacedCandidate(tombstones, existing, now) {
+ if (!wasPublished(existing)) return tombstones;
+ return recordTombstone(tombstones, existing.candidate.fingerprint, { ...tombstoneOptions, deletedAt: now });
+}
+
const verdict = (outcome, reasons) => ({ outcome, candidate: null, assay: null, reasons, findings: [] });
const unknownFoundation = (id) => verdict('unknown-foundation', [`no foundation is recorded under "${id}"`]);
@@ -303,7 +404,7 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
const portosVersion = await getPortosVersion();
return withLedgerLock(async () => {
- const foundations = await readFoundations();
+ const { foundations, tombstones } = await readLedger();
const current = foundations[id];
if (!current) return unknownFoundation(id);
if (current.updatedAt !== existing.updatedAt) {
@@ -322,7 +423,7 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
// previously packaged candidate — the verdict that vouched for it no
// longer holds, even though the bytes are unchanged.
foundations[id] = { ...current, assay, candidate: result.candidate };
- await writeFoundations(foundations);
+ await writeLedger({ foundations, tombstones });
return { ...result, assay };
});
}
@@ -350,7 +451,7 @@ export async function promoteEidoverseFoundation(id, { now = new Date().toISOStr
if (packaged.outcome !== 'packaged') return { ...packaged, promoted: false, foundation: null };
return withLedgerLock(async () => {
- const foundations = await readFoundations();
+ const { foundations, tombstones } = await readLedger();
const current = foundations[id];
if (!current) return { ...unknownFoundation(id), promoted: false, foundation: null };
// Packaging released the ledger lock before this one was taken, so an
@@ -369,7 +470,14 @@ export async function promoteEidoverseFoundation(id, { now = new Date().toISOStr
}
const foundation = { ...current, layer: 'baseline', promotedAt: now };
foundations[id] = foundation;
- await writeFoundations(foundations);
+ // Re-publishing a body that was withdrawn earlier clears its tombstone, or
+ // the offering would carry a retraction and the republication of the very
+ // same fingerprint at once and every receiver would reap what it just
+ // inherited, forever. This is `tombstones.js`'s re-create case: the
+ // fingerprint is content-addressed, so an identical body promoted again IS
+ // the same key, and only an explicit clear can distinguish "I changed my
+ // mind" from "I never withdrew it".
+ await writeLedger({ foundations, tombstones: clearTombstone(tombstones, packaged.candidate.fingerprint, TOMBSTONE_KEY_FIELD) });
return { ...packaged, outcome: 'promoted', promoted: true, foundation };
});
}
@@ -410,7 +518,7 @@ export async function recordEidoverseFoundationInheritance(candidate, { sourceIn
if (built.outcome !== 'inherited') return built;
return withLedgerLock(async () => {
- const foundations = await readFoundations();
+ const { foundations, tombstones } = await readLedger();
const originInstanceId = built.foundation.provenance.originInstanceId;
const key = inheritedFoundationStorageKey(originInstanceId, built.foundation.id);
// The storage key is chosen by `provenance.originInstanceId` — a field the
@@ -436,7 +544,144 @@ export async function recordEidoverseFoundationInheritance(candidate, { sourceIn
};
}
foundations[key] = built.foundation;
- await writeFoundations(foundations);
+ await writeLedger({ foundations, tombstones });
return { outcome: 'inherited', foundation: { ...built.foundation, lineage: foundationLineage(built.foundation) }, reasons: [], findings: [] };
});
}
+
+/**
+ * Withdraw a foundation this install PROMOTED, retracting it from the shared
+ * population (#7632).
+ *
+ * Two things happen, and the second is the one that makes this different from
+ * every de-promotion that came before it:
+ *
+ * 1. The record drops back to `vernacular` with `promotedAt` and `candidate`
+ * cleared — the same transition re-authoring performs. It leaves the
+ * offering immediately, because `listPromotedFoundationCandidates()` serves
+ * `baseline` records only.
+ * 2. The withdrawn candidate's fingerprint is TOMBSTONED, and the tombstone
+ * rides the offering. Without it, a peer that already pulled the foundation
+ * keeps its `baseline` copy indefinitely: the sweep converges upward toward
+ * whatever the sender currently lists and has no way to express "and drop
+ * what I no longer list", because a foundation legitimately absent from one
+ * offering is indistinguishable from one the sender never had.
+ *
+ * The body is KEPT. Withdrawal un-publishes; deleting the local work is
+ * `deleteEidoverseFoundation()` and a separate decision.
+ *
+ * A peer running a version that predates the tombstone key keeps its copy and
+ * says so in its log. That is unavoidable by construction — it is why the
+ * retraction is documented as best-effort rather than a guarantee — and it is
+ * the correct failure mode: it degrades to today's behavior rather than
+ * mis-reading a key it does not know.
+ *
+ * @returns {Promise<{ outcome: 'withdrawn'|'not-promoted'|'refused'|'unknown-foundation', foundation: object|null, reasons: string[] }>}
+ */
+export async function withdrawEidoverseFoundation(id, { now = new Date().toISOString() } = {}) {
+ return withLedgerLock(async () => {
+ const { foundations, tombstones } = await readLedger();
+ const current = foundations[id];
+ if (!current) return { outcome: 'unknown-foundation', foundation: null, reasons: [`no foundation is recorded under "${id}"`] };
+ if (current.inheritance) {
+ return {
+ outcome: 'refused',
+ foundation: null,
+ reasons: [`"${id}" is a local copy of a foundation install ${current.inheritance.originInstanceId} promoted — this install never published it, so it has nothing to withdraw (delete the copy instead)`],
+ };
+ }
+ if (current.layer !== 'baseline') {
+ return { outcome: 'not-promoted', foundation: { ...current, lineage: foundationLineage(current) }, reasons: [`"${id}" is not promoted, so there is nothing to retract`] };
+ }
+ // `updatedAt` is untouched: it tracks the BODY's authorship, and a
+ // withdrawal changes what this install publishes, not what it wrote.
+ const foundation = { ...current, layer: 'vernacular', candidate: null, promotedAt: null };
+ foundations[id] = foundation;
+ await writeLedger({ foundations, tombstones: tombstoneForReplacedCandidate(tombstones, current, now) });
+ console.log(`🚫 Withdrew Eidoverse foundation "${current.title}" from this install's promoted population — peers drop their copy on the next sweep`);
+ return { outcome: 'withdrawn', foundation: { ...foundation, lineage: foundationLineage(foundation) }, reasons: [] };
+ });
+}
+
+/**
+ * The retractions this install advertises beside its offering — read by
+ * `buildEidoverseFoundationOffering()` in the peer transport.
+ *
+ * Deliberately the WHOLE capped list, not a delta: a receiver that was offline
+ * across several withdrawals has no cursor, and a tombstone for a fingerprint
+ * nobody holds is a silent no-op on the receiving side, so re-sending one costs
+ * nothing but bytes.
+ */
+export async function listWithdrawnFoundationTombstones() {
+ return (await readLedger()).tombstones;
+}
+
+/**
+ * Apply a peer's retractions: drop every local copy this install inherited FROM
+ * that peer whose fingerprint the peer has tombstoned (#7632). The receiving
+ * half of `withdrawEidoverseFoundation()`.
+ *
+ * **Scoped to the peer that sent them.** A tombstone authorizes dropping only a
+ * record this install pulled from that same peer (`inheritance.sourceInstanceId`).
+ * Otherwise any registered peer could retract a third install's foundation by
+ * naming its fingerprint — a fingerprint is public inside the federation the
+ * moment it is offered, so it is an identifier, never a credential.
+ *
+ * A tombstone for a fingerprint this install does not hold is a no-op, not an
+ * error: a receiver that never pulled the foundation (or already dropped it) is
+ * already in the state the retraction asks for.
+ *
+ * The peer's tombstones are NOT persisted here. This install never re-offers an
+ * inherited record, so it can never relay one; and the sender keeps advertising
+ * the tombstone while its candidate stays absent, so there is no window in
+ * which a dropped copy could be re-inherited. Storing them would only let a
+ * peer grow this install's capped list and push out its own retractions.
+ *
+ * @returns {Promise<{ removed: number }>}
+ */
+export async function applyEidoverseFoundationTombstones(peerTombstones, { sourceInstanceId } = {}) {
+ const incoming = normalizeTombstones(peerTombstones, TOMBSTONE_KEY_FIELD);
+ if (incoming.length === 0 || !sourceInstanceId) return { removed: 0 };
+ return withLedgerLock(async () => {
+ const { foundations, tombstones } = await readLedger();
+ const doomed = Object.entries(foundations).filter(([, entry]) => entry?.inheritance
+ && entry.inheritance.sourceInstanceId === sourceInstanceId
+ && tombstoneTimestamp(incoming, entry.inheritance.fingerprint, TOMBSTONE_KEY_FIELD) !== null);
+ if (doomed.length === 0) return { removed: 0 };
+ for (const [key, entry] of doomed) {
+ delete foundations[key];
+ console.log(`🗑️ Dropped inherited Eidoverse foundation "${entry.title}" — install ${entry.inheritance.originInstanceId} withdrew it`);
+ }
+ await writeLedger({ foundations, tombstones });
+ return { removed: doomed.length };
+ });
+}
+
+/**
+ * Delete a foundation record outright — local work or an inherited copy.
+ *
+ * An inherited copy is addressed as `{ id, originInstanceId }` rather than by
+ * its raw `peer:<origin>:<id>` storage key, so the ledger's key grammar stays
+ * an implementation detail of this module instead of something a caller has to
+ * assemble (and could assemble wrong).
+ *
+ * **Deleting a PROMOTED local record withdraws it first.** Dropping the row
+ * without a tombstone would orphan every peer's copy permanently, which is the
+ * exact failure withdrawal exists to prevent — and it would be reached by the
+ * most natural gesture a regretful author makes ("remove this").
+ *
+ * @returns {Promise<{ outcome: 'deleted'|'unknown-foundation', foundation: object|null, withdrawn: boolean }>}
+ */
+export async function deleteEidoverseFoundation(id, { originInstanceId = null, now = new Date().toISOString() } = {}) {
+ return withLedgerLock(async () => {
+ const { foundations, tombstones } = await readLedger();
+ const key = originInstanceId ? inheritedFoundationStorageKey(originInstanceId, id) : id;
+ const current = foundations[key];
+ if (!current) return { outcome: 'unknown-foundation', foundation: null, withdrawn: false };
+ const withdrawn = wasPublished(current);
+ delete foundations[key];
+ await writeLedger({ foundations, tombstones: tombstoneForReplacedCandidate(tombstones, current, now) });
+ console.log(`🗑️ Deleted Eidoverse foundation "${current.title}"${withdrawn ? ' and withdrew it from the peer offering' : ''}`);
+ return { outcome: 'deleted', foundation: current, withdrawn };
+ });
+}
diff --git a/server/services/eidoverseFoundationLedger.test.js b/server/services/eidoverseFoundationLedger.test.js
index a33863ed8c..5d8720f3ad 100644
--- a/server/services/eidoverseFoundationLedger.test.js
+++ b/server/services/eidoverseFoundationLedger.test.js
@@ -17,6 +17,8 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await im
}));
const {
+ applyEidoverseFoundationTombstones,
+ deleteEidoverseFoundation,
getEidoverseFoundation,
listEidoverseFoundations,
packageEidoverseFoundationCandidate,
@@ -24,6 +26,8 @@ const {
recordEidoverseFoundation,
recordEidoverseFoundationInheritance,
listPromotedFoundationCandidates,
+ listWithdrawnFoundationTombstones,
+ withdrawEidoverseFoundation,
} = await import('./eidoverseFoundationLedger.js');
// The passing reference contribution shipped with the assay harness (#7460).
@@ -524,3 +528,199 @@ describe('building on a foundation inherited from a peer (#7631)', () => {
expect(result.foundation.derivedFrom).toBeNull();
});
});
+
+/**
+ * #7632: promotion used to be irreversible. A foundation left the install once
+ * and every peer that pulled it kept that copy forever — the offering only
+ * added, and the sweep converged upward toward whatever the sender currently
+ * listed. De-promoting (by re-authoring, the only way there was) dropped the
+ * record from the offering and told nobody.
+ *
+ * These pin the retraction path end to end, because no single-install
+ * assertion can: the ORIGIN's tombstone is meaningless unless a RECEIVER acts
+ * on it, and the receiver's reaper is meaningless unless the origin emits one.
+ *
+ * The two installs are simulated the way the #7631 suite above already does —
+ * one temp data root at a time, wiped to "become" the receiver — so the
+ * candidate and the tombstone list have to be captured on the origin before
+ * the switch, exactly as they would be carried over the wire.
+ */
+
+/** This install's own origin id, as `record()` above stamps it. */
+const LOCAL_ORIGIN = 'instance-aaaa';
+/** The peer a simulated receiver pulled from. */
+const PEER = 'instance-peer-one';
+
+/** Promote on this install and hand back what a peer would have pulled. */
+const promoteLocally = async () => {
+ await record({}, '2026-03-01T00:00:00.000Z');
+ const promoted = await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+ expect(promoted.outcome).toBe('promoted');
+ return promoted.candidate;
+};
+
+describe('withdrawing a promoted foundation (#7632)', () => {
+ /** Become a second install holding `candidate` inherited from `PEER`. */
+ const becomeReceiverHolding = async (candidate) => {
+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
+ const inherited = await recordEidoverseFoundationInheritance(candidate, {
+ sourceInstanceId: PEER, localInstanceId: 'instance-this-install', now: '2026-03-02T00:00:00.000Z',
+ });
+ expect(inherited.outcome).toBe('inherited');
+ return inherited.foundation;
+ };
+
+ it('de-promotes the record, stops offering it, and records a tombstone for what was published', async () => {
+ const candidate = await promoteLocally();
+
+ const result = await withdrawEidoverseFoundation('tide-beacon', { now: '2026-03-05T00:00:00.000Z' });
+
+ expect(result.outcome).toBe('withdrawn');
+ expect(result.foundation).toMatchObject({ layer: 'vernacular', promotedAt: null, candidate: null });
+ expect(await listPromotedFoundationCandidates()).toEqual([]);
+ // The body is KEPT — withdrawal un-publishes, it does not delete local work.
+ expect((await getEidoverseFoundation('tide-beacon')).body).toEqual(candidate.body);
+ expect(await listWithdrawnFoundationTombstones())
+ .toEqual([{ fingerprint: candidate.fingerprint, deletedAt: '2026-03-05T00:00:00.000Z' }]);
+ });
+
+ // The whole point of the feature, and the one thing only a two-install cycle
+ // can prove: a copy already on another machine actually goes away.
+ it('drops a peer\'s inherited copy across a full promote → inherit → withdraw → sweep cycle', async () => {
+ const candidate = await promoteLocally();
+ await withdrawEidoverseFoundation('tide-beacon', { now: '2026-03-05T00:00:00.000Z' });
+ const offered = await listWithdrawnFoundationTombstones();
+
+ await becomeReceiverHolding(candidate);
+ const heldKey = inheritedFoundationStorageKey(LOCAL_ORIGIN, 'tide-beacon');
+ expect(await getEidoverseFoundation(heldKey)).toBeTruthy();
+
+ expect(await applyEidoverseFoundationTombstones(offered, { sourceInstanceId: PEER })).toEqual({ removed: 1 });
+
+ expect(await getEidoverseFoundation(heldKey)).toBeNull();
+ expect((await listEidoverseFoundations()).counts.inherited).toBe(0);
+ });
+
+ it('is a silent no-op for a fingerprint this install does not hold', async () => {
+ const candidate = await promoteLocally();
+ await becomeReceiverHolding(candidate);
+
+ // A receiver that never pulled the foundation (or already dropped it) is
+ // already in the state the retraction asks for — not an error to surface.
+ expect(await applyEidoverseFoundationTombstones(
+ [{ fingerprint: 'b'.repeat(64), deletedAt: '2026-03-05T00:00:00.000Z' }], { sourceInstanceId: PEER },
+ )).toEqual({ removed: 0 });
+ expect((await listEidoverseFoundations()).counts.inherited).toBe(1);
+ });
+
+ // A fingerprint is public inside the federation the moment it is offered, so
+ // it identifies a record but authorizes nothing. Without the scope, any
+ // registered peer could retract a third install's work by naming it.
+ it('refuses to act on a retraction from a peer this install did not inherit from', async () => {
+ const candidate = await promoteLocally();
+ await becomeReceiverHolding(candidate);
+
+ expect(await applyEidoverseFoundationTombstones(
+ [{ fingerprint: candidate.fingerprint, deletedAt: '2026-03-05T00:00:00.000Z' }],
+ { sourceInstanceId: 'instance-peer-two' },
+ )).toEqual({ removed: 0 });
+ expect((await listEidoverseFoundations()).counts.inherited).toBe(1);
+ });
+
+ // `packagedAt` is hashed into the envelope, so an ordinary re-promote mints a
+ // NEW fingerprint. That is the common case and it is already correct: the old
+ // tombstone keeps retracting the bytes peers actually hold, while the fresh
+ // envelope publishes beside it.
+ it('keeps retracting the withdrawn envelope while offering the re-promoted one', async () => {
+ const candidate = await promoteLocally();
+ await withdrawEidoverseFoundation('tide-beacon', { now: '2026-03-05T00:00:00.000Z' });
+
+ const again = await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-06T00:00:00.000Z' });
+
+ expect(again.candidate.fingerprint).not.toBe(candidate.fingerprint);
+ expect((await listPromotedFoundationCandidates()).map((entry) => entry.fingerprint)).toEqual([again.candidate.fingerprint]);
+ expect((await listWithdrawnFoundationTombstones()).map((entry) => entry.fingerprint)).toEqual([candidate.fingerprint]);
+ });
+
+ // The edge the clear-on-promote exists for: promote → withdraw → promote all
+ // stamped at one instant re-mints the SAME fingerprint. Without the clear the
+ // offering would publish and retract one fingerprint at once, and the
+ // outbound backstop would then withhold the candidate — a re-promote that
+ // silently did nothing.
+ it('clears the tombstone when a re-promote re-mints the identical fingerprint', async () => {
+ const at = '2026-03-01T01:00:00.000Z';
+ await record({}, '2026-03-01T00:00:00.000Z');
+ const candidate = (await promoteEidoverseFoundation('tide-beacon', { now: at })).candidate;
+ await withdrawEidoverseFoundation('tide-beacon', { now: at });
+
+ const again = await promoteEidoverseFoundation('tide-beacon', { now: at });
+
+ expect(again.candidate.fingerprint).toBe(candidate.fingerprint);
+ expect(await listWithdrawnFoundationTombstones()).toEqual([]);
+ expect((await listPromotedFoundationCandidates()).map((entry) => entry.fingerprint)).toEqual([candidate.fingerprint]);
+ });
+
+ // The originally-reported shape: re-authoring already de-promoted the record
+ // locally and silently left every peer holding the retracted bytes.
+ it('tombstones the published fingerprint when a promoted foundation is re-authored', async () => {
+ const candidate = await promoteLocally();
+
+ await record({ body: { affordance: { inspect: 'reads the pulse count and the tide' } } }, '2026-03-05T00:00:00.000Z');
+
+ expect(await listWithdrawnFoundationTombstones())
+ .toEqual([{ fingerprint: candidate.fingerprint, deletedAt: '2026-03-05T00:00:00.000Z' }]);
+ });
+
+ it('records nothing for a foundation that was only ever packaged, never promoted', async () => {
+ await record({}, '2026-03-01T00:00:00.000Z');
+ await packageEidoverseFoundationCandidate('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });
+
+ expect(await withdrawEidoverseFoundation('tide-beacon', { now: '2026-03-05T00:00:00.000Z' }))
+ .toMatchObject({ outcome: 'not-promoted' });
+ // A packaged candidate never left the install, so a tombstone for it would
+ // broadcast a retraction no peer could possibly act on.
+ expect(await listWithdrawnFoundationTombstones()).toEqual([]);
+ });
+
+ it('refuses to withdraw an inherited copy — this install never published it', async () => {
+ await becomeReceiverHolding(await promoteLocally());
+
+ const result = await withdrawEidoverseFoundation(inheritedFoundationStorageKey(LOCAL_ORIGIN, 'tide-beacon'));
+
+ expect(result.outcome).toBe('refused');
+ expect(result.reasons[0]).toContain(LOCAL_ORIGIN);
+ });
+});
+
+describe('deleting a foundation record (#7632)', () => {
+ it('withdraws a promoted local record before deleting it, so no peer is orphaned', async () => {
+ const candidate = await promoteLocally();
+
+ expect(await deleteEidoverseFoundation('tide-beacon', { now: '2026-03-05T00:00:00.000Z' }))
+ .toMatchObject({ outcome: 'deleted', withdrawn: true });
+
+ expect(await getEidoverseFoundation('tide-beacon')).toBeNull();
+ // Deleting is the most natural gesture a regretful author makes; without
+ // this the record vanishes locally and lives on every peer forever.
+ expect(await listWithdrawnFoundationTombstones())
+ .toEqual([{ fingerprint: candidate.fingerprint, deletedAt: '2026-03-05T00:00:00.000Z' }]);
+ });
+
+ it('addresses an inherited copy by { id, originInstanceId } rather than its storage key', async () => {
+ const candidate = await promoteLocally();
+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
+ await recordEidoverseFoundationInheritance(candidate, {
+ sourceInstanceId: 'instance-peer-one', localInstanceId: 'instance-this-install', now: '2026-03-02T00:00:00.000Z',
+ });
+
+ // The bare id reaches only local work, on purpose: the two id spaces
+ // legitimately overlap.
+ expect(await deleteEidoverseFoundation('tide-beacon')).toMatchObject({ outcome: 'unknown-foundation' });
+ expect(await deleteEidoverseFoundation('tide-beacon', { originInstanceId: 'instance-aaaa' }))
+ .toMatchObject({ outcome: 'deleted', withdrawn: false });
+ expect((await listEidoverseFoundations()).foundations).toEqual([]);
+ // Deleting a copy this install merely holds retracts nothing: it was never
+ // this install's to publish.
+ expect(await listWithdrawnFoundationTombstones()).toEqual([]);
+ });
+});
diff --git a/server/services/sharing/eidoverseFoundationsSync.test.js b/server/services/sharing/eidoverseFoundationsSync.test.js
index a2d92999d5..c38c3f8179 100644
--- a/server/services/sharing/eidoverseFoundationsSync.test.js
+++ b/server/services/sharing/eidoverseFoundationsSync.test.js
@@ -29,8 +29,10 @@ vi.mock('../instanceFeatures.js', () => ({ isInstanceFeatureEnabled: vi.fn().moc
vi.mock('../../lib/peerHttpClient.js', () => ({ peerFetch: vi.fn() }));
vi.mock('../eidoverseFoundationLedger.js', () => ({
listPromotedFoundationCandidates: vi.fn().mockResolvedValue([]),
+ listWithdrawnFoundationTombstones: vi.fn().mockResolvedValue([]),
listEidoverseFoundations: vi.fn().mockResolvedValue({ foundations: [] }),
recordEidoverseFoundationInheritance: vi.fn().mockResolvedValue({ outcome: 'inherited', foundation: {}, reasons: [], findings: [] }),
+ applyEidoverseFoundationTombstones: vi.fn().mockResolvedValue({ removed: 0 }),
}));
import {
@@ -46,8 +48,10 @@ import { getInstanceId } from '../instanceIdentity.js';
import { isInstanceFeatureEnabled } from '../instanceFeatures.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
import {
+ applyEidoverseFoundationTombstones,
listEidoverseFoundations,
listPromotedFoundationCandidates,
+ listWithdrawnFoundationTombstones,
recordEidoverseFoundationInheritance,
} from '../eidoverseFoundationLedger.js';
@@ -98,9 +102,11 @@ beforeEach(() => {
vi.mocked(getInstanceId).mockResolvedValue('instance-local');
vi.mocked(isInstanceFeatureEnabled).mockResolvedValue(true);
vi.mocked(listPromotedFoundationCandidates).mockReset().mockResolvedValue([]);
+ vi.mocked(listWithdrawnFoundationTombstones).mockReset().mockResolvedValue([]);
vi.mocked(listEidoverseFoundations).mockReset().mockResolvedValue({ foundations: [] });
vi.mocked(recordEidoverseFoundationInheritance).mockReset()
.mockResolvedValue({ outcome: 'inherited', foundation: {}, reasons: [], findings: [] });
+ vi.mocked(applyEidoverseFoundationTombstones).mockReset().mockResolvedValue({ removed: 0 });
});
describe('the offering this install advertises', () => {
@@ -122,6 +128,37 @@ describe('the offering this install advertises', () => {
expect((await buildEidoverseFoundationOffering()).listHash).not.toBe(payload.listHash);
});
+ // #7632. The retraction has to be VISIBLE to a receiver that is otherwise
+ // short-circuiting, and it has to survive a full candidate list.
+ it('breaks the listHash on a withdrawal even when the candidate list is unchanged', async () => {
+ vi.mocked(listPromotedFoundationCandidates).mockResolvedValue([candidate('tide-beacon', 'a')]);
+ const before = await buildEidoverseFoundationOffering();
+ expect(before.tombstones).toEqual([]);
+
+ vi.mocked(listWithdrawnFoundationTombstones)
+ .mockResolvedValue([{ fingerprint: fingerprint('c'), deletedAt: '2026-03-04T00:00:00.000Z' }]);
+ const after = await buildEidoverseFoundationOffering();
+
+ // Without the tombstones in the hash a receiver would skip this tick and
+ // keep the withdrawn copy until the next FORCE_REVALIDATE_EVERY pass.
+ expect(after.listHash).not.toBe(before.listHash);
+ expect(after.tombstones).toEqual([{ fingerprint: fingerprint('c'), deletedAt: '2026-03-04T00:00:00.000Z' }]);
+ });
+
+ it('never drops a tombstone to make room for a candidate at the entry cap', async () => {
+ vi.mocked(listPromotedFoundationCandidates)
+ .mockResolvedValue(Array.from({ length: 600 }, (_unused, i) => candidate(`f-${i}`, String(i % 10))));
+ vi.mocked(listWithdrawnFoundationTombstones)
+ .mockResolvedValue([{ fingerprint: fingerprint('c'), deletedAt: '2026-03-04T00:00:00.000Z' }]);
+
+ const payload = await buildEidoverseFoundationOffering();
+
+ // The candidates truncate; the retraction does not. Sharing one cap would
+ // let a large promoted population silently swallow a recall.
+ expect(payload.candidates).toHaveLength(500);
+ expect(payload.tombstones).toHaveLength(1);
+ });
+
it('advertises nothing while the Eidoverse feature is off, without reading the ledger', async () => {
vi.mocked(isInstanceFeatureEnabled).mockResolvedValue(false);
vi.mocked(listPromotedFoundationCandidates).mockResolvedValue([candidate('tide-beacon')]);
@@ -198,6 +235,43 @@ describe('pulling a peer offering', () => {
);
});
+ // #7632 — the direction the sweep never had.
+ it('hands the peer\'s retractions to the ledger scoped to that peer, before inheriting', async () => {
+ const tombstone = { fingerprint: fingerprint('c'), deletedAt: '2026-03-04T00:00:00.000Z' };
+ vi.mocked(applyEidoverseFoundationTombstones).mockResolvedValue({ removed: 1 });
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('tide-beacon')], { tombstones: [tombstone] }));
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 1, removed: 1 });
+ // `sourceInstanceId` is the authorization scope: without it any peer could
+ // retract a third install's foundation by naming its (public) fingerprint.
+ expect(applyEidoverseFoundationTombstones).toHaveBeenCalledWith([tombstone], { sourceInstanceId: 'instance-peer' });
+ // Reaping runs BEFORE the held-set read, so a candidate the same offering
+ // re-publishes is re-verified on its way back in rather than surviving in
+ // place. Invocation order is the only observable form of that guarantee.
+ expect(vi.mocked(applyEidoverseFoundationTombstones).mock.invocationCallOrder[0])
+ .toBeLessThan(vi.mocked(listEidoverseFoundations).mock.invocationCallOrder[0]);
+ });
+
+ it('still applies a pre-withdrawal peer\'s offering, which carries no tombstones key at all', async () => {
+ const { tombstones: _absent, ...v2 } = await offering([candidate('tide-beacon')]).json();
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, headers: { get: () => null }, json: async () => v2 });
+
+ // A missing key must read as "nothing to retract", never fail the wrapper —
+ // that would strand the sender's candidates too, on every install that
+ // upgraded ahead of it.
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 1, removed: 0 });
+ expect(applyEidoverseFoundationTombstones).toHaveBeenCalledWith([], expect.anything());
+ });
+
+ it('counts a failed retraction as zero removed and still inherits, so the next sweep retries', async () => {
+ vi.mocked(applyEidoverseFoundationTombstones).mockRejectedValue(new Error('ledger busy'));
+ vi.mocked(peerFetch).mockResolvedValue(offering([candidate('tide-beacon')], {
+ tombstones: [{ fingerprint: fingerprint('c'), deletedAt: '2026-03-04T00:00:00.000Z' }],
+ }));
+
+ expect(await syncEidoverseFoundationsFromPeer(PEER)).toMatchObject({ inherited: 1, removed: 0 });
+ });
+
it('rejects a malformed wrapper before any candidate reaches the gate', async () => {
vi.mocked(peerFetch).mockResolvedValue({ ok: true, headers: { get: () => null }, json: async () => ({ candidates: 'not-an-array' }) });
diff --git a/server/services/sharing/peerEidoverseFoundationSync.js b/server/services/sharing/peerEidoverseFoundationSync.js
index a185e0e24d..79f3f25b8a 100644
--- a/server/services/sharing/peerEidoverseFoundationSync.js
+++ b/server/services/sharing/peerEidoverseFoundationSync.js
@@ -33,6 +33,17 @@
* payload carrying machine identity, PII or credentials rather than redacting
* it — on both sides, because a peer's payload is untrusted input and this
* install's own ledger is a file a human can edit.
+ *
+ * **The offering also RETRACTS (#7632).** It used to converge only upward: a
+ * receiver applied what the sender listed and never reconciled what it held
+ * against what the sender had stopped listing, so a promoted foundation could
+ * never be recalled from an install that had pulled it. The payload now carries
+ * `tombstones: [{ fingerprint, deletedAt }]` beside `candidates`, in its own
+ * separately-capped array — a retraction must never be displaced by the entry
+ * cap to make room for a publication. Both lists feed the `listHash`, so a
+ * withdrawal with no other change still breaks the receiver's short-circuit.
+ * A tombstone carries a content-addressed fingerprint and nothing else: it
+ * names one published body without re-transmitting any of it.
*/
import { createHash } from 'crypto';
import { isPlainObject } from '../../lib/objects.js';
@@ -55,6 +66,17 @@ import { FORCE_REVALIDATE_EVERY } from './peerSyncShared.js';
const OFFERING_ENTRY_CAP = 500;
const OFFERING_MAX_BYTES = 16 * 1024 * 1024;
+/**
+ * Tombstones cap on their OWN budget, never against `OFFERING_ENTRY_CAP`
+ * (#7632). Sharing one cap would let a large promoted population silently
+ * truncate the retractions — publishing crowding out recall, which is the one
+ * trade this feature must never make. A tombstone is two short strings, so
+ * 500 of them is a rounding error against a 16 KiB body; the ledger caps the
+ * stored list at the same order and drops the OLDEST deletion first, which by
+ * then has long since reached every peer.
+ */
+const TOMBSTONE_ENTRY_CAP = 500;
+
/**
* Deliberately NOT `ASSET_PULL_TIMEOUT_MS`: that constant is sized for
* streaming media bytes, and importing it would drag `peerSyncAssets.js` — and
@@ -86,9 +108,19 @@ const peerLabel = (peer) => peer.name || peer.instanceId;
/** Content-address the offering so a receiver can short-circuit an unchanged
* one. Each envelope already carries a sha256 of its own body, and the list is
* sorted by it, so hashing the fingerprints alone is both sufficient and
- * order-independent. */
-const offeringListHash = (candidates) => createHash('sha256')
+ * order-independent.
+ *
+ * The tombstones hash in too (#7632), under a separator that cannot appear in
+ * either list, so a withdrawal is never mistaken for "nothing changed": a
+ * retraction is usually the ONLY delta on the tick it lands (the candidate left
+ * the offering at the same moment, but a receiver that had already skipped
+ * would not look), and hashing candidates alone would hide it until the next
+ * forced re-pull. `deletedAt` is included because re-withdrawing a fingerprint
+ * refreshes the stamp and is a real change to what the sender is asserting. */
+const offeringListHash = (candidates, tombstones) => createHash('sha256')
.update(candidates.map((candidate) => String(candidate.fingerprint)).join('\n'))
+ .update('\n--tombstones--\n')
+ .update(tombstones.map((entry) => `${entry.fingerprint}@${entry.deletedAt}`).join('\n'))
.digest('hex');
/**
@@ -101,20 +133,26 @@ const offeringListHash = (candidates) => createHash('sha256')
* @returns {Promise<{ schemaVersion:number, listHash:string, candidates:Array }>}
*/
export async function buildEidoverseFoundationOffering() {
- const offering = (candidates) => ({
+ const offering = (candidates, tombstones = []) => ({
schemaVersion: PORTOS_SCHEMA_VERSIONS.eidoverseFoundations,
- listHash: offeringListHash(candidates),
+ listHash: offeringListHash(candidates, tombstones),
candidates,
+ tombstones,
});
if (!(await eidoverseEnabled())) return offering([]);
const mod = await ledger();
- if (!mod?.listPromotedFoundationCandidates) return offering([]);
+ if (!mod?.listPromotedFoundationCandidates || !mod?.listWithdrawnFoundationTombstones) return offering([]);
const candidates = await mod.listPromotedFoundationCandidates();
+ const tombstones = await mod.listWithdrawnFoundationTombstones();
+ if (tombstones.length > TOMBSTONE_ENTRY_CAP) {
+ console.log(`⚠️ peerSync: eidoverse-foundations offering hit the ${TOMBSTONE_ENTRY_CAP}-tombstone cap — truncating`);
+ }
if (candidates.length > OFFERING_ENTRY_CAP) {
console.log(`⚠️ peerSync: eidoverse-foundations offering hit the ${OFFERING_ENTRY_CAP}-entry cap — truncating`);
- return offering(candidates.slice(0, OFFERING_ENTRY_CAP));
}
- return offering(candidates);
+ // Each list slices against its OWN cap, so a full candidate list can never
+ // cost a retraction its slot.
+ return offering(candidates.slice(0, OFFERING_ENTRY_CAP), tombstones.slice(0, TOMBSTONE_ENTRY_CAP));
}
// Receiver-side bookkeeping — mirrors the cos-tasks sweep.
@@ -202,7 +240,7 @@ export async function syncEidoverseFoundationsFromPeer(peer) {
}
offeringUnchangedSkips.set(peer.instanceId, 0); // forced re-pull — fall through
}
- const applied = await applyOffering(payload.candidates, { peer, localInstanceId });
+ const applied = await applyOffering(payload.candidates, payload.tombstones, { peer, localInstanceId });
// Only remember the offering once it was actually applied: recording the
// hash after a `ledger-unavailable` pass would short-circuit the next
// FORCE_REVALIDATE_EVERY ticks on work that never happened.
@@ -213,6 +251,9 @@ export async function syncEidoverseFoundationsFromPeer(peer) {
if (applied.refused > 0) {
console.log(`⚠️ peerSync: eidoverse-foundations sweep from ${peerLabel(peer)} — refused ${applied.refused} candidate(s) at the accept-side gate`);
}
+ if (applied.removed > 0) {
+ console.log(`🗑️ peerSync: eidoverse-foundations sweep from ${peerLabel(peer)} — dropped ${applied.removed} withdrawn foundation(s)`);
+ }
return applied;
} finally {
offeringSweepInFlight.delete(peer.instanceId);
@@ -220,18 +261,37 @@ export async function syncEidoverseFoundationsFromPeer(peer) {
}
/**
- * Hand each candidate to the accept-side gate, skipping the ones this install
- * already holds at the same content-addressed fingerprint.
+ * Reconcile this install against the peer's offering in BOTH directions:
+ * drop what the peer withdrew, then inherit what it newly offers, skipping the
+ * candidates this install already holds at the same content-addressed
+ * fingerprint.
+ *
+ * **Retractions apply FIRST**, before `held` is read. The sender clears a
+ * fingerprint's tombstone when it re-promotes that exact body, so the two lists
+ * do not normally overlap — but a sender whose ledger was hand-edited could
+ * send both, and reaping first means the survivor is whatever the CANDIDATE
+ * list says. That is the safe order: a re-inherited foundation is re-verified
+ * through the whole accept-side gate on its way back in, while the opposite
+ * order would leave a retracted body in place with nothing to re-check it.
*
* Sequential on purpose: `recordEidoverseFoundationInheritance` serializes on
* the ledger's own mutex, so a `Promise.all` here would buy nothing but a
* deeper queue and a less readable failure.
*/
-async function applyOffering(candidates, { peer, localInstanceId }) {
+async function applyOffering(candidates, tombstones, { peer, localInstanceId }) {
const mod = await ledger();
- if (!mod?.recordEidoverseFoundationInheritance || !mod?.listEidoverseFoundations) {
- return { inherited: 0, refused: 0, skipped: 'ledger-unavailable' };
+ if (!mod?.recordEidoverseFoundationInheritance || !mod?.listEidoverseFoundations || !mod?.applyEidoverseFoundationTombstones) {
+ return { inherited: 0, refused: 0, removed: 0, skipped: 'ledger-unavailable' };
}
+ const { removed = 0 } = (await mod.applyEidoverseFoundationTombstones(tombstones, {
+ sourceInstanceId: peer.instanceId,
+ }).catch((err) => {
+ // Counted as "reaped nothing" and pressed on: the sender keeps advertising
+ // the tombstone until its candidate comes back, so a failed retraction
+ // retries on the next sweep rather than being lost.
+ console.log(`⚠️ peerSync: eidoverse-foundations retraction from ${peerLabel(peer)} failed: ${err.message}`);
+ return null;
+ })) || {};
const held = new Set((await mod.listEidoverseFoundations()).foundations
.filter((entry) => entry.inheritance)
.map((entry) => entry.inheritance.fingerprint));
@@ -249,7 +309,7 @@ async function applyOffering(candidates, { peer, localInstanceId }) {
if (result?.outcome === 'inherited') inherited += 1;
else refused += 1;
}
- return { inherited, refused };
+ return { inherited, refused, removed };
}
/**