{ "$schema": "https://ui.shadcn.com/schema/registry-item.json", "name": "circleback", "type": "registry:item", "title": "Circleback", "description": "Five independent Circleback raw resource streams with complete full reads, transcript availability evidence, and native relationships.", "dependencies": [ "@chkit/core@^0.2.0-beta.12", "@chkit/plugin-ingest@^0.2.0-beta.12", "zod@^4.3.6" ], "devDependencies": [ "@types/bun@^1.2.0" ], "files": [ { "path": "circleback/README.md", "type": "registry:file", "target": "src/integrations/circleback/README.md", "content": "# Circleback raw ingestion\n\nThis editable integration stores Circleback provider objects in five independent raw resource streams within one account pipeline.\n\nSet `CIRCLEBACK_API_KEY`, or pass `apiKey` in `config.ts`. Create a key in Circleback **Settings → API keys** and configure the project's direct ClickHouse connection. Native JSON requires ClickHouse 25.3 or later. The [official API reference](https://circleback.ai/docs/api) describes authentication, access and account rate limits.\n\nEdit `config.ts` for the stable `sourceId`, meeting `ownership`, and setup-time `database`. Each stream checks its configuration and API key when it runs, before any request, so `generate`, `migrate`, and `chkit check` never depend on them. `ownership: 'All'` includes meetings shared with the authenticated user. People, companies, and action items use their own authenticated-user API collections; these APIs do not promise an organization-wide export.\n\n```sh\nbunx chkit check\nbunx chkit generate --name add_circleback\n# Review the migration before applying it.\nbunx chkit migrate --apply\nbunx chkit ingest run --tag provider:circleback\n```\n\n## Resources\n\n| Resource tag | Raw table | Retrieval |\n|---|---|---|\n| `resource:meetings` | `circleback_meetings_raw` | All accessible meeting pages with configured ownership. |\n| `resource:meeting_transcripts` | `circleback_meeting_transcripts_raw` | Own complete meeting discovery, then a whole transcript snapshot per meeting. |\n| `resource:action_items` | `circleback_action_items_raw` | All pages of both `PENDING` and `DONE`, with `assigneeType=Anyone`. |\n| `resource:people` | `circleback_people_raw` | All attendee person pages and their same-person detail responses. |\n| `resource:companies` | `circleback_companies_raw` | All company pages and their same-company detail responses. |\n\n`pipeline.ts` composes the streams; `sources/` contains each raw schema and reader. `client.ts` owns authenticated requests, validation, scoped row mapping, and native `paginate()` Link traversal. `index.ts` exports the pipeline and all five tables. Selecting one resource or reversing stream order requires no other stream to run. Meeting publication does not depend on transcript retrieval.\n\nProvider fields stay under `raw.data`; meeting objects retain provider-returned notes, attendee and action-item summaries, insights, and recording links. Transcripts and independently listed action items are not fetched to assemble a meeting document. The requested projection is `tags: string[]`: every returned tag name is retained, while tag definitions have no separate stream. Recordings and other binary links are preserved without downloading their content.\n\nPeople perform one [detail GET per listed profile](https://circleback.ai/docs/api/people/get-person), preserving native fields and `externalLinks`; returned IDs must match discovery. Companies similarly request one detail per listed domain. These same-resource reads add to each full run's request cost and require matching access.\n\n```sh\nbunx chkit ingest run --tag provider:circleback --tag resource:meeting_transcripts\nbunx chkit ingest status --tag provider:circleback --json\n```\n\n## Full reads and recovery\n\nThe [provider's list endpoints](https://circleback.ai/docs/api) return arrays with RFC 8288 `Link` continuations. They expose no reliable modification feed or durable sync token. Each stream uses `fullSync()` and ordinary pagination, revisiting its complete accessible collection on every run. Cursor-only next links retain the stream's fixed ownership, assignee and status filters; conflicting filters, malformed pages, unsafe URLs and cyclic continuations fail visibly.\n\nSuccessful completion follows destination acknowledgement and includes empty reads. A failed or interrupted stream replays from its first page on the next run. Loaded rows may remain visible after a later failure; other streams keep their own successful completion. There is no custom parent ledger or scan checkpoint. Full reads ignore date backfill bounds and provide no date-range backfill.\n\nTranscript discovery has its own full meeting listing. It rechecks old meetings without relying on a meeting's `updatedAt`, capturing transcripts that become available later. IDs absent from the current listing are not an executable retry queue. A changed or inaccessible source cannot establish deletion; absent records stay stored.\n\nThe [action-item listing](https://circleback.ai/docs/api/action-items/list-action-items) defaults to the authenticated assignee and incomplete items. The integration explicitly reads any assignee across both native completion statuses. `PENDING` and `DONE` are the exhaustive statuses in the [official OpenAPI](https://circleback.ai/docs/api/openapi.json), also documented by the [update endpoint](https://circleback.ai/docs/api/action-items/update-action-item). An unexpected status or ignored partition fails visibly. Mutable lists and status partitions are not atomic snapshots; a later full run reconciles edits and moves between partitions.\n\nRequests go through the ingestion runtime, which forwards cancellation, times out after 30 seconds, and retries only network failures, timeouts, and retryable HTTP statuses. HTTP failures retain provider responses; `429` honors `Retry-After`, falling back to Circleback's `RateLimit-Reset` seconds when `Retry-After` is absent or not parsed by the shared HTTP parser. Blank and negative `Retry-After` values currently parse as zero and bypass the fallback. Without either parsed delay the executor uses its normal retry backoff. This fallback is fixture-tested hardening, not evidence of a live provider incident. Authentication and listing permission failures fail their resource. Run one ingestion process per ClickHouse target at a time and repeat runs with an external scheduler.\n\n## Identities and company joins\n\nEvery row keeps `raw.source_id`. Stable row IDs are JSON-encoded arrays:\n\n| Resource | Row identity |\n|---|---|\n| Meetings | `[sourceId, meeting.id]` |\n| Transcript snapshot | `[sourceId, meetingId]` |\n| Transcript read outcome | `[sourceId, meetingId, 'availability']` |\n| Action items | `[sourceId, actionItem.id]` |\n| People | `[sourceId, person.id]` |\n| Companies | `[sourceId, company.domain]` |\n\nNumeric provider IDs such as `assignee.profileId` and `person.companyId` remain numbers in `data`; `meetingIds` retain their native strings. Keep source identity in joins. Company identity always uses the provider domain, so a numeric ID appearing later does not change its row key.\n\nThe [company list](https://circleback.ai/docs/api/companies/list-companies) permits an optional native numeric `id`; [company detail](https://circleback.ai/docs/api/companies/get-company) includes people and external links. The companies stream preserves both listing and detail fields under `data`. Its `company_id` envelope field is the listed/detail native ID or a consistent non-null `people[].companyId`; conflicting native IDs fail. A valid empty company without a numeric ID still syncs with `company_id: null`. No numeric ID is synthesized. Join `person.data.companyId` to `company.company_id` only when present, together with `source_id`; unknown numeric identity is a documented join gap.\n\nKeep `sourceId` stable. Switching accounts or meeting filters requires a distinct source ID and deliberately configured destination. `createCirclebackPipeline(config)` binds a snapshot of reader configuration, including `apiKey`; pass another `apiKey` for a second installation. Its runtime config does not redefine exported tables; change `database` or installed raw table definitions before schema discovery and migration generation.\n\nVersion 0.1.0 used direct meeting JSON and unscoped meeting row IDs. The 0.2.0 layout introduces source envelopes, scoped row keys, string tags and four additional tables. Reingest into a fresh configured destination or migrate earlier observations deliberately; old unscoped rows are not automatically rewritten or deleted.\n\n## Transcript snapshots and availability\n\nThe transcript table contains two explicitly distinguished observations per meeting:\n\n- `kind: 'transcript'`: the last successfully retrieved full segment array under `data`, with `status: 'available'`.\n- `kind: 'availability'`: the latest read outcome, `available`, `forbidden` for HTTP 403, or `not_found` for HTTP 404.\n\nA 403/404 updates the outcome key and preserves earlier successful text. It proves neither deletion nor temporary processing. A valid HTTP 200 empty array replaces the prior snapshot with `[]`; malformed HTTP 200 content fails without publishing success. Segments retain their provider fields without synthetic segment IDs, subject to native JSON storage normalization.\n\nClickHouse native JSON is not byte- or shape-exact archival storage: explicit null paths and empty objects may be absent when queried, including a transcript segment's `speaker: null`. See [native JSON storage fidelity](https://chkit.obsessiondb.com/api-sync/destinations/).\n\nUse `FINAL` for latest observations and filter successful snapshots explicitly:\n\n```sql\nSELECT\n raw.source_id::String AS source_id,\n raw.meeting_id::String AS meeting_id,\n JSONExtractRaw(toJSONString(raw), 'data') AS transcript\nFROM default.circleback_meeting_transcripts_raw FINAL\nWHERE raw.kind::String = 'transcript';\n```\n\nLatest outcomes are the `kind = 'availability'` rows in the same table. Join them to snapshots on `source_id` and `meeting_id`; an outcome can be forbidden while a previous successful snapshot remains readable. The [integration guide](https://chkit.obsessiondb.com/integrations/circleback/) shows that query.\n\n## Fixture tests\n\n```sh\nbunx chkit add circleback --with-tests\nbun test src/integrations/circleback/tests/basic.test.ts\n```\n\nPortable fixtures pass provider responses through the ingestion runtime's `fetch` and use in-memory ingestion adapters without credentials or a live database. They cover five isolated and reordered resources, full-sync failure/replay, empty completion, scoped identities, tag names, all action statuses, company joins, late transcripts, permission-loss retention, malformed responses, and pagination safety.\n" }, { "path": "circleback/index.ts", "type": "registry:file", "target": "src/integrations/circleback/index.ts", "content": "export { circlebackPipeline, createCirclebackPipeline } from './pipeline.js'\nexport { circleback_meetingsRaw } from './sources/meetings.js'\nexport { circleback_meetingTranscriptsRaw } from './sources/meeting-transcripts.js'\nexport { circleback_actionItemsRaw } from './sources/action-items.js'\nexport { circleback_peopleRaw } from './sources/people.js'\nexport { circleback_companiesRaw } from './sources/companies.js'\n" }, { "path": "circleback/config.ts", "type": "registry:file", "target": "src/integrations/circleback/config.ts", "content": "import { z } from 'zod'\n\nconst missingApiKey = 'Set CIRCLEBACK_API_KEY or pass apiKey.'\nconst apiKey = z.string().optional().pipe(z.string({ error: missingApiKey }).trim().min(1, missingApiKey))\n\nconst circlebackConfigSchema = z.object({\n /** Stable account/installation namespace. Use a new sourceId when changing accounts or filters. */\n sourceId: z.string().refine((value) => value.trim() !== '', 'must not be blank'),\n /** Schema setup only; runtime pipeline factories do not change raw tables. */\n database: z.string(),\n ownership: z.enum(['All', 'Mine', 'Shared']),\n /** Circleback API key; read when a stream runs, never by schema commands. */\n apiKey,\n})\n\nexport type CirclebackConfig = z.input\n\nexport const circlebackReaderConfigSchema = circlebackConfigSchema.omit({ database: true })\nexport type CirclebackReaderConfig = z.input\n\n// Collections are fully revisited on every run.\nexport const circlebackConfig: CirclebackConfig = {\n sourceId: 'circleback',\n database: 'default',\n ownership: 'All',\n apiKey: process.env.CIRCLEBACK_API_KEY,\n}\n" }, { "path": "circleback/client.ts", "type": "registry:file", "target": "src/integrations/circleback/client.ts", "content": "import { HttpError, paginate, rawRows, type Page, type SourceContext } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { circlebackReaderConfigSchema, type CirclebackReaderConfig } from './config.js'\n\nexport type CirclebackObject = Record\nexport type CirclebackCollection = '/meetings' | '/action-items' | '/people' | '/companies'\nexport type CirclebackSettings = Omit, 'apiKey'>\nexport type TranscriptRead =\n | { status: 'available'; data: z.output }\n | { status: 'forbidden' | 'not_found'; data: null }\n\nexport interface CirclebackClient {\n settings: CirclebackSettings\n pages(path: CirclebackCollection, item: z.ZodType, query?: Record): AsyncGenerator>\n detail(path: string, item: z.ZodType): Promise\n transcript(meetingId: string): Promise\n}\n\nexport const circlebackId = z.int().positive()\nexport const nonBlankString = z.string().refine((value) => value.trim() !== '', 'must not be blank')\n/** Tag names are the requested projection; provider objects otherwise stay intact. */\nexport const circlebackTags = z.array(z.looseObject({ name: nonBlankString })).transform((tags) => tags.map((tag) => tag.name)).optional()\nconst baseUrl = 'https://circleback.ai/api'\nconst transcriptSegments = z.array(z.looseObject({ speaker: z.string().nullable(), text: z.string(), timestamp: z.number() }))\nconst unavailable = new Map([[403, 'forbidden'], [404, 'not_found']])\n\nexport function createCirclebackClient(context: SourceContext, config: CirclebackReaderConfig): CirclebackClient {\n const { apiKey, ...settings } = circlebackReaderConfigSchema.parse(config)\n const get = (url: string) => context.attempt(\n () => context.fetch(url, { redirect: 'error', headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' } })\n .catch((error: unknown) => { throw withResetDelay(error) }),\n { label: `GET ${new URL(url).pathname}` },\n )\n return {\n settings,\n pages(path: CirclebackCollection, item: z.ZodType, query: Record = {}) {\n const initial = new URL(`${baseUrl}${path}`)\n for (const [key, value] of Object.entries(query)) initial.searchParams.set(key, value)\n const page = z.array(item)\n return paginate({\n context, initial: initial.toString(), label: `GET ${path}`,\n fetchPage: async (url = initial.toString()) => {\n const response = await get(url)\n return { items: page.parse(await response.json()), next: nextLink(response.headers.get('link'), url, query) }\n },\n })\n },\n async detail(path: string, item: z.ZodType) {\n const response = await get(`${baseUrl}${path}`)\n return item.parse(await response.json())\n },\n async transcript(meetingId: string) {\n let response: Response\n try {\n response = await get(`${baseUrl}/meeting/${encodeURIComponent(meetingId)}/transcript`)\n } catch (error) {\n const status = error instanceof HttpError ? unavailable.get(error.status) : undefined\n if (status) return { status, data: null }\n throw error\n }\n return { status: 'available', data: transcriptSegments.parse(await response.json()) }\n },\n }\n}\n\n/** Circleback sends the wait as RateLimit-Reset seconds, without Retry-After. */\nfunction withResetDelay(error: unknown): unknown {\n if (!(error instanceof HttpError) || error.status !== 429 || error.retryAfterMs !== undefined) return error\n const reset = error.response.headers.get('ratelimit-reset')\n const resetMs = reset?.trim() ? Number(reset) * 1000 : Number.NaN\n return Number.isFinite(resetMs) && resetMs >= 0 ? HttpError.withStatus(error.response, 429, { body: error.body, retryAfterMs: resetMs }) : error\n}\n\nexport function toCirclebackRows(items: readonly T[], id: (item: T) => string | number, sourceId: string) {\n return rawRows(items.map((data) => ({ source_id: sourceId, data })), (item) => JSON.stringify([sourceId, id(item.data)]))\n}\n\nfunction nextLink(header: string | null, current: string, query: Record): string | undefined {\n if (!header?.trim()) return undefined\n const candidates: string[] = []\n for (const part of header.split(/,(?=\\s*<)/)) {\n const link = /^\\s*<([^>]+)>\\s*(.*)$/.exec(part)\n if (!link) throw new Error('Circleback returned a malformed Link header.')\n const relation = /;\\s*rel\\s*=\\s*(?:\"([^\"]+)\"|([^;\\s]+))/.exec(link[2] ?? '')\n if (!(relation?.[1] ?? relation?.[2])?.split(/\\s+/).includes('next')) continue\n if (!link[1]) throw new Error('Circleback next page URL is missing.')\n candidates.push(link[1])\n }\n if (candidates.length > 1) throw new Error('Circleback returned multiple next pages.')\n const value = candidates[0]\n if (!value) return undefined\n if (!URL.canParse(value, current)) throw new Error('Circleback returned an invalid next page URL.')\n const next = new URL(value, current)\n if (next.origin !== 'https://circleback.ai' || next.pathname !== new URL(current).pathname || next.username || next.password || next.hash) {\n throw new Error('Circleback next page changed the collection or origin.')\n }\n for (const [key, value] of Object.entries(query)) {\n const values = next.searchParams.getAll(key)\n if (values.length > 1 || values.some((nextValue) => nextValue !== value)) {\n throw new Error(`Circleback next page changed the ${key} filter.`)\n }\n next.searchParams.set(key, value)\n }\n return next.toString()\n}\n" }, { "path": "circleback/pipeline.ts", "type": "registry:file", "target": "src/integrations/circleback/pipeline.ts", "content": "import { definePipeline, defineStream, fullSync } from '@chkit/plugin-ingest'\n\nimport { circlebackConfig, type CirclebackReaderConfig } from './config.js'\nimport { circleback_meetingsRaw, readMeetings } from './sources/meetings.js'\nimport { circleback_meetingTranscriptsRaw, readMeetingTranscripts } from './sources/meeting-transcripts.js'\nimport { circleback_actionItemsRaw, readActionItems } from './sources/action-items.js'\nimport { circleback_peopleRaw, readPeople } from './sources/people.js'\nimport { circleback_companiesRaw, readCompanies } from './sources/companies.js'\n\nexport function createCirclebackPipeline(config: CirclebackReaderConfig = circlebackConfig) {\n const source = { ...config }\n const options = { incremental: fullSync() }\n return definePipeline({\n id: source.sourceId, tags: ['provider:circleback'], maxStreams: 1, maxFetches: 1,\n streams: [\n defineStream({ ...options, id: `${source.sourceId}.meetings`, tags: ['resource:meetings'], destination: circleback_meetingsRaw,\n read: (context) => readMeetings(context, source) }),\n defineStream({ ...options, id: `${source.sourceId}.meeting_transcripts`, tags: ['resource:meeting_transcripts'], destination: circleback_meetingTranscriptsRaw,\n read: (context) => readMeetingTranscripts(context, source) }),\n defineStream({ ...options, id: `${source.sourceId}.action_items`, tags: ['resource:action_items'], destination: circleback_actionItemsRaw,\n read: (context) => readActionItems(context, source) }),\n defineStream({ ...options, id: `${source.sourceId}.people`, tags: ['resource:people'], destination: circleback_peopleRaw,\n read: (context) => readPeople(context, source) }),\n defineStream({ ...options, id: `${source.sourceId}.companies`, tags: ['resource:companies'], destination: circleback_companiesRaw,\n read: (context) => readCompanies(context, source) }),\n ],\n })\n}\n\nexport const circlebackPipeline = createCirclebackPipeline()\n" }, { "path": "circleback/sources/meetings.ts", "type": "registry:file", "target": "src/integrations/circleback/sources/meetings.ts", "content": "import { rawTable, type SourceContext } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { circlebackTags, createCirclebackClient, nonBlankString, toCirclebackRows } from '../client.js'\nimport { circlebackConfig, type CirclebackReaderConfig } from '../config.js'\n\nconst meeting = z.looseObject({ id: nonBlankString, tags: circlebackTags })\n\nexport const circleback_meetingsRaw = rawTable({ database: circlebackConfig.database, name: 'circleback_meetings_raw' })\n\nexport async function* readMeetings(context: SourceContext, config: CirclebackReaderConfig) {\n const client = createCirclebackClient(context, config)\n for await (const page of client.pages('/meetings', meeting, { ownership: client.settings.ownership })) {\n yield { rows: toCirclebackRows(page.items, (item) => item.id, client.settings.sourceId) }\n }\n}\n" }, { "path": "circleback/sources/meeting-transcripts.ts", "type": "registry:file", "target": "src/integrations/circleback/sources/meeting-transcripts.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { createCirclebackClient, nonBlankString, type CirclebackObject } from '../client.js'\nimport { circlebackConfig, type CirclebackReaderConfig } from '../config.js'\n\nconst meeting = z.looseObject({ id: nonBlankString })\n\nexport const circleback_meetingTranscriptsRaw = rawTable({ database: circlebackConfig.database, name: 'circleback_meeting_transcripts_raw' })\n\n/** Discover every eligible meeting here: old meetings can gain transcripts without metadata changes. */\nexport async function* readMeetingTranscripts(context: SourceContext, config: CirclebackReaderConfig) {\n const client = createCirclebackClient(context, config)\n const { ownership, sourceId } = client.settings\n for await (const page of client.pages('/meetings', meeting, { ownership })) {\n for (const { id } of page.items) {\n const snapshot = await client.transcript(id)\n const observations: CirclebackObject[] = [{ source_id: sourceId, meeting_id: id, kind: 'availability', status: snapshot.status }]\n if (snapshot.status === 'available') observations.unshift({ source_id: sourceId, kind: 'transcript', meeting_id: id, ...snapshot })\n // Unavailability changes read evidence, not the last successful transcript snapshot.\n yield { rows: rawRows(observations, (item) => JSON.stringify(item.kind === 'transcript' ? [sourceId, id] : [sourceId, id, 'availability'])) }\n }\n }\n}\n" }, { "path": "circleback/sources/action-items.ts", "type": "registry:file", "target": "src/integrations/circleback/sources/action-items.ts", "content": "import { rawTable, type SourceContext } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { circlebackId, circlebackTags, createCirclebackClient, nonBlankString, toCirclebackRows } from '../client.js'\nimport { circlebackConfig, type CirclebackReaderConfig } from '../config.js'\n\n// The official OpenAPI and Circleback CLI enumerate exactly these native completion statuses.\nconst statuses = ['PENDING', 'DONE']\nconst actionItem = z.looseObject({ id: circlebackId, meetingIds: z.array(nonBlankString), tags: circlebackTags })\n\nexport const circleback_actionItemsRaw = rawTable({ database: circlebackConfig.database, name: 'circleback_action_items_raw' })\n\nexport async function* readActionItems(context: SourceContext, config: CirclebackReaderConfig) {\n const client = createCirclebackClient(context, config)\n for (const status of statuses) {\n for await (const page of client.pages('/action-items', actionItem, { assigneeType: 'Anyone', status })) {\n if (page.items.some((item) => item.status !== status)) throw new Error(`Circleback returned an action item outside the ${status} status partition.`)\n yield { rows: toCirclebackRows(page.items, (item) => item.id, client.settings.sourceId) }\n }\n }\n}\n" }, { "path": "circleback/sources/people.ts", "type": "registry:file", "target": "src/integrations/circleback/sources/people.ts", "content": "import { rawTable, type SourceContext } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { circlebackId, circlebackTags, createCirclebackClient, toCirclebackRows } from '../client.js'\nimport { circlebackConfig, type CirclebackReaderConfig } from '../config.js'\n\nconst person = z.looseObject({ id: circlebackId, tags: circlebackTags })\nconst personDetail = person.extend({ externalLinks: z.array(z.unknown()) })\n\nexport const circleback_peopleRaw = rawTable({ database: circlebackConfig.database, name: 'circleback_people_raw' })\n\nexport async function* readPeople(context: SourceContext, config: CirclebackReaderConfig) {\n const client = createCirclebackClient(context, config)\n for await (const page of client.pages('/people', person)) {\n for (const listed of page.items) {\n const detail = await client.detail(`/person/${listed.id}`, personDetail)\n if (detail.id !== listed.id) throw new Error('Circleback person detail changed its ID.')\n yield { rows: toCirclebackRows([{ ...listed, ...detail }], (item) => item.id, client.settings.sourceId) }\n }\n }\n}\n" }, { "path": "circleback/sources/companies.ts", "type": "registry:file", "target": "src/integrations/circleback/sources/companies.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { circlebackId, circlebackTags, createCirclebackClient, nonBlankString } from '../client.js'\nimport { circlebackConfig, type CirclebackReaderConfig } from '../config.js'\n\nconst company = z.looseObject({ domain: nonBlankString, id: circlebackId.optional(), tags: circlebackTags })\nconst companyDetail = company.extend({\n people: z.array(z.looseObject({ id: circlebackId, companyId: circlebackId.nullable() })),\n externalLinks: z.array(z.unknown()),\n})\n\nexport const circleback_companiesRaw = rawTable({ database: circlebackConfig.database, name: 'circleback_companies_raw' })\n\nexport async function* readCompanies(context: SourceContext, config: CirclebackReaderConfig) {\n const client = createCirclebackClient(context, config)\n const { sourceId } = client.settings\n for await (const page of client.pages('/companies', company)) {\n for (const listed of page.items) {\n const detail = await client.detail(`/company/${encodeURIComponent(listed.domain)}`, companyDetail)\n if (detail.domain !== listed.domain) throw new Error('Circleback company detail changed its domain.')\n const companyIds = new Set([listed.id, detail.id, ...detail.people.map((person) => person.companyId)].flatMap((id) => id ?? []))\n if (companyIds.size > 1) throw new Error('Circleback company returned conflicting numeric company IDs.')\n const snapshot = { source_id: sourceId, company_id: [...companyIds][0] ?? null, data: { ...listed, ...detail } }\n // The provider domain is always the identity, even when an optional numeric ID appears later.\n yield { rows: rawRows([snapshot], () => JSON.stringify([sourceId, listed.domain])) }\n }\n }\n}\n" }, { "path": "circleback/tests/basic.test.ts", "type": "registry:file", "target": "src/integrations/circleback/tests/basic.test.ts", "role": "test", "content": "import { expect, test } from 'bun:test'\nimport { runIngestion, selectStreams } from '@chkit/plugin-ingest'\nimport { createMemoryDestination, createMemoryJournal } from '@chkit/plugin-ingest/testing'\n\nimport { createCirclebackPipeline, circlebackPipeline } from '../index.js'\nimport { circlebackConfig, type CirclebackReaderConfig } from '../config.js'\n\nconst cutoff = new Date('2026-01-02T00:00:00Z')\nconst fixtureConfig = { ...circlebackConfig, apiKey: 'fixture' }\nconst resources = ['meetings', 'meeting_transcripts', 'action_items', 'people', 'companies']\nconst meeting = { id: 'meeting-a', name: 'Old meeting', updatedAt: '2020-01-01T00:00:00Z', notes: 'Provider notes',\n tags: [{ id: 10, name: 'Customer' }, { id: 11, name: 'Follow up' }], attendees: [{ profileId: 1 }],\n actionItems: [{ id: 252, status: 'PENDING' }], custom: { retained: true } }\nconst transcript = [{ speaker: null, text: 'Full transcript\\nwith another line', timestamp: 0.25, custom: true }]\nconst pending = { id: 252, title: 'Follow up', status: 'PENDING', completedAt: null, assignee: { profileId: 1 }, meetingIds: ['meeting-a'], custom: true }\nconst done = { id: 253, title: 'Completed work', status: 'DONE', completedAt: '2020-01-01T00:00:00Z', assignee: null, meetingIds: [], custom: true }\nconst person = { id: 1, companyId: 3, firstName: 'John', lastName: 'Appleseed', email: 'john@initech.com', companyName: 'Initech', title: 'Operations', custom: true }\nconst personDetail = { ...person, externalLinks: [{ type: 'linkedin', objectType: 'person', url: 'https://www.linkedin.com/in/john-appleseed' }] }\nconst company = { domain: 'initech.com', name: 'Initech', avatarUrl: null, custom: true }\nconst companyDetail = { ...company, people: [person], externalLinks: [{ type: 'website', objectType: 'company', url: 'https://initech.com' }] }\n\ntype Pipeline = ReturnType\ntype Responder = (url: URL, init: RequestInit) => Response | Promise\n\ntest('Circleback publishes five raw resources with scoped native IDs and string tag names', async () => {\n const calls: URL[] = [], env = circlebackEnv((url, init) => { calls.push(url); return fixtureResponse(url, init) }), pipeline = fixturePipeline()\n expect(circlebackPipeline.streams).toHaveLength(5)\n expect(pipeline.streams.map((stream) => stream.id).sort()).toEqual(resources.map((resource) => `circleback.${resource}`).sort())\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const result = await runIngestion(request(pipeline), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })\n expect(result.ok, JSON.stringify(result)).toBe(true)\n const expected = {\n meetings: [{ id: rowId('meeting-a'), raw: envelope({ ...meeting, tags: ['Customer', 'Follow up'] }) }],\n meeting_transcripts: [\n { id: rowId('meeting-a'), raw: { source_id: 'circleback', kind: 'transcript', meeting_id: 'meeting-a', status: 'available', data: transcript } },\n { id: JSON.stringify(['circleback', 'meeting-a', 'availability']), raw: { source_id: 'circleback', meeting_id: 'meeting-a', kind: 'availability', status: 'available' } },\n ],\n action_items: [pending, done].map((data) => ({ id: rowId(data.id), raw: envelope(data) })),\n people: [{ id: rowId(person.id), raw: envelope(personDetail) }],\n companies: [{ id: rowId(company.domain), raw: { source_id: 'circleback', company_id: 3, data: companyDetail } }],\n }\n expect(destination.tables.size).toBe(5)\n for (const [resource, rows] of Object.entries(expected)) {\n expect(destination.tables.get(`default.circleback_${resource}_raw`)?.map(({ id, raw }) => ({ id, raw }))).toEqual(rows)\n expect((await journal.readCheckpoint(`circleback.${resource}`)).envelope).toBeUndefined()\n expect((await journal.readCheckpoint(`circleback.${resource}`)).lastSuccessSeq).toBeGreaterThan(0)\n }\n expect(calls.some((url) => url.pathname.includes('/calendar') || url.pathname.includes('/tags') || url.hostname !== 'circleback.ai')).toBe(false)\n})\n\ntest('all resources run alone and reversing stream order preserves their raw observations', async () => {\n const pipeline = fixturePipeline(), combined = createMemoryDestination()\n expect((await runIngestion(request({ ...pipeline, streams: [...pipeline.streams].reverse() }),\n { ...circlebackEnv(), journal: createMemoryJournal(), destination: combined, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n for (const resource of resources) {\n const calls: URL[] = [], destination = createMemoryDestination()\n const env = circlebackEnv((url, init) => { calls.push(url); return fixtureResponse(url, init) })\n const selected = request(pipeline, resource)\n expect(selected.selected.map((entry) => entry.stream.id)).toEqual([`circleback.${resource}`])\n expect((await runIngestion(selected, { ...env, journal: createMemoryJournal(), destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n expect(destination.tables.size).toBe(1)\n expect(destination.tables.get(`default.circleback_${resource}_raw`)?.map(({ id, raw }) => ({ id, raw })))\n .toEqual(combined.tables.get(`default.circleback_${resource}_raw`)?.map(({ id, raw }) => ({ id, raw })))\n expect(calls).toHaveLength(resource === 'meetings' ? 1 : 2)\n if (resource === 'meetings') expect(calls.map((url) => url.pathname)).toEqual(['/api/meetings'])\n if (resource === 'action_items') expect(calls.every((url) => url.pathname === '/api/action-items')).toBe(true)\n if (resource === 'companies') expect(calls.map((url) => url.pathname)).toEqual(['/api/companies', '/api/company/initech.com'])\n if (resource === 'people') expect(calls.map((url) => url.pathname)).toEqual(['/api/people', '/api/person/1'])\n }\n})\n\ntest('action items enumerate both native completion statuses for anyone and follow each partition to exhaustion', async () => {\n const calls: URL[] = []\n const env = circlebackEnv((url) => {\n calls.push(url)\n expect(url.searchParams.get('assigneeType')).toBe('Anyone')\n const status = url.searchParams.get('status')\n expect(status === 'PENDING' || status === 'DONE').toBe(true)\n const item = status === 'PENDING' ? pending : done\n if (url.searchParams.has('cursor')) return Response.json([{ ...item, id: item.id + 10 }])\n return Response.json([item], { headers: { Link: `; rel=\"next\"` } })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'action_items'), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n expect(calls.map((url) => [url.searchParams.get('status'), url.searchParams.get('cursor')])).toEqual([\n ['PENDING', null], ['PENDING', 'next'], ['DONE', null], ['DONE', 'next'],\n ])\n expect(destination.tables.get('default.circleback_action_items_raw')?.map((row) => row.id)).toEqual([252, 262, 253, 263].map((id) => rowId(id)))\n expect((await journal.readCheckpoint('circleback.action_items')).lastSuccessSeq).toBeGreaterThan(0)\n})\n\ntest('cursor-only continuations retain ownership and completion filters and conflicting links fail visibly', async () => {\n for (const resource of ['meetings', 'action_items']) {\n const calls: URL[] = []\n const env = circlebackEnv((url) => {\n calls.push(url)\n if (resource === 'action_items' && url.searchParams.get('status') === 'PENDING') return Response.json([])\n if (url.searchParams.has('cursor')) return Response.json(resource === 'meetings' ? [meeting] : [done])\n return Response.json([], { headers: { Link: `<${url.pathname}?cursor=next>; rel=\"next\"` } })\n })\n const pipeline = fixturePipeline()\n expect((await runIngestion(request(pipeline, resource), { ...env, journal: createMemoryJournal(), destination: createMemoryDestination(), now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n const continued = calls.at(-1)\n expect(continued?.searchParams.get('cursor')).toBe('next')\n if (resource === 'meetings') expect(continued?.searchParams.get('ownership')).toBe('All')\n else {\n expect(continued?.searchParams.get('status')).toBe('DONE')\n expect(continued?.searchParams.get('assigneeType')).toBe('Anyone')\n }\n }\n for (const [resource, conflict] of [['meetings', 'ownership=Mine'], ['action_items', 'status=DONE'], ['action_items', 'assigneeType=Me']] satisfies [string, string][]) {\n let calls = 0\n const env = circlebackEnv((url) => {\n calls++\n return Response.json([], { headers: { Link: `<${url.pathname}?cursor=next&${conflict}>; rel=\"next\"` } })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion(request(pipeline, resource), { ...env, journal, destination: createMemoryDestination(), now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect(calls).toBe(1)\n expect((await journal.readCheckpoint(`circleback.${resource}`)).lastSuccessSeq).toBe(0)\n }\n})\n\ntest('late transcripts on unchanged old meetings are revisited without running the meetings stream', async () => {\n let available = false\n const starts: string[] = [], calls: string[] = []\n const env = circlebackEnv((url) => {\n calls.push(url.pathname)\n if (url.pathname.endsWith('/transcript')) {\n if (!available) return new Response('unavailable', { status: url.pathname.includes('/meeting-a/') ? 403 : 404 })\n return Response.json(url.pathname.includes('/meeting-a/') ? transcript : [])\n }\n starts.push(url.search)\n return Response.json([meeting, { ...meeting, id: 'meeting-b' }])\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'meeting_transcripts')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n expect(destination.tables.get('default.circleback_meeting_transcripts_raw')?.map((row) => row.raw)).toEqual([\n { source_id: 'circleback', meeting_id: 'meeting-a', kind: 'availability', status: 'forbidden' },\n { source_id: 'circleback', meeting_id: 'meeting-b', kind: 'availability', status: 'not_found' },\n ])\n available = true\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => new Date('2026-01-03'), retry: { retries: 0 } })).ok).toBe(true)\n expect(starts).toEqual(['?ownership=All', '?ownership=All'])\n expect(calls.filter((path) => path.endsWith('/transcript'))).toHaveLength(4)\n expect(destination.tables.get('default.circleback_meeting_transcripts_raw')?.slice(-4).map((row) => row.raw)).toEqual([\n { source_id: 'circleback', kind: 'transcript', meeting_id: 'meeting-a', status: 'available', data: transcript },\n { source_id: 'circleback', meeting_id: 'meeting-a', kind: 'availability', status: 'available' },\n { source_id: 'circleback', kind: 'transcript', meeting_id: 'meeting-b', status: 'available', data: [] },\n { source_id: 'circleback', meeting_id: 'meeting-b', kind: 'availability', status: 'available' },\n ])\n expect((await journal.readCheckpoint('circleback.meetings')).lastSuccessSeq).toBe(0)\n expect((await journal.readCheckpoint('circleback.meeting_transcripts')).envelope).toBeUndefined()\n})\n\ntest('forbidden and not-found observations preserve prior transcript content while a successful empty transcript replaces it', async () => {\n let status = 200, empty = false\n const env = circlebackEnv((url) => url.pathname === '/api/meetings' ? Response.json([meeting])\n : status === 200 ? Response.json(empty ? [] : transcript) : new Response('unavailable', { status }))\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'meeting_transcripts')\n for (const nextStatus of [200, 403, 404, 200]) {\n status = nextStatus\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n const snapshots = destination.tables.get('default.circleback_meeting_transcripts_raw')?.filter((row) => row.id === rowId(meeting.id)) ?? []\n expect(snapshots.at(-1)?.raw).toMatchObject({ kind: 'transcript', status: 'available', data: empty ? [] : transcript })\n if (status === 404) empty = true\n }\n const rows = destination.tables.get('default.circleback_meeting_transcripts_raw') ?? []\n expect(rows.filter((row) => row.id === rowId(meeting.id))).toHaveLength(2)\n expect(rows.filter((row) => row.id !== rowId(meeting.id)).map((row) => row.raw)).toEqual(\n ['available', 'forbidden', 'not_found', 'available'].map((status) => ({ source_id: 'circleback', meeting_id: meeting.id, kind: 'availability', status })))\n expect(new Set(rows.map((row) => row.id)).size).toBe(2)\n})\n\ntest('a transcript source failure leaves its full sync incomplete while all other resource streams succeed', async () => {\n let fail = true\n const transcriptCalls: string[] = []\n const env = circlebackEnv((url, init) => {\n if (url.pathname.endsWith('/transcript')) {\n transcriptCalls.push(url.pathname)\n if (fail) return new Response('unavailable', { status: 500 })\n }\n return fixtureResponse(url, init)\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const failed = await runIngestion(request(pipeline), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })\n expect(failed.ok).toBe(false)\n expect(failed.streams.filter((stream) => stream.outcome === 'failed').map((stream) => stream.streamId)).toEqual(['circleback.meeting_transcripts'])\n expect(destination.tables.get('default.circleback_meetings_raw')?.[0]?.raw).toEqual(envelope({ ...meeting, tags: ['Customer', 'Follow up'] }))\n expect((await journal.readCheckpoint('circleback.meeting_transcripts')).lastSuccessSeq).toBe(0)\n for (const resource of resources.filter((resource) => resource !== 'meeting_transcripts')) {\n expect((await journal.readCheckpoint(`circleback.${resource}`)).lastSuccessSeq).toBeGreaterThan(0)\n }\n fail = false\n expect((await runIngestion(request(pipeline, 'meeting_transcripts'), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n expect(transcriptCalls).toEqual(['/api/meeting/meeting-a/transcript', '/api/meeting/meeting-a/transcript'])\n})\n\ntest('a failed transcript write replays its own parent discovery before recording successful completion', async () => {\n const starts: string[] = []\n const env = circlebackEnv((url, init) => {\n if (url.pathname === '/api/meetings') starts.push(url.search)\n return fixtureResponse(url, init)\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'meeting_transcripts')\n expect((await runIngestion(selected, { ...env, journal, destination: { insert: async () => { throw new Error('sink rejected') } }, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect((await journal.readCheckpoint('circleback.meeting_transcripts')).lastSuccessSeq).toBe(0)\n expect((await journal.readCheckpoint('circleback.meeting_transcripts')).envelope).toBeUndefined()\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n expect(starts).toEqual(['?ownership=All', '?ownership=All'])\n expect(destination.tables.get('default.circleback_meeting_transcripts_raw')).toHaveLength(2)\n})\n\ntest('full meeting reads replay from page one after source and sink failures and retain changed observations', async () => {\n let fail = true, changed = false\n const starts: string[] = [], second = { ...meeting, id: 'meeting-b' }\n const env = circlebackEnv((url) => {\n if (url.searchParams.has('cursor')) return fail ? new Response('denied', { status: 403 }) : Response.json([second])\n starts.push(url.search)\n return Response.json([{ ...meeting, notes: changed ? 'Edited without an updatedAt change' : meeting.notes }],\n { headers: { Link: '; rel=\"next\"' } })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'meetings')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect((await journal.readCheckpoint('circleback.meetings')).lastSuccessSeq).toBe(0)\n fail = false\n expect((await runIngestion(selected, { ...env, journal, destination: { insert: async () => { throw new Error('sink rejected') } }, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect((await journal.readCheckpoint('circleback.meetings')).lastSuccessSeq).toBe(0)\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n changed = true\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => new Date('2026-01-03'), retry: { retries: 0 } })).ok).toBe(true)\n expect(starts).toEqual(Array(4).fill('?ownership=All'))\n expect((await journal.readCheckpoint('circleback.meetings')).envelope).toBeUndefined()\n expect(destination.tables.get('default.circleback_meetings_raw')?.filter((row) => row.id === rowId('meeting-a')).map((row) => row.raw)).toEqual([\n envelope({ ...meeting, tags: ['Customer', 'Follow up'] }),\n envelope({ ...meeting, notes: 'Edited without an updatedAt change', tags: ['Customer', 'Follow up'] }),\n ])\n})\n\ntest('empty full resources record completion and scan again without custom provider state', async () => {\n const calls: string[] = [], env = circlebackEnv((url) => { calls.push(url.pathname); return Response.json([]) }), pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n for (const now of [cutoff, new Date('2026-01-03')]) {\n expect((await runIngestion(request(pipeline), { ...env, journal, destination, now: () => now, retry: { retries: 0 } })).ok).toBe(true)\n }\n expect(destination.tables.size).toBe(0)\n for (const resource of resources) {\n expect((await journal.readCheckpoint(`circleback.${resource}`)).envelope).toBeUndefined()\n expect(journal.events.filter((event) => event.namespaceId === `circleback.${resource}` && event.eventKind === 'work_finished' && event.workState === 'succeeded')).toHaveLength(2)\n }\n expect(calls.filter((path) => path === '/api/meetings')).toHaveLength(4)\n expect(calls.filter((path) => path === '/api/action-items')).toHaveLength(4)\n})\n\ntest('company domains stay stable while optional native numeric IDs preserve downstream joins', async () => {\n let identified = false\n const env = circlebackEnv((url) => url.pathname === '/api/companies'\n ? Response.json([{ ...company, ...(identified ? { id: 3 } : {}) }])\n : Response.json({ ...company, externalLinks: [], people: [] }))\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'companies')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(true)\n identified = true\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => new Date('2026-01-03'), retry: { retries: 0 } })).ok).toBe(true)\n const rows = destination.tables.get('default.circleback_companies_raw') ?? []\n expect(rows.map((row) => row.id)).toEqual([rowId('initech.com'), rowId('initech.com')])\n expect(rows.map((row) => row.raw)).toEqual([\n { source_id: 'circleback', company_id: null, data: { ...company, externalLinks: [], people: [] } },\n { source_id: 'circleback', company_id: 3, data: { ...company, id: 3, externalLinks: [], people: [] } },\n ])\n expect(new Set(rows.map((row) => row.id)).size).toBe(1)\n})\n\ntest('company detail failures and conflicting native IDs cannot complete or fabricate company joins', async () => {\n for (const mode of ['forbidden', 'conflicting', 'different-domain']) {\n const env = circlebackEnv((url) => {\n if (url.pathname === '/api/companies') return Response.json([{ ...company, id: 3 }])\n if (mode === 'forbidden') return new Response('denied', { status: 403 })\n return Response.json({ ...companyDetail, ...(mode === 'different-domain' ? { domain: 'other.example' } : { people: [{ ...person, companyId: 4 }] }) })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'companies'), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect(destination.tables.size).toBe(0)\n expect((await journal.readCheckpoint('circleback.companies')).lastSuccessSeq).toBe(0)\n }\n})\n\ntest('same-person detail retains raw external references and cannot publish a different or inaccessible person', async () => {\n for (const mode of ['denied', 'mismatched-id', 'missing-links']) {\n const calls: string[] = []\n const env = circlebackEnv((url) => {\n calls.push(url.pathname)\n if (url.pathname === '/api/people') return Response.json([person])\n if (mode === 'denied') return new Response('denied', { status: 403 })\n return Response.json({ ...personDetail, ...(mode === 'mismatched-id' ? { id: 2 } : { externalLinks: null }) })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'people'), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect(calls).toEqual(['/api/people', '/api/person/1'])\n expect(destination.tables.size).toBe(0)\n expect((await journal.readCheckpoint('circleback.people')).lastSuccessSeq).toBe(0)\n }\n})\n\ntest('factory configuration, tokens and selected resource progress stay independent between installations', async () => {\n const config: CirclebackReaderConfig = { ...fixtureConfig, sourceId: 'circleback.team', ownership: 'Shared', apiKey: 'team-key' }\n const calls: URL[] = []\n const env = circlebackEnv((url, init) => {\n if (new Headers(init.headers).get('authorization') !== 'Bearer team-key') return new Response('denied', { status: 403 })\n calls.push(url)\n return Response.json([meeting])\n })\n const pipeline = createCirclebackPipeline(config)\n config.sourceId = 'changed'\n config.ownership = 'Mine'\n config.apiKey = 'changed'\n const failing = createCirclebackPipeline({ ...fixtureConfig, sourceId: 'circleback.denied', apiKey: 'denied' })\n const selected = selectStreams([failing, pipeline], ['resource:meetings'])\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const result = await runIngestion({ selected, backfill: undefined }, { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })\n expect(result.streams.map((stream) => stream.outcome)).toEqual(['failed', 'succeeded'])\n expect(calls.map((url) => url.searchParams.get('ownership'))).toEqual(['Shared'])\n expect(destination.tables.get('default.circleback_meetings_raw')?.[0]?.id).toBe(rowId(meeting.id, 'circleback.team'))\n expect(destination.tables.get('default.circleback_meetings_raw')?.[0]?.raw).toEqual(envelope({ ...meeting, tags: ['Customer', 'Follow up'] }, 'circleback.team'))\n expect((await journal.readCheckpoint('circleback.denied.meetings')).lastSuccessSeq).toBe(0)\n expect((await journal.readCheckpoint('circleback.team.meetings')).lastSuccessSeq).toBeGreaterThan(0)\n const onlyTeam = selectStreams([failing, pipeline], ['stream:circleback.team.meetings'])\n expect(onlyTeam.map((entry) => entry.stream.id)).toEqual(['circleback.team.meetings'])\n expect((await journal.readCheckpoint('circleback.meetings')).lastSuccessSeq).toBe(0)\n})\n\ntest('empty Link pages continue while cyclic, cross-collection, foreign and malformed next links fail permanently', async () => {\n for (const mode of ['empty-first', 'same-initial', 'cyclic', 'cross-collection', 'foreign', 'malformed', 'multiple-next']) {\n const calls: string[] = []\n let details = 0\n const env = circlebackEnv((url) => {\n if (url.pathname.startsWith('/api/person/')) { details++; return Response.json(personDetail) }\n calls.push(url.toString())\n if (mode === 'empty-first' && url.searchParams.has('cursor')) return Response.json([person])\n if (mode === 'same-initial') return Response.json([person], { headers: { Link: `<${url.toString()}>; rel=\"next\"` } })\n const next = mode === 'foreign' ? 'https://untrusted.example/people' : mode === 'cross-collection' ? '/api/companies?cursor=next' : '/api/people?cursor=next'\n const link = mode === 'malformed' ? 'not-a-link; rel=\"next\"' : mode === 'multiple-next' ? `<${next}>; rel=\"next\", ; rel=\"next\"` : `<${next}>; rel=\"next\"`\n return Response.json([], { headers: { Link: link } })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const result = await runIngestion(request(pipeline, 'people'), { ...env, journal, destination, now: () => cutoff, retry: { retries: 1, minTimeout: 0, maxTimeout: 0 } })\n expect(result.ok).toBe(mode === 'empty-first')\n expect(calls).toHaveLength(['empty-first', 'cyclic'].includes(mode) ? 2 : 1)\n expect(details).toBe(mode === 'empty-first' ? 1 : 0)\n expect(destination.tables.size).toBe(mode === 'empty-first' ? 1 : 0)\n expect((await journal.readCheckpoint('circleback.people')).lastSuccessSeq > 0).toBe(mode === 'empty-first')\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0)\n }\n})\n\ntest('malformed collections, identities, tag names and unsupported action status cannot become successful full syncs', async () => {\n for (const [resource, payload] of [\n ['meetings', { error: 'bad payload' }], ['meetings', [{ ...meeting, id: '' }]], ['meetings', [{ ...meeting, tags: [{ id: 10 }] }]],\n ['people', [{ ...person, id: 1.5 }]], ['action_items', [{ ...pending, status: 'UNKNOWN' }]],\n ['action_items', [{ ...pending, status: 'DONE' }]], ['action_items', [{ ...pending, meetingIds: null }]],\n ] satisfies [string, unknown][]) {\n let calls = 0\n const env = circlebackEnv(() => { calls++; return Response.json(payload) })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion(request(pipeline, resource), { ...env, journal, destination: createMemoryDestination(), now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect(calls).toBe(1)\n expect((await journal.readCheckpoint(`circleback.${resource}`)).lastSuccessSeq).toBe(0)\n }\n})\n\ntest('HTTP200 malformed transcripts fail without publishing an availability snapshot or completing the stream', async () => {\n for (const payload of [null, { error: 'denied' }, [{ speaker: null, text: 'Words' }], [{ speaker: 3, text: 'Words', timestamp: 1 }], [{ speaker: null, text: {}, timestamp: 1 }]]) {\n let calls = 0\n const env = circlebackEnv((url) => {\n if (url.pathname === '/api/meetings') return Response.json([meeting])\n calls++\n return Response.json(payload)\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'meeting_transcripts'), { ...env, journal, destination, now: () => cutoff, retry: { retries: 0 } })).ok).toBe(false)\n expect(calls).toBe(1)\n expect(destination.tables.size).toBe(0)\n expect((await journal.readCheckpoint('circleback.meeting_transcripts')).lastSuccessSeq).toBe(0)\n }\n})\n\ntest('rate exhaustion consumes exactly one executor-owned page retry and malformed JSON remains permanent', async () => {\n for (const mode of ['rate', 'malformed-json']) {\n let calls = 0\n const env = circlebackEnv((url) => {\n if (url.pathname.startsWith('/api/person/')) return Response.json(personDetail)\n calls++\n if (mode === 'malformed-json') return new Response('{', { headers: { 'Content-Type': 'application/json' } })\n return calls === 1 ? new Response('rate limited', { status: 429, headers: { 'Retry-After': '0' } }) : Response.json([person])\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion(request(pipeline, 'people'), { ...env, journal, destination: createMemoryDestination(), now: () => cutoff, retry: { retries: 1, minTimeout: 0, maxTimeout: 0 } })).ok).toBe(mode === 'rate')\n expect(calls).toBe(mode === 'rate' ? 2 : 1)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(mode === 'rate' ? 1 : 0)\n }\n})\n\ntest('Circleback checks its configuration when a stream runs, not when the module loads or a stream is selected', async () => {\n let requests = 0\n const config = { ...fixtureConfig }\n Object.assign(config, { ownership: 'Everyone' })\n const pipeline = createCirclebackPipeline(config)\n const selected = selectStreams([pipeline], [])\n expect(selected).toHaveLength(5)\n const env = circlebackEnv(() => { requests++; return Response.json([]) })\n const result = await runIngestion({ selected, backfill: undefined }, { ...env, journal: createMemoryJournal(), destination: createMemoryDestination(), now: () => cutoff })\n expect(result.streams.every((stream) => stream.outcome === 'failed' && /at ownership/.test(stream.error ?? ''))).toBe(true)\n expect(requests).toBe(0)\n})\n\ntest('Circleback fails every stream before any request without an API key', async () => {\n for (const apiKey of [undefined, ' ']) {\n let requests = 0\n const env = circlebackEnv(() => { requests++; return Response.json([]) })\n const result = await runIngestion(request(fixturePipeline({ ...fixtureConfig, apiKey })), { ...env, journal: createMemoryJournal(), destination: createMemoryDestination(), now: () => cutoff, retry: { retries: 0 } })\n expect(result.streams).toHaveLength(5)\n expect(result.streams.every((stream) => stream.outcome === 'failed' && stream.error?.includes('Set CIRCLEBACK_API_KEY or pass apiKey.'))).toBe(true)\n expect(requests).toBe(0)\n }\n})\n\ntest('Circleback fails a malformed provider payload at once and retries only a transient response', async () => {\n const run = async (respond: Responder) => {\n const journal = createMemoryJournal()\n const result = await runIngestion(request(fixturePipeline(), 'meetings'), { ...circlebackEnv(respond), journal, destination: createMemoryDestination(), now: () => cutoff, retry: { retries: 2, minTimeout: 0 } })\n return { result, retries: journal.events.filter((event) => event.eventKind === 'retry_scheduled').map((event) => event.errorClass) }\n }\n let calls = 0\n const malformed = await run(() => { calls += 1; return Response.json({ error: 'bad payload' }) })\n expect(malformed.result.streams[0]?.outcome).toBe('failed')\n expect(malformed.result.streams[0]?.error).toContain('Invalid input: expected array, received object')\n expect(calls).toBe(1)\n expect(malformed.retries).toEqual([])\n\n let unavailable = true\n const flaky = await run((url, init) => {\n if (unavailable) { unavailable = false; return new Response('busy', { status: 503 }) }\n return fixtureResponse(url, init)\n })\n expect(flaky.result.ok).toBe(true)\n expect(flaky.retries).toEqual(['transient'])\n})\n\nfunction fixturePipeline(config: CirclebackReaderConfig = fixtureConfig): Pipeline {\n return createCirclebackPipeline(config)\n}\n\nfunction circlebackEnv(respond: Responder = fixtureResponse) {\n return { fetch: async (input: string | URL, init?: RequestInit) => respond(new URL(input), init ?? {}) }\n}\n\nfunction request(pipeline: Pipeline, resource?: string) {\n return { selected: selectStreams([pipeline], resource ? [`resource:${resource}`] : []).map((entry) => ({\n ...entry, stream: { ...entry.stream, batchSize: 1 },\n })), backfill: undefined }\n}\n\nfunction fixtureResponse(url: URL, _init: RequestInit): Response {\n if (url.pathname === '/api/meetings') return Response.json([meeting])\n if (url.pathname.endsWith('/transcript')) return Response.json(transcript)\n if (url.pathname === '/api/action-items') return Response.json(url.searchParams.get('status') === 'DONE' ? [done] : [pending])\n if (url.pathname === '/api/people') return Response.json([person])\n if (url.pathname === '/api/person/1') return Response.json(personDetail)\n if (url.pathname === '/api/companies') return Response.json([company])\n if (url.pathname === '/api/company/initech.com') return Response.json(companyDetail)\n throw new Error(`Unexpected Circleback fixture request: ${url}`)\n}\n\nfunction rowId(id: string | number, sourceId = 'circleback'): string { return JSON.stringify([sourceId, id]) }\nfunction envelope(data: unknown, sourceId = 'circleback') { return { source_id: sourceId, data } }\n\ntest('Circleback honors RateLimit-Reset over HTTP, gives Retry-After precedence, and respects the retry deadline', async () => {\n for (const scenario of [\n { headers: new Headers({ 'RateLimit-Reset': '1' }), maxRetryTime: 5_000, succeeds: true, minimumDelay: 900 },\n { headers: new Headers({ 'RateLimit-Reset': '3600', 'Retry-After': '0' }), maxRetryTime: 5_000, succeeds: true, minimumDelay: 0 },\n { headers: new Headers({ 'RateLimit-Reset': '3600' }), maxRetryTime: 100, succeeds: false, minimumDelay: 0 },\n { headers: new Headers({ 'RateLimit-Reset': 'invalid' }), maxRetryTime: 5_000, succeeds: true, minimumDelay: 0 },\n ]) {\n const requestedAt: number[] = []\n const server = Bun.serve({\n port: 0,\n fetch() {\n requestedAt.push(Date.now())\n return requestedAt.length === 1\n ? new Response('{\"error\":\"Rate limited\",\"code\":\"RATE_LIMITED\"}', { status: 429, headers: scenario.headers })\n : Response.json([meeting])\n },\n })\n try {\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const env = circlebackEnv((url, init) => fetch(`http://127.0.0.1:${server.port}${url.pathname}${url.search}`, init))\n const result = await runIngestion({ selected: selectStreams([fixturePipeline()], ['resource:meetings']), backfill: undefined }, {\n ...env, journal, destination, retry: { retries: 1, minTimeout: 0, maxTimeout: 0, maxRetryTime: scenario.maxRetryTime },\n })\n expect(result.ok).toBe(scenario.succeeds)\n expect(requestedAt).toHaveLength(scenario.succeeds ? 2 : 1)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled').map((event) => event.errorClass))\n .toEqual(scenario.succeeds ? ['rate_limited'] : [])\n if (scenario.minimumDelay > 0) expect((requestedAt[1] ?? 0) - (requestedAt[0] ?? 0)).toBeGreaterThanOrEqual(scenario.minimumDelay)\n expect(destination.tables.get('default.circleback_meetings_raw')?.length ?? 0).toBe(scenario.succeeds ? 1 : 0)\n } finally {\n server.stop(true)\n }\n }\n})\n" } ], "meta": { "chkit": { "formatVersion": 1, "version": "0.3.0", "changelog": [ { "version": "0.3.0", "changes": [ "Read configuration and the API key when a stream runs, so `generate`, `migrate`, and `chkit check` never depend on them; invalid settings or a missing API key fail that run before any request. Requires zod 4 and chkit 0.2.0-beta.12.", "Send requests through the ingestion runtime, which retries only network failures, timeouts, retryable HTTP statuses, and HTTP 429 rate limits; malformed payloads and invalid Link continuations fail at once.", "Set `apiKey` in the configuration to use another API key, for example for a second installation; it defaults to `CIRCLEBACK_API_KEY`." ] }, { "version": "0.2.1", "changes": [ "Add fixture-tested RateLimit-Reset seconds fallback on HTTP 429 when Retry-After is absent or not parsed by the shared HTTP parser, without changing permission failures or transcript availability handling.", "Clarify native JSON normalization of explicit null paths and empty objects, including nullable transcript speakers." ] }, { "version": "0.2.0", "changes": [ "Provide one configurable account pipeline with independent meetings, meeting transcripts, action items, people, and companies raw streams.", "Use native full-sync completion and safe first-page replay with scoped identities and validated Link pagination that preserves query filters.", "Revisit every eligible meeting for late transcripts; retain successful snapshots separately from forbidden/not-found read outcomes.", "Read action items for anyone across both native PENDING and DONE statuses; preserve people and company relationships without inventing numeric company IDs.", "Store complete tag names as string arrays and raw provider payloads in source-scoped envelopes; adopting this layout requires reingestion or migration of earlier unscoped meeting observations.", "Add portable fixtures for independently selected resources, reversed stream order, malformed responses, pagination, late transcripts, and source/destination recovery.", "Consume full pagination pages and use shared continuation-cycle detection while preserving independent resource checkpoints and provider Link validation." ] }, { "version": "0.1.0", "changes": [ "Introduce raw meeting ingestion with transcript enrichment." ] } ], "language": "typescript", "license": "MIT", "documentation": "https://chkit.obsessiondb.com/integrations/circleback/", "logo": "https://chkit.obsessiondb.com/logos/circleback.svg", "authentication": { "method": "Bearer API key", "env": [ "CIRCLEBACK_API_KEY" ], "setup": [ "Provide CIRCLEBACK_API_KEY with read access to the selected resources.", "Keep the API key in the runtime environment and rotate it according to the provider policy." ], "documentation": "https://circleback.ai/docs/api" }, "chkit": "^0.2.0-beta.12", "ingest": "^0.2.0-beta.12", "clickhouse": ">=25.3.0", "root": "src/integrations/circleback", "entry": "index.ts", "exports": [ "circlebackPipeline", "createCirclebackPipeline", "circleback_meetingsRaw", "circleback_meetingTranscriptsRaw", "circleback_actionItemsRaw", "circleback_peopleRaw", "circleback_companiesRaw" ], "resources": [ { "name": "meetings", "title": "Meetings", "table": "circleback_meetings_raw", "description": "Accessible meeting provider objects and notes, with tag names as string arrays.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/meetings", "documentation": "https://circleback.ai/docs/api/meetings/list-meetings" } ] }, { "name": "meeting_transcripts", "title": "Meeting transcripts", "table": "circleback_meeting_transcripts_raw", "description": "Whole transcript snapshots per meeting and separate latest read outcomes; availability failures preserve earlier successful text.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/meetings", "documentation": "https://circleback.ai/docs/api/meetings/list-meetings" }, { "method": "GET", "path": "/meeting/{meetingId}/transcript", "documentation": "https://circleback.ai/docs/api/meetings/get-meeting-transcript" } ] }, { "name": "action_items", "title": "Action items", "table": "circleback_action_items_raw", "description": "Raw action items for any assignee, fully paginated across PENDING and DONE completion statuses.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/action-items", "documentation": "https://circleback.ai/docs/api/action-items/list-action-items" } ] }, { "name": "people", "title": "People", "table": "circleback_people_raw", "description": "Complete same-person listing and detail fields, preserving external references and native person/company IDs.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/people", "documentation": "https://circleback.ai/docs/api/people/list-people" }, { "method": "GET", "path": "/person/{profileId}", "documentation": "https://circleback.ai/docs/api/people/get-person" } ] }, { "name": "companies", "title": "Companies", "table": "circleback_companies_raw", "description": "Domain-keyed company listing and detail fields with a nullable, corroborated native numeric company ID for joins.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/companies", "documentation": "https://circleback.ai/docs/api/companies/list-companies" }, { "method": "GET", "path": "/company/{domain}", "documentation": "https://circleback.ai/docs/api/companies/get-company" } ] } ], "views": [], "sync": { "description": "Each resource fully reads its own provider collection and records independent successful completion after writes. Interrupted reads restart at the first page. Transcripts own complete meeting discovery and revisit late availability on unchanged old meetings.", "schedule": "Run bunx chkit ingest run --tag provider:circleback from a scheduler.", "deletions": "Absent resources remain stored. Transcript 403 and 404 responses update explicit read outcomes without deleting prior successful content; neither proves deletion or temporary processing." }, "env": { "CIRCLEBACK_API_KEY": "" }, "fileHashes": { "src/integrations/circleback/README.md": "5edcea8669a93fd6b9eb8c4c18eabf8bbc7ccf60443d0d848b0c28b115b5b833", "src/integrations/circleback/index.ts": "dbab97785e5fb11775ad7062076237e2e6af2c8bbdafd8c7e71e92b957b81a5c", "src/integrations/circleback/config.ts": "c923a7791e99e556eaa7afebd9724719c2f24b9de7fa9be9fd990f6e19bf23a8", "src/integrations/circleback/client.ts": "cd3f9b3a2cf8a1dda91da43d2c4dfd5d87cea48c10ef80dc48f3e13b96860fdb", "src/integrations/circleback/pipeline.ts": "59fb2de3e42de24a2f75ba4cb0f8e5ebf3feb4680d9663ef1d1960b13d855315", "src/integrations/circleback/sources/meetings.ts": "7f33567650b19db2588c34f184c22f093e1a5ec66170346af6a22ba11279e489", "src/integrations/circleback/sources/meeting-transcripts.ts": "ddb42e072656eb657e267c062d91fc87ebe9ae8a3961a8eb0479e5cc9f6187cc", "src/integrations/circleback/sources/action-items.ts": "4d092153ee1cfedc67e7e5e85594315a3c77cfb12e1f06d6062c537e97e1a256", "src/integrations/circleback/sources/people.ts": "cd2a20409bb587c1eaf6d8f960b616183774f4cb6bd9d06c87001367fcdf7c47", "src/integrations/circleback/sources/companies.ts": "55ace4e5f8948b80289062096b5ff088c6449aea1601282d8c5b6259bfd5e543", "src/integrations/circleback/tests/basic.test.ts": "fc628e011a0773ba052c8eae3f819d871a3a8f63806c027faaf44c49bc2e64c7" } } } }