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

refuse a promote candidate that leaks through a key name, and share the privacy scan tree-wide (#7455)

[._.]/ Adam Eivy7574511a3000
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index f3255371fc..e8eaab3181 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -697,8 +697,13 @@ like itself — palette, motif, asset paths, placement, district, display aliase
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.
+right. On top of that split there is an authoring check: an unambiguously
+cosmetic key found *inside* `body` (`palette`, `motif`, `accent`, `color`,
+`material`, `texture`, a label alias) **refuses** the package rather than being
+silently trimmed, so "I put the palette in `body` and expected peers to get it"
+gets named. Spatial and asset-binding keys (`pos`, `yaw`, `lib`, `districtId`)
+are deliberately *not* on that list — they are exactly the substance of a
+`district-template` foundation.
`data/eidoverse/foundations.json` (`server/services/eidoverseFoundationLedger.js`)
is the install-local ledger — machine-local like `portos-world.json` beside it,
@@ -714,7 +719,15 @@ 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.
+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.
Four refusals stand between a local artifact and the shared baseline, and every
one returns a readable reason naming what to fix:
@@ -724,10 +737,12 @@ one returns a readable reason naming what to fix:
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.
+4. **Federation safety** — `server/lib/federationSafety.js` refuses the package
+ when the candidate carries machine identity, network info, PII,
+ credential-shaped values, or a credential-*named* field (`{ apiKey: … }`,
+ which no value-shape scan can see), anywhere in its values **or its keys**.
+ 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
diff --git a/server/lib/README.md b/server/lib/README.md
index e96feab07d..fb1d4d5c0c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -569,7 +569,9 @@ 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`. |
+| `federationSafety.js` | "Does this JSON-shaped payload carry anything that must not leave the install?" — the structured, REFUSAL-side counterpart to the scrubbers (`secretText.js`, `homePath.js`) that rewrite text for a log. `federationSafetyFindings(value, { limit })` walks every string AND every object key, returning `{ code, path, detail }` for a home/Windows path, IPv4 or IPv6 literal, `.ts.net`/`.local` host, MAC, email, phone number, labelled GPS coordinate, credential-shaped value (`scrubSecretTokens`) or credential-NAMED key (`secretKeys.js#isSecretKey` — the half no value-shape scan can see). Deliberately over-refuses rather than under-detects: a payload leaving the machine should fail on "looks like an address", and the finding names the exact JSON path to fix. `walkJsonText` / `describeJsonPath` are the reusable path-reporting walk. Pure; reads no environment. |
+| `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`). |
+| `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`. 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.js
index e2e6ad6b89..3cb0a76423 100644
--- a/server/lib/eidoverseFoundations.js
+++ b/server/lib/eidoverseFoundations.js
@@ -42,14 +42,15 @@
* 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.
+ * 2. **Federation safety.** A promote payload is the one Eidoverse artifact
+ * authorized to cross the federation layer, so it fails closed:
+ * `lib/federationSafety.js` refuses the package outright when the
+ * candidate carries machine identity, PII, credential-shaped values or
+ * credential-NAMED fields, naming the offending JSON path. 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
@@ -63,7 +64,7 @@
import { createHash } from 'node:crypto';
import { z } from 'zod';
import { canonicalStringify } from './objects.js';
-import { scrubSecretTokens } from './secretText.js';
+import { describeJsonPath, federationSafetyFindings, walkJsonText } from './federationSafety.js';
/** Ownership layers, widest-shared first. See the module header. */
export const EIDOVERSE_FOUNDATION_LAYERS = Object.freeze(['runtime', 'baseline', 'vernacular']);
@@ -81,27 +82,33 @@ export const EIDOVERSE_FOUNDATION_KINDS = Object.freeze(['schema', 'affordance',
* 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.
+ * Keys that are UNAMBIGUOUSLY cosmetic and so must never appear inside a
+ * foundation `body`. Found there, they refuse the package.
+ *
+ * This is an authoring check on top of the `{ body, style }` split, not the
+ * mechanism — the split already guarantees `style` never leaves the install.
+ * It exists because "I put the palette in `body` and expected peers to get it"
+ * is a mistake worth naming rather than silently dropping.
+ *
+ * Kept narrow on purpose. Spatial and asset-binding keys (`pos`, `yaw`,
+ * `lib`, `placement`, `districtId`) are NOT listed even though a vernacular
+ * layout uses them: they are exactly the substance of a `district-template`
+ * foundation, and blocking them would make one of the four declared kinds
+ * impossible to promote.
*/
-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_KEYS = Object.freeze([
+ 'accent', 'alias', 'aliases', 'avatar', 'color', 'colors', 'labelAliases',
+ 'material', 'materials', 'motif', 'palette', 'texture', 'textures',
]);
-const STYLE_ONLY_KEY_SET = new Set(EIDOVERSE_STYLE_ONLY_KEYS);
+const STYLE_ONLY_KEY_SET = new Set(STYLE_ONLY_KEYS);
-export const FOUNDATION_LIMITS = Object.freeze({
+const FOUNDATION_LIMITS = Object.freeze({
idMax: 64,
titleMax: 80,
summaryMax: 400,
- bodyBytes: 16_384,
- styleBytes: 16_384,
+ jsonBytes: 16_384,
disclosureItems: 12,
disclosureItemMax: 160,
noteMax: 600,
@@ -116,10 +123,9 @@ const foundationIdSchema = z.string().trim().min(1).max(FOUNDATION_LIMITS.idMax)
* 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',
-);
+// `.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();
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`);
@@ -129,11 +135,11 @@ const boundedJsonObject = (maxBytes) => z.record(z.string().min(1).max(64), z.un
* 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 foundationBodySchema = boundedJsonObject(FOUNDATION_LIMITS.jsonBytes);
-const foundationStyleSchema = boundedJsonObject(FOUNDATION_LIMITS.styleBytes);
+const foundationStyleSchema = boundedJsonObject(FOUNDATION_LIMITS.jsonBytes);
-export const foundationDisclosureSchema = z.object({
+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),
@@ -147,13 +153,22 @@ export const foundationDisclosureSchema = z.object({
* 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']),
+const authorKindSchema = z.enum(['mind', 'cos', 'user']);
+
+const foundationProvenanceSchema = z.object({
+ // `UNKNOWN_INSTANCE_ID` is refused here rather than at each call site: this
+ // id is content-addressed into the candidate fingerprint and is what the
+ // provenance graph (#7461) hangs its edges off, so a candidate stamped
+ // "unknown" would be permanently misattributed and would collide with every
+ // other uninitialized install. Callers use `ensureInstanceId()`.
+ originInstanceId: z.string().trim().min(1).max(64)
+ .regex(/^[A-Za-z0-9_-]+$/, 'must be an opaque instance id')
+ .refine((id) => id !== 'unknown', 'this install has no federation identity yet'),
+ authorKind: authorKindSchema,
createdAt: isoDateSchema,
}).strict();
-export const foundationAssayEvidenceSchema = z.object({
+const foundationAssayEvidenceSchema = z.object({
harness: z.literal('eidoverse-resilience-assay'),
contributionId: contributionIdSchema,
pass: z.boolean(),
@@ -162,56 +177,61 @@ export const foundationAssayEvidenceSchema = z.object({
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']),
+/**
+ * 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.
+ */
+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,
+};
+
+/** The local ledger record. `style` stays here and never leaves the install. */
+export const eidoverseFoundationRecordSchema = z.object({
+ ...foundationCoreShape,
+ 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.
+ layer: z.enum(['vernacular', 'baseline']),
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(),
+ // Forward-declared storage slots, written by the promote-to-baseline step
+ // that follows this slice: nothing here ever sets `layer` to `baseline` or
+ // `promotedAt` to a timestamp yet, so a reader should not take a `baseline`
+ // count of zero as evidence about anything.
promotedAt: isoDateSchema.nullable().default(null),
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({
+ ...foundationCoreShape,
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'),
+ authorKind: authorKindSchema.default('user'),
}).strict();
/** The promote envelope — the only shape authorized to cross to a peer. */
export const eidoverseFoundationCandidateSchema = z.object({
+ ...foundationCoreShape,
candidateVersion: z.literal(EIDOVERSE_FOUNDATION_CANDIDATE_VERSION),
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),
@@ -240,66 +260,6 @@ export function layerPromoteRefusal(layer) {
// 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
@@ -310,7 +270,7 @@ 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` });
+ findings.push({ code: 'style-in-body', path: describeJsonPath(path), detail: `"${text}" belongs to the vernacular style layer and is never promoted` });
});
return findings.slice(0, FOUNDATION_LIMITS.findingsMax);
}
@@ -340,24 +300,24 @@ export function assayEvidenceFromVerdict(verdict, { ranAt }) {
}
/**
- * Why the recorded assay evidence does not clear the promote gate, or `null`.
+ * Why already-schema-parsed assay evidence does not clear the promote gate, or
+ * `null`. Both call sites validate the block first (through the record or the
+ * candidate schema), so this reads its fields directly.
*
* `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 } = {}) {
+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 (assay.contributionId !== contributionId) {
+ return `the recorded assay ran against "${assay.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);
+ if (!assay.pass) return `the agent-free resilience assay failed: ${assay.reasons[0] || 'no reason recorded'}`;
+ const covered = new Set(assay.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;
@@ -367,6 +327,13 @@ export function assayEvidenceRefusal(assay, requiredDisturbances, { contribution
// Packaging
// ---------------------------------------------------------------------------
+/** Zod issues as reader-facing reasons, capped like every other finding list. */
+const issueReasons = (error) => error.issues
+ .slice(0, FOUNDATION_LIMITS.findingsMax)
+ .map((issue) => `${describeJsonPath(issue.path.map(String))}: ${issue.message}`);
+
+const refused = (reasons, findings = []) => ({ outcome: 'refused', candidate: null, reasons, findings });
+
/** sha256 over the canonicalized envelope, excluding the digest itself. */
export function foundationCandidateFingerprint(candidate) {
return createHash('sha256').update(canonicalStringify(withoutFingerprint(candidate))).digest('hex');
@@ -395,14 +362,7 @@ function withoutFingerprint(candidate) {
*/
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: [],
- };
- }
+ if (!parsed.success) return refused(issueReasons(parsed.error));
const foundation = parsed.data;
// Two refusals the envelope gate below cannot phrase usefully: ownership
@@ -413,9 +373,9 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
// packaging side and the receiving side share one definition of valid.
const reasons = [
layerPromoteRefusal(foundation.layer),
- assayEvidenceRefusal(foundation.assay, requiredDisturbances, { contributionId: foundation.contributionId }),
+ assayEvidenceRefusal(foundation.assay, requiredDisturbances, foundation.contributionId),
].filter(Boolean);
- if (reasons.length > 0) return { outcome: 'refused', candidate: null, reasons, findings: [] };
+ if (reasons.length > 0) return refused(reasons);
const draft = {
candidateVersion: EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,
@@ -435,7 +395,7 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
// 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 };
+ if (!verified.valid) return refused(verified.reasons, verified.findings);
return { outcome: 'packaged', candidate, reasons: [], findings: [] };
}
@@ -450,21 +410,19 @@ export function packageFoundationCandidate({ record, requiredDisturbances, porto
*/
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: [],
- };
- }
+ if (!parsed.success) return { valid: false, reasons: issueReasons(parsed.error), findings: [] };
const envelope = parsed.data;
const reasons = [];
- if (foundationCandidateFingerprint(envelope) !== envelope.fingerprint) {
+ // Hash the candidate AS RECEIVED, not the zod-normalized copy: the digest has
+ // to cover the bytes the sender actually hashed. Re-hashing `parsed.data`
+ // would let a schema transform (a `.trim()` on a field that arrived padded)
+ // read as tampering, including on the packaging side's own self-check.
+ if (foundationCandidateFingerprint(candidate) !== 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 });
+ const assayRefusal = assayEvidenceRefusal(envelope.assay, requiredDisturbances, envelope.contributionId);
if (assayRefusal) reasons.push(assayRefusal);
const findings = [...styleLeakFindings(envelope.body), ...federationSafetyFindings(withoutFingerprint(envelope))];
diff --git a/server/lib/eidoverseFoundations.test.js b/server/lib/eidoverseFoundations.test.js
index 093628d2b4..5ac5b303f2 100644
--- a/server/lib/eidoverseFoundations.test.js
+++ b/server/lib/eidoverseFoundations.test.js
@@ -9,13 +9,13 @@ import {
DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
EIDOVERSE_FOUNDATION_CANDIDATE_VERSION,
assayEvidenceFromVerdict,
- federationSafetyFindings,
foundationCandidateFingerprint,
layerPromoteRefusal,
packageFoundationCandidate,
styleLeakFindings,
verifyFoundationCandidate,
} from './eidoverseFoundations.js';
+import { federationSafetyFindings } from './federationSafety.js';
const DISTURBANCES = ['reconnect', 'restart-world-host', 'missing-optional-deps'];
const NOW = '2026-03-04T05:06:07.000Z';
@@ -128,6 +128,17 @@ describe('verifying a candidate a peer was handed', () => {
expect(verifyFoundationCandidate({ ...tampered, fingerprint: foundationCandidateFingerprint(tampered) }, { requiredDisturbances: DISTURBANCES }).valid).toBe(true);
});
+ it('does not read schema normalization as tampering', () => {
+ // The digest covers the bytes as sent. Hashing the zod-normalized copy
+ // instead would make a field that arrived padded — which the envelope
+ // schema trims — verify as an altered payload.
+ const { candidate } = packageRecord();
+ const padded = { ...candidate, provenance: { ...candidate.provenance, portosVersion: ' 9.9.9 ' } };
+ const sent = { ...padded, fingerprint: foundationCandidateFingerprint(padded) };
+
+ expect(verifyFoundationCandidate(sent, { 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}$/);
@@ -153,7 +164,7 @@ describe('assay evidence', () => {
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']);
+ const findings = styleLeakFindings({ controller: { motif: 'brass' }, affordance: { render: { palette: ['#fff'] } } });
+ expect(findings.map((finding) => finding.path)).toEqual(['controller.motif', 'affordance.render.palette']);
});
});
diff --git a/server/lib/federationSafety.js b/server/lib/federationSafety.js
new file mode 100644
index 0000000000..7b0cb879c5
--- /dev/null
+++ b/server/lib/federationSafety.js
@@ -0,0 +1,112 @@
+/**
+ * "Does this JSON-shaped payload carry anything that must not leave the
+ * install?" — the structured, refusal-side reading of the federation privacy
+ * rule, over both the values a payload holds and the keys it names them with.
+ *
+ * Root `AGENTS.md` and the [machine-local privacy ADR](../../docs/decisions/2026-08-08-privacy-records-machine-local.md)
+ * say PII and machine identity must not ride the federation layer at all. The
+ * tree already has the scrubbers a free-text field needs — `scrubSecretTokens`
+ * (credential-shaped values), `scrubHomePath` (the running user's actual home
+ * prefix) — but those REWRITE text for a log or a prompt. A payload about to
+ * cross to a peer needs the opposite shape: a yes/no with a JSON path, so the
+ * caller can REFUSE and tell the author which field to fix. Redacting and
+ * sending anyway would leave an author believing they published what they wrote.
+ *
+ * Hence findings rather than a scrubber, and hence a module of its own rather
+ * than a private helper inside the first feature that needed it: the rule is
+ * tree-wide, so the second caller should reach for this instead of copying a
+ * regex list.
+ *
+ * Deliberately conservative about false NEGATIVES rather than false positives —
+ * a four-part version string is reported as an IP literal, because the payload
+ * is leaving the machine and "looks like an address" is the right side to fail
+ * on when the finding names the exact path to fix.
+ *
+ * Pure: no I/O, no environment reads. (`scrubHomePath` is intentionally NOT
+ * used here — it knows only THIS machine's home directory, while the patterns
+ * below catch the shape on any machine, which is what a payload review needs.)
+ */
+
+import { scrubSecretTokens } from './secretText.js';
+import { isSecretKey } from './secretKeys.js';
+
+// Derived from the two redaction tables already in the tree —
+// `services/agentContextMcp.js#redactAgentContextText` and
+// `services/agentErrorAnalysis.js#SNIPPET_REDACTIONS` — so this gate is not
+// weaker than what a log line already gets. Those two still own their own
+// REPLACEMENT strings; converging all three onto this list is #7474.
+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"'`]+/],
+ ['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/],
+ // IPv6, which also matches a MAC and a `14:25:30` clock time. Both are
+ // over-refusals this module accepts on purpose: the finding names the field,
+ // and a timestamp belongs in a typed date field rather than loose in a body.
+ ['ip-literal', /\b(?:[A-Fa-f0-9]{1,4}:){2,7}[A-Fa-f0-9]{0,4}\b/],
+ // Tailscale MagicDNS and mDNS names, all labels (not just the leading one).
+ ['network-host', /\b[A-Za-z0-9-]+(?:\.[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/],
+ ['phone-number', /\b\+?\d[\d ().-]{8,}\d\b/],
+ // Only the LABELLED form: a bare decimal pair is indistinguishable from any
+ // other two numbers, and refusing every such pair would be noise.
+ ['gps-coordinate', /\b(?:latitude|longitude|lat|lon|lng)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/i],
+]);
+
+/** `a.b.0.c`, or `<root>` for a bare string handed in with no path. */
+export const describeJsonPath = (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: a key named for
+ * a host leaks the host just as a value does.
+ *
+ * @param {unknown} value
+ * @param {(entry: { text: string, path: string[], kind: 'key'|'value' }) => void} visit
+ */
+export 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, network info, PII and credential findings anywhere in a
+ * JSON-shaped value.
+ *
+ * @param {unknown} value
+ * @param {{ limit?: number }} [options] - cap on findings returned
+ * @returns {Array<{ code: string, path: string, detail: string }>}
+ */
+export function federationSafetyFindings(value, { limit = 40 } = {}) {
+ const findings = [];
+ walkJsonText(value, ({ text, path, kind }) => {
+ const at = describeJsonPath(path);
+ for (const [code, pattern] of PRIVACY_PATTERNS) {
+ if (pattern.test(text)) findings.push({ code, path: at, detail: `a ${code.replace('-', ' ')} may not cross the federation layer` });
+ }
+ if (scrubSecretTokens(text) !== text) {
+ findings.push({ code: 'secret-token', path: at, detail: 'a credential-shaped value may not cross the federation layer' });
+ }
+ // The key-name half. A value-shape scan cannot see `{ apiKey: 'hunter2' }` —
+ // that secret is identifiable only by what it is CALLED, which is exactly
+ // the split `secretText.js`'s own header describes.
+ if (kind === 'key' && isSecretKey(text)) {
+ findings.push({ code: 'secret-key', path: at, detail: 'a credential-named field may not cross the federation layer' });
+ }
+ });
+ return findings.slice(0, limit);
+}
diff --git a/server/lib/federationSafety.test.js b/server/lib/federationSafety.test.js
new file mode 100644
index 0000000000..2fcdc1ef66
--- /dev/null
+++ b/server/lib/federationSafety.test.js
@@ -0,0 +1,51 @@
+/**
+ * This is a privacy boundary, so the regressions worth pinning are the ones
+ * that would let something through: a leak reachable only through an object
+ * KEY, a credential a value-shape scan cannot see, and the address families
+ * the two older redaction tables in the tree already cover.
+ */
+import { describe, expect, it } from 'vitest';
+import { federationSafetyFindings } from './federationSafety.js';
+
+const codesFor = (value) => federationSafetyFindings(value).map((finding) => finding.code);
+
+describe('federationSafetyFindings', () => {
+ it('finds machine identity, network info and PII at any depth, naming the path', () => {
+ const findings = federationSafetyFindings({
+ install: { root: '/Users/exampleuser/portos', windows: 'C:\\Users\\exampleuser\\portos' },
+ network: ['192.0.2.10', 'fe80::1ff:fe23:4567:890a', 'de:ad:be:ef:00:11', 'host-xxxx.ts.net'],
+ owner: '[email protected]',
+ reach: 'call +1 555 010 4477',
+ where: 'latitude: 37.4219',
+ });
+
+ expect(new Set(findings.map((f) => f.code))).toEqual(new Set([
+ 'home-path', 'windows-path', 'ip-literal', 'mac-address', 'network-host', 'email-address', 'phone-number', 'gps-coordinate',
+ ]));
+ expect(findings.find((f) => f.code === 'home-path').path).toBe('install.root');
+ expect(findings.find((f) => f.code === 'network-host').path).toBe('network.3');
+ });
+
+ it('scans object KEYS, not only values', () => {
+ // A field NAMED for a host leaks the host exactly as a value would.
+ expect(codesFor({ 'host-xxxx.ts.net': { status: 'up' } })).toContain('network-host');
+ });
+
+ it('catches a credential named as a key, which no value-shape scan can see', () => {
+ // `hunter2` is not credential-SHAPED; only the key says what it is.
+ expect(codesFor({ apiKey: 'hunter2' })).toEqual(['secret-key']);
+ expect(codesFor({ nested: { refresh_token: 'hunter2' } })).toEqual(['secret-key']);
+ expect(codesFor({ tokenCount: 4 })).toEqual(['secret-key']);
+ expect(codesFor({ affordance: { inspect: 'reads the pulse count' } })).toEqual([]);
+ });
+
+ it('reports nothing for an ordinary payload', () => {
+ expect(codesFor({ schema: { pulses: 'integer' }, summary: 'A beacon that keeps pulsing.' })).toEqual([]);
+ });
+
+ it('caps the findings it returns', () => {
+ const many = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`field${i}`, '[email protected]']));
+ expect(federationSafetyFindings(many)).toHaveLength(40);
+ expect(federationSafetyFindings(many, { limit: 3 })).toHaveLength(3);
+ });
+});
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 30d9d66148..3ca139092a 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -628,17 +628,19 @@ describe('deferred imports stay deferred (#6156)', () => {
// that is what makes this a budget rather than a high-water mark. Measured after
// both changes: 104,739.
//
-// 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.
+// Raised to 107,700 for the Eidoverse foundation promote gate (#7455).
+// Measured after the change: 106,329, so its own cost is +132. Most of that is
+// ONE node on each of the ~60 closures that reach `services/userActions.js`,
+// which now imports the extracted leaf `lib/secretKeys.js` instead of
+// declaring `isSecretKey` inline — the extraction is what lets the federation
+// gate ask the same question, and the leaf has no imports of its own, so the
+// alternative was a second copy of the table. The rest is four small new
+// suites and the mandatory `lib/` barrel rows. Nothing heavy gained an edge:
+// the promote path's assay dependency is reached only from the ledger service,
+// which only `routes/eidoverseWorldRoutes.js` imports. The remainder of the
+// raise restores the ~1.5k of headroom this is meant to carry — the previous
+// number had drifted back to three above the measured total, the same
+// zero-headroom state #6305 raised it out of, where any addition at all fails.
const MAX_STATIC_INSTANTIATIONS = 107700;
diff --git a/server/lib/index.js b/server/lib/index.js
index f4d9367a9a..4ded7123c8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -553,6 +553,8 @@ export * from './dispatchLabels.js';
export * from './domainAutonomy.js';
export * from './domainBudgets.js';
export * from './eidoverseFoundations.js';
+export * from './federationSafety.js';
+export * from './secretKeys.js';
export * from './eidoverseWorldDesign.js';
export * from './eidoverseWorldLabels.js';
export * from './eidoverseWorldSignals.js';
diff --git a/server/lib/secretKeys.js b/server/lib/secretKeys.js
new file mode 100644
index 0000000000..0c38eda2e8
--- /dev/null
+++ b/server/lib/secretKeys.js
@@ -0,0 +1,39 @@
+/**
+ * "Does this payload KEY name hold a credential?" — the key-side half of the
+ * secret-redaction pair whose value side is `secretText.js#scrubSecretTokens`.
+ *
+ * Split out of `services/userActions.js` (where the operator-action ledger
+ * wrote it) when the Eidoverse promote gate needed the same question at the
+ * federation boundary: a `body` of `{ apiKey: 'hunter2' }` carries a live
+ * credential that no value-shape pattern can recognize, because the secret is
+ * only identifiable by what it is CALLED. Pure and dependency-free so both a
+ * `lib/` gate and a `services/` ledger can reach it.
+ *
+ * Substring matching is deliberate OVER-redaction: dropping `tokenCount` costs
+ * one boring number, while missing `refreshToken` writes a live credential to
+ * disk (or ships it to a peer).
+ */
+
+// Matched against the key with separators and case removed, so `api_key`,
+// `apiKey` and `API-KEY` all normalize to `apikey`.
+const SECRET_KEY_FRAGMENTS = [
+ 'password', 'passwd', 'passphrase', 'secret', 'token', 'apikey', 'authorization',
+ 'credential', 'privatekey', 'ciphertext', 'cookie', 'accesskey',
+];
+// Names too short to substring-match safely (a bare `key` fragment would eat
+// `keysChanged`, `env` would eat `envelope`), so they match only as a WHOLE key.
+const SECRET_KEY_EXACT = new Set(['key', 'keys', 'auth', 'env', 'dotenv', 'vault', 'pat', 'pw']);
+
+const normalizeKey = (key) => String(key).toLowerCase().replace(/[^a-z0-9]/g, '');
+
+/** True when a payload key name looks like it holds a credential. */
+export function isSecretKey(key) {
+ const normalized = normalizeKey(key);
+ if (!normalized) return false;
+ if (SECRET_KEY_EXACT.has(normalized)) return true;
+ // A trailing `Key`/`Keys` is how every provider-specific credential is named
+ // (`openaiKey`, `sshKey`, `signingKey`, `deployKeys`), and none of them contain
+ // the literal `apikey`. Anchoring at the END keeps `keysChanged` out.
+ if (normalized.endsWith('key') || normalized.endsWith('keys')) return true;
+ return SECRET_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment));
+}
diff --git a/server/routes/eidoverseWorldRoutes.js b/server/routes/eidoverseWorldRoutes.js
index cc204e9f27..312526763e 100644
--- a/server/routes/eidoverseWorldRoutes.js
+++ b/server/routes/eidoverseWorldRoutes.js
@@ -21,7 +21,7 @@ import {
packageEidoverseFoundationCandidate,
recordEidoverseFoundation,
} from '../services/eidoverseFoundationLedger.js';
-import { getInstanceId } from '../services/instanceIdentity.js';
+import { ensureInstanceId } from '../services/instanceIdentity.js';
import {
augmentEidoverseWorld,
ensureEidoverseWorldPresence,
@@ -82,6 +82,10 @@ router.post('/say', asyncHandler(async (req, res) => {
}));
// --- Foundations: the local-vs-baseline ownership ledger (#7455) ---------
+// These bodies validate against schemas in `lib/eidoverseFoundations.js`
+// rather than `lib/eidoverseValidation.js` (the rest of this router's home),
+// because the module that owns the ownership contract owns its shapes — the
+// same split `brainValidation.js` / `persistentMindCapabilities.js` already use.
// GET /api/eidoverse/world/foundations — every foundation this install has
// authored, with its ownership layer and last packaged promote candidate.
@@ -94,7 +98,10 @@ router.get('/foundations', asyncHandler(async (_req, res) => {
// 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() }) });
+ // `ensureInstanceId`, not `getInstanceId`: the id is stamped into durable
+ // provenance and hashed into the promote fingerprint, so the `unknown`
+ // sentinel a not-yet-initialized install returns must never be recorded.
+ res.json({ success: true, foundation: await recordEidoverseFoundation(input, { originInstanceId: await ensureInstanceId() }) });
}));
// POST /api/eidoverse/world/foundations/:id/candidate — run the agent-free
@@ -105,7 +112,7 @@ 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 });
+ res.json(result);
}));
// GET /api/eidoverse/world/foundations/:id — one foundation record.
diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.js
index dedcbe4d15..1ea0ee8555 100644
--- a/server/routes/eidoverseWorldRoutes.test.js
+++ b/server/routes/eidoverseWorldRoutes.test.js
@@ -34,7 +34,7 @@ vi.mock('../services/eidoverseFoundationLedger.js', () => ({
recordEidoverseFoundation: mocks.recordFoundation,
}));
-vi.mock('../services/instanceIdentity.js', () => ({ getInstanceId: () => Promise.resolve('instance-aaaa') }));
+vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: () => Promise.resolve('instance-aaaa') }));
const { default: eidoverseWorldRoutes } = await import('./eidoverseWorldRoutes.js');
@@ -190,7 +190,7 @@ describe('Eidoverse world routes', () => {
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).toMatchObject({ outcome: 'refused' });
expect(response.body.reasons[0]).toContain('resilience assay failed');
});
diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.js
index 0e98c1d4e9..c51be2b089 100644
--- a/server/services/eidoverseFoundationLedger.js
+++ b/server/services/eidoverseFoundationLedger.js
@@ -28,12 +28,11 @@
*/
import { join } from 'node:path';
-import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { PATHS, atomicWrite, 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,
@@ -41,11 +40,15 @@ import {
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');
+/** Storage-layout version stamped on `data/eidoverse/foundations.json`. */
+const LEDGER_SCHEMA_VERSION = 1;
+
+// Read through `PATHS` per call, NOT `dataPath()`: a suite redirects the data
+// root by proxying this module's `fileUtils` import, and `dataPath()` resolves
+// against `paths.js`'s own `PATHS` binding, which that proxy never sees — so
+// the helper would send every test at the live install's ledger. Per call
+// rather than captured at module load for the same reason.
+const ledgerFile = () => join(PATHS.data, 'eidoverse', 'foundations.json');
const withLedgerLock = createMutex();
@@ -55,36 +58,29 @@ const withLedgerLock = createMutex();
* user's ledger with an empty one. `strict: true` throws on unreadable bytes,
* while a genuinely ABSENT file still reads as the empty ledger it is.
*/
-async function readLedger() {
+async function readFoundations() {
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 };
+ return raw && typeof raw === 'object' && raw.foundations && typeof raw.foundations === 'object' ? { ...raw.foundations } : {};
}
-async function writeLedger(ledger) {
- await ensureDir(ledgerDir());
- await atomicWrite(ledgerFile(), { ...ledger, schemaVersion: EIDOVERSE_FOUNDATION_LEDGER_SCHEMA_VERSION });
+async function writeFoundations(foundations) {
+ await atomicWrite(ledgerFile(), { schemaVersion: LEDGER_SCHEMA_VERSION, foundations });
}
/** Every foundation this install knows about, most recently updated first. */
export async function listEidoverseFoundations() {
- const ledger = await readLedger();
- const foundations = Object.values(ledger.foundations)
+ const foundations = Object.values(await readFoundations())
.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,
- };
+ const counts = foundations.reduce((totals, entry) => ({
+ vernacular: totals.vernacular + (entry.layer === 'vernacular' ? 1 : 0),
+ baseline: totals.baseline + (entry.layer === 'baseline' ? 1 : 0),
+ candidates: totals.candidates + (entry.candidate ? 1 : 0),
+ }), { vernacular: 0, baseline: 0, candidates: 0 });
+ return { schemaVersion: LEDGER_SCHEMA_VERSION, counts, foundations };
}
export async function getEidoverseFoundation(id) {
- const ledger = await readLedger();
- return ledger.foundations[id] || null;
+ return (await readFoundations())[id] || null;
}
/**
@@ -103,8 +99,8 @@ export async function getEidoverseFoundation(id) {
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 foundations = await readFoundations();
+ const existing = foundations[authored.id] || null;
const record = {
id: authored.id,
layer: existing?.layer === 'baseline' ? 'baseline' : DEFAULT_EIDOVERSE_FOUNDATION_LAYER,
@@ -121,12 +117,15 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
promotedAt: existing?.promotedAt ?? null,
updatedAt: now,
};
- ledger.foundations[authored.id] = record;
- await writeLedger(ledger);
+ foundations[authored.id] = record;
+ await writeFoundations(foundations);
return record;
});
}
+const verdict = (outcome, reasons) => ({ outcome, candidate: null, assay: null, reasons, findings: [] });
+const unknownFoundation = (id) => verdict('unknown-foundation', [`no foundation is recorded under "${id}"`]);
+
/**
* Run the agent-free assay against a recorded foundation and, if it and every
* other gate pass, package the promote candidate onto its record.
@@ -134,37 +133,34 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =
* 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.
+ * the diagnostic that says what to fix — while a refusal clears any candidate
+ * packaged earlier, since the verdict that vouched for it no longer holds.
*
* @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: [] };
+ if (!existing) return unknownFoundation(id);
// 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: [],
- };
+ 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`]);
}
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
+ // authored should not pay for it.
+ const portosVersion = await getPortosVersion();
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: [] };
+ const foundations = await readFoundations();
+ const current = foundations[id];
+ if (!current) return unknownFoundation(id);
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: [] };
+ return verdict('refused', ['the foundation was re-authored while the assay was running — package it again']);
}
const result = packageFoundationCandidate({
@@ -173,8 +169,13 @@ export async function packageEidoverseFoundationCandidate(id, { now = new Date()
portosVersion,
now,
});
- ledger.foundations[id] = { ...current, assay, candidate: result.candidate, updatedAt: now };
- await writeLedger(ledger);
+ // `updatedAt` tracks the BODY's authorship, not assay runs: bumping it here
+ // would reorder the list on a refusal and make the optimistic check above
+ // 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 };
+ await writeFoundations(foundations);
return { ...result, assay };
});
}
diff --git a/server/services/eidoverseResilienceContributions.js b/server/services/eidoverseResilienceContributions.js
index ed9806d33b..bbbee7853c 100644
--- a/server/services/eidoverseResilienceContributions.js
+++ b/server/services/eidoverseResilienceContributions.js
@@ -46,8 +46,12 @@ export async function listContributionModulePaths() {
*/
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`);
+ // A lone named export stands in for a default; SEVERAL do not. Picking "the
+ // first function" out of an ordinary multi-export module would silently call
+ // something that is not a factory at all and hand back its return value.
+ const named = Object.values(mod).filter((value) => typeof value === 'function');
+ const factory = typeof mod.default === 'function' ? mod.default : (named.length === 1 ? named[0] : null);
+ if (!factory) throw new Error(`${modulePath} must export a default contribution factory, or exactly one named function (found ${named.length})`);
return factory();
}
diff --git a/server/services/eidoverseResilienceContributions.test.js b/server/services/eidoverseResilienceContributions.test.js
new file mode 100644
index 0000000000..94877ac3bd
--- /dev/null
+++ b/server/services/eidoverseResilienceContributions.test.js
@@ -0,0 +1,31 @@
+/**
+ * This resolver is what keeps an HTTP-supplied contribution id from becoming an
+ * import path, and it is the single registry the CLI and the promote path must
+ * agree on. Both properties are structural, so they get a test.
+ */
+import { describe, expect, it } from 'vitest';
+import { findContributionById, listContributionModulePaths, loadContributionModule } from './eidoverseResilienceContributions.js';
+
+describe('resilience-assay contribution registry', () => {
+ it('registers only *.contribution.js, so the deliberately-failing fixture is not promotable', async () => {
+ const paths = await listContributionModulePaths();
+
+ expect(paths.length).toBeGreaterThan(0);
+ expect(paths.every((path) => path.endsWith('.contribution.js'))).toBe(true);
+ expect(paths.some((path) => path.includes('narratedOnly'))).toBe(false);
+ });
+
+ it('resolves by id and reports a miss instead of importing what the caller named', async () => {
+ expect((await findContributionById('beacon-relay-demo')).id).toBe('beacon-relay-demo');
+ // The shapes an id can never resolve to — a path is data here, not a module.
+ expect(await findContributionById('../../../etc/passwd')).toBeNull();
+ expect(await findContributionById('eidoverseResilienceAssayFixtures/narratedOnly.failing.fixture.js')).toBeNull();
+ });
+
+ it('refuses an ordinary multi-export module rather than calling its first function', async () => {
+ const [firstPath] = await listContributionModulePaths();
+ const notAContribution = `${firstPath.replace(/[^/\\]+$/, '')}../eidoverseResilienceContributions.js`;
+
+ await expect(loadContributionModule(notAContribution)).rejects.toThrow(/exactly one named function/);
+ });
+});
diff --git a/server/services/userActions.js b/server/services/userActions.js
index 5672661d8b..e6dbb7d7bf 100644
--- a/server/services/userActions.js
+++ b/server/services/userActions.js
@@ -45,6 +45,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { isPlainObject } from '../lib/objects.js';
+import { isSecretKey } from '../lib/secretKeys.js';
import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';
import { isTestRunner, isVitestRunner } from '../lib/runtimeEnv.js';
import { isUserActionActor, isUserActionType } from '../lib/userActionTypes.js';
@@ -129,32 +130,6 @@ export function __setUserActionRetention({ maxRows, maxAgeDays } = {}) {
// Pure helpers (exported for focused tests — no I/O, no side effects).
// ---------------------------------------------------------------------------
-// Credential-shaped key names, matched against the key with separators and case
-// removed (`api_key`, `apiKey`, `API-KEY` all normalize to `apikey`). Substring
-// matching is deliberate over-redaction: dropping `tokenCount` costs one boring
-// number, while missing `refreshToken` writes a live credential to disk.
-const SECRET_KEY_FRAGMENTS = [
- 'password', 'passwd', 'passphrase', 'secret', 'token', 'apikey', 'authorization',
- 'credential', 'privatekey', 'ciphertext', 'cookie', 'accesskey',
-];
-// Names too short to substring-match safely (a bare `key` fragment would eat
-// `keysChanged`, `env` would eat `envelope`), so they redact only as a WHOLE key.
-const SECRET_KEY_EXACT = new Set(['key', 'keys', 'auth', 'env', 'dotenv', 'vault', 'pat', 'pw']);
-
-const normalizeKey = (key) => String(key).toLowerCase().replace(/[^a-z0-9]/g, '');
-
-/** True when a payload key name looks like it holds a credential. */
-export function isSecretKey(key) {
- const normalized = normalizeKey(key);
- if (!normalized) return false;
- if (SECRET_KEY_EXACT.has(normalized)) return true;
- // A trailing `Key`/`Keys` is how every provider-specific credential is named
- // (`openaiKey`, `sshKey`, `signingKey`, `deployKeys`), and none of them contain
- // the literal `apikey`. Anchoring at the END keeps `keysChanged` out.
- if (normalized.endsWith('key') || normalized.endsWith('keys')) return true;
- return SECRET_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment));
-}
-
/** Collapse whitespace and clamp to one LLM-readable line. */
export function clampSummary(text, max = SUMMARY_MAX_CHARS) {
const line = String(text ?? '').replace(/\s+/g, ' ').trim();