botnote 0.2.15 → 0.2.17

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 (138) hide show
  1. package/README.md +26 -506
  2. package/dist/bin.js +28 -21
  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/http-client.d.ts +6 -5
  8. package/dist/mcp/http-client.js +28 -4
  9. package/dist/mcp/http-client.js.map +1 -1
  10. package/dist/mcp/server.js +16 -16
  11. package/dist/mcp/server.js.map +1 -1
  12. package/dist/mcp/stdio.d.ts +8 -0
  13. package/dist/mcp/stdio.js +46 -0
  14. package/dist/mcp/stdio.js.map +1 -0
  15. package/package.json +8 -40
  16. package/dist/cli.d.ts +0 -1
  17. package/dist/cli.js +0 -186
  18. package/dist/cli.js.map +0 -1
  19. package/dist/db/client.d.ts +0 -14
  20. package/dist/db/client.js +0 -16
  21. package/dist/db/client.js.map +0 -1
  22. package/dist/db/migrate.d.ts +0 -1
  23. package/dist/db/migrate.js +0 -57
  24. package/dist/db/migrate.js.map +0 -1
  25. package/dist/db/migrations/0001_init.sql +0 -89
  26. package/dist/db/migrations/0002_tasks_due_at.sql +0 -16
  27. package/dist/db/migrations/0003_task_priority_and_sequence.sql +0 -45
  28. package/dist/db/migrations/0004_pinned.sql +0 -8
  29. package/dist/db/migrations/0005_nullable_title_and_parent.sql +0 -5
  30. package/dist/db/migrations/0006_project_color_icon.sql +0 -3
  31. package/dist/db/migrations/0007_tokens.sql +0 -14
  32. package/dist/db/migrations/0008_simplify_kinds_drop_actors.sql +0 -21
  33. package/dist/db/migrations/0009_sessions.sql +0 -14
  34. package/dist/db/migrations/0010_completed_at.sql +0 -17
  35. package/dist/db/migrations/0011_completed_at_backfill_fix.sql +0 -14
  36. package/dist/db/migrations/0012_completed_at_backfill_due.sql +0 -16
  37. package/dist/db/migrations/0013_due_at_noon_utc.sql +0 -13
  38. package/dist/db/migrations/0014_recoverable_api_tokens.sql +0 -3
  39. package/dist/db/migrations/0015_collapse_delayed_archived_statuses.sql +0 -18
  40. package/dist/db/migrations/0016_embedding_settings.sql +0 -23
  41. package/dist/db/migrations/0017_recurrence_rules.sql +0 -55
  42. package/dist/db/migrations/0018_project_archived_at.sql +0 -8
  43. package/dist/db/migrations/0019_project_status.sql +0 -20
  44. package/dist/db/migrations/0020_project_archived_status.sql +0 -20
  45. package/dist/db/migrations/0021_workspace_settings.sql +0 -18
  46. package/dist/db/migrations/0022_recurrence_split.sql +0 -13
  47. package/dist/db/migrations/0023_comment_kind.sql +0 -24
  48. package/dist/db/migrations/0024_memory_access.sql +0 -12
  49. package/dist/db/migrations/0025_soft_delete.sql +0 -12
  50. package/dist/db/migrations/0026_sequence_counter.sql +0 -61
  51. package/dist/db/migrations/0027_self_parent_repair.sql +0 -10
  52. package/dist/db/migrations/0028_workspaces.sql +0 -65
  53. package/dist/db/migrations/0029_drop_global_uniques.sql +0 -38
  54. package/dist/db/migrations/0030_entity_actor_token.sql +0 -12
  55. package/dist/db/migrations/0031_entity_revisions.sql +0 -19
  56. package/dist/db/migrations/0032_touch_respects_explicit_updated_at.sql +0 -18
  57. package/dist/db/schema.d.ts +0 -2023
  58. package/dist/db/schema.js +0 -245
  59. package/dist/db/schema.js.map +0 -1
  60. package/dist/rest/attribution.d.ts +0 -22
  61. package/dist/rest/attribution.js +0 -62
  62. package/dist/rest/attribution.js.map +0 -1
  63. package/dist/rest/auth.d.ts +0 -47
  64. package/dist/rest/auth.js +0 -116
  65. package/dist/rest/auth.js.map +0 -1
  66. package/dist/rest/routes.d.ts +0 -3
  67. package/dist/rest/routes.js +0 -831
  68. package/dist/rest/routes.js.map +0 -1
  69. package/dist/rest/server.d.ts +0 -28
  70. package/dist/rest/server.js +0 -276
  71. package/dist/rest/server.js.map +0 -1
  72. package/dist/service/blockers.d.ts +0 -37
  73. package/dist/service/blockers.js +0 -46
  74. package/dist/service/blockers.js.map +0 -1
  75. package/dist/service/dates.d.ts +0 -19
  76. package/dist/service/dates.js +0 -52
  77. package/dist/service/dates.js.map +0 -1
  78. package/dist/service/embedding.d.ts +0 -75
  79. package/dist/service/embedding.js +0 -318
  80. package/dist/service/embedding.js.map +0 -1
  81. package/dist/service/embedding_settings.d.ts +0 -16
  82. package/dist/service/embedding_settings.js +0 -82
  83. package/dist/service/embedding_settings.js.map +0 -1
  84. package/dist/service/entities.d.ts +0 -96
  85. package/dist/service/entities.js +0 -628
  86. package/dist/service/entities.js.map +0 -1
  87. package/dist/service/feedback.d.ts +0 -13
  88. package/dist/service/feedback.js +0 -50
  89. package/dist/service/feedback.js.map +0 -1
  90. package/dist/service/hierarchy.d.ts +0 -31
  91. package/dist/service/hierarchy.js +0 -76
  92. package/dist/service/hierarchy.js.map +0 -1
  93. package/dist/service/index.d.ts +0 -10
  94. package/dist/service/index.js +0 -10
  95. package/dist/service/index.js.map +0 -1
  96. package/dist/service/locks.d.ts +0 -25
  97. package/dist/service/locks.js +0 -34
  98. package/dist/service/locks.js.map +0 -1
  99. package/dist/service/opening_brief.d.ts +0 -24
  100. package/dist/service/opening_brief.js +0 -210
  101. package/dist/service/opening_brief.js.map +0 -1
  102. package/dist/service/projects.d.ts +0 -9
  103. package/dist/service/projects.js +0 -59
  104. package/dist/service/projects.js.map +0 -1
  105. package/dist/service/recurrence.d.ts +0 -93
  106. package/dist/service/recurrence.js +0 -799
  107. package/dist/service/recurrence.js.map +0 -1
  108. package/dist/service/revisions.d.ts +0 -31
  109. package/dist/service/revisions.js +0 -53
  110. package/dist/service/revisions.js.map +0 -1
  111. package/dist/service/scope.d.ts +0 -14
  112. package/dist/service/scope.js +0 -19
  113. package/dist/service/scope.js.map +0 -1
  114. package/dist/service/search.d.ts +0 -34
  115. package/dist/service/search.js +0 -198
  116. package/dist/service/search.js.map +0 -1
  117. package/dist/service/sessions.d.ts +0 -24
  118. package/dist/service/sessions.js +0 -89
  119. package/dist/service/sessions.js.map +0 -1
  120. package/dist/service/tasks.d.ts +0 -48
  121. package/dist/service/tasks.js +0 -354
  122. package/dist/service/tasks.js.map +0 -1
  123. package/dist/service/tokens.d.ts +0 -21
  124. package/dist/service/tokens.js +0 -71
  125. package/dist/service/tokens.js.map +0 -1
  126. package/dist/service/transfer.d.ts +0 -64
  127. package/dist/service/transfer.js +0 -629
  128. package/dist/service/transfer.js.map +0 -1
  129. package/dist/service/types.d.ts +0 -770
  130. package/dist/service/types.js +0 -272
  131. package/dist/service/types.js.map +0 -1
  132. package/dist/service/workspace_settings.d.ts +0 -9
  133. package/dist/service/workspace_settings.js +0 -49
  134. package/dist/service/workspace_settings.js.map +0 -1
  135. package/web/dist/assets/index-C0u0ZrR4.css +0 -1
  136. package/web/dist/assets/index-CwZxw-xa.js +0 -235
  137. package/web/dist/favicon.svg +0 -13
  138. package/web/dist/index.html +0 -22
@@ -1,831 +0,0 @@
1
- import { createInterface } from "node:readline";
2
- import { Readable } from "node:stream";
3
- import { z } from "zod";
4
- import { addComment, bumpAccess, get, getByKey, getLinks, link, listChildren, listComments, listRelated, listTags, listTrash, markSuperseded, purge, recent, remove, restore, update, write } from "../service/entities.js";
5
- import { attachHierarchy } from "../service/hierarchy.js";
6
- import { formatOpeningBrief, openingBrief } from "../service/opening_brief.js";
7
- import { createProject, getProject, getProjectByKey, listProjects, updateProject } from "../service/projects.js";
8
- import { findSimilar, search } from "../service/search.js";
9
- import { listFeedback, submitFeedback } from "../service/feedback.js";
10
- import { embeddingCoverage, getEmbeddingSettings, updateEmbeddingSettings } from "../service/embedding_settings.js";
11
- import { getWorkspaceSettings, updateWorkspaceSettings } from "../service/workspace_settings.js";
12
- import { createSession, revokeSession, verifyMasterPassword } from "../service/sessions.js";
13
- import { createRecurrenceRule, getRecurrenceForTask, skipOccurrence, splitRecurrence, stopRecurrence, updateRecurrenceRule } from "../service/recurrence.js";
14
- import { listRevisions } from "../service/revisions.js";
15
- import { tasksRange } from "../service/tasks.js";
16
- import { exportWorkspace, importWorkspace } from "../service/transfer.js";
17
- import { createToken, listTokens, revokeToken, tokenLabels } from "../service/tokens.js";
18
- import { CreateCommentInput, CreateFeedbackInput, CreateNoteInput, CreateProjectInput, CreateTaskInput, CreateTokenInput, EmbeddingBackfillInput, GetLinksInput, LinkInput, ListFeedbackInput, ListProjectsInput, ListTagsInput, OpeningBriefInput, RecentInput, RecurrenceInput, SearchInput, SkipOccurrenceInput, SplitRecurrenceInput, StopRecurrenceInput, TasksRangeInput, UpdateEmbeddingSettingsInput, UpdateInput, UpdateProjectInput, UpdateRecurrenceInput, UpdateWorkspaceSettingsInput, Uuid } from "../service/types.js";
19
- import { VERSION } from "../version.js";
20
- import { attachActorLabels } from "./attribution.js";
21
- import { requestOrigin } from "./auth.js";
22
- const IdParams = z.object({ id: Uuid });
23
- const EntityIdRef = z.string().min(8).max(36).regex(/^[0-9a-fA-F-]+$/);
24
- const EntityIdParams = z.object({ id: EntityIdRef });
25
- const RuleIdParams = z.object({ id: Uuid });
26
- const KeyParams = z.object({ key: z.string() });
27
- const BooleanQuery = z.preprocess((value) => {
28
- if (value === undefined)
29
- return undefined;
30
- if (typeof value === "string")
31
- return value === "true" || value === "1";
32
- return value;
33
- }, z.boolean());
34
- const ListProjectsQuery = z.object({
35
- includeArchived: BooleanQuery.default(false)
36
- });
37
- const ExportQuery = z.object({
38
- vectors: BooleanQuery.default(false)
39
- });
40
- const KeySeqParams = z.object({
41
- key: z.string().regex(/^[A-Z][A-Z0-9_]*$/),
42
- seq: z.coerce.number().int().positive()
43
- });
44
- const OpeningBriefBody = OpeningBriefInput.omit({ projectId: true }).optional();
45
- const LinkBody = LinkInput.omit({ fromId: true });
46
- /**
47
- * Strip `bodyVec` and `bodyTsv` from an entity before sending it over the wire.
48
- * Both fields are internal-only: `bodyVec` is the 384-dim embedding used by
49
- * hybrid search, and `bodyTsv` is the tsvector used by BM25 — neither is
50
- * useful to REST consumers (web or agent) and both add significant token noise.
51
- */
52
- function serializeEntity(e) {
53
- const { bodyVec: _bv, bodyTsv: _bt, ...rest } = e;
54
- return rest;
55
- }
56
- function serializeEntities(rows) {
57
- return rows.map(serializeEntity);
58
- }
59
- function publicToken(t) {
60
- return {
61
- id: t.id,
62
- name: t.name,
63
- prefix: t.prefix,
64
- plaintext: t.plaintext,
65
- lastUsedAt: t.lastUsedAt,
66
- createdAt: t.createdAt
67
- };
68
- }
69
- async function workspaceSettingsResponse(scope, db) {
70
- const settings = await getWorkspaceSettings(scope, db);
71
- return {
72
- timezone: settings.timezone,
73
- updatedAt: settings.updatedAt
74
- };
75
- }
76
- async function embeddingSettingsResponse(scope, ctx) {
77
- const settings = await getEmbeddingSettings(scope, ctx.db);
78
- const coverage = await embeddingCoverage(scope, ctx.db);
79
- const runtime = ctx.embedding.runtimeStatus();
80
- return {
81
- enabled: settings.enabled,
82
- effectiveEnabled: runtime.enabled,
83
- provider: settings.provider,
84
- model: settings.model,
85
- baseUrl: settings.baseUrl,
86
- dimensions: settings.dimensions,
87
- apiKeyConfigured: runtime.apiKeyConfigured,
88
- settingsApiKeyConfigured: Boolean(settings.apiKey),
89
- apiKeySource: runtime.apiKeySource,
90
- apiKeyPreview: runtime.apiKeyPreview,
91
- statusReason: runtime.reason,
92
- pendingCount: ctx.embedding.pendingCount(),
93
- totalCount: coverage.totalCount,
94
- embeddedCount: coverage.embeddedCount,
95
- missingCount: coverage.missingCount,
96
- updatedAt: settings.updatedAt
97
- };
98
- }
99
- export async function registerRoutes(rawApp, ctx) {
100
- const app = rawApp.withTypeProvider();
101
- // Additive `actor: { kind, label }` on every serialized entity, resolved
102
- // from the token that wrote it. Centralised here so the entity-returning
103
- // routes (and anything nested: hits, links, briefs) stay unaware of it.
104
- app.addHook("preSerialization", async (req, _reply, payload) => {
105
- if (!req.url.startsWith("/v1/"))
106
- return payload;
107
- return attachActorLabels(payload, () => tokenLabels(req.scope, ctx.db));
108
- });
109
- app.get("/health", async () => {
110
- const embedding = ctx.embedding.runtimeStatus();
111
- return {
112
- ok: true,
113
- version: VERSION,
114
- embedding: {
115
- enabled: embedding.enabled,
116
- provider: embedding.provider,
117
- model: embedding.model,
118
- dimensions: embedding.dimensions,
119
- reason: embedding.reason
120
- }
121
- };
122
- });
123
- // ----- settings -----
124
- app.get("/v1/settings/embedding", {
125
- schema: {
126
- tags: ["settings"],
127
- summary: "Read embedding provider/model/key status and vector coverage"
128
- }
129
- }, async (req) => embeddingSettingsResponse(req.scope, ctx));
130
- app.patch("/v1/settings/embedding", {
131
- config: { rateLimit: { max: 30, timeWindow: "1 hour" } },
132
- schema: {
133
- tags: ["settings"],
134
- summary: "Update embedding provider/model/key settings",
135
- body: UpdateEmbeddingSettingsInput
136
- }
137
- }, async (req) => {
138
- const body = UpdateEmbeddingSettingsInput.parse(req.body);
139
- await updateEmbeddingSettings(req.scope, ctx.db, body);
140
- await ctx.embedding.reloadConfig();
141
- return embeddingSettingsResponse(req.scope, ctx);
142
- });
143
- app.post("/v1/settings/embedding/backfill", {
144
- config: { rateLimit: { max: 20, timeWindow: "1 hour" } },
145
- schema: {
146
- tags: ["settings"],
147
- summary: "Queue missing embeddings for existing notes and tasks",
148
- body: EmbeddingBackfillInput.optional()
149
- }
150
- }, async (req) => {
151
- const body = EmbeddingBackfillInput.parse(req.body ?? {});
152
- const coverage = await embeddingCoverage(req.scope, ctx.db);
153
- const limit = body.limit ?? coverage.missingCount;
154
- const queued = limit > 0
155
- ? await ctx.embedding.enqueueMissing(limit)
156
- : { enqueued: 0, pendingCount: ctx.embedding.pendingCount() };
157
- return {
158
- ...queued,
159
- settings: await embeddingSettingsResponse(req.scope, ctx)
160
- };
161
- });
162
- app.get("/v1/settings/workspace", {
163
- schema: {
164
- tags: ["settings"],
165
- summary: "Read workspace settings (timezone)"
166
- }
167
- }, async (req) => workspaceSettingsResponse(req.scope, ctx.db));
168
- app.patch("/v1/settings/workspace", {
169
- config: { rateLimit: { max: 30, timeWindow: "1 hour" } },
170
- schema: {
171
- tags: ["settings"],
172
- summary: "Update workspace settings (timezone)",
173
- body: UpdateWorkspaceSettingsInput
174
- }
175
- }, async (req) => {
176
- const body = UpdateWorkspaceSettingsInput.parse(req.body);
177
- await updateWorkspaceSettings(req.scope, ctx.db, body);
178
- return workspaceSettingsResponse(req.scope, ctx.db);
179
- });
180
- // ----- context -----
181
- app.get("/v1/context", {
182
- schema: {
183
- tags: ["context"],
184
- summary: "Server time, workspace timezone, version, and project list for agent date-math"
185
- }
186
- }, async (req) => {
187
- const [settings, projects] = await Promise.all([
188
- getWorkspaceSettings(req.scope, ctx.db),
189
- listProjects(req.scope, ctx.db, { includeArchived: false })
190
- ]);
191
- return {
192
- now: new Date().toISOString(),
193
- timezone: settings.timezone,
194
- version: VERSION,
195
- projects: projects.map((p) => ({ key: p.key, name: p.name, status: p.status }))
196
- };
197
- });
198
- // ----- projects -----
199
- app.post("/v1/projects", { schema: { tags: ["projects"], summary: "Create a project", body: CreateProjectInput } }, async (req) => createProject(req.scope, ctx.db, CreateProjectInput.parse(req.body)));
200
- app.get("/v1/projects", {
201
- schema: {
202
- tags: ["projects"],
203
- summary: "List non-archived projects",
204
- querystring: ListProjectsQuery
205
- }
206
- }, async (req) => {
207
- const query = ListProjectsInput.parse(ListProjectsQuery.parse(req.query));
208
- return listProjects(req.scope, ctx.db, query);
209
- });
210
- app.get("/v1/projects/:id", { schema: { tags: ["projects"], summary: "Fetch a project by id (includes AGENTS.md)", params: IdParams } }, async (req, reply) => {
211
- const { id } = IdParams.parse(req.params);
212
- const p = await getProject(req.scope, ctx.db, id);
213
- if (!p)
214
- return reply.code(404).send({ error: "not_found" });
215
- return p;
216
- });
217
- app.patch("/v1/projects/:id", {
218
- schema: {
219
- tags: ["projects"],
220
- summary: "Update project (status, name, color, icon, agents_md)",
221
- params: IdParams,
222
- body: UpdateProjectInput
223
- }
224
- }, async (req) => {
225
- const { id } = IdParams.parse(req.params);
226
- const body = UpdateProjectInput.parse(req.body);
227
- return updateProject(req.scope, ctx.db, id, body);
228
- });
229
- app.get("/v1/projects/by-key/:key", { schema: { tags: ["projects"], summary: "Fetch a project by key", params: KeyParams } }, async (req, reply) => {
230
- const { key } = KeyParams.parse(req.params);
231
- const p = await getProjectByKey(req.scope, ctx.db, key);
232
- if (!p)
233
- return reply.code(404).send({ error: "not_found" });
234
- return p;
235
- });
236
- app.post("/v1/projects/:id/opening-brief", {
237
- schema: {
238
- tags: ["brief"],
239
- summary: "Opening brief for a project",
240
- description: "Returns the agent context bundle: AGENTS.md, pinned notes, open tasks, and recent activity. Also returns a markdown-formatted version.",
241
- params: IdParams,
242
- body: OpeningBriefBody
243
- }
244
- }, async (req) => {
245
- const { id } = IdParams.parse(req.params);
246
- const bodyOpts = OpeningBriefBody.parse(req.body);
247
- const input = OpeningBriefInput.parse({ projectId: id, recentLimit: bodyOpts?.recentLimit });
248
- const brief = await openingBrief(req.scope, ctx.db, input);
249
- return {
250
- ...brief,
251
- pinnedNotes: serializeEntities(brief.pinnedNotes),
252
- openTasks: serializeEntities(brief.openTasks),
253
- latestComments: serializeEntities(brief.latestComments),
254
- recent: serializeEntities(brief.recent),
255
- markdown: formatOpeningBrief(brief)
256
- };
257
- });
258
- // Workspace-or-project opening brief. The path-param variant above is kept
259
- // for clients that already integrate against it; the MCP HTTP client and
260
- // new plugin code uses this single entry point and passes projectId in the
261
- // body (or omits it for a workspace-wide brief).
262
- app.post("/v1/opening-brief", {
263
- schema: {
264
- tags: ["brief"],
265
- summary: "Opening brief (project-scoped or workspace-wide)",
266
- body: OpeningBriefInput.partial().optional()
267
- }
268
- }, async (req) => {
269
- const input = OpeningBriefInput.parse(req.body ?? {});
270
- const brief = await openingBrief(req.scope, ctx.db, input);
271
- return {
272
- ...brief,
273
- pinnedNotes: serializeEntities(brief.pinnedNotes),
274
- openTasks: serializeEntities(brief.openTasks),
275
- latestComments: serializeEntities(brief.latestComments),
276
- recent: serializeEntities(brief.recent),
277
- markdown: formatOpeningBrief(brief)
278
- };
279
- });
280
- // ----- entities (read) -----
281
- app.get("/v1/entities/:id", { schema: { tags: ["entities"], summary: "Fetch an entity by id", params: EntityIdParams } }, async (req, reply) => {
282
- const { id } = EntityIdParams.parse(req.params);
283
- const e = await get(req.scope, ctx.db, id);
284
- if (!e)
285
- return reply.code(404).send({ error: "not_found" });
286
- await bumpAccess(req.scope, ctx.db, e.id);
287
- return serializeEntity(e);
288
- });
289
- app.get("/v1/projects/by-key/:key/entities/by-seq/:seq", {
290
- schema: {
291
- tags: ["entities"],
292
- summary: "Fetch an entity by its human-readable identifier (e.g. DEMO-12)",
293
- params: KeySeqParams
294
- }
295
- }, async (req, reply) => {
296
- const { key, seq } = KeySeqParams.parse(req.params);
297
- const e = await getByKey(req.scope, ctx.db, key, seq);
298
- if (!e)
299
- return reply.code(404).send({ error: "not_found" });
300
- await bumpAccess(req.scope, ctx.db, e.id);
301
- return serializeEntity(e);
302
- });
303
- app.get("/v1/entities/:id/revisions", {
304
- schema: {
305
- tags: ["entities"],
306
- summary: "Content history, newest first: each row is the title/body/tags/priority/status before one update, with who made that update",
307
- params: EntityIdParams
308
- }
309
- }, async (req, reply) => {
310
- const { id } = EntityIdParams.parse(req.params);
311
- const rows = await listRevisions(req.scope, ctx.db, id);
312
- if (!rows)
313
- return reply.code(404).send({ error: "not_found" });
314
- return rows;
315
- });
316
- app.get("/v1/entities/:id/related", {
317
- schema: {
318
- tags: ["entities"],
319
- summary: "List entities whose parent_id is this id (e.g. notes linked to a task)",
320
- params: EntityIdParams
321
- }
322
- }, async (req) => {
323
- const { id } = EntityIdParams.parse(req.params);
324
- return serializeEntities(await listRelated(req.scope, ctx.db, id));
325
- });
326
- app.get("/v1/entities/:id/children", {
327
- schema: {
328
- tags: ["entities"],
329
- summary: "List child work items (subtasks/notes) of an entity, via parentId or parent_of edges; comments excluded",
330
- params: EntityIdParams
331
- }
332
- }, async (req) => {
333
- const { id } = EntityIdParams.parse(req.params);
334
- return serializeEntities(await listChildren(req.scope, ctx.db, id));
335
- });
336
- app.post("/v1/recent", {
337
- schema: {
338
- tags: ["entities"],
339
- summary: "Recent entities (filterable by project, kinds, since)",
340
- body: RecentInput.optional()
341
- }
342
- }, async (req) => {
343
- const rows = await recent(req.scope, ctx.db, RecentInput.parse(req.body ?? {}));
344
- return serializeEntities(await attachHierarchy(req.scope, ctx.db, rows));
345
- });
346
- app.post("/v1/search", {
347
- schema: {
348
- tags: ["search"],
349
- summary: "Hybrid retrieval (BM25 + cosine + time decay, RRF merged)",
350
- description: "If OPENAI_API_KEY is set, the query is embedded and cosine similarity is merged in via RRF. Otherwise BM25-only.",
351
- body: SearchInput
352
- }
353
- }, async (req) => {
354
- const body = SearchInput.parse(req.body);
355
- const queryEmbedding = await ctx.embedding.embedQuery(body.query);
356
- const hits = await search(req.scope, ctx.db, body, queryEmbedding ? { queryEmbedding } : {});
357
- return {
358
- hits: hits.map((h) => ({ ...h, entity: serializeEntity(h.entity) })),
359
- embeddingUsed: queryEmbedding != null
360
- };
361
- });
362
- app.post("/v1/tasks/range", {
363
- schema: {
364
- tags: ["tasks"],
365
- summary: "Tasks in a date range + overdue + backlog (no due_at)",
366
- description: "Returns three buckets: scheduled (display date in [from, to)), overdue (unfinished due_at before from, or before now when from is omitted), backlog (no due_at, only when includeBacklog).",
367
- body: TasksRangeInput
368
- }
369
- }, async (req) => {
370
- const result = await tasksRange(req.scope, ctx.db, TasksRangeInput.parse(req.body));
371
- return {
372
- scheduled: serializeEntities(result.scheduled),
373
- overdue: serializeEntities(result.overdue),
374
- backlog: serializeEntities(result.backlog),
375
- virtualOccurrences: result.virtualOccurrences
376
- };
377
- });
378
- app.post("/v1/tasks/:id/recurrence", {
379
- schema: {
380
- tags: ["recurrence"],
381
- summary: "Configure recurrence on a task",
382
- params: IdParams,
383
- body: RecurrenceInput
384
- }
385
- }, async (req) => {
386
- const { id } = IdParams.parse(req.params);
387
- const body = RecurrenceInput.parse(req.body);
388
- return createRecurrenceRule(req.scope, ctx.db, id, body);
389
- });
390
- app.get("/v1/tasks/:id/recurrence", {
391
- schema: {
392
- tags: ["recurrence"],
393
- summary: "Read recurrence for a task",
394
- params: IdParams
395
- }
396
- }, async (req, reply) => {
397
- const { id } = IdParams.parse(req.params);
398
- const recurrence = await getRecurrenceForTask(req.scope, ctx.db, id);
399
- if (!recurrence) {
400
- reply.code(404);
401
- return { error: "not_found", path: req.url };
402
- }
403
- return {
404
- ...recurrence,
405
- currentOccurrence: recurrence.currentOccurrence
406
- ? serializeEntity(recurrence.currentOccurrence)
407
- : null
408
- };
409
- });
410
- app.patch("/v1/recurrences/:id", {
411
- schema: {
412
- tags: ["recurrence"],
413
- summary: "Update a recurrence rule",
414
- params: RuleIdParams,
415
- body: UpdateRecurrenceInput
416
- }
417
- }, async (req) => {
418
- const { id } = RuleIdParams.parse(req.params);
419
- const body = UpdateRecurrenceInput.parse(req.body);
420
- return updateRecurrenceRule(req.scope, ctx.db, id, body);
421
- });
422
- app.post("/v1/tasks/:id/skip-occurrence", {
423
- schema: {
424
- tags: ["recurrence"],
425
- summary: "Skip the current recurring occurrence and create the next one",
426
- params: IdParams,
427
- body: SkipOccurrenceInput.optional()
428
- }
429
- }, async (req) => {
430
- const { id } = IdParams.parse(req.params);
431
- const body = SkipOccurrenceInput.parse(req.body ?? {});
432
- const result = await skipOccurrence(req.scope, ctx.db, id, body);
433
- return {
434
- ...result,
435
- skipped: serializeEntity(result.skipped),
436
- next: result.next ? serializeEntity(result.next) : null
437
- };
438
- });
439
- app.post("/v1/recurrences/:id/stop", {
440
- schema: {
441
- tags: ["recurrence"],
442
- summary: "Stop a recurrence series",
443
- params: RuleIdParams,
444
- body: StopRecurrenceInput.optional()
445
- }
446
- }, async (req) => {
447
- const { id } = RuleIdParams.parse(req.params);
448
- const body = StopRecurrenceInput.parse(req.body ?? {});
449
- return stopRecurrence(req.scope, ctx.db, id, body);
450
- });
451
- app.post("/v1/recurrences/:id/split", {
452
- schema: {
453
- tags: ["recurrence"],
454
- summary: "Split a recurrence series at its current occurrence",
455
- params: RuleIdParams,
456
- body: SplitRecurrenceInput
457
- }
458
- }, async (req) => {
459
- const { id } = RuleIdParams.parse(req.params);
460
- const body = SplitRecurrenceInput.parse(req.body);
461
- return splitRecurrence(req.scope, ctx.db, id, body);
462
- });
463
- // ----- entities (write) -----
464
- app.post("/v1/tasks", {
465
- schema: {
466
- tags: ["entities"],
467
- summary: "Create a task",
468
- body: CreateTaskInput
469
- }
470
- }, async (req) => {
471
- const body = CreateTaskInput.parse(req.body);
472
- const entity = await write(req.scope, ctx.db, {
473
- ...body,
474
- kind: "task",
475
- pinned: false,
476
- actorTokenId: req.actorTokenId
477
- });
478
- if (ctx.embedding.isEnabled()) {
479
- ctx.embedding.enqueue(entity.id, `${entity.title ?? ""}\n${entity.body}`);
480
- }
481
- return serializeEntity(entity);
482
- });
483
- app.post("/v1/notes", {
484
- schema: {
485
- tags: ["entities"],
486
- summary: "Create a note (title optional; body's first line acts as the label)",
487
- body: CreateNoteInput
488
- }
489
- }, async (req, reply) => {
490
- const { supersedes, ...body } = CreateNoteInput.parse(req.body);
491
- // Resolve the supersedes target BEFORE writing so a bad reference
492
- // fails the whole request instead of leaving an orphaned note.
493
- const supersededId = supersedes ? (await get(req.scope, ctx.db, supersedes))?.id ?? null : null;
494
- if (supersedes && !supersededId) {
495
- return reply.code(404).send({ error: `supersedes target ${supersedes} not found` });
496
- }
497
- const entity = await write(req.scope, ctx.db, {
498
- ...body,
499
- kind: "note",
500
- status: "open",
501
- priority: "none",
502
- dueAt: null,
503
- actorTokenId: req.actorTokenId
504
- });
505
- if (supersededId) {
506
- await markSuperseded(req.scope, ctx.db, entity.id, supersededId);
507
- }
508
- if (ctx.embedding.isEnabled()) {
509
- ctx.embedding.enqueue(entity.id, `${entity.title ?? ""}\n${entity.body}`);
510
- }
511
- // Dedup hint: surface near-duplicate notes so the caller can decide to
512
- // supersede or update instead of accumulating parallel memories. Skipped
513
- // when the caller already declared a supersedes target.
514
- let similar = [];
515
- if (!supersededId) {
516
- const label = (entity.title ?? entity.body.split("\n")[0] ?? "").trim().slice(0, 200);
517
- const queryEmbedding = label ? await ctx.embedding.embedQuery(label) : null;
518
- const hits = await findSimilar(req.scope, ctx.db, {
519
- title: entity.title,
520
- body: entity.body,
521
- projectId: entity.projectId,
522
- excludeId: entity.id,
523
- queryEmbedding: queryEmbedding ?? undefined
524
- });
525
- similar = hits.map((h) => h.entity);
526
- }
527
- return { ...serializeEntity(entity), similar: serializeEntities(similar) };
528
- });
529
- app.post("/v1/entities/:id/comments", {
530
- schema: {
531
- tags: ["entities"],
532
- summary: "Append a comment (worklog entry) to a task or note",
533
- description: "Comments are append-only progress notes. The latest comment per in_progress task is surfaced in the opening brief.",
534
- params: EntityIdParams,
535
- body: CreateCommentInput
536
- }
537
- }, async (req) => {
538
- const { id } = EntityIdParams.parse(req.params);
539
- const body = CreateCommentInput.parse(req.body);
540
- const entity = await addComment(req.scope, ctx.db, id, body, {
541
- actorTokenId: req.actorTokenId
542
- });
543
- if (ctx.embedding.isEnabled()) {
544
- ctx.embedding.enqueue(entity.id, entity.body);
545
- }
546
- return serializeEntity(entity);
547
- });
548
- const ListCommentsQuery = z.object({
549
- limit: z.coerce.number().int().positive().max(500).default(50)
550
- });
551
- app.get("/v1/entities/:id/comments", {
552
- schema: {
553
- tags: ["entities"],
554
- summary: "List comments for an entity, oldest first",
555
- params: EntityIdParams,
556
- querystring: ListCommentsQuery
557
- }
558
- }, async (req) => {
559
- const { id } = EntityIdParams.parse(req.params);
560
- const query = ListCommentsQuery.parse(req.query);
561
- return serializeEntities(await listComments(req.scope, ctx.db, id, query.limit));
562
- });
563
- app.post("/v1/feedback", {
564
- schema: {
565
- tags: ["feedback"],
566
- summary: "File product feedback about botnote itself (bug/feature/friction/idea)",
567
- body: CreateFeedbackInput
568
- }
569
- }, async (req) => {
570
- const body = CreateFeedbackInput.parse(req.body);
571
- const entity = await submitFeedback(req.scope, ctx.db, body, {
572
- actorTokenId: req.actorTokenId
573
- });
574
- if (ctx.embedding.isEnabled()) {
575
- ctx.embedding.enqueue(entity.id, `${entity.title ?? ""}\n${entity.body}`);
576
- }
577
- return serializeEntity(entity);
578
- });
579
- app.get("/v1/feedback", {
580
- schema: {
581
- tags: ["feedback"],
582
- summary: "List feedback for triage, newest first",
583
- querystring: z.object({
584
- category: z.enum(["bug", "feature", "friction", "idea"]).optional(),
585
- status: z.enum(["open", "in_progress", "done", "rejected"]).optional(),
586
- limit: z.coerce.number().int().min(1).max(100).default(20)
587
- })
588
- }
589
- }, async (req) => {
590
- const query = ListFeedbackInput.parse(req.query);
591
- return serializeEntities(await listFeedback(req.scope, ctx.db, query));
592
- });
593
- app.patch("/v1/entities/:id", {
594
- schema: {
595
- tags: ["entities"],
596
- summary: "Update an entity (task or note)",
597
- params: EntityIdParams,
598
- body: UpdateInput
599
- }
600
- }, async (req) => {
601
- const { id } = EntityIdParams.parse(req.params);
602
- const fields = UpdateInput.parse(req.body);
603
- const updated = await update(req.scope, ctx.db, id, fields, {
604
- actorTokenId: req.actorTokenId
605
- });
606
- if (ctx.embedding.isEnabled() &&
607
- (fields.body !== undefined || fields.bodyAppend !== undefined || fields.title !== undefined)) {
608
- ctx.embedding.enqueue(updated.id, `${updated.title ?? ""}\n${updated.body}`);
609
- }
610
- return serializeEntity(updated);
611
- });
612
- const DeleteEntityQuery = z.object({
613
- // ?purge=true permanently deletes an already-trashed entity; without it,
614
- // delete is a soft delete (moves the entity to the trash).
615
- purge: z.coerce.boolean().optional()
616
- });
617
- app.delete("/v1/entities/:id", {
618
- schema: {
619
- tags: ["entities"],
620
- summary: "Move an entity to the trash (soft delete); ?purge=true permanently deletes a trashed entity",
621
- params: EntityIdParams,
622
- querystring: DeleteEntityQuery
623
- }
624
- }, async (req, reply) => {
625
- const { id } = EntityIdParams.parse(req.params);
626
- const query = DeleteEntityQuery.parse(req.query);
627
- const ok = query.purge ? await purge(req.scope, ctx.db, id) : await remove(req.scope, ctx.db, id);
628
- if (!ok)
629
- return reply.code(404).send({ error: "not_found" });
630
- return reply.code(204).send();
631
- });
632
- app.post("/v1/entities/:id/restore", {
633
- schema: {
634
- tags: ["entities"],
635
- summary: "Restore a trashed entity",
636
- params: EntityIdParams
637
- }
638
- }, async (req, reply) => {
639
- const { id } = EntityIdParams.parse(req.params);
640
- const restored = await restore(req.scope, ctx.db, id);
641
- if (!restored)
642
- return reply.code(404).send({ error: "not_found" });
643
- return serializeEntity(restored);
644
- });
645
- const TrashQuery = z.object({
646
- limit: z.coerce.number().int().positive().max(500).default(100)
647
- });
648
- app.get("/v1/trash", {
649
- schema: {
650
- tags: ["entities"],
651
- summary: "List trashed entities, most recently deleted first",
652
- querystring: TrashQuery
653
- }
654
- }, async (req) => {
655
- const query = TrashQuery.parse(req.query);
656
- return serializeEntities(await listTrash(req.scope, ctx.db, query.limit));
657
- });
658
- app.post("/v1/entities/:id/links", {
659
- schema: {
660
- tags: ["entities"],
661
- summary: "Link this entity to another (blocks / references / parent_of)",
662
- params: IdParams,
663
- body: LinkBody
664
- }
665
- }, async (req) => {
666
- const { id } = IdParams.parse(req.params);
667
- const body = LinkBody.parse(req.body);
668
- return link(req.scope, ctx.db, { fromId: id, toId: body.toId, kind: body.kind });
669
- });
670
- const GetLinksQuery = z.object({
671
- kind: z.enum(["blocks", "references", "parent_of"]).optional(),
672
- direction: z.enum(["outgoing", "incoming", "both"]).optional()
673
- });
674
- app.get("/v1/entities/:id/links", {
675
- schema: {
676
- tags: ["entities"],
677
- summary: "Read typed graph edges for an entity (blocks / references / parent_of)",
678
- params: IdParams,
679
- querystring: GetLinksQuery
680
- }
681
- }, async (req) => {
682
- const { id } = IdParams.parse(req.params);
683
- const query = GetLinksQuery.parse(req.query);
684
- const input = GetLinksInput.parse({ id, kind: query.kind, direction: query.direction ?? "both" });
685
- const links = await getLinks(req.scope, ctx.db, input);
686
- return links.map((l) => ({
687
- kind: l.kind,
688
- direction: l.direction,
689
- entity: serializeEntity(l.entity)
690
- }));
691
- });
692
- const ListTagsQuery = z.object({
693
- projectId: Uuid.optional()
694
- });
695
- app.get("/v1/tags", {
696
- schema: {
697
- tags: ["entities"],
698
- summary: "List distinct tags with counts across entities",
699
- querystring: ListTagsQuery
700
- }
701
- }, async (req) => {
702
- const query = ListTagsQuery.parse(req.query);
703
- const input = ListTagsInput.parse({ projectId: query.projectId ?? null });
704
- return listTags(req.scope, ctx.db, input);
705
- });
706
- // ----- auth (browser session cookie) -----
707
- const LoginBody = z.object({
708
- password: z.string().min(1).max(500)
709
- });
710
- app.post("/v1/auth/login", {
711
- // Tight cap — this is the brute-force surface.
712
- config: { rateLimit: { max: 10, timeWindow: "1 minute" } },
713
- schema: {
714
- tags: ["auth"],
715
- summary: "Master-password login. Sets httpOnly session cookie.",
716
- body: LoginBody
717
- }
718
- }, async (req, reply) => {
719
- const { password } = LoginBody.parse(req.body);
720
- const ok = verifyMasterPassword(password);
721
- if (!ok) {
722
- // Add a small constant-time penalty so timing attacks against the
723
- // env-lookup branch aren't easier than the rate limit makes them.
724
- await new Promise((r) => setTimeout(r, 300));
725
- return reply.code(401).send({ error: "invalid_password" });
726
- }
727
- const ua = req.headers["user-agent"] ?? null;
728
- const { plaintext, session } = await createSession(req.scope, ctx.db, { userAgent: ua });
729
- reply.setCookie("botnote_session", plaintext, {
730
- httpOnly: true,
731
- secure: process.env.NODE_ENV === "production",
732
- sameSite: "lax",
733
- path: "/",
734
- maxAge: 60 * 60 * 24 * 30 // 30 days
735
- });
736
- return { ok: true, expiresAt: session.expiresAt };
737
- });
738
- app.post("/v1/auth/logout", {
739
- schema: {
740
- tags: ["auth"],
741
- summary: "Clear session cookie and revoke the server-side row."
742
- }
743
- }, async (req, reply) => {
744
- const plaintext = req.cookies?.botnote_session;
745
- if (plaintext)
746
- await revokeSession(ctx.db, plaintext);
747
- reply.clearCookie("botnote_session", { path: "/" });
748
- return { ok: true };
749
- });
750
- app.get("/v1/auth/whoami", {
751
- schema: {
752
- tags: ["auth"],
753
- summary: "Confirm authentication state + how the caller got in."
754
- }
755
- }, async (req) => {
756
- // If the request reached this handler, the auth gate already passed —
757
- // via cookie, bearer, trusted loopback, or because auth is disabled.
758
- const hasCookie = !!req.cookies?.botnote_session;
759
- const hasBearer = !!req.headers.authorization;
760
- const via = hasCookie
761
- ? "cookie"
762
- : hasBearer
763
- ? "bearer"
764
- : ctx.auth.required
765
- ? "trusted_origin"
766
- : "auth_disabled";
767
- return { authenticated: true, via, origin: requestOrigin(req, ctx.auth) };
768
- });
769
- // ----- tokens -----
770
- app.get("/v1/tokens", { schema: { tags: ["tokens"], summary: "List API tokens (no hash; includes recoverable plaintext when available)" } }, async (req) => (await listTokens(req.scope, ctx.db)).map(publicToken));
771
- // Token write endpoints get a much tighter cap (30/hour per IP). These are
772
- // low-frequency operations — bumping them limits the blast radius if a token
773
- // leaks or someone hammers the create endpoint.
774
- app.post("/v1/tokens", {
775
- config: { rateLimit: { max: 30, timeWindow: "1 hour" } },
776
- schema: {
777
- tags: ["tokens"],
778
- summary: "Create a new API token (plaintext remains available for copying)",
779
- body: CreateTokenInput
780
- }
781
- }, async (req) => {
782
- const body = CreateTokenInput.parse(req.body);
783
- const { token, plaintext } = await createToken(req.scope, ctx.db, body);
784
- return { ...publicToken(token), plaintext };
785
- });
786
- app.delete("/v1/tokens/:id", {
787
- config: { rateLimit: { max: 30, timeWindow: "1 hour" } },
788
- schema: { tags: ["tokens"], summary: "Revoke an API token", params: IdParams }
789
- }, async (req, reply) => {
790
- const { id } = IdParams.parse(req.params);
791
- const ok = await revokeToken(req.scope, ctx.db, id);
792
- if (!ok)
793
- return reply.code(404).send({ error: "not_found" });
794
- return reply.code(204).send();
795
- });
796
- // Raw stream for JSON Lines bodies: the importer reads them line by line,
797
- // so a dump larger than memory never gets buffered.
798
- app.addContentTypeParser("application/x-ndjson", (_req, payload, done) => done(null, payload));
799
- app.get("/v1/export", {
800
- schema: {
801
- tags: ["transfer"],
802
- summary: "Stream the whole workspace as JSON Lines (header line, then one record per line)",
803
- querystring: ExportQuery
804
- }
805
- }, async (req, reply) => {
806
- const { vectors } = ExportQuery.parse(req.query);
807
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
808
- return reply
809
- .type("application/x-ndjson")
810
- .header("content-disposition", `attachment; filename="botnote-export-${stamp}.jsonl"`)
811
- .send(Readable.from(exportWorkspace(req.scope, ctx.db, { includeVectors: vectors })));
812
- });
813
- app.post("/v1/import", {
814
- schema: {
815
- tags: ["transfer"],
816
- summary: "Import a JSON Lines dump (content-type application/x-ndjson). Idempotent: existing ids are skipped, conflicts are reported."
817
- }
818
- }, async (req, reply) => {
819
- const body = req.body;
820
- if (!body || typeof body.pipe !== "function") {
821
- return reply.code(415).send({ error: "send the dump with content-type: application/x-ndjson" });
822
- }
823
- const lines = createInterface({ input: body, crlfDelay: Infinity });
824
- const report = await importWorkspace(req.scope, ctx.db, lines);
825
- if (report.entitiesWithoutVector > 0 && ctx.embedding.isEnabled()) {
826
- await ctx.embedding.enqueueMissing();
827
- }
828
- return report;
829
- });
830
- }
831
- //# sourceMappingURL=routes.js.map