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

replay the foundation being promoted, not the contribution its author named (#7625)

[._.]/ Adam Eivy49b36e0fe9ce
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
index 5703d6f1d4..b6dd8f2acc 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.jsx
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useId, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router';
import { GitFork, Globe2, Home, ShieldCheck } from 'lucide-react';
import {
- getEidoverseContributions,
+ listEidoverseControllers,
listEidoverseFoundations,
packageEidoverseFoundationCandidate,
promoteEidoverseFoundation,
@@ -48,9 +48,23 @@ const fieldClass = 'mt-1 min-h-[42px] w-full rounded-lg border border-port-borde
const secondaryButton = 'inline-flex min-h-[40px] items-center justify-center rounded-lg border border-port-border px-3 py-2 text-sm text-gray-200 transition-colors hover:border-port-accent hover:text-white disabled:cursor-wait disabled:opacity-50';
const primaryButton = 'inline-flex min-h-[40px] items-center justify-center rounded-lg bg-port-accent px-4 py-2 text-sm font-semibold text-black transition-opacity hover:opacity-90 disabled:cursor-wait disabled:opacity-50';
+/**
+ * A starting `body` per kind, because since #7625 the body IS what the promote
+ * gate replays: it derives the resilience-assay sandbox from these declarations
+ * rather than from an id the author names. An empty textarea would leave the
+ * author guessing at the one shape that can be replayed, and the refusal would
+ * be their first hint.
+ */
+const BODY_TEMPLATES = Object.freeze({
+ affordance: '{\n "schema": {\n "pulses": "integer"\n },\n "affordance": {\n "pulse": { "summary": "advance the pulse count", "reads": ["pulses"], "writes": ["pulses"] }\n }\n}',
+ controller: '{\n "controller": {\n "definitionId": "",\n "config": {}\n }\n}',
+ schema: '{\n "schema": {\n "pulses": "integer"\n }\n}',
+ 'district-template': '{\n "layoutId": "radial-ring",\n "anchor": [0, 0, 0],\n "propCount": 6,\n "seed": "",\n "facing": 0,\n "placement": []\n}',
+});
+
const EMPTY_DRAFT = Object.freeze({
- id: '', kind: 'affordance', title: '', summary: '', contributionId: '',
- body: '{\n "affordance": {}\n}', style: '{}',
+ id: '', kind: 'affordance', title: '', summary: '',
+ body: BODY_TEMPLATES.affordance, style: '{}',
requires: '', effects: '', license: '', notes: '',
// `{ originInstanceId, foundationId }` once this draft builds on a peer's
// inherited foundation — see `draftFromFoundation` (#7631).
@@ -108,7 +122,6 @@ const draftFromFoundation = (foundation) => ({
kind: foundation.kind,
title: foundation.title,
summary: foundation.summary,
- contributionId: foundation.contributionId,
body: JSON.stringify(foundation.body ?? {}, null, 2),
style: JSON.stringify(foundation.style ?? {}, null, 2),
requires: (foundation.disclosure?.requires || []).join(', '),
@@ -231,7 +244,9 @@ export default function EidoverseFoundationsPanel() {
const openId = searchParams.get('foundation');
const [foundations, setFoundations] = useState([]);
const [counts, setCounts] = useState({ vernacular: 0, baseline: 0, candidates: 0, inherited: 0 });
- const [contributions, setContributions] = useState(null);
+ // `null` means "never fetched"; an empty ARRAY means this install genuinely
+ // ships no controller definition, which is a different thing to tell the author.
+ const [controllerDefinitions, setControllerDefinitions] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [busyId, setBusyId] = useState('');
@@ -248,14 +263,11 @@ export default function EidoverseFoundationsPanel() {
useEffect(() => {
let live = true;
- Promise.all([listEidoverseFoundations(silent), getEidoverseContributions(silent)])
+ Promise.all([listEidoverseFoundations(silent), listEidoverseControllers(silent)])
.then(([listing, registry]) => {
if (!live) return;
applyListing(listing);
- // `null` means "never fetched" and renders as a plain text field; an
- // empty ARRAY means this install genuinely registers no contribution,
- // which is a different thing to tell the author.
- setContributions(registry.contributions || []);
+ setControllerDefinitions(registry.available || []);
setLoadError('');
})
.catch((reason) => { if (live) setLoadError(reason?.message || 'Could not load foundations.'); })
@@ -305,7 +317,6 @@ export default function EidoverseFoundationsPanel() {
kind: draft.kind,
title: draft.title.trim(),
summary: draft.summary.trim(),
- contributionId: draft.contributionId.trim(),
body: body.value,
style: style.value,
// Omitted rather than sent as `null` when absent: the field is optional
@@ -330,6 +341,32 @@ export default function EidoverseFoundationsPanel() {
const mutateDraft = (key) => (event) => setDraft((current) => ({ ...current, [key]: event.target.value }));
+ /**
+ * Switching kind re-seeds the body, but only while the body is still one of
+ * the untouched templates — an author who has started writing keeps what they
+ * wrote. Since #7625 the body is the thing the promote gate replays, so each
+ * kind has a genuinely different shape rather than a cosmetic label.
+ */
+ const changeKind = useCallback((event) => {
+ const kind = event.target.value;
+ setDraft((current) => ({
+ ...current,
+ kind,
+ body: Object.values(BODY_TEMPLATES).includes(current.body.trim()) ? BODY_TEMPLATES[kind] : current.body,
+ }));
+ }, []);
+
+ /** Seed the body with a shipped definition and its own example config, which
+ * the author then edits into the config this install actually runs. */
+ const seedControllerBody = useCallback((event) => {
+ const definition = (controllerDefinitions || []).find((entry) => entry.id === event.target.value);
+ if (!definition) return;
+ setDraft((current) => ({
+ ...current,
+ body: JSON.stringify({ controller: { definitionId: definition.id, config: definition.exampleConfig || {} } }, null, 2),
+ }));
+ }, [controllerDefinitions]);
+
const openFoundationRecord = useMemo(
() => foundations.find((entry) => entry.id === openId) || null,
[foundations, openId],
@@ -380,7 +417,7 @@ export default function EidoverseFoundationsPanel() {
</div>
<p className="mt-1 text-sm text-gray-400">{foundation.summary}</p>
<p className="mt-1 text-xs text-gray-500">
- Replayed as <code className="text-gray-400">{foundation.contributionId}</code>
+ Replayed as <code className="text-gray-400">{foundation.contributionId}</code> (derived from this body)
{foundation.candidate ? ' · candidate packaged' : ''}
{foundation.assay ? (foundation.assay.pass ? ' · assay passed' : ' · assay failed') : ' · assay not run'}
</p>
@@ -492,7 +529,7 @@ export default function EidoverseFoundationsPanel() {
</div>
<div>
<label htmlFor={`${fieldId}-kind`} className="text-sm text-gray-300">Kind</label>
- <select id={`${fieldId}-kind`} className={fieldClass} value={draft.kind} onChange={mutateDraft('kind')}>
+ <select id={`${fieldId}-kind`} className={fieldClass} value={draft.kind} onChange={changeKind}>
{FOUNDATION_KINDS.map((kind) => <option key={kind} value={kind}>{kind}</option>)}
</select>
</div>
@@ -500,22 +537,20 @@ export default function EidoverseFoundationsPanel() {
<label htmlFor={`${fieldId}-title`} className="text-sm text-gray-300">Title</label>
<input id={`${fieldId}-title`} className={fieldClass} value={draft.title} onChange={mutateDraft('title')} required />
</div>
- <div>
- <label htmlFor={`${fieldId}-contribution`} className="text-sm text-gray-300">Resilience-assay contribution</label>
- {contributions?.length ? (
- <select id={`${fieldId}-contribution`} className={fieldClass} value={draft.contributionId} onChange={mutateDraft('contributionId')} required>
- <option value="">Choose a registered contribution…</option>
- {contributions.map((id) => <option key={id} value={id}>{id}</option>)}
+ {draft.kind === 'controller' && (
+ <div>
+ <label htmlFor={`${fieldId}-definition`} className="text-sm text-gray-300">Controller definition</label>
+ <select id={`${fieldId}-definition`} className={fieldClass} value="" onChange={seedControllerBody}>
+ <option value="">Fill the body from a shipped definition…</option>
+ {(controllerDefinitions || []).map((definition) => <option key={definition.id} value={definition.id}>{definition.id}</option>)}
</select>
- ) : (
- <input id={`${fieldId}-contribution`} className={fieldClass} value={draft.contributionId} onChange={mutateDraft('contributionId')} required />
- )}
- {contributions?.length === 0 && (
- <p className="mt-1 text-xs text-port-warning">
- This install registers no replayable contribution, so nothing can pass the promote gate yet.
- </p>
- )}
- </div>
+ {controllerDefinitions?.length === 0 && (
+ <p className="mt-1 text-xs text-port-warning">
+ This install ships no controller definition, so a `controller` foundation has nothing to replay.
+ </p>
+ )}
+ </div>
+ )}
</div>
<div>
<label htmlFor={`${fieldId}-summary`} className="text-sm text-gray-300">Summary</label>
diff --git a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
index fea3db0b03..53fd5c9c32 100644
--- a/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
+++ b/client/src/components/eidoverse/EidoverseFoundationsPanel.test.jsx
@@ -11,7 +11,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../services/api', () => ({
listEidoverseFoundations: vi.fn(),
- getEidoverseContributions: vi.fn(),
+ listEidoverseControllers: vi.fn(),
recordEidoverseFoundation: vi.fn(),
packageEidoverseFoundationCandidate: vi.fn(),
promoteEidoverseFoundation: vi.fn(),
@@ -19,7 +19,7 @@ vi.mock('../../services/api', () => ({
}));
import {
- getEidoverseContributions,
+ listEidoverseControllers,
listEidoverseFoundations,
promoteEidoverseFoundation,
recordEidoverseFoundation,
@@ -33,8 +33,8 @@ const foundation = (overrides = {}) => ({
kind: 'controller',
title: 'Tide Beacon',
summary: 'A beacon that keeps pulsing between mind wakes.',
- contributionId: 'beacon-relay-demo',
- body: { affordance: { inspect: 'reads the pulse count' } },
+ contributionId: 'controller:ambient-beacon',
+ body: { controller: { definitionId: 'ambient-beacon', config: {} } },
style: { motif: 'weathered brass' },
assay: null,
candidate: null,
@@ -77,7 +77,7 @@ afterEach(() => { vi.clearAllMocks(); });
describe('the Eidoverse foundations promote panel', () => {
it('shows a refused promote as a refusal with its reasons, and leaves the layer where it was', async () => {
listEidoverseFoundations.mockResolvedValue(listing([foundation()]));
- getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ listEidoverseControllers.mockResolvedValue({ available: [{ id: 'ambient-beacon', title: 'Ambient beacon', summary: 'Pulses.', exampleConfig: { pulseEveryTicks: 6 } }] });
// A 200 carrying a refusal — the shape the route deliberately returns so
// the reasons reach the author instead of a generic failure.
promoteEidoverseFoundation.mockResolvedValue({
@@ -99,7 +99,7 @@ describe('the Eidoverse foundations promote panel', () => {
listEidoverseFoundations
.mockResolvedValueOnce(listing([foundation()]))
.mockResolvedValue(listing([foundation({ layer: 'baseline', promotedAt: '2026-03-04T06:00:00.000Z' })], { vernacular: 0, baseline: 1, candidates: 1 }));
- getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ listEidoverseControllers.mockResolvedValue({ available: [{ id: 'ambient-beacon', title: 'Ambient beacon', summary: 'Pulses.', exampleConfig: { pulseEveryTicks: 6 } }] });
promoteEidoverseFoundation.mockResolvedValue({ outcome: 'promoted', promoted: true, reasons: [], findings: [] });
await renderPanel();
@@ -116,7 +116,6 @@ describe('the Eidoverse foundations promote panel', () => {
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();
@@ -131,7 +130,6 @@ describe('the Eidoverse foundations promote panel', () => {
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();
@@ -139,13 +137,12 @@ describe('the Eidoverse foundations promote panel', () => {
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'] });
+ listEidoverseControllers.mockResolvedValue({ available: [{ id: 'ambient-beacon', title: 'Ambient beacon', summary: 'Pulses.', exampleConfig: { pulseEveryTicks: 6 } }] });
await renderPanel();
fireEvent.change(screen.getByLabelText('Id (lowercase slug)'), { target: { value: 'tide-beacon' } });
fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Tide Beacon' } });
fireEvent.change(screen.getByLabelText('Summary'), { target: { value: 'A beacon.' } });
- fireEvent.change(screen.getByLabelText('Resilience-assay contribution'), { target: { value: 'beacon-relay-demo' } });
fireEvent.change(screen.getByLabelText('Body — the promotable substance'), { target: { value: '{ not json' } });
await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Record locally' })); });
@@ -153,20 +150,39 @@ describe('the Eidoverse foundations promote panel', () => {
expect(recordEidoverseFoundation).not.toHaveBeenCalled();
});
- it('says so when this install registers no replayable contribution, rather than offering an empty picker', async () => {
+ it('never offers a contribution to bind a foundation to, and seeds the body from a shipped controller instead (#7625)', async () => {
+ // The field that used to sit here let the author name what the promote gate
+ // would replay, and naming a shipped fixture was sufficient to pass. What
+ // an author needs now is the body itself, so the picker fills it in.
listEidoverseFoundations.mockResolvedValue(listing([]));
- // An empty ARRAY is "nothing is registered" — a different state from a
- // failed fetch, and the one that makes the promote gate unreachable.
- getEidoverseContributions.mockResolvedValue({ contributions: [] });
+ listEidoverseControllers.mockResolvedValue({ available: [{ id: 'ambient-beacon', title: 'Ambient beacon', summary: 'Pulses.', exampleConfig: { pulseEveryTicks: 6 } }] });
await renderPanel();
- expect(screen.getByText(/registers no replayable contribution/)).toBeInTheDocument();
+ expect(screen.queryByLabelText('Resilience-assay contribution')).not.toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Kind'), { target: { value: 'controller' } });
+ fireEvent.change(screen.getByLabelText('Controller definition'), { target: { value: 'ambient-beacon' } });
+
+ expect(screen.getByLabelText('Body — the promotable substance')).toHaveValue(
+ JSON.stringify({ controller: { definitionId: 'ambient-beacon', config: { pulseEveryTicks: 6 } } }, null, 2),
+ );
+ });
+
+ it('says so when this install ships no controller definition, rather than offering an empty picker', async () => {
+ listEidoverseFoundations.mockResolvedValue(listing([]));
+ // An empty ARRAY is "none is shipped" — a different state from a failed
+ // fetch, and the one that makes a `controller` foundation unreachable.
+ listEidoverseControllers.mockResolvedValue({ available: [] });
+ await renderPanel();
+
+ fireEvent.change(screen.getByLabelText('Kind'), { target: { value: 'controller' } });
+ expect(screen.getByText(/ships no controller definition/)).toBeInTheDocument();
});
it('marks a local copy of a peer foundation as Inherited and hides the promote/run-assay actions a re-share would need (#7461)', async () => {
const inherited = inheritedFoundation();
listEidoverseFoundations.mockResolvedValue(listing([inherited], { vernacular: 0, baseline: 1, candidates: 0, inherited: 1 }));
- getEidoverseContributions.mockResolvedValue({ contributions: ['beacon-relay-demo'] });
+ listEidoverseControllers.mockResolvedValue({ available: [{ id: 'ambient-beacon', title: 'Ambient beacon', summary: 'Pulses.', exampleConfig: { pulseEveryTicks: 6 } }] });
await renderPanel();
expect(screen.getByText('Inherited')).toBeInTheDocument();
@@ -185,7 +201,6 @@ describe('the Eidoverse foundations promote panel', () => {
*/
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();
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 77303514eb..38b212db76 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -120,7 +120,6 @@ export const projectEidoverseWorld = (options = {}) => request('/eidoverse/world
// refusal verdict when a gate says no, so callers read `outcome` rather than
// treating a rejection as the failure signal.
export const listEidoverseFoundations = (options) => request('/eidoverse/world/foundations', options);
-export const getEidoverseContributions = (options) => request('/eidoverse/world/contributions', options);
export const recordEidoverseFoundation = (payload, options = {}) => request('/eidoverse/world/foundations', {
method: 'POST',
body: JSON.stringify(payload),
diff --git a/docs/API.md b/docs/API.md
index 511a3a6356..c442ab6528 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -367,7 +367,6 @@ federate world records.
| 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 b0e8585441..bbce8e1bd4 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -682,10 +682,12 @@ skips it; only `eidoverseResilienceAssay.test.js` exercises it, proving the
harness catches the "author-mind-only" failure mode).
This harness is what the promote gate below runs:
-`services/eidoverseFoundationLedger.js` replays a foundation's declared
-contribution through `runResilienceAssay()` and refuses to package a promote
-candidate on a failing verdict ([#7455](https://github.com/atomantic/PortOS/issues/7455)).
-Both the CLI and that gate resolve contributions through the one registry in
+`services/eidoverseFoundationLedger.js` replays a foundation through
+`runResilienceAssay()` and refuses to package a promote candidate on a failing
+verdict ([#7455](https://github.com/atomantic/PortOS/issues/7455)). Since #7625
+the gate builds that contribution from the foundation's OWN body
+(`server/lib/eidoverseFoundationSandbox.js`) rather than resolving one by id;
+the CLI still sweeps the shipped fixtures through the registry in
`server/services/eidoverseResilienceContributions.js`.
### Local vernacular vs shared baseline, and the promote gate (#7455)
@@ -722,32 +724,60 @@ is the install-local ledger — machine-local like `portos-world.json` beside it
never federated, no seed file and no migration, since an absent file is the empty
ledger every install starts from.
-**The promote gate runs the assay; it never accepts a verdict.**
-`POST /api/eidoverse/world/foundations/:id/candidate` resolves the foundation's
-declared `contributionId` through `server/services/eidoverseResilienceContributions.js`
-(by id against a fixed directory — never by a caller-supplied module path),
-replays it through the agent-free harness above, and packages against the verdict
-it just produced. A caller therefore cannot assert that its build survived its
+**The promote gate runs the assay against the foundation's OWN body; it never
+accepts a verdict and never replays something the author merely named.**
+`POST /api/eidoverse/world/foundations/:id/candidate` DERIVES the sandbox from
+`body` through `server/lib/eidoverseFoundationSandbox.js` (#7625), replays it
+through the agent-free harness above, and packages against the verdict it just
+produced.
+
+Until #7625 the binding was a single author-supplied string: `contributionId`
+was free text, it resolved against the shipped fixture directory, and naming a
+shipped fixture was *sufficient* to clear the gate. A local build could promote —
+and be offered to every federated peer — on evidence that described the demo
+fixture rather than the body inside the envelope. `contributionId` is now
+**derived** (`controller:<definitionId>`, or `<kind>:<id>`) and is not accepted
+on any authoring surface: not the route body, not `eidoverse.record`, not the
+panel. A receiving peer re-derives it from the envelope's own `kind`/`body` and
+refuses one whose evidence is about something else.
+
+One derivation per declared kind, each refusing a body it cannot interpret —
+which is the honest answer, because a declaration nobody but its author can
+replay is not promotable:
+
+| kind | what gets replayed |
+| --- | --- |
+| `controller` | the shipped definition named by `body.controller.definitionId`, run against **this install's** `body.controller.config` through the definition's own `configSchema`. Upstream's `exampleConfig` proves only that upstream's example survives. |
+| `district-template` | the declared `body.placement` must reproduce from its own `{ layoutId, anchor, propCount, seed, facing }` via `generateDistrictTemplatePlacement()`, and the body is the harness's projection source — a template's consequence is its projection plan. |
+| `schema` / `affordance` | the declarative interpreter: a clean world state is built from `body.schema`'s declared field types and every `body.affordance` verb is resolved against it each tick. An affordance recorded as prose (`{ inspect: 'reads the pulse count' }`) is refused; it has to declare `{ reads, writes }` over fields `body.schema` declares. |
+
+The executable part stays shipped code in every case, so this adds no
+arbitrary-code-execution surface — what varies is the declarative input the
+install actually authored. A caller therefore cannot assert that its build survived its
author's absence; it can only ask for the check — the same proposal-versus-
consequence separation the construction tools got in #7454, applied to promotion.
A foundation that is re-authored loses both its candidate and its verdict, because
both described the previous body; a refused package likewise clears any candidate
packaged earlier, since the verdict that vouched for it no longer holds.
-Contributions are resolved **by id against a fixed directory**, which today holds
-only the two reference fixtures shipped with the assay harness. So on a stock
-install the endpoint can package a candidate for the demo contribution and
-nothing else — a real author gets "no resilience-assay contribution is
-registered" until executable world controllers (#7456) add their registry as a
-second source behind the same resolver.
+`server/services/eidoverseResilienceContributions.js` still resolves the shipped
+fixtures **by id against a fixed directory** for the CLI and the harness's own
+tests. It is no longer the promote path's resolver, and there is no longer an
+endpoint or mind tool advertising its ids — `GET /api/eidoverse/world/contributions`
+and `eidoverse.contributions` are gone, because a list of ids that were
+sufficient to pass the gate was a list of ways around it. An author choosing a
+`controller` behaviour reads `GET /api/eidoverse/world/controllers` /
+`eidoverse.controllers`, which already project the shipped registry.
Four refusals stand between a local artifact and the shared baseline, and every
one returns a readable reason naming what to fix:
1. **Ownership** — only a `vernacular` foundation is promotable.
-2. **Agent-free resilience** — the verdict must pass, cover the full disturbance
- suite, and be bound to the contribution this foundation names (a passing
- verdict borrowed from another build is refused explicitly).
+2. **Agent-free resilience** — the body must have a derivable sandbox at all, and
+ the verdict must pass, cover the full disturbance suite, and be bound to the
+ label this foundation's own `kind`/`body` derives (a passing verdict borrowed
+ from another build is refused explicitly, on both the packaging and the
+ receiving side).
3. **Style leak** — a vernacular style key inside `body`.
4. **Federation safety** — `server/lib/federationSafety.js` refuses the package
when the candidate carries machine identity, network info, PII,
@@ -804,9 +834,10 @@ aged out of the capped list is likewise final.
foundation with its ownership-layer badge, records or re-authors one, runs the
assay, promotes, and renders each refusal reason verbatim beside the foundation
it refused. The expanded foundation is a `?foundation=<id>` search param, so a
-refusal is linkable. `GET /api/eidoverse/world/contributions` backs the
-contribution picker — an install that registers none says so rather than offering
-an empty list.
+refusal is linkable. The form has no contribution field: it seeds the `body` per
+kind and, for a `controller`, fills it from a shipped definition read off
+`GET /api/eidoverse/world/controllers` — an install that ships none says so
+rather than offering an empty picker.
**The mind needs its own grant to promote.** `eidoverse.promote` (with the read
beside it, `eidoverse.foundations`) is gated on `manageEidoverse` **and** the
@@ -823,8 +854,10 @@ same `recordEidoverseFoundation()` the HTTP route above uses, gated on
`manageEidoverse` alone (no promote grant needed — authoring stays local by
construction) and mind-scope only. `authorKind` is stamped `'mind'` server-side
regardless of what the call arguments claim, the same reason `layer` is never
-caller-supplied. `eidoverse.contributions` (`manageEidoverse`, read) lists the
-`contributionId` values a new foundation may bind to before it is promotable.
+caller-supplied — and, since #7625, the same reason `contributionId` is not
+accepted either: a mind that could name what the gate replays could point it at a
+shipped demo. `eidoverse.controllers` (`manageEidoverse`, read) is what a mind
+reads first, for the `definitionId` values a `controller` body may name.
### Provenance graph and inheritance edges (#7461)
@@ -989,7 +1022,18 @@ 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` (v3) is the
+**Compatibility.** The envelope's `candidateVersion` is **v3** as of #7625. The
+bump is semantic rather than structural: a pre-v3 envelope's assay evidence was
+recorded against a contribution its author named, with no required relationship
+to the body travelling beside it, so there is nothing to upgrade — the accept
+side refuses v1 and v2 outright with that reason rather than inheriting on
+them. Migration `scripts/migrations/397-eidoverse-foundation-derived-assay.js`
+does the local half: it re-derives every record's binding label, drops the
+verdicts the old replay produced, and returns an unreplayable `baseline`
+foundation to `vernacular` with `promotedAt: null` — exactly what the ledger
+already does when a body is re-authored, for exactly the same reason.
+
+`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
@@ -1187,10 +1231,10 @@ there is no await for a network, disk, or provider call to hide behind. Root
property of the tick path rather than a convention — boot arms a timer and
nothing else. The same synchronous rule is why every shipped controller is
replayable by the agent-free assay with no extra authoring: the controller
-registry is the assay's **second contribution source**, behind the same
-`findContributionById` resolver, so a `controller` foundation can name its
-controller's id as its `contributionId` and be gated for promotion on evidence
-it still runs with its author gone.
+registry is both the assay CLI's second contribution source and what a
+`controller` foundation's promote gate resolves `body.controller.definitionId`
+against — replaying the definition against **this install's own config**, so the
+evidence is about the controller this install actually configured.
**Effects are proposals, from a closed vocabulary.** A step returns effects, it
does not perform them — the same proposal-versus-consequence separation the
diff --git a/scripts/eidoverse-resilience-assay.js b/scripts/eidoverse-resilience-assay.js
index 0510dcce05..cb6a5f2c49 100644
--- a/scripts/eidoverse-resilience-assay.js
+++ b/scripts/eidoverse-resilience-assay.js
@@ -9,9 +9,11 @@
* node scripts/eidoverse-resilience-assay.js
* Runs every registered contribution — the shipped fixtures AND every
* executable world controller (#7456), both resolved through
- * server/services/eidoverseResilienceContributions.js, which the promote
- * path in eidoverseFoundationLedger.js resolves through as well, by
- * contribution id rather than by path.
+ * server/services/eidoverseResilienceContributions.js by contribution id
+ * rather than by path. The promote path no longer shares this resolver:
+ * since #7625 it derives its sandbox from the foundation's own body
+ * (server/lib/eidoverseFoundationSandbox.js), so naming a fixture listed
+ * here can no longer clear the gate.
*
* node scripts/eidoverse-resilience-assay.js <module-path> [...more]
* Runs the assay against specific contribution modules instead. Each
diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.js
index 62d42e085a..51e7c3a64c 100644
--- a/scripts/lib/migrationOwnedPaths.js
+++ b/scripts/lib/migrationOwnedPaths.js
@@ -30,4 +30,9 @@ export const MIGRATION_OWNED_PATHS = new Set([
'cos/quota-burn.pre-359.json',
// Migration 370 preserves this install's managed Tailcat serve consent/key.
'tailcat-serve.json',
+ // Migration 397 re-binds this install's own Eidoverse foundations to
+ // body-derived assay evidence (#7625). Every record in it is the user's own
+ // authored (or peer-inherited) work; a shipped seed would land first and the
+ // migration would rewrite shipped defaults where their ledger should be.
+ 'eidoverse/foundations.json',
]);
diff --git a/scripts/migrations/397-eidoverse-foundation-derived-assay.js b/scripts/migrations/397-eidoverse-foundation-derived-assay.js
new file mode 100644
index 0000000000..94211c1cad
--- /dev/null
+++ b/scripts/migrations/397-eidoverse-foundation-derived-assay.js
@@ -0,0 +1,96 @@
+/**
+ * Re-bind every Eidoverse foundation to evidence about its OWN body (#7625).
+ *
+ * Until now the agent-free resilience assay replayed whatever module the author
+ * named in `contributionId` — free text on the authoring surface — so a
+ * foundation could promote to `baseline`, and be offered to every federated
+ * peer, on a passing verdict that described a shipped demo fixture rather than
+ * the body inside the envelope. The gate now derives the sandbox from `body`
+ * (`server/lib/eidoverseFoundationSandbox.js`), which makes every verdict
+ * recorded before this release evidence about the wrong object.
+ *
+ * So each record is rewritten the same way the ledger already rewrites one that
+ * is re-authored, and for the identical reason — the verdict no longer
+ * describes the body:
+ *
+ * - `contributionId` is replaced with the label the record's own kind/body
+ * derives, so the binding check reads true for the right reason.
+ * - a record whose body has no derivable sandbox drops `assay` and
+ * `candidate` and, if it was `baseline` and locally authored, returns to
+ * `vernacular` with `promotedAt: null`. It is local work again until
+ * somebody re-authors a replayable body and promotes it.
+ * - a record that IS derivable still drops `assay`/`candidate`, because the
+ * stored verdict was produced by the old replay. Re-running the assay is a
+ * click (or one `eidoverse.promote` call) and is the honest way to get the
+ * new one; synthesizing a pass here would repeat the exact mistake.
+ * - an INHERITED copy (`peer:<origin>:<id>`) is left alone but de-promoted in
+ * the same sense: its candidate is a pre-v3 envelope this install would now
+ * refuse, so it is dropped and the copy stops being offered or trusted.
+ *
+ * `data/eidoverse/foundations.json` is machine-local and ships NO
+ * `data.reference/` seed (see `scripts/lib/migrationOwnedPaths.js`), so this
+ * gates on the INPUT's presence — an install that never authored a foundation
+ * has nothing to migrate and writes nothing.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { derivedContributionId } from '../../server/lib/eidoverseFoundations.js';
+import { foundationSandbox } from '../../server/lib/eidoverseFoundationSandbox.js';
+import { findControllerDefinitionById } from '../../server/services/eidoverseControllerRegistry.js';
+
+export default {
+ async up({ rootDir }) {
+ const file = join(rootDir, 'data', 'eidoverse', 'foundations.json');
+ const raw = await readFile(file, 'utf-8').catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (raw === null) return { updated: 0, reason: 'no-foundation-ledger' };
+
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (error) {
+ // A ledger this process cannot parse must not be replaced with an empty
+ // one — the same rule `readFoundations()` enforces at runtime.
+ console.warn(`⚠️ migration 397: data/eidoverse/foundations.json is unreadable (${error.message}); leaving it untouched`);
+ return { updated: 0, reason: 'unreadable-ledger' };
+ }
+ const foundations = parsed?.foundations;
+ if (!foundations || typeof foundations !== 'object') return { updated: 0, reason: 'no-foundation-ledger' };
+
+ let rewritten = 0;
+ let dePromoted = 0;
+ for (const [key, record] of Object.entries(foundations)) {
+ if (!record || typeof record !== 'object') continue;
+ const hadEvidence = Boolean(record.assay || record.candidate);
+ const next = { ...record, assay: null, candidate: null };
+
+ if (record.inheritance) {
+ // An inherited copy keeps the origin's label: this install never
+ // replayed it and must not start now (replaying a peer's body is what
+ // the assay harness exists to keep off every other install).
+ if (hadEvidence) { foundations[key] = next; rewritten += 1; }
+ continue;
+ }
+
+ next.contributionId = derivedContributionId({ kind: record.kind, id: record.id, body: record.body });
+ const { refusal } = await foundationSandbox(record, { findControllerDefinition: findControllerDefinitionById });
+ if (refusal && record.layer === 'baseline') {
+ next.layer = 'vernacular';
+ next.promotedAt = null;
+ dePromoted += 1;
+ }
+ if (hadEvidence || next.contributionId !== record.contributionId || next.layer !== record.layer) {
+ foundations[key] = next;
+ rewritten += 1;
+ }
+ }
+
+ if (rewritten === 0) return { updated: 0, reason: 'already-derived' };
+ await writeFile(file, `${JSON.stringify({ ...parsed, foundations }, null, 2)}\n`);
+ console.log(`🔁 migration 397: re-bound ${rewritten} Eidoverse foundation(s) to body-derived assay evidence (${dePromoted} returned to vernacular)`);
+ return { updated: rewritten, dePromoted };
+ },
+};
diff --git a/scripts/migrations/397-eidoverse-foundation-derived-assay.test.js b/scripts/migrations/397-eidoverse-foundation-derived-assay.test.js
new file mode 100644
index 0000000000..4e75fbd0e0
--- /dev/null
+++ b/scripts/migrations/397-eidoverse-foundation-derived-assay.test.js
@@ -0,0 +1,115 @@
+/**
+ * The de-promotion this migration owes installs that crossed #7625.
+ *
+ * Every record in `data/eidoverse/foundations.json` carries assay evidence
+ * produced by the OLD replay — a verdict about whatever module the author
+ * named. What matters is that a foundation whose body cannot be replayed stops
+ * being `baseline` (and so stops being offered to peers) while a replayable one
+ * keeps its place and only loses the stale verdict.
+ */
+
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import migration from './397-eidoverse-foundation-derived-assay.js';
+
+const roots = [];
+const makeRoot = () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-migration-397-'));
+ roots.push(root);
+ mkdirSync(join(root, 'data', 'eidoverse'), { recursive: true });
+ return root;
+};
+const ledgerPath = (root) => join(root, 'data', 'eidoverse', 'foundations.json');
+const writeLedger = (root, foundations) => writeFileSync(ledgerPath(root), JSON.stringify({ schemaVersion: 1, foundations }, null, 2));
+const readLedger = (root) => JSON.parse(readFileSync(ledgerPath(root), 'utf8')).foundations;
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+const base = (overrides) => ({
+ id: 'tide-beacon',
+ layer: 'baseline',
+ kind: 'controller',
+ title: 'Tide Beacon',
+ summary: 'A beacon that keeps pulsing.',
+ contributionId: 'beacon-relay-demo',
+ body: {},
+ style: {},
+ provenance: { originInstanceId: 'instance-aaaa', authorKind: 'mind', createdAt: '2026-03-01T00:00:00.000Z' },
+ disclosure: { requires: [], effects: [], license: null, notes: null },
+ assay: { harness: 'eidoverse-resilience-assay', contributionId: 'beacon-relay-demo', pass: true, disturbances: ['reconnect'], ranAt: '2026-03-01T00:00:00.000Z', reasons: [] },
+ candidate: { candidateVersion: 1, foundationId: 'tide-beacon' },
+ promotedAt: '2026-03-01T01:00:00.000Z',
+ inheritance: null,
+ updatedAt: '2026-03-01T00:00:00.000Z',
+ ...overrides,
+});
+
+describe('migration 397 — re-bind foundations to body-derived assay evidence', () => {
+ it('writes nothing on an install that never authored a foundation', async () => {
+ const root = makeRoot();
+ expect(await migration.up({ rootDir: root })).toMatchObject({ updated: 0, reason: 'no-foundation-ledger' });
+ });
+
+ it('returns an unreplayable baseline foundation to vernacular and drops its evidence', async () => {
+ const root = makeRoot();
+ // The canonical pre-#7625 record: it named a shipped demo fixture and its
+ // body describes something else, so nothing here can replay it.
+ writeLedger(root, { 'tide-beacon': base({ body: { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } } }) });
+
+ const result = await migration.up({ rootDir: root });
+
+ expect(result).toMatchObject({ updated: 1, dePromoted: 1 });
+ expect(readLedger(root)['tide-beacon']).toMatchObject({
+ layer: 'vernacular', promotedAt: null, assay: null, candidate: null, contributionId: 'controller:tide-beacon',
+ });
+ });
+
+ it('keeps a replayable foundation in the baseline but drops the verdict the old replay produced', async () => {
+ const root = makeRoot();
+ writeLedger(root, { 'tide-beacon': base({ body: { controller: { definitionId: 'ambient-beacon', config: { pulseEveryTicks: 3 } } } }) });
+
+ const result = await migration.up({ rootDir: root });
+
+ expect(result).toMatchObject({ updated: 1, dePromoted: 0 });
+ expect(readLedger(root)['tide-beacon']).toMatchObject({
+ layer: 'baseline', promotedAt: '2026-03-01T01:00:00.000Z', assay: null, candidate: null, contributionId: 'controller:ambient-beacon',
+ });
+ });
+
+ it('drops an inherited copy\'s v1 envelope without relabelling or replaying a peer\'s body', async () => {
+ const root = makeRoot();
+ const key = 'peer:instance-bbbb:tide-beacon';
+ writeLedger(root, {
+ [key]: base({
+ provenance: { originInstanceId: 'instance-bbbb', authorKind: 'mind', createdAt: '2026-03-01T00:00:00.000Z' },
+ inheritance: { type: 'inherited-from', originInstanceId: 'instance-bbbb', foundationId: 'tide-beacon', fingerprint: 'a'.repeat(64), packagedAt: '2026-03-01T01:00:00.000Z', sourceInstanceId: 'instance-cccc', inheritedAt: '2026-03-02T00:00:00.000Z' },
+ promotedAt: null,
+ }),
+ });
+
+ await migration.up({ rootDir: root });
+
+ const stored = readLedger(root)[key];
+ expect(stored).toMatchObject({ layer: 'baseline', assay: null, candidate: null, contributionId: 'beacon-relay-demo' });
+ });
+
+ it('is idempotent — a second run finds nothing left to re-bind', async () => {
+ const root = makeRoot();
+ writeLedger(root, { 'tide-beacon': base({ body: { controller: { definitionId: 'ambient-beacon', config: {} } } }) });
+
+ await migration.up({ rootDir: root });
+ expect(await migration.up({ rootDir: root })).toMatchObject({ updated: 0, reason: 'already-derived' });
+ });
+
+ it('leaves an unparseable ledger untouched rather than replacing it with an empty one', async () => {
+ const root = makeRoot();
+ writeFileSync(ledgerPath(root), '{ truncated mid-write');
+
+ expect(await migration.up({ rootDir: root })).toMatchObject({ updated: 0, reason: 'unreadable-ledger' });
+ expect(readFileSync(ledgerPath(root), 'utf8')).toBe('{ truncated mid-write');
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 7de9ae9800..736139e1d4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -604,7 +604,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `secretKeys.js` | `isSecretKey(key)` — does a payload KEY name hold a credential (`api_key`/`apiKey`/`API-KEY` all normalize to `apikey`; a trailing `Key`/`Keys` counts; short names like `auth`/`env` match only whole). The key-side half of the pair whose value side is `secretText.js#scrubSecretTokens`. Split out of `services/userActions.js` so `lib/federationSafety.js` can reach it; deliberate over-redaction (losing `tokenCount` beats shipping `refreshToken`). |
| `eidoverseCreativeToolkit.js` | The documented creative toolkit for minds building Eidoverse vernacular content (#7459, wired end-to-end in #7627): a closed catalog of `EIDOVERSE_CREATIVE_MATERIALS` and `EIDOVERSE_CREATIVE_MOTIFS` (cosmetics — style-layer only) plus `EIDOVERSE_CREATIVE_LAYOUTS` (named generative placement algorithms — `radial-ring`/`grid-plot`/`arc-row`/`grove-cluster`). `generateDistrictTemplatePlacement` is deterministic and seeded (mulberry32, no `Math.random`, no AI call) so the same `{layoutId, anchor, seed}` always reproduces the same geometry — `services/eidoverseFoundationLedger.js`'s `recordEidoverseFoundation()` replays it server-side to derive a `district-template`'s `body.placement`, never trusting a caller-supplied one. `buildDistrictTemplateAugmentOperations` turns a placement into ready-to-submit `eidoverse.augment` `spawn` operations (the `eidoverse.place-layout` tool); `buildDistrictTemplateFoundationDraft` shapes a placement plus a material/motif choice into an `eidoverseFoundationInputSchema`-ready `district-template` input, keeping the generative substance in `body` and the material/motif cosmetics in `style` (the `eidoverse.draft-foundation` tool). `describeCreativeCatalog()` is the prompt-safe catalog projection, including each material's `colorHex`. Pure: no I/O, no clock, no provider calls. |
| `eidoverseControllers.js` | Executable Eidoverse world controllers — the install schema and the sandboxed step boundary (#7456). `eidoverseControllerInstallSchema` / `eidoverseControllerRecordSchema` describe an install (a registry `controllerId`, a bounded `config`, a `tickIntervalMs`, and a `deliverEffects` flag that is FALSE by default, so installing arms bookkeeping and never a world verb). `runControllerStep` is the sandbox: it hands the controller JSON copies of its state and config, REFUSES a step that returns a Promise (an await is the shape every network/disk/AI-provider call takes, so the tick path is provider-free structurally rather than by convention), caps the state it may return, and validates its effects against a closed vocabulary — `note` (never leaves the ledger), `say`, and `augment`, which reuses `eidoverseValidation.js`'s own world-verb operation schema. `controllerTickDue` / `nextControllerTickAt` are the scheduling math, measured from now so a machine that slept wakes to ONE tick and not a replayed backlog. `summarizeControllerInstall` is the prompt-shaped projection that keeps a 16KB state blob out of a mind turn; it surfaces `derivedFrom`, the edge an install adopted from a peer's foundation carries (#7626). Pure: callers pass `now`. |
-| `eidoverseFoundations.js` | Local-vs-baseline ownership for Eidoverse world foundations and the promote-candidate packaging gate (#7455). `EIDOVERSE_FOUNDATION_LAYERS` (`runtime` / `baseline` / `vernacular`, defaulting to `vernacular` so nothing is shared by omission) and `layerPromoteRefusal`; the record / input / candidate-envelope Zod schemas, where a foundation is `{ body, style }` BY CONSTRUCTION — packaging carries `body` and drops `style`, so an inheriting peer never receives its author's cosmetics, and `styleLeakFindings` REFUSES an unambiguously cosmetic key smuggled into `body` (spatial/asset keys stay allowed — they are a district template's substance). `assayEvidenceFromVerdict` folds an agent-free resilience verdict (#7460) into the evidence the gate reads, including the binding that it ran against the contribution this foundation names. `packageFoundationCandidate` and `verifyFoundationCandidate` are the one gate seen from the sending and receiving sides, over a content-addressed `fingerprint` hashed from the payload AS SENT; federation safety comes from `federationSafety.js`. `summarizeFoundation` is the prompt-shaped projection of a ledger record (layer, identity, assay outcome, whether a candidate exists) that keeps the local style layer and the packaged envelope out of a mind turn, and `detailFoundation` is its read-ONE counterpart, adding the `body` and `disclosure` the list deliberately omits (#7626). `eidoverseFoundationTargetSchema` + `foundationLedgerKey` are how a caller NAMES one record — `{ id, originInstanceId }`, where the origin addresses a local copy of a peer's foundation without making the internal `peer:<origin>:<id>` storage key user-typeable. `planFoundationAdoption` decides, per kind, what ADOPTING an inherited foundation means: a `controller` yields a disarmed install of the shipped controller its body names plus a `derived-from` edge, while `schema` / `affordance` / `district-template` are refused by name rather than silently succeeding. Pure: callers pass `now`. |
+| `eidoverseFoundations.js` | Local-vs-baseline ownership for Eidoverse world foundations and the promote-candidate packaging gate (#7455). `EIDOVERSE_FOUNDATION_LAYERS` (`runtime` / `baseline` / `vernacular`, defaulting to `vernacular` so nothing is shared by omission) and `layerPromoteRefusal`; the record / input / candidate-envelope Zod schemas, where a foundation is `{ body, style }` BY CONSTRUCTION — packaging carries `body` and drops `style`, so an inheriting peer never receives its author's cosmetics, and `styleLeakFindings` REFUSES an unambiguously cosmetic key smuggled into `body` (spatial/asset keys stay allowed — they are a district template's substance). `assayEvidenceFromVerdict` folds an agent-free resilience verdict (#7460) into the evidence the gate reads, including the binding that it ran against the contribution this foundation names. `packageFoundationCandidate` and `verifyFoundationCandidate` are the one gate seen from the sending and receiving sides, over a content-addressed `fingerprint` hashed from the payload AS SENT; federation safety comes from `federationSafety.js`. `summarizeFoundation` is the prompt-shaped projection of a ledger record (layer, identity, assay outcome, whether a candidate exists) that keeps the local style layer and the packaged envelope out of a mind turn, and `detailFoundation` is its read-ONE counterpart, adding the `body` and `disclosure` the list deliberately omits (#7626). `eidoverseFoundationTargetSchema` + `foundationLedgerKey` are how a caller NAMES one record — `{ id, originInstanceId }`, where the origin addresses a local copy of a peer's foundation without making the internal `peer:<origin>:<id>` storage key user-typeable. `planFoundationAdoption` decides, per kind, what ADOPTING an inherited foundation means: a `controller` yields a disarmed install of the shipped controller its body names plus a `derived-from` edge, while `schema` / `affordance` / `district-template` are refused by name rather than silently succeeding. Pure: callers pass `now`. `derivedContributionId({ kind, id, body })` and `controllerDefinitionIdFromBody(body)` derive the assay binding label from the record itself, so neither an author nor a sending peer can name it (#7625); they live here rather than beside the sandbox that replays the body because the sandbox reaches this module through the creative toolkit. |
+| `eidoverseFoundationSandbox.js` | Derives the agent-free resilience-assay sandbox for a foundation FROM ITS OWN BODY (#7625), closing the hole where the promote gate replayed whatever module the author named in a free-text `contributionId`. `foundationSandbox({ kind, id, body }, { findControllerDefinition })` returns the `{ id, createSandbox, invariants }` contribution `runResilienceAssay()` consumes, or a reader-facing refusal. One derivation per declared kind: `controller` replays the shipped definition named by `body.controller.definitionId` against THIS INSTALL'S `body.controller.config` (not upstream's `exampleConfig`); `district-template` requires `body.placement` to reproduce from its own layout/anchor/seed through `generateDistrictTemplatePlacement` and hands the body to the harness as the projection source; `schema`/`affordance` are replayed by the declarative interpreter over `EIDOVERSE_DECLARED_FIELD_TYPES`, which refuses an affordance recorded as prose rather than as `{ reads, writes }` over declared fields. The binding label both the packaging side and a receiving peer re-derive is computed by `derivedContributionId` in `eidoverseFoundations.js`, which declares the schema that carries it (and which this module would otherwise import in a cycle, via the creative toolkit). Executes only code PortOS ships; no caller-supplied path is ever resolved. Pure apart from the injected definition lookup. |
| `eidoverseObservation.js` | Pure observation-first discovery report for the Eidoverse (#7457) — the read behind `eidoverse.observe`. `buildEidoverseObservation` turns already-collected snapshots (world signals, the install's RESOLVED design districts/includes, the foundation ledger, summarized controller installs) plus the previously persisted visit marker into `{ report, marker }`: districts as places a mind can describe, peers keyed to the foundations inherited through each, a peer contribution's origin/arrival instances, controllers filtered to the ones actually failing, and a `changes` diff against the last visit. Places come from the recipe rather than a constant, so a mind never names a district a later design version renamed; an unreadable source stays `null` and a recipe-disabled one reports `disabled`, neither collapsing to `0`; a first observation reports `firstObservation` rather than declaring a settled world new; and places diff on status flips only so routine signal churn never becomes noise. Scalar-vs-list source shape is shared with the projection via `EIDOVERSE_SCALAR_SOURCE_KEYS`. Pure: the caller passes `observedAt` and decides whether to commit the returned marker. |
| `eidoverseWorldDesign.js` | Immutable Eidoverse World Design V1/V2/V3 registry, override migration, semantic districts, 48-signal ceiling, and install-local asset locks for PortOS Commons. |
| `eidoverseWorldLabels.js` | The `comp.label` component PortOS attaches to every entity it projects into Eidoverse (eidoverse-worlds#5), so a rendered building says what it represents instead of only naming its decorative model. `buildEidoverseLabel(component, alias?)` reads one already-built `comp.portos` payload and returns `{name, description?, visibility, offset?}` — district and world-identity landmarks always visible, live indicators labelled `nearby`, path markers `inspect`-only so a walkway cannot bury the district it leads to — and `null` for anything not `managedBy: 'portos'`, so a caller cannot label somebody else's entity. Names and descriptions are built from PortOS's own vocabulary (district label, kind label, resource category, coarse status, freshness) plus an opaque hashed resource ref for disambiguation, never from record contents, machine identity, addresses, or filesystem paths — the append-only world log is the strictest privacy boundary PortOS writes to. Also owns bounded opaque-key alias normalization and V1 renderer capability parsing; aliases are explicit opt-in names and are never inferred from private records. Owns `safeWorldText`, the one control-character/length sanitizer shared with `services/eidoverseWorldProjection.js` so a component field and the label built from it cannot disagree about what is safe. Pure. |
diff --git a/server/lib/eidoverseCreativeToolkit.js b/server/lib/eidoverseCreativeToolkit.js
index 572057c3fd..06f0c6064b 100644
--- a/server/lib/eidoverseCreativeToolkit.js
+++ b/server/lib/eidoverseCreativeToolkit.js
@@ -241,9 +241,16 @@ export function buildDistrictTemplateAugmentOperations({ layoutId, anchor, propC
* positions) is the promotable substance and goes in `body`; the material
* and motif choice are cosmetics and go in `style`, exactly as
* `styleLeakFindings` expects.
+ *
+ * The placement is emitted BESIDE the `{ layoutId, anchor, propCount, seed,
+ * facing }` it was generated from, which is what makes the draft promotable:
+ * the promote gate re-derives the placement from those declarations and refuses
+ * one that no longer reproduces (`lib/eidoverseFoundationSandbox.js`, #7625).
+ * There is no `contributionId` to pass — the gate replays this body, so the
+ * binding label is derived from it.
*/
export function buildDistrictTemplateFoundationDraft({
- id, title, summary, contributionId, layoutId, materialId, motifId, anchor, propCount = 6, seed, facing = 0, disclosure,
+ id, title, summary, layoutId, materialId, motifId, anchor, propCount = 6, seed, facing = 0, disclosure,
}) {
const material = requireCatalogEntry(EIDOVERSE_CREATIVE_MATERIALS, materialId, 'material');
const motif = requireCatalogEntry(EIDOVERSE_CREATIVE_MOTIFS, motifId, 'motif');
@@ -254,7 +261,6 @@ export function buildDistrictTemplateFoundationDraft({
kind: 'district-template',
title,
summary,
- contributionId,
body: {
layoutId,
anchor: anchor.map((value) => Number(value)),
@@ -309,15 +315,16 @@ export const eidoversePlaceLayoutInputSchema = z.object({
* `eidoverse.draft-foundation`: compose a layout, material, and motif choice
* into an `eidoverseFoundationInputSchema`-ready `district-template` input,
* ready to pass straight to `eidoverse.record`. The `id`/`title`/`summary`/
- * `contributionId`/`disclosure` fields are lifted from
- * `eidoverseFoundationInputSchema` itself rather than re-declared, so a limit
- * change there cannot silently diverge from what this schema accepts.
+ * `disclosure` fields are lifted from `eidoverseFoundationInputSchema` itself
+ * rather than re-declared, so a limit change there cannot silently diverge
+ * from what this schema accepts. There is no `contributionId`: the promote
+ * gate derives the binding label from the drafted body (#7625), so a drafter
+ * has nothing to name.
*/
export const eidoverseDraftFoundationInputSchema = z.object({
id: eidoverseFoundationInputSchema.shape.id,
title: eidoverseFoundationInputSchema.shape.title,
summary: eidoverseFoundationInputSchema.shape.summary,
- contributionId: eidoverseFoundationInputSchema.shape.contributionId,
disclosure: eidoverseFoundationInputSchema.shape.disclosure,
layoutId: eidoverseCreativeLayoutIdSchema,
materialId: eidoverseCreativeMaterialIdSchema,
diff --git a/server/lib/eidoverseCreativeToolkit.test.js b/server/lib/eidoverseCreativeToolkit.test.js
index f2f117571e..aa5812f019 100644
--- a/server/lib/eidoverseCreativeToolkit.test.js
+++ b/server/lib/eidoverseCreativeToolkit.test.js
@@ -96,7 +96,7 @@ describe('buildDistrictTemplateAugmentOperations', () => {
describe('buildDistrictTemplateFoundationDraft', () => {
const base = {
id: 'garden-arcade', title: 'Garden Arcade', summary: 'A colonnade of lanterns around the arrival plaza.',
- contributionId: 'beacon-relay', materialId: 'sunbaked-clay', motifId: 'lantern-row', anchor: ANCHOR,
+ materialId: 'sunbaked-clay', motifId: 'lantern-row', anchor: ANCHOR,
};
it('parses as a valid eidoverseFoundationInputSchema input, with no style leak in body', () => {
diff --git a/server/lib/eidoverseFoundationSandbox.js b/server/lib/eidoverseFoundationSandbox.js
new file mode 100644
index 0000000000..d073987f97
--- /dev/null
+++ b/server/lib/eidoverseFoundationSandbox.js
@@ -0,0 +1,367 @@
+/**
+ * Derive the agent-free resilience-assay sandbox for a foundation FROM ITS OWN
+ * BODY (#7625, epic #7453).
+ *
+ * The promote gate's whole promise is "a contribution still works without its
+ * creator narrating it". #7460 built the harness and #7455 made the server run
+ * it rather than accept a caller's verdict — but the harness was pointed at
+ * whatever module the author NAMED (`contributionId`, free text on the
+ * authoring surface), never at the foundation being promoted. Any local
+ * foundation could name a shipped demo fixture and inherit its pass; peers then
+ * inherited on evidence that described the fixture, not the body inside the
+ * envelope. This module closes that: the sandbox is derived from `body`, so
+ * "what was evaluated" and "what gets promoted" are the same object by
+ * construction rather than by an author-supplied string.
+ *
+ * **This adds no arbitrary-code-execution surface.** Every executable part is
+ * still code PortOS ships: a `controller` foundation names a SHIPPED controller
+ * definition and supplies only declarative config; the other three kinds are
+ * replayed by the interpreters below, which are ordinary PortOS code. What
+ * varies per install is the declarative input the install actually authored —
+ * which is exactly what the assay needed to be replaying all along.
+ *
+ * One derivation per declared kind:
+ *
+ * - `controller` — `body.controller.definitionId` names a shipped definition
+ * and `body.controller.config` is parsed through that definition's own
+ * `configSchema`. THIS INSTALL'S config is what gets replayed, not
+ * upstream's `exampleConfig`; a broken local config now fails the gate
+ * instead of promoting on evidence about a config nobody runs.
+ * - `district-template` — the declared placement has to REPRODUCE from its
+ * own `{ layoutId, anchor, propCount, seed, facing }` through
+ * `generateDistrictTemplatePlacement()`, and the body is handed to the
+ * harness as the projection source, because a template's consequence is
+ * its projection plan.
+ * - `schema` / `affordance` — replayed through the declarative interpreter
+ * below: a clean world state is built from the declared field types, and
+ * every declared affordance is resolved against it each tick. A declaration
+ * that cannot be interpreted without its author is not promotable, which is
+ * the correct answer rather than a gap.
+ *
+ * `contributionId` survives only as a DERIVED label (`derivedContributionId()`)
+ * so `assayEvidenceRefusal()`'s binding check in `eidoverseFoundations.js` —
+ * "the evidence is about this foundation" — keeps working unchanged, and so a
+ * receiving peer can re-derive it from the envelope's own `kind`/`body` and
+ * catch an envelope whose evidence was minted against something else.
+ *
+ * Pure: no I/O, no clock, no provider calls. `foundationSandbox()` is async
+ * ONLY because resolving a shipped controller definition is; the resolver is
+ * injected so this module never imports the service layer.
+ */
+
+import { canonicalStringify } from './objects.js';
+import { generateDistrictTemplatePlacement } from './eidoverseCreativeToolkit.js';
+// Declared beside the schemas that carry the label rather than here, so this
+// module can keep reaching the creative toolkit without closing an ESM cycle
+// back through it — see `derivedContributionId`'s own note.
+import { controllerDefinitionIdFromBody, derivedContributionId } from './eidoverseFoundations.js';
+
+const isPlainObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+
+const refuse = (refusal) => ({ contribution: null, refusal });
+const accept = (contribution) => ({ contribution, refusal: null });
+
+/**
+ * The declared field-type vocabulary a `schema` foundation may use, and the
+ * interpreter that gives each one a clean starting value, a per-tick successor,
+ * and a conformance check.
+ *
+ * `advance` derives the next value from the TICK ORDINAL rather than from a
+ * clock or a random source, which is what keeps a replay deterministic and
+ * lets the harness's own re-invocation of `createSandbox()` per scenario mean
+ * something. Every sample is JSON-portable, so the harness's built-in
+ * serializability check is a real check and not a formality.
+ */
+export const EIDOVERSE_DECLARED_FIELD_TYPES = Object.freeze({
+ boolean: { sample: () => false, advance: (_prev, tick) => tick % 2 === 0, valid: (value) => typeof value === 'boolean' },
+ id: { sample: () => 'declared-0', advance: (_prev, tick) => `declared-${tick}`, valid: (value) => typeof value === 'string' && value.length > 0 },
+ integer: { sample: () => 0, advance: (prev) => prev + 1, valid: (value) => Number.isInteger(value) },
+ list: { sample: () => [], advance: (prev, tick) => [...prev, tick], valid: (value) => Array.isArray(value) },
+ map: { sample: () => ({}), advance: (prev, tick) => ({ ...prev, [`t${tick}`]: tick }), valid: isPlainObject },
+ number: { sample: () => 0, advance: (prev) => prev + 0.5, valid: (value) => typeof value === 'number' && Number.isFinite(value) },
+ string: { sample: () => 'declared', advance: (_prev, tick) => `tick-${tick}`, valid: (value) => typeof value === 'string' },
+ timestamp: {
+ sample: () => new Date(0).toISOString(),
+ advance: (_prev, tick) => new Date(tick * 1000).toISOString(),
+ valid: (value) => typeof value === 'string' && !Number.isNaN(Date.parse(value)),
+ },
+});
+
+/** The declared field types, sorted, for a reader-facing refusal. */
+const DECLARED_TYPE_NAMES = Object.freeze(Object.keys(EIDOVERSE_DECLARED_FIELD_TYPES).sort());
+
+// ---------------------------------------------------------------------------
+// controller
+// ---------------------------------------------------------------------------
+
+/**
+ * Replay a `controller` foundation through the shipped definition it names,
+ * against the config THIS INSTALL authored.
+ *
+ * `step` and `applyDisturbance` are shaped exactly as
+ * `controllerAssayContributions()` shapes them for the CLI's shipped-controller
+ * sweep, so the assay is replaying the real tick path. The difference — the
+ * whole point of #7625 — is the config: upstream's `exampleConfig` proves
+ * upstream's example survives, which says nothing about an install whose own
+ * config is broken.
+ */
+function controllerSandbox({ body, definition, definitionId, contributionId }) {
+ if (!definitionId) {
+ return refuse('a `controller` foundation must declare `body.controller.definitionId` naming a shipped controller definition — the assay replays the controller this install actually configured, not one it names in prose');
+ }
+ if (!definition) {
+ return refuse(`no shipped controller definition is registered under "${definitionId}" — this install cannot replay the foundation, so it cannot promote it`);
+ }
+ const config = definition.configSchema.safeParse(body.controller.config ?? {});
+ if (!config.success) {
+ const detail = config.error.issues.slice(0, 8).map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`).join('; ');
+ return refuse(`this foundation's own controller config does not satisfy "${definitionId}"'s schema: ${detail}`);
+ }
+
+ return accept({
+ id: contributionId,
+ description: definition.summary,
+ createSandbox() {
+ // Re-parsed per sandbox rather than closing over one parsed object: the
+ // harness re-invokes `createSandbox()` for every scenario precisely so no
+ // state survives between them, and a shared config object would be the
+ // one thing that did.
+ const scenarioConfig = definition.configSchema.parse(body.controller.config ?? {});
+ return {
+ worldState: definition.createState(scenarioConfig),
+ controller: {
+ step: (worldState, tick) => definition.step(worldState, { tick, config: scenarioConfig }).state,
+ // Every disturbance in the suite is an ENVIRONMENT event; a
+ // controller that keeps its durable state in `state` survives all
+ // three, and the round-trip proves it holds no in-process handle.
+ applyDisturbance: (worldState) => JSON.parse(JSON.stringify(worldState)),
+ },
+ projectionSource: {},
+ };
+ },
+ invariants: definition.invariants ?? [],
+ });
+}
+
+// ---------------------------------------------------------------------------
+// district-template
+// ---------------------------------------------------------------------------
+
+const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
+const isAnchor = (value) => Array.isArray(value) && value.length === 3 && value.every(isFiniteNumber);
+
+/**
+ * Replay a `district-template` foundation as its own placement.
+ *
+ * A template's consequence IS its geometry, and the one thing that makes that
+ * geometry author-free is that it re-derives from the declarations beside it.
+ * So the gate is: `generateDistrictTemplatePlacement()` run over the body's own
+ * `{ layoutId, anchor, propCount, seed, facing }` must reproduce
+ * `body.placement` exactly. A template carrying hand-edited coordinates its own
+ * declarations no longer produce is a template only its author can rebuild.
+ *
+ * The body is handed to the harness as `projectionSource`, so the assay's
+ * "load projections in a clean sandbox" leg runs `buildProjectionPlan()`
+ * against the template rather than against an empty object.
+ */
+function districtTemplateSandbox({ body, contributionId }) {
+ const { layoutId, anchor, propCount, seed, facing, placement } = body;
+ if (typeof layoutId !== 'string' || !layoutId.trim()) return refuse('a `district-template` foundation must declare `body.layoutId` — a placement that names no generator cannot be re-derived without its author');
+ if (!isAnchor(anchor)) return refuse('a `district-template` foundation must declare `body.anchor` as three finite numbers');
+ if (!Array.isArray(placement) || placement.length === 0) return refuse('a `district-template` foundation must declare `body.placement` — the geometry the template produces is the thing being promoted');
+
+ const declared = { layoutId: layoutId.trim(), anchor, propCount, seed, facing };
+ let regenerated;
+ try {
+ regenerated = generateDistrictTemplatePlacement(declared);
+ } catch (error) {
+ return refuse(`this template's placement cannot be re-derived from its own declarations: ${error.message}`);
+ }
+ if (canonicalStringify(regenerated) !== canonicalStringify(placement)) {
+ return refuse('`body.placement` does not reproduce from this template\'s own layout, anchor, count, seed and facing — a placement only its author can rebuild is not promotable');
+ }
+
+ return accept({
+ id: contributionId,
+ description: `Declared ${declared.layoutId} district template with ${placement.length} props.`,
+ createSandbox() {
+ return {
+ // `scratch` is deliberately NOT part of the template's declarations —
+ // it is what the `missing-optional-deps` disturbance takes away, so
+ // "the template does not depend on anything it did not declare" is
+ // proven rather than assumed.
+ worldState: { layoutId: declared.layoutId, anchor: [...anchor], props: instantiateProps(placement), tick: null, scratch: { hint: declared.layoutId } },
+ controller: {
+ step(worldState, tick) {
+ return { ...worldState, props: instantiateProps(generateDistrictTemplatePlacement(declared)), tick };
+ },
+ applyDisturbance(worldState, disturbance) {
+ if (disturbance === 'restart-world-host') return JSON.parse(JSON.stringify(worldState));
+ if (disturbance === 'missing-optional-deps') {
+ const { scratch: _gone, ...durable } = worldState;
+ return durable;
+ }
+ return worldState;
+ },
+ },
+ projectionSource: body,
+ };
+ },
+ invariants: [
+ function propsMatchTheDeclaredPlacement(worldState) {
+ const expected = canonicalStringify(instantiateProps(placement));
+ if (canonicalStringify(worldState.props) !== expected) {
+ return { ok: false, reason: 'the replayed props drifted from the declared placement' };
+ }
+ return true;
+ },
+ ],
+ });
+}
+
+/** Declared placement as world props — ids derived from the ordinal, so the
+ * instantiation is as reproducible as the placement it comes from. */
+function instantiateProps(placement) {
+ return placement.map((prop, index) => ({
+ id: `prop-${index}`,
+ pos: Array.isArray(prop?.pos) ? prop.pos.map(Number) : null,
+ yaw: isFiniteNumber(prop?.yaw) ? prop.yaw : null,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// schema / affordance
+// ---------------------------------------------------------------------------
+
+/**
+ * The declarative interpreter behind the `schema` and `affordance` kinds.
+ *
+ * `body.schema` is `{ fieldName: declaredType }`; `body.affordance` is
+ * `{ verb: { summary?, reads?: [...], writes?: [...] } }` naming DECLARED
+ * fields. That structure is what makes a declaration interpretable at all: an
+ * affordance recorded as free prose ("reads the pulse count") can only be
+ * resolved by the person who wrote it, which is precisely the dependency the
+ * agent-free assay exists to refuse. An `affordance` foundation therefore has
+ * to carry the schema its verbs resolve against.
+ *
+ * The replay builds a clean world state from the declared types, resolves every
+ * affordance against it each tick, and lets the harness's per-tick invariant
+ * pass assert that every declared field still holds a value of its declared
+ * type and that the whole state stays JSON-portable.
+ */
+function declarativeSandbox({ kind, body, contributionId }) {
+ const schema = body.schema;
+ if (!isPlainObject(schema) || Object.keys(schema).length === 0) {
+ return refuse(`a \`${kind}\` foundation must declare \`body.schema\` as a non-empty { field: type } map — a state shape nobody can instantiate cannot be replayed without its author`);
+ }
+ for (const [field, declaredType] of Object.entries(schema)) {
+ if (typeof declaredType !== 'string' || !Object.hasOwn(EIDOVERSE_DECLARED_FIELD_TYPES, declaredType)) {
+ return refuse(`\`body.schema.${field}\` declares "${declaredType}", which is not an interpretable field type (expected one of ${DECLARED_TYPE_NAMES.join(', ')})`);
+ }
+ }
+
+ const affordances = body.affordance;
+ if (kind === 'affordance' && (!isPlainObject(affordances) || Object.keys(affordances).length === 0)) {
+ return refuse('an `affordance` foundation must declare `body.affordance` as a non-empty { verb: … } map');
+ }
+ const resolved = [];
+ for (const [verb, declaration] of Object.entries(isPlainObject(affordances) ? affordances : {})) {
+ if (!isPlainObject(declaration)) {
+ return refuse(`\`body.affordance.${verb}\` is prose, not a resolvable declaration — declare it as { summary, reads: [...], writes: [...] } naming fields from \`body.schema\``);
+ }
+ const reads = declaration.reads ?? [];
+ const writes = declaration.writes ?? [];
+ if (!Array.isArray(reads) || !Array.isArray(writes)) return refuse(`\`body.affordance.${verb}\` must declare \`reads\` and \`writes\` as arrays of field names`);
+ if (reads.length === 0 && writes.length === 0) return refuse(`\`body.affordance.${verb}\` touches no declared field — an affordance with no readable consequence cannot be replayed`);
+ for (const field of [...reads, ...writes]) {
+ if (!Object.hasOwn(schema, field)) return refuse(`\`body.affordance.${verb}\` names "${field}", which \`body.schema\` does not declare`);
+ }
+ resolved.push({ verb, reads, writes });
+ }
+ resolved.sort((a, b) => a.verb.localeCompare(b.verb));
+
+ return accept({
+ id: contributionId,
+ description: `Declared ${Object.keys(schema).length}-field ${kind} with ${resolved.length} resolvable affordance(s).`,
+ createSandbox() {
+ const fields = Object.fromEntries(Object.entries(schema).map(([field, type]) => [field, EIDOVERSE_DECLARED_FIELD_TYPES[type].sample()]));
+ return {
+ // `scratch` is undeclared state on purpose — see the district-template
+ // sandbox: `missing-optional-deps` removes it, and nothing may miss it.
+ worldState: { fields, applied: [], scratch: { kind } },
+ controller: {
+ step(worldState, tick) {
+ const fields = { ...worldState.fields };
+ const applied = [];
+ for (const { verb, reads, writes } of resolved) {
+ for (const field of reads) {
+ if (!Object.hasOwn(fields, field)) throw new Error(`affordance "${verb}" reads "${field}", which is no longer present in the world state`);
+ }
+ for (const field of writes) fields[field] = EIDOVERSE_DECLARED_FIELD_TYPES[schema[field]].advance(fields[field], tick);
+ applied.push(verb);
+ }
+ return { ...worldState, fields, applied, tick };
+ },
+ applyDisturbance(worldState, disturbance) {
+ if (disturbance === 'restart-world-host') return JSON.parse(JSON.stringify(worldState));
+ if (disturbance === 'missing-optional-deps') {
+ const { scratch: _gone, ...durable } = worldState;
+ return durable;
+ }
+ return worldState;
+ },
+ },
+ projectionSource: {},
+ };
+ },
+ invariants: [
+ function declaredFieldsKeepTheirDeclaredTypes(worldState) {
+ for (const [field, type] of Object.entries(schema)) {
+ if (!Object.hasOwn(worldState.fields || {}, field)) return { ok: false, reason: `declared field "${field}" went missing` };
+ if (!EIDOVERSE_DECLARED_FIELD_TYPES[type].valid(worldState.fields[field])) {
+ return { ok: false, reason: `declared field "${field}" no longer holds a ${type}` };
+ }
+ }
+ return true;
+ },
+ function everyDeclaredAffordanceResolved(worldState) {
+ if (!Array.isArray(worldState.applied) || worldState.applied.length !== resolved.length) {
+ return { ok: false, reason: `expected ${resolved.length} affordance(s) to resolve, saw ${worldState.applied?.length ?? 'none'}` };
+ }
+ return true;
+ },
+ ],
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Entry point
+// ---------------------------------------------------------------------------
+
+/**
+ * The resilience-assay contribution for one foundation, derived from its own
+ * body — or a refusal reason when the body cannot be replayed at all.
+ *
+ * Async only for the `controller` kind's registry read, which is injected:
+ * `findControllerDefinition(id)` resolves a SHIPPED definition by id (the
+ * ledger and the migration both pass
+ * `eidoverseControllerRegistry.js#findControllerDefinitionById`). Nothing here
+ * imports the service layer, and no caller-supplied path is ever resolved.
+ *
+ * @param {{ kind: string, id: string, body: object }} record
+ * @param {{ findControllerDefinition: (id: string) => Promise<object|null> }} resolvers
+ * @returns {Promise<{ contribution: object|null, refusal: string|null }>}
+ */
+export async function foundationSandbox({ kind, id, body }, { findControllerDefinition } = {}) {
+ if (!isPlainObject(body)) return refuse('this foundation has no body to replay');
+ const contributionId = derivedContributionId({ kind, id, body });
+
+ if (kind === 'controller') {
+ const definitionId = controllerDefinitionIdFromBody(body);
+ const definition = definitionId && findControllerDefinition ? await findControllerDefinition(definitionId) : null;
+ return controllerSandbox({ body, definition, definitionId, contributionId });
+ }
+ if (kind === 'district-template') return districtTemplateSandbox({ body, contributionId });
+ if (kind === 'schema' || kind === 'affordance') return declarativeSandbox({ kind, body, contributionId });
+ return refuse(`"${kind}" has no sandbox derivation, so nothing can replay it without its author`);
+}
diff --git a/server/lib/eidoverseFoundationSandbox.test.js b/server/lib/eidoverseFoundationSandbox.test.js
new file mode 100644
index 0000000000..7be566d267
--- /dev/null
+++ b/server/lib/eidoverseFoundationSandbox.test.js
@@ -0,0 +1,179 @@
+/**
+ * The promote gate's binding between "what was evaluated" and "what gets
+ * promoted" (#7625).
+ *
+ * Every case here is paired: one body per declared kind that the agent-free
+ * assay genuinely passes, and one that is deliberately broken in a way only a
+ * REPLAY OF THAT BODY can notice. A derivation that always produced a passing
+ * sandbox would reproduce the hole this module exists to close, so the failing
+ * half is the load-bearing half — a refusal that never fires is the bug.
+ *
+ * The assay itself (`services/eidoverseResilienceAssay.js`) is run for real
+ * rather than stubbed: the contract under test is "this body survives the
+ * disturbance suite", and a mocked harness would only prove that the derivation
+ * returns an object.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { z } from 'zod';
+import { RESILIENCE_DISTURBANCES, runResilienceAssay } from '../services/eidoverseResilienceAssay.js';
+import { findControllerDefinitionById } from '../services/eidoverseControllerRegistry.js';
+import { buildDistrictTemplateFoundationDraft, generateDistrictTemplatePlacement } from './eidoverseCreativeToolkit.js';
+import { controllerDefinitionIdFromBody, derivedContributionId } from './eidoverseFoundations.js';
+import { foundationSandbox } from './eidoverseFoundationSandbox.js';
+
+const resolvers = { findControllerDefinition: findControllerDefinitionById };
+
+/** Derive, replay, and report the verdict the promote gate would read. */
+const replay = async (record) => {
+ const { contribution, refusal } = await foundationSandbox(record, resolvers);
+ if (refusal) return { refusal, pass: false, contributionId: null, reasons: [refusal] };
+ const verdict = runResilienceAssay(contribution, { disturbances: RESILIENCE_DISTURBANCES });
+ return { refusal: null, ...verdict };
+};
+
+const ANCHOR = [2, 0, -3];
+const templateBody = (overrides = {}) => {
+ const declared = { layoutId: 'radial-ring', anchor: ANCHOR, propCount: 4, seed: 'tide', facing: 0 };
+ return { ...declared, placement: generateDistrictTemplatePlacement(declared), ...overrides };
+};
+
+describe('deriving the assay sandbox from a foundation body', () => {
+ it('replays a controller foundation against ITS OWN config, and fails a config the shipped definition rejects', async () => {
+ // The regression this pins: the old derivation built its sandbox from
+ // `definition.exampleConfig`, so an install whose own controller config was
+ // broken still promoted on evidence that UPSTREAM's example survived.
+ const authored = { kind: 'controller', id: 'tide-beacon', body: { controller: { definitionId: 'ambient-beacon', config: { label: 'tide', pulseEveryTicks: 2 } } } };
+ const passed = await replay(authored);
+ expect(passed.refusal).toBeNull();
+ expect(passed.pass).toBe(true);
+ expect(passed.contributionId).toBe('controller:ambient-beacon');
+
+ const broken = await replay({ ...authored, body: { controller: { definitionId: 'ambient-beacon', config: { pulseEveryTicks: 0 } } } });
+ expect(broken.refusal).toMatch(/own controller config does not satisfy "ambient-beacon"/);
+
+ // …while the shipped definition's own example still passes on its own, so
+ // the refusal is about this install's config and not about the definition.
+ const definition = await findControllerDefinitionById('ambient-beacon');
+ const shipped = await replay({ ...authored, body: { controller: { definitionId: 'ambient-beacon', config: definition.exampleConfig } } });
+ expect(shipped.pass).toBe(true);
+ });
+
+ it('refuses a controller foundation that names no shipped definition', async () => {
+ const named = await replay({ kind: 'controller', id: 'tide-beacon', body: { controller: { definitionId: 'not-shipped-anywhere', config: {} } } });
+ expect(named.refusal).toMatch(/no shipped controller definition is registered under "not-shipped-anywhere"/);
+
+ const unnamed = await replay({ kind: 'controller', id: 'tide-beacon', body: { schema: { pulses: 'integer' } } });
+ expect(unnamed.refusal).toMatch(/must declare `body\.controller\.definitionId`/);
+ });
+
+ it('replays a district template only when its placement re-derives from its own declarations', async () => {
+ const passed = await replay({ kind: 'district-template', id: 'lantern-row', body: templateBody() });
+ expect(passed.refusal).toBeNull();
+ expect(passed.pass).toBe(true);
+
+ // One hand-edited coordinate: geometry only its author can rebuild.
+ const drifted = templateBody();
+ drifted.placement = drifted.placement.map((prop, index) => (index === 0 ? { ...prop, yaw: prop.yaw + 1 } : prop));
+ const refused = await replay({ kind: 'district-template', id: 'lantern-row', body: drifted });
+ expect(refused.refusal).toMatch(/does not reproduce from this template's own layout/);
+
+ const unknownLayout = await replay({ kind: 'district-template', id: 'lantern-row', body: templateBody({ layoutId: 'no-such-layout' }) });
+ expect(unknownLayout.refusal).toMatch(/cannot be re-derived from its own declarations/);
+ });
+
+ it('replays the district template the shipped creative toolkit authors', async () => {
+ // The authoring helper a mind reaches for has to produce a body this gate
+ // can replay — otherwise the one documented way to author a template is
+ // also the one way to author an unpromotable one.
+ const draft = buildDistrictTemplateFoundationDraft({
+ id: 'lantern-row', title: 'Lantern Row', summary: 'Lanterns around the plaza.',
+ layoutId: 'grid-plot', materialId: 'sunbaked-clay', motifId: 'lantern-row', anchor: ANCHOR, propCount: 5,
+ });
+ const verdict = await replay(draft);
+
+ expect(verdict.refusal).toBeNull();
+ expect(verdict.pass).toBe(true);
+ });
+
+ it('replays a declared schema, and refuses a field type no interpreter knows', async () => {
+ const passed = await replay({ kind: 'schema', id: 'tide-state', body: { schema: { pulses: 'integer', lastSeen: 'timestamp', peers: 'list' } } });
+ expect(passed.refusal).toBeNull();
+ expect(passed.pass).toBe(true);
+ expect(passed.contributionId).toBe('schema:tide-state');
+
+ const refused = await replay({ kind: 'schema', id: 'tide-state', body: { schema: { pulses: 'whatever-the-author-meant' } } });
+ expect(refused.refusal).toMatch(/not an interpretable field type/);
+ });
+
+ it('replays declared affordances, and refuses prose or a verb naming an undeclared field', async () => {
+ const passed = await replay({
+ kind: 'affordance',
+ id: 'tide-beacon',
+ body: { schema: { pulses: 'integer' }, affordance: { pulse: { summary: 'advance the count', reads: ['pulses'], writes: ['pulses'] } } },
+ });
+ expect(passed.refusal).toBeNull();
+ expect(passed.pass).toBe(true);
+
+ // The exact shape the repo's own canonical fixture used to carry.
+ const prose = await replay({ kind: 'affordance', id: 'tide-beacon', body: { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } } });
+ expect(prose.refusal).toMatch(/is prose, not a resolvable declaration/);
+
+ const dangling = await replay({
+ kind: 'affordance',
+ id: 'tide-beacon',
+ body: { schema: { pulses: 'integer' }, affordance: { pulse: { reads: ['tideHeight'] } } },
+ });
+ expect(dangling.refusal).toMatch(/names "tideHeight", which `body\.schema` does not declare/);
+ });
+
+ it('fails a controller whose own step breaks under the disturbance suite rather than refusing it up front', async () => {
+ // A derivation that only ever refused MALFORMED bodies would still let a
+ // well-formed-but-fragile one through, so this pins that the replay itself
+ // is what decides: a controller holding state outside `state` does not
+ // survive the restart disturbance.
+ let leaked = 0;
+ const fragile = {
+ id: 'leaky-beacon',
+ title: 'Leaky beacon',
+ summary: 'Keeps its counter outside the durable state.',
+ configSchema: z.object({}).strict(),
+ createState: () => ({ pulses: 0 }),
+ step: (state) => {
+ leaked += 1;
+ return { state: { ...state, pulses: leaked } };
+ },
+ invariants: [function pulsesTrackTheDurableState(state, tick) {
+ return state.pulses === tick + 1 || { ok: false, reason: `pulses was ${state.pulses} at tick ${tick}` };
+ }],
+ };
+ // Resolved through an injected registry rather than the shipped one, so the
+ // fixture does not have to become a shipped controller definition.
+ const injected = await foundationSandbox(
+ { kind: 'controller', id: 'leaky-beacon', body: { controller: { definitionId: 'leaky-beacon', config: {} } } },
+ { findControllerDefinition: async (id) => (id === 'leaky-beacon' ? fragile : null) },
+ );
+ expect(injected.refusal).toBeNull();
+ const replayed = runResilienceAssay(injected.contribution, { disturbances: RESILIENCE_DISTURBANCES });
+ expect(replayed.pass).toBe(false);
+ expect(replayed.reasons.join(' ')).toMatch(/pulses was/);
+ });
+
+ it('refuses a kind with no derivation and a body that is not an object', async () => {
+ expect((await foundationSandbox({ kind: 'mystery', id: 'x', body: {} }, resolvers)).refusal).toMatch(/has no sandbox derivation/);
+ expect((await foundationSandbox({ kind: 'schema', id: 'x', body: null }, resolvers)).refusal).toMatch(/no body to replay/);
+ });
+});
+
+describe('the derived binding label', () => {
+ it('comes from the controller definition a body names, and otherwise from kind + id', () => {
+ expect(derivedContributionId({ kind: 'controller', id: 'tide-beacon', body: { controller: { definitionId: 'ambient-beacon' } } })).toBe('controller:ambient-beacon');
+ expect(derivedContributionId({ kind: 'controller', id: 'tide-beacon', body: {} })).toBe('controller:tide-beacon');
+ expect(derivedContributionId({ kind: 'district-template', id: 'lantern-row', body: {} })).toBe('district-template:lantern-row');
+ });
+
+ it('ignores a definition id shaped like a path, so no label can smuggle one', () => {
+ expect(controllerDefinitionIdFromBody({ controller: { definitionId: '../../etc/passwd' } })).toBeNull();
+ expect(controllerDefinitionIdFromBody({ controller: { definitionId: 'ambient-beacon' } })).toBe('ambient-beacon');
+ });
+});
diff --git a/server/lib/eidoverseFoundations.js b/server/lib/eidoverseFoundations.js
index 9f8718df0e..ad0e345523 100644
--- a/server/lib/eidoverseFoundations.js
+++ b/server/lib/eidoverseFoundations.js
@@ -36,7 +36,9 @@
* the contribution itself: `assayEvidenceFromVerdict()` folds a
* `runResilienceAssay()` result into the evidence block, and packaging
* refuses evidence that is missing, failing, bound to a DIFFERENT
- * contribution than the one this foundation names, or short of the full
+ * contribution than the one this foundation's OWN body derives
+ * (`lib/eidoverseFoundationSandbox.js`, #7625 — the binding label is
+ * derived, never authored), or short of the full
* disturbance suite. Keeping execution in the harness that owns the
* sandbox leaves this module pure and synchronous, and leaves exactly one
* place in the tree that runs untrusted controller code. The ledger runs
@@ -84,18 +86,19 @@ export const EIDOVERSE_FOUNDATION_KINDS = Object.freeze(['schema', 'affordance',
*
* 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]);
+ * body stamped as its own work.
+ *
+ * **v3 (#7625) is a SEMANTIC break, not a shape change.** A v1/v2 envelope's
+ * `assay` block was evidence about whatever contribution its author NAMED,
+ * which had no required relationship to the `body` travelling beside it. v3
+ * evidence is produced by replaying the body itself
+ * (`eidoverseFoundationSandbox.js`) and its `contributionId` is DERIVED from
+ * `kind`/`body`, so a receiver can re-derive the binding instead of taking
+ * the sender's word for it. Every older envelope is therefore refused outright
+ * rather than inherited — there is no way to upgrade evidence that never
+ * described the payload, which is why this install reads exactly one version
+ * rather than a widening accepted set. */
+export const EIDOVERSE_FOUNDATION_CANDIDATE_VERSION = 3;
/**
* Keys that are UNAMBIGUOUSLY cosmetic and so must never appear inside a
@@ -133,11 +136,60 @@ const FOUNDATION_LIMITS = Object.freeze({
const foundationIdSchema = z.string().trim().min(1).max(FOUNDATION_LIMITS.idMax)
.regex(/^[a-z0-9][a-z0-9-]*$/, 'must be a lowercase slug (letters, digits, hyphens)');
-/** The resilience-assay contribution this foundation is replayed as — the
- * binding between a recorded artifact and the sandbox that proves it survives
- * its author's absence. Resolved by `services/eidoverseResilienceContributions.js`. */
+/**
+ * The binding between a recorded artifact and the sandbox that proved it
+ * survives its author's absence.
+ *
+ * **Derived, never authored (#7625).** It is absent from
+ * `eidoverseFoundationInputSchema` below and computed by
+ * `derivedContributionId()` just beneath it from the foundation's own
+ * `kind`/`body`. When an author could supply it, naming a shipped demo fixture
+ * was sufficient to clear the promote gate, and the evidence a peer inherited
+ * on described that fixture rather than the body in the envelope.
+ */
const contributionIdSchema = z.string().trim().min(1).max(120);
+/** A shipped-definition / foundation slug. Mirrors `foundationIdSchema`. */
+const CONTROLLER_DEFINITION_SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+const isPlainObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+
+/**
+ * The shipped controller definition id a `controller` foundation names, or
+ * `null` when its body names none. Exported because `eidoverseFoundationSandbox.js`
+ * has to resolve the definition (an async registry read) BEFORE it can build
+ * the sandbox.
+ */
+export function controllerDefinitionIdFromBody(body) {
+ const declared = isPlainObject(body) && isPlainObject(body.controller) ? body.controller.definitionId : null;
+ return typeof declared === 'string' && CONTROLLER_DEFINITION_SLUG.test(declared.trim()) ? declared.trim() : null;
+}
+
+/**
+ * The label a foundation's assay evidence is bound to, derived from the record
+ * rather than supplied by its author.
+ *
+ * Lives HERE rather than beside the sandbox that replays the body, even though
+ * that is where it is conceptually rooted: both binding checks below call it,
+ * and the sandbox reaches the creative toolkit, which reaches this module's
+ * input schema — so importing it the other way closes an ESM cycle and leaves
+ * `eidoverseFoundationInputSchema` in its temporal dead zone at first load.
+ * The function is pure and reads only `kind`/`id`/`body`, so it belongs to the
+ * schema layer as easily as to the harness.
+ *
+ * Total on purpose: a body too malformed to derive a sandbox from still gets a
+ * stable label, because BOTH sides of the binding check compute it the same
+ * way — the label's job is to bind evidence to a body, and refusing the
+ * malformed body is `foundationSandbox()`'s job, not this one's.
+ */
+export function derivedContributionId({ kind, id, body }) {
+ if (kind === 'controller') {
+ const definitionId = controllerDefinitionIdFromBody(body);
+ if (definitionId) return `controller:${definitionId}`;
+ }
+ return `${kind}:${id}`;
+}
+
// `.datetime()`, not a `Date.parse` refine: `Date.parse` accepts "March 4, 2026"
// and "2026", and these timestamps are hashed into a payload a peer parses.
const isoDateSchema = z.string().datetime();
@@ -266,12 +318,14 @@ export const foundationDerivationClaimSchema = z.object({
* 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
* a cap change cannot land on two of the three and silently diverge them.
+ *
+ * `contributionId` is deliberately NOT here: it is on the record and on the
+ * envelope but never on the input, because it is derived rather than authored.
*/
const foundationCoreShape = {
kind: z.enum(EIDOVERSE_FOUNDATION_KINDS),
title: z.string().trim().min(1).max(FOUNDATION_LIMITS.titleMax),
summary: z.string().trim().min(1).max(FOUNDATION_LIMITS.summaryMax),
- contributionId: contributionIdSchema,
body: foundationBodySchema,
disclosure: foundationDisclosureSchema,
};
@@ -279,6 +333,7 @@ const foundationCoreShape = {
/** The local ledger record. `style` stays here and never leaves the install. */
export const eidoverseFoundationRecordSchema = z.object({
...foundationCoreShape,
+ contributionId: contributionIdSchema,
id: foundationIdSchema,
// `runtime` is absent by construction: an install authors its own artifacts
// and may promote them, but the shared framework layer is never a record here.
@@ -344,7 +399,10 @@ export function foundationLedgerKey({ id, originInstanceId = null }) {
/** 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. */
+ * `baseline` is what the promote path is for. Neither is `contributionId`
+ * (#7625): the sandbox the assay replays is derived from `body`, so the
+ * binding label is derived from it too — a caller that could name it could
+ * borrow another contribution's passing verdict. */
export const eidoverseFoundationInputSchema = z.object({
...foundationCoreShape,
id: foundationIdSchema,
@@ -358,7 +416,8 @@ export const eidoverseFoundationInputSchema = z.object({
/** The promote envelope — the only shape authorized to cross to a peer. */
export const eidoverseFoundationCandidateSchema = z.object({
...foundationCoreShape,
- candidateVersion: z.union(EIDOVERSE_FOUNDATION_CANDIDATE_VERSIONS_ACCEPTED.map((version) => z.literal(version))),
+ contributionId: contributionIdSchema,
+ candidateVersion: z.literal(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION),
derivedFrom: foundationDerivationEdgeSchema.nullable().default(null),
foundationId: foundationIdSchema,
provenance: foundationProvenanceSchema.extend({
@@ -582,6 +641,7 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
const parsed = eidoverseFoundationRecordSchema.safeParse(record);
if (!parsed.success) return refused(issueReasons(parsed.error));
const foundation = parsed.data;
+ const derivedLabel = derivedContributionId(foundation);
// Two refusals the envelope gate below cannot phrase usefully: ownership
// layer is not carried on the envelope at all, and a missing assay would
@@ -598,6 +658,14 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
// Promotion publishes only what this install authored (#7461); it must
// never become a relay that re-shares a peer's foundation as its own.
foundation.inheritance ? `inherited from another install (${foundation.inheritance.originInstanceId}) — promotion re-shares only foundations this install authored` : null,
+ // A ledger file is a file a human (or a restored backup from before #7625)
+ // can hand us, so the derived binding is re-checked here rather than
+ // trusted because the ledger wrote it. `packageEidoverseFoundationCandidate`
+ // re-derives before calling in, so this only ever fires on a record that
+ // reached the gate some other way.
+ foundation.contributionId === derivedLabel
+ ? null
+ : `this record is labelled "${foundation.contributionId}" but its own kind and body derive "${derivedLabel}" — re-author the foundation so its assay evidence is bound to the body it describes`,
assayEvidenceRefusal(foundation.assay, requiredDisturbances, foundation.contributionId),
].filter(Boolean);
if (reasons.length > 0) return refused(reasons);
@@ -639,6 +707,22 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
* @returns {{ valid: boolean, reasons: string[], findings: Array }}
*/
export function verifyFoundationCandidate(candidate, { requiredDisturbances }) {
+ // Phrased before the schema runs, because `z.literal(3)` reports an OLDER
+ // envelope as "invalid literal value" — true, and useless to the human
+ // reading a sync log. A pre-v3 envelope is not malformed; its evidence simply
+ // described something other than the body it travels with (#7625). This also
+ // subsumes every older-shape check: a v1 envelope carrying the v2
+ // `derived-from` edge (#7631) is refused here as an older envelope rather
+ // than for the edge, because its evidence is unusable either way.
+ const declaredVersion = candidate?.candidateVersion;
+ if (Number.isInteger(declaredVersion) && declaredVersion < EIDOVERSE_FOUNDATION_CANDIDATE_VERSION) {
+ return {
+ valid: false,
+ reasons: [`this promote envelope is candidate v${declaredVersion}; this install requires v${EIDOVERSE_FOUNDATION_CANDIDATE_VERSION}. A pre-v3 envelope's resilience evidence was recorded against a contribution its author NAMED rather than against the body it carries, so it cannot be inherited — ask the origin install to re-package the foundation.`],
+ findings: [],
+ };
+ }
+
const parsed = eidoverseFoundationCandidateSchema.safeParse(candidate);
if (!parsed.success) return { valid: false, reasons: issueReasons(parsed.error), findings: [] };
const envelope = parsed.data;
@@ -652,11 +736,14 @@ 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');
+ // The label has to be the one THIS envelope's own kind/body derives, not one
+ // the sender chose. Without this a v3 envelope could still carry internally
+ // consistent evidence about some other contribution — the same
+ // borrowed-credential shape #7625 removed from the authoring surface, moved
+ // to the wire. Re-derivation is pure and reads only the envelope.
+ const derivedLabel = derivedContributionId({ kind: envelope.kind, id: envelope.foundationId, body: envelope.body });
+ if (envelope.contributionId !== derivedLabel) {
+ reasons.push(`this envelope claims to have been replayed as "${envelope.contributionId}", but its own kind and body derive "${derivedLabel}" — the evidence is not about the payload`);
}
const assayRefusal = assayEvidenceRefusal(envelope.assay, requiredDisturbances, envelope.contributionId);
diff --git a/server/lib/eidoverseFoundations.test.js b/server/lib/eidoverseFoundations.test.js
index c59899596d..3a355ec418 100644
--- a/server/lib/eidoverseFoundations.test.js
+++ b/server/lib/eidoverseFoundations.test.js
@@ -23,7 +23,22 @@ import { federationSafetyFindings } from './federationSafety.js';
const DISTURBANCES = ['reconnect', 'restart-world-host', 'missing-optional-deps'];
const NOW = '2026-03-04T05:06:07.000Z';
-const passingAssay = (contributionId = 'beacon-relay-demo') => ({
+/**
+ * A body that DESCRIBES ITSELF: the promote gate derives the sandbox it replays
+ * from these declarations (#7625), so the fixture has to be something the
+ * derivation can actually interpret. The previous fixture named a shipped demo
+ * contribution and carried an unrelated body — which was the bug, sitting in
+ * the repo's own canonical example.
+ */
+const SELF_DESCRIBING_BODY = Object.freeze({
+ schema: { pulses: 'integer' },
+ affordance: { pulse: { summary: 'advance the pulse count', reads: ['pulses'], writes: ['pulses'] } },
+});
+
+/** The label the fixture's own kind/body derives. Never authored. */
+const DERIVED_CONTRIBUTION_ID = 'affordance:tide-beacon';
+
+const passingAssay = (contributionId = DERIVED_CONTRIBUTION_ID) => ({
harness: 'eidoverse-resilience-assay',
contributionId,
pass: true,
@@ -35,11 +50,11 @@ const passingAssay = (contributionId = 'beacon-relay-demo') => ({
const makeRecord = (overrides = {}) => ({
id: 'tide-beacon',
layer: DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
- kind: 'controller',
+ kind: 'affordance',
title: 'Tide Beacon',
summary: 'A beacon that keeps pulsing between mind wakes.',
- contributionId: 'beacon-relay-demo',
- body: { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } },
+ contributionId: DERIVED_CONTRIBUTION_ID,
+ body: { ...SELF_DESCRIBING_BODY },
style: { palette: ['#102030'], motif: 'weathered brass', districtId: 'commons' },
provenance: { originInstanceId: 'instance-aaaa-bbbb', authorKind: 'mind', createdAt: NOW },
disclosure: { requires: [], effects: ['emits a pulse each tick'], license: null, notes: null },
@@ -72,7 +87,7 @@ describe('packaging a promote candidate', () => {
expect(result.outcome).toBe('packaged');
expect(result.candidate.candidateVersion).toBe(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION);
- expect(result.candidate.body).toEqual({ schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } });
+ expect(result.candidate.body).toEqual(SELF_DESCRIBING_BODY);
// The whole point of the split: nothing a peer inherits can overwrite the
// peer's own cosmetics, because the cosmetics never left this install.
expect(JSON.stringify(result.candidate)).not.toContain('weathered brass');
@@ -155,6 +170,34 @@ describe('verifying a candidate a peer was handed', () => {
expect(verifyFoundationCandidate(sent, { requiredDisturbances: DISTURBANCES }).valid).toBe(true);
});
+ it('refuses a v1 envelope with a reason that says WHY, not "invalid literal" (#7625)', () => {
+ // v1 evidence was recorded against a contribution its author NAMED, with no
+ // required relationship to the body beside it. There is no way to upgrade
+ // that, so an older peer's envelope is refused rather than inherited — and
+ // the person reading the sync log has to be able to tell that apart from a
+ // corrupt payload.
+ const { candidate } = packageRecord();
+ const verdict = verifyFoundationCandidate({ ...candidate, candidateVersion: 1 }, { requiredDisturbances: DISTURBANCES });
+
+ expect(verdict.valid).toBe(false);
+ expect(verdict.reasons).toHaveLength(1);
+ expect(verdict.reasons[0]).toContain('candidate v1');
+ expect(verdict.reasons[0]).toContain('re-package');
+ });
+
+ it('refuses an envelope whose binding label its own body does not derive (#7625)', () => {
+ // The borrowed-credential shape, moved from the authoring surface to the
+ // wire: internally consistent evidence about some other contribution. A
+ // receiver re-derives the label from the kind/body it was handed instead of
+ // taking the sender's word for it.
+ const { candidate } = packageRecord();
+ const forged = { ...candidate, contributionId: 'beacon-relay-demo', assay: passingAssay('beacon-relay-demo') };
+ const verdict = verifyFoundationCandidate({ ...forged, fingerprint: foundationCandidateFingerprint(forged) }, { requiredDisturbances: DISTURBANCES });
+
+ expect(verdict.valid).toBe(false);
+ expect(verdict.reasons.join(' ')).toContain('the evidence is not about the payload');
+ });
+
it('does not read its own sha256 fingerprint as a leaked credential', () => {
const { candidate } = packageRecord();
expect(candidate.fingerprint).toMatch(/^[a-f0-9]{64}$/);
@@ -166,7 +209,7 @@ describe('verifying a candidate a peer was handed', () => {
describe('assay evidence', () => {
it('folds a harness verdict into the evidence block without inventing a pass', () => {
const evidence = assayEvidenceFromVerdict({
- contributionId: 'beacon-relay-demo',
+ contributionId: DERIVED_CONTRIBUTION_ID,
pass: false,
scenarios: [{ disturbance: 'reconnect', pass: false }, { disturbance: 'restart-world-host', pass: true }],
reasons: ['[reconnect] tick 0: controller threw'],
@@ -263,7 +306,7 @@ describe('inheriting a foundation from a peer (#7461)', () => {
kind: 'controller',
title: 'Tide Beacon',
summary: 'A beacon that keeps pulsing between mind wakes.',
- contributionId: 'beacon-relay-demo',
+ contributionId: DERIVED_CONTRIBUTION_ID,
body: { affordance: { inspect: 'reads the pulse count' }, notes: 'built against 192.0.2.10 by [email protected]' },
disclosure: { requires: [], effects: [], license: null, notes: null },
provenance: { originInstanceId: 'instance-aaaa-bbbb', authorKind: 'mind', createdAt: NOW, packagedAt: NOW, portosVersion: '9.9.9' },
@@ -355,7 +398,11 @@ describe('the derived-from edge on a promote envelope (#7631)', () => {
expect(verifyFoundationCandidate(result.candidate, { requiredDisturbances: DISTURBANCES }).valid).toBe(true);
});
- it('refuses a v1 envelope that carries an edge its version never hashed', () => {
+ it('refuses a back-dated envelope carrying an edge its version never hashed, on the version alone', () => {
+ // A v1 payload bearing the v2 `derived-from` edge is hand-assembled, not an
+ // older peer. Since #7625 it never reaches the edge check: a pre-v3
+ // envelope's evidence is unusable whatever it carries, so the version
+ // refusal answers first — and re-fingerprinting the forgery does not help.
const packaged = packageRecord({ derivedFrom }).candidate;
const backdated = { ...packaged, candidateVersion: 1 };
backdated.fingerprint = foundationCandidateFingerprint({ ...backdated, fingerprint: undefined });
@@ -363,7 +410,8 @@ describe('the derived-from edge on a promote envelope (#7631)', () => {
const verified = verifyFoundationCandidate(backdated, { requiredDisturbances: DISTURBANCES });
expect(verified.valid).toBe(false);
- expect(verified.reasons.join(' ')).toContain('candidateVersion 2');
+ expect(verified.reasons.join(' ')).toContain('candidate v1');
+ expect(verified.reasons.join(' ')).toContain(`requires v${EIDOVERSE_FOUNDATION_CANDIDATE_VERSION}`);
});
it('carries an origin\'s own derivation edge onto the inheriting install, so the chain does not truncate to the last hop', () => {
diff --git a/server/lib/index.js b/server/lib/index.js
index fc781beefe..d38ee123e8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -585,6 +585,7 @@ export * from './domainAutonomy.js';
export * from './domainBudgets.js';
export * from './eidoverseCreativeToolkit.js';
export * from './eidoverseControllers.js';
+export * from './eidoverseFoundationSandbox.js';
export * from './eidoverseFoundations.js';
export * from './eidoverseObservation.js';
export * from './federationSafety.js';
diff --git a/server/routes/eidoverseWorldRoutes.js b/server/routes/eidoverseWorldRoutes.js
index 34643d3786..f20de63305 100644
--- a/server/routes/eidoverseWorldRoutes.js
+++ b/server/routes/eidoverseWorldRoutes.js
@@ -35,7 +35,6 @@ import {
recordEidoverseFoundation,
withdrawEidoverseFoundation,
} from '../services/eidoverseFoundationLedger.js';
-import { listRegisteredContributionIds } from '../services/eidoverseResilienceContributions.js';
import { describeControllerDefinitions } from '../services/eidoverseControllerRegistry.js';
import {
getEidoverseControllerInstall,
@@ -118,12 +117,12 @@ router.get('/foundations', asyncHandler(async (_req, res) => {
res.json(await listEidoverseFoundations());
}));
-// GET /api/eidoverse/world/contributions — the resilience-assay contributions
-// a foundation may bind itself to. Its own path rather than a
-// `/foundations/<something>` one, so no foundation id can ever shadow it.
-router.get('/contributions', asyncHandler(async (_req, res) => {
- res.json({ contributions: await listRegisteredContributionIds() });
-}));
+// `GET /contributions` lived here until #7625. It listed the resilience-assay
+// contribution ids a foundation could bind itself to — and naming one was
+// sufficient to clear the promote gate, which is the hole #7625 closed. The
+// gate now derives the sandbox from the foundation's own body, so there is
+// nothing to bind to; an author choosing a `controller` behaviour reads
+// `GET /controllers` below, which already projects the shipped registry.
// POST /api/eidoverse/world/foundations — record (or re-author) a local
// vernacular foundation. The ownership layer is not accepted from the caller:
diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.js
index 3a95016e39..98e7e6e9f5 100644
--- a/server/routes/eidoverseWorldRoutes.test.js
+++ b/server/routes/eidoverseWorldRoutes.test.js
@@ -8,7 +8,6 @@ const mocks = vi.hoisted(() => ({
listFoundations: vi.fn(),
packageCandidate: vi.fn(),
promoteFoundation: vi.fn(),
- listContributions: vi.fn(),
recordFoundation: vi.fn(),
withdrawFoundation: vi.fn(),
deleteFoundation: vi.fn(),
@@ -50,10 +49,6 @@ vi.mock('../services/eidoverseFoundationLedger.js', () => ({
deleteEidoverseFoundation: mocks.deleteFoundation,
}));
-vi.mock('../services/eidoverseResilienceContributions.js', () => ({
- listRegisteredContributionIds: mocks.listContributions,
-}));
-
vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: () => Promise.resolve('instance-aaaa') }));
vi.mock('../services/eidoverseControllerRegistry.js', () => ({
@@ -211,8 +206,7 @@ describe('Eidoverse world routes', () => {
kind: 'controller',
title: 'Tide Beacon',
summary: 'A beacon that keeps pulsing between mind wakes.',
- contributionId: 'beacon-relay-demo',
- body: { affordance: { inspect: 'reads the pulse count' } },
+ body: { controller: { definitionId: 'ambient-beacon', config: {} } },
};
mocks.recordFoundation.mockResolvedValue({ ...authored, layer: 'vernacular' });
@@ -330,15 +324,12 @@ it('reports a promote refusal as a verdict and never moves the layer itself', as
expect((await request(makeApp()).post('/api/eidoverse/world/foundations/tide-beacon/adopt')).status).toBe(404);
});
- 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.getFoundationByRef.mockResolvedValue(null);
-
- const response = await request(makeApp()).get('/api/eidoverse/world/contributions');
-
- expect(response.status).toBe(200);
- expect(response.body).toEqual({ contributions: ['beacon-relay-demo'] });
- expect(mocks.getFoundationByRef).not.toHaveBeenCalled();
+ it('no longer serves an assay-contribution list to bind a foundation to (#7625)', async () => {
+ // The route existed so an author could pick an id that would satisfy the
+ // promote gate. Naming one WAS satisfying it, which is the hole #7625
+ // closed by deriving the sandbox from the body; there is nothing to bind to
+ // now, and a lingering endpoint would keep advertising that there is.
+ expect((await request(makeApp()).get('/api/eidoverse/world/contributions')).status).toBe(404);
});
// --- Controllers: the install surface beside the mind tool (#7488) -------
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 8ab9249ff6..7e2607f248 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -434,8 +434,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'],
['foundation', 'Read ONE foundation in full — everything eidoverse.foundations lists for it plus the `body` (the substance itself) and the author\'s `disclosure`. This is how you obtain what a peer actually contributed: the list deliberately omits every body, so pick an id there and read the one you are considering here. Name an INHERITED copy with `originInstanceId` from its `inheritance` edge; omit it for a foundation this install authored. Local style is never included.', eidoverseFoundationTargetSchema, ['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. 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'],
+ ['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.controllers for a valid `body.controller.definitionId` first. You do not name what the promote gate replays: it derives the sandbox from this `body`, so a `controller` body must carry `controller: { definitionId, config }`, a `district-template` body must carry the layout/anchor/seed its `placement` re-derives from, and a `schema`/`affordance` body must declare `schema: { field: type }` (and, for an affordance, `affordance: { verb: { reads, writes } }` naming those fields). `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'],
['adopt', 'Stand an INHERITED foundation up so it actually runs on this install, keeping a `derived-from` edge back to the peer that authored it. Only a `controller` foundation is adoptable today: it installs the SHIPPED controller its body names, DISARMED and not delivering effects, so arming it is a separate act you or your human take afterwards. A `schema`, `affordance`, or `district-template` foundation is refused by name — nothing here interprets one yet. A refusal is a result, not an error: read `reasons` and never narrate a refused adopt as done. Adopting is also the only re-use path that KEEPS attribution; re-typing a peer\'s body through eidoverse.record is refused as republishing their work as your own.', eidoverseFoundationTargetSchema, ['manageEidoverse', 'installEidoverseControllers'], '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]) => ({
@@ -1013,10 +1012,6 @@ const executeAdapter = async (tool, args, context, authority) => {
const result = await ledger.adoptEidoverseFoundation(args, { installedBy: 'mind' });
return { ...result, install: result.install ? summarizeControllerInstall(result.install) : null };
}
- if (tool.adapter.operation === 'contributions') {
- const { listRegisteredContributionIds } = await import('./eidoverseResilienceContributions.js');
- return { contributions: await listRegisteredContributionIds() };
- }
if (tool.adapter.operation === 'record') {
const { ensureInstanceId } = await import('./instanceIdentity.js');
// `authorKind` is stamped 'mind' server-side rather than trusted from
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index 1f326c9561..0ca9a5f6f4 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -19,7 +19,6 @@ const mocks = vi.hoisted(() => ({
listFoundations: vi.fn(),
promoteFoundation: vi.fn(),
recordFoundation: vi.fn(),
- listContributions: vi.fn(),
ensureInstanceId: vi.fn(),
}));
@@ -79,9 +78,6 @@ vi.mock('./eidoverseFoundationLedger.js', () => ({
promoteEidoverseFoundation: (...args) => mocks.promoteFoundation(...args),
recordEidoverseFoundation: (...args) => mocks.recordFoundation(...args),
}));
-vi.mock('./eidoverseResilienceContributions.js', () => ({
- listRegisteredContributionIds: (...args) => mocks.listContributions(...args),
-}));
vi.mock('./instanceIdentity.js', () => ({
ensureInstanceId: (...args) => mocks.ensureInstanceId(...args),
}));
@@ -171,7 +167,7 @@ describe('cosToolRegistry', () => {
name: 'eidoverse.record',
arguments: {
id: 'lantern-arcade', kind: 'district-template', title: 'Lantern Arcade', summary: 'A row of lanterns around the plaza.',
- contributionId: 'beacon-relay', body: { layoutId: 'radial-ring' }, authorKind: 'user',
+ body: { layoutId: 'radial-ring' }, authorKind: 'user',
},
};
await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { promoteEidoverseFoundations: true } } }))
@@ -182,7 +178,7 @@ describe('cosToolRegistry', () => {
mocks.ensureInstanceId.mockResolvedValue('instance-example');
mocks.recordFoundation.mockResolvedValue({
id: 'lantern-arcade', layer: 'vernacular', kind: 'district-template', title: 'Lantern Arcade', summary: 'A row of lanterns around the plaza.',
- contributionId: 'beacon-relay', updatedAt: '2026-03-04T06:00:00.000Z', promotedAt: null, assay: null, candidate: null,
+ contributionId: 'district-template:lantern-arcade', updatedAt: '2026-03-04T06:00:00.000Z', promotedAt: null, assay: null, candidate: null,
});
const result = await executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { manageEidoverse: true } } });
@@ -253,13 +249,15 @@ describe('cosToolRegistry', () => {
expect(result.result.install.derivedFrom).toMatchObject({ originInstanceId: 'instance-aaaa' });
});
- it('lists registered resilience-assay contributions and the creative catalog', async () => {
- mocks.listContributions.mockResolvedValue(['beacon-relay']);
- const contributions = await executeCosToolCall({
+ it('no longer offers a contribution list for a foundation to bind to, and still serves the creative catalog', async () => {
+ // #7625: naming a registered contribution was sufficient to clear the
+ // promote gate, so advertising the ids to a mind was advertising the hole.
+ // `eidoverse.controllers` is what a mind needs now — which behaviours this
+ // install ships for a `controller` body to name.
+ await expect(executeCosToolCall({
call: { requestId: 'contrib-1', name: 'eidoverse.contributions', arguments: {} },
authority: { scope: 'mind', capabilities: { manageEidoverse: true } },
- });
- expect(contributions.result).toEqual({ contributions: ['beacon-relay'] });
+ })).rejects.toThrow(/Unknown tool/);
const catalog = await executeCosToolCall({
call: { requestId: 'catalog-1', name: 'eidoverse.creative-catalog', arguments: {} },
@@ -291,11 +289,19 @@ describe('cosToolRegistry', () => {
name: 'eidoverse.draft-foundation',
arguments: {
id: 'garden-arcade', title: 'Garden Arcade', summary: 'A colonnade of lanterns around the arrival plaza.',
- contributionId: 'beacon-relay', layoutId: 'radial-ring', materialId: 'sunbaked-clay', motifId: 'lantern-row', anchor: [4, 0, -6],
+ layoutId: 'radial-ring', materialId: 'sunbaked-clay', motifId: 'lantern-row', anchor: [4, 0, -6],
},
};
const result = await executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { manageEidoverse: true } } });
expect(result.result.foundation).toMatchObject({ id: 'garden-arcade', kind: 'district-template' });
+ // A drafter has no `contributionId` to offer: the promote gate derives the
+ // binding label from the body it replays (#7625), so naming one is refused
+ // rather than quietly carried into the record.
+ expect(result.result.foundation.contributionId).toBeUndefined();
+ await expect(executeCosToolCall({
+ call: { ...call, arguments: { ...call.arguments, contributionId: 'beacon-relay' } },
+ authority: { scope: 'mind', capabilities: { manageEidoverse: true } },
+ })).rejects.toMatchObject({ code: 'TOOL_VALIDATION_ERROR' });
expect(result.result.foundation.body.placement.length).toBeGreaterThan(0);
expect(result.result.foundation.style).toMatchObject({ materialId: 'sunbaked-clay', motifId: 'lantern-row' });
});
@@ -349,7 +355,6 @@ describe('cosToolRegistry', () => {
'eidoverse.leave',
'eidoverse.foundations',
'eidoverse.foundation',
- 'eidoverse.contributions',
'eidoverse.record',
'eidoverse.adopt',
'eidoverse.promote',
diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.js
index babde89469..1c95897400 100644
--- a/server/services/eidoverseFoundationLedger.js
+++ b/server/services/eidoverseFoundationLedger.js
@@ -22,10 +22,15 @@
* 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
+ * `packageEidoverseFoundationCandidate()` DERIVES the sandbox from the
+ * foundation's own body (`lib/eidoverseFoundationSandbox.js`, #7625), replays it
* through `runResilienceAssay()` (#7460), and packages against the verdict it
- * just produced. A caller — a route, a mind tool — therefore cannot assert that
+ * just produced. Deriving rather than resolving a caller-supplied
+ * `contributionId` is what makes 'what was evaluated' and 'what gets promoted'
+ * the same object: the id used to be free text, so a local build could name a
+ * shipped demo fixture and promote on evidence about the fixture.
+ *
+ * A caller — a route, a mind tool — therefore cannot assert that
* its build survived its author's absence; it can only ask for the check. That
* is the same proposal-versus-consequence separation #7454 gave the
* construction tools, applied to promotion.
@@ -60,6 +65,7 @@ import { getPortosVersion } from '../lib/schemaVersions.js';
import {
DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
assayEvidenceFromVerdict,
+ derivedContributionId,
eidoverseFoundationInputSchema,
foundationFromInheritedCandidate,
foundationLedgerKey,
@@ -79,7 +85,8 @@ import {
tombstoneTimestamp,
} from '../lib/tombstones.js';
import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';
-import { findContributionById } from './eidoverseResilienceContributions.js';
+import { foundationSandbox } from '../lib/eidoverseFoundationSandbox.js';
+import { findControllerDefinitionById } from './eidoverseControllerRegistry.js';
/**
* Storage-layout version stamped on `data/eidoverse/foundations.json`.
@@ -402,7 +409,12 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
kind: authored.kind,
title: authored.title,
summary: authored.summary,
- contributionId: authored.contributionId,
+ // DERIVED, never authored (#7625): the assay replays this foundation's
+ // own body, so the label that binds evidence to it is computed from that
+ // body — the STORED one derived just above, which is what the sandbox
+ // will actually replay. A caller that could name the label could point
+ // the gate at a shipped demo fixture and inherit its passing verdict.
+ contributionId: derivedContributionId({ kind: authored.kind, id: authored.id, body }),
body,
style: authored.style,
provenance: existing?.provenance || { originInstanceId, authorKind: authored.authorKind, createdAt: now },
@@ -465,11 +477,10 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
if (!existing) return unknownFoundation(id);
// Refused before resolving or replaying ANYTHING: `packageFoundationCandidate`
// (the pure lib) refuses an inherited record too, but only after running the
- // assay against whatever `contributionId` it names. This is a local copy of a
- // PEER's declared contribution id — replaying it here would be exactly the
- // "run arbitrary code pulled from a peer" this install's own assay harness
- // exists to keep off every OTHER install, even though `findContributionById`
- // only ever resolves this install's own fixed local registry.
+ // assay against the body it carries. That body came from a PEER — replaying
+ // it here would be exactly the "run arbitrary code pulled from a peer" this
+ // install's own assay harness exists to keep off every OTHER install, even
+ // though the derivation only ever executes code PortOS itself ships.
if (existing.inheritance) {
return verdict('refused', [`inherited from another install (${existing.inheritance.originInstanceId}) — promotion re-shares only foundations this install authored`]);
}
@@ -477,10 +488,14 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
// Outside the ledger lock: replaying a contribution is the slow part, and it
// reads nothing from the ledger. The lock below re-reads the record and
// re-checks that the body has not been re-authored underneath the verdict.
- const contribution = await findContributionById(existing.contributionId);
- if (!contribution) {
- return verdict('refused', [`no resilience-assay contribution is registered under "${existing.contributionId}" — a foundation is promotable only once it can be replayed without its author`]);
- }
+ //
+ // The sandbox is derived from THIS FOUNDATION'S OWN BODY (#7625). It used to
+ // be resolved by the id the author typed, so the gate replayed whatever
+ // module was named and the verdict described that module rather than this
+ // build. A body with no derivable sandbox is refused with the reason, which
+ // is the honest answer: nothing can replay it without its author.
+ const { contribution, refusal } = await foundationSandbox(existing, { findControllerDefinition: findControllerDefinitionById });
+ if (refusal) return verdict('refused', [refusal]);
const assay = assayEvidenceFromVerdict(runResilienceAssay(contribution), { ranAt: now });
// Read after the early returns: `getPortosVersion()` re-reads and re-parses
// package.json on every call, and a request naming an id this install never
@@ -495,8 +510,12 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
return verdict('refused', ['the foundation was re-authored while the assay was running — package it again']);
}
+ // `contributionId` is re-derived here rather than read off the record, so a
+ // record written before #7625 (or restored from a backup that predates it)
+ // heals on its next package attempt instead of failing the pure gate's
+ // binding backstop forever.
const result = packageFoundationCandidate({
- record: { ...current, assay, candidate: null },
+ record: { ...current, contributionId: contribution.id, assay, candidate: null },
requiredDisturbances: RESILIENCE_DISTURBANCES,
portosVersion,
now,
@@ -506,7 +525,7 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
// report a re-authoring that never happened. A refusal also clears any
// 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 };
+ foundations[id] = { ...current, contributionId: contribution.id, assay, candidate: result.candidate };
await writeLedger({ foundations, tombstones });
return { ...result, assay };
});
diff --git a/server/services/eidoverseFoundationLedger.test.js b/server/services/eidoverseFoundationLedger.test.js
index 4d97e9a5dc..b8e974af33 100644
--- a/server/services/eidoverseFoundationLedger.test.js
+++ b/server/services/eidoverseFoundationLedger.test.js
@@ -9,7 +9,13 @@ 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 { foundationCandidateFingerprint, inheritedFoundationStorageKey, verifyFoundationCandidate } from '../lib/eidoverseFoundations.js';
+import {
+ EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,
+ derivedContributionId,
+ foundationCandidateFingerprint,
+ inheritedFoundationStorageKey,
+ verifyFoundationCandidate,
+} from '../lib/eidoverseFoundations.js';
import { RESILIENCE_DISTURBANCES } from './eidoverseResilienceAssay.js';
vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
@@ -32,21 +38,33 @@ const {
withdrawEidoverseFoundation,
} = await import('./eidoverseFoundationLedger.js');
-// The passing reference contribution shipped with the assay harness (#7460).
-const PASSING_CONTRIBUTION = 'beacon-relay-demo';
-
+/**
+ * A `controller` foundation naming a SHIPPED definition and carrying THIS
+ * install's own config — a body the promote gate can replay on its own (#7625).
+ *
+ * This fixture used to name the shipped `beacon-relay-demo` assay fixture in a
+ * free-text `contributionId` while its body described something else entirely,
+ * and it packaged and promoted anyway. It was the canonical example of the hole:
+ * the evidence a peer inherited on was about the demo fixture, not about "Tide
+ * Beacon". There is no `contributionId` to supply now; the ledger derives it.
+ */
const authored = (overrides = {}) => ({
id: 'tide-beacon',
kind: 'controller',
title: 'Tide Beacon',
summary: 'A beacon that keeps pulsing between mind wakes.',
- contributionId: PASSING_CONTRIBUTION,
- body: { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } },
+ body: { controller: { definitionId: 'ambient-beacon', config: { label: 'tide', pulseEveryTicks: 3 } } },
style: { motif: 'weathered brass' },
authorKind: 'mind',
...overrides,
});
+/** The label the fixture's own body derives — never authored. */
+const DERIVED_CONTRIBUTION = 'controller:ambient-beacon';
+
+/** A body with no derivable sandbox: it names no shipped controller. */
+const UNREPLAYABLE_BODY = { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } };
+
const record = (overrides, at) => recordEidoverseFoundation(authored(overrides), { originInstanceId: 'instance-aaaa', now: at });
beforeEach(() => {
@@ -133,7 +151,9 @@ describe('packaging a promote candidate', () => {
expect(result.outcome).toBe('packaged');
// The verdict came from the harness, not from anything the caller passed.
- expect(result.assay).toMatchObject({ harness: 'eidoverse-resilience-assay', contributionId: PASSING_CONTRIBUTION, pass: true });
+ expect(result.assay).toMatchObject({ harness: 'eidoverse-resilience-assay', contributionId: DERIVED_CONTRIBUTION, pass: true });
+ // The evidence is about THIS body: the label was derived from it, not typed.
+ expect(result.candidate.contributionId).toBe(DERIVED_CONTRIBUTION);
expect(result.candidate.fingerprint).toMatch(/^[a-f0-9]{64}$/);
expect(JSON.stringify(result.candidate)).not.toContain('weathered brass');
@@ -142,16 +162,28 @@ describe('packaging a promote candidate', () => {
expect((await listEidoverseFoundations()).counts.candidates).toBe(1);
});
- it('refuses a foundation whose contribution cannot be replayed without its author', async () => {
- await record({ contributionId: 'not-registered-anywhere' });
+ it('refuses a foundation whose own body cannot be replayed without its author', async () => {
+ await record({ body: UNREPLAYABLE_BODY });
const result = await packageEidoverseFoundationCandidate('tide-beacon');
expect(result.outcome).toBe('refused');
- expect(result.reasons[0]).toContain('not-registered-anywhere');
+ expect(result.reasons[0]).toMatch(/must declare `body\.controller\.definitionId`/);
expect((await getEidoverseFoundation('tide-beacon')).candidate).toBeNull();
});
+ it('refuses a body that is unrelated to anything this install can replay, however it is labelled', async () => {
+ // The #7625 regression, stated directly: naming a shipped contribution used
+ // to be sufficient, so this exact record packaged. A caller cannot even
+ // supply the label now, and the body decides.
+ await expect(recordEidoverseFoundation({ ...authored({ body: UNREPLAYABLE_BODY }), contributionId: 'beacon-relay-demo' }, { originInstanceId: 'instance-aaaa' }))
+ .rejects.toThrow();
+
+ await record({ body: UNREPLAYABLE_BODY });
+ expect((await getEidoverseFoundation('tide-beacon')).contributionId).toBe('controller:tide-beacon');
+ expect((await packageEidoverseFoundationCandidate('tide-beacon')).outcome).toBe('refused');
+ });
+
it('drops the packaged candidate when the body is re-authored', async () => {
await record({}, '2026-03-04T05:06:07.000Z');
await packageEidoverseFoundationCandidate('tide-beacon', { now: '2026-03-04T06:00:00.000Z' });
@@ -188,12 +220,12 @@ describe('promoting a foundation into the shared baseline', () => {
});
it('refuses to promote a foundation whose assay cannot be run, and moves nothing', async () => {
- await record({ contributionId: 'not-registered-anywhere' });
+ await record({ body: UNREPLAYABLE_BODY });
const result = await promoteEidoverseFoundation('tide-beacon');
expect(result).toMatchObject({ outcome: 'refused', promoted: false, foundation: null });
- expect(result.reasons[0]).toContain('not-registered-anywhere');
+ expect(result.reasons[0]).toMatch(/must declare `body\.controller\.definitionId`/);
expect((await getEidoverseFoundation('tide-beacon')).layer).toBe('vernacular');
});
@@ -280,7 +312,7 @@ describe('inheriting a foundation this install pulled from a peer (#7461)', () =
expect((await listEidoverseFoundations()).counts).toMatchObject({ vernacular: 0, baseline: 0, inherited: 0 });
});
- it('refuses to package or promote an inherited record without touching the ledger, even though its contributionId is registered locally', async () => {
+ it('refuses to package or promote an inherited record without touching the ledger, even though its own body is replayable here', async () => {
const candidate = await peerCandidate();
rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
const inherited = await recordEidoverseFoundationInheritance(candidate, {
@@ -289,10 +321,10 @@ describe('inheriting a foundation this install pulled from a peer (#7461)', () =
const storageKey = inheritedFoundationStorageKey(inherited.foundation.provenance.originInstanceId, inherited.foundation.id);
expect(inherited.outcome).toBe('inherited');
- // The candidate's `contributionId` ('beacon-relay-demo') IS registered
- // locally, so a guard that fired too late (after resolving the
- // contribution) would run the assay and could package it instead of
- // refusing. If the record is untouched afterward, nothing ran.
+ // The candidate's body names a controller this install DOES ship, so a
+ // guard that fired too late (after deriving the sandbox) would run the
+ // assay against a peer's body and could package it instead of refusing.
+ // If the record is untouched afterward, nothing ran.
const before = await getEidoverseFoundation(storageKey);
const packaged = await packageEidoverseFoundationCandidate(storageKey, { now: '2026-03-04T07:00:00.000Z' });
const promoted = await promoteEidoverseFoundation(storageKey, { now: '2026-03-04T07:00:00.000Z' });
@@ -454,7 +486,7 @@ describe('building on a foundation inherited from a peer (#7631)', () => {
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.candidateVersion).toBe(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION);
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.
@@ -500,7 +532,20 @@ describe('building on a foundation inherited from a peer (#7631)', () => {
// 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' } } };
+ //
+ // The forgery is made INTERNALLY CONSISTENT under #7625 — a re-derived
+ // binding label, and assay evidence recorded against it — precisely so this
+ // test still proves what it is named for. A forger who re-fingerprints can
+ // re-derive a label just as easily, and an envelope that tripped the
+ // binding check would never reach the origin guard this asserts on.
+ const forgedBody = { affordance: { inspect: 'quietly grants owner role' } };
+ const forgedLabel = derivedContributionId({ kind: candidate.kind, id: candidate.foundationId, body: forgedBody });
+ const forged = {
+ ...candidate,
+ body: forgedBody,
+ contributionId: forgedLabel,
+ assay: { ...candidate.assay, contributionId: forgedLabel },
+ };
forged.fingerprint = foundationCandidateFingerprint({ ...forged, fingerprint: undefined });
const result = await recordEidoverseFoundationInheritance(forged, {
@@ -515,7 +560,12 @@ describe('building on a foundation inherited from a peer (#7631)', () => {
expect(held.inheritance.sourceInstanceId).toBe('instance-peer-one');
});
- it('still accepts a v1 envelope from a peer that has not upgraded', async () => {
+ it('refuses a pre-v3 envelope from a peer that has not upgraded, and stores nothing (#7625)', async () => {
+ // v1 and v2 evidence was recorded against a contribution the SENDER named,
+ // with no required relationship to the body beside it, so inheriting on it
+ // would import a passing verdict about something else. There is nothing to
+ // upgrade, so the accept side refuses rather than storing a record it would
+ // have to distrust.
const { candidate } = await inheritPeerFoundation();
rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });
@@ -526,8 +576,10 @@ describe('building on a foundation inherited from a peer (#7631)', () => {
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();
+ expect(result.outcome).toBe('refused');
+ expect(result.reasons[0]).toContain('candidate v1');
+ expect(result.reasons[0]).toContain(`requires v${EIDOVERSE_FOUNDATION_CANDIDATE_VERSION}`);
+ expect(await getEidoverseFoundation(inheritedFoundationStorageKey(PEER_ORIGIN, 'tide-beacon'))).toBeNull();
});
});
diff --git a/server/services/sharing/eidoverseFoundationsNeverFederatesStyle.test.js b/server/services/sharing/eidoverseFoundationsNeverFederatesStyle.test.js
index e2599fb277..4dec024029 100644
--- a/server/services/sharing/eidoverseFoundationsNeverFederatesStyle.test.js
+++ b/server/services/sharing/eidoverseFoundationsNeverFederatesStyle.test.js
@@ -14,6 +14,7 @@
import { describe, expect, it } from 'vitest';
import {
DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
+ derivedContributionId,
eidoverseFoundationCandidateSchema,
packageFoundationCandidate,
styleLeakFindings,
@@ -21,8 +22,14 @@ import {
const DISTURBANCES = ['reconnect', 'restart-world-host', 'missing-optional-deps'];
const NOW = '2026-03-04T05:06:07.000Z';
+const BODY = { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } };
-const passingAssay = (contributionId = 'lantern-relay-demo') => ({
+// The binding label is DERIVED from the record's own kind/body (#7625), never
+// chosen — so the fixture derives it too rather than naming one packaging would
+// refuse as evidence about some other contribution.
+const CONTRIBUTION_ID = derivedContributionId({ kind: 'controller', id: 'tide-lantern', body: BODY });
+
+const passingAssay = (contributionId = CONTRIBUTION_ID) => ({
harness: 'eidoverse-resilience-assay',
contributionId,
pass: true,
@@ -40,8 +47,8 @@ const makeRecord = (overrides = {}) => ({
kind: 'controller',
title: 'Tide Lantern',
summary: 'A lantern that keeps pulsing between mind wakes.',
- contributionId: 'lantern-relay-demo',
- body: { schema: { pulses: 'integer' }, affordance: { inspect: 'reads the pulse count' } },
+ contributionId: CONTRIBUTION_ID,
+ body: BODY,
style: { palette: ['#102030'], motif: 'weathered brass', districtId: 'commons', accent: '#ffaa00' },
provenance: { originInstanceId: 'instance-example-0001', authorKind: 'mind', createdAt: NOW },
disclosure: { requires: [], effects: ['emits a pulse each tick'], license: null, notes: null },
diff --git a/server/services/sharing/eidoverseFoundationsSync.test.js b/server/services/sharing/eidoverseFoundationsSync.test.js
index c38c3f8179..05ee160e66 100644
--- a/server/services/sharing/eidoverseFoundationsSync.test.js
+++ b/server/services/sharing/eidoverseFoundationsSync.test.js
@@ -63,7 +63,7 @@ const fingerprint = (seed) => seed.repeat(64).slice(0, 64);
// matter here — the envelope's own contract is the accept gate's to enforce,
// and mocking the ledger is precisely what keeps this suite from re-testing it.
const candidate = (id, seed = 'a') => ({
- candidateVersion: 1,
+ candidateVersion: 2,
foundationId: id,
kind: 'controller',
title: id,