.github/9
ISSUE_TEMPLATE/3bug_report.md config.yml feature_request.md
workflows/3ci.yml clean-clone.yml release.yml
CODEOWNERS dependabot.yml pull_request_template.md
apps/630
api/250
src/243
common/30
__tests__/3authorize.test.ts bigint-serialization.interceptor.test.ts files-limits.test.ts
filters/1all-exceptions.filter.ts
guards/3auth.guard.ts internal-service.guard.ts rate-limit.guard.ts
interceptors/2actor-context.interceptor.ts bigint-serialization.interceptor.ts
middleware/2idempotency.test.ts idempotency.ts
pipes/1zod-validation.pipe.ts
actor-context.ts audit.service.ts cache.test.ts cache.ts cookies.ts core.module.ts deprecation.ts email.service.ts errors.ts event-bus.ts log-scrubber.test.ts log-scrubber.ts logger.ts permission-cache-bridge.ts prisma.service.ts redis.service.ts trace-metadata.ts types.ts
config/1env.ts
lib/11
__tests__/5crypto.test.ts filter-builder.test.ts jwt.test.ts pagination.test.ts positions.test.ts
authorize.ts crypto.ts filter-builder.ts jwt.ts pagination.ts positions.ts
modules/197
ai/28
__tests__/4ai-writing.test.ts database-ai.test.ts generate-executor.test.ts prompts.test.ts
generator/4executor.ts generate.controller.ts generate.dto.ts generate.service.ts
ai-chat.service.ts ai-rate-limit.ts ai-writing.controller.ts ai-writing.dto.ts ai-writing.service.ts ai.controller.ts ai.module.ts ai.service.ts budget-guard.service.ts database-ai.controller.ts database-ai.dto.ts database-ai.service.ts db-prompts.ts dto.ts gateway-provider.ts ledger.service.ts prompts.ts rag.controller.ts rag.dto.ts rag.service.ts
api-keys/3api-keys.controller.ts api-keys.module.ts api-keys.service.ts
audit/2audit-log.controller.ts audit.module.ts
auth/4auth.controller.ts auth.module.ts auth.service.ts dto.ts
automations/5automations.controller.ts automations.module.ts automations.service.ts dto.ts webhook-incoming.controller.ts
blocks/5
__tests__/1batch-version-cas.test.ts
block.service.ts blocks.controller.ts blocks.module.ts dto.ts
comments/4comments.controller.ts comments.module.ts comments.service.ts dto.ts
databases/9
__tests__/3normalize-select-options.test.ts option-id-canonicalization.test.ts record-open-query-shape.test.ts
database.service.ts databases.controller.ts databases.module.ts dto.ts property-cache-schema.ts query.service.ts
docs/2docs.controller.ts docs.module.ts
files/10
__tests__/1quota.test.ts
dto.ts files.controller.ts files.module.ts files.service.ts quota.ts record.ts s3.ts uploads.controller.ts uploads.service.ts
forms/18debug.controller.ts form.dto.ts forms.controller.ts forms.module.ts forms.service.ts markdown.test.ts markdown.ts optional-auth.guard.ts public-forms.controller.ts public-forms.service.ts question.dto.ts questions.service.ts rate-limit.ts recaptcha.ts slug.ts submissions.controller.ts submissions.service.ts submit-schema.ts
health/3health.controller.ts health.module.ts health.service.ts
integrations/3integrations.controller.ts integrations.module.ts integrations.service.ts
internal/12
__tests__/2flush-query-shape.test.ts internal.endpoints.test.ts
ai-test-seam.controller.ts ai-test-seam.dto.ts ai-test-seam.service.ts internal.controller.ts internal.dto.ts internal.module.ts internal.service.ts test-seam.controller.ts test-seam.dto.ts test-seam.service.ts
notifications/3notifications.controller.ts notifications.module.ts notifications.service.ts
oauth/6
__tests__/1oauth.scopes.test.ts
oauth.controller.ts oauth.module.ts oauth.service.ts scopes.ts token-keys.ts
org/15audit.service.ts embed-preview.controller.ts guards.ts members.service.ts org-admin.controller.ts org-policy.service.ts org.module.ts overview.service.ts policy-effective.controller.ts policy.schema.ts policy.test.ts retention.service.ts totp.test.ts totp.ts two-factor.service.ts
orgs/5dto.ts orgs.controller.ts orgs.module.ts orgs.service.ts util.ts
pages/4dto.ts page.service.ts pages.controller.ts pages.module.ts
scim/15
__tests__/3email-mapping.test.ts etag.test.ts filters.test.ts
etag.ts filters.ts groups.service.ts schemas.ts scim-admin.controller.ts scim-admin.service.ts scim-auth.guard.ts scim-auth.service.ts scim-errors.ts scim.controller.ts scim.module.ts users.service.ts
search/4
__tests__/1search.service.test.ts
search.controller.ts search.module.ts search.service.ts
sessions/3sessions.controller.ts sessions.module.ts sessions.service.ts
share/3share.controller.ts share.module.ts share.service.ts
sso/16
__tests__/4enforcement.test.ts oidc.verify.test.ts provisioning.test.ts saml.validate.test.ts
enforcement.ts oidc.controller.ts oidc.service.ts oidc.ts provisioning.service.ts saml.controller.ts saml.ts schemas.ts sso-admin.controller.ts sso-admin.service.ts sso-secrets.ts sso.module.ts
teams/4dto.ts teams.controller.ts teams.module.ts teams.service.ts
users/4dto.ts users.controller.ts users.module.ts users.service.ts
webhooks/3webhooks.controller.ts webhooks.module.ts webhooks.service.ts
workspaces/4dto.ts workspaces.controller.ts workspaces.module.ts workspaces.service.ts
types/1xmldom.d.ts
app.module.ts constants.ts main.ts
_probe_rawbody.cjs .env.example Dockerfile package.json README.md tsconfig.json vitest.config.ts
realtime/33
src/17auth.ts comments.ts config.ts event-source.ts http-store.ts index.ts metrics.ts notifications.ts page-updated-source.ts presence.ts prisma-store.ts protocol.ts rate-limit.ts room-key.ts rooms.ts server.ts update-log.ts
test/11auth.test.ts config.test.ts event-source.test.ts http-store.test.ts metrics-merge.test.ts page-updated-source.test.ts presence.test.ts protocol.test.ts rate-limit.test.ts rooms.test.ts task-0094-builders.test.ts
.env.example Dockerfile package.json README.md tsconfig.json
web/255
src/244
app/45
__tests__/1theme-tokens.test.ts
(app)/26
w/25
[workspace]/25
ask/1page.tsx
databases/1
[id]/1page.tsx
favorites/1page.tsx
files/1page.tsx
notifications/1page.tsx
page/4
[id]/4
[block]/1page.tsx
share/1page.tsx
layout.tsx page.tsx
search/1page.tsx
settings/10
appearance/1page.tsx
automations/3
[id]/1page.tsx
new/1page.tsx
page.tsx
billing/1page.tsx
developers/1page.tsx
members/1page.tsx
permissions/1page.tsx
teams/1page.tsx
page.tsx
shared/1page.tsx
templates/1page.tsx
trash/1page.tsx
layout.tsx page.tsx
layout.tsx
(auth)/4
login/1page.tsx
register/1page.tsx
reset-password/1page.tsx
layout.tsx
api/2
metrics/1route.ts
v1/1
health/1route.ts
f/1
[slug]/1page.tsx
health/1
ready/1route.ts
org/2
[orgId]/2
admin/2
integrations/1page.tsx
page.tsx
share/1
[id]/1page.tsx
error.tsx global-error.tsx globals.css layout.tsx not-found.tsx page.tsx providers.tsx
components/118
admin/10
org-admin/8ApiKeysTab.tsx AuditTab.tsx MembersTab.tsx OverviewTab.tsx PoliciesTab.tsx RetentionTab.tsx WebhooksTab.tsx WorkspacePicker.tsx
ScimCard.tsx SsoTabs.tsx
ai/6ai-panel.tsx ask-ai-submenu.tsx db-ai-dialog.tsx generate-page-dialog.tsx writing-actions-menu.tsx writing-diff.tsx
automations/5action-editor.tsx condition-editor.tsx lib.ts run-history.tsx trigger-editor.tsx
collaboration/6CursorLayer.tsx OfflineBanner.tsx PresenceBar.tsx README.md ReviewFailedDialog.tsx StatusChip.tsx
comments/3comment-panel.tsx comment-thread.tsx mention-input.tsx
database/27
__tests__/2cell-editor.test.tsx cell-renderer.test.tsx
AiExtractDialog.tsx AiFormulaDialog.tsx AiGenerateDialog.tsx board-view.tsx buttons-panel.tsx calendar-view.tsx cell-editor.tsx cell-renderer.tsx chart-view.tsx database-page-view.tsx database-toolbar.tsx database-view-renderer.tsx db-embedded.tsx filter-builder.tsx form-builder-view.tsx formula-editor.tsx gallery-view.tsx group-builder.tsx list-view.tsx property-editor.tsx record-header.tsx record-panel.tsx sort-builder.tsx table-view.tsx timeline-view.tsx
dialogs/7
__tests__/1move-to-dialog.test.tsx
create-dialog.tsx dialog.tsx file-permissions-dialog.tsx invite-dialog.tsx move-to-dialog.tsx share-dialog.tsx
editor/19
__tests__/3code-block-text.test.ts code-block.test.tsx expandable.test.tsx
block-card.tsx block-renderer.tsx block-save-queue.ts block-toolbar.tsx context-menu.tsx expandable.tsx history-popover.tsx inline-editor.tsx insert-dialog.tsx page-canvas.tsx page-spinner.tsx page-view.tsx selection-toolbar.tsx slash-menu.tsx template-dialog.tsx type-menu.tsx
files/4FileBlock.tsx FileBrowser.tsx FilePicker.tsx PreviewModal.tsx
form/4form-field.tsx form-renderer.tsx form-responses-view.tsx form-view.tsx
layout/8
__tests__/1page-tree-icon.test.tsx
command-palette.tsx factory-logo.tsx page-tree-node.tsx sidebar.tsx theme-provider.tsx topbar.tsx workspace-shell.tsx
mentions/3
__tests__/1mention-model.test.ts
mention-model.ts MentionPopup.tsx
search/3ask-ai-search.tsx results-list.tsx search-dialog.tsx
settings/10
api-keys/4ApiKeyCreateDialog.tsx ApiKeyRevealDialog.tsx ApiKeyTable.tsx ScopesBadge.tsx
webhooks/5CurlExamples.tsx DeliveryInspector.tsx EventExplorer.tsx OverviewTab.tsx WebhooksTab.tsx
settings-shell.tsx
ui/3confirm-dialog.tsx form.tsx toaster.tsx
hooks/21
__tests__/4realtime-frame-handler.test.ts use-blocks.test.ts use-database-options.test.ts use-workspace.test.tsx
realtime-frame-handler.ts use-ai-stream.ts use-auth.ts use-blocks.ts use-database.ts use-db-ai-stream.ts use-forms.ts use-members.ts use-mention-sources.ts use-notifications.ts use-offline-status.ts use-pages.ts use-presence-announcer.ts use-presence-toasts.ts use-presence.ts use-realtime.ts use-workspace.ts
lib/50
__tests__/21ai-database.test.ts ai-generate.test.ts ai-sse.test.ts ai-writing.test.ts api-keys.test.ts api-members.test.ts auth-refresh.test.ts auth-store.test.ts batch-queue-drop.test.ts block-content.test.ts clipboard-import.test.ts code-highlight.test.ts offline-status.test.ts presence-announcer.test.ts presence-color.test.ts presence-cursor.test.ts presence-emitter.test.ts realtime-url.test.ts search.test.ts utils.test.ts writing-diff.test.ts
files/7
__tests__/2picker.test.ts upload.test.ts
api.ts picker.ts upload-store.ts upload.ts use-file-uploads.ts
ai-database.ts ai.ts api-keys.ts api.ts auth-store.ts batch-queue.ts block-content.ts clipboard-import.ts code-highlight.ts constants.ts offline-status.ts org-admin.ts presence-announcer.ts presence-color.ts presence-cursor.ts presence-editor-views.ts presence-emitter.ts query-client.ts realtime.ts search.ts types.ts utils.ts
stores/8
__tests__/1block-patch-store.test.ts
block-patch-store.ts comment-pill-store.ts database-store.ts editor-store.ts offlineQueue.ts presence-store.ts ui-store.ts
instrumentation.ts middleware.ts
.env.example Dockerfile next-env.d.ts next.config.mjs package.json postcss.config.mjs README.md tailwind.config.ts tsconfig.json tsconfig.tsbuildinfo vitest.config.ts
worker/92
src/87
__tests__/13ai-embedding.test.ts ai-request.test.ts ai-usage-budget.test.ts audit-export.test.ts email-decision.test.ts encrypt.test.ts health-search-index-lag.test.ts mime.test.ts retention.test.ts s3-sign.test.ts search-index.test.ts smtp.test.ts webhook-sign.test.ts
health/1server.ts
lib/12
__tests__/1clamav.test.ts
clamav.ts encrypt.ts job-otel.ts mime.ts notify.ts prisma.ts redis-stream.ts redis.ts s3.ts sharp.ts smtp.ts
processors/56
automations/28
__tests__/3condition-evaluator.spec.ts executors.spec.ts run-pipeline.spec.ts
executors/17assign-user.ts call-integration.ts change-status.ts classify.ts create-notification.ts create-page.ts email-cap.ts helpers.ts integration-registry.ts permission.ts record-write.ts registry.ts run-ai-action.ts send-email.ts send-webhook.ts types.ts update-record.ts
condition-evaluator.ts dead-letter.ts log.ts matcher.ts pipeline.ts run-state.ts schedule.ts watchdog.ts
files/15
__tests__/4errors.test.ts scan-gate.test.ts status.test.ts temp.test.ts
steps/4finalize.ts metadata.ts scan.ts thumbnails.ts
cleanup.ts errors.ts generateThumbs.ts processor.ts status.ts temp.ts types.ts
search-index/4builders.ts grants.ts index.ts processor.ts
ai-embedding.ts ai.processor.ts audit-export.ts automations.processor.ts email-decision.processor.ts email.processor.ts maintenance.processor.ts retention.ts webhooks.processor.ts
config.ts events.ts index.ts logger.ts queues.ts
.env.example Dockerfile package.json README.md tsconfig.json
docs/73
api/17ai.md authentication.md automations.md blocks.md comments.md databases.md files.md forms.md openapi.yaml org-admin.md pages.md scim.md search.md sso.md versioning.md webhooks.md workspaces.md
architecture/10ai-architecture.md automation.md backend-architecture.md database-architecture.md frontend-architecture.md realtime-architecture.md search-architecture.md security-architecture.md storage.md system-architecture.md
database/2database-architecture.md redis-keys.md
development/8admin-guide.md coding-standards.md deployment.md development-guide.md files-pipeline.md perf-report.md performance.md testing.md
product/4functional-requirements.md non-functional-requirements.md product-requirements.md ux-requirements.md
requirements/1requirements-matrix.md
security/5audit-report.md files.md forms.md license-allowlist.md security-architecture.md
tasks/16phase-00-foundation.md phase-01-authentication.md phase-02-workspace.md phase-03-pages.md phase-04-editor.md phase-05-databases.md phase-06-relations.md phase-07-collaboration.md phase-08-search.md phase-09-files.md phase-10-forms.md phase-11-automation.md phase-12-ai.md phase-13-api.md phase-14-enterprise.md phase-15-production.md
ui/9ai.md automations.md design-system.md developers.md files.md forms.md org-admin.md scim.md sso.md
support-matrix.md
infrastructure/71
caddy/1Caddyfile
docker/6
init/101-extensions.sql
opensearch/1init-indices.json
.env.docker docker-compose.yml opensearch-init.sh README.md
kubernetes/40
observability/20
alertmanager/1alertmanager.yaml
grafana/8
dashboards/6ai.json api-overview.json infra.json realtime.json search.json workers-queues.json
provisioning/2
dashboards/1dashboards.yaml
datasources/1datasource.yaml
prometheus/3alerts.yaml recording-rules.yaml scrape.yaml
scripts/1sync-sources.mjs
alertmanager.yaml grafana.yaml kustomization.yaml namespace.yaml node-exporter.yaml otel-collector.yaml prometheus.yaml
postgres/7configmap.yaml cronjob-backup.yaml cronjob-opensearch-snapshot.yaml pgbouncer.yaml replica.yaml statefulset.yaml walg-iam-policy.yaml
api.yaml configmap.yaml ingress.yaml kustomization.yaml namespace.yaml networkpolicy.yaml pdb.yaml README.md realtime.yaml redis.yaml secret.example.yaml web.yaml worker.yaml
nginx/2nginx.conf README.md
observability/14
alertmanager/1alertmanager.yaml
grafana/8
dashboards/6ai.json api-overview.json infra.json realtime.json search.json workers-queues.json
provisioning/2
dashboards/1dashboards.yaml
datasources/1datasource.yaml
prometheus/3alerts.yaml recording-rules.yaml scrape.yaml
scripts/1dashboard-completeness.mjs
README.md
terraform/8compute.tf data.tf main.tf network.tf outputs.tf README.md security.tf variables.tf
packages/289
ai/24
src/20
providers/7anthropic.ts google.ts http.ts index.ts openai-compatible.ts rag.test.ts writing.test.ts
schemas/2database.ts generate.ts
adapters.test.ts config.test.ts config.ts gateway.test.ts gateway.ts index.ts tools.test.ts tools.ts types.ts usage.test.ts usage.ts
package.json README.md tsconfig.json vitest.config.ts
auth/11
src/7index.ts passwords.test.ts passwords.ts sessions.test.ts sessions.ts tokens.test.ts tokens.ts
package.json README.md tsconfig.json vitest.config.ts
collaboration/17
src/13awareness.ts codec.test.ts codec.ts index.ts lww.test.ts lww.ts mapping.ts offline.ts outbox.test.ts outbox.ts provider.test.ts provider.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
config/7
src/4eslint.base.js index.ts prettier.base.json tsconfig.base.json
package.json README.md tsconfig.json
database-client/5
src/2index.test.ts index.ts
package.json README.md tsconfig.json
database-engine/33
src/29
filter/2filter.test.ts index.ts
formula/8evaluator.ts formula.test.ts functions.ts index.ts lexer.ts parser.ts types.ts validate.ts
query/6group.ts index.ts paginate.ts pivot.ts query.test.ts sort.ts
relations/2index.ts relations.test.ts
rollups/2index.ts rollups.test.ts
values/5dates.ts index.ts registry.ts types.ts values.test.ts
views/3buttons.ts index.ts views.test.ts
index.ts
package.json README.md tsconfig.json vitest.config.ts
editor/25
src/21
marks/1highlight.ts
nodes/2equation.ts mention.ts
autosave.test.ts autosave.ts clipboard.test.ts clipboard.ts codec.test.ts codec.ts context-menu.test.ts context-menu.ts diff.test.ts diff.ts factory.ts history.test.ts history.ts index.ts positions.ts slash.test.ts slash.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
observability/20
src/16
__tests__/8db-redis-metrics.test.ts metrics.test.ts otel.test.ts pino-otel.test.ts prometheus.test.ts resource.test.ts scrubber.test.ts traceparent.test.ts
index.ts metrics.ts otel.ts pino-otel.ts prometheus.ts resource.ts scrubber.ts traceparent.ts
package.json README.md tsconfig.json vitest.config.ts
permissions/11
src/7index.ts levels.test.ts levels.ts resolve.test.ts resolve.ts rules.test.ts rules.ts
package.json README.md tsconfig.json vitest.config.ts
search/22
src/18chunking.test.ts chunking.ts client.test.ts client.ts embeddings.test.ts embeddings.ts hybrid.test.ts hybrid.ts index.ts indexer.test.ts indexer.ts mapping.test.ts mapping.ts queries.test.ts queries.ts rrf.test.ts rrf.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
shared/61
src/57
dto/17ai.dto.ts auth.dto.test.ts auth.dto.ts block.dto.ts browser-safety.test.ts comment.dto.ts database.dto.test.ts database.dto.ts file.dto.ts formula-ast.ts index.ts notification.dto.ts page.dto.ts search.dto.ts share.dto.ts webhook.dto.ts workspace.dto.ts
events/8audit-catalog.test.ts audit-catalog.ts audit-csv.test.ts audit-csv.ts audit-scope.test.ts audit-scope.ts catalog.test.ts catalog.ts
realtime/6comment-events.ts frames.test.ts frames.ts notification-policy.ts notification-prefs.ts task-0094.test.ts
automation.test.ts automation.ts constants.ts crypto.test.ts crypto.ts env.ts errors.ts events.test.ts events.ts forms.test.ts forms.ts index.ts markdown.test.ts markdown.ts mentions.test.ts mentions.ts net.test.ts net.ts positions.test.ts positions.ts presence.test.ts presence.ts security-headers.ts webhook-delivery.test.ts webhook-delivery.ts webhook-events.ts
package.json README.md tsconfig.json vitest.config.ts
storage/16
src/12client.test.ts client.ts index.ts keys.test.ts keys.ts mime.test.ts mime.ts presign.test.ts presign.ts thumbnails.test.ts thumbnails.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
ui/37
src/33
components/19avatar.tsx badge.tsx button.tsx checkbox.tsx command.tsx context-menu.tsx dialog.tsx dropdown-menu.tsx empty-state.tsx index.ts popover.tsx separator.tsx skeleton.tsx slider.tsx spinner.tsx switch.tsx tabs.tsx toast.tsx tooltip.tsx
color.ts command-filter.test.ts command-filter.ts focus.test.ts focus.ts formatters.test.ts formatters.ts index.ts theme.test.ts theme.ts toast-store.test.ts toast-store.ts tokens.test.ts tokens.ts
package.json README.md tsconfig.json vitest.config.ts
prisma/16
migrations/13
20260927000000_init/1migration.sql
20260928000000_search_documents_content_hash/1migration.sql
20260929000000_workspace_usage_storage_bytes/1migration.sql
20260930000000_form_submitted_notification_type/1migration.sql
20261001000000_ai_phase12/1migration.sql
20261002000000_webhooks_secret_encrypted_dlq/1migration.sql
20261002111436_webhook_delivery_latency/1migration.sql
20261002120000_org_admin_2fa_retention_unique/1migration.sql
20261002215124_audit_export/1migration.sql
20261003210000_perf_indexes_hot_paths/1migration.sql
20261004004500_perf_indexes_hot_paths_2/1migration.sql
migration_lock.toml README.md
schema.prisma seed.ts verify.ts
scripts/7backup-health.ts docs-completeness.mjs generate-openapi.mjs minio-init.ts opensearch-reindex.ts storage-orphans.ts verify-clean-clone.sh
tests/169
e2e/63
.auth/1user.json
fixtures/7
files/6clip.mp4 clip.wav clip.webm hero-1400.png note.docx note.txt
realtime.ts
mocks/2oidc-issuer.ts saml-idp.ts
playwright-report/3
data/2a6557bae9c2714a658968d4eb8534195c08ebda8.png e3092d07d00a16063e46385c02a559a9054fa847.webm
index.html
reports/1files-security.json
specs/34ai-database.spec.ts ai-generate.spec.ts ai-rag.spec.ts ai-security.spec.ts ai-writing.spec.ts ai.spec.ts api-keys.spec.ts appearance-theme.spec.ts auth.spec.ts automation.spec.ts collab-two-tab.spec.ts comments.spec.ts databases.spec.ts default-workspace-alias.spec.ts developers.spec.ts editor.spec.ts files.spec.ts final-flow.spec.ts forms.spec.ts oauth.spec.ts org-admin.spec.ts pages.spec.ts performance.spec.ts presence-cursors.spec.ts qa-paste-toggle.spec.ts realtime.spec.ts scim.spec.ts search-index-lag.spec.ts search.spec.ts sharing.spec.ts sso.spec.ts task-0094-comments-notifications.spec.ts webhooks.spec.ts workspace.spec.ts
test-results-final-flow/3
final-flow-Release-v1-0-fi-6c06b-w-state-carries-sequential--chromium-desktop/2test-failed-1.png trace.zip
.last-run.json
utils/4api.ts dnd.ts search-lag.ts wait.ts
.gitignore fixtures.ts global-setup.ts package.json playwright.config.ts playwright.final-flow.config.ts README.md tsconfig.json
fixtures/1
files/1make-sparse.ts
integration/60
ai-capability/2ai-app.capability.test.ts gateway.capability.test.ts
drill/2seed-drill.mjs verify-restore.mjs
fixtures/5
files/5clip.mp4 clip.wav doc.pdf hero-1400.png note.txt
helpers/3api.ts containers.ts seed.ts
realtime/11control-channel.test.ts convergence.test.ts flush-rebase-http.test.ts handshake.test.ts heartbeat-limits.test.ts lifecycle.test.ts presence.test.ts rebase.test.ts resume.test.ts rt-helpers.ts task-0094-fanout.test.ts
ai-chat.integration.test.ts ai-database.integration.test.ts ai-generate.integration.test.ts ai-rag.integration.test.ts ai-writing.integration.test.ts api-keys.integration.test.ts audit-completeness.integration.test.ts audit-export-s3.integration.test.ts auth.integration.test.ts automation-pipeline.integration.test.ts automations.integration.test.ts blocks.integration.test.ts cache-invalidation.integration.test.ts comments.integration.test.ts databases.integration.test.ts files-lifecycle.integration.test.ts files-pipeline.integration.test.ts files-security.integration.test.ts files.integration.test.ts forms-responses.integration.test.ts forms.integration.test.ts oauth.integration.test.ts openapi.contract.test.ts org-admin.integration.test.ts package.json pages.integration.test.ts permissions.integration.test.ts README.md replica-routing.integration.test.ts retention-engine.integration.test.ts scim.integration.test.ts search.integration.test.ts sso.integration.test.ts tsconfig.json vitest.config.ts webhooks.integration.test.ts workspace.integration.test.ts
performance/28
fixtures/1search-100k.ts
helpers/2seed-100k.mjs seed-1k-load.mjs
reports/7api-load-smoke.json database-load-smoke.json editor-local.json realtime-load.json search-full.json search-last.json search-reduced.json
api-load.js api.js archive.tar database-load.js database.js editor-local.mjs extract-100k-env.mjs package.json README.md realtime-1k.js realtime-load.js realtime.js run-realtime-load.sh search-search.k6.js search-summary.json seed-100k.mjs threshold-breach-demo.js verify-zero-op-loss.mjs
security/16
helpers/1app.ts
audit-report.test.ts auth-paths.test.ts deps.test.ts formula-fuzz.test.ts gitleaks-config.test.ts headers.test.ts images.test.ts oracle.ts package.json permission-fuzz.test.ts rate-limits.test.ts README.md tsconfig.json upload-abuse.test.ts vitest.config.ts
README.md
.dockerignore .env .env.bak-task0125 .env.example .eslintrc.json .gitignore .npmrc .prettierignore .prettierrc.json AGENTS.md ARCHITECTURE.md CHANGELOG.md CONTRIBUTING.md gitleaks.toml LICENSE package.json pnpm-lock.yaml pnpm-workspace.yaml PRODUCT-SPEC.md README.md ROADMAP.md SECURITY.md tsconfig.json turbo.json
automations.integration.test.tstests/integration/automations.integration.test.tsraw← integration48,811 B← Back to the app
1/**
2 * AI Software Factory — Integration: Automations (Phase 11, TASK-0110)
3 *
4 * Covers the automation MANAGEMENT API end-to-end against Testcontainers
5 * Postgres + Redis:
6 *
7 *   - CRUD (workspace-scoped list/create, automation-scoped get/patch/delete),
8 *   - server-side authorization (non-member 403/404, GUEST VIEW-only 403,
9 *     scoped-database EDIT grant, workspace-level EDIT without a database),
10 *   - the status machine (all 6 valid transitions; the 9 invalid pairs → 409),
11 *   - sub-resource PUTs (trigger/condition/action zod validation, path-located
12 *     422 details, replace-set semantics),
13 *   - incoming-webhook lifecycle (secret minted ONCE, signature verification,
14 *     tamper/stale/unknown → 401/404, per-webhookId rate limit → 429,
15 *     regenerate invalidates the old secret, secret never leaks),
16 *   - manual run (202 + PENDING run row, DRAFT dry-run, no-actions 422),
17 *   - runs history (list cursor/limit/status, detail + logs, retry rules),
18 *   - audit events (created / status_changed / manual_triggered / retry).
19 *
20 * The trigger matcher, schedule registration and the run EXECUTION pipeline
21 * are worker-side (TASK-0113) — the API-side contract (enqueue `run-automation`
22 * with the TASK-0113 job shape) is covered by the PENDING-run assertions.
23 */
24import { afterAll, beforeAll, describe, expect, it } from "vitest";
25import {
26  AUTOMATION_MAX_ACTIONS,
27  AUTOMATION_MAX_TRIGGERS,
28  buildWebhookSignature
29} from "@factory/shared";
30import { createTestApp, type TestAppHandle } from "./helpers/api";
31import {
32  addMemberViaSeam,
33  authHeaders,
34  countAuditEvents,
35  createWorkspace,
36  createUser
37} from "./helpers/seed";
38 
39let app: TestAppHandle;
40 
41beforeAll(async () => {
42  app = await createTestApp();
43}, 180_000);
44afterAll(async () => {
45  await app?.close();
46});
47 
48// ---------------------------------------------------------------------------
49// Shared fixtures
50// ---------------------------------------------------------------------------
51 
52const json = async (res: Response): Promise<Record<string, unknown>> =>
53  (await res.json().catch(() => ({}))) as Record<string, unknown>;
54 
55/** The error envelope's `code` (the API's canonical `{ error: {...} }` shape). */
56const errCode = (body: Record<string, unknown>): string | undefined =>
57  (body.error as { code?: string } | undefined)?.code;
58 
59/** The error envelope's path-located `details[]`. */
60const errDetails = (body: Record<string, unknown>): { field?: string }[] =>
61  ((body.error as { details?: { field?: string }[] } | undefined)?.details ?? []);
62 
63/** A minimal valid UPDATE_RECORD action (valid on any automation). */
64const validAction = (i = 0) => ({
65  type: "UPDATE_RECORD",
66  config: { recordId: "from_trigger", propertyValues: { Title: `done-${i}` } },
67  retries: 3,
68  timeoutMs: 30_000
69});
70 
71/**
72 * Create a fresh workspace + its owner. Each describe block that needs
73 * isolation (rate limiting, secret regeneration) gets its own workspace so
74 * per-webhookId Redis counters never bleed between tests.
75 */
76async function newWorkspace(name: string) {
77  const owner = await createUser(app.request, { name });
78  const ws = await createWorkspace(app.request, authHeaders(owner.accessToken!), name);
79  return { owner, headers: authHeaders(owner.accessToken!), workspaceId: ws.workspaceId };
80}
81 
82/** Create an automation (via the API) in the given workspace. */
83async function createAutomation(
84  headers: Record<string, string>,
85  workspaceId: string,
86  body: Record<string, unknown> = { name: "Auto" },
87) {
88  const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
89    headers,
90    body
91  });
92  const b = await json(res);
93  return { res, body: b };
94}
95 
96/** Set status; returns [status, body]. */
97async function setStatus(headers: Record<string, string>, id: string, status: string) {
98  const res = await app.request("POST", `/api/v1/automations/${id}/status`, {
99    headers,
100    body: { status }
101  });
102  return [res.status, await json(res)] as const;
103}
104 
105/** Attach a webhook trigger and return the one-time secret + webhookId. */
106async function attachWebhook(headers: Record<string, string>, id: string, extraTriggers: unknown[] = []) {
107  const res = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
108    headers,
109    body: { triggers: [{ type: "WEBHOOK", config: {} }, ...extraTriggers] }
110  });
111  expect(res.status).toBe(200);
112  const b = await json(res);
113  const wh = (b.webhooks as { webhookId: string; secret: string; url: string }[])[0];
114  expect(wh, "webhook secret returned once").toBeTruthy();
115  return wh!;
116}
117 
118/** Fire the incoming webhook with a valid signature (returns [status, body]). */
119async function fireWebhook(webhookId: string, secret: string, payload: unknown, tsSeconds?: number) {
120  const raw = JSON.stringify(payload);
121  const ts = tsSeconds ?? Math.floor(Date.now() / 1000);
122  const res = await app.request("POST", `/api/v1/webhooks/incoming/${webhookId}`, {
123    body: payload, // the helper JSON.stringifies — byte-identical to `raw`
124    headers: { "x-fs-signature": buildWebhookSignature(secret, ts, raw) }
125  });
126  return [res.status, await json(res)] as const;
127}
128 
129// ---------------------------------------------------------------------------
130// CRUD
131// ---------------------------------------------------------------------------
132 
133describe("automation CRUD", () => {
134  let headers: Record<string, string>;
135  let workspaceId: string;
136 
137  beforeAll(async () => {
138    ({ headers, workspaceId } = await newWorkspace("CRUD"));
139  });
140 
141  it("creates a DRAFT automation (201) with default fields", async () => {
142    const { res, body } = await createAutomation(headers, workspaceId, {
143      name: "Inbox triage",
144      description: "Routes new leads"
145    });
146    expect(res.status).toBe(201);
147    expect(body.status).toBe("DRAFT");
148    expect(body.name).toBe("Inbox triage");
149    expect(body.description).toBe("Routes new leads");
150    expect(body.databaseId).toBeNull();
151    expect(body.triggers).toEqual([]);
152    expect(body.condition).toBeNull();
153    expect(body.actions).toEqual([]);
154    expect(body.latestRun).toBeNull();
155    expect(typeof body.id).toBe("string");
156  });
157 
158  it("rejects invalid names (zod 400)", async () => {
159    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
160      headers,
161      body: { name: "" }
162    });
163    expect(res.status).toBe(400);
164    const body = await json(res);
165    expect(errCode(body)).toBe("VALIDATION_ERROR");
166  });
167 
168  it("creates with inline sub-resources (triggers + condition + actions)", async () => {
169    const { res, body } = await createAutomation(headers, workspaceId, {
170      name: "With parts",
171      triggers: [{ type: "RECORD_CREATED", config: {} }],
172      condition: { field: { ref: "property", name: "Status" }, operator: "eq", value: "Open" },
173      actions: [validAction(1), validAction(2)]
174    });
175    expect(res.status).toBe(201);
176    expect(body.triggers).toHaveLength(1);
177    expect((body.condition as Record<string, unknown>).field).toBeTruthy();
178    expect(body.actions).toHaveLength(2);
179  });
180 
181  it("lists automations (default limit 50) newest-first with latestRun", async () => {
182    const res = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations`, { headers });
183    expect(res.status).toBe(200);
184    const body = await json(res);
185    const data = body.data as Record<string, unknown>[];
186    expect(data.length).toBe(2);
187    expect(body.nextCursor).toBeNull();
188    // Newest first (createdAt desc).
189    const t0 = new Date(data[1]!.createdAt as string).getTime();
190    const t1 = new Date(data[0]!.createdAt as string).getTime();
191    expect(t0).toBeLessThanOrEqual(t1);
192    expect(data[0]!.name).toBe("With parts");
193    expect(data[0]!.latestRun).toBeNull();
194    expect(data[0]!.triggers).toEqual(["RECORD_CREATED"]);
195    expect(data[0]!.actions).toEqual(["UPDATE_RECORD", "UPDATE_RECORD"]);
196  });
197 
198  it("respects the status filter", async () => {
199    const res = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations?status=DRAFT`, { headers });
200    const body = await json(res);
201    expect((body.data as unknown[]).length).toBe(2);
202 
203    const none = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations?status=ACTIVE`, { headers });
204    expect(((await json(none)).data as unknown[]).length).toBe(0);
205  });
206 
207  it("pages with a cursor (limit=1 → 2 pages)", async () => {
208    const p1 = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations?limit=1`, { headers });
209    const b1 = await json(p1);
210    expect((b1.data as unknown[]).length).toBe(1);
211    expect(typeof b1.nextCursor).toBe("string");
212 
213    const p2 = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations?limit=1&cursor=${encodeURIComponent(b1.nextCursor as string)}`, { headers });
214    const b2 = await json(p2);
215    const d1 = (b1.data as Record<string, unknown>)[0]!.id;
216    const d2 = (b2.data as Record<string, unknown>)[0]!.id;
217    expect(d2).not.toBe(d1); // no overlap across pages
218    expect(b2.nextCursor).toBeNull();
219  });
220 
221  it("rejects an invalid cursor (400)", async () => {
222    const res = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations?cursor=abc123def`, { headers });
223    expect(res.status).toBe(400);
224    expect(errCode(await json(res))).toBe("VALIDATION_ERROR");
225  });
226 
227  it("422s a create with a foreign or fabricated databaseId (server-side scope check)", async () => {
228    const other = await newWorkspace("OtherWs");
229    // A database is a page of type "database" (there is no POST /databases
230    // route — see the forms suite's setupDb).
231    const dbRes = await app.request("POST", `/api/v1/workspaces/${other.workspaceId}/pages`, {
232      headers: other.headers,
233      body: { title: "Foreign DB", type: "database" }
234    });
235    expect([200, 201]).toContain(dbRes.status);
236    const foreignDb = ((await json(dbRes)) as { databaseId: string }).databaseId;
237    // A database from ANOTHER workspace must be rejected (no cross-ws scope).
238    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
239      headers,
240      body: { name: "Cross ws", databaseId: foreignDb }
241    });
242    expect(res.status).toBe(422);
243    expect(errCode(await json(res))).toBe("UNPROCESSABLE_ENTITY");
244    // A fabricated id is rejected too.
245    const res2 = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
246      headers,
247      body: { name: "Ghost db", databaseId: "zzzzzzzzzzzzzzzzzzzzzz" }
248    });
249    expect(res2.status).toBe(422);
250  });
251 
252  it("gets full detail (incl. latestRun) by id", async () => {
253    const list = await json(await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations?status=DRAFT&limit=1`, { headers }));
254    const id = (list.data as Record<string, unknown>)[0]!.id as string;
255    const res = await app.request("GET", `/api/v1/automations/${id}`, { headers });
256    expect(res.status).toBe(200);
257    const body = await json(res);
258    expect(body.id).toBe(id);
259    expect(body.actions).toHaveLength(2);
260    expect(body.latestRun).toBeNull();
261  });
262 
263  it("returns 404 for a non-existent automation (no existence leak)", async () => {
264    const res = await app.request("GET", `/api/v1/automations/${"x".repeat(20)}`, { headers });
265    expect(res.status).toBe(404);
266    expect(errCode(await json(res))).toBe("NOT_FOUND");
267  });
268 
269  it("patches name/description", async () => {
270    const { res, body: created } = await createAutomation(headers, workspaceId, { name: "Patched" });
271    const aid = created.id as string;
272    const res2 = await app.request("PATCH", `/api/v1/automations/${aid}`, {
273      headers,
274      body: { name: "Patched v2", description: "updated" }
275    });
276    expect(res2.status).toBe(200);
277    const b2 = await json(res2);
278    expect(b2.name).toBe("Patched v2");
279    expect(b2.description).toBe("updated");
280  });
281 
282  it("deletes → ARCHIVED (soft; { archived: true })", async () => {
283    const { res, body: created } = await createAutomation(headers, workspaceId, { name: "Doomed" });
284    const aid = created.id as string;
285    const del = await app.request("DELETE", `/api/v1/automations/${aid}`, { headers });
286    expect(del.status).toBe(200);
287    expect(await json(del)).toEqual({ archived: true });
288 
289    const after = await app.request("GET", `/api/v1/automations/${aid}`, { headers });
290    expect((await json(after)).status).toBe("ARCHIVED");
291  });
292 
293  it("does not hard-delete: the row still exists (re-activation allowed)", async () => {
294    const { res, body: created } = await createAutomation(headers, workspaceId, { name: "Doomed2" });
295    const aid = created.id as string;
296    await app.request("DELETE", `/api/v1/automations/${aid}`, { headers });
297    const count = await app.prisma.automation.count({ where: { id: aid } });
298    expect(count).toBe(1);
299    const [s] = await setStatus(headers, aid, "ACTIVE");
300    expect(s).toBe(200);
301  });
302});
303 
304// ---------------------------------------------------------------------------
305// Authorization (server-side)
306// ---------------------------------------------------------------------------
307 
308describe("automation authorization", () => {
309  let ownerHeaders: Record<string, string>;
310  let workspaceId: string;
311  let ownerId: string;
312  let guestHeaders: Record<string, string>;
313  let automationId: string;
314 
315  beforeAll(async () => {
316    const { owner, headers, workspaceId: ws } = await newWorkspace("Auth");
317    ownerHeaders = headers;
318    workspaceId = ws;
319    ownerId = owner.userId;
320    const { body } = await createAutomation(headers, ws, { name: "Protected" });
321    automationId = body.id as string;
322    // GUEST is a workspace member with VIEW only.
323    const guest = await createUser(app.request, { name: "Guest" });
324    await addMemberViaSeam(app.request, app.internalServiceToken, ws, guest.email, "GUEST");
325    guestHeaders = authHeaders(guest.accessToken!);
326  });
327 
328  it("a non-member cannot list (403) nor read (403, no leak)", async () => {
329    const stranger = await createUser(app.request, { name: "Stranger" });
330    const sh = authHeaders(stranger.accessToken!);
331    const list = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations`, { headers: sh });
332    expect(list.status).toBe(403);
333    const get = await app.request("GET", `/api/v1/automations/${automationId}`, { headers: sh });
334    expect(get.status).toBe(403);
335    expect(errCode(await json(get))).toBe("FORBIDDEN");
336  });
337 
338  it("a non-member cannot create (403)", async () => {
339    const stranger = await createUser(app.request, { name: "Stranger2" });
340    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
341      headers: authHeaders(stranger.accessToken!),
342      body: { name: "Nope" }
343    });
344    expect(res.status).toBe(403);
345  });
346 
347  it("a GUEST can read but not write (VIEW-only 403)", async () => {
348    const read = await app.request("GET", `/api/v1/automations/${automationId}`, { headers: guestHeaders });
349    expect(read.status).toBe(200);
350    const list = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations`, { headers: guestHeaders });
351    expect(list.status).toBe(200);
352 
353    const patch = await app.request("PATCH", `/api/v1/automations/${automationId}`, { headers: guestHeaders, body: { name: "hack" } });
354    expect(patch.status).toBe(403);
355    const del = await app.request("DELETE", `/api/v1/automations/${automationId}`, { headers: guestHeaders });
356    expect(del.status).toBe(403);
357    const create = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, { headers: guestHeaders, body: { name: "guest auto" } });
358    expect(create.status).toBe(403);
359    const status = await app.request("POST", `/api/v1/automations/${automationId}/status`, { headers: guestHeaders, body: { status: "ACTIVE" } });
360    expect(status.status).toBe(403);
361  });
362 
363  it("the OWNER can write (baseline for the GUEST contrast)", async () => {
364    const res = await app.request("PATCH", `/api/v1/automations/${automationId}`, {
365      headers: ownerHeaders,
366      body: { description: "owner wrote" }
367    });
368    expect(res.status).toBe(200);
369  });
370 
371  it("an unknown automation id → 404 even for the owner (no cross-ws leak)", async () => {
372    const res = await app.request("GET", `/api/v1/automations/${"y".repeat(20)}`, { headers: ownerHeaders });
373    expect(res.status).toBe(404);
374  });
375 
376  it("audits the write (automation.updated exists for the owner)", async () => {
377    const n = await countAuditEvents(app.prisma, { actorId: ownerId, action: "automation.updated" });
378    expect(n).toBeGreaterThanOrEqual(1);
379  });
380});
381 
382// ---------------------------------------------------------------------------
383// Status machine
384// ---------------------------------------------------------------------------
385 
386describe("automation status machine", () => {
387  let headers: Record<string, string>;
388  let workspaceId: string;
389  let ownerId: string;
390  let id: string;
391 
392  beforeAll(async () => {
393    const { owner, headers: h, workspaceId: ws } = await newWorkspace("Status");
394    headers = h;
395    workspaceId = ws;
396    ownerId = owner.userId;
397    const { body } = await createAutomation(headers, ws, { name: "Machine" });
398    id = body.id as string;
399  });
400 
401  it("walks all 6 valid transitions in one path", async () => {
402    // DRAFT → ACTIVE
403    let [s, b] = await setStatus(headers, id, "ACTIVE");
404    expect(s).toBe(200);
405    expect(b.status).toBe("ACTIVE");
406    // ACTIVE → PAUSED
407    [s, b] = await setStatus(headers, id, "PAUSED");
408    expect(s).toBe(200);
409    expect(b.status).toBe("PAUSED");
410    // PAUSED → ACTIVE
411    [s, b] = await setStatus(headers, id, "ACTIVE");
412    expect(s).toBe(200);
413    expect(b.status).toBe("ACTIVE");
414    // ACTIVE → ARCHIVED
415    [s, b] = await setStatus(headers, id, "ARCHIVED");
416    expect(s).toBe(200);
417    expect(b.status).toBe("ARCHIVED");
418    // ARCHIVED → ACTIVE (re-arm)
419    [s, b] = await setStatus(headers, id, "ACTIVE");
420    expect(s).toBe(200);
421    expect(b.status).toBe("ACTIVE");
422    // ACTIVE → PAUSED → ARCHIVED (completes the graph)
423    [s] = await setStatus(headers, id, "PAUSED");
424    expect(s).toBe(200);
425    [s] = await setStatus(headers, id, "ARCHIVED");
426    expect(s).toBe(200);
427  });
428 
429  it("rejects every invalid pair with 409 (each pair on a fresh row)", async () => {
430    // All 16 pairs minus the 6 valid ones = 10 invalid (incl. no-ops).
431    const invalid: [string, string][] = [
432      ["DRAFT", "PAUSED"],
433      ["DRAFT", "ARCHIVED"],
434      ["ACTIVE", "DRAFT"],
435      ["PAUSED", "DRAFT"],
436      ["ARCHIVED", "DRAFT"],
437      ["ARCHIVED", "PAUSED"],
438      ["ACTIVE", "ACTIVE"],
439      ["DRAFT", "DRAFT"],
440      ["PAUSED", "PAUSED"],
441      ["ARCHIVED", "ARCHIVED"]
442    ];
443    for (const [from, to] of invalid) {
444      const { body } = await createAutomation(headers, workspaceId, { name: `T ${from}-${to}` });
445      const tid = body.id as string;
446      // Drive the fresh DRAFT row to `from` (the only valid entry path is via ACTIVE).
447      if (from === "ACTIVE") await setStatus(headers, tid, "ACTIVE");
448      else if (from === "PAUSED") {
449        await setStatus(headers, tid, "ACTIVE");
450        await setStatus(headers, tid, "PAUSED");
451      } else if (from === "ARCHIVED") {
452        await setStatus(headers, tid, "ACTIVE");
453        await setStatus(headers, tid, "ARCHIVED");
454      }
455      const [s, b] = await setStatus(headers, tid, to);
456      expect(s, `${from} → ${to} must 409`).toBe(409);
457      expect(errCode(b)).toBe("CONFLICT");
458    }
459  });
460 
461  it("audits each transition (automation.status_changed with from/to)", async () => {
462    const n = await countAuditEvents(app.prisma, { actorId: ownerId, action: "automation.status_changed" });
463    // 7 valid transitions in the first test + 6 status sets driving fresh rows
464    // (ACTIVE / PAUSED / ARCHIVED per row) + the re-arm above. Lower-bound:
465    expect(n).toBeGreaterThanOrEqual(7);
466    // Spot-check the metadata shape of one row.
467    const row = await app.prisma.auditLog.findFirst({
468      where: { actorId: ownerId, action: "automation.status_changed", resourceId: id },
469      orderBy: { createdAt: "desc" }
470    });
471    expect(row).not.toBeNull();
472    const meta = row!.metadata as Record<string, unknown>;
473    expect(typeof meta.from).toBe("string");
474    expect(typeof meta.to).toBe("string");
475    expect(meta.to).not.toBe(meta.from);
476  });
477});
478 
479// ---------------------------------------------------------------------------
480// Sub-resource PUTs (validation contract)
481// ---------------------------------------------------------------------------
482 
483describe("sub-resource PUTs", () => {
484  let headers: Record<string, string>;
485  let workspaceId: string;
486  let id: string;
487 
488  beforeAll(async () => {
489    const { headers: h, workspaceId: ws } = await newWorkspace("Subres");
490    headers = h;
491    workspaceId = ws;
492    const { body } = await createAutomation(headers, ws, { name: "Subs" });
493    id = body.id as string;
494  });
495 
496  describe("PUT triggers", () => {
497    it("validates each trigger config (path-located 422)", async () => {
498      // PROPERTY_CHANGED requires a non-empty `properties` array.
499      const res = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
500        headers,
501        body: { triggers: [{ type: "PROPERTY_CHANGED", config: {} }] }
502      });
503      expect(res.status).toBe(422);
504      const b = await json(res);
505      expect(errCode(b)).toBe("UNPROCESSABLE_ENTITY");
506      const details = errDetails(b);
507      expect(details?.some((d) => (d.field ?? "").startsWith("triggers[0].config."))).toBe(true);
508    });
509 
510    it("rejects >3 triggers (zod 400)", async () => {
511      const triggers = Array.from({ length: AUTOMATION_MAX_TRIGGERS + 1 }, () => ({ type: "MANUAL", config: {} }));
512      const res = await app.request("PUT", `/api/v1/automations/${id}/triggers`, { headers, body: { triggers } });
513      expect(res.status).toBe(400);
514    });
515 
516    it("rejects an unknown trigger type (400)", async () => {
517      const res = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
518        headers,
519        body: { triggers: [{ type: "EXPLOSION", config: {} }] }
520      });
521      expect(res.status).toBe(400);
522    });
523 
524    it("accepts a valid set (replace semantics) and returns sanitized triggers", async () => {
525      const res = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
526        headers,
527        body: {
528          triggers: [
529            { type: "RECORD_CREATED", config: {} },
530            { type: "PROPERTY_CHANGED", config: { properties: ["Status"] } }
531          ]
532        }
533      });
534      expect(res.status).toBe(200);
535      const b = await json(res);
536      expect(b.webhooks).toEqual([]);
537      expect((b.triggers as unknown[]).length).toBe(2);
538 
539      // Replace: a new set of 1 trigger removes the previous 2.
540      const res2 = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
541        headers,
542        body: { triggers: [{ type: "PAGE_CREATED", config: {} }] }
543      });
544      expect(res2.status).toBe(200);
545      const detail = await app.request("GET", `/api/v1/automations/${id}`, { headers });
546      expect(((await json(detail)).triggers as unknown[]).length).toBe(1);
547    });
548 
549    it("validates SCHEDULE cron (CRON_TOO_FREQUENT → 422)", async () => {
550      // 5s interval < 60s minimum.
551      const res = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
552        headers,
553        body: { triggers: [{ type: "SCHEDULE", config: { cron: "*/5 * * * * *" } }] }
554      });
555      expect(res.status).toBe(422);
556      // A valid hourly cron passes.
557      const ok = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
558        headers,
559        body: { triggers: [{ type: "SCHEDULE", config: { cron: "0 0 * * * *" } }] }
560      });
561      expect(ok.status).toBe(200);
562    });
563  });
564 
565  describe("PUT conditions", () => {
566    const pred = (name = "Status", op = "eq", value = "Open") => ({
567      field: { ref: "property", name },
568      operator: op,
569      value
570    });
571 
572    it("accepts null (removes the condition) and a valid tree", async () => {
573      let res = await app.request("PUT", `/api/v1/automations/${id}/conditions`, { headers, body: { condition: pred() } });
574      expect(res.status).toBe(200);
575      let b = await json(res);
576      expect((b.condition as Record<string, unknown>).operator).toBe("eq");
577 
578      res = await app.request("PUT", `/api/v1/automations/${id}/conditions`, { headers, body: { condition: null } });
579      expect(res.status).toBe(200);
580      b = await json(res);
581      expect(b.condition).toBeNull();
582      const detail = await json(await app.request("GET", `/api/v1/automations/${id}`, { headers }));
583      expect(detail.condition).toBeNull();
584    });
585 
586    it("rejects a tree deeper than 5 (CONDITION_TOO_COMPLEX, 422)", async () => {
587      // Nest 6 AND groups (depth 6 > 5).
588      let node = pred();
589      for (let i = 0; i < 6; i++) node = { op: "AND", children: [node, pred(`P${i}`, "is_empty")] };
590      const res = await app.request("PUT", `/api/v1/automations/${id}/conditions`, { headers, body: { condition: node } });
591      expect(res.status).toBe(422);
592      const b = await json(res);
593      expect(errCode(b)).toBe("UNPROCESSABLE_ENTITY");
594    });
595 
596    it("rejects a structurally invalid tree (CONDITION_INVALID, 422)", async () => {
597      // AND with a single child.
598      const res = await app.request("PUT", `/api/v1/automations/${id}/conditions`, {
599        headers,
600        body: { condition: { op: "AND", children: [pred()] } }
601      });
602      expect(res.status).toBe(422);
603    });
604  });
605 
606  describe("PUT actions", () => {
607    it("accepts a valid ordered list (defaults for omitted knobs)", async () => {
608      const res = await app.request("PUT", `/api/v1/automations/${id}/actions`, {
609        headers,
610        body: { actions: [{ type: "UPDATE_RECORD", config: { propertyValues: { Title: "x" } } }, validAction(2)] }
611      });
612      expect(res.status).toBe(200);
613      const b = await json(res);
614      const a0 = (b.actions as Record<string, unknown>)[0];
615      // recordId defaulted to "from_trigger"; retries/timeoutMs defaulted.
616      expect((a0.config as Record<string, unknown>).recordId).toBe("from_trigger");
617      expect(a0.retries).toBe(3);
618      expect(a0.timeoutMs).toBe(30_000);
619    });
620 
621    it("validates each action config (path-located 422)", async () => {
622      // UPDATE_RECORD requires ≥ 1 propertyValues entry.
623      const res = await app.request("PUT", `/api/v1/automations/${id}/actions`, {
624        headers,
625        body: { actions: [{ type: "UPDATE_RECORD", config: { propertyValues: {} } }] }
626      });
627      expect(res.status).toBe(422);
628      const b = await json(res);
629      expect(errCode(b)).toBe("UNPROCESSABLE_ENTITY");
630      const details = errDetails(b);
631      expect(details?.some((d) => (d.field ?? "").startsWith("actions[0].config."))).toBe(true);
632    });
633 
634    it("rejects >50 actions (zod 400)", async () => {
635      const actions = Array.from({ length: AUTOMATION_MAX_ACTIONS + 1 }, (_, i) => validAction(i));
636      const res = await app.request("PUT", `/api/v1/automations/${id}/actions`, { headers, body: { actions } });
637      expect(res.status).toBe(400);
638    });
639 
640    it("rejects out-of-range retries/timeoutMs (422)", async () => {
641      const res = await app.request("PUT", `/api/v1/automations/${id}/actions`, {
642        headers,
643        body: { actions: [{ type: "UPDATE_RECORD", config: { propertyValues: { A: 1 } }, retries: 9 }] }
644      });
645      expect(res.status).toBe(422);
646      const res2 = await app.request("PUT", `/api/v1/automations/${id}/actions`, {
647        headers,
648        body: { actions: [{ type: "UPDATE_RECORD", config: { propertyValues: { A: 1 } }, timeoutMs: 400_000 }] }
649      });
650      expect(res2.status).toBe(422);
651    });
652  });
653});
654 
655// ---------------------------------------------------------------------------
656// Incoming webhook (signature, rate limit, secret lifecycle)
657// ---------------------------------------------------------------------------
658 
659describe("incoming webhook", () => {
660  let ownerHeaders: Record<string, string>;
661  let workspaceId: string;
662  let ownerId: string;
663 
664  beforeAll(async () => {
665    const { owner, headers: h, workspaceId: ws } = await newWorkspace("Webhook");
666    ownerHeaders = h;
667    workspaceId = ws;
668    ownerId = owner.userId;
669  });
670 
671  it("mints the secret ONCE on first save and exposes url + webhookId", async () => {
672    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook" });
673    const id = body.id as string;
674    const wh = await attachWebhook(ownerHeaders, id);
675    expect(wh.secret.startsWith("whsec_")).toBe(true);
676    expect(wh.webhookId).toMatch(/^[0-9a-f]{24}$/);
677    expect(wh.url).toBe(`http://localhost:4000/api/v1/webhooks/incoming/${wh.webhookId}`);
678 
679    // The secret is NEVER in a subsequent GET (sanitized) nor re-issued on
680    // re-save (only the new webhooks list contains a fresh secret).
681    const detail = await json(await app.request("GET", `/api/v1/automations/${id}`, { headers: ownerHeaders }));
682    const trigger = (detail.triggers as Record<string, unknown>[]).find((t) => t.type === "WEBHOOK")!;
683    const cfg = trigger.config as Record<string, unknown>;
684    expect(cfg.secret).toBeUndefined();
685    expect(cfg.secretEncrypted).toBeUndefined();
686    expect(cfg.secretHash).toBeUndefined();
687    expect(cfg.webhookId).toBe(wh.webhookId);
688    expect(cfg.url).toBe(wh.url);
689 
690    // Re-save (editor replace-set) preserves the stored secret: the response
691    // contains NO new secret, and a signed POST with the ORIGINAL secret
692    // still works — proving the KMS-wrapped secret survived the replace-set
693    // (regression: the editor's core operation must not clobber it).
694    const resave = await app.request("PUT", `/api/v1/automations/${id}/triggers`, {
695      headers: ownerHeaders,
696      body: { triggers: [{ type: "WEBHOOK", config: { webhookId: wh.webhookId } }] }
697    });
698    expect(resave.status).toBe(200);
699    expect((await json(resave)).webhooks).toEqual([]);
700 
701    const [as] = await setStatus(ownerHeaders, id, "ACTIVE");
702    expect(as).toBe(200);
703    const [fireStatus] = await fireWebhook(wh.webhookId, wh.secret, { survived: "resave" });
704    expect(fireStatus, "original secret must still verify after re-save").toBe(200);
705  });
706 
707  it("accepts a valid signed payload → 200 {accepted:true} + PENDING run", async () => {
708    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook2" });
709    const id = body.id as string;
710    const wh = await attachWebhook(ownerHeaders, id);
711    // Activate (the endpoint only fires for ACTIVE automations).
712    const [s] = await setStatus(ownerHeaders, id, "ACTIVE");
713    expect(s).toBe(200);
714 
715    const [status, b] = await fireWebhook(wh.webhookId, wh.secret, { hello: "world" });
716    expect(status).toBe(200);
717    expect(b).toEqual({ accepted: true });
718 
719    const run = await app.prisma.automationRun.findFirst({ where: { automationId: id } });
720    expect(run).not.toBeNull();
721    expect(run!.status).toBe("PENDING");
722    expect((run!.triggerEvent as Record<string, unknown>).type).toBe("webhook");
723    expect(((run!.triggerEvent as Record<string, unknown>).payload as Record<string, unknown>).hello).toBe("world");
724  });
725 
726  it("404s an unknown webhookId (no existence leak)", async () => {
727    const res = await app.request("POST", `/api/v1/webhooks/incoming/${"0".repeat(24)}`, {
728      body: { x: 1 },
729      headers: { "x-fs-signature": buildWebhookSignature("whsec_deadbeef", Math.floor(Date.now() / 1000), JSON.stringify({ x: 1 })) }
730    });
731    expect(res.status).toBe(404);
732    expect(errCode(await json(res))).toBe("NOT_FOUND");
733  });
734 
735  it("401s a tampered body (signature over different bytes)", async () => {
736    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook3" });
737    const id = body.id as string;
738    const wh = await attachWebhook(ownerHeaders, id);
739    await setStatus(ownerHeaders, id, "ACTIVE");
740 
741    // Sign {"a":1} but send {"a":2} — the raw bytes differ from the MAC input.
742    const ts = Math.floor(Date.now() / 1000);
743    const goodSig = buildWebhookSignature(wh.secret, ts, JSON.stringify({ a: 1 }));
744    const res = await app.request("POST", `/api/v1/webhooks/incoming/${wh.webhookId}`, {
745      body: { a: 2 },
746      headers: { "x-fs-signature": goodSig }
747    });
748    expect(res.status).toBe(401);
749    expect(errCode(await json(res))).toBe("WEBHOOK_SIGNATURE_INVALID");
750  });
751 
752  it("401s a stale timestamp (±5 min window)", async () => {
753    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook4" });
754    const id = body.id as string;
755    const wh = await attachWebhook(ownerHeaders, id);
756    await setStatus(ownerHeaders, id, "ACTIVE");
757 
758    const stale = Math.floor(Date.now() / 1000) - 360; // 6 minutes ago
759    const [s, b] = await fireWebhook(wh.webhookId, wh.secret, { x: 1 }, stale);
760    expect(s).toBe(401);
761    expect(errCode(b)).toBe("WEBHOOK_TIMESTAMP_STALE");
762  });
763 
764  it("401s a missing signature header", async () => {
765    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook5" });
766    const id = body.id as string;
767    const wh = await attachWebhook(ownerHeaders, id);
768    await setStatus(ownerHeaders, id, "ACTIVE");
769 
770    const res = await app.request("POST", `/api/v1/webhooks/incoming/${wh.webhookId}`, { body: { x: 1 } });
771    expect(res.status).toBe(401);
772    expect(errCode(await json(res))).toBe("WEBHOOK_SIGNATURE_INVALID");
773  });
774 
775  it("404s a DRAFT automation's webhook (not registered yet)", async () => {
776    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook6-draft" });
777    const id = body.id as string;
778    const wh = await attachWebhook(ownerHeaders, id);
779    // Deliberately left in DRAFT.
780    const res = await app.request("POST", `/api/v1/webhooks/incoming/${wh.webhookId}`, {
781      body: { x: 1 },
782      headers: { "x-fs-signature": buildWebhookSignature(wh.secret, Math.floor(Date.now() / 1000), JSON.stringify({ x: 1 })) }
783    });
784    expect(res.status).toBe(404);
785  });
786 
787  it("404s an ARCHIVED automation's webhook (endpoint removed)", async () => {
788    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook7" });
789    const id = body.id as string;
790    const wh = await attachWebhook(ownerHeaders, id);
791    await setStatus(ownerHeaders, id, "ACTIVE");
792    await setStatus(ownerHeaders, id, "ARCHIVED");
793    const [s] = await fireWebhook(wh.webhookId, wh.secret, { x: 1 });
794    expect(s).toBe(404);
795  });
796 
797  it("rate-limits to 60/min per webhookId (61st → 429)", async () => {
798    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook8" });
799    const id = body.id as string;
800    const wh = await attachWebhook(ownerHeaders, id);
801    await setStatus(ownerHeaders, id, "ACTIVE");
802 
803    let saw429 = false;
804    for (let i = 0; i < 61; i++) {
805      const [s] = await fireWebhook(wh.webhookId, wh.secret, { i });
806      if (i < 60) {
807        expect(s, `request ${i + 1} should be accepted`).toBe(200);
808      } else {
809        expect(s, "61st request should be 429").toBe(429);
810        saw429 = true;
811      }
812    }
813    expect(saw429).toBe(true);
814    // The rate-limited request created NO run (rejected before enqueue).
815    const runs = await app.prisma.automationRun.count({ where: { automationId: id } });
816    expect(runs).toBe(60);
817  });
818 
819  it("regenerates the secret (old invalidated, new works, audited)", async () => {
820    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook9" });
821    const id = body.id as string;
822    const wh = await attachWebhook(ownerHeaders, id);
823    await setStatus(ownerHeaders, id, "ACTIVE");
824    const oldSecret = wh.secret;
825 
826    const reg = await app.request("POST", `/api/v1/automations/${id}/webhook/regenerate`, { headers: ownerHeaders });
827    expect(reg.status).toBe(200);
828    const rb = await json(reg);
829    const newSecret = rb.secret as string;
830    expect(newSecret.startsWith("whsec_")).toBe(true);
831    expect(newSecret).not.toBe(oldSecret);
832    expect(rb.webhookId).toBe(wh.webhookId);
833 
834    // Old secret now fails (401).
835    const old = await fireWebhook(wh.webhookId, oldSecret, { old: true });
836    expect(old[0]).toBe(401);
837    expect(old[1].error).toBeTruthy();
838    // New secret works.
839    const neu = await fireWebhook(wh.webhookId, newSecret, { fresh: true });
840    expect(neu[0]).toBe(200);
841    expect(neu[1]).toEqual({ accepted: true });
842 
843    const n = await countAuditEvents(app.prisma, {
844      actorId: ownerId,
845      action: "automation.webhook_secret_regenerated"
846    });
847    expect(n).toBeGreaterThanOrEqual(1);
848  });
849 
850  it("requires a WEBHOOK trigger for regenerate (404 otherwise)", async () => {
851    const { body } = await createAutomation(ownerHeaders, workspaceId, { name: "Hook10" });
852    const id = body.id as string;
853    const res = await app.request("POST", `/api/v1/automations/${id}/webhook/regenerate`, { headers: ownerHeaders });
854    expect(res.status).toBe(404);
855  });
856});
857 
858// ---------------------------------------------------------------------------
859// Manual run + runs history
860// ---------------------------------------------------------------------------
861 
862describe("manual run + runs history", () => {
863  let headers: Record<string, string>;
864  let workspaceId: string;
865  let ownerId: string;
866  let id: string;
867 
868  beforeAll(async () => {
869    const { owner, headers: h, workspaceId: ws } = await newWorkspace("Runs");
870    headers = h;
871    workspaceId = ws;
872    ownerId = owner.userId;
873    const { body } = await createAutomation(headers, ws, {
874      name: "Manual",
875      actions: [validAction(0)]
876    });
877    id = body.id as string;
878  });
879 
880  it("422s a manual run when the automation has no actions", async () => {
881    const { body } = await createAutomation(headers, workspaceId, { name: "NoActions" });
882    const empty = body.id as string;
883    const res = await app.request("POST", `/api/v1/automations/${empty}/run`, { headers, body: {} });
884    expect(res.status).toBe(422);
885    expect(errCode(await json(res))).toBe("UNPROCESSABLE_ENTITY");
886  });
887 
888  it("202 + runId; creates a PENDING run (DRAFT dry-run path)", async () => {
889    const res = await app.request("POST", `/api/v1/automations/${id}/run`, {
890      headers,
891      body: { input: { from: "test" } }
892    });
893    expect(res.status).toBe(202);
894    const b = await json(res);
895    expect(typeof b.runId).toBe("string");
896    const runId = b.runId as string;
897 
898    const run = await app.prisma.automationRun.findUnique({ where: { id: runId } });
899    expect(run).not.toBeNull();
900    expect(run!.status).toBe("PENDING");
901    expect(run!.retryCount).toBe(0);
902    expect((run!.triggerEvent as Record<string, unknown>).type).toBe("manual");
903    expect((run!.triggerEvent as Record<string, unknown>).input).toEqual({ from: "test" });
904 
905    const n = await countAuditEvents(app.prisma, { actorId: ownerId, action: "automation.manual_triggered" });
906    expect(n).toBeGreaterThanOrEqual(1);
907  });
908 
909  it("lists runs (desc) with triggerType + a nextCursor", async () => {
910    // Seed a few more runs so pagination is exercised.
911    for (let i = 0; i < 3; i++) {
912      const r = await app.request("POST", `/api/v1/automations/${id}/run`, { headers, body: {} });
913      expect(r.status).toBe(202);
914      await new Promise((r2) => setTimeout(r2, 5)); // distinct createdAt
915    }
916    const res = await app.request("GET", `/api/v1/automations/${id}/runs`, { headers });
917    expect(res.status).toBe(200);
918    const b = await json(res);
919    expect((b.data as unknown[]).length).toBe(4);
920    const first = (b.data as Record<string, unknown>)[0];
921    expect(first.triggerType).toBe("manual");
922    expect(b.nextCursor).toBeNull(); // 4 < limit 50
923 
924    const paged = await app.request("GET", `/api/v1/automations/${id}/runs?limit=2`, { headers });
925    const pb = await json(paged);
926    expect((pb.data as unknown[]).length).toBe(2);
927    expect(typeof pb.nextCursor).toBe("string");
928  });
929 
930  it("filters runs by status", async () => {
931    const res = await app.request("GET", `/api/v1/automations/${id}/runs?status=PENDING`, { headers });
932    const b = await json(res);
933    expect((b.data as Record<string, unknown>[]).every((r) => r.status === "PENDING")).toBe(true);
934    expect((b.data as unknown[]).length).toBe(4);
935  });
936 
937  it("returns run detail (input/output/logs) by id", async () => {
938    const list = await json(await app.request("GET", `/api/v1/automations/${id}/runs`, { headers }));
939    const runId = (list.data as Record<string, unknown>)[0]!.id as string;
940    const res = await app.request("GET", `/api/v1/automations/${id}/runs/${runId}`, { headers });
941    expect(res.status).toBe(200);
942    const b = await json(res);
943    expect(b.id).toBe(runId);
944    expect(b.logs).toEqual([]);
945    expect(b.input).toBeTruthy();
946    expect(b.output).toBeNull();
947  });
948 
949  it("404s a run from another automation (cross-automation isolation)", async () => {
950    const { body } = await createAutomation(headers, workspaceId, { name: "Other", actions: [validAction(9)] });
951    const otherId = body.id as string;
952    const otherRun = await (await app.request("POST", `/api/v1/automations/${otherId}/run`, { headers, body: {} })).json();
953    const list = await json(await app.request("GET", `/api/v1/automations/${id}/runs`, { headers }));
954    const foreignRunId = (otherRun as { runId: string }).runId;
955    const res = await app.request("GET", `/api/v1/automations/${id}/runs/${foreignRunId}`, { headers });
956    expect(res.status).toBe(404);
957  });
958 
959  it("retry: 409 for PENDING/SUCCEEDED, 200 for FAILED (resets + re-enqueues)", async () => {
960    const list = await json(await app.request("GET", `/api/v1/automations/${id}/runs`, { headers }));
961    const runId = (list.data as Record<string, unknown>)[0]!.id as string;
962 
963    // PENDING → not retryable.
964    const p = await app.request("POST", `/api/v1/automations/${id}/runs/${runId}/retry`, { headers });
965    expect(p.status).toBe(409);
966 
967    // Force FAILED + error, then retry → 200, reset to PENDING.
968    await app.prisma.automationRun.update({
969      where: { id: runId },
970      data: { status: "FAILED", error: { message: "boom" }, retryCount: 2, finishedAt: new Date() }
971    });
972    const ok = await app.request("POST", `/api/v1/automations/${id}/runs/${runId}/retry`, { headers });
973    expect(ok.status).toBe(200);
974    const ob = await json(ok);
975    expect(ob.runId).toBe(runId);
976    expect(ob.status).toBe("PENDING");
977    const after = await app.prisma.automationRun.findUnique({ where: { id: runId } });
978    expect(after!.status).toBe("PENDING");
979    expect(after!.retryCount).toBe(0);
980    expect(after!.error).toBeNull();
981 
982    // Force SUCCEEDED → retry 409 (terminal, not retryable).
983    await app.prisma.automationRun.update({ where: { id: runId }, data: { status: "SUCCEEDED" } });
984    const s = await app.request("POST", `/api/v1/automations/${id}/runs/${runId}/retry`, { headers });
985    expect(s.status).toBe(409);
986 
987    // Force DEAD_LETTER → retry 200.
988    await app.prisma.automationRun.update({ where: { id: runId }, data: { status: "DEAD_LETTER", error: { fatal: true } } });
989    const d = await app.request("POST", `/api/v1/automations/${id}/runs/${runId}/retry`, { headers });
990    expect(d.status).toBe(200);
991 
992    const n = await countAuditEvents(app.prisma, { actorId: ownerId, action: "automation.run_retried" });
993    expect(n).toBeGreaterThanOrEqual(2);
994  });
995 
996  it("a GUEST cannot run/retry (403)", async () => {
997    const guest = await createUser(app.request, { name: "GuestRuns" });
998    await addMemberViaSeam(app.request, app.internalServiceToken, workspaceId, guest.email, "GUEST");
999    const gh = authHeaders(guest.accessToken!);
1000    const list = await app.request("GET", `/api/v1/automations/${id}/runs`, { headers: gh });
1001    // Runs history is an EDIT surface (the editor needs it for history); a
1002    // VIEW-only guest is denied.
1003    expect(list.status).toBe(403);
1004    const run = await app.request("POST", `/api/v1/automations/${id}/run`, { headers: gh, body: {} });
1005    expect(run.status).toBe(403);
1006  });
1007});
1008 
1009// ---------------------------------------------------------------------------
1010// Scoped-database permission model (spec §1: EDIT on the scoped database)
1011//
1012// The permission model is ROLE-DRIVEN for members (MEMBER → EDIT at
1013// workspace level); per-database grants matter for a GUEST (VIEW baseline)
1014// who has been granted EDIT on ONE specific database:
1015//   - automation scoped to the granted DB  → writable
1016//   - automation scoped to ANOTHER DB      → 403 (the grant doesn't leak)
1017//   - unscoped automation                  → 403 (no baseline EDIT)
1018// ---------------------------------------------------------------------------
1019 
1020describe("scoped-database permission model", () => {
1021  let ownerHeaders: Record<string, string>;
1022  let workspaceId: string;
1023  let dbA: string;
1024  let dbB: string;
1025  let guestHeaders: Record<string, string>;
1026 
1027  beforeAll(async () => {
1028    const { owner, headers: h, workspaceId: ws } = await newWorkspace("Scoped");
1029    ownerHeaders = h;
1030    workspaceId = ws;
1031    const mk = async (title: string) => {
1032      // A database is a page of type "database" (no POST /databases route).
1033      const res = await app.request("POST", `/api/v1/workspaces/${ws}/pages`, {
1034        headers: h,
1035        body: { title, type: "database" }
1036      });
1037      expect([200, 201]).toContain(res.status);
1038      return (await json(res)) as { databaseId: string };
1039    };
1040    dbA = (await mk("DB A")).databaseId;
1041    dbB = (await mk("DB B")).databaseId;
1042    // GUEST (VIEW baseline) with an explicit EDIT grant on dbA ONLY.
1043    const guest = await createUser(app.request, { name: "ScopedGuest" });
1044    await addMemberViaSeam(app.request, app.internalServiceToken, ws, guest.email, "GUEST");
1045    await app.prisma.permission.create({
1046      data: { workspaceId: ws, granteeType: "user", granteeId: guest.userId, resourceType: "database", resourceId: dbA, level: "EDIT" }
1047    });
1048    guestHeaders = authHeaders(guest.accessToken!);
1049  });
1050 
1051  it("can write an automation scoped to the granted database (dbA)", async () => {
1052    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
1053      headers: guestHeaders,
1054      body: { name: "dbA auto", databaseId: dbA }
1055    });
1056    expect(res.status).toBe(201);
1057    const id = (await json(res)).id as string;
1058    const patch = await app.request("PATCH", `/api/v1/automations/${id}`, { headers: guestHeaders, body: { description: "granted" } });
1059    expect(patch.status).toBe(200);
1060  });
1061 
1062  it("CANNOT write an automation scoped to a database without the grant (dbB)", async () => {
1063    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
1064      headers: guestHeaders,
1065      body: { name: "dbB auto", databaseId: dbB }
1066    });
1067    expect(res.status).toBe(403);
1068    expect(errCode(await json(res))).toBe("FORBIDDEN");
1069    // …and can't write an OWNER-created automation that is dbB-scoped.
1070    const owned = await createAutomation(ownerHeaders, workspaceId, { name: "Owner dbB", databaseId: dbB });
1071    expect(owned.res.status).toBe(201);
1072    const patch = await app.request("PATCH", `/api/v1/automations/${owned.body.id as string}`, {
1073      headers: guestHeaders,
1074      body: { description: "nope" }
1075    });
1076    expect(patch.status).toBe(403);
1077  });
1078 
1079  it("CANNOT write an unscoped automation (no workspace-level EDIT baseline)", async () => {
1080    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
1081      headers: guestHeaders,
1082      body: { name: "unscoped" }
1083    });
1084    expect(res.status).toBe(403);
1085  });
1086 
1087  it("CAN still read automations (VIEW baseline)", async () => {
1088    const list = await app.request("GET", `/api/v1/workspaces/${workspaceId}/automations`, { headers: guestHeaders });
1089    expect(list.status).toBe(200);
1090    const b = await json(list);
1091    expect((b.data as unknown[]).length).toBeGreaterThanOrEqual(2);
1092  });
1093 
1094  it("an explicit NONE grant on the database hard-stops even the granted one", async () => {
1095    // Flip the guest's dbA grant to an explicit NONE (TASK-0104 explicit-deny).
1096    // UPDATE, not create: the Permission unique key is (workspace, grantee,
1097    // resource) and does NOT include level — a second row would be P2002.
1098    const grant = await app.prisma.permission.findFirst({ where: { resourceType: "database", resourceId: dbA, level: "EDIT" } });
1099    expect(grant).not.toBeNull();
1100    await app.prisma.permission.update({ where: { id: grant!.id }, data: { level: "NONE" } });
1101    const res = await app.request("POST", `/api/v1/workspaces/${workspaceId}/automations`, {
1102      headers: guestHeaders,
1103      body: { name: "dbA after deny", databaseId: dbA }
1104    });
1105    expect(res.status).toBe(403);
1106  });
1107});
1108