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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
gate Eidoverse promotions on a local-vs-baseline ownership boundary and an assay the server runs itself (#7455)
[._.]/ Adam Eivyd33f66c1c8d6
diff --git a/docs/API.md b/docs/API.mdindex f216221ac3..4089aeee84 100644--- a/docs/API.md+++ b/docs/API.md@@ -355,6 +355,10 @@ federate world records.| POST | `/eidoverse/world/project` | Project current PortOS resources into the world using the saved recipe || POST | `/eidoverse/world/augment` | Apply bounded, allowlisted world construction/role operations || POST | `/eidoverse/world/say` | Send a bounded message as the PortOS CoS presence |+| GET | `/eidoverse/world/foundations` | Local foundation ledger: ownership layer, provenance, and packaged promote candidates |+| POST | `/eidoverse/world/foundations` | Record (or re-author) a local vernacular foundation — the layer is never caller-supplied |+| GET | `/eidoverse/world/foundations/:id` | One foundation record |+| POST | `/eidoverse/world/foundations/:id/candidate` | Run the agent-free resilience assay and package a promote candidate; a refusal returns 200 with its reasons |### Legacy OpenWorld / CyberCitydiff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 4d627b0c25..41d0ce933e 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -68,6 +68,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, explicit display aliases keyed by opaque resource identity (never backfilled from records), user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. Guest travel sessions and live chat cursors are ephemeral transport state held only in memory; they are not a new record store or sync category. Explicit guest conversation follows the [guest-chat ADR](decisions/2026-09-05-eidoverse-guest-chat.md). PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.+- Eidoverse world foundations ledger — `data/eidoverse/foundations.json` (#7455). The install-local record of every durable world foundation this instance authored: its ownership layer (`vernacular` by default, `baseline` once promoted), the promotable `body`, the vernacular `style` layer that never leaves, provenance (opaque instance id + author kind), the last agent-free resilience verdict, and the last packaged promote candidate. `file-primary` and **intentionally machine-local — never federated**: the only thing authorized to leave the install is a packaged candidate envelope, and only through an explicit promote. No `data.reference/` seed and no migration — an absent file IS the empty ledger every install starts from, so a seed would only put shipped defaults where a user's foundations belong. Backed up with the rest of `data/eidoverse/`.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + an ordered list of steps, each a REFERENCE to a scheduled task (`data/cos/task-schedule.json` or the app job store) plus its per-invocation overrides. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and a step's scheduled-task reference names task types and managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).- Manual maintenance runs — `data/cos/maintenance-runs.json`. A capped list of the Schedule tab's "Run maintenance now" records: the app, the pinned provider/model/effort, the ladder's steps, the per-step completion ledger and the current hold reason. `ephemeral-file` and machine-local like the burn plan (its steps name task types and managed apps that only exist here); deleting it only forgets progress — a run in flight would have to be started again. See [Quota Burn → Maintenance sequence](./QUOTA-BURN.md#maintenance-sequence).diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdindex e1ce55632e..f3255371fc 100644--- a/docs/features/eidoverse.md+++ b/docs/features/eidoverse.md@@ -669,8 +669,68 @@ any failure. Two reference fixtures live beside the harness: a passingskips it; only `eidoverseResilienceAssay.test.js` exercises it, proving theharness catches the "author-mind-only" failure mode).-This harness is standalone and does not yet gate anything — the actual-promote-to-baseline pipeline is-[#7455](https://github.com/atomantic/PortOS/issues/7455), not yet built. Once-it exists, it is expected to call `runResilienceAssay()` (or shell out to this-script) per candidate contribution and block promotion on a failing verdict.+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+`server/services/eidoverseResilienceContributions.js`.++### Local vernacular vs shared baseline, and the promote gate (#7455)++Federated instances are meant to keep their own style and buildings while+discoveries that help everyone find a path into a shared PortOS baseline. That+boundary is a data model, not a convention. `server/lib/eidoverseFoundations.js`+declares three ownership layers:++- **`runtime`** — the shared Eidoverse/PortOS framework. Upstream's to change; an+ instance never authors into it and never promotes it.+- **`baseline`** — the shared promoted-foundation population a peer can inherit.+- **`vernacular`** — this install's own artifacts. **The default for everything+ authored locally**, so nothing is shared by omission; promoting is an explicit+ act with a gate in front of it, never the absence of a "keep this private" flag.++A foundation is `{ body, style }` **by construction** rather than one bag with a+blocklist. `body` is the promotable substance (declared schema, affordance,+optional controller spec); `style` is the cosmetics that make this Commons look+like itself — palette, motif, asset paths, placement, district, display aliases.+Packaging carries `body` and drops `style` outright, which is what makes "a peer+inherits the foundation without the author's cosmetics overwriting its own style+layer" a property of the payload rather than a merge rule a receiver has to get+right. A style-only key found *inside* `body` **refuses** the package instead of+being silently trimmed.++`data/eidoverse/foundations.json` (`server/services/eidoverseFoundationLedger.js`)+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+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.++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).+3. **Style leak** — a vernacular style key inside `body`.+4. **Federation safety** — machine identity, PII, home/Windows paths, IP or MAC+ literals, and credential-shaped values anywhere in the candidate. Nothing is+ redacted and shipped: a redacted promote would leave the author believing they+ published what they wrote.++The candidate envelope carries a content-addressed `fingerprint` (sha256 over the+canonicalized envelope), so `verifyFoundationCandidate()` is one gate seen from+both sides — the packaging side and a receiving peer's. That receiving side (peer+pull/inherit), the promote UI, and the capability-gated mind tool are still to+come; the envelope's own `candidateVersion` is what they will gate on.diff --git a/scripts/eidoverse-resilience-assay.js b/scripts/eidoverse-resilience-assay.jsindex 722ebe0b4e..481f59d7c4 100644--- a/scripts/eidoverse-resilience-assay.js+++ b/scripts/eidoverse-resilience-assay.js@@ -7,49 +7,25 @@** Usage:* node scripts/eidoverse-resilience-assay.js- * Runs every reference contribution module under- * server/services/eidoverseResilienceAssayFixtures/*.contribution.js.- * (The deliberately-failing fixture in that directory is named- * `*.failing.fixture.js` on purpose, so it is exercised only by- * eidoverseResilienceAssay.test.js and never trips this default run.)+ * Runs every registered contribution module (see+ * server/services/eidoverseResilienceContributions.js, which the promote+ * path in eidoverseFoundationLedger.js resolves through as well, by+ * contribution id rather than by path).** node scripts/eidoverse-resilience-assay.js <module-path> [...more]* Runs the assay against specific contribution modules instead. Each* module must have a default export, or a single named export, that is* a zero-argument factory returning `{ id, createSandbox, invariants? }`* — see server/services/eidoverseResilienceAssayFixtures/beaconRelay.contribution.js.- * This is the shape the promote path (#7455, not yet built) is expected- * to call with each candidate contribution's module path, or it may- * import `runResilienceAssay` directly instead of shelling out here.** Exits 0 when every contribution passes, 1 otherwise. Makes no network,* filesystem-beyond-the-fixtures, provider, or agent call.*/-import { readdirSync } from 'node:fs';-import { dirname, join, resolve } from 'node:path';-import { fileURLToPath, pathToFileURL } from 'node:url';+import { resolve } from 'node:path';import { runResilienceAssay } from '../server/services/eidoverseResilienceAssay.js';+import { listContributionModulePaths, loadContributionModule } from '../server/services/eidoverseResilienceContributions.js';import { isDirectlyInvoked } from './lib/directInvocation.js';-const __dirname = dirname(fileURLToPath(import.meta.url));-const DEFAULT_FIXTURES_DIR = join(__dirname, '..', 'server', 'services', 'eidoverseResilienceAssayFixtures');--function defaultContributionModulePaths() {- return readdirSync(DEFAULT_FIXTURES_DIR)- .filter((file) => file.endsWith('.contribution.js'))- .sort()- .map((file) => join(DEFAULT_FIXTURES_DIR, file));-}--async function loadContribution(modulePath) {- const mod = await import(pathToFileURL(modulePath).href);- const factory = mod.default || Object.values(mod).find((value) => typeof value === 'function');- if (typeof factory !== 'function') {- throw new Error(`${modulePath} does not export a contribution factory function`);- }- return factory();-}-function printResult(modulePath, result) {const icon = result.pass ? '✅' : '❌';console.log(`${icon} ${result.contributionId} (${modulePath})`);@@ -61,7 +37,7 @@ function printResult(modulePath, result) {export async function runAssayCli(args) {const modulePaths = args.length > 0? args.map((path) => resolve(process.cwd(), path))- : defaultContributionModulePaths();+ : await listContributionModulePaths();if (modulePaths.length === 0) {console.log('ℹ️ No resilience-assay contributions to run.');@@ -70,7 +46,7 @@ export async function runAssayCli(args) {let allPassed = true;for (const modulePath of modulePaths) {- const contribution = await loadContribution(modulePath);+ const contribution = await loadContributionModule(modulePath);const result = runResilienceAssay(contribution);printResult(modulePath, result);if (!result.pass) allPassed = false;diff --git a/server/lib/README.md b/server/lib/README.mdindex 3e7113d4cd..e96feab07d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -569,6 +569,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `dispatchLabels.js` | slashdo dispatch-hint contract: `model:light/medium/heavy` + `effort:low/medium/high/xhigh/max` vocabulary, prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), the read-side inverse (`dispatchHintFromLabels` — recovers `{model, effort}` from a raw label-name list, used by branch-reconcile's per-branch routing hint), GitHub/GitLab vs Jira label formatting, optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `MANDATORY_DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`, `MANDATORY_JIRA_DISPATCH_HINT_GUIDANCE`, `REFERENCE_WATCH_LABEL_CONTRACT`, plus the consumer-side pair `DISPATCH_HINT_READING_GUIDANCE` / `DISPATCH_HINT_FANOUT_GUIDANCE` — what the labels mean to an agent that RECEIVES them (the preloaded `open-issues` task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). All forge filing callers require both dispatch axes and verify labels after creation; help wanted requires specific hardware validation or valuable input from real users; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. |+| `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 a style-only key smuggled into `body` rather than silently trimming it. `federationSafetyFindings` fails a candidate closed on machine identity, PII, home/Windows paths, IP or MAC literals and credential shapes (reusing `scrubSecretTokens`), naming the offending JSON path — never redacting and shipping. `assayEvidenceFromVerdict` / `assayEvidenceRefusal` gate on the agent-free resilience verdict (#7460), including that the evidence is bound to the contribution this foundation names. `packageFoundationCandidate` and `verifyFoundationCandidate` are the one gate seen from the sending and receiving sides, over a content-addressed `fingerprint`. Pure: callers pass `now`. || `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. || `eidoverseWorldSignals.js` | Pure raw-source-to-signal shaping: `buildEidoverseWorldSignals`, stable opaque host/peer IDs, storage and Jira aggregates; no service reads. |diff --git a/server/lib/eidoverseFoundations.js b/server/lib/eidoverseFoundations.jsnew file mode 100644index 0000000000..e2e6ad6b89--- /dev/null+++ b/server/lib/eidoverseFoundations.js@@ -0,0 +1,474 @@+/**+ * Local-vs-baseline ownership for Eidoverse world foundations, plus the+ * packaging/validation step that turns one instance's vernacular artifact into+ * a promote candidate for the shared PortOS baseline (#7455, epic #7453).+ *+ * SwarmWorld's federation shape, as Adam put it: fork locally, contribute+ * foundations globally. Three ownership layers carry that:+ *+ * - `runtime` — the shared Eidoverse/PortOS framework. Upstream owns it;+ * an instance never authors into it and never promotes it.+ * - `baseline` — the shared promoted-foundation population a peer can pull+ * and inherit.+ * - `vernacular` — this install's own style and buildings.+ *+ * `vernacular` is the DEFAULT for everything authored locally, so nothing is+ * ever shared by omission — promoting is an explicit act with a gate in front+ * of it, never the absence of a "keep this private" flag.+ *+ * A foundation is `{ body, style }` by construction rather than one bag with a+ * blocklist. `body` is the promotable substance (declared schema, affordance,+ * optional controller spec); `style` is the cosmetics that make this install's+ * Commons look like itself (palette, motif, asset paths, placement, district,+ * display aliases). `packageFoundationCandidate()` carries `body` and drops+ * `style` outright, which is what makes "a peer inherits the foundation without+ * its author's cosmetics overwriting the peer's style layer" a property of the+ * payload instead of a merge rule some later receiver has to get right. A+ * style-only key found INSIDE `body` refuses the package rather than being+ * silently stripped: quietly promoting an author's accent color as though it+ * were substance is the failure this split exists to prevent.+ *+ * Two gates run before a candidate exists at all:+ *+ * 1. **Agent-free resilience evidence.** `services/eidoverseResilienceAssay.js`+ * (#7460) already decides whether a contribution still works with its+ * author mind gone. This module consumes its VERDICT rather than running+ * 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+ * 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+ * the assay fresh on every package attempt, so evidence is never older+ * than the body it vouches for.+ * 2. **Federation safety.** A promote payload is the one Eidoverse artifact+ * authorized to cross the federation layer, so it fails closed: machine+ * identity, PII, home/Windows paths, IP or MAC literals, and+ * credential-shaped values anywhere in the candidate REFUSE the package+ * with the offending JSON path named. Nothing is redacted and shipped —+ * a redacted promote would leave the author believing they published what+ * they wrote. See the "PII must not ride the federation layer" rule in+ * root `AGENTS.md` and the machine-local privacy ADR.+ *+ * `fingerprint` is content-addressed (sha256 over the canonicalized envelope+ * minus the fingerprint itself), so a peer can verify a candidate it was handed+ * and the provenance graph (#7461) has a stable artifact identity to hang edges+ * from.+ *+ * Pure: no I/O, no clock of its own (callers pass `now`), no provider calls.+ * The persisted ledger lives in `services/eidoverseFoundationLedger.js`.+ */++import { createHash } from 'node:crypto';+import { z } from 'zod';+import { canonicalStringify } from './objects.js';+import { scrubSecretTokens } from './secretText.js';++/** Ownership layers, widest-shared first. See the module header. */+export const EIDOVERSE_FOUNDATION_LAYERS = Object.freeze(['runtime', 'baseline', 'vernacular']);++/** Anything authored on this install starts local. Promotion is explicit. */+export const DEFAULT_EIDOVERSE_FOUNDATION_LAYER = 'vernacular';++/** What a foundation can BE. Deliberately closed — a promote payload a peer+ * cannot classify is a payload it cannot safely inherit. */+export const EIDOVERSE_FOUNDATION_KINDS = Object.freeze(['schema', 'affordance', 'controller', 'district-template']);++/** Wire stamp on the promote envelope. The peer pull/inherit slice gates on+ * this; it is deliberately separate from `PORTOS_SCHEMA_VERSIONS`, which+ * versions STORAGE layouts for the record-sync transports this payload does+ * not ride. */+export const EIDOVERSE_FOUNDATION_CANDIDATE_VERSION = 1;++/** Storage-layout version stamped on `data/eidoverse/foundations.json`. */+export const EIDOVERSE_FOUNDATION_LEDGER_SCHEMA_VERSION = 1;++/**+ * Keys that belong to the vernacular style layer and must never appear inside a+ * foundation `body`. Found there, they refuse the package — see the header.+ */+export const EIDOVERSE_STYLE_ONLY_KEYS = Object.freeze([+ 'accent', 'alias', 'aliases', 'asset', 'assets', 'avatar', 'color', 'colors',+ 'district', 'districtId', 'labelAliases', 'lib', 'material', 'materials',+ 'motif', 'palette', 'placement', 'pos', 'texture', 'textures', 'yaw',+]);++const STYLE_ONLY_KEY_SET = new Set(EIDOVERSE_STYLE_ONLY_KEYS);++export const FOUNDATION_LIMITS = Object.freeze({+ idMax: 64,+ titleMax: 80,+ summaryMax: 400,+ bodyBytes: 16_384,+ styleBytes: 16_384,+ disclosureItems: 12,+ disclosureItemMax: 160,+ noteMax: 600,+ findingsMax: 40,+});++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`. */+const contributionIdSchema = z.string().trim().min(1).max(120);++const isoDateSchema = z.string().trim().min(1).max(40).refine(+ (value) => !Number.isNaN(Date.parse(value)),+ 'must be an ISO-8601 timestamp',+);++const boundedJsonObject = (maxBytes) => z.record(z.string().min(1).max(64), z.unknown())+ .refine((value) => JSON.stringify(value).length <= maxBytes, `must serialize to at most ${maxBytes} bytes`);++/** The promotable substance. Free-form beneath the top level on purpose: the+ * controller/affordance vocabulary is still being written (#7456), and pinning+ * it here would make every vocabulary addition a schema migration. What IS+ * pinned is the size cap and the style/privacy scans below, which is what a+ * receiving peer actually needs to be safe. */+const foundationBodySchema = boundedJsonObject(FOUNDATION_LIMITS.bodyBytes);++const foundationStyleSchema = boundedJsonObject(FOUNDATION_LIMITS.styleBytes);++export const foundationDisclosureSchema = z.object({+ requires: z.array(z.string().trim().min(1).max(FOUNDATION_LIMITS.disclosureItemMax)).max(FOUNDATION_LIMITS.disclosureItems).default([]),+ effects: z.array(z.string().trim().min(1).max(FOUNDATION_LIMITS.disclosureItemMax)).max(FOUNDATION_LIMITS.disclosureItems).default([]),+ license: z.string().trim().min(1).max(80).nullable().default(null),+ notes: z.string().trim().min(1).max(FOUNDATION_LIMITS.noteMax).nullable().default(null),+}).strict();++/**+ * Who authored this, at the coarsest grain that is still useful. The instance+ * id is PortOS's own opaque federation identity — never a hostname, never a+ * tailnet name — and there is deliberately NO author display name: the richer+ * agent-artifact provenance graph is #7461's to design, and a name added here+ * "for now" is a privacy decision made by accident.+ */+export const foundationProvenanceSchema = z.object({+ originInstanceId: z.string().trim().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/, 'must be an opaque instance id'),+ authorKind: z.enum(['mind', 'cos', 'user']),+ createdAt: isoDateSchema,+}).strict();++export const foundationAssayEvidenceSchema = z.object({+ harness: z.literal('eidoverse-resilience-assay'),+ contributionId: contributionIdSchema,+ pass: z.boolean(),+ disturbances: z.array(z.string().trim().min(1).max(64)).min(1).max(16),+ ranAt: isoDateSchema,+ reasons: z.array(z.string().trim().min(1).max(400)).max(FOUNDATION_LIMITS.findingsMax).default([]),+}).strict();++/** The local ledger record. `style` stays here and never leaves the install. */+export const eidoverseFoundationRecordSchema = z.object({+ id: foundationIdSchema,+ layer: z.enum(['vernacular', 'baseline']),+ 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,+ style: foundationStyleSchema,+ provenance: foundationProvenanceSchema,+ disclosure: foundationDisclosureSchema,+ assay: foundationAssayEvidenceSchema.nullable().default(null),+ // The last packaged envelope, kept verbatim. Deliberately NOT re-validated+ // here: it was gated by `verifyFoundationCandidate` when it was written, and+ // a stored envelope from a newer install must not make the whole record+ // unreadable — the promote path re-verifies the envelope it actually uses.+ candidate: z.unknown().optional(),+ promotedAt: isoDateSchema.nullable().default(null),+ updatedAt: isoDateSchema,+}).strict();++/** The `:id` route parameter — the same slug contract as a record's own id. */+export const eidoverseFoundationIdParamSchema = z.object({ id: foundationIdSchema }).strict();++/** What a caller (route, mind tool, test) may author. Layer is NOT accepted:+ * a new local artifact is `vernacular` by construction, and moving to+ * `baseline` is what the promote path is for. */+export const eidoverseFoundationInputSchema = z.object({+ id: foundationIdSchema,+ 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,+ style: foundationStyleSchema.default({}),+ disclosure: foundationDisclosureSchema.default({}),+ authorKind: z.enum(['mind', 'cos', 'user']).default('user'),+}).strict();++/** The promote envelope — the only shape authorized to cross to a peer. */+export const eidoverseFoundationCandidateSchema = z.object({+ candidateVersion: z.literal(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION),+ foundationId: foundationIdSchema,+ 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,+ provenance: foundationProvenanceSchema.extend({+ packagedAt: isoDateSchema,+ portosVersion: z.string().trim().min(1).max(40),+ }).strict(),+ assay: foundationAssayEvidenceSchema,+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/, 'must be a sha256 hex digest'),+}).strict();++// ---------------------------------------------------------------------------+// Ownership+// ---------------------------------------------------------------------------++/**+ * Why this foundation cannot be offered to the shared baseline, or `null` when+ * it can. Returns a reason instead of throwing so the packaging result can+ * report every refusal together rather than surfacing the first one.+ */+export function layerPromoteRefusal(layer) {+ if (layer === 'runtime') return 'runtime is the shared Eidoverse/PortOS framework — it is upstream\'s to change, not an instance\'s to promote';+ if (layer === 'baseline') return 'already part of the shared baseline — promote applies to a local vernacular foundation';+ if (layer === DEFAULT_EIDOVERSE_FOUNDATION_LAYER) return null;+ return `unknown ownership layer "${layer}" — expected one of ${EIDOVERSE_FOUNDATION_LAYERS.join(', ')}`;+}++// ---------------------------------------------------------------------------+// Safety scans+// ---------------------------------------------------------------------------++const PRIVACY_PATTERNS = Object.freeze([+ // `/Users/<name>/…`, `/home/<name>/…` — the OS username by another name.+ ['home-path', /(?:^|[\s"'`(])(?:\/Users|\/home)\/[^/\s"'`]+/i],+ // `C:\Users\<name>` and any other Windows drive-absolute path.+ ['windows-path', /\b[A-Za-z]:[\\/](?:Users[\\/])?[^\s"'`]+/],+ // Dotted quads. A four-part version string is refused too, and deliberately:+ // the payload leaves this machine, so "looks like an address" is the right+ // side to fail on, and the finding names the exact JSON path to fix.+ ['ip-literal', /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/],+ // Tailscale MagicDNS and mDNS names.+ ['network-host', /\b[A-Za-z0-9-]+\.(?:ts\.net|local)\b/i],+ ['mac-address', /\b[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5}\b/],+ ['email-address', /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/],+]);++const describePath = (path) => (path.length === 0 ? '<root>' : path.join('.'));++/**+ * Walk a JSON-shaped value once, reporting every string it contains AND every+ * object key it passes through. Keys matter as much as values here: a key named+ * for a host leaks the host, and a key is what the style-layer scan looks at.+ *+ * @param {unknown} value+ * @param {(entry: { text: string, path: string[], kind: 'key'|'value' }) => void} visit+ */+function walkJsonText(value, visit, path = []) {+ if (typeof value === 'string') {+ visit({ text: value, path, kind: 'value' });+ return;+ }+ if (Array.isArray(value)) {+ value.forEach((child, index) => walkJsonText(child, visit, [...path, String(index)]));+ return;+ }+ if (!value || typeof value !== 'object') return;+ for (const [key, child] of Object.entries(value)) {+ const childPath = [...path, key];+ visit({ text: key, path: childPath, kind: 'key' });+ walkJsonText(child, visit, childPath);+ }+}++/**+ * Machine identity / PII / credential findings anywhere in a JSON-shaped value.+ *+ * @returns {Array<{ code: string, path: string, detail: string }>}+ */+export function federationSafetyFindings(value) {+ const findings = [];+ walkJsonText(value, ({ text, path }) => {+ for (const [code, pattern] of PRIVACY_PATTERNS) {+ if (pattern.test(text)) findings.push({ code, path: describePath(path), detail: `a ${code.replace('-', ' ')} may not cross the federation layer` });+ }+ if (scrubSecretTokens(text) !== text) {+ findings.push({ code: 'secret-token', path: describePath(path), detail: 'a credential-shaped value may not cross the federation layer' });+ }+ });+ return findings.slice(0, FOUNDATION_LIMITS.findingsMax);+}++/**+ * Style-layer keys found inside a foundation `body`. These refuse the package:+ * the split is what keeps an inheriting peer's own cosmetics intact, so a+ * foundation that smuggles its author's accent color through `body` has to be+ * fixed rather than quietly trimmed.+ */+export function styleLeakFindings(body) {+ const findings = [];+ walkJsonText(body, ({ text, path, kind }) => {+ if (kind !== 'key' || !STYLE_ONLY_KEY_SET.has(text)) return;+ findings.push({ code: 'style-in-body', path: describePath(path), detail: `"${text}" belongs to the vernacular style layer and is never promoted` });+ });+ return findings.slice(0, FOUNDATION_LIMITS.findingsMax);+}++// ---------------------------------------------------------------------------+// Assay evidence+// ---------------------------------------------------------------------------++/**+ * Fold a `runResilienceAssay()` verdict into the evidence block a candidate+ * carries. Keeping the conversion here (rather than letting each caller shape+ * its own object) is what lets the CLI, a route, and a future mind tool all+ * produce evidence that the same gate can read.+ *+ * @param {{contributionId?: string, pass?: boolean, scenarios?: Array, reasons?: string[]}} verdict+ * @param {{ranAt: string}} options+ */+export function assayEvidenceFromVerdict(verdict, { ranAt }) {+ return {+ harness: 'eidoverse-resilience-assay',+ contributionId: verdict?.contributionId || 'unknown-contribution',+ pass: verdict?.pass === true,+ disturbances: (verdict?.scenarios || []).map((scenario) => scenario?.disturbance).filter((id) => typeof id === 'string' && id.length > 0),+ ranAt,+ reasons: (verdict?.reasons || []).slice(0, FOUNDATION_LIMITS.findingsMax).map((reason) => String(reason).slice(0, 400)),+ };+}++/**+ * Why the recorded assay evidence does not clear the promote gate, or `null`.+ *+ * `requiredDisturbances` is passed in rather than imported so this pure module+ * never reaches into the service layer; callers hand it+ * `RESILIENCE_DISTURBANCES` from `services/eidoverseResilienceAssay.js`.+ */+export function assayEvidenceRefusal(assay, requiredDisturbances, { contributionId } = {}) {+ if (!assay) return 'no agent-free resilience assay has been recorded — run `npm run eidoverse:assay` against this contribution first';+ const parsed = foundationAssayEvidenceSchema.safeParse(assay);+ if (!parsed.success) return `recorded assay evidence is malformed: ${parsed.error.issues[0]?.message || 'unreadable'}`;+ // The evidence has to be about THIS foundation. Without the binding a passing+ // verdict from any other contribution would clear the gate, which is the+ // borrowed-credential version of the failure the assay exists to catch.+ if (contributionId && parsed.data.contributionId !== contributionId) {+ return `the recorded assay ran against "${parsed.data.contributionId}", not this foundation's contribution "${contributionId}"`;+ }+ if (!parsed.data.pass) return `the agent-free resilience assay failed: ${parsed.data.reasons[0] || 'no reason recorded'}`;+ const covered = new Set(parsed.data.disturbances);+ const missing = requiredDisturbances.filter((disturbance) => !covered.has(disturbance));+ if (missing.length > 0) return `the recorded assay did not cover every disturbance (missing: ${missing.join(', ')})`;+ return null;+}++// ---------------------------------------------------------------------------+// Packaging+// ---------------------------------------------------------------------------++/** sha256 over the canonicalized envelope, excluding the digest itself. */+export function foundationCandidateFingerprint(candidate) {+ return createHash('sha256').update(canonicalStringify(withoutFingerprint(candidate))).digest('hex');+}++/**+ * The envelope minus its own digest — both the hash input and the privacy-scan+ * input. The digest is excluded from the scan because a sha256 is 64 unbroken+ * hex characters, which is exactly the shape `scrubSecretTokens` treats as a+ * leaked credential; hashing our own hash would be the same mistake.+ */+function withoutFingerprint(candidate) {+ const { fingerprint: _digest, ...rest } = candidate;+ return rest;+}++/**+ * Package a local vernacular foundation into a promote candidate.+ *+ * @param {object} options+ * @param {object} options.record - a ledger record (see `eidoverseFoundationRecordSchema`)+ * @param {string[]} options.requiredDisturbances - the assay's full disturbance suite+ * @param {string} options.portosVersion+ * @param {string} options.now - ISO timestamp supplied by the caller+ * @returns {{ outcome: 'packaged'|'refused', candidate: object|null, reasons: string[], findings: Array }}+ */+export function packageFoundationCandidate({ record, requiredDisturbances, portosVersion, now }) {+ const parsed = eidoverseFoundationRecordSchema.safeParse(record);+ if (!parsed.success) {+ return {+ outcome: 'refused',+ candidate: null,+ reasons: parsed.error.issues.slice(0, FOUNDATION_LIMITS.findingsMax).map((issue) => `${describePath(issue.path.map(String))}: ${issue.message}`),+ findings: [],+ };+ }+ const foundation = parsed.data;++ // Two refusals the envelope gate below cannot phrase usefully: ownership+ // layer is not carried on the envelope at all, and a missing assay would+ // surface there as a bare "expected object, received null" rather than as+ // "go run the assay". Everything else — style leak, federation safety,+ // fingerprint, envelope shape — is left to `verifyFoundationCandidate` so the+ // packaging side and the receiving side share one definition of valid.+ const reasons = [+ layerPromoteRefusal(foundation.layer),+ assayEvidenceRefusal(foundation.assay, requiredDisturbances, { contributionId: foundation.contributionId }),+ ].filter(Boolean);+ if (reasons.length > 0) return { outcome: 'refused', candidate: null, reasons, findings: [] };++ const draft = {+ candidateVersion: EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,+ foundationId: foundation.id,+ kind: foundation.kind,+ title: foundation.title,+ summary: foundation.summary,+ contributionId: foundation.contributionId,+ body: foundation.body,+ disclosure: foundation.disclosure,+ provenance: { ...foundation.provenance, packagedAt: now, portosVersion },+ assay: foundation.assay,+ };+ const candidate = { ...draft, fingerprint: foundationCandidateFingerprint(draft) };++ // Re-read our own output through the envelope gate. The packaging path and+ // the receiving path then share one definition of "valid candidate" rather+ // than two that can drift.+ const verified = verifyFoundationCandidate(candidate, { requiredDisturbances });+ if (!verified.valid) return { outcome: 'refused', candidate: null, reasons: verified.reasons, findings: verified.findings };++ return { outcome: 'packaged', candidate, reasons: [], findings: [] };+}++/**+ * Validate a candidate envelope — the gate the packaging path runs on its own+ * output and the gate a peer runs on one it was handed. Checks the envelope+ * schema, the content-addressed fingerprint, the assay verdict, and federation+ * safety, and never throws: a malformed candidate is a verdict, not a crash.+ *+ * @returns {{ valid: boolean, reasons: string[], findings: Array }}+ */+export function verifyFoundationCandidate(candidate, { requiredDisturbances }) {+ const parsed = eidoverseFoundationCandidateSchema.safeParse(candidate);+ if (!parsed.success) {+ return {+ valid: false,+ reasons: parsed.error.issues.slice(0, FOUNDATION_LIMITS.findingsMax).map((issue) => `${describePath(issue.path.map(String))}: ${issue.message}`),+ findings: [],+ };+ }+ const envelope = parsed.data;+ const reasons = [];++ if (foundationCandidateFingerprint(envelope) !== envelope.fingerprint) {+ reasons.push('fingerprint does not match the candidate body — the payload was altered after packaging');+ }++ const assayRefusal = assayEvidenceRefusal(envelope.assay, requiredDisturbances, { contributionId: envelope.contributionId });+ if (assayRefusal) reasons.push(assayRefusal);++ const findings = [...styleLeakFindings(envelope.body), ...federationSafetyFindings(withoutFingerprint(envelope))];+ for (const finding of findings) reasons.push(`${finding.path}: ${finding.detail} (${finding.code})`);++ return { valid: reasons.length === 0, reasons, findings };+}diff --git a/server/lib/eidoverseFoundations.test.js b/server/lib/eidoverseFoundations.test.jsnew file mode 100644index 0000000000..093628d2b4--- /dev/null+++ b/server/lib/eidoverseFoundations.test.js@@ -0,0 +1,159 @@+/**+ * The promote gate is a privacy and data-ownership boundary: what it lets+ * through is what leaves this install for a shared baseline other people pull.+ * So these tests pin the REFUSALS — a leak, a borrowed assay verdict, an+ * altered payload — rather than enumerating the happy path's field list.+ */+import { describe, expect, it } from 'vitest';+import {+ DEFAULT_EIDOVERSE_FOUNDATION_LAYER,+ EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,+ assayEvidenceFromVerdict,+ federationSafetyFindings,+ foundationCandidateFingerprint,+ layerPromoteRefusal,+ packageFoundationCandidate,+ styleLeakFindings,+ verifyFoundationCandidate,+} from './eidoverseFoundations.js';++const DISTURBANCES = ['reconnect', 'restart-world-host', 'missing-optional-deps'];+const NOW = '2026-03-04T05:06:07.000Z';++const passingAssay = (contributionId = 'beacon-relay-demo') => ({+ harness: 'eidoverse-resilience-assay',+ contributionId,+ pass: true,+ disturbances: [...DISTURBANCES],+ ranAt: NOW,+ reasons: [],+});++const makeRecord = (overrides = {}) => ({+ id: 'tide-beacon',+ layer: DEFAULT_EIDOVERSE_FOUNDATION_LAYER,+ kind: 'controller',+ 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' } },+ 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 },+ assay: passingAssay(),+ candidate: null,+ promotedAt: null,+ updatedAt: NOW,+ ...overrides,+});++const packageRecord = (overrides) => packageFoundationCandidate({+ record: makeRecord(overrides),+ requiredDisturbances: DISTURBANCES,+ portosVersion: '9.9.9',+ now: NOW,+});++describe('eidoverse foundation ownership', () => {+ it('promotes only from the local vernacular layer', () => {+ expect(layerPromoteRefusal('vernacular')).toBeNull();+ expect(layerPromoteRefusal('runtime')).toMatch(/upstream/);+ expect(layerPromoteRefusal('baseline')).toMatch(/already part of the shared baseline/);+ expect(layerPromoteRefusal('mystery')).toMatch(/unknown ownership layer/);+ });+});++describe('packaging a promote candidate', () => {+ it('carries the promotable body and leaves the author\'s style layer behind', () => {+ const result = packageRecord();++ 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' } });+ // 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');+ expect(result.candidate).not.toHaveProperty('style');+ expect(verifyFoundationCandidate(result.candidate, { requiredDisturbances: DISTURBANCES }).valid).toBe(true);+ });++ it('refuses a style-only key smuggled into the body instead of trimming it', () => {+ const result = packageRecord({ body: { affordance: { inspect: 'reads the pulse count' }, accent: '#ff00aa' } });++ expect(result.outcome).toBe('refused');+ expect(result.reasons.join(' ')).toContain('accent');+ expect(result.findings.some((finding) => finding.code === 'style-in-body')).toBe(true);+ });++ it('refuses machine identity, PII and credentials anywhere in the payload', () => {+ const result = packageRecord({+ body: {+ affordance: { inspect: 'reads the pulse count' },+ notes: 'built against 192.0.2.10 by [email protected]',+ install: { root: '/Users/exampleuser/portos' },+ },+ });++ expect(result.outcome).toBe('refused');+ const codes = result.findings.map((finding) => finding.code);+ expect(codes).toContain('ip-literal');+ expect(codes).toContain('email-address');+ expect(codes).toContain('home-path');+ // The refusal names where to fix it rather than shipping a redacted body.+ expect(result.reasons.join(' ')).toContain('body.install.root');+ expect(result.candidate).toBeNull();+ });++ it('refuses without a passing agent-free assay, and refuses one borrowed from another contribution', () => {+ expect(packageRecord({ assay: null }).reasons[0]).toMatch(/eidoverse:assay/);+ expect(packageRecord({ assay: { ...passingAssay(), pass: false, reasons: ['tick 2: controller threw'] } }).reasons[0])+ .toContain('tick 2: controller threw');+ expect(packageRecord({ assay: { ...passingAssay(), disturbances: ['reconnect'] } }).reasons[0])+ .toMatch(/missing: restart-world-host, missing-optional-deps/);+ expect(packageRecord({ assay: passingAssay('some-other-build') }).reasons[0])+ .toMatch(/ran against "some-other-build"/);+ });+});++describe('verifying a candidate a peer was handed', () => {+ it('rejects a payload altered after packaging', () => {+ const { candidate } = packageRecord();+ const tampered = { ...candidate, body: { ...candidate.body, affordance: { inspect: 'quietly grants owner role' } } };++ const verdict = verifyFoundationCandidate(tampered, { requiredDisturbances: DISTURBANCES });+ expect(verdict.valid).toBe(false);+ expect(verdict.reasons.join(' ')).toContain('altered after packaging');+ // Re-fingerprinting the altered body is exactly what an honest re-package+ // does, so that alone must not be treated as tampering.+ expect(verifyFoundationCandidate({ ...tampered, fingerprint: foundationCandidateFingerprint(tampered) }, { requiredDisturbances: DISTURBANCES }).valid).toBe(true);+ });++ it('does not read its own sha256 fingerprint as a leaked credential', () => {+ const { candidate } = packageRecord();+ expect(candidate.fingerprint).toMatch(/^[a-f0-9]{64}$/);+ expect(federationSafetyFindings({ digest: candidate.fingerprint }).map((f) => f.code)).toContain('secret-token');+ expect(verifyFoundationCandidate(candidate, { requiredDisturbances: DISTURBANCES }).findings).toEqual([]);+ });+});++describe('assay evidence', () => {+ it('folds a harness verdict into the evidence block without inventing a pass', () => {+ const evidence = assayEvidenceFromVerdict({+ contributionId: 'beacon-relay-demo',+ pass: false,+ scenarios: [{ disturbance: 'reconnect', pass: false }, { disturbance: 'restart-world-host', pass: true }],+ reasons: ['[reconnect] tick 0: controller threw'],+ }, { ranAt: NOW });++ expect(evidence).toMatchObject({ harness: 'eidoverse-resilience-assay', pass: false, disturbances: ['reconnect', 'restart-world-host'] });+ // A verdict-shaped object with no explicit `pass` must never read as one.+ expect(assayEvidenceFromVerdict({ contributionId: 'x' }, { ranAt: NOW }).pass).toBe(false);+ });+});++describe('style-leak scanning', () => {+ it('reports the nested path of every style key, not just the first', () => {+ const findings = styleLeakFindings({ controller: { placement: [1, 2, 3] }, affordance: { render: { palette: ['#fff'] } } });+ expect(findings.map((finding) => finding.path)).toEqual(['controller.placement', 'affordance.render.palette']);+ });+});diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 3fb560019c..30d9d66148 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -627,7 +627,19 @@ describe('deferred imports stay deferred (#6156)', () => {// at all failed it — the same zero-headroom state #6305 raised it out of, and// that is what makes this a budget rather than a high-water mark. Measured after// both changes: 104,739.-const MAX_STATIC_INSTANTIATIONS = 106200;+//+// Raised to 107,700 for the Eidoverse foundation promote gate (#7455), and+// again to restore the ~1.5k of headroom this is supposed to carry: the+// previous number had drifted back to EXACTLY three above the measured total,+// so this change's unavoidable +7 failed it. That +7 is the whole cost — the+// two new suites are 4 and 2 (both pure leaves over zod/objects/secretText and+// a mocked fileUtils), and the mandatory `lib/` barrel row adds one node to+// `lib/index.test.js`. Nothing widely-reached gained an edge: the promote+// path's heavy dependency (`services/eidoverseResilienceAssay.js` and the+// projection planner under it) is reached only from the ledger service, which+// only `routes/eidoverseWorldRoutes.js` imports. Measured after this change:+// 106,204.+const MAX_STATIC_INSTANTIATIONS = 107700;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex 1dbc29bb8b..f4d9367a9a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -552,6 +552,7 @@ export * from './concurrencyGate.js';export * from './dispatchLabels.js';export * from './domainAutonomy.js';export * from './domainBudgets.js';+export * from './eidoverseFoundations.js';export * from './eidoverseWorldDesign.js';export * from './eidoverseWorldLabels.js';export * from './eidoverseWorldSignals.js';diff --git a/server/routes/eidoverseWorldRoutes.js b/server/routes/eidoverseWorldRoutes.jsindex 68f69bd046..cc204e9f27 100644--- a/server/routes/eidoverseWorldRoutes.js+++ b/server/routes/eidoverseWorldRoutes.js@@ -7,13 +7,21 @@*/import { Router } from 'express';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {eidoverseWorldAugmentSchema,eidoverseWorldConfigPatchSchema,eidoverseWorldSaySchema,validateRequest,} from '../lib/validation.js';+import { eidoverseFoundationIdParamSchema, eidoverseFoundationInputSchema } from '../lib/eidoverseFoundations.js';+import {+ getEidoverseFoundation,+ listEidoverseFoundations,+ packageEidoverseFoundationCandidate,+ recordEidoverseFoundation,+} from '../services/eidoverseFoundationLedger.js';+import { getInstanceId } from '../services/instanceIdentity.js';import {augmentEidoverseWorld,ensureEidoverseWorldPresence,@@ -73,4 +81,39 @@ router.post('/say', asyncHandler(async (req, res) => {res.json(await sayInEidoverseWorld(text));}));+// --- Foundations: the local-vs-baseline ownership ledger (#7455) ---------++// GET /api/eidoverse/world/foundations — every foundation this install has+// authored, with its ownership layer and last packaged promote candidate.+router.get('/foundations', asyncHandler(async (_req, res) => {+ res.json(await listEidoverseFoundations());+}));++// POST /api/eidoverse/world/foundations — record (or re-author) a local+// vernacular foundation. The ownership layer is not accepted from the caller:+// anything authored here is this install's own until it is promoted.+router.post('/foundations', asyncHandler(async (req, res) => {+ const input = validateRequest(eidoverseFoundationInputSchema, req.body || {});+ res.json({ success: true, foundation: await recordEidoverseFoundation(input, { originInstanceId: await getInstanceId() }) });+}));++// POST /api/eidoverse/world/foundations/:id/candidate — run the agent-free+// resilience assay and, on a pass, package the promote candidate. A refusal is+// a 200 carrying its reasons: "not ready to leave this install" is an expected+// verdict, not a request error.+router.post('/foundations/:id/candidate', asyncHandler(async (req, res) => {+ const { id } = validateRequest(eidoverseFoundationIdParamSchema, req.params || {});+ const result = await packageEidoverseFoundationCandidate(id);+ if (result.outcome === 'unknown-foundation') throw new ServerError('Foundation not found', { status: 404 });+ res.json({ success: result.outcome === 'packaged', ...result });+}));++// GET /api/eidoverse/world/foundations/:id — one foundation record.+router.get('/foundations/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(eidoverseFoundationIdParamSchema, req.params || {});+ const foundation = await getEidoverseFoundation(id);+ if (!foundation) throw new ServerError('Foundation not found', { status: 404 });+ res.json(foundation);+}));+export default router;diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.jsindex ca2013736e..dedcbe4d15 100644--- a/server/routes/eidoverseWorldRoutes.test.js+++ b/server/routes/eidoverseWorldRoutes.test.js@@ -5,6 +5,10 @@ import { errorMiddleware } from '../lib/errorHandler.js';const mocks = vi.hoisted(() => ({augment: vi.fn(),+ listFoundations: vi.fn(),+ packageCandidate: vi.fn(),+ recordFoundation: vi.fn(),+ getFoundation: vi.fn(),ensurePresence: vi.fn(),getProjectionStatus: vi.fn(),getStatus: vi.fn(),@@ -23,6 +27,15 @@ vi.mock('../services/eidoverseWorld.js', () => ({updateEidoverseWorldConfig: mocks.updateConfig,}));+vi.mock('../services/eidoverseFoundationLedger.js', () => ({+ getEidoverseFoundation: mocks.getFoundation,+ listEidoverseFoundations: mocks.listFoundations,+ packageEidoverseFoundationCandidate: mocks.packageCandidate,+ recordEidoverseFoundation: mocks.recordFoundation,+}));++vi.mock('../services/instanceIdentity.js', () => ({ getInstanceId: () => Promise.resolve('instance-aaaa') }));+const { default: eidoverseWorldRoutes } = await import('./eidoverseWorldRoutes.js');const makeApp = () => {@@ -148,4 +161,46 @@ describe('Eidoverse world routes', () => {expect(sayResponse.status).toBe(200);expect(mocks.say).toHaveBeenCalledWith('Example message');});++ // #7455 — the promote path's HTTP boundary. What matters here is that the+ // ownership layer and the assay verdict are NOT things a caller can assert.+ it('records a foundation without letting the caller name its ownership layer', async () => {+ const authored = {+ id: 'tide-beacon',+ kind: 'controller',+ title: 'Tide Beacon',+ summary: 'A beacon that keeps pulsing between mind wakes.',+ contributionId: 'beacon-relay-demo',+ body: { affordance: { inspect: 'reads the pulse count' } },+ };+ mocks.recordFoundation.mockResolvedValue({ ...authored, layer: 'vernacular' });++ const accepted = await request(makeApp()).post('/api/eidoverse/world/foundations').send(authored);+ const claimed = await request(makeApp()).post('/api/eidoverse/world/foundations').send({ ...authored, layer: 'baseline' });++ expect(accepted.status).toBe(200);+ expect(mocks.recordFoundation).toHaveBeenCalledWith(expect.objectContaining({ id: 'tide-beacon' }), { originInstanceId: 'instance-aaaa' });+ expect(claimed.status).toBe(400);+ expect(mocks.recordFoundation).toHaveBeenCalledTimes(1);+ });++ it('returns a promote refusal as a verdict, not as a request error', async () => {+ mocks.packageCandidate.mockResolvedValue({ outcome: 'refused', candidate: null, assay: { pass: false }, reasons: ['the agent-free resilience assay failed'], findings: [] });++ const response = await request(makeApp()).post('/api/eidoverse/world/foundations/tide-beacon/candidate');++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({ success: false, outcome: 'refused' });+ expect(response.body.reasons[0]).toContain('resilience assay failed');+ });++ it('404s a promote or read for a foundation this install never authored', async () => {+ mocks.packageCandidate.mockResolvedValue({ outcome: 'unknown-foundation', candidate: null, assay: null, reasons: ['no foundation'], findings: [] });+ mocks.getFoundation.mockResolvedValue(null);++ expect((await request(makeApp()).post('/api/eidoverse/world/foundations/tide-beacon/candidate')).status).toBe(404);+ expect((await request(makeApp()).get('/api/eidoverse/world/foundations/tide-beacon')).status).toBe(404);+ // A path that could never be an id must not reach the service at all.+ expect((await request(makeApp()).get('/api/eidoverse/world/foundations/Not An Id')).status).toBe(400);+ });});diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.jsnew file mode 100644index 0000000000..0e98c1d4e9--- /dev/null+++ b/server/services/eidoverseFoundationLedger.js@@ -0,0 +1,180 @@+/**+ * The install-local ledger of Eidoverse world foundations — which durable+ * artifacts this instance authored, which ownership layer each one sits in, and+ * the last promote candidate packaged from it (#7455, epic #7453).+ *+ * `server/lib/eidoverseFoundations.js` owns the ownership model and the+ * packaging/validation gate; this module is the persistence, clock, and+ * assay-execution shell around it. Everything authored here lands at the+ * `vernacular` layer, so an artifact is local until somebody promotes it on+ * purpose.+ *+ * **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+ * through `runResilienceAssay()` (#7460), and packages against the verdict it+ * just produced. 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.+ *+ * Storage is `data/eidoverse/foundations.json` — `file-primary` and MACHINE+ * LOCAL, the same class as `portos-world.json` beside it (`docs/STORAGE.md`).+ * PortOS never federates this file: the only thing authorized to leave the+ * install is a packaged candidate envelope, and even that leaves only through+ * an explicit promote. There is no `data.reference/` seed — an absent file is+ * an empty ledger, which is the correct state for every install that has never+ * authored a foundation, so no migration is owed.+ */++import { join } from 'node:path';+import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { createMutex } from '../lib/asyncMutex.js';+import { getPortosVersion } from '../lib/schemaVersions.js';+import {+ DEFAULT_EIDOVERSE_FOUNDATION_LAYER,+ EIDOVERSE_FOUNDATION_LEDGER_SCHEMA_VERSION,+ assayEvidenceFromVerdict,+ eidoverseFoundationInputSchema,+ packageFoundationCandidate,+} from '../lib/eidoverseFoundations.js';+import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';+import { findContributionById } from './eidoverseResilienceContributions.js';++// Resolved per call rather than captured at module load: `PATHS.data` is what+// a suite re-roots to a temp directory, and a path frozen at import time would+// point every test at the live install's own ledger.+const ledgerDir = () => join(PATHS.data, 'eidoverse');+const ledgerFile = () => join(ledgerDir(), 'foundations.json');++const withLedgerLock = createMutex();++/**+ * Strict read: a `foundations.json` this process cannot parse must NOT read as+ * "no foundations yet", because the very next write would then replace the+ * user's ledger with an empty one. `strict: true` throws on unreadable bytes,+ * while a genuinely ABSENT file still reads as the empty ledger it is.+ */+async function readLedger() {+ const raw = await readJSONFile(ledgerFile(), null, { allowArray: false, strict: true });+ const foundations = raw && typeof raw === 'object' && raw.foundations && typeof raw.foundations === 'object' ? { ...raw.foundations } : {};+ return { schemaVersion: EIDOVERSE_FOUNDATION_LEDGER_SCHEMA_VERSION, foundations };+}++async function writeLedger(ledger) {+ await ensureDir(ledgerDir());+ await atomicWrite(ledgerFile(), { ...ledger, schemaVersion: EIDOVERSE_FOUNDATION_LEDGER_SCHEMA_VERSION });+}++/** Every foundation this install knows about, most recently updated first. */+export async function listEidoverseFoundations() {+ const ledger = await readLedger();+ const foundations = Object.values(ledger.foundations)+ .sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));+ return {+ schemaVersion: EIDOVERSE_FOUNDATION_LEDGER_SCHEMA_VERSION,+ counts: {+ vernacular: foundations.filter((entry) => entry.layer === DEFAULT_EIDOVERSE_FOUNDATION_LAYER).length,+ baseline: foundations.filter((entry) => entry.layer === 'baseline').length,+ candidates: foundations.filter((entry) => Boolean(entry.candidate)).length,+ },+ foundations,+ };+}++export async function getEidoverseFoundation(id) {+ const ledger = await readLedger();+ return ledger.foundations[id] || null;+}++/**+ * Record (or re-author) a local vernacular foundation.+ *+ * `originInstanceId` is supplied by the caller rather than read here so this+ * module stays a single-purpose store; `getInstanceId()` from+ * `services/instanceIdentity.js` is what every caller passes.+ *+ * Re-authoring an existing id keeps its original `createdAt` and origin — an+ * artifact's provenance is part of its identity — and CLEARS the packaged+ * candidate and the recorded assay, because both described the previous body.+ * Carrying a passing verdict across an edit is exactly the "it worked when I+ * narrated it" claim the agent-free harness exists to refuse.+ */+export async function recordEidoverseFoundation(input, { originInstanceId, now = new Date().toISOString() } = {}) {+ const authored = eidoverseFoundationInputSchema.parse(input);+ return withLedgerLock(async () => {+ const ledger = await readLedger();+ const existing = ledger.foundations[authored.id] || null;+ const record = {+ id: authored.id,+ layer: existing?.layer === 'baseline' ? 'baseline' : DEFAULT_EIDOVERSE_FOUNDATION_LAYER,+ kind: authored.kind,+ title: authored.title,+ summary: authored.summary,+ contributionId: authored.contributionId,+ body: authored.body,+ style: authored.style,+ provenance: existing?.provenance || { originInstanceId, authorKind: authored.authorKind, createdAt: now },+ disclosure: authored.disclosure,+ assay: null,+ candidate: null,+ promotedAt: existing?.promotedAt ?? null,+ updatedAt: now,+ };+ ledger.foundations[authored.id] = record;+ await writeLedger(ledger);+ return record;+ });+}++/**+ * Run the agent-free assay against a recorded foundation and, if it and every+ * other gate pass, package the promote candidate onto its record.+ *+ * A refusal is a RESULT, not an exception: "this build is not ready to leave+ * the install" is ordinary, expected output the caller shows the author with+ * its reasons. The assay verdict is persisted either way — a failing verdict is+ * the diagnostic that says what to fix — while the candidate is written only on+ * a pass.+ *+ * @returns {Promise<{ outcome: 'packaged'|'refused'|'unknown-foundation', candidate: object|null, assay: object|null, reasons: string[], findings: Array }>}+ */+export async function packageEidoverseFoundationCandidate(id, { now = new Date().toISOString() } = {}) {+ const portosVersion = await getPortosVersion();+ const existing = await getEidoverseFoundation(id);+ if (!existing) return { outcome: 'unknown-foundation', candidate: null, assay: null, reasons: [`no foundation is recorded under "${id}"`], findings: [] };++ // 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 {+ outcome: 'refused',+ candidate: null,+ assay: null,+ reasons: [`no resilience-assay contribution is registered under "${existing.contributionId}" — a foundation is promotable only once it can be replayed without its author`],+ findings: [],+ };+ }+ const assay = assayEvidenceFromVerdict(runResilienceAssay(contribution), { ranAt: now });++ return withLedgerLock(async () => {+ const ledger = await readLedger();+ const current = ledger.foundations[id];+ if (!current) return { outcome: 'unknown-foundation', candidate: null, assay: null, reasons: [`no foundation is recorded under "${id}"`], findings: [] };+ if (current.updatedAt !== existing.updatedAt) {+ return { outcome: 'refused', candidate: null, assay: null, reasons: ['the foundation was re-authored while the assay was running — package it again'], findings: [] };+ }++ const result = packageFoundationCandidate({+ record: { ...current, assay, candidate: null },+ requiredDisturbances: RESILIENCE_DISTURBANCES,+ portosVersion,+ now,+ });+ ledger.foundations[id] = { ...current, assay, candidate: result.candidate, updatedAt: now };+ await writeLedger(ledger);+ return { ...result, assay };+ });+}diff --git a/server/services/eidoverseFoundationLedger.test.js b/server/services/eidoverseFoundationLedger.test.jsnew file mode 100644index 0000000000..e2ca378b67--- /dev/null+++ b/server/services/eidoverseFoundationLedger.test.js@@ -0,0 +1,111 @@+/**+ * The ledger is the persisted half of the local-vs-baseline ownership boundary+ * (#7455). What these tests pin is the workflow contract a route or mind tool+ * depends on: an authored artifact is LOCAL, the promote gate RUNS the+ * agent-free assay rather than believing a caller, and a re-authored body loses+ * the verdict that vouched for the previous one.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { rmSync } from 'node:fs';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-eidoverse-foundations-'),+}));++const {+ getEidoverseFoundation,+ listEidoverseFoundations,+ packageEidoverseFoundationCandidate,+ recordEidoverseFoundation,+} = await import('./eidoverseFoundationLedger.js');++// The passing reference contribution shipped with the assay harness (#7460).+const PASSING_CONTRIBUTION = 'beacon-relay-demo';++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' } },+ style: { motif: 'weathered brass' },+ authorKind: 'mind',+ ...overrides,+});++const record = (overrides, at) => recordEidoverseFoundation(authored(overrides), { originInstanceId: 'instance-aaaa', now: at });++beforeEach(() => {+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });+});++afterAll(cleanupTempDataRoots);++describe('the local foundation ledger', () => {+ it('reads as empty on an install that has never authored one', async () => {+ const listed = await listEidoverseFoundations();+ expect(listed.foundations).toEqual([]);+ expect(listed.counts).toEqual({ vernacular: 0, baseline: 0, candidates: 0 });+ });++ it('records an authored artifact as vernacular, never as baseline', async () => {+ const saved = await record({}, '2026-03-04T05:06:07.000Z');++ expect(saved.layer).toBe('vernacular');+ expect(saved.candidate).toBeNull();+ expect(saved.provenance).toEqual({ originInstanceId: 'instance-aaaa', authorKind: 'mind', createdAt: '2026-03-04T05:06:07.000Z' });+ expect((await listEidoverseFoundations()).counts.vernacular).toBe(1);+ });++ it('rejects a caller trying to author straight into the shared baseline', async () => {+ await expect(recordEidoverseFoundation({ ...authored(), layer: 'baseline' }, { originInstanceId: 'instance-aaaa' }))+ .rejects.toThrow();+ });+});++describe('packaging a promote candidate', () => {+ it('runs the assay itself and packages a foundation that survives it', async () => {+ await record({}, '2026-03-04T05:06:07.000Z');++ const result = await packageEidoverseFoundationCandidate('tide-beacon', { now: '2026-03-04T06:00:00.000Z' });++ 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.candidate.fingerprint).toMatch(/^[a-f0-9]{64}$/);+ expect(JSON.stringify(result.candidate)).not.toContain('weathered brass');++ const stored = await getEidoverseFoundation('tide-beacon');+ expect(stored.candidate.fingerprint).toBe(result.candidate.fingerprint);+ 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' });++ const result = await packageEidoverseFoundationCandidate('tide-beacon');++ expect(result.outcome).toBe('refused');+ expect(result.reasons[0]).toContain('not-registered-anywhere');+ expect((await getEidoverseFoundation('tide-beacon')).candidate).toBeNull();+ });++ 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' });++ await record({ summary: 'Now it also rings a bell.' }, '2026-03-04T07:00:00.000Z');++ const stored = await getEidoverseFoundation('tide-beacon');+ expect(stored.candidate).toBeNull();+ expect(stored.assay).toBeNull();+ // Provenance is identity: re-authoring does not reset who made it or when.+ expect(stored.provenance.createdAt).toBe('2026-03-04T05:06:07.000Z');+ });++ it('reports an unknown foundation instead of inventing one', async () => {+ expect((await packageEidoverseFoundationCandidate('never-authored')).outcome).toBe('unknown-foundation');+ });+});diff --git a/server/services/eidoverseResilienceAssay.js b/server/services/eidoverseResilienceAssay.jsindex 6eb2795040..16f44decb2 100644--- a/server/services/eidoverseResilienceAssay.js+++ b/server/services/eidoverseResilienceAssay.js@@ -33,9 +33,10 @@** This module makes no network, filesystem, or provider calls and depends* only on `buildProjectionPlan` (already pure) for the "load projections in- * a clean sandbox" leg of the assay. The promote path (#7455, not yet built)- * is expected to call `runResilienceAssay()` per candidate contribution and- * block promotion on a failing verdict; `scripts/eidoverse-resilience-assay.js`+ * a clean sandbox" leg of the assay. The promote path (#7455) calls+ * `runResilienceAssay()` per candidate contribution and refuses to package a+ * promote candidate on a failing verdict — see+ * `services/eidoverseFoundationLedger.js`; `scripts/eidoverse-resilience-assay.js`* gives CI (or a human) the same verdict from the command line.** try/catch here is deliberate, not the "errors bubble to middleware" defaultdiff --git a/server/services/eidoverseResilienceContributions.js b/server/services/eidoverseResilienceContributions.jsnew file mode 100644index 0000000000..ed9806d33b--- /dev/null+++ b/server/services/eidoverseResilienceContributions.js@@ -0,0 +1,67 @@+/**+ * Where the agent-free resilience assay finds the contributions it replays.+ *+ * `eidoverseResilienceAssay.js` is deliberately I/O-free — it is handed a+ * contribution and runs it. Something still has to turn "the foundation named+ * `beacon-relay-demo`" into that object, and both the CLI+ * (`scripts/eidoverse-resilience-assay.js`) and the promote path+ * (`eidoverseFoundationLedger.js`) need the same answer. This module is that+ * one resolver, so the two cannot drift into disagreeing about what a+ * registered contribution is.+ *+ * Resolution is by CONTRIBUTION ID against a fixed directory, never by a+ * caller-supplied path: the promote path reaches this from an HTTP body, and+ * "import the module this request names" is arbitrary code execution wearing a+ * feature's clothes. `loadContributionModule()` still takes a path because the+ * CLI is a local developer tool being handed one on purpose.+ *+ * Today the directory holds the two reference fixtures shipped with #7460. When+ * executable world controllers land (#7456) their registry becomes a second+ * source here, and neither caller changes.+ */++import { readdir } from 'node:fs/promises';+import { join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const CONTRIBUTIONS_DIR = fileURLToPath(new URL('./eidoverseResilienceAssayFixtures/', import.meta.url));++// The deliberately-failing fixture beside them is named `*.failing.fixture.js`+// so it is exercised only by the assay's own test and never registers as a+// promotable contribution.+const CONTRIBUTION_SUFFIX = '.contribution.js';++/** Absolute paths of every registered contribution module, in stable order. */+export async function listContributionModulePaths() {+ const files = await readdir(CONTRIBUTIONS_DIR);+ return files.filter((file) => file.endsWith(CONTRIBUTION_SUFFIX)).sort().map((file) => join(CONTRIBUTIONS_DIR, file));+}++/**+ * Import one contribution module and invoke its factory.+ *+ * A module must export a default (or a single named) zero-argument factory+ * returning `{ id, createSandbox, invariants? }` — the shape+ * `runResilienceAssay()` consumes.+ */+export async function loadContributionModule(modulePath) {+ const mod = await import(pathToFileURL(modulePath).href);+ const factory = mod.default || Object.values(mod).find((value) => typeof value === 'function');+ if (typeof factory !== 'function') throw new Error(`${modulePath} does not export a contribution factory function`);+ return factory();+}++/**+ * The registered contribution with this id, or `null` when none matches.+ *+ * Returning null rather than throwing is what lets the promote path report+ * "nothing is registered under that id" as one refusal reason beside the+ * others instead of as a 500.+ */+export async function findContributionById(contributionId) {+ for (const modulePath of await listContributionModulePaths()) {+ const contribution = await loadContributionModule(modulePath);+ if (contribution?.id === contributionId) return contribution;+ }+ return null;+}