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.
- package/README.md +26 -506
- package/dist/bin.js +28 -21
- package/dist/bin.js.map +1 -1
- package/dist/config.d.ts +0 -4
- package/dist/config.js +0 -31
- package/dist/config.js.map +1 -1
- package/dist/mcp/http-client.d.ts +6 -5
- package/dist/mcp/http-client.js +28 -4
- package/dist/mcp/http-client.js.map +1 -1
- package/dist/mcp/server.js +16 -16
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/stdio.d.ts +8 -0
- package/dist/mcp/stdio.js +46 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/package.json +8 -40
- package/dist/cli.d.ts +0 -1
- package/dist/cli.js +0 -186
- package/dist/cli.js.map +0 -1
- package/dist/db/client.d.ts +0 -14
- package/dist/db/client.js +0 -16
- package/dist/db/client.js.map +0 -1
- package/dist/db/migrate.d.ts +0 -1
- package/dist/db/migrate.js +0 -57
- package/dist/db/migrate.js.map +0 -1
- package/dist/db/migrations/0001_init.sql +0 -89
- package/dist/db/migrations/0002_tasks_due_at.sql +0 -16
- package/dist/db/migrations/0003_task_priority_and_sequence.sql +0 -45
- package/dist/db/migrations/0004_pinned.sql +0 -8
- package/dist/db/migrations/0005_nullable_title_and_parent.sql +0 -5
- package/dist/db/migrations/0006_project_color_icon.sql +0 -3
- package/dist/db/migrations/0007_tokens.sql +0 -14
- package/dist/db/migrations/0008_simplify_kinds_drop_actors.sql +0 -21
- package/dist/db/migrations/0009_sessions.sql +0 -14
- package/dist/db/migrations/0010_completed_at.sql +0 -17
- package/dist/db/migrations/0011_completed_at_backfill_fix.sql +0 -14
- package/dist/db/migrations/0012_completed_at_backfill_due.sql +0 -16
- package/dist/db/migrations/0013_due_at_noon_utc.sql +0 -13
- package/dist/db/migrations/0014_recoverable_api_tokens.sql +0 -3
- package/dist/db/migrations/0015_collapse_delayed_archived_statuses.sql +0 -18
- package/dist/db/migrations/0016_embedding_settings.sql +0 -23
- package/dist/db/migrations/0017_recurrence_rules.sql +0 -55
- package/dist/db/migrations/0018_project_archived_at.sql +0 -8
- package/dist/db/migrations/0019_project_status.sql +0 -20
- package/dist/db/migrations/0020_project_archived_status.sql +0 -20
- package/dist/db/migrations/0021_workspace_settings.sql +0 -18
- package/dist/db/migrations/0022_recurrence_split.sql +0 -13
- package/dist/db/migrations/0023_comment_kind.sql +0 -24
- package/dist/db/migrations/0024_memory_access.sql +0 -12
- package/dist/db/migrations/0025_soft_delete.sql +0 -12
- package/dist/db/migrations/0026_sequence_counter.sql +0 -61
- package/dist/db/migrations/0027_self_parent_repair.sql +0 -10
- package/dist/db/migrations/0028_workspaces.sql +0 -65
- package/dist/db/migrations/0029_drop_global_uniques.sql +0 -38
- package/dist/db/migrations/0030_entity_actor_token.sql +0 -12
- package/dist/db/migrations/0031_entity_revisions.sql +0 -19
- package/dist/db/migrations/0032_touch_respects_explicit_updated_at.sql +0 -18
- package/dist/db/schema.d.ts +0 -2023
- package/dist/db/schema.js +0 -245
- package/dist/db/schema.js.map +0 -1
- package/dist/rest/attribution.d.ts +0 -22
- package/dist/rest/attribution.js +0 -62
- package/dist/rest/attribution.js.map +0 -1
- package/dist/rest/auth.d.ts +0 -47
- package/dist/rest/auth.js +0 -116
- package/dist/rest/auth.js.map +0 -1
- package/dist/rest/routes.d.ts +0 -3
- package/dist/rest/routes.js +0 -831
- package/dist/rest/routes.js.map +0 -1
- package/dist/rest/server.d.ts +0 -28
- package/dist/rest/server.js +0 -276
- package/dist/rest/server.js.map +0 -1
- package/dist/service/blockers.d.ts +0 -37
- package/dist/service/blockers.js +0 -46
- package/dist/service/blockers.js.map +0 -1
- package/dist/service/dates.d.ts +0 -19
- package/dist/service/dates.js +0 -52
- package/dist/service/dates.js.map +0 -1
- package/dist/service/embedding.d.ts +0 -75
- package/dist/service/embedding.js +0 -318
- package/dist/service/embedding.js.map +0 -1
- package/dist/service/embedding_settings.d.ts +0 -16
- package/dist/service/embedding_settings.js +0 -82
- package/dist/service/embedding_settings.js.map +0 -1
- package/dist/service/entities.d.ts +0 -96
- package/dist/service/entities.js +0 -628
- package/dist/service/entities.js.map +0 -1
- package/dist/service/feedback.d.ts +0 -13
- package/dist/service/feedback.js +0 -50
- package/dist/service/feedback.js.map +0 -1
- package/dist/service/hierarchy.d.ts +0 -31
- package/dist/service/hierarchy.js +0 -76
- package/dist/service/hierarchy.js.map +0 -1
- package/dist/service/index.d.ts +0 -10
- package/dist/service/index.js +0 -10
- package/dist/service/index.js.map +0 -1
- package/dist/service/locks.d.ts +0 -25
- package/dist/service/locks.js +0 -34
- package/dist/service/locks.js.map +0 -1
- package/dist/service/opening_brief.d.ts +0 -24
- package/dist/service/opening_brief.js +0 -210
- package/dist/service/opening_brief.js.map +0 -1
- package/dist/service/projects.d.ts +0 -9
- package/dist/service/projects.js +0 -59
- package/dist/service/projects.js.map +0 -1
- package/dist/service/recurrence.d.ts +0 -93
- package/dist/service/recurrence.js +0 -799
- package/dist/service/recurrence.js.map +0 -1
- package/dist/service/revisions.d.ts +0 -31
- package/dist/service/revisions.js +0 -53
- package/dist/service/revisions.js.map +0 -1
- package/dist/service/scope.d.ts +0 -14
- package/dist/service/scope.js +0 -19
- package/dist/service/scope.js.map +0 -1
- package/dist/service/search.d.ts +0 -34
- package/dist/service/search.js +0 -198
- package/dist/service/search.js.map +0 -1
- package/dist/service/sessions.d.ts +0 -24
- package/dist/service/sessions.js +0 -89
- package/dist/service/sessions.js.map +0 -1
- package/dist/service/tasks.d.ts +0 -48
- package/dist/service/tasks.js +0 -354
- package/dist/service/tasks.js.map +0 -1
- package/dist/service/tokens.d.ts +0 -21
- package/dist/service/tokens.js +0 -71
- package/dist/service/tokens.js.map +0 -1
- package/dist/service/transfer.d.ts +0 -64
- package/dist/service/transfer.js +0 -629
- package/dist/service/transfer.js.map +0 -1
- package/dist/service/types.d.ts +0 -770
- package/dist/service/types.js +0 -272
- package/dist/service/types.js.map +0 -1
- package/dist/service/workspace_settings.d.ts +0 -9
- package/dist/service/workspace_settings.js +0 -49
- package/dist/service/workspace_settings.js.map +0 -1
- package/web/dist/assets/index-C0u0ZrR4.css +0 -1
- package/web/dist/assets/index-CwZxw-xa.js +0 -235
- package/web/dist/favicon.svg +0 -13
- package/web/dist/index.html +0 -22
|
@@ -1,799 +0,0 @@
|
|
|
1
|
-
import { and, asc, desc, eq, lte, or } from "drizzle-orm";
|
|
2
|
-
import rrulePkg from "rrule";
|
|
3
|
-
import { entities, recurrenceExceptions, recurrenceRules } from "../db/schema.js";
|
|
4
|
-
import { allDayDueAtInZone, normalizeDueAt } from "./dates.js";
|
|
5
|
-
import { getWorkspaceSettings } from "./workspace_settings.js";
|
|
6
|
-
const { RRule } = rrulePkg;
|
|
7
|
-
const WEEKDAYS = {
|
|
8
|
-
MO: RRule.MO,
|
|
9
|
-
TU: RRule.TU,
|
|
10
|
-
WE: RRule.WE,
|
|
11
|
-
TH: RRule.TH,
|
|
12
|
-
FR: RRule.FR,
|
|
13
|
-
SA: RRule.SA,
|
|
14
|
-
SU: RRule.SU
|
|
15
|
-
};
|
|
16
|
-
const FREQUENCIES = {
|
|
17
|
-
hourly: RRule.HOURLY,
|
|
18
|
-
daily: RRule.DAILY,
|
|
19
|
-
weekly: RRule.WEEKLY,
|
|
20
|
-
monthly: RRule.MONTHLY,
|
|
21
|
-
yearly: RRule.YEARLY
|
|
22
|
-
};
|
|
23
|
-
function metadataObject(value) {
|
|
24
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
25
|
-
return {};
|
|
26
|
-
return { ...value };
|
|
27
|
-
}
|
|
28
|
-
export function recurrenceMarker(e) {
|
|
29
|
-
const metadata = metadataObject(e.metadata);
|
|
30
|
-
if (!metadata.recurrence || typeof metadata.recurrence !== "object")
|
|
31
|
-
return null;
|
|
32
|
-
return metadata.recurrence;
|
|
33
|
-
}
|
|
34
|
-
function withRecurrenceMetadata(e, marker) {
|
|
35
|
-
return {
|
|
36
|
-
...metadataObject(e.metadata),
|
|
37
|
-
recurrence: marker
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
function normalizeRRuleText(raw) {
|
|
41
|
-
const lines = raw
|
|
42
|
-
.split(/\r?\n/)
|
|
43
|
-
.map((line) => line.trim())
|
|
44
|
-
.filter(Boolean);
|
|
45
|
-
const rruleLine = lines.find((line) => line.toUpperCase().startsWith("RRULE:")) ?? lines[0];
|
|
46
|
-
if (!rruleLine)
|
|
47
|
-
throw new Error("recurrence rule is empty");
|
|
48
|
-
return rruleLine.replace(/^RRULE:/i, "");
|
|
49
|
-
}
|
|
50
|
-
function rruleLine(rule) {
|
|
51
|
-
const line = rule
|
|
52
|
-
.toString()
|
|
53
|
-
.split(/\r?\n/)
|
|
54
|
-
.find((part) => part.startsWith("RRULE:"));
|
|
55
|
-
if (!line)
|
|
56
|
-
throw new Error("rrule did not produce an RRULE line");
|
|
57
|
-
return line.slice("RRULE:".length);
|
|
58
|
-
}
|
|
59
|
-
function buildRRuleFromInput(input, dtstart) {
|
|
60
|
-
if (input.rrule)
|
|
61
|
-
return normalizeRRuleText(input.rrule);
|
|
62
|
-
if (!input.preset)
|
|
63
|
-
throw new Error("recurrence preset is required");
|
|
64
|
-
const options = {
|
|
65
|
-
freq: FREQUENCIES[input.preset],
|
|
66
|
-
interval: input.interval,
|
|
67
|
-
dtstart
|
|
68
|
-
};
|
|
69
|
-
if (input.byWeekday?.length) {
|
|
70
|
-
options.byweekday = input.byWeekday.map((day) => WEEKDAYS[day]);
|
|
71
|
-
}
|
|
72
|
-
if (input.byMonthDay?.length)
|
|
73
|
-
options.bymonthday = input.byMonthDay;
|
|
74
|
-
if (input.bySetPos != null)
|
|
75
|
-
options.bysetpos = input.bySetPos;
|
|
76
|
-
if (input.byMonth?.length)
|
|
77
|
-
options.bymonth = input.byMonth;
|
|
78
|
-
if (input.until)
|
|
79
|
-
options.until = input.until;
|
|
80
|
-
if (input.count)
|
|
81
|
-
options.count = input.count;
|
|
82
|
-
return rruleLine(new RRule(options));
|
|
83
|
-
}
|
|
84
|
-
export function buildRRule(rule, dtstart = rule.dtstart) {
|
|
85
|
-
const parsed = RRule.parseString(rule.rrule);
|
|
86
|
-
return new RRule({ ...parsed, dtstart });
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Bound an existing RRULE with UNTIL at the fork point (used when freezing the
|
|
90
|
-
* old rule during a split). UNTIL supersedes any COUNT the rule carried.
|
|
91
|
-
*/
|
|
92
|
-
function applyUntilToRrule(rruleText, dtstart, until) {
|
|
93
|
-
const parsed = RRule.parseString(rruleText);
|
|
94
|
-
delete parsed.count;
|
|
95
|
-
parsed.until = until;
|
|
96
|
-
return rruleLine(new RRule({ ...parsed, dtstart }));
|
|
97
|
-
}
|
|
98
|
-
function maxDate(a, b) {
|
|
99
|
-
return a.getTime() >= b.getTime() ? a : b;
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Normalize a computed occurrence date for storage.
|
|
103
|
-
* - All-day rules: resolve the calendar day as seen in the rule's timezone,
|
|
104
|
-
* then snap to noon UTC (so the intended local calendar day is preserved
|
|
105
|
-
* across all UTC-offset clients).
|
|
106
|
-
* - Timed rules: use normalizeDueAt (exact-midnight-UTC -> noon-UTC heuristic).
|
|
107
|
-
*/
|
|
108
|
-
export function normalizeOccurrenceDueAt(rule, date) {
|
|
109
|
-
if (rule.allDay) {
|
|
110
|
-
return allDayDueAtInZone(date, rule.timezone) ?? normalizeDueAt(date) ?? date;
|
|
111
|
-
}
|
|
112
|
-
return normalizeDueAt(date) ?? date;
|
|
113
|
-
}
|
|
114
|
-
function countLimit(rule) {
|
|
115
|
-
return buildRRule(rule).options.count ?? null;
|
|
116
|
-
}
|
|
117
|
-
function computeNextOccurrenceAt(rule, occurrence, completedAt) {
|
|
118
|
-
const count = countLimit(rule);
|
|
119
|
-
if (count != null && rule.generatedCount >= count)
|
|
120
|
-
return null;
|
|
121
|
-
const anchor = rule.anchor === "completion" ? "completion" : "scheduled";
|
|
122
|
-
const dtstart = anchor === "completion" ? completedAt : rule.dtstart;
|
|
123
|
-
const rrule = buildRRule(rule, dtstart);
|
|
124
|
-
const scheduledBase = occurrence.dueAt ?? rule.dtstart;
|
|
125
|
-
const cursor = anchor === "completion" ? completedAt : maxDate(scheduledBase, completedAt);
|
|
126
|
-
const next = rrule.after(cursor, false);
|
|
127
|
-
return next ? normalizeOccurrenceDueAt(rule, next) : null;
|
|
128
|
-
}
|
|
129
|
-
function computeNextScheduledAfter(rule, after) {
|
|
130
|
-
const next = buildRRule(rule, rule.dtstart).after(after, false);
|
|
131
|
-
return next ? normalizeOccurrenceDueAt(rule, next) : null;
|
|
132
|
-
}
|
|
133
|
-
/** Internal fetch by id for rows already known to belong to a rule's workspace. */
|
|
134
|
-
async function fetchEntity(db, id) {
|
|
135
|
-
const rows = await db.select().from(entities).where(eq(entities.id, id)).limit(1);
|
|
136
|
-
const row = rows[0];
|
|
137
|
-
if (!row)
|
|
138
|
-
throw new Error(`entity ${id} not found`);
|
|
139
|
-
return row;
|
|
140
|
-
}
|
|
141
|
-
/** Entry-point fetch: the caller's scope decides whether the id is visible at all. */
|
|
142
|
-
function clientError(message, statusCode) {
|
|
143
|
-
const err = new Error(message);
|
|
144
|
-
err.statusCode = statusCode;
|
|
145
|
-
return err;
|
|
146
|
-
}
|
|
147
|
-
async function fetchEntityInScope(scope, db, id) {
|
|
148
|
-
const rows = await db
|
|
149
|
-
.select()
|
|
150
|
-
.from(entities)
|
|
151
|
-
.where(and(eq(entities.id, id), eq(entities.workspaceId, scope.workspaceId)))
|
|
152
|
-
.limit(1);
|
|
153
|
-
const row = rows[0];
|
|
154
|
-
if (!row)
|
|
155
|
-
throw clientError(`entity ${id} not found`, 404);
|
|
156
|
-
return row;
|
|
157
|
-
}
|
|
158
|
-
function ruleInScope(scope, ruleId) {
|
|
159
|
-
return and(eq(recurrenceRules.id, ruleId), eq(recurrenceRules.workspaceId, scope.workspaceId));
|
|
160
|
-
}
|
|
161
|
-
export async function findRuleForTask(db, task, includeDisabled = true) {
|
|
162
|
-
const marker = recurrenceMarker(task);
|
|
163
|
-
const cond = marker?.ruleId
|
|
164
|
-
? eq(recurrenceRules.id, marker.ruleId)
|
|
165
|
-
: or(eq(recurrenceRules.currentOccurrenceId, task.id), eq(recurrenceRules.seriesId, task.id));
|
|
166
|
-
const where = includeDisabled ? cond : and(cond, eq(recurrenceRules.enabled, true));
|
|
167
|
-
// A split leaves multiple rules per series (disabled history + one active),
|
|
168
|
-
// so the seriesId/currentOccurrenceId fallback can match more than one. Prefer
|
|
169
|
-
// the active rule, then the most recent. (The marker.ruleId branch is exact.)
|
|
170
|
-
const rows = await db
|
|
171
|
-
.select()
|
|
172
|
-
.from(recurrenceRules)
|
|
173
|
-
.where(where)
|
|
174
|
-
.orderBy(desc(recurrenceRules.enabled), desc(recurrenceRules.createdAt))
|
|
175
|
-
.limit(1);
|
|
176
|
-
return rows[0] ?? null;
|
|
177
|
-
}
|
|
178
|
-
export async function getRecurrenceForTask(scope, db, taskId) {
|
|
179
|
-
const task = await fetchEntityInScope(scope, db, taskId);
|
|
180
|
-
const rule = await findRuleForTask(db, task);
|
|
181
|
-
if (!rule)
|
|
182
|
-
return null;
|
|
183
|
-
const currentOccurrence = rule.currentOccurrenceId
|
|
184
|
-
? await fetchEntity(db, rule.currentOccurrenceId).catch(() => null)
|
|
185
|
-
: null;
|
|
186
|
-
return { rule, currentOccurrence };
|
|
187
|
-
}
|
|
188
|
-
export async function createRecurrenceRule(scope, db, taskId, input) {
|
|
189
|
-
const task = await fetchEntityInScope(scope, db, taskId);
|
|
190
|
-
if (task.kind !== "task")
|
|
191
|
-
throw clientError("recurrence can only be attached to tasks", 400);
|
|
192
|
-
if (task.status === "done" || task.status === "rejected") {
|
|
193
|
-
throw clientError("recurrence cannot be attached to a terminal task", 400);
|
|
194
|
-
}
|
|
195
|
-
// The series needs a first occurrence date: the task's dueAt, or an explicit
|
|
196
|
-
// dtstart which then also becomes the seed task's dueAt.
|
|
197
|
-
const dtstart = input.dtstart ? normalizeDueAt(input.dtstart) : task.dueAt;
|
|
198
|
-
if (!dtstart) {
|
|
199
|
-
throw clientError("task has no due date: set dueAt on the task or pass dtstart for the first occurrence", 400);
|
|
200
|
-
}
|
|
201
|
-
// Resolve timezone: explicit input wins; otherwise fall back to workspace tz.
|
|
202
|
-
const timezone = input.timezone ?? (await getWorkspaceSettings(scope, db)).timezone;
|
|
203
|
-
const existingRule = await findRuleForTask(db, task);
|
|
204
|
-
const seriesId = existingRule?.seriesId ?? recurrenceMarker(task)?.seriesId ?? task.id;
|
|
205
|
-
const rrule = buildRRuleFromInput(input, dtstart);
|
|
206
|
-
const nextOccurrenceRaw = buildRRule({ rrule, dtstart }).after(dtstart, false);
|
|
207
|
-
// Build a partial rule shape for normalizeOccurrenceDueAt before the DB row exists.
|
|
208
|
-
const ruleShape = { allDay: input.allDay ?? true, timezone };
|
|
209
|
-
const nextOccurrenceAt = nextOccurrenceRaw
|
|
210
|
-
? normalizeOccurrenceDueAt(ruleShape, nextOccurrenceRaw)
|
|
211
|
-
: null;
|
|
212
|
-
let rule;
|
|
213
|
-
if (existingRule) {
|
|
214
|
-
const [updated] = await db
|
|
215
|
-
.update(recurrenceRules)
|
|
216
|
-
.set({
|
|
217
|
-
currentOccurrenceId: task.id,
|
|
218
|
-
enabled: true,
|
|
219
|
-
rrule,
|
|
220
|
-
dtstart,
|
|
221
|
-
timezone,
|
|
222
|
-
allDay: input.allDay,
|
|
223
|
-
anchor: input.anchor,
|
|
224
|
-
maxInstancesAhead: 1,
|
|
225
|
-
nextOccurrenceAt,
|
|
226
|
-
endedAt: null
|
|
227
|
-
})
|
|
228
|
-
.where(eq(recurrenceRules.id, existingRule.id))
|
|
229
|
-
.returning();
|
|
230
|
-
if (!updated)
|
|
231
|
-
throw new Error(`recurrence rule ${existingRule.id} not found`);
|
|
232
|
-
rule = updated;
|
|
233
|
-
}
|
|
234
|
-
else {
|
|
235
|
-
const [inserted] = await db
|
|
236
|
-
.insert(recurrenceRules)
|
|
237
|
-
.values({
|
|
238
|
-
workspaceId: scope.workspaceId,
|
|
239
|
-
seriesId,
|
|
240
|
-
currentOccurrenceId: task.id,
|
|
241
|
-
enabled: true,
|
|
242
|
-
rrule,
|
|
243
|
-
dtstart,
|
|
244
|
-
timezone,
|
|
245
|
-
allDay: input.allDay,
|
|
246
|
-
anchor: input.anchor,
|
|
247
|
-
maxInstancesAhead: 1,
|
|
248
|
-
generatedCount: 1,
|
|
249
|
-
lastOccurrenceAt: null,
|
|
250
|
-
nextOccurrenceAt,
|
|
251
|
-
endedAt: null
|
|
252
|
-
})
|
|
253
|
-
.returning();
|
|
254
|
-
if (!inserted)
|
|
255
|
-
throw new Error("recurrence rule insert returned no row");
|
|
256
|
-
rule = inserted;
|
|
257
|
-
}
|
|
258
|
-
await db
|
|
259
|
-
.update(entities)
|
|
260
|
-
.set({
|
|
261
|
-
...(task.dueAt ? {} : { dueAt: dtstart }),
|
|
262
|
-
metadata: withRecurrenceMetadata(task, {
|
|
263
|
-
ruleId: rule.id,
|
|
264
|
-
seriesId: rule.seriesId,
|
|
265
|
-
role: "occurrence",
|
|
266
|
-
occurrenceAt: (task.dueAt ?? rule.dtstart).toISOString(),
|
|
267
|
-
occurrenceIndex: 1
|
|
268
|
-
})
|
|
269
|
-
})
|
|
270
|
-
.where(eq(entities.id, task.id));
|
|
271
|
-
return rule;
|
|
272
|
-
}
|
|
273
|
-
export async function updateRecurrenceRule(scope, db, ruleId, input) {
|
|
274
|
-
const rows = await db.select().from(recurrenceRules).where(ruleInScope(scope, ruleId)).limit(1);
|
|
275
|
-
const current = rows[0];
|
|
276
|
-
if (!current)
|
|
277
|
-
throw new Error(`recurrence rule ${ruleId} not found`);
|
|
278
|
-
const currentOccurrence = current.currentOccurrenceId
|
|
279
|
-
? await fetchEntity(db, current.currentOccurrenceId)
|
|
280
|
-
: null;
|
|
281
|
-
const dtstart = input.dtstart
|
|
282
|
-
? normalizeDueAt(input.dtstart)
|
|
283
|
-
: currentOccurrence?.dueAt ?? current.dtstart;
|
|
284
|
-
const nextRRuleInput = {
|
|
285
|
-
rrule: input.rrule ?? current.rrule,
|
|
286
|
-
preset: input.preset,
|
|
287
|
-
interval: input.interval ?? 1,
|
|
288
|
-
byWeekday: input.byWeekday,
|
|
289
|
-
byMonthDay: input.byMonthDay,
|
|
290
|
-
bySetPos: input.bySetPos,
|
|
291
|
-
byMonth: input.byMonth,
|
|
292
|
-
until: input.until,
|
|
293
|
-
count: input.count,
|
|
294
|
-
dtstart,
|
|
295
|
-
timezone: input.timezone ?? current.timezone,
|
|
296
|
-
allDay: input.allDay ?? current.allDay,
|
|
297
|
-
anchor: input.anchor ?? (current.anchor === "completion" ? "completion" : "scheduled")
|
|
298
|
-
};
|
|
299
|
-
const rrule = input.rrule || input.preset ? buildRRuleFromInput(nextRRuleInput, dtstart) : current.rrule;
|
|
300
|
-
const nextOccurrenceRaw = buildRRule({ rrule, dtstart }).after(dtstart, false);
|
|
301
|
-
const resolvedAllDay = input.allDay ?? current.allDay;
|
|
302
|
-
const resolvedTimezone = input.timezone ?? current.timezone;
|
|
303
|
-
const ruleShape = { allDay: resolvedAllDay, timezone: resolvedTimezone };
|
|
304
|
-
const nextOccurrenceAt = nextOccurrenceRaw
|
|
305
|
-
? normalizeOccurrenceDueAt(ruleShape, nextOccurrenceRaw)
|
|
306
|
-
: null;
|
|
307
|
-
const [updated] = await db
|
|
308
|
-
.update(recurrenceRules)
|
|
309
|
-
.set({
|
|
310
|
-
enabled: input.enabled ?? current.enabled,
|
|
311
|
-
rrule,
|
|
312
|
-
dtstart,
|
|
313
|
-
timezone: resolvedTimezone,
|
|
314
|
-
allDay: resolvedAllDay,
|
|
315
|
-
anchor: input.anchor ?? current.anchor,
|
|
316
|
-
nextOccurrenceAt,
|
|
317
|
-
endedAt: input.enabled === true ? null : current.endedAt
|
|
318
|
-
})
|
|
319
|
-
.where(eq(recurrenceRules.id, ruleId))
|
|
320
|
-
.returning();
|
|
321
|
-
if (!updated)
|
|
322
|
-
throw new Error(`recurrence rule ${ruleId} not found`);
|
|
323
|
-
return updated;
|
|
324
|
-
}
|
|
325
|
-
// ---------------------------------------------------------------------------
|
|
326
|
-
// Modified-exception helpers (scope='this' baseline management)
|
|
327
|
-
// ---------------------------------------------------------------------------
|
|
328
|
-
/**
|
|
329
|
-
* Find the existing 'modified' exception row for a given entity.
|
|
330
|
-
* Keyed by entityId (stable), not occurrenceAt.
|
|
331
|
-
*/
|
|
332
|
-
async function findModifiedExceptionForEntity(db, entityId) {
|
|
333
|
-
const rows = await db
|
|
334
|
-
.select({ id: recurrenceExceptions.id, metadata: recurrenceExceptions.metadata })
|
|
335
|
-
.from(recurrenceExceptions)
|
|
336
|
-
.where(and(eq(recurrenceExceptions.entityId, entityId), eq(recurrenceExceptions.action, "modified")))
|
|
337
|
-
.limit(1);
|
|
338
|
-
if (!rows[0])
|
|
339
|
-
return null;
|
|
340
|
-
const meta = rows[0].metadata;
|
|
341
|
-
return {
|
|
342
|
-
id: rows[0].id,
|
|
343
|
-
metadata: (meta && typeof meta === "object" && !Array.isArray(meta))
|
|
344
|
-
? meta
|
|
345
|
-
: {}
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
/**
|
|
349
|
-
* Upsert a 'modified' exception row recording the pre-edit (baseline) values
|
|
350
|
-
* of content fields for this occurrence. Uses earliest-wins merge: only
|
|
351
|
-
* adds a field to baseline if not already present.
|
|
352
|
-
*/
|
|
353
|
-
export async function upsertModifiedExceptionBaseline(db, rule, occurrence, preEditValues, changedFields) {
|
|
354
|
-
const existing = await findModifiedExceptionForEntity(db, occurrence.id);
|
|
355
|
-
if (existing) {
|
|
356
|
-
const existingMeta = existing.metadata;
|
|
357
|
-
const existingBaseline = (existingMeta.baseline && typeof existingMeta.baseline === "object" && !Array.isArray(existingMeta.baseline)
|
|
358
|
-
? existingMeta.baseline
|
|
359
|
-
: {});
|
|
360
|
-
const existingChangedFields = Array.isArray(existingMeta.changedFields)
|
|
361
|
-
? existingMeta.changedFields
|
|
362
|
-
: [];
|
|
363
|
-
// Merge: only add fields not already in baseline (earliest value wins)
|
|
364
|
-
const mergedBaseline = { ...existingBaseline };
|
|
365
|
-
const mergedChangedFields = new Set(existingChangedFields);
|
|
366
|
-
for (const field of changedFields) {
|
|
367
|
-
if (!(field in mergedBaseline)) {
|
|
368
|
-
mergedBaseline[field] = preEditValues[field] ?? null;
|
|
369
|
-
}
|
|
370
|
-
mergedChangedFields.add(field);
|
|
371
|
-
}
|
|
372
|
-
await db
|
|
373
|
-
.update(recurrenceExceptions)
|
|
374
|
-
.set({
|
|
375
|
-
metadata: {
|
|
376
|
-
scope: "this",
|
|
377
|
-
baseline: mergedBaseline,
|
|
378
|
-
changedFields: Array.from(mergedChangedFields),
|
|
379
|
-
actorKind: "human"
|
|
380
|
-
}
|
|
381
|
-
})
|
|
382
|
-
.where(eq(recurrenceExceptions.id, existing.id));
|
|
383
|
-
}
|
|
384
|
-
else {
|
|
385
|
-
const baseline = {};
|
|
386
|
-
for (const field of changedFields) {
|
|
387
|
-
baseline[field] = preEditValues[field] ?? null;
|
|
388
|
-
}
|
|
389
|
-
await db.insert(recurrenceExceptions).values({
|
|
390
|
-
ruleId: rule.id,
|
|
391
|
-
occurrenceAt: occurrence.dueAt ?? rule.dtstart,
|
|
392
|
-
action: "modified",
|
|
393
|
-
entityId: occurrence.id,
|
|
394
|
-
metadata: {
|
|
395
|
-
scope: "this",
|
|
396
|
-
baseline,
|
|
397
|
-
changedFields,
|
|
398
|
-
actorKind: "human"
|
|
399
|
-
}
|
|
400
|
-
});
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Remove the given fields from an existing 'modified' exception's baseline.
|
|
405
|
-
* If baseline becomes empty after removal, delete the row.
|
|
406
|
-
*/
|
|
407
|
-
export async function clearModifiedExceptionFields(db, _rule, occurrence, changedFields) {
|
|
408
|
-
const existing = await findModifiedExceptionForEntity(db, occurrence.id);
|
|
409
|
-
if (!existing)
|
|
410
|
-
return;
|
|
411
|
-
const existingMeta = existing.metadata;
|
|
412
|
-
const existingBaseline = (existingMeta.baseline && typeof existingMeta.baseline === "object" && !Array.isArray(existingMeta.baseline)
|
|
413
|
-
? existingMeta.baseline
|
|
414
|
-
: {});
|
|
415
|
-
const existingChangedFields = Array.isArray(existingMeta.changedFields)
|
|
416
|
-
? existingMeta.changedFields
|
|
417
|
-
: [];
|
|
418
|
-
const newBaseline = { ...existingBaseline };
|
|
419
|
-
const newChangedFields = existingChangedFields.filter((f) => !changedFields.includes(f));
|
|
420
|
-
for (const field of changedFields) {
|
|
421
|
-
delete newBaseline[field];
|
|
422
|
-
}
|
|
423
|
-
if (Object.keys(newBaseline).length === 0) {
|
|
424
|
-
await db.delete(recurrenceExceptions).where(eq(recurrenceExceptions.id, existing.id));
|
|
425
|
-
}
|
|
426
|
-
else {
|
|
427
|
-
await db
|
|
428
|
-
.update(recurrenceExceptions)
|
|
429
|
-
.set({
|
|
430
|
-
metadata: {
|
|
431
|
-
...existingMeta,
|
|
432
|
-
baseline: newBaseline,
|
|
433
|
-
changedFields: newChangedFields
|
|
434
|
-
}
|
|
435
|
-
})
|
|
436
|
-
.where(eq(recurrenceExceptions.id, existing.id));
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
/**
|
|
440
|
-
* Fetch the baseline stored in the 'modified' exception for the given template
|
|
441
|
-
* occurrence. Returns null if no such exception exists.
|
|
442
|
-
*/
|
|
443
|
-
async function fetchBaselineForTemplate(db, _rule, template) {
|
|
444
|
-
const existing = await findModifiedExceptionForEntity(db, template.id);
|
|
445
|
-
if (!existing)
|
|
446
|
-
return null;
|
|
447
|
-
const meta = existing.metadata;
|
|
448
|
-
if (!meta.baseline || typeof meta.baseline !== "object" || Array.isArray(meta.baseline)) {
|
|
449
|
-
return null;
|
|
450
|
-
}
|
|
451
|
-
return meta.baseline;
|
|
452
|
-
}
|
|
453
|
-
async function insertNextOccurrence(db, rule, occurrence, nextDueAt, baseline) {
|
|
454
|
-
const occurrenceIndex = rule.generatedCount + 1;
|
|
455
|
-
const idempotencyKey = `recurrence:${rule.id}:${nextDueAt.toISOString()}`;
|
|
456
|
-
const metadata = {
|
|
457
|
-
...metadataObject(occurrence.metadata),
|
|
458
|
-
recurrence: {
|
|
459
|
-
ruleId: rule.id,
|
|
460
|
-
seriesId: rule.seriesId,
|
|
461
|
-
role: "occurrence",
|
|
462
|
-
occurrenceAt: nextDueAt.toISOString(),
|
|
463
|
-
occurrenceIndex
|
|
464
|
-
}
|
|
465
|
-
};
|
|
466
|
-
const values = {
|
|
467
|
-
workspaceId: rule.workspaceId,
|
|
468
|
-
kind: "task",
|
|
469
|
-
projectId: occurrence.projectId,
|
|
470
|
-
title: baseline && "title" in baseline ? baseline.title : occurrence.title,
|
|
471
|
-
body: baseline && "body" in baseline ? (baseline.body ?? "") : occurrence.body,
|
|
472
|
-
tags: baseline && "tags" in baseline ? (baseline.tags ?? []) : occurrence.tags,
|
|
473
|
-
status: "open",
|
|
474
|
-
parentId: occurrence.parentId,
|
|
475
|
-
actorKind: "system",
|
|
476
|
-
metadata,
|
|
477
|
-
dueAt: nextDueAt,
|
|
478
|
-
priority: (baseline && "priority" in baseline ? baseline.priority : null) ?? occurrence.priority,
|
|
479
|
-
pinned: false,
|
|
480
|
-
completedAt: null,
|
|
481
|
-
idempotencyKey
|
|
482
|
-
};
|
|
483
|
-
const inserted = await db
|
|
484
|
-
.insert(entities)
|
|
485
|
-
.values(values)
|
|
486
|
-
.onConflictDoNothing()
|
|
487
|
-
.returning();
|
|
488
|
-
if (inserted[0])
|
|
489
|
-
return inserted[0];
|
|
490
|
-
const rows = await db
|
|
491
|
-
.select()
|
|
492
|
-
.from(entities)
|
|
493
|
-
.where(and(eq(entities.idempotencyKey, idempotencyKey), eq(entities.workspaceId, rule.workspaceId)));
|
|
494
|
-
const existing = rows[0];
|
|
495
|
-
if (!existing)
|
|
496
|
-
throw new Error("recurrence idempotent insert returned no row");
|
|
497
|
-
return existing;
|
|
498
|
-
}
|
|
499
|
-
async function advanceRuleFromOccurrence(db, rule, occurrence, completedAt) {
|
|
500
|
-
if (!rule.enabled)
|
|
501
|
-
return null;
|
|
502
|
-
const nextDueAt = computeNextOccurrenceAt(rule, occurrence, completedAt);
|
|
503
|
-
if (!nextDueAt) {
|
|
504
|
-
await db
|
|
505
|
-
.update(recurrenceRules)
|
|
506
|
-
.set({
|
|
507
|
-
enabled: false,
|
|
508
|
-
currentOccurrenceId: null,
|
|
509
|
-
lastOccurrenceAt: occurrence.dueAt ?? rule.dtstart,
|
|
510
|
-
nextOccurrenceAt: null,
|
|
511
|
-
endedAt: completedAt
|
|
512
|
-
})
|
|
513
|
-
.where(eq(recurrenceRules.id, rule.id));
|
|
514
|
-
return null;
|
|
515
|
-
}
|
|
516
|
-
const baseline = await fetchBaselineForTemplate(db, rule, occurrence);
|
|
517
|
-
const next = await insertNextOccurrence(db, rule, occurrence, nextDueAt, baseline ?? undefined);
|
|
518
|
-
await db
|
|
519
|
-
.update(recurrenceRules)
|
|
520
|
-
.set({
|
|
521
|
-
currentOccurrenceId: next.id,
|
|
522
|
-
generatedCount: Math.max(rule.generatedCount + 1, rule.generatedCount),
|
|
523
|
-
lastOccurrenceAt: occurrence.dueAt ?? rule.dtstart,
|
|
524
|
-
nextOccurrenceAt: nextDueAt
|
|
525
|
-
})
|
|
526
|
-
.where(eq(recurrenceRules.id, rule.id));
|
|
527
|
-
return next;
|
|
528
|
-
}
|
|
529
|
-
/**
|
|
530
|
-
* Create the occurrences every scheduled-anchor rule owes up to `upTo`.
|
|
531
|
-
*
|
|
532
|
-
* Each rule is processed in its own transaction under SELECT ... FOR UPDATE
|
|
533
|
-
* SKIP LOCKED: a concurrent pass (another daemon instance, or the startup
|
|
534
|
-
* pass overlapping the interval timer) skips rules already being advanced
|
|
535
|
-
* instead of waiting and then re-generating the same occurrences with a
|
|
536
|
-
* double-bumped generated_count.
|
|
537
|
-
*/
|
|
538
|
-
export async function materializeScheduledRecurrences(db, upTo, limit = 100) {
|
|
539
|
-
const due = () => and(eq(recurrenceRules.enabled, true), eq(recurrenceRules.anchor, "scheduled"), lte(recurrenceRules.nextOccurrenceAt, upTo));
|
|
540
|
-
const candidates = await db
|
|
541
|
-
.select({ id: recurrenceRules.id })
|
|
542
|
-
.from(recurrenceRules)
|
|
543
|
-
.where(due())
|
|
544
|
-
.orderBy(asc(recurrenceRules.nextOccurrenceAt))
|
|
545
|
-
.limit(limit);
|
|
546
|
-
const created = [];
|
|
547
|
-
for (const { id } of candidates) {
|
|
548
|
-
if (created.length >= limit)
|
|
549
|
-
break;
|
|
550
|
-
const budget = limit - created.length;
|
|
551
|
-
const batch = await db.transaction(async (tx) => {
|
|
552
|
-
const [rule] = await tx
|
|
553
|
-
.select()
|
|
554
|
-
.from(recurrenceRules)
|
|
555
|
-
.where(and(eq(recurrenceRules.id, id), due()))
|
|
556
|
-
.limit(1)
|
|
557
|
-
.for("update", { skipLocked: true });
|
|
558
|
-
if (!rule)
|
|
559
|
-
return [];
|
|
560
|
-
return materializeRule(tx, rule, upTo, budget);
|
|
561
|
-
});
|
|
562
|
-
created.push(...batch);
|
|
563
|
-
}
|
|
564
|
-
return created;
|
|
565
|
-
}
|
|
566
|
-
async function materializeRule(db, originalRule, upTo, limit) {
|
|
567
|
-
const created = [];
|
|
568
|
-
let rule = originalRule;
|
|
569
|
-
let template = await fetchEntity(db, rule.currentOccurrenceId ?? rule.seriesId).catch(() => fetchEntity(db, rule.seriesId));
|
|
570
|
-
while (rule.enabled &&
|
|
571
|
-
rule.nextOccurrenceAt &&
|
|
572
|
-
rule.nextOccurrenceAt.getTime() <= upTo.getTime() &&
|
|
573
|
-
created.length < limit) {
|
|
574
|
-
const count = countLimit(rule);
|
|
575
|
-
if (count != null && rule.generatedCount >= count) {
|
|
576
|
-
await db
|
|
577
|
-
.update(recurrenceRules)
|
|
578
|
-
.set({ nextOccurrenceAt: null })
|
|
579
|
-
.where(eq(recurrenceRules.id, rule.id));
|
|
580
|
-
break;
|
|
581
|
-
}
|
|
582
|
-
const nextDueAt = normalizeOccurrenceDueAt(rule, rule.nextOccurrenceAt);
|
|
583
|
-
const baseline = await fetchBaselineForTemplate(db, rule, template);
|
|
584
|
-
const next = await insertNextOccurrence(db, rule, template, nextDueAt, baseline ?? undefined);
|
|
585
|
-
created.push(next);
|
|
586
|
-
const generatedCount = rule.generatedCount + 1;
|
|
587
|
-
const following = count != null && generatedCount >= count ? null : computeNextScheduledAfter(rule, nextDueAt);
|
|
588
|
-
const [updated] = await db
|
|
589
|
-
.update(recurrenceRules)
|
|
590
|
-
.set({
|
|
591
|
-
currentOccurrenceId: next.id,
|
|
592
|
-
generatedCount,
|
|
593
|
-
lastOccurrenceAt: template.dueAt ?? rule.dtstart,
|
|
594
|
-
nextOccurrenceAt: following
|
|
595
|
-
})
|
|
596
|
-
.where(eq(recurrenceRules.id, rule.id))
|
|
597
|
-
.returning();
|
|
598
|
-
if (!updated)
|
|
599
|
-
break;
|
|
600
|
-
rule = updated;
|
|
601
|
-
template = next;
|
|
602
|
-
}
|
|
603
|
-
return created;
|
|
604
|
-
}
|
|
605
|
-
export async function advanceRecurrenceOnCompletion(db, occurrence, completedAt = occurrence.completedAt ?? new Date()) {
|
|
606
|
-
if (occurrence.kind !== "task")
|
|
607
|
-
return null;
|
|
608
|
-
const rule = await findRuleForTask(db, occurrence, false);
|
|
609
|
-
if (!rule)
|
|
610
|
-
return null;
|
|
611
|
-
if (rule.currentOccurrenceId && rule.currentOccurrenceId !== occurrence.id)
|
|
612
|
-
return null;
|
|
613
|
-
return advanceRuleFromOccurrence(db, rule, occurrence, completedAt);
|
|
614
|
-
}
|
|
615
|
-
export async function skipOccurrence(scope, db, taskId, input = {}) {
|
|
616
|
-
const task = await fetchEntityInScope(scope, db, taskId);
|
|
617
|
-
if (task.kind !== "task")
|
|
618
|
-
throw new Error("only tasks can be skipped");
|
|
619
|
-
const rule = await findRuleForTask(db, task, false);
|
|
620
|
-
if (!rule)
|
|
621
|
-
throw new Error("task is not an active recurring occurrence");
|
|
622
|
-
if (rule.currentOccurrenceId && rule.currentOccurrenceId !== task.id) {
|
|
623
|
-
throw new Error("only the current recurring occurrence can be skipped");
|
|
624
|
-
}
|
|
625
|
-
await db.insert(recurrenceExceptions).values({
|
|
626
|
-
ruleId: rule.id,
|
|
627
|
-
occurrenceAt: task.dueAt ?? rule.dtstart,
|
|
628
|
-
action: "skipped",
|
|
629
|
-
entityId: task.id,
|
|
630
|
-
metadata: { reason: input.reason ?? null, actorKind: input.actorKind ?? "human" }
|
|
631
|
-
});
|
|
632
|
-
const [skipped] = await db
|
|
633
|
-
.update(entities)
|
|
634
|
-
.set({
|
|
635
|
-
status: "rejected",
|
|
636
|
-
updatedAt: new Date(),
|
|
637
|
-
metadata: {
|
|
638
|
-
...metadataObject(task.metadata),
|
|
639
|
-
recurrence: recurrenceMarker(task),
|
|
640
|
-
skippedAt: new Date().toISOString(),
|
|
641
|
-
skipReason: input.reason ?? null
|
|
642
|
-
}
|
|
643
|
-
})
|
|
644
|
-
.where(eq(entities.id, task.id))
|
|
645
|
-
.returning();
|
|
646
|
-
if (!skipped)
|
|
647
|
-
throw new Error(`entity ${task.id} not found`);
|
|
648
|
-
const next = await advanceRuleFromOccurrence(db, rule, skipped, new Date());
|
|
649
|
-
return { skipped, next, rule };
|
|
650
|
-
}
|
|
651
|
-
export async function stopRecurrence(scope, db, ruleId, _input = {}) {
|
|
652
|
-
const [updated] = await db
|
|
653
|
-
.update(recurrenceRules)
|
|
654
|
-
.set({
|
|
655
|
-
enabled: false,
|
|
656
|
-
nextOccurrenceAt: null,
|
|
657
|
-
endedAt: new Date()
|
|
658
|
-
})
|
|
659
|
-
.where(ruleInScope(scope, ruleId))
|
|
660
|
-
.returning();
|
|
661
|
-
if (!updated)
|
|
662
|
-
throw new Error(`recurrence rule ${ruleId} not found`);
|
|
663
|
-
return updated;
|
|
664
|
-
}
|
|
665
|
-
/**
|
|
666
|
-
* Fork a recurrence series at its current occurrence: freeze the old rule and
|
|
667
|
-
* apply a new cadence going forward, keeping the same series so the UI still
|
|
668
|
-
* shows one continuous timeline (history + future).
|
|
669
|
-
*
|
|
670
|
-
* Mechanics:
|
|
671
|
-
* - The old rule is bounded with UNTIL at the fork point and disabled. It stays
|
|
672
|
-
* as frozen history (its already-materialized occurrences are untouched).
|
|
673
|
-
* - A new enabled rule is created sharing the SAME series_id (UI continuity)
|
|
674
|
-
* with the new RRULE. The live occurrence is kept as its template/display
|
|
675
|
-
* source.
|
|
676
|
-
* - The new rule has a distinct id, so its occurrences live in a disjoint
|
|
677
|
-
* idempotency-key space (`recurrence:<ruleId>:<dueAt>`): no duplicate or
|
|
678
|
-
* orphan occurrence can appear at the fork even if a date coincides.
|
|
679
|
-
* - Scheduled forks let the materializer grow the new rule from the first
|
|
680
|
-
* occurrence after the fork; the live occurrence stays on the old rule as the
|
|
681
|
-
* tail of history. Completion forks re-home the live occurrence onto the new
|
|
682
|
-
* rule so completing it advances the new cadence.
|
|
683
|
-
*
|
|
684
|
-
* The whole operation runs in one transaction: the old rule is disabled before
|
|
685
|
-
* the new one is inserted, so the partial-unique "one enabled rule per series"
|
|
686
|
-
* index holds at every step.
|
|
687
|
-
*/
|
|
688
|
-
export async function splitRecurrence(scope, db, ruleId, input) {
|
|
689
|
-
return db.transaction(async (tx) => {
|
|
690
|
-
const ruleRows = await tx
|
|
691
|
-
.select()
|
|
692
|
-
.from(recurrenceRules)
|
|
693
|
-
.where(ruleInScope(scope, ruleId))
|
|
694
|
-
.limit(1);
|
|
695
|
-
const oldRule = ruleRows[0];
|
|
696
|
-
if (!oldRule)
|
|
697
|
-
throw new Error(`recurrence rule ${ruleId} not found`);
|
|
698
|
-
if (!oldRule.enabled)
|
|
699
|
-
throw new Error("only an active recurrence can be split");
|
|
700
|
-
if (!oldRule.currentOccurrenceId) {
|
|
701
|
-
throw new Error("recurrence has no current occurrence to fork from");
|
|
702
|
-
}
|
|
703
|
-
const occRows = await tx
|
|
704
|
-
.select()
|
|
705
|
-
.from(entities)
|
|
706
|
-
.where(eq(entities.id, oldRule.currentOccurrenceId))
|
|
707
|
-
.limit(1);
|
|
708
|
-
const current = occRows[0];
|
|
709
|
-
if (!current)
|
|
710
|
-
throw new Error("recurrence has no current occurrence to fork from");
|
|
711
|
-
const forkAfter = current.dueAt ?? oldRule.dtstart;
|
|
712
|
-
const allDay = input.allDay ?? oldRule.allDay;
|
|
713
|
-
const timezone = input.timezone ?? oldRule.timezone;
|
|
714
|
-
const anchor = input.anchor ?? (oldRule.anchor === "completion" ? "completion" : "scheduled");
|
|
715
|
-
const ruleShape = { allDay, timezone };
|
|
716
|
-
// The forward cadence.
|
|
717
|
-
const newRrule = buildRRuleFromInput(input, forkAfter);
|
|
718
|
-
// Resolve the new rule's anchoring before mutating anything, so a bounded
|
|
719
|
-
// new rule with no occurrences after the fork fails cleanly (no half-split).
|
|
720
|
-
let dtstart;
|
|
721
|
-
let nextOccurrenceAt;
|
|
722
|
-
let generatedCount;
|
|
723
|
-
if (anchor === "completion") {
|
|
724
|
-
// Completion series advance on completion, not on a schedule; the re-homed
|
|
725
|
-
// live occurrence (below) carries the chain.
|
|
726
|
-
dtstart = forkAfter;
|
|
727
|
-
nextOccurrenceAt = null;
|
|
728
|
-
generatedCount = oldRule.generatedCount;
|
|
729
|
-
}
|
|
730
|
-
else {
|
|
731
|
-
const firstRaw = buildRRule({ rrule: newRrule, dtstart: forkAfter }).after(forkAfter, false);
|
|
732
|
-
if (!firstRaw) {
|
|
733
|
-
throw new Error("new recurrence has no occurrences after the fork point");
|
|
734
|
-
}
|
|
735
|
-
dtstart = normalizeOccurrenceDueAt(ruleShape, firstRaw);
|
|
736
|
-
nextOccurrenceAt = dtstart;
|
|
737
|
-
// The new rule has generated nothing yet — the scheduler materializes its
|
|
738
|
-
// first occurrence (index 1) at dtstart. Starting at 0 keeps COUNT on the
|
|
739
|
-
// new rule consistent with rrule expansion. UI continuity comes from the
|
|
740
|
-
// shared series_id, not from this counter.
|
|
741
|
-
generatedCount = 0;
|
|
742
|
-
}
|
|
743
|
-
// 1) Freeze the old rule. Must run before the insert so the partial-unique
|
|
744
|
-
// (one enabled rule per series) index is satisfied at every step.
|
|
745
|
-
await tx
|
|
746
|
-
.update(recurrenceRules)
|
|
747
|
-
.set({
|
|
748
|
-
enabled: false,
|
|
749
|
-
rrule: applyUntilToRrule(oldRule.rrule, oldRule.dtstart, forkAfter),
|
|
750
|
-
currentOccurrenceId: anchor === "completion" ? null : oldRule.currentOccurrenceId,
|
|
751
|
-
lastOccurrenceAt: current.dueAt ?? oldRule.dtstart,
|
|
752
|
-
nextOccurrenceAt: null,
|
|
753
|
-
endedAt: new Date()
|
|
754
|
-
})
|
|
755
|
-
.where(eq(recurrenceRules.id, oldRule.id));
|
|
756
|
-
// 2) Insert the new enabled rule, same series_id.
|
|
757
|
-
const [created] = await tx
|
|
758
|
-
.insert(recurrenceRules)
|
|
759
|
-
.values({
|
|
760
|
-
workspaceId: oldRule.workspaceId,
|
|
761
|
-
seriesId: oldRule.seriesId,
|
|
762
|
-
currentOccurrenceId: current.id,
|
|
763
|
-
enabled: true,
|
|
764
|
-
rrule: newRrule,
|
|
765
|
-
dtstart,
|
|
766
|
-
timezone,
|
|
767
|
-
allDay,
|
|
768
|
-
anchor,
|
|
769
|
-
maxInstancesAhead: 1,
|
|
770
|
-
generatedCount,
|
|
771
|
-
lastOccurrenceAt: anchor === "completion" ? oldRule.lastOccurrenceAt : null,
|
|
772
|
-
nextOccurrenceAt,
|
|
773
|
-
endedAt: null
|
|
774
|
-
})
|
|
775
|
-
.returning();
|
|
776
|
-
if (!created)
|
|
777
|
-
throw new Error("recurrence rule insert returned no row");
|
|
778
|
-
// 3) Completion fork: re-home the live occurrence onto the new rule so its
|
|
779
|
-
// completion advances the new cadence (findRuleForTask routes by the
|
|
780
|
-
// marker's ruleId). Scheduled forks leave it on the old rule as history.
|
|
781
|
-
if (anchor === "completion") {
|
|
782
|
-
const marker = recurrenceMarker(current);
|
|
783
|
-
await tx
|
|
784
|
-
.update(entities)
|
|
785
|
-
.set({
|
|
786
|
-
metadata: withRecurrenceMetadata(current, {
|
|
787
|
-
ruleId: created.id,
|
|
788
|
-
seriesId: created.seriesId,
|
|
789
|
-
role: "occurrence",
|
|
790
|
-
occurrenceAt: marker?.occurrenceAt ?? (current.dueAt ?? created.dtstart).toISOString(),
|
|
791
|
-
occurrenceIndex: marker?.occurrenceIndex ?? created.generatedCount
|
|
792
|
-
})
|
|
793
|
-
})
|
|
794
|
-
.where(eq(entities.id, current.id));
|
|
795
|
-
}
|
|
796
|
-
return created;
|
|
797
|
-
});
|
|
798
|
-
}
|
|
799
|
-
//# sourceMappingURL=recurrence.js.map
|