@miniaxolotl/grove-server 1.11.21 → 1.11.24

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.
@@ -1 +1 @@
1
- {"enabled":true,"revision":"c8de270184490dbf7e94d067916da4590a632595","version":"1.11.21","component":"api"}
1
+ {"enabled":true,"revision":"9ee71cc987a443c020fbf6030f76664b4cc5e914","version":"1.11.24","component":"api"}
package/dist/worker.js CHANGED
@@ -18,7 +18,7 @@ var __export = (target2, all2) => {
18
18
  var define_GROVE_TELEMETRY_default;
19
19
  var init_define_GROVE_TELEMETRY = __esm({
20
20
  "<define:__GROVE_TELEMETRY__>"() {
21
- define_GROVE_TELEMETRY_default = { enabled: true, revision: "c8de270184490dbf7e94d067916da4590a632595", version: "1.11.21", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
21
+ define_GROVE_TELEMETRY_default = { enabled: true, revision: "9ee71cc987a443c020fbf6030f76664b4cc5e914", version: "1.11.24", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
22
22
  }
23
23
  });
24
24
 
@@ -203,7 +203,7 @@ var init_limits = __esm({
203
203
 
204
204
  // lib/shared/src/contracts.ts
205
205
  import { z as z7 } from "zod";
206
- var capabilities, capabilitySchema, uuidSchema, operationSchema, expectedVersionSchema, captureSchema, kindSchema, sourceSchema, rememberSchema, listSchema, recallSchema, versionSchema, forgetSchema, projectSchema, grantSchema, connectionSchema, connectionUpdateSchema, agentSchema, connectSchema, approveConnectSchema, memorySchema, GroveError;
206
+ var capabilities, capabilitySchema, uuidSchema, localDateSchema, operationSchema, expectedVersionSchema, captureSchema, kindSchema, sourceSchema, rememberSchema, listSchema, recallSchema, versionSchema, forgetSchema, projectSchema, grantSchema, connectionSchema, connectionUpdateSchema, agentSchema, connectSchema, approveConnectSchema, memorySchema, GroveError;
207
207
  var init_contracts = __esm({
208
208
  "lib/shared/src/contracts.ts"() {
209
209
  "use strict";
@@ -217,6 +217,7 @@ var init_contracts = __esm({
217
217
  ];
218
218
  capabilitySchema = z7.enum(capabilities);
219
219
  uuidSchema = z7.uuid();
220
+ localDateSchema = z7.iso.date().refine((date) => !date.startsWith("0000-"));
220
221
  operationSchema = z7.uuid().describe(
221
222
  "New UUID for this write. Reuse the same UUID and identical arguments when retrying; changed arguments require a new operation."
222
223
  );
@@ -2577,6 +2578,60 @@ import { Model, knexSnakeCaseMappers } from "objection";
2577
2578
  // lib/database/src/migrations.ts
2578
2579
  init_define_GROVE_TELEMETRY();
2579
2580
 
2581
+ // lib/database/src/daily-note-migration.ts
2582
+ init_define_GROVE_TELEMETRY();
2583
+ var dailyNotes = {
2584
+ name: "20261117_042_daily_notes",
2585
+ async up(db) {
2586
+ await db.raw(`
2587
+ CREATE TABLE daily_notes (
2588
+ account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
2589
+ local_date date NOT NULL,
2590
+ memory_id uuid,
2591
+ PRIMARY KEY (account_id, local_date),
2592
+ UNIQUE (account_id, memory_id),
2593
+ FOREIGN KEY (account_id, memory_id) REFERENCES memories(account_id,id)
2594
+ ON DELETE SET NULL (memory_id)
2595
+ );
2596
+ ALTER TABLE daily_notes ENABLE ROW LEVEL SECURITY;
2597
+ ALTER TABLE daily_notes FORCE ROW LEVEL SECURITY;
2598
+ CREATE POLICY daily_notes_tenant ON daily_notes
2599
+ USING (account_id=nullif(current_setting('grove.account_id',true),'')::uuid);
2600
+ GRANT SELECT, INSERT ON daily_notes TO grove_runtime;
2601
+ GRANT SELECT, DELETE ON daily_notes TO grove_worker;
2602
+ `);
2603
+ },
2604
+ async down() {
2605
+ throw new Error("Use a forward migration; retain daily note identities");
2606
+ }
2607
+ };
2608
+
2609
+ // lib/database/src/cache-retention-migration.ts
2610
+ init_define_GROVE_TELEMETRY();
2611
+ var cacheRetention = {
2612
+ name: "20261118_043_cache_retention",
2613
+ async up(db) {
2614
+ const { rows } = await db.raw(
2615
+ "SELECT pg_get_functiondef('grove_schedule_cleanup()'::regprocedure) AS definition"
2616
+ );
2617
+ const definition2 = rows[0].definition;
2618
+ const anchor = "OR EXISTS(SELECT 1 FROM rate_buckets r";
2619
+ if (definition2.split(anchor).length !== 2)
2620
+ throw new Error("Unsupported retention scheduler baseline");
2621
+ await db.raw(
2622
+ definition2.replace(
2623
+ anchor,
2624
+ `OR EXISTS(SELECT 1 FROM ai_cache c WHERE c.account_id=a.id AND c.expires_at<=now())
2625
+ OR EXISTS(SELECT 1 FROM ai_provider_backoff b WHERE b.account_id=a.id AND b.retry_at<now()-interval '1 day')
2626
+ ${anchor}`
2627
+ )
2628
+ );
2629
+ },
2630
+ async down() {
2631
+ throw new Error("Use a forward migration");
2632
+ }
2633
+ };
2634
+
2580
2635
  // lib/database/src/writing-allowance-migration.ts
2581
2636
  init_define_GROVE_TELEMETRY();
2582
2637
  var writingAllowance = {
@@ -6316,7 +6371,9 @@ var migrations = [
6316
6371
  writingTools,
6317
6372
  nativeSharing,
6318
6373
  billingTrial,
6319
- writingAllowance
6374
+ writingAllowance,
6375
+ dailyNotes,
6376
+ cacheRetention
6320
6377
  ];
6321
6378
  var migrationSource = {
6322
6379
  getMigrations: async () => migrations,
@@ -6436,6 +6493,9 @@ async function probeDatabase(db) {
6436
6493
  );
6437
6494
  await db.raw("SELECT policy, version FROM writing_consents LIMIT 0");
6438
6495
  await db.raw("SELECT connection_id FROM writing_cancellations LIMIT 0");
6496
+ await db.raw(
6497
+ "SELECT account_id, local_date, memory_id FROM daily_notes LIMIT 0"
6498
+ );
6439
6499
  }
6440
6500
  var MemoryModel = class extends Model {
6441
6501
  static tableName = "memories";
@@ -21888,14 +21948,16 @@ async function owned2(trx, id2) {
21888
21948
  return row;
21889
21949
  }
21890
21950
  async function expireDocumentDrafts(trx) {
21891
- const expired = trx("document_import_batches").select("id").where("expiresAt", "<=", trx.fn.now()).where({ draftsCleared: false }).whereIn("status", ["uploading", "preparing", "ready", "cancelled"]).orderBy("id").limit(20);
21951
+ const limit = 20;
21952
+ const expired = trx("document_import_batches").select("id").where("expiresAt", "<=", trx.fn.now()).where({ draftsCleared: false }).whereIn("status", ["uploading", "preparing", "ready", "cancelled"]).orderBy("id").limit(limit);
21892
21953
  await trx("document_import_files").whereIn("batchId", expired).where({ originalReady: false }).whereNotNull("staging").update({ staging: null });
21893
21954
  await trx("document_import_notes").whereIn("batchId", expired).whereNull("memoryId").whereNot("content", "[Expired import draft]").update({
21894
21955
  content: "[Expired import draft]",
21895
21956
  included: false,
21896
21957
  suggestion: null
21897
21958
  });
21898
- await trx("document_import_batches").whereIn("id", expired).update({ draftsCleared: true });
21959
+ const processed = await trx("document_import_batches").whereIn("id", expired).update({ draftsCleared: true });
21960
+ return { processed, fullPage: processed === limit };
21899
21961
  }
21900
21962
  function documentImportHandlers(service, extract, store) {
21901
21963
  const document_prepare = async (task, signal) => {
@@ -22096,8 +22158,9 @@ var available = (q) => q.whereNull("removedAt").where(
22096
22158
  (sub) => sub.where("accepted", true).orWhere("expiresAt", ">", q.client.raw("now()"))
22097
22159
  );
22098
22160
  async function expireConversationDocuments(trx) {
22099
- const docs = await trx("conversation_documents").where({ accepted: false }).whereNull("removedAt").where("expiresAt", "<=", trx.fn.now()).orderBy("id").limit(25).select("id", "conversationId");
22100
- if (!docs.length) return;
22161
+ const limit = 25;
22162
+ const docs = await trx("conversation_documents").where({ accepted: false }).whereNull("removedAt").where("expiresAt", "<=", trx.fn.now()).orderBy("id").limit(limit).select("id", "conversationId");
22163
+ if (!docs.length) return { processed: 0, fullPage: false };
22101
22164
  await trx("conversation_document_chunks").whereIn(
22102
22165
  "documentId",
22103
22166
  docs.map((d) => d.id)
@@ -22115,6 +22178,7 @@ async function expireConversationDocuments(trx) {
22115
22178
  "id",
22116
22179
  docs.map((d) => d.conversationId)
22117
22180
  ).increment("documentsVersion", 1);
22181
+ return { processed: docs.length, fullPage: docs.length === limit };
22118
22182
  }
22119
22183
  async function documentSnapshot(trx, conversationId, query) {
22120
22184
  const chat = await documentChat(trx, conversationId);
@@ -25466,9 +25530,14 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
25466
25530
  if (table) {
25467
25531
  await taskTransaction(db, task, async (trx) => {
25468
25532
  signal.throwIfAborted();
25469
- const rows = await trx(table).select(trx.raw("ctid::text AS row_id")).limit(batchSize);
25470
- if (rows.length)
25471
- await trx(table).whereRaw("ctid=ANY(?::tid[])", [rows.map((row) => row.rowId)]).delete();
25533
+ const deleteBatch = async (target2) => {
25534
+ const rows = await trx(target2).select(trx.raw("ctid::text AS row_id")).limit(batchSize);
25535
+ if (rows.length)
25536
+ await trx(target2).whereRaw("ctid=ANY(?::tid[])", [rows.map((row) => row.rowId)]).delete();
25537
+ return rows.length;
25538
+ };
25539
+ const count2 = await deleteBatch(table);
25540
+ const daily = table === "notebook_expiries" ? await deleteBatch("daily_notes") : 0;
25472
25541
  const research = table === "inference_usage" ? await trx("research_account_usage").select("day").limit(batchSize) : [];
25473
25542
  if (research.length)
25474
25543
  await trx("research_account_usage").whereIn(
@@ -25478,9 +25547,9 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
25478
25547
  const cache = table === "memory_briefs" ? await pruneCache(trx, false) : 0;
25479
25548
  return {
25480
25549
  cursor: {
25481
- stage: rows.length === batchSize || research.length === batchSize || cache === batchSize ? stage : stage + 1
25550
+ stage: count2 === batchSize || daily === batchSize || research.length === batchSize || cache === batchSize ? stage : stage + 1
25482
25551
  },
25483
- processed: Number(task.processed) + rows.length + research.length + cache
25552
+ processed: Number(task.processed) + count2 + daily + research.length + cache
25484
25553
  };
25485
25554
  });
25486
25555
  return;
@@ -25510,8 +25579,8 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
25510
25579
  const retention_cleanup = async (task, signal) => {
25511
25580
  await taskTransaction(db, task, async (trx) => {
25512
25581
  signal.throwIfAborted();
25513
- await expireDocumentDrafts(trx);
25514
- await expireConversationDocuments(trx);
25582
+ const drafts = await expireDocumentDrafts(trx);
25583
+ const uploads = await expireConversationDocuments(trx);
25515
25584
  const writingExpired = await expireWriting(trx);
25516
25585
  const expired = await trx("memories").where("purgeAt", "<=", trx.fn.now()).select("id").orderBy("id").limit(batchSize);
25517
25586
  if (expired.length) {
@@ -25527,8 +25596,8 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
25527
25596
  await trx("rate_buckets").whereIn("minute", buckets).delete();
25528
25597
  const cache = await pruneCache(trx, true);
25529
25598
  return {
25530
- processed: Number(task.processed) + expired.length + cache + writingExpired,
25531
- complete: expired.length < batchSize && buckets.length < batchSize && writingExpired < batchSize && cache < batchSize
25599
+ processed: Number(task.processed) + expired.length + cache + writingExpired + drafts.processed + uploads.processed,
25600
+ complete: !drafts.fullPage && !uploads.fullPage && expired.length < batchSize && buckets.length < batchSize && writingExpired < batchSize && cache < batchSize
25532
25601
  };
25533
25602
  });
25534
25603
  };
@@ -26960,6 +27029,34 @@ var MemoryService = class _MemoryService {
26960
27029
  async remember(principal, input) {
26961
27030
  return this.saveMemory(principal, input, false);
26962
27031
  }
27032
+ async dailyNoteFor(trx, accountId, localDate) {
27033
+ const row = await trx("daily_notes as daily").leftJoin("memories as note", function() {
27034
+ this.on("note.account_id", "daily.account_id").andOn(
27035
+ "note.id",
27036
+ "daily.memory_id"
27037
+ );
27038
+ }).where({ "daily.account_id": accountId, "daily.local_date": localDate }).first("note.id");
27039
+ return !row ? { state: "empty" } : row.id ? { state: "saved", id: row.id } : { state: "deleted" };
27040
+ }
27041
+ async dailyNote(principal, date) {
27042
+ if (principal.type !== "session") throw forbidden();
27043
+ const localDate = localDateSchema.parse(date);
27044
+ return this.access(
27045
+ principal,
27046
+ "memory:read",
27047
+ ({ trx, account }) => this.dailyNoteFor(trx, account.id, localDate)
27048
+ );
27049
+ }
27050
+ async createDailyNote(principal, date, input) {
27051
+ if (principal.type !== "session") throw forbidden();
27052
+ const localDate = localDateSchema.parse(date);
27053
+ if (input.id || input.expectedVersion || input.archived || input.capture !== "explicit")
27054
+ throw new GroveError(
27055
+ "invalid_request",
27056
+ "A daily note must start with a new, active note"
27057
+ );
27058
+ return this.saveMemory(principal, input, false, localDate);
27059
+ }
26963
27060
  async captureWeb(principal, raw) {
26964
27061
  const input = browserCaptureRequestSchema.parse(raw);
26965
27062
  return this.access(
@@ -27228,7 +27325,7 @@ var MemoryService = class _MemoryService {
27228
27325
  return this.inTransaction(trx).updateMemory(principal, input);
27229
27326
  });
27230
27327
  }
27231
- async saveMemory(principal, request2, partial) {
27328
+ async saveMemory(principal, request2, partial, localDate) {
27232
27329
  let created = false;
27233
27330
  const result = await this.access(
27234
27331
  principal,
@@ -27244,8 +27341,23 @@ var MemoryService = class _MemoryService {
27244
27341
  trx,
27245
27342
  account.id,
27246
27343
  request2.operationId,
27247
- { action: partial ? "update_memory" : "remember", ...request2 },
27344
+ localDate ? { action: "create_daily_note", localDate, ...request2 } : { action: partial ? "update_memory" : "remember", ...request2 },
27248
27345
  async () => {
27346
+ if (localDate) {
27347
+ const daily = await this.dailyNoteFor(trx, account.id, localDate);
27348
+ if (daily.state === "saved")
27349
+ throw new GroveError(
27350
+ "daily_note_exists",
27351
+ "A daily note was already saved for this date. Copy any draft text you want to keep.",
27352
+ 409
27353
+ );
27354
+ if (daily.state === "deleted")
27355
+ throw new GroveError(
27356
+ "daily_note_deleted",
27357
+ "The daily note for this date was deleted. Your draft was not saved.",
27358
+ 410
27359
+ );
27360
+ }
27249
27361
  let old;
27250
27362
  if (request2.id) {
27251
27363
  old = await this.query(trx, grant).findById(request2.id).forUpdate();
@@ -27355,6 +27467,12 @@ var MemoryService = class _MemoryService {
27355
27467
  id: randomUUID13(),
27356
27468
  status: input.archived ? "archived" : "active"
27357
27469
  });
27470
+ if (localDate)
27471
+ await trx("daily_notes").insert({
27472
+ accountId: account.id,
27473
+ localDate,
27474
+ memoryId: row2.id
27475
+ });
27358
27476
  const session = editSession ?? principal.sessionId;
27359
27477
  await this.revise(
27360
27478
  trx,