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
feat: add explicit provider-free Eidoverse riddle rounds
Adam Eivyab3c3946f42d
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 781fe784f4..86aea58d1c 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -166,6 +166,7 @@ does not recover nonempty output or general failed saves; those still require th- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, explicit display aliases keyed by opaque resource identity (never backfilled from records), user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. Guest travel sessions and live chat cursors are ephemeral transport state held only in memory; they are not a new record store or sync category. Explicit guest conversation follows the [guest-chat ADR](decisions/2026-09-05-eidoverse-guest-chat.md). PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.- Eidoverse world foundations ledger — `data/eidoverse/foundations.json` (#7455, #7461). The install-local record of every durable world foundation this instance authored OR inherited: its ownership layer (`vernacular` by default, `baseline` once promoted or inherited), the promotable `body`, the vernacular `style` layer that never leaves, provenance (opaque instance id + author kind), the last agent-free resilience verdict, and the last packaged promote candidate. A record this install pulled from a peer additionally carries an `inheritance` edge (`{ originInstanceId, foundationId, fingerprint, sourceInstanceId, inheritedAt }`) and is stored under a `peer:<originInstanceId>:<foundationId>` key disjoint from any locally-authored id, so it can never shadow or collide with a same-id local vernacular foundation. A write under that key is REFUSED, not applied, when the record already there was inherited from a different peer: the key is chosen by an origin the sender claims and hashes into its own fingerprint, so without that check a peer could replace this install's genuine copy of a third install's foundation (#7631). A record this install AUTHORED by building on an inherited one instead carries a `derivedFrom` edge (`{ originInstanceId, foundationId, fingerprint, derivedAt }`), which is the one provenance field that also rides the promote envelope — so a body copied from a peer is refused unless it says what it was derived from, and what it publishes is "derived from that install's X" rather than local authorship. The proposal → commit → promote/inherit lineage is not stored — `foundationLineage()` derives it on every read from fields the record already carries. `file-primary` and **intentionally machine-local — never federated**: the only thing authorized to leave the install is a packaged candidate envelope, and only for a foundation somebody explicitly promoted. `services/sharing/peerEidoverseFoundationSync.js` is the transport: it serves those envelopes (and only those — never a record, so never the `style` layer) at `GET /api/peer-sync/eidoverse-foundations` to registered outbound-enabled peers, and pulls a full-sync peer's offering into `recordEidoverseFoundationInheritance()`, which re-runs the whole accept-side gate and writes nothing on a refusal. Version-gated as `PORTOS_SCHEMA_VERSIONS.eidoverseFoundations`. No `data.reference/` seed and no migration — an absent file IS the empty ledger every install starts from, and the `inheritance`/`lineage`/`derivedFrom` additions are additive/nullable so an older file on disk reads back unchanged. Backed up with the rest of `data/eidoverse/`.- Eidoverse executable world controllers — `data/eidoverse/controllers.json` (#7456). The install-local set of controllers attached to this instance's private world: which shipped controller each install names (by REGISTRY ID — never a module path, so an install can never become an import), its bounded config, its cadence, whether it is armed, whether its effects are allowed to reach the world, and the durable state the controller advances one step per supervised tick. `file-primary` and **intentionally machine-local — never federated**: an install names this world's own entities and carries its author's intent, which the [machine-local privacy ADR](decisions/2026-08-08-privacy-records-machine-local.md) keeps off the federation layer; a controller is shared with a peer only as the BODY of a promoted foundation, which carries no install. No `data.reference/` seed — an absent file IS the empty set every install starts from. Migration 425 adds nullable completed outbound-delivery history to existing stores without inferring old acknowledgements. Backed up with the rest of `data/eidoverse/`.+ The shipped `riddle-ledger` stores its bounded current round, revision and explicit-action delivery verdict inside its existing controller `state`; no new store, on-disk layout, seed, migration, cross-record query or sync category is added. Filesystem backups already cover it. The round is executable behavior from the fixed registry, separate from any declarative affordance foundation.- Eidoverse observation visit marker — `data/eidoverse/observation.json` (#7457). What this install's mind had already seen the last time it toured its own world: the foundation ids, opaque peer ids, per-district status, and already-failing controller ids observed at that moment, plus when. It exists so "what is new since I last looked" survives a WAKE BOUNDARY — the nearest in-memory equivalents do not (the world chat cursor lives in a ring buffer a restart empties; the peer sync's `lastOfferingListHash` is per-peer change detection for a background sweep). `file-primary` and **intentionally machine-local — never federated**: a marker records this install's own mind's behavior, which the [machine-local privacy ADR](decisions/2026-08-08-privacy-records-machine-local.md) keeps off the federation layer, and it holds no body, style, or record content. No `data.reference/` seed and no migration — an absent file IS the never-observed state every install starts from, and that state is deliberately distinct from an empty one: the first observation reports `firstObservation: true` rather than declaring a settled world new. A marker stamped by a NEWER PortOS degrades to that same never-observed state rather than being diffed against fields this build does not understand. Backed up with the rest of `data/eidoverse/`.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + an ordered list of steps, each a REFERENCE to a scheduled task (`data/cos/task-schedule.json` or the app job store) plus its per-invocation overrides. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and a step's scheduled-task reference names task types and managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdindex 7e8ef79495..16769c6e3c 100644--- a/docs/features/eidoverse.md+++ b/docs/features/eidoverse.md@@ -1439,6 +1439,50 @@ entities every Nth tick, so lamps an author placed stay lit across host restartswhile the author is away — re-lighting an already-lit lamp is a no-op, which iswhat makes running it on a schedule safe.+**Explicit riddle rounds.** `riddle-ledger` implements a fixed offer → guess →+reveal interaction. It evaluates no foundation body: schema/affordance+foundations remain declarative, with their body, attribution, admission and+promotion contracts intact. Install a separate controller explicitly with an+unused id, `controllerId: "riddle-ledger"`, `config: {}`, `armed: true`, and+`deliverEffects: true` to speak into the private world (false for local-only+play). Nothing installs at boot or resets another controller. Supervised ticks+are silent, including after restart.++Read `GET /api/eidoverse/world/controllers/<id>` or+`eidoverse.inspect-controller`, then send `POST+/api/eidoverse/world/controllers/<id>/riddle` or the `eidoverse.riddle` tool:++```json+{"action":"offer","expectedRevision":0,"clue":"Which shape has three sides?","answer":"triangle"}+{"action":"guess","expectedRevision":1,"guess":"TRIANGLE"}+{"action":"reveal","expectedRevision":2}+```++The tool also takes `id`. Both mind grants (`manageEidoverse` and+`installEidoverseControllers`) are required. HTTP gameplay uses the operator+gate, including authenticated local-agent sessions; scoped peer credentials do+not grant gameplay. Each request must use the inspected `state.revision`, which+advances once per accepted action. A stale revision, a second guess, a repeated+reveal, an offer before revealing the current round, or a disarmed/wrong-kind+install refuses without changing state or sending chat. Revealing without a+guess is allowed; its `correct` is null. Otherwise matching ignores case after+input trimming, and correctness is withheld until reveal.++`outcome: "applied"` means the local transition persisted, even if world+delivery failed. Inspect `state.delivery` (also returned as `delivery`):+`disabled` means local-only, `pending` means completion is unknown,+`acknowledged` means the existing world `say` protocol acknowledged one message,+and `refused` carries the failure reason and acknowledged count. The answer is+only spoken on reveal; private operator inspection includes it throughout.+World acknowledgement does not prove visible browser rendering. Progress lands+before delivery; neither a restart nor a repeated request retries the message.+A crash can leave `pending` evidence, which must not be called successful.+If a management operation replaces/retires the install during delivery,+`outcome: "superseded"` reports the receipt without attaching it to the+replacement. Round state lives entirely in the existing machine-local controller+store, never in a promoted foundation or federation envelope. This surface is+API/tool gameplay; it adds no world-client command or guest interaction UI.+**The mind needs its own grant to install.** `eidoverse.install-controller` and`eidoverse.retire-controller` are gated on `manageEidoverse` **and** the separatedefault-off `installEidoverseControllers` grant, and are mind-scope only:diff --git a/server/lib/README.md b/server/lib/README.mdindex b03c38ad16..8eb5e73306 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -699,7 +699,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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, wired end-to-end in #7627): a closed catalog of `EIDOVERSE_CREATIVE_MATERIALS` and `EIDOVERSE_CREATIVE_MOTIFS` (cosmetics — style-layer only) plus `EIDOVERSE_CREATIVE_LAYOUTS` (named generative placement algorithms — `radial-ring`/`grid-plot`/`arc-row`/`grove-cluster`). `generateDistrictTemplatePlacement` is deterministic and seeded (mulberry32, no `Math.random`, no AI call) so the same `{layoutId, anchor, seed}` always reproduces the same geometry — `services/eidoverseFoundationLedger.js`'s `recordEidoverseFoundation()` replays it server-side to derive a `district-template`'s `body.placement`, never trusting a caller-supplied one. `buildDistrictTemplateAugmentOperations` turns a placement into ready-to-submit `eidoverse.augment` `spawn` operations (the `eidoverse.place-layout` tool); `buildDistrictTemplateFoundationDraft` shapes a placement plus a material/motif choice into an `eidoverseFoundationInputSchema`-ready `district-template` input, keeping the generative substance in `body` and the material/motif cosmetics in `style` (the `eidoverse.draft-foundation` tool). `describeCreativeCatalog()` is the prompt-safe catalog projection, including each material's `colorHex`. Pure: no I/O, no clock, no provider calls. |-| `eidoverseControllers.js` | Executable Eidoverse world controllers — the install schema and the sandboxed step boundary (#7456). `eidoverseControllerInstallSchema` / `eidoverseControllerRecordSchema` describe an install (a registry `controllerId`, a bounded `config`, a `tickIntervalMs`, and a `deliverEffects` flag that is FALSE by default, so installing arms bookkeeping and never a world verb). `runControllerStep` is the sandbox: it hands the controller JSON copies of its state and config, REFUSES a step that returns a Promise (an await is the shape every network/disk/AI-provider call takes, so the tick path is provider-free structurally rather than by convention), caps the state it may return, and validates its effects against a closed vocabulary — `note` (never leaves the ledger), `say`, and `augment`, which reuses `eidoverseValidation.js`'s own world-verb operation schema. `controllerTickDue` / `nextControllerTickAt` are the scheduling math, measured from now so a machine that slept wakes to ONE tick and not a replayed backlog. `summarizeControllerInstall` is the prompt-shaped projection that keeps a 16KB state blob out of a mind turn; it surfaces `derivedFrom`, the edge an install adopted from a peer's foundation carries (#7626). Pure: callers pass `now`. |+| `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). `eidoverseRiddleActionSchema` validates the fixed offer/guess/reveal action with an inspected `expectedRevision`. `runControllerStep` is the sandbox: it hands the controller JSON copies of its state and config, REFUSES a step that returns a Promise (an await is the shape every network/disk/AI-provider call takes, so the tick path is provider-free structurally rather than by convention), caps the state it may return, and validates its effects against a closed vocabulary — `note` (never leaves the ledger), `say`, and `augment`, which reuses `eidoverseValidation.js`'s own world-verb operation schema. `controllerTickDue` / `nextControllerTickAt` are the scheduling math, measured from now so a machine that slept wakes to ONE tick and not a replayed backlog. `summarizeControllerInstall` is the prompt-shaped projection that keeps a 16KB state blob out of a mind turn; it surfaces `derivedFrom`, the edge an install adopted from a peer's foundation carries (#7626). Pure: callers pass `now`. || `eidoverseFoundations.js` | Local-vs-baseline ownership for Eidoverse world foundations and the promote-candidate packaging gate (#7455). `EIDOVERSE_FOUNDATION_LAYERS` (`runtime` / `baseline` / `vernacular`, defaulting to `vernacular` so nothing is shared by omission) and `layerPromoteRefusal`; the record / input / candidate-envelope Zod schemas, where a foundation is `{ body, style }` BY CONSTRUCTION — packaging carries `body` and drops `style`, so an inheriting peer never receives its author's cosmetics, and `styleLeakFindings` REFUSES an unambiguously cosmetic key smuggled into `body` (spatial/asset keys stay allowed — they are a district template's substance). `assayEvidenceFromVerdict` folds an agent-free resilience verdict (#7460) into the evidence the gate reads, including the binding that it ran against the contribution this foundation names. `packageFoundationCandidate` and `verifyFoundationCandidate` are the one gate seen from the sending and receiving sides, over a content-addressed `fingerprint` hashed from the payload AS SENT; federation safety comes from `federationSafety.js`. `summarizeFoundation` is the prompt-shaped projection of a ledger record (layer, identity, assay outcome, whether a candidate exists) that keeps the local style layer and the packaged envelope out of a mind turn, and `detailFoundation` is its read-ONE counterpart, adding the `body` and `disclosure` the list deliberately omits (#7626). `eidoverseFoundationTargetSchema` + `foundationLedgerKey` are how a caller NAMES one record — `{ id, originInstanceId }`, where the origin addresses a local copy of a peer's foundation without making the internal `peer:<origin>:<id>` storage key user-typeable. `planFoundationAdoption` decides, per kind, what ADOPTING an inherited foundation means: a `controller` yields a disarmed install of the shipped controller its body names plus a `derived-from` edge, while `schema` / `affordance` / `district-template` are refused by name rather than silently succeeding. Pure: callers pass `now`. `derivedContributionId({ kind, id, body })` and `controllerDefinitionIdFromBody(body)` derive the assay binding label from the record itself, so neither an author nor a sending peer can name it (#7625); they live here rather than beside the sandbox that replays the body because the sandbox reaches this module through the creative toolkit. || `eidoverseFoundationSandbox.js` | Derives the agent-free resilience-assay sandbox for a foundation FROM ITS OWN BODY (#7625), closing the hole where the promote gate replayed whatever module the author named in a free-text `contributionId`. `foundationSandbox({ kind, id, body }, { findControllerDefinition })` returns the `{ id, createSandbox, invariants }` contribution `runResilienceAssay()` consumes, or a reader-facing refusal. One derivation per declared kind: `controller` replays the shipped definition named by `body.controller.definitionId` against THIS INSTALL'S `body.controller.config` (not upstream's `exampleConfig`); `district-template` requires `body.placement` to reproduce from its own layout/anchor/seed through `generateDistrictTemplatePlacement` and hands the body to the harness as the projection source; `schema`/`affordance` are replayed by the declarative interpreter over `EIDOVERSE_DECLARED_FIELD_TYPES`, which refuses an affordance recorded as prose rather than as `{ reads, writes }` over declared fields. The binding label both the packaging side and a receiving peer re-derive is computed by `derivedContributionId` in `eidoverseFoundations.js`, which declares the schema that carries it (and which this module would otherwise import in a cycle, via the creative toolkit). Executes only code PortOS ships; no caller-supplied path is ever resolved. Pure apart from the injected definition lookup. || `eidoversePort.js` | `EIDOVERSE_PORT` (8940) — the Eidoverse Worlds HTTP port as a dependency-free leaf (#8901), so `services/managedVisitorHost.js` can default to it without pulling in the heavy `services/eidoverse.js` graph (os/path/spawn/git/apps). `services/eidoverse.js` re-exports it rather than declaring its own copy. |diff --git a/server/lib/eidoverseControllers.js b/server/lib/eidoverseControllers.jsindex 7d5543315a..a7b538c42f 100644--- a/server/lib/eidoverseControllers.js+++ b/server/lib/eidoverseControllers.js@@ -163,6 +163,14 @@ export const eidoverseControllerConfigUpdateSchema = z.object({export const eidoverseControllerArmSchema = z.object({ id: controllerInstallIdSchema, armed: z.boolean() }).strict();+// Explicit shipped gameplay, never an interpreter for foundation bodies.+const riddleActionBase = { id: controllerInstallIdSchema, expectedRevision: z.number().int().nonnegative() };+export const eidoverseRiddleActionSchema = z.discriminatedUnion('action', [+ z.object({ ...riddleActionBase, action: z.literal('offer'), clue: z.string().trim().min(1).max(200), answer: z.string().trim().min(1).max(120) }).strict(),+ z.object({ ...riddleActionBase, action: z.literal('guess'), guess: z.string().trim().min(1).max(120) }).strict(),+ z.object({ ...riddleActionBase, action: z.literal('reveal') }).strict(),+]);+/** Who installed this, at the coarsest grain that is still useful — the same* three actors a foundation records, and deliberately no display name. */const installedBySchema = z.enum(['mind', 'cos', 'user']);diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex c2d0922c60..95655d0d9e 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -821,6 +821,9 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// Eidoverse: clone and install a caller-named repo, or repoint it.'POST /api/settings/features/eidoverse/install','PUT /api/settings/features/eidoverse/source',+ // Explicit local gameplay can speak in this machine's private world. Scoped+ // peer reachability does not grant it; operator/agent sessions retain access.+ 'POST /api/eidoverse/world/controllers/:id/riddle',// GitHub actions (#9013): mutating routes run `gh` with the user's GitHub// account and change external state. Syncing repos is read-only.diff --git a/server/routes/eidoverseRiddle.test.js b/server/routes/eidoverseRiddle.test.jsnew file mode 100644index 0000000000..e893d1638e--- /dev/null+++ b/server/routes/eidoverseRiddle.test.js@@ -0,0 +1,170 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { rmSync } from 'node:fs';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot('portos-riddle-'),+}));+vi.mock('../services/eventScheduler.js', () => ({ cancel: vi.fn(), getEvent: vi.fn(), schedule: vi.fn() }));+const world = vi.hoisted(() => ({ say: vi.fn() }));+vi.mock('../services/eidoverseWorld.js', () => ({ sayInEidoverseWorld: world.say }));++const { PATHS, atomicWrite, readJSONFile } = await import('../lib/fileUtils.js');+let authGate;+let hostControlRouteGate;+let runtime;+let routes;+const appFor = (remoteAddress = '127.0.0.1') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });+ next();+ });+ app.use(authGate);+ app.use(hostControlRouteGate);+ app.use(express.json());+ app.use('/api/eidoverse/world', routes);+ app.use(errorMiddleware);+ return app;+};+const actionPath = '/api/eidoverse/world/controllers/example-game/riddle';+const offer = { action: 'offer', expectedRevision: 0, clue: 'Which shape has three sides?', answer: 'triangle' };+const act = (body, app = appFor()) => request(app).post(actionPath).send(body);+const inspect = async () => (await request(appFor()).get('/api/eidoverse/world/controllers/example-game')).body;+const install = async (deliverEffects = true) => {+ const res = await request(appFor()).post('/api/eidoverse/world/controllers').send({+ id: 'example-game', controllerId: 'riddle-ledger', config: {}, armed: true, deliverEffects,+ });+ expect(res.body.outcome).toBe('installed');+};++beforeEach(async () => {+ vi.clearAllMocks();+ vi.resetModules();+ rmSync(join(PATHS.data, 'eidoverse'), { recursive: true, force: true });+ ({ authGate, hostControlRouteGate } = await import('../services/authGate.js'));+ runtime = await import('../services/eidoverseControllerRuntime.js');+ routes = (await import('./eidoverseWorldRoutes.js')).default;+ world.say.mockResolvedValue({ success: true });+});+afterAll(cleanupTempDataRoots);++describe('explicit Eidoverse riddle round', () => {+ it('plays a full round over HTTP, survives fresh module loading, and never announces from ticks', async () => {+ await install();+ const offered = await act(offer);+ expect(offered.body).toMatchObject({ outcome: 'applied', delivery: { status: 'acknowledged', delivered: 1 } });+ expect(offered.body.install.state).toMatchObject({ revision: 1, round: 1, clue: offer.clue, guess: '', revealed: false, correct: null });+ expect(world.say).toHaveBeenLastCalledWith(`Riddle 1: ${offer.clue}`, expect.any(Object));+ expect(world.say.mock.calls[0][0]).not.toContain('triangle');++ // A fresh runtime has no in-memory round to lean on; keep the temp disk.+ vi.resetModules();+ runtime = await import('../services/eidoverseControllerRuntime.js');+ routes = (await import('./eidoverseWorldRoutes.js')).default;+ expect((await inspect()).state.revision).toBe(1);+ const guessed = await act({ action: 'guess', expectedRevision: 1, guess: 'TRIANGLE' });+ expect(guessed.body.install.state).toMatchObject({ revision: 2, guess: 'TRIANGLE', correct: null });+ const revealed = await act({ action: 'reveal', expectedRevision: 2 });+ expect(revealed.body.install.state).toMatchObject({ revision: 3, revealed: true, correct: true });+ expect(world.say).toHaveBeenLastCalledWith('Riddle 1 answer: triangle (correct)', expect.any(Object));+ await runtime.tickEidoverseControllers({ now: '2099-01-01T00:00:00.000Z' });+ expect(world.say).toHaveBeenCalledTimes(3);+ expect((await inspect()).state).toEqual(revealed.body.install.state);+ expect((await act({ ...offer, expectedRevision: 3 })).body.install.state).toMatchObject({ round: 2, guess: '', revealed: false, correct: null });+ });++ it('refuses invalid, repeated, stale and overlapping transitions without extra delivery', async () => {+ expect((await act(offer)).status).toBe(404);+ await install();+ expect((await act({ action: 'reveal', expectedRevision: 0 })).body.outcome).toBe('refused');+ expect((await act({ action: 'guess', expectedRevision: 0, guess: 'circle' })).body.outcome).toBe('refused');+ expect((await act({ ...offer, answer: '' })).status).toBe(400);+ expect((await act({ ...offer, clue: 'x'.repeat(201) })).status).toBe(400);+ expect((await act({ ...offer, action: 'interpret' })).status).toBe(400);+ await act(offer);+ expect((await act(offer)).body.outcome).toBe('refused');+ expect((await act({ ...offer, expectedRevision: 1 })).body.outcome).toBe('refused');+ const pair = await Promise.all([+ act({ action: 'guess', expectedRevision: 1, guess: 'circle' }),+ act({ action: 'guess', expectedRevision: 1, guess: 'square' }),+ ]);+ expect(pair.map((res) => res.body.outcome).sort()).toEqual(['applied', 'refused']);+ expect((await act({ action: 'guess', expectedRevision: 2, guess: 'triangle' })).body.outcome).toBe('refused');+ const revealed = await act({ action: 'reveal', expectedRevision: 2 });+ expect(revealed.body.install.state.correct).toBe(false);+ expect((await act({ action: 'reveal', expectedRevision: 3 })).body.outcome).toBe('refused');+ expect((await act({ action: 'guess', expectedRevision: 3, guess: 'triangle' })).body.outcome).toBe('refused');+ expect(world.say).toHaveBeenCalledTimes(3);+ });++ it('persists refused delivery independently of local progress, without automatic retry', async () => {+ await install();+ world.say.mockRejectedValue(new Error('Synthetic world refusal'));+ const offered = await act(offer);+ expect(offered.body).toMatchObject({ outcome: 'applied', delivery: { status: 'refused', delivered: 0, reason: 'Synthetic world refusal' } });+ expect((await inspect()).state.delivery).toEqual(offered.body.delivery);+ vi.resetModules();+ runtime = await import('../services/eidoverseControllerRuntime.js');+ routes = (await import('./eidoverseWorldRoutes.js')).default;+ expect((await inspect()).state.delivery).toEqual(offered.body.delivery);+ await runtime.tickEidoverseControllers({ now: '2099-01-01T00:00:00.000Z' });+ expect((await act(offer)).body.outcome).toBe('refused');+ expect(world.say).toHaveBeenCalledTimes(1);+ });++ it('supports local-only play, disarm refusal and rejects actions on the existing beacon', async () => {+ await install(false);+ expect((await act(offer)).body.delivery.status).toBe('disabled');+ expect((await act({ action: 'reveal', expectedRevision: 1 })).body.install.state.correct).toBeNull();+ await runtime.setEidoverseControllerArmed('example-game', false);+ expect((await act({ ...offer, expectedRevision: 2 })).body.outcome).toBe('refused');+ await runtime.installEidoverseController({ id: 'example-beacon', controllerId: 'ambient-beacon', config: {} });+ const before = await runtime.getEidoverseControllerInstall('example-beacon');+ const res = await request(appFor()).post('/api/eidoverse/world/controllers/example-beacon/riddle').send(offer);+ expect(res.body.outcome).toBe('refused');+ expect(await runtime.getEidoverseControllerInstall('example-beacon')).toEqual(before);+ expect(world.say).not.toHaveBeenCalled();+ });++ it('fences incompatible stores/state and does not stamp a receipt over a re-install', async () => {+ await install();+ const file = join(PATHS.data, 'eidoverse', 'controllers.json');+ const stored = await readJSONFile(file);+ await atomicWrite(file, { ...stored, schemaVersion: 999 });+ expect((await act(offer)).body.outcome).toBe('refused');+ expect(await readJSONFile(file)).toEqual({ ...stored, schemaVersion: 999 });+ await atomicWrite(file, { ...stored, installs: { 'example-game': { ...stored.installs['example-game'], state: { revision: 0 } } } });+ expect((await act(offer)).body.outcome).toBe('refused');+ await atomicWrite(file, stored);+ world.say.mockImplementationOnce(async () => {+ expect((await runtime.getEidoverseControllerInstall('example-game')).state.delivery.status).toBe('pending');+ await runtime.installEidoverseController({ id: 'example-game', controllerId: 'riddle-ledger', config: {}, deliverEffects: true });+ return { success: true };+ });+ const res = await act(offer);+ expect(res.body).toMatchObject({ outcome: 'superseded', install: null, delivery: { status: 'acknowledged' } });+ expect((await inspect()).state).toMatchObject({ revision: 0, round: 0, delivery: null });+ });++ it('refuses anonymous remote gameplay before state/delivery and retains authenticated agent access', async () => {+ await install();+ const denied = await act(offer, appFor('192.0.2.10'));+ expect(denied.status).toBe(403);+ expect(denied.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ expect((await inspect()).state.revision).toBe(0);+ expect(world.say).not.toHaveBeenCalled();+ // Same server-minted session used by PORTOS_API_TOKEN, with synthetic stores.+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'synthetic-riddle-password' });+ const { token } = await auth.createSession({ label: 'agent' });+ expect((await act(offer)).status).toBe(401);+ const allowed = await request(appFor()).post(actionPath).set('Authorization', `Bearer ${token}`).send(offer);+ expect(allowed.body).toMatchObject({ outcome: 'applied', delivery: { status: 'acknowledged' } });+ await auth.clearPassword({ currentPassword: 'synthetic-riddle-password' });+ });+});diff --git a/server/routes/eidoverseWorldRoutes.js b/server/routes/eidoverseWorldRoutes.jsindex f20de63305..84fb2c9aaf 100644--- a/server/routes/eidoverseWorldRoutes.js+++ b/server/routes/eidoverseWorldRoutes.js@@ -24,6 +24,7 @@ import {eidoverseControllerConfigUpdateSchema,eidoverseControllerIdParamSchema,eidoverseControllerInstallSchema,+ eidoverseRiddleActionSchema,} from '../lib/eidoverseControllers.js';import {adoptEidoverseFoundation,@@ -39,6 +40,7 @@ import { describeControllerDefinitions } from '../services/eidoverseControllerReimport {getEidoverseControllerInstall,installEidoverseController,+ interactEidoverseRiddleLedger,listEidoverseControllers,retireEidoverseController,setEidoverseControllerArmed,@@ -260,6 +262,14 @@ router.get('/controllers/:id', asyncHandler(async (req, res) => {res.json(summarizeControllerInstall(install, { includeState: true }));}));+// An explicit local round, independent of arbitrary declarative foundations.+router.post('/controllers/:id/riddle', asyncHandler(async (req, res) => {+ const input = validateRequest(eidoverseRiddleActionSchema, { ...(req.body || {}), id: req.params.id });+ const result = await interactEidoverseRiddleLedger(input);+ if (result.outcome === 'unknown-install') throw new ServerError('Controller install not found', { status: 404 });+ res.json({ ...result, install: result.install ? summarizeControllerInstall(result.install, { includeState: true }) : null });+}));+// PATCH /api/eidoverse/world/controllers/:id/config — change an installed// controller's config while its accumulated state survives (#7629). A// re-install of the same id would rebuild state from scratch instead; this isdiff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 5baaea887b..98126f094b 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -42,7 +42,7 @@ import {eidoverseChatReadSchema, eidoverseTravelVisitSchema, eidoverseVisitChatSchema, eidoverseVisitLeaveSchema,} from '../lib/validation.js';import { detailFoundation, eidoverseFoundationIdParamSchema, eidoverseFoundationInputSchema, eidoverseFoundationTargetSchema, summarizeFoundation } from '../lib/eidoverseFoundations.js';-import { eidoverseControllerArmSchema, eidoverseControllerIdParamSchema, eidoverseControllerInstallSchema, summarizeControllerInstall } from '../lib/eidoverseControllers.js';+import { eidoverseControllerArmSchema, eidoverseControllerIdParamSchema, eidoverseControllerInstallSchema, eidoverseRiddleActionSchema, summarizeControllerInstall } from '../lib/eidoverseControllers.js';import {buildDistrictTemplateAugmentOperations,buildDistrictTemplateFoundationDraft,@@ -551,6 +551,7 @@ const eidoverseControllerTools = [['install-controller', 'Attach a bounded controller to the private world so it keeps ticking between your wakes. `controllerId` names one of the ids eidoverse.controllers returns — a controller is never a path or code you supply. Every tick is synchronous and provider-free, and `deliverEffects` (default false) decides whether its effects reach the world at all. This is a REQUEST: the result is `outcome: "installed"` only when it landed, and any other outcome means nothing is running — read `reasons`. The first tick is one interval away, never immediate. Re-installing an existing id REBUILDS its state from the new config — inspect it first with eidoverse.inspect-controller if you want to keep what it has accumulated.', eidoverseControllerInstallSchema, ['manageEidoverse', 'installEidoverseControllers'], 'write'],['arm-controller', 'Pause or resume one installed controller without losing the state it has accumulated. Use this to resume a controller the supervisor disarmed after repeated failures, once you have fixed what it was failing on — re-installing would work too but starts its state over.', eidoverseControllerArmSchema, ['manageEidoverse', 'installEidoverseControllers'], 'write'],['retire-controller', 'Stop and remove one installed controller by its install id. Retiring deletes the install and its accumulated state; re-installing starts it fresh.', eidoverseControllerIdParamSchema, ['manageEidoverse', 'installEidoverseControllers'], 'write'],+ ['riddle', 'Play one explicit riddle-ledger round on an already installed, armed controller. Inspect state.revision, then pass expectedRevision and action: offer (clue, answer), guess (guess), or reveal. One guess per round; reveal before the next offer. No AI calls or recurring announcements. outcome applied means local progress persisted; delivery reports disabled, pending/unknown, acknowledged, or refused separately. Refused delivery does not undo progress and is never retried automatically. The answer stays out of world chat until reveal, but operator inspection includes it. No arbitrary foundation is executed or modified.', eidoverseRiddleActionSchema, ['manageEidoverse', 'installEidoverseControllers'], 'write'],].map(([operation, description, schema, requiredCapabilities, sideEffect]) => ({type: 'portos_tool', name: `eidoverse.${operation}`, version: COS_TOOL_SCHEMA_VERSION,providerName: providerToolName(`eidoverse.${operation}`), aliases: [providerToolName(`eidoverse.${operation}`)],@@ -1204,6 +1205,10 @@ const executeAdapter = async (tool, args, context, authority) => {// controller understood it. The list projection stays state-free.return { ...result, install: result.install ? summarizeControllerInstall(result.install, { includeState: true }) : null };}+ if (tool.adapter.operation === 'riddle') {+ const result = await runtime.interactEidoverseRiddleLedger(args, { signal: context.signal });+ return { ...result, install: result.install ? summarizeControllerInstall(result.install, { includeState: true }) : null };+ }const result = await runtime.retireEidoverseController(args.id);return { ...result, install: result.install ? summarizeControllerInstall(result.install) : null };}diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex 6f1cbe4243..64889ba72a 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({recordFoundation: vi.fn(),ensureInstanceId: vi.fn(),delegateSandbox: vi.fn(),+ interactRiddle: vi.fn(),}));vi.mock('./persistentMindManagedApps.js', () => ({ readPersistentMindManagedApps: async () => [{ id: 'example', granted: true, forge: 'github' }] }));@@ -80,6 +81,10 @@ vi.mock('./eidoverseWorld.js', () => ({augmentEidoverseWorld: (...args) => mocks.worldAugment(...args),sayInEidoverseWorld: (...args) => mocks.worldSay(...args),}));+vi.mock('./eidoverseControllerRuntime.js', async () => ({+ summarizeControllerInstall: (await import('../lib/eidoverseControllers.js')).summarizeControllerInstall,+ interactEidoverseRiddleLedger: (...args) => mocks.interactRiddle(...args),+}));vi.mock('./eidoverseFoundationLedger.js', () => ({adoptEidoverseFoundation: (...args) => mocks.adoptFoundation(...args),getEidoverseFoundationByRef: (...args) => mocks.getFoundationByRef(...args),@@ -129,6 +134,19 @@ beforeEach(() => {});describe('cosToolRegistry', () => {+ it('gates explicit riddle actions on both controller grants and returns the runtime delivery verdict', async () => {+ const call = { requestId: 'example-riddle', name: 'eidoverse.riddle', arguments: {+ id: 'example-game', action: 'reveal', expectedRevision: 2,+ } };+ await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { manageEidoverse: true } } }))+ .rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });+ expect(mocks.interactRiddle).not.toHaveBeenCalled();+ mocks.interactRiddle.mockResolvedValue({ outcome: 'applied', install: { id: 'example-game', state: { revision: 3, revealed: true } },+ delivery: { status: 'refused', delivered: 0, reason: 'Synthetic refusal' }, reasons: [] });+ const result = await executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { manageEidoverse: true, installEidoverseControllers: true } } });+ expect(result.result).toMatchObject({ outcome: 'applied', install: { state: { revision: 3, revealed: true } }, delivery: { status: 'refused' } });+ expect(mocks.interactRiddle).toHaveBeenCalledWith(call.arguments, expect.any(Object));+ });it('delivers bounded stopped-task reasons under the observation grant without enabling reports', async () => {const tasks = Array.from({ length: 2 }, (_, index) => ({ id: `invented-task-${index}`,status: 'blocked', metadata: { blockedCategory: 'user-terminated' } }));@@ -418,6 +436,7 @@ describe('cosToolRegistry', () => {'eidoverse.install-controller','eidoverse.arm-controller','eidoverse.retire-controller',+ 'eidoverse.riddle','eidoverse.status','eidoverse.inspect-scene','eidoverse.project',diff --git a/server/services/eidoverseControllerDefinitions/riddleLedger.controller.js b/server/services/eidoverseControllerDefinitions/riddleLedger.controller.jsnew file mode 100644index 0000000000..96e5d23007--- /dev/null+++ b/server/services/eidoverseControllerDefinitions/riddleLedger.controller.js@@ -0,0 +1,61 @@+/**+ * One explicit, provider-free round. The foundation ledger remains declarative:+ * no body is evaluated or rewritten here. Only an intentional action speaks;+ * supervised ticks preserve the round without announcements or retries.+ */+import { z } from 'zod';++const roundSchema = z.object({+ revision: z.number().int().nonnegative(),+ round: z.number().int().nonnegative(),+ clue: z.string().max(200),+ answer: z.string().max(120),+ guess: z.string().max(120),+ revealed: z.boolean(),+ correct: z.boolean().nullable(),+ operationId: z.string().uuid().nullable(),+ delivery: z.object({+ status: z.enum(['pending', 'disabled', 'acknowledged', 'refused']),+ delivered: z.number().int().nonnegative(),+ reason: z.string().nullable(),+ }).strict().nullable(),+}).strict();++export default function createRiddleLedgerController() {+ return {+ id: 'riddle-ledger',+ title: 'Riddle ledger',+ summary: 'Explicit offer, one guess, and reveal via eidoverse.riddle or POST controllers/:id/riddle. Inspect state.revision before each action. Ticks are silent; no foundation body is interpreted.',+ exampleConfig: {},+ configSchema: z.object({}).strict(),+ createState: () => ({ revision: 0, round: 0, clue: '', answer: '', guess: '', revealed: false, correct: null, operationId: null, delivery: null }),+ step: (state) => ({ state }),+ interact(state, input) {+ const parsed = roundSchema.safeParse(state);+ if (!parsed.success) return { refused: 'Stored riddle state is incompatible; no action was applied.' };+ if (input.expectedRevision !== state.revision) return { refused: 'Stale round revision; inspect the controller before acting again.' };+ if (input.action === 'offer') {+ if (state.round > 0 && !state.revealed) return { refused: 'Reveal the current round before offering another riddle.' };+ return {+ state: { ...state, revision: state.revision + 1, round: state.round + 1, clue: input.clue, answer: input.answer, guess: '', revealed: false, correct: null },+ effects: [{ kind: 'say', text: `Riddle ${state.round + 1}: ${input.clue}` }],+ };+ }+ if (state.round === 0) return { refused: 'Offer a riddle first.' };+ if (state.revealed) return { refused: 'This round is already revealed.' };+ if (input.action === 'guess') {+ if (state.guess) return { refused: 'This round already has a guess; reveal the answer next.' };+ return {+ state: { ...state, revision: state.revision + 1, guess: input.guess },+ effects: [{ kind: 'say', text: `Riddle ${state.round} guess: ${input.guess}` }],+ };+ }+ const correct = state.guess ? state.guess.toLowerCase() === state.answer.toLowerCase() : null;+ return {+ state: { ...state, revision: state.revision + 1, revealed: true, correct },+ effects: [{ kind: 'say', text: `Riddle ${state.round} answer: ${state.answer}${correct === null ? ' (no guess)' : correct ? ' (correct)' : ' (incorrect)'}` }],+ };+ },+ invariants: [function roundRemainsSerializable(state) { return roundSchema.safeParse(state).success; }],+ };+}diff --git a/server/services/eidoverseControllerRuntime.js b/server/services/eidoverseControllerRuntime.jsindex f2c18934f7..2c0fd555ea 100644--- a/server/services/eidoverseControllerRuntime.js+++ b/server/services/eidoverseControllerRuntime.js@@ -40,12 +40,14 @@*/import { join } from 'node:path';+import { randomUUID } from 'node:crypto';import { PATHS, atomicWrite, readJSONFile } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import {EIDOVERSE_CONTROLLER_LIMITS,controllerTickDue,eidoverseControllerInstallSchema,+ eidoverseRiddleActionSchema,nextControllerTickAt,runControllerStep,summarizeControllerEffect,@@ -80,6 +82,9 @@ const LOG_PREFIX = '🌀 Eidoverse controllers';const storeFile = () => join(PATHS.data, 'eidoverse', 'controllers.json');const withStoreLock = createMutex();+// Keep explicit round messages ordered without holding the shared store lock+// across world I/O. Ordinary controller management remains available.+const withRiddleActionLock = createMutex();/*** Serializes whole tick passes. A pass reads every install, steps the due@@ -337,6 +342,72 @@ const afterGateMove = (reason) => async (result) => {return result;};+/** Apply one explicit action to a shipped riddle-ledger install. Local progress+ * is persisted BEFORE delivery, so a restart never repeats a guess or a say.+ * `delivery` is a separate verdict; pending after a crash is unknown, not an+ * acknowledgement. Neither this path nor quiet ticks retry outbound work.+ */+export async function interactEidoverseRiddleLedger(input, {+ now = new Date().toISOString(),+ signal,+ deliver = deliverControllerEffects,+} = {}) {+ const parsed = eidoverseRiddleActionSchema.safeParse(input);+ if (!parsed.success) return refused(parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`));+ const action = parsed.data;+ return withRiddleActionLock(async () => {+ signal?.throwIfAborted();+ const applied = await withStoreLock(async () => {+ const { schemaVersion, installs } = await readInstalls();+ if (schemaVersion > STORE_SCHEMA_VERSION) return refused(['Controller store is from a newer build; upgrade before interacting.']);+ const record = installs[action.id];+ if (!record) return { outcome: 'unknown-install', install: null, reasons: ['Install a riddle-ledger controller explicitly first.'] };+ if (record.controllerId !== 'riddle-ledger') return refused(['This action only supports the shipped riddle-ledger controller.']);+ if (!record.armed) return refused(['This controller is disarmed; arm it explicitly before interacting.']);+ const definition = await findControllerDefinitionById('riddle-ledger');+ if (!definition) return refused(['This build does not ship the riddle-ledger controller.']);+ const config = definition.configSchema.safeParse(record.config);+ if (!config.success) return refused(['Stored riddle config is incompatible; no action was applied.']);+ const proposed = definition.interact(record.state, action);+ if (proposed.refused) return refused([proposed.refused]);+ const operationId = randomUUID();+ const delivery = { status: record.deliverEffects ? 'pending' : 'disabled', delivered: 0, reason: null };+ const outcome = runControllerStep({+ definition: { ...definition, step: () => ({ ...proposed, state: { ...proposed.state, operationId, delivery } }) },+ state: record.state, config: config.data, tick: record.tick,+ });+ if (!outcome.ok) return refused([outcome.reason]);+ const install = { ...record, state: outcome.state, updatedAt: now };+ installs[action.id] = install;+ await writeInstalls(installs, schemaVersion);+ return { outcome: 'applied', install, reasons: [], effects: outcome.effects };+ });+ if (applied.outcome !== 'applied') return applied;+ const { effects, ...result } = applied;+ if (!result.install.deliverEffects) return { ...result, delivery: result.install.state.delivery };+ const attempt = await deliver(effects, { signal }).catch((error) => ({ delivered: 0, error: String(error?.message ?? error) || 'World delivery failed.' }));+ const acknowledged = attempt.delivered === 1 && !attempt.error;+ const delivery = {+ status: acknowledged ? 'acknowledged' : 'refused',+ delivered: attempt.delivered,+ reason: acknowledged ? null : String(attempt.error || 'No world acknowledgement was recorded.').slice(0, EIDOVERSE_CONTROLLER_LIMITS.reasonMax),+ };+ return withStoreLock(async () => {+ const { schemaVersion, installs } = await readInstalls();+ const current = installs[action.id];+ // A management operation may replace/retire the install during delivery.+ // A fresh server-generated id prevents stamping its receipt over a reset.+ if (current?.state?.operationId !== result.install.state.operationId) {+ return { outcome: 'superseded', install: null, delivery, reasons: ['The install changed during delivery; this receipt was not attached to the replacement.'] };+ }+ const install = { ...current, state: { ...current.state, delivery } };+ installs[action.id] = install;+ await writeInstalls(installs, schemaVersion);+ return { ...result, install, delivery };+ });+ });+}+// ---------------------------------------------------------------------------// The tick pass// ---------------------------------------------------------------------------