botnote 0.2.16 → 0.2.18

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 (136) hide show
  1. package/README.md +24 -504
  2. package/dist/bin.js +16 -9
  3. package/dist/bin.js.map +1 -1
  4. package/dist/config.d.ts +0 -4
  5. package/dist/config.js +0 -31
  6. package/dist/config.js.map +1 -1
  7. package/dist/mcp/server.js +1 -1
  8. package/dist/mcp/server.js.map +1 -1
  9. package/dist/mcp/stdio.d.ts +8 -0
  10. package/dist/mcp/stdio.js +46 -0
  11. package/dist/mcp/stdio.js.map +1 -0
  12. package/package.json +8 -40
  13. package/dist/cli.d.ts +0 -1
  14. package/dist/cli.js +0 -186
  15. package/dist/cli.js.map +0 -1
  16. package/dist/db/client.d.ts +0 -14
  17. package/dist/db/client.js +0 -16
  18. package/dist/db/client.js.map +0 -1
  19. package/dist/db/migrate.d.ts +0 -1
  20. package/dist/db/migrate.js +0 -57
  21. package/dist/db/migrate.js.map +0 -1
  22. package/dist/db/migrations/0001_init.sql +0 -89
  23. package/dist/db/migrations/0002_tasks_due_at.sql +0 -16
  24. package/dist/db/migrations/0003_task_priority_and_sequence.sql +0 -45
  25. package/dist/db/migrations/0004_pinned.sql +0 -8
  26. package/dist/db/migrations/0005_nullable_title_and_parent.sql +0 -5
  27. package/dist/db/migrations/0006_project_color_icon.sql +0 -3
  28. package/dist/db/migrations/0007_tokens.sql +0 -14
  29. package/dist/db/migrations/0008_simplify_kinds_drop_actors.sql +0 -21
  30. package/dist/db/migrations/0009_sessions.sql +0 -14
  31. package/dist/db/migrations/0010_completed_at.sql +0 -17
  32. package/dist/db/migrations/0011_completed_at_backfill_fix.sql +0 -14
  33. package/dist/db/migrations/0012_completed_at_backfill_due.sql +0 -16
  34. package/dist/db/migrations/0013_due_at_noon_utc.sql +0 -13
  35. package/dist/db/migrations/0014_recoverable_api_tokens.sql +0 -3
  36. package/dist/db/migrations/0015_collapse_delayed_archived_statuses.sql +0 -18
  37. package/dist/db/migrations/0016_embedding_settings.sql +0 -23
  38. package/dist/db/migrations/0017_recurrence_rules.sql +0 -55
  39. package/dist/db/migrations/0018_project_archived_at.sql +0 -8
  40. package/dist/db/migrations/0019_project_status.sql +0 -20
  41. package/dist/db/migrations/0020_project_archived_status.sql +0 -20
  42. package/dist/db/migrations/0021_workspace_settings.sql +0 -18
  43. package/dist/db/migrations/0022_recurrence_split.sql +0 -13
  44. package/dist/db/migrations/0023_comment_kind.sql +0 -24
  45. package/dist/db/migrations/0024_memory_access.sql +0 -12
  46. package/dist/db/migrations/0025_soft_delete.sql +0 -12
  47. package/dist/db/migrations/0026_sequence_counter.sql +0 -61
  48. package/dist/db/migrations/0027_self_parent_repair.sql +0 -10
  49. package/dist/db/migrations/0028_workspaces.sql +0 -65
  50. package/dist/db/migrations/0029_drop_global_uniques.sql +0 -38
  51. package/dist/db/migrations/0030_entity_actor_token.sql +0 -12
  52. package/dist/db/migrations/0031_entity_revisions.sql +0 -19
  53. package/dist/db/migrations/0032_touch_respects_explicit_updated_at.sql +0 -18
  54. package/dist/db/migrations/0033_worklog_kind.sql +0 -42
  55. package/dist/db/schema.d.ts +0 -2023
  56. package/dist/db/schema.js +0 -245
  57. package/dist/db/schema.js.map +0 -1
  58. package/dist/rest/attribution.d.ts +0 -22
  59. package/dist/rest/attribution.js +0 -62
  60. package/dist/rest/attribution.js.map +0 -1
  61. package/dist/rest/auth.d.ts +0 -47
  62. package/dist/rest/auth.js +0 -116
  63. package/dist/rest/auth.js.map +0 -1
  64. package/dist/rest/routes.d.ts +0 -3
  65. package/dist/rest/routes.js +0 -844
  66. package/dist/rest/routes.js.map +0 -1
  67. package/dist/rest/server.d.ts +0 -28
  68. package/dist/rest/server.js +0 -276
  69. package/dist/rest/server.js.map +0 -1
  70. package/dist/service/blockers.d.ts +0 -37
  71. package/dist/service/blockers.js +0 -46
  72. package/dist/service/blockers.js.map +0 -1
  73. package/dist/service/dates.d.ts +0 -19
  74. package/dist/service/dates.js +0 -52
  75. package/dist/service/dates.js.map +0 -1
  76. package/dist/service/embedding.d.ts +0 -75
  77. package/dist/service/embedding.js +0 -318
  78. package/dist/service/embedding.js.map +0 -1
  79. package/dist/service/embedding_settings.d.ts +0 -16
  80. package/dist/service/embedding_settings.js +0 -82
  81. package/dist/service/embedding_settings.js.map +0 -1
  82. package/dist/service/entities.d.ts +0 -96
  83. package/dist/service/entities.js +0 -628
  84. package/dist/service/entities.js.map +0 -1
  85. package/dist/service/feedback.d.ts +0 -13
  86. package/dist/service/feedback.js +0 -50
  87. package/dist/service/feedback.js.map +0 -1
  88. package/dist/service/hierarchy.d.ts +0 -31
  89. package/dist/service/hierarchy.js +0 -76
  90. package/dist/service/hierarchy.js.map +0 -1
  91. package/dist/service/index.d.ts +0 -10
  92. package/dist/service/index.js +0 -10
  93. package/dist/service/index.js.map +0 -1
  94. package/dist/service/locks.d.ts +0 -25
  95. package/dist/service/locks.js +0 -34
  96. package/dist/service/locks.js.map +0 -1
  97. package/dist/service/opening_brief.d.ts +0 -24
  98. package/dist/service/opening_brief.js +0 -210
  99. package/dist/service/opening_brief.js.map +0 -1
  100. package/dist/service/projects.d.ts +0 -9
  101. package/dist/service/projects.js +0 -59
  102. package/dist/service/projects.js.map +0 -1
  103. package/dist/service/recurrence.d.ts +0 -93
  104. package/dist/service/recurrence.js +0 -799
  105. package/dist/service/recurrence.js.map +0 -1
  106. package/dist/service/revisions.d.ts +0 -31
  107. package/dist/service/revisions.js +0 -53
  108. package/dist/service/revisions.js.map +0 -1
  109. package/dist/service/scope.d.ts +0 -14
  110. package/dist/service/scope.js +0 -19
  111. package/dist/service/scope.js.map +0 -1
  112. package/dist/service/search.d.ts +0 -34
  113. package/dist/service/search.js +0 -198
  114. package/dist/service/search.js.map +0 -1
  115. package/dist/service/sessions.d.ts +0 -24
  116. package/dist/service/sessions.js +0 -89
  117. package/dist/service/sessions.js.map +0 -1
  118. package/dist/service/tasks.d.ts +0 -48
  119. package/dist/service/tasks.js +0 -354
  120. package/dist/service/tasks.js.map +0 -1
  121. package/dist/service/tokens.d.ts +0 -21
  122. package/dist/service/tokens.js +0 -71
  123. package/dist/service/tokens.js.map +0 -1
  124. package/dist/service/transfer.d.ts +0 -64
  125. package/dist/service/transfer.js +0 -629
  126. package/dist/service/transfer.js.map +0 -1
  127. package/dist/service/types.d.ts +0 -772
  128. package/dist/service/types.js +0 -274
  129. package/dist/service/types.js.map +0 -1
  130. package/dist/service/workspace_settings.d.ts +0 -9
  131. package/dist/service/workspace_settings.js +0 -49
  132. package/dist/service/workspace_settings.js.map +0 -1
  133. package/web/dist/assets/index-C0u0ZrR4.css +0 -1
  134. package/web/dist/assets/index-sCiJNYQ3.js +0 -235
  135. package/web/dist/favicon.svg +0 -13
  136. package/web/dist/index.html +0 -22
package/dist/cli.js DELETED
@@ -1,186 +0,0 @@
1
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
- import { createDb } from "./db/client.js";
3
- import { migrate } from "./db/migrate.js";
4
- import { BotnoteHttpClient } from "./mcp/http-client.js";
5
- import { buildMcpServer } from "./mcp/server.js";
6
- import { EmbeddingService } from "./service/embedding.js";
7
- import { purgeExpired } from "./service/entities.js";
8
- import { LOCK_KEYS, withAdvisoryLock } from "./service/locks.js";
9
- import { materializeScheduledRecurrences } from "./service/recurrence.js";
10
- import { resolveDefaultScope } from "./service/scope.js";
11
- import { pruneExpiredSessions } from "./service/sessions.js";
12
- import { DEFAULT_PORT, envValue, resolveBaseUrl } from "./config.js";
13
- import { authConfigFromEnv, isLoopback } from "./rest/auth.js";
14
- import { buildServer } from "./rest/server.js";
15
- import { VERSION } from "./version.js";
16
- const DEFAULT_RECURRENCE_MATERIALIZE_INTERVAL_MS = 5 * 60 * 1000;
17
- // Trashed entities are hard-deleted after this many days. 0 disables auto-purge.
18
- const DEFAULT_TRASH_RETENTION_DAYS = 30;
19
- const DAILY_MS = 24 * 60 * 60 * 1000;
20
- const TRASH_PURGE_INTERVAL_MS = DAILY_MS;
21
- const SESSION_PRUNE_INTERVAL_MS = DAILY_MS;
22
- // Re-queues task/note rows still without a vector: rows left behind by a
23
- // restart or by a provider outage become searchable without manual backfill.
24
- const EMBEDDING_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
25
- function endOfToday() {
26
- const end = new Date();
27
- end.setHours(23, 59, 59, 999);
28
- return end;
29
- }
30
- async function runRest() {
31
- const port = Number(envValue(process.env.BOTNOTE_PORT) ?? DEFAULT_PORT);
32
- const host = process.env.BOTNOTE_HOST ?? "127.0.0.1";
33
- const logLevel = process.env.BOTNOTE_LOG_LEVEL ?? "info";
34
- const recurrenceIntervalMs = Number(process.env.BOTNOTE_RECURRENCE_MATERIALIZE_INTERVAL_MS ??
35
- DEFAULT_RECURRENCE_MATERIALIZE_INTERVAL_MS);
36
- await migrate();
37
- const { db, pool } = createDb();
38
- const defaultScope = await resolveDefaultScope(db);
39
- const embedding = new EmbeddingService(db, { apiKey: process.env.OPENAI_API_KEY });
40
- await embedding.reloadConfig();
41
- const auth = authConfigFromEnv();
42
- const app = await buildServer({ db, embedding, logLevel, auth, defaultScope });
43
- await app.listen({ port, host });
44
- embedding.setLogger((msg) => app.log.warn(`embedding: ${msg}`));
45
- app.log.info(`botnote v${VERSION} listening on http://${host}:${port} (docs: /docs, embeddings ${embedding.isEnabled() ? "ON" : "OFF"})`);
46
- if (!auth.required && !isLoopback(host) && host !== "localhost") {
47
- app.log.warn(`listening on ${host} with auth disabled: anyone who can reach port ${port} can read and write everything. Set BOTNOTE_PASSWORD (and create an API token) or BOTNOTE_REQUIRE_AUTH=1.`);
48
- }
49
- // Background jobs take a database-wide advisory lock so several daemon
50
- // instances on one database (hosted mode) never run the same pass twice.
51
- const materializeRecurrences = async () => {
52
- try {
53
- const run = await withAdvisoryLock(pool, LOCK_KEYS.recurrenceMaterializer, () => materializeScheduledRecurrences(db, endOfToday(), 500));
54
- if (!run.acquired) {
55
- app.log.debug("recurrence materializer skipped: another instance holds the lock");
56
- return;
57
- }
58
- if (run.value.length > 0) {
59
- app.log.info(`materialized ${run.value.length} scheduled recurring task(s)`);
60
- }
61
- }
62
- catch (err) {
63
- app.log.error({ err }, "scheduled recurrence materializer failed");
64
- }
65
- };
66
- await materializeRecurrences();
67
- const recurrenceTimer = recurrenceIntervalMs > 0 ? setInterval(materializeRecurrences, recurrenceIntervalMs) : null;
68
- const trashRetentionDays = Number(process.env.BOTNOTE_TRASH_RETENTION_DAYS ?? DEFAULT_TRASH_RETENTION_DAYS);
69
- const purgeTrash = async () => {
70
- try {
71
- const run = await withAdvisoryLock(pool, LOCK_KEYS.trashPurge, () => purgeExpired(db, trashRetentionDays));
72
- if (!run.acquired) {
73
- app.log.debug("trash purge skipped: another instance holds the lock");
74
- return;
75
- }
76
- if (run.value > 0) {
77
- app.log.info(`purged ${run.value} trashed entit(ies) older than ${trashRetentionDays}d`);
78
- }
79
- }
80
- catch (err) {
81
- app.log.error({ err }, "trash purge failed");
82
- }
83
- };
84
- let trashTimer = null;
85
- if (trashRetentionDays > 0) {
86
- await purgeTrash();
87
- trashTimer = setInterval(purgeTrash, TRASH_PURGE_INTERVAL_MS);
88
- }
89
- const pruneSessions = async () => {
90
- try {
91
- const run = await withAdvisoryLock(pool, LOCK_KEYS.sessionPrune, () => pruneExpiredSessions(db));
92
- if (!run.acquired) {
93
- app.log.debug("session prune skipped: another instance holds the lock");
94
- return;
95
- }
96
- if (run.value > 0) {
97
- app.log.info(`pruned ${run.value} expired session(s)`);
98
- }
99
- }
100
- catch (err) {
101
- app.log.error({ err }, "session prune failed");
102
- }
103
- };
104
- await pruneSessions();
105
- const sessionTimer = setInterval(pruneSessions, SESSION_PRUNE_INTERVAL_MS);
106
- const sweepMissingEmbeddings = async () => {
107
- if (!embedding.isEnabled())
108
- return;
109
- try {
110
- const queued = await embedding.enqueueMissing();
111
- if (queued.enqueued > 0) {
112
- app.log.info(`queued ${queued.enqueued} entit(ies) for embedding backfill (${queued.pendingCount} pending)`);
113
- }
114
- }
115
- catch (err) {
116
- app.log.error({ err }, "embedding backfill sweep failed");
117
- }
118
- };
119
- await sweepMissingEmbeddings();
120
- const embeddingTimer = setInterval(sweepMissingEmbeddings, EMBEDDING_SWEEP_INTERVAL_MS);
121
- const shutdown = async (sig) => {
122
- app.log.info(`shutting down on ${sig}`);
123
- if (recurrenceTimer)
124
- clearInterval(recurrenceTimer);
125
- if (trashTimer)
126
- clearInterval(trashTimer);
127
- clearInterval(sessionTimer);
128
- clearInterval(embeddingTimer);
129
- await app.close();
130
- process.exit(0);
131
- };
132
- process.on("SIGINT", () => shutdown("SIGINT"));
133
- process.on("SIGTERM", () => shutdown("SIGTERM"));
134
- }
135
- async function runMcp() {
136
- // MCP stdio mode. The server is now an HTTP client of the botnote daemon
137
- // (no DB connection here), so this entry point is package-portable: it can
138
- // be installed via a Claude Code plugin on any machine and pointed at any
139
- // daemon (loopback by default, a private network URL, a public instance...).
140
- // Every log line must go to stderr so we don't corrupt the MCP framed JSON
141
- // on stdout.
142
- const { baseUrl, explicit } = resolveBaseUrl();
143
- const client = new BotnoteHttpClient({
144
- baseUrl,
145
- token: envValue(process.env.BOTNOTE_TOKEN),
146
- version: VERSION
147
- });
148
- const server = buildMcpServer({ client, version: VERSION });
149
- const transport = new StdioServerTransport();
150
- // Exit diagnostics: clients report the server "dropping mid-session" but the
151
- // process itself never says why it went away. Every path out of the process
152
- // leaves one stderr line so the harness log shows whether the host closed
153
- // stdin, sent a signal, or the server crashed.
154
- const sayExit = (reason) => process.stderr.write(`botnote MCP exiting: ${reason}\n`);
155
- process.stdin.on("end", () => sayExit("stdin closed by host"));
156
- process.stdin.on("close", () => sayExit("stdin stream closed"));
157
- for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
158
- process.on(sig, () => {
159
- sayExit(`received ${sig}`);
160
- process.exit(0);
161
- });
162
- }
163
- process.on("uncaughtException", (err) => {
164
- sayExit(`uncaught exception: ${err?.stack ?? err}`);
165
- process.exit(1);
166
- });
167
- process.on("unhandledRejection", (err) => {
168
- sayExit(`unhandled rejection: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
169
- process.exit(1);
170
- });
171
- await server.connect(transport);
172
- process.stderr.write(`botnote MCP v${VERSION} ready (stdio) → ${baseUrl}${explicit ? "" : " (default; set BOTNOTE_URL for another daemon)"}\n`);
173
- }
174
- async function main() {
175
- const mode = process.argv[2] ?? "rest";
176
- if (mode === "mcp") {
177
- await runMcp();
178
- return;
179
- }
180
- await runRest();
181
- }
182
- main().catch((err) => {
183
- console.error(err);
184
- process.exit(1);
185
- });
186
- //# sourceMappingURL=cli.js.map
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,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vC,OAAO,CAAC,wBAAwB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACnG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;IAEH,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,gBAAgB,OAAO,oBAAoB,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,gDAAgD,IAAI,CAC1H,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,IAAI;IACjB,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC;IACvC,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;QACnB,MAAM,MAAM,EAAE,CAAC;QACf,OAAO;IACT,CAAC;IACD,MAAM,OAAO,EAAE,CAAC;AAClB,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -1,14 +0,0 @@
1
- import { type NodePgQueryResultHKT } from "drizzle-orm/node-postgres";
2
- import type { PgDatabase } from "drizzle-orm/pg-core";
3
- import pkg from "pg";
4
- import * as schema from "./schema.js";
5
- export type Database = ReturnType<typeof createDb>;
6
- /** Either the pool-backed db or a transaction handle, so a helper can run inside both. */
7
- export type Executor = PgDatabase<NodePgQueryResultHKT, typeof schema>;
8
- export declare function createPool(connectionString?: string): pkg.Pool;
9
- export declare function createDb(pool?: pkg.Pool): {
10
- db: import("drizzle-orm/node-postgres").NodePgDatabase<typeof schema> & {
11
- $client: import("pg").Pool;
12
- };
13
- pool: import("pg").Pool;
14
- };
package/dist/db/client.js DELETED
@@ -1,16 +0,0 @@
1
- import { drizzle } from "drizzle-orm/node-postgres";
2
- import pkg from "pg";
3
- import * as schema from "./schema.js";
4
- const { Pool } = pkg;
5
- export function createPool(connectionString) {
6
- const url = connectionString ?? process.env.DATABASE_URL;
7
- if (!url) {
8
- throw new Error("DATABASE_URL is required");
9
- }
10
- return new Pool({ connectionString: url, max: 10 });
11
- }
12
- export function createDb(pool) {
13
- const p = pool ?? createPool();
14
- return { db: drizzle(p, { schema }), pool: p };
15
- }
16
- //# sourceMappingURL=client.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/db/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA6B,MAAM,2BAA2B,CAAC;AAE/E,OAAO,GAAG,MAAM,IAAI,CAAC;AACrB,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;AAOrB,MAAM,UAAU,UAAU,CAAC,gBAAyB;IAClD,MAAM,GAAG,GAAG,gBAAgB,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC;IACzD,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,IAAI,IAAI,CAAC,EAAE,gBAAgB,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,IAAe;IACtC,MAAM,CAAC,GAAG,IAAI,IAAI,UAAU,EAAE,CAAC;IAC/B,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AACjD,CAAC"}
@@ -1 +0,0 @@
1
- export declare function migrate(): Promise<void>;
@@ -1,57 +0,0 @@
1
- import { readFileSync, readdirSync } from "node:fs";
2
- import { join, dirname } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { createPool } from "./client.js";
5
- const __dirname = dirname(fileURLToPath(import.meta.url));
6
- const MIGRATIONS_DIR = join(__dirname, "migrations");
7
- export async function migrate() {
8
- const pool = createPool();
9
- try {
10
- await pool.query(`
11
- CREATE TABLE IF NOT EXISTS _migrations (
12
- name text PRIMARY KEY,
13
- applied_at timestamptz NOT NULL DEFAULT now()
14
- )
15
- `);
16
- const applied = new Set((await pool.query("SELECT name FROM _migrations")).rows.map((r) => r.name));
17
- const files = readdirSync(MIGRATIONS_DIR)
18
- .filter((f) => f.endsWith(".sql"))
19
- .sort();
20
- for (const file of files) {
21
- if (applied.has(file)) {
22
- console.log(`skip ${file} (already applied)`);
23
- continue;
24
- }
25
- const sql = readFileSync(join(MIGRATIONS_DIR, file), "utf8");
26
- console.log(`apply ${file}`);
27
- const client = await pool.connect();
28
- try {
29
- await client.query("BEGIN");
30
- await client.query(sql);
31
- await client.query("INSERT INTO _migrations (name) VALUES ($1)", [file]);
32
- await client.query("COMMIT");
33
- }
34
- catch (err) {
35
- await client.query("ROLLBACK");
36
- throw err;
37
- }
38
- finally {
39
- client.release();
40
- }
41
- }
42
- console.log("migrations done");
43
- }
44
- finally {
45
- await pool.end();
46
- }
47
- }
48
- const isDirectInvocation = import.meta.url === `file://${process.argv[1]}` ||
49
- process.argv[1]?.endsWith("/migrate.ts") ||
50
- process.argv[1]?.endsWith("/migrate.js");
51
- if (isDirectInvocation) {
52
- migrate().catch((err) => {
53
- console.error(err);
54
- process.exit(1);
55
- });
56
- }
57
- //# sourceMappingURL=migrate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/db/migrate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACpD,O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ABLE IF NOT EXISTS projects (
7
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
8
- key text NOT NULL,
9
- name text NOT NULL,
10
- agents_md text NOT NULL DEFAULT '',
11
- created_at timestamptz NOT NULL DEFAULT now(),
12
- updated_at timestamptz NOT NULL DEFAULT now()
13
- );
14
- CREATE UNIQUE INDEX IF NOT EXISTS projects_key_idx ON projects(key);
15
-
16
- CREATE TABLE IF NOT EXISTS actors (
17
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
18
- name text NOT NULL,
19
- kind text NOT NULL,
20
- key text,
21
- created_at timestamptz NOT NULL DEFAULT now()
22
- );
23
- CREATE UNIQUE INDEX IF NOT EXISTS actors_name_idx ON actors(name);
24
- CREATE UNIQUE INDEX IF NOT EXISTS actors_key_idx ON actors(key);
25
-
26
- CREATE TABLE IF NOT EXISTS entities (
27
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
28
- project_id uuid REFERENCES projects(id) ON DELETE SET NULL,
29
- kind text NOT NULL,
30
- title text NOT NULL,
31
- body text NOT NULL DEFAULT '',
32
- tags text[] NOT NULL DEFAULT '{}'::text[],
33
- status text NOT NULL DEFAULT 'open',
34
- actor_id uuid REFERENCES actors(id),
35
- actor_kind text NOT NULL DEFAULT 'human',
36
- idempotency_key text,
37
- parent_id uuid REFERENCES entities(id) ON DELETE SET NULL,
38
- body_tsv tsvector GENERATED ALWAYS AS (
39
- setweight(to_tsvector('simple', coalesce(title, '')), 'A') ||
40
- setweight(to_tsvector('simple', coalesce(body, '')), 'B')
41
- ) STORED,
42
- body_vec vector(384),
43
- metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
44
- created_at timestamptz NOT NULL DEFAULT now(),
45
- updated_at timestamptz NOT NULL DEFAULT now()
46
- );
47
-
48
- CREATE INDEX IF NOT EXISTS entities_project_created_idx
49
- ON entities(project_id, created_at DESC);
50
- CREATE INDEX IF NOT EXISTS entities_project_kind_created_idx
51
- ON entities(project_id, kind, created_at DESC);
52
- CREATE INDEX IF NOT EXISTS entities_actor_created_idx
53
- ON entities(actor_id, created_at DESC);
54
- CREATE UNIQUE INDEX IF NOT EXISTS entities_idempotency_idx
55
- ON entities(idempotency_key) WHERE idempotency_key IS NOT NULL;
56
- CREATE INDEX IF NOT EXISTS entities_body_tsv_idx
57
- ON entities USING GIN(body_tsv);
58
- CREATE INDEX IF NOT EXISTS entities_body_vec_idx
59
- ON entities USING hnsw (body_vec vector_cosine_ops);
60
- CREATE INDEX IF NOT EXISTS entities_tags_idx
61
- ON entities USING GIN(tags);
62
-
63
- CREATE TABLE IF NOT EXISTS edges (
64
- from_id uuid NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
65
- to_id uuid NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
66
- kind text NOT NULL,
67
- created_at timestamptz NOT NULL DEFAULT now(),
68
- PRIMARY KEY (from_id, to_id, kind)
69
- );
70
- CREATE INDEX IF NOT EXISTS edges_to_idx ON edges(to_id, kind);
71
- CREATE INDEX IF NOT EXISTS edges_from_idx ON edges(from_id, kind);
72
-
73
- -- updated_at trigger
74
- CREATE OR REPLACE FUNCTION botnote_touch_updated_at() RETURNS trigger AS $$
75
- BEGIN
76
- NEW.updated_at = now();
77
- RETURN NEW;
78
- END;
79
- $$ LANGUAGE plpgsql;
80
-
81
- DROP TRIGGER IF EXISTS entities_touch_updated_at ON entities;
82
- CREATE TRIGGER entities_touch_updated_at
83
- BEFORE UPDATE ON entities
84
- FOR EACH ROW EXECUTE FUNCTION botnote_touch_updated_at();
85
-
86
- DROP TRIGGER IF EXISTS projects_touch_updated_at ON projects;
87
- CREATE TRIGGER projects_touch_updated_at
88
- BEFORE UPDATE ON projects
89
- FOR EACH ROW EXECUTE FUNCTION botnote_touch_updated_at();
@@ -1,16 +0,0 @@
1
- -- botnote 0002 — tasks need due dates for the Calendar view.
2
- -- Idempotent: safe to re-run.
3
-
4
- ALTER TABLE entities ADD COLUMN IF NOT EXISTS due_at timestamptz;
5
-
6
- CREATE INDEX IF NOT EXISTS entities_due_at_idx
7
- ON entities(due_at) WHERE due_at IS NOT NULL;
8
-
9
- CREATE INDEX IF NOT EXISTS entities_kind_due_at_idx
10
- ON entities(kind, due_at) WHERE due_at IS NOT NULL;
11
-
12
- CREATE INDEX IF NOT EXISTS entities_task_due_idx
13
- ON entities(due_at) WHERE kind = 'task' AND due_at IS NOT NULL;
14
-
15
- CREATE INDEX IF NOT EXISTS entities_task_no_due_idx
16
- ON entities(created_at DESC) WHERE kind = 'task' AND due_at IS NULL AND status <> 'done';
@@ -1,45 +0,0 @@
1
- -- botnote 0003 — priority + per-project sequence id (DEMO-12 style).
2
- -- Idempotent.
3
-
4
- ALTER TABLE entities ADD COLUMN IF NOT EXISTS priority text NOT NULL DEFAULT 'none';
5
- ALTER TABLE entities ADD COLUMN IF NOT EXISTS sequence_id integer;
6
-
7
- CREATE INDEX IF NOT EXISTS entities_project_seq_idx
8
- ON entities(project_id, sequence_id) WHERE sequence_id IS NOT NULL;
9
-
10
- -- per-project sequence trigger. Assign sequence_id on INSERT when project_id
11
- -- is set (workspace-wide entities stay null).
12
- CREATE OR REPLACE FUNCTION botnote_set_sequence_id() RETURNS trigger AS $$
13
- BEGIN
14
- IF NEW.sequence_id IS NULL AND NEW.project_id IS NOT NULL THEN
15
- SELECT COALESCE(MAX(sequence_id), 0) + 1
16
- INTO NEW.sequence_id
17
- FROM entities
18
- WHERE project_id = NEW.project_id;
19
- END IF;
20
- RETURN NEW;
21
- END;
22
- $$ LANGUAGE plpgsql;
23
-
24
- DROP TRIGGER IF EXISTS entities_set_sequence_id ON entities;
25
- CREATE TRIGGER entities_set_sequence_id
26
- BEFORE INSERT ON entities
27
- FOR EACH ROW EXECUTE FUNCTION botnote_set_sequence_id();
28
-
29
- -- Backfill existing rows that have project_id but no sequence_id, ordered by created_at.
30
- DO $$
31
- DECLARE
32
- rec record;
33
- counters jsonb := '{}'::jsonb;
34
- next_n integer;
35
- BEGIN
36
- FOR rec IN
37
- SELECT id, project_id FROM entities
38
- WHERE project_id IS NOT NULL AND sequence_id IS NULL
39
- ORDER BY project_id, created_at
40
- LOOP
41
- next_n := COALESCE((counters->>rec.project_id::text)::int, 0) + 1;
42
- counters := jsonb_set(counters, ARRAY[rec.project_id::text], to_jsonb(next_n));
43
- UPDATE entities SET sequence_id = next_n WHERE id = rec.id;
44
- END LOOP;
45
- END $$;
@@ -1,8 +0,0 @@
1
- -- botnote 0004 — pinned flag for project-level context surfacing.
2
- -- Idempotent.
3
-
4
- ALTER TABLE entities ADD COLUMN IF NOT EXISTS pinned boolean NOT NULL DEFAULT false;
5
-
6
- CREATE INDEX IF NOT EXISTS entities_pinned_idx
7
- ON entities(project_id, pinned)
8
- WHERE pinned = true;
@@ -1,5 +0,0 @@
1
- -- Allow title to be null (notes without a title use body-derived placeholder in UI).
2
- ALTER TABLE entities ALTER COLUMN title DROP NOT NULL;
3
-
4
- -- Index parent_id for fast lookups of related entities (e.g. notes linked to a task).
5
- CREATE INDEX IF NOT EXISTS entities_parent_idx ON entities(parent_id) WHERE parent_id IS NOT NULL;
@@ -1,3 +0,0 @@
1
- -- Per-project color + icon. Defaults match the Linear-ish indigo accent and a simple circle dot.
2
- ALTER TABLE projects ADD COLUMN IF NOT EXISTS color text NOT NULL DEFAULT '#5e6ad2';
3
- ALTER TABLE projects ADD COLUMN IF NOT EXISTS icon text NOT NULL DEFAULT 'circle';
@@ -1,14 +0,0 @@
1
- -- API tokens. token_hash stores sha256 of the plaintext token; prefix is the first
2
- -- 8 chars of the plaintext (for display). Auth middleware enforcement is off by
3
- -- default for local deployments; these endpoints let the UI grant/revoke tokens
4
- -- when public or proxy-gated access is enabled.
5
- CREATE TABLE IF NOT EXISTS tokens (
6
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
7
- name text NOT NULL,
8
- token_hash text NOT NULL UNIQUE,
9
- prefix text NOT NULL,
10
- last_used_at timestamptz,
11
- created_at timestamptz NOT NULL DEFAULT now()
12
- );
13
-
14
- CREATE INDEX IF NOT EXISTS tokens_created_idx ON tokens(created_at DESC);
@@ -1,21 +0,0 @@
1
- -- 0008: simplify entity kinds and drop the actors table.
2
- --
3
- -- Why: the original schema had 7 entity kinds (task, note, decision, doc,
4
- -- comment, log, memory) and a separate `actors` table for writer identity.
5
- -- In practice only task and note carry real semantic weight in the UI/agent
6
- -- flows; the others are folded into note with the legacy kind preserved as a
7
- -- tag so nothing is lost. Identity is now expressed by the existing
8
- -- entities.actor_kind text column (human / agent / system) — the actors
9
- -- lookup table never accumulated rows, so we drop it.
10
-
11
- -- Fold legacy kinds into 'note'. The previous kind name is appended to tags
12
- -- so we can still query e.g. tag='decision' or tag='memory' if needed.
13
- UPDATE entities
14
- SET tags = array_append(tags, kind), kind = 'note'
15
- WHERE kind IN ('decision', 'doc', 'comment', 'log', 'memory');
16
-
17
- -- Drop the FK first to avoid a dependency error, then the column, then the
18
- -- table. None of these had any live rows referencing them.
19
- ALTER TABLE entities DROP CONSTRAINT IF EXISTS entities_actor_id_fkey;
20
- ALTER TABLE entities DROP COLUMN IF EXISTS actor_id;
21
- DROP TABLE IF EXISTS actors;
@@ -1,14 +0,0 @@
1
- -- Browser session cookies. Each row corresponds to one logged-in browser;
2
- -- plaintext is the cookie value (random 32 bytes hex), DB stores sha256.
3
-
4
- CREATE TABLE IF NOT EXISTS sessions (
5
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
6
- token_hash text NOT NULL,
7
- expires_at timestamptz NOT NULL,
8
- user_agent text,
9
- last_used_at timestamptz,
10
- created_at timestamptz NOT NULL DEFAULT now()
11
- );
12
-
13
- CREATE UNIQUE INDEX IF NOT EXISTS sessions_token_hash_idx ON sessions(token_hash);
14
- CREATE INDEX IF NOT EXISTS sessions_expires_at_idx ON sessions(expires_at);
@@ -1,17 +0,0 @@
1
- -- Add completed_at column to entities. Set automatically on a status
2
- -- transition into 'done' (and cleared when leaving). Backfill existing done
3
- -- rows from updated_at as the best available approximation. Legacy-imported
4
- -- tasks may have lost their original timestamp, so this clusters them on the
5
- -- migration day rather than guessing. New transitions are exact.
6
- ALTER TABLE entities ADD COLUMN IF NOT EXISTS completed_at timestamptz;
7
-
8
- UPDATE entities
9
- SET completed_at = updated_at
10
- WHERE kind = 'task' AND status = 'done' AND completed_at IS NULL;
11
-
12
- -- Partial index — only done rows have a non-null completed_at, so this stays
13
- -- small and keeps range scans cheap when the calendar queries by completed
14
- -- date.
15
- CREATE INDEX IF NOT EXISTS entities_completed_at_idx
16
- ON entities (completed_at)
17
- WHERE completed_at IS NOT NULL;
@@ -1,14 +0,0 @@
1
- -- Fix the 0010 backfill. The first pass used updated_at, which for imported
2
- -- tasks can be the migration day, so every legacy done task piled onto the
3
- -- same calendar cell. Re-backfill with COALESCE(due_at, updated_at) so legacy
4
- -- done items render on their original due date (the pre-change behavior),
5
- -- while freshly-completed tasks still get an exact stamp from the service
6
- -- layer at status-transition time.
7
- UPDATE entities
8
- SET completed_at = COALESCE(due_at, updated_at)
9
- WHERE kind = 'task'
10
- AND status = 'done'
11
- -- Only rows whose completed_at matches the 0010 backfill exactly (i.e.
12
- -- never updated since). Real recent completions have completed_at != updated_at
13
- -- once anything else touches the row, so this avoids stomping on real data.
14
- AND completed_at = updated_at;
@@ -1,16 +0,0 @@
1
- -- 0011's WHERE clause assumed completed_at = updated_at after 0010, but the
2
- -- BEFORE-UPDATE trigger bumps updated_at on every UPDATE, so 0010 set
3
- -- completed_at to OLD.updated_at and the trigger then advanced updated_at past
4
- -- it. As a result 0011 matched nothing.
5
- --
6
- -- This pass forces COALESCE(due_at, updated_at) onto every done task whose
7
- -- completed_at still falls before the 0010 backfill window — i.e. data the
8
- -- service layer has not freshly written. Anything completed by the running
9
- -- daemon after 0010 ran will have a strictly later completed_at and is left
10
- -- alone.
11
- UPDATE entities
12
- SET completed_at = COALESCE(due_at, updated_at)
13
- WHERE kind = 'task'
14
- AND status = 'done'
15
- AND completed_at IS NOT NULL
16
- AND completed_at < '2026-06-03 23:56:00+00';
@@ -1,13 +0,0 @@
1
- -- Date-only due dates may be imported as `YYYY-MM-DD T00:00:00Z`,
2
- -- which lands the previous calendar day in any UTC-negative timezone
3
- -- (e.g. UTC midnight = 5pm Pacific the day before). Bump every midnight-UTC
4
- -- due_at to noon-UTC so it stays on the intended calendar day in every
5
- -- timezone (UTC-12 .. UTC+11). The service layer applies the same
6
- -- normalization to new writes so this stays clean going forward.
7
- UPDATE entities
8
- SET due_at = date_trunc('day', due_at AT TIME ZONE 'UTC') + INTERVAL '12 hours'
9
- WHERE kind = 'task'
10
- AND due_at IS NOT NULL
11
- AND EXTRACT(HOUR FROM due_at AT TIME ZONE 'UTC') = 0
12
- AND EXTRACT(MINUTE FROM due_at AT TIME ZONE 'UTC') = 0
13
- AND EXTRACT(SECOND FROM due_at AT TIME ZONE 'UTC') = 0;
@@ -1,3 +0,0 @@
1
- -- Store newly generated API tokens so Settings can copy them after creation.
2
- -- Existing tokens remain NULL because only their sha256 hashes were stored.
3
- ALTER TABLE tokens ADD COLUMN IF NOT EXISTS plaintext text;
@@ -1,18 +0,0 @@
1
- -- Collapse retired task statuses into done.
2
- --
3
- -- delayed and archived were both ambiguous terminal-ish states. The product
4
- -- now has four task states: open, in_progress, done, rejected. Preserve the
5
- -- best available terminal timestamp by using the previous updated_at value as
6
- -- completed_at before the touch trigger advances updated_at.
7
- UPDATE entities
8
- SET
9
- status = 'done',
10
- completed_at = COALESCE(completed_at, updated_at, now())
11
- WHERE kind = 'task'
12
- AND status IN ('delayed', 'archived');
13
-
14
- DROP INDEX IF EXISTS entities_task_no_due_idx;
15
-
16
- CREATE INDEX IF NOT EXISTS entities_task_no_due_idx
17
- ON entities(created_at DESC)
18
- WHERE kind = 'task' AND due_at IS NULL AND status <> 'done';
@@ -1,23 +0,0 @@
1
- -- botnote 0016 embedding settings
2
- -- Idempotent: safe to re-run.
3
-
4
- CREATE TABLE IF NOT EXISTS embedding_settings (
5
- id text PRIMARY KEY DEFAULT 'default' CHECK (id = 'default'),
6
- enabled boolean NOT NULL DEFAULT true,
7
- provider text NOT NULL DEFAULT 'openai',
8
- model text NOT NULL DEFAULT 'text-embedding-3-small',
9
- base_url text,
10
- api_key text,
11
- dimensions integer NOT NULL DEFAULT 384,
12
- created_at timestamptz NOT NULL DEFAULT now(),
13
- updated_at timestamptz NOT NULL DEFAULT now()
14
- );
15
-
16
- INSERT INTO embedding_settings (id)
17
- VALUES ('default')
18
- ON CONFLICT (id) DO NOTHING;
19
-
20
- DROP TRIGGER IF EXISTS embedding_settings_touch_updated_at ON embedding_settings;
21
- CREATE TRIGGER embedding_settings_touch_updated_at
22
- BEFORE UPDATE ON embedding_settings
23
- FOR EACH ROW EXECUTE FUNCTION botnote_touch_updated_at();