### Install backend-recorder-launcher Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Install the package via npm. ```bash npm install @alwaysmeticulous/backend-recorder-launcher ``` -------------------------------- ### Install the shim Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md Install the @alwaysmeticulous/backend-recorder-workerd package for local development. ```bash npm install @alwaysmeticulous/backend-recorder-workerd ``` -------------------------------- ### .meticulousignore.twenty-front example Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md Example ignore file for a monorepo with slug 'twenty-front'. Excludes sibling apps, backend, and tooling while keeping shared libraries in coverage. ```plaintext # .meticulousignore.twenty-front # Exclude other frontend apps packages/twenty-website/** # Exclude backend code packages/twenty-server/** # Exclude tooling / config packages/twenty-docker/** packages/twenty-e2e-testing/** ``` -------------------------------- ### Start app with --require instrumentation.js Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Start the app with the --require flag so the recorder loads before application code. ```bash node --require ./instrumentation.js app.js ``` -------------------------------- ### Load and start Meticulous recorder in app entrypoint Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-loader/README.md Call loadAndStartRecorder with your recording token before initialising your app. Wrap in try/catch to log initialization failures. The example shows ReactDOM.render after the recorder starts. ```javascript import { loadAndStartRecorder } from "@alwaysmeticulous/recorder-loader"; async function startApp() { // Start the Meticulous recorder before you initialise your app. try { await loadAndStartRecorder({ recordingToken: "", }); } catch (err) { console.error(`Meticulous failed to initialise ${err}`); } // Initalise app after Meticulous' snippet, e.g: ReactDOM.render(component, document.getElementById("root")); } startApp(); ``` -------------------------------- ### Install the sidecar package Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md Install the sidecar package in a dedicated directory (its own repo or a folder in yours) before creating the Worker entry point and configuration. ```bash npm install @alwaysmeticulous/backend-recorder-sidecar-worker ``` -------------------------------- ### GitLab CI upload-container example Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md GitLab CI configuration for uploading a container image using the Meticulous CLI. Builds a Docker image with METICULOUS_BUILD baked in, then uploads it. Runs on merge request events and the default branch. ```yaml meticulous: stage: test image: docker:latest services: - docker:dind script: # METICULOUS_BUILD is baked into the image (Dockerfile: ARG/ENV METICULOUS_BUILD) so it # is present at build time and at replay runtime. - docker build --build-arg METICULOUS_BUILD=true -t myapp:$CI_COMMIT_SHA . - npx @alwaysmeticulous/cli ci upload-container --apiToken="$METICULOUS_API_TOKEN" --imageTag="myapp:$CI_COMMIT_SHA" --containerPort=3000 --commitSha="$CI_COMMIT_SHA" rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` -------------------------------- ### Run dev command through Meticulous CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md Run your dev command with the Meticulous CLI to start the recorder sidecar. If the recorder cannot start, the CLI warns and runs unrecorded. ```bash npx @alwaysmeticulous/cli record backend -- npx wrangler dev ``` -------------------------------- ### Install Meticulous CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/README.md Install the @alwaysmeticulous/cli package as a dev dependency using npm. ```bash npm install --save-dev @alwaysmeticulous/cli ``` -------------------------------- ### Case B: Critical SW Usage - Subsection Template Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/service-worker-compatibility.md Template for each critical usage site, including current behaviour, the required change, and a unified diff example. Use this for each site flagged by the reviewer. ```markdown ### **Current behaviour:** <1-2 sentences describing what the SW does and what the app will do during replay without a guard — e.g. "throws at module load because `navigator.serviceWorker.register("/sw.js")` is called unconditionally and `navigator.serviceWorker` is undefined during Meticulous replay", or "offline cache is empty during replay and the app spins on a `waiting-for-cache` state".> **Change:** feature-detect `"serviceWorker" in navigator` before the call, or gate it on `window.Meticulous?.isRunningAsTest` when the SW must still run in development. ``` ```diff // src/main.tsx import App from "./App"; +// Meticulous deletes `navigator.serviceWorker` during replay; feature-detect so we +// don't throw and so the app runs without offline caching during tests. -if (import.meta.env.PROD) { - navigator.serviceWorker.register("/sw.js"); +if (import.meta.env.PROD && "serviceWorker" in navigator) { + navigator.serviceWorker.register("/sw.js"); } ``` -------------------------------- ### GET /v1/health Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md Health check endpoint that returns `{ok: true, configured: boolean}`. `configured` is false when the recording token is unset, which is otherwise a silent misconfiguration. ```APIDOC ## [GET] /v1/health ### Description Health check endpoint that returns `{ok: true, configured: boolean}`. `configured` is false when the recording token is unset, which is otherwise a silent misconfiguration. ### Method GET ### Endpoint /v1/health ### Response #### Success Response (200) - **ok** (boolean) - Always true. - **configured** (boolean) - Whether the recording token is set. #### Response Example { "ok": true, "configured": true } ``` -------------------------------- ### GitLab CI upload-assets example Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md GitLab CI configuration for uploading assets using the Meticulous CLI. Runs on merge request events and the default branch. Requires METICULOUS_API_TOKEN and uses the provider's commit SHA variable. ```yaml meticulous: stage: test image: node:24 variables: METICULOUS_BUILD: "true" script: - npm ci - npm run build - npx @alwaysmeticulous/cli ci upload-assets --apiToken="$METICULOUS_API_TOKEN" --appDirectory="dist" --commitSha="$CI_COMMIT_SHA" rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` -------------------------------- ### Install @alwaysmeticulous/recorder-plugin with npm, yarn, or pnpm Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md Install the plugin as a dev dependency. Requires Node.js 20.19+ and ESM-only. ```shell npm install @alwaysmeticulous/recorder-plugin --save-dev # or with yarn yarn add -D @alwaysmeticulous/recorder-plugin # or with pnpm pnpm add -D @alwaysmeticulous/recorder-plugin ``` -------------------------------- ### ensureBrowser() Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/browser-installer/README.md Returns the path to the Chrome for Testing build pinned by the package's puppeteer-core version, downloading it on first use. Honors environment variables for custom Chrome paths, cache directories, and build IDs. ```APIDOC ## ensureBrowser() ### Description Returns the path to the Chrome for Testing build pinned by the package's puppeteer-core version, downloading it on first use. Honors environment variables for custom Chrome paths, cache directories, and build IDs. ### Method Function ### Endpoint ensureBrowser() ### Parameters #### Environment Variables - **PUPPETEER_EXECUTABLE_PATH** (string) - Optional - Use an already-installed Chrome instead of downloading. - **PUPPETEER_CACHE_DIR** (string) - Optional - Where to cache downloaded browsers (absolute path). - **METICULOUS_CHROME_BUILD_ID** (string) - Optional - Pin a different Chrome for Testing build id. ### Response #### Success Response - **path** (string) - The path to the Chrome for Testing build. ### Notes - Downloads honor `HTTP_PROXY` / `HTTPS_PROXY`. - Requires Node.js 22.12 or newer. ``` -------------------------------- ### Install @alwaysmeticulous/recorder-loader with npm, yarn, or pnpm Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-loader/README.md Install the recorder loader package using your preferred package manager. The commands are alternatives; choose one. ```shell npm install @alwaysmeticulous/recorder-loader --save ``` ```shell yarn add @alwaysmeticulous/recorder-loader ``` ```shell pnpm add @alwaysmeticulous/recorder-loader ``` -------------------------------- ### Example .meticulousignore patterns for single-package repo Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md Use these patterns in a repository-root .meticulousignore file to exclude non-frontend JavaScript/TypeScript areas (e.g., backend, data layer) from Meticulous coverage reports. Tailor the paths to the reviewer's Locations list. ```plaintext # Backend and data layer (not exercised by Meticulous UI replays) server/** prisma/** ``` -------------------------------- ### Rsbuild configuration using rspack plugin via tools.rspack Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md Alternative Rsbuild setup that passes the rspack plugin through tools.rspack, useful when composing with other rspack-only plugins. ```ts // rsbuild.config.ts import { defineConfig } from "@rsbuild/core"; import meticulous from "@alwaysmeticulous/recorder-plugin/rspack"; export default defineConfig({ tools: { rspack: { plugins: [meticulous({ recordingToken: "" })], }, }, }); ``` -------------------------------- ### Bind the sidecar service from your app Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md Add this service binding to every environment you want recorded so your app's Worker can reach the sidecar via env.METICULOUS_SIDECAR.fetch(). ```toml [[services]] binding = "METICULOUS_SIDECAR" service = "meticulous-recorder-sidecar" ``` -------------------------------- ### Case B - Needs-Guard Subsection Template Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/shared-worker-compatibility.md Template for each needs-guard site, including current behaviour, change description, and a unified diff example. The diff shows gating the SharedWorker construction on window.Meticulous?.isRunningAsTest and returning an alternative implementation. ```markdown ### **Current behaviour:** <1-2 sentences describing what the worker does and what the app will do during replay without a guard — e.g. "throws on module import because `new SharedWorker(...)` runs eagerly at module load".> **Change:** gate the construction on `window.Meticulous?.isRunningAsTest` and return an alternative implementation that does not require a worker. ` ` `diff // src/lib/presence.ts export function createPresenceClient() { + // During Meticulous replay `SharedWorker` is disabled, so fall back to a + // single-tab in-memory presence client (cross-tab sync is not meaningful + // inside a replay anyway). + if (typeof window !== "undefined" && window.Meticulous?.isRunningAsTest) { + return createInMemoryPresenceClient(); + } + const worker = new SharedWorker( new URL("./presence.worker.ts", import.meta.url), { type: "module" } ); return createPortClient(worker.port); } ` ` ` ``` -------------------------------- ### POST /v1/events Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md Endpoint that the shim reports to. It receives backend events for recording. ```APIDOC ## [POST] /v1/events ### Description Endpoint that the shim reports to. It receives backend events for recording. ### Method POST ### Endpoint /v1/events ``` -------------------------------- ### Step N: Service Worker Compatibility - Section Heading and Preamble Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/service-worker-compatibility.md Template for the section heading and preamble that explains Meticulous deletes navigator.serviceWorker during replay and lists files to modify. Use this as the starting point for the generated markdown section. ```markdown ## Step : Service Worker Compatibility Meticulous does not support Service Workers: during replay it deletes `navigator.serviceWorker` before any app code runs, because a Service Worker would intercept `fetch` calls and bypass Meticulous's network stubbing. There is no project setting to toggle this; the deletion always happens. Your app must therefore run correctly with no Service Worker present. The changes below ensure every `navigator.serviceWorker` access or registration either feature- detects `"serviceWorker" in navigator` or is gated on `window.Meticulous?.isRunningAsTest`. **Files to modify:** - ``` -------------------------------- ### BackendRecorderHandle split capture example Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/sdk-bundles-api/CHANGELOG.md Shows the split form of capture using isMeticulousReplaying, stubWithMeticulous, and recordWithMeticulous. The branch is unavoidable because the app keeps the invocation; isMeticulousReplaying() is the correct condition, not METICULOUS_BUILD or METICULOUS_BACKEND_RECORDER_MODE. recordWithMeticulous accepts a promise and leaves the caller's promise untouched. ```TypeScript function getUser(id: string) { if (handle.isMeticulousReplaying()) { return handle.stubWithMeticulous(`user_${id}`); } const user = crm.getUser(id); handle.recordWithMeticulous(`user_${id}`, user); return user; } ``` -------------------------------- ### Start local tunnel via CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/tunnel-client/README.md Use the CLI to start a secure reverse proxy tunnel to a locally hosted service on port 8080. Requires an API token from the Meticulous tunnels service. ```bash npx @alwaysmeticulous/cli start-local-tunnel -p 8080 --apiToken ``` -------------------------------- ### Deploy the sidecar with wrangler Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md Deploy the sidecar to your Cloudflare account after copying wrangler.template.toml and setting METICULOUS_RECORDING_TOKEN. ```bash npx wrangler deploy ``` -------------------------------- ### Apollo Client: Gate createPersistedQueryLink to production Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/persisted-graphql-queries.md Example diff for Apollo Client that wraps the persisted-query link in a production-only check. Use the same environment signal the customer already uses (e.g., NODE_ENV === "production"). ```diff import { ApolloClient, HttpLink, InMemoryCache, from } from "@apollo/client"; import { createPersistedQueryLink } from "@apollo/client/link/persisted-queries"; import { sha256 } from "crypto-hash"; const httpLink = new HttpLink({ uri: "/graphql" }); -const link = from([ - createPersistedQueryLink({ sha256 }), - httpLink, -]); +// Persisted queries send only a hash, which makes recorded sessions hard to debug and +// prevents per-operation network transformations. Enable them only in production. +const link = + process.env.NODE_ENV === "production" + ? from([createPersistedQueryLink({ sha256 }), httpLink]) + : httpLink; export const client = new ApolloClient({ link, cache: new InMemoryCache() }); ``` -------------------------------- ### redactUrl Examples Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/redaction/README.md Replaces hostname, path, query, hash, and userinfo in URLs. By default the hostname becomes 'redacted.com'; pass baseDomain to customize. The examples show default and custom baseDomain outputs. ```ts import { redactUrl } from "@alwaysmeticulous/redaction"; redactUrl("https://customer.example/private/path"); // => "https://redacted.com/redacted/redacted" redactUrl("https://customer.example/private/path", { baseDomain: "redacted.meticulous.ai", }); // => "https://redacted.meticulous.ai/redacted/redacted" ``` -------------------------------- ### POST /v1/flush Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md Upload whatever is buffered now, instead of waiting out the 5s alarm. Worth calling at the end of a CI run that recorded against a preview deployment, so the recording reaches Meticulous before the job exits. ```APIDOC ## [POST] /v1/flush ### Description Upload whatever is buffered now, instead of waiting out the 5s alarm. Worth calling at the end of a CI run that recorded against a preview deployment, so the recording reaches Meticulous before the job exits. ### Method POST ### Endpoint /v1/flush ``` -------------------------------- ### Worker entry point (src/index.ts) Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-sidecar-worker/README.md The entire Worker is defined by re-exporting the default handler and the MeticulousRecorderSession Durable Object from the sidecar package. ```ts export { default, MeticulousRecorderSession, } from "@alwaysmeticulous/backend-recorder-sidecar-worker"; ``` -------------------------------- ### asterixOut Example Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/redaction/README.md Redacts a string with asterisks, preserving length and whitespace to maintain layout for testing. The example shows the output for 'some sensitive text'. ```ts import { asterixOut } from "@alwaysmeticulous/redaction"; const redacted = asterixOut("some sensitive text"); // returns "**** ********* ****" ``` -------------------------------- ### redactString Example Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/redaction/README.md Redacts strings intelligently by recognizing common data formats like emails, reducing the risk of errors during replay. The example shows outputs for a plain string and an email address. ```ts import { redactString } from "@alwaysmeticulous/redaction"; const redacted = redactString("some sensitive text"); // returns "**** ********* ****" const redacted2 = redactString("test@example.com"); // returns "----@-------.com" // etc. ``` -------------------------------- ### run: | block for colon in command Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md Use a block scalar for any run command containing a colon followed by a space, as inline plain scalars are rejected. This example writes a YAML config line to .yarnrc.yml. ```yaml run: | echo 'nodeLinker: node-modules' > .yarnrc.yml ``` -------------------------------- ### Bitbucket Pipelines: Reset to PR source tip Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/common/CHANGELOG.md Required for Bitbucket Pipelines pull-request builds after Meticulous 2.290.3, which removed BITBUCKET_COMMIT auto-detection. Run this at the start of the pipeline step to avoid testing the ephemeral merge commit created by Bitbucket. ```bash git reset --hard "$BITBUCKET_COMMIT" ``` -------------------------------- ### Example Usage of Redaction Middleware Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/redaction/README.md Shows how to combine dropRequestHeader and transformJsonResponse to redact sensitive data from network requests and responses. The first transform redacts a 'sensitive' field using asterixOut, and the second recursively redacts all strings except those with path ending in 'uuid'. ```ts import { dropRequestHeader, transformJsonResponse, redactRecursively, asterixOut, } from "@alwaysmeticulous/redaction"; const middleware = [ dropRequestHeader("Authorization"), transformJsonResponse({ urlRegExp: /https:\/\/api\.example\.com\/.*/, transform: (data) => { return { ...data, ...(data.sensitive ? { sensitive: asterixOut(data.sensitive) } : {}), }; }, }), transformJsonResponse({ urlRegExp: /https:\/\/api\.example\.com\/sensitive.*/, transform: (data) => redactRecursively(data, { redactString: (str, path) => path[path.length - 1] === "uuid" ? str : asterixOut(str), }), }), ]; ``` -------------------------------- ### Bundle Clerk JS locally in CI pipeline Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md Add this step to the CI pipeline immediately before the production build step when Clerk is in use. It downloads and bundles Clerk's browser JS locally so replays do not depend on Clerk's CDN. Adjust the public directory (e.g., `static/clerk` for SvelteKit) and set the framework's public env var (e.g., `NEXT_PUBLIC_CLERK_JS_URL`) to `/clerk/clerk.browser.js` on the build step. ```text - name: Bundle Clerk JS locally run: | mkdir -p public/clerk CLERK_JS_MAJOR=$(node -e " const lockfile = require('fs').readFileSync('pnpm-lock.yaml', 'utf8'); const match = lockfile.match(/@clerk\/clerk-react@(\d+)/); console.log(match ? match[1] : '5'); ") echo "Packing @clerk/clerk-js@${CLERK_JS_MAJOR} dist bundle" npm pack @clerk/clerk-js@${CLERK_JS_MAJOR} --pack-destination /tmp > /dev/null tar -xzf /tmp/clerk-clerk-js-*.tgz -C /tmp cp /tmp/package/dist/*.js public/clerk/ ls -lh public/clerk/ - name: Build app run: pnpm build env: NEXT_PUBLIC_CLERK_JS_URL: /clerk/clerk.browser.js ``` -------------------------------- ### Auto-init with --require Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Use the auto-init entry point to initialize the recorder as a side effect; reads configuration from environment variables. ```bash node --require @alwaysmeticulous/backend-recorder-launcher/auto-init app.js ``` -------------------------------- ### auto-init entry point Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Initializes the backend recorder as a side effect without code changes. Reads configuration from environment variables. ```APIDOC ## auto-init entry point ### Description Initializes the backend recorder as a side effect without code changes. Reads configuration from environment variables. ### Method Module import ### Endpoint `@alwaysmeticulous/backend-recorder-launcher/auto-init` ### Parameters None (configuration via environment variables) ### Request Example ```bash node --require @alwaysmeticulous/backend-recorder-launcher/auto-init app.js ``` ### Response No return value. ``` -------------------------------- ### Onboard a repository with Meticulous CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/README.md Connect a repository to a Meticulous project and prepare a pull request with recorder and CI configuration. Requires prior connection to a Meticulous project. If not logged in, opens a browser to sign in; on remote machines, run 'npx @alwaysmeticulous/cli auth login --device' first. ```bash npx @alwaysmeticulous/cli onboard --project="/" ``` -------------------------------- ### Record a session with Meticulous CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/README.md Run the Meticulous CLI to record a user session, providing an API token. ```bash npx @alwaysmeticulous/cli record --apiToken="" ``` -------------------------------- ### Initialize backend recorder in instrumentation.js Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Create or update instrumentation.js (or .ts) at project root to initialize the recorder with a recording token from environment. ```js const { initBackendRecorder, } = require("@alwaysmeticulous/backend-recorder-launcher"); initBackendRecorder({ recordingToken: process.env.METICULOUS_RECORDING_TOKEN, }); ``` -------------------------------- ### NPM loader window global for backend recording Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/recorder-installation.md Sets the window global before calling tryLoadAndStartRecorder to inject the session-id header. The loader has no option for this, so the global must be set beforehand. ```ts // Backend recording: stamp X-Meticulous-Session-Id on same-origin requests so // backend spans correlate with this session. window.METICULOUS_INJECT_SESSION_ID_HEADER = true; await tryLoadAndStartRecorder({ recordingToken: "" }); ``` -------------------------------- ### Pin version in build config with METICULOUS_BUILD Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/false-positive-prevention.md For server-rendered values, pin the version in the build config when process.env.METICULOUS_BUILD === "true" so server and client bundles match. METICULOUS_BUILD=true is set only on the Meticulous build by the Set Up CI step. ```diff define: { - __APP_VERSION__: JSON.stringify(getGitVersion()), + // Pinned in the Meticulous build so base and head render identically. + __APP_VERSION__: JSON.stringify( + process.env.METICULOUS_BUILD === "true" ? "0.0.0-meticulous" : getGitVersion(), + ), }, ``` -------------------------------- ### Simulate a recorded session with Meticulous CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/README.md Simulate a recorded session on your local environment using the session ID and app URL. ```bash npx @alwaysmeticulous/cli simulate \ --apiToken="" \ --sessionId="" \ --appUrl="http://localhost:3000" ``` -------------------------------- ### Step N: Shared Worker Compatibility - Section Heading and Preamble Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/shared-worker-compatibility.md Template for the section heading and preamble that instructs the user to list files to modify. It explains that Meticulous disables SharedWorker during replay and requires handling the absence of window.SharedWorker. ```markdown ## Step : Shared Worker Compatibility Meticulous disables `SharedWorker` during replay so sessions are deterministic. Your app must handle `window.SharedWorker` being absent without crashing. The changes below ensure each construction site either has a feature-detected fallback or is gated on `window.Meticulous?.isRunningAsTest`. **Files to modify:** - ``` -------------------------------- ### initBackendRecorder(config) Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Initializes the backend recorder to intercept HTTP requests/responses in Node.js apps using OpenTelemetry and export spans to Meticulous. Accepts an optional BackendRecorderConfig object and returns a BackendRecorderHandle. ```APIDOC ## initBackendRecorder(config) ### Description Initializes the backend recorder to intercept HTTP requests/responses in Node.js apps using OpenTelemetry and export spans to Meticulous. Accepts an optional BackendRecorderConfig object and returns a BackendRecorderHandle. ### Method Function call ### Endpoint `initBackendRecorder(config)` ### Parameters #### Config Object (optional) - **enabled** (boolean) - Optional - Enable/disable the recorder (default: `true`) - **meticulousProjectName** (string) - Optional - The name of the Meticulous project - **recordingToken** (string) - Optional - Token used to authenticate span uploads - **exportMode** ("local" | "s3") - Optional - Where to export spans (default: `"local"`) - **localOutputDir** (string) - Optional - Directory for local exports - **flushIntervalMs** (number) - Optional - How often to flush spans (ms) - **spanRedactionHooks** ((value: string) => string[]) - Optional - Ordered record-time hooks that transform redactable span strings before upload ### Request Example ```js const { initBackendRecorder, } = require("@alwaysmeticulous/backend-recorder-launcher"); initBackendRecorder({ recordingToken: process.env.METICULOUS_RECORDING_TOKEN, }); ``` ### Response #### Success Response Returns a `BackendRecorderHandle` with a `stopRecording()` method. #### Response Example ```js const handle = await initBackendRecorder({ /* ... */ }); ``` ``` -------------------------------- ### grep for application source in logs-index Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/src/templates/CLAUDE.md Use this grep command to filter log entries by source in the logs-index file for a replay. ```bash grep 'source=application' logs-index/head-abc.txt ``` -------------------------------- ### getInitialProps guard for Meticulous replay (server and client) Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/replay-fetch-retry-compatibility.md Skips a retry-wrapped fetch in getInitialProps during Meticulous replay. Uses process.env.METICULOUS_BUILD on the server and window.Meticulous?.isRunningAsTest on the client, since the build var is not inlined client-side. ```diff Page.getInitialProps = async (ctx) => { + // On the server, gate on the Meticulous-only build var; on the client, use the + // recorder signal (process.env.METICULOUS_BUILD is not inlined client-side). + const isMeticulousReplay = ctx.req + ? process.env.METICULOUS_BUILD === "true" + : typeof window !== "undefined" && Boolean(window.Meticulous?.isRunningAsTest); + // Skip the failing-and-retried fetch under Meticulous; render with safe defaults. + if (isMeticulousReplay) { + return { items: [] }; + } + const items = await fetchWithRetry("/api/items"); return { items }; }; ``` -------------------------------- ### Use individual debug pipeline steps Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/README.md Shows how to use resolveDebugContext, downloadDebugData, and generateDebugWorkspace individually for more control. Requires a client, replayDiffId, workspaceDir, and projectRepoDir. ```typescript import { resolveDebugContext, downloadDebugData, generateDebugWorkspace, } from "@alwaysmeticulous/debug-workspace"; const debugContext = await resolveDebugContext({ client, replayDiffId }); await downloadDebugData({ client, debugContext, workspaceDir }); await generateDebugWorkspace({ client, debugContext, workspaceDir, projectRepoDir, }); ``` -------------------------------- ### Substitute placeholder in getDisplayVersion Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/false-positive-prevention.md For client-only displayed values, substitute a fixed placeholder at the single place the display string is derived. This works for all CI approaches, including Cloud Replay against preview URLs. ```ts // Meticulous diffs screenshots across builds, so show a fixed version under test. export const getDisplayVersion = (): string => window.Meticulous?.isRunningAsTest ? "0.0.0-meticulous" : APP_VERSION; ``` -------------------------------- ### grep for network stubs in events-index Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/src/templates/CLAUDE.md Use this grep command to find network stub events (pollyReplay) in the events-index file for a replay. ```bash grep 'kind=pollyReplay' events-index/head-abc.txt ``` -------------------------------- ### grep for specific API calls in events-index Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/src/templates/CLAUDE.md Use this grep command to find specific API calls (e.g., api/v9/users) in the events-index file for a replay. ```bash grep 'api/v9/users' events-index/head-abc.txt ``` -------------------------------- ### Wrap Postgres client with withMeticulousPostgres Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md Wrap your Postgres client to record queries. Returns the client unchanged and covers all clients in the isolate. ```ts import { withMeticulousPostgres } from "@alwaysmeticulous/backend-recorder-workerd"; const sql = withMeticulousPostgres( postgres(env.HYPERDRIVE.connectionString), ); ``` -------------------------------- ### Import Options type Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md Import the Options type from the recorder plugin package. ```TypeScript import type { Options } from "@alwaysmeticulous/recorder-plugin"; ``` -------------------------------- ### Apply withMeticulousPostgres to postgres instance Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/sdk-bundles-api/CHANGELOG.md Wrap the postgres.js client with the recorder's withMeticulousPostgres method when constructing it. Required for apps whose bundler inlines postgres, such as Vite SSR or Next.js/Turbopack, because the require-hook instrumentation cannot fire otherwise. Safe to apply at module-load time and a no-op when the recorder is disabled. ```typescript const handle = await initBackendRecorder(config); const sql = handle?.withMeticulousPostgres?.(postgres(connectionString)) ?? postgres(connectionString); ``` -------------------------------- ### EnabledContext Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md The context object passed to the `enabled` predicate function. Provides information about the current build environment. ```APIDOC ## EnabledContext ### Description The context object passed to the `enabled` predicate function. Provides information about the current build environment. ### Properties - **framework** ("vite" | "webpack" | "rspack") - The bundler framework being used. - **mode** (string) - Optional - Vite mode / webpack mode / NODE_ENV fallback. - **command** ("serve" | "build") - Optional - Vite-only command. - **isProduction** (boolean) - Whether the build is a production build. ``` -------------------------------- ### Set METICULOUS_SIDECAR_URL in .dev.vars Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md Configure the sidecar URL as a worker var/binding for standalone sidecar usage. Host environment variables are not visible inside workerd. ```plaintext METICULOUS_SIDECAR_URL=http://127.0.0.1:9670 ``` -------------------------------- ### Add meticulousCoverage Vite plugin Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/CHANGELOG.md Add the plugin to the build you upload for testing, not the one you deploy. The plugin marks each line of the server bundle for coverage reporting. ```ts import { meticulousCoverage } from "@alwaysmeticulous/backend-recorder-workerd/vite"; export default defineConfig({ plugins: [meticulousCoverage()] }); ``` -------------------------------- ### Next.js instrumentation hook Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md For Next.js, add the instrumentation hook in instrumentation.ts to initialize the recorder only in the Node.js runtime. ```ts export async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { const { initBackendRecorder } = await import("@alwaysmeticulous/backend-recorder-launcher"); await initBackendRecorder({ recordingToken: process.env.METICULOUS_RECORDING_TOKEN, }); } } ``` -------------------------------- ### Record a session with Meticulous CLI Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/README.md Record a new session by interacting with your application. The --apiToken flag is only required if the token is not stored in ~/.meticulous/config.json. ```bash npx @alwaysmeticulous/cli record \ --apiToken="" \ --appUrl="http://localhost:3000" ``` -------------------------------- ### Guard update decision with window.Meticulous?.isRunningAsTest Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/false-positive-prevention.md Return 'no update' when running as a Meticulous test to prevent update banners or forced reloads. The recorded /api/version response won't match the current build's version, so guard the decision, not just the fetch. ```diff export const updateAvailableAtom = atom((get) => { + // Meticulous replays the recorded /api/version response, which won't match this build's version. + if (window.Meticulous?.isRunningAsTest) { + return false; + } const deployed = get(deployedVersionAtom); if (!CURRENT_VERSION || !deployed) { return false; } return deployed !== CURRENT_VERSION; }); ``` -------------------------------- ### grep for screenshots in events-index Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/src/templates/CLAUDE.md Use this grep command to find screenshot events in the events-index file for a replay. The file is one line per timeline event with kind and key data fields. ```bash grep 'kind=screenshot' events-index/head-abc.txt ``` -------------------------------- ### grep for errors in logs-index Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/src/templates/CLAUDE.md Use this grep command to search for error keywords in the logs-index file for a replay. ```bash grep -i 'error' logs-index/head-abc.txt ``` -------------------------------- ### CLI flag (GitLab, CircleCI, etc.) — never emit this Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/ci-setup.md This bash snippet shows the CLI flag form of the rewrite for GitLab, CircleCI, and other providers. It is explicitly forbidden to include in any generated workflow because Meticulous already defaults to the SPA fallback. Do not emit this flag under any circumstances. ```bash # CLI flag (GitLab, CircleCI, etc.) — never emit this --rewrites='[{"source":"/(.*)", "destination":"/index.html"}]' ``` -------------------------------- ### Rsbuild configuration with dedicated entry Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md Preferred Rsbuild entry that hooks into Rsbuild's modifyHTML API to inject the recorder script. ```ts // rsbuild.config.ts import { defineConfig } from "@rsbuild/core"; import meticulous from "@alwaysmeticulous/recorder-plugin/rsbuild"; export default defineConfig({ plugins: [meticulous({ recordingToken: "" })], }); ``` -------------------------------- ### Replace placeholder script in index.html Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md HTML placeholder script tag that the plugin replaces when inject is set to 'replace'. ```HTML ``` -------------------------------- ### Case A: Findings - No Customer Change Needed Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/service-worker-compatibility.md Template for the findings section when the reviewer over-classified and no customer change is needed. Includes a table of existing guards and a replacement for the 'Files to modify' list. ```markdown ### Findings The Service Worker usage in this codebase is **not critical for replay**: `navigator.serviceWorker` access is already feature-detected / production-gated and the app renders correctly without a Service Worker. Meticulous deletes `navigator.serviceWorker` during replay and the existing fallback branch runs automatically. No application code changes are required. | File | Line | Guard | |------|------|-------| | | | <1-line description of the existing feature detection or env gate> | ``` ```markdown **Files to modify:** None — existing feature detection / production gates are sufficient. ``` -------------------------------- ### Enable nodejs_als compatibility flag Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md Add the nodejs_als compatibility flag to wrangler.toml for local development. ```toml compatibility_flags = ["nodejs_als"] ``` -------------------------------- ### Run full debug pipeline with runDebugPipeline Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/README.md Imports and invokes runDebugPipeline from @alwaysmeticulous/debug-workspace. Requires a client, replayDiffId, screenshot, and callbacks for worktree creation and workspace presentation. ```typescript import { runDebugPipeline } from "@alwaysmeticulous/debug-workspace"; await runDebugPipeline({ client, replayDiffId: "some-replay-diff-id", screenshot: "screenshot-after-event-00042.png", createWorktree: (ctx, workspaceDir) => createProjectWorktree({ debugContext: ctx, workspaceDir }), onWorkspaceReady: (workspaceDir, projectRepoDir) => presentWorkspace({ workspaceDir, projectRepoDir }), }); ``` -------------------------------- ### Verify createSeededRandom copies are identical Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/__docs__/replay-determinism.md Run this shell command to confirm the two copies of createSeededRandom (in the Node recorder and the workerd shim) are byte-for-byte identical. The command extracts the function definition from each file using sed and compares them with diff. ```sh diff <(sed -n '/^export const createSeededRandom/,/^};/p' packages/backend-recorder-js/src/replay/virtual-random.ts) \ <(sed -n '/^export const createSeededRandom/,/^};/p' public_packages/backend-recorder-workerd/src/virtual-random.ts) ``` -------------------------------- ### Graceful shutdown with stopRecording Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-launcher/README.md Call stopRecording() before process exit to flush pending spans. The handle is returned by initBackendRecorder. ```js const handle = await initBackendRecorder({ /* ... */ }); process.on("SIGTERM", async () => { await handle?.stopRecording(); process.exit(0); }); ``` -------------------------------- ### grep for specific virtual time in logs-index Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/debug-workspace/src/templates/CLAUDE.md Use this grep command to find events at a specific virtual time (e.g., vt=7648) in the logs-index file for a replay. ```bash grep 'vt=7648' logs-index/head-abc.txt ``` -------------------------------- ### Server-side getServerSideProps guard for Meticulous replay Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/cli/src/commands/onboard/templates/vendored/agents/replay-fetch-retry-compatibility.md Short-circuits a server-side fetch in getServerSideProps during a Meticulous replay to avoid retry storms. Uses process.env.METICULOUS_BUILD === "true" as the detection signal, which is only set in Meticulous build artifacts and never in production. ```diff export const getServerSideProps = async (ctx) => { + // During a Meticulous replay this server-side fetch has no recorded stub and would + // fail and be retried repeatedly. METICULOUS_BUILD is set only in the Meticulous + // build artifacts (never in production), so skip the fetch and render safe defaults. + if (process.env.METICULOUS_BUILD === "true") { + return { props: { items: [] } }; + } + const items = await fetchWithRetry("/api/items"); return { props: { items } }; }; ``` -------------------------------- ### Configure inject replace mode Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md Configure the plugin to replace a placeholder script tag instead of auto-injecting. Falls back to auto injection with a build warning if the placeholder is not found. ```TypeScript meticulous({ recordingToken: "", inject: "replace", // placeholderAttribute defaults to "data-meticulous" }); ``` -------------------------------- ### Set meticulous-passthrough header to keep a fetch call live during replay Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md During replay, outgoing fetch calls are answered from the recording unless the request sets the `meticulous-passthrough` header to `true`, which lets the call reach the real service. Use this for calls that must stay live during a replay. ```typescript await fetch(url, { headers: { "meticulous-passthrough": "true" } }); ``` -------------------------------- ### Wrap ES-module Worker handler with withMeticulous Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/backend-recorder-workerd/README.md Wrap your Worker's fetch handler with withMeticulous to enable recording. The wrapper is a pass-through if no sidecar is configured. ```ts import { withMeticulous } from "@alwaysmeticulous/backend-recorder-workerd"; export default withMeticulous({ async fetch(request, env, ctx) { // your app }, }); ``` -------------------------------- ### meticulous(options) Source: https://github.com/alwaysmeticulous/meticulous-sdk/blob/main/packages/recorder-plugin/README.md Configures the Meticulous recorder plugin for your bundler. Accepts an options object to control when and how the recording script is injected. ```APIDOC ## meticulous(options) ### Description Configures the Meticulous recorder plugin for your bundler. Accepts an options object to control when and how the recording script is injected. ### Parameters #### Options Object - **recordingToken** (string) - Required - Your Meticulous recording token. Emitted as `data-recording-token` on the injected `