From 84390269d232ce3ae66503ffe17c795c1fe0d948 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 09:49:00 -0600 Subject: [PATCH 01/20] chore(checks): ban named randomUUID imports from node:crypto in check:utils (cherry picked from commit 3f7d50182d96129ca940a0296563decabd65568b) --- scripts/check-utils-enforcement.test.ts | 22 ++++++++++++++++++++++ scripts/check-utils-enforcement.ts | 14 +++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/scripts/check-utils-enforcement.test.ts b/scripts/check-utils-enforcement.test.ts index 680fc09b3eb..c91867b358c 100644 --- a/scripts/check-utils-enforcement.test.ts +++ b/scripts/check-utils-enforcement.test.ts @@ -27,6 +27,28 @@ describe('helper-source exemptions', () => { }) }) +describe('randomUUID imports', () => { + it('rejects a named randomUUID import from either crypto specifier, also wrapped or renamed', () => { + const source = [ + "import { randomUUID } from 'node:crypto'", + 'import { createHash, randomUUID as uuid } from "crypto"', + 'import {', + ' randomBytes,', + ' randomUUID,', + "} from 'node:crypto'", + ].join('\n') + expect(descriptions('apps/sim/lib/example.ts', source)).toHaveLength(3) + }) + + it('leaves other crypto imports and other modules exporting the name alone', () => { + const source = [ + "import { randomBytes } from 'node:crypto'", + "import { randomUUID } from '@/lib/testing/ids'", + ].join('\n') + expect(descriptions('apps/sim/lib/example.ts', source)).toEqual([]) + }) +}) + describe('record coercion', () => { it('rejects the inline forms of toRecord and toRecordOrNull, including wrapped ones', () => { const source = [ diff --git a/scripts/check-utils-enforcement.ts b/scripts/check-utils-enforcement.ts index b2c1bb82b51..31e12788f55 100644 --- a/scripts/check-utils-enforcement.ts +++ b/scripts/check-utils-enforcement.ts @@ -14,9 +14,11 @@ * names nothing else uses are also matched in source, since tsc accepts them on an `any` receiver. * * Biome's noRestrictedImports covers the import-based bans it lists — today `nanoid` and - * `uuid`. It does NOT cover named crypto imports; `import { randomBytes } from 'node:crypto'` - * passes both gates, and deliberately so, since server code building cipher IVs and tokens - * wants node's crypto rather than the cross-context wrapper in `@sim/utils/random`. + * `uuid`. It does NOT cover named crypto imports, so this script bans the one that replaces an + * id helper: `import { randomUUID } from 'node:crypto'` (or `'crypto'`) is the same call as + * `crypto.randomUUID()` under another name. `import { randomBytes } from 'node:crypto'` stays + * allowed, deliberately, since server code building cipher IVs and tokens wants node's crypto + * rather than the cross-context wrapper in `@sim/utils/random`. * * Patterns are matched against the whole file, not line by line: every idiom banned here is a * multi-token expression that the formatter wraps at 100 columns, and a line-scoped scan sees @@ -97,6 +99,12 @@ const BANNED_PATTERNS: Array<{ suggestion: 'generateId() or generateShortId() from @sim/utils/id', replacesHelper: true, }, + { + pattern: /\bimport\s*\{[^}]*\brandomUUID\b[^}]*\}\s*from\s*['"](?:node:)?crypto['"]/g, + description: "import { randomUUID } from 'node:crypto'", + suggestion: 'generateId() or generateShortId() from @sim/utils/id', + replacesHelper: true, + }, { pattern: /\bcrypto\.randomBytes\s*\(/g, description: 'crypto.randomBytes()', From b0cab16b340c411f964633cbd1109d3c66ee7f19 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 09:50:13 -0600 Subject: [PATCH 02/20] chore(checks): ban snapshot matchers in check:test-patterns (cherry picked from commit 5c3f3c0d0d1525445367103ff5a99cf6ad7b062c) --- scripts/check-test-patterns.test.ts | 33 +++++++++++++++++++++++++++++ scripts/check-test-patterns.ts | 30 ++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/scripts/check-test-patterns.test.ts b/scripts/check-test-patterns.test.ts index 76b0b9e9b05..66fbf7c0816 100644 --- a/scripts/check-test-patterns.test.ts +++ b/scripts/check-test-patterns.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { findRealWaitViolations, + findSnapshotViolations, findStubAndHookViolations, parseSource, } from './check-test-patterns' @@ -385,3 +386,35 @@ describe('real-wait', () => { } ) }) + +describe('snapshot', () => { + function snapshots(source: string, file = 'apps/sim/lib/example.test.ts') { + return findSnapshotViolations(file, parseSource(file, source)).map(({ detail }) => detail) + } + + it('flags every snapshot matcher, negated, awaited or chained through resolves', () => { + const source = [ + 'expect(render()).toMatchSnapshot()', + "expect(value).toMatchInlineSnapshot(`'a'`)", + 'expect(value).not.toMatchSnapshot()', + 'await expect(promise).resolves.toMatchInlineSnapshot()', + 'expect(value)?.toMatchSnapshot()', + ].join('\n') + expect(snapshots(source)).toEqual([ + 'toMatchSnapshot #1', + 'toMatchInlineSnapshot #2', + 'toMatchSnapshot #3', + 'toMatchInlineSnapshot #4', + 'toMatchSnapshot #5', + ]) + }) + + it('leaves specific assertions and the word in strings alone', () => { + const source = [ + "expect(value).toEqual({ id: 'a' })", + "expect(value).toMatchObject({ id: 'a' })", + "const name = 'toMatchSnapshot'", + ].join('\n') + expect(snapshots(source)).toEqual([]) + }) +}) diff --git a/scripts/check-test-patterns.ts b/scripts/check-test-patterns.ts index 622bfba77ab..ca89dac2b10 100644 --- a/scripts/check-test-patterns.ts +++ b/scripts/check-test-patterns.ts @@ -20,6 +20,10 @@ * with no fake timers in scope. Integration and `*.live.test.ts` files wait on real Postgres, * Redis and external services, whose time is real, so the rule skips them; e2e scripts and * Playwright specs are not `*.test.ts` files and are never scanned. + * - `snapshot`: a test asserts with `toMatchSnapshot` or `toMatchInlineSnapshot`. A snapshot + * restates whatever the code produced when it was recorded, so it passes first time, breaks on + * every refactor, and is re-recorded rather than read; assert the specific property the test + * exists to prove instead (CLAUDE.md "Testing"). * * A central mock, or a global mock in `apps/sim/vitest.setup.ts`, that `vi.mock`s an `@/…` module * id that no longer resolves fails outright: it mocks nothing, and a dead central `@example` id @@ -451,6 +455,29 @@ function inEffect(timer: Site, target: Site): boolean { return !(other.kind === 'beforeEach' && earlierSibling) } +const SNAPSHOT_MATCHERS = new Set(['toMatchSnapshot', 'toMatchInlineSnapshot']) + +/** `snapshot` violations in one test file: every snapshot matcher call, numbered per file. */ +export function findSnapshotViolations( + file: string, + program: ReturnType +): Violation[] { + const violations: Violation[] = [] + walk(program, (node) => { + if (node.type !== 'CallExpression' && node.type !== 'OptionalCallExpression') return + const callee = node.callee as Node + if (callee.type !== 'MemberExpression' && callee.type !== 'OptionalMemberExpression') return + const property = callee.property as { type: string; name?: string } + if (property.type !== 'Identifier' || !SNAPSHOT_MATCHERS.has(property.name ?? '')) return + violations.push({ + file, + rule: 'snapshot', + detail: `${property.name} #${violations.length + 1}`, + }) + }) + return violations +} + /** * `real-wait` violations in one unit test file: a call that waits on the wall clock — `sleep` or * `interruptibleSleep` from `@sim/utils/helpers`, `setTimeout` from `node:timers/promises` (named @@ -706,6 +733,7 @@ function collect(globals: Set, declaredCentralIds: Set): Violati violations.push(...findStubAndHookViolations(file, program)) violations.push(...findRealWaitViolations(file, program)) + violations.push(...findSnapshotViolations(file, program)) walk(program, (node) => { const id = mockedId(node) @@ -766,6 +794,8 @@ const FIX: Record = { 'module-scope-stub': 'move the stub into a beforeEach or the test; the shared config undoes it before the first test', 'test-dir': 'move the test next to its source file', + snapshot: + 'assert the specific value or property the test exists to prove; a snapshot restates the output and is re-recorded, not read', 'real-wait': 'replace the wall-clock wait: vi.useFakeTimers() + await vi.advanceTimersByTimeAsync(ms) for ' + 'time-based code, await vi.waitFor(() => …) for a condition, or flushMicrotasks()/flushMacrotask() ' + From 97633200ba4559e9b46f553fce513b53649c30bd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 09:53:26 -0600 Subject: [PATCH 03/20] chore(checks): ratchet LRU ceilings, v2 raw responses, non-barrel re-exports and route audit in check:source-conventions lru-cache-ceiling and v2-raw-response are zero-tolerance (empty baseline). The two v2 upload routes that built a bare 204 now return the new v2NoContent helper, which adds the private no-store header every v2 response carries. non-barrel-reexport (57) and route-audit (53) are baselined; --init-rule is now repeatable. (cherry picked from commit 2259f40b41cada711c43b1c78f97b13adf4b9d7d) --- .agents/skills/v2-api-conventions/SKILL.md | 2 +- apps/sim/app/api/v2/lib/response.ts | 5 + .../[uploadId]/parts/[partNumber]/route.ts | 5 +- .../app/api/v2/uploads/[uploadId]/route.ts | 11 +- .../check-source-conventions.baseline.json | 97 ++++++++++- scripts/check-source-conventions.test.ts | 125 +++++++++++++- scripts/check-source-conventions.ts | 160 ++++++++++++++++-- 7 files changed, 386 insertions(+), 19 deletions(-) diff --git a/.agents/skills/v2-api-conventions/SKILL.md b/.agents/skills/v2-api-conventions/SKILL.md index 68bee751466..e49c004271c 100644 --- a/.agents/skills/v2-api-conventions/SKILL.md +++ b/.agents/skills/v2-api-conventions/SKILL.md @@ -30,7 +30,7 @@ Each rule below guards a caller-visible failure: a non-integer `limit` reaching ## Rule 1 — the envelope is produced by helpers, never by hand -`v2Data`, `v2Error`, and the typed error helpers in `response.ts` (`v2ValidationError`, `v2RateLimitError`, `v2HttpError`, `v2InsufficientScope`, `v2HeadNoEffect`, `v2UploadDataPlaneError`) are the only things that build a v2 body. They also set `Cache-Control: private, no-store`, which every v2 response needs because every v2 response is authed per-caller data. +`v2Data`, `v2Error`, and the typed error helpers in `response.ts` (`v2ValidationError`, `v2RateLimitError`, `v2HttpError`, `v2InsufficientScope`, `v2HeadNoEffect`, `v2NoContent`, `v2UploadDataPlaneError`) are the only things that build a v2 body. They also set `Cache-Control: private, no-store`, which every v2 response needs because every v2 response is authed per-caller data. A route built with `defineV2JsonRoute` gets this for free: its `present` returns the *body shape* and the builder renders it. Never call `NextResponse.json` from a v2 route. diff --git a/apps/sim/app/api/v2/lib/response.ts b/apps/sim/app/api/v2/lib/response.ts index 0ea4d16c24b..2b83ec23dd1 100644 --- a/apps/sim/app/api/v2/lib/response.ts +++ b/apps/sim/app/api/v2/lib/response.ts @@ -165,6 +165,11 @@ export function v2HeadNoEffect(options: V2SuccessOptions = {}): NextResponse { return new NextResponse(null, { status: options.status ?? 200, headers: successHeaders(options) }) } +/** A bodiless `204 No Content` (+ rate-limit headers), for a write with nothing to return. */ +export function v2NoContent(options: Omit = {}): NextResponse { + return new NextResponse(null, { status: 204, headers: successHeaders(options) }) +} + /** `{ data }` (+ rate-limit headers). */ export function v2Data(data: T, options: V2SuccessOptions = {}): NextResponse { return NextResponse.json( diff --git a/apps/sim/app/api/v2/uploads/[uploadId]/parts/[partNumber]/route.ts b/apps/sim/app/api/v2/uploads/[uploadId]/parts/[partNumber]/route.ts index 324db24ea98..9a2b20aa1bd 100644 --- a/apps/sim/app/api/v2/uploads/[uploadId]/parts/[partNumber]/route.ts +++ b/apps/sim/app/api/v2/uploads/[uploadId]/parts/[partNumber]/route.ts @@ -1,5 +1,5 @@ import { createLogger } from '@sim/logger' -import { type NextRequest, NextResponse } from 'next/server' +import type { NextRequest, NextResponse } from 'next/server' import { localUploadPartContract } from '@/lib/api/contracts/upload-sessions' import { parseRequest } from '@/lib/api/server' import { V2_PARSE_DEFAULTS } from '@/lib/api/server/routes' @@ -18,6 +18,7 @@ import { v2CaughtOrchestrationError, v2Error, v2HttpError, + v2NoContent, v2UploadDataPlaneError, } from '@/app/api/v2/lib/response' @@ -116,7 +117,7 @@ export const PUT = withRouteHandler( error, }) } - return new NextResponse(null, { status: 204 }) + return v2NoContent() }, { typedErrorResponse: ({ error }) => v2HttpError(error), diff --git a/apps/sim/app/api/v2/uploads/[uploadId]/route.ts b/apps/sim/app/api/v2/uploads/[uploadId]/route.ts index e8ae73eb777..d328b7d81ec 100644 --- a/apps/sim/app/api/v2/uploads/[uploadId]/route.ts +++ b/apps/sim/app/api/v2/uploads/[uploadId]/route.ts @@ -1,5 +1,5 @@ import { createLogger } from '@sim/logger' -import { type NextRequest, NextResponse } from 'next/server' +import type { NextRequest, NextResponse } from 'next/server' import { localPutUploadContract } from '@/lib/api/contracts/upload-sessions' import { parseRequest } from '@/lib/api/server' import { V2_PARSE_DEFAULTS } from '@/lib/api/server/routes' @@ -10,7 +10,12 @@ import { getOwnedUploadSession, uploadSessionObjectMetadata, } from '@/lib/uploads/upload-session/service' -import { v2Error, v2HttpError, v2UploadDataPlaneError } from '@/app/api/v2/lib/response' +import { + v2Error, + v2HttpError, + v2NoContent, + v2UploadDataPlaneError, +} from '@/app/api/v2/lib/response' const logger = createLogger('LocalUpload') @@ -106,7 +111,7 @@ export const PUT = withRouteHandler( error, }) } - return new NextResponse(null, { status: 204 }) + return v2NoContent() }, { typedErrorResponse: ({ error }) => v2HttpError(error), diff --git a/scripts/check-source-conventions.baseline.json b/scripts/check-source-conventions.baseline.json index e8a9c331e65..28accf47208 100644 --- a/scripts/check-source-conventions.baseline.json +++ b/scripts/check-source-conventions.baseline.json @@ -650,5 +650,100 @@ "bare-route-handler": { "apps/sim/app/api/health/route.ts": 1 }, - "log-message-tag": {} + "log-message-tag": {}, + "lru-cache-ceiling": {}, + "v2-raw-response": {}, + "non-barrel-reexport": { + "apps/sim/app/_shell/providers/query-provider.tsx": 1, + "apps/sim/app/workspace/[workspaceId]/components/resource/components/floating-overflow-text.tsx": 1, + "apps/sim/app/workspace/[workspaceId]/home/components/user-input/user-input.tsx": 1, + "apps/sim/app/workspace/[workspaceId]/home/types.ts": 1, + "apps/sim/app/workspace/[workspaceId]/settings/components/settings-header/settings-header.tsx": 1, + "apps/sim/app/workspace/[workspaceId]/settings/components/settings-panel/settings-panel.tsx": 1, + "apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types.ts": 1, + "apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/search-modal/search-modal.tsx": 1, + "apps/sim/blocks/types.ts": 1, + "apps/sim/content/blog/agent-as-yjs-peer/components.tsx": 1, + "apps/sim/content/blog/v0-5/components.tsx": 1, + "apps/sim/ee/access-control/utils/permission-check.ts": 1, + "apps/sim/executor/utils/resolved-secret-content-projection.ts": 1, + "apps/sim/hooks/queries/workflows.ts": 1, + "apps/sim/lib/api/contracts/custom-blocks.ts": 2, + "apps/sim/lib/api/contracts/data-drains.ts": 1, + "apps/sim/lib/api/contracts/invitations.ts": 1, + "apps/sim/lib/api/contracts/knowledge/search.ts": 1, + "apps/sim/lib/api/contracts/organization.ts": 2, + "apps/sim/lib/billing/organizations/membership.ts": 2, + "apps/sim/lib/execution/payloads/large-array-manifest.ts": 1, + "apps/sim/lib/guardrails/validate-pii.ts": 1, + "apps/sim/lib/integrations/availability.server.ts": 1, + "apps/sim/lib/integrations/availability.ts": 2, + "apps/sim/lib/invitations/core.ts": 1, + "apps/sim/lib/knowledge/connectors/sync-engine.ts": 1, + "apps/sim/lib/knowledge/documents/processing-claim.ts": 1, + "apps/sim/lib/knowledge/embedding-models.ts": 2, + "apps/sim/lib/messaging/email/mailer.ts": 1, + "apps/sim/lib/mothership/request/session/abort.ts": 2, + "apps/sim/lib/mothership/request/session/file-preview-session.ts": 2, + "apps/sim/lib/mothership/resources/persistence.ts": 2, + "apps/sim/lib/permission-groups/capability-assertions.ts": 1, + "apps/sim/lib/pptx-renderer/core/viewer.ts": 1, + "apps/sim/lib/pptx-renderer/utils/color.ts": 1, + "apps/sim/lib/resource-policies/types.ts": 1, + "apps/sim/lib/table/constants.ts": 1, + "apps/sim/lib/table/query-builder/constants.ts": 1, + "apps/sim/lib/table/workflow-columns.ts": 1, + "apps/sim/lib/uploads/config.ts": 1, + "apps/sim/lib/uploads/core/storage-client.ts": 1, + "apps/sim/lib/uploads/upload-session/provider.ts": 1, + "apps/sim/lib/workflows/autolayout/types.ts": 1, + "apps/sim/lib/workflows/executor/enqueue-execution.ts": 1, + "apps/sim/lib/workflows/persistence/utils.ts": 1, + "apps/sim/lib/workspace-files/search/pattern.ts": 1, + "apps/sim/lib/workspaces/policy.ts": 1, + "apps/sim/stores/workflows/workflow/types.ts": 1, + "apps/sim/tools/utils.ts": 1 + }, + "route-audit": { + "apps/sim/app/api/billing/switch-plan/route.ts": 1, + "apps/sim/app/api/chat/manage/[id]/password/route.ts": 1, + "apps/sim/app/api/environment/route.ts": 1, + "apps/sim/app/api/files/export/[id]/route.ts": 1, + "apps/sim/app/api/files/uploads/finalizers.ts": 2, + "apps/sim/app/api/folders/[id]/duplicate/route.ts": 1, + "apps/sim/app/api/invitations/[id]/reject/route.ts": 1, + "apps/sim/app/api/invitations/[id]/route.ts": 1, + "apps/sim/app/api/organizations/[id]/transfer-ownership/route.ts": 2, + "apps/sim/app/api/organizations/route.ts": 1, + "apps/sim/app/api/schedules/[id]/route.ts": 1, + "apps/sim/app/api/table/[tableId]/export/route.ts": 1, + "apps/sim/app/api/tools/custom/route.ts": 2, + "apps/sim/app/api/users/me/subscription/[id]/transfer/route.ts": 1, + "apps/sim/app/api/v1/admin/access-control/route.ts": 1, + "apps/sim/app/api/v1/admin/credits/route.ts": 1, + "apps/sim/app/api/v1/admin/organizations/[id]/data-retention/route.ts": 1, + "apps/sim/app/api/v1/admin/organizations/[id]/members/[memberId]/route.ts": 2, + "apps/sim/app/api/v1/admin/organizations/[id]/members/route.ts": 2, + "apps/sim/app/api/v1/admin/organizations/[id]/route.ts": 2, + "apps/sim/app/api/v1/admin/organizations/[id]/session-policy/route.ts": 1, + "apps/sim/app/api/v1/admin/organizations/[id]/transfer-ownership/route.ts": 1, + "apps/sim/app/api/v1/admin/organizations/route.ts": 1, + "apps/sim/app/api/v1/admin/workflows/export/route.ts": 1, + "apps/sim/app/api/v1/admin/workspaces/[id]/export/route.ts": 1, + "apps/sim/app/api/v1/admin/workspaces/[id]/members/[memberId]/route.ts": 2, + "apps/sim/app/api/v1/admin/workspaces/[id]/members/route.ts": 3, + "apps/sim/app/api/v1/files/route.ts": 1, + "apps/sim/app/api/v1/tables/[tableId]/columns/route.ts": 2, + "apps/sim/app/api/v1/tables/route.ts": 1, + "apps/sim/app/api/v1/workflows/[id]/export/route.ts": 1, + "apps/sim/app/api/webhooks/[id]/route.ts": 1, + "apps/sim/app/api/webhooks/route.ts": 1, + "apps/sim/app/api/workflows/[id]/duplicate/route.ts": 1, + "apps/sim/app/api/workflows/[id]/variables/route.ts": 1, + "apps/sim/app/api/workspaces/[id]/api-keys/route.ts": 1, + "apps/sim/app/api/workspaces/[id]/byok-keys/route.ts": 2, + "apps/sim/app/api/workspaces/[id]/environment/route.ts": 2, + "apps/sim/app/api/workspaces/[id]/route.ts": 2, + "apps/sim/app/api/workspaces/route.ts": 1 + } } diff --git a/scripts/check-source-conventions.test.ts b/scripts/check-source-conventions.test.ts index 2563c702540..d473d04bb2c 100644 --- a/scripts/check-source-conventions.test.ts +++ b/scripts/check-source-conventions.test.ts @@ -474,6 +474,107 @@ describe('log-message-tag', () => { }) }) +describe('lru-cache-ceiling', () => { + const MODULE = 'packages/feature/src/cache.ts' + + it('flags a cache whose options set no ceiling of their own', () => { + const source = [ + 'const a = new LRUCache({ ttl: 1000 })', + 'const b = new LRUCache({ ...shared, ttl: 1000 })', + 'const c = new LRUCache(options)', + 'const d = new lru.LRUCache({ ttlAutopurge: true, ttl: 1000 })', + ].join('\n') + expect(lines(MODULE, source, 'lru-cache-ceiling')).toEqual([1, 2, 3, 4]) + }) + + it('allows max or maxSize as a literal key, however the options are cast', () => { + const source = [ + 'const a = new LRUCache({ max: 500, ttl: 1000 })', + 'const b = new LRUCache({ ...shared, maxSize: 1024, sizeCalculation: (v) => v.length })', + "const c = new LRUCache({ 'max': 10 } as Options)", + 'const d = new Map()', + ].join('\n') + expect(hits(MODULE, source, 'lru-cache-ceiling')).toEqual([]) + expect( + hits('packages/feature/src/cache.test.ts', 'new LRUCache({})', 'lru-cache-ceiling') + ).toEqual([]) + }) +}) + +describe('v2-raw-response', () => { + const ROUTE = 'apps/sim/app/api/v2/things/route.ts' + + it('flags every hand-built JSON or empty response under app/api/v2', () => { + const source = [ + 'return NextResponse.json({ data })', + 'return Response.json({ error })', + 'return new NextResponse(null, { status: 204 })', + ].join('\n') + expect(hits(ROUTE, source, 'v2-raw-response')).toEqual([ + 'NextResponse.json', + 'Response.json', + 'new NextResponse', + ]) + expect(hits('apps/sim/app/api/v2/things/helpers.ts', source, 'v2-raw-response')).toHaveLength(3) + }) + + it('exempts the v2 response helpers, streams, tests, and routes outside v2', () => { + const raw = 'return NextResponse.json({ data })' + expect(hits('apps/sim/app/api/v2/lib/response.ts', raw, 'v2-raw-response')).toEqual([]) + expect(hits('apps/sim/app/api/v2/things/route.test.ts', raw, 'v2-raw-response')).toEqual([]) + expect(hits('apps/sim/app/api/things/route.ts', raw, 'v2-raw-response')).toEqual([]) + const stream = 'return new Response(stream, { headers })\nreturn v2Data(row)' + expect(hits(ROUTE, stream, 'v2-raw-response')).toEqual([]) + }) +}) + +describe('non-barrel-reexport', () => { + const MODULE = 'apps/sim/lib/feature/service.ts' + + it('flags every re-export form in a module that is not a barrel', () => { + const source = [ + "export { a } from '@/lib/other/a'", + "export type { B } from '@/lib/other/b'", + "export * from '@/lib/other/c'", + "export * as d from '@/lib/other/d'", + ].join('\n') + expect(hits(MODULE, source, 'non-barrel-reexport')).toEqual([ + '@/lib/other/a', + '@/lib/other/b', + '@/lib/other/c', + '@/lib/other/d', + ]) + }) + + it('allows barrels, local exports, tests, and code outside apps/sim', () => { + const reExport = "export { a } from '@/lib/other/a'" + expect(hits('apps/sim/lib/feature/index.ts', reExport, 'non-barrel-reexport')).toEqual([]) + expect(hits('apps/sim/lib/feature/index.tsx', reExport, 'non-barrel-reexport')).toEqual([]) + expect(hits('apps/sim/lib/feature/service.test.ts', reExport, 'non-barrel-reexport')).toEqual( + [] + ) + expect(hits('packages/feature/src/service.ts', reExport, 'non-barrel-reexport')).toEqual([]) + const local = "import { a } from '@/lib/other/a'\nexport const b = a + 1\nexport { b as c }" + expect(hits(MODULE, local, 'non-barrel-reexport')).toEqual([]) + }) +}) + +describe('route-audit', () => { + const ROUTE = 'apps/sim/app/api/things/route.ts' + + it('flags recordAudit in a route or a helper beside it, bare or through a namespace', () => { + const source = ['recordAudit({ action })', 'await audit.recordAudit({ action })'].join('\n') + expect(lines(ROUTE, source, 'route-audit')).toEqual([1, 2]) + expect(lines('apps/sim/app/api/things/utils.ts', source, 'route-audit')).toEqual([1, 2]) + }) + + it('leaves application use cases and tests alone', () => { + const source = 'recordAudit({ action })' + expect(hits('apps/sim/lib/things/application/create.ts', source, 'route-audit')).toEqual([]) + expect(hits('apps/sim/app/api/things/route.test.ts', source, 'route-audit')).toEqual([]) + }) +}) + describe('baseline ratchet', () => { const EMPTY: CurrentCounts = { 'relative-import': {}, @@ -482,6 +583,10 @@ describe('baseline ratchet', () => { 'api-db-import': {}, 'bare-route-handler': {}, 'log-message-tag': {}, + 'lru-cache-ceiling': {}, + 'v2-raw-response': {}, + 'non-barrel-reexport': {}, + 'route-audit': {}, } const counts = (partial: Partial): CurrentCounts => ({ ...EMPTY, ...partial }) const BASELINE: Baseline = { ...EMPTY, 'relative-import': { 'a.ts': 2, 'b.ts': 1 } } @@ -562,10 +667,28 @@ describe('baseline ratchet', () => { }) }) + it('admits several untracked rules at once when --init-rule is repeated', () => { + const { 'bare-route-handler': _a, 'static-inline-style': _b, ...untracked } = BASELINE + const current = counts({ + 'relative-import': BASELINE['relative-import'], + 'bare-route-handler': { 'route.ts': 2 }, + 'static-inline-style': { 'a.tsx': 1 }, + }) + expect(nextBaseline(untracked, current, ['bare-route-handler', 'static-inline-style'])).toEqual( + { + baseline: { + ...BASELINE, + 'bare-route-handler': { 'route.ts': 2 }, + 'static-inline-style': { 'a.tsx': 1 }, + }, + } + ) + }) + it('rejects an --init-rule that names no rule', () => { expect(nextBaseline(BASELINE, EMPTY, 'no-such-rule')).toEqual({ errors: [ - '--init-rule no-such-rule: not a rule in this script (relative-import, text-size-literal, static-inline-style, api-db-import, bare-route-handler, log-message-tag)', + '--init-rule no-such-rule: not a rule in this script (relative-import, text-size-literal, static-inline-style, api-db-import, bare-route-handler, log-message-tag, lru-cache-ceiling, v2-raw-response, non-barrel-reexport, route-audit)', ], }) }) diff --git a/scripts/check-source-conventions.ts b/scripts/check-source-conventions.ts index ba4ce7ce89d..275e62187be 100644 --- a/scripts/check-source-conventions.ts +++ b/scripts/check-source-conventions.ts @@ -39,13 +39,32 @@ * background tasks that bind one; elsewhere pass it as a field. A bracketed list mid-message * (`columns [${ids.join(', ')}]`) is not a tag. Unlike the rules above, this one covers every * `apps/*` and `packages/*` module that imports `@sim/logger`, not only `apps/sim`. + * - `lru-cache-ceiling` (`.claude/rules/sim-caching.md`): a `new LRUCache(…)` in any `apps/*` or + * `packages/*` module whose options object does not set `max` or `maxSize` as its own literal + * key. `ttl` alone does not bound memory: an expired entry lingers until its key is touched or a + * ceiling evicts it. Options passed as a variable or only through a spread cannot be shown to + * carry a ceiling, so they count too. + * - `v2-raw-response` (`.agents/skills/v2-api-conventions`): a module under `app/api/v2/` builds a + * response with `NextResponse.json(…)`, `Response.json(…)` or `new NextResponse(…)`. The helpers + * in `app/api/v2/lib/response.ts` (`v2Data`, `v2Error`, `v2NoContent`, …) are the only things + * that build a v2 response, because they also set the `Cache-Control: private, no-store` every + * authed per-caller v2 response needs and give errors their one envelope. That file is exempt. + * A streamed body (`new Response(stream, …)`) is not a JSON envelope and is not counted. + * - `non-barrel-reexport` (`.claude/rules/sim-imports.md` "No Re-exports"): an `apps/sim` module + * that is not a barrel `index.ts(x)` re-exports with `export … from '…'` or `export * from`. + * A second name for a symbol lets callers import it from a file that does not declare it, so + * import it from where it is declared instead. + * - `route-audit` (CLAUDE.md "Application Operation Boundary"): a module under `app/api/` (a + * `route.ts` or a helper beside it) calls `recordAudit(…)`. Semantic audit belongs to the + * application use case that performs the mutation, so every surface (internal API, v2, Copilot) + * records it the same way. * * Existing hits are counted per rule and file in `scripts/check-source-conventions.baseline.json`. * A file whose count rises, or that gains its first hit, fails. A count that drops also fails until * the baseline is rewritten, so the baseline only shrinks and a fix cannot be spent on a new hit in * the same file. Regenerate after removing hits: `bun run scripts/check-source-conventions.ts --update`. - * A rule added to this file later is admitted once with `--update --init-rule `, which only - * works while the baseline has no entry for that rule at all. + * A rule added to this file later is admitted once with `--update --init-rule ` (repeat the + * flag to admit several), which only works while the baseline has no entry for that rule at all. * * Run: `bun run check:source-conventions` */ @@ -65,6 +84,10 @@ const RULES = [ 'api-db-import', 'bare-route-handler', 'log-message-tag', + 'lru-cache-ceiling', + 'v2-raw-response', + 'non-barrel-reexport', + 'route-audit', ] as const export type Rule = (typeof RULES)[number] @@ -99,6 +122,14 @@ const HOW_TO_FIX: Record = { 'Export the verb as the result of a shared route builder (`defineInternalJsonRoute`, `defineV2JsonRoute`, …) or `withRouteHandler`, never a bare handler function (CLAUDE.md "API Contracts and Routes").', 'log-message-tag': 'Keep the message static and move the id into metadata: `logger.info(\'Started\', { requestId })`. Inside `withRouteHandler`, a `generateRequestId()` id is already on every line, so drop it (CLAUDE.md "Logging").', + 'lru-cache-ceiling': + 'Set `max` (or `maxSize` with `sizeCalculation`) as a literal key of the options object; `ttl` alone does not bound memory (.claude/rules/sim-caching.md).', + 'v2-raw-response': + 'Return a helper from `@/app/api/v2/lib/response` (`v2Data`, `v2Error`, `v2NoContent`, …), or let the v2 route builder render the body; add a helper there if none fits (.agents/skills/v2-api-conventions).', + 'non-barrel-reexport': + 'Delete the re-export and import the symbol from the module that declares it; only a barrel index.ts re-exports (.claude/rules/sim-imports.md "No Re-exports").', + 'route-audit': + 'Move `recordAudit` into the application use case the route calls, after the mutation it describes commits; routes never record semantic audit (CLAUDE.md "Application Operation Boundary").', } const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']) @@ -796,6 +827,84 @@ function findLogMessageTags(file: string, source: string, program: Node): Violat return violations } +/** The options object of a `new LRUCache(…)` sets `max` or `maxSize` as one of its own keys. */ +function findUnboundedLruCaches(file: string, program: Node): Violation[] { + const violations: Violation[] = [] + walk(program, (node) => { + if (node.type !== 'NewExpression') return + const callee = node.callee as Node + const name = callee.type === 'Identifier' ? callee.name : boundName(callee) + if (name !== 'LRUCache') return + const options = unwrap((node.arguments as Node[])[0]) + const bounded = + options?.type === 'ObjectExpression' && + (options.properties as Node[]).some((property) => { + if (property.type !== 'ObjectProperty' && property.type !== 'ObjectMethod') return false + const key = propertyKeyName(property) + return key === 'max' || key === 'maxSize' + }) + if (!bounded) { + violations.push({ rule: 'lru-cache-ceiling', file, line: lineOf(node), detail: 'LRUCache' }) + } + }) + return violations +} + +const V2_RESPONSE_HELPERS = 'apps/sim/app/api/v2/lib/response.ts' + +/** `NextResponse.json(…)`, `Response.json(…)` and `new NextResponse(…)`. */ +function findV2RawResponses(file: string, program: Node): Violation[] { + const violations: Violation[] = [] + walk(program, (node) => { + const callee = node.callee as Node | undefined + if (!callee) return + let detail: string | undefined + if (node.type === 'NewExpression' && callee.type === 'Identifier') { + if (callee.name === 'NextResponse') detail = 'new NextResponse' + } else if (isCallExpression(node) && isMemberExpression(callee) && !callee.computed) { + const object = unwrap(callee.object as Node) + const objectName = object?.type === 'Identifier' ? (object.name as string) : undefined + if ( + boundName(callee) === 'json' && + (objectName === 'NextResponse' || objectName === 'Response') + ) { + detail = `${objectName}.json` + } + } + if (detail) violations.push({ rule: 'v2-raw-response', file, line: lineOf(node), detail }) + }) + return violations +} + +/** `export { x } from '…'`, `export type { T } from '…'` and `export * from '…'`. */ +function findNonBarrelReExports(file: string, program: Node): Violation[] { + const violations: Violation[] = [] + for (const statement of program.body as Node[]) { + const isReExport = + (statement.type === 'ExportNamedDeclaration' && statement.source) || + statement.type === 'ExportAllDeclaration' + if (!isReExport) continue + violations.push({ + rule: 'non-barrel-reexport', + file, + line: lineOf(statement), + detail: stringValue(statement.source) ?? 'export from', + }) + } + return violations +} + +/** Every `recordAudit(…)` call in a surface adapter, bare or through a namespace. */ +function findRouteAudits(file: string, program: Node): Violation[] { + const violations: Violation[] = [] + walk(program, (node) => { + if (!isCallExpression(node)) return + if (boundName(unwrap(node.callee as Node) as Node) !== 'recordAudit') return + violations.push({ rule: 'route-audit', file, line: lineOf(node), detail: 'recordAudit' }) + }) + return violations +} + /** Unit, integration and live tests, plus fixtures: they bind real boundaries on purpose. */ function isTestFile(file: string): boolean { return /\.(?:test|spec|integration)\.tsx?$/.test(file) || file.includes('/__fixtures__/') @@ -817,7 +926,29 @@ export function findViolations(file: string, source: string): Violation[] { const wantsRoute = isApi && /(?:^|\/)route\.ts$/.test(file) const wantsLogTag = !test && source.includes('@sim/logger') && /\[(?:\$\{|['"`]\s*\+)|req(?:uest)?Id/i.test(source) - if (!(wantsRelative || wantsTextSize || wantsStyle || wantsDb || wantsRoute || wantsLogTag)) { + const wantsLru = !test && source.includes('LRUCache') + const wantsV2Response = + isApi && + file.startsWith('apps/sim/app/api/v2/') && + file !== V2_RESPONSE_HELPERS && + source.includes('Response') + const wantsReExport = + inSim && !test && !isBarrel(file) && /\bexport\s*(?:type\s*)?(?:\*|\{)/.test(source) + const wantsRouteAudit = isApi && source.includes('recordAudit') + if ( + !( + wantsRelative || + wantsTextSize || + wantsStyle || + wantsDb || + wantsRoute || + wantsLogTag || + wantsLru || + wantsV2Response || + wantsReExport || + wantsRouteAudit + ) + ) { return [] } @@ -829,6 +960,10 @@ export function findViolations(file: string, source: string): Violation[] { ...(wantsDb ? findApiDbImports(file, program) : []), ...(wantsRoute ? findBareRouteHandlers(file, program) : []), ...(wantsLogTag ? findLogMessageTags(file, source, program) : []), + ...(wantsLru ? findUnboundedLruCaches(file, program) : []), + ...(wantsV2Response ? findV2RawResponses(file, program) : []), + ...(wantsReExport ? findNonBarrelReExports(file, program) : []), + ...(wantsRouteAudit ? findRouteAudits(file, program) : []), ] } @@ -856,14 +991,15 @@ export function compareToBaseline( /** * The baseline `--update` writes: every tracked rule shrunk to the current counts, never raised. - * `initRule` admits the current hits of a rule the baseline has never tracked, and nothing else. + * `initRules` admits the current hits of rules the baseline has never tracked, and nothing else. */ export function nextBaseline( baseline: Baseline, current: CurrentCounts, - initRule?: string + initRules: string | readonly string[] = [] ): { baseline: Baseline } | { errors: string[] } { - if (initRule !== undefined) { + const admitted = typeof initRules === 'string' ? [initRules] : initRules + for (const initRule of admitted) { if (!(RULES as readonly string[]).includes(initRule)) { return { errors: [`--init-rule ${initRule}: not a rule in this script (${RULES.join(', ')})`], @@ -880,7 +1016,7 @@ export function nextBaseline( const errors: string[] = [] const next: Baseline = {} for (const rule of RULES) { - const before = rule === initRule ? current[rule] : baseline[rule] + const before = admitted.includes(rule) ? current[rule] : baseline[rule] if (before === undefined) { if (Object.keys(current[rule]).length) { errors.push( @@ -935,9 +1071,11 @@ function total(counts: Counts | undefined): number { return Object.values(counts ?? {}).reduce((sum, count) => sum + count, 0) } -function argValue(flag: string): string | undefined { - const index = process.argv.indexOf(flag) - return index === -1 ? undefined : process.argv[index + 1] +/** Every value given for a repeatable flag: `--init-rule a --init-rule b` → `['a', 'b']`. */ +function argValues(flag: string): string[] { + return process.argv.flatMap((arg, index) => + arg === flag && index + 1 < process.argv.length ? [process.argv[index + 1]] : [] + ) } /** @@ -959,7 +1097,7 @@ function main(): void { const baseline = readBaseline(current) if (process.argv.includes('--update')) { - const result = nextBaseline(baseline, current, argValue('--init-rule')) + const result = nextBaseline(baseline, current, argValues('--init-rule')) if ('errors' in result) { for (const error of result.errors) console.error(`✗ ${error}`) process.exit(1) From 9efcf96727960f37b1dec535556ffdcec6694760 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 09:54:00 -0600 Subject: [PATCH 04/20] chore(checks): ban retired styling forms in check:source-text Arbitrary font weights, --font-weight-* variables, var(--divider) and hand-rolled shadow-[inset_0_-1px_0 lines fail in apps/sim and emcn; react-email templates keep off-scale weights. Zero hits today. (cherry picked from commit e5990cc6aa3cef87f96285eb89769f9b3a7f4260) --- scripts/check-source-text.ts | 63 ++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/scripts/check-source-text.ts b/scripts/check-source-text.ts index f983388e7c4..76d5884a7fa 100644 --- a/scripts/check-source-text.ts +++ b/scripts/check-source-text.ts @@ -1,6 +1,6 @@ #!/usr/bin/env bun /** - * Asserts two properties of tracked source text that no linter covers. + * Asserts three properties of tracked source text that no linter covers. * * No raw `U+0000`. Git classifies a file as binary the moment its contents hold * a NUL byte, so a single stray `U+0000` written as a literal turns the whole @@ -21,6 +21,14 @@ * that crawlers read. The docs JSON-LD shipped that way twice. Data belongs in a * native ` -``` - -## Appendix B - Canonical Sources (read these before reinventing) - -### Material Web -- https://github.com/material-components/material-web -- https://material-web.dev/theming/material-theming/ -- https://m3.material.io/develop/web - -### Fluent UI -- https://fluent2.microsoft.design/get-started/develop -- https://fluent2.microsoft.design/components/web/react/ -- https://github.com/microsoft/fluentui -- https://learn.microsoft.com/en-us/fluent-ui/web-components/ - -### Carbon -- https://carbondesignsystem.com/ -- https://github.com/carbon-design-system/carbon -- https://carbondesignsystem.com/developing/react-tutorial/overview/ -- https://carbondesignsystem.com/developing/web-components-tutorial/overview/ - -### Shopify Polaris -- https://shopify.dev/docs/api/app-home/web-components -- https://github.com/Shopify/polaris-react -- https://polaris-react.shopify.com/components - -### Atlassian -- https://atlassian.design/get-started/develop -- https://atlassian.design/components/button/examples -- https://atlaskit.atlassian.com/packages/design-system/button/example/disabled -- https://atlassian.design/tokens/design-tokens - -### Primer -- https://primer.style/ -- https://github.com/primer/css -- https://github.com/primer/brand - -### GOV.UK -- https://design-system.service.gov.uk/components/button/ -- https://design-system.service.gov.uk/styles/layout/ -- https://github.com/alphagov/govuk-frontend - -### USWDS -- https://designsystem.digital.gov/documentation/developers/ -- https://designsystem.digital.gov/components/button/ -- https://designsystem.digital.gov/components/card/ -- https://github.com/uswds/uswds - -### Bootstrap -- https://getbootstrap.com/docs/5.3/layout/grid/ -- https://getbootstrap.com/docs/5.3/components/card/ - -### Tailwind -- https://tailwindcss.com/docs/dark-mode -- https://tailwindcss.com/blog/tailwindcss-v4 - -### Radix -- https://www.radix-ui.com/themes/docs/components/theme -- https://www.radix-ui.com/themes/docs/components/card -- https://github.com/radix-ui/themes - -### shadcn/ui -- https://ui.shadcn.com/docs -- https://ui.shadcn.com/docs/components/card -- https://github.com/shadcn-ui/ui - -### Native CSS / W3C standards -- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/backdrop-filter -- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-color-scheme -- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion -- https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Grid_layout -- https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Scroll-driven_animations -- https://drafts.csswg.org/scroll-animations-1/ - -### Apple Liquid Glass (Apple platforms only) -- https://developer.apple.com/design/human-interface-guidelines/materials -- https://developer.apple.com/documentation/TechnologyOverviews/liquid-glass -- https://developer.apple.com/documentation/TechnologyOverviews/adopting-liquid-glass -- https://developer.apple.com/documentation/SwiftUI/Material - ---- - -## Appendix C - Apple Liquid Glass: Honest Web Approximation - -Do **not** treat random CSS snippets as official Apple Liquid Glass. - -### What is official -Apple documents Liquid Glass inside Apple's Human Interface Guidelines and Developer Documentation for **Apple platforms**. It is a dynamic material used across Apple platform UI. Apple's native implementation belongs to Apple platform APIs and system components, **not a public web CSS package**. - -Relevant official docs: -- Apple Human Interface Guidelines → Materials -- Apple Developer Documentation → Liquid Glass -- Apple Developer Documentation → Adopting Liquid Glass -- SwiftUI → Material - -### What is NOT official -There is no `liquid-glass.css` from Apple for normal websites. - -A web approximation can use: -- `backdrop-filter` -- transparent backgrounds -- layered borders -- highlight overlays -- gradients -- motion -- strong contrast fallbacks - -But that is **web glassmorphism / frosted-glass approximation**, not official Apple Liquid Glass. Label it as such in comments. - -### Safer web approximation skeleton - -```css -.liquid-glass-web-approx { - position: relative; - isolation: isolate; - overflow: hidden; - border-radius: 999px; - border: 1px solid rgb(255 255 255 / .32); - background: - linear-gradient(135deg, rgb(255 255 255 / .30), rgb(255 255 255 / .08)), - rgb(255 255 255 / .12); - backdrop-filter: blur(24px) saturate(180%) contrast(1.05); - -webkit-backdrop-filter: blur(24px) saturate(180%) contrast(1.05); - box-shadow: - inset 0 1px 0 rgb(255 255 255 / .48), - inset 0 -1px 0 rgb(255 255 255 / .12), - 0 18px 60px rgb(0 0 0 / .18); -} - -.liquid-glass-web-approx::before { - content: ""; - position: absolute; - inset: 0; - z-index: -1; - border-radius: inherit; - background: - radial-gradient(circle at 20% 0%, rgb(255 255 255 / .55), transparent 34%), - linear-gradient(90deg, rgb(255 255 255 / .18), transparent 42%, rgb(255 255 255 / .14)); - pointer-events: none; -} - -.liquid-glass-web-approx::after { - content: ""; - position: absolute; - inset: 1px; - border-radius: inherit; - border: 1px solid rgb(255 255 255 / .14); - pointer-events: none; -} - -@media (prefers-color-scheme: dark) { - .liquid-glass-web-approx { - border-color: rgb(255 255 255 / .18); - background: - linear-gradient(135deg, rgb(255 255 255 / .16), rgb(255 255 255 / .04)), - rgb(15 23 42 / .42); - box-shadow: - inset 0 1px 0 rgb(255 255 255 / .22), - 0 18px 60px rgb(0 0 0 / .42); - } -} - -@media (prefers-reduced-transparency: reduce) { - .liquid-glass-web-approx { - background: rgb(255 255 255 / .96); - backdrop-filter: none; - -webkit-backdrop-filter: none; - } -} -``` - -**Important:** `prefers-reduced-transparency` has uneven browser support; test it. Always provide enough contrast even without blur. - ---- - -**End of appendices.** Install commands above are reality anchors. The Apple Liquid Glass skeleton is a labeled approximation, not an Apple-issued package. For canonical docs per design system, consult the system's official docs (links in Section 2 plus Appendix B). diff --git a/.agents/skills/emcn-design-review/SKILL.md b/.agents/skills/emcn-design-review/SKILL.md index 8a211f53c6b..8324f2adf97 100644 --- a/.agents/skills/emcn-design-review/SKILL.md +++ b/.agents/skills/emcn-design-review/SKILL.md @@ -12,68 +12,19 @@ Arguments: User arguments: $ARGUMENTS -## Context - -This codebase uses **emcn**, a custom component library built on Radix UI primitives with CVA variants and CSS variable design tokens. All UI must use emcn components and tokens. - ## Steps -1. Read the emcn public barrel at `packages/emcn/src/index.ts` (re-exports components, Calendar, Table*, and icons) to know what's available; for the full icon set read `packages/emcn/src/icons/index.ts` -2. Read `apps/sim/app/_styles/globals.css` for CSS variable tokens -3. Analyze the specified scope against every rule below -4. If fix=true, apply the fixes. If fix=false, propose the fixes without applying. - ---- - -## Imports - -- Components, `cn`, and tokens from the `@sim/emcn` barrel, never component subpaths -- Icons from `@sim/emcn/icons` - -## Design Tokens - -Use CSS variable pattern (`text-[var(--text-body)]`), never Tailwind semantics (`text-muted-foreground`) or hardcoded colors (`text-gray-500`, `#333`). - -**Text**: `--text-primary`, `--text-secondary`, `--text-tertiary`, `--text-muted`, `--text-body` (canonical value text), `--text-icon`, `--text-placeholder`, `--text-subtle`, `--text-inverse`, `--text-error` -**Surfaces**: `--bg`, `--surface-1` through `--surface-7`, `--surface-hover`, `--surface-active` -**Borders**: `--border` (`--border-1`/`--border-muted` are legacy aliases resolving to it — flag new uses) -**Brand/accent**: `--brand-secondary`, `--brand-accent` -**Z-Index**: `--z-dropdown` (100), `--z-toast` (150), `--z-modal` (200), `--z-popover` (300), `--z-tooltip` (400), `--z-takeover` (500), `--z-shell-gate` (600) -**Shadows**: `shadow-subtle`, `shadow-medium`, `shadow-overlay`, `shadow-card` -**Badges**: `--badge-*` semantic families (success/error/gray/blue/purple/orange/amber/teal/cyan/pink, each with `-bg`/`-text`) - -## Buttons and chips - -Header/action chrome is `Chip`/`ChipLink` (variants `primary`, `destructive`, `outline`, `border`, `border-shadow`; omit `variant` for the bare chip, and `filled` is reserved for chip fields and triggers). Selection and toggles use the `active` prop, never a variant. A single-resource Delete is a plain chip behind `ChipConfirmModal`; `destructive` is only for at-scale actions (`.claude/rules/sim-settings-pages.md` "Deleting a resource"). `Button` is only for icon-only toolbar controls (`ghost`/`quiet`, `size='icon'`). - -## Delete/Remove Confirmations - -Use `ChipConfirmModal` (title "Delete/Remove {ItemType}", `confirm={{ label, onClick }}`, which defaults to destructive). Keep its fail-safe `defaultAction='dismiss'` per `.claude/rules/emcn-components.md` "Modal keyboard defaults". Put irreversible-consequence copy in `text`. - -## Toast - -`toast.success()`, `toast.error()`, `toast()` from `@sim/emcn`. Never custom notification UI. - -## Badges - -`red`=error/failed, `gray-secondary`=metadata/roles, `type`=type annotations, `green`=success/active, `gray`=neutral, `amber`=processing, `orange`=paused, `blue`=info. Use `dot` prop for status indicators. - -## Icons - -Default: `size-[14px]`. Color: `text-[var(--text-icon)]`. Scale: 14px > 16px > 12px > 20px. Use the `size-*` shorthand — flag `h-[Npx] w-[Npx]` and `h-N w-N` pairs as refactor targets. - -## Mobile - -Check at 320px and 390px with touch, then desktop and fullscreen. Use `Chip`/`ChipLink`'s `mobileIconOnly` for familiar mobile toolbar actions, preserving accessible names; keep labels for ambiguous choices. Keep navigation, primary actions, and dismissal reachable without hover or dragging; aim for 44px touch targets with compact visible icons/button faces and 16px editable text. Match behavior to the actual container or viewport breakpoint. Contain horizontal scrolling to intentional tables/code, fit overlays to the dynamic viewport, and keep the composer/actions reachable with the keyboard open. Reuse EMCN tokens and brief motion with reduced-motion support; preserve desktop geometry. +1. Read the emcn barrel `packages/emcn/src/index.ts` (and `packages/emcn/src/icons/index.ts` for icons) to know what exists, and `apps/sim/app/_styles/globals.css` for tokens. +2. Review the scope against `.claude/rules/emcn-components.md`, `.claude/rules/sim-styling.md`, and the rules below. +3. If fix=true, apply the fixes; if fix=false, propose them without applying. -## Anti-patterns to flag +## Rules -- Raw ` - - - ); -} -``` - -### CSS-Only Stagger - -```css -.stagger-item { - opacity: 0; - transform: translateY(12px); - filter: blur(4px); - animation: fadeInUp 400ms ease-out forwards; -} - -.stagger-item:nth-child(1) { animation-delay: 0ms; } -.stagger-item:nth-child(2) { animation-delay: 100ms; } -.stagger-item:nth-child(3) { animation-delay: 200ms; } - -@keyframes fadeInUp { - to { - opacity: 1; - transform: translateY(0); - filter: blur(0); - } -} -``` - -## Exit Animations - -Exit animations should be softer and less attention-grabbing than enter animations. The user's focus is moving to the next thing — don't fight for attention. - -### Subtle Exit (Recommended) - -```tsx -// Small fixed translateY — indicates direction without drama - - {content} - -``` - -### Full Exit (When Context Matters) - -```tsx -// Slide fully out — use when spatial context is important -// (e.g., a card returning to a list, a drawer closing) - - {content} - -``` - -### Good vs. Bad - -```css -/* Good — subtle exit */ -.item-exit { - opacity: 0; - transform: translateY(-12px); - transition: opacity 150ms ease-in, transform 150ms ease-in; -} - -/* Bad — dramatic exit that steals focus */ -.item-exit { - opacity: 0; - transform: translateY(-100%) scale(0.5); - transition: all 400ms ease-in; -} - -/* Bad — no exit animation at all (element just vanishes) */ -.item-exit { - display: none; -} -``` - -**Key points:** -- Use a small fixed `translateY` (e.g., `-12px`) instead of the full container height -- Keep some directional movement to indicate where the element went -- Exit duration should be shorter than enter duration (150ms vs 300ms) -- Don't remove exit animations entirely — subtle motion preserves context - -## Contextual Icon Animations - -When icons appear or disappear contextually (on hover, on state change), animate them with `opacity`, `scale`, and `blur` rather than just toggling visibility. - -### Motion Example - -```tsx -import { AnimatePresence, motion } from "framer-motion"; - -function IconButton({ isActive, icon: Icon }) { - return ( - - ); -} -``` - -### CSS Transition Approach (No Motion) - -If the project doesn't use Motion (Framer Motion), keep both icons in the DOM and cross-fade them with CSS transitions. Because neither icon unmounts, both enter and exit animate smoothly. - -The trick: one icon is absolutely positioned on top of the other. Toggling state cross-fades them — the entering icon scales up from `0.25` while the exiting icon scales down to `0.25`, both with opacity and blur. - -```tsx -function IconButton({ isActive, ActiveIcon, InactiveIcon }) { - return ( - - ); -} -``` - -The non-absolute icon (InactiveIcon) defines the layout size. The absolute icon (ActiveIcon) overlays it without affecting flow. - -### Choosing Between Motion and CSS - -| | Motion (Framer Motion) | CSS transitions (both icons in DOM) | -| --- | --- | --- | -| **Enter animation** | Yes | Yes | -| **Exit animation** | Yes (via `AnimatePresence`) | Yes (cross-fade — icon never unmounts) | -| **Spring physics** | Yes | No — use `cubic-bezier(0.2, 0, 0, 1)` as approximation | -| **When to use** | Project already uses `framer-motion` (or `motion/react`) | No motion dependency, or keeping bundle small | - -**Rule:** Check the project's `package.json` for `motion` or `framer-motion`. If present, use the Motion approach. If not, use the CSS cross-fade pattern — don't add a dependency just for icon transitions. - -### When to Animate Icons - -| Animate | Don't animate | -| --- | --- | -| Icons that appear on hover (action buttons) | Static navigation icons | -| State change icons (play → pause, like → liked) | Decorative icons | -| Icons in contextual toolbars | Icons that are always visible | -| Loading/success state indicators | Icon labels (text next to icon) | - -Default values: scale 0.25→1, opacity 0→1, blur 4px→0, `{ type: "spring", duration: 0.3, bounce: 0 }`. - -## Scale on Press - -A subtle scale-down on click (about 0.96-0.97) gives buttons tactile feedback. Use CSS transitions for interruptibility — if the user releases mid-press, it should smoothly return. - -Not every button needs this. Add a `static` prop to your button component that disables the scale effect when the motion would be distracting. - -### CSS Example - -```css -.button { - transition-property: scale; - transition-duration: 150ms; - transition-timing-function: ease-out; -} - -.button:active { - scale: 0.96; -} -``` - -### Tailwind Example - -```tsx - -``` - -### Motion Example - -```tsx - - Click me - -``` - -### Static Prop Pattern - -Extract the scale class into a variable and conditionally apply it based on a `static` prop: - -```tsx -const tapScale = "active:not-disabled:scale-[0.96]"; - -function Button({ static: isStatic, className, children, ...props }) { - return ( - - ); -} - -// Usage - {/* scales on press */} - {/* no scale */} -``` - -## Skip Animation on Page Load - -Use `initial={false}` on `AnimatePresence` to prevent enter animations from firing on first render. Elements that are already in their default state shouldn't animate in on page load — only on subsequent state changes. - -### When It Works - -```tsx -// Good — icon doesn't animate in on mount, only on state change - - - - - -``` - -Works well for: icon swaps, toggles, tabs, segmented controls — anything that has a default state on page load. - -### When It Breaks - -Don't use `initial={false}` when the component relies on its `initial` prop to set up a first-time enter animation, like a staggered page hero or a loading state. In those cases, removing the initial animation skips the entire entrance. - -```tsx -// Bad — initial={false} would skip the staggered page enter entirely - - - ... - - -``` - -Verify the component still looks right on a full page refresh before applying this. diff --git a/.agents/skills/make-interfaces-feel-better/performance.md b/.agents/skills/make-interfaces-feel-better/performance.md deleted file mode 100644 index 155954988e9..00000000000 --- a/.agents/skills/make-interfaces-feel-better/performance.md +++ /dev/null @@ -1,88 +0,0 @@ -# Performance - -Transition specificity and GPU compositing hints. - -## Transition Only What Changes - -Never use `transition: all` or Tailwind's `transition` shorthand (which maps to `transition-property: all`). Always specify the exact properties that change. - -### Why - -- `transition: all` forces the browser to watch every property for changes -- Causes unexpected transitions on properties you didn't intend to animate (colors, padding, shadows) -- Prevents browser optimizations - -### CSS Example - -```css -/* Good — only transition what changes */ -.button { - transition-property: scale, background-color; - transition-duration: 150ms; - transition-timing-function: ease-out; -} - -/* Bad — transition everything */ -.button { - transition: all 150ms ease-out; -} -``` - -### Tailwind - -```tsx -// Good — explicit properties - -``` - -### Play Button Triangles - -Play icons are triangular and their geometric center is not their visual center. Shift slightly right: - -```css -/* Good — optically centered */ -.play-button svg { - margin-left: 2px; /* shift right to account for triangle shape */ -} - -/* Bad — geometrically centered but looks off */ -.play-button svg { - /* no adjustment */ -} -``` - -### Asymmetric Icons (Stars, Arrows, Carets) - -Some icons have uneven visual weight. The best fix is adjusting the SVG directly so no extra margin/padding is needed in the component code. - -```tsx -// Best — fix in the SVG itself -// Adjust the viewBox or path to visually center the icon - -// Fallback — adjust with margin - - - -``` - -## Shadows Instead of Borders - -> In this repo, use the `shadow-subtle`/`shadow-medium`/`shadow-overlay`/`shadow-card` tokens for elevation and keep neutral edges as `--border` borders (`.claude/rules/sim-styling.md`, Line weight); do not replace them with `0 0 0 1px` shadow rings. The pattern below is for projects without that token system. - -For **buttons, cards, and containers** that use a border for depth or elevation, prefer replacing it with a subtle `box-shadow`. Shadows adapt to any background since they use transparency; solid borders don't. This also helps when using images or multiple colors as backgrounds — solid border colors don't work well on backgrounds other than the ones they were designed for. - -**Do not apply this to dividers** (`border-b`, `border-t`, side borders) or any border whose purpose is layout separation rather than element depth. Those should stay as borders. - -### Shadow as Border (Light Mode) - -The shadow is comprised of three layers. The first acts as a 1px border ring, the second adds subtle lift, and the third provides ambient depth: - -```css -:root { - --shadow-border: - 0px 0px 0px 1px rgba(0, 0, 0, 0.06), - 0px 1px 2px -1px rgba(0, 0, 0, 0.06), - 0px 2px 4px 0px rgba(0, 0, 0, 0.04); - --shadow-border-hover: - 0px 0px 0px 1px rgba(0, 0, 0, 0.08), - 0px 1px 2px -1px rgba(0, 0, 0, 0.08), - 0px 2px 4px 0px rgba(0, 0, 0, 0.06); -} -``` - -### Shadow as Border (Dark Mode) - -In dark mode, simplify to a single white ring — layered depth shadows aren't visible on dark backgrounds: - -```css -/* Dark mode — adapt to whatever setup the project uses - (prefers-color-scheme, class, data attribute, etc.) */ ---shadow-border: 0 0 0 1px rgba(255, 255, 255, 0.08); ---shadow-border-hover: 0 0 0 1px rgba(255, 255, 255, 0.13); -``` - -### Usage with Hover Transition - -Apply the variable and add `transition-[box-shadow]` for a smooth hover: - -```css -.card { - box-shadow: var(--shadow-border); - transition-property: box-shadow; - transition-duration: 150ms; - transition-timing-function: ease-out; -} - -.card:hover { - box-shadow: var(--shadow-border-hover); -} -``` - -### When to Use Shadows vs. Borders - -| Use shadows | Use borders | -| --- | --- | -| Cards, containers with depth | Dividers between list items | -| Buttons with bordered styles | Table cell boundaries | -| Elevated elements (dropdowns, modals) | Form input outlines (for accessibility) | -| Elements on varied backgrounds | Hairline separators in dense UI | -| Hover/focus states for lift effect | | - -## Image Outlines - -Add a subtle `1px` outline with low opacity to images. This creates consistent depth, especially in design systems where other elements use borders or shadows. - -### Color - -- **Light mode**: pure black — `rgba(0, 0, 0, 0.1)`. -- **Dark mode**: pure white — `rgba(255, 255, 255, 0.1)`. -- Tinted neutrals (slate-900, zinc-900, `#0a0a0a`, `#f5f5f7`) and accent/ink colors pick up the surrounding surface color and read as dirt on the image edge; the outline is a neutral separator, not a themed element. - -### Light Mode - -```css -img { - outline: 1px solid rgba(0, 0, 0, 0.1); - outline-offset: -1px; /* inset so it doesn't add to layout */ -} -``` - -### Dark Mode - -```css -img { - outline: 1px solid rgba(255, 255, 255, 0.1); - outline-offset: -1px; -} -``` - -### Tailwind with Dark Mode - -```tsx -{alt} -``` - -Use `outline-black/10` and `outline-white/10` specifically — not `outline-slate-*`, `outline-zinc-*`, `outline-neutral-*`, or any tinted scale. - -**Why outline instead of border?** `outline` doesn't affect layout (no added width/height), and `outline-offset: -1px` keeps it inset so images stay their intended size. - -## Minimum Hit Area - -Interactive elements should have a minimum hit area of 44×44px (WCAG) or at least 40×40px. If the visible element is smaller (e.g., a 20×20 checkbox), extend the hit area with a pseudo-element. - -### CSS Example - -```css -/* Small checkbox with expanded hit area */ -.checkbox { - position: relative; - width: 20px; - height: 20px; -} - -.checkbox::after { - content: ""; - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - width: 40px; - height: 40px; -} -``` - -### Tailwind Example - -```tsx - -``` - -### Collision Rule - -If the extended hit area overlaps another interactive element, shrink the pseudo-element — but make it as large as possible without colliding. Two interactive elements should never have overlapping hit areas. diff --git a/.agents/skills/make-interfaces-feel-better/typography.md b/.agents/skills/make-interfaces-feel-better/typography.md deleted file mode 100644 index 6ca7ac7e6ed..00000000000 --- a/.agents/skills/make-interfaces-feel-better/typography.md +++ /dev/null @@ -1,135 +0,0 @@ -# Typography - -Typography rendering details that make interfaces feel better. - -## Text Wrapping - -### text-wrap: balance - -Distributes text evenly across lines, preventing orphaned words on headings and short text blocks. **Only works on blocks of 6 lines or fewer** (Chromium) or 10 lines or fewer (Firefox) — the balancing algorithm is computationally expensive, so browsers limit it to short text. - -```css -/* Good — even line lengths on short text */ -h1, h2, h3 { - text-wrap: balance; -} -``` - -```css -/* Bad — default wrapping leaves orphans */ -h1 { - /* no text-wrap rule → "Read our - blog" instead of balanced lines */ -} -``` - -```css -/* Bad — balance on long paragraphs (silently ignored, wastes intent) */ -.article-body p { - text-wrap: balance; -} -``` - -**Tailwind:** `text-balance` - -### text-wrap: pretty - -Prevents orphaned words (a single word dangling on the last line) by adjusting line breaks throughout the paragraph. Unlike `balance`, it doesn't try to equalize line lengths — it just ensures the last line isn't embarrassingly short. Works on text of any length with no line-count limit. - -This should be your **default for short-to-medium text** — paragraphs, descriptions, captions, list items, card text. For very long text (10+ lines), skip both `pretty` and `balance` — the browser's default wrapping is fine and you avoid unnecessary layout cost. - -```css -/* Good — descriptions, captions, short paragraphs */ -p, li, figcaption, blockquote { - text-wrap: pretty; -} -``` - -```tsx -// Tailwind -

- A short paragraph that won't leave an orphan on the last line. -

-``` - -**Tailwind:** `text-pretty` - -### When to Use Which - -| Scenario | Use | -| --- | --- | -| Headings, titles where even distribution matters | `text-wrap: balance` | -| Short-to-medium text — paragraphs, descriptions, captions, UI text | `text-wrap: pretty` | -| Long text (10+ lines), code blocks, pre-formatted text | Neither — leave default | - -## Font Smoothing (macOS) - -On macOS, text renders heavier than intended by default. Apply antialiased smoothing to the root layout so all text renders crisper and thinner. - -```css -/* CSS */ -html { - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} -``` - -```tsx -// Tailwind — apply to root layout - -``` - -### Good vs. Bad - -```css -/* Good — applied once at the root */ -html { - -webkit-font-smoothing: antialiased; -} - -/* Bad — applied per-element, inconsistent */ -.heading { - -webkit-font-smoothing: antialiased; -} -.body { - /* no smoothing → heavier than heading */ -} -``` - -**Note:** This only affects macOS rendering. Other platforms ignore these properties, so it's safe to apply universally. - -## Tabular Numbers - -When numbers update dynamically (counters, prices, timers, table columns), use tabular-nums to make all digits equal width. This prevents layout shift as values change. - -```css -/* CSS */ -.counter { - font-variant-numeric: tabular-nums; -} -``` - -```tsx -// Tailwind -{count} -``` - -### When to Use - -| Use tabular-nums | Don't use tabular-nums | -| --- | --- | -| Counters and timers | Static display numbers | -| Prices that update | Decorative large numbers | -| Table columns with numbers | Phone numbers, zip codes | -| Animated number transitions | Version numbers (v2.1.0) | -| Scoreboards, dashboards | | - -### Caveat - -Some fonts (like Inter) change the visual appearance of numerals with this property — specifically, the digit `1` becomes wider and centered. This is expected behavior and usually desirable for alignment, but verify it looks right in your specific font. - -```css -/* With Inter font: - Default: 1234 → proportional, "1" is narrow - Tabular: 1234 → all digits equal width, "1" centered */ -``` diff --git a/.agents/skills/memory-load-check/SKILL.md b/.agents/skills/memory-load-check/SKILL.md index 38c0f40864c..813060fcda8 100644 --- a/.agents/skills/memory-load-check/SKILL.md +++ b/.agents/skills/memory-load-check/SKILL.md @@ -5,162 +5,39 @@ description: Review PRs and diffs for unbounded memory loading, concurrency expl # Memory Load Check -Use this skill when a PR or diff could load unbounded data into a Node/Bun process, especially in cron routes, background tasks, API routes, workflow execution, file parsing, cleanup jobs, migrations, import/export flows, and external API integrations. +Prove each changed path has explicit bounds on rows held, bytes held, concurrency (promises, queries, HTTP calls, storage operations, jobs), and pages/batches/retries/retained intermediates. A bound that rests on current production size or "probably small" data is a finding. -## Review Goal +## Sim helpers to prefer -Prove each changed path has explicit bounds for: -- rows held in memory -- bytes held in memory -- concurrent promises, DB queries, HTTP calls, storage operations, and jobs -- number of pages, batches, chunks, retries, and retained intermediate objects +- `apps/sim/lib/cleanup/batch-delete.ts`: `chunkedBatchDelete` (bounded SELECT → side effect → DELETE loop), `batchDeleteByWorkspaceAndTimestamp`, `selectRowsByIdChunks` (chunks an id set under an overall cap). `chunkArray` (`@sim/utils/helpers`) only after the source itself is bounded. +- `apps/sim/lib/core/utils/stream-limits.ts`: `assertContentLengthWithinLimit`, `readResponseToBufferWithLimit`, `readResponseTextWithLimit`, `readStreamToBufferWithLimit`, `PayloadSizeLimitError`. +- `apps/sim/lib/billing/cleanup-dispatcher.ts`: keyset-page workspaces (`id > afterId ORDER BY id LIMIT N`), dispatch concrete chunks rather than one giant scope, prefer queue concurrency keys, run inline fallback chunks sequentially. +- File parsing (`lib/internal/file/parser.ts`, `lib/uploads/utils/fetch-external-url.server.ts`): cap download and parsed output separately, keep partial results when a later item exceeds the cap. +- Large workflow values: durable refs/manifests, materialized only behind an explicit byte budget. -If any bound depends only on current production size or "probably small" data, treat it as a finding. +## KB connector downloads -## References +Apply the size pattern in `apps/sim/connectors/utils.ts` by risk, not by connector name: connectors that download user-controlled file bytes (storage services, any `download_url` such as Zoom transcripts) must use it; API/structured-data connectors and platform-capped native documents use pagination bounds instead. -Read these when doing a deeper pass: -- Node.js streams/backpressure: https://nodejs.org/learn/modules/backpressuring-in-streams -- Node.js stream usage: https://nodejs.org/en/learn/modules/how-to-use-streams -- Keyset/cursor pagination over offset scans: https://blog.sequinstream.com/keyset-cursors-not-offsets-for-postgres-pagination/ -- Postgres pagination tradeoffs: https://www.citusdata.com/blog/2016/03/30/five-ways-to-paginate/ +- Stream via `readBodyWithLimit(resp, CONNECTOR_MAX_FILE_BYTES)`, never raw `response.text()`/`arrayBuffer()`. +- Skip oversize at listing (`stubOrSkipBySize`) and again at fetch (`markSkipped`), since listing sizes can be missing or under-reported. Never drop or truncate silently: a skipped file stays visible as a failed row with `skippedReason`. +- Connectors that already budget the body (google-docs, google-sheets, notion) keep their approach; don't add a cap to every `response.json()`. +- Litmus: can a user make one fetch arbitrarily large with nothing upstream stopping it? A self-hosted endpoint with no platform cap (Obsidian) is bounded only if content is genuinely unbounded. -## Sim Helpers To Prefer +## Review workflow -- `apps/sim/lib/cleanup/batch-delete.ts` - - `chunkedBatchDelete`: bounded SELECT -> optional side effect -> DELETE loop. - - `batchDeleteByWorkspaceAndTimestamp`: common workspace/timestamp cleanup wrapper. - - `selectRowsByIdChunks`: chunks large ID sets and enforces an overall row cap. -- `chunkArray` from `@sim/utils/helpers`: use only after the input set itself is already bounded. -- `apps/sim/lib/core/utils/stream-limits.ts` - - `PayloadSizeLimitError` - - `assertKnownSizeWithinLimit` - - `assertContentLengthWithinLimit` - - `readStreamToBufferWithLimit` - - `readNodeStreamToBufferWithLimit` - - `readResponseToBufferWithLimit` - - `readResponseTextWithLimit` -- Cleanup dispatcher pattern in `apps/sim/lib/billing/cleanup-dispatcher.ts` - - page active workspaces with `WHERE id > afterId ORDER BY id LIMIT N` - - dispatch concrete chunks (`workspaceIds`, retention, label) instead of one giant scope - - prefer Trigger.dev queue/concurrency keys when available - - execute inline fallback chunks sequentially, not with unbounded `Promise.all` -- File parse pattern in `apps/sim/lib/internal/file/parser.ts` and `apps/sim/lib/uploads/utils/fetch-external-url.server.ts` - - cap downloads and parsed output separately - - preserve partial results when a later item exceeds the cap - - never read untrusted response bodies without a byte cap -- KB connector file downloads in `apps/sim/connectors/utils.ts` - - `CONNECTOR_MAX_FILE_BYTES`: shared per-file cap (aligned with the manual KB upload limit) - - `readBodyWithLimit`: stream a download body to a Buffer with a hard byte cap (null on overflow) - - `stubOrSkipBySize`: listing-time skip when the reported size exceeds the cap - - `markSkipped` / `sizeLimitSkipReason`: surface oversized files as failed (skipped) KB rows - - `ConnectorFileTooLargeError`: thrown mid-download when the listing under-reported size -- Large workflow value payloads - - prefer durable references/manifests over inlining large arrays or files - - materialize refs only behind an explicit byte budget +1. List every changed source: queries, storage lists/downloads, external pagination, file reads and responses, workflow logs/snapshots/payloads, queues, crons, background jobs. +2. Write down each source's maximum cardinality and bytes. Not enforced in code means unbounded. +3. Trace accumulation: arrays from `select`/`findMany`/`Promise.all`/`flatMap`, maps or sets over a platform-wide scope, `Buffer.concat`/`arrayBuffer`/`text`/`JSON.parse`, promise queues or job payloads built before dispatch. +4. Concurrency separately from memory: no `Promise.all(items.map(...))` over an unbounded set; align concurrency with the DB pool, provider limits and queue semantics. +5. SQL: every bulk query has `LIMIT`; large pagination is keyset, not deep `OFFSET`; `IN (...)` lists are chunked; rows selected before a delete have per-batch and per-run caps. +6. Bytes: check `Content-Length`, stream with cumulative accounting, cap both input and expanded output, reject or reference oversized values before serializing. +7. Failure: exceeding a cap stops before loading more; partial work survives where the contract expects it; retries don't duplicate huge state; cleanup jobs make progress across runs instead of widening one run. -## KB Connector File Size Handling +Red flags beyond those: fetching all pages before processing, checking size only after materializing, chunking only after loading everything, one queue job per row with no batching or concurrency key, unbounded per-row error/result accumulation. -The connector size pattern in `apps/sim/connectors/utils.ts` (`CONNECTOR_MAX_FILE_BYTES` + `readBodyWithLimit` + `stubOrSkipBySize`/`markSkipped`) exists for one risk: a knowledge-base connector downloading **arbitrary, user-controlled file bytes** that the source does not hard-cap. Apply it by that risk, not by the connector's name. +Fixes should come with a test proving the cap stops work early and that partial results or progress are preserved. -Use the pattern when the connector downloads file content via a stream/`download_url` where the user controls the size: -- file-storage connectors: Dropbox, OneDrive, SharePoint, Google Drive, S3, GitHub, GitLab, Azure DevOps -- any connector that fetches a file via a download URL even if it is not a "storage" service (e.g. the Zoom transcript `.vtt`) +## Findings format -For those, require all three: -- stream the body with `readBodyWithLimit(resp, CONNECTOR_MAX_FILE_BYTES)` — never raw `response.text()`/`response.arrayBuffer()` -- skip oversize at listing (`stubOrSkipBySize` with the reported size) and again at fetch time (overflow -> `markSkipped`), since the listing size can be missing or under-reported -- never drop/truncate silently — oversized files become content-less failed rows carrying `skippedReason`, so they stay visible in the KB UI instead of vanishing from the index - -Skip the pattern when the source already bounds the payload: -- pure API/structured-data connectors (Jira, Linear, Sentry, Slack, Zendesk, Gmail, ...) — paginated JSON/text; apply normal pagination + concurrency bounds instead of a per-file byte cap -- native-document connectors whose platform caps each document — a 100 MB cap can never fire there - -Some connectors also budget the response body (google-docs `MAX_DOCS_RESPONSE_BYTES`, google-sheets `MAX_CONTENT_BYTES`, a remaining-bytes budget in notion); Confluence attachments use the full file pattern. Follow the connector's existing approach rather than adding a cap to every `response.json()`. - -Litmus test: "Can a user make this one fetch arbitrarily large, with nothing upstream stopping it?" Yes -> use the pattern. No (platform hard-cap, or already paginated) -> a per-file byte cap adds noise, not safety. Borderline: a user-configured/self-hosted endpoint with no platform cap (e.g. Obsidian) — bound it only if the content is genuinely unbounded. - -## Review Workflow - -1. Identify every changed data source: - - database queries - - storage lists/downloads/uploads - - external API pagination - - file reads and HTTP responses - - workflow logs, snapshots, payloads, arrays, and manifests - - queues, cron routes, and background jobs -2. For each source, write down the maximum cardinality and maximum bytes. If the code does not enforce one, it is unbounded. -3. Trace whether data is processed incrementally or accumulated: - - arrays from `select`, `findMany`, `Promise.all`, `map`, `filter`, `flatMap` - - maps/sets keyed by all users, workspaces, executions, files, or rows - - `Buffer.concat`, `response.arrayBuffer()`, `response.text()`, `JSON.stringify`, `JSON.parse` - - queues of promises or job payloads built before dispatch -4. Check concurrency separately from memory: - - no `Promise.all(items.map(...))` unless `items` is already small and bounded - - use chunks, sequential loops, queue concurrency, or a concurrency limiter - - align concurrency with DB pool size, storage/API limits, and task queue semantics -5. Verify SQL shape: - - every bulk query has `LIMIT` - - large pagination uses cursor/keyset style (`id > afterId`, timestamps plus unique ID), not deep `OFFSET` - - `IN (...)` lists are chunked - - side-effect rows selected before delete have per-batch and per-run caps -6. Verify byte safety: - - check `Content-Length` when available - - stream with cumulative byte accounting - - cap both input bytes and expanded output bytes - - reject or reference oversized values before serializing large JSON responses -7. Confirm failure behavior: - - exceeding a cap should stop before loading more data - - partial successful work should be preserved when the API contract expects it - - retries should not duplicate huge in-memory state - - cleanup jobs should make progress over future runs instead of widening one run - -## Red Flags - -- loads all active workspaces, users, executions, logs, files, messages, or subscriptions before filtering -- builds a full `Map` or `Set` for a platform-wide scope -- uses `Promise.all` over rows from an unbounded query -- fetches all pages from an external API before processing -- reads an entire file, HTTP response, or stream without a max byte budget -- checks size only after `Buffer.concat`, `arrayBuffer`, `text`, `JSON.parse`, or parse expansion -- a KB connector silently drops or truncates an oversized file instead of recording it as a failed (skipped) row -- chunks only after loading the complete dataset -- paginates with unbounded/deep `OFFSET` on a mutable or large table -- creates one queue job per row without batching or a queue-level concurrency key -- accumulates per-row errors/results with no maximum -- adds a cache, singleton, or module-level collection without eviction or size limits - -## Preferred Fixes - -- Move filters into SQL/API requests and select only needed columns. -- Replace full-table loads with cursor/keyset pagination and a deterministic order. -- Process one page/batch at a time; do not keep previous pages unless needed. -- Add per-batch and per-run row caps so long backlogs drain across repeated jobs. -- Split large ID lists with `selectRowsByIdChunks` or `chunkArray` after bounding the source. -- Use `chunkedBatchDelete` for cleanup loops with row side effects. -- Use stream-limit helpers for file/HTTP/body reads. -- Store large workflow values as refs/manifests and materialize only within a caller budget. -- Replace unbounded `Promise.all` with sequential chunk loops, queue concurrency, or a small limiter. -- Include tests that prove caps stop work early and partial results or progress are preserved. - -## Findings Format - -Lead with concrete findings, ordered by risk: - -```markdown -## Findings - -- **P1 Unbounded workspace load in cleanup dispatch** (`path/to/file.ts`) - The new path calls `select().from(workspace)` without a limit, then builds maps for every row before dispatch. In production this scales with all active workspaces and can exhaust the app process. Page by `workspace.id` with a fixed limit and dispatch bounded chunks. - -## Good Signals - -- Uses `readResponseToBufferWithLimit` for external downloads. -- Inline fallback processes chunks sequentially. - -## Residual Risk - -- The row cap is explicit, but no test currently proves the loop stops at the cap. -``` - -Only say "good to go" when every changed source has explicit row, byte, and concurrency bounds or the boundedness is proven by a stable invariant. +Lead with concrete findings ordered by risk (**P1 title** (`path`) + what scales with what, and the bounded alternative), then good signals, then residual risk. Say "good to go" only when every changed source has explicit row, byte and concurrency bounds, or boundedness is proven by a stable invariant. diff --git a/.agents/skills/migrate-application-operation/SKILL.md b/.agents/skills/migrate-application-operation/SKILL.md index c057b86b35d..6a39ad17e5c 100644 --- a/.agents/skills/migrate-application-operation/SKILL.md +++ b/.agents/skills/migrate-application-operation/SKILL.md @@ -1,362 +1,115 @@ --- name: migrate-application-operation -description: Create or migrate a protected Sim resource operation in the shared Principal and application-use-case architecture across internal APIs, public or versioned APIs, Copilot, and other trusted tool adapters. Use when adding a protected endpoint, tool command, or CRUD method; removing route- or tool-local authorization and business logic; consolidating resource reads or writes behind semantic operation policies; or adding another surface to an existing application operation while preserving contracts, identity, errors, rate limits, audit, analytics, and compatibility behavior. Treat v1, uploads, streams, large bodies, bulk recursion, and polymorphic tools as explicitly scoped special cases. +description: Create or migrate a protected operation into one authorized application use case shared by internal API, v2, Copilot and tool surfaces. Use when adding a protected endpoint, tool command, or CRUD method, removing route- or tool-local authorization, or adding a surface to an existing operation. v1, uploads, streams, large bodies, bulk recursion and polymorphic tools are explicitly scoped special cases. --- # Create Or Migrate Application Operation -Create or migrate one bounded semantic operation at a time. Share authorization and business behavior without forcing internal APIs, public APIs, Copilot, and other tools to share authentication, input schemas, or response shapes. +Migrate one bounded semantic operation at a time. Share authorization and business behavior without forcing surfaces to share authentication, input schemas or response shapes. The invariant and layer rules are in the root `CLAUDE.md` (Application Operation Boundary); this skill is how to apply them without changing behavior. -## Enforce the application boundary - -Apply this invariant: - -> Every real operation on persisted or protected data enters through an authorized application use case. - -This includes mutations, content and metadata reads, canonical resource lookup, and reference-to-resource resolution when the lookup is authorization-sensitive. - -Surface helpers may: - -- Normalize an already-authenticated surface context into a `Principal`. -- Translate aliases or wire arguments into application input. -- Select a code-defined operation and application use case. -- Call the application use case. -- Translate typed results and errors into the surface contract. - -Surface helpers must not: - -- Query databases or storage. -- Decide workspace or resource authorization. -- Implement business transactions. -- Record semantic audit or shared domain notifications. -- Infer authoritative identity, workspace, audience, or scope from untrusted arguments. -- Substitute billing attribution for identity. - -A helper that resolves a path is valid only when the actual protected lookup runs through an authorized application resolver. If a helper begins doing real data work, move that work into an application use case. +Never infer authoritative identity, workspace, audience or scope from untrusted arguments. A helper that resolves a path is valid only when the protected lookup runs through an authorized application resolver; if a helper starts doing real data work, move it into a use case. ## Read the foundation first -Read these files completely before editing: - -- `packages/auth/src/principal.ts` -- `apps/sim/lib/core/application/operation.ts` -- `apps/sim/lib/core/application/workspace-operation.ts` -- `apps/sim/lib/core/application/workspace-authorization.ts` -- `apps/sim/lib/core/application/authorized-workspace-use-case.ts` -- `apps/sim/lib/api/server/routes/definition.ts` -- `apps/sim/lib/api/server/routes/internal-json-route.ts` -- `apps/sim/lib/api/server/routes/v2-json-route.ts` -- `apps/sim/lib/auth/internal-delegation.ts` -- `apps/sim/lib/mothership/application/adapter.ts` -- `apps/sim/lib/mothership/auth/application-delegation.ts` - -Use the file domain only as a representative golden slice: +Read completely: `packages/auth/src/principal.ts`; `apps/sim/lib/core/application/{operation,workspace-operation,workspace-authorization,authorized-workspace-use-case}.ts`; `apps/sim/lib/api/server/routes/{definition,internal-json-route,v2-json-route}.ts`; `apps/sim/lib/auth/internal-delegation.ts`; `apps/sim/lib/mothership/application/adapter.ts`; `apps/sim/lib/mothership/auth/application-delegation.ts`. -- `apps/sim/lib/workspace-files/application/operations.ts` -- `apps/sim/lib/workspace-files/application/authorized-workspace-file-use-case.ts` -- `apps/sim/lib/workspace-files/application/rename-workspace-file.ts` -- `apps/sim/lib/mothership/application/execute-file-use-case.ts` -- `apps/sim/lib/mothership/auth/file-delegation.ts` +**Golden slice** (copy its shape, not invented field names): `lib/workspace-files/application/operations.ts` (registry), `authorized-workspace-file-use-case.ts` (domain binding), `rename-workspace-file.ts` (use case), `app/api/workspaces/[id]/files/[fileId]/route.ts` and `app/api/v2/files/[fileId]/` (surfaces), `lib/mothership/application/execute-file-use-case.ts` + `lib/mothership/auth/file-delegation.ts` (Copilot). -Then read the target domain's operation registry, application code, repositories, contracts, adapters, aliases, resume paths, and focused tests. Fail immediately if the shared foundation is absent. Do not recreate it inside the domain. +Then read the target domain's registry, application code, repositories, contracts, adapters, aliases, resume paths and tests. If the shared foundation is absent, fail: never recreate it inside the domain. ## Bound the migration -Inventory every entry point for the behavior before editing: - -- Internal HTTP routes and contracts. -- Public or versioned API routes and contracts. -- Copilot tools, aliases, resume paths, and polymorphic branches. -- Other tool servers, workflow executors, jobs, or service callers. -- Current authentication, authorization, workspace assertions, and concealment. -- Manager or orchestration call chains. -- Audit, notification, analytics, and billing side effects. -- Error/status/result behavior. -- Rate-limit identity, rollout gates, quota, and concurrency admission. - -Classify each as `migrate`, `defer`, or `non-goal`. Do not migrate adjacent operations merely because they share a module. Do not modify v1 unless the request explicitly includes it. - -Preserve behavior unless the task explicitly changes it. Stop and report a decision when surfaces currently disagree on security or compatibility behavior; do not silently choose one. - -## Freeze observable behavior before editing - -Treat the legacy route or tool as an ordered program, not merely a bag of business logic. Before moving code, write a compact baseline for every in-scope entry point. Pin behavior no existing test covers with a characterization test only where it passes the `test-audit` gate; otherwise record it in the baseline and verify it by hand after the move. - -Capture all of these when they apply: - -- Accepted inputs, including trimming, blank omission, duplicate query keys, aliases, defaults, and bounds. -- Authentication and authorization order, minimum roles, resource membership, concealment, and exact error/status mapping. -- Exact success bodies, optional fields, status codes, redirects, cookies, headers, and binary or stream behavior. -- Mutation ordering, transaction boundaries, idempotency, no-ops, and observable state after each possible partial failure. -- Audit, notification, analytics, and billing timing plus exact semantic dimensions and attribution. -- Browser or protocol state ownership, concurrency isolation, expiry, callback ordering, and cleanup behavior. -- Every value newly crossing into HTML, JavaScript, SQL, URLs, logs, provider payloads, or another encoding context. - -Compare the old statement order with the proposed application lifecycle explicitly: - -```text -legacy parse/normalize - -> legacy authorization checks - -> branch-specific canonical lookup - -> mutation(s) - -> per-step side effects - -> response or redirect catch -``` - -Moving those steps under a wrapper may change behavior even when each individual call is reused. In particular: - -- `projectAudit` and `afterSuccess` run only after `execute` returns. They cannot describe earlier committed mutations when a later step throws. Make the compound mutation atomic or define explicit partial-result/failure projection semantics before migrating it. -- Operation metadata is executable policy. Adding a resource role to a workspace-only legacy read is an authorization change, not an architectural cleanup. -- A shared error policy does not automatically preserve route-local concealment, subclass ordering, browser redirects, or branch-specific messages. -- A shared contract does not automatically preserve manual `URLSearchParams` normalization or exact legacy response unions. -- A shared use case may own domain behavior while separate surface presenters still preserve different wire shapes. -- Per-flow identity is insufficient when another part of the flow remains in browser-global state such as one cookie. -- Passing a newly supported parameter through old rendering code creates a new security boundary even when the renderer itself is unchanged. - -Fail fast if the baseline cannot be established from code, tests, or an explicit product decision. Do not infer that behavior is unimportant because it was previously implicit. - -## Keep the layers distinct - -Use these responsibilities: - -1. Authentication adapter: verify the surface credential or trusted execution context and construct a `Principal`. -2. Route or tool adapter: select rate policy, parse its contract, translate input, call the application use case, and render its own result. -3. Application use case: load canonical context, compare asserted scope, authorize the semantic operation, execute business behavior, project semantic audit, and trigger shared domain effects. -4. Manager or repository: perform database and storage reads or writes using canonical identifiers and scope. Never accept credentials or principals. -5. Presenter: return only the surface success body or typed binary descriptor. Never construct auth, rate, or error behavior. - -For ordinary public JSON routes, preserve this order: - -```text -IP abuse limit - -> authenticate - -> build Principal - -> operation rate limit - -> parse surface contract - -> application use case - -> canonical load - -> asserted-scope concealment - -> current authorization - -> manager read or mutation - -> semantic audit - -> shared domain effects - -> surface presenter -``` - -Internal routes may omit the IP bucket or operation limit only through an explicit policy with a reason. Usage billing, storage quota, cost admission, and concurrency are separate from request-rate limiting. - -Never query API keys or sessions from the application layer. Never add fallback identity or authorization behavior. Propagate infrastructure failures instead of turning them into not-found or forbidden results. - -## Define the semantic operation once - -Add one stable entry to the target domain's operation registry: - -```ts -rename: defineWorkspaceOperation({ - id: 'widgets.rename', - minimumRole: 'write', - workspaceApiKey: 'allow', - capability: 'widgets.use', - principalKinds: ['session', 'personal_api_key', 'workspace_api_key', 'delegated'], - delegatedServices: ['copilot'], -}) -``` - -Do not create internal-, public-, or Copilot-specific versions of the same semantic operation. If two callers have materially different business or transactional semantics, define separate semantic operations and use cases and explain the distinction. - -Choose principal kinds from actual behavior. Do not accept every principal merely because the use case is shared. Workspace API keys have a write ceiling and cannot satisfy admin operations. The operation definition must fail fast when its role, workspace-key policy, and principal kinds disagree. +Inventory every entry point before editing: internal routes, public/versioned routes, Copilot tools (aliases, resume paths, polymorphic branches), other tool servers, executors, jobs; plus current authentication, authorization, workspace assertions, concealment, manager call chains, audit/notification/analytics/billing effects, error mapping, rate-limit identity, rollout gates, quota and concurrency admission. -`capability` is required: a static, operation-declarable capability (not parameterized, not principal-wide), or `'none'` with a `// permission-group-exempt: ` comment directly above it. If `principalKinds` includes `oauth_access_token`, `oauthScope` (`api:read` | `api:write` | `search:read`) is required. `defineWorkspaceOperation` throws at definition time on any violation. See `add-permission-group-item`. +Classify each as `migrate`, `defer` or `non-goal`. Don't migrate adjacent operations because they share a module; don't touch v1 unless asked. Preserve behavior unless the task changes it; **when surfaces disagree on security or compatibility, stop and report** rather than silently picking one. -Route declarations, tool adapters, and use cases must use the same literal operation. Runtime operation selection is permitted only from a trusted, code-defined registry. Never accept an operation ID or permission tag from an HTTP body, model argument, or other untrusted input. +## Freeze observable behavior -### Unified selector execution is one operation +Treat the legacy route or tool as an ordered program, not a bag of business logic. Write a compact baseline per in-scope entry point (pin uncovered behavior with a characterization test only where it passes `test-audit`; otherwise verify by hand after the move): -Dynamic selector dispatch is the deliberate instance of trusted runtime selection. Define and -authorize `selectors.execute` once: it means "enumerate options while configuring a workflow or -workspace resource." The browser supplies only a selector key from the exhaustive browser-safe -manifest, scope, allowlisted context, and list/detail request. After canonical scope authorization, -the application use case selects the matching attachment from the exhaustive server-only registry. +- Accepted inputs: trimming, blank omission, duplicate query keys, aliases, defaults, bounds. +- Auth order, minimum roles, membership, concealment, exact error/status mapping. +- Exact success bodies, optional fields, statuses, redirects, cookies, headers, binary/stream behavior. +- Mutation order, transaction boundaries, idempotency, no-ops, state after each partial failure. +- Audit/notification/analytics/billing timing, dimensions and attribution. +- Browser or protocol state ownership, concurrency isolation, expiry, callback ordering, cleanup. +- Every value newly crossing into HTML, JS, SQL, URLs, logs, provider payloads or another encoding. -Provider and internal attachments are trusted implementation adapters under that semantic operation, -not separate application operations. Do not create one operation per selector, provider, or listing -endpoint. Attachments may choose only code-defined credential/service binding, destination policy, -provider primitive, and projection behavior; they must not accept a module, provider, service, -operation kind, origin, or permission tag from the request. The `selectors.execute` use case owns -reference resolution, credential authorization, provider invocation, sanitization, and safe result -projection end to end. +Then compare the legacy statement order (parse → authorize → branch-specific lookup → mutations → per-step effects → response/redirect catch) with the wrapper's lifecycle. Moving steps under the wrapper changes behavior even when each call is reused: -## Implement the application use case +- `projectAudit` and `afterSuccess` run only after `execute` returns, so they cannot describe earlier committed mutations when a later step throws. Make the compound mutation atomic, or define partial-result semantics first. +- Operation metadata is executable policy: adding a resource role to a workspace-only legacy read is an authorization change, not a cleanup. +- A shared error policy doesn't preserve route-local concealment, subclass ordering, redirects or branch-specific messages; a shared contract doesn't preserve manual `URLSearchParams` normalization or legacy response unions. +- Per-flow identity is insufficient when part of the flow lives in browser-global state (one cookie). +- Passing a newly supported parameter through old rendering code creates a new security boundary even if the renderer is unchanged. -Use `defineAuthorizedWorkspaceUseCase` directly or a thin domain binding that supplies domain-specific authorization options: +If the baseline can't be established from code, tests or an explicit product decision, fail. Implicit behavior is not unimportant behavior. -```ts -export const renameWidget = defineAuthorizedWorkspaceUseCase({ - operation: widgetOperations.rename, - resolveContext: ({ input }: { input: RenameWidgetInput }) => - loadCanonicalWidgetContext(input.id, input.assertedWorkspaceId), - authorizationOptions: { delegation: widgetDelegationPolicy }, - execute: async ({ input, context }) => renameWidgetRecord({ - workspaceId: context.workspaceId, - widgetId: context.resourceId, - name: input.name, - }), - projectAudit: ({ result }) => ({ - action: AuditAction.WIDGET_UPDATED, - resourceType: AuditResourceType.WIDGET, - resourceId: result.id, - resourceName: result.name, - }), - afterSuccess: ({ context }) => notifyWidgetsChanged(context.workspaceId), -}) -``` +## Define the operation once -Adapt the example to the domain's real authorization options; do not copy invented field names. +One registry entry via `defineWorkspaceOperation`. No internal-, public- or Copilot-specific variants of one semantic operation; if two callers have materially different business or transactional semantics, define two operations and explain why. -The wrapper must own this lifecycle: +- Choose principal kinds from actual behavior, not "the use case is shared so accept everything". Capability and OAuth scope rules: see `add-permission-group-item`. +- Routes, tool adapters and use cases use the same literal operation object. Runtime selection only from a trusted code-defined registry; never take an operation id or permission tag from a body, model argument or other untrusted input. `selectors.execute` is the deliberate instance: one operation, with selector attachments as trusted adapters under it (see `add-selector`). -1. Reject disallowed principal kinds before protected loading. -2. Load canonical context and conceal asserted-scope mismatches as required. -3. Authorize the operation using current policy state. -4. Execute the manager or repository primitive. -5. Project audit from authoritative results. -6. Await shared post-success effects. +## Implement the use case -Do not call shared authorization, principal audit attribution, or `recordAudit` manually from an ordinary migrated use-case body. Use `projectAudit` only when the operation has semantic audit. Return no audit entries for authoritative no-ops. Keep product analytics such as `captureServerEvent` surface-specific through the adapter's success hook. +Use `defineAuthorizedWorkspaceUseCase` or a thin domain binding (like `authorized-workspace-file-use-case.ts`). The wrapper owns the lifecycle: reject disallowed principal kinds before loading, load canonical context and conceal asserted-scope mismatches, authorize against current policy, execute, project audit from authoritative results, await shared effects. -Inspect legacy orchestration before reusing it. If it already authorizes, audits, notifies, or captures analytics, call a lower-level primitive or remove duplicate responsibility for migrated callers. +- No manual authorization, audit attribution or `recordAudit` in the body. Return no audit entries for an authoritative no-op. Product analytics (`captureServerEvent`) stay surface-specific in the adapter's success hook. +- Inspect legacy orchestration before reusing it: if it already authorizes, audits, notifies or captures analytics, call a lower-level primitive or remove the duplicate for migrated callers. +- Never query API keys or sessions in the application layer, add fallback identity, or turn infrastructure failures into not-found or forbidden. +- Surface facts (a cursor's route) come in as input; return domain values and let each presenter project its wire shape. -Application code stays surface-neutral (`check:boundaries`): never `next/server` or `app/api/**`, and never a runtime import of a route contract object, presenter, or Copilot handler (contract types, schemas, and constants are fine); a surface fact, such as a cursor's route, comes in as input. Return domain values and let each surface presenter project its own wire result. +## Surfaces -## Adapt internal APIs +**Internal routes** (`defineInternalJsonRoute`): `internalSessionAuth` for session-only; `createInternalSessionOrExecutorAuth` only when signed executor delegation is genuinely supported (the operation then allows `delegated` from `executor`). Never turn an actorless legacy JWT into a fake session, owner or user. Omitting the IP or operation rate limit needs an explicit policy with a reason; billing, quota, cost admission and concurrency are separate from request rate. If routes repeat auth/parsing/rendering, improve the shared builder rather than adding a domain wrapper. -Use `defineInternalJsonRoute` for ordinary JSON routes. Explicitly declare the contract, authentication policy, semantic operation, rate policy, error policy, input mapping, use case, and presenter when the wire result differs. +**Public routes** (`defineV2JsonRoute`, see `v2-api-conventions`): rate-limit by credential subject, never a billed owner. Keep contracts separate when wire shapes differ, share primitive schemas and validators, import the same schema when the shape is genuinely identical, and never cast one surface's response into another's. -Use `internalSessionAuth` for session-only routes. Use `createInternalSessionOrExecutorAuth` only when the endpoint genuinely supports signed executor delegation; the semantic operation must then allow `delegated` principals from the `executor` service. Never turn an actorless legacy JWT into a fake session, owner, or user principal. +**Copilot**: call the exact use case other surfaces use, through one domain adapter built with `createCopilotApplicationAdapter` (it requires the trusted execution marker, builds the delegated principal once, and checks registry membership). -The internal adapter owns authentication and internal response envelopes. It must not implement workspace authorization. Preserve internal-only analytics through `onSuccess` after application success. +- Never build delegation from model-provided workspace ids, user ids, operation ids, resource scope or permission tags: model arguments are requested targets only. +- Tool handlers own aliases, resumable legacy names, abort checks and presentation; never managers, authorization or protected business logic. A Copilot-only compound action that is real domain behavior becomes a surface-neutral operation. +- Resolve references only through an authorized resolver under the intended operation (a code-defined operation object, never a string). Reuse a principal only within one request; reauthenticate across resumed tool calls, executor callbacks, background work, upload legs and finalization, and long-running provider operations. Prefer one use case (`renameWidgetByReference`) when resolve and execute are one business operation or need a consistent snapshot. +- An explicitly best-effort command coordinating several operations needs hard input and expansion caps, cancellation checkpoints, partial-result semantics, audit behavior and rate/quota policy. Keep it exceptional. +- Map typed errors to safe tool results; unknown errors become generic retryable messages with full causes in server logs. Never return raw database or storage errors to the model. -Keep the route module declarative. If several internal routes repeat authentication, parsing, error rendering, or response construction, improve the shared internal route builder instead of adding a domain-specific route wrapper. +**Other tool runtimes**: one shared principal adapter per runtime, the same use case, the tool protocol's own retry/cancellation semantics, and server-authored workspace and subject scope. An internal caller is not trusted to bypass authorization: it supplies an explicit principal or a deliberately designed service/delegation principal. External tool endpoints authenticate once, at the adapter. -## Adapt public or versioned APIs +## Identity and attribution -Use the appropriate public/versioned route builder, such as `defineV2JsonRoute`, with API-key authentication, explicit semantic operation and rate policy, external error projection, input mapping, application use case, and an external presenter. +Workspace keys authorize as the workspace, independent of creator membership; delegated principals re-check subject, workspace, audience, expiry, execution and resource scope. Keep structured `PrincipalActor` metadata in audit. If a required legacy user column can't represent the real actor, label the compatibility attribution explicitly; never pretend it is the acting human. If the principal model can't express a caller's authority, stop and extend it deliberately. -Authentication and HTTP formatting may differ from internal APIs; authorization and business behavior must not. Rate-limit using the credential or principal subject, never a billed owner. Resolve billing attribution only for billing, quota, or legacy required-user fields. +## Special operations -Keep surface contracts separate when their wire shapes differ. Reuse shared primitive schemas and domain validators for invariants such as IDs, names, bounds, and formats. Do not maintain duplicate internal and external schemas merely because the routes are separate; import the same schema when the wire shape is genuinely identical. Never cast one surface response into another. +Don't force these through an ordinary JSON migration: -Keep v1 middleware and routes unchanged unless explicitly included. +- Uploads/multipart: bind immutable credential identity, reauthorize control legs and finalization, make durable completion idempotent. +- Large bodies: authenticate and run cheap admission before bounded buffering. +- Binary/streaming: binary/stream builders and typed descriptors. +- Bulk/recursive: deduplicate and cap inputs and expansion, load everything canonically, define atomic vs best-effort. +- Polymorphic tools: select the operation only after trusted target-kind resolution. +- Multi-resource transactions: canonical scope predicates; audit from authoritative affected rows. -## Adapt Copilot +Stop and report a missing design rather than weakening identity, authorization, limits or errors. -Copilot is a surface adapter, not a separate application layer. If an HTTP or other surface already uses an application use case, Copilot must call that exact use case rather than reimplementing protected business behavior under `lib/mothership`. +## Tests -Create one domain-level Copilot application adapter with `createCopilotApplicationAdapter` instead of constructing delegated principals in every tool: +Own each risk at exactly one boundary: -```ts -executeCopilotWidgetUseCase(context, renameWidget, input, { resourceId }) -``` +- **Use-case tests**: authorization, principal-kind rejection before loading, workspace assertion mismatch, delegated scope, not found, conflict, no-op, audit from authoritative results, and infrastructure failures propagating as 5xx (never not-found/forbidden). +- **One `*.integration.ts`**: canonical active lookup, workspace-predicated writes, archived resources, affected rows, DB error propagation. +- **Surface tests** only for surface-specific risk (a v2 envelope or rate header, a Copilot forged-scope rejection, a pinned legacy redirect/cookie). Don't restate the registry or the builders' auth-before-parse per surface. -That adapter must: +When the change introduces them: inject a failure after each independently committing step and assert persisted state and effects; overlap stateful browser/provider flows to prove each callback consumes only its own state; feed hostile values through every newly connected input that reaches HTML, inline JS, URLs, logs or provider requests. -- Require a trusted server-authored Copilot execution marker. -- Require the authenticated subject, canonical workspace, tool-call or execution identity, and required audience or lifecycle scope. -- Construct the shared delegated `Principal` in one place. -- Optionally bind the canonical resource scope after trusted resolution. -- Verify that the use case exposes a registered code-defined operation. -- Use the domain's exact immutable operation registry so operation-object membership and identity are checked centrally. -- Call the application use case directly. +Don't claim a check passed unless it completed. -Never construct authoritative delegation from model-provided workspace IDs, user IDs, operation IDs, resource scope, or permission tags. Model arguments are requested targets only and must be checked against trusted execution context and canonical data. +## Parallel work -Tool handlers own argument aliases, resumable legacy names, abort checks, tool-call reporting, and tool-specific presentation. They must not query managers directly for protected operations, manually authorize, or implement protected business behavior. If a Copilot-only compound action expresses real domain behavior, define a surface-neutral domain operation and application use case for it. - -A Copilot reference helper may translate a path to a resource only by calling an authorized application resolver under the intended semantic operation. Passing a code-defined operation object is acceptable; passing a model-provided operation string is not. An immediate same-request resolver followed by the operation may reuse one trusted principal, though the application operation still performs its own canonical authorization. Fresh authentication and authorization are required across lifecycle boundaries such as resumed tool calls, executor callbacks, queued or background work, upload control legs and finalization, durable completion, and long-running provider operations. When resolution and execution form one business operation, need a consistent snapshot, or appear repeatedly together, prefer a top-level application use case such as `renameWidgetByReference`. - -Surface adapters must not compose protected mutations. An atomic compound action requires one top-level semantic domain operation and application use case that owns the transaction and authoritative result. An explicitly best-effort application command may coordinate multiple operations only when it defines hard input and expansion caps, cancellation checkpoints, partial-result semantics, audit behavior, and rate/quota policy. Keep composition exceptional and explicit; ordinary tools should use the shared execution adapter. - -Map expected typed errors to safe tool results. Unknown errors must become generic system/retryable messages while retaining full causes in server logs. Never return raw database or storage errors to the model. - -## Adapt other internal or external tools - -Treat every tool runtime as a surface adapter: - -- Normalize its already-authenticated execution context into an existing `Principal` through one shared adapter for that runtime or domain. -- Call the same application use case used by HTTP and Copilot surfaces. -- Preserve the tool protocol's input, output, retry, and cancellation semantics. -- Keep authoritative workspace and subject scope server-authored. - -An internal caller is not automatically trusted to bypass authorization. It must supply an explicit principal or use a deliberately designed service/delegation principal. If the current principal model cannot express its authority, stop and extend the identity model intentionally; do not fall back to an owner, uploader, creator, or arbitrary user ID. - -External tool endpoints authenticate at their adapter exactly like public APIs. Do not authenticate again inside the application use case. - -## Preserve identity and attribution - -- Session and personal-key principals authorize through current human workspace permission. -- Personal API keys also respect the workspace's personal-key policy. -- Workspace keys authorize as the workspace under explicit operation policy and the write ceiling, independent of creator membership. -- Delegated principals re-check the current subject and their workspace, audience, expiry, execution, and resource scope. -- Billing owners are attribution for billing or legacy required columns only, never authorization, rate identity, delegated identity, audit actor, or human analytics identity. -- Preserve structured `PrincipalActor` metadata in semantic audit. - -If a required legacy user column cannot represent the real actor, label the compatibility attribution explicitly. Never pretend it is the acting human. - -## Handle special operations explicitly - -Do not force these through an ordinary JSON migration: - -- Upload or multipart lifecycles: bind immutable credential identity, reauthorize control legs and finalization, and make durable completion idempotent. -- Large bodies: authenticate and perform cheap admission before bounded buffering. -- Binary or streaming responses: use binary/stream builders and typed descriptors. -- Bulk or recursive operations: deduplicate and cap inputs and expansion, load all resources canonically, and define atomic versus best-effort behavior. -- Polymorphic tools: select the semantic operation only after trusted target-kind resolution; do not route unrelated branches through one domain registry. -- Multi-resource transactions: keep canonical scope predicates and derive audit from authoritative affected rows. - -Stop and report a missing design rather than weakening identity, authorization, limits, or errors. - -## Test each risk at one boundary - -Run the `test-audit` authoring gate before writing any test. Prefer one E2E/integration run over the real boundary; where a use-case unit test is justified, list its failure modes before writing code (CLAUDE.md → Testing). Own each risk at exactly one boundary: - -- Application use-case tests own authorization, principal-kind rejection before canonical loading, workspace assertion mismatch, delegated scope, not found, conflict, no-op, audit derived from authoritative results, and infrastructure failures (storage, rate-limit, provider, or database errors raised by delegated services) propagating as 5xx-mapped errors — never converted to not-found or forbidden. -- One `*.integration.ts` owns repository semantics: canonical active lookup, workspace-predicated writes, archived resources, authoritative affected rows, and database error propagation. -- Add a surface test only for a surface-specific risk (for example, a v2 envelope or rate header, a Copilot forged-scope rejection, or a legacy redirect/cookie behavior the characterization baseline pinned). Do not restate the operation registry or the shared builders' auth-before-parse behavior per surface. - -Risks that usually earn a test when the change introduces them: - -- Failure sequencing: inject a failure after each independently committing step and assert persisted state plus audit, analytics, and notification effects. -- Concurrency: overlap stateful browser or provider flows and prove each callback consumes only its own state and return destination. -- Rendering boundaries: exercise hostile values for every newly connected input that reaches HTML, inline JavaScript, URLs, logs, or provider requests. - -Run at minimum: - -```bash -bun run --cwd apps/sim test -bunx biome check -bunx turbo run type-check --filter=@sim/app --filter=@sim/auth -bun run check:audits -git diff --check -``` - -Do not claim a check passed unless it completed successfully. - -## Work safely in parallel - -- Assign non-overlapping route modules and caller sets. Two methods in one route file are one ownership unit. -- Treat operation registries, contract families, route policies, and shared surface adapters as merge hotspots. -- Keep shared core foundations owned by one task; ordinary domain migrations should consume them without modifying them. -- Preserve unrelated working-tree changes. Never stage proposal docs, lockfile drift, or another agent's edits. -- Do not commit, push, or open a PR unless requested. +Assign non-overlapping route modules and caller sets (two methods in one route file are one unit). Operation registries, contract families, route policies and shared adapters are merge hotspots. Shared core foundations are owned by one task; domain migrations consume them without modifying them. ## Hand off -Report: - -1. Semantic operation, role, workspace-key policy, and principal kinds. -2. Migrated, deferred, and non-goal entry points. -3. Behavior preserved per internal, public, Copilot, and other tool surface. -4. Identity construction and authoritative scope source for each surface. -5. Files changed and shared merge hotspots. -6. Tests and checks run with results. -7. Remaining risks or blockers. Fail fast when an invariant could not be implemented. +Report: the operation (role, workspace-key policy, principal kinds); migrated, deferred and non-goal entry points; behavior preserved per surface; identity construction and scope source per surface; files changed and merge hotspots; tests and checks with results; remaining risks or invariants that couldn't be implemented. diff --git a/.agents/skills/react-query-best-practices/SKILL.md b/.agents/skills/react-query-best-practices/SKILL.md index 81e86004947..839dc20a616 100644 --- a/.agents/skills/react-query-best-practices/SKILL.md +++ b/.agents/skills/react-query-best-practices/SKILL.md @@ -12,42 +12,12 @@ Arguments: User arguments: $ARGUMENTS -## Context +Review the scope against `.claude/rules/sim-queries.md` (keys, hooks, mutations, optimistic updates, server prefetching) and these judgment calls no check catches: -This codebase uses React Query (TanStack Query) as the single source of truth for all server state. All query hooks live in `hooks/queries/`. Zustand is used only for client-only UI state. Server data must never be duplicated into useState or Zustand outside of mutation callbacks that coordinate cross-store state. +- Warm data on hover/focus with `prefetchQueryOnIntent` (`hooks/queries/utils/prefetch-query-on-intent.ts`); never temporarily enable a mounted hidden observer, which can stay active after focus restoration and refetch data for closed UI. +- When gating a query by view or modal state, move every consumer to the active query too: imperative refresh and pagination, loading and error feedback, and data-derived controls must never read a disabled query or a previous key's placeholder data. +- Compose caller `enabled` with required-param guards (`Boolean(id) && (options?.enabled ?? true)`); spreading options after the guard lets `{ enabled: true }` re-enable an invalid request. +- A disabled query can still report `isPending: true`. Aggregate loading only over enabled queries, or an optional query holds the whole surface in a permanent loading state. +- Authorization and policy queries fail closed: pending or errored data must not get the same fallback as a loaded unrestricted policy; disable guarded actions until the query succeeds. -## References - -Read these before analyzing: -1. https://tkdodo.eu/blog/practical-react-query — foundational defaults, custom hooks, avoiding local state copies -2. https://tkdodo.eu/blog/effective-react-query-keys — key factory pattern, hierarchical keys, fuzzy invalidation -3. https://tkdodo.eu/blog/react-query-as-a-state-manager — React Query IS your server state manager - -## Rules to enforce - -### Query keys and hooks -Enforce `.claude/rules/sim-queries.md` (key factory with `all` + plural prefixes, `signal` forwarding, named `staleTime` constants reused by prefetches, `keepPreviousData` only on variable keys, `requestJson` boundary). Additionally: -- Key factories live next to their hooks — except a factory, standalone fetcher/mapper, or `staleTime` constant that a server module (a `prefetch.ts`, route, block, trigger) imports, which must live in a non-`'use client'` module under `hooks/queries/utils/` per `.claude/rules/sim-queries.md` (a `'use client'` export called from the server crashes SSR) -- Use `enabled` to prevent queries from running without required params -- Warm data for hover/focus intent with `prefetchQueryOnIntent(queryClient, sharedQueryOptions)` (`hooks/queries/utils/prefetch-query-on-intent.ts`, which cleans up a speculative failure per `sim-react-performance.md`); never temporarily enable a mounted hidden observer, which can remain active after focus restoration and refetch data for closed UI -- When gating a query by view or modal state, move every consumer to the active query too: imperative refresh/pagination, loading and error feedback, and data-derived controls must never read a disabled query or placeholder data from a previous key -- Compose caller-controlled `enabled` options with required-param guards (`Boolean(id) && (options?.enabled ?? true)`). Never spread options after an internal guard, because `{ enabled: true }` can silently re-enable an invalid request. -- A disabled query can still report `isPending: true`. Aggregate loading state only for queries that are applicable/enabled, or an optional query can hold the whole surface in a permanent loading state. -- Deferred authorization or policy queries must fail closed. Do not give pending/error data the same fallback as a successfully loaded unrestricted policy; disable guarded actions until the policy query succeeds. -- Server prefetches must call the authorized use case, apply the route presenter/response schema, and reuse the client's exact key, mapper, and stale time. Keep all fallible auth/read/parse work inside `queryFn` so an optional warm cannot fail the page, and never bypass a route that redacts fields. - -### Mutations -Enforce `.claude/rules/sim-queries.md` "Mutation Hook" (targeted invalidation, `onMutate`/`onError` rollback, mutation objects out of `useCallback` deps). Additionally: -- Plain mutations invalidate in `onSuccess`; optimistic mutations reconcile in `onSettled` (fires on success and error) with rollback in `onError` — see `.claude/rules/sim-queries.md` "Mutation Hook" / "Optimistic Updates" - -### Server state ownership -- Never copy query data into useState. Use query data directly in components. -- Never copy query data into Zustand stores (exception: mutation callbacks that coordinate cross-store state like temp ID replacement) -- The query cache is not a local state manager — `setQueryData` is for optimistic updates and the server-prefetch seeding case in `.claude/rules/sim-queries.md` "Server prefetching", nothing else -- Forms are the one deliberate exception (a keyed form child initialized lazily from loaded query data) — the pattern is owned by `/you-might-not-need-an-effect` "Query-backed forms"; do not duplicate its finding - -## Steps - -1. Read the references above to understand the guidelines -2. Analyze the specified scope against the rules listed above -3. If fix=true, apply the fixes. If fix=false, propose the fixes without applying. +If fix=true, apply the fixes; if fix=false, propose them without applying. diff --git a/.agents/skills/ship/SKILL.md b/.agents/skills/ship/SKILL.md index 119a5ee218b..9c23083c0ff 100644 --- a/.agents/skills/ship/SKILL.md +++ b/.agents/skills/ship/SKILL.md @@ -4,177 +4,48 @@ description: Commit, push, and open a PR to staging in one shot — runs the cle argument-hint: "[optional context or scope notes]" --- -# Ship Command +# Ship -You help ship code by creating commits, pushing to the remote branch, and creating PRs in the user's voice. +Don't ask the user to confirm the commit message or PR description before executing. -## Your Task +1. **Sync check**: `git fetch origin staging && git log --oneline origin/staging..HEAD`. Every listed commit must be one you can attribute to this session; a branch cut from a stale local `staging` silently drags in unrelated commits. If you see any you don't recognize, fix it before committing new work: + - Commit WIP as a temp commit before rebasing and drop it after (never `git stash`: the stash list is shared across every worktree of the repo, so another session can pop your entry or you theirs). + - Try `git rebase origin/staging`, then re-run the log: a rebase can replay stray commits onto the new base without any conflict. + - Else: note your SHAs, `git checkout -B origin/staging && git cherry-pick `, re-check the log. +2. **Commit message**: `type(scope): description`. Types in use: `fix`, `feat`, `improvement`, `chore`, `docs`, `perf`, `refactor`, `test`, `ci`. Scope is a short identifier (`undo-redo`, `api`, `ui`). +3. **Cleanup and tests** + - If the diff touches UI code (any non-test `.tsx`, or `apps/sim/components/`, `hooks/`, `stores/`), run `/cleanup` so its fixes land in this commit. + - Otherwise, if it adds or changes tests, run `/test-audit audit `; delete tests that fail the authoring gate rather than shipping them. + - Run the changed tests plus the tests beside changed source with `bun run --cwd test `. A failure aborts ship. +4. **Migrations**: only if the diff touches `packages/db/migrations/**` or `packages/db/schema.ts`, run `/db-migrate`. +5. **Local gate**: run the commands in root `CLAUDE.md` → "How your work is checked", each block as written and never wrapped in a backgrounded loop (a bare `wait` swallows exit codes). Also run `bun run check:sdk-names-frozen origin/staging`; `check:audits` skips it because it diffs against a base ref. Stage whatever `bun run generate` rewrote. Fix the cause of any failure; never silence it. + - Domain generators outside `bun run generate` (`mship-tools:generate`, `generate:pi-model-catalog`, `scripts/generate-docs.ts`) read sources most worktrees lack; run one and its `:check` only when this diff touches its inputs. +6. **Commit and push.** Use `--force-with-lease` if step 1 rewrote history on an already-pushed branch. +7. **PR**: `gh pr create --base staging --title "" --body ""`, filling in `.github/PULL_REQUEST_TEMPLATE.md`. Then re-fetch and confirm `git log --oneline --reverse origin/staging..HEAD` and `gh pr view --json commits -q '.commits[].messageHeadline'` list the same commits in the same order; if not, redo step 1 and force-push. -When the user runs `/ship`: +## Voice -1. **Check git status** - See what files have changed -2. **Sync check**: `git fetch origin staging && git log --oneline origin/staging..HEAD`. The list must contain ONLY commits you can attribute to this session (recognizable subjects/SHAs) — a worktree/branch cut from a stale local `staging` silently drags in unrelated commits. - - If it shows commits you don't recognize, fix it now, **before** staging/committing any new work (step 7 hasn't run yet): - - If the working tree has uncommitted changes, stash them first so the rebase below isn't blocked by dirty state, and pin the entry by SHA — the stash list is shared across every worktree of the repo, so `stash@{0}` and `git stash pop` can grab another session's entry: - ```bash - git stash push -u -m ship-sync-fix && SHIP_STASH=$(git rev-parse 'stash@{0}') - # once the branch is fixed (`git stash drop` rejects a raw SHA, so resolve the pinned - # entry's current stash@{n} and drop only that; an empty lookup drops nothing): - git stash apply "$SHIP_STASH" && - SHIP_STASH_REF=$(git stash list --format='%gd %H' | awk -v s="$SHIP_STASH" '$2==s{print $1}') && - { [ -z "$SHIP_STASH_REF" ] || git stash drop "$SHIP_STASH_REF"; } - ``` - - Try `git rebase origin/staging` first. - - **A rebase finishing without conflicts does NOT by itself mean the branch is clean** — it can replay stray commits onto the new base with no conflict at all. After the rebase (clean or not), re-run `git log --oneline origin/staging..HEAD` and re-check the commit list against what you recognize. - - If the rebase conflicted on unrecognized commits, OR finished cleanly but the log still shows them, abandon it (`git rebase --abort` if mid-rebase) and rebuild, in this exact order: - 1. Still on ``, list `git log --oneline --reverse origin/staging..` and write down ONLY the SHA(s) that are this session's work — the range also contains the stray commits, so cherry-picking the whole range recreates the polluted branch. Capture them now; after step 4 they are no longer in `HEAD`. - 2. `git checkout ` (required if an interrupted attempt left you on `ship-sync-tmp`) - 3. `git branch -D ship-sync-tmp 2>/dev/null || true` - 4. `git checkout -b ship-sync-tmp origin/staging` - 5. `git cherry-pick` the captured SHAs, oldest-first. Resolve conflicts. - 6. `git branch -f HEAD && git checkout && git branch -D ship-sync-tmp` - - Re-verify with `git log --oneline origin/staging..HEAD` — it must list only commits you recognize before you proceed to committing new work. -3. **Generate a commit message** following this format: `type(scope): description` - - Types: `fix`, `feat`, `improvement`, `chore` - - Scope: short identifier (e.g., `undo-redo`, `api`, `ui`) - - Keep it concise -4. **Run the cleanup and test gates** - - If the diff modifies UI code (any non-test `.tsx` file, or anything under `apps/sim/components/`, `apps/sim/hooks/`, or `apps/sim/stores/`), run `/cleanup`. It fans out the React/UI passes (effects, memo, callbacks, state, React Query, emcn, url-state), the comment pass, and the test-audit pass, and applies fixes so they land in this commit. - - Otherwise, if the diff adds or changes tests (`*.test.ts(x)`, `*.integration.ts`, `**/e2e/**`, `apps/sim/scripts/test-*-e2e.ts`), run `/test-audit audit ` on its own. Every new or changed test must pass the authoring gate; delete the ones that don't rather than shipping them. - - Then run the test files the diff adds or changes, plus the existing tests beside changed source files, with `bun run --cwd test ` (`bun run --cwd apps/sim test ` for the app; `*.integration.ts` needs the setup in `.claude/rules/sim-testing.md`). A failing test aborts ship. - - Then run root `bun run test` from the repo root. It chains `test:scripts` (the `scripts/*.test.ts` suite CI runs) before every workspace suite; workspace-scoped runs skip it, which is how a `scripts/check-*.test.ts` failure has reached CI. A failing test aborts ship. -5. **Run migration safety** — only if the diff touches `packages/db/migrations/**` or `packages/db/schema.ts`: - - Run `/db-migrate` to review the migration for zero-downtime safety (expand/contract phasing, backward-compatibility with the deployed app version). - - `(cd packages/db && bunx drizzle-kit generate && git status --porcelain ./migrations)` must print nothing (CI's schema/migration sync step). - - `bun run check:migrations origin/staging` must pass (staging is the PR base). Do not silence a flagged statement with a `-- migration-safe:` annotation unless `/db-migrate` confirmed the old code no longer depends on it; otherwise split the destructive change into a later deploy. -6. **Run pre-ship checks** from the repo root before staging. This has two phases: first **regenerate** every committed artifact so generated files never drift into a CI failure (this is what catches things like `agent-stream-docs` going stale after a `models.ts` edit), then run the **full audit suite** CI's `lint` job enforces. Both phases abort ship if any generator or audit fails: their runners (`scripts/generate-all.ts`, `scripts/run-audits.ts`) collect each job's exit code and exit non-zero, so never replace them with a backgrounded loop and a bare `wait`, which swallows child exit codes. +- Short, direct bullets, active voice, no fluff. +- Testing names what actually ran: test files, lint, `check:audits`, `check:migrations` when migrations changed, E2E artifacts. +- Drop template sections that don't apply; no screenshots section unless UI changed. +- No `Co-Authored-By` lines in commits. - **Phase A — regenerate the always-in-repo committed artifacts, then let step 7 stage whatever changed.** Run the umbrella generator. It derives its list from package.json (every `generate:` that has a matching `check:`, plus `skills:sync`; see the header of `scripts/generate-all.ts`), so it covers every repo-local generator an ordinary code change can drift (a `models.ts` edit drifts `agent-stream-docs` and the SDK fixture catalog, a tool change drifts `tool-metadata`), runs them in the order their inputs require, and each is idempotent (a no-op when already in sync): - ```bash - # A non-zero exit means a generator FAILED: the summary names it and its output is above. Fix it - # before shipping; a silently-failed generate leaves a stale artifact that Phase B / CI then - # rejects. Keep the `exit 1`: it makes the block's own status non-zero so a caller actually stops. - bun run generate || { echo "❌ generator(s) failed — do not ship"; exit 1; } - echo "✅ artifacts regenerated" - ``` - Then `git status --short` to see what regenerated — those files must be staged in step 7 alongside your own changes. +## What to omit - **Do NOT blanket-run the domain generators here.** `mship-tools:generate` merges Sim's tool contracts into the base tool catalog in the **external** Mothership worker checkout (`/worker/packages/contracts/tool-catalog-v1.json`), which most worktrees lack, so it hard-fails with `ENOENT` and would abort ship for an unrelated reason. The other mothership contracts in `apps/sim/lib/mothership/generated/` are copied in by the worker's `contracts:sync`, never generated here. `generate:pi-model-catalog` (under `apps/sim`) likewise regenerates from the installed Pi package, not repo source. `scripts/generate-docs.ts` rewrites the integration docs and client-safe catalog; run it when this PR changes their block/icon/landing-content inputs or when `check:integration-catalog` reports drift, then review its broad generated diff. Only when **this PR's diff actually touches** a domain generator's input do you regenerate it deliberately and run its matching `:check` (e.g. `bun run mship-tools:check`) — with the external source present. - - **Phase B — run lint + every audit CI enforces, in parallel, and abort ship if any fails.** Before running the commands, compare this list with `.github/workflows/checks.yml`; when CI adds an audit, run it and update this skill instead of trusting a stale snapshot. The env-flag audit is currently an inline workflow block rather than a package script: when `apps/sim/lib/core/config/env-flags.ts` changed, run that current workflow block verbatim instead of copying a second version into this skill. Run `bun run lint` first (it autofixes formatting and mutates files, so don't parallelize it with the read-only audits), then run the base-sensitive block-registry check, then fan the independent audits out and collect exit codes: - ```bash - # autofix formatting first (mutating; not parallel-safe with the audits). Gate its exit too — - # a non-zero lint (unfixable errors) must abort before the audits run, not be ignored. - bun run lint || { echo "❌ lint failed — do not ship"; exit 1; } - bun run apps/sim/scripts/check-block-registry.ts origin/staging || { - echo "❌ block registry audit failed — do not ship" - exit 1 - } - # Runs every audit CI runs, concurrently, and replays the output of any that fail. - # The audit list is derived in scripts/run-audits.ts — do not hand-list audits here. - # Workflow lint (actionlint) runs only in CI's "Lint workflows" step. - bun run check:audits || { echo "❌ audit(s) failed — do not ship"; exit 1; } - bun run type-check || { echo "❌ type-check failed — do not ship"; exit 1; } - # CI's "Security audit" `bun audit` step is `continue-on-error` — advisory only, not a gate — - # so it is deliberately not run here. - ``` - If Phase A regenerated a file, its matching `check:*` audit in Phase B now passes trivially — that parity is the point. Do not ship with any generator or audit failing; fix the cause (never silence it) and re-run. `check:migrations` is covered by step 5 and is not repeated here. -7. **Stage and commit** the changes with the generated message — including any files Phase A regenerated in step 6 -8. **Push to origin** using the current branch name — `--force-with-lease` if step 2's sync - check did any history rewrite (a clean rebase or a cherry-pick rebuild) on a branch that had - already been pushed once; a plain push would be rejected in exactly the polluted-remote case - step 2 exists to fix -9. **Create a PR** to staging with a description in the user's voice, then do a final content check — not a count check — comparing what actually landed: - ```bash - git fetch origin staging && git log --oneline --reverse origin/staging..HEAD - gh pr view --json commits -q '.commits[].messageHeadline' - ``` - Re-fetch first — comparing against a stale local `origin/staging` ref can mask real drift or - flag a false mismatch even when the branch and push are correct. `--reverse` makes the git log - oldest-first, matching the PR commit list's order — plain `git log` is newest-first, and a - positional/line-by-line comparison against the PR's oldest-first list can spuriously fail on - any multi-commit branch. These two lists must describe the same commits in the same order - (same subjects, the last one being the commit from step 7). If they don't match, the branch - still has a problem — redo step 2's fix and `git push --force-with-lease`. - -## Commit Message Format - -Based on the repo's commit history: - -``` -fix(scope): description for bug fixes -feat(scope): description for new features -improvement(scope): description for enhancements -chore(scope): description for maintenance -``` - -## What to Omit - -The repo is public. **Everything you publish — title, description, commit messages, and every later comment — must stand on its own without the incident that produced it.** Never include: +The repo is public. Everything you publish (title, body, commit messages, code and migration comments, later PR comments) must stand on its own without the incident that produced it. Never include: - Customer, company, or user names; workspace/user/org/KB/connector IDs; email addresses - Prod or staging operational data: log lines, DB rows, metrics, timestamps, incident details, canary/alert output - Infrastructure specifics: hostnames (incl. tenant subdomains), ARNs, internal URLs, env var values, secret names - Verbatim customer content: file names, document titles, sheet/column names, folder paths -Describe the bug by its mechanism, not by how you found it. "Expired OAuth credentials fail to refresh in the worker" — not "the Sheets canary failed at 16:31Z for workspace abc-123". Aggregate counts are fine once detached from the tenant ("1,379 PDFs failed"); the same number attributed to a named customer is not. Replace real examples with placeholders (``) rather than cutting them — the illustration is usually the useful part. +Describe the bug by its mechanism, not how you found it: "Expired OAuth credentials fail to refresh in the worker", not "the Sheets canary failed at 16:31Z for workspace abc-123". Replace real examples with placeholders (``) rather than cutting them. -**Measurements are not the problem; absolute production scale is.** Keep the numbers that justify a change — durations, ratios, before/after timings, test and audit counts. They are the evidence a reviewer needs, and stripping them makes the rationale unfalsifiable. What does not belong is anything that sizes production or a tenant: table and index byte sizes, row/chunk/document totals, dead-tuple counts, buffer and heap-fetch counts, worker or instance counts. "Visiting four times as many tuples took 5.1s and 9.7s on consecutive runs" is fine; "on a 132k-chunk index" or "reclaims ~19 GB" is not. The same rule applies to code comments and migration comments, which are published exactly like a PR body — this is the most commonly missed case, because they do not feel like publishing. +Keep timings, ratios, and test counts; drop anything sizing prod or a tenant (byte sizes, row/doc totals, instance counts). Code and migration comments are the most commonly missed case. -**Scrub before publishing, not after** — a leak is public the instant it posts, and editing later does not unsend the notification email. This applies to every PR you open, including ones created directly with `gh pr create` rather than through this skill. Grep the title, body, `git log origin/staging..HEAD`, AND the diff itself before publishing: +Scrub before publishing, not after: a leak is public the instant it posts. Grep the title, body, `git log origin/staging..HEAD`, and the diff: ```bash -# identities, IDs, infrastructure grep -niE 'customer-or-company-name|@[a-z0-9.-]+\.(com|io|ai)|[0-9a-f]{8}-[0-9a-f]{4}-|\.sharepoint\.com|arn:aws|https?://[a-z0-9.-]*\.internal' -# absolute production scale — byte sizes, k/M-scale entity counts, 7-figure totals grep -niE '[0-9][0-9.,]* ?(TB|GB)\b|[0-9]+(\.[0-9]+)?[kKmM][- ](row|chunk|document|vector|tuple|doc)|[0-9]{1,3}(,[0-9]{3}){2,}' ``` - -The second pattern deliberately allows ordinary engineering numbers (`5.1s`, `46 audits`, `2,921 tests`) and flags only production sizing. - -## PR Description Format - -Use this exact template in the user's voice (concise, bullet points): - -```markdown -## Summary -- bullet point describing what changed -- another bullet point if needed - -## Type of Change -- [x] Bug fix (or appropriate type) - -## Testing -Describe the checks, tests, and E2E artifacts run - -## Checklist -- [x] Code follows project style guidelines -- [x] Self-reviewed my changes -- [ ] Tests added/updated and passing (new tests pass the `test-audit` authoring gate) -- [x] No new warnings introduced -- [x] I confirm that I have read and agree to the terms outlined in the [Contributor License Agreement (CLA)](./CONTRIBUTING.md#contributor-license-agreement-cla) -``` - -## PR Creation Command - -Use this command structure: - -```bash -gh pr create --base staging --title "COMMIT_MESSAGE" --body "PR_BODY" -``` - -## Important Notes - -- Do not ask the user to confirm the commit message or PR description before executing -- The PR should be created against `staging` branch -- Keep descriptions concise and in active voice -- Match the user's previous PR style: direct, no fluff, bullet points -- **DO NOT add "Co-Authored-By" lines to commits** - keep commit messages clean - -## User's Voice Characteristics (based on previous PRs) - -- Short, direct bullet points -- No unnecessary explanation -- Testing section names what actually ran: the test files, lint, `check:audits`, (when migrations changed) `check:migrations`, and any E2E artifacts -- Checkboxes filled in appropriately -- No screenshots section unless UI changes diff --git a/.agents/skills/test-audit/SKILL.md b/.agents/skills/test-audit/SKILL.md index e7829f4f992..c03c805f7ef 100644 --- a/.agents/skills/test-audit/SKILL.md +++ b/.agents/skills/test-audit/SKILL.md @@ -15,12 +15,6 @@ but a test that cannot name the bug it catches is cost, not coverage. Read `.claude/rules/sim-testing.md` first: it defines the test layers, file naming, and the mechanics (global mocks, `@sim/testing`, performance rules). -## The three rules - -CLAUDE.md → Testing sets them: no unit tests after the code; prefer E2E at the real boundary, -ending in a verifiable artifact; list failure modes before testing in isolation. A mode you cannot -list is not a test you should write. This skill enforces them. - ## Authoring gate Before adding any test, answer all four. A missing answer means do not add it. @@ -38,22 +32,16 @@ Then check it against every junk pattern below. A match fails the gate unless th names the contract it independently guards. A test that would break under behavior-preserving refactoring asserts implementation, not behavior. -**Regression tests** must fail on the pre-fix code for the intended reason. Revert each guard of -the fix separately and watch the test named for that guard go red, then restore. A regression -test that never demonstrably failed proves the mock, not the fix. One regression at the owner -boundary covers the bug; do not replay it at every layer it crosses. +**Regression tests**: one at the owner boundary covers the bug; do not replay it at every layer +it crosses. ## Junk patterns - assertion-free or `toBeDefined()`-only tests; "renders without crashing"; -- restating declarations: block/tool/trigger/provider config (subBlock ids, params, outputs, URL - templates, header maps), constant tables, registries, enums, export lists — type-check and - `check:audits` own these; -- route/handler tests that mock every collaborator and assert `toHaveBeenCalledWith` on the mocks, - or re-assert a mock's canned return; +- re-asserting a mock's canned return; - mocks that implement the asserted behavior, or one mock standing in for different APIs; - Zod contract tests proving a schema accepts a valid object or rejects an obviously invalid one; -- React tests of text, class names, aria presence, snapshots, "calls onClick"; +- React tests of aria presence or "calls onClick"; - hook tests asserting query keys or fetch URLs; store tests of trivial setters; - tests of test infrastructure (mocks, factories, builders testing themselves); - source-text or import greps (`readFileSync(src)` + `toContain`); @@ -63,8 +51,6 @@ boundary covers the bug; do not replay it at every layer it crosses. - negative controls that pass for an unrelated reason (a different guard short-circuits first); - names or fixtures that promise more than the input exercises; - dead production code or exports whose only callers are tests. -- a hand-rolled `vi.mock` factory for a module `vitest.setup.ts` or `@sim/testing` already mocks, or a - local copy of a `@sim/testing` helper (`bun run check:test-patterns` fails on these). ## Retention bar @@ -125,11 +111,9 @@ For a whole subsystem or the whole repo: Never edit source or tests while Vitest is running in the same checkout. -1. Run the touched and sibling test files (`.claude/rules/sim-testing.md` → Running). -2. If production code changed: `bun run type-check` in that workspace. -3. `bun run check:audits` from the repo root (some audits list test files by path). -4. `bun run lint`, then `git diff --check`. -5. Report `git diff --shortstat` with production and test changes counted separately. +1. Run the touched and sibling test files (`.claude/rules/sim-testing.md` → Running), then the + root gate in `CLAUDE.md` → "How your work is checked" (some audits list test files by path). +2. Report `git diff --shortstat` with production and test changes counted separately. ## Handoff diff --git a/.agents/skills/tool-registry-boundary/SKILL.md b/.agents/skills/tool-registry-boundary/SKILL.md index c063d66e861..178f54c1faf 100644 --- a/.agents/skills/tool-registry-boundary/SKILL.md +++ b/.agents/skills/tool-registry-boundary/SKILL.md @@ -3,93 +3,32 @@ name: tool-registry-boundary description: Keep the executable tool registry out of client-reachable module graphs — when to read `@/tools/metadata` instead of `getTool`, how to measure whether an import edge pulls the registry, and how to regenerate the metadata artifacts. Use when touching `apps/sim/tools/registry.ts`, `tools/utils.ts`, `tools/params.ts`, or anything that calls `getTool`. --- -# Tool Registry Boundary Skill +# Tool Registry Boundary -You keep the 5,000+-tool executable registry out of module graphs that don't execute tools. - -## The rule - -> Client-reachable code reads tool **metadata**. Only code that actually executes a tool imports the **registry**. - -`@/tools/registry` is a 10,000+-line barrel importing every tool. External `ToolConfig` entries mix -plain data (`params`, `outputs`, `name`) with request/response closures, while -`InternalToolConfig` entries contain semantic input projection and load their server implementation -through `lib/internal/tool-operations/registry.server.ts`. Request closures can still reach SDK -clients, API helpers, and parsers, which is what makes the executable barrel expensive: reaching it -costs roughly 4,700 additional modules (measured; re-measure with `--verbose`). - -`getTool()` returns the whole `ExecutableToolConfig`, so a single `getTool` import anywhere in a client-reachable file drags all of it in. +Keep the 5,000+-tool executable registry out of module graphs that don't execute tools. `check:tool-registry-boundary` fails with the import chain when one does; this skill covers choosing the import and fixing a failure. ## Which module to import -| you need | import | notes | +| You need | Import | Cost | | --- | --- | --- | -| whether a tool id exists | `hasToolId` from `@/tools/tool-ids` | ~110 KB — the cheapest module | -| to resolve an unversioned name | `resolveToolId` from `@/tools/tool-ids` | | -| every tool id | `getToolIds` from `@/tools/tool-ids` | | -| a tool's params | `getToolParams` / `getToolMetadata` from `@/tools/metadata` | ~4 MB | -| a tool's declared outputs | `getToolOutputsMetadata` from `@/tools/metadata-outputs` | ~4 MB, separate on purpose | -| to **execute** a tool | `getTool` from `@/tools/utils`, or `getToolAsync` from `@/tools/utils.server` (async/workspace-context lookup) | server paths only | - -Three modules, cheapest first. Ids are their own artifact because resolution and existence checks need only the key set; outputs are their own because they are the larger half of the data with a single consumer. `@/tools/metadata` and `@/tools/metadata-outputs` both resolve ids through `@/tools/tool-ids`, which is what keeps them independent of each other — do not "helpfully" re-export one from another, or every caller pays for all three. - -All lookups guard with `Object.hasOwn`. `JSON.parse` yields an object with the normal prototype, so a bare bracket lookup returns inherited members: a bare bracket lookup would answer `getToolMetadata('constructor')` with a *function* typed as tool metadata. - -## The generated artifacts - -`apps/sim/tools/generated/tool-ids.ts`, `tool-metadata.ts` and `tool-outputs.ts` are produced by `scripts/sync-tool-metadata.ts`: - -```bash -bun run generate:tool-metadata # after adding/changing a tool -bun run check:tool-metadata # what CI runs; fails if stale -``` - -Never hand-edit them. If you add a tool or change a tool's `params`/`outputs`, regenerate and commit the result, or CI fails. - -Four non-obvious properties, each of which was measured and is easy to undo by accident: - -- **The data is a JSON string parsed at runtime, not an imported `.json` and not an object literal.** With `resolveJsonModule` (which this repo enables), a `.json` import makes TypeScript infer a literal type for all 5,000+ entries and takes `tsc --noEmit` from **12.6s to 8m07s** — a 38x regression. An ambient `declare module` does *not* short-circuit it, and an object literal costs the same. A single string literal is one cheap token for both the compiler and the bundler, and `JSON.parse` beats evaluating the equivalent literal at runtime. Do not "clean this up" into a `.json` import. -- **The generator refuses to emit function values.** If you add a field to `METADATA_FIELDS` that contains a closure, generation fails loudly rather than shipping executable config to the client. `hosting` and `schemaEnrichment` are excluded for exactly this reason (`hosting.enabled`, `pricing`, and `enrichSchema` are functions) — they are server-only. -- **Empty param entries are stripped.** The registry contains one (`stt_deepgram_v2`), which crashes callers that read `param.type` while iterating. -- **Lookups resolve versions.** `getTool` maps an unversioned name onto the newest version, and a few hundred tools are versioned. A plain key lookup would silently report them missing — a quiet correctness bug, not a crash. `resolveToolId` reproduces that against the id set and is differentially tested against the original. - -## Testing code that reads tool metadata - -Mock the module the code under test actually reads. `@/tools/metadata` and `@/tools/metadata-outputs` are mocked globally in `apps/sim/vitest.setup.ts` and return `undefined`; never `vi.mock` them again (`check:test-patterns` fails a `global-remock`). Install fixtures on the global mock instead: - -```ts -import { toolsMetadataMock } from '@sim/testing/mocks/blocks.mock' -import { getToolMetadata } from '@/tools/metadata' - -vi.mocked(getToolMetadata).mockImplementation(toolsMetadataMock.getToolMetadata) -``` - -Do the same for `getToolParams`. `vi.mock('@/tools/utils', () => toolsUtilsMock)` controls only `getTool`. Both mocks share `mockToolConfigs`, so together they give one consistent tool universe. If you are unsure whether a mock is load-bearing, change a fixture value to a sentinel and confirm the test fails. -## The guard - -`bun run check:tool-registry-boundary` (run in CI by `check:audits`) walks the module graph from each workspace route and fails if `@/tools/registry` is reachable, printing the exact import chain that reintroduced it. - -If it fails, do not add the entry to an allowlist — there isn't one. Find the symbol the offending file actually needs and move it to a registry-free module (e.g. `tools/merge-params.ts`). - -Run it with `--verbose` to print per-route module counts, which is also the quickest way to see whether a change moved the graph. - -The same command also ratchets those counts against `check-tool-registry-boundary.baseline.json`. `--check` (what CI runs) fails when an entry exceeds its baseline by more than `max(25 modules, 2%)`, naming the import chain responsible. The baseline also catches graph growth that never touches `@/tools/registry`. - -Re-record with `--update-baseline` and commit the JSON when growth is deliberate. A *shrink* passes but is reported — re-record then too, or the win is silently spendable again. +| whether a tool id exists | `hasToolId` from `@/tools/tool-ids` | ~170 KB, the cheapest | +| to resolve an unversioned name, or every id | `resolveToolId` / `getToolIds` from `@/tools/tool-ids` | | +| a tool's params | `getToolParams` / `getToolMetadata` from `@/tools/metadata` | ~8 MB | +| a tool's declared outputs | `getToolOutputsMetadata` from `@/tools/metadata-outputs` | ~8 MB, separate on purpose | +| to **execute** a tool | `getTool` (`@/tools/utils`) or `getToolAsync` (`@/tools/utils.server`) | the whole registry; server paths only | -## How to verify an edge actually got cut +The three metadata modules each resolve ids through `@/tools/tool-ids` and stay independent of each other: never re-export one from another, or every caller pays for all three. -Do not eyeball imports — the registry is reached through several redundant paths, so cutting one buys nothing while another survives. Walk the graph: +A caller that reads `params`, `outputs`, `name` or `description`, or only checks existence, uses metadata, **even on a path you believe is server-only**: a future client import would silently re-attach the registry. Only code that builds a request, transforms a response, or dispatches an internal operation uses `getTool`, and that file stays off client-reachable paths. -1. From the entry you care about, follow `import` and `export … from` (skipping `import type`), resolving `@/` against `apps/sim`. -2. Check whether `apps/sim/tools/registry.ts` is in the reachable set, and print the parent chain if it is. -3. Compare the reachable module count before and after. +The generated artifacts under `apps/sim/tools/generated/` come from `bun run generate`; never hand-edit them. -A route can reach the registry through several redundant edges; cutting one changes nothing until all are gone, so measure the route, not the file you edited. +## Tests -## When adding a new caller +`@/tools/metadata` and `@/tools/metadata-outputs` are globally mocked to return `undefined`. Install fixtures on the global mock: `vi.mocked(getToolMetadata).mockImplementation(toolsMetadataMock.getToolMetadata)` (from `@sim/testing/mocks/blocks.mock`), same for `getToolParams`. `toolsUtilsMock` controls only `getTool`; both share `mockToolConfigs`, giving one consistent tool universe. If unsure a mock is load-bearing, set a fixture value to a sentinel and confirm the test fails. -Ask what the caller does with the config. If it reads `params`, `outputs`, `name`, `description` or just checks existence, it belongs on `@/tools/metadata` — no exceptions, even on a path you believe is server-only today, because a future client import will silently re-attach the registry to the graph. +## When the guard fails -If it genuinely executes — builds an external request, transforms a response, or dispatches a -registered internal operation — use `getTool`, and keep that file off client-reachable paths. +- There is no allowlist. Find the symbol the offending file actually needs and move it to a registry-free module (e.g. `tools/merge-params.ts`). +- Measure the route, not the file you edited: the registry is reached through several redundant edges, so cutting one changes nothing until all are gone. `--verbose` prints per-route module counts before and after. +- The command also ratchets module counts; re-record with `--update-baseline` when growth is deliberate, and after a shrink too, or the win is silently spendable again. diff --git a/.agents/skills/v2-api-conventions/SKILL.md b/.agents/skills/v2-api-conventions/SKILL.md index e49c004271c..93abb1f7bea 100644 --- a/.agents/skills/v2-api-conventions/SKILL.md +++ b/.agents/skills/v2-api-conventions/SKILL.md @@ -6,7 +6,7 @@ argument-hint: # v2 API Conventions -The v2 surface makes one promise: **every response is the same two shapes, and a caller-supplied value can never produce a 500.** +The v2 surface makes one promise: **every response is one of these shapes, and a caller-supplied value can never produce a 500.** ``` success (single) { "data": {...} } @@ -14,226 +14,73 @@ success (collection) { "data": [...], "nextCursor": "..." | null } failure (always) { "error": { "code": "...", "message": "...", "details"?: ..., "requestId"?: "..." } } ``` -Nothing else at the top level. No `success: true`, no bare `{ "error": "string" }`, no HTML. +Machinery: envelope, error codes and cursor codecs in `apps/sim/app/api/v2/lib/response.ts`; the builder in `lib/api/server/routes/v2-json-route.ts`; cross-tenant concealment in `lib/api/server/routes/resource-concealment.ts`; contracts in `lib/api/contracts/v2/**`; keyset helpers in `lib/api/list-query.ts`. Build order is contract → application use case → route (see `migrate-application-operation`); the presenter reads request params (active sort, filters) from the parsed request rather than making the use case carry them back. -Each rule below guards a caller-visible failure: a non-integer `limit` reaching SQL, a non-envelope error body, an HTML 404 for unknown paths, an unapplied `limit` stripped by non-strict Zod, and an untyped bound parameter into an overloaded SQL function. +## Errors and status codes -## Where the machinery lives +**500 is never caller-reachable.** Any input a caller can send is rejected at the contract with a 400; a request that 500s is a contract bug, not something to wrap in `try`/`catch`, and the highest-severity defect on this surface. Known shapes: non-integer numerics, a method guard rejecting HEAD-on-GET, untyped placeholders into SQL functions. A response schema is `.parse`d on the way out, so asserting a field the producer doesn't always emit turns a successful read into a 500: assert only what you can prove. -| Concern | File | -|---|---| -| Envelope + error codes + cursor codecs | `apps/sim/app/api/v2/lib/response.ts` | -| Cross-tenant concealment | `apps/sim/lib/api/server/routes/resource-concealment.ts` | -| Route builder | `apps/sim/lib/api/server/routes/v2-json-route.ts` | -| Contracts | `apps/sim/lib/api/contracts/v2/**` | -| Shared list/keyset helpers | `apps/sim/lib/api/list-query.ts` | +**Validating a value is half of it; it must also reach SQL with a type.** A bound parameter takes its type from context, which always works against a typed column (`sort_order > $1`) but can resolve to nothing as an argument to an overloaded function. A bound value passed as an argument to a SQL function (not a comparison) must carry an explicit type. When a change alters generated SQL *shape*, run it against Postgres: `keysetAfter` once passed every unit test and only the parser rejected it. -## Rule 1 — the envelope is produced by helpers, never by hand +**404 is deliberately overloaded.** A workspace the caller cannot reach answers `404 "Workspace not found"`, never 403, which would confirm it exists; the unknown-path catch-all answers the same body. Every v2 response is `Cache-Control: private, no-store`, which matters most here: 404 is heuristically cacheable and an authorization-dependent 404 must never be stored. -`v2Data`, `v2Error`, and the typed error helpers in `response.ts` (`v2ValidationError`, `v2RateLimitError`, `v2HttpError`, `v2InsufficientScope`, `v2HeadNoEffect`, `v2NoContent`, `v2UploadDataPlaneError`) are the only things that build a v2 body. They also set `Cache-Control: private, no-store`, which every v2 response needs because every v2 response is authed per-caller data. +**403 vs 404 follows authorization, not whether it's a read.** No workspace access (`NoWorkspaceAccessError`) is concealed as 404; access below `minimumRole` stays 403. A `read` operation can't 403 on role, but can through `PersonalApiKeysDisabledError` or `WorkspaceApiKeyAuthorizationError`, and every v2 operation is reachable by a personal key, so **every workspace-scoped v2 operation documents 403**. Use the shared `RESOURCE_*_ERRORS` sets in `contracts/v2/openapi/shared.ts`; hand-assembled lists drop `Forbidden`. -A route built with `defineV2JsonRoute` gets this for free: its `present` returns the *body shape* and the builder renders it. Never call `NextResponse.json` from a v2 route. +**A 403 a caller can act on names its cause in `error.details.code`.** One status covers different remedies (raise a role, use a personal key, buy a plan, get under a quota), and clients that string-match messages break on every reword. Codes come from the closed `FORBIDDEN_DETAIL_CODES` (`lib/core/application/forbidden.ts`); a new one is warranted only when the remedy differs. Throw `ForbiddenOperationError(code, message)` from the domain, never attach a code at the route. Clients treat `details.code` as optional (some domain 403s still lack one; see `FORBIDDEN_DESCRIPTION`); new 403s always carry one. Cross-tenant refusals carry **no** code: naming the cause would leak the existence signal the 404 withholds. -**The envelope must hold for every failure mode, including the ones that happen before your handler runs.** Defaults for the transport-level failures live on the builder — `v2PayloadTooLargeResponse` (413) and `v2InvalidJsonResponse` (400) — precisely so a route cannot forget them. +**HEAD runs the GET handler** (Next aliases it; the builders accept the pairing). That is only sound because HEAD is safe, so **a GET with side effects declares `headSafe: false`**: `GET /files/{fileId}` records `FILE_DOWNLOADED`, and without it an uptime monitor's HEAD would fabricate downloads. Such a route still authenticates and rate-limits a HEAD, then answers a bodiless 200 without executing. Recheck whenever a read gains an audit projection or outbound call. -## Rule 2 — status codes mean specific things +## Pagination -| Status | `code` | Meaning | -|---|---|---| -| 200 / 201 | — | Success. 201 only for a created resource. | -| 400 | `BAD_REQUEST` | Contract validation. Carries field-level `details` from `serializeZodIssues`. | -| 401 | `UNAUTHORIZED` | No/!valid API key. | -| 403 | `FORBIDDEN` | Authenticated, same tenant, insufficient rights. Where the cause is one a caller can act on it is named in `details.code`, from the closed set in `lib/core/application/forbidden.ts` (e.g. `INSUFFICIENT_WORKSPACE_ROLE`, `PERSONAL_API_KEYS_DISABLED`). A few domain refusals still reach the wire without one. | -| 404 | `NOT_FOUND` | Not found, **and** cross-tenant concealment, **and** an unknown path. | -| 409 | `CONFLICT` | Uniqueness/state conflict, human-readable message. | -| 413 | `PAYLOAD_TOO_LARGE` | Body over the route's `maxBodyBytes` — **and** a collection the response must materialize that is over *its* ceiling. Fourteen bodyless `GET`/`DELETE` operations publish it for the folder-tree cap (`FolderCollectionLimitExceededError`) or the rendered-artifact cap. | -| 429 | `RATE_LIMITED` | With `Retry-After` and `X-RateLimit-*`. | -| 500 | `INTERNAL_ERROR` | Genuine server fault only. Message is always generic. | +A list returning `nextCursor` accepts `limit` + `cursor` from `v2PaginationFields` and actually applies them; whether a list pages at all is pinned in `lib/api/contracts/v2/list-pagination.test.ts`. -Two of these carry real design weight: +- **Keyset** (`readSortedCursor`/`encodeSortedCursor`) is the default; it needs the page to come from one ordered SQL read. The key list must end in a unique column (`id`), or tied rows repeat or drop at the boundary. +- **Offset** (`decodeOffsetCursor`/`encodeOffsetCursor`) only when keyset is impossible (`GET /skills` merges an in-code registry with DB rows; `GET /knowledge/{id}/documents`). +- Stamp `cursorSortKey(sortBy, sortOrder)` and `cursorScopeKey(cursorRoute(contract, pathParams), {...filters})` so changing sort or filters mid-pagination is a 400, not a skipped page. Never stamp `limit` or response-shaping params: binding `limit` strands every cursor when a caller changes page size. +- Legacy domain-minted cursors on re-filterable lists are wrapped with `encodeScopedCursor`/`readScopedCursor`; new lists use keyset or offset, never a new scheme. +- `nextCursor: null` on the last page and only then. +- **Cursors are opaque, not trusted.** They are unsigned base64-JSON on purpose: `KeysetKey.bind` re-validates every value (a forged cursor can't reach SQL as `NaN`), filters are hashed into the stamp, and authorization is re-derived from the principal every time. Never put a resource id, filter or scope in a cursor and trust it back: a cursor is a position hint, never an access-decision input. -**404 is deliberately overloaded.** A workspace the caller cannot reach answers `404 "Workspace not found"`, never 403 — a 403 would confirm the resource exists. `createV2ResourceConcealmentPolicy` does this by mapping a cross-tenant authorization failure to `v2Error('NOT_FOUND', ...)`. The unknown-path catch-all at `app/api/v2/[[...segments]]/route.ts` answers with the same body on purpose. +**Ordering is `sortBy` + `sortOrder`.** The only exception is `GET /workflows/{workflowId}/runs` (one sortable column, so a single `order`). Don't accept `sortOrder` as an alias (two spellings, undefined precedence). Before documenting a second `order`-style exception, check sibling endpoints on the same rows: if any sorts them more than one way, the premise is false. -**500 is never caller-reachable.** Any input a caller can send must be rejected at the contract boundary with a 400. If you can construct a query string or body that produces a 500, that is a bug in the contract, not something to wrap in a `try`/`catch`. `v2ErrorForOrchestration` also replaces the message on an unclassified failure with a generic one, so internal detail never leaks. Treat any well-formed request that produces a 500 as the highest-severity defect on this surface: non-integer numerics, a method guard rejecting the `HEAD`-on-`GET` pairing, and untyped placeholders into SQL functions are the known shapes. +**Boolean query params** use `booleanQueryFlagSchema`; reusing an internal `.shape.x` inherits its `z.enum(['true','false'])` spelling. -**Validating a value is only half of it; the value also has to reach SQL with a type.** A bound parameter arrives as `unknown` and takes its type from context. Against a typed column (`sort_order > $1`) that inference always succeeds, which is why the gap stays invisible almost everywhere — but as an argument to an overloaded function it can resolve to nothing at all. So: **if a bound value is an argument to a SQL function rather than one side of a comparison, write its type down** (`lib/api/list-query.ts`, `timestampKey`, casts from the column). +## Reject what you don't implement -And this class survives a green test suite — `keysetAfter` returned well-formed SQL and every assertion passed; only Postgres's parser rejected it. When a change alters the *shape* of generated SQL rather than its values, execute it somewhere before believing the suite. +Unknown query params are a 400: safe for first-party callers (the SDKs send only declared params; the UI makes no v2 calls) and documented in `api-reference/getting-started.mdx` for third parties. Non-strict Zod strips unknown keys, so `?limit=1` against a list without `limit` answers 200 with everything: a contract lie and an unbounded response. -**Which of 403 and 404 an operation documents follows from its authorization, not from whether it is a read.** `requirePermission` throws two different failures: no workspace access at all is `NoWorkspaceAccessError`, which `createV2ResourceConcealmentPolicy` conceals as 404; access below the operation's `minimumRole` is `InsufficientWorkspacePermissionsError`, which stays a 403. So: +`.strict()` binds the top level only: a strict body with a non-strict nested object silently drops keys one level down (`sort: [{ field, direction, nulls: 'last' }]` answered 200 ordered by default). Put strictness on the shared nested schema (`sortSpecSchema`'s element, `tableViewConfigSchema`). Before making a schema that is also a stored blob or response strict, canonicalize reads (`normalizeStoredViewConfig`) so legacy keys don't 500. -- An operation whose `minimumRole` is `write` or `admin` can always 403 — a member with a lower role hits it. Document 403. -- An operation whose `minimumRole` is `read` cannot 403 *that* way, because `read` is the floor of the `read < write < admin` ordering and anyone without access is concealed as 404 instead. It can still 403 through `PersonalApiKeysDisabledError` (a personal API key against a workspace whose organization disabled them) or `WorkspaceApiKeyAuthorizationError` (`workspaceApiKey: 'deny'`), and every v2 operation is reachable by a personal API key. **So in practice every workspace-scoped v2 operation documents 403**, and the reads that omitted it were wrong, not principled. +Validation messages name the field and the escape hatch: `Limit cannot exceed 1000; use limit=0 to stream all rows, or create an export`. `Invalid input` is not actionable. -**A 403 a caller can act on names its cause in `error.details.code` — but not every 403 does yet.** One status covers several different remedies — raise a member's role, issue a personal key instead of a workspace-scoped one, re-point a workspace key, buy an enterprise plan, delete a resource to get under a quota — and prose is not branchable, so a client that must tell them apart was string-matching messages, which turns every reword into a silent break. A handful of domain refusals still throw a bare `OrchestrationError('forbidden', …)` and reach the wire with no code, so **write client code that treats `details.code` as optional**, and read `openapi/shared.ts`'s `FORBIDDEN_DESCRIPTION` for the current position rather than assuming the sweep is finished. For code you are *writing*, the rule below is unconditional. +## Descriptions -The vocabulary is the closed tuple `FORBIDDEN_DETAIL_CODES` in `lib/core/application/forbidden.ts` (each member TSDoc-documented), published to OpenAPI as the `V2ForbiddenDetailCode` enum via `v2ForbiddenDetailCodeSchema`. A new code needs a documented entry there and is warranted only when the remedy differs. Do not invent a code at a route: throw `ForbiddenOperationError(code, message)` from the domain and let `v2CaughtOrchestrationError` — the function every v2 error policy falls through to — attach it. `InsufficientWorkspacePermissionsError`, `PersonalApiKeysDisabledError`, `WorkspaceApiKeyAuthorizationError`, and `PrincipalKindAuthorizationError` already carry theirs. +Follow `lib/api/contracts/v2/openapi/README.md`. A description claiming behavior the route lacks is the same bug as a wrong schema: verify archive vs permanent delete, replace vs partial update, partial success, retry safety, redaction and async completion against the implementation. Field rules live in the source schema; shared descriptions feed CLI help, so name related operations, not HTTP paths. Regenerate with `bun run generate`. -The cross-tenant refusals (`NoWorkspaceAccessError`, `WorkspaceApiKeyScopeAuthorizationError`, `DelegatedWorkspaceAuthorizationError`) deliberately carry **no** code. They are concealed as 404, and naming their cause would hand back the resource-existence signal the concealment exists to withhold. +## Retry-After -Use the shared sets in `contracts/v2/openapi/shared.ts` — `RESOURCE_ERRORS`, `RESOURCE_CONFLICT_ERRORS`, `RESOURCE_MUTATION_ERRORS` — rather than assembling a per-operation list; all three already include `Forbidden`, which hand-assembled lists drop. +429 (`v2RateLimitError`, from the caller's bucket) and 503 (`v2Error` default keyed on status) carry it; a route with a better number passes the header and wins. Add no default for other codes: 400/403/404/409 aren't fixed by waiting, 402 by a billing change, and 413s are fixed ceilings. -**HEAD is answered by the `GET` handler, not rejected.** Next aliases a missing `HEAD` export onto `GET` and drops the body when sending, so a route's `GET` legitimately runs with `request.method === 'HEAD'`. The builders' method guard accepts that pairing via `methodMatchesContract`; any other mismatch stays a hard error. Never hand-write a `HEAD` export to "fix" this. +- **Where a policy knows the wait, carry it end to end** (`descriptor.retryAfterSeconds → PreprocessExecutionError.retryAfterMs → ExecuteWorkflowServiceFailure.retryAfterMs → serviceFailureResponse`); a mapping that drops it turns a concurrency denial into a bare 429. The `v2Error` default is the floor for paths with no policy signal. +- **An unknown-outcome failure must not advise a retry.** `ASYNC_ENQUEUE_AMBIGUOUS` may have enqueued: it passes `omitRetryAfter: true` and returns the run id, because a "retry in 5s" invites a client without `X-Run-Id` to start and bill a second run. Any future "we don't know if it happened" failure does the same. -**A `GET` with side effects must declare `headSafe: false`.** The aliasing above is only sound because RFC 9110 §9.2.1 defines `HEAD` as safe. A `GET` that writes a row or opens an outbound connection is not, and an uptime monitor or link checker walking the documented URL list would drive those effects on every probe — `GET /files/{fileId}` records a `FILE_DOWNLOADED` audit event, so without `headSafe: false` a `HEAD` would fabricate a download that never happened. Both the JSON and binary builders take `headSafe`: a route that sets it `false` still authenticates and rate-limits a `HEAD`, then answers `v2HeadNoEffect()` — a bodiless 200 — before parsing or executing. Nothing observable is lost, because `HEAD` carries no body either way. Audit this whenever a read acquires an audit projection or an outbound call. +## X-Run-Id: at-most-once, not replay -## Rule 3 — a collection that returns `nextCursor` must accept `limit` + `cursor`, and must apply them - -Every list returns `{ data, nextCursor }`. Whether it *pages* is a separate, pinned decision — see `lib/api/contracts/v2/list-pagination.test.ts`, which enumerates both sets and fails when a new list is in neither. - -Build the query slice from the shared helper, never by hand: - -```ts -...v2PaginationFields({ description: 'Maximum widgets to return per page.' }) -``` - -That gives `limit` (integer, 1..`V2_MAX_PAGE_SIZE`, defaulting to `V2_DEFAULT_PAGE_SIZE` = 50) and an opaque `cursor`. Never re-declare `limit: z.coerce.number()...` inline; inline schemas drift from `.int()`. - -Three cursor schemes exist. Two are the shared codecs in `response.ts`, both opaque base64-JSON, and which of them you use is decided by what the read can express, not by taste: - -- **Keyset** (`readSortedCursor` in, `encodeSortedCursor` out) — the default. Requires the page to come from one ordered SQL read. The sort AND the filters are stamped into the cursor and re-checked on replay, so changing `sortBy` or any filter mid-pagination is a 400, not a silently skipped page. -- **Offset** (`decodeOffsetCursor` / `encodeOffsetCursor`) — only when a keyset is impossible. Two lists qualify: `GET /skills` merges a static in-code registry with DB rows and re-sorts in JS, and `GET /knowledge/{id}/documents` sits on a limit/offset query. A bare offset replayed against a re-sorted or re-filtered sequence names a different row, which skips or repeats results. - -Both take the same two stamps: `cursorSortKey(sortBy, sortOrder)` for the ordering, and `cursorScopeKey(cursorRoute(contract, pathParams), { ... })` for every param that filters the sequence — the route identity is the first argument, the filter parts the second. **`limit` is never a stamp** — it selects how much of the sequence to return, not what the sequence is, and binding it strands every cursor the moment a caller changes page size. Params that only shape the response body are out for the same reason. - -The third is **per-domain**: a list whose read predates the shared codecs, or whose page boundary is not expressible as one, mints its own — a bare `encodeCursor({ version })` on `GET /workflows/{id}/versions` and `encodeCursor({ email })` on the workspace member list, the local codecs in `lib/audit-logs/query.ts`, `lib/logs/list-logs.ts`, and `lib/table/rows/cursor.ts`, and a usage-event id passed straight through by `GET /billing/logs`. Those tokens stay opaque and untouched, but a domain-minted cursor on a list a caller can re-filter is wrapped at the surface with `encodeScopedCursor(cursorScopeKey(cursorRoute(contract, pathParams), {...}), token)` and unwrapped with `readScopedCursor`, so it carries the same binding as the shared schemes. **A new list picks one of the two shared schemes.** Do not add a fourth. - -Every paged list's binding is declared in `lib/api/contracts/v2/list-pagination.test.ts` and checked against what the contract actually accepts, in both directions. A new list, or a new filter on an existing one, fails that test until its binding is declared or the param is explicitly recorded as unable to change the sequence. - -**A keyset's key list must end in a unique column (`id`).** A non-unique trailing key cannot separate tied rows, so the page boundary either repeats or drops them. `lib/api/list-keyset-paging.test.ts` demonstrates the failure. - -Return `nextCursor: null` on the last page and only then. Never construct a cursor client-side. - -**Ordering is `sortBy` + `sortOrder`, except where there is nothing to sort by.** Nearly every paged list takes the pair; `CURSOR_BINDINGS` in `contracts/v2/list-pagination.test.ts` is the authoritative set. Exactly one — `GET /workflows/{workflowId}/runs` — has a single sortable column (start time), so there is no `sortBy` to pair with and the direction rides on a single `order` param; `sortBy`/`sortOrder` are not accepted there. That is the *only* sanctioned deviation, and it is documented in its contract. A new list picks the pair. Do not "fix" it by accepting `sortOrder` as an alias: an alias is a second spelling of one thing with undefined precedence when both arrive, which is its own inconsistency. - -Before documenting a second `order`-style exception, check every other endpoint on the same collection: if one of them already sorts those rows more than one way, the "exactly one sortable column" premise is false — fix the premise rather than documenting the exception. - -**A boolean query param is a real boolean**, declared with `booleanQueryFlagSchema` from `contracts/primitives.ts`; it coerces `'true'`/`'1'` and `'false'`/`'0'`/`''`. Reusing an internal `.shape.x` inherits the internal spelling (often a `z.enum(['true','false'])`); re-declare instead when the internal one is not the v2 convention. - -## Rule 4 — reject what you do not implement - -**Every contract declares a `query`, even when the endpoint takes none** — `query: noInputSchema` (`z.object({}).strict()`), never omission. `parseRequest` validates the query slice only when the contract declares one, so an omitted `query` means "never look at the query string", not "takes no query params". An omitted `query` silently accepts any query string; `query-declaration.test.ts` fails a contract that omits it. - -Unknown query params are a 400. That is safe for first-party callers — the two SDKs send only `includeOutput`/`selectedOutputs`, both declared; the UI makes no v2 calls; `requestJson` appends nothing implicitly and there is no v2 cache buster — and it matches the already-strict body slice. Third-party callers appending a tracking tag or cache buster do break, which is why `api-reference/getting-started.mdx` documents the behavior rather than leaving it to be discovered from a 400. - -Query and body schemas are **`.strict()`** — and `.strict()` binds the **top level only**. A strict body containing a non-strict nested object still drops unknown keys one level down, which is the headline `filter` bug at a smaller scale: `sort: [{ field, direction, nulls: 'last' }]` answered 200 and ordered by the default. Strictness belongs on the shared nested schema (`sortSpecSchema`'s element, `tableViewConfigSchema`), not restated per body. - -Before tightening a schema that is **also** a response or a stored blob, make the read canonical first. `table_views.config` is schemaless JSONB, so a legacy row carrying a retired key would fail a newly strict response parse and become a 500; `normalizeStoredViewConfig` projects the stored blob onto the declared keys so the tightening is safe in both directions. Zod strips unknown keys by default, so a non-strict schema answers `?limit=1` with 200 and the whole set — the caller believes it bounded the response and it did not. That is a contract lie, and on an uncapped list it is also an unbounded-response risk. - -Error messages name the field and, where there is one, the escape hatch: - -``` -limit must be a whole number -limit cannot exceed 100 -search cannot be empty -sortBy: expected one of "name" | "createdAt" | "updatedAt" -Limit cannot exceed 1000; use limit=0 to stream all rows, or create an export -``` - -That last one is the standard to aim for. A message that only says `Invalid input` fails this rule — the caller cannot act on it. - -## Rule 5 — contract first, then use case, then route - -Order matters because each layer is checked against the one before it. - -1. **Contract** in `lib/api/contracts/v2/.ts` via `defineRouteContract`. Response schemas are `.parse`d on the way out, so a field the producer does not actually emit becomes a 500 on a successful read — assert only what you can prove. -2. **Application use case** owns canonical loading, authorization, business behavior, and audit. The route's `present` receives the use-case result **and the parsed request**, so a presenter reads request params (the active `sortBy`/`sortOrder` and filters it stamps into a cursor) straight from `query`/`params` rather than making the use case carry an HTTP concern back out. -3. **Route** with `defineV2JsonRoute`, declaring `contract`, `auth: v2ApiKeyAuth`, `operation`, `rateLimit`, `errorPolicy`, `mapInput`, `useCase`, `present`. Auth and rate limiting run before parsing. -4. **OpenAPI description** in `lib/api/contracts/v2/openapi/.ts`, then `bun run generate:openapi`. A description that claims behaviour the route does not have is the same class of bug as a wrong schema. - -### Public descriptions - -Use the [API description conventions](../../../apps/sim/lib/api/contracts/v2/openapi/README.md) when writing or auditing endpoint and field descriptions. Keep a short action-and-resource summary; use the description for behavior that changes the caller's choice, input, interpretation, or next action. Ordinary operations usually need one to three sentences, with no mandatory minimum. - -Keep archive versus permanent-delete behavior, replacement versus partial-update semantics, partial success, retry safety, redaction, and asynchronous completion explicit. Verify these claims against the implementation. Describe observable behavior without exposing storage formats, locking mechanisms, internal identifiers, deployment architecture, or implementation history unless that detail changes how the caller must use the API. - -Reuse wording across resource families when behavior matches: “Omitted fields remain unchanged,” “Archive,” and “permanently delete.” Prefer “during the request” or “asynchronously” to “settled inline.” Preserve real semantic differences; do not standardize them away. - -Put field-specific rules in the source schema and reuse shared authentication and pagination wording. Shared schema descriptions also feed CLI help, so refer to related operation names rather than HTTP paths. Regenerate OpenAPI, CLI metadata, and CLI docs after changing their source descriptions; never hand-edit generated output. - -## Rule 6 — a transient failure says when to come back - -A response the caller is *expected* to retry must say how long to wait. Two statuses qualify, and both are wired: - -| Status | Source of the value | Where | -|---|---|---| -| 429 | The caller's own token bucket (`retryAfterMs`, else `resetAt - now`) | `v2RateLimitError` | -| 503 | A fixed floor, `RETRY_AFTER_SECONDS_BY_STATUS` | `v2Error`, applied automatically | - -The 503 default is applied by `v2Error` keyed on the response *status* — `Retry-After` is defined against the status, and the status is the only half of the code/status pair a client sees — so every 503 the surface can emit carries it — the three route builders' `unhandledErrorResponse`, the execute and resume routes, and `serviceFailureResponse`'s `infra` failures. A route with a better number passes `headers: { 'Retry-After': … }` and wins. - -Do not add a default for any other code. 400/403/404/409 are not fixed by waiting, and 402 (`USAGE_LIMIT_EXCEEDED`) is resolved by a billing change, not by time. - -**Where a policy already knows the wait, carry it — do not re-guess it at the transport.** The admission descriptors in `lib/core/admission/transient-failure` declare `retryAfterSeconds` per denial. Carry it the whole way: `descriptor.retryAfterSeconds → PreprocessExecutionError.retryAfterMs → ExecuteWorkflowServiceFailure.retryAfterMs → serviceFailureResponse`; a mapping that drops it turns a concurrency denial into a bare 429 with no `Retry-After` even though the policy named the wait. The `v2Error` default is the floor for paths with *no* policy signal, not the source of truth. - -**A failure whose outcome is unknown must not advise a retry.** `ASYNC_ENQUEUE_AMBIGUOUS` is a 503 whose enqueue may have succeeded — it deliberately retains its execution-ID claim. Telling that caller to come back in 5 seconds invites a client with no `X-Run-Id` to start and bill a second run. It passes `omitRetryAfter: true` and returns the run id so the caller reconciles instead. Any future "we don't know if it happened" failure does the same. - -RFC 9110 §10.2.3 gives 503 this field's clearest meaning — "how long the service is expected to be unavailable to the client". Note the requirement level is only `MAY`, on 503 (§15.6.4) and, via RFC 6585 §4, on 429. It is `SHOULD` on exactly one status, 413, and only when the condition is temporary; none of Sim's 413s are temporary — they are fixed ceilings, on the request body and on the collections a response must materialize — so it correctly sends none. +`X-Run-Id` on `POST /workflows/{id}/execute` (API-key and OAuth callers) is a uniqueness claim, not an idempotency key: a claimed id returns 409 `RUN_ID_CONFLICT` (with `details.runId` and the header) and never replays the earlier result. Ids stay reserved after logs are deleted; an ambiguous enqueue can hold a claim with no retrievable run, so 409 then 404 is unresolved, not proof nothing ran. On an uncertain outcome, retry with the same id and check Get Workflow Run; never auto-restart with a fresh or omitted id. Do not alias Stripe's `Idempotency-Key`: replay needs a fingerprint, retention window, in-flight state and body storage, and clients written for Stripe semantics would misread our 409. ## Deliberate non-adoptions -Audited against the primary specs and against Stripe, GitHub, and Google's AIPs. Each is a considered "no", not an oversight. Re-open one only with new evidence. - -| Practice | Verdict | Why | -|---|---|---| -| **RFC 9457 `application/problem+json`** | No | 9457 §4 steers APIs with an existing format toward keeping it: "Problem details are intended to avoid the necessity of establishing new 'fault' or 'error' document formats, **not to replace existing domain-specific formats**." Nothing in it is a `MUST` to adopt, and none of Stripe, GitHub, or Google use it. Our envelope is load-bearing for every client. **The default error shape does not change.** | -| **`RateLimit`/`RateLimit-Policy` (IETF draft)** | No | Still an unpublished IETF draft whose wire format has changed incompatibly across revisions — anything built against an earlier revision is already broken. None of the three surveyed APIs emit it; GitHub uses `x-ratelimit-*`, as we do. Re-check the draft's status before re-opening. | -| **Renaming `X-RateLimit-*` per RFC 6648** | No | 6648 is a `SHOULD NOT` binding *creators of new* parameters, and §1 item 4 "**makes no recommendation as to whether existing 'X-' parameters ought to remain in use or be migrated**". Appendix B argues the migration is itself the interoperability harm. A rename is a client-visible break bought with nothing. | -| **`X-RateLimit-Reset` as delta-seconds** | No | It is an absolute ISO 8601 timestamp, so it is clock-skew sensitive — but the response where timing actually decides behaviour (429) also carries `Retry-After`, which is skew-free. The absolute value stays useful for scheduling. | -| **422 for semantic validation** | No | RFC 9110 §15.5.21 defines 422, but Appendix B.3 records that 9110 **deleted** RFC 4918's clause saying 400 was inappropriate. 400 covers "cannot or will not process… perceived to be a client error". The split is convention, not requirement — GitHub splits, Stripe and Google do not. Our machine-readable `error.code` already carries the distinction, and restatusing now breaks clients. | -| **`Location` on 201** | No | §9.3.3 makes this a `SHOULD` **for POST**; the status code itself (§15.3.2) requires nothing and defines the fallback — absent `Location`, the target URI identifies the resource. Declined knowingly: several 201 responses (signed upload sessions, table exports, knowledge folders) have no canonical single-resource GET, so a `Location` would 404, and adopting it on some of the 19 is worse for a client than on none. Every 201 returns the full representation including its `id`. Revisit per-route if one gains a canonical GET. | -| **ETag / `If-None-Match` / `If-Match`** | No | Every v2 response is `Cache-Control: private, no-store` per-caller data, so `If-None-Match` buys nothing. The exception is a content-addressed read (the source catalog) that sets the route builder's `entityTag`: its 200 and 304 say `private, no-cache`, so the client keeps the body and revalidates it. For writes, `If-Match` needs a **strong** validator: §8.8.3.2's strong comparison fails if *either* tag is weak, so a weak ETag silently makes every `If-Match` fail. None of the three surveyed APIs does HTTP optimistic concurrency — Google does the semantics via a resource `etag` **field** (AIP-154), deliberately not the header. If Sim needs optimistic concurrency, do it that way. | -| **`Deprecation` / `Sunset` on v1** | Not yet | RFC 9745 (Standards Track) and RFC 8594 (Informational) both apply, and GitHub emits both. But `Sunset` is a timestamp and 9745 §4 makes `Sunset >= Deprecation` a `MUST`, so emitting either commits Sim to a v1 retirement date — a product decision, not an engineering one. When that date exists: `Deprecation` is an RFC 9651 Structured Field **Date** (`@1688169599`); `Sunset` is an **HTTP-date** (`Sat, 31 Dec 2033 23:59:59 GMT`). Two encodings in one response — the most common implementation error here. | -| **`application/merge-patch+json`** | No | v2 PATCH bodies are merge-patch *shaped* — absent means unchanged, `null` clears — but they are `.strict()`, so unknown members are rejected where RFC 7396 §2 would merge them, and nested objects are replaced wholesale rather than merged. Advertising the media type would over-claim. Document the semantics per contract instead. | - -## Idempotency: at-most-once, not replay - -`POST /workflows/{id}/execute` accepts `X-Run-Id` from API-key and OAuth callers; anonymous requests ignore it. It is a **uniqueness claim, not an idempotency key**: - -- An available ID is claimed before execution starts. -- An already claimed ID returns **409** with `error.details.code: "RUN_ID_CONFLICT"`, the run id in `error.details.runId`, and an `X-Run-Id` response header. It never replays the earlier run's result. Get Workflow Run can retrieve an existing run, but a claim does not guarantee a retrievable run. -- IDs of runs that started remain reserved after their execution logs are deleted. -- An ambiguous enqueue can retain the claim indefinitely without creating a retrievable run. A **409** followed by **404** is an unresolved outcome, not proof that execution never started or that the ID will become reusable. - -For an uncertain execution outcome, reuse the same run ID if retrying and check Get Workflow Run. Do not promise polling will eventually find a run. If the outcome cannot be verified, do not automatically restart with a fresh ID or an omitted header: either can start another execution. Failures before a run starts can release the claim, so phrase the conflict rule as an ID that is already claimed. - -That makes the money path safe against double-execution **for callers that opt in**. What it is not: a Stripe-style `Idempotency-Key` that stores and replays the original status and body. Building that means a request fingerprint, a retention window, an in-flight-vs-completed distinction (the expired IETF draft would have these be 422 and 409 respectively), and somewhere to put a large synchronous execution body. It is a designed piece of work, not an increment — do not half-build it by aliasing the header name, which would invite clients written against Stripe semantics to treat our 409 as a hard failure. - -## Cursors are opaque, not trusted - -The base64-JSON cursor is **not signed**, and does not need to be. Tampering is bounded by construction, and that is a property to preserve: - -- Every key value is re-validated by its `KeysetKey.bind`, which returns `null` for a wrong-typed or unparseable value and becomes a 400. A forged cursor cannot reach SQL as `NaN` or an `Invalid Date`. -- The sort and a fingerprint of the filters are stamped into the cursor and re-checked (`decodeSortedCursor`), so a cursor from a differently-sorted or differently-filtered query is a 400, not a silently skipped page. The filters are hashed (SHA-256, via `lib/api/cursor-binding.ts`) rather than embedded, so the token stays short and a caller cannot cheaply construct a filter that collides with another sequence's stamp. -- The offset codec rejects anything that is not a non-negative integer. -- Authorization is **never** carried in the cursor. Every list re-derives its workspace scope from the authenticated principal, so a cursor lifted from another query — or another tenant — can only move the caller within their own authorized result set. - -The consequence to keep true: **never put a resource id, filter, or scope into a cursor and then trust it on the way back.** A cursor is a position hint, never an input to an access decision. - -## Checklist - -Run this against any new or changed v2 endpoint. +Audited against the RFCs and Stripe, GitHub and Google AIPs; reopen only with new evidence. -- [ ] Success body is exactly `{data}` or `{data, nextCursor}`; failures are exactly `{error:{code,message,details?,requestId?}}`, where `v2Error` alone sets `requestId` (the `x-request-id` value). -- [ ] Route uses a shared builder; no hand-built `NextResponse.json`. -- [ ] Query and body schemas are `.strict()`. -- [ ] The contract declares a `query` — `noInputSchema` when the endpoint takes no query params, never omission. -- [ ] No caller-supplied value can produce a 500 — check every numeric param reaches SQL as a validated integer, and that any bound value passed as an argument to a SQL function carries an explicit type. -- [ ] `limit` comes from `v2PaginationFields`, not a hand-written `z.coerce.number()`. -- [ ] If the response carries `nextCursor`, the query accepts `limit` + `cursor` and the query actually applies them. -- [ ] The cursor is bound to every param that filters or orders the sequence, and to none that do not (never `limit`), with the binding declared in `list-pagination.test.ts`. -- [ ] Keyset sorts end in a unique `id` key. -- [ ] The list is classified in `list-pagination.test.ts`. -- [ ] Cross-tenant access answers 404, never 403 — and carries `Cache-Control: private, no-store`, because RFC 9110 §15.5.5 makes 404 heuristically cacheable and an authorization-dependent 404 must never be stored. `v2Error` sets this unconditionally; do not build a v2 response any other way. -- [ ] A retryable failure says when: 429 and 503 carry `Retry-After`. No other status invents one. -- [ ] 403s carry a machine-readable `details.code` from `FORBIDDEN_DETAIL_CODES`, thrown as `ForbiddenOperationError` in the domain rather than attached at the route. -- [ ] Nested objects inside a `.strict()` body are strict too — `.strict()` does not recurse. -- [ ] Ordering uses `sortBy` + `sortOrder`; boolean query params use `booleanQueryFlagSchema`. -- [ ] Validation messages name the field and echo the valid set. -- [ ] Response schema matches every field the route actually emits. -- [ ] OpenAPI description regenerated and truthful about pagination. -- [ ] `bun run type-check` (apps/sim) and `bun run check:audits` pass (includes `check:api-validation:strict`, `check:openapi`, `check:v2-route-table`, `check:cli-api`, `check:mcp-operations`). +- No problem+json (RFC 9457 §4 itself steers existing formats to stay): keep the envelope. +- No `RateLimit` draft headers (unstable draft); keep `X-RateLimit-*` names (RFC 6648 makes no recommendation to migrate existing ones). +- `X-RateLimit-Reset` stays an absolute timestamp; 429 has skew-free `Retry-After`. +- Validation is 400, not 422; `error.code` carries the distinction. +- No `Location` on 201: several 201s (upload sessions, exports, knowledge folders) have no canonical GET, so it would 404. Every 201 returns the full representation with its `id`. +- No ETag/If-Match headers except `entityTag` reads (content-addressed, `private, no-cache`); optimistic concurrency, if needed, uses a resource `etag` field (AIP-154), since a weak header ETag silently fails every `If-Match`. +- No `Deprecation`/`Sunset` on v1 until a retirement date exists (it commits to one). When it does: `Deprecation` is a Structured Field Date (`@1688169599`), `Sunset` an HTTP-date. +- Do not advertise merge-patch+json: bodies are strict and replace nested objects wholesale. Document PATCH semantics per contract. ## Known gap -A 405 on a path that *does* have a route file but does not export that verb is generated by Next.js before any Sim code runs: zero-byte body, no `content-type`, and no `Allow` header, which RFC 9110 §15.5.6 requires. Fixing it means either exporting explicit rejecting handlers from every v2 route file or intercepting in `apps/sim/proxy.ts` with a static path→methods table. Neither is done. Unknown *paths* are handled — the catch-all covers those. +A 405 for a verb a route file doesn't export comes from Next before Sim code runs: empty body, no `Allow` header. Fixing it needs rejecting handlers in every route file or a path→methods table in `apps/sim/proxy.ts`; neither exists. Unknown paths are handled by the catch-all. diff --git a/.agents/skills/validate-connector/SKILL.md b/.agents/skills/validate-connector/SKILL.md index 0a1a1788296..b77ff3aa880 100644 --- a/.agents/skills/validate-connector/SKILL.md +++ b/.agents/skills/validate-connector/SKILL.md @@ -4,358 +4,34 @@ description: Validate an existing knowledge base connector against its service's argument-hint: [api-docs-url] --- -# Validate Connector Skill +# Validate Connector ## Identify the runtime under review -For **Sim Search**, validate the [live provider registration and access pipeline](../../../apps/sim/lib/sim-search/live/README.md#adding-a-live-search-connector): catalog and metadata parity, both search/read handlers, current member grants, service-source restrictions, safe scoped references, pagination, provenance, and provider failure behavior. Test real localhost setup/search/read with authorized fixtures when available, and distinguish those results from mocked provider tests. Live Search must not enqueue content indexing or background ACL/directory builds; GitLab still computes request-time permissions or uses current CSV grants. +For **Sim Search**, validate the [live provider registration and access pipeline](../../../apps/sim/lib/sim-search/live/README.md#adding-a-live-search-connector): catalog and metadata parity, both search/read handlers, current member grants, service-source restrictions, safe scoped references, pagination, provenance, and provider failure behavior. Test real localhost setup/search/read with authorized fixtures when available, and keep those results distinct from mocked provider tests. Live Search must not enqueue content indexing or background ACL/directory builds; GitLab still computes request-time permissions or uses current CSV grants. -The ingestion-specific checks below apply to ordinary workspace KB connectors only. Do not require a live-only provider to implement content hashes, ingestion cursors, embeddings, or stored ACL snapshots. +The checks below apply to ordinary workspace KB connectors only. Don't require a live-only provider to implement content hashes, ingestion cursors, embeddings, or stored ACL snapshots. -You are an expert auditor for Sim knowledge base connectors. Your job is to thoroughly validate that an existing connector is correct, complete, and follows all conventions. +The rules are in `/add-connector`; this skill is the audit procedure. Read every file in `apps/sim/connectors/{service}/`, its two registry entries, and its OAuth service, and apply the `validate-selector` skill to any selector key. The official API docs are the source of truth; note any claim you could only check against training knowledge, and report unknown schemas instead of guessing. -## Your Task +## Checks -When the user asks you to validate a connector: -1. Read the service's API documentation (via Context7 or WebFetch) -2. Read the connector implementation, OAuth config, and registry entries -3. Cross-reference everything against the API docs and Sim conventions -4. Report all issues found, grouped by severity (critical, warning, suggestion) -5. Fix all issues after reporting them +**Requests.** URLs, methods, auth headers, service headers (`Notion-Version`), and body fields match the docs; optional fields are omitted rather than sent empty. User values in query languages are escaped: OData `$filter` doubles single quotes, SOQL escapes them with `\'`, GraphQL passes variables instead of interpolating. URL-type config fields are trimmed and normalized (scheme, trailing slash) to what the API expects. -## Step 1: Gather All Files +**Scopes.** Every scope in `requiredScopes` is real, exists in the provider's `OAUTH_PROVIDERS` entry (otherwise the connector fails at runtime), and covers every endpoint the connector calls, with nothing extra. Check the provider's token refresh settings (`useBasicAuth`, `supportsRefreshTokenRotation`, token URL) in `getProviderAuthConfig` (`apps/sim/lib/oauth/refresh.server.ts`). -Read **every** file for the connector — do not skip any: +**Pagination.** Cursor names and `hasMore` follow the docs; a `maxItems` cap is applied across pages through `syncContext.totalDocsFetched`, with the last page requesting `Math.min(PAGE_SIZE, remaining)`; page size stays within the API maximum; no undocumented ceiling (HubSpot search stops at 10k) is hit silently. Every truncation path sets `listingCapped` per `/add-connector`. Cross-page state (user names, field maps, instance URLs) is cached in `syncContext`. -``` -apps/sim/connectors/{service}/meta.ts # ConnectorMeta — client-safe metadata (icon, name, auth, configFields, tagDefinitions) -apps/sim/connectors/{service}/{service}.ts # Connector implementation — spreads the meta + runtime functions -apps/sim/connectors/{service}/index.ts # Barrel export -apps/sim/connectors/registry.server.ts # Server-only full registry entry (CONNECTOR_REGISTRY; full connector) -apps/sim/connectors/registry.ts # Client-safe meta registry entry (CONNECTOR_META_REGISTRY) -apps/sim/connectors/types.ts # ConnectorMeta / ConnectorConfig interfaces, ExternalDocument, etc. -apps/sim/connectors/utils.ts # Shared utilities (computeContentHash, htmlToPlainText, etc.) -apps/sim/lib/oauth/oauth.ts # OAUTH_PROVIDERS — single source of truth for scopes -apps/sim/lib/oauth/utils.ts # getCanonicalScopesForProvider, getScopesForService, SCOPE_DESCRIPTIONS -apps/sim/lib/oauth/types.ts # OAuthService union type -apps/sim/components/icons.tsx # Icon definition for the service -``` +**Documents.** Deferral and `contentHash` per `/add-connector`. Content is not silently dropped (nested blocks, tables, code) or truncated without a warning, blank documents are filtered, and byte limits use `Buffer.byteLength`, not `text.length`. `externalId` is stable; `title` has a fallback. -If the connector uses selectors, also read: -``` -apps/sim/lib/selectors/manifest.ts # Browser-safe exhaustive metadata -apps/sim/lib/selectors/types.ts # Selector context and option types -apps/sim/lib/selectors/context.ts # Active canonical context projection -apps/sim/lib/selectors/server/registry.ts # Exhaustive server attachments -apps/sim/lib/selectors/server/providers/* # Matching provider attachment -``` +**Tags.** Every `tagDefinitions` id is produced by `mapTags` and vice versa, `fieldType` matches the data, numbers are checked for `NaN`, and the metadata keys read exist in what `listDocuments`/`getDocument` store. -Apply the `validate-selector` skill to the matching key and provider primitive. There is no client -provider selector registry. +**Config and validation.** Every config field sets `required` explicitly. `validateConfig` checks required and numeric fields first, makes one lightweight call, uses `VALIDATE_RETRY_OPTIONS`, and returns friendly `{ valid: false, error }` messages. -## Step 2: Pull API Documentation +**`getDocument`.** Returns `null` on 404, handles every type `listDocuments` emits (pages *and* blogposts), forwards `syncContext` when it needs cached state, and doesn't re-fetch data the first response already held. -Fetch the official API docs for the service. This is the **source of truth** for: -- Endpoint URLs, HTTP methods, and auth headers -- Required vs optional parameters -- Parameter types and allowed values -- Response shapes and field names -- Pagination patterns (cursor, offset, next token) -- Rate limits and error formats -- OAuth scopes and their meanings +**Efficiency and isolation.** Field selection (`$select`, `fields`) in both list and get; per-item calls batched with a concurrency of 3–5, never an unbounded `Promise.all`; one document's failure is logged without aborting the sync; error messages carry status codes. -Use Context7 (resolve-library-id → query-docs) or WebFetch to retrieve documentation. If both fail, note which claims are based on training knowledge vs verified docs. +## Report and fix -### Hard Rule: No Guessed Source Schemas - -If the service docs do not clearly show document list responses, document fetch responses, metadata fields, or pagination shapes, you MUST tell the user instead of guessing. - -- Do NOT infer document fields from unrelated endpoints -- Do NOT guess pagination cursors or response wrappers -- Do NOT assume metadata keys that are not documented -- Do NOT treat probable shapes as validated - -If a schema is unknown, validation must explicitly recommend: -1. sample API responses, -2. live test credentials, or -3. trimming the connector to only documented fields. - -## Step 3: Validate API Endpoints - -For **every** API call in the connector (`listDocuments`, `getDocument`, `validateConfig`, and any helper functions), verify against the API docs: - -### URLs and Methods -- [ ] Base URL is correct for the service's API version -- [ ] Endpoint paths match the API docs exactly -- [ ] HTTP method is correct (GET, POST, PUT, PATCH, DELETE) -- [ ] Path parameters are correctly interpolated and URI-encoded where needed -- [ ] Query parameters use correct names and formats per the API docs - -### Headers -- [ ] Authorization header uses the correct format: - - OAuth: `Authorization: Bearer ${accessToken}` - - API Key: correct header name per the service's docs -- [ ] `Content-Type` is set for POST/PUT/PATCH requests -- [ ] Any service-specific headers are present (e.g., `Notion-Version`, `Dropbox-API-Arg`) -- [ ] No headers are sent that the API doesn't support or silently ignores - -### Request Bodies -- [ ] POST/PUT body fields match API parameter names exactly -- [ ] Required fields are always sent -- [ ] Optional fields are conditionally included (not sent as `null` or empty unless the API expects that) -- [ ] Field value types match API expectations (string vs number vs boolean) - -### Input Sanitization -- [ ] User-controlled values interpolated into query strings are properly escaped: - - OData `$filter`: single quotes escaped with `''` (e.g., `externalId.replace(/'/g, "''")`) - - SOQL: single quotes escaped with `\'` - - GraphQL variables: passed as variables, not interpolated into query strings - - A single ID URL path segment: `safeUrlPathSegment(value, 'paramName')` from `@/tools/url-path`; query values: `encodeURIComponent()` -- [ ] URL-type config fields (e.g., `siteUrl`, `instanceUrl`) are normalized: - - Strip `https://` / `http://` prefix if the API expects bare domains - - Strip trailing `/` - - Apply `.trim()` before validation - -### Response Parsing -- [ ] Response structure is correctly traversed (e.g., `data.results` vs `data.items` vs `data`) -- [ ] Field names extracted match what the API actually returns -- [ ] Nullable fields are handled with `?? null` or `|| undefined` -- [ ] Error responses are checked before accessing data fields -- [ ] Every extracted field and pagination value is backed by official docs or live-verified sample payloads - -## Step 4: Validate OAuth Scopes (if OAuth connector) - -Scopes must be correctly declared and sufficient for all API calls the connector makes. - -### Connector requiredScopes -- [ ] `requiredScopes` in the connector's `auth` config lists all scopes needed by the connector -- [ ] Each scope in `requiredScopes` is a real, valid scope recognized by the service's API -- [ ] No invalid, deprecated, or made-up scopes are listed -- [ ] No unnecessary excess scopes beyond what the connector actually needs - -### Scope Subset Validation -- [ ] Every scope in `requiredScopes` exists in the OAuth provider's `scopes` array in `lib/oauth/oauth.ts` -- [ ] Find the provider in `OAUTH_PROVIDERS[providerGroup].services[serviceId].scopes` -- [ ] Verify: `requiredScopes` ⊆ `OAUTH_PROVIDERS scopes` (every required scope is present in the provider config) -- [ ] If a required scope is NOT in the provider config, flag as **critical** — the connector will fail at runtime - -### Scope Sufficiency -For each API endpoint the connector calls: -- [ ] Identify which scopes are required per the API docs -- [ ] Verify those scopes are included in the connector's `requiredScopes` -- [ ] If the connector calls endpoints requiring scopes not in `requiredScopes`, flag as **warning** - -### Token Refresh Config -- [ ] Check the provider's entry in `getProviderAuthConfig` (`lib/oauth/oauth.ts`) -- [ ] `useBasicAuth` matches the service's token exchange requirements -- [ ] `supportsRefreshTokenRotation` matches whether the service issues rotating refresh tokens -- [ ] Token endpoint URL is correct - -## Step 5: Validate Pagination - -### listDocuments Pagination -- [ ] Cursor/pagination parameter name matches the API docs -- [ ] Response pagination field is correctly extracted (e.g., `next_cursor`, `nextPageToken`, `@odata.nextLink`, `offset`) -- [ ] `hasMore` is correctly determined from the response -- [ ] `nextCursor` is correctly passed back for the next page -- [ ] `maxItems` / `maxRecords` cap is correctly applied across pages using `syncContext.totalDocsFetched` -- [ ] Page size is within the API's allowed range (not exceeding max page size) -- [ ] Last page precision: when a `maxItems` cap exists, the final page request uses `Math.min(PAGE_SIZE, remaining)` to avoid fetching more records than needed -- [ ] No off-by-one errors in pagination tracking -- [ ] The connector does NOT hit known API pagination limits silently (e.g., HubSpot search 10k cap) - -### Deletion-Reconciliation Safety (`listingCapped`) -The sync engine tombstones, then hard-deletes, any stored document absent from a full listing. Audit every path where `listDocuments` can return less than the full source set: -- [ ] `syncContext.listingCapped = true` is set when a `maxItems`-style cap truncates the listing while more documents exist -- [ ] `listingCapped` is set when a transient per-item error drops a still-existing document from the listing -- [ ] `listingCapped` is NOT set when the source is genuinely exhausted (deleted documents must reconcile) or for intentional scope filters (date cutoffs) -Verify it against the `checkpoint.unsafe` computation in `lib/knowledge/connectors/listing-checkpoint.ts`. - -### Pagination State Across Pages -- [ ] `syncContext` is used to cache state across pages (user names, field maps, instance URLs, portal IDs, etc.) -- [ ] Cached state in `syncContext` is correctly initialized on first page and reused on subsequent pages - -## Step 6: Validate Data Transformation - -### Content Deferral -Connectors that require per-document API calls to fetch content (file download, export, blocks fetch) MUST use `contentDeferred: true`. This is the standard pattern for reliability — without it, content downloads during listing can exhaust the sync task's time budget before any documents are saved. - -- [ ] If the connector downloads content per-doc during `listDocuments`, it MUST use `contentDeferred: true` instead -- [ ] `listDocuments` returns lightweight stubs with `content: ''` and `contentDeferred: true` -- [ ] `getDocument` fetches actual content and returns the full document with `contentDeferred: false` -- [ ] A shared stub function (e.g., `fileToStub`) is used by both `listDocuments` and `getDocument` to guarantee `contentHash` consistency -- [ ] `contentHash` is metadata-based (e.g., `service:{id}:{modifiedTime}`), NOT content-based — it must be derivable from list metadata alone -- [ ] The `contentHash` is identical whether produced by `listDocuments` or `getDocument` - -Connectors where the list API already returns content inline (e.g., Slack messages, Reddit posts) do NOT need `contentDeferred`. - -### ExternalDocument Construction -- [ ] `externalId` is a stable, unique identifier from the source API -- [ ] `title` is extracted from the correct field and has a sensible fallback (e.g., `'Untitled'`) -- [ ] `content` is plain text — HTML content is stripped using `htmlToPlainText` from `@/connectors/utils` -- [ ] `mimeType` is `'text/plain'` for extracted text, or the document hands over `sourceFile` for a format the KB pipeline parses -- [ ] `contentHash` uses a metadata-based format (e.g., `service:{id}:{modifiedTime}`) for connectors with `contentDeferred: true`, or `computeContentHash` from `@/connectors/utils` for inline-content connectors -- [ ] `sourceUrl` is a valid, complete URL back to the original resource (not relative) -- [ ] `metadata` contains all fields referenced by `mapTags` and `tagDefinitions` - -### Content Extraction -- [ ] Rich text / HTML fields are converted to plain text before indexing -- [ ] Important content is not silently dropped (e.g., nested blocks, table cells, code blocks) -- [ ] Content is not silently truncated without logging a warning -- [ ] Empty/blank documents are properly filtered out -- [ ] Size checks use `Buffer.byteLength(text, 'utf8')` not `text.length` when comparing against byte-based limits (e.g., `MAX_FILE_SIZE` in bytes) - -## Step 7: Validate Tag Definitions and mapTags - -### tagDefinitions -- [ ] Each `tagDefinition` has an `id`, `displayName`, and `fieldType` -- [ ] `fieldType` matches the actual data type: `'text'` for strings, `'number'` for numbers, `'date'` for dates, `'boolean'` for booleans -- [ ] Every `id` in `tagDefinitions` is returned by `mapTags` -- [ ] No `tagDefinition` references a field that `mapTags` never produces - -### mapTags -- [ ] Return keys match `tagDefinition` `id` values exactly -- [ ] Date values are properly parsed using `parseTagDate` from `@/connectors/utils` -- [ ] Array values are properly joined using `joinTagArray` from `@/connectors/utils` -- [ ] Number values are validated (not `NaN`) -- [ ] Metadata field names accessed in `mapTags` match what `listDocuments`/`getDocument` store in `metadata` - -## Step 8: Validate Config Fields and Validation - -### configFields -- [ ] Every field has `id`, `title`, `type` -- [ ] `required` is set explicitly (not omitted) -- [ ] Dropdown fields have `options` with `label` and `id` for each option -- [ ] Selector fields follow the canonical pair pattern: - - A `type: 'selector'` field with `selectorKey`, `canonicalParamId`, `mode: 'basic'` - - A `type: 'short-input'` field with the same `canonicalParamId`, `mode: 'advanced'` - - `required` is identical on both fields in the pair -- [ ] `dependsOn` references selector field `id` values, not `canonicalParamId` -- [ ] Each selector key passes the `validate-selector` skill - -### validateConfig -- [ ] Validates all required fields are present before making API calls -- [ ] Validates optional numeric fields (checks `Number.isNaN`, positive values) -- [ ] Makes a lightweight API call to verify access (e.g., fetch 1 record, get profile) -- [ ] Uses `VALIDATE_RETRY_OPTIONS` for retry budget -- [ ] Returns `{ valid: true }` on success -- [ ] Returns `{ valid: false, error: 'descriptive message' }` on failure -- [ ] Catches exceptions and returns user-friendly error messages -- [ ] Does NOT make expensive calls (full data listing, large queries) - -## Step 9: Validate getDocument - -- [ ] Fetches a single document by `externalId` -- [ ] Returns `null` for 404 / not found (does not throw) -- [ ] Returns the same `ExternalDocument` shape as `listDocuments` -- [ ] If `listDocuments` uses `contentDeferred: true`, `getDocument` MUST fetch actual content and return `contentDeferred: false` -- [ ] If `listDocuments` uses `contentDeferred: true`, `getDocument` MUST use the same stub function to ensure `contentHash` is identical -- [ ] Handles all content types that `listDocuments` can produce (e.g., if `listDocuments` returns both pages and blogposts, `getDocument` must handle both — not hardcode one endpoint) -- [ ] Forwards `syncContext` if it needs cached state (user names, field maps, etc.) -- [ ] Error handling is graceful (catches, logs, returns null or throws with context) -- [ ] Does not redundantly re-fetch data already included in the initial API response (e.g., if comments come back with the post, don't fetch them again separately) - -## Step 10: Validate General Quality - -### fetchWithRetry Usage -- [ ] All external API calls use `fetchWithRetry` (or `secureFetchWithRetry` for user-controlled hosts) from `@/lib/knowledge/documents/secure-fetch.server` -- [ ] No raw `fetch()` calls to external APIs -- [ ] `VALIDATE_RETRY_OPTIONS` used in `validateConfig` -- [ ] If `validateConfig` calls a shared helper (e.g., `linearGraphQL`, `resolveId`), that helper must accept and forward `retryOptions` to `fetchWithRetry` -- [ ] Default retry options used in `listDocuments`/`getDocument` - -### API Efficiency -- [ ] APIs that support field selection (e.g., `$select`, `sysparm_fields`, `fields`) should request only the fields the connector needs — in both `listDocuments` AND `getDocument` -- [ ] No redundant API calls: if a helper already fetches data (e.g., site metadata), callers should reuse the result instead of making a second call for the same information -- [ ] Sequential per-item API calls (fetching details for each document in a loop) should be batched with `Promise.all` and a concurrency limit of 3-5 - -### Error Handling -- [ ] Individual document failures are caught and logged without aborting the sync -- [ ] API error responses include status codes in error messages -- [ ] No unhandled promise rejections in concurrent operations - -### Concurrency -- [ ] Concurrent API calls use reasonable batch sizes (3-5 is typical) -- [ ] No unbounded `Promise.all` over large arrays - -### Logging -- [ ] Uses `createLogger` from `@sim/logger` (not `console.log`) -- [ ] Logs sync progress at `info` level -- [ ] Logs errors at `warn` or `error` level with context - -### Meta / Runtime Split -- [ ] `connectors/{service}/meta.ts` exports `{service}ConnectorMeta: ConnectorMeta` (id, name, description, version, icon, auth, configFields, and any `tagDefinitions` / `supportsIncrementalSync`) -- [ ] `meta.ts` imports ONLY the icon from `@/components/icons`, `ConnectorMeta` (type-only), and pure-data constants — NO server/runtime imports (`@/lib/knowledge/...`, `input-validation.server`, `fetchWithRetry`, etc.); any such import in `meta.ts` is **critical** (breaks the client bundle) -- [ ] `connectors/{service}/{service}.ts` spreads `...{service}ConnectorMeta` as the first property and adds the runtime functions (`listDocuments`, `getDocument`, `validateConfig`, `mapTags?`) -- [ ] Metadata fields (id, name, auth, configFields, etc.) live ONLY in `meta.ts`, not duplicated in `{service}.ts` - -### Registry -- [ ] Connector is exported from `connectors/{service}/index.ts` -- [ ] Full connector is registered in `connectors/registry.server.ts` (server-only registry, `CONNECTOR_REGISTRY`) -- [ ] Meta is registered in `connectors/registry.ts` (client-safe registry, `CONNECTOR_META_REGISTRY`), importing `@/connectors/{service}/meta` -- [ ] Both registries use the same key and it matches the connector's `id` field -- [ ] Both registries keep the same alphabetical-by-id ordering - -## Step 11: Report and Fix - -### Report Format - -Group findings by severity: - -**Critical** (will cause runtime errors, data loss, or auth failures): -- Wrong API endpoint URL or HTTP method -- Invalid or missing OAuth scopes (not in provider config) -- Incorrect response field mapping (accessing wrong path) -- SOQL/query fields that don't exist on the target object -- Pagination that silently hits undocumented API limits -- Missing `syncContext.listingCapped = true` when a cap or transient error truncates the listing — the sync engine tombstones and later hard-deletes the documents absent from the partial listing -- Missing error handling that would crash the sync -- `requiredScopes` not a subset of OAuth provider scopes -- Query/filter injection: user-controlled values interpolated into OData `$filter`, SOQL, or query strings without escaping -- Per-document content download in `listDocuments` without `contentDeferred: true` — causes sync timeouts for large document sets -- `contentHash` mismatch between `listDocuments` stub and `getDocument` return — causes unnecessary re-processing every sync -- Server/runtime import in `meta.ts` (e.g. `@/lib/knowledge/...`, `input-validation.server`, `fetchWithRetry`) — pulls server-only code into the client bundle and breaks the build -- Connector missing from `connectors/registry.ts` (the client-safe meta registry) — or its entry there imports the runtime module instead of `meta.ts` — the knowledge UI can't render it -- A connector selector resolves shared secrets in the browser, lacks scope or credential provider - binding, combines hidden authentication with an unsafe user-controlled destination, or forwards - protected/provider payload data to the client - -**Warning** (incorrect behavior, data quality issues, or convention violations): -- HTML content not stripped via `htmlToPlainText` -- `getDocument` not forwarding `syncContext` -- `getDocument` hardcoded to one content type when `listDocuments` returns multiple (e.g., only pages but not blogposts) -- Missing `tagDefinition` for metadata fields returned by `mapTags` -- Incorrect `useBasicAuth` or `supportsRefreshTokenRotation` in token refresh config -- Invalid scope names that the API doesn't recognize (even if silently ignored) -- Private resources excluded from name-based lookup despite scopes being available -- Silent data truncation without logging -- Size checks using `text.length` (character count) instead of `Buffer.byteLength` (byte count) for byte-based limits -- URL-type config fields not normalized (protocol prefix, trailing slashes cause API failures) -- `VALIDATE_RETRY_OPTIONS` not threaded through helper functions called by `validateConfig` - -**Suggestion** (minor improvements): -- Missing incremental sync support despite API supporting it -- Overly broad scopes that could be narrowed (not wrong, but could be tighter) -- Source URL format could be more specific -- Missing `orderBy` for deterministic pagination -- Redundant API calls that could be cached in `syncContext` -- Sequential per-item API calls that could be batched with `Promise.all` (concurrency 3-5) -- API supports field selection but connector fetches all fields (e.g., missing `$select`, `sysparm_fields`, `fields`) -- `getDocument` re-fetches data already included in the initial API response (e.g., comments returned with post) -- Last page of pagination requests full `PAGE_SIZE` when fewer records remain (`Math.min(PAGE_SIZE, remaining)`) - -### Fix All Issues - -After reporting, fix every **critical** and **warning** issue. Apply **suggestions** where they don't add unnecessary complexity. - -### Validation Output - -After fixing, confirm: -1. `bun run lint` passes -2. TypeScript compiles clean -3. Re-read all modified files to verify fixes are correct -4. Any remaining unknown source schemas were explicitly reported to the user instead of guessed - -## Checklist Summary - -Before reporting, confirm every step above was checked, issues are grouped by severity, critical and warning fixes are applied, and `bun run lint` plus type-check pass. +Report as **Critical** (data loss, including a missing `listingCapped`; auth or scope failures; query injection; per-document downloads during listing; a hash mismatch between stub and full document; a server import in `meta.ts` or a missing meta registry entry, which breaks the client bundle or the UI; a selector boundary break), **Warning** (data quality and conventions: raw HTML, unforwarded `syncContext`, single-type `getDocument`, tag gaps, refresh config, unnormalized URLs, silent truncation), and **Suggestion** (efficiency: incremental sync, field selection, batching, deterministic `orderBy`). Fix every critical and warning, and suggestions where cheap. diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index 0d6b2098728..0e4666104a6 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -4,542 +4,41 @@ description: Validate an existing Sim integration (tools, block, registry, and r argument-hint: [api-docs-url] --- -# Validate Integration Skill +# Validate Integration -You are an expert auditor for Sim integrations. Your job is to thoroughly validate that an existing integration is correct, complete, and follows all conventions. +The rules live in the authoring guidance; this skill is the audit procedure. Measure against `apps/sim/tools/AGENTS.md`, `apps/sim/blocks/AGENTS.md`, `/add-tools` (effect, resolved secrets), `/add-block` (credentials, BlockMeta), and `/add-integration` (auth, deployment availability, docs intro, versioning). -## Your Task +## 1. Read everything -When the user asks you to validate an integration: -1. Read the service's API documentation (via WebFetch or Context7) -2. Read every tool, the block, and registry entries -3. Cross-reference everything against the API docs and Sim conventions -4. Report all issues found, grouped by severity (critical, warning, suggestion) -5. Fix all issues after reporting them +Every file in `apps/sim/tools/{service}/`, the block `apps/sim/blocks/blocks/{service}.ts`, its registry entries, its icon, the OAuth service in `apps/sim/lib/oauth/oauth.ts`, and, for OAuth or service-account integrations, `packages/deployment-config/src/env-capabilities.ts` and `packages/deployment-config/src/service-account-metadata.ts`. If anything uses a `selectorKey`, also run the `validate-selector` skill. -## Step 1: Gather All Files +## 2. Pull the API docs -Read **every** file for the integration — do not skip any: +The official docs are the source of truth for URLs, methods, auth headers, params (required, types, allowed values), response fields, pagination names, and error formats. A claim the docs don't settle is reported as unverified, never guessed. -``` -apps/sim/tools/{service}/ # All tool files, types.ts, index.ts -apps/sim/blocks/blocks/{service}.ts # Block definition -apps/sim/tools/registry.ts # Tool registry entries for this service -apps/sim/blocks/registry-maps.ts # Block + meta registry entry (BLOCK_REGISTRY / BLOCK_META_REGISTRY) -apps/sim/components/icons.tsx # Icon definition -apps/sim/lib/auth/connectors/providers.ts # Better Auth connector providers (buildConnectorProviders) — should use getCanonicalScopesForProvider() -apps/sim/lib/oauth/oauth.ts # OAuth provider config — single source of truth for scopes -apps/sim/lib/oauth/utils.ts # Scope utilities, SCOPE_DESCRIPTIONS for modal UI -packages/deployment-config/src/env-capabilities.ts # OAuth client runtime capability source of truth -apps/sim/lib/core/config/env.ts # Runtime env schema for capability fields -packages/sim-setup/src/capability-config.ts # Exhaustive CLI input-mode mapping for OAuth fields -packages/deployment-config/src/integrations.json # Generated client-safe integration catalog -packages/deployment-config/src/service-account-providers.generated.ts # Generated provider-ID facts -packages/deployment-config/src/service-account-metadata.ts # Handwritten deployment policy -``` +## 3. Tools -If the block, its triggers, or connector fields use a `selectorKey`, also apply the `validate-selector` skill and read -the key's entry in `apps/sim/lib/selectors/manifest.ts`, its server attachment and provider listing -primitive, and the shared context builder. Selector provider logic runs only server-side through -`selectors.execute`. +For each tool, compare against the docs: -## Step 2: Pull API Documentation +- URL, path params, method, auth header format, `Content-Type`, and body: required fields always sent, optional ones only when provided. +- Response traversal (`data.data` vs `data.results`), every mapped field, error checks before data access with specific messages. +- Param requiredness and types; `visibility` (`hidden` only for injected tokens, `user-only` for keys and account ids, `user-or-llm` otherwise); descriptions. +- `effect` by `/add-tools` → Declaring the effect. +- Request fields that reach a model or a Sim-durable sink, by `/add-tools` → Resolved Secrets and Provenance Boundaries. +- Pagination: param and response names match the docs, endpoints with different names get separate subblocks, the next-page token is an output. +- Anything that lists, downloads, uploads, batches, or reads bodies: apply the `memory-load-check` skill, and check every file-producing path, including attachment fetches inside `transformResponse` and old and new block versions, not only download-named tools. -Fetch the official API docs for the service. This is the **source of truth** for: -- Endpoint URLs, HTTP methods, and auth headers -- Required vs optional parameters -- Parameter types and allowed values -- Response shapes and field names -- Pagination patterns (which param name, which response field) -- Rate limits and error formats +## 4. Block -### Hard Rule: No Guessed Response Schemas +- Each operation maps to the right tool, every required param has a subblock under exactly the operations that use it, subblock types match param types, and `dependsOn` covers cascades. +- `tools.config.params` converts strings to numbers and booleans, turns empty optional dropdowns into `undefined`, and renames only optional or `user-or-llm` params. +- Outputs cover the key fields of all tools, with specific descriptions (never "Response data") and `properties` on known `json` shapes. +- Credentials, BlockMeta, placeholders, modes, `wandConfig`, and canvas sentences per `/add-block` and `apps/sim/blocks/AGENTS.md`. +- Scopes: none hardcoded, none beyond what the tools need, each with a `SCOPE_DESCRIPTIONS` entry. +- Deployment availability per `/add-integration` §6; a missing capability is critical, since runtime availability deliberately throws rather than exposing an unusable integration. -If the official docs do not clearly show the response JSON shape for an endpoint, you MUST tell the user instead of guessing. +## 5. Report and fix -- Do NOT assume field names from nearby endpoints -- Do NOT infer nested JSON paths without evidence -- Do NOT treat "likely" fields as confirmed outputs -- Do NOT accept implementation guesses as valid just because they are defensive +Report findings as **Critical** (wrong runtime behaviour: endpoint, method, required params, response mapping, tool id mismatches, coercion in `tools.config.tool`, missing capability, or a broken auth, provenance, or selector security boundary), **Warning** (conventions and usability: visibility, `?? null`, missing `optional`, opaque json, advanced mode, `wandConfig`, hardcoded scopes, condition gaps), and **Suggestion** (descriptions, naming, polish). Fix every critical and warning, and suggestions where cheap. -If a response schema is unknown, the validation must explicitly call that out and require: -1. sample responses from the user, -2. live test credentials for verification, or -3. trimming the tool/block down to only documented fields. - -## Step 3: Validate Tools - -For **every** tool file, check: - -### Tool ID and Naming -- [ ] Tool ID uses `snake_case`: `{service}_{action}` (e.g., `x_create_tweet`, `slack_send_message`) -- [ ] Tool `name` is human-readable (e.g., `'X Create Tweet'`) -- [ ] Tool `description` is a concise one-liner describing what it does -- [ ] Tool `version` is set (`'1.0.0'` or `'2.0.0'` for V2) - -### Effect -- [ ] Every tool declares `effect`, and the label matches the API docs, not the name (rules: - `add-tools` → Declaring the effect) -- [ ] Any `// tool-effect: ` sits on a genuine verb/label exception, and - `bun run check:tool-effects` passes -- [ ] A dry run (`sim workflows run --dry --input '{…}'` on a workflow using the - block) lists every write operation in `sideEffects.stubbed` (at most 50 entries; the rest - are counted in `sideEffects.omitted.stubbed`) with the request the API docs expect where - `request` is not `null`, and every read runs for real; a write absent from `stubbed` counts - only if its block ran (not on an untaken branch or `--mock`ed) (rules: `add-tools` → - Declaring the effect) -- [ ] A write's `dryRunOutput`, where it declares one, echoes only what its request determines, - provider-assigned ids as `dryRunId(kind, n)`, and shares any param normalisation with the - request builder through a named helper (rules: `add-tools` → Declaring the effect) - -### Params -- [ ] All required API params are marked `required: true` -- [ ] All optional API params are marked `required: false` -- [ ] Every param has explicit `required: true` or `required: false` — never omitted -- [ ] Param types match the API (`'string'`, `'number'`, `'boolean'`, `'json'`) -- [ ] Visibility is correct: - - `'hidden'` — ONLY for OAuth access tokens and system-injected params - - `'user-only'` — for API keys, credentials, and account-specific IDs the user must provide - - `'user-or-llm'` — for everything else (search queries, content, filters, IDs that could come from other blocks) -- [ ] Every param has a `description` that explains what it does - -### Request -- [ ] URL matches the API endpoint exactly (correct base URL, path segments, path params) -- [ ] HTTP method matches the API spec (GET, POST, PUT, PATCH, DELETE) -- [ ] Headers include correct auth pattern: - - OAuth: `Authorization: Bearer ${params.accessToken}` - - API Key: correct header name and format per the service's docs -- [ ] `Content-Type` header is set for POST/PUT/PATCH requests -- [ ] Body sends all required fields and only includes optional fields when provided -- [ ] For GET requests with query params: URL is constructed correctly with query string -- [ ] Each single ID path segment goes through `safeUrlPathSegment(params.id, 'id')` from `@/tools/url-path` (trims, rejects empty, dot, and separator values, then encodes); query values use `encodeURIComponent` or `URLSearchParams` - -### Response / transformResponse -- [ ] Correctly parses the API response (`await response.json()`) -- [ ] Extracts the right fields from the response structure (e.g., `data.data` vs `data` vs `data.results`) -- [ ] All nullable fields use `?? null` -- [ ] All optional arrays use `?? []` -- [ ] Error cases are handled: checks for missing/empty data and returns meaningful error -- [ ] Does NOT do raw JSON dumps — extracts meaningful, individual fields -- [ ] Every extracted field is backed by official docs or live-verified sample payloads - -### Outputs -- [ ] All output fields match what the API actually returns -- [ ] No fields are missing that the API provides and users would commonly need -- [ ] No phantom fields defined that the API doesn't return -- [ ] `optional: true` is set on fields that may not exist in all responses -- [ ] When using `type: 'json'` and the shape is known, `properties` defines the inner fields (tool outputs only — block outputs do not support `properties`) -- [ ] When using `type: 'array'`, `items` defines the item structure with `properties` (tool outputs only) -- [ ] Field descriptions are accurate and helpful - -### Types (types.ts) -- [ ] Has param interfaces for every tool (e.g., `XCreateTweetParams`) -- [ ] Has response interfaces for every tool (extending `ToolResponse`) -- [ ] Optional params use `?` in the interface (e.g., `replyTo?: string`) -- [ ] Field names in types match actual API field names -- [ ] Shared response types are properly reused (e.g., `XTweetResponse` shared across tweet tools) - -### Barrel Export (index.ts) -- [ ] Every tool is exported -- [ ] All types are re-exported (`export * from './types'`) -- [ ] No orphaned exports (tools that don't exist) - -### Tool Registry (tools/registry.ts) -- [ ] Every tool is imported and registered -- [ ] Registry keys use snake_case and match tool IDs exactly -- [ ] Entries are in alphabetical order within the file - -### Resolved-Secret Provenance and Model Input - -For every request field, determine whether it is ordinary API input, model-visible text/structured -content, opaque model input, or a value persisted into Sim-owned durable storage. - -Treat model-input provenance as opt-in. Require official documentation or an unambiguous local -execution path proving that the exact field reaches an AI model. If the evidence is ambiguous, -leave the integration unchanged; do not infer a model boundary merely from natural-language, -search, extraction, or "AI-powered" marketing terminology. - -- [ ] AI-consumed text/structured fields use `request.modelInput` with `mode: 'project'` and a - minimal exact selector; nested/JSON-string adapters preserve shape through `applyProjected` -- [ ] Ordinary external URLs, domains, resource IDs, and control fields retain normal request - semantics unless the exact field is proven model-visible; an AI-backed provider or later model - processing of the referenced resource is not sufficient evidence -- [ ] Serialized content proven to be sent directly to an external model is selected by - `request.modelInput`, projected before the existing formatter parses it, and has deterministic - formatter behavior when a whole-value placeholder is invalid for the serialized grammar -- [ ] Actual inline/raw AI-consumed bytes owned by a registered in-process operation use - `operation.modelInput` with `privateInputPaths` (or `mode: 'private-provenance'`), and the - operation calls `validateOpaqueModelInputProvenance` before model egress; storage keys, paths, signed URLs, - and ordinary remote URLs are not treated as byte provenance, while tracked stored bytes are - authorized independently at the owning model-egress boundary -- [ ] Persisted workspace-file contents are checked with the shared provenance guard only when - their bytes or decoded content cross into a model/tool-result boundary; ordinary file APIs - remain unchanged. Unsupported secret-bearing file paths are rejected at `file_write` -- [ ] Sim-owned durable writes and internal execution handoffs that can enter workflows/models use - field-scoped `operation.secretProvenance`; the owning operation validates the exact selection - and scope, strip private metadata, and persist, import, or propagate it at the owning boundary -- [ ] Private provenance is never attached to external URLs; registered in-process operations - preserve it through `operation.modelInput` / `operation.secretProvenance`, while proven - model-visible external fields use request projection and other external inputs remain unchanged -- [ ] No tool performs raw secret plaintext/source substitution or serializes plaintext provenance -- [ ] No `transformResponse` or tool-local helper blanket-sanitizes ordinary third-party results; - only execution-scoped, activated Sim provenance is projected at shared model/log boundaries -- [ ] Private headers/envelopes are produced and stripped by the shared tool executor, never - hand-rolled or returned as functional output -- [ ] Every added provenance hook has a concrete Sim `{{...}}` resolution path and a later - persistence/model/log crossing; there is no generic handling for arbitrary filenames, - metadata, provider results, or API payloads -- [ ] Diagnostic projection is applied only to values carrying execution-scoped provenance; - ordinary provider responses, filenames, URLs, and errors are unchanged -- [ ] Tests cover named `{{NAME}}` projection, unproven identical public text, nested and serialized - shape handling, unchanged ordinary external inputs, malformed/incomplete metadata, headerless - legacy requests, metadata stripping, and durable legacy/stale/scope cases when applicable - -Treat a missing or bypassed model, durable, or internal-execution provenance boundary as -**critical**. Do not fix it with a tool-specific string replacer or by sanitizing every provider -result; repair the shared request, in-process operation, persistence, or re-entry boundary -that owns the data. - -## Step 4: Validate Block - -### Block ↔ Tool Alignment - -This is the most important validation — the block must be perfectly aligned with every tool it references. - -For **each tool** in `tools.access`: -- [ ] The operation dropdown has an option whose ID matches the tool ID (or the `tools.config.tool` function correctly maps to it) -- [ ] Every **required** tool param (except `accessToken`) has a corresponding subBlock input that is: - - Shown when that operation is selected (correct `condition`) - - Marked as `required: true` (or conditionally required) -- [ ] Every **optional** tool param has a corresponding subBlock input (or is intentionally omitted if truly never needed) -- [ ] Every subBlock `id` is unique (duplicates collide silently; the last definition wins). `blocks.test.ts` fails a duplicate within one condition unless the copies are a basic/advanced mode-swap pair, one basic plus trigger-mode copies, or all carry `canonicalParamId`. The only sanctioned cross-condition reuse is the hosted-key `apiKey` pair (`add-hosted-key` skill) -- [ ] The `tools.config.tool` function returns the correct tool ID for every possible operation value -- [ ] Each subBlock (or its `canonicalParamId`) is named exactly after the tool param it fills. A required `user-only` param that is only renamed in `tools.config.params` fails `bun run apps/sim/scripts/check-block-registry.ts origin/staging`; remap only optional or `user-or-llm` params - -### SubBlocks -- [ ] Operation dropdown lists ALL tool operations available in `tools.access` -- [ ] Dropdown option labels are human-readable and descriptive -- [ ] Conditions use correct syntax: - - Single value: `{ field: 'operation', value: 'x_create_tweet' }` - - Multiple values (OR): `{ field: 'operation', value: ['x_create_tweet', 'x_delete_tweet'] }` - - Negation: `{ field: 'operation', value: 'delete', not: true }` - - Compound: `{ field: 'op', value: 'send', and: { field: 'type', value: 'dm' } }` -- [ ] Condition arrays include ALL operations that use that field — none missing -- [ ] `dependsOn` is set for fields that need other values (selectors depending on credential, cascading dropdowns) -- [ ] SubBlock types match tool param types: - - Enum/fixed options → `dropdown` - - Free text → `short-input` - - Long text/content → `long-input` - - True/false → `switch` (a Yes/No `dropdown` only when the tool needs a third "unset" state) - - Credentials → `oauth-input` with correct `serviceId` - - Every tool with a `credential`/`oauthCredential` param declares `oauth: { required: true, provider }` matching that `serviceId`, plus `credentialKind: 'service-account'` when only service accounts are supported -- [ ] In a new block or credential-only successor, a pasted key, token, or token + host comes from a - saved token credential (add-integration → Token credentials), not an inline `password` field - (legacy blocks keep theirs); a successor changes its legacy block only by `hideFromToolbar` - and `sunset`, and its picker sits under the operation -- [ ] For a token-credential integration, every tool in `tools.access` declares the service's - `tokenCredentialOAuth` policy, every - param that decides the request host is mapped, and the stored domain is in the form the tools - build URLs from (`check-block-registry.ts origin/staging` passes) -- [ ] A non-successor token block's tools declare `oauth: { required: true, provider, - credentialKind: 'service-account' }` and pin every host or account param in - `authoritativeParams` (`check-block-registry` enforces this for every block with a - saved-credential picker) -- [ ] A keyless provider appears in every table in `lib/credentials/workload-identity/audiences.ts` - and in `MIXED_MODE_PROVIDERS` (`prepare-workload-identity.ts`), and the provider catalog - shows `keyless` only when the deployment can sign tokens -- [ ] The `tokenCheckValidator` request uses the tools' host and auth, its normalizers refuse - anything that could steer the host or path, and a fake key is rejected without a valid - scoped key being refused -- [ ] Dropdown `value: () => 'default'` is set for dropdowns with a sensible default -- [ ] Every `short-input`, `long-input`, `code`, and selector subBlock has a `placeholder` — including - password fields (`Enter your API key`). Formatted values show the shape - (`2023-01-01T00:00:00Z`); optional fields with a server default name it. See add-integration → Step 3 - -### Advanced Mode -- [ ] Optional, rarely-used fields are set to `mode: 'advanced'`: - - Pagination tokens / next tokens - - Time range filters (start/end time) - - Sort order / direction options - - Max results / per page limits - - Reply settings / threading options - - Rarely used IDs (reply-to, quote-tweet, etc.) - - Exclude filters -- [ ] **Required** fields are NEVER set to `mode: 'advanced'` -- [ ] Fields that users fill in most of the time are NOT set to `mode: 'advanced'` - -### WandConfig -- [ ] Timestamp fields have `wandConfig` with `generationType: 'timestamp'` -- [ ] Comma-separated list fields have `wandConfig` with a descriptive prompt -- [ ] Complex filter/query fields have `wandConfig` with format examples in the prompt -- [ ] All `wandConfig` prompts end with an explicit `Return ONLY the ` instruction so the generated value can be pasted directly into the field -- [ ] `wandConfig.placeholder` describes what to type in natural language - -### Tools Config -- [ ] `tools.access` lists **every** tool ID the block can use — none missing -- [ ] `tools.config.tool` returns the correct tool ID for each operation -- [ ] Type coercions are in `tools.config.params` (runs at execution time), NOT in `tools.config.tool` (runs at serialization time before variable resolution — coercing there destroys dynamic references like ``) -- [ ] `tools.config.params` handles: - - `Number()` conversion for numeric params that come as strings from inputs - - `Boolean` / string-to-boolean conversion for toggle params - - Empty string → `undefined` conversion for optional dropdown values - - SubBlock ID → tool param name remapping only for optional or `user-or-llm` params - -### Block Outputs -- [ ] Outputs cover the key fields returned by ALL tools (not just one operation) -- [ ] Output types are correct (`'string'`, `'number'`, `'boolean'`, `'json'`, `'file'`, `'file[]'`) -- [ ] `type: 'json'` outputs describe inner fields in the description string: `'User profile (id, name, username, bio)'` or `'[{address, status, type}]'` for arrays -- [ ] **Do NOT add a `properties: {...}` field on block outputs.** Block-level `OutputFieldDefinition` (from `@sim/workflow-types/blocks`) only accepts `{ type, description?, condition?, hiddenFromDisplay? }`. Nested `properties` is a tool-level construct (`OutputProperty`) — adding it to a block output will fail TypeScript at build time -- [ ] No opaque `type: 'json'` with vague descriptions like `'Response data'` -- [ ] Outputs that only appear for certain operations use `condition` if supported, or document which operations return them - -### Block Metadata -- [ ] `type` is snake_case (e.g., `'x'`, `'cloudflare'`) -- [ ] `name` is human-readable (e.g., `'X'`, `'Cloudflare'`) -- [ ] `description` is a concise one-liner -- [ ] `longDescription` provides detail for docs -- [ ] `docsLink` points to `'https://docs.sim.ai/integrations/{service}'` -- [ ] `category` is `'tools'` -- [ ] `bgColor` uses the service's brand color hex -- [ ] `icon` references the correct icon component from `@/components/icons` -- [ ] `authMode` is set correctly (`AuthMode.OAuth` or `AuthMode.ApiKey`) -- [ ] Block + meta are registered in `blocks/registry-maps.ts` (`BLOCK_REGISTRY` / `BLOCK_META_REGISTRY`) alphabetically - -### BlockMeta -- [ ] `{Service}BlockMeta` is exported in the same file as the block -- [ ] Has at least 7 templates, each with `icon`, `title`, `prompt`, `modules`, `category`, and `tags` -- [ ] Prompts describe concrete use cases, not generic descriptions of what the service does -- [ ] `alsoIntegrations` is set on any template whose prompt references another service -- [ ] `skills` present (3–5 mainstream, 2–3 niche), each grounded in `tools.access` — flag any skill implying an unsupported action -- [ ] **Each skill is real, not hallucinated** — web-search and confirm it maps to a popular use case attested online (vendor use-case pages, official docs describing the workflow, reputable "top automations" articles); rewrite/remove any you cannot source -- [ ] Each skill has a kebab-case `name` (≤64 chars, unique), a one-line `description`, and markdown `content` with `# Title` + `## Steps` + an output/guidance section - -### Block Inputs -- [ ] `inputs` section lists all subBlock params that the block accepts -- [ ] Input types match the subBlock types -- [ ] When using `canonicalParamId`, inputs list the canonical ID (not the raw subBlock IDs) - -### Dynamic Selectors - -- [ ] Every remote `selectorKey` is classified in the browser-safe manifest and has exactly one - server attachment -- [ ] The manifest allowlists the minimal active `dependsOn` context and matches list/search/detail, - pagination, scope, and stale-time behavior -- [ ] Canonical basic/advanced and trigger/action modes project only their active values; exact - `{{KEY}}` references remain unresolved in the browser -- [ ] Stored credentials are bound to the actor, workspace, and trusted provider/service -- [ ] Each attachment declares and enforces a `fixed`, `credential-bound`, or explicitly reviewed - `user-controlled` destination policy -- [ ] Provider results are explicitly projected to safe option fields; secrets, tokens, credential - IDs, context values, and raw upstream errors do not enter responses, logs, or query keys -- [ ] No selector provider module, provider fetch, or OAuth-token request runs in the browser, and no - selector-only provider route remains - -## Step 5: Validate OAuth Scopes (if OAuth service) - -Scopes are centralized — the single source of truth is `OAUTH_PROVIDERS` in `lib/oauth/oauth.ts`. - -- [ ] Scopes defined in `lib/oauth/oauth.ts` under `OAUTH_PROVIDERS[provider].services[service].scopes` -- [ ] `lib/auth/connectors/providers.ts` (`buildConnectorProviders`) uses `getCanonicalScopesForProvider(providerId)` — NOT a hardcoded array -- [ ] Block `requiredScopes` uses `getScopesForService(serviceId)` — NOT a hardcoded array -- [ ] No hardcoded scope arrays in `lib/auth/connectors/providers.ts` or block files (should all use utility functions) -- [ ] Each scope has a human-readable description in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` -- [ ] No excess scopes that aren't needed by any tool - -## Step 6: Validate Deployment Availability (if OAuth service) - -The deployment UI and setup CLI do not infer OAuth client fields from scopes. They resolve the -block's generated `oauthServiceId` through the shared deployment capability catalog. - -- [ ] The visible integration block has exactly one distinct `oauth-input.serviceId` -- [ ] `resolveOAuthClientCapabilityId(serviceId)` returns the intended provider capability -- [ ] The resolved provider exists in `OAUTH_CLIENT_CAPABILITIES` -- [ ] Every field listed by that capability exists in `apps/sim/lib/core/config/env.ts` -- [ ] Every capability field has the correct `text` or `secret` entry in `OAUTH_CLIENT_SETUP_FIELDS`; no CLI naming heuristic is required -- [ ] Shared Google/Microsoft service IDs resolve to their provider capability rather than duplicate entries -- [ ] `npx sim-setup add integration ` is the command emitted by availability; the CLI has only the exhaustive input-mode projection, not a second runtime provider definition -- [ ] If the canonical OAuth service declares `serviceAccountProviderId`, - the generated `SERVICE_ACCOUNT_PROVIDER_BY_OAUTH_SERVICE_ID[serviceId]` has the same provider ID -- [ ] The service-account `deploymentRequirement` matches how that credential actually works: - omitted for an independent path, `'oauth-client'` when it needs the OAuth client fields, or - `'preview-gated'` when controlled by a preview block - -Treat a missing capability as **critical**: runtime availability intentionally throws instead of -silently exposing an unusable integration. - -## Step 7: Validate Pagination Consistency - -If any tools support pagination: -- [ ] Pagination param names match the API docs (e.g., `pagination_token` vs `next_token` vs `cursor`) -- [ ] Different API endpoints that use different pagination param names have separate subBlocks in the block -- [ ] Pagination response fields (`nextToken`, `cursor`, etc.) are included in tool outputs -- [ ] Pagination subBlocks are set to `mode: 'advanced'` - -## Step 8: Validate Memory Load Safety - -If any tool lists, searches, exports, imports, downloads, uploads, paginates, batches, transforms arrays, or reads file/HTTP bodies, read `.agents/skills/memory-load-check/SKILL.md` and apply it to the integration. - -- [ ] List/search tools expose API limits and do not auto-fetch every page into memory -- [ ] Transform logic does not build unbounded arrays, maps, sets, or `Promise.all` fan-outs -- [ ] File and HTTP body reads use explicit byte caps or existing stream-limit helpers -- [ ] Internal file results reach `createInternalToolFileResult` / `createInternalToolFilesResult` - before JSON serialization; external raw downloads explicitly use `request.responseType: 'binary'` - and return a buffered `output.file`. Provider base64 JSON needs separate handling -- [ ] Transforms retain stored `UserFile` identity/access fields, and tests cover a >10 MiB file - crossing executor admission without another upload. New file outputs contain references only, - without inline content aliases; preserve legacy versions when removing existing inline fields -- [ ] Scan every file-producing path, including attachment fetches inside `transformResponse`, URL - descriptors, export operations, and old/new block versions; checking download-named tools alone - misses late reads that occur after the first response admission -- [ ] Late attachment reads share a per-call byte budget, bound actual streamed bytes independently - of provider size metadata, and forward `ToolResponseContext.signal` through every fetch/read -- [ ] Both workflow and Copilot tests produce compact `UserFile` outputs; nested message attachment - aliases reference the same stored files, with no duplicate upload or raw bytes left behind -- [ ] New output contracts omit redundant copies of file name, MIME type, size, URL, and success; - retained provider metadata has a distinct purpose, and types match the stored-file runtime shape -- [ ] Large result payloads are summarized, paginated, referenced, or capped rather than raw-dumped -- [ ] Pagination and download tests cover caps, early stop behavior, or partial-result preservation when relevant - -## Step 9: Validate Error Handling - -- [ ] `transformResponse` checks for error conditions before accessing data -- [ ] Error responses include meaningful messages (not just generic "failed") -- [ ] HTTP error status codes are handled (check `response.ok` or status codes) - -## Step 10: Report and Fix - -### Report Format - -Group findings by severity: - -**Critical** (will cause runtime errors or incorrect behavior): -- Wrong endpoint URL or HTTP method -- Missing required params or wrong `required` flag -- Incorrect response field mapping (accessing wrong path in response) -- Missing error handling that would cause crashes -- Tool ID mismatch between tool file, registry, and block `tools.access` -- OAuth scopes missing in `lib/auth/connectors/providers.ts` that tools need -- OAuth integration `serviceId` missing from the deployment capability catalog -- Capability references an env field absent from the runtime env schema -- Service-account metadata disagrees with the canonical OAuth service configuration -- `tools.config.tool` returning wrong tool ID for an operation -- Type coercions in `tools.config.tool` instead of `tools.config.params` -- Proven model-visible request fields bypass the shared projection or private-provenance boundary -- Opaque model input is downloaded or sent before provenance and workspace-file checks -- A Sim-owned durable sink or internal execution handoff drops encrypted provenance or breaks - legacy headerless/`NULL` data -- A tool substitutes secret plaintext into source, leaks private metadata, or generically sanitizes - unrelated third-party results -- A selector resolves shared secret plaintext in the browser, lacks credential provider binding or - destination enforcement, or returns provider payloads or protected values across the selector - boundary - -**Warning** (follows conventions incorrectly or has usability issues): -- Optional field not set to `mode: 'advanced'` -- Missing `wandConfig` on timestamp/complex fields -- Wrong `visibility` on params (e.g., `'hidden'` instead of `'user-or-llm'`) -- Missing `optional: true` on nullable outputs -- Opaque `type: 'json'` without property descriptions -- Missing `.trim()` on ID fields in request URLs -- Missing `?? null` on nullable response fields -- Block condition array missing an operation that uses that field -- Hardcoded scope arrays instead of using `getScopesForService()` / `getCanonicalScopesForProvider()` -- Missing scope description in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` - -**Suggestion** (minor improvements): -- Better description text -- Inconsistent naming across tools -- Missing `longDescription` or `docsLink` -- Pagination fields that could benefit from `wandConfig` - -### Fix All Issues - -After reporting, fix every **critical** and **warning** issue. Apply **suggestions** where they don't add unnecessary complexity. - -### Regenerate Derived Artifacts - -Several files are generated from tool and block definitions. Editing a tool or block WITHOUT regenerating them fails CI, so run this before pushing: - -```bash -bun run generate # every generator below (and any other generate:/check: pair) -bun run check:integration-catalog # registry ↔ committed deployment metadata drift -bun run check:docs # committed docs ↔ what the generator renders today -bun run check:deployment-config # OAuth registry/catalog ↔ provider-ID fact drift -bun run check:audits # every audit CI enforces, including check:docs -bun run apps/sim/scripts/check-block-registry.ts origin/staging # block ↔ tool param coverage (CI, not in check:audits) -``` - -- **`generate:tool-metadata`** — required whenever a tool's `outputs`, `params`, or descriptions change. CI enforces this with `bun run check:tool-metadata`, which fails with *"Generated tool metadata is stale"*. This is the easiest gate to miss, because nothing in the tool file hints that a generated artifact mirrors it. -- **`generate:docs`** — required whenever block metadata changes (`bgColor`, `name`, `description`, operations, outputs). Regenerates the integration `.mdx`, `packages/deployment-config/src/integrations.json`, and the docs copy of `components/icons.tsx`. -- **`generate:deployment-config`** — required for OAuth or service-account changes. Regenerates provider-ID facts from the canonical OAuth registry and integration catalog; special deployment requirements remain handwritten policy. -- **`check:integration-catalog`** — loads the executable block registry, derives visible integration - deployment fields, and compares them with the committed catalog. It catches missing/unexpected - entries and stale auth/service IDs without loading the executable registry in client code. -- **`check:docs`** — check mode of `generate:docs`: renders every generated docs artifact in - memory and fails listing any committed file that differs. Runs in CI via `check:audits`. - -**Always diff the regen output before committing — but commit all of it.** These generators rewrite -every file they own, so they also true up drift that accumulated on the base branch (pages whose -source changed without a regen). That catch-up is correct output, not a regression: `check:docs` -fails CI on any page left stale, so reverting swept-in hunks with `git checkout --` reintroduces the -failure. Review the diff to confirm each hunk is explained by a real source change (yours or an -upstream PR that skipped regeneration), and investigate anything that looks like content loss — a -page losing a section usually means its source block moved or a generator input broke, not that the -hunk should be reverted. - -The integration's page must carry a `{/* MANUAL-CONTENT-START:intro */}` section directly under -``. If it is missing, write one using the template in add-integration → Step 8, and -check an existing intro against what the block actually ships (no removed or unshipped operations). - -If an icon changed, `apps/sim/components/icons.tsx` is the source of truth and `apps/docs/components/icons.tsx` is its generated mirror — they must end up byte-identical for that component. - -### Validation Output - -After fixing, confirm: -1. `bun run lint` passes with no fixes needed -2. TypeScript compiles clean (no type errors) — check the error list is empty for the files you touched; pre-existing unrelated errors in a worktree usually mean workspace packages resolve to the main checkout -3. The integration's tests pass, and any test you added actually fails without its fix (revert it once and watch it go red) -4. Derived artifacts regenerated and their diffs reviewed (see above) -5. `bun run check:integration-catalog` passes -6. `bun run check:docs` passes -7. `bun run apps/sim/scripts/check-block-registry.ts origin/staging` passes -8. For OAuth or service-account changes, `bun run check:deployment-config` passes -9. For OAuth or service-account changes, `bun run --cwd apps/sim test lib/integrations/availability.server.test.ts` passes -10. Re-read all modified files to verify fixes are correct -11. Any remaining unknown response schemas were explicitly reported to the user instead of guessed - -## Checklist Summary - -- [ ] Read ALL tool files, block, types, index, and registries -- [ ] Pulled and read official API documentation -- [ ] Validated every tool's ID, params, request, response, outputs, and types against API docs -- [ ] Validated block ↔ tool alignment (every tool param has a subBlock, every condition is correct) -- [ ] Validated advanced mode on optional/rarely-used fields -- [ ] Validated every text-entry and selector subBlock has a `placeholder` -- [ ] Validated wandConfig on timestamps and complex inputs -- [ ] Validated tools.config mapping, tool selector, and type coercions -- [ ] Validated block outputs match what tools return, with typed JSON where possible -- [ ] Validated OAuth scopes use centralized utilities (getScopesForService, getCanonicalScopesForProvider) — no hardcoded arrays -- [ ] Validated scope descriptions exist in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` for all scopes -- [ ] Validated OAuth `serviceId` resolves to the intended `OAUTH_CLIENT_CAPABILITIES` entry and all capability fields exist in the env schema -- [ ] Validated service-account projection and deployment requirement against the canonical OAuth service config -- [ ] Regenerated deployment config when block/OAuth metadata changed and ran both catalog checks -- [ ] Validated pagination consistency across tools and block -- [ ] Validated memory load safety using `.agents/skills/memory-load-check/SKILL.md` when tools list/search/download/import/export/batch data -- [ ] Validated error handling (error checks, meaningful messages) -- [ ] Validated registry entries (tools and block, alphabetical, correct imports) -- [ ] Validated model-visible/opaque inputs and Sim-durable/internal-execution provenance at their - owning boundaries -- [ ] Confirmed legacy persisted data keeps working and tracked invalid provenance fails closed -- [ ] Confirmed ordinary third-party results remain unchanged absent activated Sim provenance -- [ ] Validated `{Service}BlockMeta` exported with at least 7 templates -- [ ] Validated every dynamic selector through the shared manifest, server attachment, and - `selectors.execute` boundary -- [ ] Reported all issues grouped by severity -- [ ] Fixed all critical and warning issues -- [ ] Ran `bun run generate:tool-metadata` if any tool outputs/params changed, and confirmed `bun run check:tool-metadata` passes -- [ ] Ran `bun run generate:docs` if any block metadata changed, and committed the full generated diff — including stale-page catch-up for other integrations (`bun run check:docs` fails CI on reverted generator output) -- [ ] Validated the docs page has an accurate `MANUAL-CONTENT-START:intro` section -- [ ] Ran `bun run lint` after fixes -- [ ] Verified TypeScript compiles clean -- [ ] Verified added tests fail without their fix +Then run the root gate, `bun run apps/sim/scripts/check-block-registry.ts origin/staging`, and for OAuth or service-account changes `bun run --cwd apps/sim test lib/integrations/availability.server.test.ts`. Review the regenerated diff (`/add-integration` §7), confirm the docs intro still matches what the block ships, and report any response shape that remains unverified. diff --git a/.agents/skills/validate-model/SKILL.md b/.agents/skills/validate-model/SKILL.md index 776df5ab93d..7b83920908e 100644 --- a/.agents/skills/validate-model/SKILL.md +++ b/.agents/skills/validate-model/SKILL.md @@ -4,141 +4,32 @@ description: Validate a model entry (or every model in a provider) in apps/sim/p argument-hint: [model-id] --- -# Validate Model Skill +# Validate Model -You audit one or more model entries in `apps/sim/providers/models.ts` against the provider's official live API docs. **Hallucinated pricing and capabilities are the #1 failure mode in this file.** Every numeric and capability claim must be re-derived from a live web fetch in this session — not from memory, not from training data, not from the user's marketing email. +Audit entries in `apps/sim/providers/models.ts` against the provider's live docs. With no `model-id`, validate every model of the provider. The `add-model` skill owns the rules (live-fetch, two-source pricing, cite every URL), the source URL table, which provider code reads which capability flag, and the field conventions: read it first. -## Hard rules (do not skip) +## Procedure -1. **Live-fetch or report unverified.** Each field must be backed by a live WebFetch in this session. If you cannot reach an authoritative URL for a field, mark it **UNVERIFIED** in the report — do not silently confirm it from memory. -2. **Cite every fact.** Every value in the report must show the source URL it was checked against. No URL → mark UNVERIFIED. -3. **Two-source rule for pricing.** Cross-check input/output/cached against at least one secondary source (OpenRouter, Artificial Analysis, CloudPrice). If sources disagree, the provider's own docs win — flag the disagreement. -4. **Inspect provider implementation before flagging capability mismatches.** A capability flag in `models.ts` is dead unless the provider's code under `apps/sim/providers/{provider}/` consumes it (see Consumption Matrix below). Setting a flag the provider ignores is a warning, not a critical. -5. **Never auto-fix without printing the diff.** Show the user the proposed diff before applying. Get confirmation. +1. Read each target entry: `id`, `pricing`, `capabilities`, `contextWindow`, `releaseDate`, `recommended`, `speedOptimized`, `sunset`. +2. Live-fetch the provider's models, pricing and reasoning pages (add-model Step 1) plus one secondary pricing source. A failed fetch (404, timeout, paywall) marks its fields UNVERIFIED with the URL attempted; never confirm from memory. +3. Grep `apps/sim/providers//` for each flag the entry sets. A flag the code does not read is a dead-flag warning. +4. Per model, check: + - `id` matches the API identifier exactly (reseller prefix included); `releaseDate`; `sunset.status` reflects any announced retirement (`deprecated` once calls fail, `legacy` once superseded). + - `input` / `output` / `cachedInput` (or `cachedInput` correctly omitted); `pricing.updatedAt` older than 60 days is a suggestion to refresh. + - `contextWindow` and `maxOutputTokens`. + - Every capability is both documented as supported **and** read by the provider code. `reasoningEffort` must be omitted on a model whose API rejects it (grok-4.3), but kept on always-reasoning models that accept it (OpenAI o-series): verify per model. `thinking.streamed` per add-model. + - At most one or two `recommended`; `speedOptimized` only on the smallest tier. + - A model under a provider `getHostedModels()` expands is billed with Sim's key: confirm that is intended (a BYOK-only model there is a billing bug). -## Your Task +## Report -When invoked as `/validate-model [model-id]`: +Per model: field | repo | docs | URL | status (✓ / ✗ / ⚠️ single-source / ❓ unverified), then findings by severity and a one-line count (`N models · X critical · Y warnings · Z suggestions · W unverified`). -1. Read the target entries from `models.ts` -2. Live-fetch the provider's official models, pricing, and capability/reasoning pages + at least one secondary source for pricing -3. Inspect the provider implementation to know which flags are actually consumed -4. Run the checklist below per model -5. Report findings (critical / warning / suggestion / unverified) with every cell linked to its source URL -6. Offer to fix; on confirm, edit `models.ts` in a single pass and re-lint +- **critical**: misleads about cost or breaks calls (wrong price, id, context window, a capability the API rejects). +- **warning**: dead flag, internal inconsistency, unintended hosting, missing `sunset` after retirement. +- **suggestion**: stale `updatedAt`, field order, a missing `speedOptimized`. +- **unverified**: no authoritative source found. Never mark the validation passed; say which URLs you tried and what third-party sources report, and ask. -If `model-id` is omitted, validate every model in the provider. +## Fixing -## Step 1: Read entries from `models.ts` - -Capture per model: `id`, full `pricing`, full `capabilities`, `contextWindow`, `releaseDate`, `recommended`, `speedOptimized`, `deprecated`. - -## Step 2: Live-fetch authoritative sources - -Use the canonical provider URL table in the `add-model` skill (`.agents/skills/add-model/SKILL.md`), Step 1, as the single source of truth — fetch the models index, pricing, and reasoning/parameter caveats pages listed there for the target provider. - -Secondary cross-check (use at least one): OpenRouter, Artificial Analysis, CloudPrice. - -If a fetch fails (404, timeout, paywall), record the URL attempted and mark dependent fields UNVERIFIED. - -## Step 3: Build the consumption map for this provider - -Use the Consumption Matrix in `.agents/skills/add-model/SKILL.md` Step 2 and run its re-grep commands for the target provider before relying on it. A flag set in `models.ts` that the provider's code does not read = **warning: dead flag**. - -## Step 4: Run the checklist - -For each model, evaluate every row. Statuses: ✓ matches docs, ✗ disagrees, ⚠️ single-source, ❓ UNVERIFIED (could not fetch). - -### Identity -- [ ] `id` exactly matches provider's API model identifier (case, dots, dashes, prefix for resellers) -- [ ] `releaseDate` matches launch announcement -- [ ] `deprecated: true` set if provider has announced retirement (or removed from active list) - -### Pricing (per 1M tokens, USD) -- [ ] `pricing.input` matches provider pricing page -- [ ] `pricing.output` matches provider pricing page -- [ ] `pricing.cachedInput` matches provider's documented cached/prompt-cache rate (or is correctly omitted if no caching offered) -- [ ] `pricing.updatedAt` is recent — warn if older than 60 days - -### Context & output limits -- [ ] `contextWindow` matches docs (in tokens) -- [ ] `capabilities.maxOutputTokens` matches documented output cap (or is correctly omitted if "no output limit") - -### Capabilities (each must be DOCUMENTED-AS-SUPPORTED **and** CONSUMED-BY-PROVIDER-CODE) -- [ ] `temperature` — provider accepts it for this model (reasoning-always-on models often reject) -- [ ] `reasoningEffort.values` — list matches docs; **omitted** for always-reasoning models that reject the parameter (e.g., grok-4.3, where xAI docs explicitly state `reasoning_effort` is not supported). Verify per model — some always-reasoning models (e.g., OpenAI's o-series) DO accept `reasoning_effort` and should keep the flag. -- [ ] `verbosity.values` — only on OpenAI gpt-5.x family; values match docs -- [ ] `thinking.levels` + `thinking.default` — only on providers whose code reads `thinking`/`thinkingLevel` (see the add-model Consumption Matrix); values match docs -- [ ] `thinking.streamed` — REQUIRED on Anthropic-family thinking models. Current Claude thinking models use `'summary'` (Sim requests `display: 'summarized'`); use `'full'` only if official API docs explicitly guarantee raw thinking deltas. Verify against the provider's thinking-display docs. After any change, run `bun run generate:agent-stream-docs` so the Agent block docs table stays in sync (CI diffs it) -- [ ] `nativeStructuredOutputs` — only on providers whose code consumes it (see the Consumption Matrix); provider must document Structured Outputs / JSON-mode for this model -- [ ] `toolUsageControl` — provider supports `tool_choice` semantics -- [ ] `computerUse` — provider implements computer-use loop AND model is a computer-use SKU -- [ ] `deepResearch` — only on actual deep-research SKUs -- [ ] `memory: false` — only when the model genuinely cannot maintain conversation history - -### Flags -- [ ] `recommended: true` — at most one or two per provider; should be current flagship -- [ ] `speedOptimized: true` — only on smallest/fastest tier (nano / flash-lite / haiku class) - -### Hosting / billing -- [ ] If `getHostedModels()` includes the model ID (`providers/models.ts` expands whole providers — more than openai/anthropic/google — plus the static Fireworks catalog), the model is served with Sim's rotating key and billed via `shouldBillModelUsage()`. Confirm that is the intent (a BYOK-only model parked under a hosted provider is a billing bug — warning). -- [ ] If the model is hosted, the deployment is expected to have its `{PREFIX}_COUNT` / `{PREFIX}_1..N` env vars set (ops concern; note if it looks unset for a model claiming hosted support). - -## Step 5: Report (mandatory format) - -For each model, emit a table with one row per checklist item. Every row that claims ✓ must have a URL. - -```markdown -### Validation — - -| Field | Repo | Live docs | Source URL | Status | -|---|---|---|---|---| -| `input` | $1.25/M | $1.25/M | https://docs.x.ai/... | ✓ | -| `cachedInput` | $0.50/M | $0.20/M | https://cloudprice.net/... | ✗ stale (price cut not picked up) | -| `reasoningEffort` | low/medium/high | rejected by API | https://docs.x.ai/.../reasoning | ✗ inert — selecting silently no-ops | -| `contextWindow` | 1,000,000 | 1,000,000 | https://docs.x.ai/... + https://openrouter.ai/... | ✓ (2 sources) | -| `releaseDate` | 2026-04-30 | not found in scraped pages | _attempted: docs.x.ai, x.ai/news_ | ❓ UNVERIFIED | - -**Findings** -- 🔴 critical — `cachedInput` is wrong: docs say $0.20/M, repo has $0.50/M -- 🟡 warning — `reasoningEffort` is set but provider rejects it for this model (xAI docs explicitly: "reasoning_effort is not supported by grok-4.3") -- 🔵 suggestion — `pricing.updatedAt` is 90 days old; refresh -- ❓ unverified — `releaseDate` could not be confirmed from any fetched page; ask user - -**Disagreements between sources** -- _none_ OR _OpenRouter says $X, provider docs say $Y — went with provider docs_ -``` - -End each multi-model run with a summary count: `N models checked · X critical · Y warnings · Z suggestions · W unverified`. - -## Step 6: Offer to fix - -After reporting, ask: *"Want me to fix the critical and warning items? I'll print the diff first."* On yes: - -1. Print the proposed diff (do not apply yet) -2. Get user confirmation -3. Edit `models.ts` in a single pass -4. Run `bun run lint` -5. Re-run only the failed rows of the checklist on the new state - -## Severity definitions - -- 🔴 **critical** — wrong number or wrong identifier that misleads users about cost or breaks API calls. Examples: incorrect pricing, wrong model id, wrong context window, capability the API rejects. -- 🟡 **warning** — dead code or internal inconsistency. Examples: capability flag the provider ignores, multiple `recommended: true` per provider, `pricing.updatedAt` >60 days old, missing `deprecated: true` on retired model. -- 🔵 **suggestion** — style/consistency. Examples: field order, missing `speedOptimized` on a clearly smallest-tier model. -- ❓ **unverified** — could not fetch an authoritative source for this field. Surface it; never silently confirm. - -## Common drift - -Pricing changes after provider price cuts; `reasoningEffort`/`thinking`/`verbosity` set on a model whose provider code or API does not accept them; stale `pricing.updatedAt`; wrong context window; more than one `recommended` after a flagship swap; missing `deprecated: true` after a provider retirement announcement. - -## What "I cannot verify this" looks like - -If, after fetching the documented sources, a field cannot be confirmed: - -- Mark the row ❓ UNVERIFIED with the URL(s) attempted -- Surface it in the **Findings** section with severity ❓ -- Do NOT mark the validation as passed -- Ask the user for a docs URL or guidance before changing anything - -The skill is allowed to say *"I could not verify the cached input price for grok-4.3 from the official xAI docs in this session — I attempted [URLs] without finding the value. Third-party sources [URL1, URL2] both report $0.20/M. Confirm before I update."* That is correct behavior. Hallucinating a number is not. +Offer to fix critical and warning items. Print the diff and get confirmation before editing; edit in one pass, run `bun run lint` (and `bun run generate` if a `thinking`/`reasoningEffort` entry changed), then re-check only the failed rows. diff --git a/.agents/skills/validate-permission-group-item/SKILL.md b/.agents/skills/validate-permission-group-item/SKILL.md index 578e936f212..e0e9af137e4 100644 --- a/.agents/skills/validate-permission-group-item/SKILL.md +++ b/.agents/skills/validate-permission-group-item/SKILL.md @@ -4,155 +4,82 @@ description: Audit an existing enterprise permission-group item end-to-end — r argument-hint: --- -# Validate Permission Group Item Skill +# Validate Permission Group Item -The question is not "does this key exist in the right places" — the registry makes most of that compiler-enforced. It is: +The question is not "does this key exist in the right places" (the registry makes most of that compiler-enforced). It is: > **If an organization admin sets this, what refuses, and can I make that refusal happen?** -A key with an admin checkbox but no server gate passes every structural audit. Assume nothing enforces until you have found the throw. +A key with an admin control but no server gate passes every structural audit. Assume nothing enforces until you have found the throw. Read `add-permission-group-item` first: it owns the invariants and their reasons; this skill is the audit procedure. -**`add-permission-group-item` owns the procedure and the rationale for every invariant named below.** Read it for *why*; this skill is the checklist. Its "Read the system first" list is the same one — start there. +## Step 1: Registry entry and copy -## Step 1: Registry entry (`lib/permission-groups/fields.ts`) +Record the builder, `enforcement`, `scope` and position in `lib/permission-groups/fields.ts`. -Record the builder, the `enforcement`, and the position. +- `git log -p` shows the key appended, never moved (wire order; no test catches a reorder). +- The name keeps the permissive value falsy (no `allowX` boolean). +- `scope` is true: an `organization` key read from a workspace group, or the reverse, misleads the admin about which group applies. +- **The hint, label and category tell the truth.** A `'capability'` key refuses at the API, so "Hide the … from the sidebar" is a lie an admin acts on; the same string is the active-restriction prose Copilot reads. An allowlist's `empty` phrasing says "none allowed", not "unrestricted". Rank a misleading hint with the enforcement findings. -- **Default permissive?** The builders hardcode `false` / `null` / `[]`, so the risk is a *name* that inverts the meaning — an `allowX` boolean. The checkbox renders `checked={!editingConfig[feature.configKey]}` (ticked = allowed), so a positively-named boolean renders backwards. -- **Position stable?** Declaration order is the wire order, and no test catches a reorder. If `git log -p` shows the key was ever *moved* rather than appended, every open editor reads as unsaved (`group-detail.tsx` dirty-checks stringified configs). -- **Phrasing accurate?** An allowlist's `{ limited, empty }` and a denylist's string are read by `getActivePermissionGroupRestrictions` in `features.ts` and surface to users through the Copilot workspace VFS and the enterprise platform context. Confirm `empty` says "none allowed", not "unrestricted". -- **Does the `hint` tell the truth?** Highest-value read in this step. A `'capability'` key refuses at the API, so a hint saying it hides a tab, module, or nav item "from the sidebar" is a **lie an admin acts on** — they believe they are tidying chrome while withholding a module. The same string is reused as the prose for an *active* restriction, where "hide" is simply false. Any surviving "Hide the …" hint on a `'capability'` key is a finding, not a nit; check `label` and `category` the same way (a "Sidebar" or "Settings Tabs" section makes the claim structurally). - -## Step 2: Schemas, type, defaults, parser - -All derived by `collectFieldProperty` from the same registry. **Do not hand-verify them.** Verify nothing bypasses the derivation: +## Step 2: Nothing bypasses the derivation ```bash grep -rn "" apps/sim --include='*.ts' --include='*.tsx' \ | grep -vE 'lib/permission-groups/(fields|resolve\.server|config-scope\.server)\.ts' ``` -Only the registry and the resolvers are excluded, so `capabilities.ts` stays in the output — its `CAPABILITY_RULES` entry and `deniedBy` are the authoritative reads this step exists to check. Every hit should be a rule's `deniedBy`, an enforcement site, a UI binding, or a test. A route restating the key, a client re-deriving a default, or a second coercion path is a leak. Specifically: - -- **`z.array(...).catch(...)` anywhere on this key's path** — whole-value tolerant, so one bad member discards every good one, and on an allowlist the `null` fallback means unrestricted. That is fail-**open**. `tolerantArray` filters element-wise. Rank a regression here with the enforcement findings. -- **`?? []` applied to an allowlist** — collapses "allows everything" into "allows nothing". -- **A hand-rolled comparison against an integration allowlist.** `allowedIntegrations` and the deployment's `ALLOWED_INTEGRATIONS` are written independently, so one names `slack` where the other names `slack_v2`; anything folding only case intersects them to nothing and hides an integration both allow. Both halves must canonicalize through `integration-allowlist.ts` (`intersectAccessControlAllowlists` / `toAccessControlAllowlist` / `resolveAccessControlBlockType`) *before* intersecting, with the checked type resolved the same way. That module reads `block-successors.generated.ts` through `Object.hasOwn` — a bare bracket lookup answers an admin-supplied `constructor` with an inherited function and 500s every path reading that group; `check:block-successors` catches the map going stale. -- **Any config read not from `parsePermissionGroupConfig` or a `resolvePermissionGroupConfig` caller.** - -Two structural guards must still be present: - -- **`parsePermissionGroupConfig` still tests `Array.isArray(config)`.** `typeof [] === 'object'`, the column is `jsonb` so a row genuinely can hold `[]`, and `z.object().parse([])` throws — the guard is what returns defaults instead of a 500. `tolerantArray` carries the mirror image. -- **`CAPABILITY_RULES` still uses `satisfies`, not an annotation.** An annotation collapses `StaticPermissionGroupCapability` to `never`, silently disabling the type system around capabilities with nothing wrong at runtime. `AssertsStaticCapabilityResolves` catches it; any weakening is a top-tier finding. - -Confirm the assertions at the bottom of `fields.ts` still name a field of this kind (`AssertsAllowlistStaysPrecise`, `AssertsDenylistStaysPrecise`, `AssertsRestrictionStaysPrecise`, `AssertsAuthTypesStayPrecise`, `AssertsParserReturnsTheConfig`) — a zod generic degrading to `unknown` is invisible at runtime and quietly loses every call site's narrowing. +Every hit should be a rule's `deniedBy`, an enforcement site, a UI binding, or a test. A route restating the key, a client re-deriving a default, a second coercion path, a config read not via `parsePermissionGroupConfig`/`resolvePermissionGroupConfig`, a `.catch()` on an array, a `?? []` on an allowlist, or a hand-rolled integration-allowlist comparison is a finding. Confirm `parsePermissionGroupConfig` keeps its `Array.isArray` guard and `CAPABILITY_RULES` keeps `satisfies`. ## Step 3: Admin UI (`ee/access-control/components/group-detail.tsx`) -- **Boolean:** appears automatically via `PLATFORM_FEATURES`. Confirm its `category` is in `PLATFORM_CATEGORY_ORDER`; an unlisted one renders after every ordered section. -- **Nested allowlist / denylist** (one that qualifies a platform-feature boolean): renders **nothing** unless it is in the `featureExtras` map — keyed by the *parent boolean's feature id*, not the config key. No picker there means no admin can ever set it. Report it. Top-level lists — `allowedIntegrations`, `allowedModelProviders`, `deniedModels`, `deniedTools` — are not in `featureExtras` and must not be reported for it; they render from the dedicated Providers and Blocks sections, so check them there. -- For an **allowlist** picker, check both behaviors: refuses an empty selection (`if (values.length === 0) return`) and collapses a full one back to `null` (otherwise the allowlist freezes at today's members). A **denylist** picker must do neither: clearing every entry is how an admin denies nothing, and a full selection is a real state that denies everything. -- Check the parent is the right one (`allowedKnowledgeConnectors` under `hide-knowledge-base`, not `disable-knowledge-base-creation`). +- Booleans render from `PLATFORM_FEATURES`; check the category is in `PLATFORM_CATEGORY_ORDER`. +- A nested allowlist/denylist renders nothing unless it has an `AccessRequestTarget` kind and a `PermissionGrid` in `featureExtras` under the right parent feature id. No picker means no admin can set it. The four run-scoped lists render from the Providers and Blocks sections instead; don't report them for `featureExtras`. +- Allowlist writes (`ee/access-control/utils/access-state.ts`) collapse a full selection back to `null`; a denylist write must not. ## Step 4: Capability rule -A `'capability'` key must appear in some rule's `configKeys` — the audit asserts this (D) and the converse (E): a key declared `'executor'` or `'ui-only'` that a rule reads is flagged, so a key cannot gain enforcement while staying documented as weaker. Then check what the audit cannot: - -- **`configKeys` lists every key `deniedBy` reads.** The audit parses it textually and never reads the closure; a key read but unlisted is invisible to D and E. -- **`kind` is right.** A rule needing a request value must be `'parameterized'` — and a parameterized rule named on an operation cannot have run in production (`defineWorkspaceOperation` throws at definition time), so something else is wrong. -- **A narrower capability subsumes the broader one it replaced.** An operation carries exactly one capability. Precedent: `knowledge.create` / `knowledge.upload` both read `hideKnowledgeBaseTab`, without which a group withholding the whole module could still create a KB through the API. Check `git log` for a re-pointed `capability:` and verify the narrower rule grew the broader key in the same commit. -- **`detailCode` matches the remedy** — `FORBIDDEN_DETAIL_CODES` is closed over remedies, not causes; otherwise `PERMISSION_GROUP_CAPABILITY_BLOCKED`. Any code in use needs a TSDoc-documented entry in `FORBIDDEN_DETAIL_CODES`, published to OpenAPI as the `V2ForbiddenDetailCode` enum. -- **`describe` reads correctly** as the subject of `" is not available under your organization's permission group"` — a singular noun or gerund agreeing with "is". Exactly two functions build that sentence, both defined in `capabilities.ts` (`refuseCapability` throws it, `capabilityRefusal` returns it); any call site writing it out is a drift finding. +- `kind` is right: a rule needing a request value is `'parameterized'`. +- A narrower capability that replaced a broader one also reads the broader key: check `git log` for a re-pointed `capability:` and verify the rule grew the key in the same commit. +- `detailCode` matches the remedy; `describe` reads as the subject of "… is not available under your organization's permission group". A call site writing the sentence itself is drift. -## Step 5: Prove the enforcement — do not assume it +## Step 5: Prove the enforcement -The step the skill exists for. Find the **actual refusal**, name file and line, and say what a caller sees. +The step this skill exists for. Find the **actual refusal**: file, line, and what the caller sees. ```bash grep -rn "''" apps/sim --include='*.ts' --include='*.tsx' grep -rn "permission-group-enforced: " apps/sim ``` -The second grep misses a gate whose annotation sits in a TSDoc block above the enclosing statement — read the surrounding function. - -Classify into exactly one of: - -1. **Declared on operations.** The funnel enforces in `requireCurrentHumanAccess` → `requireCapability`. Verify the set is *complete*: enumerate every route and tool reaching the same behavior. One declaring `capability: 'none'` is the hole. -2. **Asserted at a call site** with a `// permission-group-enforced: — ` annotation. Verify it goes through `capability-assertions.ts` (`assertWorkspaceCapability`, `isWorkspaceCapabilityWithheld`, `isOrganizationCapabilityWithheld`, `capabilityDeniedBy`), through `isCapabilityWithheldForUser` (`lib/permission-groups/user-scope.server.ts` — workspace group first, else the organization's default, for a user-level act that may or may not name a workspace; outside `capability-assertions.ts` on purpose because it reads org membership through the billing graph, a guarded root of `check:application-graph`; `app/api/cli/auth/approve/route.ts` is the shape), or a direct `CAPABILITY_RULES[''].deniedBy(...)` rather than reading `config.disableX` inline, **and** that it *raises* through `refuseCapability` / renders `capabilityRefusal(cap)` rather than building its own `ForbiddenOperationError` with a hand-written message — the easy half to miss, because the decision looks right. Use-case shape: `validatePublicFileSharing`, `validateChatDeployAuth` (`ee/access-control/utils/permission-check.ts`), `assertConnectorTypeAllowed` (`lib/knowledge/application/connectors.ts`). Raw-route shape: `app/api/logs/stats/route.ts`, `app/api/table/[tableId]/export/route.ts`. A raw route should render through `capabilityRefusalResponse` (`lib/permission-groups/capability-response.ts`), which reads `details.code` off the rule — a hand-rolled `NextResponse.json({ error: capabilityRefusal(cap) }, { status: 403 })` drops it, reporting the four specifically-coded capabilities (`deploy.chat.auth_mode`, `file_share.publish`, `file_share.auth_mode`, `personal_api_key.use`) as the generic block. Convergence is partial: `grep -rln "capabilityRefusal(" apps/sim/app --include=route.ts` lists the raw routes that still hand-roll it (ignore `*.test.ts`, `app/api/v1/middleware.ts`, `app/api/table/utils.ts`, and the v2 envelope, which are not raw-route responses). A raw route you add or touch renders through `capabilityRefusalResponse`; report an untouched hand-rolled one as a finding when its capability carries a specific code, otherwise as a note. v1 is deliberately not converged on it (`resolveCapabilityRefusal` in `app/api/v1/middleware.ts`). -3. **Executor-gated** by `assertPermissionsAllowed`, per block / tool / model, matching through the shared primitives in `lib/permission-groups/` — `block-access.ts`, `operation-access.ts`, `model-access.ts`, `integration-allowlist.ts` — which the editor and Copilot projections read too, so a second copy of a match rule is a finding. Verify the branch throws a real error and that the id it compares against is the vocabulary the admin UI writes — `deniedTools` holds block `tools.access` ids verbatim, version suffix included. `allowedIntegrations` is *also* enforced off the run, by `assertSelectorIntegrationAllowed` (`lib/selectors/server/integration-access.ts`), so an executor key's coverage is not complete until every non-run path that reaches the third party is checked too. -4. **A field projection, not a gate.** `logs.trace_spans` and `logs.cost` withhold fields, so the logs routes correctly declare `capability: 'none'`. Single owner: `lib/logs/projection.ts` (`resolveLogFieldProjection`, `projectExecutionData`, `projectCostTotal`), which carries both annotations. A **second** implementation of the same redaction is the finding — as is a query that lets a caller filter or sort on a withheld field, which turns the projection into an oracle. -5. **Nothing.** Report as a defect: "an organization that sets this believes it applied a restriction that does not exist". - -Ahead of all five: the principal-wide capabilities (`personal_api_key.use`, `oauth_apps.use`; `PRINCIPAL_WIDE_CAPABILITIES` in `lib/core/application/operation.ts`) fit none of them. They withhold a *principal kind* across every operation — the funnel's `personal_api_key` / `oauth_access_token` branches (`lib/core/application/workspace-authorization.ts`) and `app/api/v1/middleware.ts` — and declaring one on an operation throws, so their absence from every `capability:` field is correct, not a hole. - -Then **make the refusal happen**: write a failing case, or remove the gate (the `capability:` field, the `deniedBy` body, the assertion call) and confirm an existing test goes red. A test that still passes with the gate removed proves nothing. Restore afterward. **Check the fixture's `workspaceOrganizationId` first**: `requireCapability` short-circuits when it is `null` (`requireCapability` in `lib/core/application/workspace-authorization.ts`), so a context that leaves it unset passes either way and the existing test proves nothing even before you touch it. - -For an allowlist the three states must be tested separately — `null` permits every member, a populated list only the named ones, `[]` permits **none**. `capabilities.test.ts` pins all three for `knowledge.connectors`; less than that elsewhere is a gap. - -### Who the gate runs against - -**Read the subject, not the nearest user id.** Every capability sink must take its subject from the `capabilityGoverned*` helper for the identity the surface holds — `capabilityGovernedPrincipalUserId` for a `Principal` (`lib/core/application`), `capabilityGovernedUserId` for a v1 `RateLimitResult` or a `TableAccessPrincipal`, `capabilityGovernedAuthUserId` for a `checkSessionOrInternalAuth` result. Each returns `null` where no group governs, and `null` is a pass. Reading `rateLimit.userId`, `auth.userId`, `subjectUserId` or `triggeredByUserId` into a sink is the finding: for a workspace key the first is the key's *creator*, for an internal JWT the second is the run's actor, and the last is a billing *attribution*. `check-capability-subject.ts` audits **v1 only**, so every other surface is on you. Where the subject is persisted and read back later (`capabilityGovernedUserId` on `table_run_dispatches` / `table_row_executions`), it must be declared required as `string | null` — an optional field with a fallback is exactly how producers re-inherited `triggeredByUserId`, so a proposal to make it optional is a finding. - -- **`/api/v1`** authorizes in `app/api/v1/middleware.ts`, not through `authorizeWorkspaceOperation`; `capabilityGovernedUserId(rateLimit)` branches on `keyType`, never on the presence of a user id. Each route also threads a required, spelled-out `V1RouteCapability`. -- **Raw internal table routes** gate `tables.use` in `checkAccess` (`app/api/table/utils.ts`) via a `TableAccessPrincipal` union — `{ kind: 'user'; userId }` or `{ kind: 'workspace_api_key'; keyCreatorUserId }` — so a bare id does not type-check. `tableAccessPrincipal(rateLimit)` is the one place v1 builds it. -- **The definition-time `undefined` guard** on `defineWorkspaceOperation` is not redundant even though `capability` is required on the `ApplicationOperation` **base type** (the `capability` field in `lib/core/application/operation.ts`, not merely on the builder — which is what stops a bare-literal factory from compiling): `apps/sim/tsconfig.json` excludes `*.test.ts` / `*.test.tsx` and the enforcement audit walks past test files, so a fixture is the one construction site no static check reads. Without it a capability-less operation defines cleanly and then throws `Cannot read properties of undefined` inside `capabilityDeniedBy` **only for tenants that actually have a permission group**, passing CI and every personal workspace. A proposal to drop it is a finding. - -## Step 6: Tests - -- **`fields.test.ts`** — the key must be in both the `input` and `expected` halves of the `'a fully populated config'` fixture; that corpus is pinned so a changed row is defended rather than slipping through. The rest of the file derives from `DEFAULT_PERMISSION_GROUP_CONFIG` and needs no per-key edit. -- **`capabilities.test.ts`** — a case for any rule with logic beyond reading one key: subsumption, allowlist three-state, auth-mode membership. -- **`features.test.ts`** — no edit for a boolean; a non-boolean key's `limited` / `empty` prose should be pinned here. -- **`config-scope.server.test.ts`** — the per-request memo. A gate resolving the config outside `resolvePermissionGroupConfig` is a Step 2 finding, not one here. - -## Step 7: Run the checks - -```bash -bun run check:permission-group-enforcement -bun run check:application-graph -bun run check:capability-subject -cd apps/sim && bun run type-check -bun run --cwd apps/sim test lib/permission-groups -``` - -All three are inside `check:audits`, which derives its list from the `check:*` scripts in `package.json` — a new audit is opted *out* deliberately. Read the output, not the exit codes. Success-line shapes (the counts must include the item under audit): - -``` -✓ permission-group enforcement: operations declare a capability, capabilities all enforced -✅ Application graph clean: roots reach none of forbidden module trees -check:capability-subject — v1 files, capability subjects resolved through capabilityGovernedUserId. -``` +The second grep misses an annotation in a TSDoc block above the statement; read the surrounding function. Classify into exactly one: -| Audit | What it catches | -|---|---| -| `check:permission-group-enforcement` | Every operation declares a capability and every capability is enforced. All-or-nothing — no migration mode exits 0 with work outstanding, so do not go looking for a `pending enforcement:` list | -| `check:application-graph` | The funnel roots (`lib/core/application/index.ts`, `capabilities.ts`, `capability-assertions.ts`, `config-scope.server.ts`) and `with-route-handler.ts` reach no heavy module tree at *runtime* (`import type` is erased and allowed). A gate that imports a resolver into a guarded root is a finding even if the gate is correct; such an edge can also make unrelated tests fail on partial mocks | -| `check:capability-subject` | Every v1 capability sink takes its subject from `capabilityGovernedUserId`, no v1 file outside the middleware imports the permission-group modules, and at least one governed sink was found at all | +1. **Declared on operations** (funnel: `requireCurrentHumanAccess` → `requireCapability`). Verify coverage is *complete*: enumerate every route and tool reaching the same behavior; one declaring `capability: 'none'` is the hole. A capability declared on an operation nothing routes to also satisfies the audit. +2. **Asserted at a call site**: must go through `capability-assertions.ts` / `isCapabilityWithheldForUser` or `CAPABILITY_RULES[id].deniedBy`, raise via `refuseCapability` (not a hand-built `ForbiddenOperationError`; the decision can look right while the message drifts), and raw routes render `capabilityRefusalResponse`. Examples: `assertConnectorTypeAllowed`, `app/api/logs/stats/route.ts`. `grep -rln "capabilityRefusal(" apps/sim/app --include=route.ts` lists raw routes still hand-rolling the 403: a finding when the capability carries a specific `detailCode`, otherwise a note. v1 renders its own envelope on purpose. +3. **Executor-gated** by `assertPermissionsAllowed` through the shared `lib/permission-groups/*-access.ts` primitives; a second copy of a match rule is a finding. Check the compared id is the vocabulary the admin UI writes (`deniedTools` holds `tools.access` ids verbatim, version suffix included), and that non-run paths reaching the third party are gated too (`assertSelectorIntegrationAllowed` for `allowedIntegrations`). +4. **A field projection** (`logs.trace_spans`, `logs.cost`): single owner `lib/logs/projection.ts`. A second redaction, or a query that filters/sorts on a withheld field, is the finding. +5. **Nothing.** Report: "an organization that sets this believes it applied a restriction that does not exist". -Two ways the enforcement audit passes without proving what you want: +Principal-wide capabilities (`personal_api_key.use`, `oauth_apps.use`) fit none of these: their absence from every `capability:` field is correct. -- **Vacuous parse.** It reads source text with regexes, so it refuses success when the three registries parse to nothing, cross-checks rule count against capability count, reports per call any unreadable `id`, fails a file that mints an operation but parses to **zero** declarations, and flags any exported `*Operations` registry member it read no operation from. If one fires the audit is broken, not the code — fix the parsers rather than leaving it green. (That last guard is what catches an operation minted by a factory that never calls the builder, which bypasses the required type *and* the audit.) -- **A capability declared on an operation nothing routes to.** Assertion C is satisfied by the declaration alone. +**Then make the refusal happen**: write a failing case, or remove the gate and confirm an existing test goes red; restore afterward. Check the fixture's `workspaceOrganizationId` first: `requireCapability` short-circuits on `null`, so such a test proves nothing even before you touch it. -The audits prove *reachability*, never correctness — that a capability is named, a key is read by some rule, a subject came from the right helper. Step 5 is what covers the rest. +**Check the subject.** The gate's user id must come from the `capabilityGoverned*` helper for the identity held. Reading `rateLimit.userId` (a workspace key's creator), `auth.userId` (an internal JWT's run actor) or `triggeredByUserId` (a billing attribution) into a sink is a finding; `check:capability-subject` covers v1 only. A proposal to make a persisted subject optional, to drop the definition-time `capability` guard (test fixtures are the one construction site no static check reads), or to exempt Copilot is a finding. -## Known gaps — recognize these, do not re-report them +## Step 6: Tests and checks -Each is deliberate and documented in the code; `add-permission-group-item` carries the full reasoning. +- `fields.test.ts`: key in both halves of `'a fully populated legacy config'`. +- `capabilities.test.ts`: a case for any rule with logic beyond one key (subsumption, allowlist `null`/list/`[]`, auth-mode membership). `features.test.ts`: a non-boolean key's `limited`/`empty` prose pinned. +- Run `check:permission-group-enforcement`, `check:application-graph`, `check:capability-subject`, and `bun run --cwd apps/sim test lib/permission-groups`; the success-line counts must include this item. The audits prove reachability, never correctness: Step 5 covers the rest. -- **A workspace API key resolves no permission group** — it authorizes as the workspace, so there is no user and `operation.capability` does not apply; the same reasoning shapes `TableAccessPrincipal`, `capabilityGovernedUserId` and the log projection. Substituting the key's creator would apply a bystander's group to every caller of a shared key and break the key when that person left. Minting a workspace key is itself capability-gated. -- **An executor delegation carries role but not capabilities** — a delegated `executor` principal with a `sim_user` subject goes through `requireCurrentHumanRole` only. A capability names what a *person* may reach; applying it to a run makes "hide Tables" a kill-switch for every workflow with a Table block. -- **An actorless deployment run passes through** — a delegated executor principal in `mode: 'deployment'` with no resolvable subject acts with the workspace's authority; denying would 403 every scheduled run, webhook and public-API call. What such a run *does* is still governed by `assertPermissionsAllowed`, which is why the four run-scoped keys carry `enforcement: 'executor'`. -- **Copilot is NOT exempt** — a delegated principal with a `sim_user` subject whose `serviceId` is anything other than `executor` takes the full `requireCurrentHumanAccess`. Copilot acts as the person. A proposal to exempt it is a finding. -- **Capability is checked after the role check** — `NoWorkspaceAccessError` is concealed as a 404 by the v2 surface, so refusing on capability first would hand a non-member an oracle for what the organization withholds. The v1 middleware states the same ordering in its TSDoc. Not a bug. -- **`allowedEgressHosts` does not exist** — there is no network-egress allowlist. Requests for one are a feature, not missing wiring. -- **Nothing currently ships as `ui-only`** — the union member has no user; an absent `ui-only` key is not a gap. +## Known gaps: do not re-report -## Report Format +These are deliberate (reasons in `add-permission-group-item` Traps): a workspace API key resolves no group; an executor delegation is role-only; an actorless deployment run passes; capability is checked after the role check; nothing ships as `ui-only`. `allowedEgressHosts` does not exist: a request for one is a feature, not missing wiring. -1. **Kind and enforcement** — as declared, and whether the declaration is true. -2. **The refusal** — file, line, error thrown, what the caller sees (status, `detailCode`, message). Or: it is a projection, and here is its single owner. Or: nothing refuses. -3. **The subject** — whose user id the gate reads, and that a workspace key reaches it ungated rather than as its creator. -4. **Proof** — the test that fails when the gate is removed, or that no such test exists. -5. **Coverage gaps** — routes, tools, surfaces reaching the same behavior without the gate. -6. **Findings**, ordered: unenforced key > key-creator substituted for the acting principal > fail-open coercion (`.catch()` on an array, a dropped `Array.isArray` guard, `CAPABILITY_RULES` annotated instead of `satisfies`) > incomplete operation coverage > allowlist three-state confusion > **admin copy that misstates the enforcement** > duplicated projection logic > missing admin UI > missing test > cosmetic. +## Report -A hint saying "hide" for a key that 403s is not cosmetic — it is the one defect an admin acts on directly: they tick it believing they hid a link, and members lose the module. Rank it with the enforcement findings. +1. **Kind and enforcement**, as declared and whether true. +2. **The refusal**: file, line, error, what the caller sees (status, `detailCode`, message); or its projection owner; or nothing. +3. **The subject**: whose user id the gate reads; a workspace key reaches it ungated, never as its creator. +4. **Proof**: the test that fails with the gate removed, or that none exists. +5. **Coverage gaps**: routes, tools, surfaces reaching the behavior without the gate. +6. **Findings**, ordered: unenforced key > key creator substituted for the acting principal > fail-open coercion > incomplete operation coverage > allowlist three-state confusion > admin copy that misstates enforcement > duplicated projection > missing admin UI > missing test > cosmetic. diff --git a/.agents/skills/validate-selector/SKILL.md b/.agents/skills/validate-selector/SKILL.md index 1b2ea55fd7a..8f230c4ad16 100644 --- a/.agents/skills/validate-selector/SKILL.md +++ b/.agents/skills/validate-selector/SKILL.md @@ -6,95 +6,29 @@ argument-hint: # Validate Selector -Validate the complete path, not only the provider adapter. +Validate the complete path (declaration, manifest, context, attachment, provider primitive, shared executor), not only the provider adapter. `add-selector` holds the conventions. Search literal API paths as well as imports before declaring an old provider route or contract unused. -## Gather the path +## Declaration and manifest -Read: +- Allowed context is minimal; readiness matches the provider request; list, pagination, search, detail, scope and stale-time metadata match the actual UX. +- `dependsOn` names the required source fields; canonical pairs contribute only their active member; action/trigger and connector surfaces build the same context. -- Every block, trigger, and connector field using the selector key. -- `apps/sim/lib/selectors/manifest.ts` and `types.ts`. -- `apps/sim/lib/selectors/context.ts`. -- The matching server attachment and any shared provider listing primitive. -- `apps/sim/lib/selectors/server/registry.ts`. -- The shared application executor, route contract, client transport, and focused tests when the - finding concerns shared behavior. +## Server boundary -Search literal API paths as well as TypeScript imports before deciding whether an old provider route -or contract is unused. +`selectors.execute` accepts session, personal API key, OAuth token and delegated Copilot principals (internal route and `v2/selectors`). Confirm the shared executor owns this order, and the attachment duplicates none of it: -## Validate the declaration and manifest - -- The key has exactly one classification and one attachment (`local` keys use the local registry). -- Allowed context is minimal and readiness matches the provider request. -- List, pagination, search, detail, unknown-detail, scope, and stale-time metadata match actual UX. -- `dependsOn` names the required source fields; canonical pairs contribute only their active member. -- Action/trigger and connector surfaces build the same canonical context. -- Exact `{{KEY}}` references remain unresolved in the browser; runtime references are omitted, - while embedded interpolation is forwarded unresolved and rejected by the server executor. -- Query keys contain no context value, reference, credential ID, secret, or hash of one. - -## Validate the server boundary - -For provider and internal selectors, confirm the shared executor owns this order: - -1. Session authentication before request parsing. -2. Canonical workflow/workspace loading and read authorization. +1. Authenticate the principal before parsing. +2. Load the canonical workflow/workspace and authorize read. 3. Manifest capability and exact-context allowlisting. 4. Exact environment-reference resolution on the server. 5. Credential use, workspace, and trusted provider/service binding. -6. Destination-policy enforcement before provider network access. -7. Provider/internal execution followed by explicit option projection and sanitization. - -The attachment must not duplicate these shared checks. It must not accept a browser-provided module, -provider, service, operation kind, origin, or scope list. - -Review its destination classification: - -- `fixed` origins are code-defined. -- `credential-bound` origins are derived from or checked against the authorized credential. -- `user-controlled` destinations have an explicit policy for hidden use-only authentication and - network safety. - -Missing and inaccessible references, and missing, unauthorized, or provider-mismatched credentials, -must not become existence oracles. Hidden/server-only resolved plaintext, credentials, authentication -material, and raw upstream errors must not enter responses, query/cache/rate keys, selector result -caches, logs, audit metadata, redirects, or error messages. Browser-known literals and viewable -personal/shared values are not automatically protected plaintext, but the executor must still never -deliberately or wholesale echo selector context. Only intentionally projected, normalized -`{ id, label, meta? }` options and bounded cursors may cross the boundary. - -Selector code adds no context, token, or result cache beyond the single accepted exception -described in the `add-selector` skill ("Wire the UI declaration"). - -## Validate provider reuse and browser boundaries - -- The attachment calls a server-only provider primitive, not a route handler or internal HTTP URL. -- A surviving provider route has a proven non-selector caller and delegates to the same primitive. -- There is no client provider selector module, selector-specific token request, or browser request to - a provider-specific selector route. -- Internal selectors delegate to existing authorized use cases rather than querying protected data - in the route or adapter. - -## Tests and report - -Use existing Vitest/route/React Query patterns. Preserve valuable provider tests, but do not demand a -per-selector authorization matrix. Shared executor tests should cover ordering, references, -credential binding, sanitization, and safe errors; adapter tests should cover only special provider -behavior. +6. Destination policy before any provider network access (`assertSelectorIntegrationAllowed` included). +7. Execution, then explicit option projection and sanitization. -Report critical, warning, and suggestion findings. Treat browser secret resolution, missing scope or -credential authorization, unsafe destination binding, provider payload passthrough, and plaintext -egress as critical. +Missing or unauthorized references and credentials must not be existence oracles; resolved secrets and raw upstream errors never reach responses, keys, caches, logs, audit or errors. Only projected `{ id, label, meta? }` options and bounded cursors cross. Browser-known literals and viewable values are not automatically protected, but context is never echoed wholesale. -Run the smallest relevant focused suites plus: +Check the destination classification is honest and that internal selectors delegate to authorized use cases rather than querying in the adapter. -```bash -bun run --cwd apps/sim type-check -bun run check:api-validation:strict -bun run check:fork-dependent-coverage -bun run check:client-boundary -git diff --check -``` +## Report -State which live-provider checks remain pending when disposable credentials are unavailable. +Critical, warning and suggestion findings. Critical: browser secret resolution, missing scope or credential authorization, unsafe destination binding, provider payload passthrough, plaintext egress. State which live-provider checks remain pending when disposable credentials are unavailable. diff --git a/.agents/skills/validate-trigger/SKILL.md b/.agents/skills/validate-trigger/SKILL.md index fe61054b4bc..f4276b0a3d7 100644 --- a/.agents/skills/validate-trigger/SKILL.md +++ b/.agents/skills/validate-trigger/SKILL.md @@ -6,236 +6,23 @@ argument-hint: [api-docs-url] # Validate Trigger -You are an expert auditor for Sim webhook triggers. Your job is to validate that an existing trigger implementation is correct, complete, secure, and aligned across all layers. +The rules are in `/add-trigger` and `apps/sim/triggers/AGENTS.md`; this skill is the audit procedure. Read every file in `apps/sim/triggers/{service}/`, the handler `apps/sim/lib/webhooks/providers/{service}.ts` and its registry entry, and the block's trigger wiring. If a trigger subblock uses a `selectorKey`, also run the `validate-selector` skill. -## Your Task +The service's webhook docs are the source of truth for event types and payloads, the signature method (algorithm, header, secret format), any challenge handshake, the subscription API, and retry behaviour. Report payload fields the docs don't show instead of guessing them. -1. Read the service's webhook/API documentation (via WebFetch) -2. Read every trigger file, provider handler, and registry entry -3. Cross-reference against the API docs and Sim conventions -4. Report all issues grouped by severity (critical, warning, suggestion) -5. Fix all issues after reporting them +## Checks -## Step 1: Gather All Files +- **Definitions.** Webhook triggers use `buildTriggerSubBlocks` (directly or through a service wrapper) unless they deliberately keep a custom layout, as `apps/sim/triggers/airtable/webhook.ts` does. Trigger ids follow `{service}_{event}`, and `provider` equals the handler registry key. +- **Event mapping.** Every trigger id `matchEvent` references exists in the service's trigger options and maps to the documented event type; a generic webhook trigger passes every event. Challenge or verification events never match. Trigger utils are loaded with a dynamic `await import()` to avoid a cycle. +- **Auth.** `verifyAuth` uses the documented algorithm, header name, and signature format (hex, `sha256=` prefix, base64), computed over the raw body, compared with `safeCompare` (never `===`), and fails closed when a required secret is missing. It runs before any processing; the replay window tolerates provider retries without being loose; secrets are never logged, even at debug. +- **`formatInput`.** Matches `outputs` exactly per `apps/sim/triggers/AGENTS.md`, nested at the right depth, returned as `{ input }`. +- **Idempotency.** `extractIdempotencyId` uses the provider's delivery id (`Linear-Delivery`, `svix-id`) when there is one, otherwise a content id like `${type}:${id}`, never a timestamp (that breaks dedup on retries). +- **Challenge.** `handleChallenge` returns exactly the documented response; env-backed secrets resolve through `resolveEnvVarsInObject`. +- **Subscriptions.** `createSubscription` calls the right endpoint with the right events and `getNotificationUrl(ctx.webhook)`, maps 401 and similar to friendly messages, and returns the external id. `deleteSubscription` treats 404 as done and skips quietly when the key or external id is missing. No provider logic in the shared orchestration (`route.ts`, `provider-subscriptions.ts`, `deploy.ts`). +- **Block wiring.** `triggers.available` and the spread `getTrigger(...).subBlocks` name the same triggers. -Read **every** file for the trigger — do not skip any: +## Report and fix -``` -apps/sim/triggers/{service}/ # All trigger files, utils.ts, index.ts -apps/sim/lib/webhooks/providers/{service}.ts # Provider handler (if exists) -apps/sim/lib/webhooks/providers/registry.ts # Handler registry -apps/sim/triggers/registry.ts # Trigger registry -apps/sim/blocks/blocks/{service}.ts # Block definition (trigger wiring) -``` +Report as **Critical** (wrong signature algorithm or header, `===` on secrets, missing `verifyAuth` for signed webhooks, `formatInput`/`outputs` mismatch, id mismatches across trigger, registry, and block, provider logic in shared orchestration, a wrong subscription endpoint, or a selector security break), **Warning** (missing idempotency or challenge handling, timestamps in idempotency keys, too tight a replay window, unfiltered challenge events, undiscoverable fields, incomplete setup instructions), and **Suggestion** (descriptions, extra outputs, messages, logging). Fix every critical and warning, and suggestions where cheap. -Also read for reference: -``` -apps/sim/lib/webhooks/providers/types.ts # WebhookProviderHandler interface -apps/sim/lib/webhooks/providers/utils.ts # Shared helpers (createHmacVerifier, etc.) -apps/sim/lib/webhooks/provider-subscription-utils.ts # Subscription helpers -apps/sim/lib/webhooks/processor.ts # Central webhook processor -``` - -If trigger sub-blocks use a `selectorKey`, also apply the `validate-selector` skill and read the -key's browser-safe manifest entry, shared active-value context builder, server attachment, and -provider listing primitive. - -## Step 2: Pull API Documentation - -Fetch the service's official webhook documentation. This is the **source of truth** for: -- Webhook event types and payload shapes -- Signature/auth verification method (HMAC algorithm, header names, secret format) -- Challenge/verification handshake requirements -- Webhook subscription API (create/delete endpoints, if applicable) -- Retry behavior and delivery guarantees - -### Hard Rule: No Guessed Webhook Payload Schemas - -If the official docs do not clearly show the webhook payload JSON for an event, you MUST tell the user instead of guessing. - -- Do NOT invent payload field names -- Do NOT infer nested payload paths without evidence -- Do NOT treat likely event shapes as verified -- Do NOT accept `formatInput` mappings that are not backed by docs or live payloads - -If a payload schema is unknown, validation must explicitly recommend: -1. sample webhook payloads, -2. a live test webhook source, or -3. trimming the trigger to only documented outputs. - -## Step 3: Validate Trigger Definitions - -### utils.ts -- [ ] `{service}TriggerOptions` lists all trigger IDs accurately -- [ ] `{service}SetupInstructions` provides clear, correct steps for the service -- [ ] `build{Service}ExtraFields` includes relevant filter/config fields with correct `condition` -- [ ] Output builders expose all meaningful fields from the webhook payload -- [ ] Output builders do NOT use `optional: true` or `items` (tool-output-only features) -- [ ] Nested output objects correctly model the payload structure - -### Trigger Files -- [ ] Exactly one primary trigger has `includeDropdown: true` -- [ ] All secondary triggers do NOT have `includeDropdown` -- [ ] Webhook triggers use `buildTriggerSubBlocks` (directly or through a service wrapper) unless they deliberately keep a custom layout, as `triggers/airtable/webhook.ts` does; polling triggers (`polling: true`) declare subBlocks manually -- [ ] Every trigger's `id` matches the convention `{service}_{event_name}` -- [ ] Every trigger's `provider` matches the service name used in the handler registry -- [ ] `index.ts` barrel exports all triggers -- [ ] Every remote `selectorKey` is present in `apps/sim/lib/selectors/manifest.ts` and has exactly - one server attachment -- [ ] Trigger-mode `dependsOn` fields project only active canonical values; exact `{{KEY}}` - references stay unresolved in the browser -- [ ] Trigger selectors use the shared `selectors.execute` transport, with no client provider - module, browser token request, or selector-only provider route - -### Trigger ↔ Provider Alignment -- [ ] Every trigger ID referenced in `matchEvent` logic exists in `{service}TriggerOptions` -- [ ] Event matching logic in the provider correctly maps trigger IDs to service event types -- [ ] Event matching logic in `is{Service}EventMatch` (if exists) correctly identifies events per the API docs - -## Step 4: Validate Provider Handler - -### Auth Verification -- [ ] `verifyAuth` correctly validates webhook signatures per the service's documentation -- [ ] HMAC algorithm matches (SHA-1, SHA-256, SHA-512) -- [ ] Signature header name matches the API docs exactly -- [ ] Signature format is handled (raw hex, `sha256=` prefix, base64, etc.) -- [ ] Uses `safeCompare` for timing-safe comparison (no `===`) -- [ ] If `webhookSecret` is required, handler rejects when it's missing (fail-closed) -- [ ] Signature is computed over raw body (not parsed JSON) - -### Event Matching -- [ ] `matchEvent` returns `true` to run, or `false` / a `NextResponse` to skip with a custom body -- [ ] Challenge/verification events are excluded from matching (e.g., `endpoint.url_validation`) -- [ ] When `triggerId` is a generic webhook ID, all events pass through -- [ ] When `triggerId` is specific, only matching events pass -- [ ] Event matching logic uses dynamic `await import()` for trigger utils (avoids circular deps) - -### formatInput -- [ ] Every key in the `formatInput` return matches a key in the trigger `outputs` schema -- [ ] Every key in the trigger `outputs` schema is populated by `formatInput` -- [ ] No extra undeclared keys that users can't discover in the UI -- [ ] No wrapper objects (`webhook: { ... }`, `{service}: { ... }`) -- [ ] Nested output paths exist at the correct depth (e.g., `resource.id` actually has `resource: { id: ... }`) -- [ ] `null` is used for missing optional fields (not empty strings or empty objects) -- [ ] Returns `{ input: { ... } }` — not a bare object -- [ ] Every mapped payload field is backed by official docs or live-verified webhook payloads - -### Idempotency -- [ ] `extractIdempotencyId` returns a stable, unique key per delivery -- [ ] Uses provider-specific delivery IDs when available (e.g., `X-Request-Id`, `Linear-Delivery`, `svix-id`) -- [ ] Falls back to content-based ID (e.g., `${type}:${id}`) when no delivery header exists -- [ ] Does NOT include timestamps in the idempotency key (would break dedup on retries) - -### Challenge Handling (if applicable) -- [ ] `handleChallenge` correctly implements the service's URL verification handshake -- [ ] Returns the expected response format per the API docs -- [ ] Env-backed secrets are resolved via `resolveEnvVarsInObject` if needed - -## Step 5: Validate Automatic Subscription Lifecycle - -If the service supports programmatic webhook creation: - -### createSubscription -- [ ] Calls the correct API endpoint to create a webhook -- [ ] Sends the correct event types/filters -- [ ] Passes the notification URL from `getNotificationUrl(ctx.webhook)` -- [ ] Returns `{ providerConfigUpdates: { externalId } }` with the external webhook ID -- [ ] Throws on failure (orchestration handles rollback) -- [ ] Provides user-friendly error messages (401 → "Invalid API Key", etc.) - -### deleteSubscription -- [ ] Calls the correct API endpoint to delete the webhook -- [ ] Handles 404 gracefully (webhook already deleted) -- [ ] Never throws — catches errors and logs non-fatally -- [ ] Skips gracefully when `apiKey` or `externalId` is missing - -### Orchestration Isolation -- [ ] NO provider-specific logic in `route.ts`, `provider-subscriptions.ts`, or `deploy.ts` -- [ ] All subscription logic lives on the handler (`createSubscription`/`deleteSubscription`) - -## Step 6: Validate Registration and Block Wiring - -### Trigger Registry (`triggers/registry.ts`) -- [ ] All triggers are imported and registered -- [ ] Registry keys match trigger IDs exactly -- [ ] No orphaned entries (triggers that don't exist) - -### Provider Handler Registry (`providers/registry.ts`) -- [ ] Handler is imported and registered (if handler exists) -- [ ] Registry key matches the `provider` field on the trigger configs -- [ ] Entries are in alphabetical order - -### Block Wiring (`blocks/blocks/{service}.ts`) -- [ ] Block has `triggers.enabled: true` -- [ ] `triggers.available` lists all trigger IDs -- [ ] All trigger subBlocks are spread into `subBlocks`: `...getTrigger('id').subBlocks` -- [ ] No trigger IDs in `triggers.available` that aren't in the registry -- [ ] No trigger subBlocks spread that aren't in `triggers.available` - -## Step 7: Validate Security - -- [ ] Webhook secrets are never logged (not even at debug level) -- [ ] Auth verification runs before any event processing -- [ ] No secret comparison uses `===` (must use `safeCompare` or `crypto.timingSafeEqual`) -- [ ] Timestamp/replay protection is reasonable (not too tight for retries, not too loose for security) -- [ ] Raw body is used for signature verification (not re-serialized JSON) - -## Step 8: Report and Fix - -### Report Format - -Group findings by severity: - -**Critical** (runtime errors, security issues, or data loss): -- Wrong HMAC algorithm or header name -- `formatInput` keys don't match trigger `outputs` -- Missing `verifyAuth` when the service sends signed webhooks -- Provider-specific logic leaking into shared orchestration files -- Trigger IDs mismatch between trigger files, registry, and block -- `createSubscription` calling wrong API endpoint -- Auth comparison using `===` instead of `safeCompare` -- Trigger selector credential/reference resolution occurring in the browser, or a selector missing - scope authorization, credential provider binding, destination enforcement, or safe projection - -**Warning** (convention violations or usability issues): -- Missing `extractIdempotencyId` when the service provides delivery IDs -- Timestamps in idempotency keys (breaks dedup on retries) -- Missing challenge handling when the service requires URL verification -- Output schema missing fields that `formatInput` returns (undiscoverable data) -- Overly tight timestamp skew window that rejects legitimate retries -- `matchEvent` not filtering challenge/verification events -- Setup instructions missing important steps - -**Suggestion** (minor improvements): -- More specific output field descriptions -- Additional output fields that could be exposed -- Better error messages in `createSubscription` -- Logging improvements - -### Fix All Issues - -After reporting, fix every **critical** and **warning** issue. Apply **suggestions** where they don't add unnecessary complexity. - -### Validation Output - -After fixing, confirm: -1. `bun run type-check` passes -2. Re-read all modified files to verify fixes are correct -3. Provider handler tests pass (if they exist): `bun run --cwd apps/sim test lib/webhooks/providers/` — handler files are kebab-case (`azure-devops.ts`) while trigger directories are snake_case (`azure_devops`), so use the handler's actual basename -4. Any remaining unknown webhook payload schemas were explicitly reported to the user instead of guessed - -## Checklist Summary - -- [ ] Read all trigger files, provider handler, types, registries, and block -- [ ] Pulled and read official webhook/API documentation -- [ ] Validated trigger definitions: options, instructions, extra fields, outputs -- [ ] Validated dynamic selector declarations through the shared manifest and server attachment -- [ ] Validated primary/secondary trigger distinction (`includeDropdown`) -- [ ] Validated provider handler: auth, matchEvent, formatInput, idempotency -- [ ] Validated output alignment: every `outputs` key ↔ every `formatInput` key -- [ ] Validated subscription lifecycle: createSubscription, deleteSubscription, no shared-file edits -- [ ] Validated registration: trigger registry, handler registry, block wiring -- [ ] Validated security: safe comparison, no secret logging, replay protection -- [ ] Reported all issues grouped by severity -- [ ] Fixed all critical and warning issues -- [ ] `bun run type-check` passes after fixes +Run the handler's tests with `bun run --cwd apps/sim test lib/webhooks/providers/`: handler files are kebab-case (`azure-devops.ts`) while trigger folders are snake_case (`azure_devops`). diff --git a/.agents/skills/you-might-not-need-a-callback/SKILL.md b/.agents/skills/you-might-not-need-a-callback/SKILL.md deleted file mode 100644 index 3e78befc072..00000000000 --- a/.agents/skills/you-might-not-need-a-callback/SKILL.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -name: you-might-not-need-a-callback -description: Analyze and fix useCallback anti-patterns in your code -argument-hint: "[scope] [fix=true|false]" ---- - -# You Might Not Need a Callback - -Arguments: -- scope: what to analyze (default: your current changes). Examples: "diff to staging", "PR #123", "src/components/", "whole codebase" -- fix: whether to apply fixes (default: true). Set to false to only propose changes. - -User arguments: $ARGUMENTS - -## References - -Read before analyzing: -1. https://react.dev/reference/react/useCallback — official docs on when useCallback is actually needed - -## The one rule that matters - -`useCallback` is only useful when **something observes the reference**. Ask: does anything care if this function gets a new identity on re-render? - -Observers that care about reference stability: -- A `useEffect` that lists the function in its deps array -- A `useMemo` that lists the function in its deps array -- Another `useCallback` that lists the function in its deps array -- A child component wrapped in `React.memo` that receives the function as a prop -- A custom hook that documents a referential-stability requirement for the callback - -If none of those apply — if the function is only called inline, or passed to a non-memoized child, or assigned to a native element event — the reference is unobserved and `useCallback` adds overhead with zero benefit. - -## Anti-patterns to detect - -1. **No observer tracks the reference**: The function is only called inline in the same component, or passed to a non-memoized child, or used as a native element handler (` + + + ); +} +``` + +### CSS-Only Stagger + +```css +.stagger-item { + opacity: 0; + transform: translateY(12px); + filter: blur(4px); + animation: fadeInUp 400ms ease-out forwards; +} + +.stagger-item:nth-child(1) { animation-delay: 0ms; } +.stagger-item:nth-child(2) { animation-delay: 100ms; } +.stagger-item:nth-child(3) { animation-delay: 200ms; } + +@keyframes fadeInUp { + to { + opacity: 1; + transform: translateY(0); + filter: blur(0); + } +} +``` + +## Exit Animations + +Exit animations should be softer and less attention-grabbing than enter animations. The user's focus is moving to the next thing — don't fight for attention. + +### Subtle Exit (Recommended) + +```tsx +// Small fixed translateY — indicates direction without drama + + {content} + +``` + +### Full Exit (When Context Matters) + +```tsx +// Slide fully out — use when spatial context is important +// (e.g., a card returning to a list, a drawer closing) + + {content} + +``` + +### Good vs. Bad + +```css +/* Good — subtle exit */ +.item-exit { + opacity: 0; + transform: translateY(-12px); + transition: opacity 150ms ease-in, transform 150ms ease-in; +} + +/* Bad — dramatic exit that steals focus */ +.item-exit { + opacity: 0; + transform: translateY(-100%) scale(0.5); + transition: all 400ms ease-in; +} + +/* Bad — no exit animation at all (element just vanishes) */ +.item-exit { + display: none; +} +``` + +**Key points:** +- Use a small fixed `translateY` (e.g., `-12px`) instead of the full container height +- Keep some directional movement to indicate where the element went +- Exit duration should be shorter than enter duration (150ms vs 300ms) +- Don't remove exit animations entirely — subtle motion preserves context + +## Contextual Icon Animations + +When icons appear or disappear contextually (on hover, on state change), animate them with `opacity`, `scale`, and `blur` rather than just toggling visibility. + +### Motion Example + +```tsx +import { AnimatePresence, motion } from "framer-motion"; + +function IconButton({ isActive, icon: Icon }) { + return ( + + ); +} +``` + +### CSS Transition Approach (No Motion) + +If the project doesn't use Motion (Framer Motion), keep both icons in the DOM and cross-fade them with CSS transitions. Because neither icon unmounts, both enter and exit animate smoothly. + +The trick: one icon is absolutely positioned on top of the other. Toggling state cross-fades them — the entering icon scales up from `0.25` while the exiting icon scales down to `0.25`, both with opacity and blur. + +```tsx +function IconButton({ isActive, ActiveIcon, InactiveIcon }) { + return ( + + ); +} +``` + +The non-absolute icon (InactiveIcon) defines the layout size. The absolute icon (ActiveIcon) overlays it without affecting flow. + +### Choosing Between Motion and CSS + +| | Motion (Framer Motion) | CSS transitions (both icons in DOM) | +| --- | --- | --- | +| **Enter animation** | Yes | Yes | +| **Exit animation** | Yes (via `AnimatePresence`) | Yes (cross-fade — icon never unmounts) | +| **Spring physics** | Yes | No — use `cubic-bezier(0.2, 0, 0, 1)` as approximation | +| **When to use** | Project already uses `framer-motion` (or `motion/react`) | No motion dependency, or keeping bundle small | + +**Rule:** Check the project's `package.json` for `motion` or `framer-motion`. If present, use the Motion approach. If not, use the CSS cross-fade pattern — don't add a dependency just for icon transitions. + +### When to Animate Icons + +| Animate | Don't animate | +| --- | --- | +| Icons that appear on hover (action buttons) | Static navigation icons | +| State change icons (play → pause, like → liked) | Decorative icons | +| Icons in contextual toolbars | Icons that are always visible | +| Loading/success state indicators | Icon labels (text next to icon) | + +Default values: scale 0.25→1, opacity 0→1, blur 4px→0, `{ type: "spring", duration: 0.3, bounce: 0 }`. + +## Scale on Press + +A subtle scale-down on click (about 0.96-0.97) gives buttons tactile feedback. Use CSS transitions for interruptibility — if the user releases mid-press, it should smoothly return. + +Not every button needs this. Add a `static` prop to your button component that disables the scale effect when the motion would be distracting. + +### CSS Example + +```css +.button { + transition-property: scale; + transition-duration: 150ms; + transition-timing-function: ease-out; +} + +.button:active { + scale: 0.96; +} +``` + +### Tailwind Example + +```tsx + +``` + +### Motion Example + +```tsx + + Click me + +``` + +### Static Prop Pattern + +Extract the scale class into a variable and conditionally apply it based on a `static` prop: + +```tsx +const tapScale = "active:not-disabled:scale-[0.96]"; + +function Button({ static: isStatic, className, children, ...props }) { + return ( + + ); +} + +// Usage + {/* scales on press */} + {/* no scale */} +``` + +## Skip Animation on Page Load + +Use `initial={false}` on `AnimatePresence` to prevent enter animations from firing on first render. Elements that are already in their default state shouldn't animate in on page load — only on subsequent state changes. + +### When It Works + +```tsx +// Good — icon doesn't animate in on mount, only on state change + + + + + +``` + +Works well for: icon swaps, toggles, tabs, segmented controls — anything that has a default state on page load. + +### When It Breaks + +Don't use `initial={false}` when the component relies on its `initial` prop to set up a first-time enter animation, like a staggered page hero or a loading state. In those cases, removing the initial animation skips the entire entrance. + +```tsx +// Bad — initial={false} would skip the staggered page enter entirely + + + ... + + +``` + +Verify the component still looks right on a full page refresh before applying this. diff --git a/.agents/skills/make-interfaces-feel-better/performance.md b/.agents/skills/make-interfaces-feel-better/performance.md new file mode 100644 index 00000000000..155954988e9 --- /dev/null +++ b/.agents/skills/make-interfaces-feel-better/performance.md @@ -0,0 +1,88 @@ +# Performance + +Transition specificity and GPU compositing hints. + +## Transition Only What Changes + +Never use `transition: all` or Tailwind's `transition` shorthand (which maps to `transition-property: all`). Always specify the exact properties that change. + +### Why + +- `transition: all` forces the browser to watch every property for changes +- Causes unexpected transitions on properties you didn't intend to animate (colors, padding, shadows) +- Prevents browser optimizations + +### CSS Example + +```css +/* Good — only transition what changes */ +.button { + transition-property: scale, background-color; + transition-duration: 150ms; + transition-timing-function: ease-out; +} + +/* Bad — transition everything */ +.button { + transition: all 150ms ease-out; +} +``` + +### Tailwind + +```tsx +// Good — explicit properties + +``` + +### Play Button Triangles + +Play icons are triangular and their geometric center is not their visual center. Shift slightly right: + +```css +/* Good — optically centered */ +.play-button svg { + margin-left: 2px; /* shift right to account for triangle shape */ +} + +/* Bad — geometrically centered but looks off */ +.play-button svg { + /* no adjustment */ +} +``` + +### Asymmetric Icons (Stars, Arrows, Carets) + +Some icons have uneven visual weight. The best fix is adjusting the SVG directly so no extra margin/padding is needed in the component code. + +```tsx +// Best — fix in the SVG itself +// Adjust the viewBox or path to visually center the icon + +// Fallback — adjust with margin + + + +``` + +## Shadows Instead of Borders + +> In this repo, use the `shadow-subtle`/`shadow-medium`/`shadow-overlay`/`shadow-card` tokens for elevation and keep neutral edges as `--border` borders (`.claude/rules/sim-styling.md`, Line weight); do not replace them with `0 0 0 1px` shadow rings. The pattern below is for projects without that token system. + +For **buttons, cards, and containers** that use a border for depth or elevation, prefer replacing it with a subtle `box-shadow`. Shadows adapt to any background since they use transparency; solid borders don't. This also helps when using images or multiple colors as backgrounds — solid border colors don't work well on backgrounds other than the ones they were designed for. + +**Do not apply this to dividers** (`border-b`, `border-t`, side borders) or any border whose purpose is layout separation rather than element depth. Those should stay as borders. + +### Shadow as Border (Light Mode) + +The shadow is comprised of three layers. The first acts as a 1px border ring, the second adds subtle lift, and the third provides ambient depth: + +```css +:root { + --shadow-border: + 0px 0px 0px 1px rgba(0, 0, 0, 0.06), + 0px 1px 2px -1px rgba(0, 0, 0, 0.06), + 0px 2px 4px 0px rgba(0, 0, 0, 0.04); + --shadow-border-hover: + 0px 0px 0px 1px rgba(0, 0, 0, 0.08), + 0px 1px 2px -1px rgba(0, 0, 0, 0.08), + 0px 2px 4px 0px rgba(0, 0, 0, 0.06); +} +``` + +### Shadow as Border (Dark Mode) + +In dark mode, simplify to a single white ring — layered depth shadows aren't visible on dark backgrounds: + +```css +/* Dark mode — adapt to whatever setup the project uses + (prefers-color-scheme, class, data attribute, etc.) */ +--shadow-border: 0 0 0 1px rgba(255, 255, 255, 0.08); +--shadow-border-hover: 0 0 0 1px rgba(255, 255, 255, 0.13); +``` + +### Usage with Hover Transition + +Apply the variable and add `transition-[box-shadow]` for a smooth hover: + +```css +.card { + box-shadow: var(--shadow-border); + transition-property: box-shadow; + transition-duration: 150ms; + transition-timing-function: ease-out; +} + +.card:hover { + box-shadow: var(--shadow-border-hover); +} +``` + +### When to Use Shadows vs. Borders + +| Use shadows | Use borders | +| --- | --- | +| Cards, containers with depth | Dividers between list items | +| Buttons with bordered styles | Table cell boundaries | +| Elevated elements (dropdowns, modals) | Form input outlines (for accessibility) | +| Elements on varied backgrounds | Hairline separators in dense UI | +| Hover/focus states for lift effect | | + +## Image Outlines + +Add a subtle `1px` outline with low opacity to images. This creates consistent depth, especially in design systems where other elements use borders or shadows. + +### Color + +- **Light mode**: pure black — `rgba(0, 0, 0, 0.1)`. +- **Dark mode**: pure white — `rgba(255, 255, 255, 0.1)`. +- Tinted neutrals (slate-900, zinc-900, `#0a0a0a`, `#f5f5f7`) and accent/ink colors pick up the surrounding surface color and read as dirt on the image edge; the outline is a neutral separator, not a themed element. + +### Light Mode + +```css +img { + outline: 1px solid rgba(0, 0, 0, 0.1); + outline-offset: -1px; /* inset so it doesn't add to layout */ +} +``` + +### Dark Mode + +```css +img { + outline: 1px solid rgba(255, 255, 255, 0.1); + outline-offset: -1px; +} +``` + +### Tailwind with Dark Mode + +```tsx +{alt} +``` + +Use `outline-black/10` and `outline-white/10` specifically — not `outline-slate-*`, `outline-zinc-*`, `outline-neutral-*`, or any tinted scale. + +**Why outline instead of border?** `outline` doesn't affect layout (no added width/height), and `outline-offset: -1px` keeps it inset so images stay their intended size. + +## Minimum Hit Area + +Interactive elements should have a minimum hit area of 44×44px (WCAG) or at least 40×40px. If the visible element is smaller (e.g., a 20×20 checkbox), extend the hit area with a pseudo-element. + +### CSS Example + +```css +/* Small checkbox with expanded hit area */ +.checkbox { + position: relative; + width: 20px; + height: 20px; +} + +.checkbox::after { + content: ""; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 40px; + height: 40px; +} +``` + +### Tailwind Example + +```tsx + +``` + +### Collision Rule + +If the extended hit area overlaps another interactive element, shrink the pseudo-element — but make it as large as possible without colliding. Two interactive elements should never have overlapping hit areas. diff --git a/.agents/skills/make-interfaces-feel-better/typography.md b/.agents/skills/make-interfaces-feel-better/typography.md new file mode 100644 index 00000000000..6ca7ac7e6ed --- /dev/null +++ b/.agents/skills/make-interfaces-feel-better/typography.md @@ -0,0 +1,135 @@ +# Typography + +Typography rendering details that make interfaces feel better. + +## Text Wrapping + +### text-wrap: balance + +Distributes text evenly across lines, preventing orphaned words on headings and short text blocks. **Only works on blocks of 6 lines or fewer** (Chromium) or 10 lines or fewer (Firefox) — the balancing algorithm is computationally expensive, so browsers limit it to short text. + +```css +/* Good — even line lengths on short text */ +h1, h2, h3 { + text-wrap: balance; +} +``` + +```css +/* Bad — default wrapping leaves orphans */ +h1 { + /* no text-wrap rule → "Read our + blog" instead of balanced lines */ +} +``` + +```css +/* Bad — balance on long paragraphs (silently ignored, wastes intent) */ +.article-body p { + text-wrap: balance; +} +``` + +**Tailwind:** `text-balance` + +### text-wrap: pretty + +Prevents orphaned words (a single word dangling on the last line) by adjusting line breaks throughout the paragraph. Unlike `balance`, it doesn't try to equalize line lengths — it just ensures the last line isn't embarrassingly short. Works on text of any length with no line-count limit. + +This should be your **default for short-to-medium text** — paragraphs, descriptions, captions, list items, card text. For very long text (10+ lines), skip both `pretty` and `balance` — the browser's default wrapping is fine and you avoid unnecessary layout cost. + +```css +/* Good — descriptions, captions, short paragraphs */ +p, li, figcaption, blockquote { + text-wrap: pretty; +} +``` + +```tsx +// Tailwind +

+ A short paragraph that won't leave an orphan on the last line. +

+``` + +**Tailwind:** `text-pretty` + +### When to Use Which + +| Scenario | Use | +| --- | --- | +| Headings, titles where even distribution matters | `text-wrap: balance` | +| Short-to-medium text — paragraphs, descriptions, captions, UI text | `text-wrap: pretty` | +| Long text (10+ lines), code blocks, pre-formatted text | Neither — leave default | + +## Font Smoothing (macOS) + +On macOS, text renders heavier than intended by default. Apply antialiased smoothing to the root layout so all text renders crisper and thinner. + +```css +/* CSS */ +html { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +``` + +```tsx +// Tailwind — apply to root layout + +``` + +### Good vs. Bad + +```css +/* Good — applied once at the root */ +html { + -webkit-font-smoothing: antialiased; +} + +/* Bad — applied per-element, inconsistent */ +.heading { + -webkit-font-smoothing: antialiased; +} +.body { + /* no smoothing → heavier than heading */ +} +``` + +**Note:** This only affects macOS rendering. Other platforms ignore these properties, so it's safe to apply universally. + +## Tabular Numbers + +When numbers update dynamically (counters, prices, timers, table columns), use tabular-nums to make all digits equal width. This prevents layout shift as values change. + +```css +/* CSS */ +.counter { + font-variant-numeric: tabular-nums; +} +``` + +```tsx +// Tailwind +{count} +``` + +### When to Use + +| Use tabular-nums | Don't use tabular-nums | +| --- | --- | +| Counters and timers | Static display numbers | +| Prices that update | Decorative large numbers | +| Table columns with numbers | Phone numbers, zip codes | +| Animated number transitions | Version numbers (v2.1.0) | +| Scoreboards, dashboards | | + +### Caveat + +Some fonts (like Inter) change the visual appearance of numerals with this property — specifically, the digit `1` becomes wider and centered. This is expected behavior and usually desirable for alignment, but verify it looks right in your specific font. + +```css +/* With Inter font: + Default: 1234 → proportional, "1" is narrow + Tabular: 1234 → all digits equal width, "1" centered */ +``` diff --git a/.agents/skills/memory-load-check/SKILL.md b/.agents/skills/memory-load-check/SKILL.md index e104581be5b..38c0f40864c 100644 --- a/.agents/skills/memory-load-check/SKILL.md +++ b/.agents/skills/memory-load-check/SKILL.md @@ -5,39 +5,162 @@ description: Review PRs and diffs for unbounded memory loading, concurrency expl # Memory Load Check -Prove each changed path has explicit bounds on rows held, bytes held, concurrency (promises, queries, HTTP calls, storage operations, jobs), and pages/batches/retries/retained intermediates. A bound that rests on current production size or "probably small" data is a finding. +Use this skill when a PR or diff could load unbounded data into a Node/Bun process, especially in cron routes, background tasks, API routes, workflow execution, file parsing, cleanup jobs, migrations, import/export flows, and external API integrations. -## Sim helpers to prefer +## Review Goal -- `apps/sim/lib/cleanup/batch-delete.ts`: `chunkedBatchDelete` (bounded SELECT → side effect → DELETE loop), `batchDeleteByWorkspaceAndTimestamp`, `selectRowsByIdChunks` (chunks an id set under an overall cap). `chunkArray` (`@sim/utils/helpers`) only after the source itself is bounded. -- `apps/sim/lib/core/utils/stream-limits.ts`: `assertContentLengthWithinLimit`, `readResponseToBufferWithLimit`, `readResponseTextWithLimit`, `readStreamToBufferWithLimit`, `PayloadSizeLimitError`. -- `apps/sim/lib/billing/cleanup-dispatcher.ts`: keyset-page workspaces (`id > afterId ORDER BY id LIMIT N`), dispatch concrete chunks rather than one giant scope, prefer queue concurrency keys, run inline fallback chunks sequentially. -- File parsing (`lib/internal/file/parser.ts`, `lib/uploads/utils/fetch-external-url.server.ts`): cap download and parsed output separately, keep partial results when a later item exceeds the cap. -- Large workflow values: durable refs/manifests, materialized only behind an explicit byte budget. +Prove each changed path has explicit bounds for: +- rows held in memory +- bytes held in memory +- concurrent promises, DB queries, HTTP calls, storage operations, and jobs +- number of pages, batches, chunks, retries, and retained intermediate objects -## KB connector downloads +If any bound depends only on current production size or "probably small" data, treat it as a finding. -Apply the size pattern in `apps/sim/connectors/utils.ts` by risk, not by connector name: connectors that download user-controlled file bytes (storage services, any `download_url` such as Zoom transcripts) must use it; API/structured-data connectors and platform-capped native documents use pagination bounds instead. +## References -- Stream via `readBodyWithLimit(resp, CONNECTOR_MAX_FILE_BYTES)`, never raw `response.text()`/`arrayBuffer()`. -- Skip oversize at listing (`stubOrSkipBySize`) and again at fetch (`markSkipped`), since listing sizes can be missing or under-reported. Never drop or truncate silently: a skipped file stays visible as a failed row with `skippedReason`. -- Connectors that already budget the body (google-docs, google-sheets, notion) keep their approach; don't add a cap to every `response.json()`. -- Litmus: can a user make one fetch arbitrarily large with nothing upstream stopping it? Yes: use the pattern. Borderline, a self-hosted endpoint with no platform cap (Obsidian): bound it when its content is genuinely unbounded. +Read these when doing a deeper pass: +- Node.js streams/backpressure: https://nodejs.org/learn/modules/backpressuring-in-streams +- Node.js stream usage: https://nodejs.org/en/learn/modules/how-to-use-streams +- Keyset/cursor pagination over offset scans: https://blog.sequinstream.com/keyset-cursors-not-offsets-for-postgres-pagination/ +- Postgres pagination tradeoffs: https://www.citusdata.com/blog/2016/03/30/five-ways-to-paginate/ -## Review workflow +## Sim Helpers To Prefer -1. List every changed source: queries, storage lists/downloads, external pagination, file reads and responses, workflow logs/snapshots/payloads, queues, crons, background jobs. -2. Write down each source's maximum cardinality and bytes. Not enforced in code means unbounded. -3. Trace accumulation: arrays from `select`/`findMany`/`Promise.all`/`flatMap`, maps or sets over a platform-wide scope, `Buffer.concat`/`arrayBuffer`/`text`/`JSON.parse`, promise queues or job payloads built before dispatch. -4. Concurrency separately from memory: no `Promise.all(items.map(...))` over an unbounded set; align concurrency with the DB pool, provider limits and queue semantics. -5. SQL: every bulk query has `LIMIT`; large pagination is keyset, not deep `OFFSET`; `IN (...)` lists are chunked; rows selected before a delete have per-batch and per-run caps. -6. Bytes: check `Content-Length`, stream with cumulative accounting, cap both input and expanded output, reject or reference oversized values before serializing. -7. Failure: exceeding a cap stops before loading more; partial work survives where the contract expects it; retries don't duplicate huge state; cleanup jobs make progress across runs instead of widening one run. +- `apps/sim/lib/cleanup/batch-delete.ts` + - `chunkedBatchDelete`: bounded SELECT -> optional side effect -> DELETE loop. + - `batchDeleteByWorkspaceAndTimestamp`: common workspace/timestamp cleanup wrapper. + - `selectRowsByIdChunks`: chunks large ID sets and enforces an overall row cap. +- `chunkArray` from `@sim/utils/helpers`: use only after the input set itself is already bounded. +- `apps/sim/lib/core/utils/stream-limits.ts` + - `PayloadSizeLimitError` + - `assertKnownSizeWithinLimit` + - `assertContentLengthWithinLimit` + - `readStreamToBufferWithLimit` + - `readNodeStreamToBufferWithLimit` + - `readResponseToBufferWithLimit` + - `readResponseTextWithLimit` +- Cleanup dispatcher pattern in `apps/sim/lib/billing/cleanup-dispatcher.ts` + - page active workspaces with `WHERE id > afterId ORDER BY id LIMIT N` + - dispatch concrete chunks (`workspaceIds`, retention, label) instead of one giant scope + - prefer Trigger.dev queue/concurrency keys when available + - execute inline fallback chunks sequentially, not with unbounded `Promise.all` +- File parse pattern in `apps/sim/lib/internal/file/parser.ts` and `apps/sim/lib/uploads/utils/fetch-external-url.server.ts` + - cap downloads and parsed output separately + - preserve partial results when a later item exceeds the cap + - never read untrusted response bodies without a byte cap +- KB connector file downloads in `apps/sim/connectors/utils.ts` + - `CONNECTOR_MAX_FILE_BYTES`: shared per-file cap (aligned with the manual KB upload limit) + - `readBodyWithLimit`: stream a download body to a Buffer with a hard byte cap (null on overflow) + - `stubOrSkipBySize`: listing-time skip when the reported size exceeds the cap + - `markSkipped` / `sizeLimitSkipReason`: surface oversized files as failed (skipped) KB rows + - `ConnectorFileTooLargeError`: thrown mid-download when the listing under-reported size +- Large workflow value payloads + - prefer durable references/manifests over inlining large arrays or files + - materialize refs only behind an explicit byte budget -Red flags beyond those: fetching all pages before processing, checking size only after materializing, chunking only after loading everything, one queue job per row with no batching or concurrency key, unbounded per-row error/result accumulation. +## KB Connector File Size Handling -Fixes should come with a test proving the cap stops work early and that partial results or progress are preserved. +The connector size pattern in `apps/sim/connectors/utils.ts` (`CONNECTOR_MAX_FILE_BYTES` + `readBodyWithLimit` + `stubOrSkipBySize`/`markSkipped`) exists for one risk: a knowledge-base connector downloading **arbitrary, user-controlled file bytes** that the source does not hard-cap. Apply it by that risk, not by the connector's name. -## Findings format +Use the pattern when the connector downloads file content via a stream/`download_url` where the user controls the size: +- file-storage connectors: Dropbox, OneDrive, SharePoint, Google Drive, S3, GitHub, GitLab, Azure DevOps +- any connector that fetches a file via a download URL even if it is not a "storage" service (e.g. the Zoom transcript `.vtt`) -Lead with concrete findings ordered by risk (**P1 title** (`path`) + what scales with what, and the bounded alternative), then good signals, then residual risk. Say "good to go" only when every changed source has explicit row, byte and concurrency bounds, or boundedness is proven by a stable invariant. +For those, require all three: +- stream the body with `readBodyWithLimit(resp, CONNECTOR_MAX_FILE_BYTES)` — never raw `response.text()`/`response.arrayBuffer()` +- skip oversize at listing (`stubOrSkipBySize` with the reported size) and again at fetch time (overflow -> `markSkipped`), since the listing size can be missing or under-reported +- never drop/truncate silently — oversized files become content-less failed rows carrying `skippedReason`, so they stay visible in the KB UI instead of vanishing from the index + +Skip the pattern when the source already bounds the payload: +- pure API/structured-data connectors (Jira, Linear, Sentry, Slack, Zendesk, Gmail, ...) — paginated JSON/text; apply normal pagination + concurrency bounds instead of a per-file byte cap +- native-document connectors whose platform caps each document — a 100 MB cap can never fire there + +Some connectors also budget the response body (google-docs `MAX_DOCS_RESPONSE_BYTES`, google-sheets `MAX_CONTENT_BYTES`, a remaining-bytes budget in notion); Confluence attachments use the full file pattern. Follow the connector's existing approach rather than adding a cap to every `response.json()`. + +Litmus test: "Can a user make this one fetch arbitrarily large, with nothing upstream stopping it?" Yes -> use the pattern. No (platform hard-cap, or already paginated) -> a per-file byte cap adds noise, not safety. Borderline: a user-configured/self-hosted endpoint with no platform cap (e.g. Obsidian) — bound it only if the content is genuinely unbounded. + +## Review Workflow + +1. Identify every changed data source: + - database queries + - storage lists/downloads/uploads + - external API pagination + - file reads and HTTP responses + - workflow logs, snapshots, payloads, arrays, and manifests + - queues, cron routes, and background jobs +2. For each source, write down the maximum cardinality and maximum bytes. If the code does not enforce one, it is unbounded. +3. Trace whether data is processed incrementally or accumulated: + - arrays from `select`, `findMany`, `Promise.all`, `map`, `filter`, `flatMap` + - maps/sets keyed by all users, workspaces, executions, files, or rows + - `Buffer.concat`, `response.arrayBuffer()`, `response.text()`, `JSON.stringify`, `JSON.parse` + - queues of promises or job payloads built before dispatch +4. Check concurrency separately from memory: + - no `Promise.all(items.map(...))` unless `items` is already small and bounded + - use chunks, sequential loops, queue concurrency, or a concurrency limiter + - align concurrency with DB pool size, storage/API limits, and task queue semantics +5. Verify SQL shape: + - every bulk query has `LIMIT` + - large pagination uses cursor/keyset style (`id > afterId`, timestamps plus unique ID), not deep `OFFSET` + - `IN (...)` lists are chunked + - side-effect rows selected before delete have per-batch and per-run caps +6. Verify byte safety: + - check `Content-Length` when available + - stream with cumulative byte accounting + - cap both input bytes and expanded output bytes + - reject or reference oversized values before serializing large JSON responses +7. Confirm failure behavior: + - exceeding a cap should stop before loading more data + - partial successful work should be preserved when the API contract expects it + - retries should not duplicate huge in-memory state + - cleanup jobs should make progress over future runs instead of widening one run + +## Red Flags + +- loads all active workspaces, users, executions, logs, files, messages, or subscriptions before filtering +- builds a full `Map` or `Set` for a platform-wide scope +- uses `Promise.all` over rows from an unbounded query +- fetches all pages from an external API before processing +- reads an entire file, HTTP response, or stream without a max byte budget +- checks size only after `Buffer.concat`, `arrayBuffer`, `text`, `JSON.parse`, or parse expansion +- a KB connector silently drops or truncates an oversized file instead of recording it as a failed (skipped) row +- chunks only after loading the complete dataset +- paginates with unbounded/deep `OFFSET` on a mutable or large table +- creates one queue job per row without batching or a queue-level concurrency key +- accumulates per-row errors/results with no maximum +- adds a cache, singleton, or module-level collection without eviction or size limits + +## Preferred Fixes + +- Move filters into SQL/API requests and select only needed columns. +- Replace full-table loads with cursor/keyset pagination and a deterministic order. +- Process one page/batch at a time; do not keep previous pages unless needed. +- Add per-batch and per-run row caps so long backlogs drain across repeated jobs. +- Split large ID lists with `selectRowsByIdChunks` or `chunkArray` after bounding the source. +- Use `chunkedBatchDelete` for cleanup loops with row side effects. +- Use stream-limit helpers for file/HTTP/body reads. +- Store large workflow values as refs/manifests and materialize only within a caller budget. +- Replace unbounded `Promise.all` with sequential chunk loops, queue concurrency, or a small limiter. +- Include tests that prove caps stop work early and partial results or progress are preserved. + +## Findings Format + +Lead with concrete findings, ordered by risk: + +```markdown +## Findings + +- **P1 Unbounded workspace load in cleanup dispatch** (`path/to/file.ts`) + The new path calls `select().from(workspace)` without a limit, then builds maps for every row before dispatch. In production this scales with all active workspaces and can exhaust the app process. Page by `workspace.id` with a fixed limit and dispatch bounded chunks. + +## Good Signals + +- Uses `readResponseToBufferWithLimit` for external downloads. +- Inline fallback processes chunks sequentially. + +## Residual Risk + +- The row cap is explicit, but no test currently proves the loop stops at the cap. +``` + +Only say "good to go" when every changed source has explicit row, byte, and concurrency bounds or the boundedness is proven by a stable invariant. diff --git a/.agents/skills/migrate-application-operation/SKILL.md b/.agents/skills/migrate-application-operation/SKILL.md index b455c277d25..c057b86b35d 100644 --- a/.agents/skills/migrate-application-operation/SKILL.md +++ b/.agents/skills/migrate-application-operation/SKILL.md @@ -1,115 +1,362 @@ --- name: migrate-application-operation -description: Create or migrate a protected operation into one authorized application use case shared by internal API, v2, Copilot and tool surfaces. Use when adding a protected endpoint, tool command, or CRUD method, removing route- or tool-local authorization, or adding a surface to an existing operation. v1, uploads, streams, large bodies, bulk recursion and polymorphic tools are explicitly scoped special cases. +description: Create or migrate a protected Sim resource operation in the shared Principal and application-use-case architecture across internal APIs, public or versioned APIs, Copilot, and other trusted tool adapters. Use when adding a protected endpoint, tool command, or CRUD method; removing route- or tool-local authorization and business logic; consolidating resource reads or writes behind semantic operation policies; or adding another surface to an existing application operation while preserving contracts, identity, errors, rate limits, audit, analytics, and compatibility behavior. Treat v1, uploads, streams, large bodies, bulk recursion, and polymorphic tools as explicitly scoped special cases. --- # Create Or Migrate Application Operation -Migrate one bounded semantic operation at a time. Share authorization and business behavior without forcing surfaces to share authentication, input schemas or response shapes. The invariant and layer rules are in the root `CLAUDE.md` (Application Operation Boundary); this skill is how to apply them without changing behavior. +Create or migrate one bounded semantic operation at a time. Share authorization and business behavior without forcing internal APIs, public APIs, Copilot, and other tools to share authentication, input schemas, or response shapes. -Never infer authoritative identity, workspace, audience or scope from untrusted arguments. A helper that resolves a path is valid only when the protected lookup runs through an authorized application resolver; if a helper starts doing real data work, move it into a use case. +## Enforce the application boundary + +Apply this invariant: + +> Every real operation on persisted or protected data enters through an authorized application use case. + +This includes mutations, content and metadata reads, canonical resource lookup, and reference-to-resource resolution when the lookup is authorization-sensitive. + +Surface helpers may: + +- Normalize an already-authenticated surface context into a `Principal`. +- Translate aliases or wire arguments into application input. +- Select a code-defined operation and application use case. +- Call the application use case. +- Translate typed results and errors into the surface contract. + +Surface helpers must not: + +- Query databases or storage. +- Decide workspace or resource authorization. +- Implement business transactions. +- Record semantic audit or shared domain notifications. +- Infer authoritative identity, workspace, audience, or scope from untrusted arguments. +- Substitute billing attribution for identity. + +A helper that resolves a path is valid only when the actual protected lookup runs through an authorized application resolver. If a helper begins doing real data work, move that work into an application use case. ## Read the foundation first -Read completely: `packages/auth/src/principal.ts`; `apps/sim/lib/core/application/{operation,workspace-operation,workspace-authorization,authorized-workspace-use-case}.ts`; `apps/sim/lib/api/server/routes/{definition,internal-json-route,v2-json-route}.ts`; `apps/sim/lib/auth/internal-delegation.ts`; `apps/sim/lib/mothership/application/adapter.ts`; `apps/sim/lib/mothership/auth/application-delegation.ts`. +Read these files completely before editing: + +- `packages/auth/src/principal.ts` +- `apps/sim/lib/core/application/operation.ts` +- `apps/sim/lib/core/application/workspace-operation.ts` +- `apps/sim/lib/core/application/workspace-authorization.ts` +- `apps/sim/lib/core/application/authorized-workspace-use-case.ts` +- `apps/sim/lib/api/server/routes/definition.ts` +- `apps/sim/lib/api/server/routes/internal-json-route.ts` +- `apps/sim/lib/api/server/routes/v2-json-route.ts` +- `apps/sim/lib/auth/internal-delegation.ts` +- `apps/sim/lib/mothership/application/adapter.ts` +- `apps/sim/lib/mothership/auth/application-delegation.ts` + +Use the file domain only as a representative golden slice: -**Golden slice** (copy its shape, not invented field names): `apps/sim/lib/workspace-files/application/operations.ts` (registry), `apps/sim/lib/workspace-files/application/authorized-workspace-file-use-case.ts` (domain binding), `apps/sim/lib/workspace-files/application/rename-workspace-file.ts` (use case), `apps/sim/app/api/workspaces/[id]/files/[fileId]/route.ts` and `apps/sim/app/api/v2/files/[fileId]/` (surfaces), `apps/sim/lib/mothership/application/execute-file-use-case.ts` + `apps/sim/lib/mothership/auth/file-delegation.ts` (Copilot). +- `apps/sim/lib/workspace-files/application/operations.ts` +- `apps/sim/lib/workspace-files/application/authorized-workspace-file-use-case.ts` +- `apps/sim/lib/workspace-files/application/rename-workspace-file.ts` +- `apps/sim/lib/mothership/application/execute-file-use-case.ts` +- `apps/sim/lib/mothership/auth/file-delegation.ts` -Then read the target domain's registry, application code, repositories, contracts, adapters, aliases, resume paths and tests. If the shared foundation is absent, fail: never recreate it inside the domain. +Then read the target domain's operation registry, application code, repositories, contracts, adapters, aliases, resume paths, and focused tests. Fail immediately if the shared foundation is absent. Do not recreate it inside the domain. ## Bound the migration -Inventory every entry point before editing: internal routes, public/versioned routes, Copilot tools (aliases, resume paths, polymorphic branches), other tool servers, executors, jobs; plus current authentication, authorization, workspace assertions, concealment, manager call chains, audit/notification/analytics/billing effects, error mapping, rate-limit identity, rollout gates, quota and concurrency admission. +Inventory every entry point for the behavior before editing: + +- Internal HTTP routes and contracts. +- Public or versioned API routes and contracts. +- Copilot tools, aliases, resume paths, and polymorphic branches. +- Other tool servers, workflow executors, jobs, or service callers. +- Current authentication, authorization, workspace assertions, and concealment. +- Manager or orchestration call chains. +- Audit, notification, analytics, and billing side effects. +- Error/status/result behavior. +- Rate-limit identity, rollout gates, quota, and concurrency admission. + +Classify each as `migrate`, `defer`, or `non-goal`. Do not migrate adjacent operations merely because they share a module. Do not modify v1 unless the request explicitly includes it. + +Preserve behavior unless the task explicitly changes it. Stop and report a decision when surfaces currently disagree on security or compatibility behavior; do not silently choose one. + +## Freeze observable behavior before editing + +Treat the legacy route or tool as an ordered program, not merely a bag of business logic. Before moving code, write a compact baseline for every in-scope entry point. Pin behavior no existing test covers with a characterization test only where it passes the `test-audit` gate; otherwise record it in the baseline and verify it by hand after the move. + +Capture all of these when they apply: + +- Accepted inputs, including trimming, blank omission, duplicate query keys, aliases, defaults, and bounds. +- Authentication and authorization order, minimum roles, resource membership, concealment, and exact error/status mapping. +- Exact success bodies, optional fields, status codes, redirects, cookies, headers, and binary or stream behavior. +- Mutation ordering, transaction boundaries, idempotency, no-ops, and observable state after each possible partial failure. +- Audit, notification, analytics, and billing timing plus exact semantic dimensions and attribution. +- Browser or protocol state ownership, concurrency isolation, expiry, callback ordering, and cleanup behavior. +- Every value newly crossing into HTML, JavaScript, SQL, URLs, logs, provider payloads, or another encoding context. + +Compare the old statement order with the proposed application lifecycle explicitly: + +```text +legacy parse/normalize + -> legacy authorization checks + -> branch-specific canonical lookup + -> mutation(s) + -> per-step side effects + -> response or redirect catch +``` + +Moving those steps under a wrapper may change behavior even when each individual call is reused. In particular: + +- `projectAudit` and `afterSuccess` run only after `execute` returns. They cannot describe earlier committed mutations when a later step throws. Make the compound mutation atomic or define explicit partial-result/failure projection semantics before migrating it. +- Operation metadata is executable policy. Adding a resource role to a workspace-only legacy read is an authorization change, not an architectural cleanup. +- A shared error policy does not automatically preserve route-local concealment, subclass ordering, browser redirects, or branch-specific messages. +- A shared contract does not automatically preserve manual `URLSearchParams` normalization or exact legacy response unions. +- A shared use case may own domain behavior while separate surface presenters still preserve different wire shapes. +- Per-flow identity is insufficient when another part of the flow remains in browser-global state such as one cookie. +- Passing a newly supported parameter through old rendering code creates a new security boundary even when the renderer itself is unchanged. + +Fail fast if the baseline cannot be established from code, tests, or an explicit product decision. Do not infer that behavior is unimportant because it was previously implicit. + +## Keep the layers distinct + +Use these responsibilities: + +1. Authentication adapter: verify the surface credential or trusted execution context and construct a `Principal`. +2. Route or tool adapter: select rate policy, parse its contract, translate input, call the application use case, and render its own result. +3. Application use case: load canonical context, compare asserted scope, authorize the semantic operation, execute business behavior, project semantic audit, and trigger shared domain effects. +4. Manager or repository: perform database and storage reads or writes using canonical identifiers and scope. Never accept credentials or principals. +5. Presenter: return only the surface success body or typed binary descriptor. Never construct auth, rate, or error behavior. + +For ordinary public JSON routes, preserve this order: + +```text +IP abuse limit + -> authenticate + -> build Principal + -> operation rate limit + -> parse surface contract + -> application use case + -> canonical load + -> asserted-scope concealment + -> current authorization + -> manager read or mutation + -> semantic audit + -> shared domain effects + -> surface presenter +``` + +Internal routes may omit the IP bucket or operation limit only through an explicit policy with a reason. Usage billing, storage quota, cost admission, and concurrency are separate from request-rate limiting. + +Never query API keys or sessions from the application layer. Never add fallback identity or authorization behavior. Propagate infrastructure failures instead of turning them into not-found or forbidden results. + +## Define the semantic operation once + +Add one stable entry to the target domain's operation registry: + +```ts +rename: defineWorkspaceOperation({ + id: 'widgets.rename', + minimumRole: 'write', + workspaceApiKey: 'allow', + capability: 'widgets.use', + principalKinds: ['session', 'personal_api_key', 'workspace_api_key', 'delegated'], + delegatedServices: ['copilot'], +}) +``` + +Do not create internal-, public-, or Copilot-specific versions of the same semantic operation. If two callers have materially different business or transactional semantics, define separate semantic operations and use cases and explain the distinction. + +Choose principal kinds from actual behavior. Do not accept every principal merely because the use case is shared. Workspace API keys have a write ceiling and cannot satisfy admin operations. The operation definition must fail fast when its role, workspace-key policy, and principal kinds disagree. -Classify each as `migrate`, `defer` or `non-goal`. Don't migrate adjacent operations because they share a module; don't touch v1 unless asked. Preserve behavior unless the task changes it; **when surfaces disagree on security or compatibility, stop and report** rather than silently picking one. +`capability` is required: a static, operation-declarable capability (not parameterized, not principal-wide), or `'none'` with a `// permission-group-exempt: ` comment directly above it. If `principalKinds` includes `oauth_access_token`, `oauthScope` (`api:read` | `api:write` | `search:read`) is required. `defineWorkspaceOperation` throws at definition time on any violation. See `add-permission-group-item`. -## Freeze observable behavior +Route declarations, tool adapters, and use cases must use the same literal operation. Runtime operation selection is permitted only from a trusted, code-defined registry. Never accept an operation ID or permission tag from an HTTP body, model argument, or other untrusted input. -Treat the legacy route or tool as an ordered program, not a bag of business logic. Write a compact baseline per in-scope entry point (pin uncovered behavior with a characterization test only where it passes `test-audit`; otherwise verify by hand after the move): +### Unified selector execution is one operation -- Accepted inputs: trimming, blank omission, duplicate query keys, aliases, defaults, bounds. -- Auth order, minimum roles, membership, concealment, exact error/status mapping. -- Exact success bodies, optional fields, statuses, redirects, cookies, headers, binary/stream behavior. -- Mutation order, transaction boundaries, idempotency, no-ops, state after each partial failure. -- Audit/notification/analytics/billing timing, dimensions and attribution. -- Browser or protocol state ownership, concurrency isolation, expiry, callback ordering, cleanup. -- Every value newly crossing into HTML, JS, SQL, URLs, logs, provider payloads or another encoding. +Dynamic selector dispatch is the deliberate instance of trusted runtime selection. Define and +authorize `selectors.execute` once: it means "enumerate options while configuring a workflow or +workspace resource." The browser supplies only a selector key from the exhaustive browser-safe +manifest, scope, allowlisted context, and list/detail request. After canonical scope authorization, +the application use case selects the matching attachment from the exhaustive server-only registry. -Then compare the legacy statement order (parse → authorize → branch-specific lookup → mutations → per-step effects → response/redirect catch) with the wrapper's lifecycle. Moving steps under the wrapper changes behavior even when each call is reused: +Provider and internal attachments are trusted implementation adapters under that semantic operation, +not separate application operations. Do not create one operation per selector, provider, or listing +endpoint. Attachments may choose only code-defined credential/service binding, destination policy, +provider primitive, and projection behavior; they must not accept a module, provider, service, +operation kind, origin, or permission tag from the request. The `selectors.execute` use case owns +reference resolution, credential authorization, provider invocation, sanitization, and safe result +projection end to end. -- `projectAudit` and `afterSuccess` run only after `execute` returns, so they cannot describe earlier committed mutations when a later step throws. Make the compound mutation atomic, or define partial-result semantics first. -- Operation metadata is executable policy: adding a resource role to a workspace-only legacy read is an authorization change, not a cleanup. -- A shared error policy doesn't preserve route-local concealment, subclass ordering, redirects or branch-specific messages; a shared contract doesn't preserve manual `URLSearchParams` normalization or legacy response unions. -- Per-flow identity is insufficient when part of the flow lives in browser-global state (one cookie). -- Passing a newly supported parameter through old rendering code creates a new security boundary even if the renderer is unchanged. +## Implement the application use case -If the baseline can't be established from code, tests or an explicit product decision, fail. Implicit behavior is not unimportant behavior. +Use `defineAuthorizedWorkspaceUseCase` directly or a thin domain binding that supplies domain-specific authorization options: -## Define the operation once +```ts +export const renameWidget = defineAuthorizedWorkspaceUseCase({ + operation: widgetOperations.rename, + resolveContext: ({ input }: { input: RenameWidgetInput }) => + loadCanonicalWidgetContext(input.id, input.assertedWorkspaceId), + authorizationOptions: { delegation: widgetDelegationPolicy }, + execute: async ({ input, context }) => renameWidgetRecord({ + workspaceId: context.workspaceId, + widgetId: context.resourceId, + name: input.name, + }), + projectAudit: ({ result }) => ({ + action: AuditAction.WIDGET_UPDATED, + resourceType: AuditResourceType.WIDGET, + resourceId: result.id, + resourceName: result.name, + }), + afterSuccess: ({ context }) => notifyWidgetsChanged(context.workspaceId), +}) +``` -One registry entry via the builder for the operation's authorization scope: `defineWorkspaceOperation`, `defineOrganizationOperation`, or the domain's own `define*Operation` (principal-scoped registries build on `defineOperation`). No internal-, public- or Copilot-specific variants of one semantic operation; if two callers have materially different business or transactional semantics, define two operations and explain why. +Adapt the example to the domain's real authorization options; do not copy invented field names. -- Choose principal kinds from actual behavior, not "the use case is shared so accept everything". Capability and OAuth scope rules: see `add-permission-group-item`. -- Routes, tool adapters and use cases use the same literal operation object. Runtime selection only from a trusted code-defined registry; never take an operation id or permission tag from a body, model argument or other untrusted input. `selectors.execute` is the deliberate instance: one operation, with selector attachments as trusted adapters under it (see `add-selector`). +The wrapper must own this lifecycle: -## Implement the use case +1. Reject disallowed principal kinds before protected loading. +2. Load canonical context and conceal asserted-scope mismatches as required. +3. Authorize the operation using current policy state. +4. Execute the manager or repository primitive. +5. Project audit from authoritative results. +6. Await shared post-success effects. -Use the matching authorized builder (`defineAuthorizedWorkspaceUseCase`, `defineAuthorizedOrganizationUseCase`) or a thin domain binding (like `authorized-workspace-file-use-case.ts`). The wrapper owns the lifecycle: reject disallowed principal kinds before loading, load canonical context and conceal asserted-scope mismatches, authorize against current policy, execute, project audit from authoritative results, await shared effects. +Do not call shared authorization, principal audit attribution, or `recordAudit` manually from an ordinary migrated use-case body. Use `projectAudit` only when the operation has semantic audit. Return no audit entries for authoritative no-ops. Keep product analytics such as `captureServerEvent` surface-specific through the adapter's success hook. -- No manual authorization, audit attribution or `recordAudit` in the body. Return no audit entries for an authoritative no-op. Product analytics (`captureServerEvent`) stay surface-specific in the adapter's success hook. -- Inspect legacy orchestration before reusing it: if it already authorizes, audits, notifies or captures analytics, call a lower-level primitive or remove the duplicate for migrated callers. -- Never query API keys or sessions in the application layer, add fallback identity, or turn infrastructure failures into not-found or forbidden. -- Surface facts (a cursor's route) come in as input; return domain values and let each presenter project its wire shape. +Inspect legacy orchestration before reusing it. If it already authorizes, audits, notifies, or captures analytics, call a lower-level primitive or remove duplicate responsibility for migrated callers. -## Surfaces +Application code stays surface-neutral (`check:boundaries`): never `next/server` or `app/api/**`, and never a runtime import of a route contract object, presenter, or Copilot handler (contract types, schemas, and constants are fine); a surface fact, such as a cursor's route, comes in as input. Return domain values and let each surface presenter project its own wire result. -**Internal routes** (`defineInternalJsonRoute`): `internalSessionAuth` for session-only; `createInternalSessionOrExecutorAuth` only when signed executor delegation is genuinely supported (the operation then allows `delegated` from `executor`). Never turn an actorless legacy JWT into a fake session, owner or user. Omitting the IP or operation rate limit needs an explicit policy with a reason; billing, quota, cost admission and concurrency are separate from request rate. If routes repeat auth/parsing/rendering, improve the shared builder rather than adding a domain wrapper. +## Adapt internal APIs -**Public routes** (`defineV2JsonRoute`, see `v2-api-conventions`): rate-limit by credential subject, never a billed owner. Keep contracts separate when wire shapes differ, share primitive schemas and validators, import the same schema when the shape is genuinely identical, and never cast one surface's response into another's. +Use `defineInternalJsonRoute` for ordinary JSON routes. Explicitly declare the contract, authentication policy, semantic operation, rate policy, error policy, input mapping, use case, and presenter when the wire result differs. -**Copilot**: call the exact use case other surfaces use, through one domain adapter built with `createCopilotApplicationAdapter` (it requires the trusted execution marker, builds the delegated principal once, and checks registry membership). +Use `internalSessionAuth` for session-only routes. Use `createInternalSessionOrExecutorAuth` only when the endpoint genuinely supports signed executor delegation; the semantic operation must then allow `delegated` principals from the `executor` service. Never turn an actorless legacy JWT into a fake session, owner, or user principal. -- Never build delegation from model-provided workspace ids, user ids, operation ids, resource scope or permission tags: model arguments are requested targets only. -- Tool handlers own aliases, resumable legacy names, abort checks and presentation; never managers, authorization or protected business logic. A Copilot-only compound action that is real domain behavior becomes a surface-neutral operation. -- Resolve references only through an authorized resolver under the intended operation (a code-defined operation object, never a string). Reuse a principal only within one request; reauthenticate across resumed tool calls, executor callbacks, background work, upload legs and finalization, and long-running provider operations. Prefer one use case (`renameWidgetByReference`) when resolve and execute are one business operation or need a consistent snapshot. -- An explicitly best-effort command coordinating several operations needs hard input and expansion caps, cancellation checkpoints, partial-result semantics, audit behavior and rate/quota policy. Keep it exceptional. -- Map typed errors to safe tool results; unknown errors become generic retryable messages with full causes in server logs. Never return raw database or storage errors to the model. +The internal adapter owns authentication and internal response envelopes. It must not implement workspace authorization. Preserve internal-only analytics through `onSuccess` after application success. -**Other tool runtimes**: one shared principal adapter per runtime, the same use case, the tool protocol's own retry/cancellation semantics, and server-authored workspace and subject scope. An internal caller is not trusted to bypass authorization: it supplies an explicit principal or a deliberately designed service/delegation principal. External tool endpoints authenticate once, at the adapter. +Keep the route module declarative. If several internal routes repeat authentication, parsing, error rendering, or response construction, improve the shared internal route builder instead of adding a domain-specific route wrapper. -## Identity and attribution +## Adapt public or versioned APIs -Workspace keys authorize as the workspace, independent of creator membership; delegated principals re-check subject, workspace, audience, expiry, execution and resource scope. Keep structured `PrincipalActor` metadata in audit. If a required legacy user column can't represent the real actor, label the compatibility attribution explicitly; never pretend it is the acting human. If the principal model can't express a caller's authority, stop and extend it deliberately. +Use the appropriate public/versioned route builder, such as `defineV2JsonRoute`, with API-key authentication, explicit semantic operation and rate policy, external error projection, input mapping, application use case, and an external presenter. -## Special operations +Authentication and HTTP formatting may differ from internal APIs; authorization and business behavior must not. Rate-limit using the credential or principal subject, never a billed owner. Resolve billing attribution only for billing, quota, or legacy required-user fields. -Don't force these through an ordinary JSON migration: +Keep surface contracts separate when their wire shapes differ. Reuse shared primitive schemas and domain validators for invariants such as IDs, names, bounds, and formats. Do not maintain duplicate internal and external schemas merely because the routes are separate; import the same schema when the wire shape is genuinely identical. Never cast one surface response into another. -- Uploads/multipart: bind immutable credential identity, reauthorize control legs and finalization, make durable completion idempotent. -- Large bodies: authenticate and run cheap admission before bounded buffering. -- Binary/streaming: binary/stream builders and typed descriptors. -- Bulk/recursive: deduplicate and cap inputs and expansion, load everything canonically, define atomic vs best-effort. -- Polymorphic tools: select the operation only after trusted target-kind resolution. -- Multi-resource transactions: canonical scope predicates; audit from authoritative affected rows. +Keep v1 middleware and routes unchanged unless explicitly included. -Stop and report a missing design rather than weakening identity, authorization, limits or errors. +## Adapt Copilot -## Tests +Copilot is a surface adapter, not a separate application layer. If an HTTP or other surface already uses an application use case, Copilot must call that exact use case rather than reimplementing protected business behavior under `lib/mothership`. -Own each risk at exactly one boundary: +Create one domain-level Copilot application adapter with `createCopilotApplicationAdapter` instead of constructing delegated principals in every tool: -- **Use-case tests**: authorization, principal-kind rejection before loading, workspace assertion mismatch, delegated scope, not found, conflict, no-op, audit from authoritative results, and infrastructure failures propagating as 5xx (never not-found/forbidden). -- **One `*.integration.ts`**: canonical active lookup, workspace-predicated writes, archived resources, affected rows, DB error propagation. -- **Surface tests** only for surface-specific risk (a v2 envelope or rate header, a Copilot forged-scope rejection, a pinned legacy redirect/cookie). Don't restate the registry or the builders' auth-before-parse per surface. +```ts +executeCopilotWidgetUseCase(context, renameWidget, input, { resourceId }) +``` -When the change introduces them: inject a failure after each independently committing step and assert persisted state and effects; overlap stateful browser/provider flows to prove each callback consumes only its own state; feed hostile values through every newly connected input that reaches HTML, inline JS, URLs, logs or provider requests. +That adapter must: -Don't claim a check passed unless it completed. +- Require a trusted server-authored Copilot execution marker. +- Require the authenticated subject, canonical workspace, tool-call or execution identity, and required audience or lifecycle scope. +- Construct the shared delegated `Principal` in one place. +- Optionally bind the canonical resource scope after trusted resolution. +- Verify that the use case exposes a registered code-defined operation. +- Use the domain's exact immutable operation registry so operation-object membership and identity are checked centrally. +- Call the application use case directly. -## Parallel work +Never construct authoritative delegation from model-provided workspace IDs, user IDs, operation IDs, resource scope, or permission tags. Model arguments are requested targets only and must be checked against trusted execution context and canonical data. -Assign non-overlapping route modules and caller sets (two methods in one route file are one unit). Operation registries, contract families, route policies and shared adapters are merge hotspots. Shared core foundations are owned by one task; domain migrations consume them without modifying them. +Tool handlers own argument aliases, resumable legacy names, abort checks, tool-call reporting, and tool-specific presentation. They must not query managers directly for protected operations, manually authorize, or implement protected business behavior. If a Copilot-only compound action expresses real domain behavior, define a surface-neutral domain operation and application use case for it. + +A Copilot reference helper may translate a path to a resource only by calling an authorized application resolver under the intended semantic operation. Passing a code-defined operation object is acceptable; passing a model-provided operation string is not. An immediate same-request resolver followed by the operation may reuse one trusted principal, though the application operation still performs its own canonical authorization. Fresh authentication and authorization are required across lifecycle boundaries such as resumed tool calls, executor callbacks, queued or background work, upload control legs and finalization, durable completion, and long-running provider operations. When resolution and execution form one business operation, need a consistent snapshot, or appear repeatedly together, prefer a top-level application use case such as `renameWidgetByReference`. + +Surface adapters must not compose protected mutations. An atomic compound action requires one top-level semantic domain operation and application use case that owns the transaction and authoritative result. An explicitly best-effort application command may coordinate multiple operations only when it defines hard input and expansion caps, cancellation checkpoints, partial-result semantics, audit behavior, and rate/quota policy. Keep composition exceptional and explicit; ordinary tools should use the shared execution adapter. + +Map expected typed errors to safe tool results. Unknown errors must become generic system/retryable messages while retaining full causes in server logs. Never return raw database or storage errors to the model. + +## Adapt other internal or external tools + +Treat every tool runtime as a surface adapter: + +- Normalize its already-authenticated execution context into an existing `Principal` through one shared adapter for that runtime or domain. +- Call the same application use case used by HTTP and Copilot surfaces. +- Preserve the tool protocol's input, output, retry, and cancellation semantics. +- Keep authoritative workspace and subject scope server-authored. + +An internal caller is not automatically trusted to bypass authorization. It must supply an explicit principal or use a deliberately designed service/delegation principal. If the current principal model cannot express its authority, stop and extend the identity model intentionally; do not fall back to an owner, uploader, creator, or arbitrary user ID. + +External tool endpoints authenticate at their adapter exactly like public APIs. Do not authenticate again inside the application use case. + +## Preserve identity and attribution + +- Session and personal-key principals authorize through current human workspace permission. +- Personal API keys also respect the workspace's personal-key policy. +- Workspace keys authorize as the workspace under explicit operation policy and the write ceiling, independent of creator membership. +- Delegated principals re-check the current subject and their workspace, audience, expiry, execution, and resource scope. +- Billing owners are attribution for billing or legacy required columns only, never authorization, rate identity, delegated identity, audit actor, or human analytics identity. +- Preserve structured `PrincipalActor` metadata in semantic audit. + +If a required legacy user column cannot represent the real actor, label the compatibility attribution explicitly. Never pretend it is the acting human. + +## Handle special operations explicitly + +Do not force these through an ordinary JSON migration: + +- Upload or multipart lifecycles: bind immutable credential identity, reauthorize control legs and finalization, and make durable completion idempotent. +- Large bodies: authenticate and perform cheap admission before bounded buffering. +- Binary or streaming responses: use binary/stream builders and typed descriptors. +- Bulk or recursive operations: deduplicate and cap inputs and expansion, load all resources canonically, and define atomic versus best-effort behavior. +- Polymorphic tools: select the semantic operation only after trusted target-kind resolution; do not route unrelated branches through one domain registry. +- Multi-resource transactions: keep canonical scope predicates and derive audit from authoritative affected rows. + +Stop and report a missing design rather than weakening identity, authorization, limits, or errors. + +## Test each risk at one boundary + +Run the `test-audit` authoring gate before writing any test. Prefer one E2E/integration run over the real boundary; where a use-case unit test is justified, list its failure modes before writing code (CLAUDE.md → Testing). Own each risk at exactly one boundary: + +- Application use-case tests own authorization, principal-kind rejection before canonical loading, workspace assertion mismatch, delegated scope, not found, conflict, no-op, audit derived from authoritative results, and infrastructure failures (storage, rate-limit, provider, or database errors raised by delegated services) propagating as 5xx-mapped errors — never converted to not-found or forbidden. +- One `*.integration.ts` owns repository semantics: canonical active lookup, workspace-predicated writes, archived resources, authoritative affected rows, and database error propagation. +- Add a surface test only for a surface-specific risk (for example, a v2 envelope or rate header, a Copilot forged-scope rejection, or a legacy redirect/cookie behavior the characterization baseline pinned). Do not restate the operation registry or the shared builders' auth-before-parse behavior per surface. + +Risks that usually earn a test when the change introduces them: + +- Failure sequencing: inject a failure after each independently committing step and assert persisted state plus audit, analytics, and notification effects. +- Concurrency: overlap stateful browser or provider flows and prove each callback consumes only its own state and return destination. +- Rendering boundaries: exercise hostile values for every newly connected input that reaches HTML, inline JavaScript, URLs, logs, or provider requests. + +Run at minimum: + +```bash +bun run --cwd apps/sim test +bunx biome check +bunx turbo run type-check --filter=@sim/app --filter=@sim/auth +bun run check:audits +git diff --check +``` + +Do not claim a check passed unless it completed successfully. + +## Work safely in parallel + +- Assign non-overlapping route modules and caller sets. Two methods in one route file are one ownership unit. +- Treat operation registries, contract families, route policies, and shared surface adapters as merge hotspots. +- Keep shared core foundations owned by one task; ordinary domain migrations should consume them without modifying them. +- Preserve unrelated working-tree changes. Never stage proposal docs, lockfile drift, or another agent's edits. +- Do not commit, push, or open a PR unless requested. ## Hand off -Report: the operation (role, workspace-key policy, principal kinds); migrated, deferred and non-goal entry points; behavior preserved per surface; identity construction and scope source per surface; files changed and merge hotspots; tests and checks with results; remaining risks or invariants that couldn't be implemented. +Report: + +1. Semantic operation, role, workspace-key policy, and principal kinds. +2. Migrated, deferred, and non-goal entry points. +3. Behavior preserved per internal, public, Copilot, and other tool surface. +4. Identity construction and authoritative scope source for each surface. +5. Files changed and shared merge hotspots. +6. Tests and checks run with results. +7. Remaining risks or blockers. Fail fast when an invariant could not be implemented. diff --git a/.agents/skills/react-query-best-practices/SKILL.md b/.agents/skills/react-query-best-practices/SKILL.md index 839dc20a616..81e86004947 100644 --- a/.agents/skills/react-query-best-practices/SKILL.md +++ b/.agents/skills/react-query-best-practices/SKILL.md @@ -12,12 +12,42 @@ Arguments: User arguments: $ARGUMENTS -Review the scope against `.claude/rules/sim-queries.md` (keys, hooks, mutations, optimistic updates, server prefetching) and these judgment calls no check catches: +## Context -- Warm data on hover/focus with `prefetchQueryOnIntent` (`hooks/queries/utils/prefetch-query-on-intent.ts`); never temporarily enable a mounted hidden observer, which can stay active after focus restoration and refetch data for closed UI. -- When gating a query by view or modal state, move every consumer to the active query too: imperative refresh and pagination, loading and error feedback, and data-derived controls must never read a disabled query or a previous key's placeholder data. -- Compose caller `enabled` with required-param guards (`Boolean(id) && (options?.enabled ?? true)`); spreading options after the guard lets `{ enabled: true }` re-enable an invalid request. -- A disabled query can still report `isPending: true`. Aggregate loading only over enabled queries, or an optional query holds the whole surface in a permanent loading state. -- Authorization and policy queries fail closed: pending or errored data must not get the same fallback as a loaded unrestricted policy; disable guarded actions until the query succeeds. +This codebase uses React Query (TanStack Query) as the single source of truth for all server state. All query hooks live in `hooks/queries/`. Zustand is used only for client-only UI state. Server data must never be duplicated into useState or Zustand outside of mutation callbacks that coordinate cross-store state. -If fix=true, apply the fixes; if fix=false, propose them without applying. +## References + +Read these before analyzing: +1. https://tkdodo.eu/blog/practical-react-query — foundational defaults, custom hooks, avoiding local state copies +2. https://tkdodo.eu/blog/effective-react-query-keys — key factory pattern, hierarchical keys, fuzzy invalidation +3. https://tkdodo.eu/blog/react-query-as-a-state-manager — React Query IS your server state manager + +## Rules to enforce + +### Query keys and hooks +Enforce `.claude/rules/sim-queries.md` (key factory with `all` + plural prefixes, `signal` forwarding, named `staleTime` constants reused by prefetches, `keepPreviousData` only on variable keys, `requestJson` boundary). Additionally: +- Key factories live next to their hooks — except a factory, standalone fetcher/mapper, or `staleTime` constant that a server module (a `prefetch.ts`, route, block, trigger) imports, which must live in a non-`'use client'` module under `hooks/queries/utils/` per `.claude/rules/sim-queries.md` (a `'use client'` export called from the server crashes SSR) +- Use `enabled` to prevent queries from running without required params +- Warm data for hover/focus intent with `prefetchQueryOnIntent(queryClient, sharedQueryOptions)` (`hooks/queries/utils/prefetch-query-on-intent.ts`, which cleans up a speculative failure per `sim-react-performance.md`); never temporarily enable a mounted hidden observer, which can remain active after focus restoration and refetch data for closed UI +- When gating a query by view or modal state, move every consumer to the active query too: imperative refresh/pagination, loading and error feedback, and data-derived controls must never read a disabled query or placeholder data from a previous key +- Compose caller-controlled `enabled` options with required-param guards (`Boolean(id) && (options?.enabled ?? true)`). Never spread options after an internal guard, because `{ enabled: true }` can silently re-enable an invalid request. +- A disabled query can still report `isPending: true`. Aggregate loading state only for queries that are applicable/enabled, or an optional query can hold the whole surface in a permanent loading state. +- Deferred authorization or policy queries must fail closed. Do not give pending/error data the same fallback as a successfully loaded unrestricted policy; disable guarded actions until the policy query succeeds. +- Server prefetches must call the authorized use case, apply the route presenter/response schema, and reuse the client's exact key, mapper, and stale time. Keep all fallible auth/read/parse work inside `queryFn` so an optional warm cannot fail the page, and never bypass a route that redacts fields. + +### Mutations +Enforce `.claude/rules/sim-queries.md` "Mutation Hook" (targeted invalidation, `onMutate`/`onError` rollback, mutation objects out of `useCallback` deps). Additionally: +- Plain mutations invalidate in `onSuccess`; optimistic mutations reconcile in `onSettled` (fires on success and error) with rollback in `onError` — see `.claude/rules/sim-queries.md` "Mutation Hook" / "Optimistic Updates" + +### Server state ownership +- Never copy query data into useState. Use query data directly in components. +- Never copy query data into Zustand stores (exception: mutation callbacks that coordinate cross-store state like temp ID replacement) +- The query cache is not a local state manager — `setQueryData` is for optimistic updates and the server-prefetch seeding case in `.claude/rules/sim-queries.md` "Server prefetching", nothing else +- Forms are the one deliberate exception (a keyed form child initialized lazily from loaded query data) — the pattern is owned by `/you-might-not-need-an-effect` "Query-backed forms"; do not duplicate its finding + +## Steps + +1. Read the references above to understand the guidelines +2. Analyze the specified scope against the rules listed above +3. If fix=true, apply the fixes. If fix=false, propose the fixes without applying. diff --git a/.agents/skills/ship/SKILL.md b/.agents/skills/ship/SKILL.md index a7af57d3e89..119a5ee218b 100644 --- a/.agents/skills/ship/SKILL.md +++ b/.agents/skills/ship/SKILL.md @@ -4,48 +4,177 @@ description: Commit, push, and open a PR to staging in one shot — runs the cle argument-hint: "[optional context or scope notes]" --- -# Ship +# Ship Command -Don't ask the user to confirm the commit message or PR description before executing. +You help ship code by creating commits, pushing to the remote branch, and creating PRs in the user's voice. -1. **Sync check**: `git fetch origin staging && git log --oneline origin/staging..HEAD`. Every listed commit must be one you can attribute to this session; a branch cut from a stale local `staging` silently drags in unrelated commits. If you see any you don't recognize, fix it before committing new work: - - Commit WIP as a temp commit before rebasing and drop it after (never `git stash`: the stash list is shared across every worktree of the repo, so another session can pop your entry or you theirs). - - Try `git rebase origin/staging`, then re-run the log: a rebase can replay stray commits onto the new base without any conflict. - - If the rebase conflicts, `git rebase --abort` first. Then note your SHAs, `git checkout -B origin/staging && git cherry-pick `, re-check the log. -2. **Commit message**: `type(scope): description`. Types in use: `fix`, `feat`, `improvement`, `chore`, `docs`, `perf`, `refactor`, `test`, `ci`. Scope is a short identifier (`undo-redo`, `api`, `ui`). -3. **Cleanup and tests** - - If the diff touches UI code (any non-test `.tsx`, or `apps/sim/components/`, `apps/sim/hooks/`, `apps/sim/stores/`), run `/cleanup` so its fixes land in this commit. - - Otherwise, if it adds or changes tests, run `/test-audit audit `; delete tests that fail the authoring gate rather than shipping them. - - Run the changed tests plus the tests beside changed source with `bun run --cwd test `. A failure aborts ship. -4. **Migrations**: only if the diff touches `packages/db/migrations/**` or `packages/db/schema.ts`, run `/db-migrate`. -5. **Local gate**: run the commands in root `CLAUDE.md` → "Before calling a change done", each block as written and never wrapped in a backgrounded loop (a bare `wait` swallows exit codes). Also run `bun run check:sdk-names-frozen origin/staging`; `check:audits` skips it because it diffs against a base ref. Stage whatever `bun run generate` rewrote. Fix the cause of any failure; never silence it. - - Domain generators outside `bun run generate` (`mship-tools:generate`, `generate:pi-model-catalog`, `scripts/generate-docs.ts`) read sources most worktrees lack; run one and its `:check` only when this diff touches its inputs. -6. **Commit and push.** Use `--force-with-lease` if step 1 rewrote history on an already-pushed branch. -7. **PR**: `gh pr create --base staging --title "" --body ""`, filling in `.github/PULL_REQUEST_TEMPLATE.md`. Then re-fetch and confirm `git log --oneline --reverse origin/staging..HEAD` and `gh pr view --json commits -q '.commits[].messageHeadline'` list the same commits in the same order; if not, redo step 1 and force-push. +## Your Task -## Voice +When the user runs `/ship`: -- Short, direct bullets, active voice, no fluff. -- Testing names what actually ran: test files, lint, `check:audits`, `check:migrations` when migrations changed, E2E artifacts. -- Drop template sections that don't apply; no screenshots section unless UI changed. -- No `Co-Authored-By` lines in commits. +1. **Check git status** - See what files have changed +2. **Sync check**: `git fetch origin staging && git log --oneline origin/staging..HEAD`. The list must contain ONLY commits you can attribute to this session (recognizable subjects/SHAs) — a worktree/branch cut from a stale local `staging` silently drags in unrelated commits. + - If it shows commits you don't recognize, fix it now, **before** staging/committing any new work (step 7 hasn't run yet): + - If the working tree has uncommitted changes, stash them first so the rebase below isn't blocked by dirty state, and pin the entry by SHA — the stash list is shared across every worktree of the repo, so `stash@{0}` and `git stash pop` can grab another session's entry: + ```bash + git stash push -u -m ship-sync-fix && SHIP_STASH=$(git rev-parse 'stash@{0}') + # once the branch is fixed (`git stash drop` rejects a raw SHA, so resolve the pinned + # entry's current stash@{n} and drop only that; an empty lookup drops nothing): + git stash apply "$SHIP_STASH" && + SHIP_STASH_REF=$(git stash list --format='%gd %H' | awk -v s="$SHIP_STASH" '$2==s{print $1}') && + { [ -z "$SHIP_STASH_REF" ] || git stash drop "$SHIP_STASH_REF"; } + ``` + - Try `git rebase origin/staging` first. + - **A rebase finishing without conflicts does NOT by itself mean the branch is clean** — it can replay stray commits onto the new base with no conflict at all. After the rebase (clean or not), re-run `git log --oneline origin/staging..HEAD` and re-check the commit list against what you recognize. + - If the rebase conflicted on unrecognized commits, OR finished cleanly but the log still shows them, abandon it (`git rebase --abort` if mid-rebase) and rebuild, in this exact order: + 1. Still on ``, list `git log --oneline --reverse origin/staging..` and write down ONLY the SHA(s) that are this session's work — the range also contains the stray commits, so cherry-picking the whole range recreates the polluted branch. Capture them now; after step 4 they are no longer in `HEAD`. + 2. `git checkout ` (required if an interrupted attempt left you on `ship-sync-tmp`) + 3. `git branch -D ship-sync-tmp 2>/dev/null || true` + 4. `git checkout -b ship-sync-tmp origin/staging` + 5. `git cherry-pick` the captured SHAs, oldest-first. Resolve conflicts. + 6. `git branch -f HEAD && git checkout && git branch -D ship-sync-tmp` + - Re-verify with `git log --oneline origin/staging..HEAD` — it must list only commits you recognize before you proceed to committing new work. +3. **Generate a commit message** following this format: `type(scope): description` + - Types: `fix`, `feat`, `improvement`, `chore` + - Scope: short identifier (e.g., `undo-redo`, `api`, `ui`) + - Keep it concise +4. **Run the cleanup and test gates** + - If the diff modifies UI code (any non-test `.tsx` file, or anything under `apps/sim/components/`, `apps/sim/hooks/`, or `apps/sim/stores/`), run `/cleanup`. It fans out the React/UI passes (effects, memo, callbacks, state, React Query, emcn, url-state), the comment pass, and the test-audit pass, and applies fixes so they land in this commit. + - Otherwise, if the diff adds or changes tests (`*.test.ts(x)`, `*.integration.ts`, `**/e2e/**`, `apps/sim/scripts/test-*-e2e.ts`), run `/test-audit audit ` on its own. Every new or changed test must pass the authoring gate; delete the ones that don't rather than shipping them. + - Then run the test files the diff adds or changes, plus the existing tests beside changed source files, with `bun run --cwd test ` (`bun run --cwd apps/sim test ` for the app; `*.integration.ts` needs the setup in `.claude/rules/sim-testing.md`). A failing test aborts ship. + - Then run root `bun run test` from the repo root. It chains `test:scripts` (the `scripts/*.test.ts` suite CI runs) before every workspace suite; workspace-scoped runs skip it, which is how a `scripts/check-*.test.ts` failure has reached CI. A failing test aborts ship. +5. **Run migration safety** — only if the diff touches `packages/db/migrations/**` or `packages/db/schema.ts`: + - Run `/db-migrate` to review the migration for zero-downtime safety (expand/contract phasing, backward-compatibility with the deployed app version). + - `(cd packages/db && bunx drizzle-kit generate && git status --porcelain ./migrations)` must print nothing (CI's schema/migration sync step). + - `bun run check:migrations origin/staging` must pass (staging is the PR base). Do not silence a flagged statement with a `-- migration-safe:` annotation unless `/db-migrate` confirmed the old code no longer depends on it; otherwise split the destructive change into a later deploy. +6. **Run pre-ship checks** from the repo root before staging. This has two phases: first **regenerate** every committed artifact so generated files never drift into a CI failure (this is what catches things like `agent-stream-docs` going stale after a `models.ts` edit), then run the **full audit suite** CI's `lint` job enforces. Both phases abort ship if any generator or audit fails: their runners (`scripts/generate-all.ts`, `scripts/run-audits.ts`) collect each job's exit code and exit non-zero, so never replace them with a backgrounded loop and a bare `wait`, which swallows child exit codes. -## What to omit + **Phase A — regenerate the always-in-repo committed artifacts, then let step 7 stage whatever changed.** Run the umbrella generator. It derives its list from package.json (every `generate:` that has a matching `check:`, plus `skills:sync`; see the header of `scripts/generate-all.ts`), so it covers every repo-local generator an ordinary code change can drift (a `models.ts` edit drifts `agent-stream-docs` and the SDK fixture catalog, a tool change drifts `tool-metadata`), runs them in the order their inputs require, and each is idempotent (a no-op when already in sync): + ```bash + # A non-zero exit means a generator FAILED: the summary names it and its output is above. Fix it + # before shipping; a silently-failed generate leaves a stale artifact that Phase B / CI then + # rejects. Keep the `exit 1`: it makes the block's own status non-zero so a caller actually stops. + bun run generate || { echo "❌ generator(s) failed — do not ship"; exit 1; } + echo "✅ artifacts regenerated" + ``` + Then `git status --short` to see what regenerated — those files must be staged in step 7 alongside your own changes. -The repo is public. Everything you publish (title, body, commit messages, code and migration comments, later PR comments) must stand on its own without the incident that produced it. Never include: + **Do NOT blanket-run the domain generators here.** `mship-tools:generate` merges Sim's tool contracts into the base tool catalog in the **external** Mothership worker checkout (`/worker/packages/contracts/tool-catalog-v1.json`), which most worktrees lack, so it hard-fails with `ENOENT` and would abort ship for an unrelated reason. The other mothership contracts in `apps/sim/lib/mothership/generated/` are copied in by the worker's `contracts:sync`, never generated here. `generate:pi-model-catalog` (under `apps/sim`) likewise regenerates from the installed Pi package, not repo source. `scripts/generate-docs.ts` rewrites the integration docs and client-safe catalog; run it when this PR changes their block/icon/landing-content inputs or when `check:integration-catalog` reports drift, then review its broad generated diff. Only when **this PR's diff actually touches** a domain generator's input do you regenerate it deliberately and run its matching `:check` (e.g. `bun run mship-tools:check`) — with the external source present. + + **Phase B — run lint + every audit CI enforces, in parallel, and abort ship if any fails.** Before running the commands, compare this list with `.github/workflows/checks.yml`; when CI adds an audit, run it and update this skill instead of trusting a stale snapshot. The env-flag audit is currently an inline workflow block rather than a package script: when `apps/sim/lib/core/config/env-flags.ts` changed, run that current workflow block verbatim instead of copying a second version into this skill. Run `bun run lint` first (it autofixes formatting and mutates files, so don't parallelize it with the read-only audits), then run the base-sensitive block-registry check, then fan the independent audits out and collect exit codes: + ```bash + # autofix formatting first (mutating; not parallel-safe with the audits). Gate its exit too — + # a non-zero lint (unfixable errors) must abort before the audits run, not be ignored. + bun run lint || { echo "❌ lint failed — do not ship"; exit 1; } + bun run apps/sim/scripts/check-block-registry.ts origin/staging || { + echo "❌ block registry audit failed — do not ship" + exit 1 + } + # Runs every audit CI runs, concurrently, and replays the output of any that fail. + # The audit list is derived in scripts/run-audits.ts — do not hand-list audits here. + # Workflow lint (actionlint) runs only in CI's "Lint workflows" step. + bun run check:audits || { echo "❌ audit(s) failed — do not ship"; exit 1; } + bun run type-check || { echo "❌ type-check failed — do not ship"; exit 1; } + # CI's "Security audit" `bun audit` step is `continue-on-error` — advisory only, not a gate — + # so it is deliberately not run here. + ``` + If Phase A regenerated a file, its matching `check:*` audit in Phase B now passes trivially — that parity is the point. Do not ship with any generator or audit failing; fix the cause (never silence it) and re-run. `check:migrations` is covered by step 5 and is not repeated here. +7. **Stage and commit** the changes with the generated message — including any files Phase A regenerated in step 6 +8. **Push to origin** using the current branch name — `--force-with-lease` if step 2's sync + check did any history rewrite (a clean rebase or a cherry-pick rebuild) on a branch that had + already been pushed once; a plain push would be rejected in exactly the polluted-remote case + step 2 exists to fix +9. **Create a PR** to staging with a description in the user's voice, then do a final content check — not a count check — comparing what actually landed: + ```bash + git fetch origin staging && git log --oneline --reverse origin/staging..HEAD + gh pr view --json commits -q '.commits[].messageHeadline' + ``` + Re-fetch first — comparing against a stale local `origin/staging` ref can mask real drift or + flag a false mismatch even when the branch and push are correct. `--reverse` makes the git log + oldest-first, matching the PR commit list's order — plain `git log` is newest-first, and a + positional/line-by-line comparison against the PR's oldest-first list can spuriously fail on + any multi-commit branch. These two lists must describe the same commits in the same order + (same subjects, the last one being the commit from step 7). If they don't match, the branch + still has a problem — redo step 2's fix and `git push --force-with-lease`. + +## Commit Message Format + +Based on the repo's commit history: + +``` +fix(scope): description for bug fixes +feat(scope): description for new features +improvement(scope): description for enhancements +chore(scope): description for maintenance +``` + +## What to Omit + +The repo is public. **Everything you publish — title, description, commit messages, and every later comment — must stand on its own without the incident that produced it.** Never include: - Customer, company, or user names; workspace/user/org/KB/connector IDs; email addresses - Prod or staging operational data: log lines, DB rows, metrics, timestamps, incident details, canary/alert output - Infrastructure specifics: hostnames (incl. tenant subdomains), ARNs, internal URLs, env var values, secret names - Verbatim customer content: file names, document titles, sheet/column names, folder paths -Describe the bug by its mechanism, not how you found it: "Expired OAuth credentials fail to refresh in the worker", not "the Sheets canary failed at 16:31Z for workspace abc-123". Replace real examples with placeholders (``) rather than cutting them. +Describe the bug by its mechanism, not by how you found it. "Expired OAuth credentials fail to refresh in the worker" — not "the Sheets canary failed at 16:31Z for workspace abc-123". Aggregate counts are fine once detached from the tenant ("1,379 PDFs failed"); the same number attributed to a named customer is not. Replace real examples with placeholders (``) rather than cutting them — the illustration is usually the useful part. -Keep timings, ratios, and test counts; drop anything sizing prod or a tenant (byte sizes, row/doc totals, instance counts). Code and migration comments are the most commonly missed case. +**Measurements are not the problem; absolute production scale is.** Keep the numbers that justify a change — durations, ratios, before/after timings, test and audit counts. They are the evidence a reviewer needs, and stripping them makes the rationale unfalsifiable. What does not belong is anything that sizes production or a tenant: table and index byte sizes, row/chunk/document totals, dead-tuple counts, buffer and heap-fetch counts, worker or instance counts. "Visiting four times as many tuples took 5.1s and 9.7s on consecutive runs" is fine; "on a 132k-chunk index" or "reclaims ~19 GB" is not. The same rule applies to code comments and migration comments, which are published exactly like a PR body — this is the most commonly missed case, because they do not feel like publishing. -Scrub before publishing, not after: a leak is public the instant it posts. Grep the title, body, `git log origin/staging..HEAD`, and the diff: +**Scrub before publishing, not after** — a leak is public the instant it posts, and editing later does not unsend the notification email. This applies to every PR you open, including ones created directly with `gh pr create` rather than through this skill. Grep the title, body, `git log origin/staging..HEAD`, AND the diff itself before publishing: ```bash +# identities, IDs, infrastructure grep -niE 'customer-or-company-name|@[a-z0-9.-]+\.(com|io|ai)|[0-9a-f]{8}-[0-9a-f]{4}-|\.sharepoint\.com|arn:aws|https?://[a-z0-9.-]*\.internal' +# absolute production scale — byte sizes, k/M-scale entity counts, 7-figure totals grep -niE '[0-9][0-9.,]* ?(TB|GB)\b|[0-9]+(\.[0-9]+)?[kKmM][- ](row|chunk|document|vector|tuple|doc)|[0-9]{1,3}(,[0-9]{3}){2,}' ``` + +The second pattern deliberately allows ordinary engineering numbers (`5.1s`, `46 audits`, `2,921 tests`) and flags only production sizing. + +## PR Description Format + +Use this exact template in the user's voice (concise, bullet points): + +```markdown +## Summary +- bullet point describing what changed +- another bullet point if needed + +## Type of Change +- [x] Bug fix (or appropriate type) + +## Testing +Describe the checks, tests, and E2E artifacts run + +## Checklist +- [x] Code follows project style guidelines +- [x] Self-reviewed my changes +- [ ] Tests added/updated and passing (new tests pass the `test-audit` authoring gate) +- [x] No new warnings introduced +- [x] I confirm that I have read and agree to the terms outlined in the [Contributor License Agreement (CLA)](./CONTRIBUTING.md#contributor-license-agreement-cla) +``` + +## PR Creation Command + +Use this command structure: + +```bash +gh pr create --base staging --title "COMMIT_MESSAGE" --body "PR_BODY" +``` + +## Important Notes + +- Do not ask the user to confirm the commit message or PR description before executing +- The PR should be created against `staging` branch +- Keep descriptions concise and in active voice +- Match the user's previous PR style: direct, no fluff, bullet points +- **DO NOT add "Co-Authored-By" lines to commits** - keep commit messages clean + +## User's Voice Characteristics (based on previous PRs) + +- Short, direct bullet points +- No unnecessary explanation +- Testing section names what actually ran: the test files, lint, `check:audits`, (when migrations changed) `check:migrations`, and any E2E artifacts +- Checkboxes filled in appropriately +- No screenshots section unless UI changes diff --git a/.agents/skills/test-audit/SKILL.md b/.agents/skills/test-audit/SKILL.md index 5db07c2c903..e7829f4f992 100644 --- a/.agents/skills/test-audit/SKILL.md +++ b/.agents/skills/test-audit/SKILL.md @@ -15,6 +15,12 @@ but a test that cannot name the bug it catches is cost, not coverage. Read `.claude/rules/sim-testing.md` first: it defines the test layers, file naming, and the mechanics (global mocks, `@sim/testing`, performance rules). +## The three rules + +CLAUDE.md → Testing sets them: no unit tests after the code; prefer E2E at the real boundary, +ending in a verifiable artifact; list failure modes before testing in isolation. A mode you cannot +list is not a test you should write. This skill enforces them. + ## Authoring gate Before adding any test, answer all four. A missing answer means do not add it. @@ -32,16 +38,22 @@ Then check it against every junk pattern below. A match fails the gate unless th names the contract it independently guards. A test that would break under behavior-preserving refactoring asserts implementation, not behavior. -**Regression tests**: one at the owner boundary covers the bug; do not replay it at every layer -it crosses. +**Regression tests** must fail on the pre-fix code for the intended reason. Revert each guard of +the fix separately and watch the test named for that guard go red, then restore. A regression +test that never demonstrably failed proves the mock, not the fix. One regression at the owner +boundary covers the bug; do not replay it at every layer it crosses. ## Junk patterns - assertion-free or `toBeDefined()`-only tests; "renders without crashing"; -- re-asserting a mock's canned return; +- restating declarations: block/tool/trigger/provider config (subBlock ids, params, outputs, URL + templates, header maps), constant tables, registries, enums, export lists — type-check and + `check:audits` own these; +- route/handler tests that mock every collaborator and assert `toHaveBeenCalledWith` on the mocks, + or re-assert a mock's canned return; - mocks that implement the asserted behavior, or one mock standing in for different APIs; - Zod contract tests proving a schema accepts a valid object or rejects an obviously invalid one; -- React tests of aria presence or "calls onClick"; +- React tests of text, class names, aria presence, snapshots, "calls onClick"; - hook tests asserting query keys or fetch URLs; store tests of trivial setters; - tests of test infrastructure (mocks, factories, builders testing themselves); - source-text or import greps (`readFileSync(src)` + `toContain`); @@ -51,6 +63,8 @@ it crosses. - negative controls that pass for an unrelated reason (a different guard short-circuits first); - names or fixtures that promise more than the input exercises; - dead production code or exports whose only callers are tests. +- a hand-rolled `vi.mock` factory for a module `vitest.setup.ts` or `@sim/testing` already mocks, or a + local copy of a `@sim/testing` helper (`bun run check:test-patterns` fails on these). ## Retention bar @@ -111,9 +125,11 @@ For a whole subsystem or the whole repo: Never edit source or tests while Vitest is running in the same checkout. -1. Run the touched and sibling test files (`.claude/rules/sim-testing.md` → Running), then the - root gate in `CLAUDE.md` → "Before calling a change done" (some audits list test files by path). -2. Report `git diff --shortstat` with production and test changes counted separately. +1. Run the touched and sibling test files (`.claude/rules/sim-testing.md` → Running). +2. If production code changed: `bun run type-check` in that workspace. +3. `bun run check:audits` from the repo root (some audits list test files by path). +4. `bun run lint`, then `git diff --check`. +5. Report `git diff --shortstat` with production and test changes counted separately. ## Handoff diff --git a/.agents/skills/tool-registry-boundary/SKILL.md b/.agents/skills/tool-registry-boundary/SKILL.md index 1bb49cee3ad..c063d66e861 100644 --- a/.agents/skills/tool-registry-boundary/SKILL.md +++ b/.agents/skills/tool-registry-boundary/SKILL.md @@ -3,36 +3,93 @@ name: tool-registry-boundary description: Keep the executable tool registry out of client-reachable module graphs — when to read `@/tools/metadata` instead of `getTool`, how to measure whether an import edge pulls the registry, and how to regenerate the metadata artifacts. Use when touching `apps/sim/tools/registry.ts`, `tools/utils.ts`, `tools/params.ts`, or anything that calls `getTool`. --- -# Tool Registry Boundary +# Tool Registry Boundary Skill -Keep the 5,000+-tool executable registry out of module graphs that don't execute tools. `check:tool-registry-boundary` fails with the import chain when one does; this skill covers choosing the import and fixing a failure. +You keep the 5,000+-tool executable registry out of module graphs that don't execute tools. + +## The rule + +> Client-reachable code reads tool **metadata**. Only code that actually executes a tool imports the **registry**. + +`@/tools/registry` is a 10,000+-line barrel importing every tool. External `ToolConfig` entries mix +plain data (`params`, `outputs`, `name`) with request/response closures, while +`InternalToolConfig` entries contain semantic input projection and load their server implementation +through `lib/internal/tool-operations/registry.server.ts`. Request closures can still reach SDK +clients, API helpers, and parsers, which is what makes the executable barrel expensive: reaching it +costs roughly 4,700 additional modules (measured; re-measure with `--verbose`). + +`getTool()` returns the whole `ExecutableToolConfig`, so a single `getTool` import anywhere in a client-reachable file drags all of it in. ## Which module to import -| You need | Import | Cost | +| you need | import | notes | | --- | --- | --- | -| whether a tool id exists | `hasToolId` from `@/tools/tool-ids` | ~170 KB, the cheapest | -| to resolve an unversioned name, or every id | `resolveToolId` / `getToolIds` from `@/tools/tool-ids` | | -| a tool's params | `getToolParams` / `getToolMetadata` from `@/tools/metadata` | ~8 MB | -| a tool's declared outputs | `getToolOutputsMetadata` from `@/tools/metadata-outputs` | ~8 MB, separate on purpose | -| to **execute** a tool | `getTool` (`@/tools/utils`) or `getToolAsync` (`@/tools/utils.server`) | the whole registry; server paths only | +| whether a tool id exists | `hasToolId` from `@/tools/tool-ids` | ~110 KB — the cheapest module | +| to resolve an unversioned name | `resolveToolId` from `@/tools/tool-ids` | | +| every tool id | `getToolIds` from `@/tools/tool-ids` | | +| a tool's params | `getToolParams` / `getToolMetadata` from `@/tools/metadata` | ~4 MB | +| a tool's declared outputs | `getToolOutputsMetadata` from `@/tools/metadata-outputs` | ~4 MB, separate on purpose | +| to **execute** a tool | `getTool` from `@/tools/utils`, or `getToolAsync` from `@/tools/utils.server` (async/workspace-context lookup) | server paths only | + +Three modules, cheapest first. Ids are their own artifact because resolution and existence checks need only the key set; outputs are their own because they are the larger half of the data with a single consumer. `@/tools/metadata` and `@/tools/metadata-outputs` both resolve ids through `@/tools/tool-ids`, which is what keeps them independent of each other — do not "helpfully" re-export one from another, or every caller pays for all three. + +All lookups guard with `Object.hasOwn`. `JSON.parse` yields an object with the normal prototype, so a bare bracket lookup returns inherited members: a bare bracket lookup would answer `getToolMetadata('constructor')` with a *function* typed as tool metadata. + +## The generated artifacts + +`apps/sim/tools/generated/tool-ids.ts`, `tool-metadata.ts` and `tool-outputs.ts` are produced by `scripts/sync-tool-metadata.ts`: + +```bash +bun run generate:tool-metadata # after adding/changing a tool +bun run check:tool-metadata # what CI runs; fails if stale +``` + +Never hand-edit them. If you add a tool or change a tool's `params`/`outputs`, regenerate and commit the result, or CI fails. + +Four non-obvious properties, each of which was measured and is easy to undo by accident: + +- **The data is a JSON string parsed at runtime, not an imported `.json` and not an object literal.** With `resolveJsonModule` (which this repo enables), a `.json` import makes TypeScript infer a literal type for all 5,000+ entries and takes `tsc --noEmit` from **12.6s to 8m07s** — a 38x regression. An ambient `declare module` does *not* short-circuit it, and an object literal costs the same. A single string literal is one cheap token for both the compiler and the bundler, and `JSON.parse` beats evaluating the equivalent literal at runtime. Do not "clean this up" into a `.json` import. +- **The generator refuses to emit function values.** If you add a field to `METADATA_FIELDS` that contains a closure, generation fails loudly rather than shipping executable config to the client. `hosting` and `schemaEnrichment` are excluded for exactly this reason (`hosting.enabled`, `pricing`, and `enrichSchema` are functions) — they are server-only. +- **Empty param entries are stripped.** The registry contains one (`stt_deepgram_v2`), which crashes callers that read `param.type` while iterating. +- **Lookups resolve versions.** `getTool` maps an unversioned name onto the newest version, and a few hundred tools are versioned. A plain key lookup would silently report them missing — a quiet correctness bug, not a crash. `resolveToolId` reproduces that against the id set and is differentially tested against the original. + +## Testing code that reads tool metadata + +Mock the module the code under test actually reads. `@/tools/metadata` and `@/tools/metadata-outputs` are mocked globally in `apps/sim/vitest.setup.ts` and return `undefined`; never `vi.mock` them again (`check:test-patterns` fails a `global-remock`). Install fixtures on the global mock instead: + +```ts +import { toolsMetadataMock } from '@sim/testing/mocks/blocks.mock' +import { getToolMetadata } from '@/tools/metadata' + +vi.mocked(getToolMetadata).mockImplementation(toolsMetadataMock.getToolMetadata) +``` + +Do the same for `getToolParams`. `vi.mock('@/tools/utils', () => toolsUtilsMock)` controls only `getTool`. Both mocks share `mockToolConfigs`, so together they give one consistent tool universe. If you are unsure whether a mock is load-bearing, change a fixture value to a sentinel and confirm the test fails. +## The guard + +`bun run check:tool-registry-boundary` (run in CI by `check:audits`) walks the module graph from each workspace route and fails if `@/tools/registry` is reachable, printing the exact import chain that reintroduced it. + +If it fails, do not add the entry to an allowlist — there isn't one. Find the symbol the offending file actually needs and move it to a registry-free module (e.g. `tools/merge-params.ts`). + +Run it with `--verbose` to print per-route module counts, which is also the quickest way to see whether a change moved the graph. -`@/tools/metadata` and `@/tools/metadata-outputs` both resolve ids through `@/tools/tool-ids`, which keeps them independent of each other: never re-export one from another, or every caller pays for all three. +The same command also ratchets those counts against `check-tool-registry-boundary.baseline.json`. `--check` (what CI runs) fails when an entry exceeds its baseline by more than `max(25 modules, 2%)`, naming the import chain responsible. The baseline also catches graph growth that never touches `@/tools/registry`. -A caller that reads `params`, `outputs`, `name` or `description`, or only checks existence, uses metadata, **even on a path you believe is server-only**: a future client import would silently re-attach the registry. Only code that builds a request, transforms a response, or dispatches an internal operation uses `getTool`, and that file stays off client-reachable paths. +Re-record with `--update-baseline` and commit the JSON when growth is deliberate. A *shrink* passes but is reported — re-record then too, or the win is silently spendable again. -The generated artifacts under `apps/sim/tools/generated/` come from `bun run generate`; never hand-edit them. +## How to verify an edge actually got cut -## Generated data +Do not eyeball imports — the registry is reached through several redundant paths, so cutting one buys nothing while another survives. Walk the graph: -The metadata modules hold the tool data as one JSON string parsed at runtime. A `.json` import (or an object literal) makes `tsc` infer a literal type for every entry, about 38x slower; an ambient `declare module` doesn't help. Don't "clean it up" into a `.json` import. +1. From the entry you care about, follow `import` and `export … from` (skipping `import type`), resolving `@/` against `apps/sim`. +2. Check whether `apps/sim/tools/registry.ts` is in the reachable set, and print the parent chain if it is. +3. Compare the reachable module count before and after. -## Tests +A route can reach the registry through several redundant edges; cutting one changes nothing until all are gone, so measure the route, not the file you edited. -`@/tools/metadata` and `@/tools/metadata-outputs` are globally mocked to return `undefined`. Install fixtures on the global mock: `vi.mocked(getToolMetadata).mockImplementation(toolsMetadataMock.getToolMetadata)` (from `@sim/testing/mocks/blocks.mock`), same for `getToolParams`. `toolsUtilsMock` controls only `getTool`; both share `mockToolConfigs`, giving one consistent tool universe. If unsure a mock is load-bearing, set a fixture value to a sentinel and confirm the test fails. +## When adding a new caller -## When the guard fails +Ask what the caller does with the config. If it reads `params`, `outputs`, `name`, `description` or just checks existence, it belongs on `@/tools/metadata` — no exceptions, even on a path you believe is server-only today, because a future client import will silently re-attach the registry to the graph. -- There is no allowlist. Find the symbol the offending file actually needs and move it to a registry-free module (e.g. `tools/merge-params.ts`). -- Measure the route, not the file you edited: the registry is reached through several redundant edges, so cutting one changes nothing until all are gone. `--verbose` prints per-route module counts before and after. -- The command also ratchets module counts; re-record with `--update-baseline` when growth is deliberate, and after a shrink too, or the win is silently spendable again. +If it genuinely executes — builds an external request, transforms a response, or dispatches a +registered internal operation — use `getTool`, and keep that file off client-reachable paths. diff --git a/.agents/skills/v2-api-conventions/SKILL.md b/.agents/skills/v2-api-conventions/SKILL.md index 93abb1f7bea..e49c004271c 100644 --- a/.agents/skills/v2-api-conventions/SKILL.md +++ b/.agents/skills/v2-api-conventions/SKILL.md @@ -6,7 +6,7 @@ argument-hint: # v2 API Conventions -The v2 surface makes one promise: **every response is one of these shapes, and a caller-supplied value can never produce a 500.** +The v2 surface makes one promise: **every response is the same two shapes, and a caller-supplied value can never produce a 500.** ``` success (single) { "data": {...} } @@ -14,73 +14,226 @@ success (collection) { "data": [...], "nextCursor": "..." | null } failure (always) { "error": { "code": "...", "message": "...", "details"?: ..., "requestId"?: "..." } } ``` -Machinery: envelope, error codes and cursor codecs in `apps/sim/app/api/v2/lib/response.ts`; the builder in `lib/api/server/routes/v2-json-route.ts`; cross-tenant concealment in `lib/api/server/routes/resource-concealment.ts`; contracts in `lib/api/contracts/v2/**`; keyset helpers in `lib/api/list-query.ts`. Build order is contract → application use case → route (see `migrate-application-operation`); the presenter reads request params (active sort, filters) from the parsed request rather than making the use case carry them back. +Nothing else at the top level. No `success: true`, no bare `{ "error": "string" }`, no HTML. -## Errors and status codes +Each rule below guards a caller-visible failure: a non-integer `limit` reaching SQL, a non-envelope error body, an HTML 404 for unknown paths, an unapplied `limit` stripped by non-strict Zod, and an untyped bound parameter into an overloaded SQL function. -**500 is never caller-reachable.** Any input a caller can send is rejected at the contract with a 400; a request that 500s is a contract bug, not something to wrap in `try`/`catch`, and the highest-severity defect on this surface. Known shapes: non-integer numerics, a method guard rejecting HEAD-on-GET, untyped placeholders into SQL functions. A response schema is `.parse`d on the way out, so asserting a field the producer doesn't always emit turns a successful read into a 500: assert only what you can prove. +## Where the machinery lives -**Validating a value is half of it; it must also reach SQL with a type.** A bound parameter takes its type from context, which always works against a typed column (`sort_order > $1`) but can resolve to nothing as an argument to an overloaded function. A bound value passed as an argument to a SQL function (not a comparison) must carry an explicit type. When a change alters generated SQL *shape*, run it against Postgres: `keysetAfter` once passed every unit test and only the parser rejected it. +| Concern | File | +|---|---| +| Envelope + error codes + cursor codecs | `apps/sim/app/api/v2/lib/response.ts` | +| Cross-tenant concealment | `apps/sim/lib/api/server/routes/resource-concealment.ts` | +| Route builder | `apps/sim/lib/api/server/routes/v2-json-route.ts` | +| Contracts | `apps/sim/lib/api/contracts/v2/**` | +| Shared list/keyset helpers | `apps/sim/lib/api/list-query.ts` | -**404 is deliberately overloaded.** A workspace the caller cannot reach answers `404 "Workspace not found"`, never 403, which would confirm it exists; the unknown-path catch-all answers the same body. Every v2 response is `Cache-Control: private, no-store`, which matters most here: 404 is heuristically cacheable and an authorization-dependent 404 must never be stored. +## Rule 1 — the envelope is produced by helpers, never by hand -**403 vs 404 follows authorization, not whether it's a read.** No workspace access (`NoWorkspaceAccessError`) is concealed as 404; access below `minimumRole` stays 403. A `read` operation can't 403 on role, but can through `PersonalApiKeysDisabledError` or `WorkspaceApiKeyAuthorizationError`, and every v2 operation is reachable by a personal key, so **every workspace-scoped v2 operation documents 403**. Use the shared `RESOURCE_*_ERRORS` sets in `contracts/v2/openapi/shared.ts`; hand-assembled lists drop `Forbidden`. +`v2Data`, `v2Error`, and the typed error helpers in `response.ts` (`v2ValidationError`, `v2RateLimitError`, `v2HttpError`, `v2InsufficientScope`, `v2HeadNoEffect`, `v2NoContent`, `v2UploadDataPlaneError`) are the only things that build a v2 body. They also set `Cache-Control: private, no-store`, which every v2 response needs because every v2 response is authed per-caller data. -**A 403 a caller can act on names its cause in `error.details.code`.** One status covers different remedies (raise a role, use a personal key, buy a plan, get under a quota), and clients that string-match messages break on every reword. Codes come from the closed `FORBIDDEN_DETAIL_CODES` (`lib/core/application/forbidden.ts`); a new one is warranted only when the remedy differs. Throw `ForbiddenOperationError(code, message)` from the domain, never attach a code at the route. Clients treat `details.code` as optional (some domain 403s still lack one; see `FORBIDDEN_DESCRIPTION`); new 403s always carry one. Cross-tenant refusals carry **no** code: naming the cause would leak the existence signal the 404 withholds. +A route built with `defineV2JsonRoute` gets this for free: its `present` returns the *body shape* and the builder renders it. Never call `NextResponse.json` from a v2 route. -**HEAD runs the GET handler** (Next aliases it; the builders accept the pairing). That is only sound because HEAD is safe, so **a GET with side effects declares `headSafe: false`**: `GET /files/{fileId}` records `FILE_DOWNLOADED`, and without it an uptime monitor's HEAD would fabricate downloads. Such a route still authenticates and rate-limits a HEAD, then answers a bodiless 200 without executing. Recheck whenever a read gains an audit projection or outbound call. +**The envelope must hold for every failure mode, including the ones that happen before your handler runs.** Defaults for the transport-level failures live on the builder — `v2PayloadTooLargeResponse` (413) and `v2InvalidJsonResponse` (400) — precisely so a route cannot forget them. -## Pagination +## Rule 2 — status codes mean specific things -A list returning `nextCursor` accepts `limit` + `cursor` from `v2PaginationFields` and actually applies them; whether a list pages at all is pinned in `lib/api/contracts/v2/list-pagination.test.ts`. +| Status | `code` | Meaning | +|---|---|---| +| 200 / 201 | — | Success. 201 only for a created resource. | +| 400 | `BAD_REQUEST` | Contract validation. Carries field-level `details` from `serializeZodIssues`. | +| 401 | `UNAUTHORIZED` | No/!valid API key. | +| 403 | `FORBIDDEN` | Authenticated, same tenant, insufficient rights. Where the cause is one a caller can act on it is named in `details.code`, from the closed set in `lib/core/application/forbidden.ts` (e.g. `INSUFFICIENT_WORKSPACE_ROLE`, `PERSONAL_API_KEYS_DISABLED`). A few domain refusals still reach the wire without one. | +| 404 | `NOT_FOUND` | Not found, **and** cross-tenant concealment, **and** an unknown path. | +| 409 | `CONFLICT` | Uniqueness/state conflict, human-readable message. | +| 413 | `PAYLOAD_TOO_LARGE` | Body over the route's `maxBodyBytes` — **and** a collection the response must materialize that is over *its* ceiling. Fourteen bodyless `GET`/`DELETE` operations publish it for the folder-tree cap (`FolderCollectionLimitExceededError`) or the rendered-artifact cap. | +| 429 | `RATE_LIMITED` | With `Retry-After` and `X-RateLimit-*`. | +| 500 | `INTERNAL_ERROR` | Genuine server fault only. Message is always generic. | -- **Keyset** (`readSortedCursor`/`encodeSortedCursor`) is the default; it needs the page to come from one ordered SQL read. The key list must end in a unique column (`id`), or tied rows repeat or drop at the boundary. -- **Offset** (`decodeOffsetCursor`/`encodeOffsetCursor`) only when keyset is impossible (`GET /skills` merges an in-code registry with DB rows; `GET /knowledge/{id}/documents`). -- Stamp `cursorSortKey(sortBy, sortOrder)` and `cursorScopeKey(cursorRoute(contract, pathParams), {...filters})` so changing sort or filters mid-pagination is a 400, not a skipped page. Never stamp `limit` or response-shaping params: binding `limit` strands every cursor when a caller changes page size. -- Legacy domain-minted cursors on re-filterable lists are wrapped with `encodeScopedCursor`/`readScopedCursor`; new lists use keyset or offset, never a new scheme. -- `nextCursor: null` on the last page and only then. -- **Cursors are opaque, not trusted.** They are unsigned base64-JSON on purpose: `KeysetKey.bind` re-validates every value (a forged cursor can't reach SQL as `NaN`), filters are hashed into the stamp, and authorization is re-derived from the principal every time. Never put a resource id, filter or scope in a cursor and trust it back: a cursor is a position hint, never an access-decision input. +Two of these carry real design weight: -**Ordering is `sortBy` + `sortOrder`.** The only exception is `GET /workflows/{workflowId}/runs` (one sortable column, so a single `order`). Don't accept `sortOrder` as an alias (two spellings, undefined precedence). Before documenting a second `order`-style exception, check sibling endpoints on the same rows: if any sorts them more than one way, the premise is false. +**404 is deliberately overloaded.** A workspace the caller cannot reach answers `404 "Workspace not found"`, never 403 — a 403 would confirm the resource exists. `createV2ResourceConcealmentPolicy` does this by mapping a cross-tenant authorization failure to `v2Error('NOT_FOUND', ...)`. The unknown-path catch-all at `app/api/v2/[[...segments]]/route.ts` answers with the same body on purpose. -**Boolean query params** use `booleanQueryFlagSchema`; reusing an internal `.shape.x` inherits its `z.enum(['true','false'])` spelling. +**500 is never caller-reachable.** Any input a caller can send must be rejected at the contract boundary with a 400. If you can construct a query string or body that produces a 500, that is a bug in the contract, not something to wrap in a `try`/`catch`. `v2ErrorForOrchestration` also replaces the message on an unclassified failure with a generic one, so internal detail never leaks. Treat any well-formed request that produces a 500 as the highest-severity defect on this surface: non-integer numerics, a method guard rejecting the `HEAD`-on-`GET` pairing, and untyped placeholders into SQL functions are the known shapes. -## Reject what you don't implement +**Validating a value is only half of it; the value also has to reach SQL with a type.** A bound parameter arrives as `unknown` and takes its type from context. Against a typed column (`sort_order > $1`) that inference always succeeds, which is why the gap stays invisible almost everywhere — but as an argument to an overloaded function it can resolve to nothing at all. So: **if a bound value is an argument to a SQL function rather than one side of a comparison, write its type down** (`lib/api/list-query.ts`, `timestampKey`, casts from the column). -Unknown query params are a 400: safe for first-party callers (the SDKs send only declared params; the UI makes no v2 calls) and documented in `api-reference/getting-started.mdx` for third parties. Non-strict Zod strips unknown keys, so `?limit=1` against a list without `limit` answers 200 with everything: a contract lie and an unbounded response. +And this class survives a green test suite — `keysetAfter` returned well-formed SQL and every assertion passed; only Postgres's parser rejected it. When a change alters the *shape* of generated SQL rather than its values, execute it somewhere before believing the suite. -`.strict()` binds the top level only: a strict body with a non-strict nested object silently drops keys one level down (`sort: [{ field, direction, nulls: 'last' }]` answered 200 ordered by default). Put strictness on the shared nested schema (`sortSpecSchema`'s element, `tableViewConfigSchema`). Before making a schema that is also a stored blob or response strict, canonicalize reads (`normalizeStoredViewConfig`) so legacy keys don't 500. +**Which of 403 and 404 an operation documents follows from its authorization, not from whether it is a read.** `requirePermission` throws two different failures: no workspace access at all is `NoWorkspaceAccessError`, which `createV2ResourceConcealmentPolicy` conceals as 404; access below the operation's `minimumRole` is `InsufficientWorkspacePermissionsError`, which stays a 403. So: -Validation messages name the field and the escape hatch: `Limit cannot exceed 1000; use limit=0 to stream all rows, or create an export`. `Invalid input` is not actionable. +- An operation whose `minimumRole` is `write` or `admin` can always 403 — a member with a lower role hits it. Document 403. +- An operation whose `minimumRole` is `read` cannot 403 *that* way, because `read` is the floor of the `read < write < admin` ordering and anyone without access is concealed as 404 instead. It can still 403 through `PersonalApiKeysDisabledError` (a personal API key against a workspace whose organization disabled them) or `WorkspaceApiKeyAuthorizationError` (`workspaceApiKey: 'deny'`), and every v2 operation is reachable by a personal API key. **So in practice every workspace-scoped v2 operation documents 403**, and the reads that omitted it were wrong, not principled. -## Descriptions +**A 403 a caller can act on names its cause in `error.details.code` — but not every 403 does yet.** One status covers several different remedies — raise a member's role, issue a personal key instead of a workspace-scoped one, re-point a workspace key, buy an enterprise plan, delete a resource to get under a quota — and prose is not branchable, so a client that must tell them apart was string-matching messages, which turns every reword into a silent break. A handful of domain refusals still throw a bare `OrchestrationError('forbidden', …)` and reach the wire with no code, so **write client code that treats `details.code` as optional**, and read `openapi/shared.ts`'s `FORBIDDEN_DESCRIPTION` for the current position rather than assuming the sweep is finished. For code you are *writing*, the rule below is unconditional. -Follow `lib/api/contracts/v2/openapi/README.md`. A description claiming behavior the route lacks is the same bug as a wrong schema: verify archive vs permanent delete, replace vs partial update, partial success, retry safety, redaction and async completion against the implementation. Field rules live in the source schema; shared descriptions feed CLI help, so name related operations, not HTTP paths. Regenerate with `bun run generate`. +The vocabulary is the closed tuple `FORBIDDEN_DETAIL_CODES` in `lib/core/application/forbidden.ts` (each member TSDoc-documented), published to OpenAPI as the `V2ForbiddenDetailCode` enum via `v2ForbiddenDetailCodeSchema`. A new code needs a documented entry there and is warranted only when the remedy differs. Do not invent a code at a route: throw `ForbiddenOperationError(code, message)` from the domain and let `v2CaughtOrchestrationError` — the function every v2 error policy falls through to — attach it. `InsufficientWorkspacePermissionsError`, `PersonalApiKeysDisabledError`, `WorkspaceApiKeyAuthorizationError`, and `PrincipalKindAuthorizationError` already carry theirs. -## Retry-After +The cross-tenant refusals (`NoWorkspaceAccessError`, `WorkspaceApiKeyScopeAuthorizationError`, `DelegatedWorkspaceAuthorizationError`) deliberately carry **no** code. They are concealed as 404, and naming their cause would hand back the resource-existence signal the concealment exists to withhold. -429 (`v2RateLimitError`, from the caller's bucket) and 503 (`v2Error` default keyed on status) carry it; a route with a better number passes the header and wins. Add no default for other codes: 400/403/404/409 aren't fixed by waiting, 402 by a billing change, and 413s are fixed ceilings. +Use the shared sets in `contracts/v2/openapi/shared.ts` — `RESOURCE_ERRORS`, `RESOURCE_CONFLICT_ERRORS`, `RESOURCE_MUTATION_ERRORS` — rather than assembling a per-operation list; all three already include `Forbidden`, which hand-assembled lists drop. -- **Where a policy knows the wait, carry it end to end** (`descriptor.retryAfterSeconds → PreprocessExecutionError.retryAfterMs → ExecuteWorkflowServiceFailure.retryAfterMs → serviceFailureResponse`); a mapping that drops it turns a concurrency denial into a bare 429. The `v2Error` default is the floor for paths with no policy signal. -- **An unknown-outcome failure must not advise a retry.** `ASYNC_ENQUEUE_AMBIGUOUS` may have enqueued: it passes `omitRetryAfter: true` and returns the run id, because a "retry in 5s" invites a client without `X-Run-Id` to start and bill a second run. Any future "we don't know if it happened" failure does the same. +**HEAD is answered by the `GET` handler, not rejected.** Next aliases a missing `HEAD` export onto `GET` and drops the body when sending, so a route's `GET` legitimately runs with `request.method === 'HEAD'`. The builders' method guard accepts that pairing via `methodMatchesContract`; any other mismatch stays a hard error. Never hand-write a `HEAD` export to "fix" this. -## X-Run-Id: at-most-once, not replay +**A `GET` with side effects must declare `headSafe: false`.** The aliasing above is only sound because RFC 9110 §9.2.1 defines `HEAD` as safe. A `GET` that writes a row or opens an outbound connection is not, and an uptime monitor or link checker walking the documented URL list would drive those effects on every probe — `GET /files/{fileId}` records a `FILE_DOWNLOADED` audit event, so without `headSafe: false` a `HEAD` would fabricate a download that never happened. Both the JSON and binary builders take `headSafe`: a route that sets it `false` still authenticates and rate-limits a `HEAD`, then answers `v2HeadNoEffect()` — a bodiless 200 — before parsing or executing. Nothing observable is lost, because `HEAD` carries no body either way. Audit this whenever a read acquires an audit projection or an outbound call. -`X-Run-Id` on `POST /workflows/{id}/execute` (API-key and OAuth callers) is a uniqueness claim, not an idempotency key: a claimed id returns 409 `RUN_ID_CONFLICT` (with `details.runId` and the header) and never replays the earlier result. Ids stay reserved after logs are deleted; an ambiguous enqueue can hold a claim with no retrievable run, so 409 then 404 is unresolved, not proof nothing ran. On an uncertain outcome, retry with the same id and check Get Workflow Run; never auto-restart with a fresh or omitted id. Do not alias Stripe's `Idempotency-Key`: replay needs a fingerprint, retention window, in-flight state and body storage, and clients written for Stripe semantics would misread our 409. +## Rule 3 — a collection that returns `nextCursor` must accept `limit` + `cursor`, and must apply them + +Every list returns `{ data, nextCursor }`. Whether it *pages* is a separate, pinned decision — see `lib/api/contracts/v2/list-pagination.test.ts`, which enumerates both sets and fails when a new list is in neither. + +Build the query slice from the shared helper, never by hand: + +```ts +...v2PaginationFields({ description: 'Maximum widgets to return per page.' }) +``` + +That gives `limit` (integer, 1..`V2_MAX_PAGE_SIZE`, defaulting to `V2_DEFAULT_PAGE_SIZE` = 50) and an opaque `cursor`. Never re-declare `limit: z.coerce.number()...` inline; inline schemas drift from `.int()`. + +Three cursor schemes exist. Two are the shared codecs in `response.ts`, both opaque base64-JSON, and which of them you use is decided by what the read can express, not by taste: + +- **Keyset** (`readSortedCursor` in, `encodeSortedCursor` out) — the default. Requires the page to come from one ordered SQL read. The sort AND the filters are stamped into the cursor and re-checked on replay, so changing `sortBy` or any filter mid-pagination is a 400, not a silently skipped page. +- **Offset** (`decodeOffsetCursor` / `encodeOffsetCursor`) — only when a keyset is impossible. Two lists qualify: `GET /skills` merges a static in-code registry with DB rows and re-sorts in JS, and `GET /knowledge/{id}/documents` sits on a limit/offset query. A bare offset replayed against a re-sorted or re-filtered sequence names a different row, which skips or repeats results. + +Both take the same two stamps: `cursorSortKey(sortBy, sortOrder)` for the ordering, and `cursorScopeKey(cursorRoute(contract, pathParams), { ... })` for every param that filters the sequence — the route identity is the first argument, the filter parts the second. **`limit` is never a stamp** — it selects how much of the sequence to return, not what the sequence is, and binding it strands every cursor the moment a caller changes page size. Params that only shape the response body are out for the same reason. + +The third is **per-domain**: a list whose read predates the shared codecs, or whose page boundary is not expressible as one, mints its own — a bare `encodeCursor({ version })` on `GET /workflows/{id}/versions` and `encodeCursor({ email })` on the workspace member list, the local codecs in `lib/audit-logs/query.ts`, `lib/logs/list-logs.ts`, and `lib/table/rows/cursor.ts`, and a usage-event id passed straight through by `GET /billing/logs`. Those tokens stay opaque and untouched, but a domain-minted cursor on a list a caller can re-filter is wrapped at the surface with `encodeScopedCursor(cursorScopeKey(cursorRoute(contract, pathParams), {...}), token)` and unwrapped with `readScopedCursor`, so it carries the same binding as the shared schemes. **A new list picks one of the two shared schemes.** Do not add a fourth. + +Every paged list's binding is declared in `lib/api/contracts/v2/list-pagination.test.ts` and checked against what the contract actually accepts, in both directions. A new list, or a new filter on an existing one, fails that test until its binding is declared or the param is explicitly recorded as unable to change the sequence. + +**A keyset's key list must end in a unique column (`id`).** A non-unique trailing key cannot separate tied rows, so the page boundary either repeats or drops them. `lib/api/list-keyset-paging.test.ts` demonstrates the failure. + +Return `nextCursor: null` on the last page and only then. Never construct a cursor client-side. + +**Ordering is `sortBy` + `sortOrder`, except where there is nothing to sort by.** Nearly every paged list takes the pair; `CURSOR_BINDINGS` in `contracts/v2/list-pagination.test.ts` is the authoritative set. Exactly one — `GET /workflows/{workflowId}/runs` — has a single sortable column (start time), so there is no `sortBy` to pair with and the direction rides on a single `order` param; `sortBy`/`sortOrder` are not accepted there. That is the *only* sanctioned deviation, and it is documented in its contract. A new list picks the pair. Do not "fix" it by accepting `sortOrder` as an alias: an alias is a second spelling of one thing with undefined precedence when both arrive, which is its own inconsistency. + +Before documenting a second `order`-style exception, check every other endpoint on the same collection: if one of them already sorts those rows more than one way, the "exactly one sortable column" premise is false — fix the premise rather than documenting the exception. + +**A boolean query param is a real boolean**, declared with `booleanQueryFlagSchema` from `contracts/primitives.ts`; it coerces `'true'`/`'1'` and `'false'`/`'0'`/`''`. Reusing an internal `.shape.x` inherits the internal spelling (often a `z.enum(['true','false'])`); re-declare instead when the internal one is not the v2 convention. + +## Rule 4 — reject what you do not implement + +**Every contract declares a `query`, even when the endpoint takes none** — `query: noInputSchema` (`z.object({}).strict()`), never omission. `parseRequest` validates the query slice only when the contract declares one, so an omitted `query` means "never look at the query string", not "takes no query params". An omitted `query` silently accepts any query string; `query-declaration.test.ts` fails a contract that omits it. + +Unknown query params are a 400. That is safe for first-party callers — the two SDKs send only `includeOutput`/`selectedOutputs`, both declared; the UI makes no v2 calls; `requestJson` appends nothing implicitly and there is no v2 cache buster — and it matches the already-strict body slice. Third-party callers appending a tracking tag or cache buster do break, which is why `api-reference/getting-started.mdx` documents the behavior rather than leaving it to be discovered from a 400. + +Query and body schemas are **`.strict()`** — and `.strict()` binds the **top level only**. A strict body containing a non-strict nested object still drops unknown keys one level down, which is the headline `filter` bug at a smaller scale: `sort: [{ field, direction, nulls: 'last' }]` answered 200 and ordered by the default. Strictness belongs on the shared nested schema (`sortSpecSchema`'s element, `tableViewConfigSchema`), not restated per body. + +Before tightening a schema that is **also** a response or a stored blob, make the read canonical first. `table_views.config` is schemaless JSONB, so a legacy row carrying a retired key would fail a newly strict response parse and become a 500; `normalizeStoredViewConfig` projects the stored blob onto the declared keys so the tightening is safe in both directions. Zod strips unknown keys by default, so a non-strict schema answers `?limit=1` with 200 and the whole set — the caller believes it bounded the response and it did not. That is a contract lie, and on an uncapped list it is also an unbounded-response risk. + +Error messages name the field and, where there is one, the escape hatch: + +``` +limit must be a whole number +limit cannot exceed 100 +search cannot be empty +sortBy: expected one of "name" | "createdAt" | "updatedAt" +Limit cannot exceed 1000; use limit=0 to stream all rows, or create an export +``` + +That last one is the standard to aim for. A message that only says `Invalid input` fails this rule — the caller cannot act on it. + +## Rule 5 — contract first, then use case, then route + +Order matters because each layer is checked against the one before it. + +1. **Contract** in `lib/api/contracts/v2/.ts` via `defineRouteContract`. Response schemas are `.parse`d on the way out, so a field the producer does not actually emit becomes a 500 on a successful read — assert only what you can prove. +2. **Application use case** owns canonical loading, authorization, business behavior, and audit. The route's `present` receives the use-case result **and the parsed request**, so a presenter reads request params (the active `sortBy`/`sortOrder` and filters it stamps into a cursor) straight from `query`/`params` rather than making the use case carry an HTTP concern back out. +3. **Route** with `defineV2JsonRoute`, declaring `contract`, `auth: v2ApiKeyAuth`, `operation`, `rateLimit`, `errorPolicy`, `mapInput`, `useCase`, `present`. Auth and rate limiting run before parsing. +4. **OpenAPI description** in `lib/api/contracts/v2/openapi/.ts`, then `bun run generate:openapi`. A description that claims behaviour the route does not have is the same class of bug as a wrong schema. + +### Public descriptions + +Use the [API description conventions](../../../apps/sim/lib/api/contracts/v2/openapi/README.md) when writing or auditing endpoint and field descriptions. Keep a short action-and-resource summary; use the description for behavior that changes the caller's choice, input, interpretation, or next action. Ordinary operations usually need one to three sentences, with no mandatory minimum. + +Keep archive versus permanent-delete behavior, replacement versus partial-update semantics, partial success, retry safety, redaction, and asynchronous completion explicit. Verify these claims against the implementation. Describe observable behavior without exposing storage formats, locking mechanisms, internal identifiers, deployment architecture, or implementation history unless that detail changes how the caller must use the API. + +Reuse wording across resource families when behavior matches: “Omitted fields remain unchanged,” “Archive,” and “permanently delete.” Prefer “during the request” or “asynchronously” to “settled inline.” Preserve real semantic differences; do not standardize them away. + +Put field-specific rules in the source schema and reuse shared authentication and pagination wording. Shared schema descriptions also feed CLI help, so refer to related operation names rather than HTTP paths. Regenerate OpenAPI, CLI metadata, and CLI docs after changing their source descriptions; never hand-edit generated output. + +## Rule 6 — a transient failure says when to come back + +A response the caller is *expected* to retry must say how long to wait. Two statuses qualify, and both are wired: + +| Status | Source of the value | Where | +|---|---|---| +| 429 | The caller's own token bucket (`retryAfterMs`, else `resetAt - now`) | `v2RateLimitError` | +| 503 | A fixed floor, `RETRY_AFTER_SECONDS_BY_STATUS` | `v2Error`, applied automatically | + +The 503 default is applied by `v2Error` keyed on the response *status* — `Retry-After` is defined against the status, and the status is the only half of the code/status pair a client sees — so every 503 the surface can emit carries it — the three route builders' `unhandledErrorResponse`, the execute and resume routes, and `serviceFailureResponse`'s `infra` failures. A route with a better number passes `headers: { 'Retry-After': … }` and wins. + +Do not add a default for any other code. 400/403/404/409 are not fixed by waiting, and 402 (`USAGE_LIMIT_EXCEEDED`) is resolved by a billing change, not by time. + +**Where a policy already knows the wait, carry it — do not re-guess it at the transport.** The admission descriptors in `lib/core/admission/transient-failure` declare `retryAfterSeconds` per denial. Carry it the whole way: `descriptor.retryAfterSeconds → PreprocessExecutionError.retryAfterMs → ExecuteWorkflowServiceFailure.retryAfterMs → serviceFailureResponse`; a mapping that drops it turns a concurrency denial into a bare 429 with no `Retry-After` even though the policy named the wait. The `v2Error` default is the floor for paths with *no* policy signal, not the source of truth. + +**A failure whose outcome is unknown must not advise a retry.** `ASYNC_ENQUEUE_AMBIGUOUS` is a 503 whose enqueue may have succeeded — it deliberately retains its execution-ID claim. Telling that caller to come back in 5 seconds invites a client with no `X-Run-Id` to start and bill a second run. It passes `omitRetryAfter: true` and returns the run id so the caller reconciles instead. Any future "we don't know if it happened" failure does the same. + +RFC 9110 §10.2.3 gives 503 this field's clearest meaning — "how long the service is expected to be unavailable to the client". Note the requirement level is only `MAY`, on 503 (§15.6.4) and, via RFC 6585 §4, on 429. It is `SHOULD` on exactly one status, 413, and only when the condition is temporary; none of Sim's 413s are temporary — they are fixed ceilings, on the request body and on the collections a response must materialize — so it correctly sends none. ## Deliberate non-adoptions -Audited against the RFCs and Stripe, GitHub and Google AIPs; reopen only with new evidence. +Audited against the primary specs and against Stripe, GitHub, and Google's AIPs. Each is a considered "no", not an oversight. Re-open one only with new evidence. + +| Practice | Verdict | Why | +|---|---|---| +| **RFC 9457 `application/problem+json`** | No | 9457 §4 steers APIs with an existing format toward keeping it: "Problem details are intended to avoid the necessity of establishing new 'fault' or 'error' document formats, **not to replace existing domain-specific formats**." Nothing in it is a `MUST` to adopt, and none of Stripe, GitHub, or Google use it. Our envelope is load-bearing for every client. **The default error shape does not change.** | +| **`RateLimit`/`RateLimit-Policy` (IETF draft)** | No | Still an unpublished IETF draft whose wire format has changed incompatibly across revisions — anything built against an earlier revision is already broken. None of the three surveyed APIs emit it; GitHub uses `x-ratelimit-*`, as we do. Re-check the draft's status before re-opening. | +| **Renaming `X-RateLimit-*` per RFC 6648** | No | 6648 is a `SHOULD NOT` binding *creators of new* parameters, and §1 item 4 "**makes no recommendation as to whether existing 'X-' parameters ought to remain in use or be migrated**". Appendix B argues the migration is itself the interoperability harm. A rename is a client-visible break bought with nothing. | +| **`X-RateLimit-Reset` as delta-seconds** | No | It is an absolute ISO 8601 timestamp, so it is clock-skew sensitive — but the response where timing actually decides behaviour (429) also carries `Retry-After`, which is skew-free. The absolute value stays useful for scheduling. | +| **422 for semantic validation** | No | RFC 9110 §15.5.21 defines 422, but Appendix B.3 records that 9110 **deleted** RFC 4918's clause saying 400 was inappropriate. 400 covers "cannot or will not process… perceived to be a client error". The split is convention, not requirement — GitHub splits, Stripe and Google do not. Our machine-readable `error.code` already carries the distinction, and restatusing now breaks clients. | +| **`Location` on 201** | No | §9.3.3 makes this a `SHOULD` **for POST**; the status code itself (§15.3.2) requires nothing and defines the fallback — absent `Location`, the target URI identifies the resource. Declined knowingly: several 201 responses (signed upload sessions, table exports, knowledge folders) have no canonical single-resource GET, so a `Location` would 404, and adopting it on some of the 19 is worse for a client than on none. Every 201 returns the full representation including its `id`. Revisit per-route if one gains a canonical GET. | +| **ETag / `If-None-Match` / `If-Match`** | No | Every v2 response is `Cache-Control: private, no-store` per-caller data, so `If-None-Match` buys nothing. The exception is a content-addressed read (the source catalog) that sets the route builder's `entityTag`: its 200 and 304 say `private, no-cache`, so the client keeps the body and revalidates it. For writes, `If-Match` needs a **strong** validator: §8.8.3.2's strong comparison fails if *either* tag is weak, so a weak ETag silently makes every `If-Match` fail. None of the three surveyed APIs does HTTP optimistic concurrency — Google does the semantics via a resource `etag` **field** (AIP-154), deliberately not the header. If Sim needs optimistic concurrency, do it that way. | +| **`Deprecation` / `Sunset` on v1** | Not yet | RFC 9745 (Standards Track) and RFC 8594 (Informational) both apply, and GitHub emits both. But `Sunset` is a timestamp and 9745 §4 makes `Sunset >= Deprecation` a `MUST`, so emitting either commits Sim to a v1 retirement date — a product decision, not an engineering one. When that date exists: `Deprecation` is an RFC 9651 Structured Field **Date** (`@1688169599`); `Sunset` is an **HTTP-date** (`Sat, 31 Dec 2033 23:59:59 GMT`). Two encodings in one response — the most common implementation error here. | +| **`application/merge-patch+json`** | No | v2 PATCH bodies are merge-patch *shaped* — absent means unchanged, `null` clears — but they are `.strict()`, so unknown members are rejected where RFC 7396 §2 would merge them, and nested objects are replaced wholesale rather than merged. Advertising the media type would over-claim. Document the semantics per contract instead. | + +## Idempotency: at-most-once, not replay + +`POST /workflows/{id}/execute` accepts `X-Run-Id` from API-key and OAuth callers; anonymous requests ignore it. It is a **uniqueness claim, not an idempotency key**: + +- An available ID is claimed before execution starts. +- An already claimed ID returns **409** with `error.details.code: "RUN_ID_CONFLICT"`, the run id in `error.details.runId`, and an `X-Run-Id` response header. It never replays the earlier run's result. Get Workflow Run can retrieve an existing run, but a claim does not guarantee a retrievable run. +- IDs of runs that started remain reserved after their execution logs are deleted. +- An ambiguous enqueue can retain the claim indefinitely without creating a retrievable run. A **409** followed by **404** is an unresolved outcome, not proof that execution never started or that the ID will become reusable. + +For an uncertain execution outcome, reuse the same run ID if retrying and check Get Workflow Run. Do not promise polling will eventually find a run. If the outcome cannot be verified, do not automatically restart with a fresh ID or an omitted header: either can start another execution. Failures before a run starts can release the claim, so phrase the conflict rule as an ID that is already claimed. + +That makes the money path safe against double-execution **for callers that opt in**. What it is not: a Stripe-style `Idempotency-Key` that stores and replays the original status and body. Building that means a request fingerprint, a retention window, an in-flight-vs-completed distinction (the expired IETF draft would have these be 422 and 409 respectively), and somewhere to put a large synchronous execution body. It is a designed piece of work, not an increment — do not half-build it by aliasing the header name, which would invite clients written against Stripe semantics to treat our 409 as a hard failure. + +## Cursors are opaque, not trusted + +The base64-JSON cursor is **not signed**, and does not need to be. Tampering is bounded by construction, and that is a property to preserve: + +- Every key value is re-validated by its `KeysetKey.bind`, which returns `null` for a wrong-typed or unparseable value and becomes a 400. A forged cursor cannot reach SQL as `NaN` or an `Invalid Date`. +- The sort and a fingerprint of the filters are stamped into the cursor and re-checked (`decodeSortedCursor`), so a cursor from a differently-sorted or differently-filtered query is a 400, not a silently skipped page. The filters are hashed (SHA-256, via `lib/api/cursor-binding.ts`) rather than embedded, so the token stays short and a caller cannot cheaply construct a filter that collides with another sequence's stamp. +- The offset codec rejects anything that is not a non-negative integer. +- Authorization is **never** carried in the cursor. Every list re-derives its workspace scope from the authenticated principal, so a cursor lifted from another query — or another tenant — can only move the caller within their own authorized result set. + +The consequence to keep true: **never put a resource id, filter, or scope into a cursor and then trust it on the way back.** A cursor is a position hint, never an input to an access decision. + +## Checklist + +Run this against any new or changed v2 endpoint. -- No problem+json (RFC 9457 §4 itself steers existing formats to stay): keep the envelope. -- No `RateLimit` draft headers (unstable draft); keep `X-RateLimit-*` names (RFC 6648 makes no recommendation to migrate existing ones). -- `X-RateLimit-Reset` stays an absolute timestamp; 429 has skew-free `Retry-After`. -- Validation is 400, not 422; `error.code` carries the distinction. -- No `Location` on 201: several 201s (upload sessions, exports, knowledge folders) have no canonical GET, so it would 404. Every 201 returns the full representation with its `id`. -- No ETag/If-Match headers except `entityTag` reads (content-addressed, `private, no-cache`); optimistic concurrency, if needed, uses a resource `etag` field (AIP-154), since a weak header ETag silently fails every `If-Match`. -- No `Deprecation`/`Sunset` on v1 until a retirement date exists (it commits to one). When it does: `Deprecation` is a Structured Field Date (`@1688169599`), `Sunset` an HTTP-date. -- Do not advertise merge-patch+json: bodies are strict and replace nested objects wholesale. Document PATCH semantics per contract. +- [ ] Success body is exactly `{data}` or `{data, nextCursor}`; failures are exactly `{error:{code,message,details?,requestId?}}`, where `v2Error` alone sets `requestId` (the `x-request-id` value). +- [ ] Route uses a shared builder; no hand-built `NextResponse.json`. +- [ ] Query and body schemas are `.strict()`. +- [ ] The contract declares a `query` — `noInputSchema` when the endpoint takes no query params, never omission. +- [ ] No caller-supplied value can produce a 500 — check every numeric param reaches SQL as a validated integer, and that any bound value passed as an argument to a SQL function carries an explicit type. +- [ ] `limit` comes from `v2PaginationFields`, not a hand-written `z.coerce.number()`. +- [ ] If the response carries `nextCursor`, the query accepts `limit` + `cursor` and the query actually applies them. +- [ ] The cursor is bound to every param that filters or orders the sequence, and to none that do not (never `limit`), with the binding declared in `list-pagination.test.ts`. +- [ ] Keyset sorts end in a unique `id` key. +- [ ] The list is classified in `list-pagination.test.ts`. +- [ ] Cross-tenant access answers 404, never 403 — and carries `Cache-Control: private, no-store`, because RFC 9110 §15.5.5 makes 404 heuristically cacheable and an authorization-dependent 404 must never be stored. `v2Error` sets this unconditionally; do not build a v2 response any other way. +- [ ] A retryable failure says when: 429 and 503 carry `Retry-After`. No other status invents one. +- [ ] 403s carry a machine-readable `details.code` from `FORBIDDEN_DETAIL_CODES`, thrown as `ForbiddenOperationError` in the domain rather than attached at the route. +- [ ] Nested objects inside a `.strict()` body are strict too — `.strict()` does not recurse. +- [ ] Ordering uses `sortBy` + `sortOrder`; boolean query params use `booleanQueryFlagSchema`. +- [ ] Validation messages name the field and echo the valid set. +- [ ] Response schema matches every field the route actually emits. +- [ ] OpenAPI description regenerated and truthful about pagination. +- [ ] `bun run type-check` (apps/sim) and `bun run check:audits` pass (includes `check:api-validation:strict`, `check:openapi`, `check:v2-route-table`, `check:cli-api`, `check:mcp-operations`). ## Known gap -A 405 for a verb a route file doesn't export comes from Next before Sim code runs: empty body, no `Allow` header. Fixing it needs rejecting handlers in every route file or a path→methods table in `apps/sim/proxy.ts`; neither exists. Unknown paths are handled by the catch-all. +A 405 on a path that *does* have a route file but does not export that verb is generated by Next.js before any Sim code runs: zero-byte body, no `content-type`, and no `Allow` header, which RFC 9110 §15.5.6 requires. Fixing it means either exporting explicit rejecting handlers from every v2 route file or intercepting in `apps/sim/proxy.ts` with a static path→methods table. Neither is done. Unknown *paths* are handled — the catch-all covers those. diff --git a/.agents/skills/validate-connector/SKILL.md b/.agents/skills/validate-connector/SKILL.md index 459ada2ed1b..0a1a1788296 100644 --- a/.agents/skills/validate-connector/SKILL.md +++ b/.agents/skills/validate-connector/SKILL.md @@ -4,34 +4,358 @@ description: Validate an existing knowledge base connector against its service's argument-hint: [api-docs-url] --- -# Validate Connector +# Validate Connector Skill ## Identify the runtime under review -For **Sim Search**, validate the [live provider registration and access pipeline](../../../apps/sim/lib/sim-search/live/README.md#adding-a-live-search-connector): catalog and metadata parity, both search/read handlers, current member grants, service-source restrictions, safe scoped references, pagination, provenance, and provider failure behavior. Test real localhost setup/search/read with authorized fixtures when available, and keep those results distinct from mocked provider tests. Live Search must not enqueue content indexing or background ACL/directory builds; GitLab still computes request-time permissions or uses current CSV grants. +For **Sim Search**, validate the [live provider registration and access pipeline](../../../apps/sim/lib/sim-search/live/README.md#adding-a-live-search-connector): catalog and metadata parity, both search/read handlers, current member grants, service-source restrictions, safe scoped references, pagination, provenance, and provider failure behavior. Test real localhost setup/search/read with authorized fixtures when available, and distinguish those results from mocked provider tests. Live Search must not enqueue content indexing or background ACL/directory builds; GitLab still computes request-time permissions or uses current CSV grants. -The checks below apply to ordinary workspace KB connectors only. Don't require a live-only provider to implement content hashes, ingestion cursors, embeddings, or stored ACL snapshots. +The ingestion-specific checks below apply to ordinary workspace KB connectors only. Do not require a live-only provider to implement content hashes, ingestion cursors, embeddings, or stored ACL snapshots. -The rules are in `/add-connector`; this skill is the audit procedure. Read every file in `apps/sim/connectors/{service}/`, its two registry entries, and its OAuth service, and apply the `validate-selector` skill to any selector key. The official API docs are the source of truth; note any claim you could only check against training knowledge, and report unknown schemas instead of guessing. +You are an expert auditor for Sim knowledge base connectors. Your job is to thoroughly validate that an existing connector is correct, complete, and follows all conventions. -## Checks +## Your Task -**Requests.** URLs, methods, auth headers, service headers (`Notion-Version`), and body fields match the docs; optional fields are omitted rather than sent empty. User values in query languages are escaped: OData `$filter` doubles single quotes, SOQL escapes them with `\'`, GraphQL passes variables instead of interpolating. URL-type config fields are trimmed and normalized (scheme, trailing slash) to what the API expects. +When the user asks you to validate a connector: +1. Read the service's API documentation (via Context7 or WebFetch) +2. Read the connector implementation, OAuth config, and registry entries +3. Cross-reference everything against the API docs and Sim conventions +4. Report all issues found, grouped by severity (critical, warning, suggestion) +5. Fix all issues after reporting them -**Scopes.** Every scope in `requiredScopes` is real, exists in the provider's `OAUTH_PROVIDERS` entry (otherwise the connector fails at runtime), and covers every endpoint the connector calls, with nothing extra. Check the provider's token refresh settings (`useBasicAuth`, `supportsRefreshTokenRotation`, token URL) in `getProviderAuthConfig` (`apps/sim/lib/oauth/refresh.server.ts`). +## Step 1: Gather All Files -**Pagination.** Cursor names and `hasMore` follow the docs; a `maxItems` cap is applied across pages through `syncContext.totalDocsFetched`, with the last page requesting `Math.min(PAGE_SIZE, remaining)`; page size stays within the API maximum; no undocumented ceiling (HubSpot search stops at 10k) is hit silently. Every truncation path sets `listingCapped` per `/add-connector`. Cross-page state (user names, field maps, instance URLs) is cached in `syncContext`. +Read **every** file for the connector — do not skip any: -**Documents.** Deferral and `contentHash` per `/add-connector`. Content is not silently dropped (nested blocks, tables, code) or truncated without a warning, blank documents are filtered, and byte limits use `Buffer.byteLength`, not `text.length`. `externalId` is stable; `title` has a fallback. +``` +apps/sim/connectors/{service}/meta.ts # ConnectorMeta — client-safe metadata (icon, name, auth, configFields, tagDefinitions) +apps/sim/connectors/{service}/{service}.ts # Connector implementation — spreads the meta + runtime functions +apps/sim/connectors/{service}/index.ts # Barrel export +apps/sim/connectors/registry.server.ts # Server-only full registry entry (CONNECTOR_REGISTRY; full connector) +apps/sim/connectors/registry.ts # Client-safe meta registry entry (CONNECTOR_META_REGISTRY) +apps/sim/connectors/types.ts # ConnectorMeta / ConnectorConfig interfaces, ExternalDocument, etc. +apps/sim/connectors/utils.ts # Shared utilities (computeContentHash, htmlToPlainText, etc.) +apps/sim/lib/oauth/oauth.ts # OAUTH_PROVIDERS — single source of truth for scopes +apps/sim/lib/oauth/utils.ts # getCanonicalScopesForProvider, getScopesForService, SCOPE_DESCRIPTIONS +apps/sim/lib/oauth/types.ts # OAuthService union type +apps/sim/components/icons.tsx # Icon definition for the service +``` -**Tags.** Every `tagDefinitions` id is produced by `mapTags` and vice versa, `fieldType` matches the data, numbers are checked for `NaN`, and the metadata keys read exist in what `listDocuments`/`getDocument` store. +If the connector uses selectors, also read: +``` +apps/sim/lib/selectors/manifest.ts # Browser-safe exhaustive metadata +apps/sim/lib/selectors/types.ts # Selector context and option types +apps/sim/lib/selectors/context.ts # Active canonical context projection +apps/sim/lib/selectors/server/registry.ts # Exhaustive server attachments +apps/sim/lib/selectors/server/providers/* # Matching provider attachment +``` -**Config and validation.** Every config field sets `required` explicitly. `validateConfig` checks required and numeric fields first, makes one lightweight call, uses `VALIDATE_RETRY_OPTIONS`, and returns friendly `{ valid: false, error }` messages. +Apply the `validate-selector` skill to the matching key and provider primitive. There is no client +provider selector registry. -**`getDocument`.** Returns `null` on 404, handles every type `listDocuments` emits (pages *and* blogposts), forwards `syncContext` when it needs cached state, and doesn't re-fetch data the first response already held. +## Step 2: Pull API Documentation -**Efficiency and isolation.** Where the API supports field selection (`$select`, `fields`), it is used in both list and get; per-item calls batched with a concurrency of 3–5, never an unbounded `Promise.all`; one document's failure is logged without aborting the sync; error messages carry status codes. +Fetch the official API docs for the service. This is the **source of truth** for: +- Endpoint URLs, HTTP methods, and auth headers +- Required vs optional parameters +- Parameter types and allowed values +- Response shapes and field names +- Pagination patterns (cursor, offset, next token) +- Rate limits and error formats +- OAuth scopes and their meanings -## Report and fix +Use Context7 (resolve-library-id → query-docs) or WebFetch to retrieve documentation. If both fail, note which claims are based on training knowledge vs verified docs. -Report as **Critical** (data loss, including a missing `listingCapped`; auth or scope failures; query injection; per-document downloads during listing; a hash mismatch between stub and full document; a server import in `meta.ts` or a missing meta registry entry, which breaks the client bundle or the UI; a selector boundary break), **Warning** (data quality and conventions: raw HTML, unforwarded `syncContext`, single-type `getDocument`, tag gaps, refresh config, unnormalized URLs, silent truncation), and **Suggestion** (efficiency: incremental sync, field selection, batching, deterministic `orderBy`). Fix every critical and warning, and suggestions where cheap. +### Hard Rule: No Guessed Source Schemas + +If the service docs do not clearly show document list responses, document fetch responses, metadata fields, or pagination shapes, you MUST tell the user instead of guessing. + +- Do NOT infer document fields from unrelated endpoints +- Do NOT guess pagination cursors or response wrappers +- Do NOT assume metadata keys that are not documented +- Do NOT treat probable shapes as validated + +If a schema is unknown, validation must explicitly recommend: +1. sample API responses, +2. live test credentials, or +3. trimming the connector to only documented fields. + +## Step 3: Validate API Endpoints + +For **every** API call in the connector (`listDocuments`, `getDocument`, `validateConfig`, and any helper functions), verify against the API docs: + +### URLs and Methods +- [ ] Base URL is correct for the service's API version +- [ ] Endpoint paths match the API docs exactly +- [ ] HTTP method is correct (GET, POST, PUT, PATCH, DELETE) +- [ ] Path parameters are correctly interpolated and URI-encoded where needed +- [ ] Query parameters use correct names and formats per the API docs + +### Headers +- [ ] Authorization header uses the correct format: + - OAuth: `Authorization: Bearer ${accessToken}` + - API Key: correct header name per the service's docs +- [ ] `Content-Type` is set for POST/PUT/PATCH requests +- [ ] Any service-specific headers are present (e.g., `Notion-Version`, `Dropbox-API-Arg`) +- [ ] No headers are sent that the API doesn't support or silently ignores + +### Request Bodies +- [ ] POST/PUT body fields match API parameter names exactly +- [ ] Required fields are always sent +- [ ] Optional fields are conditionally included (not sent as `null` or empty unless the API expects that) +- [ ] Field value types match API expectations (string vs number vs boolean) + +### Input Sanitization +- [ ] User-controlled values interpolated into query strings are properly escaped: + - OData `$filter`: single quotes escaped with `''` (e.g., `externalId.replace(/'/g, "''")`) + - SOQL: single quotes escaped with `\'` + - GraphQL variables: passed as variables, not interpolated into query strings + - A single ID URL path segment: `safeUrlPathSegment(value, 'paramName')` from `@/tools/url-path`; query values: `encodeURIComponent()` +- [ ] URL-type config fields (e.g., `siteUrl`, `instanceUrl`) are normalized: + - Strip `https://` / `http://` prefix if the API expects bare domains + - Strip trailing `/` + - Apply `.trim()` before validation + +### Response Parsing +- [ ] Response structure is correctly traversed (e.g., `data.results` vs `data.items` vs `data`) +- [ ] Field names extracted match what the API actually returns +- [ ] Nullable fields are handled with `?? null` or `|| undefined` +- [ ] Error responses are checked before accessing data fields +- [ ] Every extracted field and pagination value is backed by official docs or live-verified sample payloads + +## Step 4: Validate OAuth Scopes (if OAuth connector) + +Scopes must be correctly declared and sufficient for all API calls the connector makes. + +### Connector requiredScopes +- [ ] `requiredScopes` in the connector's `auth` config lists all scopes needed by the connector +- [ ] Each scope in `requiredScopes` is a real, valid scope recognized by the service's API +- [ ] No invalid, deprecated, or made-up scopes are listed +- [ ] No unnecessary excess scopes beyond what the connector actually needs + +### Scope Subset Validation +- [ ] Every scope in `requiredScopes` exists in the OAuth provider's `scopes` array in `lib/oauth/oauth.ts` +- [ ] Find the provider in `OAUTH_PROVIDERS[providerGroup].services[serviceId].scopes` +- [ ] Verify: `requiredScopes` ⊆ `OAUTH_PROVIDERS scopes` (every required scope is present in the provider config) +- [ ] If a required scope is NOT in the provider config, flag as **critical** — the connector will fail at runtime + +### Scope Sufficiency +For each API endpoint the connector calls: +- [ ] Identify which scopes are required per the API docs +- [ ] Verify those scopes are included in the connector's `requiredScopes` +- [ ] If the connector calls endpoints requiring scopes not in `requiredScopes`, flag as **warning** + +### Token Refresh Config +- [ ] Check the provider's entry in `getProviderAuthConfig` (`lib/oauth/oauth.ts`) +- [ ] `useBasicAuth` matches the service's token exchange requirements +- [ ] `supportsRefreshTokenRotation` matches whether the service issues rotating refresh tokens +- [ ] Token endpoint URL is correct + +## Step 5: Validate Pagination + +### listDocuments Pagination +- [ ] Cursor/pagination parameter name matches the API docs +- [ ] Response pagination field is correctly extracted (e.g., `next_cursor`, `nextPageToken`, `@odata.nextLink`, `offset`) +- [ ] `hasMore` is correctly determined from the response +- [ ] `nextCursor` is correctly passed back for the next page +- [ ] `maxItems` / `maxRecords` cap is correctly applied across pages using `syncContext.totalDocsFetched` +- [ ] Page size is within the API's allowed range (not exceeding max page size) +- [ ] Last page precision: when a `maxItems` cap exists, the final page request uses `Math.min(PAGE_SIZE, remaining)` to avoid fetching more records than needed +- [ ] No off-by-one errors in pagination tracking +- [ ] The connector does NOT hit known API pagination limits silently (e.g., HubSpot search 10k cap) + +### Deletion-Reconciliation Safety (`listingCapped`) +The sync engine tombstones, then hard-deletes, any stored document absent from a full listing. Audit every path where `listDocuments` can return less than the full source set: +- [ ] `syncContext.listingCapped = true` is set when a `maxItems`-style cap truncates the listing while more documents exist +- [ ] `listingCapped` is set when a transient per-item error drops a still-existing document from the listing +- [ ] `listingCapped` is NOT set when the source is genuinely exhausted (deleted documents must reconcile) or for intentional scope filters (date cutoffs) +Verify it against the `checkpoint.unsafe` computation in `lib/knowledge/connectors/listing-checkpoint.ts`. + +### Pagination State Across Pages +- [ ] `syncContext` is used to cache state across pages (user names, field maps, instance URLs, portal IDs, etc.) +- [ ] Cached state in `syncContext` is correctly initialized on first page and reused on subsequent pages + +## Step 6: Validate Data Transformation + +### Content Deferral +Connectors that require per-document API calls to fetch content (file download, export, blocks fetch) MUST use `contentDeferred: true`. This is the standard pattern for reliability — without it, content downloads during listing can exhaust the sync task's time budget before any documents are saved. + +- [ ] If the connector downloads content per-doc during `listDocuments`, it MUST use `contentDeferred: true` instead +- [ ] `listDocuments` returns lightweight stubs with `content: ''` and `contentDeferred: true` +- [ ] `getDocument` fetches actual content and returns the full document with `contentDeferred: false` +- [ ] A shared stub function (e.g., `fileToStub`) is used by both `listDocuments` and `getDocument` to guarantee `contentHash` consistency +- [ ] `contentHash` is metadata-based (e.g., `service:{id}:{modifiedTime}`), NOT content-based — it must be derivable from list metadata alone +- [ ] The `contentHash` is identical whether produced by `listDocuments` or `getDocument` + +Connectors where the list API already returns content inline (e.g., Slack messages, Reddit posts) do NOT need `contentDeferred`. + +### ExternalDocument Construction +- [ ] `externalId` is a stable, unique identifier from the source API +- [ ] `title` is extracted from the correct field and has a sensible fallback (e.g., `'Untitled'`) +- [ ] `content` is plain text — HTML content is stripped using `htmlToPlainText` from `@/connectors/utils` +- [ ] `mimeType` is `'text/plain'` for extracted text, or the document hands over `sourceFile` for a format the KB pipeline parses +- [ ] `contentHash` uses a metadata-based format (e.g., `service:{id}:{modifiedTime}`) for connectors with `contentDeferred: true`, or `computeContentHash` from `@/connectors/utils` for inline-content connectors +- [ ] `sourceUrl` is a valid, complete URL back to the original resource (not relative) +- [ ] `metadata` contains all fields referenced by `mapTags` and `tagDefinitions` + +### Content Extraction +- [ ] Rich text / HTML fields are converted to plain text before indexing +- [ ] Important content is not silently dropped (e.g., nested blocks, table cells, code blocks) +- [ ] Content is not silently truncated without logging a warning +- [ ] Empty/blank documents are properly filtered out +- [ ] Size checks use `Buffer.byteLength(text, 'utf8')` not `text.length` when comparing against byte-based limits (e.g., `MAX_FILE_SIZE` in bytes) + +## Step 7: Validate Tag Definitions and mapTags + +### tagDefinitions +- [ ] Each `tagDefinition` has an `id`, `displayName`, and `fieldType` +- [ ] `fieldType` matches the actual data type: `'text'` for strings, `'number'` for numbers, `'date'` for dates, `'boolean'` for booleans +- [ ] Every `id` in `tagDefinitions` is returned by `mapTags` +- [ ] No `tagDefinition` references a field that `mapTags` never produces + +### mapTags +- [ ] Return keys match `tagDefinition` `id` values exactly +- [ ] Date values are properly parsed using `parseTagDate` from `@/connectors/utils` +- [ ] Array values are properly joined using `joinTagArray` from `@/connectors/utils` +- [ ] Number values are validated (not `NaN`) +- [ ] Metadata field names accessed in `mapTags` match what `listDocuments`/`getDocument` store in `metadata` + +## Step 8: Validate Config Fields and Validation + +### configFields +- [ ] Every field has `id`, `title`, `type` +- [ ] `required` is set explicitly (not omitted) +- [ ] Dropdown fields have `options` with `label` and `id` for each option +- [ ] Selector fields follow the canonical pair pattern: + - A `type: 'selector'` field with `selectorKey`, `canonicalParamId`, `mode: 'basic'` + - A `type: 'short-input'` field with the same `canonicalParamId`, `mode: 'advanced'` + - `required` is identical on both fields in the pair +- [ ] `dependsOn` references selector field `id` values, not `canonicalParamId` +- [ ] Each selector key passes the `validate-selector` skill + +### validateConfig +- [ ] Validates all required fields are present before making API calls +- [ ] Validates optional numeric fields (checks `Number.isNaN`, positive values) +- [ ] Makes a lightweight API call to verify access (e.g., fetch 1 record, get profile) +- [ ] Uses `VALIDATE_RETRY_OPTIONS` for retry budget +- [ ] Returns `{ valid: true }` on success +- [ ] Returns `{ valid: false, error: 'descriptive message' }` on failure +- [ ] Catches exceptions and returns user-friendly error messages +- [ ] Does NOT make expensive calls (full data listing, large queries) + +## Step 9: Validate getDocument + +- [ ] Fetches a single document by `externalId` +- [ ] Returns `null` for 404 / not found (does not throw) +- [ ] Returns the same `ExternalDocument` shape as `listDocuments` +- [ ] If `listDocuments` uses `contentDeferred: true`, `getDocument` MUST fetch actual content and return `contentDeferred: false` +- [ ] If `listDocuments` uses `contentDeferred: true`, `getDocument` MUST use the same stub function to ensure `contentHash` is identical +- [ ] Handles all content types that `listDocuments` can produce (e.g., if `listDocuments` returns both pages and blogposts, `getDocument` must handle both — not hardcode one endpoint) +- [ ] Forwards `syncContext` if it needs cached state (user names, field maps, etc.) +- [ ] Error handling is graceful (catches, logs, returns null or throws with context) +- [ ] Does not redundantly re-fetch data already included in the initial API response (e.g., if comments come back with the post, don't fetch them again separately) + +## Step 10: Validate General Quality + +### fetchWithRetry Usage +- [ ] All external API calls use `fetchWithRetry` (or `secureFetchWithRetry` for user-controlled hosts) from `@/lib/knowledge/documents/secure-fetch.server` +- [ ] No raw `fetch()` calls to external APIs +- [ ] `VALIDATE_RETRY_OPTIONS` used in `validateConfig` +- [ ] If `validateConfig` calls a shared helper (e.g., `linearGraphQL`, `resolveId`), that helper must accept and forward `retryOptions` to `fetchWithRetry` +- [ ] Default retry options used in `listDocuments`/`getDocument` + +### API Efficiency +- [ ] APIs that support field selection (e.g., `$select`, `sysparm_fields`, `fields`) should request only the fields the connector needs — in both `listDocuments` AND `getDocument` +- [ ] No redundant API calls: if a helper already fetches data (e.g., site metadata), callers should reuse the result instead of making a second call for the same information +- [ ] Sequential per-item API calls (fetching details for each document in a loop) should be batched with `Promise.all` and a concurrency limit of 3-5 + +### Error Handling +- [ ] Individual document failures are caught and logged without aborting the sync +- [ ] API error responses include status codes in error messages +- [ ] No unhandled promise rejections in concurrent operations + +### Concurrency +- [ ] Concurrent API calls use reasonable batch sizes (3-5 is typical) +- [ ] No unbounded `Promise.all` over large arrays + +### Logging +- [ ] Uses `createLogger` from `@sim/logger` (not `console.log`) +- [ ] Logs sync progress at `info` level +- [ ] Logs errors at `warn` or `error` level with context + +### Meta / Runtime Split +- [ ] `connectors/{service}/meta.ts` exports `{service}ConnectorMeta: ConnectorMeta` (id, name, description, version, icon, auth, configFields, and any `tagDefinitions` / `supportsIncrementalSync`) +- [ ] `meta.ts` imports ONLY the icon from `@/components/icons`, `ConnectorMeta` (type-only), and pure-data constants — NO server/runtime imports (`@/lib/knowledge/...`, `input-validation.server`, `fetchWithRetry`, etc.); any such import in `meta.ts` is **critical** (breaks the client bundle) +- [ ] `connectors/{service}/{service}.ts` spreads `...{service}ConnectorMeta` as the first property and adds the runtime functions (`listDocuments`, `getDocument`, `validateConfig`, `mapTags?`) +- [ ] Metadata fields (id, name, auth, configFields, etc.) live ONLY in `meta.ts`, not duplicated in `{service}.ts` + +### Registry +- [ ] Connector is exported from `connectors/{service}/index.ts` +- [ ] Full connector is registered in `connectors/registry.server.ts` (server-only registry, `CONNECTOR_REGISTRY`) +- [ ] Meta is registered in `connectors/registry.ts` (client-safe registry, `CONNECTOR_META_REGISTRY`), importing `@/connectors/{service}/meta` +- [ ] Both registries use the same key and it matches the connector's `id` field +- [ ] Both registries keep the same alphabetical-by-id ordering + +## Step 11: Report and Fix + +### Report Format + +Group findings by severity: + +**Critical** (will cause runtime errors, data loss, or auth failures): +- Wrong API endpoint URL or HTTP method +- Invalid or missing OAuth scopes (not in provider config) +- Incorrect response field mapping (accessing wrong path) +- SOQL/query fields that don't exist on the target object +- Pagination that silently hits undocumented API limits +- Missing `syncContext.listingCapped = true` when a cap or transient error truncates the listing — the sync engine tombstones and later hard-deletes the documents absent from the partial listing +- Missing error handling that would crash the sync +- `requiredScopes` not a subset of OAuth provider scopes +- Query/filter injection: user-controlled values interpolated into OData `$filter`, SOQL, or query strings without escaping +- Per-document content download in `listDocuments` without `contentDeferred: true` — causes sync timeouts for large document sets +- `contentHash` mismatch between `listDocuments` stub and `getDocument` return — causes unnecessary re-processing every sync +- Server/runtime import in `meta.ts` (e.g. `@/lib/knowledge/...`, `input-validation.server`, `fetchWithRetry`) — pulls server-only code into the client bundle and breaks the build +- Connector missing from `connectors/registry.ts` (the client-safe meta registry) — or its entry there imports the runtime module instead of `meta.ts` — the knowledge UI can't render it +- A connector selector resolves shared secrets in the browser, lacks scope or credential provider + binding, combines hidden authentication with an unsafe user-controlled destination, or forwards + protected/provider payload data to the client + +**Warning** (incorrect behavior, data quality issues, or convention violations): +- HTML content not stripped via `htmlToPlainText` +- `getDocument` not forwarding `syncContext` +- `getDocument` hardcoded to one content type when `listDocuments` returns multiple (e.g., only pages but not blogposts) +- Missing `tagDefinition` for metadata fields returned by `mapTags` +- Incorrect `useBasicAuth` or `supportsRefreshTokenRotation` in token refresh config +- Invalid scope names that the API doesn't recognize (even if silently ignored) +- Private resources excluded from name-based lookup despite scopes being available +- Silent data truncation without logging +- Size checks using `text.length` (character count) instead of `Buffer.byteLength` (byte count) for byte-based limits +- URL-type config fields not normalized (protocol prefix, trailing slashes cause API failures) +- `VALIDATE_RETRY_OPTIONS` not threaded through helper functions called by `validateConfig` + +**Suggestion** (minor improvements): +- Missing incremental sync support despite API supporting it +- Overly broad scopes that could be narrowed (not wrong, but could be tighter) +- Source URL format could be more specific +- Missing `orderBy` for deterministic pagination +- Redundant API calls that could be cached in `syncContext` +- Sequential per-item API calls that could be batched with `Promise.all` (concurrency 3-5) +- API supports field selection but connector fetches all fields (e.g., missing `$select`, `sysparm_fields`, `fields`) +- `getDocument` re-fetches data already included in the initial API response (e.g., comments returned with post) +- Last page of pagination requests full `PAGE_SIZE` when fewer records remain (`Math.min(PAGE_SIZE, remaining)`) + +### Fix All Issues + +After reporting, fix every **critical** and **warning** issue. Apply **suggestions** where they don't add unnecessary complexity. + +### Validation Output + +After fixing, confirm: +1. `bun run lint` passes +2. TypeScript compiles clean +3. Re-read all modified files to verify fixes are correct +4. Any remaining unknown source schemas were explicitly reported to the user instead of guessed + +## Checklist Summary + +Before reporting, confirm every step above was checked, issues are grouped by severity, critical and warning fixes are applied, and `bun run lint` plus type-check pass. diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index 4b6f43b9d0e..0d6b2098728 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -4,41 +4,542 @@ description: Validate an existing Sim integration (tools, block, registry, and r argument-hint: [api-docs-url] --- -# Validate Integration +# Validate Integration Skill -The rules live in the authoring guidance; this skill is the audit procedure. Measure against `apps/sim/tools/AGENTS.md`, `apps/sim/blocks/AGENTS.md`, `/add-tools` (effect, resolved secrets), `/add-block` (credentials, BlockMeta), and `/add-integration` (auth, deployment availability, docs intro, versioning). +You are an expert auditor for Sim integrations. Your job is to thoroughly validate that an existing integration is correct, complete, and follows all conventions. -## 1. Read everything +## Your Task -Every file in `apps/sim/tools/{service}/`, the block `apps/sim/blocks/blocks/{service}.ts`, its registry entries, its icon, the OAuth service in `apps/sim/lib/oauth/oauth.ts`, and, for OAuth or service-account integrations, `packages/deployment-config/src/env-capabilities.ts` `packages/deployment-config/src/service-account-metadata.ts`, `apps/sim/lib/oauth/utils.ts` (scopes), `apps/sim/lib/auth/connectors/providers.ts`, `apps/sim/lib/core/config/env.ts`, and `packages/sim-setup/src/capability-config.ts`. If anything uses a `selectorKey`, also run the `validate-selector` skill; if the service has triggers, run `validate-trigger`. +When the user asks you to validate an integration: +1. Read the service's API documentation (via WebFetch or Context7) +2. Read every tool, the block, and registry entries +3. Cross-reference everything against the API docs and Sim conventions +4. Report all issues found, grouped by severity (critical, warning, suggestion) +5. Fix all issues after reporting them -## 2. Pull the API docs +## Step 1: Gather All Files -The official docs are the source of truth for URLs, methods, auth headers, params (required, types, allowed values), response fields, pagination names, and error formats. A claim the docs don't settle is reported as unverified, never guessed. +Read **every** file for the integration — do not skip any: -## 3. Tools +``` +apps/sim/tools/{service}/ # All tool files, types.ts, index.ts +apps/sim/blocks/blocks/{service}.ts # Block definition +apps/sim/tools/registry.ts # Tool registry entries for this service +apps/sim/blocks/registry-maps.ts # Block + meta registry entry (BLOCK_REGISTRY / BLOCK_META_REGISTRY) +apps/sim/components/icons.tsx # Icon definition +apps/sim/lib/auth/connectors/providers.ts # Better Auth connector providers (buildConnectorProviders) — should use getCanonicalScopesForProvider() +apps/sim/lib/oauth/oauth.ts # OAuth provider config — single source of truth for scopes +apps/sim/lib/oauth/utils.ts # Scope utilities, SCOPE_DESCRIPTIONS for modal UI +packages/deployment-config/src/env-capabilities.ts # OAuth client runtime capability source of truth +apps/sim/lib/core/config/env.ts # Runtime env schema for capability fields +packages/sim-setup/src/capability-config.ts # Exhaustive CLI input-mode mapping for OAuth fields +packages/deployment-config/src/integrations.json # Generated client-safe integration catalog +packages/deployment-config/src/service-account-providers.generated.ts # Generated provider-ID facts +packages/deployment-config/src/service-account-metadata.ts # Handwritten deployment policy +``` -For each tool, compare against the docs: +If the block, its triggers, or connector fields use a `selectorKey`, also apply the `validate-selector` skill and read +the key's entry in `apps/sim/lib/selectors/manifest.ts`, its server attachment and provider listing +primitive, and the shared context builder. Selector provider logic runs only server-side through +`selectors.execute`. -- URL, path params, method, auth header format, `Content-Type`, and body: required fields always sent, optional ones only when provided. -- Response traversal (`data.data` vs `data.results`), every mapped field, error checks before data access with specific messages. -- Param requiredness and types; `visibility` (`hidden` only for injected tokens, `user-only` for keys and account ids, `user-or-llm` otherwise); descriptions. -- `effect` by `/add-tools` → Declaring the effect. -- Request fields that reach a model or a Sim-durable sink, by `/add-tools` → Resolved Secrets and Provenance Boundaries. -- Pagination: param and response names match the docs, endpoints with different names get separate subblocks, the next-page token is an output. -- Anything that lists, downloads, uploads, batches, or reads bodies: apply the `memory-load-check` skill, and check every file-producing path, including attachment fetches inside `transformResponse` and old and new block versions, not only download-named tools. +## Step 2: Pull API Documentation -## 4. Block +Fetch the official API docs for the service. This is the **source of truth** for: +- Endpoint URLs, HTTP methods, and auth headers +- Required vs optional parameters +- Parameter types and allowed values +- Response shapes and field names +- Pagination patterns (which param name, which response field) +- Rate limits and error formats -- Each operation maps to the right tool, every required param has a subblock under exactly the operations that use it, subblock types match param types, and `dependsOn` covers cascades. -- `tools.config.params` converts strings to numbers and booleans, turns empty optional dropdowns into `undefined`, and renames only optional or `user-or-llm` params. -- Outputs cover the key fields of all tools, with specific descriptions (never "Response data") and `properties` on known `json` shapes. -- Credentials, BlockMeta, placeholders, modes, `wandConfig`, and canvas sentences per `/add-block` and `apps/sim/blocks/AGENTS.md`. -- Scopes: none hardcoded, none beyond what the tools need, each with a `SCOPE_DESCRIPTIONS` entry. -- Deployment availability per `/add-integration` §6; a missing capability is critical, since runtime availability deliberately throws rather than exposing an unusable integration. +### Hard Rule: No Guessed Response Schemas -## 5. Report and fix +If the official docs do not clearly show the response JSON shape for an endpoint, you MUST tell the user instead of guessing. -Report findings as **Critical** (wrong runtime behaviour: endpoint, method, required params, response mapping, tool id mismatches, coercion in `tools.config.tool`, missing capability, or a broken auth, provenance, or selector security boundary), **Warning** (conventions and usability: visibility, `?? null`, missing `optional`, opaque json, advanced mode, `wandConfig`, hardcoded scopes, condition gaps), and **Suggestion** (descriptions, naming, polish). Fix every critical and warning, and suggestions where cheap. +- Do NOT assume field names from nearby endpoints +- Do NOT infer nested JSON paths without evidence +- Do NOT treat "likely" fields as confirmed outputs +- Do NOT accept implementation guesses as valid just because they are defensive -Then run the root gate, `bun run apps/sim/scripts/check-block-registry.ts origin/staging`, and for OAuth or service-account changes `bun run --cwd apps/sim test lib/integrations/availability.server.test.ts`. Review the regenerated diff (`/add-integration` §7), confirm the docs intro still matches what the block ships, and report any response shape that remains unverified. +If a response schema is unknown, the validation must explicitly call that out and require: +1. sample responses from the user, +2. live test credentials for verification, or +3. trimming the tool/block down to only documented fields. + +## Step 3: Validate Tools + +For **every** tool file, check: + +### Tool ID and Naming +- [ ] Tool ID uses `snake_case`: `{service}_{action}` (e.g., `x_create_tweet`, `slack_send_message`) +- [ ] Tool `name` is human-readable (e.g., `'X Create Tweet'`) +- [ ] Tool `description` is a concise one-liner describing what it does +- [ ] Tool `version` is set (`'1.0.0'` or `'2.0.0'` for V2) + +### Effect +- [ ] Every tool declares `effect`, and the label matches the API docs, not the name (rules: + `add-tools` → Declaring the effect) +- [ ] Any `// tool-effect: ` sits on a genuine verb/label exception, and + `bun run check:tool-effects` passes +- [ ] A dry run (`sim workflows run --dry --input '{…}'` on a workflow using the + block) lists every write operation in `sideEffects.stubbed` (at most 50 entries; the rest + are counted in `sideEffects.omitted.stubbed`) with the request the API docs expect where + `request` is not `null`, and every read runs for real; a write absent from `stubbed` counts + only if its block ran (not on an untaken branch or `--mock`ed) (rules: `add-tools` → + Declaring the effect) +- [ ] A write's `dryRunOutput`, where it declares one, echoes only what its request determines, + provider-assigned ids as `dryRunId(kind, n)`, and shares any param normalisation with the + request builder through a named helper (rules: `add-tools` → Declaring the effect) + +### Params +- [ ] All required API params are marked `required: true` +- [ ] All optional API params are marked `required: false` +- [ ] Every param has explicit `required: true` or `required: false` — never omitted +- [ ] Param types match the API (`'string'`, `'number'`, `'boolean'`, `'json'`) +- [ ] Visibility is correct: + - `'hidden'` — ONLY for OAuth access tokens and system-injected params + - `'user-only'` — for API keys, credentials, and account-specific IDs the user must provide + - `'user-or-llm'` — for everything else (search queries, content, filters, IDs that could come from other blocks) +- [ ] Every param has a `description` that explains what it does + +### Request +- [ ] URL matches the API endpoint exactly (correct base URL, path segments, path params) +- [ ] HTTP method matches the API spec (GET, POST, PUT, PATCH, DELETE) +- [ ] Headers include correct auth pattern: + - OAuth: `Authorization: Bearer ${params.accessToken}` + - API Key: correct header name and format per the service's docs +- [ ] `Content-Type` header is set for POST/PUT/PATCH requests +- [ ] Body sends all required fields and only includes optional fields when provided +- [ ] For GET requests with query params: URL is constructed correctly with query string +- [ ] Each single ID path segment goes through `safeUrlPathSegment(params.id, 'id')` from `@/tools/url-path` (trims, rejects empty, dot, and separator values, then encodes); query values use `encodeURIComponent` or `URLSearchParams` + +### Response / transformResponse +- [ ] Correctly parses the API response (`await response.json()`) +- [ ] Extracts the right fields from the response structure (e.g., `data.data` vs `data` vs `data.results`) +- [ ] All nullable fields use `?? null` +- [ ] All optional arrays use `?? []` +- [ ] Error cases are handled: checks for missing/empty data and returns meaningful error +- [ ] Does NOT do raw JSON dumps — extracts meaningful, individual fields +- [ ] Every extracted field is backed by official docs or live-verified sample payloads + +### Outputs +- [ ] All output fields match what the API actually returns +- [ ] No fields are missing that the API provides and users would commonly need +- [ ] No phantom fields defined that the API doesn't return +- [ ] `optional: true` is set on fields that may not exist in all responses +- [ ] When using `type: 'json'` and the shape is known, `properties` defines the inner fields (tool outputs only — block outputs do not support `properties`) +- [ ] When using `type: 'array'`, `items` defines the item structure with `properties` (tool outputs only) +- [ ] Field descriptions are accurate and helpful + +### Types (types.ts) +- [ ] Has param interfaces for every tool (e.g., `XCreateTweetParams`) +- [ ] Has response interfaces for every tool (extending `ToolResponse`) +- [ ] Optional params use `?` in the interface (e.g., `replyTo?: string`) +- [ ] Field names in types match actual API field names +- [ ] Shared response types are properly reused (e.g., `XTweetResponse` shared across tweet tools) + +### Barrel Export (index.ts) +- [ ] Every tool is exported +- [ ] All types are re-exported (`export * from './types'`) +- [ ] No orphaned exports (tools that don't exist) + +### Tool Registry (tools/registry.ts) +- [ ] Every tool is imported and registered +- [ ] Registry keys use snake_case and match tool IDs exactly +- [ ] Entries are in alphabetical order within the file + +### Resolved-Secret Provenance and Model Input + +For every request field, determine whether it is ordinary API input, model-visible text/structured +content, opaque model input, or a value persisted into Sim-owned durable storage. + +Treat model-input provenance as opt-in. Require official documentation or an unambiguous local +execution path proving that the exact field reaches an AI model. If the evidence is ambiguous, +leave the integration unchanged; do not infer a model boundary merely from natural-language, +search, extraction, or "AI-powered" marketing terminology. + +- [ ] AI-consumed text/structured fields use `request.modelInput` with `mode: 'project'` and a + minimal exact selector; nested/JSON-string adapters preserve shape through `applyProjected` +- [ ] Ordinary external URLs, domains, resource IDs, and control fields retain normal request + semantics unless the exact field is proven model-visible; an AI-backed provider or later model + processing of the referenced resource is not sufficient evidence +- [ ] Serialized content proven to be sent directly to an external model is selected by + `request.modelInput`, projected before the existing formatter parses it, and has deterministic + formatter behavior when a whole-value placeholder is invalid for the serialized grammar +- [ ] Actual inline/raw AI-consumed bytes owned by a registered in-process operation use + `operation.modelInput` with `privateInputPaths` (or `mode: 'private-provenance'`), and the + operation calls `validateOpaqueModelInputProvenance` before model egress; storage keys, paths, signed URLs, + and ordinary remote URLs are not treated as byte provenance, while tracked stored bytes are + authorized independently at the owning model-egress boundary +- [ ] Persisted workspace-file contents are checked with the shared provenance guard only when + their bytes or decoded content cross into a model/tool-result boundary; ordinary file APIs + remain unchanged. Unsupported secret-bearing file paths are rejected at `file_write` +- [ ] Sim-owned durable writes and internal execution handoffs that can enter workflows/models use + field-scoped `operation.secretProvenance`; the owning operation validates the exact selection + and scope, strip private metadata, and persist, import, or propagate it at the owning boundary +- [ ] Private provenance is never attached to external URLs; registered in-process operations + preserve it through `operation.modelInput` / `operation.secretProvenance`, while proven + model-visible external fields use request projection and other external inputs remain unchanged +- [ ] No tool performs raw secret plaintext/source substitution or serializes plaintext provenance +- [ ] No `transformResponse` or tool-local helper blanket-sanitizes ordinary third-party results; + only execution-scoped, activated Sim provenance is projected at shared model/log boundaries +- [ ] Private headers/envelopes are produced and stripped by the shared tool executor, never + hand-rolled or returned as functional output +- [ ] Every added provenance hook has a concrete Sim `{{...}}` resolution path and a later + persistence/model/log crossing; there is no generic handling for arbitrary filenames, + metadata, provider results, or API payloads +- [ ] Diagnostic projection is applied only to values carrying execution-scoped provenance; + ordinary provider responses, filenames, URLs, and errors are unchanged +- [ ] Tests cover named `{{NAME}}` projection, unproven identical public text, nested and serialized + shape handling, unchanged ordinary external inputs, malformed/incomplete metadata, headerless + legacy requests, metadata stripping, and durable legacy/stale/scope cases when applicable + +Treat a missing or bypassed model, durable, or internal-execution provenance boundary as +**critical**. Do not fix it with a tool-specific string replacer or by sanitizing every provider +result; repair the shared request, in-process operation, persistence, or re-entry boundary +that owns the data. + +## Step 4: Validate Block + +### Block ↔ Tool Alignment + +This is the most important validation — the block must be perfectly aligned with every tool it references. + +For **each tool** in `tools.access`: +- [ ] The operation dropdown has an option whose ID matches the tool ID (or the `tools.config.tool` function correctly maps to it) +- [ ] Every **required** tool param (except `accessToken`) has a corresponding subBlock input that is: + - Shown when that operation is selected (correct `condition`) + - Marked as `required: true` (or conditionally required) +- [ ] Every **optional** tool param has a corresponding subBlock input (or is intentionally omitted if truly never needed) +- [ ] Every subBlock `id` is unique (duplicates collide silently; the last definition wins). `blocks.test.ts` fails a duplicate within one condition unless the copies are a basic/advanced mode-swap pair, one basic plus trigger-mode copies, or all carry `canonicalParamId`. The only sanctioned cross-condition reuse is the hosted-key `apiKey` pair (`add-hosted-key` skill) +- [ ] The `tools.config.tool` function returns the correct tool ID for every possible operation value +- [ ] Each subBlock (or its `canonicalParamId`) is named exactly after the tool param it fills. A required `user-only` param that is only renamed in `tools.config.params` fails `bun run apps/sim/scripts/check-block-registry.ts origin/staging`; remap only optional or `user-or-llm` params + +### SubBlocks +- [ ] Operation dropdown lists ALL tool operations available in `tools.access` +- [ ] Dropdown option labels are human-readable and descriptive +- [ ] Conditions use correct syntax: + - Single value: `{ field: 'operation', value: 'x_create_tweet' }` + - Multiple values (OR): `{ field: 'operation', value: ['x_create_tweet', 'x_delete_tweet'] }` + - Negation: `{ field: 'operation', value: 'delete', not: true }` + - Compound: `{ field: 'op', value: 'send', and: { field: 'type', value: 'dm' } }` +- [ ] Condition arrays include ALL operations that use that field — none missing +- [ ] `dependsOn` is set for fields that need other values (selectors depending on credential, cascading dropdowns) +- [ ] SubBlock types match tool param types: + - Enum/fixed options → `dropdown` + - Free text → `short-input` + - Long text/content → `long-input` + - True/false → `switch` (a Yes/No `dropdown` only when the tool needs a third "unset" state) + - Credentials → `oauth-input` with correct `serviceId` + - Every tool with a `credential`/`oauthCredential` param declares `oauth: { required: true, provider }` matching that `serviceId`, plus `credentialKind: 'service-account'` when only service accounts are supported +- [ ] In a new block or credential-only successor, a pasted key, token, or token + host comes from a + saved token credential (add-integration → Token credentials), not an inline `password` field + (legacy blocks keep theirs); a successor changes its legacy block only by `hideFromToolbar` + and `sunset`, and its picker sits under the operation +- [ ] For a token-credential integration, every tool in `tools.access` declares the service's + `tokenCredentialOAuth` policy, every + param that decides the request host is mapped, and the stored domain is in the form the tools + build URLs from (`check-block-registry.ts origin/staging` passes) +- [ ] A non-successor token block's tools declare `oauth: { required: true, provider, + credentialKind: 'service-account' }` and pin every host or account param in + `authoritativeParams` (`check-block-registry` enforces this for every block with a + saved-credential picker) +- [ ] A keyless provider appears in every table in `lib/credentials/workload-identity/audiences.ts` + and in `MIXED_MODE_PROVIDERS` (`prepare-workload-identity.ts`), and the provider catalog + shows `keyless` only when the deployment can sign tokens +- [ ] The `tokenCheckValidator` request uses the tools' host and auth, its normalizers refuse + anything that could steer the host or path, and a fake key is rejected without a valid + scoped key being refused +- [ ] Dropdown `value: () => 'default'` is set for dropdowns with a sensible default +- [ ] Every `short-input`, `long-input`, `code`, and selector subBlock has a `placeholder` — including + password fields (`Enter your API key`). Formatted values show the shape + (`2023-01-01T00:00:00Z`); optional fields with a server default name it. See add-integration → Step 3 + +### Advanced Mode +- [ ] Optional, rarely-used fields are set to `mode: 'advanced'`: + - Pagination tokens / next tokens + - Time range filters (start/end time) + - Sort order / direction options + - Max results / per page limits + - Reply settings / threading options + - Rarely used IDs (reply-to, quote-tweet, etc.) + - Exclude filters +- [ ] **Required** fields are NEVER set to `mode: 'advanced'` +- [ ] Fields that users fill in most of the time are NOT set to `mode: 'advanced'` + +### WandConfig +- [ ] Timestamp fields have `wandConfig` with `generationType: 'timestamp'` +- [ ] Comma-separated list fields have `wandConfig` with a descriptive prompt +- [ ] Complex filter/query fields have `wandConfig` with format examples in the prompt +- [ ] All `wandConfig` prompts end with an explicit `Return ONLY the ` instruction so the generated value can be pasted directly into the field +- [ ] `wandConfig.placeholder` describes what to type in natural language + +### Tools Config +- [ ] `tools.access` lists **every** tool ID the block can use — none missing +- [ ] `tools.config.tool` returns the correct tool ID for each operation +- [ ] Type coercions are in `tools.config.params` (runs at execution time), NOT in `tools.config.tool` (runs at serialization time before variable resolution — coercing there destroys dynamic references like ``) +- [ ] `tools.config.params` handles: + - `Number()` conversion for numeric params that come as strings from inputs + - `Boolean` / string-to-boolean conversion for toggle params + - Empty string → `undefined` conversion for optional dropdown values + - SubBlock ID → tool param name remapping only for optional or `user-or-llm` params + +### Block Outputs +- [ ] Outputs cover the key fields returned by ALL tools (not just one operation) +- [ ] Output types are correct (`'string'`, `'number'`, `'boolean'`, `'json'`, `'file'`, `'file[]'`) +- [ ] `type: 'json'` outputs describe inner fields in the description string: `'User profile (id, name, username, bio)'` or `'[{address, status, type}]'` for arrays +- [ ] **Do NOT add a `properties: {...}` field on block outputs.** Block-level `OutputFieldDefinition` (from `@sim/workflow-types/blocks`) only accepts `{ type, description?, condition?, hiddenFromDisplay? }`. Nested `properties` is a tool-level construct (`OutputProperty`) — adding it to a block output will fail TypeScript at build time +- [ ] No opaque `type: 'json'` with vague descriptions like `'Response data'` +- [ ] Outputs that only appear for certain operations use `condition` if supported, or document which operations return them + +### Block Metadata +- [ ] `type` is snake_case (e.g., `'x'`, `'cloudflare'`) +- [ ] `name` is human-readable (e.g., `'X'`, `'Cloudflare'`) +- [ ] `description` is a concise one-liner +- [ ] `longDescription` provides detail for docs +- [ ] `docsLink` points to `'https://docs.sim.ai/integrations/{service}'` +- [ ] `category` is `'tools'` +- [ ] `bgColor` uses the service's brand color hex +- [ ] `icon` references the correct icon component from `@/components/icons` +- [ ] `authMode` is set correctly (`AuthMode.OAuth` or `AuthMode.ApiKey`) +- [ ] Block + meta are registered in `blocks/registry-maps.ts` (`BLOCK_REGISTRY` / `BLOCK_META_REGISTRY`) alphabetically + +### BlockMeta +- [ ] `{Service}BlockMeta` is exported in the same file as the block +- [ ] Has at least 7 templates, each with `icon`, `title`, `prompt`, `modules`, `category`, and `tags` +- [ ] Prompts describe concrete use cases, not generic descriptions of what the service does +- [ ] `alsoIntegrations` is set on any template whose prompt references another service +- [ ] `skills` present (3–5 mainstream, 2–3 niche), each grounded in `tools.access` — flag any skill implying an unsupported action +- [ ] **Each skill is real, not hallucinated** — web-search and confirm it maps to a popular use case attested online (vendor use-case pages, official docs describing the workflow, reputable "top automations" articles); rewrite/remove any you cannot source +- [ ] Each skill has a kebab-case `name` (≤64 chars, unique), a one-line `description`, and markdown `content` with `# Title` + `## Steps` + an output/guidance section + +### Block Inputs +- [ ] `inputs` section lists all subBlock params that the block accepts +- [ ] Input types match the subBlock types +- [ ] When using `canonicalParamId`, inputs list the canonical ID (not the raw subBlock IDs) + +### Dynamic Selectors + +- [ ] Every remote `selectorKey` is classified in the browser-safe manifest and has exactly one + server attachment +- [ ] The manifest allowlists the minimal active `dependsOn` context and matches list/search/detail, + pagination, scope, and stale-time behavior +- [ ] Canonical basic/advanced and trigger/action modes project only their active values; exact + `{{KEY}}` references remain unresolved in the browser +- [ ] Stored credentials are bound to the actor, workspace, and trusted provider/service +- [ ] Each attachment declares and enforces a `fixed`, `credential-bound`, or explicitly reviewed + `user-controlled` destination policy +- [ ] Provider results are explicitly projected to safe option fields; secrets, tokens, credential + IDs, context values, and raw upstream errors do not enter responses, logs, or query keys +- [ ] No selector provider module, provider fetch, or OAuth-token request runs in the browser, and no + selector-only provider route remains + +## Step 5: Validate OAuth Scopes (if OAuth service) + +Scopes are centralized — the single source of truth is `OAUTH_PROVIDERS` in `lib/oauth/oauth.ts`. + +- [ ] Scopes defined in `lib/oauth/oauth.ts` under `OAUTH_PROVIDERS[provider].services[service].scopes` +- [ ] `lib/auth/connectors/providers.ts` (`buildConnectorProviders`) uses `getCanonicalScopesForProvider(providerId)` — NOT a hardcoded array +- [ ] Block `requiredScopes` uses `getScopesForService(serviceId)` — NOT a hardcoded array +- [ ] No hardcoded scope arrays in `lib/auth/connectors/providers.ts` or block files (should all use utility functions) +- [ ] Each scope has a human-readable description in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` +- [ ] No excess scopes that aren't needed by any tool + +## Step 6: Validate Deployment Availability (if OAuth service) + +The deployment UI and setup CLI do not infer OAuth client fields from scopes. They resolve the +block's generated `oauthServiceId` through the shared deployment capability catalog. + +- [ ] The visible integration block has exactly one distinct `oauth-input.serviceId` +- [ ] `resolveOAuthClientCapabilityId(serviceId)` returns the intended provider capability +- [ ] The resolved provider exists in `OAUTH_CLIENT_CAPABILITIES` +- [ ] Every field listed by that capability exists in `apps/sim/lib/core/config/env.ts` +- [ ] Every capability field has the correct `text` or `secret` entry in `OAUTH_CLIENT_SETUP_FIELDS`; no CLI naming heuristic is required +- [ ] Shared Google/Microsoft service IDs resolve to their provider capability rather than duplicate entries +- [ ] `npx sim-setup add integration ` is the command emitted by availability; the CLI has only the exhaustive input-mode projection, not a second runtime provider definition +- [ ] If the canonical OAuth service declares `serviceAccountProviderId`, + the generated `SERVICE_ACCOUNT_PROVIDER_BY_OAUTH_SERVICE_ID[serviceId]` has the same provider ID +- [ ] The service-account `deploymentRequirement` matches how that credential actually works: + omitted for an independent path, `'oauth-client'` when it needs the OAuth client fields, or + `'preview-gated'` when controlled by a preview block + +Treat a missing capability as **critical**: runtime availability intentionally throws instead of +silently exposing an unusable integration. + +## Step 7: Validate Pagination Consistency + +If any tools support pagination: +- [ ] Pagination param names match the API docs (e.g., `pagination_token` vs `next_token` vs `cursor`) +- [ ] Different API endpoints that use different pagination param names have separate subBlocks in the block +- [ ] Pagination response fields (`nextToken`, `cursor`, etc.) are included in tool outputs +- [ ] Pagination subBlocks are set to `mode: 'advanced'` + +## Step 8: Validate Memory Load Safety + +If any tool lists, searches, exports, imports, downloads, uploads, paginates, batches, transforms arrays, or reads file/HTTP bodies, read `.agents/skills/memory-load-check/SKILL.md` and apply it to the integration. + +- [ ] List/search tools expose API limits and do not auto-fetch every page into memory +- [ ] Transform logic does not build unbounded arrays, maps, sets, or `Promise.all` fan-outs +- [ ] File and HTTP body reads use explicit byte caps or existing stream-limit helpers +- [ ] Internal file results reach `createInternalToolFileResult` / `createInternalToolFilesResult` + before JSON serialization; external raw downloads explicitly use `request.responseType: 'binary'` + and return a buffered `output.file`. Provider base64 JSON needs separate handling +- [ ] Transforms retain stored `UserFile` identity/access fields, and tests cover a >10 MiB file + crossing executor admission without another upload. New file outputs contain references only, + without inline content aliases; preserve legacy versions when removing existing inline fields +- [ ] Scan every file-producing path, including attachment fetches inside `transformResponse`, URL + descriptors, export operations, and old/new block versions; checking download-named tools alone + misses late reads that occur after the first response admission +- [ ] Late attachment reads share a per-call byte budget, bound actual streamed bytes independently + of provider size metadata, and forward `ToolResponseContext.signal` through every fetch/read +- [ ] Both workflow and Copilot tests produce compact `UserFile` outputs; nested message attachment + aliases reference the same stored files, with no duplicate upload or raw bytes left behind +- [ ] New output contracts omit redundant copies of file name, MIME type, size, URL, and success; + retained provider metadata has a distinct purpose, and types match the stored-file runtime shape +- [ ] Large result payloads are summarized, paginated, referenced, or capped rather than raw-dumped +- [ ] Pagination and download tests cover caps, early stop behavior, or partial-result preservation when relevant + +## Step 9: Validate Error Handling + +- [ ] `transformResponse` checks for error conditions before accessing data +- [ ] Error responses include meaningful messages (not just generic "failed") +- [ ] HTTP error status codes are handled (check `response.ok` or status codes) + +## Step 10: Report and Fix + +### Report Format + +Group findings by severity: + +**Critical** (will cause runtime errors or incorrect behavior): +- Wrong endpoint URL or HTTP method +- Missing required params or wrong `required` flag +- Incorrect response field mapping (accessing wrong path in response) +- Missing error handling that would cause crashes +- Tool ID mismatch between tool file, registry, and block `tools.access` +- OAuth scopes missing in `lib/auth/connectors/providers.ts` that tools need +- OAuth integration `serviceId` missing from the deployment capability catalog +- Capability references an env field absent from the runtime env schema +- Service-account metadata disagrees with the canonical OAuth service configuration +- `tools.config.tool` returning wrong tool ID for an operation +- Type coercions in `tools.config.tool` instead of `tools.config.params` +- Proven model-visible request fields bypass the shared projection or private-provenance boundary +- Opaque model input is downloaded or sent before provenance and workspace-file checks +- A Sim-owned durable sink or internal execution handoff drops encrypted provenance or breaks + legacy headerless/`NULL` data +- A tool substitutes secret plaintext into source, leaks private metadata, or generically sanitizes + unrelated third-party results +- A selector resolves shared secret plaintext in the browser, lacks credential provider binding or + destination enforcement, or returns provider payloads or protected values across the selector + boundary + +**Warning** (follows conventions incorrectly or has usability issues): +- Optional field not set to `mode: 'advanced'` +- Missing `wandConfig` on timestamp/complex fields +- Wrong `visibility` on params (e.g., `'hidden'` instead of `'user-or-llm'`) +- Missing `optional: true` on nullable outputs +- Opaque `type: 'json'` without property descriptions +- Missing `.trim()` on ID fields in request URLs +- Missing `?? null` on nullable response fields +- Block condition array missing an operation that uses that field +- Hardcoded scope arrays instead of using `getScopesForService()` / `getCanonicalScopesForProvider()` +- Missing scope description in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` + +**Suggestion** (minor improvements): +- Better description text +- Inconsistent naming across tools +- Missing `longDescription` or `docsLink` +- Pagination fields that could benefit from `wandConfig` + +### Fix All Issues + +After reporting, fix every **critical** and **warning** issue. Apply **suggestions** where they don't add unnecessary complexity. + +### Regenerate Derived Artifacts + +Several files are generated from tool and block definitions. Editing a tool or block WITHOUT regenerating them fails CI, so run this before pushing: + +```bash +bun run generate # every generator below (and any other generate:/check: pair) +bun run check:integration-catalog # registry ↔ committed deployment metadata drift +bun run check:docs # committed docs ↔ what the generator renders today +bun run check:deployment-config # OAuth registry/catalog ↔ provider-ID fact drift +bun run check:audits # every audit CI enforces, including check:docs +bun run apps/sim/scripts/check-block-registry.ts origin/staging # block ↔ tool param coverage (CI, not in check:audits) +``` + +- **`generate:tool-metadata`** — required whenever a tool's `outputs`, `params`, or descriptions change. CI enforces this with `bun run check:tool-metadata`, which fails with *"Generated tool metadata is stale"*. This is the easiest gate to miss, because nothing in the tool file hints that a generated artifact mirrors it. +- **`generate:docs`** — required whenever block metadata changes (`bgColor`, `name`, `description`, operations, outputs). Regenerates the integration `.mdx`, `packages/deployment-config/src/integrations.json`, and the docs copy of `components/icons.tsx`. +- **`generate:deployment-config`** — required for OAuth or service-account changes. Regenerates provider-ID facts from the canonical OAuth registry and integration catalog; special deployment requirements remain handwritten policy. +- **`check:integration-catalog`** — loads the executable block registry, derives visible integration + deployment fields, and compares them with the committed catalog. It catches missing/unexpected + entries and stale auth/service IDs without loading the executable registry in client code. +- **`check:docs`** — check mode of `generate:docs`: renders every generated docs artifact in + memory and fails listing any committed file that differs. Runs in CI via `check:audits`. + +**Always diff the regen output before committing — but commit all of it.** These generators rewrite +every file they own, so they also true up drift that accumulated on the base branch (pages whose +source changed without a regen). That catch-up is correct output, not a regression: `check:docs` +fails CI on any page left stale, so reverting swept-in hunks with `git checkout --` reintroduces the +failure. Review the diff to confirm each hunk is explained by a real source change (yours or an +upstream PR that skipped regeneration), and investigate anything that looks like content loss — a +page losing a section usually means its source block moved or a generator input broke, not that the +hunk should be reverted. + +The integration's page must carry a `{/* MANUAL-CONTENT-START:intro */}` section directly under +``. If it is missing, write one using the template in add-integration → Step 8, and +check an existing intro against what the block actually ships (no removed or unshipped operations). + +If an icon changed, `apps/sim/components/icons.tsx` is the source of truth and `apps/docs/components/icons.tsx` is its generated mirror — they must end up byte-identical for that component. + +### Validation Output + +After fixing, confirm: +1. `bun run lint` passes with no fixes needed +2. TypeScript compiles clean (no type errors) — check the error list is empty for the files you touched; pre-existing unrelated errors in a worktree usually mean workspace packages resolve to the main checkout +3. The integration's tests pass, and any test you added actually fails without its fix (revert it once and watch it go red) +4. Derived artifacts regenerated and their diffs reviewed (see above) +5. `bun run check:integration-catalog` passes +6. `bun run check:docs` passes +7. `bun run apps/sim/scripts/check-block-registry.ts origin/staging` passes +8. For OAuth or service-account changes, `bun run check:deployment-config` passes +9. For OAuth or service-account changes, `bun run --cwd apps/sim test lib/integrations/availability.server.test.ts` passes +10. Re-read all modified files to verify fixes are correct +11. Any remaining unknown response schemas were explicitly reported to the user instead of guessed + +## Checklist Summary + +- [ ] Read ALL tool files, block, types, index, and registries +- [ ] Pulled and read official API documentation +- [ ] Validated every tool's ID, params, request, response, outputs, and types against API docs +- [ ] Validated block ↔ tool alignment (every tool param has a subBlock, every condition is correct) +- [ ] Validated advanced mode on optional/rarely-used fields +- [ ] Validated every text-entry and selector subBlock has a `placeholder` +- [ ] Validated wandConfig on timestamps and complex inputs +- [ ] Validated tools.config mapping, tool selector, and type coercions +- [ ] Validated block outputs match what tools return, with typed JSON where possible +- [ ] Validated OAuth scopes use centralized utilities (getScopesForService, getCanonicalScopesForProvider) — no hardcoded arrays +- [ ] Validated scope descriptions exist in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` for all scopes +- [ ] Validated OAuth `serviceId` resolves to the intended `OAUTH_CLIENT_CAPABILITIES` entry and all capability fields exist in the env schema +- [ ] Validated service-account projection and deployment requirement against the canonical OAuth service config +- [ ] Regenerated deployment config when block/OAuth metadata changed and ran both catalog checks +- [ ] Validated pagination consistency across tools and block +- [ ] Validated memory load safety using `.agents/skills/memory-load-check/SKILL.md` when tools list/search/download/import/export/batch data +- [ ] Validated error handling (error checks, meaningful messages) +- [ ] Validated registry entries (tools and block, alphabetical, correct imports) +- [ ] Validated model-visible/opaque inputs and Sim-durable/internal-execution provenance at their + owning boundaries +- [ ] Confirmed legacy persisted data keeps working and tracked invalid provenance fails closed +- [ ] Confirmed ordinary third-party results remain unchanged absent activated Sim provenance +- [ ] Validated `{Service}BlockMeta` exported with at least 7 templates +- [ ] Validated every dynamic selector through the shared manifest, server attachment, and + `selectors.execute` boundary +- [ ] Reported all issues grouped by severity +- [ ] Fixed all critical and warning issues +- [ ] Ran `bun run generate:tool-metadata` if any tool outputs/params changed, and confirmed `bun run check:tool-metadata` passes +- [ ] Ran `bun run generate:docs` if any block metadata changed, and committed the full generated diff — including stale-page catch-up for other integrations (`bun run check:docs` fails CI on reverted generator output) +- [ ] Validated the docs page has an accurate `MANUAL-CONTENT-START:intro` section +- [ ] Ran `bun run lint` after fixes +- [ ] Verified TypeScript compiles clean +- [ ] Verified added tests fail without their fix diff --git a/.agents/skills/validate-model/SKILL.md b/.agents/skills/validate-model/SKILL.md index 893e13ea936..776df5ab93d 100644 --- a/.agents/skills/validate-model/SKILL.md +++ b/.agents/skills/validate-model/SKILL.md @@ -4,32 +4,141 @@ description: Validate a model entry (or every model in a provider) in apps/sim/p argument-hint: [model-id] --- -# Validate Model +# Validate Model Skill -Audit entries in `apps/sim/providers/models.ts` against the provider's live docs. With no `model-id`, validate every model of the provider. The `add-model` skill owns the rules (live-fetch, two-source pricing, cite every URL), the source URL table, which provider code reads which capability flag, and the field conventions: read it first. +You audit one or more model entries in `apps/sim/providers/models.ts` against the provider's official live API docs. **Hallucinated pricing and capabilities are the #1 failure mode in this file.** Every numeric and capability claim must be re-derived from a live web fetch in this session — not from memory, not from training data, not from the user's marketing email. -## Procedure +## Hard rules (do not skip) -1. Read each target entry: `id`, `pricing`, `capabilities`, `contextWindow`, `releaseDate`, `recommended`, `speedOptimized`, `sunset`. -2. Live-fetch the provider's models, pricing and reasoning pages (add-model Step 1) plus one secondary pricing source. A failed fetch (404, timeout, paywall) marks its fields UNVERIFIED with the URL attempted; never confirm from memory. -3. Grep `apps/sim/providers//` for each flag the entry sets. A flag the code does not read is a dead-flag warning. -4. Per model, check: - - `id` matches the API identifier exactly (reseller prefix included); `releaseDate`; `sunset.status` reflects any announced retirement (`deprecated` once calls fail, `legacy` once superseded). - - `input` / `output` / `cachedInput` (or `cachedInput` correctly omitted); `pricing.updatedAt` older than 60 days is a suggestion to refresh. - - `contextWindow` and `maxOutputTokens`. - - Every capability is both documented as supported **and** read by the provider code. `reasoningEffort` must be omitted on a model whose API rejects it (grok-4.3), but kept on always-reasoning models that accept it (OpenAI o-series): verify per model. `thinking.streamed` per add-model. - - At most one or two `recommended`; `speedOptimized` only on the smallest tier. - - A model under a provider `getHostedModels()` expands is billed with Sim's key: confirm that is intended (a BYOK-only model there is a billing bug), and note that hosted runs need the deployment's `{PREFIX}_COUNT` / `{PREFIX}_1..N` key pool set; a validation pass can't see that. +1. **Live-fetch or report unverified.** Each field must be backed by a live WebFetch in this session. If you cannot reach an authoritative URL for a field, mark it **UNVERIFIED** in the report — do not silently confirm it from memory. +2. **Cite every fact.** Every value in the report must show the source URL it was checked against. No URL → mark UNVERIFIED. +3. **Two-source rule for pricing.** Cross-check input/output/cached against at least one secondary source (OpenRouter, Artificial Analysis, CloudPrice). If sources disagree, the provider's own docs win — flag the disagreement. +4. **Inspect provider implementation before flagging capability mismatches.** A capability flag in `models.ts` is dead unless the provider's code under `apps/sim/providers/{provider}/` consumes it (see Consumption Matrix below). Setting a flag the provider ignores is a warning, not a critical. +5. **Never auto-fix without printing the diff.** Show the user the proposed diff before applying. Get confirmation. -## Report +## Your Task -Per model: field | repo | docs | URL | status (✓ / ✗ / ⚠️ single-source / ❓ unverified), then findings by severity and a one-line count (`N models · X critical · Y warnings · Z suggestions · W unverified`). +When invoked as `/validate-model [model-id]`: -- **critical**: misleads about cost or breaks calls (wrong price, id, context window, a capability the API rejects). -- **warning**: dead flag, internal inconsistency, unintended hosting, missing `sunset` after retirement. -- **suggestion**: stale `updatedAt`, field order, a missing `speedOptimized`. -- **unverified**: no authoritative source found. Never mark the validation passed; say which URLs you tried and what third-party sources report, and ask. +1. Read the target entries from `models.ts` +2. Live-fetch the provider's official models, pricing, and capability/reasoning pages + at least one secondary source for pricing +3. Inspect the provider implementation to know which flags are actually consumed +4. Run the checklist below per model +5. Report findings (critical / warning / suggestion / unverified) with every cell linked to its source URL +6. Offer to fix; on confirm, edit `models.ts` in a single pass and re-lint -## Fixing +If `model-id` is omitted, validate every model in the provider. -Offer to fix critical and warning items. Print the diff and get confirmation before editing; edit in one pass, run `bun run lint` (and `bun run generate` if a `thinking`/`reasoningEffort` entry changed), then re-check only the failed rows. +## Step 1: Read entries from `models.ts` + +Capture per model: `id`, full `pricing`, full `capabilities`, `contextWindow`, `releaseDate`, `recommended`, `speedOptimized`, `deprecated`. + +## Step 2: Live-fetch authoritative sources + +Use the canonical provider URL table in the `add-model` skill (`.agents/skills/add-model/SKILL.md`), Step 1, as the single source of truth — fetch the models index, pricing, and reasoning/parameter caveats pages listed there for the target provider. + +Secondary cross-check (use at least one): OpenRouter, Artificial Analysis, CloudPrice. + +If a fetch fails (404, timeout, paywall), record the URL attempted and mark dependent fields UNVERIFIED. + +## Step 3: Build the consumption map for this provider + +Use the Consumption Matrix in `.agents/skills/add-model/SKILL.md` Step 2 and run its re-grep commands for the target provider before relying on it. A flag set in `models.ts` that the provider's code does not read = **warning: dead flag**. + +## Step 4: Run the checklist + +For each model, evaluate every row. Statuses: ✓ matches docs, ✗ disagrees, ⚠️ single-source, ❓ UNVERIFIED (could not fetch). + +### Identity +- [ ] `id` exactly matches provider's API model identifier (case, dots, dashes, prefix for resellers) +- [ ] `releaseDate` matches launch announcement +- [ ] `deprecated: true` set if provider has announced retirement (or removed from active list) + +### Pricing (per 1M tokens, USD) +- [ ] `pricing.input` matches provider pricing page +- [ ] `pricing.output` matches provider pricing page +- [ ] `pricing.cachedInput` matches provider's documented cached/prompt-cache rate (or is correctly omitted if no caching offered) +- [ ] `pricing.updatedAt` is recent — warn if older than 60 days + +### Context & output limits +- [ ] `contextWindow` matches docs (in tokens) +- [ ] `capabilities.maxOutputTokens` matches documented output cap (or is correctly omitted if "no output limit") + +### Capabilities (each must be DOCUMENTED-AS-SUPPORTED **and** CONSUMED-BY-PROVIDER-CODE) +- [ ] `temperature` — provider accepts it for this model (reasoning-always-on models often reject) +- [ ] `reasoningEffort.values` — list matches docs; **omitted** for always-reasoning models that reject the parameter (e.g., grok-4.3, where xAI docs explicitly state `reasoning_effort` is not supported). Verify per model — some always-reasoning models (e.g., OpenAI's o-series) DO accept `reasoning_effort` and should keep the flag. +- [ ] `verbosity.values` — only on OpenAI gpt-5.x family; values match docs +- [ ] `thinking.levels` + `thinking.default` — only on providers whose code reads `thinking`/`thinkingLevel` (see the add-model Consumption Matrix); values match docs +- [ ] `thinking.streamed` — REQUIRED on Anthropic-family thinking models. Current Claude thinking models use `'summary'` (Sim requests `display: 'summarized'`); use `'full'` only if official API docs explicitly guarantee raw thinking deltas. Verify against the provider's thinking-display docs. After any change, run `bun run generate:agent-stream-docs` so the Agent block docs table stays in sync (CI diffs it) +- [ ] `nativeStructuredOutputs` — only on providers whose code consumes it (see the Consumption Matrix); provider must document Structured Outputs / JSON-mode for this model +- [ ] `toolUsageControl` — provider supports `tool_choice` semantics +- [ ] `computerUse` — provider implements computer-use loop AND model is a computer-use SKU +- [ ] `deepResearch` — only on actual deep-research SKUs +- [ ] `memory: false` — only when the model genuinely cannot maintain conversation history + +### Flags +- [ ] `recommended: true` — at most one or two per provider; should be current flagship +- [ ] `speedOptimized: true` — only on smallest/fastest tier (nano / flash-lite / haiku class) + +### Hosting / billing +- [ ] If `getHostedModels()` includes the model ID (`providers/models.ts` expands whole providers — more than openai/anthropic/google — plus the static Fireworks catalog), the model is served with Sim's rotating key and billed via `shouldBillModelUsage()`. Confirm that is the intent (a BYOK-only model parked under a hosted provider is a billing bug — warning). +- [ ] If the model is hosted, the deployment is expected to have its `{PREFIX}_COUNT` / `{PREFIX}_1..N` env vars set (ops concern; note if it looks unset for a model claiming hosted support). + +## Step 5: Report (mandatory format) + +For each model, emit a table with one row per checklist item. Every row that claims ✓ must have a URL. + +```markdown +### Validation — + +| Field | Repo | Live docs | Source URL | Status | +|---|---|---|---|---| +| `input` | $1.25/M | $1.25/M | https://docs.x.ai/... | ✓ | +| `cachedInput` | $0.50/M | $0.20/M | https://cloudprice.net/... | ✗ stale (price cut not picked up) | +| `reasoningEffort` | low/medium/high | rejected by API | https://docs.x.ai/.../reasoning | ✗ inert — selecting silently no-ops | +| `contextWindow` | 1,000,000 | 1,000,000 | https://docs.x.ai/... + https://openrouter.ai/... | ✓ (2 sources) | +| `releaseDate` | 2026-04-30 | not found in scraped pages | _attempted: docs.x.ai, x.ai/news_ | ❓ UNVERIFIED | + +**Findings** +- 🔴 critical — `cachedInput` is wrong: docs say $0.20/M, repo has $0.50/M +- 🟡 warning — `reasoningEffort` is set but provider rejects it for this model (xAI docs explicitly: "reasoning_effort is not supported by grok-4.3") +- 🔵 suggestion — `pricing.updatedAt` is 90 days old; refresh +- ❓ unverified — `releaseDate` could not be confirmed from any fetched page; ask user + +**Disagreements between sources** +- _none_ OR _OpenRouter says $X, provider docs say $Y — went with provider docs_ +``` + +End each multi-model run with a summary count: `N models checked · X critical · Y warnings · Z suggestions · W unverified`. + +## Step 6: Offer to fix + +After reporting, ask: *"Want me to fix the critical and warning items? I'll print the diff first."* On yes: + +1. Print the proposed diff (do not apply yet) +2. Get user confirmation +3. Edit `models.ts` in a single pass +4. Run `bun run lint` +5. Re-run only the failed rows of the checklist on the new state + +## Severity definitions + +- 🔴 **critical** — wrong number or wrong identifier that misleads users about cost or breaks API calls. Examples: incorrect pricing, wrong model id, wrong context window, capability the API rejects. +- 🟡 **warning** — dead code or internal inconsistency. Examples: capability flag the provider ignores, multiple `recommended: true` per provider, `pricing.updatedAt` >60 days old, missing `deprecated: true` on retired model. +- 🔵 **suggestion** — style/consistency. Examples: field order, missing `speedOptimized` on a clearly smallest-tier model. +- ❓ **unverified** — could not fetch an authoritative source for this field. Surface it; never silently confirm. + +## Common drift + +Pricing changes after provider price cuts; `reasoningEffort`/`thinking`/`verbosity` set on a model whose provider code or API does not accept them; stale `pricing.updatedAt`; wrong context window; more than one `recommended` after a flagship swap; missing `deprecated: true` after a provider retirement announcement. + +## What "I cannot verify this" looks like + +If, after fetching the documented sources, a field cannot be confirmed: + +- Mark the row ❓ UNVERIFIED with the URL(s) attempted +- Surface it in the **Findings** section with severity ❓ +- Do NOT mark the validation as passed +- Ask the user for a docs URL or guidance before changing anything + +The skill is allowed to say *"I could not verify the cached input price for grok-4.3 from the official xAI docs in this session — I attempted [URLs] without finding the value. Third-party sources [URL1, URL2] both report $0.20/M. Confirm before I update."* That is correct behavior. Hallucinating a number is not. diff --git a/.agents/skills/validate-permission-group-item/SKILL.md b/.agents/skills/validate-permission-group-item/SKILL.md index 6c8b44b91ee..578e936f212 100644 --- a/.agents/skills/validate-permission-group-item/SKILL.md +++ b/.agents/skills/validate-permission-group-item/SKILL.md @@ -4,82 +4,155 @@ description: Audit an existing enterprise permission-group item end-to-end — r argument-hint: --- -# Validate Permission Group Item +# Validate Permission Group Item Skill -The question is not "does this key exist in the right places" (the registry makes most of that compiler-enforced). It is: +The question is not "does this key exist in the right places" — the registry makes most of that compiler-enforced. It is: > **If an organization admin sets this, what refuses, and can I make that refusal happen?** -A key with an admin control but no server gate passes every structural audit. Assume nothing enforces until you have found the throw. Read `add-permission-group-item` first: it owns the invariants and their reasons; this skill is the audit procedure. +A key with an admin checkbox but no server gate passes every structural audit. Assume nothing enforces until you have found the throw. -## Step 1: Registry entry and copy +**`add-permission-group-item` owns the procedure and the rationale for every invariant named below.** Read it for *why*; this skill is the checklist. Its "Read the system first" list is the same one — start there. -Record the builder, `enforcement`, `scope` and position in `lib/permission-groups/fields.ts`. +## Step 1: Registry entry (`lib/permission-groups/fields.ts`) -- `git log -p` shows the key appended, never moved (wire order; no test catches a reorder). -- The name keeps the permissive value falsy (no `allowX` boolean). -- `scope` is true: an `organization` key read from a workspace group, or the reverse, misleads the admin about which group applies. -- **The hint, label and category tell the truth.** A `'capability'` key refuses at the API, so "Hide the … from the sidebar" is a lie an admin acts on; the same string is the active-restriction prose Copilot reads. An allowlist's `empty` phrasing says "none allowed", not "unrestricted". Rank a misleading hint with the enforcement findings. +Record the builder, the `enforcement`, and the position. -## Step 2: Nothing bypasses the derivation +- **Default permissive?** The builders hardcode `false` / `null` / `[]`, so the risk is a *name* that inverts the meaning — an `allowX` boolean. The checkbox renders `checked={!editingConfig[feature.configKey]}` (ticked = allowed), so a positively-named boolean renders backwards. +- **Position stable?** Declaration order is the wire order, and no test catches a reorder. If `git log -p` shows the key was ever *moved* rather than appended, every open editor reads as unsaved (`group-detail.tsx` dirty-checks stringified configs). +- **Phrasing accurate?** An allowlist's `{ limited, empty }` and a denylist's string are read by `getActivePermissionGroupRestrictions` in `features.ts` and surface to users through the Copilot workspace VFS and the enterprise platform context. Confirm `empty` says "none allowed", not "unrestricted". +- **Does the `hint` tell the truth?** Highest-value read in this step. A `'capability'` key refuses at the API, so a hint saying it hides a tab, module, or nav item "from the sidebar" is a **lie an admin acts on** — they believe they are tidying chrome while withholding a module. The same string is reused as the prose for an *active* restriction, where "hide" is simply false. Any surviving "Hide the …" hint on a `'capability'` key is a finding, not a nit; check `label` and `category` the same way (a "Sidebar" or "Settings Tabs" section makes the claim structurally). + +## Step 2: Schemas, type, defaults, parser + +All derived by `collectFieldProperty` from the same registry. **Do not hand-verify them.** Verify nothing bypasses the derivation: ```bash grep -rn "" apps/sim --include='*.ts' --include='*.tsx' \ | grep -vE 'lib/permission-groups/(fields|resolve\.server|config-scope\.server)\.ts' ``` -Every hit should be a rule's `deniedBy`, an enforcement site, a UI binding, or a test. A route restating the key, a client re-deriving a default, a second coercion path, a config read not via `parsePermissionGroupConfig`/`resolvePermissionGroupConfig`, a `.catch()` on an array, a `?? []` on an allowlist, or a hand-rolled integration-allowlist comparison is a finding. Confirm `parsePermissionGroupConfig` keeps its `Array.isArray` guard and `CAPABILITY_RULES` keeps `satisfies`. +Only the registry and the resolvers are excluded, so `capabilities.ts` stays in the output — its `CAPABILITY_RULES` entry and `deniedBy` are the authoritative reads this step exists to check. Every hit should be a rule's `deniedBy`, an enforcement site, a UI binding, or a test. A route restating the key, a client re-deriving a default, or a second coercion path is a leak. Specifically: + +- **`z.array(...).catch(...)` anywhere on this key's path** — whole-value tolerant, so one bad member discards every good one, and on an allowlist the `null` fallback means unrestricted. That is fail-**open**. `tolerantArray` filters element-wise. Rank a regression here with the enforcement findings. +- **`?? []` applied to an allowlist** — collapses "allows everything" into "allows nothing". +- **A hand-rolled comparison against an integration allowlist.** `allowedIntegrations` and the deployment's `ALLOWED_INTEGRATIONS` are written independently, so one names `slack` where the other names `slack_v2`; anything folding only case intersects them to nothing and hides an integration both allow. Both halves must canonicalize through `integration-allowlist.ts` (`intersectAccessControlAllowlists` / `toAccessControlAllowlist` / `resolveAccessControlBlockType`) *before* intersecting, with the checked type resolved the same way. That module reads `block-successors.generated.ts` through `Object.hasOwn` — a bare bracket lookup answers an admin-supplied `constructor` with an inherited function and 500s every path reading that group; `check:block-successors` catches the map going stale. +- **Any config read not from `parsePermissionGroupConfig` or a `resolvePermissionGroupConfig` caller.** + +Two structural guards must still be present: + +- **`parsePermissionGroupConfig` still tests `Array.isArray(config)`.** `typeof [] === 'object'`, the column is `jsonb` so a row genuinely can hold `[]`, and `z.object().parse([])` throws — the guard is what returns defaults instead of a 500. `tolerantArray` carries the mirror image. +- **`CAPABILITY_RULES` still uses `satisfies`, not an annotation.** An annotation collapses `StaticPermissionGroupCapability` to `never`, silently disabling the type system around capabilities with nothing wrong at runtime. `AssertsStaticCapabilityResolves` catches it; any weakening is a top-tier finding. + +Confirm the assertions at the bottom of `fields.ts` still name a field of this kind (`AssertsAllowlistStaysPrecise`, `AssertsDenylistStaysPrecise`, `AssertsRestrictionStaysPrecise`, `AssertsAuthTypesStayPrecise`, `AssertsParserReturnsTheConfig`) — a zod generic degrading to `unknown` is invisible at runtime and quietly loses every call site's narrowing. ## Step 3: Admin UI (`ee/access-control/components/group-detail.tsx`) -- Booleans render from `PLATFORM_FEATURES`; check the category is in `PLATFORM_CATEGORY_ORDER`. -- A nested allowlist/denylist renders nothing unless it has an `AccessRequestTarget` kind and a `PermissionGrid` in `featureExtras` under the right parent feature id. No picker means no admin can set it. The four run-scoped lists render from the Providers and Blocks sections instead; don't report them for `featureExtras`. -- Allowlist writes (`ee/access-control/utils/access-state.ts`) collapse a full selection back to `null`; a denylist write must not. +- **Boolean:** appears automatically via `PLATFORM_FEATURES`. Confirm its `category` is in `PLATFORM_CATEGORY_ORDER`; an unlisted one renders after every ordered section. +- **Nested allowlist / denylist** (one that qualifies a platform-feature boolean): renders **nothing** unless it is in the `featureExtras` map — keyed by the *parent boolean's feature id*, not the config key. No picker there means no admin can ever set it. Report it. Top-level lists — `allowedIntegrations`, `allowedModelProviders`, `deniedModels`, `deniedTools` — are not in `featureExtras` and must not be reported for it; they render from the dedicated Providers and Blocks sections, so check them there. +- For an **allowlist** picker, check both behaviors: refuses an empty selection (`if (values.length === 0) return`) and collapses a full one back to `null` (otherwise the allowlist freezes at today's members). A **denylist** picker must do neither: clearing every entry is how an admin denies nothing, and a full selection is a real state that denies everything. +- Check the parent is the right one (`allowedKnowledgeConnectors` under `hide-knowledge-base`, not `disable-knowledge-base-creation`). ## Step 4: Capability rule -- `kind` is right: a rule needing a request value is `'parameterized'`. -- A narrower capability that replaced a broader one also reads the broader key: check `git log` for a re-pointed `capability:` and verify the rule grew the key in the same commit. -- `detailCode` matches the remedy; `describe` reads as the subject of "… is not available under your organization's permission group". A call site writing the sentence itself is drift. +A `'capability'` key must appear in some rule's `configKeys` — the audit asserts this (D) and the converse (E): a key declared `'executor'` or `'ui-only'` that a rule reads is flagged, so a key cannot gain enforcement while staying documented as weaker. Then check what the audit cannot: + +- **`configKeys` lists every key `deniedBy` reads.** The audit parses it textually and never reads the closure; a key read but unlisted is invisible to D and E. +- **`kind` is right.** A rule needing a request value must be `'parameterized'` — and a parameterized rule named on an operation cannot have run in production (`defineWorkspaceOperation` throws at definition time), so something else is wrong. +- **A narrower capability subsumes the broader one it replaced.** An operation carries exactly one capability. Precedent: `knowledge.create` / `knowledge.upload` both read `hideKnowledgeBaseTab`, without which a group withholding the whole module could still create a KB through the API. Check `git log` for a re-pointed `capability:` and verify the narrower rule grew the broader key in the same commit. +- **`detailCode` matches the remedy** — `FORBIDDEN_DETAIL_CODES` is closed over remedies, not causes; otherwise `PERMISSION_GROUP_CAPABILITY_BLOCKED`. Any code in use needs a TSDoc-documented entry in `FORBIDDEN_DETAIL_CODES`, published to OpenAPI as the `V2ForbiddenDetailCode` enum. +- **`describe` reads correctly** as the subject of `" is not available under your organization's permission group"` — a singular noun or gerund agreeing with "is". Exactly two functions build that sentence, both defined in `capabilities.ts` (`refuseCapability` throws it, `capabilityRefusal` returns it); any call site writing it out is a drift finding. -## Step 5: Prove the enforcement +## Step 5: Prove the enforcement — do not assume it -The step this skill exists for. Find the **actual refusal**: file, line, and what the caller sees. +The step the skill exists for. Find the **actual refusal**, name file and line, and say what a caller sees. ```bash grep -rn "''" apps/sim --include='*.ts' --include='*.tsx' grep -rn "permission-group-enforced: " apps/sim ``` -The second grep misses an annotation in a TSDoc block above the statement; read the surrounding function. Classify into exactly one: +The second grep misses a gate whose annotation sits in a TSDoc block above the enclosing statement — read the surrounding function. + +Classify into exactly one of: + +1. **Declared on operations.** The funnel enforces in `requireCurrentHumanAccess` → `requireCapability`. Verify the set is *complete*: enumerate every route and tool reaching the same behavior. One declaring `capability: 'none'` is the hole. +2. **Asserted at a call site** with a `// permission-group-enforced: — ` annotation. Verify it goes through `capability-assertions.ts` (`assertWorkspaceCapability`, `isWorkspaceCapabilityWithheld`, `isOrganizationCapabilityWithheld`, `capabilityDeniedBy`), through `isCapabilityWithheldForUser` (`lib/permission-groups/user-scope.server.ts` — workspace group first, else the organization's default, for a user-level act that may or may not name a workspace; outside `capability-assertions.ts` on purpose because it reads org membership through the billing graph, a guarded root of `check:application-graph`; `app/api/cli/auth/approve/route.ts` is the shape), or a direct `CAPABILITY_RULES[''].deniedBy(...)` rather than reading `config.disableX` inline, **and** that it *raises* through `refuseCapability` / renders `capabilityRefusal(cap)` rather than building its own `ForbiddenOperationError` with a hand-written message — the easy half to miss, because the decision looks right. Use-case shape: `validatePublicFileSharing`, `validateChatDeployAuth` (`ee/access-control/utils/permission-check.ts`), `assertConnectorTypeAllowed` (`lib/knowledge/application/connectors.ts`). Raw-route shape: `app/api/logs/stats/route.ts`, `app/api/table/[tableId]/export/route.ts`. A raw route should render through `capabilityRefusalResponse` (`lib/permission-groups/capability-response.ts`), which reads `details.code` off the rule — a hand-rolled `NextResponse.json({ error: capabilityRefusal(cap) }, { status: 403 })` drops it, reporting the four specifically-coded capabilities (`deploy.chat.auth_mode`, `file_share.publish`, `file_share.auth_mode`, `personal_api_key.use`) as the generic block. Convergence is partial: `grep -rln "capabilityRefusal(" apps/sim/app --include=route.ts` lists the raw routes that still hand-roll it (ignore `*.test.ts`, `app/api/v1/middleware.ts`, `app/api/table/utils.ts`, and the v2 envelope, which are not raw-route responses). A raw route you add or touch renders through `capabilityRefusalResponse`; report an untouched hand-rolled one as a finding when its capability carries a specific code, otherwise as a note. v1 is deliberately not converged on it (`resolveCapabilityRefusal` in `app/api/v1/middleware.ts`). +3. **Executor-gated** by `assertPermissionsAllowed`, per block / tool / model, matching through the shared primitives in `lib/permission-groups/` — `block-access.ts`, `operation-access.ts`, `model-access.ts`, `integration-allowlist.ts` — which the editor and Copilot projections read too, so a second copy of a match rule is a finding. Verify the branch throws a real error and that the id it compares against is the vocabulary the admin UI writes — `deniedTools` holds block `tools.access` ids verbatim, version suffix included. `allowedIntegrations` is *also* enforced off the run, by `assertSelectorIntegrationAllowed` (`lib/selectors/server/integration-access.ts`), so an executor key's coverage is not complete until every non-run path that reaches the third party is checked too. +4. **A field projection, not a gate.** `logs.trace_spans` and `logs.cost` withhold fields, so the logs routes correctly declare `capability: 'none'`. Single owner: `lib/logs/projection.ts` (`resolveLogFieldProjection`, `projectExecutionData`, `projectCostTotal`), which carries both annotations. A **second** implementation of the same redaction is the finding — as is a query that lets a caller filter or sort on a withheld field, which turns the projection into an oracle. +5. **Nothing.** Report as a defect: "an organization that sets this believes it applied a restriction that does not exist". + +Ahead of all five: the principal-wide capabilities (`personal_api_key.use`, `oauth_apps.use`; `PRINCIPAL_WIDE_CAPABILITIES` in `lib/core/application/operation.ts`) fit none of them. They withhold a *principal kind* across every operation — the funnel's `personal_api_key` / `oauth_access_token` branches (`lib/core/application/workspace-authorization.ts`) and `app/api/v1/middleware.ts` — and declaring one on an operation throws, so their absence from every `capability:` field is correct, not a hole. + +Then **make the refusal happen**: write a failing case, or remove the gate (the `capability:` field, the `deniedBy` body, the assertion call) and confirm an existing test goes red. A test that still passes with the gate removed proves nothing. Restore afterward. **Check the fixture's `workspaceOrganizationId` first**: `requireCapability` short-circuits when it is `null` (`requireCapability` in `lib/core/application/workspace-authorization.ts`), so a context that leaves it unset passes either way and the existing test proves nothing even before you touch it. + +For an allowlist the three states must be tested separately — `null` permits every member, a populated list only the named ones, `[]` permits **none**. `capabilities.test.ts` pins all three for `knowledge.connectors`; less than that elsewhere is a gap. + +### Who the gate runs against + +**Read the subject, not the nearest user id.** Every capability sink must take its subject from the `capabilityGoverned*` helper for the identity the surface holds — `capabilityGovernedPrincipalUserId` for a `Principal` (`lib/core/application`), `capabilityGovernedUserId` for a v1 `RateLimitResult` or a `TableAccessPrincipal`, `capabilityGovernedAuthUserId` for a `checkSessionOrInternalAuth` result. Each returns `null` where no group governs, and `null` is a pass. Reading `rateLimit.userId`, `auth.userId`, `subjectUserId` or `triggeredByUserId` into a sink is the finding: for a workspace key the first is the key's *creator*, for an internal JWT the second is the run's actor, and the last is a billing *attribution*. `check-capability-subject.ts` audits **v1 only**, so every other surface is on you. Where the subject is persisted and read back later (`capabilityGovernedUserId` on `table_run_dispatches` / `table_row_executions`), it must be declared required as `string | null` — an optional field with a fallback is exactly how producers re-inherited `triggeredByUserId`, so a proposal to make it optional is a finding. + +- **`/api/v1`** authorizes in `app/api/v1/middleware.ts`, not through `authorizeWorkspaceOperation`; `capabilityGovernedUserId(rateLimit)` branches on `keyType`, never on the presence of a user id. Each route also threads a required, spelled-out `V1RouteCapability`. +- **Raw internal table routes** gate `tables.use` in `checkAccess` (`app/api/table/utils.ts`) via a `TableAccessPrincipal` union — `{ kind: 'user'; userId }` or `{ kind: 'workspace_api_key'; keyCreatorUserId }` — so a bare id does not type-check. `tableAccessPrincipal(rateLimit)` is the one place v1 builds it. +- **The definition-time `undefined` guard** on `defineWorkspaceOperation` is not redundant even though `capability` is required on the `ApplicationOperation` **base type** (the `capability` field in `lib/core/application/operation.ts`, not merely on the builder — which is what stops a bare-literal factory from compiling): `apps/sim/tsconfig.json` excludes `*.test.ts` / `*.test.tsx` and the enforcement audit walks past test files, so a fixture is the one construction site no static check reads. Without it a capability-less operation defines cleanly and then throws `Cannot read properties of undefined` inside `capabilityDeniedBy` **only for tenants that actually have a permission group**, passing CI and every personal workspace. A proposal to drop it is a finding. + +## Step 6: Tests + +- **`fields.test.ts`** — the key must be in both the `input` and `expected` halves of the `'a fully populated config'` fixture; that corpus is pinned so a changed row is defended rather than slipping through. The rest of the file derives from `DEFAULT_PERMISSION_GROUP_CONFIG` and needs no per-key edit. +- **`capabilities.test.ts`** — a case for any rule with logic beyond reading one key: subsumption, allowlist three-state, auth-mode membership. +- **`features.test.ts`** — no edit for a boolean; a non-boolean key's `limited` / `empty` prose should be pinned here. +- **`config-scope.server.test.ts`** — the per-request memo. A gate resolving the config outside `resolvePermissionGroupConfig` is a Step 2 finding, not one here. + +## Step 7: Run the checks + +```bash +bun run check:permission-group-enforcement +bun run check:application-graph +bun run check:capability-subject +cd apps/sim && bun run type-check +bun run --cwd apps/sim test lib/permission-groups +``` + +All three are inside `check:audits`, which derives its list from the `check:*` scripts in `package.json` — a new audit is opted *out* deliberately. Read the output, not the exit codes. Success-line shapes (the counts must include the item under audit): + +``` +✓ permission-group enforcement: operations declare a capability, capabilities all enforced +✅ Application graph clean: roots reach none of forbidden module trees +check:capability-subject — v1 files, capability subjects resolved through capabilityGovernedUserId. +``` -1. **Declared on operations** (funnel: `requireCurrentHumanAccess` → `requireCapability`). Verify coverage is *complete*: enumerate every route and tool reaching the same behavior; one declaring `capability: 'none'` is the hole. A capability declared on an operation nothing routes to also satisfies the audit. -2. **Asserted at a call site**: must go through `capability-assertions.ts` / `isCapabilityWithheldForUser` or `CAPABILITY_RULES[id].deniedBy`, raise via `refuseCapability`, or wrap `capabilityRefusal(cap)` where the surface keeps its own error type (OAuth, MCP, `OrchestrationError`); a hand-written refusal message is the finding (the decision can look right while the message drifts). Raw routes render `capabilityRefusalResponse`. Examples: `assertConnectorTypeAllowed`, `app/api/logs/stats/route.ts`. `grep -rln "capabilityRefusal(" apps/sim/app --include=route.ts` lists raw routes still hand-rolling the 403: a finding when the capability carries a specific `detailCode`, otherwise a note. v1 renders its own envelope on purpose. -3. **Executor-gated** by `assertPermissionsAllowed` through the shared `lib/permission-groups/*-access.ts` primitives; a second copy of a match rule is a finding. Check the compared id is the vocabulary the admin UI writes (`deniedTools` holds `tools.access` ids verbatim, version suffix included), and that non-run paths reaching the third party are gated too (`assertSelectorIntegrationAllowed` for `allowedIntegrations`). -4. **A field projection** (`logs.trace_spans`, `logs.cost`): single owner `lib/logs/projection.ts`. A second redaction, or a query that filters/sorts on a withheld field, is the finding. -5. **Nothing.** Report: "an organization that sets this believes it applied a restriction that does not exist". +| Audit | What it catches | +|---|---| +| `check:permission-group-enforcement` | Every operation declares a capability and every capability is enforced. All-or-nothing — no migration mode exits 0 with work outstanding, so do not go looking for a `pending enforcement:` list | +| `check:application-graph` | The funnel roots (`lib/core/application/index.ts`, `capabilities.ts`, `capability-assertions.ts`, `config-scope.server.ts`) and `with-route-handler.ts` reach no heavy module tree at *runtime* (`import type` is erased and allowed). A gate that imports a resolver into a guarded root is a finding even if the gate is correct; such an edge can also make unrelated tests fail on partial mocks | +| `check:capability-subject` | Every v1 capability sink takes its subject from `capabilityGovernedUserId`, no v1 file outside the middleware imports the permission-group modules, and at least one governed sink was found at all | -Principal-wide capabilities (`personal_api_key.use`, `oauth_apps.use`) fit none of these: their absence from every `capability:` field is correct. +Two ways the enforcement audit passes without proving what you want: -**Then make the refusal happen**: write a failing case, or remove the gate and confirm an existing test goes red; restore afterward. Check the fixture's `workspaceOrganizationId` first: `requireCapability` short-circuits on `null`, so such a test proves nothing even before you touch it. +- **Vacuous parse.** It reads source text with regexes, so it refuses success when the three registries parse to nothing, cross-checks rule count against capability count, reports per call any unreadable `id`, fails a file that mints an operation but parses to **zero** declarations, and flags any exported `*Operations` registry member it read no operation from. If one fires the audit is broken, not the code — fix the parsers rather than leaving it green. (That last guard is what catches an operation minted by a factory that never calls the builder, which bypasses the required type *and* the audit.) +- **A capability declared on an operation nothing routes to.** Assertion C is satisfied by the declaration alone. -**Check the subject.** The gate's user id must come from the `capabilityGoverned*` helper for the identity held. Reading `rateLimit.userId` (a workspace key's creator), `auth.userId` (an internal JWT's run actor) or `triggeredByUserId` (a billing attribution) into a sink is a finding; `check:capability-subject` covers v1 only. A proposal to make a persisted subject optional, to drop the definition-time `capability` guard (test fixtures are the one construction site no static check reads), or to exempt Copilot is a finding. +The audits prove *reachability*, never correctness — that a capability is named, a key is read by some rule, a subject came from the right helper. Step 5 is what covers the rest. -## Step 6: Tests and checks +## Known gaps — recognize these, do not re-report them -- `fields.test.ts`: key in both halves of `'a fully populated legacy config'`. -- `capabilities.test.ts`: a case for any rule with logic beyond one key (subsumption, allowlist `null`/list/`[]`, auth-mode membership). `features.test.ts`: a non-boolean key's `limited`/`empty` prose pinned. -- Run `check:permission-group-enforcement`, `check:application-graph`, `check:capability-subject`, and `bun run --cwd apps/sim test lib/permission-groups`; the success-line counts must include this item. The audits prove reachability, never correctness: Step 5 covers the rest. +Each is deliberate and documented in the code; `add-permission-group-item` carries the full reasoning. -## Known gaps: do not re-report +- **A workspace API key resolves no permission group** — it authorizes as the workspace, so there is no user and `operation.capability` does not apply; the same reasoning shapes `TableAccessPrincipal`, `capabilityGovernedUserId` and the log projection. Substituting the key's creator would apply a bystander's group to every caller of a shared key and break the key when that person left. Minting a workspace key is itself capability-gated. +- **An executor delegation carries role but not capabilities** — a delegated `executor` principal with a `sim_user` subject goes through `requireCurrentHumanRole` only. A capability names what a *person* may reach; applying it to a run makes "hide Tables" a kill-switch for every workflow with a Table block. +- **An actorless deployment run passes through** — a delegated executor principal in `mode: 'deployment'` with no resolvable subject acts with the workspace's authority; denying would 403 every scheduled run, webhook and public-API call. What such a run *does* is still governed by `assertPermissionsAllowed`, which is why the four run-scoped keys carry `enforcement: 'executor'`. +- **Copilot is NOT exempt** — a delegated principal with a `sim_user` subject whose `serviceId` is anything other than `executor` takes the full `requireCurrentHumanAccess`. Copilot acts as the person. A proposal to exempt it is a finding. +- **Capability is checked after the role check** — `NoWorkspaceAccessError` is concealed as a 404 by the v2 surface, so refusing on capability first would hand a non-member an oracle for what the organization withholds. The v1 middleware states the same ordering in its TSDoc. Not a bug. +- **`allowedEgressHosts` does not exist** — there is no network-egress allowlist. Requests for one are a feature, not missing wiring. +- **Nothing currently ships as `ui-only`** — the union member has no user; an absent `ui-only` key is not a gap. -These are deliberate (reasons in `add-permission-group-item` Traps): a workspace API key resolves no group; an executor delegation is role-only; an actorless deployment run passes; capability is checked after the role check; nothing ships as `ui-only`. `allowedEgressHosts` does not exist: a request for one is a feature, not missing wiring. +## Report Format -## Report +1. **Kind and enforcement** — as declared, and whether the declaration is true. +2. **The refusal** — file, line, error thrown, what the caller sees (status, `detailCode`, message). Or: it is a projection, and here is its single owner. Or: nothing refuses. +3. **The subject** — whose user id the gate reads, and that a workspace key reaches it ungated rather than as its creator. +4. **Proof** — the test that fails when the gate is removed, or that no such test exists. +5. **Coverage gaps** — routes, tools, surfaces reaching the same behavior without the gate. +6. **Findings**, ordered: unenforced key > key-creator substituted for the acting principal > fail-open coercion (`.catch()` on an array, a dropped `Array.isArray` guard, `CAPABILITY_RULES` annotated instead of `satisfies`) > incomplete operation coverage > allowlist three-state confusion > **admin copy that misstates the enforcement** > duplicated projection logic > missing admin UI > missing test > cosmetic. -1. **Kind and enforcement**, as declared and whether true. -2. **The refusal**: file, line, error, what the caller sees (status, `detailCode`, message); or its projection owner; or nothing. -3. **The subject**: whose user id the gate reads; a workspace key reaches it ungated, never as its creator. -4. **Proof**: the test that fails with the gate removed, or that none exists. -5. **Coverage gaps**: routes, tools, surfaces reaching the behavior without the gate. -6. **Findings**, ordered: unenforced key > key creator substituted for the acting principal > fail-open coercion > incomplete operation coverage > allowlist three-state confusion > admin copy that misstates enforcement > duplicated projection > missing admin UI > missing test > cosmetic. +A hint saying "hide" for a key that 403s is not cosmetic — it is the one defect an admin acts on directly: they tick it believing they hid a link, and members lose the module. Rank it with the enforcement findings. diff --git a/.agents/skills/validate-selector/SKILL.md b/.agents/skills/validate-selector/SKILL.md index 2e7d9e29661..1b2ea55fd7a 100644 --- a/.agents/skills/validate-selector/SKILL.md +++ b/.agents/skills/validate-selector/SKILL.md @@ -6,30 +6,95 @@ argument-hint: # Validate Selector -Validate the complete path (declaration, manifest, context, attachment, provider primitive, shared executor), not only the provider adapter. `add-selector` holds the conventions. Search literal API paths as well as imports before declaring an old provider route or contract unused. +Validate the complete path, not only the provider adapter. -## Declaration and manifest +## Gather the path -- Allowed context is minimal; readiness matches the provider request; list, pagination, search, detail, scope and stale-time metadata match the actual UX. -- `dependsOn` names the required source fields; canonical pairs contribute only their active member; action/trigger and connector surfaces build the same context. -- Exact `{{KEY}}` references stay unresolved in the browser and runtime references are omitted; embedded interpolation is forwarded unresolved and rejected by the server executor. +Read: -## Server boundary +- Every block, trigger, and connector field using the selector key. +- `apps/sim/lib/selectors/manifest.ts` and `types.ts`. +- `apps/sim/lib/selectors/context.ts`. +- The matching server attachment and any shared provider listing primitive. +- `apps/sim/lib/selectors/server/registry.ts`. +- The shared application executor, route contract, client transport, and focused tests when the + finding concerns shared behavior. -`selectors.execute` accepts session, personal API key, OAuth token and delegated Copilot principals (internal route and `v2/selectors`). Confirm the shared executor owns this order, and the attachment duplicates none of it: +Search literal API paths as well as TypeScript imports before deciding whether an old provider route +or contract is unused. -1. Authenticate the principal before parsing. -2. Load the canonical workflow/workspace and authorize read. +## Validate the declaration and manifest + +- The key has exactly one classification and one attachment (`local` keys use the local registry). +- Allowed context is minimal and readiness matches the provider request. +- List, pagination, search, detail, unknown-detail, scope, and stale-time metadata match actual UX. +- `dependsOn` names the required source fields; canonical pairs contribute only their active member. +- Action/trigger and connector surfaces build the same canonical context. +- Exact `{{KEY}}` references remain unresolved in the browser; runtime references are omitted, + while embedded interpolation is forwarded unresolved and rejected by the server executor. +- Query keys contain no context value, reference, credential ID, secret, or hash of one. + +## Validate the server boundary + +For provider and internal selectors, confirm the shared executor owns this order: + +1. Session authentication before request parsing. +2. Canonical workflow/workspace loading and read authorization. 3. Manifest capability and exact-context allowlisting. 4. Exact environment-reference resolution on the server. 5. Credential use, workspace, and trusted provider/service binding. -6. Destination policy before any provider network access (`assertSelectorIntegrationAllowed` included). -7. Execution, then explicit option projection and sanitization. +6. Destination-policy enforcement before provider network access. +7. Provider/internal execution followed by explicit option projection and sanitization. + +The attachment must not duplicate these shared checks. It must not accept a browser-provided module, +provider, service, operation kind, origin, or scope list. + +Review its destination classification: + +- `fixed` origins are code-defined. +- `credential-bound` origins are derived from or checked against the authorized credential. +- `user-controlled` destinations have an explicit policy for hidden use-only authentication and + network safety. + +Missing and inaccessible references, and missing, unauthorized, or provider-mismatched credentials, +must not become existence oracles. Hidden/server-only resolved plaintext, credentials, authentication +material, and raw upstream errors must not enter responses, query/cache/rate keys, selector result +caches, logs, audit metadata, redirects, or error messages. Browser-known literals and viewable +personal/shared values are not automatically protected plaintext, but the executor must still never +deliberately or wholesale echo selector context. Only intentionally projected, normalized +`{ id, label, meta? }` options and bounded cursors may cross the boundary. + +Selector code adds no context, token, or result cache beyond the single accepted exception +described in the `add-selector` skill ("Wire the UI declaration"). + +## Validate provider reuse and browser boundaries + +- The attachment calls a server-only provider primitive, not a route handler or internal HTTP URL. +- A surviving provider route has a proven non-selector caller and delegates to the same primitive. +- There is no client provider selector module, selector-specific token request, or browser request to + a provider-specific selector route. +- Internal selectors delegate to existing authorized use cases rather than querying protected data + in the route or adapter. + +## Tests and report + +Use existing Vitest/route/React Query patterns. Preserve valuable provider tests, but do not demand a +per-selector authorization matrix. Shared executor tests should cover ordering, references, +credential binding, sanitization, and safe errors; adapter tests should cover only special provider +behavior. -Missing or unauthorized references and credentials must not be existence oracles; resolved secrets and raw upstream errors never reach responses, keys, caches, logs, audit or errors. Only projected `{ id, label, meta? }` options and bounded cursors cross. Browser-known literals and viewable values are not automatically protected, but context is never echoed wholesale. +Report critical, warning, and suggestion findings. Treat browser secret resolution, missing scope or +credential authorization, unsafe destination binding, provider payload passthrough, and plaintext +egress as critical. -Check the destination classification is honest and that internal selectors delegate to authorized use cases rather than querying in the adapter. +Run the smallest relevant focused suites plus: -## Report +```bash +bun run --cwd apps/sim type-check +bun run check:api-validation:strict +bun run check:fork-dependent-coverage +bun run check:client-boundary +git diff --check +``` -Critical, warning and suggestion findings. Critical: browser secret resolution, missing scope or credential authorization, unsafe destination binding, provider payload passthrough, plaintext egress. State which live-provider checks remain pending when disposable credentials are unavailable. +State which live-provider checks remain pending when disposable credentials are unavailable. diff --git a/.agents/skills/validate-trigger/SKILL.md b/.agents/skills/validate-trigger/SKILL.md index b174ea9fcf3..fe61054b4bc 100644 --- a/.agents/skills/validate-trigger/SKILL.md +++ b/.agents/skills/validate-trigger/SKILL.md @@ -6,24 +6,236 @@ argument-hint: [api-docs-url] # Validate Trigger -The rules are in `/add-trigger` and `apps/sim/triggers/AGENTS.md`; this skill is the audit procedure. Read every file in `apps/sim/triggers/{service}/`, the handler `apps/sim/lib/webhooks/providers/.ts` (kebab-case: `azure-devops.ts` for `azure_devops`) and its registry entry, and the block's trigger wiring. If a trigger subblock uses a `selectorKey`, also run the `validate-selector` skill. +You are an expert auditor for Sim webhook triggers. Your job is to validate that an existing trigger implementation is correct, complete, secure, and aligned across all layers. -The service's webhook docs are the source of truth for event types and payloads, the signature method (algorithm, header, secret format), any challenge handshake, the subscription API, and retry behaviour. Report payload fields the docs don't show instead of guessing them. +## Your Task -## Checks +1. Read the service's webhook/API documentation (via WebFetch) +2. Read every trigger file, provider handler, and registry entry +3. Cross-reference against the API docs and Sim conventions +4. Report all issues grouped by severity (critical, warning, suggestion) +5. Fix all issues after reporting them -- **Definitions.** Webhook triggers use `buildTriggerSubBlocks` (directly or through a service wrapper) unless they deliberately keep a custom layout, as `apps/sim/triggers/airtable/webhook.ts` does. Trigger ids follow `{service}_{event}`, and `provider` equals the handler registry key. -- **Event mapping.** Every trigger id `matchEvent` references exists in the service's trigger options and maps to the documented event type; a generic webhook trigger passes every event. Challenge or verification events never match. Trigger utils are loaded with a dynamic `await import()` to avoid a cycle. -- **Auth.** `verifyAuth` uses the documented algorithm, header name, and signature format (hex, `sha256=` prefix, base64), computed over the raw body, compared with `safeCompare` (never `===`), and fails closed when a required secret is missing. It runs before any processing; the replay window tolerates provider retries without being loose; secrets are never logged, even at debug. -- **`formatInput`.** Matches `outputs` exactly per `apps/sim/triggers/AGENTS.md`, nested at the right depth, returned as `{ input }`. -- **Idempotency.** `extractIdempotencyId` uses the provider's delivery id (`Linear-Delivery`, `svix-id`) when there is one, otherwise a content id like `${type}:${id}`, never a timestamp (that breaks dedup on retries). -- **Challenge.** `handleChallenge` returns exactly the documented response; env-backed secrets resolve through `resolveEnvVarsInObject`. -- **Subscriptions.** `createSubscription` calls the right endpoint with the right events and `getNotificationUrl(ctx.webhook)`, maps 401 and similar to friendly messages, and returns the external id. `deleteSubscription` treats 404 as done and skips quietly when the key or external id is missing, unless `ctx.strict` is set, when it throws. No provider logic in the shared orchestration (`route.ts`, `provider-subscriptions.ts`, `deploy.ts`). -- **Registration.** Every trigger file has an `apps/sim/triggers/registry.ts` entry keyed by its exact id. -- **Block wiring.** `triggers.available` and the spread `getTrigger(...).subBlocks` name the same triggers. +## Step 1: Gather All Files -## Report and fix +Read **every** file for the trigger — do not skip any: -Report as **Critical** (wrong signature algorithm or header, `===` on secrets, missing `verifyAuth` for signed webhooks, `formatInput`/`outputs` mismatch, id mismatches across trigger, registry, and block, provider logic in shared orchestration, a wrong subscription endpoint, or a selector security break), **Warning** (missing idempotency or challenge handling, timestamps in idempotency keys, too tight a replay window, unfiltered challenge events, undiscoverable fields, incomplete setup instructions), and **Suggestion** (descriptions, extra outputs, messages, logging). Fix every critical and warning, and suggestions where cheap. +``` +apps/sim/triggers/{service}/ # All trigger files, utils.ts, index.ts +apps/sim/lib/webhooks/providers/{service}.ts # Provider handler (if exists) +apps/sim/lib/webhooks/providers/registry.ts # Handler registry +apps/sim/triggers/registry.ts # Trigger registry +apps/sim/blocks/blocks/{service}.ts # Block definition (trigger wiring) +``` -Run the handler's tests with `bun run --cwd apps/sim test lib/webhooks/providers/`: handler files are kebab-case (`azure-devops.ts`) while trigger folders are snake_case (`azure_devops`). +Also read for reference: +``` +apps/sim/lib/webhooks/providers/types.ts # WebhookProviderHandler interface +apps/sim/lib/webhooks/providers/utils.ts # Shared helpers (createHmacVerifier, etc.) +apps/sim/lib/webhooks/provider-subscription-utils.ts # Subscription helpers +apps/sim/lib/webhooks/processor.ts # Central webhook processor +``` + +If trigger sub-blocks use a `selectorKey`, also apply the `validate-selector` skill and read the +key's browser-safe manifest entry, shared active-value context builder, server attachment, and +provider listing primitive. + +## Step 2: Pull API Documentation + +Fetch the service's official webhook documentation. This is the **source of truth** for: +- Webhook event types and payload shapes +- Signature/auth verification method (HMAC algorithm, header names, secret format) +- Challenge/verification handshake requirements +- Webhook subscription API (create/delete endpoints, if applicable) +- Retry behavior and delivery guarantees + +### Hard Rule: No Guessed Webhook Payload Schemas + +If the official docs do not clearly show the webhook payload JSON for an event, you MUST tell the user instead of guessing. + +- Do NOT invent payload field names +- Do NOT infer nested payload paths without evidence +- Do NOT treat likely event shapes as verified +- Do NOT accept `formatInput` mappings that are not backed by docs or live payloads + +If a payload schema is unknown, validation must explicitly recommend: +1. sample webhook payloads, +2. a live test webhook source, or +3. trimming the trigger to only documented outputs. + +## Step 3: Validate Trigger Definitions + +### utils.ts +- [ ] `{service}TriggerOptions` lists all trigger IDs accurately +- [ ] `{service}SetupInstructions` provides clear, correct steps for the service +- [ ] `build{Service}ExtraFields` includes relevant filter/config fields with correct `condition` +- [ ] Output builders expose all meaningful fields from the webhook payload +- [ ] Output builders do NOT use `optional: true` or `items` (tool-output-only features) +- [ ] Nested output objects correctly model the payload structure + +### Trigger Files +- [ ] Exactly one primary trigger has `includeDropdown: true` +- [ ] All secondary triggers do NOT have `includeDropdown` +- [ ] Webhook triggers use `buildTriggerSubBlocks` (directly or through a service wrapper) unless they deliberately keep a custom layout, as `triggers/airtable/webhook.ts` does; polling triggers (`polling: true`) declare subBlocks manually +- [ ] Every trigger's `id` matches the convention `{service}_{event_name}` +- [ ] Every trigger's `provider` matches the service name used in the handler registry +- [ ] `index.ts` barrel exports all triggers +- [ ] Every remote `selectorKey` is present in `apps/sim/lib/selectors/manifest.ts` and has exactly + one server attachment +- [ ] Trigger-mode `dependsOn` fields project only active canonical values; exact `{{KEY}}` + references stay unresolved in the browser +- [ ] Trigger selectors use the shared `selectors.execute` transport, with no client provider + module, browser token request, or selector-only provider route + +### Trigger ↔ Provider Alignment +- [ ] Every trigger ID referenced in `matchEvent` logic exists in `{service}TriggerOptions` +- [ ] Event matching logic in the provider correctly maps trigger IDs to service event types +- [ ] Event matching logic in `is{Service}EventMatch` (if exists) correctly identifies events per the API docs + +## Step 4: Validate Provider Handler + +### Auth Verification +- [ ] `verifyAuth` correctly validates webhook signatures per the service's documentation +- [ ] HMAC algorithm matches (SHA-1, SHA-256, SHA-512) +- [ ] Signature header name matches the API docs exactly +- [ ] Signature format is handled (raw hex, `sha256=` prefix, base64, etc.) +- [ ] Uses `safeCompare` for timing-safe comparison (no `===`) +- [ ] If `webhookSecret` is required, handler rejects when it's missing (fail-closed) +- [ ] Signature is computed over raw body (not parsed JSON) + +### Event Matching +- [ ] `matchEvent` returns `true` to run, or `false` / a `NextResponse` to skip with a custom body +- [ ] Challenge/verification events are excluded from matching (e.g., `endpoint.url_validation`) +- [ ] When `triggerId` is a generic webhook ID, all events pass through +- [ ] When `triggerId` is specific, only matching events pass +- [ ] Event matching logic uses dynamic `await import()` for trigger utils (avoids circular deps) + +### formatInput +- [ ] Every key in the `formatInput` return matches a key in the trigger `outputs` schema +- [ ] Every key in the trigger `outputs` schema is populated by `formatInput` +- [ ] No extra undeclared keys that users can't discover in the UI +- [ ] No wrapper objects (`webhook: { ... }`, `{service}: { ... }`) +- [ ] Nested output paths exist at the correct depth (e.g., `resource.id` actually has `resource: { id: ... }`) +- [ ] `null` is used for missing optional fields (not empty strings or empty objects) +- [ ] Returns `{ input: { ... } }` — not a bare object +- [ ] Every mapped payload field is backed by official docs or live-verified webhook payloads + +### Idempotency +- [ ] `extractIdempotencyId` returns a stable, unique key per delivery +- [ ] Uses provider-specific delivery IDs when available (e.g., `X-Request-Id`, `Linear-Delivery`, `svix-id`) +- [ ] Falls back to content-based ID (e.g., `${type}:${id}`) when no delivery header exists +- [ ] Does NOT include timestamps in the idempotency key (would break dedup on retries) + +### Challenge Handling (if applicable) +- [ ] `handleChallenge` correctly implements the service's URL verification handshake +- [ ] Returns the expected response format per the API docs +- [ ] Env-backed secrets are resolved via `resolveEnvVarsInObject` if needed + +## Step 5: Validate Automatic Subscription Lifecycle + +If the service supports programmatic webhook creation: + +### createSubscription +- [ ] Calls the correct API endpoint to create a webhook +- [ ] Sends the correct event types/filters +- [ ] Passes the notification URL from `getNotificationUrl(ctx.webhook)` +- [ ] Returns `{ providerConfigUpdates: { externalId } }` with the external webhook ID +- [ ] Throws on failure (orchestration handles rollback) +- [ ] Provides user-friendly error messages (401 → "Invalid API Key", etc.) + +### deleteSubscription +- [ ] Calls the correct API endpoint to delete the webhook +- [ ] Handles 404 gracefully (webhook already deleted) +- [ ] Never throws — catches errors and logs non-fatally +- [ ] Skips gracefully when `apiKey` or `externalId` is missing + +### Orchestration Isolation +- [ ] NO provider-specific logic in `route.ts`, `provider-subscriptions.ts`, or `deploy.ts` +- [ ] All subscription logic lives on the handler (`createSubscription`/`deleteSubscription`) + +## Step 6: Validate Registration and Block Wiring + +### Trigger Registry (`triggers/registry.ts`) +- [ ] All triggers are imported and registered +- [ ] Registry keys match trigger IDs exactly +- [ ] No orphaned entries (triggers that don't exist) + +### Provider Handler Registry (`providers/registry.ts`) +- [ ] Handler is imported and registered (if handler exists) +- [ ] Registry key matches the `provider` field on the trigger configs +- [ ] Entries are in alphabetical order + +### Block Wiring (`blocks/blocks/{service}.ts`) +- [ ] Block has `triggers.enabled: true` +- [ ] `triggers.available` lists all trigger IDs +- [ ] All trigger subBlocks are spread into `subBlocks`: `...getTrigger('id').subBlocks` +- [ ] No trigger IDs in `triggers.available` that aren't in the registry +- [ ] No trigger subBlocks spread that aren't in `triggers.available` + +## Step 7: Validate Security + +- [ ] Webhook secrets are never logged (not even at debug level) +- [ ] Auth verification runs before any event processing +- [ ] No secret comparison uses `===` (must use `safeCompare` or `crypto.timingSafeEqual`) +- [ ] Timestamp/replay protection is reasonable (not too tight for retries, not too loose for security) +- [ ] Raw body is used for signature verification (not re-serialized JSON) + +## Step 8: Report and Fix + +### Report Format + +Group findings by severity: + +**Critical** (runtime errors, security issues, or data loss): +- Wrong HMAC algorithm or header name +- `formatInput` keys don't match trigger `outputs` +- Missing `verifyAuth` when the service sends signed webhooks +- Provider-specific logic leaking into shared orchestration files +- Trigger IDs mismatch between trigger files, registry, and block +- `createSubscription` calling wrong API endpoint +- Auth comparison using `===` instead of `safeCompare` +- Trigger selector credential/reference resolution occurring in the browser, or a selector missing + scope authorization, credential provider binding, destination enforcement, or safe projection + +**Warning** (convention violations or usability issues): +- Missing `extractIdempotencyId` when the service provides delivery IDs +- Timestamps in idempotency keys (breaks dedup on retries) +- Missing challenge handling when the service requires URL verification +- Output schema missing fields that `formatInput` returns (undiscoverable data) +- Overly tight timestamp skew window that rejects legitimate retries +- `matchEvent` not filtering challenge/verification events +- Setup instructions missing important steps + +**Suggestion** (minor improvements): +- More specific output field descriptions +- Additional output fields that could be exposed +- Better error messages in `createSubscription` +- Logging improvements + +### Fix All Issues + +After reporting, fix every **critical** and **warning** issue. Apply **suggestions** where they don't add unnecessary complexity. + +### Validation Output + +After fixing, confirm: +1. `bun run type-check` passes +2. Re-read all modified files to verify fixes are correct +3. Provider handler tests pass (if they exist): `bun run --cwd apps/sim test lib/webhooks/providers/` — handler files are kebab-case (`azure-devops.ts`) while trigger directories are snake_case (`azure_devops`), so use the handler's actual basename +4. Any remaining unknown webhook payload schemas were explicitly reported to the user instead of guessed + +## Checklist Summary + +- [ ] Read all trigger files, provider handler, types, registries, and block +- [ ] Pulled and read official webhook/API documentation +- [ ] Validated trigger definitions: options, instructions, extra fields, outputs +- [ ] Validated dynamic selector declarations through the shared manifest and server attachment +- [ ] Validated primary/secondary trigger distinction (`includeDropdown`) +- [ ] Validated provider handler: auth, matchEvent, formatInput, idempotency +- [ ] Validated output alignment: every `outputs` key ↔ every `formatInput` key +- [ ] Validated subscription lifecycle: createSubscription, deleteSubscription, no shared-file edits +- [ ] Validated registration: trigger registry, handler registry, block wiring +- [ ] Validated security: safe comparison, no secret logging, replay protection +- [ ] Reported all issues grouped by severity +- [ ] Fixed all critical and warning issues +- [ ] `bun run type-check` passes after fixes diff --git a/.agents/skills/you-might-not-need-a-callback/SKILL.md b/.agents/skills/you-might-not-need-a-callback/SKILL.md new file mode 100644 index 00000000000..3e78befc072 --- /dev/null +++ b/.agents/skills/you-might-not-need-a-callback/SKILL.md @@ -0,0 +1,60 @@ +--- +name: you-might-not-need-a-callback +description: Analyze and fix useCallback anti-patterns in your code +argument-hint: "[scope] [fix=true|false]" +--- + +# You Might Not Need a Callback + +Arguments: +- scope: what to analyze (default: your current changes). Examples: "diff to staging", "PR #123", "src/components/", "whole codebase" +- fix: whether to apply fixes (default: true). Set to false to only propose changes. + +User arguments: $ARGUMENTS + +## References + +Read before analyzing: +1. https://react.dev/reference/react/useCallback — official docs on when useCallback is actually needed + +## The one rule that matters + +`useCallback` is only useful when **something observes the reference**. Ask: does anything care if this function gets a new identity on re-render? + +Observers that care about reference stability: +- A `useEffect` that lists the function in its deps array +- A `useMemo` that lists the function in its deps array +- Another `useCallback` that lists the function in its deps array +- A child component wrapped in `React.memo` that receives the function as a prop +- A custom hook that documents a referential-stability requirement for the callback + +If none of those apply — if the function is only called inline, or passed to a non-memoized child, or assigned to a native element event — the reference is unobserved and `useCallback` adds overhead with zero benefit. + +## Anti-patterns to detect + +1. **No observer tracks the reference**: The function is only called inline in the same component, or passed to a non-memoized child, or used as a native element handler (`