[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7B31E3SRD2C2J1CTJ57153E":3,"skill-same:01M7B31E3SRD2C2J1CTJ57153E":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7B31E3SRD2C2J1CTJ57153E","hamster-sync-integration-testing",null,"Deterministic integration testing patterns for `apps\u002Fsync`. Use this whenever you need to add, modify, review, or debug sync integration tests, especially if the work involves MSW mocks, Linear webhooks, queue consumers, reconciliation, connection lifecycle HTTP flows, or bidirectional task\u002Fbrief\u002Finitiative sync. This skill should win over generic testing advice whenever the user mentions `apps\u002Fsync`, `.integration.spec.ts`, Linear mocking, webhook tests, or sync runtime canaries.","gethamster\u002Fskills","gethamster","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F215697643?v=4","01M7B2R6PGB3SDZZ71E0WE2S74","Hamster","01M7B2R6Q21HWJRXZZWB78BNDG",4,"MIT","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002F.experimental\u002Fhamster-sync-integration-testing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: hamster-sync-integration-testing\ndescription: \"Deterministic integration testing patterns for `apps\u002Fsync`. Use this whenever you need to add, modify, review, or debug sync integration tests, especially if the work involves MSW mocks, Linear webhooks, queue consumers, reconciliation, connection lifecycle HTTP flows, or bidirectional task\u002Fbrief\u002Finitiative sync. This skill should win over generic testing advice whenever the user mentions `apps\u002Fsync`, `.integration.spec.ts`, Linear mocking, webhook tests, or sync runtime canaries.\"\nversion: \"1.0.0\"\n---\n\n# Hamster Sync Integration Testing\n\n## Overview\n\n`apps\u002Fsync` integration tests are **not** generic NestJS integration tests. The established repo pattern is:\n\n- use **real Redis + real local Supabase**\n- boot a **real `SyncEngineModule` test app**\n- replace BullMQ workers with **UUID-suffixed test queues**\n- mock **Linear only** with MSW\n- drain queue jobs **deterministically inside the test** instead of relying on live workers\n\nThis skill exists to keep new sync integration tests aligned with that architecture.\n\n## Use This Skill When\n\n- Adding or editing `apps\u002Fsync\u002Fsrc\u002F**\u002F*.integration.spec.ts`\n- Writing tests for Linear webhook ingress, inbound sync, outbound sync, reconciliation, or connection lifecycle flows\n- Adding MSW handlers or Linear GraphQL overrides for sync tests\n- Debugging a flaky or incomplete sync integration test\n- Choosing the right sync test harness or spec family for a runtime change\n\n## Core Rules\n\n1. **Keep the boundary honest**\n\n- Integration tests trust DB contracts from `apps\u002Fweb` and focus on the sync runtime: controller -> queue -> consumer -> orchestrator -> DB state.\n- Do not replace Supabase or Redis with mocks in sync integration specs.\n- If the behavior under test depends on RLS, triggers, outbox RPCs, or DB constraints, inspect the matching `apps\u002Fweb\u002Ftest\u002Fdatabase\u002F**` or pgTAP files instead of re-testing the same contract indirectly.\n\n2. **Mock only Linear**\n\n- Use `setupMswTestServer()` from `test\u002Fmsw\u002Fserver.ts`.\n- Default mode is `strict-linear`: unexpected Linear calls fail, local traffic is allowed through.\n- Add shared handlers to `linearBaseHandlers` only when the operation is broadly reused. Use `testServer.use(...)` for one-off behavior.\n\n3. **Use the right harness** (see Quick Reference table below)\n\n- `createInboundAppHarness()` for webhook + inbound queue tests\n- `createOutboxHarness()` for outbound event and provider mutation tests (disables background polling automatically)\n- `createSyncAppHarness()` for controller, reconciliation, and general multi-queue flows\n\n4. **Process queues manually**\n\n- Use `processWebhookAndInboundJobs`, `processOutboundJobs`, or `processReconciliationAndInboundJobs`.\n- Do not rely on background BullMQ workers starting inside the tests.\n\n5. **Preserve deterministic cleanup**\n\n- Use `runIntegrationSpecAfterEach(...)` in full-runtime\u002FMSW specs so cleanup failures do not hide MSW unhandled-request failures.\n- Focused ingress or worker specs may use bespoke cleanup instead when they do not boot the shared runtime harness.\n- Never reuse a BullMQ queue across tests.\n\n6. **Assert runtime side effects, not only HTTP status**\n\n- Check domain rows (`tasks`, `brief`, `initiatives`)\n- Check `sync_entity_mappings`\n- Check `sync_logs`\n- Check `sync_outbound_events` when relevant\n\n## Quick Reference\n\n| Runtime area changed | Start from | Harness \u002F helpers |\n| --- | --- | --- |\n| `webhooks\u002Flinear-webhook.controller.ts` | `webhooks\u002Flinear-webhook.controller.integration.spec.ts` | focused test module + `createTestQueue`, `cleanupQueue` |\n| `queues\u002Fwebhook.consumer.ts`, `queues\u002Finbound-sync.consumer.ts` | `integration\u002Fbidirectional-*.integration.spec.ts` | `createInboundAppHarness`, `postLinearWebhook`, `setWebhookSecret`, `processWebhookAndInboundJobs` |\n| `queues\u002Foutbound-sync.consumer.ts`, `services\u002Foutbox-worker.service.ts` | `integration\u002Foutbound-operational.integration.spec.ts` or outbound sections in `bidirectional-*.integration.spec.ts` | `createOutboxHarness`, `clearOutboundEvents`, `insertOutboundEvent`, `processOutboundJobs` |\n| Outbox claiming, lease handling, dedupe, job-ID generation | `services\u002Foutbound-event-worker.integration.spec.ts` or `services\u002Foutbox-worker.integration.spec.ts` | focused worker\u002Fservice setup, direct service invocation, queue assertions |\n| `queues\u002Freconciliation.consumer.ts` | `integration\u002Freconciliation-operational.integration.spec.ts` | `createSyncAppHarness`, `createHeaders`, `processReconciliationAndInboundJobs` |\n| `controllers\u002Fsync-connections.controller.ts` | `controllers\u002Fsync-connections.controller.integration.spec.ts` | `createSyncAppHarness({ useTestAuthGuard: true, useValidationPipe: true })`, `request(...)`, queue assertions |\n| `adapters\u002Flinear\u002F*` | `providers\u002Flinear-provider.integration.spec.ts` or adapter-specific integration specs | direct adapter tests + `testServer.use(...)` overrides |\n| Document polling \u002F retry \u002F user mapping refresh \u002F retention cleanup | matching `queues\u002F*.integration.spec.ts` | `createSyncAppHarness` and the specific queue under test |\n| Orchestration of task \u002F brief \u002F initiative entities | relevant `bidirectional-*.integration.spec.ts` | `createInboundAppHarness` or `createOutboxHarness` depending on direction |\n\n## Canonical Source Files\n\nAll paths in this section are relative to `apps\u002Fsync\u002F`. Read these before editing tests:\n\n| File | What to look for |\n| --- | --- |\n| `apps\u002Fsync\u002FTESTING.md` | Authoritative test guide — prerequisites, architecture, MSW harness, fixtures, troubleshooting |\n| `test\u002Fhelpers\u002Fbidirectional-integration-helpers.ts` | All harness factories, job-processing helpers, actor management, cleanup, auth headers |\n| `test\u002Fhelpers\u002Fsupabase-helpers.ts` | Seed functions, query helpers, outbox management, admin client factory |\n| `test\u002Fhelpers\u002Fbullmq-helpers.ts` | Queue creation with UUID suffix, job completion waiting, cleanup |\n| `test\u002Fmsw\u002Fserver.ts` | MSW server factory with `strict-linear` mode |\n| `test\u002Fmsw\u002Flinear-handlers.ts` | Base handlers for all Linear operations, override factories, error fixtures |\n| `test\u002Ffixtures\u002Flinear-responses.ts` | Factory functions for Linear response shapes, webhook payloads, `signLinearWebhook` |\n\nRepresentative specs (read the one closest to your change before writing new tests):\n\n- `integration\u002Fbidirectional-task-sync.integration.spec.ts`\n- `integration\u002Fbidirectional-brief-sync.integration.spec.ts`\n- `integration\u002Fbidirectional-initiative-sync.integration.spec.ts`\n- `integration\u002Foutbound-operational.integration.spec.ts`\n- `integration\u002Freconciliation-operational.integration.spec.ts`\n- `controllers\u002Fsync-connections.controller.integration.spec.ts`\n- `webhooks\u002Flinear-webhook.controller.integration.spec.ts`\n- `services\u002Foutbound-event-worker.integration.spec.ts`\n- `services\u002Foutbox-worker.integration.spec.ts`\n- `msw-interception.integration.spec.ts`\n\nRelated DB contract tests to consult when the runtime change depends on DB behavior:\n\n- `apps\u002Fweb\u002Ftest\u002Fdatabase\u002F**`\n- `apps\u002Fweb\u002Fsupabase\u002Ftests\u002Fdatabase\u002F**`\n\n## Test Selection Workflow\n\n1. **Find the matching row** in the Quick Reference table above.\n2. **Clone the nearest existing test shape** — do not invent a fresh test harness if the target entity already has a matching bidirectional or operational spec.\n3. **Choose the narrowest seam** that proves the behavior:\n\n- Need webhook ingress + HMAC + queue enqueue? test the controller.\n- Need provider -> local convergence? use inbound webhook + inbound queue.\n- Need local -> provider mutation? seed outbox state and drive outbound processing.\n- Need resync \u002F page walking behavior? use reconciliation HTTP flow.\n- Need exact GraphQL variable shape? test the adapter directly or capture variables via MSW in an outbound canary.\n\n## New Test Skeleton\n\nUse this as the starting template for a new bidirectional integration spec.\n\n```typescript\nimport { HttpResponse } from 'msw';\n\nimport {\n  createLinearIssue, \u002F\u002F or createLinearProject, createLinearInitiative\n  createLinearWebhookPayload,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Ffixtures\u002Flinear-responses';\nimport {\n  TEST_WEBHOOK_SECRET,\n  type TestActor,\n  createActor,\n  createInboundAppHarness,\n  linearProviderConfig,\n  postLinearWebhook,\n  processWebhookAndInboundJobs,\n  runIntegrationSpecAfterEach,\n  setWebhookSecret,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fhelpers\u002Fbidirectional-integration-helpers';\nimport {\n  createTestSupabaseAdmin,\n  querySyncLogs,\n  seedSyncConnection,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fhelpers\u002Fsupabase-helpers';\nimport {\n  createLinearQueryOverride,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fmsw\u002Flinear-handlers';\nimport { setupMswTestServer, testServer } from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fmsw\u002Fserver';\n\nimport { randomUUID } from 'crypto';\n\n\u002F\u002F vi.hoisted runs before module loading — required because the sync engine\n\u002F\u002F calls getConnectionProviderCredentials at runtime to resolve both webhook\n\u002F\u002F secrets (inbound) and provider access tokens (outbound\u002Freconciliation).\nconst vaultCredentialsMock = vi.hoisted(() => vi.fn());\n\nvi.mock('@kit\u002Fsupabase\u002Fvault-connection-credentials', async () => {\n  const actual = await vi.importActual\u003C\n    typeof import('@kit\u002Fsupabase\u002Fvault-connection-credentials')\n  >('@kit\u002Fsupabase\u002Fvault-connection-credentials');\n\n  return {\n    ...actual,\n    getConnectionProviderCredentials: vaultCredentialsMock,\n  };\n});\n\nconst msw = setupMswTestServer();\nconst ACTOR_EMAIL_PREFIX = 'my-entity-sync'; \u002F\u002F keep unique across spec files\n\ndescribe('My entity sync (integration)', () => {\n  const supabase = createTestSupabaseAdmin();\n  const actorsForCleanup: TestActor[] = [];\n  const accountIdsForSyncCleanup = new Set\u003Cstring>();\n\n  beforeAll(msw.beforeAll);\n\n  beforeEach(() => {\n    vi.stubEnv('SYNC_ENGINE_ENABLED', 'true');\n    vi.stubEnv('SYNC_OUTBOUND_ENABLED', 'true');\n    vi.stubEnv(\n      'NEXT_PUBLIC_SUPABASE_URL',\n      process.env.NEXT_PUBLIC_SUPABASE_URL ?? process.env.SUPABASE_URL ?? '',\n    );\n\n    \u002F\u002F For inbound specs use TEST_WEBHOOK_SECRET; for outbound\u002Freconciliation\n    \u002F\u002F specs use serializeStoredProviderCredentials({access_token: ...}).\n    vaultCredentialsMock.mockResolvedValue(TEST_WEBHOOK_SECRET);\n    msw.beforeEach();\n  });\n\n  afterEach(async () => {\n    vi.unstubAllEnvs();\n\n    await runIntegrationSpecAfterEach({\n      supabase,\n      actors: actorsForCleanup,\n      accountIdsForSyncCleanup,\n      msw,\n    });\n  });\n\n  afterAll(msw.afterAll);\n\n  it('Inbound: creates entity from webhook', async () => {\n    const actor = await createActor(ACTOR_EMAIL_PREFIX);\n    actorsForCleanup.push(actor);\n    accountIdsForSyncCleanup.add(actor.accountId);\n\n    const { connection } = await seedSyncConnection(\n      {\n        accountId: actor.accountId,\n        createdBy: actor.userId,\n        syncEnabled: true,\n        providerConfig: linearProviderConfig,\n      },\n      supabase,\n    );\n    const connectionId = String(connection.id);\n    await setWebhookSecret(connectionId);\n\n    const harness = await createInboundAppHarness();\n    try {\n      testServer.use(\n        createLinearQueryOverride('IssueById', async ({ variables }) => {\n          return HttpResponse.json({\n            data: {\n              issue: createLinearIssue({\n                id: (variables.id as string) ?? 'linear-issue-1',\n                title: 'Expected title',\n              }),\n            },\n          });\n        }),\n      );\n\n      const payload = createLinearWebhookPayload(\n        'Issue',\n        'create',\n        createLinearIssue({ id: 'linear-issue-1', title: 'Expected title' }),\n      );\n\n      const response = await postLinearWebhook({\n        app: harness.app,\n        accountId: actor.accountId,\n        connectionId,\n        payload,\n        deliveryId: `delivery-${randomUUID()}`,\n      });\n\n      expect(response.status).toBe(200);\n\n      await processWebhookAndInboundJobs({\n        moduleRef: harness.moduleRef,\n        webhookQueue: harness.webhookQueue,\n        inboundQueue: harness.inboundQueue,\n      });\n\n      \u002F\u002F Assert domain row\n      const { data: rows } = await supabase\n        .from('tasks')\n        .select('id,title,status')\n        .eq('account_id', actor.accountId)\n        .eq('title', 'Expected title')\n        .limit(1);\n\n      expect(rows).toHaveLength(1);\n\n      \u002F\u002F Assert mapping\n      const { data: mapping } = await supabase\n        .from('sync_entity_mappings')\n        .select('external_entity_type,external_id,hamster_entity_type,hamster_id')\n        .eq('sync_connection_id', connectionId)\n        .eq('external_id', 'linear-issue-1')\n        .single();\n\n      expect(mapping?.hamster_entity_type).toBe('task');\n      expect(mapping?.hamster_id).toBe(rows?.[0]?.id);\n\n      \u002F\u002F Assert sync log\n      const logs = await querySyncLogs(\n        connectionId,\n        { direction: 'inbound', entityType: 'issue' },\n        supabase,\n      );\n\n      expect(\n        logs.filter((l) => l.operation === 'create' && l.status === 'success'),\n      ).toHaveLength(1);\n    } finally {\n      await harness.cleanup();\n    }\n  });\n});\n```\n\n### Skeleton conventions\n\n- **Vault mock with `vi.hoisted`**: every bidirectional spec needs this. For outbound\u002Freconciliation specs, mock with `serializeStoredProviderCredentials({access_token: ...})` instead of `TEST_WEBHOOK_SECRET`.\n- **`linearProviderConfig`**: canonical Linear config from `bidirectional-integration-helpers.ts`. Use it so status mapping, team ID, and workspace config match what MSW base handlers expect.\n- **Actor tracking**: push every actor to `actorsForCleanup` and add the account ID to `accountIdsForSyncCleanup` immediately after creation.\n- **`try \u002F finally` around harness**: always clean up even if the test throws — leaked Redis connections cause \"Connection is closed\" errors in subsequent tests.\n- **`String(connection.id)`**: connection IDs from Supabase are typed `string | number`. Cast once at the top.\n\n## Full-runtime harnesses vs focused worker specs\n\n- **Full-runtime sync specs** boot `SyncEngineModule`, use real Supabase + Redis, and often use MSW at the Linear boundary. These are the `bidirectional-*.integration.spec.ts`, `outbound-operational`, `reconciliation-operational`, and `sync-connections.controller` specs.\n- **Focused worker\u002Fservice integration specs** exercise one worker or service with real queue\u002Fstorage seams but without the full shared app harness. These are `outbound-event-worker.integration.spec.ts`, `outbox-worker.integration.spec.ts`, etc.\n\nUse the focused specs when the behavior under test is primarily about outbox claiming, lease handling, dedupe, or deterministic job construction. Do not force those cases into the larger operational canary shape.\n\n## Loop suppression and sync markers\n\nThis repo uses `sync_entity_mappings.last_sync_origin` and `last_sync_applied_at` to suppress immediate echo loops. When testing follow-up inbound or outbound behavior:\n\n- prefer directly nulling or backdating those fields in test setup\n- avoid `sleep` or arbitrary timeouts to wait out the suppression window\n\n```typescript\n\u002F\u002F Deactivate suppression for a follow-up inbound update test\nawait supabase\n  .from('sync_entity_mappings')\n  .update({ last_sync_origin: null, last_sync_applied_at: null })\n  .eq('sync_connection_id', connectionId)\n  .eq('external_id', 'linear-issue-1');\n```\n\n`NULL` values in both fields bypass the check entirely.\n\n## MSW and Fixtures\n\nSee `apps\u002Fsync\u002FTESTING.md` for the full MSW setup reference, fixture factory list, and error helper catalog.\n\nKey decision rules:\n\n- Add to `linearBaseHandlers` when the same Linear operation will be used across several tests.\n- Use `createLinearQueryOverride` or `createLinearMutationOverride` when the behavior is specific to one test.\n- Base handlers intentionally validate minimal required inputs (e.g. `IssueCreate` rejects missing `title` or `teamId`). Do not weaken them to make a test pass — override the operation instead.\n- Service-level integration tests use MSW. Lower-level adapter or service unit specs use direct `vi.stubGlobal('fetch', ...)`. Default to MSW + harness for sync integration tests.\n\n## Assertions That Matter\n\nPrefer these repo-native assertions over shallow status checks:\n\n- domain row updated in the correct table\n- mapping row exists and points to the expected `hamster_id` \u002F `external_id`\n- `sync_logs` contains the expected `direction`, `entity_type`, `operation`, and `status`\n- `sync_outbound_events.processed_at` changed when testing outbound completion\n- relevant queue received the right job name when testing HTTP flows\n\nFor initiative-related sync, remember that `initiative_briefs` is the canonical relationship set. When a change affects initiative\u002Fproject linkage, assert the canonical link rows instead of treating `brief.initiative_id` as the primary contract.\n\n## Anti-Patterns\n\n- Do **not** mock Supabase or Redis in sync integration tests.\n- Do **not** put new sync integration tests outside `apps\u002Fsync\u002Fsrc\u002F**\u002F*.integration.spec.ts`.\n- Do **not** use arbitrary sleeps for queue or suppression timing.\n- Do **not** reuse a queue after cleanup; create fresh queues in `beforeEach`.\n- Do **not** bypass unexpected Linear requests with `'bypass'` unless the test explicitly needs it.\n- Do **not** assert only the local entity row when mappings or sync logs are the real contract.\n- Do **not** forget `clearOutboundEvents(...)` before asserting update\u002Fdelete outbox events for an entity that was just inserted.\n- Do **not** pass `accountId` where a real auth user ID is required (for example `initiatives.owner_id` references `auth.users.id`).\n- Do **not** forget `vi.unstubAllEnvs()` in afterEach — env stubs leak across tests without it.\n- Do **not** skip the vault credentials mock — the sync engine calls `getConnectionProviderCredentials` to resolve both webhook secrets and provider tokens.\n- Do **not** forget `try \u002F finally` around harness usage — leaked Redis connections cause \"Connection is closed\" errors in subsequent tests.\n\n## Verification\n\nRun the smallest useful test first:\n\n```bash\npnpm --filter sync exec vitest run --config vitest.config.integration.ts \\\n  apps\u002Fsync\u002Fsrc\u002Fmodules\u002Fsync-engine\u002F\u003Cpath-to-spec>.integration.spec.ts\n```\n\nThen run the full integration suite when the change affects shared helpers, MSW setup, queue wiring, or multiple spec families:\n\n```bash\npnpm --filter sync test:integration\n```\n\nIf runtime code changed alongside tests, also run:\n\n```bash\npnpm --filter sync typecheck\n```\n\nIf the change touches shared helpers, queue wiring, or sync runtime code beyond a narrow test-only edit, also run:\n\n```bash\npnpm --filter sync build\n```\n","# Hamster Sync Integration Testing\n\n## Overview\n\n`apps\u002Fsync` integration tests are **not** generic NestJS integration tests. The established repo pattern is:\n\n- use **real Redis + real local Supabase**\n- boot a **real `SyncEngineModule` test app**\n- replace BullMQ workers with **UUID-suffixed test queues**\n- mock **Linear only** with MSW\n- drain queue jobs **deterministically inside the test** instead of relying on live workers\n\nThis skill exists to keep new sync integration tests aligned with that architecture.\n\n## Use This Skill When\n\n- Adding or editing `apps\u002Fsync\u002Fsrc\u002F**\u002F*.integration.spec.ts`\n- Writing tests for Linear webhook ingress, inbound sync, outbound sync, reconciliation, or connection lifecycle flows\n- Adding MSW handlers or Linear GraphQL overrides for sync tests\n- Debugging a flaky or incomplete sync integration test\n- Choosing the right sync test harness or spec family for a runtime change\n\n## Core Rules\n\n1. **Keep the boundary honest**\n\n- Integration tests trust DB contracts from `apps\u002Fweb` and focus on the sync runtime: controller -> queue -> consumer -> orchestrator -> DB state.\n- Do not replace Supabase or Redis with mocks in sync integration specs.\n- If the behavior under test depends on RLS, triggers, outbox RPCs, or DB constraints, inspect the matching `apps\u002Fweb\u002Ftest\u002Fdatabase\u002F**` or pgTAP files instead of re-testing the same contract indirectly.\n\n2. **Mock only Linear**\n\n- Use `setupMswTestServer()` from `test\u002Fmsw\u002Fserver.ts`.\n- Default mode is `strict-linear`: unexpected Linear calls fail, local traffic is allowed through.\n- Add shared handlers to `linearBaseHandlers` only when the operation is broadly reused. Use `testServer.use(...)` for one-off behavior.\n\n3. **Use the right harness** (see Quick Reference table below)\n\n- `createInboundAppHarness()` for webhook + inbound queue tests\n- `createOutboxHarness()` for outbound event and provider mutation tests (disables background polling automatically)\n- `createSyncAppHarness()` for controller, reconciliation, and general multi-queue flows\n\n4. **Process queues manually**\n\n- Use `processWebhookAndInboundJobs`, `processOutboundJobs`, or `processReconciliationAndInboundJobs`.\n- Do not rely on background BullMQ workers starting inside the tests.\n\n5. **Preserve deterministic cleanup**\n\n- Use `runIntegrationSpecAfterEach(...)` in full-runtime\u002FMSW specs so cleanup failures do not hide MSW unhandled-request failures.\n- Focused ingress or worker specs may use bespoke cleanup instead when they do not boot the shared runtime harness.\n- Never reuse a BullMQ queue across tests.\n\n6. **Assert runtime side effects, not only HTTP status**\n\n- Check domain rows (`tasks`, `brief`, `initiatives`)\n- Check `sync_entity_mappings`\n- Check `sync_logs`\n- Check `sync_outbound_events` when relevant\n\n## Quick Reference\n\n| Runtime area changed | Start from | Harness \u002F helpers |\n| --- | --- | --- |\n| `webhooks\u002Flinear-webhook.controller.ts` | `webhooks\u002Flinear-webhook.controller.integration.spec.ts` | focused test module + `createTestQueue`, `cleanupQueue` |\n| `queues\u002Fwebhook.consumer.ts`, `queues\u002Finbound-sync.consumer.ts` | `integration\u002Fbidirectional-*.integration.spec.ts` | `createInboundAppHarness`, `postLinearWebhook`, `setWebhookSecret`, `processWebhookAndInboundJobs` |\n| `queues\u002Foutbound-sync.consumer.ts`, `services\u002Foutbox-worker.service.ts` | `integration\u002Foutbound-operational.integration.spec.ts` or outbound sections in `bidirectional-*.integration.spec.ts` | `createOutboxHarness`, `clearOutboundEvents`, `insertOutboundEvent`, `processOutboundJobs` |\n| Outbox claiming, lease handling, dedupe, job-ID generation | `services\u002Foutbound-event-worker.integration.spec.ts` or `services\u002Foutbox-worker.integration.spec.ts` | focused worker\u002Fservice setup, direct service invocation, queue assertions |\n| `queues\u002Freconciliation.consumer.ts` | `integration\u002Freconciliation-operational.integration.spec.ts` | `createSyncAppHarness`, `createHeaders`, `processReconciliationAndInboundJobs` |\n| `controllers\u002Fsync-connections.controller.ts` | `controllers\u002Fsync-connections.controller.integration.spec.ts` | `createSyncAppHarness({ useTestAuthGuard: true, useValidationPipe: true })`, `request(...)`, queue assertions |\n| `adapters\u002Flinear\u002F*` | `providers\u002Flinear-provider.integration.spec.ts` or adapter-specific integration specs | direct adapter tests + `testServer.use(...)` overrides |\n| Document polling \u002F retry \u002F user mapping refresh \u002F retention cleanup | matching `queues\u002F*.integration.spec.ts` | `createSyncAppHarness` and the specific queue under test |\n| Orchestration of task \u002F brief \u002F initiative entities | relevant `bidirectional-*.integration.spec.ts` | `createInboundAppHarness` or `createOutboxHarness` depending on direction |\n\n## Canonical Source Files\n\nAll paths in this section are relative to `apps\u002Fsync\u002F`. Read these before editing tests:\n\n| File | What to look for |\n| --- | --- |\n| `apps\u002Fsync\u002FTESTING.md` | Authoritative test guide — prerequisites, architecture, MSW harness, fixtures, troubleshooting |\n| `test\u002Fhelpers\u002Fbidirectional-integration-helpers.ts` | All harness factories, job-processing helpers, actor management, cleanup, auth headers |\n| `test\u002Fhelpers\u002Fsupabase-helpers.ts` | Seed functions, query helpers, outbox management, admin client factory |\n| `test\u002Fhelpers\u002Fbullmq-helpers.ts` | Queue creation with UUID suffix, job completion waiting, cleanup |\n| `test\u002Fmsw\u002Fserver.ts` | MSW server factory with `strict-linear` mode |\n| `test\u002Fmsw\u002Flinear-handlers.ts` | Base handlers for all Linear operations, override factories, error fixtures |\n| `test\u002Ffixtures\u002Flinear-responses.ts` | Factory functions for Linear response shapes, webhook payloads, `signLinearWebhook` |\n\nRepresentative specs (read the one closest to your change before writing new tests):\n\n- `integration\u002Fbidirectional-task-sync.integration.spec.ts`\n- `integration\u002Fbidirectional-brief-sync.integration.spec.ts`\n- `integration\u002Fbidirectional-initiative-sync.integration.spec.ts`\n- `integration\u002Foutbound-operational.integration.spec.ts`\n- `integration\u002Freconciliation-operational.integration.spec.ts`\n- `controllers\u002Fsync-connections.controller.integration.spec.ts`\n- `webhooks\u002Flinear-webhook.controller.integration.spec.ts`\n- `services\u002Foutbound-event-worker.integration.spec.ts`\n- `services\u002Foutbox-worker.integration.spec.ts`\n- `msw-interception.integration.spec.ts`\n\nRelated DB contract tests to consult when the runtime change depends on DB behavior:\n\n- `apps\u002Fweb\u002Ftest\u002Fdatabase\u002F**`\n- `apps\u002Fweb\u002Fsupabase\u002Ftests\u002Fdatabase\u002F**`\n\n## Test Selection Workflow\n\n1. **Find the matching row** in the Quick Reference table above.\n2. **Clone the nearest existing test shape** — do not invent a fresh test harness if the target entity already has a matching bidirectional or operational spec.\n3. **Choose the narrowest seam** that proves the behavior:\n\n- Need webhook ingress + HMAC + queue enqueue? test the controller.\n- Need provider -> local convergence? use inbound webhook + inbound queue.\n- Need local -> provider mutation? seed outbox state and drive outbound processing.\n- Need resync \u002F page walking behavior? use reconciliation HTTP flow.\n- Need exact GraphQL variable shape? test the adapter directly or capture variables via MSW in an outbound canary.\n\n## New Test Skeleton\n\nUse this as the starting template for a new bidirectional integration spec.\n\n```typescript\nimport { HttpResponse } from 'msw';\n\nimport {\n  createLinearIssue, \u002F\u002F or createLinearProject, createLinearInitiative\n  createLinearWebhookPayload,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Ffixtures\u002Flinear-responses';\nimport {\n  TEST_WEBHOOK_SECRET,\n  type TestActor,\n  createActor,\n  createInboundAppHarness,\n  linearProviderConfig,\n  postLinearWebhook,\n  processWebhookAndInboundJobs,\n  runIntegrationSpecAfterEach,\n  setWebhookSecret,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fhelpers\u002Fbidirectional-integration-helpers';\nimport {\n  createTestSupabaseAdmin,\n  querySyncLogs,\n  seedSyncConnection,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fhelpers\u002Fsupabase-helpers';\nimport {\n  createLinearQueryOverride,\n} from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fmsw\u002Flinear-handlers';\nimport { setupMswTestServer, testServer } from '..\u002F..\u002F..\u002F..\u002Ftest\u002Fmsw\u002Fserver';\n\nimport { randomUUID } from 'crypto';\n\n\u002F\u002F vi.hoisted runs before module loading — required because the sync engine\n\u002F\u002F calls getConnectionProviderCredentials at runtime to resolve both webhook\n\u002F\u002F secrets (inbound) and provider access tokens (outbound\u002Freconciliation).\nconst vaultCredentialsMock = vi.hoisted(() => vi.fn());\n\nvi.mock('@kit\u002Fsupabase\u002Fvault-connection-credentials', async () => {\n  const actual = await vi.importActual\u003C\n    typeof import('@kit\u002Fsupabase\u002Fvault-connection-credentials')\n  >('@kit\u002Fsupabase\u002Fvault-connection-credentials');\n\n  return {\n    ...actual,\n    getConnectionProviderCredentials: vaultCredentialsMock,\n  };\n});\n\nconst msw = setupMswTestServer();\nconst ACTOR_EMAIL_PREFIX = 'my-entity-sync'; \u002F\u002F keep unique across spec files\n\ndescribe('My entity sync (integration)', () => {\n  const supabase = createTestSupabaseAdmin();\n  const actorsForCleanup: TestActor[] = [];\n  const accountIdsForSyncCleanup = new Set\u003Cstring>();\n\n  beforeAll(msw.beforeAll);\n\n  beforeEach(() => {\n    vi.stubEnv('SYNC_ENGINE_ENABLED', 'true');\n    vi.stubEnv('SYNC_OUTBOUND_ENABLED', 'true');\n    vi.stubEnv(\n      'NEXT_PUBLIC_SUPABASE_URL',\n      process.env.NEXT_PUBLIC_SUPABASE_URL ?? process.env.SUPABASE_URL ?? '',\n    );\n\n    \u002F\u002F For inbound specs use TEST_WEBHOOK_SECRET; for outbound\u002Freconciliation\n    \u002F\u002F specs use serializeStoredProviderCredentials({access_token: ...}).\n    vaultCredentialsMock.mockResolvedValue(TEST_WEBHOOK_SECRET);\n    msw.beforeEach();\n  });\n\n  afterEach(async () => {\n    vi.unstubAllEnvs();\n\n    await runIntegrationSpecAfterEach({\n      supabase,\n      actors: actorsForCleanup,\n      accountIdsForSyncCleanup,\n      msw,\n    });\n  });\n\n  afterAll(msw.afterAll);\n\n  it('Inbound: creates entity from webhook', async () => {\n    const actor = await createActor(ACTOR_EMAIL_PREFIX);\n    actorsForCleanup.push(actor);\n    accountIdsForSyncCleanup.add(actor.accountId);\n\n    const { connection } = await seedSyncConnection(\n      {\n        accountId: actor.accountId,\n        createdBy: actor.userId,\n        syncEnabled: true,\n        providerConfig: linearProviderConfig,\n      },\n      supabase,\n    );\n    const connectionId = String(connection.id);\n    await setWebhookSecret(connectionId);\n\n    const harness = await createInboundAppHarness();\n    try {\n      testServer.use(\n        createLinearQueryOverride('IssueById', async ({ variables }) => {\n          return HttpResponse.json({\n            data: {\n              issue: createLinearIssue({\n                id: (variables.id as string) ?? 'linear-issue-1',\n                title: 'Expected title',\n              }),\n            },\n          });\n        }),\n      );\n\n      const payload = createLinearWebhookPayload(\n        'Issue',\n        'create',\n        createLinearIssue({ id: 'linear-issue-1', title: 'Expected title' }),\n      );\n\n      const response = await postLinearWebhook({\n        app: harness.app,\n        accountId: actor.accountId,\n        connectionId,\n        payload,\n        deliveryId: `delivery-${randomUUID()}`,\n      });\n\n      expect(response.status).toBe(200);\n\n      await processWebhookAndInboundJobs({\n        moduleRef: harness.moduleRef,\n        webhookQueue: harness.webhookQueue,\n        inboundQueue: harness.inboundQueue,\n      });\n\n      \u002F\u002F Assert domain row\n      const { data: rows } = await supabase\n        .from('tasks')\n        .select('id,title,status')\n        .eq('account_id', actor.accountId)\n        .eq('title', 'Expected title')\n        .limit(1);\n\n      expect(rows).toHaveLength(1);\n\n      \u002F\u002F Assert mapping\n      const { data: mapping } = await supabase\n        .from('sync_entity_mappings')\n        .select('external_entity_type,external_id,hamster_entity_type,hamster_id')\n        .eq('sync_connection_id', connectionId)\n        .eq('external_id', 'linear-issue-1')\n        .single();\n\n      expect(mapping?.hamster_entity_type).toBe('task');\n      expect(mapping?.hamster_id).toBe(rows?.[0]?.id);\n\n      \u002F\u002F Assert sync log\n      const logs = await querySyncLogs(\n        connectionId,\n        { direction: 'inbound', entityType: 'issue' },\n        supabase,\n      );\n\n      expect(\n        logs.filter((l) => l.operation === 'create' && l.status === 'success'),\n      ).toHaveLength(1);\n    } finally {\n      await harness.cleanup();\n    }\n  });\n});\n```\n\n### Skeleton conventions\n\n- **Vault mock with `vi.hoisted`**: every bidirectional spec needs this. For outbound\u002Freconciliation specs, mock with `serializeStoredProviderCredentials({access_token: ...})` instead of `TEST_WEBHOOK_SECRET`.\n- **`linearProviderConfig`**: canonical Linear config from `bidirectional-integration-helpers.ts`. Use it so status mapping, team ID, and workspace config match what MSW base handlers expect.\n- **Actor tracking**: push every actor to `actorsForCleanup` and add the account ID to `accountIdsForSyncCleanup` immediately after creation.\n- **`try \u002F finally` around harness**: always clean up even if the test throws — leaked Redis connections cause \"Connection is closed\" errors in subsequent tests.\n- **`String(connection.id)`**: connection IDs from Supabase are typed `string | number`. Cast once at the top.\n\n## Full-runtime harnesses vs focused worker specs\n\n- **Full-runtime sync specs** boot `SyncEngineModule`, use real Supabase + Redis, and often use MSW at the Linear boundary. These are the `bidirectional-*.integration.spec.ts`, `outbound-operational`, `reconciliation-operational`, and `sync-connections.controller` specs.\n- **Focused worker\u002Fservice integration specs** exercise one worker or service with real queue\u002Fstorage seams but without the full shared app harness. These are `outbound-event-worker.integration.spec.ts`, `outbox-worker.integration.spec.ts`, etc.\n\nUse the focused specs when the behavior under test is primarily about outbox claiming, lease handling, dedupe, or deterministic job construction. Do not force those cases into the larger operational canary shape.\n\n## Loop suppression and sync markers\n\nThis repo uses `sync_entity_mappings.last_sync_origin` and `last_sync_applied_at` to suppress immediate echo loops. When testing follow-up inbound or outbound behavior:\n\n- prefer directly nulling or backdating those fields in test setup\n- avoid `sleep` or arbitrary timeouts to wait out the suppression window\n\n```typescript\n\u002F\u002F Deactivate suppression for a follow-up inbound update test\nawait supabase\n  .from('sync_entity_mappings')\n  .update({ last_sync_origin: null, last_sync_applied_at: null })\n  .eq('sync_connection_id', connectionId)\n  .eq('external_id', 'linear-issue-1');\n```\n\n`NULL` values in both fields bypass the check entirely.\n\n## MSW and Fixtures\n\nSee `apps\u002Fsync\u002FTESTING.md` for the full MSW setup reference, fixture factory list, and error helper catalog.\n\nKey decision rules:\n\n- Add to `linearBaseHandlers` when the same Linear operation will be used across several tests.\n- Use `createLinearQueryOverride` or `createLinearMutationOverride` when the behavior is specific to one test.\n- Base handlers intentionally validate minimal required inputs (e.g. `IssueCreate` rejects missing `title` or `teamId`). Do not weaken them to make a test pass — override the operation instead.\n- Service-level integration tests use MSW. Lower-level adapter or service unit specs use direct `vi.stubGlobal('fetch', ...)`. Default to MSW + harness for sync integration tests.\n\n## Assertions That Matter\n\nPrefer these repo-native assertions over shallow status checks:\n\n- domain row updated in the correct table\n- mapping row exists and points to the expected `hamster_id` \u002F `external_id`\n- `sync_logs` contains the expected `direction`, `entity_type`, `operation`, and `status`\n- `sync_outbound_events.processed_at` changed when testing outbound completion\n- relevant queue received the right job name when testing HTTP flows\n\nFor initiative-related sync, remember that `initiative_briefs` is the canonical relationship set. When a change affects initiative\u002Fproject linkage, assert the canonical link rows instead of treating `brief.initiative_id` as the primary contract.\n\n## Anti-Patterns\n\n- Do **not** mock Supabase or Redis in sync integration tests.\n- Do **not** put new sync integration tests outside `apps\u002Fsync\u002Fsrc\u002F**\u002F*.integration.spec.ts`.\n- Do **not** use arbitrary sleeps for queue or suppression timing.\n- Do **not** reuse a queue after cleanup; create fresh queues in `beforeEach`.\n- Do **not** bypass unexpected Linear requests with `'bypass'` unless the test explicitly needs it.\n- Do **not** assert only the local entity row when mappings or sync logs are the real contract.\n- Do **not** forget `clearOutboundEvents(...)` before asserting update\u002Fdelete outbox events for an entity that was just inserted.\n- Do **not** pass `accountId` where a real auth user ID is required (for example `initiatives.owner_id` references `auth.users.id`).\n- Do **not** forget `vi.unstubAllEnvs()` in afterEach — env stubs leak across tests without it.\n- Do **not** skip the vault credentials mock — the sync engine calls `getConnectionProviderCredentials` to resolve both webhook secrets and provider tokens.\n- Do **not** forget `try \u002F finally` around harness usage — leaked Redis connections cause \"Connection is closed\" errors in subsequent tests.\n\n## Verification\n\nRun the smallest useful test first:\n\n```bash\npnpm --filter sync exec vitest run --config vitest.config.integration.ts \\\n  apps\u002Fsync\u002Fsrc\u002Fmodules\u002Fsync-engine\u002F\u003Cpath-to-spec>.integration.spec.ts\n```\n\nThen run the full integration suite when the change affects shared helpers, MSW setup, queue wiring, or multiple spec families:\n\n```bash\npnpm --filter sync test:integration\n```\n\nIf runtime code changed alongside tests, also run:\n\n```bash\npnpm --filter sync typecheck\n```\n\nIf the change touches shared helpers, queue wiring, or sync runtime code beyond a narrow test-only edit, also run:\n\n```bash\npnpm --filter sync build\n```\n",{"name":5,"version":24,"description":7},"1.0.0","main","fe3bb1476c3ec23d8a366eac0fa8cd9f0852360a","skills\u002F.experimental\u002Fhamster-sync-integration-testing",0,"https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills","https:\u002F\u002Fgithub.com\u002Fgethamster","https:\u002F\u002Ftryhamster.com","We're building the AI-native future of work, unlocking the promised acceleration for your whole team, from idea to impact.","2026-11-05 11:33:33",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add gethamster\u002Fskills --skill hamster-sync-integration-testing",{"tool":40,"command":41},"bunx","bunx skills add gethamster\u002Fskills --skill hamster-sync-integration-testing",{"tool":43,"command":44},"pnpm","pnpm dlx skills add gethamster\u002Fskills --skill hamster-sync-integration-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002F.experimental\u002Fhamster-sync-integration-testing\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7B5MWYW0KE251276S56KQDZ","writing-waterfall-requirements-documents","Write a waterfall requirements document: elicit, structure and review testable, traceable requirements, then baseline the specification before design.","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-waterfall-requirements-documents\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7B5MRCXWWPKREPB1CHQ7H90","writing-vision-and-values-statements","Write a V2MOM vision a reader can test and a ranked list of values that settles real tradeoffs, so the rest of the document has a clear anchor.","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-vision-and-values-statements\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7B5MKH2CH22YZAHQW3080VQ","writing-system-prompts-for-claude","Write Claude prompts and CLAUDE.md files that supply exact inputs, scope the task, and define done so the first attempt can be checked.","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-system-prompts-for-claude\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7B5ME1Y3X9RNRKP5HKHKACZ","writing-page-specific-website-copy","Website copywriting by page type: write homepage, landing page, pricing page and feature page copy that fits each page's visitor and single job.","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-page-specific-website-copy\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7B5M8MQNM8MN8PYH6BVWJ2B","writing-internal-press-releases","How to write an internal press release: the one-page working backwards press release that opens a PR\u002FFAQ document before anything is built.","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-internal-press-releases\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7B5M3P3YH1XF37R8PWXXSBK","writing-email-sequences-that-sell","Email sequence copywriting for nurture and sales: give each email one job, write clear subject lines, and close with one specific call to action.","https:\u002F\u002Fgithub.com\u002Fgethamster\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-email-sequences-that-sell\u002FSKILL.md",[],[]]