@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.
package/dist/server.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 z6 } from "zod";
206
- var capabilities, capabilitySchema, oauthScopes, uuidSchema, operationSchema, expectedVersionSchema, captureSchema, kindSchema, sourceSchema, rememberSchema, listSchema, recallSchema, versionSchema, forgetSchema, projectSchema, grantSchema, connectionSchema, connectionUpdateSchema, agentSchema, agentNames, connectSchema, approveConnectSchema, memorySchema, GroveError;
206
+ var capabilities, capabilitySchema, oauthScopes, uuidSchema, localDateSchema, operationSchema, expectedVersionSchema, captureSchema, kindSchema, sourceSchema, rememberSchema, listSchema, recallSchema, versionSchema, forgetSchema, projectSchema, grantSchema, connectionSchema, connectionUpdateSchema, agentSchema, agentNames, connectSchema, approveConnectSchema, memorySchema, GroveError;
207
207
  var init_contracts = __esm({
208
208
  "lib/shared/src/contracts.ts"() {
209
209
  "use strict";
@@ -218,6 +218,7 @@ var init_contracts = __esm({
218
218
  capabilitySchema = z6.enum(capabilities);
219
219
  oauthScopes = ["openid", "offline_access"];
220
220
  uuidSchema = z6.uuid();
221
+ localDateSchema = z6.iso.date().refine((date) => !date.startsWith("0000-"));
221
222
  operationSchema = z6.uuid().describe(
222
223
  "New UUID for this write. Reuse the same UUID and identical arguments when retrying; changed arguments require a new operation."
223
224
  );
@@ -2592,6 +2593,60 @@ import { Model, knexSnakeCaseMappers } from "objection";
2592
2593
  // lib/database/src/migrations.ts
2593
2594
  init_define_GROVE_TELEMETRY();
2594
2595
 
2596
+ // lib/database/src/daily-note-migration.ts
2597
+ init_define_GROVE_TELEMETRY();
2598
+ var dailyNotes = {
2599
+ name: "20261117_042_daily_notes",
2600
+ async up(db) {
2601
+ await db.raw(`
2602
+ CREATE TABLE daily_notes (
2603
+ account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
2604
+ local_date date NOT NULL,
2605
+ memory_id uuid,
2606
+ PRIMARY KEY (account_id, local_date),
2607
+ UNIQUE (account_id, memory_id),
2608
+ FOREIGN KEY (account_id, memory_id) REFERENCES memories(account_id,id)
2609
+ ON DELETE SET NULL (memory_id)
2610
+ );
2611
+ ALTER TABLE daily_notes ENABLE ROW LEVEL SECURITY;
2612
+ ALTER TABLE daily_notes FORCE ROW LEVEL SECURITY;
2613
+ CREATE POLICY daily_notes_tenant ON daily_notes
2614
+ USING (account_id=nullif(current_setting('grove.account_id',true),'')::uuid);
2615
+ GRANT SELECT, INSERT ON daily_notes TO grove_runtime;
2616
+ GRANT SELECT, DELETE ON daily_notes TO grove_worker;
2617
+ `);
2618
+ },
2619
+ async down() {
2620
+ throw new Error("Use a forward migration; retain daily note identities");
2621
+ }
2622
+ };
2623
+
2624
+ // lib/database/src/cache-retention-migration.ts
2625
+ init_define_GROVE_TELEMETRY();
2626
+ var cacheRetention = {
2627
+ name: "20261118_043_cache_retention",
2628
+ async up(db) {
2629
+ const { rows } = await db.raw(
2630
+ "SELECT pg_get_functiondef('grove_schedule_cleanup()'::regprocedure) AS definition"
2631
+ );
2632
+ const definition2 = rows[0].definition;
2633
+ const anchor = "OR EXISTS(SELECT 1 FROM rate_buckets r";
2634
+ if (definition2.split(anchor).length !== 2)
2635
+ throw new Error("Unsupported retention scheduler baseline");
2636
+ await db.raw(
2637
+ definition2.replace(
2638
+ anchor,
2639
+ `OR EXISTS(SELECT 1 FROM ai_cache c WHERE c.account_id=a.id AND c.expires_at<=now())
2640
+ OR EXISTS(SELECT 1 FROM ai_provider_backoff b WHERE b.account_id=a.id AND b.retry_at<now()-interval '1 day')
2641
+ ${anchor}`
2642
+ )
2643
+ );
2644
+ },
2645
+ async down() {
2646
+ throw new Error("Use a forward migration");
2647
+ }
2648
+ };
2649
+
2595
2650
  // lib/database/src/writing-allowance-migration.ts
2596
2651
  init_define_GROVE_TELEMETRY();
2597
2652
  var writingAllowance = {
@@ -6331,7 +6386,9 @@ var migrations = [
6331
6386
  writingTools,
6332
6387
  nativeSharing,
6333
6388
  billingTrial,
6334
- writingAllowance
6389
+ writingAllowance,
6390
+ dailyNotes,
6391
+ cacheRetention
6335
6392
  ];
6336
6393
  var migrationSource = {
6337
6394
  getMigrations: async () => migrations,
@@ -6451,6 +6508,9 @@ async function probeDatabase(db) {
6451
6508
  );
6452
6509
  await db.raw("SELECT policy, version FROM writing_consents LIMIT 0");
6453
6510
  await db.raw("SELECT connection_id FROM writing_cancellations LIMIT 0");
6511
+ await db.raw(
6512
+ "SELECT account_id, local_date, memory_id FROM daily_notes LIMIT 0"
6513
+ );
6454
6514
  }
6455
6515
  var MemoryModel = class extends Model {
6456
6516
  static tableName = "memories";
@@ -21951,14 +22011,16 @@ async function owned2(trx, id2) {
21951
22011
  return row;
21952
22012
  }
21953
22013
  async function expireDocumentDrafts(trx) {
21954
- 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);
22014
+ const limit = 20;
22015
+ 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);
21955
22016
  await trx("document_import_files").whereIn("batchId", expired).where({ originalReady: false }).whereNotNull("staging").update({ staging: null });
21956
22017
  await trx("document_import_notes").whereIn("batchId", expired).whereNull("memoryId").whereNot("content", "[Expired import draft]").update({
21957
22018
  content: "[Expired import draft]",
21958
22019
  included: false,
21959
22020
  suggestion: null
21960
22021
  });
21961
- await trx("document_import_batches").whereIn("id", expired).update({ draftsCleared: true });
22022
+ const processed = await trx("document_import_batches").whereIn("id", expired).update({ draftsCleared: true });
22023
+ return { processed, fullPage: processed === limit };
21962
22024
  }
21963
22025
  var DocumentImports = class {
21964
22026
  constructor(service) {
@@ -22448,8 +22510,9 @@ var available = (q) => q.whereNull("removedAt").where(
22448
22510
  (sub) => sub.where("accepted", true).orWhere("expiresAt", ">", q.client.raw("now()"))
22449
22511
  );
22450
22512
  async function expireConversationDocuments(trx) {
22451
- const docs = await trx("conversation_documents").where({ accepted: false }).whereNull("removedAt").where("expiresAt", "<=", trx.fn.now()).orderBy("id").limit(25).select("id", "conversationId");
22452
- if (!docs.length) return;
22513
+ const limit = 25;
22514
+ const docs = await trx("conversation_documents").where({ accepted: false }).whereNull("removedAt").where("expiresAt", "<=", trx.fn.now()).orderBy("id").limit(limit).select("id", "conversationId");
22515
+ if (!docs.length) return { processed: 0, fullPage: false };
22453
22516
  await trx("conversation_document_chunks").whereIn(
22454
22517
  "documentId",
22455
22518
  docs.map((d) => d.id)
@@ -22467,6 +22530,7 @@ async function expireConversationDocuments(trx) {
22467
22530
  "id",
22468
22531
  docs.map((d) => d.conversationId)
22469
22532
  ).increment("documentsVersion", 1);
22533
+ return { processed: docs.length, fullPage: docs.length === limit };
22470
22534
  }
22471
22535
  async function documentSnapshot(trx, conversationId, query) {
22472
22536
  const chat = await documentChat(trx, conversationId);
@@ -26183,9 +26247,14 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
26183
26247
  if (table) {
26184
26248
  await taskTransaction(db, task, async (trx) => {
26185
26249
  signal.throwIfAborted();
26186
- const rows = await trx(table).select(trx.raw("ctid::text AS row_id")).limit(batchSize);
26187
- if (rows.length)
26188
- await trx(table).whereRaw("ctid=ANY(?::tid[])", [rows.map((row) => row.rowId)]).delete();
26250
+ const deleteBatch = async (target2) => {
26251
+ const rows = await trx(target2).select(trx.raw("ctid::text AS row_id")).limit(batchSize);
26252
+ if (rows.length)
26253
+ await trx(target2).whereRaw("ctid=ANY(?::tid[])", [rows.map((row) => row.rowId)]).delete();
26254
+ return rows.length;
26255
+ };
26256
+ const count2 = await deleteBatch(table);
26257
+ const daily = table === "notebook_expiries" ? await deleteBatch("daily_notes") : 0;
26189
26258
  const research = table === "inference_usage" ? await trx("research_account_usage").select("day").limit(batchSize) : [];
26190
26259
  if (research.length)
26191
26260
  await trx("research_account_usage").whereIn(
@@ -26195,9 +26264,9 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
26195
26264
  const cache = table === "memory_briefs" ? await pruneCache(trx, false) : 0;
26196
26265
  return {
26197
26266
  cursor: {
26198
- stage: rows.length === batchSize || research.length === batchSize || cache === batchSize ? stage : stage + 1
26267
+ stage: count2 === batchSize || daily === batchSize || research.length === batchSize || cache === batchSize ? stage : stage + 1
26199
26268
  },
26200
- processed: Number(task.processed) + rows.length + research.length + cache
26269
+ processed: Number(task.processed) + count2 + daily + research.length + cache
26201
26270
  };
26202
26271
  });
26203
26272
  return;
@@ -26227,8 +26296,8 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
26227
26296
  const retention_cleanup = async (task, signal) => {
26228
26297
  await taskTransaction(db, task, async (trx) => {
26229
26298
  signal.throwIfAborted();
26230
- await expireDocumentDrafts(trx);
26231
- await expireConversationDocuments(trx);
26299
+ const drafts = await expireDocumentDrafts(trx);
26300
+ const uploads = await expireConversationDocuments(trx);
26232
26301
  const writingExpired = await expireWriting(trx);
26233
26302
  const expired = await trx("memories").where("purgeAt", "<=", trx.fn.now()).select("id").orderBy("id").limit(batchSize);
26234
26303
  if (expired.length) {
@@ -26244,8 +26313,8 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
26244
26313
  await trx("rate_buckets").whereIn("minute", buckets).delete();
26245
26314
  const cache = await pruneCache(trx, true);
26246
26315
  return {
26247
- processed: Number(task.processed) + expired.length + cache + writingExpired,
26248
- complete: expired.length < batchSize && buckets.length < batchSize && writingExpired < batchSize && cache < batchSize
26316
+ processed: Number(task.processed) + expired.length + cache + writingExpired + drafts.processed + uploads.processed,
26317
+ complete: !drafts.fullPage && !uploads.fullPage && expired.length < batchSize && buckets.length < batchSize && writingExpired < batchSize && cache < batchSize
26249
26318
  };
26250
26319
  });
26251
26320
  };
@@ -28233,6 +28302,34 @@ var MemoryService = class _MemoryService {
28233
28302
  async remember(principal, input) {
28234
28303
  return this.saveMemory(principal, input, false);
28235
28304
  }
28305
+ async dailyNoteFor(trx, accountId, localDate) {
28306
+ const row = await trx("daily_notes as daily").leftJoin("memories as note", function() {
28307
+ this.on("note.account_id", "daily.account_id").andOn(
28308
+ "note.id",
28309
+ "daily.memory_id"
28310
+ );
28311
+ }).where({ "daily.account_id": accountId, "daily.local_date": localDate }).first("note.id");
28312
+ return !row ? { state: "empty" } : row.id ? { state: "saved", id: row.id } : { state: "deleted" };
28313
+ }
28314
+ async dailyNote(principal, date) {
28315
+ if (principal.type !== "session") throw forbidden();
28316
+ const localDate = localDateSchema.parse(date);
28317
+ return this.access(
28318
+ principal,
28319
+ "memory:read",
28320
+ ({ trx, account }) => this.dailyNoteFor(trx, account.id, localDate)
28321
+ );
28322
+ }
28323
+ async createDailyNote(principal, date, input) {
28324
+ if (principal.type !== "session") throw forbidden();
28325
+ const localDate = localDateSchema.parse(date);
28326
+ if (input.id || input.expectedVersion || input.archived || input.capture !== "explicit")
28327
+ throw new GroveError(
28328
+ "invalid_request",
28329
+ "A daily note must start with a new, active note"
28330
+ );
28331
+ return this.saveMemory(principal, input, false, localDate);
28332
+ }
28236
28333
  async captureWeb(principal, raw) {
28237
28334
  const input = browserCaptureRequestSchema.parse(raw);
28238
28335
  return this.access(
@@ -28501,7 +28598,7 @@ var MemoryService = class _MemoryService {
28501
28598
  return this.inTransaction(trx).updateMemory(principal, input);
28502
28599
  });
28503
28600
  }
28504
- async saveMemory(principal, request2, partial) {
28601
+ async saveMemory(principal, request2, partial, localDate) {
28505
28602
  let created = false;
28506
28603
  const result = await this.access(
28507
28604
  principal,
@@ -28517,8 +28614,23 @@ var MemoryService = class _MemoryService {
28517
28614
  trx,
28518
28615
  account.id,
28519
28616
  request2.operationId,
28520
- { action: partial ? "update_memory" : "remember", ...request2 },
28617
+ localDate ? { action: "create_daily_note", localDate, ...request2 } : { action: partial ? "update_memory" : "remember", ...request2 },
28521
28618
  async () => {
28619
+ if (localDate) {
28620
+ const daily = await this.dailyNoteFor(trx, account.id, localDate);
28621
+ if (daily.state === "saved")
28622
+ throw new GroveError(
28623
+ "daily_note_exists",
28624
+ "A daily note was already saved for this date. Copy any draft text you want to keep.",
28625
+ 409
28626
+ );
28627
+ if (daily.state === "deleted")
28628
+ throw new GroveError(
28629
+ "daily_note_deleted",
28630
+ "The daily note for this date was deleted. Your draft was not saved.",
28631
+ 410
28632
+ );
28633
+ }
28522
28634
  let old;
28523
28635
  if (request2.id) {
28524
28636
  old = await this.query(trx, grant).findById(request2.id).forUpdate();
@@ -28628,6 +28740,12 @@ var MemoryService = class _MemoryService {
28628
28740
  id: randomUUID14(),
28629
28741
  status: input.archived ? "archived" : "active"
28630
28742
  });
28743
+ if (localDate)
28744
+ await trx("daily_notes").insert({
28745
+ accountId: account.id,
28746
+ localDate,
28747
+ memoryId: row2.id
28748
+ });
28631
28749
  const session = editSession ?? principal.sessionId;
28632
28750
  await this.revise(
28633
28751
  trx,
@@ -48776,6 +48894,24 @@ function createApp(deps) {
48776
48894
  )
48777
48895
  })
48778
48896
  );
48897
+ app.get(
48898
+ "/v1/memories/daily/:date",
48899
+ async (c) => c.json({
48900
+ success: true,
48901
+ data: await service.dailyNote(c.get("principal"), c.req.param("date"))
48902
+ })
48903
+ );
48904
+ app.post(
48905
+ "/v1/memories/daily/:date",
48906
+ async (c) => c.json({
48907
+ success: true,
48908
+ data: await service.createDailyNote(
48909
+ c.get("principal"),
48910
+ c.req.param("date"),
48911
+ await mutation(c, rememberSchema)
48912
+ )
48913
+ })
48914
+ );
48779
48915
  app.post("/v1/memories", async (c) => {
48780
48916
  const input = await mutation(
48781
48917
  c,