# Agent quickstart Source: https://docs.tuturuuu.com/agents/quickstart Read the public docs, locate repository code, and follow contribution conventions. ## Read the docs * Start with [llms.txt](https://docs.tuturuuu.com/llms.txt) for a page index. * Append `.md` to a page URL for Markdown. For example, read the [documenting guide as Markdown](https://docs.tuturuuu.com/build/development-tools/documenting.md). * Connect an MCP client to `https://docs.tuturuuu.com/mcp` and use `search_tuturuuu_docs` to search public documentation. The endpoint accepts MCP POST requests; a browser GET is not a connectivity test. ## Repository map The [platform repository](https://github.com/tutur3u/platform) separates application entrypoints from shared libraries. | Directory | Purpose | | - | - | | `apps/` | Product applications, the docs site, and supporting services. | | `packages/` | Shared domain libraries, UI, SDKs, integrations, and development configuration. | Start with these public contribution areas. This is a selected map, excluding paused runtimes and operational tooling. | Path | Purpose | | - | - | | `apps/web/` | Main platform web application and API routes. | | `apps/docs/` | Mintlify documentation pages and navigation. | | `apps/mobile/` | Flutter mobile application. | | `apps/calendar/` | Calendar application. | | `apps/tasks/` | Task management application. | | `apps/finance/` | Finance application. | | `apps/meet/` | Meetings application. | | `apps/learn/` | Learning application. | | `apps/mail/` | Mail application. | | `apps/drive/` | File management application. | | `packages/ui/` | Shared UI components. | | `packages/editor/` | Localized rich-text editor and rendering utilities. | | `packages/sdk/` | Public TypeScript and JavaScript platform SDK. | | `packages/types/` | Shared TypeScript types. | | `packages/utils/` | Shared utility functions. | | `packages/typescript-config/` | Shared TypeScript configuration. | | `packages/education-core/` | Shared education domain logic. | | `packages/finance-core/` | Shared finance domain logic. | | `packages/storage-core/` | Shared storage domain logic. | ## Follow repository conventions Read the root [AGENTS.md](https://github.com/tutur3u/platform/blob/main/AGENTS.md) and the nearest applicable `AGENTS.md` before editing. Public contribution conventions include: * Use Bun, with the version pinned in the root `package.json`. Change dependencies through the package manager. * Use Conventional Commits and an accepted branch prefix such as `docs/`, `feat/`, or `fix/`. * Run focused non-build checks for changed code. Run `bun check:changed` before pushing; applicable CI checks must pass for the exact commit. * For docs, use the local Mintlify wrapper. Run `node scripts/local-docs.js validate` and `node scripts/local-docs.js broken-links` from the repository root. * Add new docs pages to `apps/docs/docs.json` and keep documentation aligned with behavior changes. * Add user-facing strings to both English and Vietnamese bundles. Update every affected shared UI bundle and run `bun i18n:sort`. * Keep new authored source files at or below 700 lines. Generated and vendored files are excluded. * Modify and commit only files intentionally changed for the task. ## Find product decisions Product behavior decisions live in the `platform/` section of these docs. Start with the [platform overview](/platform/overview), then read the relevant feature page for defaults, scope, exceptions, and regression evidence. ## Contribute documentation Follow [Documenting](/build/development-tools/documenting) for page structure, navigation, preview, validation, and review. # Browser session-surface guard Source: https://docs.tuturuuu.com/build/development-tools/browser-session-surface The shrink-only check that stops new browser access to session tokens while the shared session moves to a server-held HttpOnly cookie. The shared session is moving to a server-held `HttpOnly` cookie that page script cannot read (shared-session decision (b); see [Authentication](/platform/architecture/authentication)). Until every browser-side use is migrated, `scripts/check-browser-session-surface.js` keeps the existing surfaces from growing. It runs in `bun check:changed` whenever app or package source changes, and in `bun check`/`bun validate`. ## Rules The guard scans `apps/*/src` and `packages/*/src`. It skips tests, stories, generated output and the paused `backend` and `tanstack-web` runtimes. **Limits.** * Only `src/` trees are scanned. App-root files such as `next.config.ts`, Worker entries outside `src/`, and `scripts/` are not covered. * The Flutter app (Dart) is excluded. It holds bearer tokens in native secure storage by design. * The rules are lexical. A token returned through an indirect variable, or a client created through a re-exported helper, needs review rather than this guard. | Rule | Matches | Baseline | | - | - | - | | `browserSupabaseClientImports` | Imports, dynamic imports or `require` of `@tuturuuu/supabase/next/client` or `next/auth-browser`; `createBrowserClient` from `@supabase/ssr`; `@supabase/supabase-js` `createClient` in a `'use client'` module | 91 files, including the `packages/supabase` definition sites | | `postgresChangesSubscriptions` | A `'postgres_changes'` string literal (a realtime subscription that needs a JS-held session) | 0 | | `sessionCookieScriptAccess` | A file that uses `document.cookie` and names `sb-`, `auth-token` or `app_session` anywhere | 0 | | `sessionTokenResponses` | An `access_token`/`refresh_token` (or camelCase) key, plain, quoted or shorthand, in a file that builds JSON responses, `{ body: … }` results or `new Response(JSON.stringify(…))`; or a `.json(session)` dump | 41 files, each with a reason | The allowlist is `scripts/browser-session-surface-allowlist.json`, and it only shrinks: * A new match fails. Fix it by calling a same-origin API through `@tuturuuu/internal-api`, never by adding a browser client. * A token response that must exist (native, CLI or provider OAuth) needs an allowlist entry with a `reason` and a security review. * An entry that no longer matches also fails until it is removed, so migrated files drop out of the list. ## Short-lived capabilities inventory Script may hold a capability only when it is scoped to one topic or object, lasts at most 5 minutes (15 minutes for private download links) and cannot be exchanged for a session. Inventory as of 26 Oct 2026: | Capability | Where | Lifetime | Status | | - | - | - | - | | Realtime channel join ticket | `apps/web/src/app/api/v1/realtime/channels/route.ts` | 60 s, one topic | Within bounds | | Meet collaboration-room ticket | `apps/meet-realtime/src/collaboration-room-do.ts` | 30 s | Within bounds | | Cross-app handoff token | `generate_cross_app_token` | 60 s (300 s for CLI) once the bounds migration ships | Bounded | | Chat file and time-tracking image signed URLs | `ai/chat/file-urls`, `ai/chat/signed-read-url`, `time-tracking/requests/[id]/image-urls` | 3600 s | Clamp to at most 15 min | | AI image and QR tool outputs | `packages/ai/src/tools/executors/{image,qr}.ts` | 30 days | Clamp, or serve through an authorized route | | User avatar signed URL | `packages/users-core/src/routes/users/avatar.ts` | 1 year | Clamp, or serve public avatars through an authorized route | | Task update attachment signed URL | `apps/tasks/.../updates/[updateId]/attachments/route.ts` | 1 year | Clamp | The Meet `*-check.ts` tickets (600–1800 s) are integration-check fixtures, not browser capabilities. The clamps are scheduled with the storage helper migration in the shared-session plan. # cf CLI and Void over Wrangler Source: https://docs.tuturuuu.com/build/development-tools/cf-cli-wrangler-parity Per-operation parity matrix, native Worker template, rollback, the Wrangler usage guard and the per-service cutover checklist. ## Decision The target toolchain for active Worker-backed apps and services is **cf + Void**. Adopt it per verified operation. Preserve existing commands and configuration until authentication, target identity, bindings and migrations, emitted artifacts and rollback parity are established. Wrangler remains for recorded gaps with an owner and removal condition. The shrink-only usage guard requires structured admission for expansion, changed Wrangler lines, or changed gap scope. This page refines the cf adoption gates in [Oxc and Cloudflare adoption](/build/development-tools/oxc-cloudflare-adoption). A merged tooling switch is CI-verified, not production-delivered: every deploy target change still needs the gated production workflow, exact-commit evidence and the cutover checklist below. ## Toolchain shape | Surface | Build | Deploy artifact | Publisher | | - | - | - | - | | Native Workers (fetch, scheduled) | Vite+ with `@cloudflare/vite-plugin` reading `cloudflare.config.ts` (`experimental.newConfig.cfBuildOutput`) | cf Build Output Specification, `.cloudflare/output/v0` | `cf deploy --prebuilt` | | Durable Object Workers | Vite+ with the cf config | Same emitted bundle, with retained `v1` migration metadata | Wrangler until a separate rehearsal-backed publication change | | Framework apps (TanStack Start on Void) | Void SDK plugin on Vite+ | Void-emitted Worker config | Wrangler until the Void publication gap closes | | OpenNext apps (Parley, Lettin) | OpenNext Cloudflare adapter | OpenNext Worker | Wrangler (adapter-owned) until the app moves to Start on Void | The Void SDK is not applied to native Workers. Void's supported app types are Void apps, meta-frameworks and static sites, so a native fetch/scheduled/Durable Object Worker would have to be rewritten into Void's routes and crons model. For publication, Void's own Cloudflare deploy converts the emitted config into a cf Build Output and calls `cf deploy --prebuilt`. Native Workers emit that format directly, so they share Void's publication path without its runtime layer. The stable Vite plugin (1.64) already supports `cloudflare.config.ts` and Build Output emission; the 2.0 beta is not required. Loading `cloudflare.config.ts` requires Node.js (not Bun). The cf package requires Node `^22.23 || ^24.22 || ^26.12`. The **cf/Void Wrangler-exit lane** owns the `cf@1.0.0-beta.20` pin. Upgrade through a scoped dependency PR after checking upstream release notes and rerunning config/output parity, credential-free artifact checks, secret handling, settings readback fixtures and real Worker CI tests on the candidate version. DO publication remains Wrangler until a disposable migration rehearsal and a separate reviewed publisher change. Renovate holds cf prerelease pins via the `cf` package rule in `renovate.json`; update this hold only with the qualified upgrade PR. Do not float this beta pin automatically. ## Operation parity matrix Checked against installed cf `1.0.0-beta.20` source/help and `@cloudflare/vite-plugin` 1.64.0. Command availability below does not establish live authentication, resource identity or production acceptance for every caller. The existing native profiles qualify only their declared configuration fields. | Operation | Wrangler | cf / Void | Verdict | | - | - | - | - | | Configuration | `wrangler.jsonc` | `cloudflare.config.ts` (`cf/config`), generated by `cf migrate` | Parity, guarded by a normalized identity diff | | Local development | `wrangler dev` or Vite plugin with `configPath` | `vp dev` with the Vite plugin `newConfig`; `cf dev` also works but delegates to `bunx vite` (stock Vite, not Vite+ core) | Parity | | Local runtime tests | `createTestHarness` from `wrangler` | `scripts/ci/cf-vite-worker.mjs`: Vite dev server (source) or preview (emitted Build Output) in workerd; DO SQL through the Local Explorer API; `restart()` replaces eviction | Parity | | Binding types | `wrangler types` | `cf workers types` requires `cloudflare.config.ts`; writes `.cloudflare/types/index.d.ts` | Qualified for migrated native configs; no JSONC input, output-path or `--env-interface` equivalent | | CI build | Vite plugin emits `dist/*/wrangler.json` | Vite plugin emits `.cloudflare/output/v0` | Parity | | Credential-free artifact check | `wrangler deploy --dry-run` | `cf deploy --prebuilt --mode production --dry-run --no-provision` | Parity | | Deploy the exact artifact | `wrangler deploy -c --message` | `cf deploy --prebuilt --mode production --no-provision --message` | Parity; `--provision` defaults to true, so always pass `--no-provision` | | Secrets with a deploy | `wrangler secret bulk` then `wrangler deploy` | `cf deploy --secrets-file` uploads secrets with the same version | Parity (atomic) | | Bulk secret change | `wrangler secret bulk` | `cf workers secrets bulk --worker --secrets @file` | API available; its map contains secret objects, not the plain string map accepted by deploy `--secrets-file` | | Single secret put | `wrangler secret put` | `cf workers secrets update ` | API available; interactive/stdin and deployment parity unverified; never place secret values in command arguments | | Secret names | `wrangler secret list` | `cf workers secrets list` (API command) | Parity, verify output shape before scripting | | Versions | `wrangler versions list` | `cf workers versions list --worker-id ` | Parity | | Deployments | `wrangler deployments list` | `cf workers deployments list --worker ` | Parity | | Rollback | `wrangler rollback ` | `cf workers deployments create --worker --strategy percentage --versions '[{"version_id":"","percentage":100}]'` | Parity | | Gradual rollout | `wrangler versions upload` / `versions deploy` | `cf workers versions create --prebuilt`, then `cf workers deployments create` | Parity | | Cron, routes, custom domains | top-level `triggers`, `routes` | `worker.triggers`, `worker.domains`; `cf workers triggers deploy` | Parity in config; verify applied settings at cutover | | Durable Object migrations | `migrations` tags | `worker.exports` lifecycle declaration; `cf migrate` does not convert it | Manual conversion; needs a disposable rehearsal before production | | D1 migrations | `wrangler d1 migrations apply` | `cf d1 migrations apply --dir `; remote unless `--local` | Requires UUID, migration directory/table and local-persistence parity; binding names are rejected | | Installed cf config conversion and drift helpers | `convertToWranglerConfig`, `wranglerConfig` names inside cf | Pinned cf exposes only these internal names | `cf-config-internals`: admit compatibility references until equivalent cf APIs replace them; no Wrangler CLI invocation | | Deployment-source snapshots | API value `last_deployed_from: wrangler` | `cf` and `cf_cli` are also accepted; `cf_cli` is what the API reports for cf CLI deploys; historical provenance values remain distinct | `deployment-source-compatibility`: retain recognition until supported snapshots stop reporting the legacy value; no Wrangler CLI invocation | | Live logs | `wrangler tail` | Not supported (cf docs) | Gap | | Prebuilt Void deploy | n/a | `void deploy` always builds and provisions; `--skip-build` is static-only (Void 1.1.12 and 1.2.1) | Gap for the exact-artifact contract | | OpenNext publication | `opennextjs-cloudflare deploy` invokes Wrangler | None | Gap until Start on Void | ### Void emitted runtime qualification The native cf/Vite runtime harness accepts `cloudflare.config.ts` or cf Build Output under `.cloudflare/output/v0`. It does not accept Void's sealed `dist/server/wrangler.json` artifact. Mastermind retains an isolated `unstable_startWorker` acceptance fixture under the `void-emitted-runtime` gap with bundling and entrypoint processing disabled, disposable bindings, intercepted JWKS egress and denied provider authentication. Its pinned runtime dependency is covered by the same gap; cache ignores and source-audit exclusions are data-only `shared-toolchain` references. [PR #7301](https://github.com/tutur3u/platform/pull/7301) records the admission, exact usage counts and digests in the usage allowlist. Retire this gap only when a qualified cf/Void runner accepts the same sealed artifact and preserves the fixture's host, owner, session and bilingual rendering assertions, secret isolation and egress controls without rebuilding or publishing. This qualification does not admit production publication, DNS or Access changes. ### Capability limits before replacing a caller `cf workers types --no-include-runtime` skips the runtime declaration generator; its default can start workerd through Miniflare. The command discovers typed config by filename, so replacing a legacy `types --config ` invocation requires config and declaration-consumer migration, including the global interface. `cf dev` can delegate to Wrangler's new-config implementation. Detected Vite projects use the package manager's Vite command; use the owning `vp dev` script to preserve Vite+. `cf build` can delegate too, and `cf deploy --dry-run` can build unless `--prebuilt` is supplied. None is a universal replacement for legacy JSONC. Treat **`cf d1 migrations list` as potentially mutating**: migration preparation can issue `CREATE TABLE IF NOT EXISTS` for its history table before listing it. It is unsuitable for a read-only production inventory. No replacement for every Wrangler SQL file/export operation has been qualified. R2 object and KV key API commands exist, but require explicit bucket/namespace identifiers and verification of byte output, metadata, TTL, pagination and local state. `cf logs query` and `cf o11y telemetry query` do not establish live-tail parity. Keep the existing commands until their exact caller contracts pass. The configuration normalizer compares live DO classes/storage, not historical migration tags or module bytes. Its current binding mappings cover text, JSON, secrets and DOs; assets, AI, R2, D1, KV, services and email triggers need explicit profiles. The retained publication adapter separately enforces the original `v1` history and exact module inventory. Preserve both gates and unknown-field rejection. ### Calendar emitted binding types Calendar's ASSETS-only profile uses `calendar-cf-types.mjs` after its existing emitted-artifact validator. The helper creates a disposable literal typed config and runs the owning pinned `cf workers types --no-include-runtime` on a supported Node executor. It never loads a Worker module, environment file or credential. The self-contained `cloudflare-env.d.ts` comes from an ASSETS-only template; cf output checks that template rather than supplying the declaration text. A new binding requires changing the template and validator together. The cf-inferred binding and template must have the exact required ASSETS key and Fetcher type, with no `any`. During CI qualification the existing producer remains an explicit reference oracle; the same checks apply to its declaration. Additional resources, vars, secrets and named environments remain rejected by the existing artifact profile. Only after declaration parity and unchanged hashes for the bundle, assets, emitted config and deploy pointer does the helper atomically replace `cloudflare-env.d.ts`. Exclusive directory custody serializes supported generators through comparison and replacement; an existing lock fails closed. Detected edits and partial, empty or symlinked producer output preserve prior declarations. This is cooperative publication custody; do not edit the destination during generation. Its disposable config is removed; the output remains self-contained when the sealed artifact is restored. The JSON receipt records source/tool versions and before/after artifact digests. Local `cf:typegen` requires a qualified existing build; it does not build or publish. Exact-head CI must run the real cf CLI and the retained reference producer. Fixture tests exercise failure handling and the real TypeScript proof; they do not establish supported-runtime cf execution on an older local Node. Read declaration and receipt inputs through an opened regular-file descriptor; verify its inode/device against the named file before reading. Path checks alone leave a replacement race. Keep supplier-dependent fixtures and restored copies under `apps/calendar/tmp`. Copying the workspace manifest into repository-level `tmp` does not install its dependencies there; Bun's isolated layout resolves cf and its type imports through the owning Calendar workspace. Test that layout without a root-hoisted cf package. ### Calendar Build Output qualification Paired `.js.map`/`.mjs.map` files remain hashed in the source seal and listed in `excludedServerMetadata`; they are not executable modules or copied upload files. Orphan maps remain rejected. Source-map upload semantics remain unqualified. `calendar-cf-output.mjs` copies the sealed Calendar ESM bundle and client assets into an isolated cf Build Output tree, retaining relative paths and exact bytes. The native build also emits hashed CSS and Noto Sans fonts under `dist/server/assets`. The Vite manifest must list each server static file, and its name must have an approved `.css` or `.woff2` extension and build hash. These files go to the static assets output, never the executable module manifest. Their bytes must match the source seal; a file also present under `dist/client` must have identical bytes. Orphan, unhashed and unknown server files still stop emission. It validates the output with the config and reader suppliers resolved from the owning pinned cf installation. The complete module manifest is checked against all copied files; supplier schema acceptance alone does not prove coverage. Qualification is mostly self-referential: cf's side is only schema parsing and `readBuildOutput`, rather than an independently emitted upload comparison. `.assetsignore`, `_headers` and `_redirects` are copied as plain assets; their control-file semantics remain unqualified and are identified in `parity.json`. Vite metadata and the source configuration remain covered by the source seal, while unqualified server maps or non-ESM files stop emission. The existing exact-source CI runs this comparison before Worker runtime checks, verifies unchanged source bytes afterward, and verifies a same-run restored copy. Transport the comparison as a tar archive: direct artifact upload drops empty directories, which remain part of the verified inventory. List and validate archive members before extraction; reject absolute paths, `..` components and links, and extract with `--no-same-owner`. Its receipt records source/config supplier identity, all output hashes, excluded metadata and the unqualified account/publication state. This helper never invokes the deployment CLI or loads a Worker, environment file or credential. Keep existing publishers and validation commands. cf adds `./` to secondary upload module names where the current publisher uses bare relative names. Byte-preserving emission does not establish upload-name equivalence, routing/asset semantics or hosted runtime parity. A separate isolated, network-denied cf dry-run and module resolution rehearsal must close those gaps before a publisher switch; cf dry-run has no emitted-upload output flag. Do not treat it as an upload byte comparison. ## Native Worker template Applied to Cron Control, Devbox Control and Coordination. Each migrated Worker has: * `cloudflare.config.ts`, generated by `cf migrate --no-install` and reviewed. Durable Object `migrations` become `exports: { Class: exports.durableObject({ storage: 'sqlite' }) }` for every live class. * `vite.config.ts` with `cloudflare({ experimental: { newConfig: { cfBuildOutput: true } } })`, no `configPath`, explicit preview URL and observability/log settings, loopback dev server settings, `persistState` under a disposable directory for runtime tests (normal dev uses `.cloudflare/state`), and the Worker environment's `build.sourcemap: false` (Wrangler did not upload source maps). * Scripts: `dev: vp dev` (host/port in `vite.config.ts`), `build: vp build`, `type-check: cf workers types && tsc`. `cf` is an exact devDependency; the app-level `wrangler` devDependency is removed. * A parity baseline in `scripts/ci/fixtures/cf-worker-parity/.json`, normalized from the final `wrangler.jsonc`. `scripts/ci/cf-worker-parity.test.mjs` compares `cloudflare.config.ts` with it, and CI compares the emitted Build Output after the build with `node scripts/ci/cf-worker-parity.mjs apps/ scripts/ci/fixtures/cf-worker-parity/.json`. * The workflow validates, runs the runtime checks on source and on the emitted Build Output, dry-runs `cf deploy --prebuilt`, then uploads `.cloudflare/output` as the exact-commit artifact. The gated deploy job downloads that artifact and publishes it without rebuilding. For DO Workers, `cf-wrangler-publication.mjs` validates the same emitted bundle against `wrangler.publish.jsonc`, retains its original `v1` history and emits a Wrangler `no_bundle` publication config. Both credential-free publisher checks run in CI. Production has no cf deploy branch; enabling one needs a separate reviewed change with the disposable migration/data-retention rehearsal receipt. `@cloudflare/vite-plugin` 1.x still depends on the Wrangler library internally. That is a library dependency, not CLI usage; it disappears with plugin 2.x. The DO publication adapter excludes exactly `bundle/.vite/manifest.json` from module inventory. This Vite metadata is not a Worker module. Other undeclared files and symlinked metadata still fail qualification. After building in CI, run `CF_PUBLICATION_TEST_APP=coordination node --test scripts/ci/cf-wrangler-publication.runtime.mjs` (and select `devbox-control` for that app) against the real emitted output. The test requires Vite's manifest, preserves module bytes and applied `v1` migrations, and rejects unexpected metadata and symlinks. `CF_PUBLICATION_TEST_ROOT` can select an extracted exact-commit CI artifact tree; never commit the built bundles. ## Rollback ```bash theme={null} # Identify the previous version (first deployment is the one serving traffic). cf workers deployments list --worker tuturuuu-cron-control # Route 100% of traffic back to it. cf workers deployments create --worker tuturuuu-cron-control --strategy percentage \ --versions '[{"version_id":"","percentage":100}]' ``` Rollback cannot cross a Durable Object lifecycle change. Secret changes can block rollback; inspect the error before using `--bypass-deployment-checks`. Retained CI artifacts (`-worker-`) allow re-publishing an exact earlier build. The local harness rejects `.dev.vars*` and `.env*` files in both the app root and working directory (template `.example` files are allowed). Every declared secret needs a nonempty disposable fixture. Undeclared/control-key fixtures are rejected, and declared text vars are masked from the shell before process-env loading. It restores the first prior environment value after startup failure or close. `cf-vite-worker.test.mjs` covers both source and artifact modes using a disposable Vite fixture; real Worker runtime acceptance remains a CI gate. Each run allocates a private temporary persistence directory, keeps it through Worker restarts and deletes it on close or startup failure. The app Vite configs consume only the harness-owned `CF_VITE_TEST_PERSIST_PATH` override; ordinary development retains its usual state. ## Wrangler usage guard `node scripts/ci/wrangler-usage.js` prints the inventory. The guard scans tracked files, including executables under `plugins/`, `.agents/` and `tmp/`; Markdown, text, lockfiles and binary assets are excluded. Ignored/untracked `tmp/` files are not an inventory: executable files there enter the guard only when tracked. `.md`, `.mdx` and `.txt` are documentation exclusions in every directory; commands embedded in those files need normal review, since the guard does not parse executable documentation examples. It counts mention lines and all Wrangler token occurrences conservatively, including comments and strings. A SHA-256 digest also covers each file's Wrangler lines (all content for config files), so same-count substitutions require admission. Lower or remove counts when usage falls. An `admitted` record must be `{ "decision": "https://github.com/tutur3u/platform/pull/", "reason": "" }`. New entries, growth, changed digests and changed gap scope need a fresh record; reverting a migration follows the same rule. Compatibility references need admission too: cache policies must still recognize legacy declaration producers and scratch directories, and cleanup exclusions must retain local state until its owning toolchain is retired. These references do not invoke the CLI; replacing their names with cf would change their safety coverage. Use the existing `shared-toolchain` gap for scratch/state policy references and `producer-inventory` for declaration-producer detection, with exact counts, digests and the admitting PR decision. Remove each reference only with its covered usage. CI compares the allowlist with its base commit (`HEAD^1` of the pull request merge ref) and fails if that commit is unavailable. Current gaps: `cf-config-internals` (installed cf API names), `deployment-source-compatibility` (historical Worker snapshot provenance), `paused-runtime` (retained paused runtimes), `opennext-adapter`, `void-wave1-publication`, `pending-migration` (services awaiting their parity PR), `shared-toolchain` (root CLI provider, trusted-dependency and policy files), `parity-tooling` (the migration parity checker, which reads former Wrangler configs), `do-publication-rehearsal` (Wrangler publication of existing DO migration tags), and `producer-inventory` (native-check declaration-producer detection and its data-only fixture; no CLI invocation). The latter recognizes both legacy and `cf types` producers and is removed when legacy recognition is no longer needed. ## Service inventory | Service | Current publisher | Status | Gap | | - | - | - | - | | Cron Control | cf (after its parity PR) | Template | — | | Devbox Control, Coordination | Wrangler until a rehearsal-backed publisher change | Template with DO `exports`, runtime SQLite namespace checks | — | | Colab | Wrangler bundler with assets and AI | Local Worker preview uses Vite+; release build-output conversion pending | `pending-migration` | | Meet realtime | Wrangler, three SQLite DO classes | Needs DO `exports` and runtime fixtures | `pending-migration` | | Mail email routing | Wrangler config, email handler | Needs the email trigger mapping | `pending-migration` | | API | None yet; Vite+ build from `wrangler.jsonc` | Needs `cloudflare.config.ts` and a cf runtime harness | `pending-migration` | | Meet, Apps, Calendar, Mail, Shortener; CMS, Finance, Tasks and Track native candidates | Void build, Wrangler publication | Wave 1 owner | `void-wave1-publication` | | Parley, Lettin | OpenNext, Wrangler | Start on Void migration | `opennext-adapter` | | Backend, TanStack Web | Paused | Excluded | `paused-runtime` | ### Colab local Worker preview Run `bun run --cwd apps/colab preview` to serve the Worker and source UI on `127.0.0.1:8795`. The UI's separate `7835` dev proxy remains available. `vite.worker.config.ts` reuses the UI's React/Tailwind plugins and source alias, replaces its proxy with the local Worker, and reads the existing service configuration through the Cloudflare Vite plugin. It preserves the plugin's default local persistence path, disables remote bindings and leaves the UI build and production publisher intact. HMR stays disabled so React cannot inject an inline refresh preamble rejected by the Worker's production CSP. Cloud AI calls are outside this local-only scope. The Colab workflow exercises the actual preview config after its UI build: health and session responses, signed-out workshop denial and foreign-origin rejection. It also requests HTML, transformed client imports and compiled Tailwind CSS so an API-only pass cannot hide a broken UI. It uses disposable signing/persistence fixtures, refuses local credential files, and restores the process environment and removes only its own state on close. Types, release Build Output, DO migration history and publisher cutover remain separate gates; do not rename those commands based on this development change. ## Settings preflight token permissions The deploy token must cover the pinned account and every zone in that account. The settings snapshots require these Cloudflare API token permissions in addition to the publication permissions: | Resource | Read permission | Snapshot data | | - | - | - | | Target account | Account → Workers Scripts → Read (Write also grants read) | Worker settings, schedules, secret names, deployments and custom domains | | Every target-account zone | Zone → Zone → Read | Zone enumeration | | Every target-account zone | Zone → Workers Routes → Read | Worker route enumeration | Grant zone visibility for **all zones in the target account**. Limiting visibility to the expected hostname's zone can hide unexpected routes and cannot establish route parity. Do not grant unrelated accounts. These requirements apply to `COLAB_CLOUDFLARE_API_TOKEN` and to `COORDINATION_CLOUDFLARE_API_TOKEN` when supplied instead of the fallback. Keep values in GitHub secrets; never attach token values to receipts. Actual token scope remains unverified until the bounded read-only preflight succeeds. Missing access, truncated lists and unsupported account size fail before publication; do not bypass that gate to deploy. Drift-relevant list snapshots (secrets, domains, zones and routes) follow locally constructed `page` URLs for at most eight pages of at most 50 entries each, sharing the unchanged 28-request snapshot budget. They reject repeated pages, inconsistent pagination metadata and incomplete reported totals. The 20-zone account limit still applies. Settings-object endpoints retain their full object even if the envelope includes list metadata; `result_info.total_pages` alone does not imply that an object was truncated. Pagination failures name the same safe request display path as HTTP failures. Regression coverage lives in `scripts/ci/cf-worker-settings.test.mjs`. Deployment history is an explicit exception to list completeness. The [deployment API](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/deployments/methods/list/) defines the first deployment as the one currently serving traffic. Read only the first page and retain that deployment's id and complete version/percentage split for rollback. Historical deployments and their pagination totals do not describe current settings and are not captured. A missing first deployment, non-first page, missing versions, duplicate version ids or traffic percentages that do not total 100 fail closed; never substitute an older deployment. This uses one request inside the same 28-request budget. Domain, route and secret completeness and exact schedule comparison remain required. The twenty-page history and missing-active regressions cover this exception. Recovery requires a production commit containing the fixed script. Planner deploy jobs check out the triggering production SHA; re-running an older failed run retains its old script even after a fix merges into main. Promote the approved fix, then inspect the new planner run and its gated production migration result. Each snapshot phase first logs `Cloudflare API token fp:<12 hex> status ` from `/user/tokens/verify` (or the account-owned token endpoint); this diagnostic cannot fail the job. The fingerprint is the first 12 hex of `sha256(id)`, computed only for a well-formed 32-hex token id (otherwise `fp:`); the raw id is never printed because it is response-derived. A failed read prints its HTTP status, numeric Cloudflare error codes and a request path built only from the pinned account, the Worker name and zone ordinals (`/zones//workers/routes`), so a `403` shows which token and zone lack access. Diagnostics never print response-derived text (error messages, bodies, zone names or IDs, JSON parse errors or assertion diffs of live values). The status prints only when it is a known value, and binding names only when the baseline already declares them (others print as ``). Undeclared text or Durable Object bindings fail before they are recorded; undeclared secret bindings are tolerated because their values are never read. The CLI prints only its own assertion messages and the name of any other error. To identify the token, hash each candidate id from the Cloudflare dashboard token list (`printf %s | shasum -a 256 | cut -c1-12`) and compare before changing the GitHub secret. Cloudflare documents the accepted permissions for [Worker secrets](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/secrets/methods/list/), [deployments](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/deployments/methods/list/), [custom domains](https://developers.cloudflare.com/api/resources/workers/subresources/domains/methods/list/), [zones](https://developers.cloudflare.com/api/resources/zones/methods/list/) and [routes](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/). ### Secret inventory from settings snapshots Coordination's existing before/after settings capture verifies the required `COORDINATION_TOKEN` name against its recorded identity. Each snapshot already performs one bounded secret-name GET on the pinned account and Worker. Reuse its `secrets` array for the workflow's explicit token gates instead of issuing a second CLI request. Require array shape and membership; keep both checks fatal, keep the after check after publication, and retain the private settings receipts. No secret values are captured. The original migration-tag publisher stays in place. `cf-worker-settings.test.mjs` exercises the actual Coordination profile, one read per phase, and missing-token rejection before and after publication. ## Deployment account variable Set the non-secret **Actions repository variable** `CLOUDFLARE_ACCOUNT_ID` in `tutur3u/platform` (Settings → Secrets and variables → Actions → Variables). Use the account ID recorded in the service's `cloudflare.config.ts` and parity baseline; the deploy job checks it against the emitted artifact. One repository variable supplies `cron-control-production`, `devbox-control-production` and `coordination-production`. If any of those environments defines the same variable, it must have the same value because the environment value takes precedence. Missing or mismatched configuration blocks deployment. Source publication does not provision this variable; the release owner must set it before promotion. ## Cached Build Output The root Turbo `build.outputs` includes `.cloudflare/output/**`, including hidden Vite metadata. Cache hits must restore the complete emitted tree before parity, runtime and publication checks. `.cloudflare/state` remains outside the output scope. `cf-build-output-cache.test.mjs` runs a disposable emit-only task through an actual cache miss and hit, verifies restored bytes and execution count, and checks the old output list as a negative control. It never compiles an app or uses shared/remote cache credentials. ## Production cutover checklist For each service, the orchestrator verifies before promotion: 1. Exact-commit CI on the promoted SHA is green for the service workflow, including: source runtime checks, emitted Build Output parity (`cf-worker-parity.mjs` prints `matches deployment identity`), emitted runtime checks, the `cf deploy --prebuilt --dry-run --no-provision` step, and the uploaded `-worker-` artifact. 2. The production job publishes that artifact with `cf deploy --prebuilt` (no rebuild) and the same `--message` SHA. 3. The deploy job runs `cf-worker-settings.mjs before` before any publication or secret mutation, then `after` before recording success. It checks the pinned account, compatibility, preview URLs, observability/logs, cron schedules and declared secret names; snapshots routes/custom domains and hashes remaining settings without persisting text bindings. It captures the active deployment and version IDs (`cf workers deployments list`) as the rollback target. Also capture `cf workers get `, `cf workers secrets list` and, with the Cloudflare API, the script's cron schedules (`/workers/scripts//schedules`), routes or custom domains, and `workers.dev`/preview URL state. The job captures them again after deployment and compares; unexplained changes fail the job before its success marker. Evidence is retained even on failure. This route-free pilot supports at most 20 account zones and one API list page, uses at most 28 GET requests per snapshot, and fails closed on missing read permissions, truncated results or unsupported scope. It never retries writes. The expected preview setting is explicitly true; this is unverified against current production until the preflight runs. A mismatch stops before mutation. To change crons, text vars or Durable Objects, the parity baseline records a reviewed `transition` (`decision` ID and `fields`, limited to `crons`, `vars`, `durableObjects` and `durableObjectClasses`) from `previousIdentity` (live) to `identity` (the emitted artifact). Every other identity field must be equal and every declared field must change. `before` reads once and must match exactly one stage, verifying text values (digest only, differing names in errors) and Durable Object bindings; unreviewed binding attributes such as `environment` or `dispatch_namespace` fail. A Worker matching neither stage fails closed. `after` must match the target. On the first publication only the settings hash, bindings and schedules may change; once live already matches the target, settings must stay unchanged. Storage classes are verified on the artifact, not read back live. Remove the transition in a follow-up change after production matches the target. 4. Production publication for Devbox Control and Coordination remains Wrangler with their applied `v1` migration metadata. A separate reviewed change must carry the rehearsal receipt before enabling cf publication. For these Workers, rehearse the first cf deploy on a disposable Worker created with the same Wrangler migration history and data, and confirm object data survives the switch to `exports`. Do not promote until that rehearsal passes. 5. Health checks pass on the canonical host, and the deployment marker records the SHA. 6. If a check fails, roll back with `cf workers deployments create` to the captured version, then reconcile before retrying. # ChatGPT and MCP Source: https://docs.tuturuuu.com/build/development-tools/chatgpt-mcp Portable plugins, hosted read workflows and authorization gates. Source audit: October 1, 2026. This package now has a portable root `plugin.json` and `mcp.json`, with `.codex-plugin/plugin.json` and `.mcp.json` retained for compatibility. The portable manifest deliberately omits `extensions.com.openai`, so the existing OpenAI presentation overlay remains active in full. Portable version is omitted; Release Please continues to own the compatibility manifest's version. No legacy `ai-plugin.json` is used. ### Capability and security gates | Capability | Existing source / first slice | Gate before claiming ChatGPT delivery | | - | - | - | | Portable packaging | Root manifests plus existing developer skills | Install and smoke-test the package in each intended host | | Workspace discovery and task summaries | Local opt-in CLI bridge plus hosted user/grant-bound source, tested with synthetic accounts | Reviewed issuer/grant/session authority, private-board/RLS proof and permitted-account delivery | | Tasks / Calendar navigation and Calendar summaries | Canonical links and hosted bounded event projection; existing Calendar permission preserved | Signed-in smoke tests and reviewed Calendar/RLS compatibility; no live event reads yet | | Hosted ChatGPT MCP | Connected official SDK source and real Streamable HTTP protocol tests; no registered endpoint | Public HTTPS deployment, persistent grants, provider/live-session policy, read-only API/RLS and rate admission | | ChatGPT OAuth | Existing CLI browser exchange and external-app token exchange are different protocols | Protected-resource and issuer discovery, resource/audience binding, authorization code + S256 PKCE, exact redirect allowlist, scopes and consent; choose CIMD or supported registration flow | | MCP Apps UI | No widget or UI resource yet | Standard MCP Apps bridge first, output schemas, resource CSP and approved origins; keep credentials server-side | | Sidebar / panels / deep links | Optional OpenAI extension stage | Capability detection and MCP App entrypoints; Free/Go web extensions are documented as coming soon | | Composer mentions | Optional later stage | Desktop only per current docs; workspace-authorized search and IDs, never raw token/file paths | | File viewers / editors | Deferred; no current workspace task need | File access/size/type authorization and user-confirmed writes | | Writes / marketplace | No write tools, public submission, credentials, grants, or production configuration changes | Separate parent approval, reviewed scope/consent, idempotency tied to actor/workspace, stale-state checks; publication requires review materials and remote endpoint | Current OpenAI docs describe portable Agent Plugins as the authoring format, MCP Apps as the shared UI bridge, and OpenAI MCP Extensions as optional host surfaces. Existing plugin functionality remains available while Free/Go web extensions are coming soon. Do not infer availability on every plan, mobile client, or host from a successful desktop example. See [packaging](https://developers.openai.com/plugins/build/plugins), [extensions](https://developers.openai.com/plugins/build/extensions), [UI reference](https://developers.openai.com/plugins/reference), and [changelog](https://developers.openai.com/plugins/changelog). ### Local read bridge This is a local stdio server using the official MCP Python SDK's maintained FastMCP API, pinned to `mcp==1.30.0`; SDK v2 is now stable and needs a separately validated migration. It is not a hosted ChatGPT connector. Public MCP submission requires a remote HTTPS endpoint. The server binds to no network port and exposes: * `list_workspaces`: only workspace IDs and bounded names. * `list_workspace_tasks`: one page of open task IDs and bounded names with an explicit workspace UUID, limit 1–50 and offset 0–10000. Default CLI status filtering still applies. Personal external placements fail closed. * `get_workspace_navigation`: a canonical Tasks or Calendar workspace link; does not launch a browser or fetch events. Each call uses the current local CLI identity. Workspace membership is rechecked before scoped reads and links; the API remains the permission authority. There is no MCP cache. The current workspace API uses private response caching; this bridge adds no cache and does not prove immediate upstream revocation. The task GET route already uses a server admin client behind explicit membership checks and workspace filters; the MCP layer adds no admin client or bypass. Hosted rollout still needs actor/guest/private-board authorization and revocation tests. The bridge never reads the CLI config or tokens directly, accepts no model-selected origin/config/executable, invokes no shell, disables update checks, and emits no raw CLI errors. The existing CLI may refresh its user session and rotate its local config. The CLI session itself is broader than these three read tools: this process allowlist is not a new narrowly scoped OAuth grant. Never serve this adapter over HTTP or reuse a machine CLI identity for multiple remote users. A future hosted adapter must bind issuer/subject/workspace/scopes per request, partition caches by that identity, and reauthorize after revocation. Names returned by Tuturuuu are hostile content boundaries: treat them as data, never instructions, links, commands or authorization. No descriptions, assignee identities, raw provider events, secrets or tokens are returned. All tools declare read-only, nondestructive, idempotent and closed-world annotations; typed results generate `outputSchema`. A CLI call times out after 20 seconds and its parsed response is capped at 1 MiB; temporary output is deleted after each call. Setup is deliberate and separate from installation of repository dependencies: ```bash theme={null} # Use a reviewed Python 3.10+ environment and an already installed ttr CLI. # Run dependency setup and validation through the shared FIFO resource queue. ttr resources run -- python3 -m pip install --require-hashes -r plugins/tuturuuu/mcp/requirements.lock # Authenticate manually using the existing user CLI flow if needed. # Enabling reads authorizes requested workspace/task data to reach the MCP host. export TUTURUUU_MCP_READS_ENABLED=1 python3 plugins/tuturuuu/mcp/server.py ``` Install the SDK in the Python 3.10+ environment that the host uses to launch the manifest's `python3` command. A repo-local virtualenv is not copied into plugin caches. Codex's compatibility overlay explicitly forwards only `TUTURUUU_MCP_READS_ENABLED` via `.mcp.json` `env_vars`; start/restart the host with that variable after review. No manifest hardcodes enablement. Both manifests use contained plugin-relative `cwd: "./"` and `mcp/server.py` arguments. The portable schema has literal `env`, not `env_vars`; generic portable hosts must explicitly configure opt-in forwarding, otherwise reads remain disabled. Codex uses the existing OpenAI compatibility overlay. Loader rules were checked against pinned official Codex source [`plugin_config.rs`](https://github.com/openai/codex/blob/d2b254fd17ced848dbc269705373cf5a02ed3284/codex-rs/codex-mcp/src/plugin_config.rs) and [`agent_plugin_config.rs`](https://github.com/openai/codex/blob/d2b254fd17ced848dbc269705373cf5a02ed3284/codex-rs/codex-mcp/src/agent_plugin_config.rs). The legacy loader joins relative cwd to the package root and does not expand `${PLUGIN_ROOT}` in arguments. Tests launch the actual packaged manifests using these path/forwarding contracts and the real Python SDK; they do not execute the Rust loader or prove live host installation. Local discovery also fails closed while its actor-bound Hidden reader is unavailable: it returns no workspaces. The installed CLI currently has no owner Hidden read command. The trusted integration seam must read the owner-only route with the current CLI `whoami` identity and `expectedActorId`, without token export, admin fallback, or caching. Missing/malformed authority or an actor switch returns no discovery rows. Hidden never removes canonical membership: explicit authorized task reads and navigation still work. Production wiring of that seam remains a gate. Do not place tokens in either manifest or enable reads globally without understanding the host's data handling. Reinstall/refresh the plugin cache after source changes; cached packages do not follow source edits automatically. Offline verification (synthetic responses; does not authenticate or call APIs): ```bash theme={null} ttr resources run -- python3 -m unittest discover -s plugins/tuturuuu/mcp -p 'test_*.py' python3 plugins/tuturuuu/scripts/validate_plugin.py ``` The focused suite checks scope rejection, missing membership, cross-workspace and external rows, bounded pagination/output, sensitive-field projection, safe error handling, opt-in behavior, and actual SDK schemas/annotations. Live user reads, ChatGPT host installation, OAuth, UI, and CI builds are separate evidence gates. ### Smallest staged rollout and owned paths 1. Local read slice: `plugins/tuturuuu/{plugin.json,mcp.json,.mcp.json}`, `.codex-plugin/plugin.json`, `plugins/tuturuuu/mcp/`, the plugin validator, and this existing documentation page, and `.github/workflows/codex-plugin.yaml` for offline protocol/security tests. No mobile, workspace picker, Calendar UI, database, SDK, or live API files change. 2. Hosted read adapter: propose isolated `packages/mcp/` transport/auth modules and `apps/web/src/app/api/mcp/` only after OAuth design review. Keep Rust/API migration registration in step under repository rules. Reuse existing user-authorized API reads; never introduce a service-role bypass. Gate calendar reads on verified per-user/provider visibility and bounded time ranges. 3. MCP App: a workspace/task view built on the standard bridge, then optional sidebar/panel entrypoints and desktop composer mentions when supported. 4. Writes and publication: independent review and approval; use explicit proposed changes and server-enforced confirmation/idempotency, then host testing, privacy/support/terms, test-account and review materials, metadata scan and directory publication. No stage silently enables another. Authentication and review requirements: [OAuth](https://developers.openai.com/plugins/build/auth), [security and privacy](https://developers.openai.com/plugins/guides/security-privacy), [MCP review](https://developers.openai.com/plugins/deploy/app-review), and [submission](https://developers.openai.com/plugins/deploy/submission). MCP itself requires no OpenAI API key or paid model call. ### Corrected hosted boundary plan Reconciled against verified remote main `e819953329392db746bb22e2e918f3c8bbb06579` on October 1, 2026. The local stdio implementation above is Codex/desktop groundwork, not completion of the requested hosted ChatGPT integration. Portable packaging supports local stdio, but public ChatGPT MCP distribution needs a remote HTTPS endpoint and its own authorization contract. No placeholder remote URL or registered connection ID is advertised. Current source boundaries to reuse: * `packages/internal-api/src/workspaces.ts` and `tasks.ts` own typed user-facing read requests; `client.ts` owns API transport. Do not wrap every API operation. * `packages/tasks-api/src/server/tasks/route.ts` owns task visibility and membership checks; the current handler has admin-backed branches. A hosted adapter must not treat a verified MCP token as permission to use those branches without checking the actor, workspace, private board and guest boundaries. * `apps/web/src/lib/api-auth.ts` and `api-auth-audiences.ts` own gateway session, audience, abuse and step-up decisions. Its `allowAppSessionAuth` path explicitly uses an admin-backed client. Do not enable that path for MCP as an RLS substitute. * `packages/auth/src/cli-session.ts` grants broad `cli:access`; it is not the hosted token contract. `app-session.ts` handles internal target-app sessions. Neither token is returned to ChatGPT or accepted as an MCP access token. * `apps/web/src/app/api/v1/auth/app-token/exchange/route.ts` handles external-app secrets, scopes, workspace checks and rotation. Reuse its authorization and refresh principles; do not send ChatGPT a cross-app token or app secret. * `apps/web/src/lib/auth/oauth-providers.ts` configures incoming account sign-in providers. The audit did not find a complete MCP OAuth authorization server in this source. Outbound Google/SePay OAuth is unrelated. Issuer capability, client registration, consent storage and audience binding remain explicit design gates. Proposed hosted dataflow, source design only: 1. ChatGPT discovers the MCP protected-resource document and the approved issuer's discovery document. No account-specific data is available anonymously. 2. Authorization code + S256 PKCE enters the existing Tuturuuu sign-in boundary. A Tuturuuu-owned consent screen chooses one accessible workspace and read scopes for workspace discovery/task summaries/navigation. Preserve required MFA and deny suspended users. Bind client, exact redirect, resource, workspace and granted scopes to a single-use code; never infer consent from sign-in alone. 3. The approved issuer produces a resource-bound OAuth user access token with subject, expiry, client and revisioned MCP grant claims. ChatGPT receives this restricted credential. Ordinary account, CLI, internal-app and refresh tokens are rejected as tool-access credentials and never appear in tool output. 4. A stateless Streamable HTTP request verifies issuer/signature or introspection, audience/resource, expiry, grant revocation, scopes and actor on every POST. Reject browser cookie-only requests, unsafe Origin/Host, oversized JSON/batches and unsupported methods. Missing auth returns the discoverable 401 challenge. Apply shared gateway abuse/rate limits and redacted correlation-only logging. 5. Construct a request-scoped typed read client using `packages/internal-api`. The adapter uses the verified OAuth user JWT on three fixed resource-read GET paths plus the owner-private Hidden GET at canonical platform/Tasks/Calendar origins. Release requires those gateways to enforce the MCP audience, client, domain grant and read-only user authority. Ordinary Supabase `authenticated` audience acceptance is insufficient. If gateway/RLS compatibility cannot be established safely, keep this adapter disabled and implement the narrow actor-aware boundary first. No process CLI identity, workspace API key or service-role client is constructed by MCP. 6. Recheck selected-workspace membership and operation-specific task visibility; return only projected summaries and canonical allowlisted links. No MCP cache in the first hosted slice; later cache keys include issuer/subject/grant/workspace and scopes, and never bypass revocation. Names remain untrusted content. 7. Start without widgets or writes. The prepared Calendar adapter preserves the current `manage_calendar` requirement and projects event ID/title/times only, within a seven-day interval and 100-event cap. It does not weaken Calendar permissions or return guests, descriptions or provider credentials. Add MCP Apps UI only after this read path passes isolation tests; use standard bridge/resource CSP before optional OpenAI sidebar/panel/desktop composer surfaces. ### Prepared hosted source slice The source has one connected composition root and remains unregistered. The shipping web package pins the official `@modelcontextprotocol/sdk@1.31.0` in `apps/web/package.json` and the root `bun.lock`. Package-manager generation added only that workspace dependency and eight new SDK-related lock records; existing package records, other workspaces and lock settings did not change. Existing JOSE, Zod and internal-api dependencies support the source core. A bounded local FIFO run passed all 37 focused tests, including three real official SDK client/server Streamable HTTP tests. It exercised initialize/initialized, typed tools/list, task/navigation tools/call and forged-workspace/cross-tenant rejection through JWT, provider and typed API boundaries. Test identities, signing keys and upstream provider/API responses are synthetic; no live grants, credentials, public endpoint, database or application build was used. This proves the source read workflow, not deployed OAuth/RLS authority or production readiness. Exact owned paths: | Paths | Responsibility / prerequisite | | - | - | | `apps/web/src/lib/mcp/contracts.ts` | Revisioned actor/client/resource/workspace grant, projected outputs and mandatory fresh authority interfaces | | `apps/web/src/lib/mcp/authorization.ts` | Official JOSE signature validation; issuer/audience/expiry/client checks; fresh grant, provider session, account, MFA and admission checks | | `apps/web/src/lib/mcp/provider.ts` and `provider-client.ts` | Installed Auth SDK response contract, fixed issuer identity/grant GETs, public publishable key and mandatory live-session policy; no administrator or refresh session | | `apps/web/src/lib/mcp/read-service.ts` | Visible workspace discovery; bounded task/Calendar summaries and navigation require explicit workspace grants plus current member/operation permission | | `apps/web/src/lib/mcp/internal-api.ts` | Fixed-origin GET-only, no-store, redirect-denying user bearer transport; 10-second timeout, 1 MiB cap, tenant projections and owner Hidden API allowlist | | `apps/web/src/lib/mcp/visibility.ts` | Per-request verified-actor Hidden reader through existing internal-api transport, expected actor check, unavailable route means unknown, no cache | | `apps/web/src/lib/mcp/consent.ts` and `grant-store.ts` | Pure trusted provider/actor/redirect/workspace consent preparation; persistent atomic reserve/activate/revoke contract and owner-bound grant reader; no production store or provider approval | | `apps/web/src/lib/mcp/runtime.ts` | Single provider/grant/session/visibility/admission/internal-api/HTTP composition root; no environment defaults | | `apps/web/src/lib/mcp/http.ts` | Unregistered HTTP factory/discovery payload; stateless request instances, 64 KiB body cap, Origin/Host checks and sanitized errors | | `apps/web/src/lib/mcp/tools.ts` | Four accurate typed output schemas and read-only/idempotent/non-destructive/closed-world annotations; hostile-content instructions | | `apps/web/src/lib/mcp/hosted.test.ts`, `workflow.test.ts` and `workflow-fixtures.ts` | Unit coverage plus composed signed-JOSE/provider-REST/internal-api/task projection/Hidden/consent/store fixtures; passed in the focused suite | | `apps/web/src/lib/mcp/sdk.ts` and `sdk-workflow.ts` | Concrete official SDK Streamable HTTP composition; fresh server/transport per request, JSON responses, structured outputs, no shared sessions; exact official SDK dependency declared | | `plugins/tuturuuu/hosted/sdk-protocol.test.ts` | Real SDK client/server initialize, initialized notification, typed tools/list, task/navigation tools/call and cross-tenant failure tests; all three passed | | `plugins/tuturuuu/hosted/vitest.config.mjs` and `tsconfig.test.json` | Focused Node/one-worker non-build tests, isolated from unrelated sparse project references and application environment loading | | Existing portable manifests, local Python MCP, validator, plugin workflow and this page | Local groundwork preserved separately; no remote endpoint or connection ID advertised | No route, route-override, mobile, workspace selector, existing API, database or Calendar lane file is changed. Route registration and any Rust gateway mirror remain required before deployment, using the repository's normal ownership rules. ### Provider, consent and release gates Current Supabase documentation describes a managed OAuth 2.1/OIDC server with authorization-code PKCE, custom consent and user grant revocation. It is a candidate issuer, not evidence that the Tuturuuu project has enabled it. The provider handles codes, token issuance and refresh; do not implement custom OAuth cryptography. Use its authorization-details and approval/denial APIs from a trusted authenticated consent boundary with existing MFA/account rules, same-origin CSRF protection and exact approved client/redirect checks. Persist actor/client/resource/selected workspaces/read scopes before approval in an atomic revisioned grant store. No consent page, grant store, access-token hook or OAuth configuration was created. [Supabase OAuth flows](https://supabase.com/docs/guides/auth/oauth-server/oauth-flows). Supabase's default audience is `authenticated`; OAuth tokens carry `client_id`. Its OIDC scopes are not Tuturuuu task/Calendar permissions. The prepared `mcp:*:read` values are a local domain grant contract, not a claim that the provider supports arbitrary OAuth scopes. A reviewed provider hook must bind the MCP resource audience and grant ID/revision. Restrictive RLS and gateway checks must prevent this JWT from gaining ordinary write or unrelated workspace access via another API. No RLS, signing key, issuer, hook or gateway security configuration was changed. [Supabase token security](https://supabase.com/docs/guides/auth/oauth-server/token-security). The current user API wrappers can enter administrator proxy paths and some task and Calendar handlers use admin queries after authorization. Their existing membership/private-board gates must be proved for OAuth user tokens; MCP does not enable app-session fallback or construct a service-role client. Raw public-key Supabase identity access is required at the provider seam. The installed `@supabase/auth-js@2.117.1` differs from the public flow page examples: it exposes `oauth.listGrants()` and rows with `client.id`. That SDK method requires a local refreshable session, even with global bearer headers. The prepared stateless provider reader therefore uses its two fixed read endpoints (`/user` and `/user/oauth/grants`) with the verified request JWT and public publishable key; it does not fabricate a refresh session or credential vault. `getUser` and JWKS verification alone do not satisfy the live-session/account/MFA policy contract. The parallel workspace lane defines owner-only `HIDDEN_WORKSPACE = true` rows in `user_workspace_configs`, with absent rows visible and an actor-bound owner GET. The verified base does not yet contain that lane's route. The prepared reader returns `visible`, `hidden` or `unknown`; Hidden/unknown are excluded from discovery and consent choices. Explicit granted reads and authorized navigation preserve canonical membership, matching that lane's documented deep-link rule: hiding is not permission revocation. The route must be integrated and its OAuth user behavior proved before deployment. This lane does not edit or copy its preference writes. There is no MCP data cache or cross-user session cache. Task API responses that include external placements or lack the workspace relation are rejected in full; native-only API query behavior remains a compatibility gate. No OAuth grant, secret, client registration, public endpoint, database/security configuration or marketplace action occurs during this source slice. Before runtime wiring, resolve issuer, consent/grant storage, live session policy, Hidden visibility and gateway/RLS authority; before installs or tests, use bounded FIFO admission. Prepared synthetic tests cover wrong issuer/audience, expired/revoked grants, refresh-as-access, account switching, forged workspace IDs, guest workspace access, Origin/Host confusion and hostile names. Private-board API fixtures, real signature/key-rotation tests, real SDK initialize/list/call tests, provider refresh/revocation, restrictive RLS and gateway compatibility tests remain required. Delivery evidence also needs actual Streamable HTTP host tests and parent-approved permitted-account reads. Writes require separately reviewed confirmation/idempotency; widgets require standard MCP Apps bridge/CSP review; marketplace publication remains a later parent-approved stage. ### Remaining authority design against existing contracts The runtime's required policy/store callbacks are seams, not a deployed authority. No environment loader supplies them and no public route invokes the workflow. Keep `securityReviewComplete` false until these boundaries are implemented and reviewed with the provider and gateway behavior. * `packages/supabase/src/next/auth-session-user.ts` revalidates identity with `getUser()` after checking claims. Reuse that identity principle, but do not equate identity/JWKS success with an authoritative active OAuth session. No existing source contract inspected here proves owner-bound live `session_id` and client revocation together. A narrow reviewed provider/session adapter remains required; never query unrestricted auth tables via an MCP admin client or fabricate a local refresh session to obtain SDK grant methods. * `packages/utils/src/required-mfa-policy.ts` owns the server `app_metadata` policy and verified AMR/session proof helpers: `readRequiredMfaPolicy`, `mfaProofFromVerifiedClaims` and `satisfiesRequiredMfaPolicy`. A future adapter must carry already-verified claims and current server-owned metadata in request context, bind proof to the same session, and preserve recovery/primary-proof cutoffs. The current `(userId, sessionId)` callback is intentionally unwired; enrich its verified context before implementing MFA policy. Refresh `iat`, browser flags and editable `user_metadata` do not establish fresh MFA. * `packages/utils/src/abuse-protection/user-suspension.ts` owns suspension reads. Some existing `apps/web/src/lib/api-auth.ts` branches catch suspension lookup errors and continue. Do not inherit that fail-open behavior for MCP: unavailable policy or unknown account/session state must deny access. * The persistent grant store must uniquely bind user/client/provider authorization ID, resource, redirect, selected workspace IDs and domain read scopes. Reserve consent atomically; activate only after trusted provider approval; the token hook reads only active grants. Never reuse generic editable user configuration as grant authority. Revisioned revoke/change commits must reject old JWTs before returning tool data. Provider revocation is a separate distributed side effect: use durable reconciliation/outbox semantics rather than claiming an atomic database/provider transaction. No schema, RPC, privileged policy or hook is created by this slice. ### Focused validation and SDK provenance From an installed checkout, run the non-build Node tests with one worker: ```bash theme={null} node node_modules/vitest/vitest.mjs run \ --config plugins/tuturuuu/hosted/vitest.config.mjs --configLoader native \ --maxWorkers 1 --no-file-parallelism ``` Locally, wrap that command in `ttr resources run --`. The focused config isolates unrelated TypeScript project references and never loads application environment files. It resolves the shipping SDK from the web package. An explicitly owned isolated validation installation can be selected with `TUTURUUU_MCP_SDK_DIR`; that option changes only test module resolution, not runtime authorization or API origins. `workflow.test.ts` uses an explicitly synthetic dispatcher to isolate the source boundary; `sdk-protocol.test.ts` uses the actual official Client, Streamable HTTP client transport, McpServer and Web Standard Streamable HTTP server transport. Both share real JOSE-signed synthetic identities and the actual internal-api client. No stub dispatcher is used to claim SDK protocol compatibility. The official registry's compatible v1 package `@modelcontextprotocol/sdk@1.31.0` was published September 28, 2026 at 18:59:36 UTC. It exceeded this repository's `minimumReleaseAge = 86400`; MCP has no exemption. The newer generation uses separate v2 packages; this source targets the maintained v1 API. See the [official v1 release](https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/1.31.0). The SDK lock integrity matches the registry: `sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==`. Local SDK installation used an owned isolated directory/cache, exact pin, disabled lifecycle scripts and normal FIFO admission. The shipping manifest/lock were package-manager-generated in a manifest-only workspace copy with unchanged existing patch/vendor inputs, then inspected before export. No donor/global dependency or credential mutation occurred. Focused evidence does not replace exact-commit CI lint/type/build checks, live provider refresh/revocation, private-board/RLS fixtures or permitted-account delivery checks; the parent owns integration and monitoring. Provider consent must prove the authorization transaction was issued for the exact MCP resource before grant reservation. The installed provider SDK currently omits that resource field, so its unaugmented authorization details intentionally fail closed. A reviewed provider resource-binding integration is still required before activation; the source factory does not infer audience from configuration or user input. The packaged local bridge uses `python3` (Python 3.10 or newer), with a generated transitive dependency hash lock and pip cache in CI. A missing trusted Hidden discovery reader returns an empty workspace list without launching the CLI. Local CLI output is bounded while reading the pipe; oversized output terminates the child before it can accumulate in a temporary file. # CI/CD Pipeline Optimization Source: https://docs.tuturuuu.com/build/development-tools/ci-cd-optimization Centralized affected-path gating and smart caching to minimize unnecessary CI/CD runs. > [!NOTE] > > **Prerequisite**: Read the [CI/CD > Pipelines](/build/development-tools/ci-cd-pipelines) page to understand the > basic workflow structure. ## Overview Our CI/CD pipelines avoid wasted builds, tests, and deployments through a **centralized affected-path gate** plus **build caching**. Instead of every workflow re-implementing its own change detection, automatic deployments share the same TypeScript decision function while avoiding a separate configuration runner when the decision can be made inside an already-required job. This page documents how that gate works, how the per-app Vercel workflows are wired, and how to debug skip decisions. The maintained runtime is Next.js Web and its satellite apps. Rust (`apps/backend`) and TanStack Start (`apps/tanstack-web`) are paused and not in use. Docker setup is inactive and the Docker cron runner is retired. Retained migration designs describe a possible future, not live traffic or a current setup requirement. See the [active runtime map](/build/devops/active-runtime). ## Parallel test validation Mobile analysis and four Flutter test shards run independently. The stable `build` check requires analysis and every shard to succeed; a cancelled or unexpectedly skipped shard fails the gate. Flutter's native `--total-shards=4` and zero-based `--shard-index` partition all test files, with two processes per runner. Format, static analysis and Bloc lint run once in the analysis job. TypeScript unit tests and coverage each use four workspace shards. The planner in `scripts/ci/test-shards.js` assigns every workspace with a `test` script (except the paused TanStack app) exactly once, putting larger suites first and balancing by test-file count. Counts only guide scheduling: each workspace still runs its complete configured Vitest suite, preserving isolation, discovery and coverage thresholds. New test workspaces join automatically. Each runner uses at most two Turbo tasks with two Vitest workers per task. Coverage artifacts retain their workspace paths. Only after all shards pass does the coverage gate download the complete set and upload once to Codecov. Shard-specific fallback-cache families prevent concurrent jobs from competing for one cache entry. Main and production runs are never cancelled by a newer push; superseded feature-branch runs are cancelled. Inspect a shard locally with `node scripts/ci/run-test-shard.js 0 4 --plan`. Execute it through `ttr resources run -- node scripts/ci/run-test-shard.js 0 4` (or append `--coverage`). Reproduce a Flutter shard with `flutter test --total-shards=4 --shard-index=0 --concurrency=2` from `apps/mobile`. Use the resource queue locally rather than launching CI-sized parallel runner groups on one machine. Measure optimization using actual Actions step start/end times and aggregate runner minutes. Compare cold runs separately from Turbo cache hits. The prior observed unit and coverage test steps took 15m07s and 16m27s; the mobile test step took 4m04s after analysis. New timings must be measured on the changed workflow; increasing shard count alone is not proof of a speedup. ## The Problem Before centralized gating, workflows ran on every push regardless of: * Whether files relevant to that specific app or package actually changed * Whether the change only touched an unrelated app * Whether build artifacts were already cached With a large monorepo of apps and shared packages, this meant a single commit to one app could trigger dozens of unrelated build and deploy workflows, slowing feedback and congesting the Actions queue. ## How Gating Works Today Vercel affected-app gating does **not** rely on GitHub's native `on.push.paths` filters. Path filters are coarse (they cannot understand workspace dependency graphs), so the Vercel logic stays centralized. A narrow exception is the external-app compatibility build: its contract is simply "`apps/external` or any internal package changed," so native trigger paths can avoid creating a runner at all for unrelated app-only commits. The shared logic is organized in four pieces: 1. **`tuturuuu.ts`** — the source of truth. It exports a `ci` toggle map (each workflow can be globally enabled/disabled), the `vercelWorkflowTargets` table that maps each app to its preview/production workflow and package name, and the `getWorkflowDecision()` function that decides whether a given workflow is affected by a set of changed files. 2. **`scripts/ci/resolve-changed-files.ts`** — resolves the changed-file set for the current event (push payload, pull-request base/head, or git diff against the last successful deployment marker). 3. **`.github/workflows/ci-check.yml`** — the reusable gate for non-Vercel workflows that still need an individual `should_run` output. 4. **`.github/workflows/vercel-production.yaml`** — the single production planner. It resolves Vercel and Cloudflare apps against each app's last successful deployment marker in one runner, then calls affected workflows as reusable jobs in the same commit-associated push run. ### Reusable and inline gates Test and Coverage opt into `check_release_only: true` on the existing `ci-check.yml` job. One full-history sparse checkout at `github.sha` now resolves both the CI switchboard and the release-only comparison; callers use its separate `should_run` and `run_checks` outputs. Other callers retain the default `run_checks=true`. Missing, zero, invalid, or unavailable comparison SHAs and malformed manifests still default to running checks. A failed preflight cannot schedule the heavy jobs; shard aggregates still require every shard to succeed. The shared-preflight change removed three redundant runner allocations per push that creates Test, Coverage, and Type Check, without changing tests, shard counts, aggregate check names, or coverage uploads. The singleton Type Check exception below removes one additional allocation. It does not estimate elapsed time savings. Before removing the `Check release-only changes` jobs, live effective branch rules for `main` and `production` and ruleset `8839175` were checked: they required PR approval, code-owner review, and resolved threads, with no required status-check contexts; legacy branch protection was absent (verified on October 1, 2026). Recheck those rules before future check renames. Deployment-aware callers retain `deployments: read`. Run the focused contracts and decisions with: ```sh theme={null} node --test --test-concurrency=1 \ scripts/ci/ci-preflight-workflow.test.js \ scripts/ci/release-only-changes.test.js \ scripts/ci/check-workflow-config.test.js \ scripts/ci/resolve-changed-files.test.js ``` Type Check is a singleton exception: `type-check.yaml` evaluates the same changed-file, CI configuration, and release-only scripts directly inside its existing `Type Check` job. One full-history checkout pinned to `github.sha` serves preflight and the existing heavy steps. Only when both decisions are `true` do Bun setup, cache restore, install, dependency builds, and type checking run. Missing or uncertain comparisons still run checks; preflight script errors fail the named job before any heavy step. A disabled configuration skips release comparison as well as heavy steps; its absent release output cannot enable work. There is no condition override that continues after a failed step. Keep inline resolve/config/release wiring aligned with `ci-check.yml`; the workflow comment records intentional differences and `type-check-inline-workflow.test.js` compares the actual shell commands to protect parity. A configuration-disabled or release-only run now reports a successful `Type Check` job with heavy steps skipped and an explicit skip summary, instead of a skipped job. It does not claim compilation occurred. Effective GitHub rules for `main` and `production` still had no required status-check contexts when this change was prepared on October 1, 2026. The job name, triggers, runner label, and secrets remain unchanged. The whole singleton job explicitly uses `permissions: { contents: read }`; unspecified token permissions are `none`. This keeps preflight read-only and removes the heavy job's inherited write access. Checkout and Node setup need repository read access. Type Check's changed-file resolver uses push payloads or manual dispatch, not deployment API markers, and does not inject a token into its preflight environment. Bun setup, install, compiler commands, and the skip summary need no GitHub write grant. GitHub cache save/restore uses the Actions runtime token; Turbo remote caching uses its existing separately scoped credential. The workflow has no artifact upload, publishing, deployment, or custom check/status API step, so no privileged job is needed. GitHub Actions generates the named job check. Deployment-aware callers continue using the reusable gate with `deployments: read`. This singleton layout removes one additional runner allocation relative to the shared-preflight layout (two to one), or two relative to the earlier separate CI-config and release-only layout (three to one). It cannot affect runs already queued under older workflow source and does not establish the cause of hosted runner delays. Verify it with `node --test --test-concurrency=1 scripts/ci/type-check-inline-workflow.test.js` alongside the focused contracts above. Non-Vercel gated workflows can declare a `check-ci` job that calls `ci-check.yml`, then gate their real job on the result. Platform preview is different: it must complete on every protected `main` push so `supabase-staging.yaml` receives its workflow-run signal. Its deploy job checks configuration and affected paths inline, then skips install/build/deploy steps when the app is unaffected. This keeps the workflow signal while using one runner instead of a configuration runner followed by a deploy runner. ```yaml theme={null} jobs: Deploy-Preview: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: 24 - name: Compute changed files id: changed_files run: node --experimental-strip-types scripts/ci/resolve-changed-files.ts - name: Check preview configuration id: check_config run: node --experimental-strip-types scripts/ci/check-workflow-config.ts ``` Internally, `ci-check.yml` uses a sparse checkout (only the manifests and scripts it needs), computes the changed files, and runs the decision script: ```yaml theme={null} - name: Compute changed files id: changed_files env: GITHUB_TOKEN: ${{ github.token }} WORKFLOW_NAME: ${{ inputs.workflow_name }} run: node --experimental-strip-types scripts/ci/resolve-changed-files.ts - name: Check Configuration id: check_config env: CHANGED_FILES_FILE: ${{ steps.changed_files.outputs.changed_files_path }} WORKFLOW_NAME: ${{ inputs.workflow_name }} run: node --experimental-strip-types scripts/ci/check-workflow-config.ts ``` The scripts run with Node's `--experimental-strip-types`, so the `.ts` sources execute directly without a separate build step. Trusted manual satellite preview workflows launch their guarded deploy job directly: manual dispatch already bypasses affected-path gating, so a reusable preflight would only add a second queued runner. These workflows remain protected by the `main` dispatch ref, `TRUSTED_PREVIEW_DEPLOY_ACTORS`, and their GitHub Environment. Preview concurrency is keyed by workflow and `preview_ref`; a repeated request for the same preview cancels stale work, while different preview refs remain independent. ### The production planner A `production` push starts one `plan` job instead of starting one `check-ci` runner per Vercel app. `resolve-production-vercel-targets.ts` reads the workspace graph once, memoizes dependency closures, resolves each target from its own successful deployment marker, and emits a reviewable Actions summary. Static reusable jobs call selected Vercel and Cloudflare workflows, so deployments stay attached to the original push SHA instead of appearing as detached `workflow_dispatch` runs. Per-app production workflows remain independently protected by their GitHub Environment and a static per-app concurrency group. The group must include the app identifier because reusable workflows inherit caller context; a shared caller-derived key would cancel sibling deployments and show red X statuses instead of clean skips. They accept `workflow_call` for commit-driven planner jobs and retain `workflow_dispatch` for deliberate operator reruns. Their `cancel-in-progress` predicate is enabled only for a `production` push, so a `main` commit or manual recovery run cannot cancel an active production deploy. A missing or untrusted marker fails open for that app without forcing every other app's gate open. Colab, Coordination, Lettin, Meet, and Parley use the same per-app marker baseline. Their production push deployments are called by the planner; their `main` and pull request validation runs remain independent. Markers are recorded only after deployment verification, so a failed Cloudflare deploy is selected again on the next production push. Coordination uses its worker and coordination utility paths; the other apps use their workspace dependency closure and any explicitly shared runtime paths. ### The decision function `getWorkflowDecision()` in `tuturuuu.ts` resolves to `should_run` using this order of precedence: 1. **Global toggle.** If the workflow is `false` in the `ci` map, it never runs. 2. **`workflow_dispatch` bypass.** Manual runs always proceed (affected-path gating is skipped), so you can force a deploy from the Actions UI. 3. **Other workflows.** Workflows without an entry in `vercelWorkflowTargets` or `cloudflareProductionTargets` fall back to their static `ci` toggle. 4. **Unavailable change data.** If the changed-file set cannot be resolved, the gate stays **open** (`should_run = true`) to fail safe. 5. **Affected-path matching (deployment workflows).** The workflow runs only if at least one changed file matches one of: * a **global affecting path** (`bun.lock`, `package.json`, `turbo.json`, the shared Bun/remote-cache actions, or Vercel's deterministic metadata generator); * the workflow's **own** workflow file; * the target app's directory (e.g. `apps/web/**` for the platform target); * any package inside the target app's **workspace dependency closure**. The closure is built from `workspace:*` dependencies, so editing a shared package only triggers the apps that actually depend on it. Cloudflare Meet also watches its signaling Worker and meeting API paths. Coordination is a Vite+ workspace. Its worker and coordination utility paths remain explicit so source-level shared contracts also trigger validation. If nothing matches, the decision is `should_run = false` and the heavy job is skipped. ### Vercel target table Every Vercel app is registered once in `vercelWorkflowTargets`. Adding a new app means adding a single entry there (app slug, app path, package name, and the preview/production workflow filenames) — the gating logic and changed-file matching then apply automatically. ```ts theme={null} { app: 'platform', appPath: 'apps/web', packageName: '@tuturuuu/web', previewWorkflow: 'vercel-preview-platform.yaml', productionWorkflow: 'vercel-production-platform.yaml', } ``` **Applied to:** the 24-target production planner, the inline platform preview gate, and other gated CI workflows wired through `ci-check.yml`. The other 23 preview workflows are trusted manual dispatches and therefore do not allocate a standalone configuration runner. ## Build Caching Once a workflow decides it must run, cacheable JavaScript work is invoked from the repository root through `.github/actions/run-with-turbo-remote-cache/action.yml`: ```yaml theme={null} - name: Type check uses: ./.github/actions/run-with-turbo-remote-cache with: command: bun turbo:local run type-check --concurrency=4 token: ${{ secrets.TURBO_TOKEN }} team: ${{ vars.TURBO_TEAM || secrets.TURBO_TEAM }} ``` The composite action exposes credentials only to the wrapped command step. It runs locally when both token and team are absent, rejects a token without a team, and keeps Turbo's local rebuild behavior available if the remote service is unavailable. `TURBO_TOKEN` must never be passed to pull-request or Dependabot jobs. Those jobs restore a task-family-scoped `.turbo` fallback from GitHub's cache without writing shared entries; trusted default-branch jobs seed that fallback. The shared Bun runtime and package-download caches follow the same ownership rule: only trusted `main` jobs save entries. Production, pull-request, Dependabot, and other branch jobs restore the default-branch cache without creating branch-scoped duplicates. This is especially important for Bun's package cache, which can approach 1 GB for the full monorepo lockfile. Turborepo hashes inputs and reuses cached task outputs, so unchanged builds, type checks, and tests resolve to cache hits instead of recompiling. The task graph includes transit-only dependency nodes for tests: dependency source changes invalidate downstream tests without running every dependency's test suite. Build outputs include framework output, coverage, and TypeScript incremental state where those artifacts are deterministic. Output-affecting environment values are hashed, while CPU, heap, and concurrency controls are pass-through values. Every active Vercel project has a checked-in `buildCommand` that invokes its full workspace build through root Turbo. The 48 deployment workflows generate deterministic source metadata and then wrap `vercel build`; they do not run a separate dependency prebuild. This lets an unchanged full app build restore as one task while `.vercel/output` remains an in-job handoff to `vercel deploy --prebuilt`, not an uploaded artifact or generic cache. Docker and Rust verification use the same principle at their native cache layers. Each shared GitHub BuildKit scope has one trusted `main` writer: Docker setup owns web, TanStack, and storage scopes; Rust CI owns the backend scope; and E2E shard 1 owns the small leaf-service scopes. Production, other shards, and migration E2E restore without exporting. Expensive web, TanStack, and backend images use `mode=max`; validation-only development and small leaf images use `mode=min` or restore-only caching. Dockerized E2E jobs explicitly select a `docker-container` Buildx builder so Compose can import and export the GitHub cache backend. Turbo values enter image builds only as BuildKit secrets. Rust verify and deploy jobs share one pinned, toolchain-aware Cargo cache, with writes restricted to protected branches. Flutter workflows cache dependencies and native tool state (pub, Gradle, and CocoaPods), never final APK, AAB, IPA, archive, or application-bundle outputs. Dependency resolution and the platform build always execute so a cache hit cannot skip validation. Managed uv and CodeQL caches remain owned by their upstream actions rather than being duplicated. Automatic CodeQL is owned by GitHub's organization-managed `dynamic/github-code-scanning/codeql` workflow, which scans JavaScript/TypeScript and Python. The checked-in `.github/workflows/codeql.yml` is manual-only: it preserves an explicit fallback and avoids the Security UI's missing-workflow warning without adding push, pull-request, or cron duplicates. `bun git-sync` mirrors the already-scanned `main` SHA to `production`. The full Dockerized E2E graph is created for E2E specs, Playwright and Docker configuration, database fixtures, package manifests, lockfiles, and its own runner scripts. Ordinary application source commits do not create six expensive E2E consumers. There is no cron schedule: automatic E2E runs are commit-driven and path-scoped, while manual dispatch remains available for deliberate validation. E2E uses native push paths and launches its image producer directly, without an extra static switchboard job. Supabase staging and production migrations use the last successful migration deployment marker as their change-range baseline. Each workflow resolves the entire pending range, fails open when no trustworthy marker exists, and runs `supabase db push --include-all` only when `apps/database/**` or migration control files changed. Evaluation and deployment share one serialized job per environment, so no-op workflow-run signals finish quickly while database migrations cannot race. Production still requires the successful same-SHA platform deployment marker and staging migration before applying changes. ## Runner And Storage Policy Tuturuuu is a public repository in a GitHub Free organization. Standard hosted Linux and Windows jobs are budgeted for 4 CPUs and 16 GB RAM; the organization can run 20 jobs concurrently, including at most 5 macOS jobs. CPU-bound Turbo checks therefore default to concurrency 4. Memory-heavy Next.js and Docker stages limit inner build concurrency to 2 and retain an 8 GB Node heap. Keep independent jobs parallel, keep macOS matrices below the platform limit, and do not switch to billable larger runners as a cache optimization. The live repository cache configuration, queried through GitHub's API, is a 10 GB maximum with 7-day retention. The weekly Actions resource report groups cache usage by key prefix and reports informational status at 80%, warning at 90%, and critical status at 100%. It also reports artifact count, bytes, age, and largest workflow families without enforcing a fixed artifact byte cap. Steady-state cache usage should stay below 9 GB to leave eviction headroom. The July 10 audit observed active usage temporarily above the configured limit; that is eviction lag and cache churn, not an additional open-source allowance. Artifacts are retained only as long as their handoff or diagnostic value requires: * E2E and Playwright diagnostics: one failure-only artifact per shard or migration mode, 7 days. * Package-release tarballs: 1 day with compression disabled. * Mobile development deliverables: 7 days; production store deliverables: 14 days. Pre-compressed bundles are archived first and uploaded without redundant compression. * Discord JUnit and Cloudflare smoke diagnostics: failure-only or explicit 7-day retention as applicable. Every artifact upload must declare both retention and missing-file behavior. Required release outputs fail when absent; optional diagnostics may warn. Closed trusted pull requests delete cache entries scoped to their merge ref. Legacy broad Turbo, run-ID Supabase, final Flutter-output, and old Rust cache prefixes are removed manually only after their replacements demonstrate hits; default-branch CodeQL caches are never part of automated cleanup. > [!NOTE] > > Earlier versions of these workflows ran an inline Turborepo `--dry-run=json` > step to *decide* whether to skip a build. That per-workflow skip step has been > removed in favor of the centralized `ci-check` gate above. Turborepo is now > used for caching the build itself, not for the run/skip decision. ## Race-Condition Handling Production deployments serialize each app and branch with GitHub Actions concurrency: ```yaml theme={null} concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'push' && github.ref == 'refs/heads/production' }} ``` When another production commit arrives, GitHub cancels the superseded run and keeps the newest run deployable. Older runs no longer finish green after skipping every deployment step, which makes queued and deployed SHAs observable without allowing stale artifacts to replace newer production code. Commits that exist only on `main` and manual recovery dispatches leave an active production deployment running. Affected-app gating always diffs the newest SHA against the last successful deployment marker. If no trustworthy marker is available, the gate fails open and runs the deployment instead of considering only the newest push payload; this preserves app changes from canceled intermediate commits. ## Edge Case Handling `resolve-changed-files.ts` and the gate are written to fail safe. ### Missing or unresolvable change data If the changed-file set cannot be computed (e.g. an unusual event payload or a missing base commit), `getWorkflowDecision()` returns `should_run = true`. The guiding principle: **build when uncertain** rather than skip incorrectly. ### Initial commits and shallow clones When a parent commit is unavailable (the very first commit, or a shallow clone without history), the changed-file resolver cannot diff against a base, so the gate opens and a full build runs. The workflow that needs deeper history checks out with an appropriate `fetch-depth`, and `ci-check.yml` uses `fetch-depth: 0` with a sparse checkout so it always has enough history to diff. ### Last-successful-deployment markers For push events, the resolver can diff against the SHA of the last successful deployment (recorded as a GitHub deployment marker) rather than only the parent commit. This catches the case where intermediate commits never deployed, so the full diff since the last live deploy is considered. ## Monitoring & Debugging ### Inspect the gate decision `check-workflow-config.ts` logs its decision and the matched paths. Preview `check-ci` logs show the individual decision; production uses the planner's **Production Vercel deployment plan** job summary, including the per-app baseline source and deploy/skip result. Individual logs still look like: ```text theme={null} Workflow: vercel-production-platform.yaml Should run: false Reason: vercel-production-platform.yaml is unaffected by the changed paths ``` or, when it does run: ```text theme={null} Should run: true Reason: vercel-production-platform.yaml is affected by 3 changed path(s) Matched paths: - apps/web/src/app/page.tsx - packages/ui/src/button.tsx ``` ### Reproduce a decision locally You can run the decision script directly to debug why a workflow did or did not run: ```bash theme={null} CHANGED_FILES="apps/web/src/app/page.tsx" \ WORKFLOW_NAME="vercel-production-platform.yaml" \ node --experimental-strip-types scripts/ci/check-workflow-config.ts ``` There are also unit tests covering the gating logic: ```bash theme={null} node --test scripts/ci/check-workflow-config.test.js node --test scripts/ci/resolve-changed-files.test.js node --test scripts/ci/resolve-production-vercel-targets.test.js ``` ### Common Issues #### Issue: A workflow never runs for legitimate changes **Likely causes:** * The app is missing (or misconfigured) in `vercelWorkflowTargets`. * The changed package is not in the target app's workspace dependency closure (the app does not actually `workspace:*`-depend on it). * The workflow is toggled off in the `ci` map in `tuturuuu.ts`. **Fix:** Verify the target entry and the dependency edges, then re-run the local reproduction above to confirm the decision. #### Issue: A workflow always runs **Likely causes:** * A global affecting path (`bun.lock`, `package.json`, `turbo.json`, `tuturuuu.ts`) changed — these intentionally trigger every Vercel target. * The change-data resolver failed, so the gate fell open by design. This is usually correct behavior; only investigate if it persists for changes that clearly do not touch shared roots. #### Issue: Need to force a run Use the app workflow's manual trigger. A direct `workflow_dispatch` starts that app without re-running affected-path gating: ```yaml theme={null} on: workflow_dispatch: ``` ## Performance Impact The exact savings depend on the size of the app set and how localized each commit is, so treat the following as **illustrative** rather than a fixed figure. The monorepo currently registers **24 active Vercel app targets**, each with a preview and a production workflow (**48 Vercel deploy workflows**), out of 91 workflow files. Production planning prevents a single-app change from creating 23 unrelated production runners. Preview workflows create a runner only for the inline platform signal or an explicitly requested satellite preview. For a change that touches only one app: ```text theme={null} 1 production planner workflow + only the affected app deployment workflows + one inline platform preview gate on protected main + direct satellite preview jobs only when explicitly dispatched ``` Each skipped production app now consumes no runner at all; only the shared planner and selected reusable deployment jobs run under the production push. Changes to shared roots (`package.json`, `bun.lock`, `turbo.json`, `tuturuuu.ts`) intentionally fan out to all targets, so headline skip rates will vary with how often those roots change. > [!NOTE] > > To measure real-world impact, inspect the production planner's job summary and > compare its selected workflow count with the 24 registered targets. Platform > preview reports its inline decision in the deploy job; manual satellite > previews have no separate gate job. ## Best Practices ### 1. Keep `tuturuuu.ts` as the source of truth When adding an app or workflow, register Vercel app metadata in `vercelWorkflowTargets` and register automatic switchboard-controlled workflows in the `ci` map. Trusted manual satellite previews and intentionally path-triggered compatibility smokes do not keep unused `ci` toggles. The gate and the tests key off these boundaries. ### 2. Trust the fail-safe When change data is missing, the gate opens and the workflow runs. This is intentional — it is safer to build unnecessarily than to skip a real change. Don't add ad-hoc skip logic that defeats it. ### 3. Model dependencies with `workspace:*` The dependency-closure matching only works because shared packages are wired as `workspace:*` dependencies. If an app consumes shared code without declaring the dependency, the gate will not know to run it when that package changes. ### 4. Use `workflow_dispatch` to debug To bypass gating for a one-off investigation, trigger the workflow manually from the Actions UI rather than touching the gate logic. ### 5. Update tests when changing the gate `getWorkflowDecision()` and the resolver are covered by unit tests under `scripts/ci/`. Update them alongside any change to the matching rules so the behavior stays pinned. ## Further Reading * [CI/CD Pipelines](/build/development-tools/ci-cd-pipelines) * [TanStack + Rust migration](/platform/architecture/tanstack-rust-migration) * [Turborepo: Remote Caching](https://turborepo.com/docs/core-concepts/remote-caching) * [GitHub Actions: Reusing workflows](https://docs.github.com/en/actions/using-workflows/reusing-workflows) ## Summary Our CI/CD optimization centralizes change detection so each workflow stays thin: * Reusable `ci-check.yml` calls remain available where a separate gate is necessary; production planning and platform preview avoid per-app preflight fan-out. * `tuturuuu.ts` decides, per workflow, whether the change is relevant — including workspace dependency-closure awareness for shared packages. * The remote-cache wrapper keeps Turbo credentials step-scoped and gives secretless jobs a GitHub-backed local fallback. * Turborepo caches full app builds, type checks, tests, and release preparation once a run is warranted. * The gate fails safe (builds on uncertainty), and trusted manual satellite previews start their guarded deploy job directly. The result: a one-app change selects only the necessary production deploys in the commit-associated push run, platform preview retains its required staging signal without a second runner, manual previews never queue a redundant preflight, and superseded previews are canceled before they occupy the queue indefinitely. ## Runner Queue Efficiency Translation validation runs on every pull request (including forks and stacked PRs), plus direct pushes to `main` and `production`. Feature-branch pushes no longer duplicate the same four translation checks alongside the pull-request run. Manual dispatch remains available for work without a PR. Superseded feature-branch translation and E2E runs cancel; protected branch runs retain their exact-commit verification evidence. E2E keeps all four general shards and all six isolated invitation cohorts. Only the first general shard writes the shared Supabase image cache on a cold main run. Invitation cohorts also have `shard: 1`, so checking only that field caused seven jobs to serialize and compete to upload the same multi-gigabyte archive. Failure artifacts use the unique matrix ID so separate invitation failures do not collide on the same artifact name. Run `node --test scripts/ci/runner-efficiency.test.js` to verify trigger coverage, the single cache writer, cohort preservation, artifact uniqueness, and protected branch cancellation policy. More matrix jobs are not automatically faster: runner queue time and repeated database/container startup must be considered alongside test duration. # CI/CD Pipelines Source: https://docs.tuturuuu.com/build/development-tools/ci-cd-pipelines High-level CI/CD overview, with current operational runbooks linked from one place. > [!NOTE] > > Current runtime policy: Docker setup and Docker-backed E2E/image CI are paused; > the Docker cron runner is retired. Rust and TanStack Start are not in use and > remain paused for runtime and deployment. The branch-scoped hosted Rust source > qualification below is the authorized exception for this release integration; > it does not activate either migration runtime. Retained Docker and > migration sections below are historical procedures. Current hosted Next.js, > package, Worker, database, and mobile workflows retain their own gates. See the > [active runtime map](/build/devops/active-runtime). This page is the entry point for CI/CD. The day-to-day operational detail now lives in the dedicated DevOps pages below so the docs stay current as workflows change. ## Read Next * [DevOps & Deployment Overview](/build/devops/overview) * [Environments & Release Flow](/build/devops/environments-release-flow) * [Web Docker Deployment](/build/devops/web-docker-deployment) * [GitHub Actions Runbook](/build/devops/github-actions-runbook) * Secrets & Configuration ## Current CI/CD Shape Tuturuuu currently automates: * Vercel preview deployments for non-`production` branches * Vercel production deployments from the `production` branch * Independent Vercel preview and production deployments for satellite apps such as `apps/cms` * Affected-app gating for Vercel deployments before dependency install, build, or deploy work * Supabase staging migrations driven from `main` and production migrations driven from `production` * Docker parity and image validation for the self-hosted web runtime * Modal deployment for `apps/discord` * Mobile build artifact generation * Package publishing to npm * Quality, lint, type, test, and security checks ## Important Repo Conventions * For most authored changes, run the applicable check, lint, test, and build workflows in CI and verify their results on the exact commit. Focused local checks help find problems quickly but do not replace that CI evidence. If a workflow queue is demonstrably stuck, record the pending jobs and local results; resume the exact-commit CI checks before claiming release readiness. * `ci-check.yml` reads `tuturuuu.ts` and can disable an individual workflow centrally. * Vercel workflows use `tuturuuu.ts` app metadata and workspace `workspace:*` dependency closures to run only affected app deploys. * `bun.lock` changes run all Vercel app deploys because lockfile ownership is ambiguous without a source or manifest path. * Manual `workflow_dispatch` runs enabled workflows even when changed paths would otherwise be unaffected. * Production Vercel workflows cancel superseded per-app runs only for newer `production` pushes. A `main` commit or manual recovery run never cancels an active production deployment. * The external-app internal-package build uses the same cancel-superseded policy, so rapid pushes cannot finish as green no-op builds. * Database migrations are not treated the same as app deploys; staging and production each have explicit prerequisite logic, with staging now sourced from `main`. * Docker setup and image-build CI (`docker-setup-check.yaml`) are disabled, including manual dispatch, until explicitly resumed. ## Inline Type Check preflight regressions `type-check.yaml` runs `node --test --test-reporter=tap scripts/ci/type-check-inline-workflow.test.js` on its exact checkout with Node 24, after the existing Setup Bun step and before dependency installation. Bun is required by the workflow YAML test helper; these 21 regression cases need no workspace dependency installation. The step uses the existing configuration and release-relevance gates. A skipped step is not test evidence. Before merging a preflight fixture change, verify the exact-head hosted step succeeded and its TAP summary reports 21 tests, 21 passes, and zero failures, cancellations, skips, or todos. ## Worker validation caching Cron Control and Devbox Control run package build, test and type-check tasks through the existing Turbo remote-cache action with explicit workspace filters. Meet Realtime uses the same action for build and type-check. Worker builds restore the declared `dist/**` outputs before emitted-artifact verification. Cron Control and Devbox Control generate binding types before cached type checks because the generated `.d.ts` file is not a declared type-check output. Lint, source and emitted runtime checks, SQLite and Durable Object verification, and deploy dry-runs still run directly. Remote credentials remain step-scoped and are supplied only to trusted main or production runs, never untrusted PRs. ## Hosted root script qualification The `Test` workflow runs the complete selection exported by `scripts/run-script-tests.js` in a separate `Root script tests (24)` job on the exact checkout. Node 24 runs it with two test-file workers and the TAP reporter; the existing paused-runtime discovery policy remains unchanged. No shell glob or subset replaces the canonical selection. The job installs the frozen dependencies with the existing Bun setup, verifies Ruby and `@playwright/test` resolution, and exposes the owning Web dependency location through `NODE_PATH`. It needs no application secrets, browser install, workspace build, deployment, or production action. The unit-test aggregation requires successful package shards or verified duplicate package evidence, and always requires the fresh root script job to succeed when checks are relevant. Configuration and release-relevance gates still apply. The root script job does not reuse the package-shard duplicate-validation result. A skipped job or green package shards do not prove root script qualification: require the exact-head job, prerequisite results, complete discovery count, and full TAP summary. Historical failures remain unresolved until their actual cases pass on the qualified source; do not infer a fix from a different branch's test bytes. ## Hosted Rust source qualification On `fix/release-5795-reconciliation` and `fix/main-production-reconciliation-20261012`, the existing `Test` workflow runs `Rust source qualification (1.95)` after the shared configuration and release relevance gates. The read-only job checks out the exact workflow commit, records its SHA and Cargo manifest/lock hashes, and uses pinned Rust 1.95.0 with two Cargo build workers. It runs formatting, warning-denying native Clippy, all native library tests with two test threads, and the wasm Worker target check against the locked dependency graph. It needs no application secrets or deployment action. The stable `Unit Tests (24)` aggregate requires this fresh job to succeed on those branches, including when verified package duplicate evidence skips shards. A skipped Rust job or successful root script tests do not qualify Rust: require the exact-head job and its complete Cargo results. Other branches retain their existing package/root gates. The standalone Rust workflows, TanStack migration, and backend deployment remain paused; the backend is a future migration target, and Web continues to serve the live API. ## Cross-app users-core regression tests The canonical approval regressions live outside the package source tree: * `packages/users-core/tests/approvals/get-tenant-boundary.test.ts` * `packages/users-core/tests/approvals/review-reads-tenant-boundary.test.ts` The source type-check project keeps `rootDir: "src"`. Vitest discovers the cross-app tests separately through `packages/users-core/vitest.config.ts`; relocating these tests does not expand the package's source compiler boundary. That config maps the Web-specific imports `@/lib/post-email-queue` and `@/features/reports/report-limits` to their exact `apps/web/src` files before its default `@` alias, which still points to `packages/users-core/src`. The exact `@tuturuuu/satellite/auth` mapping points to `packages/satellite/src/auth.ts`; it keeps the satellite namespace separate from the package-local `@` imports. Run selected tests from `packages/users-core` with that canonical config and the receiver's qualified dependencies. For a source `TS6059` error, check that the cross-app test is outside `src`. For a Vitest module-resolution failure, check the owning cwd, specific alias destination, and installed dependency closure before changing compiler roots or alias scope. A config/source handoff or historical donor test and type results do not prove the current receiver's test, type, CI, or runtime outcome. ## When To Use This Page Use this page for orientation. Use the DevOps pages for the runbook you actually need while operating the system. ### Learn preview build validation The trusted manual `vercel-preview-learn.yaml` workflow builds the checked-out `preview_ref` with a 35-minute timeout and the existing two-task Turbo limit. It records a `build` marker using `git rev-parse HEAD`, rather than the main workflow dispatch SHA. It does not deploy the artifacts. Learn build markers cannot advance the successful deployment baseline; existing Platform marker compatibility remains unchanged. A successful build proves compilation, while actual-device validation and deployment are separate gates. Focused checks: `node --test scripts/ci/learn-preview-build.test.js scripts/ci/github-deployment-markers.test.js scripts/ci/release-workflows.test.js`. ### Generated release inventory Release Please owns platform and independent package version changes. Release normalization derives only `apps/docs/reference/repository/versions.mdx` using the complete documentation inventory generator. Other stale inventory pages fail the job; this phase does not repair unrelated source or navigation changes. Before updating the generated PR, the workflow captures its previous immutable head. A retained versions page must match either the production page, the new complete projection, or the independently verified projection at that captured head. Changed generator/configuration sources and unproven docs bytes fail closed. The amended generated commit keeps its release annotations and is pushed using its exact head lease. Concurrent updates reject that push. Auto-approval verifies the final immutable page before rechecking the PR head and base. `bun git-release-please` also regenerates this page after resolving the platform version during integration and before validation or commit. Run `node scripts/ci/release-docs-inventory.js --verify BASE HEAD` to verify immutable release output. This is derived source evidence, not a publication or deployment receipt; failed release PR checks continue to block auto-integration. # Cleaning Your Tuturuuu Clone Source: https://docs.tuturuuu.com/build/development-tools/cleaning-clone How to reset your local Tuturuuu repository to a clean state. > [!NOTE] > > This guide helps you reset your Tuturuuu repository to a clean state, which is > useful if you encounter dependency issues or want to ensure a fresh > development environment. The current stable pin is Bun `1.4.4` ([official release](https://github.com/oven-sh/bun/releases/tag/bun-v1.4.4)). Keep active workspace metadata and CI pins aligned with the root `packageManager`. Change manifest metadata with `bun pm pkg set packageManager=bun@1.4.4` in each owning workspace. An updated pin does not upgrade an installed host or runner; verify `bun --version` separately. Retained paused runtime files and historical reproduction notes keep their original versions. ## Prerequisites * Ensure you have [bun](https://bun.sh/) installed. The repository pins a specific Bun version via the `packageManager` field in the root `package.json` (currently `bun@1.4.4`) — match that version so your local toolchain stays in sync. * Use the Node.js version pinned in the root `.node-version` (currently `26.12.1`). The root `engines` field keeps a `>=22.13.0` support floor; see [Node.js runtime pin](/build/development-tools/node-runtime). ## Quick Cleanup (Recommended) The repository ships a one-shot root script that performs the full cleanup for you: ```bash theme={null} bun clean ``` This removes `bun.lock`, deletes every `node_modules` directory, and clears all `.next` and `.turbo` build caches across the monorepo (it uses `npkill --delete-all` under the hood). After it finishes, reinstall everything: ```bash theme={null} bun i ``` > [!TIP] > > `bun clean` is the supported shortcut for the manual steps below. Reach for the > manual steps when you want finer control over which folders are removed. ## Manual Cleanup (Granular Alternative) ### 1. Delete the lockfile Remove the `bun.lock` file at the root of your repository (if it exists): ```bash theme={null} rm bun.lock ``` ### 2. Remove all `node_modules` folders Use [npkill](https://github.com/voidcosmos/npkill) to find and remove all `node_modules` directories: ```bash theme={null} bunx npkill ``` * In the `npkill` interface, select and delete all `node_modules` folders found in your repo. > [!TIP] > > If you don't have `npkill` installed, `bunx` will download and run it > automatically. ### 3. Clear build caches (optional) Remove stale `.next` and `.turbo` build caches if you suspect they are causing issues (the `bun clean` shortcut does this automatically): ```bash theme={null} find . -name node_modules -prune -o \( -name .next -o -name .turbo \) -type d -exec rm -rf {} + ``` ### 4. Reinstall dependencies Install all required dependencies using bun: ```bash theme={null} bun i ``` This will install fresh dependencies for all apps and packages in the monorepo. > [!NOTE] > > After completing these steps, your repository should be in a clean state. You > can now continue with the usual development workflow as described in > [Development](/build/development-tools/development). ## Troubleshooting * If you still encounter issues, try restarting your IDE or terminal. * Make sure your bun version is up to date: `bun upgrade`. * If problems persist, check the [Development](/build/development-tools/development) guide or ask for help in the project discussions. # Codex Plugin Source: https://docs.tuturuuu.com/build/development-tools/codex-plugin Use and maintain the local Tuturuuu Codex plugin. The local Tuturuuu Codex plugin lives at `plugins/tuturuuu`. It packages repo-specific operating knowledge as Codex skills so future agent sessions can load focused guidance without copying long instructions into every prompt. ## Maintaining focused agent guidance Tuturuuu skills support a specific operation. Discover the capability from its short description, read its entrypoint when needed, then open only the relevant reference section. CLI task capture, finance reads, CLI implementation, and PR integration have different procedures; using one does not require all the others. This organization follows OpenAI's [Rethinking skills and prompts for GPT-6 Astra](https://developers.openai.com/blog/rethinking-skills-and-prompts-for-gpt-6-astra). The guidance remains model-neutral: preserve repository invariants while letting the agent choose routine implementation details. The maintained source is `plugins/tuturuuu/skills`. Audit all skill descriptions, entrypoints, and `agents/openai.yaml` prompts there. Keep existing short skills when their boundaries are already clear. Update source packages rather than installed plugin caches or third-party skill copies. App `CLAUDE.md` aliases and generated Next.js instruction blocks retain their canonical owners. | Work | Guidance to load | | - | - | | CLI install/auth/implementation | `tuturuuu-cli`, then relevant CLI procedure | | Task capture or templates | `tuturuuu-cli-tasks`, then task or template procedure | | Finance read or mutation | `tuturuuu-cli-finance`, then finance diagnostics/examples | | Rollback or shared API rollout recovery | `tuturuuu-rollout-recovery`, then live graph and recovery evidence | | Declarative database adoption readiness | `tuturuuu-database/references/declarative-schema-adoption.md`, read-only checker and baseline evidence gates | | PR integration | `tuturuuu-pr-merge-sync`, then merge gates and watcher commands | | Skill or prompt audit | `tuturuuu-development-tooling/references/agent-guidance-review.md` | Task prompts should name the desired outcome, relevant constraints, and completion boundary. For example: "Fix the invoice loading failure, verify recovery, open a PR, and merge only after 15 minutes without new review activity, zero unresolved review threads, and green checks on the current head." The duration belongs to that request; it does not change the default for every future PR. Required checks, ownership, production data protections, and migration parity still apply. The default quiet window for PR merge sync and automated Release Please merges is five minutes when a request does not specify a duration. For dependent PR work, the merge skill uses native GitHub stacks as the daily default. Follow [stack operations](/build/development-tools/stacked-pull-requests) for `gh stack` adoption, worktree ownership, cascading fixes, and verified prefix merges. The official upstream skill is installed at `.agents/skills/gh-stack` from `github/gh-stack@v0.2.0`, with installer source metadata. Preserve its upstream content and review updates; repository rules override generic upstream examples. Apply review, quiet-window, and exact-head checks to every included layer; register each PR with the T3 thread when linking tools are available. Manual chains are a documented fallback for concrete limitations. A main-only merge request ends after main verification; production sync still needs production authorization. For authorized parallel work, follow the [autonomy contract](https://github.com/tutur3u/platform/blob/main/plugins/tuturuuu/skills/tuturuuu-agent-coordination/references/program-orchestration.md#autonomy-and-asynchronous-waits). Use useful subagents for independent ready backlog while PR/CI or resource gates run. Arrange child work before arming a native PR watch, then end the turn as the tool requires; native result/watch events resume delivery without a user reminder. Relay the policy, project instructions, current custody overrides and remaining child budget in each brief. The agent operating model allows up to 10 subagents per thread tree, including descendants. That number is a contract plus checker, not a runtime-enforced or observed live-session limit. Leads receive explicit remaining budgets, and lower observed runtime, provider and resource limits still apply. After observed delays or unnecessary handovers, use a bounded child workflow audit at a safe checkpoint. Apply accepted improvements to maintained source, then refresh the plugin through its installer and compare the resolved cache content. Already-running agents need the update in their next substantive brief; new files do not retroactively change a live session. Preserve permissions, exact-head verification, paused predecessors and urgent release priority. Finished repository work includes scoped commits and a normal push without a separate user reminder. Follow the [completion contract](https://github.com/tutur3u/platform/blob/main/plugins/tuturuuu/skills/tuturuuu-agent-coordination/references/program-orchestration.md#completion-and-publication) for branch/review gates, shared-index ownership and blocked-publication receipts. A push does not certify CI, merge or production delivery. A plugin validator proves structural validity, not better model behavior. Review representative read, mutation, implementation, and delivery requests for correct routing. Record any isolated behavioral evaluation separately. Live product AI prompts need their own behavior evaluation before changing their contracts. ## Typed workspace boundaries `@tuturuuu/utils/workspace-id` owns the framework-free `workspaceIdSchema` and its inferred `WorkspaceId` type. Construct the brand only through the schema. It accepts UUID literals (including the root UUID), `personal`, and `internal`; alias casing and surrounding whitespace use the existing workspace-context normalizer. Empty input is invalid, rather than defaulting to a personal workspace. The first adoption is template background GET/HEAD. Preserve authentication and call the existing `normalizeWorkspaceId` before parsing its result: this retains personal workspace lookup and custom handle resolution. Keep the existing `400 { error: 'Invalid workspace ID' }` error envelope and pass the parsed ID to `getBackgroundTemplate`, whose parameter rejects an unparsed string. Membership, workspace filtering, creator and visibility checks still enforce authorization. Other resource families retain their current types and responses. Regression coverage lives in `packages/utils/src/__tests__/workspace-id.test.ts` (UUID/alias tables, deterministic fast-check properties and type assertions), the colocated template background route tests (normalization, error responses, HEAD and tenant isolation), and `apps/web/src/__tests__/board-template-background-authorization.test.ts`. Adopt this pattern one resource at a time, preserving its error contract and testing alias resolution and access checks before publication. ## Discovery Codex discovers repo-local plugins through `.agents/plugins/marketplace.json`. The Tuturuuu marketplace is named `tuturuuu`, displays as `Tuturuuu`, and points its local plugin entry at `./plugins/tuturuuu`. After changing marketplace metadata or plugin files, validate the plugin and refresh the repo-local marketplace from the repo root. Do not bump `plugins/tuturuuu/.codex-plugin/plugin.json` `version` for ordinary authored workflow updates unless a release workflow or user request requires it. The repo-local plugin manifest is currently refreshed to `0.2.23`. ```bash theme={null} codex plugin marketplace add ./ ``` Restart Codex after refreshing the marketplace. Then open the plugin directory, choose the `Tuturuuu` marketplace, and install or update the `Tuturuuu` plugin. If Codex does not show the repo marketplace after restart, add the repo root as a local marketplace source from the CLI: ```bash theme={null} codex plugin marketplace add ./ ``` ## skills.sh Discovery The public skills.sh registry discovers skills from GitHub repositories after someone installs the repo with the `skills` CLI. The platform repo exposes the Tuturuuu plugin skills for that flow through two root metadata files: * `.claude-plugin/marketplace.json` points compatible skill installers at `plugins/tuturuuu/skills`. * `skills.sh.json` groups the public repo page so Tuturuuu skills appear ahead of unrelated installed project skills. Do not run the public install trigger before the metadata is pushed to GitHub. After pushing the metadata commit, run the trigger from a disposable directory, not from this checkout: ```bash theme={null} npx skills add tutur3u/platform --agent codex --copy -y \ --skill tuturuuu-agent-coordination \ --skill tuturuuu-browser-vercel-debugging \ --skill tuturuuu-ci-docs \ --skill tuturuuu-cli \ --skill tuturuuu-cli-resources \ --skill tuturuuu-cli-finance \ --skill tuturuuu-cli-tasks \ --skill tuturuuu-cms-studio \ --skill tuturuuu-commit \ --skill tuturuuu-database \ --skill tuturuuu-devbox-ops \ --skill tuturuuu-development-tooling \ --skill tuturuuu-e2e-auth-debugging \ --skill tuturuuu-external-apps \ --skill tuturuuu-mobile-task-board \ --skill tuturuuu-platform \ --skill tuturuuu-pr-merge-sync \ --skill tuturuuu-review-comments \ --skill tuturuuu-rollout-recovery \ --skill tuturuuu-satellite-app-ux \ --skill tuturuuu-validation-offload \ --skill tuturuuu-web-release ``` Then verify the cached page after refresh at `https://skills.sh/tutur3u/platform`. ## Included Skills * `$tuturuuu-rollout-recovery`: mixed-version and Instant Rollback diagnosis, canonical alias/source audits, safe recovery evidence, and bounded CI retries. Read the [critical rollout runbook](../devops/critical-app-rollout) for the maintained staging/probe/promotion contract. Ingress 401 checks do not prove signed-in business recovery; preserve per-app authentication and QA privacy. * `$tuturuuu-platform`: repo-wide workflow guidance for `apps/web`, `packages/*`, `apps/database`, `apps/docs`, translations, navigation, and verification follow-through, including shared-worktree preflight, scoped staging expectations, and Effect adoption guidance for TypeScript server/service orchestration. * `$tuturuuu-browser-vercel-debugging`: authenticated Browser/Chrome and Vercel CLI guidance for reproducing deployed UI/API bugs, correlating runtime and build logs, checking satellite routing/auth, auditing responsive and i18n behavior, investigating performance/cost, and verifying improvements without mutating customer data. * `$tuturuuu-cms-studio`: CMS and external-project content studio guidance for `apps/cms`, branded project adapters, landing-page content editing, content collections, media workflows, preview delivery, and non-technical editor UX. * `$tuturuuu-satellite-app-ux`: standalone app shell guidance for satellite apps such as Mail and CMS, including `@tuturuuu/satellite` auth, app-session routes, i18n, workspace navigation, permissions, and focused operational UX. * `$tuturuuu-external-apps`: external and branded sibling app integration guidance for app-token exchange, first-class workspace invitation decisions, member and role administration, Drive management, refreshable admin sessions, direct signed storage uploads, external-project mutations, delivery fallbacks, and sanitized diagnostics. * `$tuturuuu-e2e-auth-debugging`: local E2E authentication guidance for native Playwright patch iteration, `dev-session`, guest access, onboarding redirects, app-session verification, rate-limit tests, and explicit Docker-parity auth checks. * `$tuturuuu-commit`: scoped commit workflow guidance for explicit commit, commit-and-push, atomic staging, Conventional Commit subjects, shared-worktree path isolation, commit-window claim/wait/release, proof-gated no-verify commit evidence, hook failure handling, and final commit reporting. * `$tuturuuu-agent-coordination`: shared-worktree coordination guidance for dirty checkouts, active ownership notes, archived context, overlapping edits, stale handoffs, explicit write sets, commit-window coordination, and path-scoped staging safety. * `$tuturuuu-cli`: core native `ttr` CLI install, browser login, copy-token login, workspace discovery, scoped help, SDK-backed command surfaces, task template command boundaries, version checks, and release verification guidance. It documents autonomous Bun and CLI installation with `curl -fsSL https://bun.sh/install | bash` on macOS/Linux, `powershell -c "irm bun.sh/install.ps1 | iex"` on Windows, then `bun i -g tuturuuu`. * `$tuturuuu-cli-resources`: opt-in machine resource control through `ttr resources`, shared validation admission across projects/worktrees, independent Turbo and Vitest limits, memory-pressure diagnostics, remote-runner checks, and rollback. * `$tuturuuu-cli-tasks`: focused `ttr tasks` and `ttr task-templates` guidance for task capture, task board/list/label discovery, open-task defaults, compact task tables, task creation, reusable task-template import/export, template instantiation, splitting, movement, completion, closure, and task verification. It documents ttr-first task capture for requests to add, create, template, track, or split Tuturuuu tasks, including label discovery and closing superseded combined tasks after replacements are created. * `$tuturuuu-cli-finance`: focused `ttr finance` guidance for wallet, transaction, category, budget, and recurring CRUD; analytics reads; finance pagination footers; explicit-workspace finance read diagnostics; and wrapped finance response normalization in the SDK client. * `$tuturuuu-development-tooling`: shared guidance for improving Codex skills, plugin behavior, validation scripts, docs runbooks, helper scripts, and durable workflow learnings that should benefit future Tuturuuu contributors and assistants, including Turborepo/Next cache boundaries, local dev-speed diagnostics, release-please merge automation, and package release automation rules. * `$tuturuuu-pr-merge-sync`: PR closeout guidance for quiet-window review watching, efficient GitHub polling, merge/admin-merge follow-through, the hard main-green gate before `bun git-sync`, production sync, and production workflow verification. * `$tuturuuu-devbox-ops`: operational guidance for `ttr box` setup, runner registration, one-shot smoke tests, 24/7 system services, runner-token cleanup, CLI upgrades, and infrastructure devbox observability. * `$tuturuuu-validation-offload`: validation strategy guidance for deciding when to run focused tests, `bun validate`, Supabase, Docker, or browser-heavy workflows through internal devboxes instead of the local agent session. * `$tuturuuu-web-release`: `apps/web` release badge metadata, blue/green runtime snapshot fallback, `PLATFORM_BUILD_*` precedence, and release-please-managed `TUTURUUU_PLATFORM_VERSION` guidance. * `$tuturuuu-mobile-task-board`: Flutter mobile task-board guidance for task dates, overdue behavior, task detail routing, description mode, assignee flows, and release-please-managed mobile version metadata. * `$tuturuuu-database`: Supabase migration, RLS, workspace-scoped API write, generated type, storage, and database verification guidance. Agents never push production migrations manually; the gated production workflow applies them after authorized sync and requires separate exact-SHA verification. * `$tuturuuu-ci-docs`: GitHub Actions, `tuturuuu.ts`, validation script, docs-page, and docs navigation guidance. * `$tuturuuu-review-comments`: GitHub PR review-thread guidance for checking, re-checking, validating, fixing, resolving, and committing unresolved review comments. Addressed review threads are resolved by default after validation; commits and pushes still require an explicit user request. Its bundled `fetch_review_threads.py` helper supports `--active-only --summary` and emits review-thread counts for final re-check reports. ## Translation Key Workflow When a platform change introduces a new translation key, prefer the root helper instead of editing message JSON by hand: ```bash theme={null} bun i18n:add --app web --key common.save --value en=Save --value vi=Lưu ``` Use `--dir apps//messages` for non-standard message directories and `--all` only for shared UI keys that must exist in every detected app message setup. The helper detects locale JSON files in the target setup, requires a value for each locale, blocks unsafe key paths, prevents accidental overwrites unless `--overwrite` is passed, and writes sorted JSON. Manual message edits are reserved for broad copy rewrites or value-only updates; run `bun i18n:sort` after those edits. For larger translation updates, use bulk modes instead of repeatedly editing JSON: ```bash theme={null} bun i18n:add --app web --mode add --entries '{"common.save":{"en":"Save","vi":"Lưu"}}' bun i18n:add --app web --mode remove --entries '["common.old"]' bun i18n:add --app web --mode replace --entries-file ./translations.json ``` Bulk add and replace entries use a JSON object keyed by translation key, with locale values underneath each key. Bulk remove accepts an array of translation keys. Replace and remove fail when a key is missing unless `--ignore-missing` is passed. ## CI Coverage `.github/workflows/codex-plugin.yaml` runs the plugin-local validator and parses the docs navigation JSON. The workflow is enabled through `tuturuuu.ts`, matching the repo's other CI switchboard-controlled checks. ### Native parallel validation pilot After checkout, Python 3.13 setup, plugin validation and the hash-locked MCP dependency install, one native `parallel` group runs the MCP boundary/stdio suite and orchestration-evidence suite. Both read repository source and use separate temporary fixtures; neither consumes the other's output. Each suite retains its original discovery command and applies a five-minute timeout and a 1 GiB per-process virtual memory ceiling. The job has a fifteen-minute timeout and read-only permissions. GitHub's [June 25, 2026 announcement](https://github.blog/changelog/2026-06-25-actions-steps-can-now-be-run-in-parallel/) and [workflow syntax](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstepsparallel) document `parallel` as background steps followed by an implicit wait. Any suite failure fails that barrier and the job; no step uses `continue-on-error`. Docs navigation validation stays after the barrier. Triggers, switchboard gating and the required check name remain unchanged. Run `node --test scripts/ci/codex-plugin-parallel-workflow.test.js` to check the parsed workflow's prerequisite order, bounded two-suite group and failure gates. This structural check does not execute GitHub's scheduler. Confirm overlapping suite intervals and successful completion in the automatic exact-head hosted run before treating the pilot as qualified. No speed improvement is established; compare equivalent runner, source, dependency/cache and suite inputs before claiming one. Roll back by expanding the two children into sequential steps. The CI check currently verifies: * plugin manifest JSON and interface metadata * natural default prompt examples for the invokable skills, written as short user requests instead of visible `$skill` commands * dedicated prompt coverage for CMS studio and landing-page content management * dedicated prompt coverage for external app integrations, in-app workspace invitations and membership, Drive management, and direct uploads * dedicated prompt coverage for satellite app UX and app-session workflows * dedicated prompt coverage for native local E2E auth and dev-session debugging * dedicated prompt coverage for browser and Vercel production troubleshooting * dedicated prompt coverage for shared-worktree coordination and agent handoff * dedicated prompt coverage for PR quiet-window merge sync with main-green gating before production sync * dedicated prompt coverage for devbox runner operations and validation offload * dedicated prompt coverage for web release badge metadata * durable CI tooling guidance for npm package release auto-recovery * durable CI tooling guidance for Supabase CLI setup retry and GitHub-tokened release lookup * durable CI tooling guidance for bounded Codecov coverage test retries * scoped commit workflow coverage for explicit commit requests * native `ttr` task-template workflow coverage in the CLI task skill * proof-gated no-verify commit evidence coverage * commit-window claim, wait, release, and stale-lock guidance * repo marketplace metadata at `.agents/plugins/marketplace.json` * public skills.sh discovery metadata at `.claude-plugin/marketplace.json` * public skills.sh grouping metadata at `skills.sh.json` * skill folder and frontmatter naming parity * `agents/openai.yaml` defaults for every skill * skill `references/` links * plugin docs page registration in `apps/docs/docs.json` * Codex plugin workflow registration in `tuturuuu.ts` * absence of scaffold `[TODO: ...]` placeholders * absence of machine-specific local paths in plugin text ## Program Ownership And Verification For authorized work spanning multiple owners and delivery wakes, the coordinator owns scope, acceptance, dependency order, source review and delivery evidence. Workers own disjoint implementation lanes. Use the plugin coordination skill's `references/program-orchestration.md` for the brief and current-board format. Completions are reconciled after critical sections and before status reports; an idle worker is resumed only with concrete work, never merely for status. Keep the coordinator-owned current board in ignored `tmp/agent-coordination/` state rather than reconstructing current progress from a growing event history. The read-only checker rejects stale-head delivery claims, conflicting gates and multiple active writers in the same worktree: ```bash theme={null} python3 plugins/tuturuuu/scripts/check_program_state.py tmp/agent-coordination//state.json python3 -m unittest discover -s plugins/tuturuuu/scripts -p 'test_program_state.py' ``` Recorded PASS requires a real receipt. This checker does not query remote systems or validate receipt contents. A merge, green summary, skipped deployment or old store upload cannot establish new-source availability. Each requested delivery stage needs current-source evidence; new heads invalidate prior head receipts. Use native PR wakes and an explicitly authorized cadence instead of polling. For a task-specific harness change, the board may also record bounded baseline and candidate experiments. The checker requires fixed input/context/control pins, a closed paired case census, explicit probe usage, and separate failure/unknown/error outcomes. Adoption requires observed improvement without regressions, a comparison, a scoped lesson and a current candidate regression receipt. See the coordination skill's `references/program-orchestration.md` for the contract and offline example. This adapts [Harness²'s contrastive method](https://github.com/google-research/harness2) without its executor or model calls. Matching pins and unit tests establish record consistency, not semantic guardrail preservation or improved agent quality. Experiment acceptance never replaces a unit's delivery evidence or changes authority. This workflow adapts [pstack's upstream orchestration playbook](https://github.com/cursor/plugins/blob/df581122cde17e6e27686b5a448bde23e4ad4318/pstack/skills/poteto-mode/playbooks/orchestrate.md) to T3's actual child-task tools and Tuturuuu's ownership, resource and production boundaries. It does not require Cursor, Graphite, cloud agents or a new plugin installation. Structural/routing checks are bounded evidence, not a behavioral agent evaluation. Managed plugin caches are updated by their installer. ## Long-Term Request Intake When a user assigns ongoing program ownership, capture each idea, bug, feature, improvement and amendment before dispatch. Use stable IDs, source pointers, checkable acceptance, dependencies and current owners. The coordination skill's `references/request-backlog.md` defines the private SQLite ledger and commands. Intake survives conversation compaction and task-worktree retirement; it is local persistence, not cross-machine synchronization or a guarantee of unlimited recall. The standard store is under `~/.local/share/tuturuuu/orchestration/programs/`. Never commit user dumps, transcripts, credentials or the database. Repeated imports preserve progress, conflicting scopes fail rather than overwrite, and updates retain event history. Read backlog and current-unit evidence at every wake. Keep captured, active, implemented and verified distinct. Native Tuturuuu task creation still uses `ttr` after destination discovery. The requested pstack upstream package can be used alongside this plugin. Its Cursor marketplace does not expose pstack through the Claude marketplace Codex reads, so the local compatibility installation adds a Codex manifest/marketplace without modifying upstream skills. Pin the reviewed upstream commit, retain the license and verify installed/enabled status with the official installer. This adapter does not make Cursor-only tools available or override Tuturuuu policy. Managed caches stay installer-owned. Start a subsequent turn to discover newly installed skills. ## Shared Worktree Coordination Agents should assume that humans or other agents may have uncommitted work in the same checkout. The docs-facing protocol lives in the Agent Operating Manual, and the agent-facing workflow lives in `$tuturuuu-agent-coordination`. Open Tuturuuu pull requests are always handled in isolated worktrees under `.worktrees/`. Run `bun install` immediately after creating the PR worktree; builds run in CI. Keep the worktree and local task branch while the PR is open, and remove both only after the merge is confirmed on `main` and post-merge verification is complete. This lifecycle is documented in the Agent Operating Manual and enforced as a cross-cutting rule in `AGENTS.md`. For user-authorized continuous integration, the same lifecycle applies to each verified checkpoint: integrate it into current `main`, require the exact main SHA to be fully green, run `bun git-sync`, verify production, then remove only the completed worktree and local task branch. Rust-heavy retained worktrees use `bun rust-cache report` plus bounded `prune`/`auto` cleanup rather than broad filesystem deletion. Use `tmp/agent-coordination/` for lightweight agent-to-agent notes when work may overlap, the worktree is dirty, the task is long-running, or the task changes agent workflow rules. The directory is ignored by git, so it can hold live intent, ownership, status, verification, risk, and handoff messages without polluting commits. Active notes are notes marked `working`, `blocked`, or `handoff`. Treat stale active notes as ownership signals until you have read them and checked the current worktree. Keep active notes as direct files under `tmp/agent-coordination/`; archive completed notes under `tmp/agent-coordination/archive//.md` after they are marked `done` and no longer need top-level visibility. Use `bun git-commit-window` before changing the staged set or creating commits in a shared checkout. `claim` creates an advisory lock under `tmp/agent-coordination/git-commit-window.lock.json`; `wait` sleeps until the current lock is released or expires, then claims it before notifying the waiting agent that it can commit. Claims default to 10 minutes, accept only 5-10-minute TTLs, and should be held only while staging, inspecting, committing, amending, rebasing, or finishing commit-and-push follow-through. Release the lock with `bun git-commit-window release --token ` after the commit operation finishes or aborts, and do not record tokens in coordination notes. Archived notes are historical context for targeted lookup, not locks. Agents should search them by path, feature, or workflow only when previous decisions or verification matter to the current task. If another active note claims the same file set, agents should choose non-overlapping slices, write a response note, or ask the human partner to arbitrate. They should never format, stage, or fix unrelated dirty files simply because a repo-wide check or commit hook reports them. When coordinating subagents, split work into named lanes with disjoint owned paths, excluded paths, validation commands, and a no-stage/no-commit boundary unless the lane explicitly owns a commit. The coordinator owns integration and shared generated artifacts by default, including TanStack route trees, migration manifests, route overrides, OpenAPI snapshots, docs navigation, sorted translation bundles, and Supabase generated types. Workers should report generated drift and hand off exact follow-up instead of silently committing it. When a generator can see dirty or untracked files owned by another lane, regenerate from a clean worktree or an explicit input set and copy back only the intended artifact. Write a lane contract before spawning: owner, mode, owned paths, excluded paths, generated outputs, validation, handoff shape, and commit authority. Read-only lanes return evidence and risks without taking ownership. In Codex, choose either a typed worker/explorer role with explicit lane context in the prompt or a full-history fork without a role override; the harness rejects a spawn request that asks for both. After integrating a slice, checkpoint before dispatching more work: refresh status, close completed subagents, update the parent note with the commit or handoff state, list validation and unrelated blockers, and choose the next lane from the current worktree state. The normal scoped commit path still lets Git hooks run. Agents may use `git commit --no-verify` only when they can produce a proof packet for their exact staged paths: reviewed status and staged diff output, path ownership, separated validation mapped to the relevant `bun validate` components, path-based rationale for skipped components, and `bun check:mobile` coverage when `apps/mobile` is touched. Incomplete proof, unclear ownership, or uncertain check mapping means the hook should run or the risk should be reported instead of bypassed. ## AGENTS.md Split Root `AGENTS.md` is intentionally a compact hard-policy index. Detailed implementation gotchas and composable patterns live in focused Tuturuuu skill references instead: * web/API/shared UI patterns in `$tuturuuu-platform` * release badge/version metadata in `$tuturuuu-web-release` * database/API/storage patterns in `$tuturuuu-database` * CI/root-script/tooling patterns in `$tuturuuu-development-tooling` * Docker blue/green watcher patterns in `$tuturuuu-ci-docs` * mobile task-board and overlay patterns in `$tuturuuu-mobile-task-board` When a session reveals durable knowledge, update the narrowest matching skill reference and docs page. Add to root `AGENTS.md` only when the rule is a cross-cutting hard mandate that agents must see before skill loading. ## Skill Scope And Maintenance Descriptions should identify the capability and its actual trigger in a short sentence. There is no minimum description length. Avoid exhaustive keyword lists, mandatory self-selection, and competing style prescriptions. Keep a small entrypoint and route substantial conditional detail to references; a simple skill needs no extra router. Preserve user intent, existing authorization, and concrete security/ownership/release boundaries. Skills should not fabricate tool execution, force unrelated image generation, require approval after every local step, or stop a requested implementation at a plan. Choose checks for meaningful behavior and repository requirements, not repeated rituals. Audit canonical source files and symlink targets once. Installed plugin caches and runtime system skills remain installer-managed. Keep upstream licenses and metadata; local customizations to imported skills may need reapplying after an upstream reinstall. Personal skills outside this Git repository are maintained and verified separately. The September 2026 audit applied these principles from [Eric Provencher's article](https://x.com/pvncher/status/2095991462416490862). See the [repository audit inventory](https://github.com/tutur3u/platform/blob/main/docs/audits/2026-09-05-skills-agents.md) for per-file disposition and known managed copies. ## Validate The Plugin Run the local validator after changing the plugin manifest or its skills: ```bash theme={null} python3 plugins/tuturuuu/scripts/validate_plugin.py ``` The local validator also checks the root skills.sh metadata files against the actual Tuturuuu skill folders, so add every new public skill to both `.claude-plugin/marketplace.json` and `skills.sh.json`. For individual skills, run the Codex skill validator: ```bash theme={null} python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-platform python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-cms-studio python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-satellite-app-ux python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-e2e-auth-debugging python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-external-apps python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-commit python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-agent-coordination python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-cli python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-cli-tasks python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-cli-finance python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-development-tooling python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-devbox-ops python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-validation-offload python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-web-release python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-mobile-task-board python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-database python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-ci-docs python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-review-comments python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py plugins/tuturuuu/skills/tuturuuu-rollout-recovery ``` The Codex skill validator imports `yaml`, so it requires `PyYAML` in the active Python environment. The plugin-local validator uses only the Python standard library. ## Maintenance Rules * Keep `plugins/tuturuuu/.codex-plugin/plugin.json` aligned with the plugin folder name. Do not bump its `version` for ordinary authored work unless a release workflow or user request requires it; when a user explicitly asks for a plugin refresh, bump the manifest and keep this page current. * Keep each skill folder name aligned with its `SKILL.md` frontmatter `name`. * Keep plugin and skill default prompts short, natural, and action-oriented. Marketplace prompt cards should read like user goals, for example "Clear the unresolved review comments on this PR." * Keep skill text portable across machines. Prefer repo-relative paths, ``, or `~` over user-specific absolute paths. * Put detailed guidance in `references/` and keep `SKILL.md` focused on the workflow that should be loaded immediately. * Keep shared-worktree and commit-window coordination guidance aligned across `AGENTS.md`, the Agent Operating Manual, `$tuturuuu-agent-coordination`, and `$tuturuuu-commit`. * Keep the open-PR `.worktrees/` lifecycle, immediate `bun install` (without local builds), and post-merge worktree/branch cleanup guidance aligned across `AGENTS.md`, the Agent Operating Manual, `$tuturuuu-agent-coordination`, the platform checklist, and `$tuturuuu-pr-merge-sync`. Keep the authorized continuous integration, main-green, `bun git-sync`, production verification, and bounded Rust-cache cleanup rules aligned on those same surfaces. * Keep parallel subagent lane, staged-set ownership, generated-artifact ownership, and hook-failure guidance aligned across the Agent Operating Manual, `$tuturuuu-agent-coordination`, `$tuturuuu-commit`, and Git conventions docs. * Keep platform release/version guidance aligned across `AGENTS.md`, `$tuturuuu-web-release`, and the Web Docker Deployment runbook. * Add marketplace metadata only when deciding where the plugin should be installed from: repo-local `.agents/plugins/marketplace.json` or home-local `~/.agents/plugins/marketplace.json`. * Keep public skills.sh metadata aligned across `.claude-plugin/marketplace.json` and `skills.sh.json`; do not modify `.agents/skills` just to publish the Tuturuuu plugin skills. ## ChatGPT and MCP integration See [ChatGPT and MCP](./chatgpt-mcp) for the portable plugin gap matrix, hosted read-only workflow, capability support, authorization gates and validation. ### Realtime services `$tuturuuu-realtime` implements shared room protocols, collaboration, cursors, private checkpoints and reconnect recovery. It reuses `packages/realtime` and the shared programming workbench. Its focused reference covers admission, capability scope, persistence, egress and service verification; operational configuration lives in [the programming realtime runbook](/build/devops/programming-realtime-runbook). ### Backlog priority and dependent receipts Reprioritize requests through the audited `program_backlog.py update --priority <0-3>` command; reimporting a changed priority is rejected. Reopened prerequisites invalidate current dependent verification transitively while preserving audit history and implemented source. Parent recovery never silently restores dependent delivery receipts. See the coordination skill's request-backlog reference and `test_program_backlog.py` for the contract and regressions. ## Operational peer sync source foundation `packages/sdk/src/operational-sync/` defines a version 1 protocol and an inert coordination/replica fixture adapter. It adds no CLI command, HTTP route, production store, grant or service. The local offline CLI remains independent. Existing runner tokens, resource admission and Git commit windows retain their own scope. Bindings carry principal, workspace, project, program, machine, agent, source store, replica and grant identities. A grant revision binds each request. The future server adapter must authenticate the principal and machine, enforce staff and personal-project permissions, and recheck current consent/revocation. Client identity fields are claims to compare against authority, never authentication. The supplied authority callback in tests is synthetic. A SQLite transaction does not serialize revocation in a separate provider or database; production needs a reviewed atomic grant check or equivalent revocation fence in its server adapter. Planning events use expected outcome revision and prior hash. The coordinator assigns a global cursor and immutable hash chain. Operation IDs dedupe exact requests; persisted receipts must match original proposals and immutable event history. Changed requests fail, and stale proposals retain an explicit conflict alongside the existing history. No clock-based or last-writer-wins resolution is implemented. Completion is `user-confirmed`, never `evidence-verified`. Leases bind the complete owner/grant identity, a monotonically increasing fence and server-clock expiry. Acquire, renew and release participate in outcome CAS. Expired/released/foreign owners cannot mutate. Tombstones remain in event history and block resurrection. Lease expiry never proves that an old process stopped, and a lease never bypasses a host resource queue or local commit window. Replicas validate scope, peer store, audience, contiguous global cursors, per-outcome ancestry, hashes and command/projection semantics. SQLite commits the accepted page, projection and cursor together. Interrupted application rolls back; exact replay is harmless and divergent replay fails. Hashes are integrity checks, not peer authentication. Trusted transport and grant validation remain prerequisites. The fixture adapter requires explicit private paths and initialization, rejects symlinks and insecure permissions, and never defaults to the live backlog. Payloads allow only planning state and identities; no credentials, personal memory, customer archives, arbitrary file bodies or operational-note export is wired. Pages contain at most 500 events; stores cap 1,000 outcomes, 10,000 events, 20,000 operation receipts and 32 MiB of serialized state. Saturation fails without truncation. Regression coverage in `operational-sync/engine.test.ts` uses two persisted local synthetic replicas. It proves local CAS/conflict/fence/tombstone/recovery behavior, not network, provider authentication, consent, private SQL or two-machine delivery. The rehashed-projection regression first fails against hash-only chain validation, then passes with shared transition validation. Activation remains denied pending a reviewed grant/backend/transport adapter, exact-head CI and actual authorized runtime qualification. See the focused repository skill reference `plugins/tuturuuu/skills/tuturuuu-agent-coordination/references/machine-sync.md`. ## Pinned security audit skill The shared `.agents/skills/security-audit` directory vendors Cloudflare's MIT security audit skill. `UPSTREAM.json` pins its commit and file hashes; agent aliases resolve to this single copy. It is manually vendored, outside `skills-lock.json`. Keep upstream files unchanged when updating the pin and retain its license. Repository authority, inactive-runtime rules and resource admission still apply. Audit output stays private and unstaged. Target execution requires the skill's OS-enforced sandbox; missing controls produce validation gaps, not confirmed findings. Parent-owned JSON validators do not establish target security. Remediation, CI, integration and production verification remain separate gates. # Contributing with AI agents Source: https://docs.tuturuuu.com/build/development-tools/contributing-with-agents How AI coding agents and people share the same repository rules, reviews and release path. AI coding agents contribute to Tuturuuu under the same rules as people. The repository's root `AGENTS.md` is the single source for those rules; this page summarizes what that means for a contributor, human or agent. ## Principles * **One set of rules.** Agents follow the conventions in [Git conventions](/build/development-tools/git-conventions), [Pre-push checks](/build/development-tools/pre-push-checks) and [Documenting](/build/development-tools/documenting). An agent's change is reviewed like any other change. * **Small, isolated changes.** Work happens on its own branch or worktree and is published as a normal pull request; see [Stacked pull requests](/build/development-tools/stacked-pull-requests) for larger changes. * **Verify locally first.** Run the focused checks for the area you changed and record the commands and results in the pull request. * **Docs ship with code.** A feature pull request updates the matching docs page, or says why no documentation is needed. * **No secrets in the repository.** Never commit tokens, keys, credentials or rendered environment dumps, and never paste them into docs, issues or pull requests. See [Deployment configuration](/build/devops/deployment-configuration). * **Sensitive areas get a security review.** Changes to authentication, authorization, data protection, billing or infrastructure are reviewed by a human code owner before merge; see [Code owners](/build/devops/code-owners). * **Stay inside the active runtime.** Follow the [active runtime map](/build/devops/active-runtime) and do not resume paused runtimes unless a maintainer asks. ## Where to start New contributors can begin with [Development](/build/development-tools/development), [Without Docker](/build/development-tools/without-docker) and the [monorepo architecture](/build/development-tools/monorepo-architecture). # Development Source: https://docs.tuturuuu.com/build/development-tools/development Learn how to preview changes locally. > [!NOTE] > > **Prerequisite**: You should have installed [Node.js](https://nodejs.org) > (matching the repository floor of `>=22.13.0`). ## Installation ### Supabase Auth declaration compatibility The repository pins a Bun patch for `@supabase/auth-js@2.117.1`. Its credential interface retains every native `PublicKeyCredential` member except `toJSON`, which the package declares separately with its existing response type. Native DOM JSON uses an encoded large-blob string; the package's existing extension output type uses `ArrayBuffer`. Treat these as distinct contracts. The patch changes declarations only. It does not encode extension data, alter authentication behavior, or qualify browser passkey delivery. Both shipped declaration formats and the package source carry the same correction. Keep `skipLibCheck` disabled when checking this compatibility boundary: ```sh theme={null} ttr resources run -- ./node_modules/.bin/tsgo --project packages/supabase/type-tests/auth-webauthn-compat.tsconfig.json ttr resources run -- bun packages/supabase/type-tests/auth-webauthn-compat.ts ``` Bun installs the patch through `patchedDependencies`; do not edit installed dependencies as a permanent fix. Before updating Auth JS or removing the patch, check the strict public verification types and the negative native-credential and encoded-blob controls against the installed replacement. The finite behavior controls call the installed ESM and CommonJS serialization functions with typed mocks. They check registration and authentication separately. The native `toJSON` branch returns its encoded extension output unchanged; the fallback returns raw extension buffers unchanged. Stringifying a fallback large-blob buffer produces `{}`, so this patch does not prove extension data can be transmitted correctly. Native registration JSON also requires fields that the existing fallback does not emit. The controls retain expected type errors for native DOM JSON and credentials without `toJSON`. The package's serializer signatures still require `toJSON` and advertise the package's raw-extension response type even though the implementation supports both branches. Those signature limitations remain separate from this inheritance correction. The mocks exercise pure serialization, not browser credential acquisition or server verification. Step 1. Install [bun](https://bun.sh/docs/installation) on your machine (if you don't already have it yet), by running the following command: **macOS/Linux:** ```bash theme={null} curl -fsSL https://bun.sh/install | bash ``` **Windows:** ```bash theme={null} powershell -c "irm bun.sh/install.ps1 | iex" ``` ## Install the repository dependencies Use the Bun version pinned by the root `packageManager` field. The [version reference](/reference/repository/versions) is generated from repository manifests and lockfiles, so it records the current pins without relying on outdated prose or a globally installed CLI. ```bash theme={null} bun install --frozen-lockfile ``` The Tiptap Pro registry step is retired; no private registry setup is required. `bun setup` is not a minimal installation command: it can build packages and probe services. Use [development without Docker](/build/development-tools/without-docker) for the supported minimal Next.js path. Rust and TanStack Start are not in use and are not required to work on the active web apps. This repository's Bun configuration enforces a minimum release age of 1 day for new npm package versions. If Bun skips a just-published release during install, wait for the package to age past the gate or choose an older published version. First-party package families that publish coordinated releases together may be explicitly excluded from the age gate in `bunfig.toml`; keep each trusted family's exact-name list aligned with the packages resolved in `bun.lock` and cover the list with a policy test. Discord's Python environment is resolved separately in `apps/discord/uv.lock`. For targeted transitive updates, use `uv lock --upgrade-package pyjwt --upgrade-package urllib3`, then confirm that unrelated package records and the project's Python floor are unchanged. Validate artifact hashes against PyPI and run the owning locked Python CI, including the offline dependency security tests in `tests/test_dependency_security.py`. PyJWT 2.15.1 includes malformed-payload/JWKS hardening and accepts valid trailing Base64URL padding while continuing to reject invalid characters. urllib3 2.8.0 bounds chunk-size lines and fixes HTTPS proxy TLS configuration and Deflate streaming. Proxy-specific trust settings belong in `proxy_ssl_context` and the proxy identity options; destination TLS settings are separate. These dependencies are reached through Supabase Auth/MSAL and Requests, respectively. A locked CI environment does not establish the version in an already deployed Modal image: `app.py` has a separate floating `.pip_install(...)` recipe. Verify that image's resolved versions during the separately authorized deployment process. To complete the initial setup, please restart your IDE so that it can recognize the newly installed dependencies. Additionally, some recommended VS Code Extensions may only work after restarting your IDE. > [!TIP] > > If you're using VS Code, you can install following the recommended extensions > that will help you with the development process: > [Oxc](https://marketplace.visualstudio.com/items?itemName=oxc.oxc-vscode) > (this repo standardizes on Oxc for linting and formatting via `.oxfmtrc.json` > and `.oxlintrc.json`, not ESLint or Prettier), > [Vitest](https://marketplace.visualstudio.com/items?itemName=vitest.explorer), > [Tailwind CSS > IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss), > [Version > Lens](https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens), > [Error > Lens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens), > [Pretty TypeScript > Errors](https://marketplace.visualstudio.com/items?itemName=YoavBls.pretty-ts-errors), > [Material Icon > Theme](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme). ### Zed This monorepo tracks project-level Zed settings in `.zed/settings.json`. Opening the repository root in Zed can otherwise trigger expensive scans across generated output and local dependency trees, especially `node_modules`, `.turbo`, `.next`, package `dist` directories, Flutter build output, Rust `target`, and Python virtualenv/cache folders. Keep large generated directories in `file_scan_exclusions`. Zed's `file_scan_exclusions` setting replaces the default list instead of extending it, so include Zed's default VCS/system exclusions whenever adding project exclusions. The project uses TypeScript 7 RC's `tsc` for compiler checks and a single TypeScript language server path for TypeScript, TSX, and JavaScript; avoid enabling competing TypeScript language servers for the same language unless you are deliberately comparing language server behavior. Every app configuration overrides TypeScript 7's `types` compatibility wildcard with its explicit runtime globals, so editors with an older bundled language service do not report `Cannot find type definition file for '*'` across the app tree. ## Development ### Start Next.js apps To develop all apps and packages (without requiring a local setup), run the following command: ```bash bun theme={null} bun dev ``` > [!NOTE] > > This command will start all Next.js apps in development mode. You can access > the platform app by visiting the following URL: > [https://tuturuuu.localhost](https://tuturuuu.localhost) Local app development uses Portless, so each app gets a stable Tuturuuu subdomain instead of relying on its fallback port. The app package `dev` scripts run the repo's Portless-safe wrapper, and the underlying framework command remains available through `dev:app` for direct port-based debugging. The wrapper only removes stale static aliases for the same app when their default backend port is closed, then starts Portless with the original app config. This fixes old worktree aliases such as `zalo-qr-chat-setup.tuturuuu.localhost` without cleaning certificates, deleting unrelated routes, or touching other apps' active aliases. Package-local `bun dev --force` delegates to `portless run --name --force` so Portless can take over a live route when you explicitly request it. Root app-specific commands such as `bun dev:chat`, `bun dev:calendar`, and `bun dev:edu` reuse app servers that are already running. The launcher checks active Portless routes first, then the app's default localhost port; if it finds a direct localhost listener, it tries to register a matching Portless alias so cross-app auth can still use the `*.tuturuuu.localhost` URL. Pass `--force` or `--no-reuse` when you intentionally want the command to include already-running app workspaces. Force mode starts the package `dev --force` path so Portless can take over the matching route instead of leaving a stale static alias in place. ### Inactive migration tooling Rust (`apps/backend`) and TanStack Start (`apps/tanstack-web`) are paused and not in use. Retained commands and Worker entrypoints are future-resumption references, not steps in the current Next.js setup. Do not start these services or require their migration gates for routine app development. See the [active runtime map](/build/devops/active-runtime). `bun dev:web` is intentionally lean: by default it starts only `apps/web` and does not start the `@tuturuuu/types` or `@tuturuuu/supabase` package watch builds. Use this default for app-route and UI work so the local process tree stays small. When you are actively editing those package sources and need their `dist` output rebuilt live, opt in explicitly: ```bash theme={null} bun dev:web --with-shared-watchers ``` You can also pass `--no-shared-watchers` to other root app launchers when you want the same low-memory posture for a focused app session. `apps/web` does not mount React Query Devtools in its default development provider. Keep the default off for faster cold route compiles and lower Turbopack memory pressure; add a local, temporary devtools mount only while debugging query cache behavior, then remove it before committing. Keep the always-mounted public shell small. The mobile menu drawer, marketing footer body, report-problem dialog, and authenticated dropdown-only affordances should stay behind dynamic imports when possible, and shell icons should use `@tuturuuu/icons/lucide-static` instead of the root `@tuturuuu/icons` entrypoint. This prevents the public `/login` compile graph from pulling large Radix, footer, or full icon-package chunks into every `bun dev:web` session. `bun dev:chat` also manages the local chat realtime sidecar. It reuses `localhost:7817` when a sidecar is already running; otherwise it starts `apps/chat-realtime` so `apps/web` can proxy chat SSE traffic for `apps/chat`. | App | Local URL | | - | - | | Platform | `https://tuturuuu.localhost` | | Calendar | `https://calendar.tuturuuu.localhost` | | Chat | `https://chat.tuturuuu.localhost` | | CMS | `https://cms.tuturuuu.localhost` | | Drive | `https://drive.tuturuuu.localhost` | | External | `https://external.tuturuuu.localhost` | | Finance | `https://finance.tuturuuu.localhost` | | Hive | `https://hive.tuturuuu.localhost` | | Hive Realtime | `https://realtime.hive.tuturuuu.localhost` | | Infra | `https://infra.tuturuuu.localhost` | | Inventory | `https://inventory.tuturuuu.localhost` | | Learn | `https://learn.tuturuuu.localhost` | | Mail | `https://mail.tuturuuu.localhost` | | Meet | `https://meet.tuturuuu.localhost` | | Mind | `https://mind.tuturuuu.localhost` | | Nova | `https://nova.tuturuuu.localhost` | | Playground | `https://playground.tuturuuu.localhost` | | QR | `https://qr.tuturuuu.localhost` | | Rewise | `https://rewise.tuturuuu.localhost` | | Shortener | `https://shortener.tuturuuu.localhost` | | Tasks | `https://tasks.tuturuuu.localhost` | | Teach | `https://teach.tuturuuu.localhost` | | Track | `https://track.tuturuuu.localhost` | When debugging without Portless, run an app's `dev:app` script directly. If auth redirects or absolute links must stay on the raw listener port, set `BASE_URL`, `WEB_APP_URL`, or the app-specific URL environment variable to that legacy fallback port for the direct debug session. Keep runtime defaults, auth redirects, and cross-app links on the Portless origins during local development. Use the shared local app URL helpers instead of hard-coding `localhost` fallbacks in satellite app constants or proxies, so a browser session that starts on `tasks.tuturuuu.localhost` stays under the `tuturuuu.localhost` namespace through login and return URLs. When a satellite proxies a Web-owned API collection through an external rewrite, use an exact collection rule and a separate nonempty `:path+` descendant rule. A `:path*` destination can compile to a regex backreference whose empty value leaves a trailing slash. If Web strips that slash with a relative 308, the satellite can repeat the same request indefinitely. Infrastructure's employee collection regression exercises both installed Next runtime matching and the deployment rewrite converter in `apps/infrastructure/next.config.test.ts`. Preserve satellite session and API guards, and verify the emitted deployment route plus an authenticated request after the authorized rollout; passing source tests alone does not establish production availability. For a production-mode smoke test of `apps/web`, use the preview deployment built by CI for the PR's exact head commit. Do not create a local production build on this machine. Local development still uses the Portless hostname for cross-app login and routing checks. Use `bun dev:edu` when working on the education apps together. It starts Learn, Teach, their shared packages, and the central web app so cross-app login can complete locally. Next.js still prints the internal listener port, for example `http://localhost:4803`, because Portless assigns a free backend port to the app process. App `dev:app` scripts also print a `Portless URL:` line from the `PORTLESS_URL` environment variable; use that URL in the browser: ```text theme={null} Portless URL: https://tuturuuu.localhost ``` If Turbo cannot prompt for the Portless sudo password while starting app dev scripts, run the Portless setup helper first: ```bash theme={null} bun portless:setup ``` The helper starts the Portless HTTPS proxy on port `443` before Turbo launches package `dev` scripts. It no-ops when the proxy is already responding and skips in non-interactive shells or CI. `bun setup` runs this helper after dependency installation so fresh local checkouts are ready before the build step, then invokes Turborepo through the repo-local `turbo:local` helper instead of any globally installed Turbo binary. To install Portless as an OS startup service instead of only starting the current proxy daemon, run: ```bash theme={null} bun portless:setup -- --service ``` ### Diagnose a broken local environment When a local app suddenly cannot reach another app — for example the Inventory landing page throws `InternalApiError: 404` because its server-side call to `https://tuturuuu.localhost/api/...` is not routed — run the doctor: ```bash theme={null} bun doctor ``` It checks the Node runtime, Docker daemon, local Supabase ports, local Redis ports, apps/web Redis env wiring, app-local Supabase env consistency, whether the Portless proxy is responding on port `443`, and the health of every registered Portless route. The report uses colored `OK`, `WARN`, and `FAIL` statuses in interactive terminals. Supabase env mismatch warnings are compact by default so secret-like values stay out of the normal output; use the verbose view when you need redacted per-file fingerprints: ```bash theme={null} bun doctor --verbose ``` The most common failure after overlapping or crashed dev sessions is a **stale routing table**: the proxy still points a live app route at a dead dev-server port, so cross-app internal API calls return `404`. The doctor flags those routes as `DEAD` and exits non-zero. Static aliases for apps you simply are not running are reported as warnings, not failures, and include an exact cleanup command. An initialized but empty Portless route table is treated as healthy because no apps may be running yet. Apply the safe automatic Portless repair (start the proxy, or reset it when routes are stale) and re-run the checks: ```bash theme={null} bun doctor --fix ``` `bun setup` deliberately no-ops when a proxy is already responding, so it does **not** clear a stale routing table on its own. To force a clean restart — stop the proxy, prune orphaned dev servers from crashed sessions, then start a fresh proxy that apps re-register against — run: ```bash theme={null} bun portless:reset ``` After a reset, restart your dev servers (for example `bun dev:inventory`) so each app re-registers its route with the new proxy. If `bun doctor` still warns about an inactive static alias after a reset, that alias was created with `portless alias` and is not deleted by proxy resets. Start the app if you still use the alias, or remove the alias shown in the doctor output: ```bash theme={null} bunx portless alias --remove ``` If the doctor warns that app env files use mismatched Supabase values, choose the intended source app and keep these three keys together: `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`, and `SUPABASE_SECRET_KEY`. For quick local development, copy `apps/web/.env.local` to app-local `.env.local` files: ```bash theme={null} bun dev:sync:apps ``` Preview the target files first with: ```bash theme={null} bun dev:sync:apps:dry-run ``` This sync compares app env files only. The root `.env.local` can intentionally target a different Docker or deployment workflow without keeping the app mismatch warning alive. ### Diagnose web dev memory and cache pressure When `apps/web` feels slow or Activity Monitor reports high Node.js usage, start with the dev diagnostic before moving routes into another app: ```bash theme={null} bun diagnose:dev:web ``` Read the report by pressure type: * `Live Next dev process RSS` is the memory held by the running `next dev` process tree. If this is high, inspect the top processes and the latest trace spans before changing architecture. * `apps/web/.next/dev/cache/turbopack` is generated Turbopack filesystem cache. Multi-GB cache growth can make disk usage look like a live memory leak even when process RSS is modest. * `apps/web/.next/cache` can include the Next 16.3 Turbopack build filesystem cache from local builds. It speeds repeated local `next build` runs, but it is still local artifact state and must stay out of Turborepo task outputs. * `.turbo/cache` is Turborepo task cache. It is separate from the live Next.js dev server and should not be treated as app RSS. * `Build memory policy` reports Docker and `next build` memory budgets. Those caps explain build behavior only; do not compare them directly to `next dev` RSS. * `Likely pressure` calls out whether the current evidence points to live RSS, cache growth, watcher limits, or build-only memory settings. If the report points at Turbopack cache growth, stop the web dev server and preview the targeted cleanup first: ```bash theme={null} bun clean:dev:web --dry-run ``` Then remove the web Next dev output: ```bash theme={null} bun clean:dev:web ``` Use `bun clean:dev:web --all-next-dev --dry-run` when several app dev caches exist and you want to inspect every `apps/*/.next/dev` target before deleting them. Add `--include-turbo-cache` only when the report also calls out `.turbo/cache` growth after branch or dependency graph churn. Avoid the broad root `bun clean` command for this problem because it deletes dependency and build state that is unrelated to the current dev-server slowdown. Then restart the targeted app command you were using, such as `bun dev:web`. Avoid deleting unrelated app output while other agents or local sessions are working in the same checkout. If live RSS is the real pressure, use the latest `.next/dev/trace` spans and the matching process tree to reduce the compiled import graph first. Favor narrow package subpath imports and lazy-loaded settings panels before splitting an app boundary. A dedicated infrastructure app only reduces `apps/web` memory when infrastructure pages leave the web route graph; running `apps/web` and an infrastructure app together can increase total RAM. Native local dev leaves Watchpack polling off unless the environment explicitly sets `WATCHPACK_POLLING`. This keeps file watching lighter on macOS and Linux. If the diagnostic reports watcher `EMFILE` errors or route discovery stops updating on your machine, restart with polling enabled: ```bash theme={null} WATCHPACK_POLLING=true bun dev:web ``` If the doctor warns that apps/web is missing Redis env, configure the local SRH bridge and start the Redis stack in one step: ```bash theme={null} bun redis:setup ``` `bun redis:setup` writes `UPSTASH_REDIS_REST_URL=http://localhost:8079` and the matching local token into `apps/web/.env.local`, then runs `bun redis:start`. Restart `bun dev:web` after setup so the app picks up the new env values. To clear local Redis data while keeping the same local env wiring, run: ```bash theme={null} bun redis:reset ``` This starts the local Redis stack if needed, then runs `FLUSHALL` inside the Redis container. To stop the local dev environment, run: ```bash theme={null} bun stop ``` This stops this repo's Portless-registered Next.js dev servers, prunes Portless routes, removes stale static aliases for this project, stops local Supabase, and finishes by running `bun doctor`. Preview the cleanup first with: ```bash theme={null} bun stop --dry-run ``` ### Start Local Supabase Instance To start a local supabase instance (database), run the following command: ```bash bun theme={null} bun sb:start ``` > [!NOTE] > > This command will start a local supabase instance on your machine. You can > access the supabase instance by visiting the following URL: > [http://localhost:8003](http://localhost:8003) > [!WARNING] > > You need to have Docker installed and running on your machine to start a local > supabase instance. ### Stop Local Supabase Instance To stop the local supabase instance, run the following command: ```bash standard theme={null} bun sb:stop ``` `bun stop` is broader than Supabase. It stops this repo's local dev servers, cleans stale Portless aliases, stops Supabase, and verifies the result with `bun doctor`. ### Better Development Experience In case you want to run all local development servers, run the following command: ```bash bun theme={null} bun devx ``` > [!NOTE] > > Running `devx` will: > > 1. Stop the currently running supabase instance and save current data as backup (if there is any) > 2. Install all dependencies > 3. Start a new supabase instance (using backed up data) > 4. Start all Next.js apps in development mode > > If you want to have the same procedure without the backup, you can run `bun devrs` instead. This will: > > 1. Stop the currently running supabase instance (if there is any) > 2. Install all dependencies > 3. Start a new supabase instance (with clean data from seed.sql) > 4. Start all Next.js apps in development mode > [!TIP] > > In case you don't want to run a local supabase instance, you can run `bun dev` > instead. ### Local development #### Seed accounts There are 5 seed accounts that are already set up for local development: 1. [local@tuturuuu.com](mailto:local@tuturuuu.com) 2. [user1@tuturuuu.com](mailto:user1@tuturuuu.com) 3. [user2@tuturuuu.com](mailto:user2@tuturuuu.com) 4. [user3@tuturuuu.com](mailto:user3@tuturuuu.com) 5. [user4@tuturuuu.com](mailto:user4@tuturuuu.com) You can use any of these accounts to log in to the app and quickly test the functionality of the app, since they are already set up with the necessary data. #### Authentication A local mail server (**InBucket**) is automatically set up by Supabase to handle authentication emails. > [!NOTE] > > You can access the mail server by visiting the following URL: > [http://localhost:8004](http://localhost:8004) ## Build Builds run in CI on this machine's workflow. Open a PR, wait for the relevant app build checks on its exact head commit, and inspect the preview deployment when runtime behavior needs verification. `bun setup` also invokes package builds, so use `bun install` for a new local worktree. Do not run `bun run build` or app-level build scripts locally. Run focused tests locally if needed; `bun validate` can build workspace dependencies through Turbo. Use the applicable test, type-check, lint, and build workflows on the PR's exact head commit instead of running it here. ## Test To run all tests, run the following command: ```bash bun theme={null} bun run test ``` To run the Flutter mobile quality gate, use: ```bash bun theme={null} bun check:mobile ``` `bun check:mobile` runs Dart format, Flutter analyze, and Flutter tests for `apps/mobile`. Flutter test output is streamed by default so slow suites still show progress instead of appearing stuck. ### Verify dependency patches Check the official stable version and publication time before resolving an update. Keep `bunfig.toml`'s release-age policy in force. Resolve a small coherent group in an isolated checkout using the package manager, then compare resolved entries and workspace declarations in the lockfile. A new nested entry can be required when a transitive consumer pins the old version exactly; report that constraint rather than claiming every consumer uses the new version. For example, DOMPurify 3.4.16 fixes in-place raw-text and hook-detachment behavior. Test the real browser and isomorphic packages with the owning app configurations, including safe markup, executable attributes and whole-document forms. An old version that fails the targeted regression provides a useful negative control. The contacts preview uses DOMPurify; Mail uses a separate `sanitize-html` contract, so tests of one sanitizer do not verify the other. Monaco 0.57.0 pins DOMPurify 3.4.15, including in its current stable registry metadata; upgrading compatible consumers does not remove that pin. Queue installs and test stages through `ttr resources run` after fresh resource checks, leaving urgent validation ahead of dependency maintenance. A focused test fixture does not establish full workspace resolution, type-checking or app builds. Require those results from CI on the exact implementation commit. ### Mobile release builds The native build commands verify or hydrate each flavor's ignored Firebase SDK configuration from the `tuturuuu-mobile` Firebase project before compiling. The Firebase CLI must be authenticated with access to that project. ```bash theme={null} # Production Android App Bundle bun build:android # Signed production iOS IPA bun build:ios ``` The default iOS command requires an Apple signing identity and provisioning profile. `bun build:ios:ipa` is an alias for the same signed release build. To compile the production app on a machine without signing credentials, use: ```bash theme={null} bun build:ios:unsigned ``` `bun build:android` only produces signed production bundles. Configure the protected upload keystore through all four `ANDROID_KEYSTORE_*` environment variables or `apps/mobile/android/key.properties`; the command fails before compilation when signing is absent and verifies the resulting AAB with `jarsigner`. The Mobile Store Deployment workflow hydrates these credentials in its protected runner and executes this exact command. Each store upload derives its app version from the major and minor values in `apps/mobile/pubspec.yaml` and the highest existing TestFlight prerelease version for that series. For example, an unused `0.11.0` ships as `0.11.0`; once that version exists in TestFlight, later uploads advance to `0.11.1`, then `0.11.2`. An unused higher source patch is retained rather than incremented. Android and iOS receive the same version, while the unique CI build number remains separate. This does not commit a version bump; Release Please still owns the source version. Development builds remain available through `bun build:android:dev`. TestFlight distribution defaults to all available beta groups. Configure `TESTFLIGHT_BETA_ENABLED=false` to disable automatic distribution, or set `TESTFLIGHT_BETA_GROUPS` to a comma-separated list of group names or IDs to limit it. If Apple is still reviewing another build of the same app version, the new build remains available to internal testers and its external review is deferred. Reviews of older app versions do not block a newer version. The Mobile TestFlight Review Queue workflow checks every five minutes and can be run manually; it submits the newest processed internal build to the selected external groups without falling back to an older build. It never withdraws an earlier submission. Once an approved build is available, the retry also expires superseded builds older than 14 days while retaining the two newest uploads, the two newest approved builds, builds in review, and builds attached to an App Store release. The retry workflow accesses App Store Connect only after its code has been promoted to `production`. Validate the store workflow and review queue locally with `node --test scripts/ci/mobile-store-workflow.test.js scripts/mobile-deployment/verify-store.test.mjs`. To hydrate or validate a native Firebase configuration without compiling, run: ```bash theme={null} bun mobile:firebase:configure --environment production --platform android bun mobile:firebase:configure --environment production --platform ios ``` > [!WARNING] > > Tests are still a work in progress. We're currently working on adding tests to all packages to ensure the best quality possible. ## Git Conventions Tuturuuu uses standardized conventions for Git commits and branch naming. For more information, see the [Git Conventions](/build/development-tools/git-conventions) guide to learn how to format your commits and branch names to align with our workflow. ### Diagnosing a first-attempt Playwright failure `trace: 'on-first-retry'` records a trace only when Playwright runs a retry. A suite with no configured retries therefore produces no trace for its initial failure. For the Inventory / Storefront cache contract, use `trace: 'retain-on-failure'` so the first failed navigation has an uploaded trace without adding automatic reruns. A URL assertion can complete before a streamed route enters its recovery boundary. Capture browser errors and recovery details after the failing content assertion, before deleting the local fixture. Keep the original assertion error, timeout, and shell-persistence checks intact; diagnostic failures must not mask it. The cache contract attaches bounded browser errors with Bearer/JWT values redacted and a failure screenshot. Its trace may contain local fixture request data, so keep it within the existing failure-artifact access and seven-day retention policy; never use production credentials or customer records in this fixture. Inspect the trace and attached errors before deciding whether the cause belongs to the application, fixture, or development runtime. A recovery boundary alone does not establish that a failure is a flake. A push changing this test/config already triggers `e2e-tests.yaml`; use that exact-head run rather than creating a duplicate manual dispatch. Manual dispatch currently selects the full E2E workflow, rather than an individual cache-contract job. ### Validating Undici dependency upgrades The direct Undici 8.x owners are Infrastructure and Web. Update their package declarations through Bun and review the lock diff: a scoped direct upgrade should change those workspace entries and the shared 8.x resolution. A recursive update can also refresh SDK/Discord consumers on maintained 6.x and 7.x lines; validate those as a separate consumer group rather than assuming the direct owners cover them. Preserve the repository's minimum release age and lifecycle-script policy. Run the existing managed-cron network and chat link-preview tests in both owning apps using their actual Vitest configs. These checks preserve public-address DNS validation, private-address rejection and redirect handling with injected transport dependencies. They do not establish real socket, HTTP/2 or Worker transport behavior. Web's `src/lib/undici-compatibility.test.ts` additionally uses the actual library to preserve a literal `__proto__` cookie as an own property of a null-prototype result and retain an epoch expiry when clearing a cookie. Require exact-commit Infrastructure and Web type checks and builds on hosted CI after frozen-lock installation. Do not run local builds. A skipped build job is not verification. Infrastructure's existing preview workflow also deploys; use a CI-only build route when deployment is outside the authorized scope. # Documenting Source: https://docs.tuturuuu.com/build/development-tools/documenting Learn how to contribute to our documentation. ## Preview and validate Install the pinned Bun/Node toolchain and clone the repository. Docker, Rust, and TanStack Start are paused and are not prerequisites for writing docs. ```bash theme={null} bun dev:docs bun dev:docs --port 3333 ``` The local wrapper runs the version pinned in `apps/docs/mintlify-version.json` through `npx` from `apps/docs`. Preview at `http://localhost:3000` (or the selected port), and stop with Ctrl+C. It does not start containers or other apps. Run finite source checks from the repository root: ```bash theme={null} node scripts/generate-docs-inventory.js node scripts/generate-app-seo.js node scripts/docs-audit.js node scripts/generate-docs-inventory.js --check node scripts/generate-app-seo.js --check node scripts/local-docs.js broken-links ``` The inventory covers maintained app routes, packages, toolchains, and declared and locked dependencies. Do not hand-edit generated reference pages. It excludes paused Rust/TanStack source and dependency refreshes. Version references describe checked-in versions, not the newest upstream release or a deployment claim. Generated pages under `reference/repository/` carry `noindex: true` in their frontmatter. They remain public and visible in navigation, but stay out of site search, search-engine indexing, AI assistant context, `llms.txt`, and `llms-full.txt`. The inventory generator owns this flag. Keep `seo.indexing` unset (or at its default) in `docs.json`; `"all"` can override the exclusions. See Mintlify's [indexing rules](https://www.mintlify.com/docs/organize/hidden-pages#search-seo-and-ai-indexing) and [LLM files](https://www.mintlify.com/docs/ai/llmstxt). Authored package guides, including SDK and masonry, stay indexed. The pinned 4.2.1184 static exporter excludes these pages from its search index and emits their HTML with `noindex`, but still lists them in its `llms.txt`. It emits no `llms-full.txt`. Use hosted checks below to verify the documented LLM exclusions; a successful static export does not establish them. After an authorized deployment, fetch `llms-full.txt` and confirm that no `Source: https://docs.tuturuuu.com/reference/repository/` sections remain; ordinary links to those pages may remain. Check `llms.txt` for excluded entries, following any split indexes it links. Fetch every generated page anonymously: it must return HTTP 200 with its body and a robots `noindex` directive. Confirm that the Reference navigation still lists those pages. Search for exact generated page titles and distinctive body text in the site's search: those pages must be absent, while an authored guide still returns results. Record full-file byte size after the deployment and search-index refresh. Source checks alone do not prove hosted LLM output or search behavior. `docs-seo-check.yaml` runs inventory, navigation/link, SEO-policy tests, and strict Mintlify validation in CI. Strict validation compiles docs; do not run it or app builds on this machine. Require relevant lint, type-check, unit-test, and real Next build workflows for the exact commit when implementation changes. ## Sitemap ownership and Search Console `packages/utils/src/seo-policy.json` is the canonical app-domain and public-page allowlist. Generate satellite assets with `node scripts/generate-app-seo.js` and verify them with `--check`. The generator removes obsolete static sitemaps for private apps and the platform; it leaves unrelated public files untouched. Authenticated workspace pages, login flows, private share links, and checkout pages are not sitemap candidates. A private app needs no sitemap until it has explicitly indexable public content; do not copy the platform sitemap into it. The platform owns `src/app/sitemap.ts` and `src/app/robots.ts`; static files with those names conflict with its publication-aware metadata routes. Satellite sitemaps advertise their own canonical origin, including Nova (`nova.tuturuuu.com`) and Rewise (`rewise.tuturuuu.com`) production domains. The retired `rewise.me` and `rewise.school` hosts and the noncanonical `nova.ai.vn` host must not appear in generated discovery links. Do not invent `lastmod` values from build time or add language URLs that redirect to the same canonical page. Dynamic publication paths need an anonymous, publication-aware reader before being enumerated; public route patterns alone do not expose a content catalog. After deployment, verify each advertised sitemap returns XML with successful HTTP status and canonical URLs before submitting it under its matching Search Console property. Repository checks do not prove deployment or crawlability. The invite-only Colab SPA also declares `noindex`; its authenticated workshop URLs are not a public sitemap catalog. Docs hosting generates its own `https://docs.tuturuuu.com/sitemap.xml`. ## Writing Documentation ### File Structure Each documentation file should follow this structure: ```mdx theme={null} --- title: "Page Title" description: "Brief description of the page content" updatedAt: "YYYY-MM-DD" --- # Page Title Content goes here... ``` ### Content Guidelines 1. **Use clear headings** to structure your content 2. **Include code examples** with proper syntax highlighting 3. **Add cross-references** to related documentation 4. **Keep content up-to-date** by updating the `updatedAt` field 5. **Use consistent formatting** throughout ### Product Decisions and Regression Evidence Record intentional customer behavior in the owning feature page alongside the change: scope, defaults, affected web/mobile surfaces, persistence and permission rules, and intentional exceptions. Distinguish implemented behavior from pending stages and installed or deployed behavior. Link the owning regression tests and exact validation evidence; do not convert a user preference into a repo-wide rule. Exercise the real boundary that previously failed. Examples include server-to-client date serialization, cache provenance before membership-based cancellation, and route-to-provider payload propagation. A helper-only mock can pass while those contracts remain broken. Use synthetic fixtures; keep private calendars, mail, credentials and live notifications out of shared test evidence. ### Long-session learning maintenance Finish sustained agent work by updating reusable guidance, not by copying the conversation into documentation. Use the existing feature page for customer behavior, the operational runbook for debugging/delivery, and the source skill reference for a fragile agent procedure. Keep AGENTS.md for rules that apply across tasks; managed plugin caches are not editable source. Record the observed cause, the evidence that distinguishes it from alternatives, the safe repair procedure, relevant regression tests and outstanding runtime proof. Separate source implementation, focused local validation, exact-commit CI, deployment markers, production migrations and authenticated runtime behavior. A merge alone proves none of the later stages. Avoid promoting an unverified inference or a one-off workaround into a permanent rule. Use the [autonomy contract](/build/development-tools/codex-plugin#maintaining-focused-agent-guidance) for useful child work during PR/CI waits and occasional evidence-led workflow audits. Propagate accepted guidance through the maintained plugin and next substantive child/owner briefs. Do not add recurring timers or wake retired controllers as a maintenance side effect. For parallel work, assign one owner per overlapping path and Git publication lane. A child agent being listed is not proof that it is active: check its current state and request a concrete path/check/commit handoff. If a PR branch has another agent's dirty packet, integrate main in a fresh isolated worktree rather than staging or overwriting that packet. After the parent merges, transplant the owned follow-up patch onto current main; do not replay the whole old branch. Keep temporary receipts, exact SHAs, pending gates and scheduler IDs in an unstaged coordination note. Register every worked-on PR with T3 Code, including follow-ups. Use native PR watches for PR news; use an explicitly authorized scheduled task for broader delivery follow-through. Record its cadence and next run, and disable it when delivery is complete. Recheck live refs after each wake. The latest explicit user instruction determines merge/review timing; a speed exception for merging does not silently authorize production promotion or expand the release range. ### Code Examples When including code examples: * Use proper syntax highlighting * Include TypeScript types * Show both server and client examples * Include error handling * Test examples before committing ### Images and Assets * Store images in the `images/` directory * Use descriptive filenames * Optimize images for web * Include alt text for accessibility ## Contributing ### Before You Start 1. Check if documentation already exists 2. Look for similar patterns in existing docs 3. Follow the established structure 4. Read the [Organization Guide](/overview/organization-guide) for structure ### Making Changes 1. **Create a branch** for your documentation changes 2. **Write clear, concise content** that's easy to understand 3. **Include practical examples** that developers can use 4. **Update related documentation** if needed 5. **Test your changes** locally with `bun dev:docs` ### Review Process 1. **Self-review** your changes for clarity and accuracy 2. **Check links** to ensure they work correctly 3. **Verify code examples** are correct and complete 4. **Update the table of contents** if adding new sections 5. **Submit a pull request** with a clear description ## Best Practices ### Writing Style * **Be concise** but comprehensive * **Use active voice** when possible * **Write for your audience** (developers) * **Include context** for complex topics * **Use consistent terminology** throughout ### Organization * **Group related content** together * **Use clear section headings** * **Include a table of contents** for long pages * **Cross-reference** related documentation * **Keep examples practical** and realistic ### Maintenance * **Update documentation** when APIs change * **Remove outdated information** promptly * **Keep examples current** with latest versions * **Review documentation regularly** for accuracy * **Ask for feedback** from other developers ### Mintlify runtime compatibility The docs wrapper pins Node 24.19.0 alongside Mintlify in `apps/docs/mintlify-version.json`, independent of the repository `.node-version` pin (see [Node.js runtime pin](/build/development-tools/node-runtime)). Other host versions use an isolated `npx` Node executable; the host installation is unchanged. Got 12.6.1, used by the pinned CLI's connectivity probe, can schedule a retry after rejection on Node 24.20+ and crash before validation reports an MDX result. The compatibility pin preserves validation and failure exits; it does not retry or ignore errors. The initial tool download needs network access. Reassess the pin when the CLI's Got dependency contains the upstream connection-error fix. The wrapper gives npm an empty temporary `--prefix` while Mintlify still runs from `apps/docs`. This prevents npm from traversing Bun's installed workspace graph: published packages can contain development-only `catalog:` ranges that npm cannot parse when applying the repository's security overrides. Keep those overrides and installed manifests intact. The prefix is removed after success or failure; `scripts/paused-runtimes.test.js` covers working directory, prefix isolation, cleanup and exit propagation. Strict validation remains CI-only. # Feature flags Source: https://docs.tuturuuu.com/build/development-tools/feature-flags Flag policy, lifecycle catalog, admin dashboard and the mobile evaluation contract. The root `config/feature-flags.json` owns the mobile runtime flag inventory. Each array entry has `key` (unique snake\_case), `description`, `owner`, `class` (`read`, `write`, `ui`, `kill`), `default: false`, and `removeBy` (ISO date). The initial 16 mobile flags belong to `mona` and retain legacy removal-date metadata of `2027-01-31`. Removal eligibility follows the catalog kind below. ## Add a flag Name the flag in its PR, add its registry entry with default OFF, assign an owner and lifecycle metadata, and wire its kill switch before enabling the feature. Follow the [trunk-based delivery rule](/build/development-tools/git-conventions#trunk-based-delivery): flags default OFF; kill switch first, rollback second. Run `cd packages/feature-flags && bun run generate` after editing the JSON, then format the generated file with Oxc and commit it. `@tuturuuu/feature-flags` exports `registry`, the generated `FlagKey` union, and the pure `evaluateFlags(registry, context, overrides?)` function. Its tests validate the registry and detect generated-source drift. ## When to add a flag Gate new features behind a flag. Routine UX/UI changes and non-critical fixes ship without one. ## Lifecycle catalog `config/feature-flag-catalog.json` lists every platform flag family with its lifecycle metadata. `@tuturuuu/feature-flags` exports it as `featureFlagCatalog` together with `getFlagLifecycle` and `validateCatalog`. | Family | Scope | Source of truth | | - | - | - | | `mobile-runtime` | global | `config/feature-flags.json` and the mobile endpoint | | `workspace-secret` | workspace | Workspace secrets read through `@tuturuuu/utils/feature-flags` and Infrastructure secret definitions | | `mobile-build` | build | Non-secret mobile deployment settings compiled with `bool.fromEnvironment` | Each entry records `owner`, `createdAt`, `apps` (with `appsComplete` when every consumer app is traced), `sources`, `defaults` per environment (`development`, `staging`, `production`) and `verifiedOnProdAt`. Defaults are the declared value when no override or workspace setting exists; they are not observed production state. `kind` separates removable feature flags from retained controls: * `release` flags gate a new feature. Once `verifiedOnProdAt` is recorded, `removeBy` is derived as that instant plus 48 hours and the flag is overdue after it. * `kill-switch`, `workspace-gate`, `safety-control` and `operational` entries are retained controls. Neither verification nor legacy deadline metadata makes them removal-due. Entries adopted without historic metadata have `legacy: true`; their unknown owner or creation date stays `null` and renders as unknown. For release flags only, a `legacyRemoveBy` date is due through the end of that UTC day. New entries need `legacy: false`, an owner, `createdAt`, a description and a complete app list. Record `verifiedOnProdAt` only from an actual production verification, never from defaults or CI results. `packages/feature-flags/src/catalog.test.ts` fails when a source family gains or loses a flag without a catalog change, when a recorded source stops naming its flag, or when a new entry is marked legacy. ### Overdue check `node packages/feature-flags/scripts/check-lifecycle.mjs` reports malformed metadata and overdue flags as GitHub annotations. Cheap PR Checks runs it in warning mode, which exits 0. `--strict` exits 1 on any report; `--now ` and `--catalog ` pin the clock and input. ### Dashboard Infrastructure `//feature-flags` renders every catalog flag for root workspace members with `view_infrastructure`. A root member with `manage_workspace_roles` can override the 16 mobile-runtime registry keys per `development`, `staging`, and `production`. The page shows the declared default and the effective value after the `mobile_offline` master gate. Workspace-secret flags stay read-only, with the label "Managed per workspace in Secrets" and a link to `//workspaces`. Mobile-build flags stay read-only and are labeled build-time. `cookieConsentBanner` is a separate export and is not a registry toggle. Saved-state or audit failure stays explicit. The page does not invent a persisted OFF value, and it does not select a workspace or write workspace secrets. Platform state is one row per flag key and environment. Resetting to the declared default keeps the revision and stores an empty override. Audit is append-only. Merging this documentation does not apply the database migration or expose the private functions; that deployment is separate. ## Mobile endpoint `GET /api/v1/mobile/feature-flags?wsId=` accepts the existing session or mobile app-session authentication. Authentication failures return 401. `wsId` is optional; when supplied it must be a UUID (400 otherwise), and the caller must belong to that workspace (403 otherwise). Membership lookup failures return 500. A 200 response contains only: ```json theme={null} { "version": "", "ttlSeconds": 30, "flags": { "mobile_offline": false, "offline_read_notes": false } } ``` The example abbreviates `flags`; the response includes **every registry key**. `version` hashes the JSON payload `{ttlSeconds, flags}` with SHA-256, excluding `version` itself. `ETag` is that version in double quotes. A matching `If-None-Match` returns 304 with no body, after authentication and membership checks. Responses use `Cache-Control: private, no-cache` and `Vary: Authorization, Cookie`. The mobile reader polls using the 30-second TTL and retains the last payload on 304. No user or workspace identifiers are returned. User identity comes only from the authenticated session; query parameters cannot select a user. The handler uses `await connection()` for request-time evaluation, with no shared output cache. Both `CDN-Cache-Control` and `Vercel-CDN-Cache-Control` are `no-store`, including 304 and error responses. ## Evaluation After authentication and membership, the endpoint reads platform overrides for one server-selected environment. `VERCEL_ENV=production` selects production, `preview` selects staging, and `development` selects development. An unknown `VERCEL_ENV` selects production. When `VERCEL_ENV` is unset, `NODE_ENV` of `development` or `test` selects development and every other value selects production. A query or body field cannot select the environment. Missing or unreachable storage uses each registry default. An authorization failure or a malformed payload returns an error and does not substitute defaults. The pure evaluator accepts overrides for known keys only and applies the kill switch last: `mobile_offline: false` forces every `offline_` key OFF, including reads, writes and status UI. Context currently has no effect on the boolean result. This endpoint does not enable offline functionality or grant access to underlying data. Regression coverage lives in `packages/feature-flags/src/index.test.ts`, `packages/feature-flags/src/{catalog,lifecycle,check-lifecycle}.test.ts`, `apps/web/src/app/api/v1/mobile/feature-flags/route.test.ts` and the Infrastructure `feature-flags` page and table tests. Cookie-authenticated state mutations require the Infrastructure origin and the `x-tuturuuu-feature-flag-action: 1` header. Bearer API requests use verified token authentication without a cookie fallback. # Git Conventions Source: https://docs.tuturuuu.com/build/development-tools/git-conventions Learn how Tuturuuu uses Conventional Commits and Branch naming to improve development workflow. > [!NOTE] > > **Prerequisite**: You should be familiar with basic Git operations and > understand the [Monorepo Architecture](/build/development-tools/monorepo-architecture) of our > codebase. ## Overview Tuturuuu follows standardized conventions for Git commits and branch naming to improve collaboration, automate releases, and maintain a clean, navigable repository history. We use two main specifications: 1. [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for structured commit messages 2. [Conventional Branch](https://conventional-branch.github.io/) for consistent branch naming These conventions help automate our CI/CD workflows, generate changelogs, and make our development process more efficient. ## Conventional Commits ### What are Conventional Commits? Conventional Commits is a specification for adding human and machine-readable meaning to commit messages. It provides a set of rules for creating an explicit commit history, making it easier to write automated tools on top of. The basic structure of a conventional commit is: ``` [optional scope]: [optional body] [optional footer(s)] ``` ### Types Tuturuuu uses the following commit types: | Type | Description | Example | | - | - | - | | `feat` | New feature or enhancement | `feat: add dark mode support` | | `fix` | Bug fix | `fix: prevent crash when user data is undefined` | | `docs` | Documentation changes | `docs: update installation instructions` | | `style` | Code style changes (formatting, no code change) | `style: format code with prettier` | | `refactor` | Code refactoring | `refactor: simplify authentication logic` | | `perf` | Performance improvements | `perf: optimize database queries` | | `test` | Add or fix tests | `test: add unit tests for auth middleware` | | `build` | Changes affecting build system or dependencies | `build: update dependency to fix security issue` | | `ci` | Changes to CI configuration files and scripts | `ci: simplify workflow branch filters` | | `chore` | Routine tasks, maintenance | `chore: update package.json metadata` | ### Scopes Scopes provide additional context about which part of the codebase is affected. In our monorepo structure, we often use package or app names as scopes: ``` feat(web): add new dashboard layout fix(ui): correct button alignment in mobile view chore(types): update supabase database types ``` ### Breaking Changes Breaking changes must be indicated by adding a `!` after the type/scope or by using a `BREAKING CHANGE:` footer: ``` feat(api)!: require authentication for all endpoints BREAKING CHANGE: All API endpoints now require authentication tokens. ``` ### Examples Here are some examples of conventional commits used in our codebase: ``` feat(web): add new calendar integration fix(supabase): correct permission issue in auth policy docs(readme): update development setup instructions style: apply consistent formatting with prettier refactor(utils): simplify date formatting functions perf(queries): optimize workspace user loading test(auth): add tests for token verification build(deps): update Next.js to v14 ci(vercel): add automatic preview deployments chore(release): publish packages ``` ## Conventional Branches ### What are Conventional Branches? Conventional Branch refers to a structured naming convention for Git branches that makes it easier to identify branches by type and purpose. The basic structure is: ``` / ``` ### Branch Types Tuturuuu uses the following branch types: | Type | Description | Example | | - | - | - | | `main` | Main development branch | `main` | | `feature` | For new features | `feature/user-dashboard` | | `feat` | Short feature prefix also accepted | `feat/invite-link-permissions` | | `fix` | Short bug-fix prefix also accepted | `fix/invite-membership-check` | | `bugfix` | For bug fixes | `bugfix/login-error` | | `hotfix` | For urgent fixes | `hotfix/security-vulnerability` | | `release` | For preparing releases | `release/v1.2.0` | | `chore` | For maintenance tasks | `chore/update-dependencies` | | `docs` | For documentation-only work | `docs/git-conventions-refresh` | | `style` | For formatting or stylistic cleanups | `style/oxc-pass` | | `refactor` | For internal code restructuring | `refactor/task-query-shell` | | `perf` | For performance-focused changes | `perf/workspace-user-search` | | `dependabot` | Automated dependency update branches | `dependabot/npm_and_yarn/next` | | `claude` | AI-assisted scratch or experimental PR | `claude/rate-limit-audit` | Release Please bot branches are also accepted with the `release-please--branches--` prefix. The exact automated image-optimization branch `imgbot` is also allowed; similarly named branches still require a conventional prefix. Do not create human-authored branches with that prefix. ### Naming Rules 1. Use lowercase alphanumeric characters and hyphens 2. Keep names concise but descriptive 3. Include ticket/issue numbers when applicable 4. Avoid special characters (except hyphens) ### Examples ``` feature/workspace-sharing feat/public-course-sharing fix/file-upload-error bugfix/auth-vulnerability release/v2.5.0 chore/update-react-18 docs/git-conventions-refresh feature/issue-123-user-profile ``` ### Merge Commit Exception Authored commits should follow Conventional Commits. The common exception is a Git-generated merge commit when syncing a long-lived branch, for example: ```bash theme={null} Merge branch 'main' into feat/studying-platform ``` Keep that merge summary when the goal is to preserve the branch's merge history. Use a conventional commit message again for the next authored commit after the merge. ## How These Conventions Improve Our Workflow ### 1. Automated Changelog Generation Our conventional commits are used to automatically generate changelogs for releases. Different commit types are categorized accordingly: ```markdown theme={null} # Changelog ## Features - add dark mode support (#123) - add calendar integration (#124) ## Bug Fixes - prevent crash when user data is undefined (#125) ## Documentation - update installation instructions (#126) ``` ### 2. Semantic Versioning Conventional commits help determine the next semantic version for packages: * `fix:` commits trigger a PATCH increment (1.0.0 → 1.0.1) * `feat:` commits trigger a MINOR increment (1.0.0 → 1.1.0) * Commits with `BREAKING CHANGE` trigger a MAJOR increment (1.0.0 → 2.0.0) ### 3. Automated Release PRs And Package Publishing Release Please reads Conventional Commits from `production`, updates `release-please-config.json` packages through `.release-please-manifest.json`, and opens one combined release PR with package versions and changelogs. Package publish workflows do not generate versions; they publish only after a release-please version bump lands on `production`. Local manifests keep Tuturuuu workspace dependencies as `workspace:*`; npm release workflows rewrite the checked-out package manifest with `scripts/ci/prepare-npm-package-manifest.js` immediately before `npm pack` so published artifacts contain installable npm version ranges. Package-included `file:` tarball dependencies, such as `@tuturuuu/ui`'s vendored SheetJS tarball, must not leak a consumer-relative `file:` range into the npm manifest. Package preparation expands the checked-in archive into the artifact, redirects the package export to those immutable bytes, and removes the install-time dependency edge. Do not rewrite the vetted archive to a mutable external tarball URL. Before any build or pack work starts, package workflows run `scripts/ci/package-release-readiness.js gate-package-release packages/`. The gate checks publishable Tuturuuu workspace dependency versions on npm once, dispatches missing dependency workflows, and exits green without occupying a runner while dependencies are pending. If the related dependency workflow for the same production SHA failed, completed successfully without npm visibility, or cannot be inspected, the gate fails immediately. Publish jobs still wait for their own version to become visible after `npm publish`, then a separate non-OIDC job dispatches direct dependent package workflows. Workflow-published package manifests must carry provenance-compatible `repository` metadata for `tutur3u/platform`; otherwise npm rejects trusted publishes with `E422`. For example, `release-types-package.yaml` triggers from production changes to `packages/types/package.json`: When bringing the generated release PR branch back to `main`, run `bun git-release-please` from a clean `main` checkout. The helper fetches the latest `release-please--branches--production` branch, merges it without committing, syncs `platform-version.txt` into the platform badge constant and test expectation, runs `bun ff`, stages the resolved merge, then runs `bun validate` directly before the merge commit lands. When the staged release merge includes `apps/mobile` paths, the helper also runs `bun check:mobile`. If you are already inside a manual merge, run `bun release:sync-platform-version` to resolve the recurring `TUTURUUU_PLATFORM_VERSION` conflict before staging the merge. ```yaml theme={null} on: push: branches: [production] paths: - "packages/types/package.json" # ... jobs: check-version-bump: if: github.ref == 'refs/heads/production' && needs.check-ci.outputs.should_run == 'true' # ... ``` ### 4. Better Code Reviews With conventional commits and branches, it's easier to understand the purpose of a pull request at a glance: * A PR from `feature/user-dashboard` with commits like `feat: add user stats widget` clearly indicates a new feature * A PR from `bugfix/auth-issue` with commits like `fix: prevent token expiration error` indicates a bug fix ### 5. Simplifying Navigation Conventional branch names make it easier to navigate the repository history and find specific changes. For example: ```bash theme={null} # Find all feature branches git branch --list "feature/*" # Find branches related to authentication git branch --list "*auth*" ``` ## Tools and Enforcement We use a dedicated CI/CD check to enforce our Git conventions: ### Branch Naming Check We use a GitHub Action workflow to verify that branch names follow our convention: ```yaml theme={null} name: Branch Name Check on: push: branches-ignore: - main - production jobs: check-branch-name: name: Check branch name runs-on: ubuntu-latest steps: - name: Check branch name run: | BRANCH_NAME=${GITHUB_REF#refs/heads/} if ! [[ $BRANCH_NAME =~ ^(feature|feat|fix|bugfix|hotfix|release|chore|docs|style|refactor|perf|dependabot|claude)/.+|^release-please--branches--.+|^imgbot$ ]]; then echo "❌ Branch name '$BRANCH_NAME' doesn't follow the conventional branch format." echo "Branch name should be in format: type/description" echo "Allowed types: feature, feat, fix, bugfix, hotfix, release, chore, docs, style, refactor, perf, dependabot, claude" echo "Bot branches are also allowed with the release-please--branches-- prefix or the exact name imgbot." exit 1 else echo "✅ Branch name follows convention: $BRANCH_NAME" fi ``` ## Best Practices ### Writing Good Commit Messages 1. Use the imperative mood ("add" not "added" or "adds") 2. Keep the description in lowercase to match the repository's observed convention (for example, `feat(backend): migrate nova team read`) 3. Do not end the description with a period 4. Keep the description under 72 characters 5. Use the body to explain the what and why, not the how Example of a well-formatted commit: ``` feat(auth): add multi-factor authentication support Implement TOTP-based multi-factor authentication to improve security. The implementation follows the RFC 6238 standard. Closes #123 ``` ### Coordinating Commits In Shared Checkouts When multiple agents or humans may commit in the same checkout, use the commit window before changing the staged set. The lock is advisory and lives under the ignored `tmp/agent-coordination/` directory, so it protects the Git index and commit operation without becoming part of a commit. Claims default to 10 minutes and may only be 5-10 minutes, so claim only when ready to stage, inspect, and commit. This coordination is **per-checkout** and **harness-agnostic**. The commit window and the `tmp/agent-coordination/` notes both live in the working directory, so they coordinate every agent or human sharing one checkout — parallel Codex or Claude Code sessions, background tasks, and same-directory subagents — regardless of which tool they run under. A separate `git worktree` has its own lock file, its own notes, and its own Git index, so the window does not span worktrees; separate worktrees stay isolated by being on different branches and integrate through the shared remote instead. In a hot shared checkout, commit your owned paths promptly in small scoped commits: a large unstaged set can be discarded by a concurrent rebase, `reset --hard`, `checkout`, or `stash` from any agent or human. (`bun git-sync` is isolated and safe; manual destructive Git is not.) ```bash theme={null} bun git-commit-window status bun git-commit-window claim --owner "" --scope "type(scope): subject" git add path/to/file-a path/to/file-b git diff --cached --stat git diff --cached --name-only git commit -m "type(scope): subject" bun git-commit-window release --token ``` If another agent owns the window and it is appropriate to wait, use `wait`. The command sleeps until the active lock is released or expires, then claims the window before reporting that it is safe to proceed. The waiting period can be longer than the claim TTL, but the claimed window remains capped at 10 minutes: ```bash theme={null} bun git-commit-window wait --owner "" --scope "type(scope): subject" ``` Use `--allow-staged` only after inspecting existing staged files. The commit window does not grant ownership of files or permission to stage unrelated paths. Existing staged files are owned by the staging agent or coordinator until explicitly reassigned. If a file appears as `MM`, both its staged and unstaged diffs need owner review before commit. Let commit hooks run by default. This is a proof-gated no-verify path: use `git commit --no-verify` only when the current agent can prove its exact staged paths would pass the checks normally covered by `bun validate`. The proof packet should include reviewed `git status --short`, `git diff --cached --stat`, and `git diff --cached --name-only` output; the touched files or narrow path group; the separated checks that covered each affected `bun validate` component; any skipped components with path-based rationale; unrelated dirty files excluded from the claim; and `bun check:mobile` coverage when `apps/mobile` is touched. If ownership is unclear, proof is incomplete, or the check mapping is uncertain, do not bypass the hook. Commit hooks and repo checks can read the whole worktree, including files owned by other agents. If they fail on unrelated dirty files, release the commit window and report the blocker instead of formatting, fixing, staging, or committing those files for convenience. Only the staged-set owner may use the proof-gated no-verify path, and only with exact-path evidence for the staged files. ### Branch Management 1. Create branches from the latest `main` branch 2. Keep branches focused on a single task or issue 3. Regularly rebase long-lived branches on `main` to avoid merge conflicts 4. Delete branches after they've been merged ### Synchronizing Release Branches Use the root command below when `production` should point at the same commit as `main`: ```bash theme={null} bun git-sync ``` The command fetches `origin`, creates a temporary detached worktree, refreshes `main`, and fast-forwards `production` to the current `main` commit from that temporary worktree before pushing those branches. It finishes by fetching again and verifying that local and remote `main` and `production` both resolve to the same commit. The checkout you started from is left untouched, so uncommitted work on another branch can keep running while the release refs are synchronized. If a branch that needs to move is already checked out in another worktree, Git will refuse to force-update that branch. Switch that worktree away from the branch or update it manually, then rerun `bun git-sync`. `bun git-sync` does not create commits for you. Commit all intended changes on `main` first; if `production` contains commits that are not already in `main`, reconcile the branch manually before rerunning the command. Use `--only-branch` to update one active sync branch while leaving the other untouched: ```bash theme={null} bun git-sync --only-branch production ``` `main` is still refreshed locally as the source commit, but only `production` is fast-forwarded and pushed. Use `--only-branch main` when you only want to pull and push `main`. The retired `staging` branch is no longer a supported `--only-branch` target. The Supabase staging environment still exists, but its workflow is driven from `main`. Use `--current-branch` or `-c` when `main` and `production` should move to the latest commit on the branch you currently have checked out instead of latest `origin/main`: ```bash theme={null} bun git-sync --current-branch bun git-sync -c ``` Current-branch mode still uses a temporary detached worktree, leaves the checkout you started from untouched, and only moves the selected sync branches. It does not push the source branch unless the source branch is itself one of the selected sync branches, such as running from `main`. Combine `-c` with `--only-branch` when only one long-lived branch should move to the current checkout's commit: ```bash theme={null} bun git-sync -c --only-branch production ``` Use `--no-push` for local-only synchronization: ```bash theme={null} bun git-sync --no-push bun git-sync --only-branch production --no-push bun git-sync -c --no-push ``` With `--no-push`, the command fetches, pulls with `--ff-only`, and fast-forwards the selected local branches, but it never pushes to `origin`. Final verification checks local refs only. ### Pull Request Workflow 1. Create a branch with the appropriate type based on the work 2. Make commits using conventional commit messages 3. Push the branch and create a pull request 4. Use conventional commit style for the PR title 5. After approval and merge, delete the branch ## Conclusion Following these Git conventions helps us maintain a clean, understandable repository history, automate release processes, and improve collaboration across the team. By standardizing both commit messages and branch names, we create a more efficient development workflow. When a branch grows large enough that one pull request cannot be reviewed comfortably, split it into a chain of dependent PRs — see [Stacked Pull Requests](/build/development-tools/stacked-pull-requests). For more information, refer to the official documentation for [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) and [Conventional Branch](https://conventional-branch.github.io/). ## Trunk-based delivery Integrate small changes into main behind flags that default OFF. Add and verify the kill switch before enabling a feature. During an incident, disable the kill switch first, then roll back if needed. Track each flag owner and removal date in the [feature-flag registry](/build/development-tools/feature-flags). # Hosted Dev Supabase Preview Source: https://docs.tuturuuu.com/build/development-tools/hosted-dev-supabase-preview Push migrations to a hosted dev Supabase project and share a running web and Tasks preview through Cloudflare quick tunnels. Use this when a change has to be tried on a real database without a local Docker stack, or when someone else has to click through a running build. It covers a hosted **dev** Supabase project that the project owner has authorized for migration pushes and test data. It never applies to production: production migrations still go through the gated `supabase-production.yaml` workflow, and `bun sb:push` / `bun sb:linkpush` stay off-limits in agent checkouts. ## Push migrations to the dev project Run the repo's pinned CLI from `apps/database`. Pass the access token as `SUPABASE_ACCESS_TOKEN`: on macOS the pinned binary can otherwise block on a Keychain prompt with no output. ```bash theme={null} cd apps/database export SUPABASE_ACCESS_TOKEN= # never commit it node_modules/.bin/supabase link --project-ref node_modules/.bin/supabase db push --linked --include-all --dry-run node_modules/.bin/supabase db push --linked --include-all ``` Read the dry run before pushing. * **Remote-only versions.** "Remote migration versions not found" usually means a migration was renamed in the repo after the dev project applied it. Check that the renamed file is idempotent, then run `supabase migration repair --status reverted ` and let the renamed file apply. * **Unqualified extension functions.** Without a database password, the CLI connects through a temporary `cli_login_postgres` role and switches to `postgres`. That session's `search_path` does not include `extensions`, so a migration that calls an extension function such as `gen_random_bytes` outside a function body fails with `function ... does not exist`. Apply that one file through the Management API (`POST /v1/projects//database/query`, which runs as `postgres` with `extensions` on the path) inside a transaction. In the same transaction, insert its row into `supabase_migrations.schema_migrations`. Then resume `db push`. * **API schemas.** PostgREST must expose the same schemas as `apps/database/supabase/config.toml` (`public, graphql_public, storage, private`). A project that only exposes `public` fails on `private` RPCs, for example task list counts on a board. Run SQL suites such as `apps/database/supabase/tests/task-board-sprints.sql` with `psql` over the temporary login role (`SET ROLE postgres` first). They begin and roll back their own transaction, so the dev data is unchanged. ## Share a running preview Keep the preview in its own detached worktree under `.worktrees/`, so feature branches keep moving while it serves. Build only the workspace packages that export from `dist` (`types`, `supabase`, `internal-api`, `devbox`, `editor`, `masonry`) with their `tsc` build scripts. These are the dev runtime's prerequisites, not release builds. 1. Start two quick tunnels first, because `NEXT_PUBLIC_*` values are read at boot. Do not override the Host header. ```bash theme={null} cloudflared tunnel --no-autoupdate --url http://localhost:7803 # WEB_ORIGIN cloudflared tunnel --no-autoupdate --url http://localhost:7809 # TASKS_ORIGIN ``` 2. Write each app's own `.env.local` (not the root one). Both need the Supabase URL, the publishable and secret keys, and the same `TUTURUUU_APP_COORDINATION_SECRET`, plus: | App | Variables | | - | - | | `apps/web` | `BASE_URL`, `WEB_APP_URL`, `NEXT_PUBLIC_WEB_APP_URL` = WEB\_ORIGIN; `TASKS_APP_URL`, `NEXT_PUBLIC_TASKS_APP_URL` = TASKS\_ORIGIN; `TUTURUUU_EXTERNAL_APP_DOMAINS=tasks:TASKS_ORIGIN`; `INTERNAL_WEB_API_ORIGIN=http://localhost:7803` | | `apps/tasks` | `TASKS_APP_URL`, `NEXT_PUBLIC_TASKS_APP_URL` = TASKS\_ORIGIN; `TTR_URL`, `NEXT_PUBLIC_WEB_APP_URL` = WEB\_ORIGIN; `INTERNAL_WEB_API_ORIGIN=http://localhost:7803` | With a hosted Supabase URL, dev sign-in requires Turnstile. Use Cloudflare's public always-pass test keys (`NEXT_PUBLIC_TURNSTILE_SITE_KEY=1x00000000000000000000AA`, `TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA`) and keep captcha off on the dev project. 3. Next 16 rejects cross-origin dev requests, and HMR reloads the page about every 40 seconds when its socket is refused. In the preview worktree only, add `allowedDevOrigins: ['*.trycloudflare.com']` to the `createTuturuuuNextConfig` call in `apps/web/next.config.ts` and `apps/tasks/next.config.ts`. Never commit it. 4. Start `bun run dev:app` in `apps/web` and `apps/tasks`. Do not use `bun dev`, which wraps them in portless. Opening TASKS\_ORIGIN redirects to web's login. After password sign-in, web asks to continue to Tasks and returns through `/verify-token`. Keep the Mac awake (`caffeinate -dimsu`) for an overnight preview. Quick-tunnel URLs change whenever cloudflared restarts, and the env files and both apps must follow. ## Known limits * Realtime (live board updates between people, collaborative descriptions in the task panel) needs the `meet-realtime` worker and its token secret. The preview does not run it, so the panel shows "Reconnecting". * Sessions are tied to each quick-tunnel host. The app-session refresh fetch targets `https://localhost:` and fails after about eight hours, so people have to sign in again. * Quick tunnels allow roughly 200 in-flight requests. The first cold page load in `next dev` may see a few retries. # Local End-to-End Environment Source: https://docs.tuturuuu.com/build/development-tools/local-e2e Run the isolated Supabase stack, web, Playwright and mobile simulator/emulator end-to-end tests on a dedicated build Mac. A dedicated build Mac (reached over SSH) hosts a repeatable local end-to-end environment: an isolated Supabase project with migrations and seed data, the `apps/web` dev server, Playwright, and the mobile app on a dedicated iOS Simulator and Android Emulator. Use it to validate changes against real simulator/emulator runs instead of host-only widget tests. The entry point is `scripts/thanh-e2e/thanh-e2e.mjs`. It works on any macOS host with the same toolchain; the build Mac's defaults are baked in and overridable by environment variables. > [!WARNING] > > Use the build Mac only for this lane. Queue heavy steps (`up`, `seed`, `web`, > `web-e2e`, `mobile-e2e`) with `ttr resources run --` from a checkout under > `/tuturuuu-*`, and never stop other projects' or lanes' > containers, emulators or queue owners. Android's dummy Firebase input is created exclusively: an existing file or symlink is preserved, including a dangling symlink. PID state is opened without following symlinks and classified and read through the same descriptor; malformed PID values are ignored, while unsafe file types fail explicitly. Run the focused filesystem regressions with `node --test scripts/thanh-e2e/*.test.mjs`; no simulator or database setup is required. ## Toolchain Everything Tuturuuu-specific lives in user space under `/tuturuuu-tools` (`$T`). Source `$T/mobile-env.sh` first; it sets `DEVELOPER_DIR`, `JAVA_HOME`, `ANDROID_HOME`/`ANDROID_AVD_HOME`, `PUB_CACHE`, `GRADLE_USER_HOME`, an isolated `XDG_CONFIG_HOME` for Flutter settings, and `PATH` (Flutter 3.47.7, Temurin 17, Android SDK tools, Bun, Docker). | Component | Location | | - | - | | Xcode 26.5 + iOS 26.5 runtime | `/Applications/Xcode.app` | | Flutter 3.47.7 | `$T/flutter-3.47.7-stable-arm64/flutter` | | JDK 17 (Temurin) | `$T/jdk` | | Android SDK (platforms 36 + 37, NDK 28.2, API 36 arm64 image) | `$T/android-sdk` | | AVDs | `$T/android-avd` | | E2E state (Supabase workdir, env files, logs, screenshots) | `$T/e2e/` | `xcode-select` on the build Mac still points at the Command Line Tools. Dart native-asset build hooks run with a filtered environment that keeps `PATH` but drops `DEVELOPER_DIR`, so `$T/bin/xcrun` pins Xcode. Without it, iOS builds fail in `objective_c/hook/build.dart` with `Bad state: No element`. Remove the shim after an administrator runs `sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`. ## Isolation | Resource | Value | Override | | - | - | - | | Supabase project id | `tuturuuu-e2e` | `TUTURUUU_E2E_PROJECT_ID` | | Supabase ports | `8000`-`8007` (API `8001`, DB `8002`, Studio `8003`, mail `8004`) | `TUTURUUU_E2E_SUPABASE_BASE_PORT` | | Web dev server | `http://127.0.0.1:7803` | `TUTURUUU_E2E_WEB_PORT` | | Satellites | Calendar on `http://localhost:7806` | `TUTURUUU_E2E_SATELLITES` (`calendar`, `none`) | | iOS Simulator | `tuturuuu-ios-iphone17pro` | `TUTURUUU_E2E_IOS_SIM` | | Android Emulator | `tuturuuu-android-36-pixel9pro` on `emulator-5580` | `TUTURUUU_E2E_AVD`, `TUTURUUU_E2E_AVD_PORT` | The ports stay canonical on purpose: the web local-E2E auth and captcha bypass (`apps/web/src/lib/auth/local-e2e.ts`) and the Playwright safety guard (`apps/web/e2e/helpers/environment.ts`) only trust Supabase `:8001` and web `:7803` on loopback. With other ports, mobile password sign-in fails with `Turnstile is not configured`. Isolation comes from the project id instead: the script refuses the default `tuturuuu` id and `up` fails fast when any port in the block is already listening, so it never adopts another lane's stack. Only one stack on the canonical ports can run on a host at a time; stop it with `down` when you finish. The Supabase config is staged from tracked `apps/database/supabase` files and rewritten with the isolated helpers from `apps/database/scripts/run-supabase-isolated.js`. Docker over SSH cannot use the macOS keychain (`credsStore: desktop`). The script points `DOCKER_CONFIG` at a credential-free directory in the state dir and `DOCKER_HOST` at the Docker Desktop socket, so public image pulls work anonymously and the keychain is never touched. ## Run it ```bash theme={null} ssh . /tuturuuu-tools/mobile-env.sh cd /tuturuuu-e2e # any checkout under /tuturuuu-* bun install # once per checkout E2E=scripts/thanh-e2e/thanh-e2e.mjs node $E2E doctor ttr resources run -- node $E2E up # start + migrations + seed ttr resources run -- node $E2E web # build types/supabase, start web + satellites node $E2E devices # boot simulator + emulator headless ttr resources run -- node $E2E web-e2e --install -- e2e/auth.noauth.spec.ts ttr resources run -- node $E2E mobile-e2e ios ttr resources run -- node $E2E mobile-e2e android ttr resources run -- node $E2E mobile-e2e android --mode=profile node $E2E status node $E2E down # stop web + Supabase; --web-only, --purge ``` `seed` re-applies migrations and seed data. `env` rewrites `$T/e2e//env/web.env` and `mobile.json` from `supabase status`. `web.log` and other logs live in the state dir's `logs/`. ## Test accounts The seed creates `local@tuturuuu.com` (root admin) and `user1`-`user4@tuturuuu.com` with the public local-only seed password from `apps/database/supabase/seed.sql`. The mobile flow defaults to `local@tuturuuu.com`; override with `--dart-define=E2E_EMAIL=...` only for other seeded accounts. ## Satellites Web proxies some owner APIs to satellite apps; Calendar's event API is proxied to the Calendar app, so without it Agenda shows `ApiException(500): Request failed` and web logs `Failed to proxy https://calendar.tuturuuu.localhost/... ECONNREFUSED`. `web` therefore also starts each satellite in `TUTURUUU_E2E_SATELLITES` (default `calendar`) on its default port with the same local Supabase env and `WEB_APP_URL`/`INTERNAL_WEB_API_ORIGIN` pointing back at web; web gets `CALENDAR_APP_URL=http://localhost:7806`. `down` stops web and satellites. `web` also builds `@tuturuuu/internal-api`, which Calendar imports from `dist/`. Satellites run on their Next.js runtime (`next dev`), not Vite+ `dev:app`. Vite+ dev runs Calendar inside workerd, which loads linked workspace packages unbundled; `@tuturuuu/internal-api` builds as CommonJS (`NodeNext` without `"type": "module"`), so startup fails with `ReferenceError: exports is not defined`, or `Failed to resolve entry for package "@tuturuuu/internal-api"` before it is built. The Next runtime serves the same route handlers. ## Meet and the realtime Worker The script does not start Meet. For Meet verification (coding room, shared document, backup checkpoints) run, from the same checkout and with the `web.env` values exported: * the realtime Worker: `node_modules/.bin/wrangler dev --local --config apps/meet-realtime/wrangler.jsonc --ip 127.0.0.1 --port 8786 --persist-to --var MEET_REALTIME_TOKEN_SECRET: --var PLATFORM_API_BASE_URL:http://localhost:7803`; * web with the same `MEET_REALTIME_TOKEN_SECRET` (the document checkpoint route verifies the Worker's ticket with it; `node $E2E web` inherits it from the shell), plus `PROGRAMMING_REALTIME_URL=ws://127.0.0.1:8786/collaboration` and `CLOUDFLARE_CHANNELS_URL=ws://127.0.0.1:8786/channels`; * Meet with `apps/meet/node_modules/.bin/next dev -p 7807 --turbopack` and `WEB_APP_URL`/`INTERNAL_WEB_API_ORIGIN=http://localhost:7803`, `NEXT_PUBLIC_APP_URL=http://localhost:7807` and the same secret and realtime URLs. Meet must run on `7807`: web validates satellite return URLs against the registered local origins in `packages/utils/src/internal-domains.ts`, and the login page refuses an unregistered port. Start these servers as plain background processes you own, never inside `ttr resources run` (a dev server would hold a shared validation slot indefinitely); use admission only for finite captures. Sign in once on web through `dev-session` with a fresh `@tuturuuu.com` address (it creates a confirmed account): the seeded accounts carry version-0 UUIDs that Meet's realtime token schema rejects, so they cannot join a call. The Supabase cookie is shared across `localhost` ports, and a confirmed `@tuturuuu.com` identity can open a meeting coding room without a playground benefit. The `[wsId]/meetings` page panics under `next dev --turbopack` (`node:async_hooks` external), so create the meeting through `POST /api/v1/workspaces//meetings` and open `/r/` directly. A local Worker `fetch` sends no `User-Agent`, and the API proxy treats other bearer tokens as Supabase sessions; the Worker therefore sends explicit service headers and the proxy exempts verified realtime service tickets on the checkpoint routes. Code execution still needs a runner, so Run reports a failure locally; the layout, collaboration and Drive checkpoints are exercised end to end. ### Native Worker imports Workerd rejects random generation during module initialization. Meet and Parley's shared chat initializes its unguessable mention marker on first rendering use, then reuses it for that module instance. Keep the marker lazy; a fixed marker would let authored links impersonate generated mentions. The import and lifetime regressions are in `packages/meet-core/src/features/call/lib/assistant-identity-import.test.ts`. An authenticated native preview returning 500 is not a valid performance sample. ## Mobile wiring `mobile.json` is passed with `--dart-define-from-file` and routes `NEXT_PUBLIC_SUPABASE_URL` and every `*_API_BASE_URL` owner to loopback `127.0.0.1`. Android permits cleartext only to `127.0.0.1`/`localhost`, and the app rewrites `localhost` to `10.0.2.2`, so the script uses `127.0.0.1` and runs `adb reverse` for the web and Supabase ports. All satellite API owners point at the local web server, which owns the live API handlers. `apps/mobile/integration_test/e2e_flows_test.dart` signs in with the seeded account, opens Agenda, opens Settings → Preferences, changes the personal timezone (default `Pacific/Niue`, override with `--dart-define=E2E_TIMEZONE=...`; pick a zone near the top of the picker, whose list is lazy and lives in a draggable sheet) and returns to Agenda. It fails if an `ErrorWidget` renders at any step. At each checkpoint it prints an `E2E_SHOT ` marker and holds the frame; the runner streams `flutter drive` output and captures the device with `xcrun simctl io ... screenshot` or `adb exec-out screencap`, so screenshots work in debug, profile and release builds. Shots and `flutter-drive.log` land in `$T/e2e//shots/--/`. (On Android, `IntegrationTestWidgetsFlutterBinding.takeScreenshot` after `convertFlutterSurfaceToImage` captured only the first frame.) Before each run the script prepares the gitignored Firebase inputs the same way mobile CI does: `scripts/mobile-deployment/firebase-service-config.py` copies the tracked development plist on iOS, and Android gets the synthetic `google-services.json` CI writes. iOS builds run `pod install`, which can leave `ios/Podfile.lock` and `project.pbxproj` modified in the E2E checkout; do not commit those side effects. `flutter test -d test/...` does not run on the device: files outside `integration_test/` run on the host VM. Widget tests that resize `tester.view` also fail under the live binding, so on-device coverage belongs in `integration_test/`. ## Release-mode gray screen Release builds replace the debug red error box with a gray `ErrorWidget`. iOS simulators run debug builds only (Flutter refuses `--profile` and `--release`), so reproduce release-only rendering on the Android emulator with `mobile-e2e android --mode=profile` or `--mode=release`. The same `ErrorWidget` assertion reports the failing screen, and the screenshots show it. ## Web Playwright `web` and `web-e2e` set `BASE_URL=http://127.0.0.1:7803`, the local Supabase keys and `TUTURUUU_LOCAL_E2E_AUTH_BYPASS=1`, the same local-only opt-in CI web E2E uses. `local-e2e.ts` honors it only for the loopback `:7803`/`:8001` origins; without it the `/api/auth/dev-session` rate-limit reset returns 403 and most auth specs fail in `beforeEach`. `--install` installs the Playwright Chromium build first. Pass spec paths or Playwright flags after `--`. ## Gotchas * Browsers must open web at `http://localhost:7803`, not `127.0.0.1`: Next dev serves its dev resources (HMR, hydration) only to `localhost`, so a `127.0.0.1` page stays unhydrated and the login form remains disabled. The script uses `localhost` for `BASE_URL`/`NEXT_PUBLIC_WEB_APP_URL` and keeps `127.0.0.1` for mobile, which Android cleartext requires. * `bootstrap()` installs the app's `FlutterError.onError`. The integration test restores the test binding's handler after `app.main()`; otherwise a framework error surfaces only as `A test overrode FlutterError.onError ...` and the real failure is hidden. * Mobile login ignores "Continue with email" while OTP availability resolves (a short grace period); the test retries the tap until the password stage renders. * Every wait in the flow captures `timeout-