.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
block.service.tsapps/api/src/modules/blocks/block.service.tsraw← blocks35,102 B← Back to the app
1import { Inject, Injectable } from "@nestjs/common";
2import { Prisma } from "@prisma/client";
3import { z } from "zod";
4import { PrismaService } from "../../common/prisma.service.js";
5import { AuditService } from "../../common/audit.service.js";
6import { EventBus } from "../../common/event-bus.js";
7import { NotificationsService } from "../notifications/notifications.service.js";
8import { CacheService } from "../../common/cache.js";
9import { ApiError } from "../../common/errors.js";
10import { assertCan } from "../../lib/authorize.js";
11import { between, compare, rebalancePositions } from "../../lib/positions.js";
12import { EVENTS, MAX_BLOCK_TREE } from "../../constants.js";
13import type {
14  BatchBlocksInput,
15  CreateBlockInput,
16  MoveBlockInput,
17  UpdateBlockInput
18} from "./dto.js";
19 
20const BLOCK_SELECT = {
21  id: true, pageId: true, workspaceId: true, parentId: true, type: true,
22  position: true, content: true, properties: true, isSynced: true,
23  syncedSourceId: true, version: true, createdAt: true, updatedAt: true,
24  deletedAt: true
25} as const;
26type BlockRow = Prisma.BlockGetPayload<{ select: typeof BLOCK_SELECT }>;
27 
28/**
29 * TASK-0135: the full-page block tree (the editor-open load) is the hottest
30 * read. It is cached under a version-key (see common/cache.ts): the key embeds
31 * the workspace content-version, which every page/block write bumps — so a
32 * write always changes the key and the next read is fresh. Entries are
33 * zod-validated on read (corrupt entry = miss, never a 500). The shape below
34 * matches BLOCK_SELECT as JSON (Prisma dates serialize to ISO strings).
35 */
36const BLOCK_ROW_CACHE = z.object({
37  id: z.string(),
38  pageId: z.string(),
39  workspaceId: z.string(),
40  parentId: z.string().nullable(),
41  type: z.string(),
42  position: z.string(),
43  content: z.unknown(),
44  properties: z.unknown(),
45  isSynced: z.boolean(),
46  syncedSourceId: z.string().nullable(),
47  version: z.number(),
48  createdAt: z.string(),
49  updatedAt: z.string(),
50  deletedAt: z.string().nullable()
51});
52const BLOCK_ROWS_CACHE = z.array(BLOCK_ROW_CACHE);
53 
54/**
55 * Block service: CRUD on the block tree, fractional positioning, batch ops,
56 * duplicate, and flat text export. Every mutation emits `page.updated` with
57 * the affected `blockIds` (the realtime sync contract).
58 */
59@Injectable()
60export class BlockService {
61  constructor(
62    @Inject(PrismaService) private readonly prisma: PrismaService,
63    @Inject(AuditService) private readonly audit: AuditService,
64    @Inject(EventBus) private readonly events: EventBus,
65    @Inject(CacheService) private readonly cache: CacheService,
66    @Inject(NotificationsService) private readonly notifications: NotificationsService
67  ) {}
68 
69  private async getBlock(blockId: string) {
70    const block = await this.prisma.block.findUnique({ where: { id: blockId }, select: BLOCK_SELECT });
71    if (!block || block.deletedAt) throw ApiError.notFound("Block not found.");
72    return block;
73  }
74 
75  private async requirePageAccess(pageId: string, userId: string, need: "VIEW" | "EDIT") {
76    const page = await this.prisma.page.findUnique({
77      where: { id: pageId },
78      select: { id: true, workspaceId: true, deletedAt: true, version: true }
79    });
80    if (!page || page.deletedAt) throw ApiError.notFound("Page not found.");
81    await assertCan(this.prisma, { workspaceId: page.workspaceId, userId, resource: { pageId: page.id } }, need);
82    return page;
83  }
84 
85  /** Siblings of a parent (or root), ordered. */
86  private async siblings(tx: Prisma.TransactionClient, pageId: string, parentId: string | null): Promise<BlockRow[]> {
87    return tx.block.findMany({
88      where: { pageId, parentId, deletedAt: null },
89      select: BLOCK_SELECT,
90      orderBy: { position: "asc" }
91    });
92  }
93 
94  // ---------- list ----------
95 
96  async list(pageId: string, userId: string, query: { parentId?: string | null; depth?: string | number }) {
97    const page = await this.requirePageAccess(pageId, userId, "VIEW");
98    const depth = typeof query.depth === "string" ? query.depth : query.depth ? String(query.depth) : "1";
99 
100    if (depth === "all") {
101      // TASK-0135: cache the full tree (the editor-open load) under a
102      // version-key. `pageId` scopes the key; the version is the workspace
103      // content-version (bumped on every page/block write). The loader is the
104      // real PG read — on a cache hit we skip it entirely.
105      const { data: rowsData } = await this.cache.getTree(page.workspaceId, pageId, async () => {
106        // TASK-0135 (replica routing): the tree load is a spec-named replica
107        // read (`db.read()`). The version-key cache above already guards
108        // concurrent-write staleness; a tiny replica-lag window on a cache
109        // MISS is the documented, spec-acceptable staleness for tree loads.
110        const r = await this.prisma.read().block.findMany({
111          where: { pageId, deletedAt: null },
112          select: BLOCK_SELECT,
113          orderBy: { position: "asc" }
114        });
115        return r as unknown[];
116      }, BLOCK_ROWS_CACHE);
117      const flat = rowsData as unknown as BlockRow[];
118      if (flat.length > MAX_BLOCK_TREE) {
119        throw new ApiError("PAYLOAD_TOO_LARGE", 413, `Block tree exceeds ${MAX_BLOCK_TREE} blocks.`, [
120          { maxBlocks: MAX_BLOCK_TREE, received: flat.length }
121        ]);
122      }
123      return { data: flat, tree: this.buildTree(flat), total: flat.length };
124    }
125 
126    const parentId = query.parentId ?? null;
127    const rows = await this.prisma.block.findMany({
128      where: { pageId, parentId, deletedAt: null },
129      select: BLOCK_SELECT,
130      orderBy: { position: "asc" },
131      take: 1000
132    });
133    return { data: rows };
134  }
135 
136  private buildTree(rows: BlockRow[]) {
137    const byId = new Map<string, BlockRow & { children: unknown[] }>();
138    for (const r of rows) byId.set(r.id, { ...r, children: [] });
139    const roots: (BlockRow & { children: unknown[] })[] = [];
140    for (const r of rows) {
141      const node = byId.get(r.id)!;
142      if (r.parentId && byId.has(r.parentId)) byId.get(r.parentId)!.children.push(node);
143      else roots.push(node);
144    }
145    return roots;
146  }
147 
148  // ---------- position helpers ----------
149 
150  private async resolvePosition(
151    tx: Prisma.TransactionClient,
152    pageId: string,
153    opts: { parentId?: string | null; afterBlockId?: string; beforeBlockId?: string; position?: string }
154  ): Promise<string> {
155    const parentId = opts.parentId ?? null;
156    if (opts.position) return opts.position;
157 
158    let before: string | undefined;
159    let after: string | undefined;
160    if (opts.beforeBlockId) {
161      const b = await tx.block.findUnique({ where: { id: opts.beforeBlockId }, select: { position: true, parentId: true, pageId: true, deletedAt: true } });
162      if (!b || b.deletedAt || b.pageId !== pageId) throw ApiError.notFound("beforeBlockId not found.");
163      before = b.position;
164    }
165    if (opts.afterBlockId) {
166      const a = await tx.block.findUnique({ where: { id: opts.afterBlockId }, select: { position: true, parentId: true, pageId: true, deletedAt: true } });
167      if (!a || a.deletedAt || a.pageId !== pageId) throw ApiError.notFound("afterBlockId not found.");
168      after = a.position;
169    }
170    // `after` = the block the new position sits BELOW (lower bound, sorts
171    // earlier); `before` = the block it sits ABOVE (upper bound, sorts later).
172    // `between(a, b)` requires a to sort before b, so pass (lower, upper) —
173    // the same (after, before) ordering database.service uses. The previous
174    // `between(before, after)` always threw (before sorts after after) → 500
175    // on every move that sent both anchors (moving a middle block).
176    if (before && after) return between(after, before);
177    if (after) {
178      // A single AFTER anchor must be bounded by the anchor's NEXT LIVE
179      // sibling (in the target parent), not by the grid top: `between(a)`
180      // is deterministic (midpoint of a and top), so re-inserting after the
181      // same anchor returns the SAME position the anchor's next sibling
182      // already occupies → duplicate position (ordering corruption). With
183      // the neighbour bound the new position always lands strictly between
184      // two live siblings. No next sibling → the append case (after top).
185      const next = await tx.block.findFirst({
186        where: { pageId, parentId, deletedAt: null, position: { gt: after } },
187        orderBy: { position: "asc" },
188        select: { position: true }
189      });
190      return between(after, next?.position);
191    }
192    if (before) {
193      // Mirror image: bound a single BEFORE anchor from below by its
194      // previous live sibling (previously `between(undefined, before)` — the
195      // deterministic bottom-midpoint, same collision class).
196      const prev = await tx.block.findFirst({
197        where: { pageId, parentId, deletedAt: null, position: { lt: before } },
198        orderBy: { position: "desc" },
199        select: { position: true }
200      });
201      return between(prev?.position, before);
202    }
203    const last = await tx.block.findFirst({
204      where: { pageId, parentId, deletedAt: null },
205      orderBy: { position: "desc" },
206      select: { position: true }
207    });
208    return between(last?.position);
209  }
210 
211  /**
212   * Re-space a sibling list that exhausted its fractional headroom (the
213   * historical "position too close to the top" RangeError on large pastes):
214   * rewrite every row to an even grid (rebalancePositions) and return the
215   * fresh positions by id. Runs inside the caller's transaction — the
216   * pending updates are visible to subsequent reads in the same tx.
217   */
218  private async rebalanceSiblingList(tx: Prisma.TransactionClient, pageId: string, parentId: string | null): Promise<Map<string, string>> {
219    const siblings = await this.siblings(tx, pageId, parentId);
220    const fresh = rebalancePositions(siblings.map((s) => s.position));
221    const byId = new Map<string, string>();
222    for (let i = 0; i < siblings.length; i++) {
223      const s = siblings[i]!;
224      const pos = fresh[i]!;
225      if (s.position !== pos) {
226        await tx.block.update({ where: { id: s.id }, data: { position: pos } });
227      }
228      byId.set(s.id, pos);
229    }
230    return byId;
231  }
232 
233  /**
234   * `resolvePosition` with a last-resort rebalance: when the sibling list
235   * has no splittable gap left, re-space the whole list in-transaction and
236   * recompute against the fresh grid. The happy path costs nothing extra.
237   */
238  private async resolvePositionSafe(tx: Prisma.TransactionClient, pageId: string, opts: { parentId?: string | null; afterBlockId?: string; beforeBlockId?: string; position?: string }): Promise<string> {
239    try {
240      return await this.resolvePosition(tx, pageId, opts);
241    } catch (err) {
242      if (!(err instanceof RangeError)) throw err;
243      await this.rebalanceSiblingList(tx, pageId, opts.parentId ?? null);
244      return this.resolvePosition(tx, pageId, opts);
245    }
246  }
247 
248  /** Fill the positional gap left by a removed sibling. */
249  private async fillGap(tx: Prisma.TransactionClient, pageId: string, parentId: string | null, removedPosition: string): Promise<void> {
250    const siblings = await this.siblings(tx, pageId, parentId);
251    const prev = [...siblings].reverse().find((s) => compare(s.position, removedPosition) < 0);
252    const next = siblings.find((s) => compare(s.position, removedPosition) > 0);
253    if (prev && next) {
254      await tx.block.update({ where: { id: prev.id }, data: { position: between(prev.position, next.position) } });
255    } else if (prev) {
256      await tx.block.update({ where: { id: prev.id }, data: { position: between(prev.position) } });
257    }
258  }
259 
260  // ---------- create / update ----------
261 
262  /**
263   * A `column_list` created through the API (slash menu, paste import, AI)
264   * ships as a Notion-style 2-column grid: two `column` children, each with
265   * one empty `paragraph` inside. Without this the list is an uneditable
266   * dead end (the renderer has no "add column" affordance and `column` rows
267   * render nothing standalone).
268   */
269  private async seedColumnChildren(tx: Prisma.TransactionClient, block: { id: string; pageId: string; workspaceId: string }, userId: string): Promise<void> {
270    const workspaceId = block.workspaceId;
271    for (const colPos of ["A", between("A")]) {
272      const column = await tx.block.create({
273        data: {
274          pageId: block.pageId,
275          workspaceId,
276          parentId: block.id,
277          // The BlockType column is the UPPERCASE DB enum (the REST DTO
278          // transform stores `type` upper-cased), so the seed children must
279          // use the enum literals or the insert fails.
280          type: "COLUMN",
281          position: colPos,
282          content: {} as Prisma.InputJsonValue,
283          properties: {} as object,
284          createdBy: userId
285        }
286      });
287      await tx.block.create({
288        data: {
289          pageId: block.pageId,
290          workspaceId,
291          parentId: column.id,
292          type: "PARAGRAPH",
293          position: "A",
294          content: {} as Prisma.InputJsonValue,
295          properties: {} as object,
296          createdBy: userId
297        }
298      });
299    }
300  }
301 
302  async create(pageId: string, userId: string, input: CreateBlockInput, req: any) {
303    const page = await this.requirePageAccess(pageId, userId, "EDIT");
304    const block = await this.prisma.$transaction(async (tx) => {
305      const parentId = input.parentId ?? null;
306      if (parentId) {
307        const parent = await tx.block.findUnique({ where: { id: parentId }, select: { pageId: true, deletedAt: true } });
308        if (!parent || parent.deletedAt || parent.pageId !== pageId) throw ApiError.notFound("parentId not found.");
309      }
310      const position = await this.resolvePositionSafe(tx, pageId, input);
311      const created = await tx.block.create({
312        data: {
313          pageId,
314          workspaceId: page.workspaceId,
315          parentId,
316          type: input.type,
317          position,
318          content: input.content as Prisma.InputJsonValue,
319          properties: input.properties as object,
320          createdBy: userId
321        },
322        select: BLOCK_SELECT
323      });
324      if (created.type === "COLUMN_LIST") {
325        // UPPERCASE: the REST DTO transform stores `type` as the DB enum
326        // (the client sends codec-lowercase `column_list`).
327        await this.seedColumnChildren(tx, created, userId);
328      }
329      return created;
330    });
331    await this.audit.audit(req, req?.auth, {
332      action: "block.created",
333      resourceType: "block",
334      resourceId: block.id,
335      workspaceId: page.workspaceId,
336      pageId,
337      metadata: { type: block.type, parentId: block.parentId }
338    });
339    await this.events.publish(EVENTS.PAGE_UPDATED, {
340      workspaceId: page.workspaceId,
341      pageId,
342      blockIds: [block.id],
343      changed: "created"
344    });
345    return block;
346  }
347 
348  async update(blockId: string, userId: string, input: UpdateBlockInput, req: any) {
349    const block = await this.getBlock(blockId);
350    await this.requirePageAccess(block.pageId, userId, "EDIT");
351    const data: Prisma.BlockUpdateInput = { version: { increment: 1 }, updatedBy: userId };
352    if (input.content !== undefined) data.content = input.content as object;
353    if (input.type !== undefined) {
354      data.type = input.type;
355      // type conversion: unsupported props are cleared
356      data.properties = (input.properties ?? {}) as object;
357    } else if (input.properties !== undefined) {
358      data.properties = input.properties as object;
359    }
360    if (input.archived !== undefined) {
361      // soft-archive via deletedAt (blocks have no archivedAt column)
362      data.deletedAt = input.archived ? new Date() : null;
363    }
364    // TASK-0123: optional optimistic concurrency. When `baseVersion` is given
365    // the write only lands if the block is STILL at that version; a stale
366    // version is a 409 CONFLICT carrying the actual version (the writing
367    // apply path uses this to offer a rebase). Omitted → today's behavior
368    // (unconditional increment) — full backward compatibility.
369    let updated: BlockRow | null;
370    if (input.baseVersion !== undefined) {
371      const res = await this.prisma.block.updateMany({
372        where: { id: blockId, version: input.baseVersion, deletedAt: null },
373        data,
374      });
375      if (res.count === 0) {
376        const current = await this.prisma.block.findUnique({
377          where: { id: blockId },
378          select: { version: true, deletedAt: true }
379        });
380        if (!current || current.deletedAt) throw ApiError.notFound("Block not found.");
381        throw ApiError.conflict("Block version conflict (stale version).", [
382          { reason: "stale_version", blockId, expected: input.baseVersion, actualVersion: current.version }
383        ]);
384      }
385      updated = await this.prisma.block.findUnique({ where: { id: blockId }, select: BLOCK_SELECT });
386    } else {
387      updated = await this.prisma.block.update({ where: { id: blockId }, data, select: BLOCK_SELECT });
388    }
389    if (!updated) throw ApiError.notFound("Block not found.");
390    await this.audit.audit(req, req?.auth, {
391      action: "block.updated",
392      resourceType: "block",
393      resourceId: blockId,
394      workspaceId: block.workspaceId,
395      pageId: block.pageId,
396      metadata: { fields: Object.keys(input) }
397    });
398    await this.events.publish(EVENTS.PAGE_UPDATED, {
399      workspaceId: block.workspaceId,
400      pageId: block.pageId,
401      blockIds: [blockId],
402      changed: "updated"
403    });
404    return updated;
405  }
406 
407  // ---------- move / delete / duplicate ----------
408 
409  async move(blockId: string, userId: string, input: MoveBlockInput, req: any) {
410    const block = await this.getBlock(blockId);
411    await this.requirePageAccess(block.pageId, userId, "EDIT");
412    const result = await this.prisma.$transaction(async (tx) => {
413      const newParentId = input.parentId ?? block.parentId;
414      if (newParentId) {
415        const parent = await tx.block.findUnique({ where: { id: newParentId }, select: { pageId: true, deletedAt: true } });
416        if (!parent || parent.deletedAt || parent.pageId !== block.pageId) throw ApiError.notFound("Target parent not found.");
417        if (this.isDescendant(await tx.block.findMany({ where: { pageId: block.pageId, deletedAt: null }, select: { id: true, parentId: true } }), blockId, newParentId)) {
418          throw ApiError.validation("Cannot move a block into its own subtree.", [{ issue: "circular" }]);
419        }
420      }
421      // remove from old position
422      await tx.block.update({ where: { id: blockId }, data: { parentId: newParentId } });
423      await this.fillGap(tx, block.pageId, block.parentId, block.position);
424      const position = await this.resolvePositionSafe(tx, block.pageId, {
425        parentId: newParentId,
426        afterBlockId: input.afterBlockId,
427        beforeBlockId: input.beforeBlockId,
428        position: input.position
429      });
430      return tx.block.update({ where: { id: blockId }, data: { position }, select: BLOCK_SELECT });
431    });
432    await this.audit.audit(req, req?.auth, {
433      action: "block.moved",
434      resourceType: "block",
435      resourceId: blockId,
436      workspaceId: block.workspaceId,
437      pageId: block.pageId
438    });
439    await this.events.publish(EVENTS.PAGE_UPDATED, {
440      workspaceId: block.workspaceId,
441      pageId: block.pageId,
442      blockIds: [blockId],
443      moved: true
444    });
445    return result;
446  }
447 
448  private isDescendant(allBlocks: { id: string; parentId: string | null }[], ancestorId: string, candidateId: string): boolean {
449    let cursor: string | null = candidateId;
450    const seen = new Set<string>();
451    while (cursor) {
452      if (cursor === ancestorId) return true;
453      if (seen.has(cursor)) return false;
454      seen.add(cursor);
455      cursor = allBlocks.find((b) => b.id === cursor)?.parentId ?? null;
456    }
457    return false;
458  }
459 
460  async delete(blockId: string, userId: string, req: any) {
461    const block = await this.getBlock(blockId);
462    await this.requirePageAccess(block.pageId, userId, "EDIT");
463    const subtreeIds = await this.subtreeIds(block.pageId, [blockId]);
464    await this.prisma.$transaction(async (tx) => {
465      await tx.block.deleteMany({ where: { pageId: block.pageId, id: { in: subtreeIds } } });
466      await this.fillGap(tx, block.pageId, block.parentId, block.position);
467    });
468    await this.audit.audit(req, req?.auth, {
469      action: "block.deleted",
470      resourceType: "block",
471      resourceId: blockId,
472      workspaceId: block.workspaceId,
473      pageId: block.pageId,
474      metadata: { subtreeSize: subtreeIds.length }
475    });
476    await this.events.publish(EVENTS.PAGE_UPDATED, {
477      workspaceId: block.workspaceId,
478      pageId: block.pageId,
479      blockIds: [blockId],
480      changed: "deleted"
481    });
482    return { deleted: true, blockIds: subtreeIds };
483  }
484 
485  private async subtreeIds(pageId: string, roots: string[]): Promise<string[]> {
486    const rows = await this.prisma.block.findMany({
487      where: { pageId, deletedAt: null },
488      select: { id: true, parentId: true }
489    });
490    const childrenOf = new Map<string | null, string[]>();
491    for (const r of rows) {
492      const list = childrenOf.get(r.parentId) ?? [];
493      list.push(r.id);
494      childrenOf.set(r.parentId, list);
495    }
496    const ids: string[] = [];
497    const queue = [...roots];
498    while (queue.length > 0) {
499      const id = queue.shift()!;
500      ids.push(id);
501      queue.push(...(childrenOf.get(id) ?? []));
502    }
503    return ids;
504  }
505 
506  /** Deep-copy a block subtree, inserted right after the source. */
507  async duplicate(blockId: string, userId: string, req: any, input?: { parentId?: string | null; afterBlockId?: string }) {
508    const source = await this.getBlock(blockId);
509    await this.requirePageAccess(source.pageId, userId, "EDIT");
510    const rows = await this.prisma.block.findMany({
511      where: { pageId: source.pageId, deletedAt: null },
512      select: { id: true, parentId: true, type: true, content: true, properties: true, position: true }
513    });
514    const subtree = await this.subtreeIds(source.pageId, [blockId]);
515    const set = new Set(subtree);
516    const nodes = rows.filter((r) => set.has(r.id));
517    const idMap = new Map<string, string>();
518    for (const n of nodes) idMap.set(n.id, `blk_${Math.random().toString(36).slice(2, 14)}`);
519    // Target slot: by default directly BELOW the source in its own parent
520    // list; an explicit `afterBlockId` anchors the copy somewhere else (the
521    // web "Paste below" / "Copy" path) and `parentId` re-parents the copy.
522    const targetParentId = input?.parentId === undefined ? source.parentId : input.parentId;
523    const afterId = input?.afterBlockId ?? blockId;
524    await this.prisma.$transaction(async (tx) => {
525      const position = await this.resolvePositionSafe(tx, source.pageId, {
526        parentId: targetParentId,
527        afterBlockId: afterId
528      });
529      for (const n of nodes) {
530        await tx.block.create({
531          data: {
532            id: idMap.get(n.id)!,
533            pageId: source.pageId,
534            workspaceId: source.workspaceId,
535            // The ROOT lands in the (possibly re-parented) target; inner
536            // nodes keep their subtree-relative parents via the id map.
537            parentId: n.id === blockId ? targetParentId : (n.parentId ? (idMap.get(n.parentId) ?? n.parentId) : null),
538            type: n.type,
539            // keep intra-tree relative order; the root gets the computed position
540            position: n.id === blockId ? position : n.position,
541            content: n.content as Prisma.InputJsonValue,
542            properties: n.properties as Prisma.InputJsonValue,
543            createdBy: userId
544          }
545        });
546      }
547    });
548    await this.audit.audit(req, req?.auth, {
549      action: "block.duplicated",
550      resourceType: "block",
551      resourceId: blockId,
552      workspaceId: source.workspaceId,
553      pageId: source.pageId,
554      metadata: { subtreeSize: subtree.length }
555    });
556    await this.events.publish(EVENTS.PAGE_UPDATED, {
557      workspaceId: source.workspaceId,
558      pageId: source.pageId,
559      blockIds: [...subtree],
560      changed: "duplicated"
561    });
562    return { duplicated: true, newRootId: idMap.get(blockId), blockIds: subtree };
563  }
564 
565  // ---------- batch ----------
566 
567  async batch(pageId: string, userId: string, input: BatchBlocksInput, req: any) {
568    const page = await this.requirePageAccess(pageId, userId, "EDIT");
569    // Stale-base fast path: a pre-check is an optimization, not the guard —
570    // the authoritative check is the CAS UPDATE inside the transaction
571    // below. A stale baseVersion 409s immediately with the CURRENT version
572    // (the "CONFLICT carries the new version" contract — the REST client
573    // re-reads and retries).
574    if (input.baseVersion !== undefined && page.version !== input.baseVersion) {
575      throw ApiError.conflict(
576        "The page changed since you last read it (a concurrent edit — including a realtime flush). Re-read and retry.",
577        [
578          { issue: "stale_base_version", received: input.baseVersion },
579          { currentVersion: page.version },
580          { reason: "flush_wins" }
581        ]
582      );
583    }
584    const touched = new Set<string>();
585    let newVersion: number;
586    try {
587      newVersion = await this.prisma.$transaction(async (tx) => {
588        // The `pages.version` CAS (TASK-0092, backend-architecture §12):
589        // the REST batch serializes against a concurrent realtime flush —
590        // the flush's `POST /internal/blocks/flush` runs
591        // `UPDATE pages SET version = v+1 WHERE version = base`; if a REST
592        // write advanced the version first, that CAS fails and the flush
593        // rebases over the REST write ("flush wins; the doc absorbs REST
594        // writes, never clobbers them"). The bump is the FIRST statement
595        // of the transaction (a race between the pre-check above and the
596        // UPDATE aborts everything — nothing written, the 409 path below).
597        const base = input.baseVersion ?? page.version;
598        const cas = await tx.page.updateMany({
599          where: { id: pageId, version: base },
600          data: { version: base + 1, updatedAt: new Date() }
601        });
602        if (cas.count !== 1) throw new BatchVersionCasConflict();
603        for (const op of input.ops) {
604          if (op.op === "update") {
605            // The web editor's debounced save (block-save-queue.ts) flushes one
606            // `op:"update"` per typed block to this endpoint. Inlined here (NOT
607            // `this.update`) so the write stays inside the transaction — batch
608            // atomicity ("one invalid op → 400 and NO partial application") and
609            // the pages.version CAS hold for update ops too. Semantics mirror
610            // the single `update()`: version increment + updatedBy, type
611            // conversion clears properties, re-parenting guards against
612            // circular moves.
613            const block = await tx.block.findUnique({ where: { id: op.blockId }, select: { id: true, pageId: true, parentId: true, position: true, type: true, deletedAt: true } });
614            if (!block || block.deletedAt || block.pageId !== pageId) throw ApiError.notFound(`block ${op.blockId} not found.`);
615            const patch = op.patch;
616            const data: Prisma.BlockUpdateInput = { version: { increment: 1 }, updatedBy: userId };
617            if (patch.content !== undefined) data.content = patch.content as unknown as object;
618            if (patch.type !== undefined && patch.type !== block.type) {
619              data.type = patch.type;
620              data.properties = (patch.properties ?? {}) as object;
621            } else if (patch.properties !== undefined) {
622              data.properties = patch.properties as object;
623            }
624            if (patch.parentId !== undefined && patch.parentId !== block.parentId) {
625              const newParentId = patch.parentId;
626              if (newParentId) {
627                const parent = await tx.block.findUnique({ where: { id: newParentId }, select: { pageId: true, deletedAt: true } });
628                if (!parent || parent.deletedAt || parent.pageId !== pageId) throw ApiError.notFound(`update parent ${newParentId} not found.`);
629                if (this.isDescendant(await tx.block.findMany({ where: { pageId, deletedAt: null }, select: { id: true, parentId: true } }), op.blockId, newParentId)) {
630                  throw ApiError.validation("Cannot move a block into its own subtree.", [{ issue: "circular" }]);
631                }
632              }
633              data.parentId = newParentId;
634            }
635            await tx.block.update({ where: { id: op.blockId }, data });
636            touched.add(op.blockId);
637        } else if (op.op === "upsert") {
638          const b = op.block;
639          const parentId = b.parentId ?? null;
640          if (parentId) {
641            const parent = await tx.block.findUnique({ where: { id: parentId }, select: { pageId: true, deletedAt: true } });
642            if (!parent || parent.deletedAt || parent.pageId !== pageId) throw ApiError.notFound(`parentId ${parentId} not found.`);
643          }
644          const position = await this.resolvePositionSafe(tx, pageId, b);
645          const created = await tx.block.create({
646            data: {
647              // Client-chosen ids (the web paste path references nested
648              // parents by id within the SAME batch): the DB primary key
649              // enforces uniqueness — a collision aborts the whole batch.
650              ...(b.id ? { id: b.id } : {}),
651              pageId,
652              workspaceId: page.workspaceId,
653              parentId,
654              type: b.type,
655              position,
656              content: b.content as Prisma.InputJsonValue,
657              properties: b.properties as object,
658              createdBy: userId
659            }
660          });
661          touched.add(created.id);
662        } else if (op.op === "delete") {
663          const block = await tx.block.findUnique({ where: { id: op.blockId }, select: { id: true, pageId: true, parentId: true, position: true, deletedAt: true } });
664          if (!block || block.deletedAt || block.pageId !== pageId) throw ApiError.notFound(`block ${op.blockId} not found.`);
665          const ids = await this.subtreeTx(tx, pageId, [op.blockId]);
666          await tx.block.deleteMany({ where: { pageId, id: { in: ids } } });
667          await this.fillGap(tx, pageId, block.parentId, block.position);
668          touched.add(op.blockId);
669        } else if (op.op === "move") {
670          const block = await tx.block.findUnique({ where: { id: op.blockId }, select: { id: true, pageId: true, parentId: true, position: true, deletedAt: true } });
671          if (!block || block.deletedAt || block.pageId !== pageId) throw ApiError.notFound(`block ${op.blockId} not found.`);
672          const mv = op.move;
673          const newParentId = mv.parentId ?? block.parentId;
674          if (newParentId) {
675            const parent = await tx.block.findUnique({ where: { id: newParentId }, select: { pageId: true, deletedAt: true } });
676            if (!parent || parent.deletedAt || parent.pageId !== pageId) throw ApiError.notFound(`move parent ${newParentId} not found.`);
677          }
678          await tx.block.update({ where: { id: op.blockId }, data: { parentId: newParentId } });
679          await this.fillGap(tx, pageId, block.parentId, block.position);
680          const position = await this.resolvePositionSafe(tx, pageId, mv);
681          await tx.block.update({ where: { id: op.blockId }, data: { position } });
682          touched.add(op.blockId);
683        }
684      }
685      return base + 1;
686    });
687    } catch (err) {
688      if (err instanceof BatchVersionCasConflict) {
689        // The authoritative CAS failed inside the transaction (a concurrent
690        // writer advanced pages.version between the pre-check and the
691        // UPDATE) → nothing was written; report the CURRENT version.
692        const fresh = await this.prisma.page.findUnique({ where: { id: pageId }, select: { version: true } });
693        const current = fresh?.version ?? page.version + 1;
694        throw ApiError.conflict(
695          "The page changed since you last read it (a concurrent edit — including a realtime flush). Re-read and retry.",
696          [
697            { issue: "stale_base_version", received: input.baseVersion ?? page.version },
698            { currentVersion: current },
699            { reason: "flush_wins" }
700          ]
701        );
702      }
703      throw err;
704    }
705    await this.audit.audit(req, req?.auth, {
706      action: "block.batch",
707      resourceType: "block",
708      resourceId: pageId,
709      workspaceId: page.workspaceId,
710      pageId,
711      metadata: { ops: input.ops.length, version: newVersion }
712    });
713    await this.events.publish(EVENTS.PAGE_UPDATED, {
714      workspaceId: page.workspaceId,
715      pageId,
716      version: newVersion,
717      blockIds: [...touched]
718    });
719    // T-157: watched-page fan-out (batch is the single block-write path); awaited
720    // + guarded (deterministic for tests, never fails the request).
721    try { await this.notifications.notifyWatchersForPageUpdate(pageId, userId); } catch { /* best-effort */ }
722    return { applied: input.ops.length, blockIds: [...touched], version: newVersion };
723  }
724 
725  private async subtreeTx(tx: Prisma.TransactionClient, pageId: string, roots: string[]): Promise<string[]> {
726    const rows = await tx.block.findMany({
727      where: { pageId, deletedAt: null },
728      select: { id: true, parentId: true }
729    });
730    const childrenOf = new Map<string | null, string[]>();
731    for (const r of rows) {
732      const list = childrenOf.get(r.parentId) ?? [];
733      list.push(r.id);
734      childrenOf.set(r.parentId, list);
735    }
736    const ids: string[] = [];
737    const queue = [...roots];
738    while (queue.length > 0) {
739      const id = queue.shift()!;
740      ids.push(id);
741      queue.push(...(childrenOf.get(id) ?? []));
742    }
743    return ids;
744  }
745 
746  // ---------- export ----------
747 
748  /** Flat text of a page (search fallback / export). */
749  async content(pageId: string, userId: string): Promise<{ pageId: string; text: string; blocks: number }> {
750    await this.requirePageAccess(pageId, userId, "VIEW");
751    const rows = await this.prisma.block.findMany({
752      where: { pageId, deletedAt: null },
753      select: { type: true, content: true, position: true },
754      orderBy: { position: "asc" },
755      take: MAX_BLOCK_TREE
756    });
757    const lines: string[] = [];
758    for (const r of rows) {
759      const c = r.content as { text?: string; title?: string };
760      const text = c.text ?? c.title ?? "";
761      if (text) lines.push(text);
762    }
763    return { pageId, text: lines.join("\n"), blocks: rows.length };
764  }
765}
766 
767/**
768 * The REST batch's `pages.version` CAS guard failed inside the transaction
769 * (TASK-0092): a concurrent writer advanced the version between the
770 * pre-check and the CAS UPDATE → the transaction aborts (nothing written)
771 * and `batch` converts this into the 409 CONFLICT carrying the new version.
772 */
773class BatchVersionCasConflict extends Error {
774  constructor() {
775    super("pages.version CAS conflict (concurrent external writer)");
776  }
777}
778