From 147b11e60ae99c25d4e32b8707c5bb457eaf1bf8 Mon Sep 17 00:00:00 2001 From: Leonhard Breuer Date: Sun, 22 Nov 2026 19:44:12 +0100 Subject: [PATCH 1/2] feat(dev): add credential-free local AI development --- .fallowrc.json | 2 + CHANGELOG.md | 1 + apps/docs/content/contributing/index.md | 45 ++ apps/server/src/app/server.test.ts | 96 +++ apps/server/src/app/server.ts | 62 +- apps/server/src/app/tenant.ts | 19 +- apps/server/src/providers/emulate-profile.ts | 23 + apps/server/src/providers/emulate.test.ts | 96 +++ apps/server/src/providers/emulate.ts | 67 ++ apps/server/src/providers/providers.ts | 17 +- bun.lock | 9 + docs/designs/emulate-local-development.md | 76 +++ .../2026-11-21-emulate-local-development.md | 149 +++++ package.json | 7 +- tools/check-emulate.ts | 595 ++++++++++++++++++ tools/dev-emulate.ts | 75 +++ tools/emulate-process.test.ts | 27 + tools/emulate-process.ts | 195 ++++++ tools/emulate-scenarios.ts | 69 ++ tools/emulate-server.ts | 33 + tools/emulate-service.ts | 28 + 21 files changed, 1674 insertions(+), 17 deletions(-) create mode 100644 apps/server/src/providers/emulate-profile.ts create mode 100644 apps/server/src/providers/emulate.test.ts create mode 100644 apps/server/src/providers/emulate.ts create mode 100644 docs/designs/emulate-local-development.md create mode 100644 docs/plans/2026-11-21-emulate-local-development.md create mode 100644 tools/check-emulate.ts create mode 100644 tools/dev-emulate.ts create mode 100644 tools/emulate-process.test.ts create mode 100644 tools/emulate-process.ts create mode 100644 tools/emulate-scenarios.ts create mode 100644 tools/emulate-server.ts create mode 100644 tools/emulate-service.ts diff --git a/.fallowrc.json b/.fallowrc.json index e2af5347..f2d131ec 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -5,6 +5,8 @@ "apps/server/drizzle.*.config.ts", "apps/server/test/fixtures/*.ts", "apps/server/tools/*.ts", + "tools/emulate-server.ts", + "tools/emulate-service.ts", "apps/docs/blume.config.ts", "apps/docs/theme.css", "apps/docs/content/**/*.{ts,mdx}", diff --git a/CHANGELOG.md b/CHANGELOG.md index ecc5f80d..a802a878 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Add `bun run dev:emulate` for credential-free local bot chat with scripted replies, streaming, tool calls, errors, and cancellation. Run emulator-backed verification separately with the local-only `bun run check:emulate` command. - Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with ๐Ÿ‘ instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note. - Push notifications wait at least three seconds after enqueue and are suppressed on every device when the reply was seen or its bot or group chat is active in a focused web tab. Request cards count as seen only after their content loads and appears in the viewport. Browser notifications and unread counters are unchanged. - Breaking: independent chat views and explicit reply acknowledgements replace the device-presence endpoint. Existing Apple and Android clients still register for and receive pushes, but must adopt the new attention API before their foreground chats suppress pushes on other devices. diff --git a/apps/docs/content/contributing/index.md b/apps/docs/content/contributing/index.md index c19bed32..16a38d9f 100644 --- a/apps/docs/content/contributing/index.md +++ b/apps/docs/content/contributing/index.md @@ -34,6 +34,51 @@ Server code uses [Effect](https://effect.website). Read `AGENTS.md` before changing it. [Architecture](/contributing/architecture) shows how the pieces fit. +## Run credential-free local development + +Use Bun 1.4.4 and Node.js 24 or later. From the `bot` root: + +1. Start Crumble and Emulate: + + ```bash + bun run dev:emulate + ``` + +2. Open `http://127.0.0.1:7338`. +3. Sign up through the normal local account flow, or sign in to an existing account in this profile. +4. Create a bot with the preconfigured **Emulate (local)** provider and one of the scenario models. +5. Send the bot a message. + +Emulate returns scripted responses through Pi's real HTTP transport, without provider keys or model inference. +The model picker offers only these local scenarios: + +| Model | Behavior | +| -------------- | --------------------------------------------------------------------------------------- | +| `local-reply` | Returns a fixed reply. | +| `local-stream` | Streams a fixed reply incrementally. | +| `local-tool` | Calls the actual `history_search` tool, receives its result, and returns a final reply. | +| `local-error` | Returns a provider error with HTTP status `400`. | +| `local-stall` | Stalls the stream for 30 seconds. As the owner, select **Stop** to cancel it. | + +Account and chat data persist in `.cache/emulate/data` between runs. This directory is not automatically reset. +The profile never opens the ordinary `data` directory or imports its saved provider credentials. +Emulator state resets on restart. Press `Ctrl+C` to close Crumble and the emulator services owned by the command. + +If Emulate is unavailable or a request does not match a scenario, the operation fails visibly. +Fallback to a live model provider is forbidden. + +This profile does not provide workspaces or emulate GitHub, Google Workspace, push notifications, payments, or other services. +It is not a full network sandbox: integrations you enable manually can make external requests. + +Run emulator-backed verification separately: + +```bash +bun run check:emulate +``` + +This command is local-only. It does not run in CI, default tests, or `bun run check`. +Existing `fauxProvider` tests are retained. Normal `bun run dev` and `bun run start` behavior is unchanged. + ## Running the Checks From the `bot` root: diff --git a/apps/server/src/app/server.test.ts b/apps/server/src/app/server.test.ts index e03c848f..386f4524 100644 --- a/apps/server/src/app/server.test.ts +++ b/apps/server/src/app/server.test.ts @@ -22,8 +22,11 @@ import { agentResponse, groupChatResponse, historyResponse, + modelResponse, + providerResponse, scriptRunResponse, } from "../contract/api-responses"; +import { EMULATE_MODEL_IDS } from "../providers/emulate-profile"; import { startServer, voiceGatewayResponse } from "./server"; import type { Workspaces } from "../workspaces/workspace"; import { @@ -861,4 +864,97 @@ test.serial( }, ); +test.serial( + "Emulate signup and restored accounts keep an isolated, configured catalog", + async () => { + const dataDir = mkdtempSync(join(tmpdir(), "crumble-server-emulate-")); + const inherited = { + CRUMBLE_HOST: "0.0.0.0", + CRUMBLE_PUBLIC_URL: "https://inherited.example", + BETTER_AUTH_URL: "https://auth.example", + CRUMBLE_APNS_TEAM_ID: "incomplete-push-configuration", + CRUMBLE_FCM_SERVICE_ACCOUNT_PATH: join(dataDir, "missing-fcm.json"), + CRUMBLE_WORKSPACE_IMAGE: "must-not-load", + }; + const original = Object.keys(inherited).map( + (name) => [name, process.env[name]] as const, + ); + let running: Running | undefined; + + try { + Object.assign(process.env, inherited); + running = await startServer({ + dataDir, + port: 0, + emulate: { baseUrl: "http://127.0.0.1:1/v1" }, + }); + expect(running.server.url.hostname).toBe("127.0.0.1"); + expect( + (await fetch(new URL("/v1/providers", running.server.url))).status, + ).toBe(401); + const suffix = crypto.randomUUID(); + const headers = await signUp(running, suffix); + const catalog = async (current: Running) => { + const providers = await fetch( + new URL("/v1/providers", current.server.url), + { + headers: { ...headers, origin: current.server.url.origin }, + }, + ); + expect(providers.status).toBe(200); + expect( + providerResponse + .array() + .parse(await providers.json()) + .map(({ provider, configured, credentialType }) => ({ + provider, + configured, + credentialType, + })), + ).toEqual([ + { provider: "emulate", configured: true, credentialType: null }, + ]); + const models = await fetch(new URL("/v1/models", current.server.url), { + headers, + }); + expect(models.status).toBe(200); + expect( + modelResponse + .array() + .parse(await models.json()) + .map(({ provider, id }) => ({ provider, id })), + ).toEqual(EMULATE_MODEL_IDS.map((id) => ({ provider: "emulate", id }))); + const capabilities = await fetch( + new URL("/v1/capabilities", current.server.url), + { headers }, + ); + expect(capabilities.status).toBe(200); + expect(await capabilities.json()).toMatchObject({ coding: false }); + expect( + (await fetch(new URL(CLIENT_DOCUMENT_PATH, current.server.url))) + .status, + ).toBe(404); + }; + + await catalog(running); + await running.close(); + running = undefined; + running = await startServer({ + dataDir, + port: 0, + emulate: { baseUrl: "http://127.0.0.1:2/v1" }, + }); + await catalog(running); + await signIn(running, `${suffix}@example.test`); + } finally { + await running?.close(); + for (const [name, value] of original) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + rmSync(dataDir, { recursive: true, force: true }); + } + }, +); + export { signIn, signUp }; diff --git a/apps/server/src/app/server.ts b/apps/server/src/app/server.ts index bb5a3229..89418fec 100644 --- a/apps/server/src/app/server.ts +++ b/apps/server/src/app/server.ts @@ -1,5 +1,12 @@ -import { chmodSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"; -import { resolve } from "node:path"; +import { + chmodSync, + existsSync, + mkdirSync, + readdirSync, + realpathSync, + rmSync, +} from "node:fs"; +import { basename, dirname, resolve } from "node:path"; import { type BunWebSocketData, websocket } from "@hono/bun"; import { createAuth, trustedOriginsFor } from "./auth"; import { accountDir, accountsDir } from "./data-dir"; @@ -11,6 +18,11 @@ import { viewerPathOwner, } from "../bot-desktop/desktop-viewer"; import { createTenant } from "./tenant"; +import { + emulateDirectoriesOverlap, + type EmulateProfile, +} from "../providers/emulate-profile"; +import { validateEmulateBaseUrl } from "../providers/emulate"; import { webUIRoutes } from "./web-ui"; import { CLIENT_DOCUMENT_PATH, @@ -122,6 +134,7 @@ async function closeTenants(tenants: Iterable>) { } type ServerOptions = { + emulate?: EmulateProfile; dataDir?: string; hostname?: string; port?: number; @@ -133,7 +146,37 @@ type ServerOptions = { ) => Effect.Effect; }; +function canonicalPath(path: string): string { + return existsSync(path) + ? realpathSync(path) + : resolve(canonicalPath(dirname(path)), basename(path)); +} + function listenSettings(options: ServerOptions) { + if (options.emulate) { + validateEmulateBaseUrl(options.emulate.baseUrl); + const root = resolve(import.meta.dir, "../../../.."); + + const dataDir = resolve( + options.dataDir ?? resolve(root, ".cache/emulate/data"), + ); + + const ordinary = canonicalPath(resolve(root, "data")); + const actual = canonicalPath(dataDir); + + if (emulateDirectoriesOverlap(actual, ordinary)) + throw new Error( + "Emulate cannot use or overlap the ordinary data directory", + ); + + return { + dataDir, + publicUrl: undefined, + hostname: "127.0.0.1", + port: options.port ?? 7338, + }; + } + return { dataDir: resolve( options.dataDir ?? process.env["CRUMBLE_DATA_DIR"] ?? "./data", @@ -199,8 +242,11 @@ function tenantPool(pool: { tenantId: userId, skillsDir: options.skillsDir ?? process.env["CRUMBLE_SKILLS_DIR"], oauthClient, - workspaceEnv: options.workspaceEnv ?? process.env, - workspaces: options.workspaces?.(userId), + workspaceEnv: options.emulate + ? {} + : (options.workspaceEnv ?? process.env), + workspaces: options.emulate ? undefined : options.workspaces?.(userId), + emulate: options.emulate, serverSettings, }); tenants.set(userId, pending); @@ -456,9 +502,11 @@ export async function startServer(options: ServerOptions = {}) { try { server = serve(requestHandler(state, pool, oauthClient), hostname, port); - const origin = new URL( - publicUrl ?? process.env["BETTER_AUTH_URL"] ?? server.url.origin, - ).origin; + const origin = options.emulate + ? server.url.origin + : new URL( + publicUrl ?? process.env["BETTER_AUTH_URL"] ?? server.url.origin, + ).origin; state.trustedOrigins = trustedOriginsFor(origin); state.ready = connectAccounts(state, pool, dataDir, origin); diff --git a/apps/server/src/app/tenant.ts b/apps/server/src/app/tenant.ts index 5b7851e7..a586ecec 100644 --- a/apps/server/src/app/tenant.ts +++ b/apps/server/src/app/tenant.ts @@ -99,8 +99,10 @@ import { requestCallTools } from "../voice-gateway/request-call"; import { eventPayloadTools } from "../automations/event-tools"; import { usesDesktop } from "../contract/tools"; import type { ServerSettings } from "./server-settings"; +import type { EmulateProfile } from "../providers/emulate-profile"; export type TenantOptions = { + emulate?: EmulateProfile | undefined; dataDir: string; skillsDir?: string | undefined; oauthClient?: ClientDocument | undefined; @@ -157,6 +159,9 @@ function accountLayer(options: TenantOptions, dataDir: string) { ...credentialInterception(run), }; + if (options.emulate) + return BotWorkspaces.layer(Effect.succeed(undefined)); + return BotWorkspaces.layer( options.workspaces ?? acquireWorkspaces(() => @@ -178,7 +183,7 @@ function accountLayer(options: TenantOptions, dataDir: string) { const installed = builtinPlugins({ dataDir, secret: secretText(yield* Secrets), - env: process.env, + env: options.emulate ? {} : process.env, workspaces: yield* BotWorkspaces, questionGraceMs: () => options.serverSettings().questionGraceMinutes * 60_000, @@ -207,7 +212,11 @@ function accountLayer(options: TenantOptions, dataDir: string) { const models = Layer.unwrap( Plugins.use((installed) => Effect.succeed( - ProviderModels.layer(accountModels, pluginProviders(installed)), + ProviderModels.layer( + (credentials, contributions) => + accountModels(credentials, contributions, options.emulate), + pluginProviders(installed), + ), ), ), ); @@ -284,7 +293,11 @@ function accountLayer(options: TenantOptions, dataDir: string) { const push = Layer.mergeAll(PushDelivery, attentionCleanup).pipe( Layer.provideMerge(Push.layerNoDeps), - Layer.provideMerge(PushTransports.layer), + Layer.provideMerge( + options.emulate + ? Layer.succeed(PushTransports, { apns: undefined, fcm: undefined }) + : PushTransports.layer, + ), Layer.provideMerge(PushRepository.layerNoDeps), ); diff --git a/apps/server/src/providers/emulate-profile.ts b/apps/server/src/providers/emulate-profile.ts new file mode 100644 index 00000000..192df856 --- /dev/null +++ b/apps/server/src/providers/emulate-profile.ts @@ -0,0 +1,23 @@ +import { isAbsolute, relative, sep } from "node:path"; + +export function emulateDirectoriesOverlap( + actual: string, + ordinary: string, +): boolean { + return [relative(actual, ordinary), relative(ordinary, actual)].some( + (path) => + !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`), + ); +} + +export const EMULATE_MODEL_IDS = [ + "local-reply", + "local-stream", + "local-tool", + "local-error", + "local-stall", +] as const; + +export type EmulateModelId = (typeof EMULATE_MODEL_IDS)[number]; + +export type EmulateProfile = { baseUrl: string }; diff --git a/apps/server/src/providers/emulate.test.ts b/apps/server/src/providers/emulate.test.ts new file mode 100644 index 00000000..0f2ab35b --- /dev/null +++ b/apps/server/src/providers/emulate.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from "bun:test"; +import type { CredentialStore } from "@earendil-works/pi-ai"; +import { emulateProvider } from "./emulate"; +import { + EMULATE_MODEL_IDS, + emulateDirectoriesOverlap, +} from "./emulate-profile"; +import { meliousProvider } from "./melious"; +import { accountModels } from "./providers"; + +test("local data rejects filesystem roots, ordinary data and overlapping directories", () => { + for (const path of [ + "/", + "/repository", + "/repository/data", + "/repository/data/nested", + ]) { + expect(emulateDirectoriesOverlap(path, "/repository/data")).toBe(true); + } + for (const path of [ + "/isolated/data", + "/repository/data-other", + "/repository/.cache/emulate/data", + ]) { + expect(emulateDirectoriesOverlap(path, "/repository/data")).toBe(false); + } +}); + +const baseUrl = "http://127.0.0.1:1/v1"; +const forbidden = async (): Promise => { + throw new Error("The local catalog must never access saved credentials"); +}; +const credentials: CredentialStore = { + read: forbidden, + list: forbidden, + modify: forbidden, + delete: forbidden, +}; + +test("local accounts expose only configured Emulate models without reading credentials", async () => { + for (const store of [undefined, credentials]) { + const models = accountModels(store, [{ provider: meliousProvider() }], { + baseUrl, + }); + + expect(models.getProviders().map((provider) => provider.id)).toEqual([ + "emulate", + ]); + expect(models.getModels().map((model) => model.id)).toEqual([ + ...EMULATE_MODEL_IDS, + ]); + expect((await models.getAvailable()).map((model) => model.id)).toEqual([ + ...EMULATE_MODEL_IDS, + ]); + expect(await models.checkAuth("emulate")).toEqual({ + type: "api_key", + source: "emulate-local", + }); + expect(await models.getAuth("emulate")).toEqual({ + auth: { apiKey: "emulate-local" }, + source: "emulate-local", + }); + expect(await models.getAuth("melious")).toBeUndefined(); + expect(await models.getAuth("openai")).toBeUndefined(); + } +}); + +test("each local catalog uses its current emulator endpoint", () => { + for (const url of [baseUrl, "http://127.0.0.1:2/v1"]) { + const models = accountModels(credentials, [], { baseUrl: url }); + + expect(models.getProvider("emulate")?.baseUrl).toBe(url); + expect(models.getModels().map((model) => model.baseUrl)).toEqual( + EMULATE_MODEL_IDS.map(() => url), + ); + } +}); + +test("Emulate rejects remote, credential-bearing and ambiguous endpoints", () => { + for (const url of [ + "https://127.0.0.1:1/v1", + "http://example.test:1/v1", + "http://localhost:1/v1", + "http://0.0.0.0:1/v1", + "http://[::1]:1/v1", + "http://user:password@127.0.0.1:1/v1", + "http://127.0.0.1/v1", + "http://127.0.0.1:0/v1", + "http://127.0.0.1:65536/v1", + `${baseUrl}/`, + `${baseUrl}?key=secret`, + `${baseUrl}#fragment`, + ]) { + expect(() => emulateProvider(url)).toThrow(); + } +}); diff --git a/apps/server/src/providers/emulate.ts b/apps/server/src/providers/emulate.ts new file mode 100644 index 00000000..03fb0d93 --- /dev/null +++ b/apps/server/src/providers/emulate.ts @@ -0,0 +1,67 @@ +import { + createModels, + createProvider, + type Model, + type Models, + type Provider, +} from "@earendil-works/pi-ai"; +import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy"; +import { EMULATE_MODEL_IDS } from "./emulate-profile"; + +export function validateEmulateBaseUrl(baseUrl: string): void { + const match = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})\/v1$/.exec(baseUrl); + + if (!match || match[0] !== baseUrl || Number(match[1]) > 65535) { + throw new Error( + "Emulate requires http://127.0.0.1:PORT/v1 with a port from 1 to 65535", + ); + } +} + +export function emulateProvider( + baseUrl: string, +): Provider<"openai-completions"> { + validateEmulateBaseUrl(baseUrl); + + return createProvider<"openai-completions">({ + id: "emulate", + name: "Emulate (local)", + baseUrl, + auth: { + apiKey: { + name: "Local Emulate", + check: async () => ({ type: "api_key", source: "emulate-local" }), + resolve: async () => ({ + auth: { apiKey: "emulate-local" }, + source: "emulate-local", + }), + }, + }, + models: EMULATE_MODEL_IDS.map((id): Model<"openai-completions"> => ({ + id, + name: id, + api: "openai-completions", + provider: "emulate", + baseUrl, + input: ["text"], + reasoning: false, + contextWindow: 128000, + maxTokens: 16384, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + })), + api: openAICompletionsApi(), + }); +} + +export function emulateModels(baseUrl: string): Models { + const models = createModels({ + authContext: { + env: async () => undefined, + fileExists: async () => false, + }, + }); + + models.setProvider(emulateProvider(baseUrl)); + + return models; +} diff --git a/apps/server/src/providers/providers.ts b/apps/server/src/providers/providers.ts index 2b62ff68..b4abd1bb 100644 --- a/apps/server/src/providers/providers.ts +++ b/apps/server/src/providers/providers.ts @@ -3,6 +3,8 @@ import { Context, Effect, Layer } from "effect"; import { ProviderCredentials } from "./provider-credentials"; import { builtinModels } from "@earendil-works/pi-ai/providers/all"; import type { ProviderContribution } from "../plugins/plugins"; +import type { EmulateProfile } from "./emulate-profile"; +import { emulateModels } from "./emulate"; type CatalogOptions = NonNullable[0]>; @@ -24,13 +26,16 @@ const catalog = ( export const accountModels = ( credentials: CredentialStore | undefined, contributions: readonly ProviderContribution[], + emulate?: EmulateProfile, ) => - catalog(credentials, contributions, { - authContext: { - env: async () => {}, - fileExists: async () => false, - }, - }); + emulate + ? emulateModels(emulate.baseUrl) + : catalog(credentials, contributions, { + authContext: { + env: async () => {}, + fileExists: async () => false, + }, + }); export const hostModels = ( credentials: CredentialStore | undefined, diff --git a/bun.lock b/bun.lock index 3af34973..f873e104 100644 --- a/bun.lock +++ b/bun.lock @@ -5,14 +5,17 @@ "": { "name": "bot", "devDependencies": { + "@earendil-works/pi-ai": "1.4.0", "@oxlint/plugins": "1.88.0", "@types/bun": "latest", "@types/node": "^26.6.6", + "emulate": "0.14.0", "fallow": "3.38.0", "oxlint": "1.88.0", "oxlint-plugin-effect": "^0.32.1", "oxlint-tsgolint": "7.0.2005", "typescript": "7.0.2", + "zod": "4.6.7", }, }, "apps/server": { @@ -599,6 +602,8 @@ "cn": ["cn@0.5.0", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-JGEixZEpfFXm1P5uXwvEobOFLlHwIWi5v4tjd1ZwfiYmcEilkuD2l+054rvJcYCR1B+uVThHeUbgmNz1FwuxuA=="], + "commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="], + "content-disposition": ["content-disposition@2.0.1", "", {}, "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog=="], "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], @@ -703,6 +708,8 @@ "effect": ["effect@4.0.6", "", {}, "sha512-Tc3mkzuLR6t6P9dhLt0D2GrxYtmU5td4XEJEiXCmILz53IRIfJyHsKZWjTA3xEjiwpNTtXBgI4iqYPxMztBDrw=="], + "emulate": ["emulate@0.14.0", "", { "dependencies": { "commander": "^14", "picocolors": "^1.1.1", "yaml": "^2" }, "bin": { "emulate": "dist/index.js" } }, "sha512-mlM/PJ34ynD2OTGVBvy+8/F7gEDwkHWmpqLG/JetaDmaqifkHtCw2VMmXTKBy6Zwa5yvCziLvyyvmAoVeuPZoA=="], + "encodeurl": ["encodeurl@2.0.1", "", {}, "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A=="], "enhanced-resolve": ["enhanced-resolve@5.26.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw=="], @@ -907,6 +914,8 @@ "pele": ["pele@1.9.0", "", {}, "sha512-KUmBt7P5JduVKQaP6FKfXiRgH3LBVIKsmdgPJZU7jD3ye6F+Z8fbms+OjivE7rWY09Qx+5X65VKe/9ywKFJ9Sw=="], + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + "pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="], "pkijs": ["pkijs@4.0.0", "", { "dependencies": { "@noble/hashes": "^2.4.0", "@peculiar/utils": "^4.1.0", "bytestreamjs": "^3.0.0" }, "peerDependencies": { "asn1js": "^4.0.0" } }, "sha512-2cRrl7hofMVkgP8uB4V/1v5ofFatz9CC3kId41pWVxJVpoh9LfCiU8z+aTegfC3O9qstY6p+aSzHi3age8DlNw=="], diff --git a/docs/designs/emulate-local-development.md b/docs/designs/emulate-local-development.md new file mode 100644 index 00000000..8f0730ac --- /dev/null +++ b/docs/designs/emulate-local-development.md @@ -0,0 +1,76 @@ +# Credential-free local development + +**Status:** approved + +## Problem + +Exercising Crumble locally requires live provider credentials. Developers need repeatable bot replies, streaming, tool activity, and failures without connecting personal accounts or paying for model calls. + +The existing `fauxProvider` tests cover runtime behavior, but they do not provide an interactive development environment through Pi's real HTTP transport. + +## Solution + +Add an opt-in `bun run dev:emulate` command that starts Emulate and Crumble together. The web app offers a clearly named local provider with deterministic scenarios. After creating a normal local account, developers can create bots and exchange messages without entering provider keys. + +This first slice covers model-dependent bot chat and local tool execution. It does not emulate every external service Crumble supports. + +## Behavior + +1. Starting the command launches the AI emulator on IPv4 loopback before starting Crumble. Crumble defaults to `127.0.0.1:7338` and an isolated `.cache/emulate/data` directory. Startup prints the app address, emulator address, data location, and scenario names. +2. The local provider is already configured with nonsecret dummy authentication. The model picker offers only local scenario models in this profile. Normal account creation and sign-in remain unchanged. +3. Named scenario models provide a fixed reply, a visibly streamed reply, a tool round trip, a provider error, and a stalled stream that the owner can stop. Scenario selection uses the existing model picker, not a new settings screen. +4. The tool scenario calls the existing `history_search` tool, receives its result, and returns a final reply. It needs no workspace, external MCP server, or network service. The transcript shows the actual tool activity. +5. Scenario rules are deterministic and bounded. Unknown models or unmatched requests fail visibly rather than producing an accidental successful test. A provider error follows Crumble's existing error handling and retry behavior. +6. If the emulator fails to start or becomes unavailable, the command or affected model call fails clearly. No model request falls back to a live provider. An occupied app port fails rather than terminating another process. +7. Stopping the command closes the app and emulator. Development reloads do not leave duplicate listeners or orphaned child processes. Emulator state resets on restart; local account and chat data persist. No existing database is deleted automatically. +8. Ordinary `bun run dev`, production startup, existing accounts, and faux-based tests retain their behavior. The profile never opens the ordinary `data` directory or imports saved provider credentials from another installation. + +## Decisions + +- Keep `fauxProvider`: replacing the existing test suite would add migration work without solving the immediate local-development problem. +- Start with one OpenAI-compatible protocol through Pi's existing HTTP transport. Follow the explicit provider URL pattern in `apps/server/src/providers/melious.ts`; do not implement another fake Pi provider. +- Register the local provider only in the explicit development profile. Do not expose a generic provider URL setting or modify production provider endpoints. +- Restrict model availability to local scenarios in this profile. Adding an emulator provider beside live providers is insufficient to prevent accidental live model calls. +- Use a pinned development dependency for Emulate. Keep Bun for Crumble and its package management. Check Emulate's supported Node runtime when launching it; do not assume Bun compatibility or install global tools automatically. +- Preserve the no-emulators-in-CI policy. Emulator-backed verification runs only through a separate local command, outside default test discovery and `bun run check`. +- Seed no external integrations or network-capable workspace. This is not a process-wide network sandbox: bundled scenarios and model routing are local, but arbitrary integrations enabled manually are outside this guarantee. + +## Interfaces and data + +- New development and local-verification commands; no public API contract or database schema change. +- Reuse `startServer` listener/data options and account-scoped model construction. Profile selection must happen before account restoration. +- New scenario definitions are shared by interactive development and local verification. +- Ignore generated profile state through the existing `.cache` rule. Never copy, overwrite, or remove ordinary installation data. + +## Affected code + +- `package.json` and `bun.lock`: development dependency and explicit commands. +- `tools/dev-emulate.ts` and `tools/emulate-scenarios.ts` (new): lifecycle ownership and deterministic scenario definitions. +- `apps/server/src/providers/emulate.ts` (new): local model metadata and Pi HTTP provider configuration, following `providers/melious.ts`. +- `apps/server/src/app/server.ts`, `apps/server/src/app/tenant.ts`, `apps/server/src/app/builtin-plugins.ts`, and `apps/server/src/providers/providers.ts`: opt-in profile wiring before restoration, preserving ordinary account credential isolation. +- `tools/check-emulate.ts` (new): separately invoked local smoke verification. +- `apps/docs/content/contributing/index.md` and `CHANGELOG.md`: setup, scenario selection, limitations, local verification, and the new command. + +## Testing + +Approved testing seams: + +- Configuration/lifecycle checks that need no emulator can remain in the ordinary suite. They verify explicit opt-in, loopback restrictions, isolated data selection, and unchanged normal startup defaults. +- A separate local smoke command uses real Pi HTTP requests and Crumble's authenticated API/runtime. It verifies incremental streaming, the `history_search` round trip, provider errors, stopping a stalled reply, and failure without live fallback. Use `apps/server/src/app/e2e.test.ts` as prior art for submission and transcript persistence, without replacing that test. +- Manual verification in the actual web app confirms a new local account can select a scenario and receive replies without provider sign-in. + +Run `bun run check` and `bun run check` in `apps/docs` after implementation. Do not add emulator-dependent checks to any CI workflow. + +Pi/Emulate compatibility is not yet proven. A successful real HTTP streaming and tool-call exchange is a prerequisite for claiming the feature works. If compatibility requires replacing Pi or creating another simulated transport, stop and revisit the design. + +## Out of scope + +- Wholesale faux migration or changes to CI policy. +- GitHub, Google Workspace, push, payment, or other service emulation. +- Credential-free real inference, model-quality evaluation, or emulated browser interfaces. +- Workspaces, desktop jobs, gateway provisioning, or automatic account/bot seeding. +- New production settings, authentication bypasses, or automatic data resets. + +## Open questions + +None. diff --git a/docs/plans/2026-11-21-emulate-local-development.md b/docs/plans/2026-11-21-emulate-local-development.md new file mode 100644 index 00000000..46ef7f39 --- /dev/null +++ b/docs/plans/2026-11-21-emulate-local-development.md @@ -0,0 +1,149 @@ +# Credential-free local development implementation plan + +> Implement one task at a time. Review each deliverable before starting the next. Steps use `- [ ]`. + +**Goal:** Run Crumble locally with deterministic AI scenarios and no live provider credentials. +**Architecture:** A Bun development supervisor owns one Node Emulate sidecar and a watched Crumble entry point. An explicit local profile replaces the account model catalog with a preconfigured Pi HTTP provider. Interactive development and a separate local smoke command share the emulator scenarios and lifecycle helper. +**Source:** [Approved spec](../designs/emulate-local-development.md). + +## Decisions + +- Keep all existing `fauxProvider` tests; wholesale migration does not solve the development setup problem. +- Add `bun run dev:emulate`, using loopback, port `7338`, and repository-local `.cache/emulate/data`. +- Offer five scenario models: `local-reply`, `local-stream`, `local-tool`, `local-error`, and `local-stall`. The tool scenario calls `history_search` and then answers. +- Use the existing Pi OpenAI-compatible HTTP transport, nonsecret dummy authentication, and a local-only model catalog. There is no generic endpoint setting or production fallback. +- Keep normal authentication and production startup unchanged. No account/bot seeding, real integrations, or workspaces. +- Run emulator-backed checks only with the new `bun run check:emulate` command. Do not add them to default test discovery or CI. + +## Constraints + +- Crumble uses Bun `1.4.4` (`.bun-version`). Use Bun for dependency installation and application execution. Pin `emulate` to `0.14.0`; require Node `24+` for its sidecar. The available Node runtime is `26.10.0`. +- Before writing Effect code, read `apps/server/node_modules/effect/AGENTS.md` completely. +- "Nothing that needs a simulator or emulator runs in CI, in any workflow: no UI tests, no app-hosted tests. Those run locally." +- "CI unit-test jobs that run on push or pull requests must finish in at most two minutes; check a job's duration after changing it." +- No real keys, paid APIs, external network calls, automatic global tool installation, or modification of existing installation data during verification. +- No commits, staging, push, or pull request without explicit permission. + +## Out of scope + +Faux replacement, CI policy changes, other service emulators, real model inference, new UI screens, workspaces, gateways, schema changes, generic provider URL configuration, and automatic data resets. + +## Review focus + +1. Existing environment configuration must not redirect the local profile into real data, credentials, push transports, or workspaces. +2. A separate local catalog must not reintroduce live providers through plugin contributions or account restoration. +3. Tool-result requests must match a terminating scenario rule rather than recursively calling the tool. +4. App reload, early startup failure, occupied ports, and interrupts must not leave sidecars or duplicate app listeners. +5. Stalled/error scenarios must remain stoppable and bounded without provider fallback. + +## Files + +- `package.json`, `bun.lock`: pinned development dependency and explicit local commands. +- `apps/server/src/providers/emulate-profile.ts` (new): dependency-free profile type and scenario model IDs shared with the tools. +- `tools/emulate-scenarios.ts` (new): deterministic AI seed rules and expected reply text. +- `tools/emulate-service.ts` (new): Node-only sidecar entry point; the only runtime import of `emulate`. +- `tools/emulate-process.ts` (new): Bun-side child ownership, clean environment, and readiness protocol. +- `tools/dev-emulate.ts`, `tools/emulate-server.ts` (new): supervisor and watched app entry point. +- `apps/server/src/providers/emulate.ts` (new): Pi HTTP provider and strict loopback validation. +- `apps/server/src/providers/providers.ts`, `apps/server/src/app/server.ts`, `apps/server/src/app/tenant.ts`: explicit local catalog/profile propagation. `tenantPool` lives inside `server.ts:183`; no separate pool module is needed. +- `apps/server/src/providers/emulate.test.ts`, `tools/emulate-process.test.ts` (new): non-emulator provider/environment assertions. +- `apps/server/src/app/server.test.ts`, `apps/server/src/app/tenant.test.ts`: profile forwarding, restored accounts, and unchanged ordinary behavior. +- `tools/check-emulate.ts` (new): local authenticated app/runtime smoke checks, outside automatic test discovery. +- `apps/docs/content/contributing/index.md`, `CHANGELOG.md`: development instructions and behavior change. + +### Task 1: Prove the real transport and provide deterministic scenarios + +**Files:** dependency files; new profile, scenario, sidecar, process-helper and provider modules listed in Files. Begin `tools/check-emulate.ts` with the transport checks; Task 4 extends it. +**Interfaces:** +- Produces `EMULATE_MODEL_IDS`, the five literal IDs in Decisions; `EmulateModelId` is their union. The dependency-free profile module also exports `EmulateProfile = { baseUrl: string }`. +- Produces `emulateProvider(baseUrl: string): Provider<'openai-completions'>`. Accept only `http://127.0.0.1:PORT/v1`, with an explicit nonzero port and no credentials, query, or fragment. +- Produces `startEmulate(): Promise<{ url: string; close(): Promise }>` in `tools/emulate-process.ts`; `url` is the listener origin. Each call owns an independent sidecar; `close` is idempotent. +- The sidecar uses published `createEmulator({ service: 'ai', hostname: '127.0.0.1', port: 0, seed: { ai: ... } })`, not the CLI's differently named `--host` option. See [published API types][emulate-api]. +- Pi supports fixed dummy auth through `auth.apiKey.check` and `auth.apiKey.resolve`; neither reads ambient or saved credentials. Use `createProvider` with `openAICompletionsApi()` as in `apps/server/src/providers/melious.ts:28`. SDK definitions: `apps/server/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts:170` and `apps/server/node_modules/@earendil-works/pi-ai/dist/models.d.ts:215` (version `1.4.0`). + +- [x] Run `bun add --dev --exact --ignore-scripts emulate@0.14.0` in this worktree. Ignoring lifecycle scripts avoids the root `prepare` script modifying shared Git configuration. Do not link another worktree's dependencies or install global tools. +- [x] Implement the Node sidecar using `node --experimental-strip-types` and erasable TypeScript without path aliases. Emit `{ type: 'ready', url }` after listening; send diagnostics to stderr. Give startup 10 seconds and graceful shutdown 5 seconds before terminating only the owned child. +- [x] Set `strict: true` and match the exact model plus `format: 'openai-chat'`. Fixed reply text is `Local reply.`; streamed text is `This reply is streamed locally without live credentials.` with a 150 ms chunk delay. Export these expected strings from the scenario module. For the tool model, match `hasToolResult: false` plus declared `history_search`, call it with `{ query: 'local' }`, then match `hasToolResult: true` and answer `Local tool finished.`. Do not spend a global one-call budget that would break later chats. Use HTTP `400` and `Scripted local provider error.` for the error model; stall the streaming model after one content chunk for 30 seconds. See [AI rule documentation][emulate-ai]. +- [x] Implement the text-only, zero-cost local provider and validate its URL before transport creation. `check` reports API-key availability; `resolve` supplies the constant nonsecret `emulate-local` key without a login flow. +- [x] Use the first local smoke checks to make real Pi HTTP calls for streaming and tool-result continuation. Assert incremental output, the expected tool name/arguments, and final reply after its result. Run `bun --no-env-file tools/check-emulate.ts` for this first transport-only version. Expected: streaming and the tool continuation pass, and owned resources close. Stop and revisit the design if success requires replacing Pi or implementing another simulated transport. + +### Task 2: Wire the isolated, preconfigured local catalog + +**Files:** server, tenant and provider-catalog modules; new `emulate.test.ts`; existing `server.test.ts` and `tenant.test.ts`. +**Interfaces:** +- Consumes `EmulateProfile` and `emulateProvider` from Task 1. +- Extends `ServerOptions` (`apps/server/src/app/server.ts:124`) and `TenantOptions` (`apps/server/src/app/tenant.ts:103`) with `emulate?: EmulateProfile`; `tenantPool` forwards it before account restoration. +- Extends `accountModels(credentials, contributions, emulate?)` with an optional final profile argument, preserving existing two-argument callers. Its local branch uses `createModels` and only `emulateProvider`, not `builtinModels` or contributed live providers (`apps/server/src/providers/providers.ts:16,24`; SDK `apps/server/node_modules/@earendil-works/pi-ai/dist/models.d.ts:207โ€“214`). Pass the explicit branch through the existing `ProviderModels.layer` factory seam (`apps/server/src/providers/providers.ts:43`, `apps/server/src/app/tenant.ts:207`). + +- [x] Thread the explicit profile through startup and every restored/new account. Preserve normal defaults when absent. For the profile, choose loopback, isolated data and local auth origins before `startServer` restores accounts; ignore inherited `CRUMBLE_PUBLIC_URL` and `BETTER_AUTH_URL`. +- [x] Build only the preconfigured local catalog. Do not give it the account credential store or register live plugin-provider contributions. Restored bots referencing nonlocal providers fail as unavailable rather than falling back; secondary model selection obeys the same catalog. +- [x] Force an empty workspace configuration for this profile and supply an unconfigured `PushTransports` service instead of its ambient-environment layer (`apps/server/src/push/push-transports.ts:52`; `apps/server/src/app/tenant.ts:287`). Normal startup keeps its existing layers. +- [x] Add non-emulator assertions: `expect(providerIds).toEqual(['emulate'])`; model IDs equal `EMULATE_MODEL_IDS`; empty-store auth resolves to `emulate-local`; non-loopback/credential-bearing URLs reject; a supplied live plugin provider is absent. Test new and restored account catalogs and preserve the existing ordinary host-key-isolation tests. +- [x] Run `bun test apps/server/src/providers/emulate.test.ts apps/server/src/app/tenant.test.ts apps/server/src/app/server.test.ts`. Expected: pass without starting Emulate or contacting external services. + +### Task 3: Add the development command and process ownership + +**Files:** supervisor/app entry points; process helper and its new unit test; `package.json`; documentation and changelog. +**Interfaces:** +- Consumes `startEmulate` and `EmulateProfile` from Tasks 1โ€“2. +- Adds `startLocalApp(options: { baseUrl: string; dataDir: string; port: number; watch?: boolean }): Promise<{ url: string; close(): Promise }>` to `tools/emulate-process.ts`. It owns the Bun app child, accepts port `0` for smoke checks, and shares the readiness/cleanup contract from Task 1. +- Produces `bun run dev:emulate`; the supervisor owns one sidecar and one watched app child. Use Bun's verified `--no-env-file`, `--watch`, and `--watch-kill-signal=SIGTERM` flags. Reloading the app does not restart the sidecar. +- The app entry point calls `startServer({ dataDir, hostname: '127.0.0.1', port, workspaceEnv: {}, emulate: { baseUrl } })`. Existing startup returns `{ server, auth, close }` (`apps/server/src/app/server.ts:421,467`); signal handlers await `close()` before exit. + +- [x] Add an allowlisted child environment containing only needed OS/runtime variables such as `PATH`, `HOME`, temporary-directory and locale settings. Do not forward `CRUMBLE_*`, `BETTER_AUTH_*`, provider keys, `BUN_OPTIONS`, or `NODE_OPTIONS`; disable Bun dotenv loading in the app child. Pass explicit profile arguments, not inherited app configuration. Unit-test this filtering with dummy values and no subprocess or emulator. +- [x] Resolve profile paths relative to the repository, not the caller's directory. Start on `127.0.0.1:7338` with `.cache/emulate/data`. Reject the ordinary `data` location, and never auto-delete accounts or chats. Non-emulator tests verify that inherited data/listener/push/workspace values cannot override the profile. +- [x] Start Emulate before the watched app, then log addresses, data location, and scenario names. A missing Node executable or version below `24` produces an actionable error without installing anything. Readiness is the app's actual listening URL, not a guessed fixed address. +- [x] On interrupt, child exit, or partial startup failure, close owned child processes, including the watcher, using bounded graceful shutdown. Refuse an occupied app port; never terminate its listener. No failure path launches an ordinary/live app as fallback. +- [x] Document local account creation, scenario selection, Node/Bun prerequisites, retained data, and limits. Add an Unreleased entry. +- [x] Run `bun test tools/emulate-process.test.ts`. Then verify the actual web app: create a local account/bot without provider sign-in, exercise each scenario, reload the app, and confirm the account/transcript persist with one emulator listener. Stop the command and confirm both owned listeners close. + +### Task 4: Verify the complete local path without changing CI + +**Files:** extend `tools/check-emulate.ts` from Task 1; local-command documentation; `package.json` command entry. +**Interfaces:** +- Consumes `startEmulate` and `startLocalApp` from Tasks 1โ€“3. +- Produces `bun run check:emulate`, running `tsc -p tools && bun --no-env-file tools/check-emulate.ts`. The existing `tools/tsconfig.json` extends the strict base configuration; root `typecheck` currently covers only server/web. The command returns nonzero on failed assertions and cleans up owned resources. The smoke script imports no `bun:test` hooks and has no default-test filename. +- Signup: `POST /api/auth/sign-up/email` with a dummy `name`, unique `example.test` email and password; use the returned token as `Authorization: Bearer TOKEN` (`apps/server/src/app/server.test.ts:46โ€“65`). +- Create each bot with `POST /v1/agents`, explicit `provider: 'emulate'`, its scenario model ID, and reviews disabled; ordinary schema defaults cover the remaining fields (`apps/server/src/contract/agents.ts:51`; `apps/server/src/contract/api-contract.ts:714`). +- Submit `{ content, requestId: crypto.randomUUID() }` to `POST /v1/agents/ID/messages`; read `GET /v1/agents/ID/chat` and `GET /v1/agents/ID/events?partial=true`; stop with `POST /v1/agents/ID/abort` (`apps/server/src/contract/api-contract.ts:154,853,948,963`). + +- [x] Start the actual app with `startLocalApp({ baseUrl, dataDir: TEMP_DIR, port: 0 })`, using clean child configuration and shared scenarios. Complete normal signup and assert provider discovery is already configured with exactly five local models before creating any bot or credential. +- [x] Assert exact fixed/final tool reply text from Task 1, at least two distinct nonempty partial-stream snapshots before completion, and the real tool arguments/result in the transcript. Confirm `GET /_ai/calls` shows the matching tool-call and tool-result rules rather than a default reply. +- [x] Assert a visible failed turn for the HTTP `400` model; a stalled turn accepts `/abort` and stops running; after closing Emulate a new turn fails rather than succeeding through another provider. Every wait has a deadline and every stream is canceled in cleanup. Verify unmatched raw model requests fail under strict mode. +- [x] Verify new/restored local accounts retain only the local catalog; a changed emulator port after restart cannot restore an old model endpoint. Exercise watcher reload, partial startup failure, and occupied-port cleanup with owned temporary resources. Preserve pre-existing listeners and non-test data. Do not add emulator startup to ordinary tests or any workflow. +- [x] Run `bun run check:emulate`, root `bun run check`, and `bun fmt --check tools/dev-emulate.ts tools/check-emulate.ts tools/emulate-*.ts`. Run `bun run check` in `apps/docs`, installing its dependencies with `bun install --frozen-lockfile --ignore-scripts` first if necessary. Report failures, skips, and unverified manual scenarios honestly. +- [x] Get a fresh-context `vet` review against the approved spec and this plan's Deviations. Resolve in-scope defects and rerun affected checks. Do not commit or stage without permission. + +## Verified API sources + +- [Published Emulate `0.14.0` metadata][emulate-package] and [API types][emulate-api]: `hostname`, root `seed.ai`, ephemeral ports, and awaitable close. +- [Pinned upstream runtime requirement][emulate-runtime]: Node `24+`. Local `node --help` confirms `--experimental-strip-types`; keep the sidecar's TypeScript erasable. +- [Pinned AI documentation][emulate-ai]: strict mode, model/format/tool-result matching, timing, native errors, and stalls. +- Pi SDK declarations cited in Task 1 were read from the existing checkout's installed `@earendil-works/pi-ai@1.4.0`; install this worktree's matching locked version before implementation. No runtime compatibility claim follows from those type definitions. + +## Deviations + +- Task 1 ยท added `emulateModels(baseUrl)` alongside `emulateProvider` so application catalogs and the transport probe share the same fixed-auth factory. +- Task 1 ยท declared the already-used `@earendil-works/pi-ai@1.4.0` as an exact root development dependency as well. Root tooling consumes its schema/types directly; this avoids importing through a workspace's `node_modules` path. No new SDK or production dependency was selected. +- Task 2 ยท retained the existing `app/tenant.test.ts` host-key-isolation tests unchanged. Added the new signup/restore assertions to `server.test.ts` and the pure provider suite instead. +- Tasks 2โ€“3 ยท canonicalize local/ordinary data paths, including existing symlink parents, and reject overlapping directories. A fresh review found a filesystem-root edge case in the initial prefix comparison; a pure predicate regression failed before the separator-safe `relative` fix and passed afterward. No filesystem-root startup was attempted. +- Task 3 ยท declared the existing server dependency `zod@4.6.7` as a matching root development dependency for subprocess readiness/argument validation. It introduces no new production library. +- Task 3 ยท verified signup, provider selection, streaming, tool reply, provider error, Stop, fixed reply, and persistence across watcher reload in an isolated headless Helium profile. UI interactions and same-origin API submissions used only the generated local account. A screenshot is kept under ignored `.cache/emulate/`. +- Task 4 ยท failed executions produce an idle chat snapshot with `error`, not a snapshot whose status is `failed`. The smoke command correlates execution status by request ID and separately checks the transcript/error. It also confirms the stalled HTTP stream records `client_aborted`. +- Task 4 ยท additional temporary local lifecycle checks verified preserved occupied listeners, failed-start cleanup, idempotent close, closed listeners, and an actionable missing-Node error. +- Shipping checks ยท registered the two subprocess entry points in `.fallowrc.json`, since they are launched by path rather than imported. No analysis rule was disabled. + +## Verification results + +- Root `bun run check`: passed; 1,302 tests passed, 118 skipped, no failures (test phase 15.41 seconds locally). +- `bun run check:emulate`: passed; real Pi transport, eight partial snapshots, actual local tool execution, provider error, stream abort confirmed as `client_aborted`, strict rejection, no fallback, restored transcript on a new emulator endpoint, and occupied-listener preservation. +- `apps/docs` `bun run check`: passed; no doctor or link-validation problems. +- Tool formatting and Git whitespace checks: passed. +- Fallow audit: passed after registering subprocess entries; warnings remain for development-tool dependency classification and complexity. +- Isolated browser walkthrough: passed; no live provider credentials used. Watcher reload retained the account and transcript. SIGINT exited the development supervisor with code zero and both listeners were confirmed closed. +- Fresh-context review: the single data-directory containment defect was fixed and verified in a follow-up review. No remaining concrete findings were reported. CI itself was not run or changed. + +[emulate-package]: https://registry.npmjs.org/emulate/0.14.0 +[emulate-api]: https://unpkg.com/emulate@0.14.0/dist/api.d.ts +[emulate-runtime]: https://github.com/vercel-labs/emulate/blob/66dc87dda12fdfc3b389dbeffb298c5128fe53c4/package.json#L28 +[emulate-ai]: https://github.com/vercel-labs/emulate/blob/66dc87dda12fdfc3b389dbeffb298c5128fe53c4/apps/web/content/docs/ai.mdx diff --git a/package.json b/package.json index be18513a..6438ce1d 100644 --- a/package.json +++ b/package.json @@ -8,18 +8,23 @@ "apps/web" ], "devDependencies": { + "@earendil-works/pi-ai": "1.4.0", "@oxlint/plugins": "1.88.0", "@types/bun": "latest", "@types/node": "^26.6.6", + "emulate": "0.14.0", "fallow": "3.38.0", "oxlint": "1.88.0", "oxlint-plugin-effect": "^0.32.1", "oxlint-tsgolint": "7.0.2005", - "typescript": "7.0.2" + "typescript": "7.0.2", + "zod": "4.6.7" }, "scripts": { "prepare": "git rev-parse --git-dir >/dev/null 2>&1 && git config core.hooksPath .githooks || true", "dev": "bun --watch apps/server/src/app/server.ts --dev-workspaces", + "dev:emulate": "bun --no-env-file tools/dev-emulate.ts", + "check:emulate": "tsc -p tools && bun --no-env-file tools/check-emulate.ts", "start": "bun apps/server/src/app/server.ts", "test": "bun test --parallel", "typecheck": "tsc -p apps/server && tsc -p apps/web", diff --git a/tools/check-emulate.ts b/tools/check-emulate.ts new file mode 100644 index 00000000..4bc8c0eb --- /dev/null +++ b/tools/check-emulate.ts @@ -0,0 +1,595 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { z } from "zod"; +import { + agentResponse, + chatSnapshotResponse, + executionResponse, + modelResponse, + providerResponse, +} from "../apps/server/src/contract/api-responses"; +import { EMULATE_MODEL_IDS } from "../apps/server/src/providers/emulate-profile"; +import { + Type, + type AssistantMessage, + type Context, +} from "@earendil-works/pi-ai"; +import { emulateModels } from "../apps/server/src/providers/emulate"; +import { + startEmulate, + startLocalApp, + type LocalProcess, +} from "./emulate-process"; +import { + ERROR_TEXT, + REPLY_TEXT, + STREAM_TEXT, + TOOL_REPLY_TEXT, +} from "./emulate-scenarios"; + +const textOf = (message: AssistantMessage) => + message.content + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join(""); + +async function transportSmoke() { + const emulator = await startEmulate(); + + try { + const models = emulateModels(`${emulator.url}/v1`); + const model = models.getModel("emulate", "local-stream"); + assert(model); + + const context: Context = { + messages: [ + { role: "user", content: "local transport", timestamp: Date.now() }, + ], + }; + + const stream = models.streamSimple(model, context, { + signal: AbortSignal.timeout(15_000), + maxRetries: 0, + }); + + const deltas: string[] = []; + + for await (const event of stream) { + if (event.type === "text_delta") deltas.push(event.delta); + } + + const answer = await stream.result(); + assert.equal( + answer.stopReason, + "stop", + answer.errorMessage ?? "stream failed", + ); + assert(deltas.length > 1, "Pi must receive incremental content"); + assert.equal(deltas.join(""), STREAM_TEXT); + + const toolModel = models.getModel("emulate", "local-tool"); + assert(toolModel); + context.tools = [ + { + name: "history_search", + description: "Search local history", + parameters: Type.Object({ query: Type.Optional(Type.String()) }), + }, + ]; + + const first = await models.completeSimple(toolModel, context, { + signal: AbortSignal.timeout(15_000), + maxRetries: 0, + }); + + assert.equal( + first.stopReason, + "toolUse", + first.errorMessage ?? "tool call failed", + ); + const call = first.content.find((block) => block.type === "toolCall"); + assert(call?.type === "toolCall"); + assert.equal(call.name, "history_search"); + assert.deepEqual(call.arguments, { query: "local" }); + context.messages.push(first, { + role: "toolResult", + toolCallId: call.id, + toolName: call.name, + content: [{ type: "text", text: "[]" }], + isError: false, + timestamp: Date.now(), + }); + + const final = await models.completeSimple(toolModel, context, { + signal: AbortSignal.timeout(15_000), + maxRetries: 0, + }); + + assert.equal( + final.stopReason, + "stop", + final.errorMessage ?? "continuation failed", + ); + assert.equal(textOf(final), TOOL_REPLY_TEXT); + console.log("PASS real Pi streaming and tool-result continuation"); + } finally { + await emulator.close(); + } +} + +async function closeChildren(children: readonly LocalProcess[]) { + const closed = await Promise.allSettled( + children.toReversed().map((child) => child.close()), + ); + + const failures: unknown[] = []; + + for (const result of closed) { + if (result.status === "rejected") failures.push(result.reason); + } + + if (failures.length) + throw new AggregateError(failures, "Local smoke cleanup failed"); +} + +type Snapshot = z.infer; + +type SmokeRequest = Record; + +const authResponse = z.object({ token: z.string().min(1) }); + +const callsResponse = z.array( + z.object({ + model: z.string(), + status: z.number(), + fault: z.enum(["none", "stall", "disconnect"]), + delivery: z.enum(["pending", "completed", "client_aborted", "error"]), + matched: z.object({ id: z.string() }).nullable(), + }), +); + +async function request(url: string, init: RequestInit = {}, status = 200) { + const response = await fetch(url, { + ...init, + redirect: "error", + signal: AbortSignal.any([ + AbortSignal.timeout(20_000), + ...(init.signal ? [init.signal] : []), + ]), + }); + + assert.equal( + response.status, + status, + `${url}: ${response.status === status ? "" : await response.text()}`, + ); + + return response; +} + +async function until( + read: () => Promise, + accept: (value: T) => boolean, +): Promise { + const deadline = Date.now() + 20_000; + let last: T | undefined; + + do { + const value = await read(); + last = value; + + if (accept(value)) return value; + await delay(100); + } while (Date.now() < deadline); + + throw new Error( + `Local smoke wait exceeded 20 seconds: ${JSON.stringify(last)}`, + ); +} + +async function applicationSmoke() { + const dataDir = await mkdtemp(join(tmpdir(), "crumble-emulate-")); + const owned: LocalProcess[] = []; + const bots = new Map(); + const streams = new Set(); + let app: LocalProcess | undefined; + let token = ""; + + const credentials = { + name: "Local smoke", + email: `${crypto.randomUUID()}@example.test`, + password: "local-smoke-password", + }; + + const api = (path: string, body?: SmokeRequest, status = 200) => { + assert(app); + + const init: RequestInit = { + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json", + }, + }; + + if (body !== undefined) { + init.method = "POST"; + init.body = JSON.stringify(body); + } + + return request(`${app.url}${path}`, init, status); + }; + + const snapshot = async (id: string) => + chatSnapshotResponse.parse( + await (await api(`/v1/agents/${id}/chat`)).json(), + ); + + const send = async (id: string) => { + const requestId = crypto.randomUUID(); + + const receipt = executionResponse.parse( + await ( + await api( + `/v1/agents/${id}/messages`, + { content: "local smoke", requestId }, + 202, + ) + ).json(), + ); + + assert.equal(receipt.requestId, requestId); + assert.equal(receipt.agentId, id); + + return requestId; + }; + + const turn = async (id: string, expected: "done" | "failed" = "done") => { + const requestId = await send(id); + + const execution = await until( + async () => + executionResponse + .array() + .parse(await (await api(`/v1/executions?agentId=${id}`)).json()) + .find((entry) => entry.requestId === requestId), + (entry) => + !!entry && ["done", "failed", "cancelled"].includes(entry.status), + ); + + assert.equal( + execution?.status, + expected, + execution?.error ?? "Unexpected execution result", + ); + + return until( + () => snapshot(id), + (chat) => + chat.status !== "running" && + chat.messages.some((message) => message.requestId === requestId), + ); + }; + + const checkCatalog = async () => { + const providers = providerResponse + .array() + .parse(await (await api("/v1/providers")).json()); + + assert.deepEqual( + providers.map((provider) => [provider.provider, provider.configured]), + [["emulate", true]], + ); + + const models = modelResponse + .array() + .parse(await (await api("/v1/models")).json()); + + assert(models.every((model) => model.provider === "emulate")); + assert.deepEqual( + models.map((model) => model.id).sort(), + [...EMULATE_MODEL_IDS].sort(), + ); + }; + + const observe = async (id: string, accept: (chat: Snapshot) => boolean) => { + assert(app); + const controller = new AbortController(); + streams.add(controller); + let reader: ReadableStreamDefaultReader | undefined; + + try { + const response = await request( + `${app.url}/v1/agents/${id}/events?partial=true`, + { + headers: { authorization: `Bearer ${token}` }, + signal: controller.signal, + }, + ); + + assert.match( + response.headers.get("content-type") ?? "", + /text\/event-stream/, + ); + assert(response.body); + reader = response.body.getReader(); + await send(id); + const decoder = new TextDecoder(); + let buffer = ""; + + for (;;) { + const chunk: Awaited< + ReturnType["read"]> + > = await reader.read(); + + assert(!chunk.done, "Chat event stream ended before completion"); + buffer += decoder + .decode(chunk.value, { stream: true }) + .replaceAll("\r\n", "\n"); + let boundary: number; + + while ((boundary = buffer.indexOf("\n\n")) >= 0) { + const frame = buffer.slice(0, boundary); + buffer = buffer.slice(boundary + 2); + + if ( + !frame.split("\n").some((line) => line.trim() === "event: snapshot") + ) + continue; + + const data = frame + .split("\n") + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).trimStart()) + .join("\n"); + + const chat = chatSnapshotResponse.parse(JSON.parse(data)); + + if (accept(chat)) return chat; + } + } + } finally { + controller.abort(); + await reader?.cancel().catch(() => {}); + streams.delete(controller); + } + }; + + try { + let emulator = await startEmulate(); + owned.push(emulator); + app = await startLocalApp({ + baseUrl: `${emulator.url}/v1`, + dataDir, + port: 0, + }); + owned.push(app); + token = authResponse.parse( + await (await api("/api/auth/sign-up/email", credentials)).json(), + ).token; + await checkCatalog(); + + for (const model of EMULATE_MODEL_IDS) { + const bot = agentResponse.parse( + await ( + await api( + "/v1/agents", + { + name: model, + provider: "emulate", + model, + review: { enabled: false }, + }, + 201, + ) + ).json(), + ); + + bots.set(model, bot.id); + } + + const bot = (model: string) => { + const id = bots.get(model); + assert(id); + + return id; + }; + + const hasReply = (chat: Snapshot, text: string) => + chat.messages.some( + (message) => message.role === "assistant" && message.content === text, + ); + + assert(hasReply(await turn(bot("local-reply")), REPLY_TEXT)); + const partials = new Set(); + await observe(bot("local-stream"), (chat) => { + if (chat.partial && !hasReply(chat, STREAM_TEXT)) + partials.add(chat.partial); + + return chat.status === "idle" && hasReply(chat, STREAM_TEXT); + }); + assert( + partials.size >= 2, + `Expected distinct partial texts before completion, got ${partials.size}`, + ); + const toolChat = await turn(bot("local-tool")); + assert(hasReply(toolChat, TOOL_REPLY_TEXT)); + + const call = toolChat.messages + .flatMap((message) => message.blocks ?? []) + .find( + (block) => block.type === "toolCall" && block.name === "history_search", + ); + + assert(call?.type === "toolCall"); + assert.deepEqual(call.arguments, { query: "local" }); + + const result = toolChat.messages.find( + (message) => message.toolCallId === call.id, + ); + + assert( + result && + result.toolName === "history_search" && + result.content.trim() && + result.isError !== true, + "Missing successful actual history_search result", + ); + + const calls = async () => + callsResponse.parse( + await (await request(`${emulator.url}/_ai/calls`)).json(), + ); + + const toolCalls = (await calls()).filter( + (entry) => entry.model === "local-tool", + ); + + assert.deepEqual( + toolCalls.map((entry) => [entry.matched?.id, entry.status]), + [ + ["local-tool-call", 200], + ["local-tool-result", 200], + ], + ); + const failed = await turn(bot("local-error"), "failed"); + assert.equal(failed.status, "idle"); + assert(!failed.messages.some((message) => message.role === "assistant")); + assert(failed.error?.includes(ERROR_TEXT)); + await send(bot("local-stall")); + await until( + () => snapshot(bot("local-stall")), + (chat) => chat.status === "running", + ); + await until(calls, (entries) => + entries.some((entry) => entry.model === "local-stall"), + ); + await api(`/v1/agents/${bot("local-stall")}/abort`, {}, 204); + + const stopped = await until( + () => snapshot(bot("local-stall")), + (chat) => chat.status !== "running", + ); + + assert.equal(stopped.working, "idle", "Aborted bot is still working"); + await until(calls, (entries) => + entries.some( + (entry) => + entry.model === "local-stall" && + entry.status === 200 && + entry.fault === "stall" && + entry.delivery === "client_aborted", + ), + ); + + const unknown = await request( + `${emulator.url}/v1/chat/completions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + model: "unknown-local-model", + messages: [{ role: "user", content: "local" }], + }), + }, + 400, + ); + + assert((await unknown.text()).length > 0); + await emulator.close(); + const unavailable = await turn(bot("local-reply"), "failed"); + assert.equal(unavailable.status, "idle"); + assert(unavailable.error); + assert.equal( + unavailable.messages.filter( + (message) => + message.role === "assistant" && message.content === REPLY_TEXT, + ).length, + 1, + "Unavailable emulator must not produce a fallback reply", + ); + await app.close(); + const oldUrl = emulator.url; + emulator = await startEmulate(); + owned.push(emulator); + assert.notEqual( + emulator.url, + oldUrl, + "Restart must exercise a different emulator port", + ); + app = await startLocalApp({ + baseUrl: `${emulator.url}/v1`, + dataDir, + port: 0, + }); + owned.push(app); + token = authResponse.parse( + await (await api("/api/auth/sign-in/email", credentials)).json(), + ).token; + await checkCatalog(); + assert( + hasReply(await snapshot(bot("local-reply")), REPLY_TEXT), + "Saved transcript was not restored", + ); + const restored = await turn(bot("local-reply")); + assert.equal(restored.status, "idle"); + assert.equal( + restored.messages.filter( + (message) => + message.role === "assistant" && message.content === REPLY_TEXT, + ).length, + 2, + ); + assert( + (await calls()).some( + (entry) => + entry.model === "local-reply" && entry.matched?.id === "local-reply", + ), + "Restored bot did not use the new endpoint", + ); + + const listener = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch: () => new Response("pre-existing listener"), + }); + + try { + const port = listener.port; + assert(port); + await assert.rejects(async () => { + const unexpected = await startLocalApp({ + baseUrl: `${emulator.url}/v1`, + dataDir: join(dataDir, "occupied"), + port, + }); + + owned.push(unexpected); + }, /exited before readiness/); + assert.equal( + await (await request(`http://127.0.0.1:${listener.port}`)).text(), + "pre-existing listener", + ); + } finally { + await listener.stop(true); + } + + console.log( + `PASS authenticated app: five models, fixed reply, ${partials.size} streamed partials, history_search, provider error, abort, strict mismatch, no fallback, restart persistence/new endpoint, occupied-port preservation`, + ); + } finally { + for (const stream of streams) stream.abort(); + + if (app) + await Promise.allSettled( + [...bots.values()].map((id) => api(`/v1/agents/${id}/abort`, {}, 204)), + ); + await closeChildren(owned); + await rm(dataDir, { recursive: true, force: true }); + } +} + +await transportSmoke(); + +await applicationSmoke(); diff --git a/tools/dev-emulate.ts b/tools/dev-emulate.ts new file mode 100644 index 00000000..2b276260 --- /dev/null +++ b/tools/dev-emulate.ts @@ -0,0 +1,75 @@ +import { resolve } from "node:path"; +import { EMULATE_MODEL_IDS } from "../apps/server/src/providers/emulate-profile"; +import { + REPOSITORY_DIR, + startEmulate, + startLocalApp, + type LocalProcess, +} from "./emulate-process"; + +const pending: Promise[] = []; +const interrupted = Promise.withResolvers(); +let stopping = false; +let closing: Promise | undefined; + +const close = () => + (closing ??= (async () => { + const settled = await Promise.allSettled(pending); + await Promise.all( + settled.flatMap((item) => + item.status === "fulfilled" ? [item.value.close()] : [], + ), + ); + })()); + +const stop = () => { + stopping = true; + interrupted.resolve(); +}; + +process.once("SIGINT", stop); + +process.once("SIGTERM", stop); + +try { + const emulatorStarting = startEmulate(); + pending.push(emulatorStarting); + const emulator = await emulatorStarting; + + if (!stopping) { + const dataDir = resolve(REPOSITORY_DIR, ".cache/emulate/data"); + + const appStarting = startLocalApp({ + baseUrl: `${emulator.url}/v1`, + dataDir, + port: 7338, + watch: true, + }); + + pending.push(appStarting); + const app = await appStarting; + + if (!stopping) { + console.log(`Crumble: ${app.url}`); + console.log(`Emulate: ${emulator.url}`); + console.log(`Local data: ${dataDir}`); + console.log(`Scenarios: ${EMULATE_MODEL_IDS.join(", ")}`); + console.log( + "Create a local account, then choose Emulate (local) when creating a bot. Ctrl+C stops both services.", + ); + await Promise.race([ + interrupted.promise, + app.exited.then(() => { + throw new Error("The local Crumble process exited"); + }), + emulator.exited.then(() => { + throw new Error("The AI emulator exited"); + }), + ]); + } + } +} finally { + await close(); + process.removeListener("SIGINT", stop); + process.removeListener("SIGTERM", stop); +} diff --git a/tools/emulate-process.test.ts b/tools/emulate-process.test.ts new file mode 100644 index 00000000..2ed830ac --- /dev/null +++ b/tools/emulate-process.test.ts @@ -0,0 +1,27 @@ +import { expect, test } from "bun:test"; +import { localEnvironment } from "./emulate-process"; + +test("local child environments exclude installation, provider and preload configuration", () => { + expect( + localEnvironment({ + PATH: "/bin", + HOME: "/tmp/local-home", + TMPDIR: "/tmp", + LANG: "en_US.UTF-8", + CRUMBLE_DATA_DIR: "/ordinary-data", + CRUMBLE_PUBLIC_URL: "https://example.test", + CRUMBLE_FCM_SERVICE_ACCOUNT_PATH: "/private/key.json", + BETTER_AUTH_URL: "https://example.test", + OPENAI_API_KEY: "dummy-not-forwarded", + ANTHROPIC_API_KEY: "dummy-not-forwarded", + BUN_OPTIONS: "--preload=unwanted.ts", + NODE_OPTIONS: "--require=unwanted.cjs", + HTTPS_PROXY: "http://example.test", + }), + ).toEqual({ + PATH: "/bin", + HOME: "/tmp/local-home", + TMPDIR: "/tmp", + LANG: "en_US.UTF-8", + }); +}); diff --git a/tools/emulate-process.ts b/tools/emulate-process.ts new file mode 100644 index 00000000..2720f42c --- /dev/null +++ b/tools/emulate-process.ts @@ -0,0 +1,195 @@ +import { spawn, spawnSync } from "node:child_process"; +import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; +import { setTimeout as delay } from "node:timers/promises"; +import { z } from "zod"; + +const readiness = z.object({ type: z.literal("ready"), url: z.url() }); +const missingProcess = z.object({ code: z.literal("ESRCH") }); + +export const REPOSITORY_DIR = fileURLToPath(new URL("../", import.meta.url)); + +export function localEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return Object.fromEntries( + [ + "PATH", + "HOME", + "TMPDIR", + "TMP", + "TEMP", + "LANG", + "LC_ALL", + "TERM", + "SystemRoot", + ].flatMap((key) => (env[key] === undefined ? [] : [[key, env[key]]])), + ); +} + +export type LocalProcess = { + url: string; + exited: Promise; + close(): Promise; +}; + +async function startProcess( + command: string, + args: string[], +): Promise { + const child = spawn(command, args, { + cwd: REPOSITORY_DIR, + env: localEnvironment(process.env), + detached: process.platform !== "win32", + stdio: ["ignore", "pipe", "pipe"], + }); + + const ready = Promise.withResolvers(); + const exit = Promise.withResolvers(); + const lines = createInterface({ input: child.stdout }); + child.stderr.pipe(process.stderr, { end: false }); + + const timeout = setTimeout( + () => + ready.reject( + new Error("Local service startup timed out after 10 seconds"), + ), + 10_000, + ); + + child.once("error", (error) => { + ready.reject(error); + exit.resolve(null); + }); + child.once("exit", (code, signal) => { + ready.reject( + new Error(`Local service exited before readiness (${code ?? signal})`), + ); + exit.resolve(code); + }); + lines.on("line", (line: string) => { + try { + const record = readiness.safeParse(JSON.parse(line)); + + if (!record.success) { + console.error(line); + + return; + } + + const url = new URL(record.data.url); + + if ( + url.protocol !== "http:" || + url.hostname !== "127.0.0.1" || + !url.port || + url.username || + url.password + ) + throw new Error("Local service returned a non-loopback address"); + ready.resolve(url.origin); + } catch { + console.error(line); + } + }); + let closing: Promise | undefined; + + const signal = (value: NodeJS.Signals | 0) => { + if (!child.pid) return; + + try { + if (process.platform === "win32") child.kill(value); + else process.kill(-child.pid, value); + } catch (error) { + if (!missingProcess.safeParse(error).success) throw error; + } + }; + + const close = () => + (closing ??= (async () => { + const deadline = Date.now() + 5_000; + signal("SIGTERM"); + let killTimer: ReturnType | undefined; + + try { + await Promise.race([ + exit.promise, + new Promise((resolve) => { + killTimer = setTimeout(() => { + signal("SIGKILL"); + resolve(); + }, 5_000); + }), + ]); + await exit.promise; + + if (process.platform !== "win32" && child.pid) { + const pid = child.pid; + + const groupExists = () => { + try { + process.kill(-pid, 0); + + return true; + } catch (error) { + if (!missingProcess.safeParse(error).success) throw error; + + return false; + } + }; + + while (groupExists() && Date.now() < deadline) await delay(25); + + if (groupExists()) signal("SIGKILL"); + } + } finally { + clearTimeout(killTimer); + lines.close(); + } + })()); + + try { + return { url: await ready.promise, exited: exit.promise, close }; + } catch (error) { + await close(); + throw error; + } finally { + clearTimeout(timeout); + } +} + +export async function startEmulate(): Promise { + const version = spawnSync("node", ["--version"], { + env: localEnvironment(process.env), + encoding: "utf8", + timeout: 3_000, + }); + + if ( + version.error || + version.status !== 0 || + Number(/^v(\d+)/.exec(version.stdout)?.[1] ?? 0) < 24 + ) + throw new Error( + "Emulate needs Node 24 or later on PATH. Install Node, then run this command again.", + ); + + return startProcess("node", [ + "--experimental-strip-types", + "tools/emulate-service.ts", + ]); +} + +export function startLocalApp(options: { + baseUrl: string; + dataDir: string; + port: number; + watch?: boolean; +}): Promise { + const { watch, ...profile } = options; + + return startProcess(process.execPath, [ + "--no-env-file", + ...(watch ? ["--watch", "--watch-kill-signal=SIGTERM"] : []), + "tools/emulate-server.ts", + JSON.stringify(profile), + ]); +} diff --git a/tools/emulate-scenarios.ts b/tools/emulate-scenarios.ts new file mode 100644 index 00000000..40e0b6a1 --- /dev/null +++ b/tools/emulate-scenarios.ts @@ -0,0 +1,69 @@ +import { EMULATE_MODEL_IDS } from "../apps/server/src/providers/emulate-profile.ts"; + +export const REPLY_TEXT = "Local reply."; + +export const STREAM_TEXT = + "This reply is streamed locally without live credentials."; + +export const TOOL_REPLY_TEXT = "Local tool finished."; +export const ERROR_TEXT = "Scripted local provider error."; + +export const EMULATE_SEED = { + ai: { + strict: true, + models: [...EMULATE_MODEL_IDS], + rules: [ + { + id: "local-reply", + match: { model: "local-reply", format: "openai-chat" }, + reply: [{ type: "text", text: REPLY_TEXT }], + }, + { + id: "local-stream", + match: { model: "local-stream", format: "openai-chat" }, + reply: [{ type: "text", text: STREAM_TEXT }], + timing: { chunkDelayMs: 150 }, + }, + { + id: "local-tool-call", + match: { + model: "local-tool", + format: "openai-chat", + hasToolResult: false, + tool: "history_search", + }, + reply: [ + { + type: "tool_call", + name: "history_search", + arguments: { query: "local" }, + }, + ], + }, + { + id: "local-tool-result", + match: { + model: "local-tool", + format: "openai-chat", + hasToolResult: true, + }, + reply: [{ type: "text", text: TOOL_REPLY_TEXT }], + }, + { + id: "local-error", + match: { model: "local-error", format: "openai-chat" }, + error: { status: 400, message: ERROR_TEXT }, + }, + { + id: "local-stall", + match: { + model: "local-stall", + format: "openai-chat", + stream: true, + }, + reply: [{ type: "text", text: STREAM_TEXT }], + fault: { kind: "stall", afterChunks: 1, stallMs: 30000 }, + }, + ], + }, +}; diff --git a/tools/emulate-server.ts b/tools/emulate-server.ts new file mode 100644 index 00000000..050682ad --- /dev/null +++ b/tools/emulate-server.ts @@ -0,0 +1,33 @@ +import { z } from "zod"; +import { startServer } from "../apps/server/src/app/server"; + +const options = z + .object({ + baseUrl: z.string(), + dataDir: z.string().min(1), + port: z.number().int().min(0).max(65535), + }) + .parse(JSON.parse(process.argv[2] ?? "{}")); + +const running = await startServer({ + dataDir: options.dataDir, + hostname: "127.0.0.1", + port: options.port, + workspaceEnv: {}, + emulate: { baseUrl: options.baseUrl }, +}); + +console.log(JSON.stringify({ type: "ready", url: running.server.url.origin })); + +let closing = false; + +const close = async () => { + if (closing) return; + closing = true; + await running.close(); + process.exit(0); +}; + +process.once("SIGINT", close); + +process.once("SIGTERM", close); diff --git a/tools/emulate-service.ts b/tools/emulate-service.ts new file mode 100644 index 00000000..85e18015 --- /dev/null +++ b/tools/emulate-service.ts @@ -0,0 +1,28 @@ +import { createEmulator } from "emulate"; +import { EMULATE_SEED } from "./emulate-scenarios.ts"; + +const emulator = await createEmulator({ + service: "ai", + hostname: "127.0.0.1", + port: 0, + seed: EMULATE_SEED, +}); + +const url = new URL(emulator.url); + +url.hostname = "127.0.0.1"; + +console.log(JSON.stringify({ type: "ready", url: url.origin })); + +let closing = false; + +const close = async () => { + if (closing) return; + closing = true; + await emulator.close(); + process.exit(0); +}; + +process.once("SIGINT", close); + +process.once("SIGTERM", close); From 17ad18d9c989e6f990a1903d23b822711e12912d Mon Sep 17 00:00:00 2001 From: Leonhard Breuer Date: Sun, 22 Nov 2026 20:13:52 +0100 Subject: [PATCH 2/2] chore(tooling): remove fallow integration --- .fallowrc.json | 95 ------------------- .githooks/pre-commit | 1 - .githooks/pre-push | 2 - .github/workflows/fallow.yml | 60 ------------ CHANGELOG.md | 1 + CONTRIBUTING.md | 4 +- apps/docs/content/contributing/index.md | 10 +- bun.lock | 3 - docs/architecture.md | 2 +- .../2026-11-21-emulate-local-development.md | 3 +- package.json | 1 - 11 files changed, 10 insertions(+), 172 deletions(-) delete mode 100644 .fallowrc.json delete mode 100644 .github/workflows/fallow.yml diff --git a/.fallowrc.json b/.fallowrc.json deleted file mode 100644 index f2d131ec..00000000 --- a/.fallowrc.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json", - // Run by drizzle-kit, spawned by tests by path, run as `bun tools/...`, or loaded by Blume, Panda, or TanStack Start by file name. - "entry": [ - "apps/server/drizzle.*.config.ts", - "apps/server/test/fixtures/*.ts", - "apps/server/tools/*.ts", - "tools/emulate-server.ts", - "tools/emulate-service.ts", - "apps/docs/blume.config.ts", - "apps/docs/theme.css", - "apps/docs/content/**/*.{ts,mdx}", - "apps/site/panda.config.ts" - ], - "workspaces": { - "patterns": ["apps/docs", "apps/site"] - }, - // Vendored oxlint plugins; tools/oxlint/anti-slop/UPSTREAM.md tracks them by checksum, so they stay as upstream wrote them. - // The workspace image's files reach guests through its Dockerfile and the Railway upload, not through imports. - // The shadcn stylesheet is copied from npm; its clone groups have no SARIF location, which Code Scanning rejects. - "ignorePatterns": [ - "tools/oxlint/**", - "apps/server/workspace-image/**", - "apps/web/shadcn-tailwind.css" - ], - // Imported only by the ignored oxlint plugins. - "ignoreDependencies": ["@oxlint/plugins"], - // Generated by `panda codegen` on apps/site's install, so it is absent in a root-only checkout. - "ignoreUnresolvedImports": ["styled-system/*"], - // Same route wiring for two features: Hono types each handler by its route, so sharing more loses those types. - // A clone group has no SARIF location, which Code Scanning rejects, so a kept clone must be ignored here. - "duplicates": { - "ignore": [ - "apps/server/src/credentials/credentials-api.ts", - "apps/server/src/logins/logins-api.ts" - ] - }, - "ignoreFindings": ["apps/web/components/ui/**"], - "ignoreExportsUsedInFile": true, - // The stylesheet's `:where()` lists keep markdown rules at zero specificity, and reduced motion needs !important to beat every animation. - // Panda fills the site's declared @layers at build time, so Fallow reports them as unused. - "rules": { - "boundary-violation": "error", - "css-selector-complexity": "off", - "css-dead-surface": "off" - }, - "boundaries": { - // A file joins the first zone it matches; tests boot the whole app, so they match first and stay unrestricted. - "zones": [ - { "name": "tests", "patterns": ["apps/**/*.test.ts", "apps/**/*.test.tsx"] }, - { "name": "app", "patterns": ["apps/server/src/app/**"] }, - { "name": "shared", "patterns": ["apps/server/src/shared/**"] }, - { "name": "contract", "patterns": ["apps/server/src/contract/**"] }, - { "name": "workspaces", "patterns": ["apps/server/src/workspaces/**"] }, - // Below features: the store and the ports let features reach bots without importing the runtime above them. - { "name": "bot-store", "patterns": ["apps/server/src/bot-store/**"] }, - { "name": "bot-ports", "patterns": ["apps/server/src/bot-ports/**"] }, - { "name": "learned-changes", "patterns": ["apps/server/src/learned-changes/**"] }, - { "name": "features", "patterns": ["apps/server/src/**"] }, - // Web, leaf first: a feature's api.ts is importable by every feature, the chat kernel by features, and the bot chat assembles features. - { "name": "web-base", "patterns": ["apps/web/lib/**", "apps/web/components/**", "apps/web/hooks/**"] }, - { "name": "web-api", "patterns": ["apps/web/features/*/api.ts"] }, - { "name": "web-chat", "patterns": ["apps/web/features/chat/**"] }, - { "name": "web-bot-chat", "patterns": ["apps/web/features/bot-chat/**"] }, - { "name": "web-features", "patterns": ["apps/web/features/**"] }, - { "name": "web", "patterns": ["apps/web/**"] } - ], - "rules": [ - { "from": "shared", "allow": [] }, - { "from": "contract", "allow": ["shared"] }, - { "from": "workspaces", "allow": ["shared"] }, - { "from": "bot-store", "allow": ["shared", "contract"] }, - { "from": "bot-ports", "allow": ["shared", "contract"] }, - { "from": "learned-changes", "allow": ["shared", "contract", "bot-store"] }, - { "from": "features", "allow": ["shared", "contract", "workspaces", "bot-store", "bot-ports", "learned-changes"] }, - { "from": "web-base", "allow": ["contract"] }, - { "from": "web-api", "allow": ["web-base", "contract"] }, - { "from": "web-chat", "allow": ["web-api", "web-base", "contract"] }, - { "from": "web-features", "allow": ["web-chat", "web-api", "web-base", "contract"] }, - { "from": "web-bot-chat", "allow": ["web-features", "web-chat", "web-api", "web-base", "contract"] }, - { "from": "web", "allow": ["web-bot-chat", "web-features", "web-chat", "web-api", "web-base", "contract"] } - ] - }, - "health": { - // A describe() callback counts every test inside it, so test length says nothing about risk. - "ignore": ["apps/**/*.test.ts", "apps/**/*.test.tsx"] - }, - "overrides": [ - { - // The server serves the web UI's bundle, and the web UI imports only the server's API types; nothing builds packages in dependency order. - "files": ["apps/server/src/app/web-ui.ts", "apps/web/lib/api.ts"], - "rules": { "package-cycle": "off" } - } - ] -} diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 01207cc4..ede070de 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -7,4 +7,3 @@ bun run agents:check bun run lint bun run format:check bun run typecheck -bunx fallow audit --base HEAD diff --git a/.githooks/pre-push b/.githooks/pre-push index bce34b57..9c539c3c 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -33,8 +33,6 @@ base=$(git rev-parse origin/main) bun run check -bunx fallow audit --base "$base" - changed=$(git diff --name-only "$base" HEAD) if printf '%s\n' "$changed" | grep -q '^apps/docs/'; then (cd apps/docs && bun install --frozen-lockfile && bun --bun run check && bun --bun run build) diff --git a/.github/workflows/fallow.yml b/.github/workflows/fallow.yml deleted file mode 100644 index efa62f3b..00000000 --- a/.github/workflows/fallow.yml +++ /dev/null @@ -1,60 +0,0 @@ -name: Fallow - -on: - pull_request: - push: - branches: [main] - -permissions: - contents: read - -jobs: - audit: - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: read - pull-requests: write - checks: write - security-events: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - # The audit compares against the base commit, so it needs the history. - fetch-depth: 0 - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version-file: .bun-version - - run: bun install --frozen-lockfile - # Only findings this change introduces fail; the repository's older ones are reported as inherited. - - uses: fallow-rs/fallow@d052786ef2baf78fa5b196f06dbccd6f0d26798e # v3.38.1 - id: fallow - with: - command: audit - args: --base ${{ github.event.pull_request.base.sha || github.event.before }} - auto-changed-since: false - format: sarif - sarif: false - comment: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }} - branded-token: false - # Fallow audit emits multiple runs; Code Scanning requires a category for each - # and rejects results without a location, which the PR comment still reports. - - name: Assign SARIF run categories - id: sarif - if: always() && steps.fallow.outputs.sarif != '' - env: - SARIF_FILE: ${{ steps.fallow.outputs.sarif }} - run: | - jq '.runs |= (to_entries | map( - .key as $index | .value | - .automationDetails.id = ("fallow/audit/" + ($index | tostring) + "/") | - .results = ((.results // []) | map(select((.locations // []) | length > 0))) - ))' "$SARIF_FILE" > fallow-upload.sarif - - name: Upload SARIF - if: >- - always() && steps.sarif.outcome == 'success' && - (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) - uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 - with: - sarif_file: fallow-upload.sarif diff --git a/CHANGELOG.md b/CHANGELOG.md index 27f84027..8ca09305 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Remove Fallow from development dependencies, Git hooks, and CI. Lint, formatting, type checks, tests, and documentation checks remain in place. - Add `bun run dev:emulate` for credential-free local bot chat with scripted replies, streaming, tool calls, errors, and cancellation. Run emulator-backed verification separately with the local-only `bun run check:emulate` command. - Bot avatars show what their bot is doing, using `open-bot-avatar` 0.3.0: three hopping dots while it thinks, bent over the work while it writes, searches, remembers, or uses tools, an exclamation mark while it retries, a short celebration when a reply finishes, and waiting in a group chat while it answers next. Live avatars ease from one state to the next instead of restarting. The `/avatars` page previews every state. Paused bots and disabled automations no longer show a dimmed, still avatar. - **Settings** > **Providers** has a **Usage** tab: tokens and cost for each model across all of the account's bots, grouped by provider, and for tools that call a model of their own, with totals. `GET /v1/usage` returns the same figures. Job panes now include tool costs, such as intent checks, in their cost. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index da65a320..23dd8a2b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -163,9 +163,9 @@ The `commit-msg` hook checks each commit, and the PR title workflow checks pull `bun install` configures Git to use [`.githooks/`](.githooks). Skip a hook once with `--no-verify`. -- **`pre-commit`:** checks the Bun version, runs `agents:check`, `lint`, `format:check`, and `typecheck` on the whole tree, and runs `fallow audit` on changes since `HEAD`. +- **`pre-commit`:** checks the Bun version, runs `agents:check`, `lint`, `format:check`, and `typecheck` on the whole tree. - **`commit-msg`:** rejects a commit whose subject isn't a Conventional Commit. Merge, revert, `fixup!`, `squash!`, and `amend!` commits that Git writes are allowed. -- **`pre-push`:** refuses the push if the working tree has uncommitted or untracked files, or if the pushed branch isn't checked out. It then runs the full PR suite against `origin/main`: `bun install --frozen-lockfile`, `bun run check`, `fallow audit`, and `apps/docs` / `apps/site` builds when those directories changed. +- **`pre-push`:** refuses the push if the working tree has uncommitted or untracked files, or if the pushed branch isn't checked out. It then runs the full PR suite against `origin/main`: `bun install --frozen-lockfile`, `bun run check`, and `apps/docs` / `apps/site` builds when those directories changed. ## Database migrations diff --git a/apps/docs/content/contributing/index.md b/apps/docs/content/contributing/index.md index 16a38d9f..ef9d3abd 100644 --- a/apps/docs/content/contributing/index.md +++ b/apps/docs/content/contributing/index.md @@ -93,11 +93,11 @@ bun run ui:add COMPONENT # add a shadcn/ui component to apps/web hooks require the Bun version in `.bun-version`, which CI also uses. Skip them once with `--no-verify`: -| Hook | Runs | -| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Commit | Generates and stages OpenAPI artifacts from staged sources, then runs the steering-file path check, lint, format check, and typecheck on the whole tree, and `fallow audit` on the changes since the last commit. | -| Commit message | Rejects a commit subject that isn't a Conventional Commit, such as `feat(web): add bot avatars`. Pull request titles get the same check in CI. | -| Push | Runs the PR checks against the pushed commit and a freshly fetched `origin/main` (`bun install --frozen-lockfile`, `bun run check`, contract validation and compatibility, `fallow audit`, and `apps/docs` / `apps/site` when changed). Refuses dirty trees or un-checked-out branches. | +| Hook | Runs | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Commit | Generates and stages OpenAPI artifacts from staged sources, then runs the steering-file path check, lint, format check, and typecheck on the whole tree. | +| Commit message | Rejects a commit subject that isn't a Conventional Commit, such as `feat(web): add bot avatars`. Pull request titles get the same check in CI. | +| Push | Runs the PR checks against the pushed commit and a freshly fetched `origin/main` (`bun install --frozen-lockfile`, `bun run check`, contract validation and compatibility, and `apps/docs` / `apps/site` when changed). Refuses dirty trees or un-checked-out branches. | Unit test jobs in CI must finish in two minutes or less. diff --git a/bun.lock b/bun.lock index f4f12eb8..d847c205 100644 --- a/bun.lock +++ b/bun.lock @@ -10,7 +10,6 @@ "@types/bun": "latest", "@types/node": "^26.6.6", "emulate": "0.14.0", - "fallow": "3.38.0", "oxlint": "1.88.0", "oxlint-plugin-effect": "^0.32.1", "oxlint-tsgolint": "7.0.2005", @@ -736,8 +735,6 @@ "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], - "fallow": ["fallow@3.38.0", "", { "dependencies": { "detect-libc": "2.1.2" }, "optionalDependencies": { "@fallow-cli/darwin-arm64": "3.38.0", "@fallow-cli/darwin-x64": "3.38.0", "@fallow-cli/linux-arm64-gnu": "3.38.0", "@fallow-cli/linux-arm64-musl": "3.38.0", "@fallow-cli/linux-x64-gnu": "3.38.0", "@fallow-cli/linux-x64-musl": "3.38.0", "@fallow-cli/win32-arm64-msvc": "3.38.0", "@fallow-cli/win32-x64-msvc": "3.38.0", "fallow-type-aware": "3.38.0" }, "bin": { "fallow": "bin/fallow", "fallow-lsp": "bin/fallow-lsp", "fallow-mcp": "bin/fallow-mcp" } }, "sha512-7bPRDOle89CR1qvm3Usp/KVtSthVYXPvnEk0znOl1eTmo/mMCjuZ/F4WuW6dVgzBH6saHvli+X37p17oQrxeXQ=="], - "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-sha256": ["fast-sha256@1.3.0", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="], diff --git a/docs/architecture.md b/docs/architecture.md index 1a862b97..647a1391 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -21,7 +21,7 @@ Source files named below live in feature folders under `apps/server/src/`, such - **Admins and server settings (`admin-api.ts`, `invites.ts`, `server-settings.ts`):** Better Auth's `admin` plugin adds user roles; its own `/api/auth/admin/*` routes are closed, and the host answers `/v1/admin/*` itself before any account runtime. The first user becomes admin in a `user.create.before` database hook, which is also the one gate for closed sign-up: an email sign-up needs an open invite in `x-crumble-invite`, and a passkey-only sign-up (passkey plugin with `requireSession: false`) checks and spends its invite in `afterVerification`. Server settings and invites are tables of `auth.sqlite`, added through a schema-only Better Auth plugin; queries inside a sign-up go through `getCurrentAdapter`, since SQLite would wait forever on the sign-up's own transaction. Each account runtime reads workspace size, coding image, and question grace period through a function the host passes in. - **Product store (repositories) vs. Pi Durable (`runtime.ts`):** Product SQLite (`store.sqlite`), read and written through each feature's Drizzle repository, stores agent profiles, canonical chat references, group chats, memories, skill packages, learned-change logs, schedules, MCP servers, and encrypted credentials. Each bot owns a separate Pi Durable SQLite store that manages conversation entries, model calls, tool execution, compaction, and retries. -- **Layers below features (`bot-store/`, `bot-ports/`, `learned-changes/`):** `bot-store/` holds the rows of bots, conversations, executions, and automations; `bot-ports/` holds what features use to reach the bot runtime without importing it, such as `BotExtensions` and `BotNotices`; `learned-changes/` records changes, so `memory/` and `skills/` never depend on `learning/`, the reviews above them. Fallow zones keep all three from importing `bots/` or any other feature. The skill library sits above the store, so `AgentRepository` reads a bot's skills through the `AgentSkills` port. +- **Layers below features (`bot-store/`, `bot-ports/`, `learned-changes/`):** `bot-store/` holds the rows of bots, conversations, executions, and automations; `bot-ports/` holds what features use to reach the bot runtime without importing it, such as `BotExtensions` and `BotNotices`; `learned-changes/` records changes, so `memory/` and `skills/` never depend on `learning/`, the reviews above them. All three sit below `bots/` and the other feature modules. The skill library sits above the store, so `AgentRepository` reads a bot's skills through the `AgentSkills` port. - **Effect services (`app/tenant.ts`):** Each account is one Effect `Layer` graph: repositories over `ProductDatabase`, then feature services such as `Bots`, `BotRuntime`, `GroupChats`, `BotSkills`, `Scheduler`, and `Push`, each with its own scope. Features offer their bot tools by registering them in `BotExtensions` from a layer of their own. Closing the account releases the graph in reverse. Domain failures are tagged errors (`shared/errors.ts`) that the API maps to HTTP statuses in one place; HTTP handlers reach services through access adapters (`botsAccess`, `groupChatsAccess`, and similar), which keep a Promise API at the Hono boundary. `createAPI` reads the services its routes need from the account's Context and registers every feature's routes from one list (`featureRoutes`); the store's Drizzle config collects each folder's `schema.ts` and `schema..ts` ([ADR 0008](adr/0008-feature-wiring.md)). - **Provider credentials (`provider-auth.ts`):** Encrypted at rest using the account's key: `.secret.key`, or `.secret.key.wrapped` sealed with `CRUMBLE_MASTER_KEY` when set. Pi AI owns interactive sign-in, token refresh, and request authentication; `ProviderCredentials` serializes logins, refreshes, key updates, and sign-outs per provider within the account. - **MCP integrations:** Bots load tools only from enabled, permitted MCP servers. Unreachable or unauthenticated MCP servers are skipped for the turn with their error surfaced in status. OAuth supports dynamic client registration, Client ID Metadata Documents (`CRUMBLE_PUBLIC_URL`), and owner-registered OAuth client credentials. diff --git a/docs/plans/2026-11-21-emulate-local-development.md b/docs/plans/2026-11-21-emulate-local-development.md index 5b0469a7..0c42fe73 100644 --- a/docs/plans/2026-11-21-emulate-local-development.md +++ b/docs/plans/2026-11-21-emulate-local-development.md @@ -131,7 +131,7 @@ Faux replacement, CI policy changes, other service emulators, real model inferen - Task 3 ยท verified signup, provider selection, streaming, tool reply, provider error, Stop, fixed reply, and persistence across watcher reload in an isolated headless Helium profile. UI interactions and same-origin API submissions used only the generated local account. A screenshot is kept under ignored `.cache/emulate/`. - Task 4 ยท failed executions produce an idle chat snapshot with `error`, not a snapshot whose status is `failed`. The smoke command correlates execution status by request ID and separately checks the transcript/error. It also confirms the stalled HTTP stream records `client_aborted`. - Task 4 ยท additional temporary local lifecycle checks verified preserved occupied listeners, failed-start cleanup, idempotent close, closed listeners, and an actionable missing-Node error. -- Shipping checks ยท registered the two subprocess entry points in `.fallowrc.json`, since they are launched by path rather than imported. No analysis rule was disabled. +- Follow-up ยท removed Fallow's repository integration at the owner's request. The canceled metric-only refactors were not retained; other checks remain unchanged. ## Verification results @@ -140,7 +140,6 @@ Faux replacement, CI policy changes, other service emulators, real model inferen - `bun run check:emulate`: passed; real Pi transport, eight partial snapshots, actual local tool execution, provider error, stream abort confirmed as `client_aborted`, strict rejection, no fallback, restored transcript on a new emulator endpoint, and occupied-listener preservation. - `apps/docs` `bun run check`: passed; no doctor or link-validation problems. - Tool formatting and Git whitespace checks: passed. -- Fallow audit: passed after registering subprocess entries; warnings remain for development-tool dependency classification and complexity. - Isolated browser walkthrough: passed; no live provider credentials used. Watcher reload retained the account and transcript. SIGINT exited the development supervisor with code zero and both listeners were confirmed closed. - Fresh-context review: the single data-directory containment defect was fixed and verified in a follow-up review. No remaining concrete findings were reported. CI itself was not run or changed. diff --git a/package.json b/package.json index 6438ce1d..aadf3280 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,6 @@ "@types/bun": "latest", "@types/node": "^26.6.6", "emulate": "0.14.0", - "fallow": "3.38.0", "oxlint": "1.88.0", "oxlint-plugin-effect": "^0.32.1", "oxlint-tsgolint": "7.0.2005",