neuralbrain 0.0.1 → 0.1.0

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 (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +3 -2
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
@@ -1,10 +1,23 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { getDb } from '../lib/db';
3
- import { resolveScope, ScopeValue } from '../lib/scope';
3
+ import { redactOptional, redactSecrets } from '../lib/redactSecrets';
4
+ import { computeNextOccurrence, normalizeUtcIso, validateRecurrence } from '../lib/recurrence';
5
+ import {
6
+ buildHierarchicalScopeSql,
7
+ classifyMatchTier,
8
+ MatchTier,
9
+ resolveScope,
10
+ ScopeValue,
11
+ } from '../lib/scope';
12
+ import { transaction } from '../lib/sqlite';
13
+ import { enqueueForEmbedding } from './embedQueueStore';
4
14
 
5
15
  export type ActionStatus = 'ready' | 'blocked' | 'in_progress' | 'done' | 'dismissed';
6
16
  export type ActionPriority = 'low' | 'normal' | 'high' | 'urgent';
7
17
 
18
+ export const ACTION_COLUMNS =
19
+ 'id, session_id, scope, project_id, user_id, agent_id, title, description, status, priority, blocked_reason, files_json, due_at, remind_at, recurrence, last_reminded_at, snooze_until, parent_action_id, created_at, updated_at, resolved_at, resolved_by_session_id';
20
+
8
21
  const VALID_STATUSES = new Set<ActionStatus>([
9
22
  'ready',
10
23
  'blocked',
@@ -25,16 +38,27 @@ export interface ActionRecord {
25
38
  session_id: string | null;
26
39
  scope: ScopeValue;
27
40
  project_id: string | null;
41
+ user_id: string | null;
42
+ agent_id: string | null;
28
43
  title: string;
29
44
  description: string | null;
30
45
  status: ActionStatus;
31
46
  priority: ActionPriority;
32
47
  blocked_reason: string | null;
33
48
  files_json: string | null;
49
+ due_at: string | null;
50
+ remind_at: string | null;
51
+ recurrence: string | null;
52
+ last_reminded_at: string | null;
53
+ snooze_until: string | null;
54
+ parent_action_id: string | null;
34
55
  created_at: string;
35
56
  updated_at: string;
36
57
  resolved_at: string | null;
37
58
  resolved_by_session_id: string | null;
59
+ match_tier?: MatchTier;
60
+ overdue?: boolean;
61
+ next_occurrence?: ActionRecord;
38
62
  }
39
63
 
40
64
  export interface CreateActionInput {
@@ -44,6 +68,10 @@ export interface CreateActionInput {
44
68
  scope?: ScopeValue;
45
69
  project_id?: string | null;
46
70
  projectId?: string | null;
71
+ user_id?: string | null;
72
+ userId?: string | null;
73
+ agent_id?: string | null;
74
+ agentId?: string | null;
47
75
  title: string;
48
76
  description?: string | null;
49
77
  status?: ActionStatus;
@@ -52,12 +80,27 @@ export interface CreateActionInput {
52
80
  blockedReason?: string | null;
53
81
  files?: string[];
54
82
  files_json?: string | null;
83
+ due_at?: string | Date | null;
84
+ dueAt?: string | Date | null;
85
+ remind_at?: string | Date | null;
86
+ remindAt?: string | Date | null;
87
+ recurrence?: string | null;
88
+ last_reminded_at?: string | Date | null;
89
+ lastRemindedAt?: string | Date | null;
90
+ snooze_until?: string | Date | null;
91
+ snoozeUntil?: string | Date | null;
92
+ parent_action_id?: string | null;
93
+ parentActionId?: string | null;
55
94
  }
56
95
 
57
96
  export interface UpdateActionPatch {
58
97
  scope?: ScopeValue;
59
98
  project_id?: string | null;
60
99
  projectId?: string | null;
100
+ user_id?: string | null;
101
+ userId?: string | null;
102
+ agent_id?: string | null;
103
+ agentId?: string | null;
61
104
  title?: string;
62
105
  description?: string | null;
63
106
  status?: ActionStatus;
@@ -66,6 +109,17 @@ export interface UpdateActionPatch {
66
109
  blockedReason?: string | null;
67
110
  files?: string[];
68
111
  files_json?: string | null;
112
+ due_at?: string | Date | null;
113
+ dueAt?: string | Date | null;
114
+ remind_at?: string | Date | null;
115
+ remindAt?: string | Date | null;
116
+ recurrence?: string | null;
117
+ last_reminded_at?: string | Date | null;
118
+ lastRemindedAt?: string | Date | null;
119
+ snooze_until?: string | Date | null;
120
+ snoozeUntil?: string | Date | null;
121
+ parent_action_id?: string | null;
122
+ parentActionId?: string | null;
69
123
  resolved_by_session_id?: string | null;
70
124
  resolvedBySessionId?: string | null;
71
125
  }
@@ -84,11 +138,81 @@ function optionalString(value: unknown, field: string): string | null {
84
138
  return value.trim() || null;
85
139
  }
86
140
 
141
+ function pickField<T>(camel: T | undefined, snake: T | undefined): T | undefined {
142
+ return camel !== undefined ? camel : snake;
143
+ }
144
+
145
+ function normalizeRecurrenceInput(raw: unknown): string | null {
146
+ if (raw === undefined || raw === null) return null;
147
+ if (typeof raw !== 'string') {
148
+ throw makeSchemaError('recurrence must be a string');
149
+ }
150
+ if (raw.trim() === '') return null;
151
+ const validated = validateRecurrence(raw);
152
+ if (!validated.ok) {
153
+ throw makeSchemaError(validated.error);
154
+ }
155
+ return validated.normalized;
156
+ }
157
+
158
+ function parseValidDate(raw: string | null | undefined): Date | null {
159
+ if (!raw) return null;
160
+ const d = new Date(raw);
161
+ return Number.isNaN(d.getTime()) ? null : d;
162
+ }
163
+
164
+ const PRIORITY_ORDER_SQL = `
165
+ CASE priority
166
+ WHEN 'urgent' THEN 0
167
+ WHEN 'high' THEN 1
168
+ WHEN 'normal' THEN 2
169
+ WHEN 'low' THEN 3
170
+ ELSE 4
171
+ END ASC
172
+ `;
173
+
174
+ function appendScopeAndUserFilters(
175
+ conditions: string[],
176
+ params: unknown[],
177
+ filters?: {
178
+ projectId?: string;
179
+ includeAncestors?: boolean;
180
+ includeChildren?: boolean;
181
+ includeGlobal?: boolean;
182
+ userId?: string;
183
+ }
184
+ ): string | null {
185
+ const projectId = typeof filters?.projectId === 'string' ? filters.projectId.trim() || null : null;
186
+ const includeGlobal = filters?.includeGlobal !== false;
187
+
188
+ if (projectId) {
189
+ const scopeSql = buildHierarchicalScopeSql({
190
+ projectId,
191
+ includeAncestors: filters?.includeAncestors ?? true,
192
+ includeChildren: filters?.includeChildren ?? false,
193
+ includeGlobal,
194
+ userId: filters?.userId,
195
+ });
196
+ conditions.push(scopeSql.clause);
197
+ params.push(...scopeSql.params);
198
+ return scopeSql.normalizedProjectId;
199
+ }
200
+
201
+ if (filters?.includeGlobal === false) {
202
+ conditions.push("scope != 'global'");
203
+ }
204
+ if (typeof filters?.userId === 'string' && filters.userId.trim() !== '') {
205
+ conditions.push('user_id = ?');
206
+ params.push(filters.userId.trim());
207
+ }
208
+ return null;
209
+ }
210
+
87
211
  /**
88
212
  * Create a new next-action record with explicit 3-state scope validation.
89
213
  */
90
214
  export function createAction(input: CreateActionInput): ActionRecord {
91
- const rawProject = input.projectId !== undefined ? input.projectId : input.project_id;
215
+ const rawProject = pickField(input.projectId, input.project_id);
92
216
  const scoped = resolveScope(input.scope, rawProject);
93
217
  if (!scoped.ok) {
94
218
  throw makeSchemaError(scoped.error);
@@ -112,77 +236,104 @@ export function createAction(input: CreateActionInput): ActionRecord {
112
236
  );
113
237
  }
114
238
 
115
- const db = getDb();
116
239
  const customId = optionalString(input.id, 'id');
117
240
  const id = customId || `act_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
118
- const rawSession = input.sessionId !== undefined ? input.sessionId : input.session_id;
119
- const sessionId = optionalString(rawSession, 'session_id');
120
- const description = optionalString(input.description, 'description');
121
- const rawBlockedReason =
122
- input.blockedReason !== undefined ? input.blockedReason : input.blocked_reason;
123
- const blockedReason = optionalString(rawBlockedReason, 'blocked_reason');
241
+ const sessionId = optionalString(pickField(input.sessionId, input.session_id), 'session_id');
242
+ const userId = optionalString(pickField(input.userId, input.user_id), 'user_id');
243
+ const agentId = optionalString(pickField(input.agentId, input.agent_id), 'agent_id');
244
+ const title = redactSecrets(input.title.trim());
245
+ const description = redactOptional(optionalString(input.description, 'description'));
246
+ const blockedReason = redactOptional(
247
+ optionalString(pickField(input.blockedReason, input.blocked_reason), 'blocked_reason')
248
+ );
124
249
  const filesJson = Array.isArray(input.files)
125
250
  ? JSON.stringify(input.files)
126
251
  : input.files_json ?? null;
252
+ const dueAt = normalizeUtcIso(pickField(input.dueAt, input.due_at), 'due_at');
253
+ const remindAt = normalizeUtcIso(pickField(input.remindAt, input.remind_at), 'remind_at');
254
+ const recurrence = normalizeRecurrenceInput(input.recurrence);
255
+ const lastRemindedAt = normalizeUtcIso(
256
+ pickField(input.lastRemindedAt, input.last_reminded_at),
257
+ 'last_reminded_at'
258
+ );
259
+ const snoozeUntil = normalizeUtcIso(
260
+ pickField(input.snoozeUntil, input.snooze_until),
261
+ 'snooze_until'
262
+ );
263
+ const parentActionId = optionalString(
264
+ pickField(input.parentActionId, input.parent_action_id),
265
+ 'parent_action_id'
266
+ );
127
267
 
128
268
  const isResolved = status === 'done' || status === 'dismissed';
269
+ const db = getDb();
129
270
 
130
- db.prepare(
131
- `
132
- INSERT INTO actions (
133
- id, session_id, scope, project_id, title, description,
134
- status, priority, blocked_reason, files_json, resolved_at
135
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CASE WHEN ? = 1 THEN datetime('now') ELSE NULL END)
136
- `
137
- ).run(
138
- id,
139
- sessionId,
140
- scoped.scope,
141
- scoped.projectId,
142
- input.title.trim(),
143
- description,
144
- status,
145
- priority,
146
- blockedReason,
147
- filesJson,
148
- isResolved ? 1 : 0
149
- );
271
+ return transaction(db, () => {
272
+ db.prepare(
273
+ `
274
+ INSERT INTO actions (
275
+ id, session_id, scope, project_id, user_id, agent_id, title, description,
276
+ status, priority, blocked_reason, files_json,
277
+ due_at, remind_at, recurrence, last_reminded_at, snooze_until, parent_action_id,
278
+ resolved_at
279
+ ) VALUES (
280
+ ?, ?, ?, ?, ?, ?, ?, ?,
281
+ ?, ?, ?, ?,
282
+ ?, ?, ?, ?, ?, ?,
283
+ CASE WHEN ? = 1 THEN datetime('now') ELSE NULL END
284
+ )
285
+ `
286
+ ).run(
287
+ id,
288
+ sessionId,
289
+ scoped.scope,
290
+ scoped.projectId,
291
+ userId,
292
+ agentId,
293
+ title,
294
+ description,
295
+ status,
296
+ priority,
297
+ blockedReason,
298
+ filesJson,
299
+ dueAt,
300
+ remindAt,
301
+ recurrence,
302
+ lastRemindedAt,
303
+ snoozeUntil,
304
+ parentActionId,
305
+ isResolved ? 1 : 0
306
+ );
150
307
 
151
- return getAction(id)!;
308
+ enqueueForEmbedding(id, 'action');
309
+ return getAction(id)!;
310
+ })();
152
311
  }
153
312
 
154
313
  export function getAction(id: string): ActionRecord | undefined {
155
314
  const db = getDb();
156
- return db.prepare('SELECT * FROM actions WHERE id = ?').get(id) as
315
+ return db.prepare(`SELECT ${ACTION_COLUMNS} FROM actions WHERE id = ?`).get(id) as
157
316
  | ActionRecord
158
317
  | undefined;
159
318
  }
160
319
 
161
320
  export function listActions(filters?: {
162
321
  projectId?: string;
322
+ includeAncestors?: boolean;
323
+ includeChildren?: boolean;
163
324
  includeGlobal?: boolean;
325
+ userId?: string;
164
326
  status?: string | string[];
165
327
  sessionId?: string;
328
+ dueOnly?: boolean;
329
+ before?: string;
166
330
  limit?: number;
167
331
  }): ActionRecord[] {
168
332
  const db = getDb();
169
333
  const conditions: string[] = [];
170
334
  const params: unknown[] = [];
171
335
 
172
- const projectId = typeof filters?.projectId === 'string' ? filters.projectId.trim() || null : null;
173
- const includeGlobal = filters?.includeGlobal !== false;
174
-
175
- if (projectId) {
176
- if (includeGlobal) {
177
- conditions.push("((project_id = ? AND scope = 'project') OR scope = 'global')");
178
- params.push(projectId);
179
- } else {
180
- conditions.push("(project_id = ? AND scope = 'project')");
181
- params.push(projectId);
182
- }
183
- } else if (filters?.includeGlobal === false) {
184
- conditions.push("scope != 'global'");
185
- }
336
+ const queryProjectId = appendScopeAndUserFilters(conditions, params, filters);
186
337
 
187
338
  if (filters?.status) {
188
339
  const statuses = Array.isArray(filters.status)
@@ -200,41 +351,133 @@ export function listActions(filters?: {
200
351
  params.push(filters.sessionId.trim());
201
352
  }
202
353
 
354
+ const beforeIso = filters?.before !== undefined ? normalizeUtcIso(filters.before, 'before') : null;
355
+ if (filters?.dueOnly === true) {
356
+ const cutoffIso = beforeIso ?? new Date().toISOString();
357
+ conditions.push("status IN ('ready', 'in_progress')");
358
+ conditions.push('((remind_at IS NOT NULL AND remind_at <= ?) OR (due_at IS NOT NULL AND due_at <= ?))');
359
+ params.push(cutoffIso, cutoffIso);
360
+ conditions.push('(snooze_until IS NULL OR snooze_until <= ?)');
361
+ params.push(cutoffIso);
362
+ } else if (beforeIso !== null) {
363
+ conditions.push('((due_at IS NOT NULL AND due_at <= ?) OR (remind_at IS NOT NULL AND remind_at <= ?))');
364
+ params.push(beforeIso, beforeIso);
365
+ }
366
+
203
367
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
204
368
  const limit = filters?.limit ?? 50;
205
369
  params.push(limit);
206
370
 
207
- return db
371
+ const rows = db
372
+ .prepare(
373
+ `
374
+ SELECT ${ACTION_COLUMNS} FROM actions
375
+ ${whereClause}
376
+ ORDER BY
377
+ ${PRIORITY_ORDER_SQL},
378
+ created_at DESC,
379
+ rowid DESC
380
+ LIMIT ?
381
+ `
382
+ )
383
+ .all(...params) as ActionRecord[];
384
+
385
+ return rows.map((row) => ({
386
+ ...row,
387
+ match_tier: classifyMatchTier(row.scope, row.project_id, queryProjectId).match_tier,
388
+ }));
389
+ }
390
+
391
+ /**
392
+ * Return due or reminded open actions ('ready' or 'in_progress') not snoozed past cutoff.
393
+ */
394
+ export function getDueActions(filters?: {
395
+ projectId?: string;
396
+ includeAncestors?: boolean;
397
+ includeChildren?: boolean;
398
+ includeGlobal?: boolean;
399
+ userId?: string;
400
+ before?: string;
401
+ unremindedOnly?: boolean;
402
+ cooldownMs?: number;
403
+ limit?: number;
404
+ }): ActionRecord[] {
405
+ const db = getDb();
406
+ const conditions: string[] = [];
407
+ const params: unknown[] = [];
408
+
409
+ const queryProjectId = appendScopeAndUserFilters(conditions, params, filters);
410
+
411
+ const nowIso = new Date().toISOString();
412
+ const beforeIso = filters?.before !== undefined ? normalizeUtcIso(filters.before, 'before') : null;
413
+ const cutoffIso = beforeIso ?? nowIso;
414
+
415
+ conditions.push("status IN ('ready', 'in_progress')");
416
+ conditions.push('((remind_at IS NOT NULL AND remind_at <= ?) OR (due_at IS NOT NULL AND due_at <= ?))');
417
+ params.push(cutoffIso, cutoffIso);
418
+ conditions.push('(snooze_until IS NULL OR snooze_until <= ?)');
419
+ params.push(cutoffIso);
420
+
421
+ if (filters?.unremindedOnly === true) {
422
+ if (filters.cooldownMs !== undefined && filters.cooldownMs !== null) {
423
+ if (
424
+ typeof filters.cooldownMs !== 'number' ||
425
+ !Number.isFinite(filters.cooldownMs) ||
426
+ filters.cooldownMs < 0
427
+ ) {
428
+ throw makeSchemaError('cooldownMs must be a non-negative finite number');
429
+ }
430
+ const cooldownCutoffIso = new Date(Date.now() - filters.cooldownMs).toISOString();
431
+ conditions.push('(last_reminded_at IS NULL OR last_reminded_at <= ?)');
432
+ params.push(cooldownCutoffIso);
433
+ } else {
434
+ conditions.push('last_reminded_at IS NULL');
435
+ }
436
+ }
437
+
438
+ const whereClause = `WHERE ${conditions.join(' AND ')}`;
439
+ const limit = filters?.limit ?? 50;
440
+ params.push(limit);
441
+
442
+ const rows = db
208
443
  .prepare(
209
444
  `
210
- SELECT * FROM actions
445
+ SELECT ${ACTION_COLUMNS} FROM actions
211
446
  ${whereClause}
212
447
  ORDER BY
213
- CASE priority
214
- WHEN 'urgent' THEN 0
215
- WHEN 'high' THEN 1
216
- WHEN 'normal' THEN 2
217
- WHEN 'low' THEN 3
218
- ELSE 4
219
- END ASC,
448
+ COALESCE(remind_at, due_at) ASC,
449
+ ${PRIORITY_ORDER_SQL},
220
450
  created_at DESC,
221
451
  rowid DESC
222
452
  LIMIT ?
223
453
  `
224
454
  )
225
455
  .all(...params) as ActionRecord[];
456
+
457
+ return rows.map((row) => ({
458
+ ...row,
459
+ match_tier: classifyMatchTier(row.scope, row.project_id, queryProjectId).match_tier,
460
+ overdue: Boolean(row.due_at && row.due_at <= nowIso),
461
+ }));
226
462
  }
227
463
 
228
464
  /**
229
- * Return open ('ready' or 'in_progress') actions for a project plus global actions.
465
+ * Return open ('ready' or 'in_progress') actions for a project (plus ancestors and global by default).
230
466
  */
231
467
  export function getReadyActions(params?: {
232
468
  projectId?: string;
469
+ includeAncestors?: boolean;
470
+ includeChildren?: boolean;
471
+ includeGlobal?: boolean;
472
+ userId?: string;
233
473
  limit?: number;
234
474
  }): ActionRecord[] {
235
475
  return listActions({
236
476
  projectId: params?.projectId,
237
- includeGlobal: true,
477
+ includeAncestors: params?.includeAncestors ?? true,
478
+ includeChildren: params?.includeChildren ?? false,
479
+ includeGlobal: params?.includeGlobal ?? true,
480
+ userId: params?.userId,
238
481
  status: ['ready', 'in_progress'],
239
482
  limit: params?.limit ?? 10,
240
483
  });
@@ -242,137 +485,365 @@ export function getReadyActions(params?: {
242
485
 
243
486
  /**
244
487
  * Update an action record. Automatically sets resolved_at when status becomes
245
- * 'done' or 'dismissed', and always updates updated_at.
488
+ * 'done' or 'dismissed', spawns the next occurrence when completing a recurring
489
+ * action, and always updates updated_at inside a single transaction.
246
490
  */
247
491
  export function updateAction(
248
492
  id: string,
249
493
  patch: UpdateActionPatch
250
494
  ): ActionRecord | undefined {
251
- const existing = getAction(id);
252
- if (!existing) return undefined;
253
-
254
- let nextScope = existing.scope;
255
- let nextProjectId = existing.project_id;
256
- if (
257
- patch.scope !== undefined ||
258
- patch.projectId !== undefined ||
259
- patch.project_id !== undefined
260
- ) {
261
- const rawScope = patch.scope !== undefined ? patch.scope : existing.scope;
262
- const rawProject =
263
- patch.projectId !== undefined
264
- ? patch.projectId
265
- : patch.project_id !== undefined
266
- ? patch.project_id
267
- : existing.project_id;
268
- const scoped = resolveScope(rawScope, rawProject);
269
- if (!scoped.ok) {
270
- throw makeSchemaError(scoped.error);
495
+ const db = getDb();
496
+
497
+ return transaction(db, () => {
498
+ const existing = getAction(id);
499
+ if (!existing) return undefined;
500
+
501
+ let nextScope = existing.scope;
502
+ let nextProjectId = existing.project_id;
503
+ if (
504
+ patch.scope !== undefined ||
505
+ patch.projectId !== undefined ||
506
+ patch.project_id !== undefined
507
+ ) {
508
+ const rawScope = patch.scope !== undefined ? patch.scope : existing.scope;
509
+ const rawProject =
510
+ patch.projectId !== undefined
511
+ ? patch.projectId
512
+ : patch.project_id !== undefined
513
+ ? patch.project_id
514
+ : existing.project_id;
515
+ const scoped = resolveScope(rawScope, rawProject);
516
+ if (!scoped.ok) {
517
+ throw makeSchemaError(scoped.error);
518
+ }
519
+ nextScope = scoped.scope;
520
+ nextProjectId = scoped.projectId;
271
521
  }
272
- nextScope = scoped.scope;
273
- nextProjectId = scoped.projectId;
274
- }
275
522
 
276
- let nextTitle = existing.title;
277
- if (patch.title !== undefined) {
278
- if (typeof patch.title !== 'string' || patch.title.trim() === '') {
279
- throw makeSchemaError('title cannot be empty');
523
+ const rawUser = pickField(patch.userId, patch.user_id);
524
+ const nextUserId = rawUser !== undefined ? optionalString(rawUser, 'user_id') : existing.user_id;
525
+
526
+ const rawAgent = pickField(patch.agentId, patch.agent_id);
527
+ const nextAgentId =
528
+ rawAgent !== undefined ? optionalString(rawAgent, 'agent_id') : existing.agent_id;
529
+
530
+ let nextTitle = existing.title;
531
+ if (patch.title !== undefined) {
532
+ if (typeof patch.title !== 'string' || patch.title.trim() === '') {
533
+ throw makeSchemaError('title cannot be empty');
534
+ }
535
+ nextTitle = redactSecrets(patch.title.trim());
280
536
  }
281
- nextTitle = patch.title.trim();
282
- }
283
537
 
284
- let nextStatus = existing.status;
285
- if (patch.status !== undefined) {
286
- if (!VALID_STATUSES.has(patch.status)) {
287
- throw makeSchemaError(
288
- `Invalid action status '${String(patch.status)}'. Must be one of: ready, blocked, in_progress, done, dismissed`
289
- );
538
+ let nextStatus = existing.status;
539
+ if (patch.status !== undefined) {
540
+ if (!VALID_STATUSES.has(patch.status)) {
541
+ throw makeSchemaError(
542
+ `Invalid action status '${String(patch.status)}'. Must be one of: ready, blocked, in_progress, done, dismissed`
543
+ );
544
+ }
545
+ nextStatus = patch.status;
546
+ }
547
+
548
+ let nextPriority = existing.priority;
549
+ if (patch.priority !== undefined) {
550
+ if (!VALID_PRIORITIES.has(patch.priority)) {
551
+ throw makeSchemaError(
552
+ `Invalid action priority '${String(patch.priority)}'. Must be one of: low, normal, high, urgent`
553
+ );
554
+ }
555
+ nextPriority = patch.priority;
290
556
  }
291
- nextStatus = patch.status;
292
- }
293
557
 
294
- let nextPriority = existing.priority;
295
- if (patch.priority !== undefined) {
296
- if (!VALID_PRIORITIES.has(patch.priority)) {
297
- throw makeSchemaError(
298
- `Invalid action priority '${String(patch.priority)}'. Must be one of: low, normal, high, urgent`
558
+ const nextDescription =
559
+ patch.description !== undefined
560
+ ? redactOptional(optionalString(patch.description, 'description'))
561
+ : existing.description;
562
+
563
+ const rawBlockedReason = pickField(patch.blockedReason, patch.blocked_reason);
564
+ const nextBlockedReason =
565
+ rawBlockedReason !== undefined
566
+ ? redactOptional(optionalString(rawBlockedReason, 'blocked_reason'))
567
+ : existing.blocked_reason;
568
+
569
+ const nextFilesJson = Array.isArray(patch.files)
570
+ ? JSON.stringify(patch.files)
571
+ : patch.files_json !== undefined
572
+ ? optionalString(patch.files_json, 'files_json')
573
+ : existing.files_json;
574
+
575
+ const rawDueAt = pickField(patch.dueAt, patch.due_at);
576
+ const nextDueAt =
577
+ rawDueAt !== undefined ? normalizeUtcIso(rawDueAt, 'due_at') : existing.due_at;
578
+
579
+ const rawRemindAt = pickField(patch.remindAt, patch.remind_at);
580
+ const nextRemindAt =
581
+ rawRemindAt !== undefined ? normalizeUtcIso(rawRemindAt, 'remind_at') : existing.remind_at;
582
+
583
+ const nextRecurrence =
584
+ patch.recurrence !== undefined
585
+ ? normalizeRecurrenceInput(patch.recurrence)
586
+ : existing.recurrence;
587
+
588
+ const rawLastRemindedAt = pickField(patch.lastRemindedAt, patch.last_reminded_at);
589
+ const nextLastRemindedAt =
590
+ rawLastRemindedAt !== undefined
591
+ ? normalizeUtcIso(rawLastRemindedAt, 'last_reminded_at')
592
+ : existing.last_reminded_at;
593
+
594
+ const rawSnoozeUntil = pickField(patch.snoozeUntil, patch.snooze_until);
595
+ const nextSnoozeUntil =
596
+ rawSnoozeUntil !== undefined
597
+ ? normalizeUtcIso(rawSnoozeUntil, 'snooze_until')
598
+ : existing.snooze_until;
599
+
600
+ const rawParentActionId = pickField(patch.parentActionId, patch.parent_action_id);
601
+ const nextParentActionId =
602
+ rawParentActionId !== undefined
603
+ ? optionalString(rawParentActionId, 'parent_action_id')
604
+ : existing.parent_action_id;
605
+
606
+ const rawResolvedBy = pickField(patch.resolvedBySessionId, patch.resolved_by_session_id);
607
+ const nextResolvedBy =
608
+ rawResolvedBy !== undefined
609
+ ? optionalString(rawResolvedBy, 'resolved_by_session_id')
610
+ : existing.resolved_by_session_id;
611
+
612
+ const shouldSetResolvedAt =
613
+ (nextStatus === 'done' || nextStatus === 'dismissed') &&
614
+ existing.status !== 'done' &&
615
+ existing.status !== 'dismissed';
616
+
617
+ const shouldClearResolvedAt =
618
+ nextStatus !== 'done' &&
619
+ nextStatus !== 'dismissed' &&
620
+ (existing.status === 'done' || existing.status === 'dismissed');
621
+
622
+ db.prepare(
623
+ `
624
+ UPDATE actions
625
+ SET scope = ?,
626
+ project_id = ?,
627
+ user_id = ?,
628
+ agent_id = ?,
629
+ title = ?,
630
+ description = ?,
631
+ status = ?,
632
+ priority = ?,
633
+ blocked_reason = ?,
634
+ files_json = ?,
635
+ due_at = ?,
636
+ remind_at = ?,
637
+ recurrence = ?,
638
+ last_reminded_at = ?,
639
+ snooze_until = ?,
640
+ parent_action_id = ?,
641
+ resolved_by_session_id = ?,
642
+ resolved_at = CASE
643
+ WHEN ? = 1 THEN datetime('now')
644
+ WHEN ? = 1 THEN NULL
645
+ ELSE resolved_at
646
+ END,
647
+ updated_at = datetime('now')
648
+ WHERE id = ?
649
+ `
650
+ ).run(
651
+ nextScope,
652
+ nextProjectId,
653
+ nextUserId,
654
+ nextAgentId,
655
+ nextTitle,
656
+ nextDescription,
657
+ nextStatus,
658
+ nextPriority,
659
+ nextBlockedReason,
660
+ nextFilesJson,
661
+ nextDueAt,
662
+ nextRemindAt,
663
+ nextRecurrence,
664
+ nextLastRemindedAt,
665
+ nextSnoozeUntil,
666
+ nextParentActionId,
667
+ nextResolvedBy,
668
+ shouldSetResolvedAt ? 1 : 0,
669
+ shouldClearResolvedAt ? 1 : 0,
670
+ id
671
+ );
672
+
673
+ const textOrRankChanged =
674
+ nextTitle !== existing.title ||
675
+ nextDescription !== existing.description ||
676
+ nextBlockedReason !== existing.blocked_reason ||
677
+ nextStatus !== existing.status ||
678
+ nextPriority !== existing.priority;
679
+
680
+ if (textOrRankChanged) {
681
+ enqueueForEmbedding(id, 'action');
682
+ }
683
+
684
+ let nextOccurrence: ActionRecord | undefined;
685
+ if (nextStatus === 'done' && existing.status !== 'done' && nextRecurrence) {
686
+ const now = new Date();
687
+ const dueDate = parseValidDate(nextDueAt);
688
+ const remindDate = parseValidDate(nextRemindAt);
689
+ let spawnedDueAt: string | null = null;
690
+ let spawnedRemindAt: string | null = null;
691
+
692
+ if (dueDate && remindDate) {
693
+ const leadMs = dueDate.getTime() - remindDate.getTime();
694
+ const nextDue = computeNextOccurrence(nextRecurrence, dueDate);
695
+ spawnedDueAt = nextDue.toISOString();
696
+ spawnedRemindAt = new Date(nextDue.getTime() - leadMs).toISOString();
697
+ } else if (dueDate) {
698
+ spawnedDueAt = computeNextOccurrence(nextRecurrence, dueDate).toISOString();
699
+ } else if (remindDate) {
700
+ spawnedRemindAt = computeNextOccurrence(nextRecurrence, remindDate).toISOString();
701
+ } else {
702
+ spawnedDueAt = computeNextOccurrence(nextRecurrence, now).toISOString();
703
+ }
704
+
705
+ const spawnedId = `act_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
706
+ db.prepare(
707
+ `
708
+ INSERT INTO actions (
709
+ id, session_id, scope, project_id, user_id, agent_id, title, description,
710
+ status, priority, blocked_reason, files_json,
711
+ due_at, remind_at, recurrence, last_reminded_at, snooze_until, parent_action_id
712
+ ) VALUES (
713
+ ?, ?, ?, ?, ?, ?, ?, ?,
714
+ 'ready', ?, NULL, ?,
715
+ ?, ?, ?, NULL, NULL, ?
716
+ )
717
+ `
718
+ ).run(
719
+ spawnedId,
720
+ existing.session_id,
721
+ nextScope,
722
+ nextProjectId,
723
+ nextUserId,
724
+ nextAgentId,
725
+ nextTitle,
726
+ nextDescription,
727
+ nextPriority,
728
+ nextFilesJson,
729
+ spawnedDueAt,
730
+ spawnedRemindAt,
731
+ nextRecurrence,
732
+ existing.id
299
733
  );
734
+
735
+ enqueueForEmbedding(spawnedId, 'action');
736
+ nextOccurrence = getAction(spawnedId)!;
300
737
  }
301
- nextPriority = patch.priority;
302
- }
303
738
 
304
- const nextDescription =
305
- patch.description !== undefined
306
- ? optionalString(patch.description, 'description')
307
- : existing.description;
308
-
309
- const rawBlockedReason =
310
- patch.blockedReason !== undefined ? patch.blockedReason : patch.blocked_reason;
311
- const nextBlockedReason =
312
- rawBlockedReason !== undefined
313
- ? optionalString(rawBlockedReason, 'blocked_reason')
314
- : existing.blocked_reason;
315
-
316
- const nextFilesJson = Array.isArray(patch.files)
317
- ? JSON.stringify(patch.files)
318
- : patch.files_json !== undefined
319
- ? optionalString(patch.files_json, 'files_json')
320
- : existing.files_json;
321
-
322
- const rawResolvedBy =
323
- patch.resolvedBySessionId !== undefined
324
- ? patch.resolvedBySessionId
325
- : patch.resolved_by_session_id;
326
- const nextResolvedBy =
327
- rawResolvedBy !== undefined
328
- ? optionalString(rawResolvedBy, 'resolved_by_session_id')
329
- : existing.resolved_by_session_id;
330
-
331
- const shouldSetResolvedAt =
332
- (nextStatus === 'done' || nextStatus === 'dismissed') &&
333
- existing.status !== 'done' &&
334
- existing.status !== 'dismissed';
335
-
336
- const shouldClearResolvedAt =
337
- nextStatus !== 'done' &&
338
- nextStatus !== 'dismissed' &&
339
- (existing.status === 'done' || existing.status === 'dismissed');
739
+ const updated = getAction(id)!;
740
+ return nextOccurrence ? { ...updated, next_occurrence: nextOccurrence } : updated;
741
+ })();
742
+ }
340
743
 
744
+ /**
745
+ * Evaluate due unreminded actions and, unless dryRun is true, stamp last_reminded_at.
746
+ */
747
+ export function checkReminders(options?: {
748
+ projectId?: string;
749
+ includeAncestors?: boolean;
750
+ includeChildren?: boolean;
751
+ includeGlobal?: boolean;
752
+ userId?: string;
753
+ before?: string;
754
+ cooldownMs?: number;
755
+ dryRun?: boolean;
756
+ limit?: number;
757
+ }): { checked_at: string; reminders: ActionRecord[]; marked_count: number } {
341
758
  const db = getDb();
342
- db.prepare(
343
- `
344
- UPDATE actions
345
- SET scope = ?,
346
- project_id = ?,
347
- title = ?,
348
- description = ?,
349
- status = ?,
350
- priority = ?,
351
- blocked_reason = ?,
352
- files_json = ?,
353
- resolved_by_session_id = ?,
354
- resolved_at = CASE
355
- WHEN ? = 1 THEN datetime('now')
356
- WHEN ? = 1 THEN NULL
357
- ELSE resolved_at
358
- END,
359
- updated_at = datetime('now')
360
- WHERE id = ?
361
- `
362
- ).run(
363
- nextScope,
364
- nextProjectId,
365
- nextTitle,
366
- nextDescription,
367
- nextStatus,
368
- nextPriority,
369
- nextBlockedReason,
370
- nextFilesJson,
371
- nextResolvedBy,
372
- shouldSetResolvedAt ? 1 : 0,
373
- shouldClearResolvedAt ? 1 : 0,
374
- id
759
+
760
+ return transaction(db, () => {
761
+ const nowIso = new Date().toISOString();
762
+ const reminders = getDueActions({
763
+ projectId: options?.projectId,
764
+ includeAncestors: options?.includeAncestors,
765
+ includeChildren: options?.includeChildren,
766
+ includeGlobal: options?.includeGlobal,
767
+ userId: options?.userId,
768
+ before: options?.before,
769
+ unremindedOnly: true,
770
+ cooldownMs: options?.cooldownMs,
771
+ limit: options?.limit,
772
+ });
773
+
774
+ if (options?.dryRun || reminders.length === 0) {
775
+ return {
776
+ checked_at: nowIso,
777
+ reminders,
778
+ marked_count: 0,
779
+ };
780
+ }
781
+
782
+ const CHUNK_SIZE = 500;
783
+ const ids = reminders.map((r) => r.id);
784
+ let markedCount = 0;
785
+ for (let i = 0; i < ids.length; i += CHUNK_SIZE) {
786
+ const chunk = ids.slice(i, i + CHUNK_SIZE);
787
+ const placeholders = chunk.map(() => '?').join(',');
788
+ const res = db
789
+ .prepare(
790
+ `UPDATE actions SET last_reminded_at = ?, updated_at = datetime('now') WHERE id IN (${placeholders})`
791
+ )
792
+ .run(nowIso, ...chunk);
793
+ markedCount += res.changes;
794
+ }
795
+
796
+ const stamped = reminders.map((r) => ({
797
+ ...r,
798
+ last_reminded_at: nowIso,
799
+ }));
800
+
801
+ return {
802
+ checked_at: nowIso,
803
+ reminders: stamped,
804
+ marked_count: markedCount,
805
+ };
806
+ })();
807
+ }
808
+
809
+ /**
810
+ * Acknowledge delivered reminders by stamping last_reminded_at on the specified action IDs.
811
+ */
812
+ export function ackReminders(
813
+ ids: string[],
814
+ remindedAt?: string
815
+ ): { updated: number; reminded_at: string } {
816
+ if (!Array.isArray(ids)) {
817
+ throw makeSchemaError('ids must be an array of action IDs');
818
+ }
819
+
820
+ const cleanIds = Array.from(
821
+ new Set(ids.map((id) => (typeof id === 'string' ? id.trim() : '')).filter(Boolean))
375
822
  );
823
+ const remindedAtIso =
824
+ (remindedAt !== undefined ? normalizeUtcIso(remindedAt, 'reminded_at') : null) ??
825
+ new Date().toISOString();
826
+
827
+ if (cleanIds.length === 0) {
828
+ return { updated: 0, reminded_at: remindedAtIso };
829
+ }
830
+
831
+ const db = getDb();
832
+ const updated = transaction(db, () => {
833
+ const CHUNK_SIZE = 500;
834
+ let total = 0;
835
+ for (let i = 0; i < cleanIds.length; i += CHUNK_SIZE) {
836
+ const chunk = cleanIds.slice(i, i + CHUNK_SIZE);
837
+ const placeholders = chunk.map(() => '?').join(',');
838
+ const res = db
839
+ .prepare(
840
+ `UPDATE actions SET last_reminded_at = ?, updated_at = datetime('now') WHERE id IN (${placeholders})`
841
+ )
842
+ .run(remindedAtIso, ...chunk);
843
+ total += res.changes;
844
+ }
845
+ return total;
846
+ })();
376
847
 
377
- return getAction(id)!;
848
+ return { updated, reminded_at: remindedAtIso };
378
849
  }