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