@composable-os/cli 0.0.0-stage → 0.1.0-beta.8

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.
Files changed (140) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/blocks-DEELKGDC.js +233 -0
  4. package/dist/chunk-2ABSVMGB.js +13 -0
  5. package/dist/chunk-2S7375SC.js +802 -0
  6. package/dist/chunk-5KSXSK7Y.js +47 -0
  7. package/dist/chunk-6UWRT4VM.js +220 -0
  8. package/dist/chunk-E5JLTLRM.js +50 -0
  9. package/dist/chunk-G3ORKXVP.js +1178 -0
  10. package/dist/chunk-HDIOVFAZ.js +544 -0
  11. package/dist/chunk-KGHA67HG.js +765 -0
  12. package/dist/chunk-KOKYDJ7Z.js +1423 -0
  13. package/dist/chunk-KTXGEXTY.js +358 -0
  14. package/dist/chunk-LTQDLCP7.js +16486 -0
  15. package/dist/chunk-MAXLUQKB.js +1287 -0
  16. package/dist/chunk-STJZJIRA.js +11378 -0
  17. package/dist/chunk-X6I2LWB3.js +24319 -0
  18. package/dist/chunk-XDDBLYKW.js +29154 -0
  19. package/dist/chunk-ZRWF6QZS.js +2357 -0
  20. package/dist/cli-BRSACHSG.js +31393 -0
  21. package/dist/cli-DTMGNDXN.js +121 -0
  22. package/dist/cli.js +25 -0
  23. package/dist/client-repo-ZVZ6KW5S.js +55 -0
  24. package/dist/create.js +25 -0
  25. package/dist/fields-64BQJA62.js +48 -0
  26. package/dist/invoke-NHHOLLF6.js +26 -0
  27. package/dist/person-WMWRF2HV.js +58 -0
  28. package/dist/platform/migrations/0001_init.sql +59 -0
  29. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  30. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  31. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  32. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  33. package/dist/platform/migrations/0006_search.sql +223 -0
  34. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  35. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  36. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  37. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  38. package/dist/platform/migrations/0020_extensions.sql +373 -0
  39. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  40. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  41. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  42. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  43. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  44. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  45. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  46. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  47. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  48. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  49. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  50. package/dist/platform/migrations/0110_integrations.sql +103 -0
  51. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  52. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  53. package/dist/platform/migrations/0130_automations.sql +113 -0
  54. package/dist/platform/migrations/0131_notifications.sql +29 -0
  55. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  56. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  57. package/dist/platform/migrations/0160_releases.sql +41 -0
  58. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  59. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  60. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  61. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  62. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  63. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  64. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  65. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  66. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  67. package/dist/platform/migrations/0250_judge.sql +11 -0
  68. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  69. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  70. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  71. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  72. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  73. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  74. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  75. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  76. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  77. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  78. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  79. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  80. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  81. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  82. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  83. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  84. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  85. package/dist/platform/migrations/0365_routines.sql +38 -0
  86. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  87. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  88. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  89. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  90. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  91. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  92. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  93. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  94. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  95. package/dist/platform/migrations/0421_orders.sql +134 -0
  96. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  97. package/dist/platform/migrations/0440_capacity.sql +100 -0
  98. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  99. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  100. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  101. package/dist/platform/migrations/0460_content.sql +59 -0
  102. package/dist/platform/migrations/0461_media.sql +52 -0
  103. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  104. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  105. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  106. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  107. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  108. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  109. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  110. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  111. package/dist/platform/sdk/automation-check.ts +534 -0
  112. package/dist/platform/sdk/automation.ts +743 -0
  113. package/dist/platform/sdk/behaviour.ts +215 -0
  114. package/dist/platform/sdk/capacity.ts +112 -0
  115. package/dist/platform/sdk/contract.ts +766 -0
  116. package/dist/platform/sdk/document.ts +788 -0
  117. package/dist/platform/sdk/field-types.ts +106 -0
  118. package/dist/platform/sdk/formula/ast.ts +72 -0
  119. package/dist/platform/sdk/formula/compile.ts +454 -0
  120. package/dist/platform/sdk/formula/index.ts +4 -0
  121. package/dist/platform/sdk/formula/parser.ts +417 -0
  122. package/dist/platform/sdk/index.ts +33 -0
  123. package/dist/platform/sdk/manifest.ts +1484 -0
  124. package/dist/platform/sdk/media.ts +46 -0
  125. package/dist/platform/sdk/permissions.ts +60 -0
  126. package/dist/platform/sdk/renamed.ts +63 -0
  127. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  128. package/dist/platform/sdk/rich-text.ts +173 -0
  129. package/dist/platform/sdk/runtime.ts +410 -0
  130. package/dist/platform/sdk/sellable.ts +396 -0
  131. package/dist/platform/sdk/slug.ts +25 -0
  132. package/dist/platform/sdk/states.ts +162 -0
  133. package/dist/platform/sdk/testing.ts +836 -0
  134. package/dist/products-2H5DR232.js +11 -0
  135. package/dist/run-4JNFLYXV.js +847 -0
  136. package/dist/src-G6OF5SKW.js +31 -0
  137. package/dist/src-J27WXNLY.js +270 -0
  138. package/dist/token-MOJUA2U6.js +70 -0
  139. package/dist/token-util-TENRN4V7.js +6 -0
  140. package/package.json +33 -4
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ productContract,
4
+ renderClient
5
+ } from "./chunk-KTXGEXTY.js";
6
+ import "./chunk-XDDBLYKW.js";
7
+ import "./chunk-LTQDLCP7.js";
8
+ import "./chunk-ZRWF6QZS.js";
9
+ import "./chunk-6UWRT4VM.js";
10
+ import "./chunk-MAXLUQKB.js";
11
+ import "./chunk-STJZJIRA.js";
12
+ import "./chunk-KGHA67HG.js";
13
+ import "./chunk-2S7375SC.js";
14
+ import "./chunk-X6I2LWB3.js";
15
+ import "./chunk-5KSXSK7Y.js";
16
+
17
+ // ../client-gen/src/node/cli.ts
18
+ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
19
+ import { tmpdir } from "node:os";
20
+ import { dirname, join, resolve } from "node:path";
21
+ import { pathToFileURL } from "node:url";
22
+ var CLIENT_HELP = `cos client generate: write a product's typed client.
23
+
24
+ cos client generate --out <dir> [--product <id>] [--extension <dir>]... [--runtime <module>]
25
+
26
+ --out <dir> where customer.ts and staff.ts are written (commit them)
27
+ --product <id> the product whose registry is read (default: the active product)
28
+ --extension <dir> an extension of the org's own, besides the product's packs (repeatable)
29
+ --runtime <module> the runtime import (default @composable-os/client)
30
+ `;
31
+ function repoRoot(from) {
32
+ let dir = resolve(from);
33
+ for (; ; ) {
34
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
35
+ const parent = dirname(dir);
36
+ if (parent === dir) return null;
37
+ dir = parent;
38
+ }
39
+ }
40
+ async function loadExtension(dir) {
41
+ const entry = join(resolve(dir), "index.ts");
42
+ if (!existsSync(entry)) throw new Error(`${dir} has no index.ts`);
43
+ const { build } = await import("esbuild");
44
+ const out = join(mkdtempSync(join(tmpdir(), "cos-client-")), "extension.mjs");
45
+ await build({
46
+ entryPoints: [entry],
47
+ outfile: out,
48
+ bundle: true,
49
+ platform: "node",
50
+ format: "esm",
51
+ logLevel: "error"
52
+ });
53
+ const module = await import(pathToFileURL(out).href);
54
+ if (!module.default) throw new Error(`${entry} has no default export (defineExtension)`);
55
+ return module.default;
56
+ }
57
+ function parse(argv) {
58
+ const parsed = { extensions: [] };
59
+ for (let i = 0; i < argv.length; i += 1) {
60
+ const flag = argv[i];
61
+ const value = argv[i + 1];
62
+ if (!value || value.startsWith("--")) throw new Error(`${flag} needs a value`);
63
+ if (flag === "--out") parsed.out = value;
64
+ else if (flag === "--product") parsed.product = value;
65
+ else if (flag === "--extension") parsed.extensions.push(value);
66
+ else if (flag === "--runtime") parsed.runtime = value;
67
+ else throw new Error(`Unknown option ${flag}`);
68
+ i += 1;
69
+ }
70
+ return parsed;
71
+ }
72
+ async function runClient(argv, io) {
73
+ if (argv[0] !== "generate" || argv.includes("--help")) {
74
+ io.out(CLIENT_HELP);
75
+ return argv[0] === "generate" || argv.includes("--help") ? 0 : 2;
76
+ }
77
+ let parsed;
78
+ try {
79
+ parsed = parse(argv.slice(1));
80
+ } catch (error) {
81
+ io.err(error.message);
82
+ return 2;
83
+ }
84
+ if (!parsed.out) {
85
+ io.err("--out <dir> is required");
86
+ return 2;
87
+ }
88
+ const { products, DEFAULT_PRODUCT } = await import("./products-2H5DR232.js");
89
+ const id = parsed.product ?? DEFAULT_PRODUCT;
90
+ const product = products[id];
91
+ if (!product) {
92
+ io.err(`No product named ${id}. Known: ${Object.keys(products).join(", ")}`);
93
+ return 2;
94
+ }
95
+ const root = repoRoot(process.cwd());
96
+ const dirs = [
97
+ ...product.packs.map((pack) => {
98
+ if (!root) throw new Error("Run cos client generate in a checkout of the repository");
99
+ return join(root, "packs", pack);
100
+ }),
101
+ ...parsed.extensions
102
+ ];
103
+ const extensions = await Promise.all(dirs.map(loadExtension));
104
+ const contract = productContract(extensions);
105
+ const files = renderClient(contract, {
106
+ product: id,
107
+ ...parsed.runtime ? { runtime: parsed.runtime } : {}
108
+ });
109
+ mkdirSync(parsed.out, { recursive: true });
110
+ for (const [name, text] of Object.entries(files)) writeFileSync(join(parsed.out, name), text);
111
+ const counts = Object.entries(files).map(
112
+ ([name, text]) => `${name} (${(text.match(/^ {2}"[^"]+": \{$/gm) ?? []).length} operations)`
113
+ ).join(", ");
114
+ io.out(`Wrote ${counts} in ${parsed.out} for ${id}, API ${contract.version}.`);
115
+ return 0;
116
+ }
117
+ export {
118
+ CLIENT_HELP,
119
+ loadExtension,
120
+ runClient
121
+ };
package/dist/cli.js ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ghAvailable,
4
+ ghVerifier
5
+ } from "./chunk-E5JLTLRM.js";
6
+ import {
7
+ Redactor,
8
+ runCli,
9
+ terminalIo
10
+ } from "./chunk-G3ORKXVP.js";
11
+ import "./chunk-ZRWF6QZS.js";
12
+ import "./chunk-2ABSVMGB.js";
13
+ import "./chunk-6UWRT4VM.js";
14
+ import "./chunk-KGHA67HG.js";
15
+ import "./chunk-5KSXSK7Y.js";
16
+
17
+ // src/cli.ts
18
+ var redactor = new Redactor();
19
+ var code = await runCli(process.argv.slice(2), {
20
+ io: terminalIo(redactor),
21
+ redactor,
22
+ env: process.env,
23
+ ghVerifier: await ghAvailable() ? ghVerifier : null
24
+ });
25
+ process.exitCode = code;
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ IMPORT_LOOPBACK_REDIRECT,
4
+ chooseEnvironment,
5
+ create,
6
+ deploy,
7
+ edgeRuleStep,
8
+ fetchKit,
9
+ gatekeeperPlan,
10
+ generateClients,
11
+ hostBindingText,
12
+ hostRoutes,
13
+ init,
14
+ isClientRepo,
15
+ kitPacks,
16
+ loadClientProduct,
17
+ nativeRedirectUri,
18
+ nativeRedirectUris,
19
+ regenerate,
20
+ templateFiles,
21
+ typeErrors,
22
+ upgradeRepo,
23
+ withEnvBinding,
24
+ withTsExtensions
25
+ } from "./chunk-KOKYDJ7Z.js";
26
+ import "./chunk-G3ORKXVP.js";
27
+ import "./chunk-ZRWF6QZS.js";
28
+ import "./chunk-2ABSVMGB.js";
29
+ import "./chunk-6UWRT4VM.js";
30
+ import "./chunk-KGHA67HG.js";
31
+ import "./chunk-5KSXSK7Y.js";
32
+ export {
33
+ IMPORT_LOOPBACK_REDIRECT,
34
+ chooseEnvironment,
35
+ create,
36
+ deploy,
37
+ edgeRuleStep,
38
+ fetchKit,
39
+ gatekeeperPlan,
40
+ generateClients,
41
+ hostBindingText,
42
+ hostRoutes,
43
+ init,
44
+ isClientRepo,
45
+ kitPacks,
46
+ loadClientProduct,
47
+ nativeRedirectUri,
48
+ nativeRedirectUris,
49
+ regenerate,
50
+ templateFiles,
51
+ typeErrors,
52
+ upgradeRepo,
53
+ withEnvBinding,
54
+ withTsExtensions
55
+ };
package/dist/create.js ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ghAvailable,
4
+ ghVerifier
5
+ } from "./chunk-E5JLTLRM.js";
6
+ import {
7
+ Redactor,
8
+ runCli,
9
+ terminalIo
10
+ } from "./chunk-G3ORKXVP.js";
11
+ import "./chunk-ZRWF6QZS.js";
12
+ import "./chunk-2ABSVMGB.js";
13
+ import "./chunk-6UWRT4VM.js";
14
+ import "./chunk-KGHA67HG.js";
15
+ import "./chunk-5KSXSK7Y.js";
16
+
17
+ // src/create.ts
18
+ var redactor = new Redactor();
19
+ var code = await runCli(["create", ...process.argv.slice(2)], {
20
+ io: terminalIo(redactor),
21
+ redactor,
22
+ env: process.env,
23
+ ghVerifier: await ghAvailable() ? ghVerifier : null
24
+ });
25
+ process.exitCode = code;
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ BASE_OBJECTS,
4
+ BASE_TABLES,
5
+ CORE_OBJECTS,
6
+ ORDER_MACHINE,
7
+ ORDER_STATES,
8
+ activityObject,
9
+ defineObject,
10
+ getField,
11
+ getObject,
12
+ isCoreObject,
13
+ listObjects,
14
+ mediaObject,
15
+ orderLineObject,
16
+ orderObject,
17
+ organisationObject,
18
+ personObject,
19
+ setExtensionObjects,
20
+ taskObject,
21
+ timelineFields
22
+ } from "./chunk-2S7375SC.js";
23
+ import {
24
+ MEDIA_TYPES
25
+ } from "./chunk-X6I2LWB3.js";
26
+ import "./chunk-5KSXSK7Y.js";
27
+ export {
28
+ BASE_OBJECTS,
29
+ BASE_TABLES,
30
+ CORE_OBJECTS,
31
+ MEDIA_TYPES,
32
+ ORDER_MACHINE,
33
+ ORDER_STATES,
34
+ activityObject,
35
+ defineObject,
36
+ getField,
37
+ getObject,
38
+ isCoreObject,
39
+ listObjects,
40
+ mediaObject,
41
+ orderLineObject,
42
+ orderObject,
43
+ organisationObject,
44
+ personObject,
45
+ setExtensionObjects,
46
+ taskObject,
47
+ timelineFields
48
+ };
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ coreInvoker,
4
+ coreRegistry,
5
+ createInvoker,
6
+ invoke,
7
+ invokeByName,
8
+ listOperations
9
+ } from "./chunk-XDDBLYKW.js";
10
+ import "./chunk-LTQDLCP7.js";
11
+ import "./chunk-ZRWF6QZS.js";
12
+ import "./chunk-6UWRT4VM.js";
13
+ import "./chunk-MAXLUQKB.js";
14
+ import "./chunk-STJZJIRA.js";
15
+ import "./chunk-KGHA67HG.js";
16
+ import "./chunk-2S7375SC.js";
17
+ import "./chunk-X6I2LWB3.js";
18
+ import "./chunk-5KSXSK7Y.js";
19
+ export {
20
+ coreInvoker,
21
+ coreRegistry,
22
+ createInvoker,
23
+ invoke,
24
+ invokeByName,
25
+ listOperations
26
+ };
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ emailInputSchema,
4
+ loadPerson,
5
+ newPersonValue,
6
+ normalisePhoneNumber,
7
+ personChangeJob,
8
+ personCreate,
9
+ personDelete,
10
+ personDeleteMany,
11
+ personErase,
12
+ personGet,
13
+ personList,
14
+ personListItemSchema,
15
+ personMerge,
16
+ personOperations,
17
+ personRestore,
18
+ personSchema,
19
+ personSnapshot,
20
+ personUpdate,
21
+ personUpdateMany,
22
+ phoneInputSchema,
23
+ socialProfileSchema,
24
+ updatePerson
25
+ } from "./chunk-LTQDLCP7.js";
26
+ import "./chunk-6UWRT4VM.js";
27
+ import {
28
+ TRASH_RETENTION_DAYS
29
+ } from "./chunk-STJZJIRA.js";
30
+ import "./chunk-KGHA67HG.js";
31
+ import "./chunk-2S7375SC.js";
32
+ import "./chunk-X6I2LWB3.js";
33
+ import "./chunk-5KSXSK7Y.js";
34
+ export {
35
+ TRASH_RETENTION_DAYS,
36
+ emailInputSchema,
37
+ loadPerson,
38
+ newPersonValue,
39
+ normalisePhoneNumber,
40
+ personChangeJob,
41
+ personCreate,
42
+ personDelete,
43
+ personDeleteMany,
44
+ personErase,
45
+ personGet,
46
+ personList,
47
+ personListItemSchema,
48
+ personMerge,
49
+ personOperations,
50
+ personRestore,
51
+ personSchema,
52
+ personSnapshot,
53
+ personUpdate,
54
+ personUpdateMany,
55
+ phoneInputSchema,
56
+ socialProfileSchema,
57
+ updatePerson
58
+ };
@@ -0,0 +1,59 @@
1
+ -- Migration 0001: identity tables for the Better Auth adapter, plus core_meta.
2
+ -- Core tables are prefixed core_ (enforced by packages/db/test/core-prefix.test.ts).
3
+ -- Column names are snake_case; packages/auth maps Better Auth's camelCase fields onto them.
4
+
5
+ CREATE TABLE core_meta (
6
+ key TEXT PRIMARY KEY NOT NULL,
7
+ value TEXT NOT NULL
8
+ );
9
+
10
+ CREATE TABLE core_user (
11
+ id TEXT PRIMARY KEY NOT NULL,
12
+ name TEXT NOT NULL,
13
+ email TEXT NOT NULL UNIQUE,
14
+ email_verified INTEGER NOT NULL DEFAULT 0,
15
+ image TEXT,
16
+ created_at DATE NOT NULL,
17
+ updated_at DATE NOT NULL
18
+ );
19
+
20
+ CREATE TABLE core_session (
21
+ id TEXT PRIMARY KEY NOT NULL,
22
+ user_id TEXT NOT NULL REFERENCES core_user (id) ON DELETE CASCADE,
23
+ token TEXT NOT NULL UNIQUE,
24
+ expires_at DATE NOT NULL,
25
+ ip_address TEXT,
26
+ user_agent TEXT,
27
+ created_at DATE NOT NULL,
28
+ updated_at DATE NOT NULL
29
+ );
30
+ CREATE INDEX core_session_user_id_idx ON core_session (user_id);
31
+
32
+ CREATE TABLE core_account (
33
+ id TEXT PRIMARY KEY NOT NULL,
34
+ user_id TEXT NOT NULL REFERENCES core_user (id) ON DELETE CASCADE,
35
+ account_id TEXT NOT NULL,
36
+ provider_id TEXT NOT NULL,
37
+ access_token TEXT,
38
+ refresh_token TEXT,
39
+ id_token TEXT,
40
+ access_token_expires_at DATE,
41
+ refresh_token_expires_at DATE,
42
+ scope TEXT,
43
+ password TEXT,
44
+ created_at DATE NOT NULL,
45
+ updated_at DATE NOT NULL
46
+ );
47
+ CREATE INDEX core_account_user_id_idx ON core_account (user_id);
48
+
49
+ CREATE TABLE core_verification (
50
+ id TEXT PRIMARY KEY NOT NULL,
51
+ identifier TEXT NOT NULL,
52
+ value TEXT NOT NULL,
53
+ expires_at DATE NOT NULL,
54
+ created_at DATE NOT NULL,
55
+ updated_at DATE NOT NULL
56
+ );
57
+ CREATE INDEX core_verification_identifier_idx ON core_verification (identifier);
58
+
59
+ INSERT INTO core_meta (key, value) VALUES ('schema_version', '1');
@@ -0,0 +1,34 @@
1
+ -- Migration 0002: CRM roles on users, and org settings (ADR 0015, ADR 0011, ADR 0018).
2
+ --
3
+ -- Roles live on core_user, the table Better Auth already owns. Better Auth is not told about the
4
+ -- column, so its sign-up endpoints can never set it; the DEFAULT applies. The first user of a
5
+ -- deployment becomes admin through a trigger, which works for every identity adapter (Better Auth
6
+ -- sign-up, or a Cloudflare Access user provisioned on first request).
7
+
8
+ ALTER TABLE core_user ADD COLUMN role TEXT NOT NULL DEFAULT 'member'
9
+ CHECK (role IN ('admin', 'member', 'viewer'));
10
+
11
+ CREATE TRIGGER core_user_first_admin
12
+ AFTER INSERT ON core_user
13
+ WHEN (SELECT COUNT(*) FROM core_user) = 1
14
+ BEGIN
15
+ UPDATE core_user SET role = 'admin' WHERE id = NEW.id;
16
+ END;
17
+
18
+ -- Users who already exist when this migration runs: the earliest becomes admin.
19
+ UPDATE core_user SET role = 'admin'
20
+ WHERE id = (SELECT id FROM core_user ORDER BY created_at, id LIMIT 1);
21
+
22
+ -- Org-wide settings, one JSON value per key. Changed only through operations (e.g. policy.update),
23
+ -- which audit every change.
24
+ CREATE TABLE core_settings (
25
+ key TEXT PRIMARY KEY NOT NULL,
26
+ value TEXT NOT NULL CHECK (json_valid(value)),
27
+ updated_at TEXT NOT NULL,
28
+ updated_by TEXT REFERENCES core_user (id) ON DELETE SET NULL
29
+ );
30
+
31
+ INSERT INTO core_settings (key, value, updated_at)
32
+ VALUES ('approval_policy', '{"preset":"balanced"}', strftime('%Y-%m-%dT%H:%M:%fZ', 'now'));
33
+
34
+ UPDATE core_meta SET value = '2' WHERE key = 'schema_version';
@@ -0,0 +1,225 @@
1
+ -- Migration 0003: People, Organisations, Affiliations and Tags (ADR 0015, ADR 0018).
2
+ --
3
+ -- Conventions for every core record table from here on:
4
+ -- * id is a prefixed, time-sortable text id generated by @crm/core (per_, org_, aff_, ...).
5
+ -- * Timestamps are ISO-8601 UTC text (`2026-11-04T10:00:00.000Z`). Calendar dates are
6
+ -- `YYYY-MM-DD` text.
7
+ -- * Soft delete: `deleted_at` / `deleted_by`. Live rows have `deleted_at IS NULL`. Trash is the
8
+ -- set of soft-deleted rows; a scheduled purge hard-deletes them after 30 days.
9
+ -- * `merged_into_id` points a merged-away record at its survivor.
10
+ -- * Child rows (emails, phones, domains, addresses) are owned by their parent and replaced
11
+ -- wholesale by operations; they are hard-deleted with the parent on purge or erase.
12
+ -- * Uniqueness "across live records" uses a denormalised `live` flag on the child row, kept in
13
+ -- step with the parent's `deleted_at` by triggers, so a partial unique index can enforce it.
14
+ -- Restoring a parent whose email/domain has since been taken fails with a UNIQUE error.
15
+
16
+ -- People ---------------------------------------------------------------------------------------
17
+
18
+ CREATE TABLE core_person (
19
+ id TEXT PRIMARY KEY NOT NULL,
20
+ given_name TEXT,
21
+ family_name TEXT,
22
+ display_name TEXT NOT NULL,
23
+ location TEXT,
24
+ timezone TEXT,
25
+ -- JSON array of { network, url, handle? }.
26
+ social_profiles TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(social_profiles)),
27
+ -- R2 object key of the avatar image.
28
+ avatar_key TEXT,
29
+ owner_id TEXT REFERENCES core_user (id) ON DELETE SET NULL,
30
+ -- Rich text, stored as Markdown.
31
+ description TEXT,
32
+ created_at TEXT NOT NULL,
33
+ created_by TEXT REFERENCES core_user (id) ON DELETE SET NULL,
34
+ updated_at TEXT NOT NULL,
35
+ deleted_at TEXT,
36
+ deleted_by TEXT REFERENCES core_user (id) ON DELETE SET NULL,
37
+ merged_into_id TEXT REFERENCES core_person (id) ON DELETE SET NULL
38
+ );
39
+ CREATE INDEX core_person_display_name_idx ON core_person (display_name COLLATE NOCASE, id);
40
+ CREATE INDEX core_person_owner_idx ON core_person (owner_id);
41
+ CREATE INDEX core_person_deleted_idx ON core_person (deleted_at);
42
+
43
+ CREATE TABLE core_person_emails (
44
+ id TEXT PRIMARY KEY NOT NULL,
45
+ person_id TEXT NOT NULL REFERENCES core_person (id) ON DELETE CASCADE,
46
+ -- Stored lower-cased and trimmed by the operation layer.
47
+ email TEXT NOT NULL CHECK (email = lower(trim(email)) AND email <> ''),
48
+ label TEXT,
49
+ is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),
50
+ position INTEGER NOT NULL DEFAULT 0,
51
+ live INTEGER NOT NULL DEFAULT 1 CHECK (live IN (0, 1)),
52
+ created_at TEXT NOT NULL
53
+ );
54
+ CREATE INDEX core_person_emails_person_idx ON core_person_emails (person_id, position);
55
+ CREATE UNIQUE INDEX core_person_emails_live_email_uq ON core_person_emails (email) WHERE live = 1;
56
+ CREATE UNIQUE INDEX core_person_emails_primary_uq ON core_person_emails (person_id)
57
+ WHERE is_primary = 1;
58
+ CREATE UNIQUE INDEX core_person_emails_person_email_uq ON core_person_emails (person_id, email);
59
+
60
+ CREATE TABLE core_person_phones (
61
+ id TEXT PRIMARY KEY NOT NULL,
62
+ person_id TEXT NOT NULL REFERENCES core_person (id) ON DELETE CASCADE,
63
+ -- As entered; `number_normalised` holds digits and a leading + for matching.
64
+ number TEXT NOT NULL CHECK (number <> ''),
65
+ number_normalised TEXT NOT NULL,
66
+ label TEXT,
67
+ is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),
68
+ position INTEGER NOT NULL DEFAULT 0,
69
+ created_at TEXT NOT NULL
70
+ );
71
+ CREATE INDEX core_person_phones_person_idx ON core_person_phones (person_id, position);
72
+ CREATE INDEX core_person_phones_number_idx ON core_person_phones (number_normalised);
73
+ CREATE UNIQUE INDEX core_person_phones_primary_uq ON core_person_phones (person_id)
74
+ WHERE is_primary = 1;
75
+
76
+ CREATE TRIGGER core_person_emails_live_on_insert
77
+ AFTER INSERT ON core_person_emails
78
+ WHEN (SELECT deleted_at FROM core_person WHERE id = NEW.person_id) IS NOT NULL
79
+ BEGIN
80
+ UPDATE core_person_emails SET live = 0 WHERE id = NEW.id;
81
+ END;
82
+
83
+ CREATE TRIGGER core_person_emails_live_on_delete
84
+ AFTER UPDATE OF deleted_at ON core_person
85
+ WHEN (OLD.deleted_at IS NULL) <> (NEW.deleted_at IS NULL)
86
+ BEGIN
87
+ UPDATE core_person_emails SET live = (NEW.deleted_at IS NULL) WHERE person_id = NEW.id;
88
+ END;
89
+
90
+ -- Organisations --------------------------------------------------------------------------------
91
+
92
+ CREATE TABLE core_organisation (
93
+ id TEXT PRIMARY KEY NOT NULL,
94
+ name TEXT NOT NULL CHECK (name <> ''),
95
+ website TEXT,
96
+ industry TEXT,
97
+ parent_id TEXT REFERENCES core_organisation (id) ON DELETE SET NULL CHECK (parent_id <> id),
98
+ -- R2 object key of the logo.
99
+ avatar_key TEXT,
100
+ owner_id TEXT REFERENCES core_user (id) ON DELETE SET NULL,
101
+ -- Rich text, stored as Markdown.
102
+ description TEXT,
103
+ created_at TEXT NOT NULL,
104
+ created_by TEXT REFERENCES core_user (id) ON DELETE SET NULL,
105
+ updated_at TEXT NOT NULL,
106
+ deleted_at TEXT,
107
+ deleted_by TEXT REFERENCES core_user (id) ON DELETE SET NULL,
108
+ merged_into_id TEXT REFERENCES core_organisation (id) ON DELETE SET NULL
109
+ );
110
+ CREATE INDEX core_organisation_name_idx ON core_organisation (name COLLATE NOCASE, id);
111
+ CREATE INDEX core_organisation_parent_idx ON core_organisation (parent_id);
112
+ CREATE INDEX core_organisation_owner_idx ON core_organisation (owner_id);
113
+ CREATE INDEX core_organisation_deleted_idx ON core_organisation (deleted_at);
114
+
115
+ CREATE TABLE core_organisation_domains (
116
+ id TEXT PRIMARY KEY NOT NULL,
117
+ organisation_id TEXT NOT NULL REFERENCES core_organisation (id) ON DELETE CASCADE,
118
+ -- Bare host, lower-cased, no scheme or `www.` (normalised by the operation layer).
119
+ domain TEXT NOT NULL CHECK (domain = lower(trim(domain)) AND domain <> ''),
120
+ is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),
121
+ position INTEGER NOT NULL DEFAULT 0,
122
+ live INTEGER NOT NULL DEFAULT 1 CHECK (live IN (0, 1)),
123
+ created_at TEXT NOT NULL
124
+ );
125
+ CREATE INDEX core_organisation_domains_org_idx ON core_organisation_domains (organisation_id, position);
126
+ CREATE UNIQUE INDEX core_organisation_domains_live_domain_uq ON core_organisation_domains (domain)
127
+ WHERE live = 1;
128
+ CREATE UNIQUE INDEX core_organisation_domains_primary_uq ON core_organisation_domains (organisation_id)
129
+ WHERE is_primary = 1;
130
+ CREATE UNIQUE INDEX core_organisation_domains_org_domain_uq
131
+ ON core_organisation_domains (organisation_id, domain);
132
+
133
+ CREATE TRIGGER core_organisation_domains_live_on_insert
134
+ AFTER INSERT ON core_organisation_domains
135
+ WHEN (SELECT deleted_at FROM core_organisation WHERE id = NEW.organisation_id) IS NOT NULL
136
+ BEGIN
137
+ UPDATE core_organisation_domains SET live = 0 WHERE id = NEW.id;
138
+ END;
139
+
140
+ CREATE TRIGGER core_organisation_domains_live_on_delete
141
+ AFTER UPDATE OF deleted_at ON core_organisation
142
+ WHEN (OLD.deleted_at IS NULL) <> (NEW.deleted_at IS NULL)
143
+ BEGIN
144
+ UPDATE core_organisation_domains SET live = (NEW.deleted_at IS NULL)
145
+ WHERE organisation_id = NEW.id;
146
+ END;
147
+
148
+ CREATE TABLE core_organisation_addresses (
149
+ id TEXT PRIMARY KEY NOT NULL,
150
+ organisation_id TEXT NOT NULL REFERENCES core_organisation (id) ON DELETE CASCADE,
151
+ label TEXT,
152
+ line1 TEXT,
153
+ line2 TEXT,
154
+ city TEXT,
155
+ region TEXT,
156
+ postal_code TEXT,
157
+ -- ISO 3166-1 alpha-2 where known.
158
+ country TEXT,
159
+ is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),
160
+ position INTEGER NOT NULL DEFAULT 0,
161
+ created_at TEXT NOT NULL
162
+ );
163
+ CREATE INDEX core_organisation_addresses_org_idx ON core_organisation_addresses (organisation_id, position);
164
+ CREATE UNIQUE INDEX core_organisation_addresses_primary_uq ON core_organisation_addresses (organisation_id)
165
+ WHERE is_primary = 1;
166
+
167
+ -- Affiliations ---------------------------------------------------------------------------------
168
+ -- A Person's link to an Organisation. Ending one and starting another is a job change.
169
+
170
+ CREATE TABLE core_affiliation (
171
+ id TEXT PRIMARY KEY NOT NULL,
172
+ person_id TEXT NOT NULL REFERENCES core_person (id) ON DELETE CASCADE,
173
+ organisation_id TEXT NOT NULL REFERENCES core_organisation (id) ON DELETE CASCADE,
174
+ -- Job title, e.g. "Head of Sales".
175
+ title TEXT,
176
+ -- Free-text role in the relationship, e.g. "Decision maker".
177
+ role TEXT,
178
+ started_on TEXT,
179
+ ended_on TEXT,
180
+ is_current INTEGER NOT NULL DEFAULT 1 CHECK (is_current IN (0, 1)),
181
+ is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),
182
+ created_at TEXT NOT NULL,
183
+ created_by TEXT REFERENCES core_user (id) ON DELETE SET NULL,
184
+ updated_at TEXT NOT NULL,
185
+ deleted_at TEXT,
186
+ deleted_by TEXT REFERENCES core_user (id) ON DELETE SET NULL
187
+ );
188
+ CREATE INDEX core_affiliation_person_idx ON core_affiliation (person_id);
189
+ CREATE INDEX core_affiliation_org_idx ON core_affiliation (organisation_id);
190
+ CREATE UNIQUE INDEX core_affiliation_primary_uq ON core_affiliation (person_id)
191
+ WHERE is_primary = 1 AND deleted_at IS NULL;
192
+
193
+ -- Tags -----------------------------------------------------------------------------------------
194
+ -- One org-wide tag vocabulary, applied to any record through a polymorphic link (object type +
195
+ -- record id), so extension objects can be tagged later without schema changes.
196
+
197
+ CREATE TABLE core_tags (
198
+ id TEXT PRIMARY KEY NOT NULL,
199
+ name TEXT NOT NULL COLLATE NOCASE UNIQUE CHECK (name = trim(name) AND name <> ''),
200
+ color TEXT,
201
+ created_at TEXT NOT NULL,
202
+ created_by TEXT REFERENCES core_user (id) ON DELETE SET NULL
203
+ );
204
+
205
+ CREATE TABLE core_record_tags (
206
+ tag_id TEXT NOT NULL REFERENCES core_tags (id) ON DELETE CASCADE,
207
+ object_type TEXT NOT NULL,
208
+ record_id TEXT NOT NULL,
209
+ created_at TEXT NOT NULL,
210
+ PRIMARY KEY (object_type, record_id, tag_id)
211
+ );
212
+ CREATE INDEX core_record_tags_tag_idx ON core_record_tags (tag_id, object_type);
213
+
214
+ -- Hard-deleting a core record (purge or erase) removes its tag links.
215
+ CREATE TRIGGER core_person_purge_tags AFTER DELETE ON core_person
216
+ BEGIN
217
+ DELETE FROM core_record_tags WHERE object_type = 'person' AND record_id = OLD.id;
218
+ END;
219
+
220
+ CREATE TRIGGER core_organisation_purge_tags AFTER DELETE ON core_organisation
221
+ BEGIN
222
+ DELETE FROM core_record_tags WHERE object_type = 'organisation' AND record_id = OLD.id;
223
+ END;
224
+
225
+ UPDATE core_meta SET value = '3' WHERE key = 'schema_version';