@miniaxolotl/grove-server 1.11.15 → 1.11.20

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/bootstrap.js CHANGED
@@ -4,6 +4,21 @@ import { createRequire as __groveCreateRequire } from "node:module"; const requi
4
4
  import knex from "knex";
5
5
  import { Model, knexSnakeCaseMappers } from "objection";
6
6
 
7
+ // lib/database/src/writing-allowance-migration.ts
8
+ var writingAllowance = {
9
+ name: "20261107_041_writing_allowance",
10
+ async up(db2) {
11
+ await db2.raw(`
12
+ ALTER TABLE action_usage DROP CONSTRAINT action_usage_metric_check;
13
+ ALTER TABLE action_usage ADD CONSTRAINT action_usage_metric_check
14
+ CHECK(metric IN ('recall','ask','organization','assistance','writing'));
15
+ `);
16
+ },
17
+ async down() {
18
+ throw new Error("Use a forward migration");
19
+ }
20
+ };
21
+
7
22
  // lib/database/src/structured-document-migration.ts
8
23
  var structuredDocuments = {
9
24
  name: "20261105_036_structured_documents",
@@ -76,6 +91,229 @@ var browserCapture = {
76
91
  }
77
92
  };
78
93
 
94
+ // lib/database/src/writing-migration.ts
95
+ async function extendClaim(db2, signature, edits) {
96
+ const { rows } = await db2.raw(
97
+ "SELECT pg_get_functiondef(?::regprocedure) AS definition",
98
+ [signature]
99
+ );
100
+ let definition = rows[0].definition;
101
+ for (const [before, after] of edits) {
102
+ if (definition.split(before).length !== 2)
103
+ throw new Error("Unsupported queue claim baseline for writing migration");
104
+ definition = definition.replace(before, after);
105
+ }
106
+ await db2.raw(definition);
107
+ }
108
+ var writingTools = {
109
+ name: "20261106_038_writing_tools",
110
+ async up(db2) {
111
+ await db2.raw(`
112
+ ALTER TABLE connections ADD COLUMN writing_enabled boolean NOT NULL DEFAULT false;
113
+ ALTER TABLE accounts ADD COLUMN sentence_rewrites_enabled boolean NOT NULL DEFAULT true;
114
+ ALTER TABLE background_tasks DROP CONSTRAINT background_tasks_kind_check;
115
+ ALTER TABLE background_tasks ADD CONSTRAINT background_tasks_kind_check CHECK(kind IN
116
+ ('export','account_cleanup','retention_cleanup','artifact_cleanup','model_backfill','import','connector_sync',
117
+ 'document_prepare','document_import','conversation_document','speech_transcribe','speech_synthesize','sentence_rewrite'));
118
+ ALTER TABLE background_tasks ALTER COLUMN lane SET EXPRESSION AS
119
+ (CASE WHEN kind='sentence_rewrite' THEN 'enrichment'
120
+ WHEN kind IN ('account_cleanup','retention_cleanup','artifact_cleanup') THEN 'maintenance' ELSE 'bulk' END);
121
+ CREATE TABLE writing_consents (
122
+ account_id uuid NOT NULL, connection_id uuid NOT NULL, version integer NOT NULL DEFAULT 1,
123
+ policy text NOT NULL, profile text NOT NULL, accepted boolean NOT NULL DEFAULT false,
124
+ PRIMARY KEY(account_id,connection_id),
125
+ FOREIGN KEY(account_id,connection_id) REFERENCES connections(account_id,id) ON DELETE CASCADE
126
+ );
127
+ CREATE TABLE writing_requests (
128
+ account_id uuid NOT NULL, id uuid NOT NULL, connection_id uuid NOT NULL, session_id uuid NOT NULL,
129
+ tool text NOT NULL CHECK(tool IN ('concise','verbose','rewrite','humanize','synonyms','antonyms')),
130
+ fingerprint text NOT NULL, profile text NOT NULL, consent_version integer NOT NULL, epoch bigint NOT NULL,
131
+ input_ciphertext text, result_ciphertext text,
132
+ status text NOT NULL DEFAULT 'queued' CHECK(status IN
133
+ ('queued','processing','backoff','uncertain','completed','failed','cancelled','expired')),
134
+ provider_started_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(),
135
+ expires_at timestamptz NOT NULL DEFAULT now()+interval '15 minutes',
136
+ PRIMARY KEY(account_id,id),
137
+ FOREIGN KEY(account_id,connection_id) REFERENCES connections(account_id,id) ON DELETE CASCADE
138
+ );
139
+ CREATE TABLE writing_cancellations (
140
+ account_id uuid NOT NULL, id uuid NOT NULL, connection_id uuid NOT NULL,
141
+ created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id,id),
142
+ FOREIGN KEY(account_id,connection_id) REFERENCES connections(account_id,id) ON DELETE CASCADE
143
+ );
144
+ CREATE INDEX writing_requests_expiry ON writing_requests(account_id,expires_at,id)
145
+ WHERE input_ciphertext IS NOT NULL OR result_ciphertext IS NOT NULL;
146
+ `);
147
+ for (const table of [
148
+ "writing_consents",
149
+ "writing_requests",
150
+ "writing_cancellations"
151
+ ]) {
152
+ await db2.raw("ALTER TABLE ?? ENABLE ROW LEVEL SECURITY", [table]);
153
+ await db2.raw("ALTER TABLE ?? FORCE ROW LEVEL SECURITY", [table]);
154
+ await db2.raw(
155
+ `CREATE POLICY tenant ON ?? USING (account_id=NULLIF(current_setting('grove.account_id',true),'')::uuid)
156
+ WITH CHECK(account_id=NULLIF(current_setting('grove.account_id',true),'')::uuid)`,
157
+ [table]
158
+ );
159
+ await db2.raw(
160
+ "GRANT SELECT,INSERT,UPDATE,DELETE ON ?? TO grove_runtime,grove_worker",
161
+ [table]
162
+ );
163
+ }
164
+ await db2.raw(`
165
+ CREATE FUNCTION grove_fence_writing() RETURNS trigger LANGUAGE plpgsql
166
+ SET search_path=pg_catalog,public,pg_temp AS $$
167
+ DECLARE aid uuid; cid uuid;
168
+ BEGIN
169
+ IF TG_TABLE_NAME='connections' THEN
170
+ IF NEW.writing_enabled IS NOT DISTINCT FROM OLD.writing_enabled AND NEW.revoked_at IS NOT DISTINCT FROM OLD.revoked_at
171
+ AND NEW.authorized_after IS NOT DISTINCT FROM OLD.authorized_after THEN RETURN NEW; END IF;
172
+ aid:=NEW.account_id; cid:=NEW.id;
173
+ ELSE
174
+ IF NEW.status IS NOT DISTINCT FROM OLD.status AND NEW.sentence_rewrites_enabled IS NOT DISTINCT FROM OLD.sentence_rewrites_enabled THEN RETURN NEW; END IF;
175
+ aid:=NEW.id;
176
+ END IF;
177
+ UPDATE writing_consents SET accepted=false,version=version+1 WHERE account_id=aid AND (cid IS NULL OR connection_id=cid);
178
+ UPDATE writing_requests SET status=CASE WHEN provider_started_at IS NOT NULL AND status='processing' THEN 'uncertain' ELSE 'cancelled' END,
179
+ input_ciphertext=NULL,result_ciphertext=NULL WHERE account_id=aid AND (cid IS NULL OR connection_id=cid);
180
+ UPDATE background_tasks SET status='cancelled',lease_id=NULL,lease_until=NULL,result=NULL,updated_at=now()
181
+ WHERE account_id=aid AND kind='sentence_rewrite'
182
+ AND id IN (SELECT id FROM writing_requests WHERE account_id=aid AND (cid IS NULL OR connection_id=cid));
183
+ UPDATE action_usage SET status=CASE WHEN worked THEN 'completed' ELSE 'released' END,updated_at=now()
184
+ WHERE account_id=aid AND metric='assistance' AND status='reserved'
185
+ AND operation IN (SELECT 'writing:'||id::text FROM writing_requests WHERE account_id=aid AND (cid IS NULL OR connection_id=cid));
186
+ RETURN NEW;
187
+ END $$;
188
+ REVOKE ALL ON FUNCTION grove_fence_writing() FROM PUBLIC;
189
+ CREATE TRIGGER writing_connection_changed AFTER UPDATE OF writing_enabled,revoked_at,authorized_after
190
+ ON connections FOR EACH ROW EXECUTE FUNCTION grove_fence_writing();
191
+ CREATE TRIGGER writing_account_changed AFTER UPDATE OF status,sentence_rewrites_enabled
192
+ ON accounts FOR EACH ROW EXECUTE FUNCTION grove_fence_writing();
193
+ `);
194
+ await extendClaim(
195
+ db2,
196
+ "grove_claim_processing(text[],uuid,text,integer,integer)",
197
+ [
198
+ [
199
+ "(SELECT count(*) FROM jobs busy WHERE busy.account_id=j.account_id AND busy.lane=j.lane AND busy.lease_until>now())",
200
+ "((SELECT count(*) FROM jobs busy WHERE busy.account_id=j.account_id AND busy.lane=j.lane AND busy.lease_until>now()) + (SELECT count(*) FROM background_tasks t WHERE t.account_id=j.account_id AND t.lane=j.lane AND t.status='running' AND t.lease_until>now()))"
201
+ ],
202
+ [
203
+ "(SELECT count(*) FROM jobs WHERE lane=selected_lane AND lease_until>now())",
204
+ "((SELECT count(*) FROM jobs WHERE lane=selected_lane AND lease_until>now()) + (SELECT count(*) FROM background_tasks WHERE lane=selected_lane AND status='running' AND lease_until>now()))"
205
+ ],
206
+ [
207
+ "(SELECT count(*) FROM jobs WHERE account_id=owner_id AND lane=selected_lane AND lease_until>now())",
208
+ "((SELECT count(*) FROM jobs WHERE account_id=owner_id AND lane=selected_lane AND lease_until>now()) + (SELECT count(*) FROM background_tasks WHERE account_id=owner_id AND lane=selected_lane AND status='running' AND lease_until>now()))"
209
+ ]
210
+ ]
211
+ );
212
+ await extendClaim(db2, "grove_claim_task(uuid,text,integer)", [
213
+ [
214
+ "PERFORM 1 FROM background_tasks t WHERE t.id=selected",
215
+ `IF selected_lane='enrichment' THEN
216
+ IF NOT pg_try_advisory_xact_lock(hashtextextended(selected_lane,68142020)) THEN CONTINUE; END IF;
217
+ IF ((SELECT count(*) FROM jobs WHERE lane=selected_lane AND lease_until>now()) +
218
+ (SELECT count(*) FROM background_tasks WHERE lane=selected_lane AND status='running' AND lease_until>now()))
219
+ >= greatest(1,least(COALESCE(NULLIF(current_setting('grove.provider_limit',true),''),'8')::integer,128)) THEN RETURN; END IF;
220
+ IF ((SELECT count(*) FROM jobs WHERE account_id=owner_id AND lane=selected_lane AND lease_until>now()) +
221
+ (SELECT count(*) FROM background_tasks WHERE account_id=owner_id AND lane=selected_lane AND status='running' AND lease_until>now()))
222
+ >= greatest(1,least(account_limit,32)) THEN CONTINUE; END IF;
223
+ END IF;
224
+ PERFORM 1 FROM background_tasks t WHERE t.id=selected`
225
+ ]
226
+ ]);
227
+ await extendClaim(db2, "grove_schedule_cleanup()", [
228
+ [
229
+ "OR EXISTS(SELECT 1 FROM document_import_batches b",
230
+ "OR EXISTS(SELECT 1 FROM writing_requests w WHERE w.account_id=a.id AND w.expires_at<=now() AND (w.input_ciphertext IS NOT NULL OR w.result_ciphertext IS NOT NULL)) OR EXISTS(SELECT 1 FROM document_import_batches b"
231
+ ]
232
+ ]);
233
+ },
234
+ async down() {
235
+ throw new Error("Use a forward migration");
236
+ }
237
+ };
238
+
239
+ // lib/database/src/native-sharing-migration.ts
240
+ var nativeSharing = {
241
+ name: "20261106_039_native_note_sharing",
242
+ async up(db2) {
243
+ await db2.raw(
244
+ "ALTER TABLE connections ADD COLUMN sharing_enabled boolean NOT NULL DEFAULT false"
245
+ );
246
+ },
247
+ async down() {
248
+ throw new Error("Use a forward migration");
249
+ }
250
+ };
251
+
252
+ // lib/database/src/trial-migration.ts
253
+ var billingTrial = {
254
+ name: "20261107_040_billing_trial",
255
+ async up(db2) {
256
+ await db2.raw(`
257
+ CREATE TABLE billing_trials (
258
+ account_id uuid PRIMARY KEY REFERENCES accounts(id),
259
+ consumed_at timestamptz NOT NULL DEFAULT now(),
260
+ subscription_id text,
261
+ reset_by uuid REFERENCES accounts(id),
262
+ reset_at timestamptz
263
+ );
264
+ `);
265
+ await db2.raw(
266
+ "ALTER TABLE billing_trials ENABLE ROW LEVEL SECURITY"
267
+ );
268
+ await db2.raw("ALTER TABLE billing_trials FORCE ROW LEVEL SECURITY");
269
+ await db2.raw(
270
+ `CREATE POLICY tenant ON billing_trials USING (account_id = NULLIF(current_setting('grove.account_id',true),'')::uuid) WITH CHECK (account_id = NULLIF(current_setting('grove.account_id',true),'')::uuid)`
271
+ );
272
+ await db2.raw("GRANT SELECT, INSERT, UPDATE ON billing_trials TO grove_runtime");
273
+ await db2.raw("GRANT SELECT ON billing_trials TO grove_worker");
274
+ await db2.raw(`
275
+ CREATE FUNCTION grove_admin_trial_reset(target uuid, operation uuid, explanation text) RETURNS jsonb
276
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
277
+ DECLARE actor uuid; previous public.system_admin_audit; original text; deleted integer;
278
+ BEGIN
279
+ actor := public.grove_admin_guard();
280
+ IF target IS NULL OR operation IS NULL OR explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300 THEN
281
+ RAISE EXCEPTION 'invalid_request' USING ERRCODE='GA002';
282
+ END IF;
283
+ SELECT * INTO previous FROM public.system_admin_audit WHERE id=operation;
284
+ IF FOUND THEN
285
+ IF previous.kind<>'change' OR previous.actor_id IS DISTINCT FROM actor OR previous.account_id IS DISTINCT FROM target
286
+ OR previous.reason IS DISTINCT FROM explanation THEN
287
+ RAISE EXCEPTION 'operation_conflict' USING ERRCODE='GA003';
288
+ END IF;
289
+ RETURN previous.after;
290
+ END IF;
291
+ original := current_setting('grove.account_id',true);
292
+ PERFORM set_config('grove.account_id',target::text,true);
293
+ DELETE FROM public.billing_trials WHERE account_id=target;
294
+ GET DIAGNOSTICS deleted = ROW_COUNT;
295
+ PERFORM set_config('grove.account_id',COALESCE(original,''),true);
296
+ IF deleted = 0 THEN
297
+ RAISE EXCEPTION 'trial_not_consumed' USING ERRCODE='GA007';
298
+ END IF;
299
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
300
+ VALUES(operation,actor,target,'change',explanation,
301
+ jsonb_build_object('trialEligible',false),
302
+ jsonb_build_object('trialEligible',true));
303
+ RETURN jsonb_build_object('accountId',target,'eligible',true);
304
+ EXCEPTION WHEN OTHERS THEN
305
+ IF original IS NOT NULL THEN PERFORM set_config('grove.account_id',original,true); END IF;
306
+ RAISE;
307
+ END $$;
308
+ REVOKE ALL ON FUNCTION grove_admin_trial_reset(uuid,uuid,text) FROM PUBLIC,grove_runtime,grove_worker;
309
+ GRANT EXECUTE ON FUNCTION grove_admin_trial_reset(uuid,uuid,text) TO grove_runtime;
310
+ `);
311
+ },
312
+ async down() {
313
+ throw new Error("Use a forward migration");
314
+ }
315
+ };
316
+
79
317
  // lib/database/src/action-usage-migration.ts
80
318
  var actionUsage = {
81
319
  name: "20261025_028_action_usage",
@@ -3457,7 +3695,11 @@ var migrations = [
3457
3695
  adminUsageReports,
3458
3696
  notebookOrder,
3459
3697
  structuredDocuments,
3460
- browserCapture
3698
+ browserCapture,
3699
+ writingTools,
3700
+ nativeSharing,
3701
+ billingTrial,
3702
+ writingAllowance
3461
3703
  ];
3462
3704
  var migrationSource = {
3463
3705
  getMigrations: async () => migrations,