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
address review (codex): API-safe tool names + tighten wrapped-service contracts
[._.]/ Adam Eivycfdd30042757
diff --git a/server/services/creative/toolRegistry.js b/server/services/creative/toolRegistry.jsindex 4642b02876..75091cba28 100644--- a/server/services/creative/toolRegistry.js+++ b/server/services/creative/toolRegistry.js@@ -50,6 +50,12 @@ export const CREATIVE_TOOLS = [const COST_SET = new Set(COST_CLASSES);+// OpenAI/compatible function-calling APIs only accept names matching this+// pattern — a dotted `domain.action` name would make the model request 400+// before the orchestrator could dispatch. Enforce it at load so a new tool+// can't reintroduce an unsafe name.+const SAFE_TOOL_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;+/*** Fail-fast integrity check (navManifest / voice-tools precedent): every tool* must carry a unique name, a Zod schema, an execute fn, and a valid cost class;@@ -66,6 +72,9 @@ export function assertCreativeToolIntegrity(tools, resolveMeta = getToolMetadataif (!t || typeof t.name !== 'string' || !t.name) {throw new Error('creative tools: a tool is missing its name');}+ if (!SAFE_TOOL_NAME_RE.test(t.name)) {+ throw new Error(`creative tools: "${t.name}" is not a function-calling-safe name (letters/digits/_/-, ≤64 chars)`);+ }if (seen.has(t.name)) {throw new Error(`creative tools: duplicate tool name "${t.name}"`);}diff --git a/server/services/creative/toolRegistry.test.js b/server/services/creative/toolRegistry.test.jsindex f9c04a5d31..0bf47d6d8a 100644--- a/server/services/creative/toolRegistry.test.js+++ b/server/services/creative/toolRegistry.test.js@@ -71,7 +71,7 @@ describe('registry shape', () => {it('registers the six-domain tool inventory with unique names', () => {const names = getAllCreativeToolNames();expect(new Set(names).size).toBe(names.length);- for (const prefix of ['universe.', 'storyBuilder.', 'writersRoom.', 'pipeline.', 'media.', 'catalog.']) {+ for (const prefix of ['universe_', 'storyBuilder_', 'writersRoom_', 'pipeline_', 'media_', 'catalog_']) {expect(names.some((n) => n.startsWith(prefix))).toBe(true);}});@@ -84,6 +84,12 @@ describe('registry shape', () => {}});+ it('every registered tool name is function-calling-safe (no dots)', () => {+ for (const name of getAllCreativeToolNames()) {+ expect(name).toMatch(/^[a-zA-Z0-9_-]{1,64}$/);+ }+ });+it('getToolSpecs returns OpenAI function specs suitable for a prompt', () => {const specs = getToolSpecs();expect(specs.length).toBe(CREATIVE_TOOLS.length);@@ -95,14 +101,14 @@ describe('registry shape', () => {});it('hydrates catalog.searchIngredients description + parameters from the voice tool', () => {- const meta = getCreativeToolMetadata('catalog.searchIngredients');+ const meta = getCreativeToolMetadata('catalog_searchIngredients');expect(meta.description).toBe('VOICE catalog search description');expect(meta.parameters.required).toEqual(['query']);});});describe('assertCreativeToolIntegrity', () => {- const ok = { name: 'a.x', costClass: 'free', schema: z.object({}), execute: () => {} };+ const ok = { name: 'a_x', costClass: 'free', schema: z.object({}), execute: () => {} };it('accepts a valid tool set', () => {expect(() => assertCreativeToolIntegrity([ok])).not.toThrow();@@ -110,6 +116,9 @@ describe('assertCreativeToolIntegrity', () => {it('throws on a duplicate name', () => {expect(() => assertCreativeToolIntegrity([ok, { ...ok }])).toThrow(/duplicate tool name/);});+ it('throws on a function-calling-unsafe (dotted) name', () => {+ expect(() => assertCreativeToolIntegrity([{ ...ok, name: 'a.x' }])).toThrow(/function-calling-safe/);+ });it('throws on a missing execute', () => {expect(() => assertCreativeToolIntegrity([{ ...ok, execute: undefined }])).toThrow(/missing execute/);});@@ -135,7 +144,7 @@ describe('filterDestructive', () => {describe('dispatch gating per mode', () => {it('off → rejects without executing or charging', async () => {setMode('off');- const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ const out = await dispatchCreativeTool('pipeline_createSeries', { name: 'S' });expect(out).toMatchObject({ ok: false, rejected: true, reason: 'autonomy-off', mode: 'off' });expect(createSeries).not.toHaveBeenCalled();expect(recordDomainUsage).not.toHaveBeenCalled();@@ -143,8 +152,8 @@ describe('dispatch gating per mode', () => {it('dry-run → returns a plan frame with no side effects', async () => {setMode('dry-run');- const out = await dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' });- expect(out).toMatchObject({ ok: true, planned: true, mode: 'dry-run', tool: 'pipeline.generateStage', costClass: 'llm' });+ const out = await dispatchCreativeTool('pipeline_generateStage', { issueId: 'i1', stageId: 'st1' });+ expect(out).toMatchObject({ ok: true, planned: true, mode: 'dry-run', tool: 'pipeline_generateStage', costClass: 'llm' });expect(out.args).toMatchObject({ issueId: 'i1', stageId: 'st1' });expect(generateStage).not.toHaveBeenCalled();expect(recordDomainUsage).not.toHaveBeenCalled();@@ -152,15 +161,15 @@ describe('dispatch gating per mode', () => {it('execute → runs the wrapped entry point and returns its result', async () => {setMode('execute');- const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });- expect(out).toMatchObject({ ok: true, mode: 'execute', tool: 'pipeline.createSeries' });+ const out = await dispatchCreativeTool('pipeline_createSeries', { name: 'S' });+ expect(out).toMatchObject({ ok: true, mode: 'execute', tool: 'pipeline_createSeries' });expect(out.result).toEqual({ id: 'ser1' });expect(createSeries).toHaveBeenCalledWith({ name: 'S' });});it('creative mode mirrors cos but an explicit creative override wins', async () => {loadState.mockResolvedValue({ config: { domainAutonomy: { cos: 'off', creative: 'execute' } } });- const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ const out = await dispatchCreativeTool('pipeline_createSeries', { name: 'S' });expect(out.ok).toBe(true);expect(createSeries).toHaveBeenCalled();});@@ -171,7 +180,7 @@ describe('dispatch gating per mode', () => {it('throws on invalid args (Zod) before any gating', async () => {setMode('execute');- await expect(dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1' })).rejects.toBeInstanceOf(z.ZodError);+ await expect(dispatchCreativeTool('pipeline_generateStage', { issueId: 'i1' })).rejects.toBeInstanceOf(z.ZodError);expect(generateStage).not.toHaveBeenCalled();});});@@ -179,27 +188,27 @@ describe('dispatch gating per mode', () => {describe('budget charging', () => {it('charges one action for an llm tool on execute', async () => {setMode('execute');- await dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' });+ await dispatchCreativeTool('pipeline_generateStage', { issueId: 'i1', stageId: 'st1' });expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });expect(generateStage).toHaveBeenCalled();});it('charges for a render (media) tool on execute', async () => {setMode('execute');- await dispatchCreativeTool('media.enqueueImageJob', { params: { prompt: 'p' } }, { projectId: 'p1' });+ await dispatchCreativeTool('media_enqueueImageJob', { params: { prompt: 'p' } }, { projectId: 'p1' });expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });expect(enqueueJob).toHaveBeenCalledWith({ kind: 'image', params: { prompt: 'p' }, owner: 'creative-director:p1' });});it('does not charge a free tool', async () => {setMode('execute');- await dispatchCreativeTool('pipeline.createSeries', { name: 'S' });+ await dispatchCreativeTool('pipeline_createSeries', { name: 'S' });expect(recordDomainUsage).not.toHaveBeenCalled();});it('catalog.searchIngredients delegates to the voice catalog_lookup tool (honors the hydrated contract)', async () => {setMode('execute');- const out = await dispatchCreativeTool('catalog.searchIngredients', { query: 'noir' }, { some: 'ctx' });+ const out = await dispatchCreativeTool('catalog_searchIngredients', { query: 'noir' }, { some: 'ctx' });expect(dispatchVoiceTool).toHaveBeenCalledWith('catalog_lookup', { query: 'noir' }, { some: 'ctx' });expect(out.ok).toBe(true);expect(recordDomainUsage).not.toHaveBeenCalled(); // free tool@@ -208,7 +217,7 @@ describe('budget charging', () => {it('rejects when the budget is exhausted, without executing', async () => {setMode('execute');getDomainBudgetStatus.mockResolvedValue({ withinBudget: false, exceeded: 'actions' });- const out = await dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' });+ const out = await dispatchCreativeTool('pipeline_generateStage', { issueId: 'i1', stageId: 'st1' });expect(out).toMatchObject({ ok: false, rejected: true, reason: 'budget', exceeded: 'actions' });expect(generateStage).not.toHaveBeenCalled();expect(recordDomainUsage).not.toHaveBeenCalled();@@ -219,10 +228,10 @@ describe('run ledger append', () => {it('appends an executed entry with tool, digest, outcome and timing', async () => {setMode('execute');const appendLedger = vi.fn(async () => {});- await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { projectId: 'p1', appendLedger });+ await dispatchCreativeTool('pipeline_createSeries', { name: 'S' }, { projectId: 'p1', appendLedger });expect(appendLedger).toHaveBeenCalledTimes(1);const entry = appendLedger.mock.calls[0][0];- expect(entry).toMatchObject({ tool: 'pipeline.createSeries', outcome: 'executed' });+ expect(entry).toMatchObject({ tool: 'pipeline_createSeries', outcome: 'executed' });expect(typeof entry.argsDigest).toBe('string');expect(typeof entry.timingMs).toBe('number');});@@ -230,14 +239,14 @@ describe('run ledger append', () => {it('records outcome=rejected when off', async () => {setMode('off');const appendLedger = vi.fn(async () => {});- await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { appendLedger });+ await dispatchCreativeTool('pipeline_createSeries', { name: 'S' }, { appendLedger });expect(appendLedger.mock.calls[0][0].outcome).toBe('rejected');});it('records outcome=planned in dry-run', async () => {setMode('dry-run');const appendLedger = vi.fn(async () => {});- await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { appendLedger });+ await dispatchCreativeTool('pipeline_createSeries', { name: 'S' }, { appendLedger });expect(appendLedger.mock.calls[0][0].outcome).toBe('planned');});@@ -246,7 +255,7 @@ describe('run ledger append', () => {generateStage.mockRejectedValueOnce(new Error('boom'));const appendLedger = vi.fn(async () => {});await expect(- dispatchCreativeTool('pipeline.generateStage', { issueId: 'i1', stageId: 'st1' }, { appendLedger }),+ dispatchCreativeTool('pipeline_generateStage', { issueId: 'i1', stageId: 'st1' }, { appendLedger }),).rejects.toThrow('boom');expect(appendLedger.mock.calls[0][0]).toMatchObject({ outcome: 'error', error: 'boom' });});@@ -254,7 +263,7 @@ describe('run ledger append', () => {it('a ledger sink failure never breaks the dispatch', async () => {setMode('execute');const appendLedger = vi.fn(async () => { throw new Error('disk full'); });- const out = await dispatchCreativeTool('pipeline.createSeries', { name: 'S' }, { projectId: 'p1', appendLedger });+ const out = await dispatchCreativeTool('pipeline_createSeries', { name: 'S' }, { projectId: 'p1', appendLedger });expect(out.ok).toBe(true);});});diff --git a/server/services/creative/tools/catalog.js b/server/services/creative/tools/catalog.jsindex 63ad5f1f5f..f4d7166da7 100644--- a/server/services/creative/tools/catalog.js+++ b/server/services/creative/tools/catalog.js@@ -12,7 +12,7 @@ import { COST_FREE, COST_LLM } from './shared.js';export const CATALOG_TOOLS = [{- name: 'catalog.searchIngredients',+ name: 'catalog_searchIngredients',// Full conductor over the voice `catalog_lookup` tool: description +// parameters are hydrated from it (single source of the ingredient-search// schema; the guard guarantees hydration resolves) AND execute delegates to@@ -25,7 +25,7 @@ export const CATALOG_TOOLS = [execute: (args, ctx) => dispatchVoiceTool('catalog_lookup', args, ctx),},{- name: 'catalog.suggestCastForBrief',+ name: 'catalog_suggestCastForBrief',description: 'Suggest catalog ingredients to cast for a creative brief (ranked). Uses embedding search over the catalog.',costClass: COST_LLM,schema: z.object({ brief: z.string().min(1), types: z.array(z.string()).optional(), limit: z.number().int().positive().max(50).optional() }),diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex 238939c26e..9fa5ce6ece 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -11,7 +11,7 @@ import { COST_RENDER, resolveOwner } from './shared.js';const paramsSchema = z.object({ params: z.record(z.any()).default({}), owner: z.string().optional() });const mediaTool = (kind, label) => ({- name: `media.enqueue${label}Job`,+ name: `media_enqueue${label}Job`,description: `Enqueue a ${kind} media job. Long-running: returns a job handle; completion arrives via media-job events. Tags the job owner to the calling project.`,costClass: COST_RENDER,longRunning: true,diff --git a/server/services/creative/tools/pipeline.js b/server/services/creative/tools/pipeline.jsindex 2060919f0f..1bac882059 100644--- a/server/services/creative/tools/pipeline.js+++ b/server/services/creative/tools/pipeline.js@@ -14,7 +14,7 @@ import { COST_FREE, COST_LLM, COST_RENDER } from './shared.js';export const PIPELINE_TOOLS = [{- name: 'pipeline.createSeries',+ name: 'pipeline_createSeries',description: 'Create a new pipeline series record. Persists a record; returns it.',costClass: COST_FREE,// The wrapped service rejects a missing/blank `name`; require it here so a@@ -32,7 +32,7 @@ export const PIPELINE_TOOLS = [execute: (args) => createSeries(args),},{- name: 'pipeline.generateSeriesConcept',+ name: 'pipeline_generateSeriesConcept',description: 'Generate a series concept (name, logline, premise, shape) for a universe via the LLM.',costClass: COST_LLM,schema: z.object({ universeId: z.string().min(1), options: z.record(z.any()).optional() }),@@ -47,7 +47,7 @@ export const PIPELINE_TOOLS = [execute: ({ universeId, options }) => generateSeriesConcept(universeId, options || {}),},{- name: 'pipeline.generateStage',+ name: 'pipeline_generateStage',description: 'Generate one text stage (LLM) for a pipeline issue and persist the updated issue.',costClass: COST_LLM,schema: z.object({ issueId: z.string().min(1), stageId: z.string().min(1), options: z.record(z.any()).optional() }),@@ -63,7 +63,7 @@ export const PIPELINE_TOOLS = [execute: ({ issueId, stageId, options }) => generateStage(issueId, stageId, options || {}),},{- name: 'pipeline.enqueueComicCover',+ name: 'pipeline_enqueueComicCover',description: 'Enqueue a comic-cover image render for an issue. Long-running: returns a job handle; completion arrives via media-job events.',costClass: COST_RENDER,longRunning: true,@@ -79,7 +79,7 @@ export const PIPELINE_TOOLS = [execute: ({ issueId, options }) => enqueueComicCover(issueId, options || {}),},{- name: 'pipeline.startSeriesAutopilot',+ name: 'pipeline_startSeriesAutopilot',description: 'Start (or no-op resume) the Series Autopilot for a series. Long-running: returns a run handle; progress and pauses arrive via events. Autopilot has its own cos-off gate; the orchestrator gate applies first.',costClass: COST_LLM,longRunning: true,diff --git a/server/services/creative/tools/storyBuilder.js b/server/services/creative/tools/storyBuilder.jsindex 67811c123e..3a6f023e02 100644--- a/server/services/creative/tools/storyBuilder.js+++ b/server/services/creative/tools/storyBuilder.js@@ -9,7 +9,7 @@ import { COST_FREE, COST_LLM } from './shared.js';export const STORY_BUILDER_TOOLS = [{- name: 'storyBuilder.createStorySession',+ name: 'storyBuilder_createStorySession',description: 'Create a new story-builder session (optionally minting a universe/series from the title + seed). Persists the session; returns its id.',costClass: COST_FREE,// The wrapped service requires a non-empty `title` (it doubles as the minted@@ -29,7 +29,7 @@ export const STORY_BUILDER_TOOLS = [execute: (args) => createStorySession(args),},{- name: 'storyBuilder.generateStep',+ name: 'storyBuilder_generateStep',description: 'Generate one story-builder step (LLM) for a session and persist the result.',costClass: COST_LLM,schema: z.object({ id: z.string().min(1), stepId: z.string().min(1), options: z.record(z.any()).optional() }),@@ -45,7 +45,7 @@ export const STORY_BUILDER_TOOLS = [execute: ({ id, stepId, options }) => generateStep(id, stepId, options || {}),},{- name: 'storyBuilder.generateIssuesFromArc',+ name: 'storyBuilder_generateIssuesFromArc',description: 'Generate the issue breakdown for a story arc (LLM). Long-running: creates multiple issue records.',costClass: COST_LLM,longRunning: true,diff --git a/server/services/creative/tools/universe.js b/server/services/creative/tools/universe.jsindex d775e8be88..5626869a1d 100644--- a/server/services/creative/tools/universe.js+++ b/server/services/creative/tools/universe.js@@ -11,7 +11,7 @@ import { COST_FREE, COST_LLM, COST_RENDER } from './shared.js';export const UNIVERSE_TOOLS = [{- name: 'universe.createUniverse',+ name: 'universe_createUniverse',description: 'Create a new universe record (a creative world container). Persists a record; does not generate content.',costClass: COST_FREE,schema: z.object({ name: z.string().min(1) }).passthrough(),@@ -23,15 +23,28 @@ export const UNIVERSE_TOOLS = [execute: (args) => createUniverse(args),},{- name: 'universe.expandWorldTemplate',+ name: 'universe_expandWorldTemplate',description: 'Expand a starter prompt into a universe bible (logline, premise, style, canon) via the configured LLM. Returns the parsed bible; does not persist.',costClass: COST_LLM,- schema: z.object({ starterPrompt: z.string().min(1) }).passthrough(),+ // `influences` must be the structured `{ embrace, avoid }` token-list shape —+ // the service's sanitizeInfluences ignores a bare string and silently drops+ // the style direction, so advertise (and validate) the object shape.+ schema: z.object({+ starterPrompt: z.string().min(1),+ influences: z.object({ embrace: z.array(z.string()).optional(), avoid: z.array(z.string()).optional() }).optional(),+ }).passthrough(),parameters: {type: 'object',properties: {starterPrompt: { type: 'string', description: 'Seed prompt describing the world to expand.' },- influences: { type: 'string', description: 'Optional comma-separated stylistic influences.' },+ influences: {+ type: 'object',+ description: 'Optional stylistic influences as token lists.',+ properties: {+ embrace: { type: 'array', items: { type: 'string' }, description: 'Positive-prompt style tokens to embrace.' },+ avoid: { type: 'array', items: { type: 'string' }, description: 'Negative-prompt tokens to avoid.' },+ },+ },providerId: { type: 'string', description: 'Optional LLM provider override.' },model: { type: 'string', description: 'Optional model override.' },},@@ -40,7 +53,7 @@ export const UNIVERSE_TOOLS = [execute: (args) => expandWorldTemplate(args),},{- name: 'universe.renderUniverseJobs',+ name: 'universe_renderUniverseJobs',description: "Enqueue a batch of image-generation jobs for a universe's canon/variations/composite sheets (requires local or codex image-gen mode). Long-running: returns job handles; completion arrives via media-job events.",costClass: COST_RENDER,longRunning: true,diff --git a/server/services/creative/tools/writersRoom.js b/server/services/creative/tools/writersRoom.jsindex 6f9f5096e5..bec82f9435 100644--- a/server/services/creative/tools/writersRoom.js+++ b/server/services/creative/tools/writersRoom.js@@ -6,11 +6,12 @@import { z } from 'zod';import { createWork } from '../../writersRoom/local.js';import { runAnalysis } from '../../writersRoom/evaluator.js';+import { ANALYSIS_KINDS } from '../../../lib/writersRoomPresets.js';import { COST_FREE, COST_LLM } from './shared.js';export const WRITERS_ROOM_TOOLS = [{- name: 'writersRoom.createWork',+ name: 'writersRoom_createWork',description: 'Create a new writers-room work (short-story, novel, etc.). Persists a manifest; returns it.',costClass: COST_FREE,schema: z.object({ title: z.string().min(1), folderId: z.string().nullish(), kind: z.string().optional() }),@@ -26,17 +27,20 @@ export const WRITERS_ROOM_TOOLS = [execute: ({ title, folderId, kind }) => createWork({ title, folderId: folderId ?? null, kind }),},{- name: 'writersRoom.runAnalysis',+ name: 'writersRoom_runAnalysis',description: 'Run an editorial analysis pass (LLM) over a writers-room work and persist the result.',costClass: COST_LLM,- schema: z.object({ workId: z.string().min(1), kind: z.string().optional() }),+ // The wrapped service rejects any kind outside ANALYSIS_KINDS; require it and+ // constrain to the supported set so a bad call fails validation (before the+ // budget is charged) instead of deep in the service.+ schema: z.object({ workId: z.string().min(1), kind: z.enum(ANALYSIS_KINDS) }),parameters: {type: 'object',properties: {workId: { type: 'string', description: 'Work id to analyze.' },- kind: { type: 'string', description: 'Analysis kind.' },+ kind: { type: 'string', enum: ANALYSIS_KINDS, description: 'Analysis kind.' },},- required: ['workId'],+ required: ['workId', 'kind'],},execute: ({ workId, kind }) => runAnalysis(workId, { kind }),},