@supacloud/cli 0.116.0 → 0.117.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +672 -222
- package/dist/shared/tools/app-model-command-starter.d.ts +3 -0
- package/dist/shared/tools/app-model-command-starter.test.d.ts +1 -0
- package/dist/shared/tools/app-starter-database.d.ts +5 -3
- package/dist/shared/tools/app-starter-query.d.ts +1 -1
- package/dist/shared/tools/app-starter-tasks.d.ts +1 -1
- package/dist/shared/tools/app-starter-templates.d.ts +2 -1
- package/dist/shared/tools/app-tools.d.ts +1 -1
- package/dist/shared/tools/command-receipts.d.ts +1 -0
- package/dist/shared/tools/db-governance-tools.d.ts +1 -1
- package/dist/shared/tools/remote-dev-tools.d.ts +1 -7
- package/package.json +14 -10
- package/skills/supacloud/references/command-map.md +1 -1
- package/skills/supacloud/references/database-workflow.md +1 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type StarterSdkDependencies } from "./app-starter-templates";
|
|
2
|
+
/** Complete model-backed business recipe; the complex native-SQL command recipe stays separate. */
|
|
3
|
+
export declare function modelCommandTemplateFiles(name: string, sdk: StarterSdkDependencies): Record<string, string>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -7,10 +7,12 @@ export declare const STARTER_DATABASE_CONFIG: {
|
|
|
7
7
|
audit: string;
|
|
8
8
|
consumers: string[];
|
|
9
9
|
auditConsumers: never[];
|
|
10
|
+
trustedHosts: string[];
|
|
10
11
|
role: string;
|
|
11
12
|
};
|
|
12
|
-
export declare const
|
|
13
|
-
export declare const
|
|
13
|
+
export declare const STARTER_DATABASE_MODEL = "datasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\nplugin policy {\n provider = \"@zenstackhq/plugin-policy\"\n}\ntype Principal {\n id String\n canApprove Boolean\n @@auth()\n}\nmodel Application {\n singleton Boolean @id @default(true)\n projectId String @map(\"project_id\")\n tenantId String @map(\"tenant_id\")\n @@map(\"starter_application\")\n @@allow(\"read\", auth() != null)\n}\nmodel Review {\n id String @id\n ownerId String @map(\"owner_id\")\n state String\n version Int\n attachment Attachment?\n results AttachmentResult[]\n @@map(\"starter_reviews\")\n @@allow(\"read\", auth() != null && (ownerId == auth().id || auth().canApprove))\n}\nmodel Member {\n subject String @id\n enabled Boolean @default(true)\n canApprove Boolean @default(false) @map(\"can_approve\")\n storageSubject String? @unique @db.Uuid @map(\"storage_subject\")\n @@map(\"starter_members\")\n @@allow(\"read\", auth() != null && subject == auth().id)\n}\nmodel Attachment {\n reviewId String @id @map(\"review_id\")\n review Review @relation(fields: [reviewId], references: [id])\n artifactId String @unique @db.Uuid @map(\"artifact_id\")\n ownerId String @map(\"owner_id\")\n runId String @unique @db.Uuid @map(\"run_id\")\n objectPath String @unique @map(\"object_path\")\n retries AttachmentRetry[]\n @@map(\"starter_attachments\")\n @@allow(\"read\", auth() != null && ownerId == auth().id)\n}\nmodel AttachmentResult {\n reviewId String @map(\"review_id\")\n review Review @relation(fields: [reviewId], references: [id])\n version Int\n artifactId String @db.Uuid @map(\"artifact_id\")\n result Json\n @@id([reviewId, version, artifactId])\n @@map(\"starter_attachment_results\")\n @@allow(\"read\", auth() != null && review.ownerId == auth().id)\n}\nmodel AttachmentRetry {\n runId String @id @db.Uuid @map(\"run_id\")\n reviewId String @map(\"review_id\")\n attachment Attachment @relation(fields: [reviewId], references: [reviewId])\n previousRunId String @unique @db.Uuid @map(\"previous_run_id\")\n generation Int\n @@unique([reviewId, generation])\n @@map(\"starter_attachment_retries\")\n @@allow(\"read\", auth() != null && attachment.ownerId == auth().id)\n}\n";
|
|
14
|
+
export declare const STARTER_DATABASE_SCHEMA = "export type { Review as ReviewRow, Attachment as AttachmentRow, AttachmentRetry as AttachmentRetryRow } from \"../zenstack/generated/models\";\nimport type { Review } from \"../zenstack/generated/models\";\nexport type NewReview = Review;\n";
|
|
15
|
+
export declare const STARTER_DATABASE_MODULES = "import { defineDatabaseModule } from \"@supacloud/db\";\n\nconst backendPolicies = [\n [\"starter_backend_binding_read\", \"public.starter_application\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_lock\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_binding_immutable\", \"public.starter_application\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_read\", \"public.starter_members\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_lock\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_member_immutable\", \"public.starter_members\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_read\", \"public.starter_reviews\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_review_update\", \"public.starter_reviews\", \"update\", [\"starter_review_http\"]],\n [\"starter_worker_review_immutable\", \"public.starter_reviews\", \"update\", [\"starter_review_worker\"]],\n [\"starter_backend_attachment_read\", \"public.starter_attachments\", \"select\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_lock\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_backend_attachment_immutable\", \"public.starter_attachments\", \"update\", [\"starter_review_http\", \"starter_review_worker\"]],\n [\"starter_http_attachment_insert\", \"public.starter_attachments\", \"insert\", [\"starter_review_http\"]],\n [\"starter_worker_result_read\", \"public.starter_attachment_results\", \"select\", [\"starter_review_worker\"]],\n [\"starter_worker_result_insert\", \"public.starter_attachment_results\", \"insert\", [\"starter_review_worker\"]],\n] as const;\n\n// The module is the single live-Catalog ownership contract for starter tables.\nexport default defineDatabaseModule({\n name: \"starter\",\n tables: [\"public.starter_application\", \"public.starter_reviews\", \"public.starter_members\", \"public.starter_attachments\", \"public.starter_attachment_results\", \"public.starter_attachment_retries\"],\n policies: [\n ...([\n [\"starter_http_retry_read\", \"select\", \"starter_review_http\"],\n [\"starter_http_retry_insert\", \"insert\", \"starter_review_http\"],\n [\"starter_worker_retry_read\", \"select\", \"starter_review_worker\"],\n ] as const).map(([name, operation, role]) => ({\n name, table: \"public.starter_attachment_retries\", operation, roles: [role],\n source: \"migrations/005-review-task-recovery.sql\", tests: [\"tests/database-governance.sql\"],\n })),\n ...backendPolicies.map(([name, table, operation, roles]) => ({\n name, table, operation, roles: [...roles], source: \"migrations/004-review-runtime-roles.sql\",\n tests: [\"tests/database-governance.sql\"],\n })),\n {\n name: \"starter_member_read\", table: \"public.starter_members\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n {\n name: \"starter_review_read\", table: \"public.starter_reviews\", operation: \"select\",\n roles: [\"authenticated\"], source: \"migrations/003-review-uploads.sql\",\n tests: [\"tests/database-governance.sql\"],\n },\n ],\n});\n";
|
|
14
16
|
export declare const STARTER_DATABASE_TEST = "-- Read-only catalog assertions; behavioral authorization tests remain separate.\nBEGIN READ ONLY;\nDO $test$\nDECLARE\n owned text[] := ARRAY['starter_application','starter_reviews','starter_members',\n 'starter_attachments','starter_attachment_results','starter_attachment_retries'];\nBEGIN\n IF (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned) AND c.relrowsecurity) <> 6 THEN\n RAISE EXCEPTION 'All starter tables must exist with RLS enabled';\n END IF;\n IF (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname='public' AND c.relname=ANY(owned)) <> 20 THEN\n RAISE EXCEPTION 'Starter policy inventory changed; reconcile db/modules.ts';\n END IF;\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')\n AND (rolsuper OR rolbypassrls)) THEN\n RAISE EXCEPTION 'Starter roles must not bypass row security';\n END IF;\n IF (SELECT count(*) FROM pg_roles WHERE rolname IN ('starter_review_http','starter_review_worker')) <> 2 THEN\n RAISE EXCEPTION 'Starter runtime roles are missing';\n END IF;\nEND\n$test$;\nROLLBACK;\n";
|
|
15
|
-
export declare const STARTER_DATABASE_GUIDE = "\n##
|
|
17
|
+
export declare const STARTER_DATABASE_GUIDE = "\n## Model and migration workflow\n\nMaintain zenstack/schema.zmodel. Run `bun run db:generate` to compile model and RPC\ncontracts; commit generated types with their sources. Do not introduce any/@ts-ignore\nto bypass model or contract diagnostics. `bun run db:check` compares\nfresh generation without writing files or opening a database. Model read policies\ncomplement existing database RLS; command writes still use the shared transaction,\nreceipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs and RLS\nremain explicit reviewed migrations when the model language cannot express them.\n\nUse `bun run db:diff -- --candidate output/database-audit/change.sql` with an\nexplicit read-only SUPACLOUD_MODEL_DATABASE_URL. Review the SQL, then promote a new\nforward migration through the existing SupaCloud plan/apply ledger. Never run\nzen migrate deploy or db push against a managed production database.\n`bun run db:pull -- --candidate output/database-audit/schema.zmodel` writes a\nreview candidate only; it never overwrites the maintained model. Add policies\nbefore adopting introspection output. Keep one migration history and preserve RLS.\n";
|
|
16
18
|
export declare function starterDatabaseFiles(): Record<string, string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const STARTER_REVIEW_QUERY = "import type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { ReviewRow } from \"../../db/schema\";\n\n// This read projection uses SQL column names shared with the
|
|
1
|
+
export declare const STARTER_REVIEW_QUERY = "import type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { ReviewRow } from \"../../db/schema\";\n\n// This read projection uses SQL column names shared with the model source.\n// Do not expose camelCase model property names as PostgREST column names.\nexport type ReviewSummary = Pick<ReviewRow, \"id\" | \"state\" | \"version\">;\nexport type ReviewReadDatabase = {\n public: {\n Tables: {\n starter_reviews: {\n Row: ReviewSummary;\n Insert: never;\n Update: never;\n Relationships: [];\n };\n };\n Views: Record<never, never>;\n Functions: Record<never, never>;\n };\n};\n\nexport interface ReviewPageOptions {\n page?: number;\n pageSize?: number;\n signal?: AbortSignal;\n}\n\n// Reuse the application's user-scoped client. Identity verification and row\n// authorization belong to the gateway and database, never a caller-supplied owner.\nexport async function listReviews(\n client: SupabaseClient<ReviewReadDatabase>,\n { page = 1, pageSize = 25, signal }: ReviewPageOptions = {},\n) {\n if (!Number.isSafeInteger(page) || page < 1\n || !Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100\n || !Number.isSafeInteger(page * pageSize)) {\n throw new RangeError(\"Invalid review page: page >= 1 and pageSize between 1 and 100 are required\");\n }\n signal?.throwIfAborted();\n const start = (page - 1) * pageSize;\n const query = client.from(\"starter_reviews\")\n .select(\"id,state,version\", { count: \"exact\" })\n .order(\"id\", { ascending: true })\n .range(start, start + pageSize - 1);\n const { data, error, count } = await (signal ? query.abortSignal(signal) : query);\n if (error) throw error;\n if (data === null || count === null) throw new Error(\"Incomplete review page response\");\n if (!Array.isArray(data)\n || !Number.isSafeInteger(count) || count < 0\n || data.length > pageSize\n || (data.length > 0 && start + data.length > count)) {\n throw new Error(\"Invalid review page response\");\n }\n return { data, total: count, page, pageSize, hasNextPage: start + data.length < count };\n}\n";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export declare const STARTER_TASK_CONTRACTS = "import { t, type UnwrapSchema } from \"elysia\";\nimport { AttachmentResult } from \"./attachment\";\nimport { REVIEW_VERSION_MAX } from \"./limits\";\nimport { ReviewVersion } from \"./contracts\";\n\nexport const TaskParams = t.Object({ id: t.String({ minLength: 1, maxLength: 100 }) }, { additionalProperties: false });\nexport const RetryBody = t.Object({\n expectedVersion: t.Integer({ minimum: 2, maximum: REVIEW_VERSION_MAX }),\n expectedRunId: t.String({ format: \"uuid\" }),\n recoveryId: t.String({ format: \"uuid\" }),\n}, { additionalProperties: false });\nexport const RetryInput = t.Object({\n reviewId: TaskParams.properties.id, ...RetryBody.properties,\n}, { additionalProperties: false });\nexport const TaskStatus = t.Object({\n reviewId: TaskParams.properties.id,\n version: ReviewVersion,\n artifactId: t.Nullable(t.String({ format: \"uuid\" })),\n runId: t.Nullable(t.String({ format: \"uuid\" })),\n state: t.Union([t.Literal(\"not_submitted\"), t.Literal(\"queued\"), t.Literal(\"running\"),\n t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n canRetry: t.Boolean(),\n result: t.Nullable(AttachmentResult),\n}, { additionalProperties: false });\nexport const RetryResult = t.Object({\n reviewId: TaskParams.properties.id,\n previousRunId: t.String({ format: \"uuid\" }),\n runId: t.String({ format: \"uuid\" }),\n state: t.Literal(\"queued\"),\n}, { additionalProperties: false });\nexport type ReviewTaskStatus = UnwrapSchema<typeof TaskStatus>;\nexport type ReviewRetryBody = UnwrapSchema<typeof RetryBody>;\nexport type ReviewRetryInput = UnwrapSchema<typeof RetryInput>;\nexport type ReviewRetryResult = UnwrapSchema<typeof RetryResult>;\n";
|
|
2
2
|
export declare const STARTER_TASK_FEATURE = "import { Effect } from \"effect\";\nimport { Body, Controller, DB_CLIENT, Get, Inject, Injectable, Param, Post, REQUEST_CONTEXT } from \"@supacloud/app\";\nimport { ApplicationError } from \"@supacloud/elysia\";\nimport { RetryBody, RetryResult, TaskParams, TaskStatus,\n type ReviewRetryBody, type ReviewRetryInput, type ReviewRetryResult, type ReviewTaskStatus } from \"./task-contracts\";\n\nexport interface ReviewTaskPort {\n attachmentTask(context: unknown, reviewId: string): Promise<ReviewTaskStatus>;\n retryAttachmentTask(context: unknown, input: ReviewRetryInput): Promise<ReviewRetryResult>;\n}\ntype TaskError =\n | { readonly _tag: \"AUTHENTICATION_REQUIRED\" }\n | { readonly _tag: \"TASK_INPUT_INVALID\" }\n | { readonly _tag: \"TASK_DENIED\" }\n | { readonly _tag: \"TASK_CONFLICT\" }\n | { readonly _tag: \"TASK_UNAVAILABLE\" }\n | { readonly _tag: \"TASK_OUTCOME_UNKNOWN\" };\n\n@Injectable({ scope: \"request\" })\nexport class ReviewTasks {\n constructor(@Inject(DB_CLIENT) private readonly store: Partial<ReviewTaskPort>,\n @Inject(REQUEST_CONTEXT) private readonly context: unknown) {}\n\n status(id: string): Promise<ReviewTaskStatus> {\n if (!this.store.attachmentTask) throw new ApplicationError(\"Attachment tasks are not configured\", { status: 501, code: \"TASK_UNAVAILABLE\" });\n return this.store.attachmentTask(this.context, id);\n }\n retry(input: ReviewRetryInput): Promise<ReviewRetryResult> {\n if (!this.store.retryAttachmentTask) throw new ApplicationError(\"Attachment tasks are not configured\", { status: 501, code: \"TASK_UNAVAILABLE\" });\n return this.store.retryAttachmentTask(this.context, input);\n }\n}\n\n@Controller(\"/reviews\")\nexport class ReviewTasksController {\n constructor(@Inject(ReviewTasks) private readonly tasks: ReviewTasks) {}\n\n @Get(\"/:id/attachment-task\", {\n params: TaskParams, responses: { 200: TaskStatus },\n effect: { required: true, dependencies: [], retry: \"none\", errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"TASK_INPUT_INVALID\", status: 400, code: \"TASK_INPUT_INVALID\" },\n { tag: \"TASK_DENIED\", status: 403, code: \"TASK_DENIED\" },\n { tag: \"TASK_CONFLICT\", status: 409, code: \"TASK_CONFLICT\" },\n { tag: \"TASK_UNAVAILABLE\", status: 501, code: \"TASK_UNAVAILABLE\" },\n { tag: \"TASK_OUTCOME_UNKNOWN\", status: 503, code: \"TASK_OUTCOME_UNKNOWN\" },\n ] },\n })\n status(@Param(\"id\") id: string): Effect.Effect<ReviewTaskStatus, TaskError, never> {\n return Effect.promise(() => this.tasks.status(id));\n }\n\n @Post(\"/:id/attachment-task/retry\", {\n params: TaskParams, body: RetryBody, responses: { 200: RetryResult },\n effect: { required: true, dependencies: [], retry: \"none\", errors: [\n { tag: \"AUTHENTICATION_REQUIRED\", status: 401, code: \"AUTHENTICATION_REQUIRED\" },\n { tag: \"TASK_INPUT_INVALID\", status: 400, code: \"TASK_INPUT_INVALID\" },\n { tag: \"TASK_DENIED\", status: 403, code: \"TASK_DENIED\" },\n { tag: \"TASK_CONFLICT\", status: 409, code: \"TASK_CONFLICT\" },\n { tag: \"TASK_UNAVAILABLE\", status: 501, code: \"TASK_UNAVAILABLE\" },\n { tag: \"TASK_OUTCOME_UNKNOWN\", status: 503, code: \"TASK_OUTCOME_UNKNOWN\" },\n ] },\n })\n retry(@Param(\"id\") id: string, @Body() body: ReviewRetryBody): Effect.Effect<ReviewRetryResult, TaskError, never> {\n return Effect.promise(() => this.tasks.retry({ ...body, reviewId: id }));\n }\n}\n";
|
|
3
3
|
export declare const STARTER_TASK_SCHEMA = "-- Forward-only operator provisioning after 004 and the platform Workflow runtime.\nCREATE TABLE public.starter_attachment_retries (\n run_id uuid PRIMARY KEY,\n review_id text NOT NULL REFERENCES public.starter_attachments(review_id),\n previous_run_id uuid NOT NULL UNIQUE,\n generation integer NOT NULL CHECK (generation > 0),\n UNIQUE(review_id,generation),\n CHECK (run_id <> previous_run_id)\n);\nALTER TABLE public.starter_attachment_retries ENABLE ROW LEVEL SECURITY;\nREVOKE ALL ON public.starter_attachment_retries FROM PUBLIC, anon, authenticated;\nGRANT SELECT,INSERT ON public.starter_attachment_retries TO starter_review_http;\nGRANT SELECT ON public.starter_attachment_retries TO starter_review_worker;\nDROP POLICY IF EXISTS starter_http_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_http USING (true);\nDROP POLICY IF EXISTS starter_http_retry_insert ON public.starter_attachment_retries;\nCREATE POLICY starter_http_retry_insert ON public.starter_attachment_retries\n FOR INSERT TO starter_review_http WITH CHECK (true);\nDROP POLICY IF EXISTS starter_worker_retry_read ON public.starter_attachment_retries;\nCREATE POLICY starter_worker_retry_read ON public.starter_attachment_retries\n FOR SELECT TO starter_review_worker USING (true);\n-- Trusted HTTP adapters authorize the review before inspecting its bound run.\nGRANT EXECUTE ON FUNCTION supacloud_workflows.snapshot(uuid,boolean) TO starter_review_http;\n";
|
|
4
|
-
export declare const STARTER_TASK_HOST = "import { t } from \"elysia\";\nimport { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport { ApplicationError, createSchemaDecoder, requireTrustedIdentity } from \"@supacloud/elysia\";\nimport { AttachmentInput, AttachmentResult } from \"../review/attachment\";\nimport { ReviewResult } from \"../review/contracts\";\nimport { RetryInput, RetryResult, TaskParams, TaskStatus, type ReviewRetryInput } from \"../review/task-contracts\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport type { attachments, attachmentRetries, ReviewRow } from \"../../db/schema\";\n\nexport interface ReviewTaskOptions { database: CommandDatabase; projectId: string; tenantId: string }\ntype Binding = Pick<typeof attachments.$inferSelect, \"artifactId\" | \"runId\">\n & Pick<typeof attachmentRetries.$inferSelect, \"generation\" | \"runId\">;\nconst decodeInput = createSchemaDecoder(RetryInput, { normalize: false });\nconst decodeRetry = createSchemaDecoder(RetryResult, { normalize: false });\nconst decodeStatus = createSchemaDecoder(TaskStatus, { normalize: false });\nconst decodeParams = createSchemaDecoder(TaskParams, { normalize: false });\nconst decodeReview: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\nconst decodeResult = createSchemaDecoder(AttachmentResult, { normalize: false });\nconst decodeBinding: (value: unknown) => Binding = createSchemaDecoder(t.Object({\n artifactId: t.String({ format: \"uuid\" }), runId: t.String({ format: \"uuid\" }),\n generation: t.Integer({ minimum: 0 }),\n}), { normalize: false });\nconst decodeRun = createSchemaDecoder(t.Object({\n runId: t.String({ format: \"uuid\" }), workflowName: t.Literal(\"review.verify-attachment\"),\n workflowVersion: t.Literal(\"1\"),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n input: AttachmentInput, output: t.Unknown(), idempotent: t.Boolean(),\n steps: t.Array(t.Object({\n stepKey: t.Literal(\"verify\"), attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"dead_lettered\"), t.Literal(\"cancelled\")]),\n }, { additionalProperties: true }), { minItems: 1, maxItems: 1 }),\n}, { additionalProperties: true }), { normalize: false });\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new Error(\"Invalid task record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new Error(\"Invalid task rows\");\n return value.map(record);\n}\nfunction capture(value: unknown): ReviewRetryInput {\n try {\n const input = decodeInput(value);\n return { ...input, recoveryId: input.recoveryId.toLowerCase(), expectedRunId: input.expectedRunId.toLowerCase() };\n } catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n}\nfunction failure(error: unknown): never {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && error.code === \"COMMAND_REJECTED\") {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n if (error instanceof CommandError && error.code === \"COMMAND_IDEMPOTENCY_CONFLICT\") {\n throw new ApplicationError(\"Task changed or is not retryable\", { status: 409, code: \"TASK_CONFLICT\" });\n }\n throw new ApplicationError(\"Task outcome could not be confirmed\", { status: 503, code: \"TASK_OUTCOME_UNKNOWN\" });\n}\nconst conflict = () => { throw new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\"); };\n\nexport async function createReviewTaskAdapters(options: ReviewTaskOptions): Promise<ReviewTaskPort> {\n const { database, projectId, tenantId } = options;\n const configured = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (!projectId.trim() || !tenantId.trim() || configured.length !== 1\n || configured[0]?.[\"project_id\"] !== projectId || configured[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Task database project/tenant binding mismatch\");\n }\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n return who.subject;\n }\n async function authorize(tx: CommandTransaction, subject: string, reviewId: string) {\n const found = rows(await tx.query(\n \"SELECT r.state,r.version FROM public.starter_reviews r \" +\n \"JOIN public.starter_members m ON m.subject=r.owner_id CROSS JOIN public.starter_application p \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND p.singleton AND p.project_id=$3 AND p.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF p\",\n [reviewId, subject, projectId, tenantId],\n ));\n if (found.length !== 1) throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n return decodeReview(found[0]);\n }\n async function binding(tx: CommandTransaction, reviewId: string) {\n const found = rows(await tx.query(\n 'SELECT a.artifact_id AS \"artifactId\",COALESCE(retry.run_id,a.run_id) AS \"runId\",COALESCE(retry.generation,0) AS generation ' +\n \"FROM public.starter_attachments a LEFT JOIN LATERAL (\" +\n \"SELECT run_id,generation FROM public.starter_attachment_retries WHERE review_id=a.review_id ORDER BY generation DESC LIMIT 1\" +\n \") retry ON true WHERE a.review_id=$1\", [reviewId],\n ));\n return found.length === 0 ? null : decodeBinding(found[0]);\n }\n async function snapshot(tx: CommandTransaction, runId: string) {\n return rows(await tx.query(\"SELECT supacloud_workflows.snapshot($1::uuid,false) AS run\", [runId]))[0]?.[\"run\"];\n }\n function boundRun(value: unknown, reviewId: string, version: number, bound: NonNullable<Awaited<ReturnType<typeof binding>>>) {\n const run = decodeRun(value);\n if (run.runId !== bound.runId || run.input.reviewId !== reviewId\n || run.input.version !== version || run.input.artifactId !== bound.artifactId) {\n throw new Error(\"Task Workflow binding mismatch\");\n }\n const step = run.steps[0];\n if (!step || (run.status === \"queued\" && step.status !== \"queued\")\n || (run.status === \"running\" && step.status !== \"queued\" && step.status !== \"running\")\n || (run.status === \"completed\" && step.status !== \"completed\")\n || (run.status === \"failed\" && step.status !== \"failed\" && step.status !== \"dead_lettered\")\n || (run.status === \"cancelled\" && step.status !== \"cancelled\")) {\n throw new Error(\"Task Workflow state mismatch\");\n }\n return run;\n }\n const retry = createTransactionalCommand({\n name: \"review.retry-attachment\", store: createPostgresCommandStore(database),\n inputCodec: plaintextCommandInput, input: capture, result: decodeRetry,\n async authorize(who, input, tx) {\n try {\n const review = await authorize(tx, who.actorId, input.reviewId);\n return review.state === \"approved\" && review.version === input.expectedVersion ? \"allow\" : \"deny\";\n } catch (error) {\n if (error instanceof ApplicationError && error.code === \"TASK_DENIED\") return \"deny\";\n throw error;\n }\n },\n async execute(tx, input) {\n const bound = await binding(tx, input.reviewId);\n if (!bound || bound.runId !== input.expectedRunId || input.recoveryId === bound.runId) return conflict();\n const previous = boundRun(await snapshot(tx, bound.runId), input.reviewId, input.expectedVersion, bound);\n if (previous.status !== \"failed\") return conflict();\n if (await snapshot(tx, input.recoveryId) !== null) return conflict();\n const started = rows(await tx.query(\n \"SELECT supacloud_workflows.start_run($1::uuid,'review.verify-attachment','1','verify',$2::text::jsonb,3) AS run\",\n [input.recoveryId, JSON.stringify(previous.input)],\n ))[0]?.[\"run\"];\n const next = boundRun(started, input.reviewId, input.expectedVersion, { ...bound, runId: input.recoveryId });\n if (next.idempotent || next.status !== \"queued\") return conflict();\n await tx.query(\"INSERT INTO public.starter_attachment_retries(run_id,review_id,previous_run_id,generation) VALUES($1,$2,$3,$4)\",\n [input.recoveryId, input.reviewId, bound.runId, bound.generation + 1]);\n return { reviewId: input.reviewId, previousRunId: bound.runId, runId: input.recoveryId, state: \"queued\" as const };\n },\n audit: { event: \"review.attachment-retried\", details: input => ({\n reviewId: input.reviewId, previousRunId: input.expectedRunId, runId: input.recoveryId,\n }) },\n });\n return {\n async attachmentTask(context, reviewId) {\n try {\n const subject = actor(context);\n try { decodeParams({ id: reviewId }); }\n catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n return await database.transaction(async tx => {\n const review = await authorize(tx, subject, reviewId);\n const bound = await binding(tx, reviewId);\n const empty = { reviewId, version: review.version, artifactId: bound?.artifactId ?? null,\n runId: null, state: \"not_submitted\", attempts: 0, maxAttempts: 3, canRetry: false, result: null } as const;\n if (!bound) return decodeStatus(empty);\n const value = await snapshot(tx, bound.runId);\n if (value === null && review.state === \"draft\" && bound.generation === 0) return decodeStatus(empty);\n const run = boundRun(value, reviewId, review.version, bound);\n const step = run.steps[0];\n if (!step) throw new Error(\"Missing task step\");\n const result = run.status === \"completed\" ? decodeResult(run.output) : null;\n if (result && (result.reviewId !== reviewId || result.version !== review.version || result.artifactId !== bound.artifactId)) {\n throw new Error(\"Task result binding mismatch\");\n }\n return decodeStatus({ ...empty, runId: run.runId,\n state: run.status === \"running\" && step.status === \"queued\" ? \"queued\" : run.status,\n attempts: step.attempts, canRetry: run.status === \"failed\", result });\n });\n } catch (error) { return failure(error); }\n },\n async retryAttachmentTask(context, value) {\n try {\n const subject = actor(context), input = capture(value);\n const receipt = await retry.execute({ actorId: subject, tenantId }, input.recoveryId, input);\n if (receipt.status !== \"confirmed\") throw new CommandError(\"COMMAND_OUTCOME_UNKNOWN\");\n return receipt.result;\n } catch (error) { return failure(error); }\n },\n };\n}\n";
|
|
4
|
+
export declare const STARTER_TASK_HOST = "import { t } from \"elysia\";\nimport { createTransactionalCommand, plaintextCommandInput } from \"@supacloud/commands\";\nimport { CommandError } from \"@supacloud/contracts\";\nimport { createPostgresCommandStore, type CommandDatabase, type CommandTransaction } from \"@supacloud/db\";\nimport { ApplicationError, createSchemaDecoder, requireTrustedIdentity } from \"@supacloud/elysia\";\nimport { AttachmentInput, AttachmentResult } from \"../review/attachment\";\nimport { ReviewResult } from \"../review/contracts\";\nimport { RetryInput, RetryResult, TaskParams, TaskStatus, type ReviewRetryInput } from \"../review/task-contracts\";\nimport type { ReviewTaskPort } from \"../review/tasks\";\nimport type { ReviewRow } from \"../../db/schema\";\n\nexport interface ReviewTaskOptions { database: CommandDatabase; projectId: string; tenantId: string }\ntype Binding = { artifactId: string; runId: string; generation: number };\nconst decodeInput = createSchemaDecoder(RetryInput, { normalize: false });\nconst decodeRetry = createSchemaDecoder(RetryResult, { normalize: false });\nconst decodeStatus = createSchemaDecoder(TaskStatus, { normalize: false });\nconst decodeParams = createSchemaDecoder(TaskParams, { normalize: false });\nconst decodeReview: (value: unknown) => Pick<ReviewRow, \"state\" | \"version\"> =\n createSchemaDecoder(ReviewResult, { normalize: false });\nconst decodeResult = createSchemaDecoder(AttachmentResult, { normalize: false });\nconst decodeBinding: (value: unknown) => Binding = createSchemaDecoder(t.Object({\n artifactId: t.String({ format: \"uuid\" }), runId: t.String({ format: \"uuid\" }),\n generation: t.Integer({ minimum: 0 }),\n}), { normalize: false });\nconst decodeRun = createSchemaDecoder(t.Object({\n runId: t.String({ format: \"uuid\" }), workflowName: t.Literal(\"review.verify-attachment\"),\n workflowVersion: t.Literal(\"1\"),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"cancelled\")]),\n input: AttachmentInput, output: t.Unknown(), idempotent: t.Boolean(),\n steps: t.Array(t.Object({\n stepKey: t.Literal(\"verify\"), attempts: t.Integer({ minimum: 0 }),\n maxAttempts: t.Literal(3),\n status: t.Union([t.Literal(\"queued\"), t.Literal(\"running\"), t.Literal(\"completed\"), t.Literal(\"failed\"), t.Literal(\"dead_lettered\"), t.Literal(\"cancelled\")]),\n }, { additionalProperties: true }), { minItems: 1, maxItems: 1 }),\n}, { additionalProperties: true }), { normalize: false });\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction record(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) throw new Error(\"Invalid task record\");\n return value;\n}\nfunction rows(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) throw new Error(\"Invalid task rows\");\n return value.map(record);\n}\nfunction capture(value: unknown): ReviewRetryInput {\n try {\n const input = decodeInput(value);\n return { ...input, recoveryId: input.recoveryId.toLowerCase(), expectedRunId: input.expectedRunId.toLowerCase() };\n } catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n}\nfunction failure(error: unknown): never {\n if (error instanceof ApplicationError) throw error;\n if (error instanceof CommandError && error.code === \"COMMAND_REJECTED\") {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n if (error instanceof CommandError && error.code === \"COMMAND_IDEMPOTENCY_CONFLICT\") {\n throw new ApplicationError(\"Task changed or is not retryable\", { status: 409, code: \"TASK_CONFLICT\" });\n }\n throw new ApplicationError(\"Task outcome could not be confirmed\", { status: 503, code: \"TASK_OUTCOME_UNKNOWN\" });\n}\nconst conflict = () => { throw new CommandError(\"COMMAND_IDEMPOTENCY_CONFLICT\"); };\n\nexport async function createReviewTaskAdapters(options: ReviewTaskOptions): Promise<ReviewTaskPort> {\n const { database, projectId, tenantId } = options;\n const configured = rows(await database.transaction(tx => tx.query(\n \"SELECT project_id,tenant_id FROM public.starter_application WHERE singleton\",\n )));\n if (!projectId.trim() || !tenantId.trim() || configured.length !== 1\n || configured[0]?.[\"project_id\"] !== projectId || configured[0]?.[\"tenant_id\"] !== tenantId) {\n throw new Error(\"Task database project/tenant binding mismatch\");\n }\n function actor(context: unknown): string {\n const who = requireTrustedIdentity(context);\n const access = record(record(context)[\"access\"]);\n if (access[\"projectId\"] !== projectId || access[\"tenantId\"] !== tenantId\n || !Array.isArray(access[\"permissions\"]) || !access[\"permissions\"].includes(\"review.approve\")) {\n throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n }\n return who.subject;\n }\n async function authorize(tx: CommandTransaction, subject: string, reviewId: string) {\n const found = rows(await tx.query(\n \"SELECT r.state,r.version FROM public.starter_reviews r \" +\n \"JOIN public.starter_members m ON m.subject=r.owner_id CROSS JOIN public.starter_application p \" +\n \"WHERE r.id=$1 AND r.owner_id=$2 AND m.enabled AND m.can_approve \" +\n \"AND p.singleton AND p.project_id=$3 AND p.tenant_id=$4 FOR UPDATE OF r,m FOR SHARE OF p\",\n [reviewId, subject, projectId, tenantId],\n ));\n if (found.length !== 1) throw new ApplicationError(\"Task access denied\", { status: 403, code: \"TASK_DENIED\" });\n return decodeReview(found[0]);\n }\n async function binding(tx: CommandTransaction, reviewId: string) {\n const found = rows(await tx.query(\n 'SELECT a.artifact_id AS \"artifactId\",COALESCE(retry.run_id,a.run_id) AS \"runId\",COALESCE(retry.generation,0) AS generation ' +\n \"FROM public.starter_attachments a LEFT JOIN LATERAL (\" +\n \"SELECT run_id,generation FROM public.starter_attachment_retries WHERE review_id=a.review_id ORDER BY generation DESC LIMIT 1\" +\n \") retry ON true WHERE a.review_id=$1\", [reviewId],\n ));\n return found.length === 0 ? null : decodeBinding(found[0]);\n }\n async function snapshot(tx: CommandTransaction, runId: string) {\n return rows(await tx.query(\"SELECT supacloud_workflows.snapshot($1::uuid,false) AS run\", [runId]))[0]?.[\"run\"];\n }\n function boundRun(value: unknown, reviewId: string, version: number, bound: NonNullable<Awaited<ReturnType<typeof binding>>>) {\n const run = decodeRun(value);\n if (run.runId !== bound.runId || run.input.reviewId !== reviewId\n || run.input.version !== version || run.input.artifactId !== bound.artifactId) {\n throw new Error(\"Task Workflow binding mismatch\");\n }\n const step = run.steps[0];\n if (!step || (run.status === \"queued\" && step.status !== \"queued\")\n || (run.status === \"running\" && step.status !== \"queued\" && step.status !== \"running\")\n || (run.status === \"completed\" && step.status !== \"completed\")\n || (run.status === \"failed\" && step.status !== \"failed\" && step.status !== \"dead_lettered\")\n || (run.status === \"cancelled\" && step.status !== \"cancelled\")) {\n throw new Error(\"Task Workflow state mismatch\");\n }\n return run;\n }\n const retry = createTransactionalCommand({\n name: \"review.retry-attachment\", store: createPostgresCommandStore(database),\n inputCodec: plaintextCommandInput, input: capture, result: decodeRetry,\n async authorize(who, input, tx) {\n try {\n const review = await authorize(tx, who.actorId, input.reviewId);\n return review.state === \"approved\" && review.version === input.expectedVersion ? \"allow\" : \"deny\";\n } catch (error) {\n if (error instanceof ApplicationError && error.code === \"TASK_DENIED\") return \"deny\";\n throw error;\n }\n },\n async execute(tx, input) {\n const bound = await binding(tx, input.reviewId);\n if (!bound || bound.runId !== input.expectedRunId || input.recoveryId === bound.runId) return conflict();\n const previous = boundRun(await snapshot(tx, bound.runId), input.reviewId, input.expectedVersion, bound);\n if (previous.status !== \"failed\") return conflict();\n if (await snapshot(tx, input.recoveryId) !== null) return conflict();\n const started = rows(await tx.query(\n \"SELECT supacloud_workflows.start_run($1::uuid,'review.verify-attachment','1','verify',$2::text::jsonb,3) AS run\",\n [input.recoveryId, JSON.stringify(previous.input)],\n ))[0]?.[\"run\"];\n const next = boundRun(started, input.reviewId, input.expectedVersion, { ...bound, runId: input.recoveryId });\n if (next.idempotent || next.status !== \"queued\") return conflict();\n await tx.query(\"INSERT INTO public.starter_attachment_retries(run_id,review_id,previous_run_id,generation) VALUES($1,$2,$3,$4)\",\n [input.recoveryId, input.reviewId, bound.runId, bound.generation + 1]);\n return { reviewId: input.reviewId, previousRunId: bound.runId, runId: input.recoveryId, state: \"queued\" as const };\n },\n audit: { event: \"review.attachment-retried\", details: input => ({\n reviewId: input.reviewId, previousRunId: input.expectedRunId, runId: input.recoveryId,\n }) },\n });\n return {\n async attachmentTask(context, reviewId) {\n try {\n const subject = actor(context);\n try { decodeParams({ id: reviewId }); }\n catch { throw new ApplicationError(\"Invalid task request\", { status: 400, code: \"TASK_INPUT_INVALID\" }); }\n return await database.transaction(async tx => {\n const review = await authorize(tx, subject, reviewId);\n const bound = await binding(tx, reviewId);\n const empty = { reviewId, version: review.version, artifactId: bound?.artifactId ?? null,\n runId: null, state: \"not_submitted\", attempts: 0, maxAttempts: 3, canRetry: false, result: null } as const;\n if (!bound) return decodeStatus(empty);\n const value = await snapshot(tx, bound.runId);\n if (value === null && review.state === \"draft\" && bound.generation === 0) return decodeStatus(empty);\n const run = boundRun(value, reviewId, review.version, bound);\n const step = run.steps[0];\n if (!step) throw new Error(\"Missing task step\");\n const result = run.status === \"completed\" ? decodeResult(run.output) : null;\n if (result && (result.reviewId !== reviewId || result.version !== review.version || result.artifactId !== bound.artifactId)) {\n throw new Error(\"Task result binding mismatch\");\n }\n return decodeStatus({ ...empty, runId: run.runId,\n state: run.status === \"running\" && step.status === \"queued\" ? \"queued\" : run.status,\n attempts: step.attempts, canRetry: run.status === \"failed\", result });\n });\n } catch (error) { return failure(error); }\n },\n async retryAttachmentTask(context, value) {\n try {\n const subject = actor(context), input = capture(value);\n const receipt = await retry.execute({ actorId: subject, tenantId }, input.recoveryId, input);\n if (receipt.status !== \"confirmed\") throw new CommandError(\"COMMAND_OUTCOME_UNKNOWN\");\n return receipt.result;\n } catch (error) { return failure(error); }\n },\n };\n}\n";
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export type StarterTemplate = "minimal" | "command";
|
|
1
|
+
export type StarterTemplate = "minimal" | "command" | "model-command";
|
|
2
2
|
export interface StarterSdkDependencies {
|
|
3
3
|
"@supacloud/js": string;
|
|
4
4
|
"@supabase/supabase-js": string;
|
|
5
5
|
}
|
|
6
|
+
export declare function baseTemplateFiles(name: string, sdkDependencies: StarterSdkDependencies): Record<string, string>;
|
|
6
7
|
/** New projects use the minimal layout; the command recipe is emitted separately. */
|
|
7
8
|
export declare function appTemplateFiles(name: string, template: "minimal", sdkDependencies: StarterSdkDependencies): Record<string, string>;
|
|
@@ -67,7 +67,7 @@ export interface AppToolArguments {
|
|
|
67
67
|
wait?: boolean;
|
|
68
68
|
timeout_seconds?: number;
|
|
69
69
|
kind?: "module" | "command" | "query" | "controller" | "job" | "contract" | "resource" | "feature";
|
|
70
|
-
template?: "minimal" | "command";
|
|
70
|
+
template?: "minimal" | "command" | "model-command";
|
|
71
71
|
name?: string;
|
|
72
72
|
module?: string;
|
|
73
73
|
permission?: string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const COMMAND_RECEIPT_SQL = "CREATE SCHEMA IF NOT EXISTS supacloud_commands;\nREVOKE ALL ON SCHEMA supacloud_commands FROM PUBLIC;\nCREATE TABLE IF NOT EXISTS supacloud_commands.execution_receipts (\n tenant_id text NOT NULL,\n actor_id text NOT NULL,\n command text NOT NULL,\n operation_key text NOT NULL,\n kind text NOT NULL CHECK (kind IN ('transactional', 'external')),\n input_fingerprint text NOT NULL CHECK (input_fingerprint ~ '^[a-f0-9]{64}$'),\n input_payload text,\n dispatch_key uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,\n status text NOT NULL CHECK (status IN ('pending', 'unknown', 'confirmed', 'rejected')),\n audit_state text NOT NULL CHECK (audit_state IN ('pending', 'complete')),\n result jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (tenant_id, actor_id, command, operation_key),\n CHECK ((status = 'confirmed') = (result IS NOT NULL)),\n CONSTRAINT execution_receipts_audit_terminal_check CHECK (\n (audit_state <> 'complete' OR status IN ('confirmed', 'rejected'))\n AND (status <> 'rejected' OR audit_state = 'complete')),\n CONSTRAINT execution_receipts_transactional_check CHECK (\n kind <> 'transactional' OR (status = 'confirmed' AND audit_state = 'complete'))\n);\nCREATE TABLE IF NOT EXISTS supacloud_commands.execution_audit (\n tenant_id text NOT NULL,\n actor_id text NOT NULL,\n command text NOT NULL,\n operation_key text NOT NULL,\n event text NOT NULL,\n details jsonb NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (tenant_id, actor_id, command, operation_key),\n FOREIGN KEY (tenant_id, actor_id, command, operation_key)\n REFERENCES supacloud_commands.execution_receipts (tenant_id, actor_id, command, operation_key)\n);\nREVOKE ALL ON supacloud_commands.execution_receipts, supacloud_commands.execution_audit FROM PUBLIC;\nCREATE OR REPLACE FUNCTION supacloud_commands.protect_terminal_execution()\nRETURNS trigger LANGUAGE plpgsql SET search_path = '' AS $terminal$\nBEGIN\n IF OLD.status IN ('confirmed','rejected') AND (\n NEW.status IS DISTINCT FROM OLD.status OR NEW.result IS DISTINCT FROM OLD.result\n OR (OLD.audit_state = 'complete' AND NEW.audit_state IS DISTINCT FROM OLD.audit_state)) THEN\n RAISE EXCEPTION 'SUPACLOUD_COMMAND_TERMINAL_RECEIPT';\n END IF;\n RETURN NEW;\nEND\n$terminal$;\nCREATE OR REPLACE TRIGGER execution_terminal_guard\nBEFORE UPDATE ON supacloud_commands.execution_receipts\nFOR EACH ROW EXECUTE FUNCTION supacloud_commands.protect_terminal_execution();\n\nCREATE OR REPLACE FUNCTION supacloud_commands.require_rejection_audit()\nRETURNS trigger LANGUAGE plpgsql SET search_path = '' AS $rejection$\nBEGIN\n IF NEW.status = 'rejected' AND NOT EXISTS (\n SELECT FROM supacloud_commands.execution_audit a\n WHERE a.tenant_id=NEW.tenant_id AND a.actor_id=NEW.actor_id\n AND a.command=NEW.command AND a.operation_key=NEW.operation_key\n ) THEN\n RAISE EXCEPTION 'SUPACLOUD_COMMAND_REJECTION_AUDIT_REQUIRED';\n END IF;\n RETURN NEW;\nEND\n$rejection$;\nDROP TRIGGER IF EXISTS execution_rejection_audit ON supacloud_commands.execution_receipts;\nCREATE CONSTRAINT TRIGGER execution_rejection_audit\nAFTER INSERT OR UPDATE ON supacloud_commands.execution_receipts\nDEFERRABLE INITIALLY DEFERRED\nFOR EACH ROW WHEN (NEW.status = 'rejected')\nEXECUTE FUNCTION supacloud_commands.require_rejection_audit();\n";
|
|
@@ -43,7 +43,7 @@ export interface DatabaseAiContext {
|
|
|
43
43
|
target: string | null;
|
|
44
44
|
objects: DatabaseAiContextObject[];
|
|
45
45
|
maintenance: {
|
|
46
|
-
structureSource: "
|
|
46
|
+
structureSource: "zmodel" | "declarative-sql";
|
|
47
47
|
behaviorSource: "sql";
|
|
48
48
|
generatedPaths: string[];
|
|
49
49
|
protectedPaths: string[];
|
|
@@ -6,7 +6,6 @@ type CommandResult = {
|
|
|
6
6
|
stderr: string;
|
|
7
7
|
};
|
|
8
8
|
type CommandExecutor = (command: string, args: string[], cwd: string) => Promise<CommandResult>;
|
|
9
|
-
type DatabaseCallback = (args: Record<string, unknown>) => Promise<unknown>;
|
|
10
9
|
export interface RemoteDevToolOptions {
|
|
11
10
|
cwd?: string;
|
|
12
11
|
host?: string;
|
|
@@ -16,10 +15,9 @@ export interface RemoteDevToolOptions {
|
|
|
16
15
|
projectRef?: string;
|
|
17
16
|
environment?: string;
|
|
18
17
|
execute?: CommandExecutor;
|
|
19
|
-
runDatabase?: DatabaseCallback;
|
|
20
18
|
}
|
|
21
19
|
export declare const remoteDevToolSchema: {
|
|
22
|
-
action: Type.TEnum<("
|
|
20
|
+
action: Type.TEnum<("status" | "sync" | "watch")[]>;
|
|
23
21
|
target: Type.TOptional<Type.TEnum<("db" | "frontend" | "functions" | "project")[]>>;
|
|
24
22
|
project_dir: Type.TOptional<Type.TString>;
|
|
25
23
|
remote_root: Type.TOptional<Type.TString>;
|
|
@@ -31,10 +29,6 @@ export declare const remoteDevToolSchema: {
|
|
|
31
29
|
delete: Type.TOptional<Type.TBoolean>;
|
|
32
30
|
reload: Type.TOptional<Type.TBoolean>;
|
|
33
31
|
interval_ms: Type.TOptional<Type.TNumber>;
|
|
34
|
-
apply: Type.TOptional<Type.TBoolean>;
|
|
35
|
-
drizzle_config: Type.TOptional<Type.TString>;
|
|
36
|
-
migrations_dir: Type.TOptional<Type.TString>;
|
|
37
|
-
drizzle_bin: Type.TOptional<Type.TString>;
|
|
38
32
|
};
|
|
39
33
|
export declare function registerRemoteDevTools(server: ToolServer, options?: RemoteDevToolOptions): void;
|
|
40
34
|
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.117.0",
|
|
4
4
|
"description": "Project-scoped CLI for SupaCloud users",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
],
|
|
30
30
|
"scripts": {
|
|
31
31
|
"dev": "bun run --watch src/index.ts",
|
|
32
|
-
"prepare:db": "bun install --cwd ../contracts --frozen-lockfile && bun run --cwd ../contracts build && bun install --cwd ../db --force --frozen-lockfile && bun run --cwd ../db build && bun install --force --frozen-lockfile",
|
|
32
|
+
"prepare:db": "bun install --cwd ../contracts --frozen-lockfile && bun run --cwd ../contracts build && bun install --cwd ../compiler --frozen-lockfile && bun run --cwd ../compiler build && bun install --cwd ../db --force --frozen-lockfile && bun run --cwd ../db build && bun install --force --frozen-lockfile",
|
|
33
33
|
"prebuild": "bun run prepare:db",
|
|
34
34
|
"build": "bun build src/index.ts --outdir dist --target node --conditions=supacloud-source --external @supacloud/compiler --external @supacloud/db && bun run build:tool-runtime && bun run build:types",
|
|
35
35
|
"build:tool-runtime": "bun build src/tool-runtime.ts --outdir dist --target node --external typebox && tsc -p tsconfig.tool-runtime.json --emitDeclarationOnly",
|
|
@@ -52,22 +52,26 @@
|
|
|
52
52
|
"directory": "packages/cli"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@supacloud/compiler": "^0.
|
|
56
|
-
"@supacloud/delivery": "0.
|
|
57
|
-
"@supacloud/db": "0.
|
|
55
|
+
"@supacloud/compiler": "^0.57.0",
|
|
56
|
+
"@supacloud/delivery": "0.25.0",
|
|
57
|
+
"@supacloud/db": "0.21.0",
|
|
58
58
|
"typebox": "1.4.3"
|
|
59
59
|
},
|
|
60
60
|
"overrides": {
|
|
61
|
-
"@supacloud/contracts": "0.
|
|
62
|
-
"@supacloud/delivery": "0.
|
|
63
|
-
"@graphql-tools/utils": "^12.0.4"
|
|
61
|
+
"@supacloud/contracts": "0.16.0",
|
|
62
|
+
"@supacloud/delivery": "0.25.0",
|
|
63
|
+
"@graphql-tools/utils": "^12.0.4",
|
|
64
|
+
"@supacloud/compiler": "^0.57.0",
|
|
65
|
+
"@supacloud/db": "0.21.0",
|
|
66
|
+
"deepmerge-ts": "8.0.2",
|
|
67
|
+
"prisma": "6.19.3"
|
|
64
68
|
},
|
|
65
69
|
"devDependencies": {
|
|
66
70
|
"@supabase/supabase-js": "2.118.0",
|
|
67
|
-
"@supacloud/elysia": "0.
|
|
71
|
+
"@supacloud/elysia": "0.40.0",
|
|
68
72
|
"@types/bun": "^1.4.4",
|
|
69
73
|
"effect": "4.0.5",
|
|
70
74
|
"elysia": "2.0.0-rc.1",
|
|
71
|
-
"typescript": "
|
|
75
|
+
"typescript": "7.1.0-beta"
|
|
72
76
|
}
|
|
73
77
|
}
|
|
@@ -20,7 +20,7 @@ Load this reference when selecting a command surface or when a user asks an AI t
|
|
|
20
20
|
| Read database rows or metadata | `database query` and database inspection actions | `SELECT`/read-only by default |
|
|
21
21
|
| Create schema/function/RPC/trigger/RLS/index/grant/extension | `supabase migration_new`, then edit SQL | Never direct remote DDL |
|
|
22
22
|
| Generate migration from local schema changes | `supabase db_diff` | Review generated SQL before use |
|
|
23
|
-
| Generate migration from declarative SQL | `supabase db_schema_declarative_sync` | Defaults to no-apply; preserve an existing
|
|
23
|
+
| Generate migration from declarative SQL | `supabase db_schema_declarative_sync` | Defaults to no-apply; preserve an existing ZModel/schema authority |
|
|
24
24
|
| Capture declarative schema files | `supabase db_schema_declarative_generate` | Explicit DSN or upstream linked project; overwrite requires approval |
|
|
25
25
|
| Pull official Supabase configuration | `supabase config_pull` | Preview by default; local write requires `dry_run=false` and `yes`; not SupaCloud settings |
|
|
26
26
|
| Run the official local stack | `supabase stack_start`, `stack_prepare`, `stack_status`, `stack_stop` | Docker default; native alpha requires `SUPACLOUD_ENABLE_NATIVE_STACK=1` |
|
|
@@ -43,7 +43,7 @@ supacloud supabase db_schema_declarative_sync --name <intent> --strict_coverage
|
|
|
43
43
|
|
|
44
44
|
The adapter defaults to no-apply. Review the generated migration, then use the
|
|
45
45
|
same local verification and controlled remote push steps above. Do not introduce
|
|
46
|
-
a second declarative source over
|
|
46
|
+
a second declarative source over ZModel-generated schemas. Verify the installed
|
|
47
47
|
official CLI supports this experimental command before changing project config.
|
|
48
48
|
|
|
49
49
|
`supabase config_pull` previews official Supabase settings. Applying that local
|