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
wire the Eidoverse creative toolkit's layout builders to real callers (#7627)
[._.]/ Adam Eivy498d633a2ac5
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdindex d6eb4f9a46..e3be619399 100644--- a/docs/features/eidoverse.md+++ b/docs/features/eidoverse.md@@ -893,7 +893,7 @@ own `candidateVersion`, which pins one envelope's shape and is hashed into itsfingerprint: a change to the envelope bumps both, a change to the wrapper orthe caps bumps only the category.-### Creative toolkit for minds (#7459)+### Creative toolkit for minds (#7459, wired end-to-end in #7627)Authoring a foundation from a blank `body`/`style` is a lot to invent fromscratch every time. `server/lib/eidoverseCreativeToolkit.js` is a small,@@ -902,25 +902,43 @@ and **motifs** (cosmetics — install-local `style`, the same class of value`styleLeakFindings` refuses inside a `body`) and named **generative placementlayouts** (`radial-ring`, `grid-plot`, `arc-row`, `grove-cluster` — structure,safe as `body`). `eidoverse.creative-catalog` (`manageEidoverse`, read) lists-all three; nothing here calls an AI provider — every layout is deterministic-and seeded (`generateDistrictTemplatePlacement`), so the same-`{layoutId, anchor, seed}` reproduces the same geometry on replay or on a peer-that later inherits the promoted foundation.--Two ways to use a chosen layout:--- `buildDistrictTemplateAugmentOperations()` turns a placement into- ready-to-submit `eidoverse.augment` `spawn` operations for the *live* scene- (asset-path validity is still checked where `eidoverse.augment` lands them).-- `buildDistrictTemplateFoundationDraft()` composes a placement plus a- material/motif choice into an `eidoverseFoundationInputSchema`-shaped- `district-template` input — the generative substance (layout id, anchor,- seed, resulting positions) in `body`, the material/motif cosmetics in- `style` — ready to pass straight to `eidoverse.record`. It always lands on- the local `vernacular` layer, matching every other authored foundation;- publishing it to the shared baseline remains the separate, explicit+all three, including each material's `colorHex` — a palette id whose value a+mind cannot see is not a usable catalog entry. Nothing here calls an AI+provider; every layout is deterministic and seeded+(`generateDistrictTemplatePlacement`), so the same `{layoutId, anchor, seed}`+reproduces the same geometry on replay or on a peer that later inherits the+promoted foundation.++Two tools use a chosen layout, both read-only (they compute; they do not write+to the world or the foundation ledger):++- **`eidoverse.place-layout`** (`manageEidoverse`) calls+ `buildDistrictTemplateAugmentOperations()` and returns ready-to-submit+ `eidoverse.augment` `spawn` operations for the *live* scene (asset-path+ validity is still checked where `eidoverse.augment` lands them). The same+ `{layoutId, anchor, seed}` yields byte-identical operations every call.+- **`eidoverse.draft-foundation`** (`manageEidoverse`) calls+ `buildDistrictTemplateFoundationDraft()` and returns an+ `eidoverseFoundationInputSchema`-shaped `district-template` input — the+ generative substance (layout id, anchor, seed, resulting positions) in+ `body`, the material/motif cosmetics in `style` — ready to pass straight to+ `eidoverse.record`. Drafting composes nothing itself; recording still lands+ on the local `vernacular` layer, matching every other authored foundation,+ and publishing to the shared baseline remains the separate, explicit`eidoverse.promote` act above.+**`eidoverse.record` derives, never trusts, a `district-template`'s+placement.** When a recorded `district-template`'s `body` carries+`{layoutId, anchor}` (with an optional `seed`), `recordEidoverseFoundation()`+(`services/eidoverseFoundationLedger.js`) replays+`generateDistrictTemplatePlacement()` server-side and stores the result as+`body.placement` — REPLACING any placement the caller supplied, not merging+it. That is what makes the replay claim above hold for a hand-assembled+`eidoverse.record` call too, not only for one built from+`eidoverse.draft-foundation`'s output, and it is why the same `district-template`+is comparable and replayable on an older or newer install that later inherits+it (#7625).+## Observation-first discovery (#7457)SwarmWorld's finding is that reuse between agents starts by **looking at thediff --git a/server/lib/README.md b/server/lib/README.mdindex 0edf6a5135..c34dc6486d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -591,7 +591,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `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 (the shared table is `piiRedactionPatterns.js`), 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. || `piiRedactionPatterns.js` | `PII_PATTERNS` — the machine-identity/PII `{ code, pattern, replacement }` table shared by `federationSafety.js` (detection, via `pattern.test()`) and `services/agentContextMcp.js#redactAgentContextText` / `services/agentErrorAnalysis.js#redactFailureSnippet` (replacement, via `redactPii(text)`). One list for home/Windows paths, IPv4/IPv6, MAC, `.ts.net`/`.local` hosts, email, phone, and labelled GPS coordinates, so a correction reaches every consumer instead of drifting across independent copies (#7474). `globalPattern(pattern)` derives a global-flagged copy for a `.replace()` caller without mutating the shared (deliberately non-global) regex object. Dependency-free leaf — credential-shaped/-named checks stay in `secretText.js`/`secretKeys.js`. 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`). |-| `eidoverseCreativeToolkit.js` | The documented creative toolkit for minds building Eidoverse vernacular content (#7459): a closed catalog of `EIDOVERSE_CREATIVE_MATERIALS` and `EIDOVERSE_CREATIVE_MOTIFS` (cosmetics — style-layer only) plus `EIDOVERSE_CREATIVE_LAYOUTS` (named generative placement algorithms — `radial-ring`/`grid-plot`/`arc-row`/`grove-cluster`). `generateDistrictTemplatePlacement` is deterministic and seeded (mulberry32, no `Math.random`, no AI call) so the same `{layoutId, anchor, seed}` always reproduces the same geometry. `buildDistrictTemplateAugmentOperations` turns a placement into ready-to-submit `eidoverse.augment` `spawn` operations; `buildDistrictTemplateFoundationDraft` shapes a placement plus a material/motif choice into an `eidoverseFoundationInputSchema`-ready `district-template` input, keeping the generative substance in `body` and the material/motif cosmetics in `style`. `describeCreativeCatalog()` is the prompt-safe catalog projection. Pure: no I/O, no clock, no provider calls. |+| `eidoverseCreativeToolkit.js` | The documented creative toolkit for minds building Eidoverse vernacular content (#7459, wired end-to-end in #7627): a closed catalog of `EIDOVERSE_CREATIVE_MATERIALS` and `EIDOVERSE_CREATIVE_MOTIFS` (cosmetics — style-layer only) plus `EIDOVERSE_CREATIVE_LAYOUTS` (named generative placement algorithms — `radial-ring`/`grid-plot`/`arc-row`/`grove-cluster`). `generateDistrictTemplatePlacement` is deterministic and seeded (mulberry32, no `Math.random`, no AI call) so the same `{layoutId, anchor, seed}` always reproduces the same geometry — `services/eidoverseFoundationLedger.js`'s `recordEidoverseFoundation()` replays it server-side to derive a `district-template`'s `body.placement`, never trusting a caller-supplied one. `buildDistrictTemplateAugmentOperations` turns a placement into ready-to-submit `eidoverse.augment` `spawn` operations (the `eidoverse.place-layout` tool); `buildDistrictTemplateFoundationDraft` shapes a placement plus a material/motif choice into an `eidoverseFoundationInputSchema`-ready `district-template` input, keeping the generative substance in `body` and the material/motif cosmetics in `style` (the `eidoverse.draft-foundation` tool). `describeCreativeCatalog()` is the prompt-safe catalog projection, including each material's `colorHex`. Pure: no I/O, no clock, no provider calls. || `eidoverseControllers.js` | Executable Eidoverse world controllers — the install schema and the sandboxed step boundary (#7456). `eidoverseControllerInstallSchema` / `eidoverseControllerRecordSchema` describe an install (a registry `controllerId`, a bounded `config`, a `tickIntervalMs`, and a `deliverEffects` flag that is FALSE by default, so installing arms bookkeeping and never a world verb). `runControllerStep` is the sandbox: it hands the controller JSON copies of its state and config, REFUSES a step that returns a Promise (an await is the shape every network/disk/AI-provider call takes, so the tick path is provider-free structurally rather than by convention), caps the state it may return, and validates its effects against a closed vocabulary — `note` (never leaves the ledger), `say`, and `augment`, which reuses `eidoverseValidation.js`'s own world-verb operation schema. `controllerTickDue` / `nextControllerTickAt` are the scheduling math, measured from now so a machine that slept wakes to ONE tick and not a replayed backlog. `summarizeControllerInstall` is the prompt-shaped projection that keeps a 16KB state blob out of a mind turn. Pure: callers pass `now`. || `eidoverseFoundations.js` | Local-vs-baseline ownership for Eidoverse world foundations and the promote-candidate packaging gate (#7455). `EIDOVERSE_FOUNDATION_LAYERS` (`runtime` / `baseline` / `vernacular`, defaulting to `vernacular` so nothing is shared by omission) and `layerPromoteRefusal`; the record / input / candidate-envelope Zod schemas, where a foundation is `{ body, style }` BY CONSTRUCTION — packaging carries `body` and drops `style`, so an inheriting peer never receives its author's cosmetics, and `styleLeakFindings` REFUSES an unambiguously cosmetic key smuggled into `body` (spatial/asset keys stay allowed — they are a district template's substance). `assayEvidenceFromVerdict` folds an agent-free resilience verdict (#7460) into the evidence the gate reads, including the binding that it ran against the contribution this foundation names. `packageFoundationCandidate` and `verifyFoundationCandidate` are the one gate seen from the sending and receiving sides, over a content-addressed `fingerprint` hashed from the payload AS SENT; federation safety comes from `federationSafety.js`. `summarizeFoundation` is the prompt-shaped projection of a ledger record (layer, identity, assay outcome, whether a candidate exists) that keeps the local style layer and the packaged envelope out of a mind turn. Pure: callers pass `now`. || `eidoverseObservation.js` | Pure observation-first discovery report for the Eidoverse (#7457) — the read behind `eidoverse.observe`. `buildEidoverseObservation` turns already-collected snapshots (world signals, the install's RESOLVED design districts/includes, the foundation ledger, summarized controller installs) plus the previously persisted visit marker into `{ report, marker }`: districts as places a mind can describe, peers keyed to the foundations inherited through each, a peer contribution's origin/arrival instances, controllers filtered to the ones actually failing, and a `changes` diff against the last visit. Places come from the recipe rather than a constant, so a mind never names a district a later design version renamed; an unreadable source stays `null` and a recipe-disabled one reports `disabled`, neither collapsing to `0`; a first observation reports `firstObservation` rather than declaring a settled world new; and places diff on status flips only so routine signal churn never becomes noise. Scalar-vs-list source shape is shared with the projection via `EIDOVERSE_SCALAR_SOURCE_KEYS`. Pure: the caller passes `observedAt` and decides whether to commit the returned marker. |diff --git a/server/lib/eidoverseCreativeToolkit.js b/server/lib/eidoverseCreativeToolkit.jsindex 091bec61ca..572057c3fd 100644--- a/server/lib/eidoverseCreativeToolkit.js+++ b/server/lib/eidoverseCreativeToolkit.js@@ -30,8 +30,21 @@* generative placement is substance and lands in `body`; the material/motif* choice is cosmetics and lands in `style`. Pure: no I/O, no clock, no* provider calls.+ *+ * Every builder here has a real, non-test caller (#7627): `describeCreativeCatalog()`+ * is `eidoverse.creative-catalog`; `buildDistrictTemplateAugmentOperations()`+ * (via `generateDistrictTemplatePlacement()`) is `eidoverse.place-layout`;+ * `buildDistrictTemplateFoundationDraft()` is `eidoverse.draft-foundation`+ * (`services/cosToolRegistry.js`); and `generateDistrictTemplatePlacement()`+ * is also what `services/eidoverseFoundationLedger.js`'s+ * `recordEidoverseFoundation()` replays server-side to derive a+ * `district-template`'s `body.placement` from its declared+ * `{layoutId, anchor, seed}` rather than trusting a caller-supplied one.*/+import { z } from 'zod';+import { eidoverseFoundationInputSchema } from './eidoverseFoundations.js';+const clampInt = (value, min, max) => Math.min(max, Math.max(min, Math.round(value)));// ---------------------------------------------------------------------------@@ -127,11 +140,20 @@ function requireCatalogEntry(catalog, id, label) {return entry;}-/** A mind- and prompt-safe projection of the toolkit: ids, labels, descriptions only. */+/**+ * A mind- and prompt-safe projection of the toolkit: ids, labels, descriptions+ * — plus, for materials, `colorHex` (#7627). A palette id whose value a mind+ * cannot see is not a usable catalog entry: the mind picks `sunbaked-clay` for+ * a foundation's `style` and needs the actual hex to reason about how it reads+ * next to whatever else it is building. `colorHex` is cosmetic display data,+ * not a foundation `body` key, so exposing it here does not widen what a mind+ * can put in a promotable body.+ */export function describeCreativeCatalog() {const project = (catalog) => catalog.map(({ id, label, description }) => ({ id, label, description }));+ const projectMaterials = (catalog) => catalog.map(({ id, label, description, colorHex }) => ({ id, label, description, colorHex }));return {- materials: project(EIDOVERSE_CREATIVE_MATERIALS),+ materials: projectMaterials(EIDOVERSE_CREATIVE_MATERIALS),motifs: project(EIDOVERSE_CREATIVE_MOTIFS),layouts: project(EIDOVERSE_CREATIVE_LAYOUTS),};@@ -245,3 +267,63 @@ export function buildDistrictTemplateFoundationDraft({disclosure: disclosure ?? {},};}++// ---------------------------------------------------------------------------+// Tool input schemas (#7627)+// ---------------------------------------------------------------------------+// `services/cosToolRegistry.js` wires the two generative builders above as+// `eidoverse.place-layout` (live-scene augment operations) and+// `eidoverse.draft-foundation` (an `eidoverse.record`-ready district-template+// input) — the "two ways to use a chosen layout" the module header always+// described, now with a caller on both. Declared here, beside the functions+// they validate for, rather than in `services/cosToolRegistry.js`.++const eidoverseCreativeLayoutIdSchema = z.enum(EIDOVERSE_CREATIVE_LAYOUTS.map((layout) => layout.id));+const eidoverseCreativeMaterialIdSchema = z.enum(EIDOVERSE_CREATIVE_MATERIALS.map((material) => material.id));+const eidoverseCreativeMotifIdSchema = z.enum(EIDOVERSE_CREATIVE_MOTIFS.map((motif) => motif.id));+// `.length(3)`, not `z.tuple`, matching `eidoverseValidation.js`'s own vector+// schema: a fixed-length array survives the `zodToOpenApiSchema` → JSON Schema+// → `z.fromJSONSchema` round trip `validateArguments()` runs at dispatch.+const eidoverseAnchorSchema = z.array(z.number().finite()).length(3);+const eidoverseSeedSchema = z.string().trim().min(1).max(120).optional();+const eidoverseFacingSchema = z.number().finite().optional();+const eidoversePropCountSchema = z.number().int().min(1).max(16).optional();++/**+ * `eidoverse.place-layout`: compute a named layout's placement and return+ * augment-ready `eidoverse.augment` `spawn` operations. Read-only — it+ * computes, it never writes to the world; the operations still need a+ * separate `eidoverse.augment` call to land.+ */+export const eidoversePlaceLayoutInputSchema = z.object({+ layoutId: eidoverseCreativeLayoutIdSchema,+ anchor: eidoverseAnchorSchema,+ propCount: eidoversePropCountSchema,+ seed: eidoverseSeedSchema,+ facing: eidoverseFacingSchema,+ assetPath: z.string().trim().min(1).max(512),+ idPrefix: z.string().trim().min(1).max(64).optional(),+}).strict();++/**+ * `eidoverse.draft-foundation`: compose a layout, material, and motif choice+ * into an `eidoverseFoundationInputSchema`-ready `district-template` input,+ * ready to pass straight to `eidoverse.record`. The `id`/`title`/`summary`/+ * `contributionId`/`disclosure` fields are lifted from+ * `eidoverseFoundationInputSchema` itself rather than re-declared, so a limit+ * change there cannot silently diverge from what this schema accepts.+ */+export const eidoverseDraftFoundationInputSchema = z.object({+ id: eidoverseFoundationInputSchema.shape.id,+ title: eidoverseFoundationInputSchema.shape.title,+ summary: eidoverseFoundationInputSchema.shape.summary,+ contributionId: eidoverseFoundationInputSchema.shape.contributionId,+ disclosure: eidoverseFoundationInputSchema.shape.disclosure,+ layoutId: eidoverseCreativeLayoutIdSchema,+ materialId: eidoverseCreativeMaterialIdSchema,+ motifId: eidoverseCreativeMotifIdSchema,+ anchor: eidoverseAnchorSchema,+ propCount: eidoversePropCountSchema,+ seed: eidoverseSeedSchema,+ facing: eidoverseFacingSchema,+}).strict();diff --git a/server/lib/eidoverseCreativeToolkit.test.js b/server/lib/eidoverseCreativeToolkit.test.jsindex e6a70f4198..f2f117571e 100644--- a/server/lib/eidoverseCreativeToolkit.test.js+++ b/server/lib/eidoverseCreativeToolkit.test.js@@ -22,12 +22,18 @@ describe('describeCreativeCatalog', () => {]) {expect(catalog[key]).toHaveLength(source.length);expect(new Set(catalog[key].map((entry) => entry.id)).size).toBe(source.length);+ const expectedKeys = key === 'materials' ? ['colorHex', 'description', 'id', 'label'] : ['description', 'id', 'label'];for (const entry of catalog[key]) {- expect(Object.keys(entry).sort()).toEqual(['description', 'id', 'label']);+ expect(Object.keys(entry).sort()).toEqual(expectedKeys);}}- // Cosmetics (colorHex) never ride into the prompt-facing projection.- expect(JSON.stringify(catalog.materials)).not.toContain('colorHex');+ });++ it('exposes each material\'s colorHex value (#7627: a palette id whose value a mind cannot see is not usable)', () => {+ const catalog = describeCreativeCatalog();+ for (const material of EIDOVERSE_CREATIVE_MATERIALS) {+ expect(catalog.materials.find((entry) => entry.id === material.id).colorHex).toBe(material.colorHex);+ }});});diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 4137c2e93b..5369afb383 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -29,7 +29,13 @@ import {} from '../lib/validation.js';import { eidoverseFoundationIdParamSchema, eidoverseFoundationInputSchema, summarizeFoundation } from '../lib/eidoverseFoundations.js';import { eidoverseControllerArmSchema, eidoverseControllerIdParamSchema, eidoverseControllerInstallSchema, summarizeControllerInstall } from '../lib/eidoverseControllers.js';-import { describeCreativeCatalog } from '../lib/eidoverseCreativeToolkit.js';+import {+ buildDistrictTemplateAugmentOperations,+ buildDistrictTemplateFoundationDraft,+ describeCreativeCatalog,+ eidoverseDraftFoundationInputSchema,+ eidoversePlaceLayoutInputSchema,+} from '../lib/eidoverseCreativeToolkit.js';import { persistentMindChooseNameSchema } from '../lib/persistentMindChosenName.js';import { persistentMindProtectMemorySchema } from '../lib/persistentMindMemory.js';import { persistentMindThinkingRequestSchema } from '../lib/persistentMindThinkingPresets.js';@@ -412,21 +418,23 @@ const eidoverseObserveTool = Object.freeze({},adapter: { kind: 'eidoverse-observe', operation: 'observe' },});-// The documented creative toolkit (#7459): named materials, motifs, and-// generative placement layouts a mind reaches for instead of inventing-// coordinates and colors from scratch. Purely a catalog read — deterministic,-// seeded, no AI provider call (`lib/eidoverseCreativeToolkit.js`). Feed a-// chosen layout into eidoverse.record (a district-template) or-// into eidoverse.augment (live spawn operations).-const eidoverseCreativeCatalogTool = Object.freeze({- type: 'portos_tool',- name: 'eidoverse.creative-catalog',- version: COS_TOOL_SCHEMA_VERSION,- providerName: providerToolName('eidoverse.creative-catalog'),- aliases: [providerToolName('eidoverse.creative-catalog')],- description: 'List the documented creative toolkit for Eidoverse vernacular building: named materials and motifs (cosmetics for a foundation\'s `style`) and named generative district-template placement layouts (structure for a foundation\'s `body`). Deterministic and seeded — no AI provider call.',- input_schema: zodToOpenApiSchema(z.object({}).strict()),- output_schema: objectOutputSchema,+// The documented creative toolkit (#7459, wired end-to-end in #7627): named+// materials, motifs, and generative placement layouts a mind reaches for+// instead of inventing coordinates and colors from scratch. Every operation+// is deterministic, seeded, and provider-free (`lib/eidoverseCreativeToolkit.js`).+// `place-layout` and `draft-foundation` are the two ways to use a chosen+// layout the catalog's own description points at: into eidoverse.augment+// (live spawn operations) or into eidoverse.record (a district-template).+// Both stay read-only here — computing a placement or a draft is not writing+// to the world or the foundation ledger.+const eidoverseCreativeTools = [+ ['creative-catalog', 'List the documented creative toolkit for Eidoverse vernacular building: named materials and motifs (cosmetics for a foundation\'s `style`) and named generative district-template placement layouts (structure for a foundation\'s `body`). Deterministic and seeded — no AI provider call.', z.object({}).strict()],+ ['place-layout', 'Compute a named layout\'s placement (from eidoverse.creative-catalog) into ready-to-submit eidoverse.augment `spawn` operations. Deterministic and seeded: the same {layoutId, anchor, seed} always yields the same operations. This only computes — it never places anything; pass the returned `operations` to eidoverse.augment to actually build.', eidoversePlaceLayoutInputSchema],+ ['draft-foundation', 'Compose a chosen layout plus a material and motif (from eidoverse.creative-catalog) into an eidoverse.record-ready `district-template` input — the generative placement in `body`, the material/motif cosmetics in `style`. This only drafts — it never records anything; pass the returned `foundation` to eidoverse.record to persist it.', eidoverseDraftFoundationInputSchema],+].map(([operation, description, schema]) => ({+ type: 'portos_tool', name: `eidoverse.${operation}`, version: COS_TOOL_SCHEMA_VERSION,+ providerName: providerToolName(`eidoverse.${operation}`), aliases: [providerToolName(`eidoverse.${operation}`)],+ description, input_schema: zodToOpenApiSchema(schema), output_schema: objectOutputSchema,policy: {scopes: ['mind'],requiredCapabilities: ['manageEidoverse'],@@ -435,8 +443,8 @@ const eidoverseCreativeCatalogTool = Object.freeze({async: false,confirmation: 'capability-grant',},- adapter: { kind: 'eidoverse-creative', operation: 'catalog' },-});+ adapter: { kind: 'eidoverse-creative', operation },+}));// Installing a controller leaves something RUNNING in the world after the turn// ends, which is a different act from building in it during a turn — so it// carries its own default-off grant on top of `manageEidoverse`, the same way@@ -456,7 +464,7 @@ const eidoverseControllerTools = [idempotent: sideEffect === 'read', async: false, confirmation: 'capability-grant' },adapter: { kind: 'eidoverse-controllers', operation },}));-const eidoverseTools = [eidoverseObserveTool, ...eidoverseTravelTools, ...eidoverseFoundationTools, eidoverseCreativeCatalogTool, ...eidoverseControllerTools, eidoverseStatusTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];+const eidoverseTools = [eidoverseObserveTool, ...eidoverseTravelTools, ...eidoverseFoundationTools, ...eidoverseCreativeTools, ...eidoverseControllerTools, eidoverseStatusTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];const thinkingTools = ['mind.thinking-presets', 'mind.request-thinking-preset'].map((name, index) => ({type: 'portos_tool', name, version: COS_TOOL_SCHEMA_VERSION,providerName: providerToolName(name), aliases: [],@@ -771,6 +779,8 @@ const executeAdapter = async (tool, args, context, authority) => {return observeEidoverseWorld({ signal: context.signal });}if (tool.adapter.kind === 'eidoverse-creative') {+ if (tool.adapter.operation === 'place-layout') return { operations: buildDistrictTemplateAugmentOperations(args) };+ if (tool.adapter.operation === 'draft-foundation') return { foundation: buildDistrictTemplateFoundationDraft(args) };return describeCreativeCatalog();}if (tool.adapter.kind === 'eidoverse-controllers') {diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex 37d0245945..f635ba17f6 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -190,9 +190,40 @@ describe('cosToolRegistry', () => {authority: { scope: 'mind', capabilities: { manageEidoverse: true } },});expect(catalog.result.materials.length).toBeGreaterThan(0);+ expect(catalog.result.materials[0].colorHex).toMatch(/^#[0-9a-f]{6}$/i);expect(catalog.result.layouts.map((layout) => layout.id)).toContain('radial-ring');});+ it('computes a named layout into augment-ready operations, deterministically', async () => {+ const call = {+ requestId: 'place-1',+ name: 'eidoverse.place-layout',+ arguments: { layoutId: 'radial-ring', anchor: [1, 0, 2], propCount: 3, seed: 'plaza', assetPath: 'eidoverse/assets/models/lantern.glb', idPrefix: 'plaza' },+ };+ const first = await executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { manageEidoverse: true } } });+ const second = await executeCosToolCall({ call: { ...call, requestId: 'place-2' }, authority: { scope: 'mind', capabilities: { manageEidoverse: true } } });+ expect(first.result.operations).toHaveLength(3);+ expect(first.result.operations.every((op) => op.verb === 'spawn')).toBe(true);+ // Same {layoutId, anchor, seed} must yield byte-identical operations — the+ // determinism the replay claim (#7627) rests on.+ expect(second.result).toEqual(first.result);+ });++ it('drafts an eidoverse.record-ready district-template foundation from a chosen layout, material, and motif', async () => {+ const call = {+ requestId: 'draft-1',+ name: 'eidoverse.draft-foundation',+ arguments: {+ id: 'garden-arcade', title: 'Garden Arcade', summary: 'A colonnade of lanterns around the arrival plaza.',+ contributionId: 'beacon-relay', layoutId: 'radial-ring', materialId: 'sunbaked-clay', motifId: 'lantern-row', anchor: [4, 0, -6],+ },+ };+ const result = await executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { manageEidoverse: true } } });+ expect(result.result.foundation).toMatchObject({ id: 'garden-arcade', kind: 'district-template' });+ expect(result.result.foundation.body.placement.length).toBeGreaterThan(0);+ expect(result.result.foundation.style).toMatchObject({ materialId: 'sunbaked-clay', motifId: 'lantern-row' });+ });+it('keeps local thinking authority separate and refuses raw configuration arguments', async () => {const call = { requestId: 'thinking-1', name: 'mind.request-thinking-preset', arguments: { presetId: 'local', reason: 'Try a focused pass' } };await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { writePortos: true, createTasks: true } } })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });@@ -244,6 +275,8 @@ describe('cosToolRegistry', () => {'eidoverse.record','eidoverse.promote','eidoverse.creative-catalog',+ 'eidoverse.place-layout',+ 'eidoverse.draft-foundation','eidoverse.controllers','eidoverse.install-controller','eidoverse.arm-controller',diff --git a/server/services/eidoverseFoundationLedger.js b/server/services/eidoverseFoundationLedger.jsindex 234e178609..372d1cf291 100644--- a/server/services/eidoverseFoundationLedger.js+++ b/server/services/eidoverseFoundationLedger.js@@ -57,6 +57,7 @@ import {verifyFoundationCandidate,} from '../lib/eidoverseFoundations.js';import { ServerError } from '../lib/errorHandler.js';+import { generateDistrictTemplatePlacement } from '../lib/eidoverseCreativeToolkit.js';import { RESILIENCE_DISTURBANCES, runResilienceAssay } from './eidoverseResilienceAssay.js';import { findContributionById } from './eidoverseResilienceContributions.js';@@ -160,6 +161,28 @@ export async function getEidoverseFoundation(id) {return found ? { ...found, lineage: foundationLineage(found) } : null;}+/**+ * A `district-template` foundation's `body.placement` is DERIVED, never+ * trusted verbatim from the caller (#7627): `generateDistrictTemplatePlacement()`+ * is deterministic and seeded, so replaying `{layoutId, anchor, seed}` here —+ * the same replay a peer runs on inherit — is what makes the module's "same+ * inputs reproduce the same geometry" claim actually hold on the install that+ * authored it. A caller-supplied `placement` that disagrees with the+ * derivation is REPLACED wholesale, not merged: a stale or hand-edited value+ * must never ride along looking like the derivation's own output.+ *+ * A body missing `layoutId` or `anchor` (an older shape, or a foundation kind+ * this doesn't apply to) is returned unchanged — this only expands the one+ * documented generative shape, never invents one.+ */+function deriveDistrictTemplateBody(authored) {+ if (authored.kind !== 'district-template') return authored.body;+ const { layoutId, anchor, propCount, seed, facing } = authored.body;+ if (typeof layoutId !== 'string' || !Array.isArray(anchor)) return authored.body;+ const placement = generateDistrictTemplatePlacement({ layoutId, anchor, propCount, seed, facing });+ return { ...authored.body, placement };+}+/*** Record (or re-author) a local vernacular foundation.*@@ -194,9 +217,16 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =// the route and the mind tool — treat this function's return value as the// recorded foundation, and a verdict shape would make "refused" look like// a saved record to anything that did not read the new field.+ // Digest the body as it will be STORED, not as it arrived (#7627 + #7631).+ // A district-template's `placement` is derived here rather than supplied, so+ // a caller who re-submits only the `{layoutId, anchor, seed}` recipe of an+ // inherited template — which is exactly what `eidoverse.draft-foundation`+ // hands back — would otherwise digest a body the inherited copy never had,+ // slip past the republish guard, and then be stored byte-identical to it.+ const body = deriveDistrictTemplateBody(authored);const derivation = resolveFoundationDerivation({claim: authored.derivedFrom,- body: authored.body,+ body,inheritedRecords: Object.values(foundations),existingEdge: existing?.derivedFrom || null,now,@@ -209,7 +239,7 @@ export async function recordEidoverseFoundation(input, { originInstanceId, now =title: authored.title,summary: authored.summary,contributionId: authored.contributionId,- body: authored.body,+ body,style: authored.style,provenance: existing?.provenance || { originInstanceId, authorKind: authored.authorKind, createdAt: now },disclosure: authored.disclosure,diff --git a/server/services/eidoverseFoundationLedger.test.js b/server/services/eidoverseFoundationLedger.test.jsindex fce08d4e5e..a33863ed8c 100644--- a/server/services/eidoverseFoundationLedger.test.js+++ b/server/services/eidoverseFoundationLedger.test.js@@ -71,6 +71,54 @@ describe('the local foundation ledger', () => {});});+describe('deriving a district-template placement server-side (#7627)', () => {+ const districtTemplate = (bodyOverrides = {}) => authored({+ id: 'garden-arcade',+ kind: 'district-template',+ body: { layoutId: 'radial-ring', anchor: [1, 0, 2], propCount: 4, seed: 'plaza', ...bodyOverrides },+ });++ it('persists a server-derived placement for a declared {layoutId, anchor, seed}', async () => {+ const saved = await record(districtTemplate(), '2026-03-04T05:06:07.000Z');++ expect(saved.body.placement).toBeTruthy();+ expect(saved.body.placement).toHaveLength(4);+ expect(saved.body.layoutId).toBe('radial-ring');+ });++ it('reproduces byte-identical placement for the same {layoutId, anchor, seed} across two recordings', async () => {+ const first = await record(districtTemplate(), '2026-03-04T05:06:07.000Z');+ const second = await record(districtTemplate({ }), '2026-03-04T05:06:08.000Z');++ expect(second.body.placement).toEqual(first.body.placement);+ });++ it('replaces a caller-supplied placement that disagrees with the derivation, rather than merging it', async () => {+ const bogusPlacement = [{ pos: [999, 999, 999], yaw: 0 }];+ const saved = await record(districtTemplate({ placement: bogusPlacement }), '2026-03-04T05:06:07.000Z');++ expect(saved.body.placement).not.toEqual(bogusPlacement);+ expect(saved.body.placement).toHaveLength(4);+ });++ it('leaves a non-district-template body untouched even if it happens to carry a layoutId-shaped field', async () => {+ const saved = await record(authored({ body: { schema: { layoutId: 'not-a-real-layout', anchor: [0, 0, 0] } } }), '2026-03-04T05:06:07.000Z');++ expect(saved.body).toEqual({ schema: { layoutId: 'not-a-real-layout', anchor: [0, 0, 0] } });+ });++ it('leaves a district-template body without a declared layoutId/anchor untouched', async () => {+ const saved = await record(authored({ id: 'legacy-district', kind: 'district-template', body: { note: 'hand-authored, pre-toolkit' } }), '2026-03-04T05:06:07.000Z');++ expect(saved.body).toEqual({ note: 'hand-authored, pre-toolkit' });+ });++ it('refuses an unknown layoutId rather than silently storing an unusable declaration', async () => {+ await expect(record(districtTemplate({ layoutId: 'floating-islands' })))+ .rejects.toThrow(/Unknown layout "floating-islands"/);+ });+});+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');@@ -339,6 +387,28 @@ describe('building on a foundation inherited from a peer (#7631)', () => {return { candidate: promoted.candidate, inherited: inherited.foundation };};+ // #7627 derives a district-template's `placement` server-side, so the guard+ // has to digest the body it will STORE. Digesting the body as it arrived let a+ // caller re-submit just the inherited template's {layoutId, anchor, seed}+ // recipe — what `eidoverse.draft-foundation` returns — and land a stored body+ // byte-identical to the peer's while never matching it at the check.+ it('refuses a district-template whose recipe only derives into the inherited body', async () => {+ await record({ id: 'tide-beacon', kind: 'district-template', body: { layoutId: 'radial-ring', anchor: [1, 0, 2], propCount: 4, seed: 'plaza' } }, '2026-03-01T00:00:00.000Z');+ const promoted = await promoteEidoverseFoundation('tide-beacon', { now: '2026-03-01T01:00:00.000Z' });+ rmSync(lazyTempDataRoot('portos-eidoverse-foundations-'), { recursive: true, force: true });+ expect((await recordEidoverseFoundationInheritance(promoted.candidate, {+ sourceInstanceId: 'instance-peer-one', localInstanceId: 'instance-this-install', now: '2026-03-02T00:00:00.000Z',+ })).outcome).toBe('inherited');++ // The recipe ALONE — no `placement` key, so its raw digest cannot match the+ // inherited body, which carries the derived placement.+ await expect(recordEidoverseFoundation(+ authored({ id: 'my-own-arcade', kind: 'district-template', body: { layoutId: 'radial-ring', anchor: [1, 0, 2], propCount: 4, seed: 'plaza' } }),+ { originInstanceId: 'instance-this-install', now: '2026-03-03T00:00:00.000Z' },+ )).rejects.toThrow(new RegExp(`inherited from install ${PEER_ORIGIN}`));+ expect(await getEidoverseFoundation('my-own-arcade')).toBeNull();+ });+it('refuses to record a peer\'s body as this install\'s own work, naming the origin it came from', async () => {const { candidate } = await inheritPeerFoundation();