@ghostpaw/questlog 0.9.2 → 0.10.1

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/dist/index.js CHANGED
@@ -1,9 +1,1026 @@
1
+ import { randomBytes, createHmac } from 'node:crypto';
2
+ import { basename, extname } from 'node:path';
3
+
1
4
  var __defProp = Object.defineProperty;
2
5
  var __export = (target, all) => {
3
6
  for (var name in all)
4
7
  __defProp(target, name, { get: all[name], enumerable: true });
5
8
  };
6
9
 
10
+ // src/hooks/index.ts
11
+ var hooks_exports = {};
12
+ __export(hooks_exports, {
13
+ addHook: () => addHook,
14
+ hookEventTypes: () => hookEventTypes,
15
+ hookLabel: () => hookLabel,
16
+ listDeliveries: () => listDeliveries,
17
+ listHooks: () => listHooks,
18
+ removeHook: () => removeHook,
19
+ testHook: () => testHook,
20
+ tickQuestlog: () => tickQuestlog,
21
+ watchQuestlog: () => watchQuestlog
22
+ });
23
+
24
+ // src/tags/normalize_tag_name.ts
25
+ function normalizeTagName(name) {
26
+ return name.trim().toLowerCase().replace(/\s+/g, " ");
27
+ }
28
+
29
+ // src/hooks/types.ts
30
+ var hookEventTypes = [
31
+ "quest.due",
32
+ "quest.overdue",
33
+ "quest.unblocked",
34
+ "repeatable.spawned",
35
+ "rumor.captured"
36
+ ];
37
+
38
+ // src/hooks/add_hook.ts
39
+ function addHook(db, input) {
40
+ let url;
41
+ try {
42
+ url = new URL(input.url);
43
+ } catch {
44
+ throw new Error("Expected an HTTP or HTTPS URL");
45
+ }
46
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("Expected an HTTP or HTTPS URL");
47
+ const minGap = input.minGap ?? 60;
48
+ if (!Number.isSafeInteger(minGap) || minGap < 0)
49
+ throw new Error("Min gap must be a nonnegative integer");
50
+ const events = input.events ?? [...hookEventTypes];
51
+ if (!events.length || events.some((e) => !hookEventTypes.includes(e)))
52
+ throw new Error("Unknown event filter");
53
+ if (input.tag !== void 0 && !normalizeTagName(input.tag))
54
+ throw new Error("Expected a tag name");
55
+ const secret = input.secret ?? randomBytes(32).toString("hex");
56
+ if (!secret.trim()) throw new Error("Expected a nonempty signing secret");
57
+ const result = db.prepare(
58
+ "INSERT INTO hook_targets(url, secret, tag, events, min_gap, created_at) VALUES (?, ?, ?, ?, ?, ?)"
59
+ ).run(
60
+ url.href,
61
+ secret,
62
+ input.tag === void 0 ? null : normalizeTagName(input.tag),
63
+ JSON.stringify(events),
64
+ minGap,
65
+ input.now ?? Date.now()
66
+ );
67
+ return { id: Number(result.lastInsertRowid), secret };
68
+ }
69
+ function hookLabel(db, name) {
70
+ if (name !== void 0) {
71
+ if (!name.trim()) throw new Error("Expected a nonempty database label");
72
+ db.prepare(
73
+ "INSERT INTO hook_settings(id, label) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET label = excluded.label"
74
+ ).run(name);
75
+ }
76
+ const saved = db.prepare("SELECT label FROM hook_settings WHERE id = 1").get();
77
+ if (saved) return String(saved.label);
78
+ const path = String(
79
+ db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? ""
80
+ );
81
+ return path ? basename(path, extname(path)) : "questlog";
82
+ }
83
+
84
+ // src/hooks/list_deliveries.ts
85
+ function listDeliveries(db, options = {}) {
86
+ return db.prepare(
87
+ `SELECT * FROM hook_deliveries ${options.includeDelivered ? "" : "WHERE status <> 'delivered'"} ORDER BY target_id, next_attempt_at, id`
88
+ ).all().map(
89
+ (row) => ({
90
+ id: String(row.id),
91
+ targetId: Number(row.target_id),
92
+ events: JSON.parse(String(row.events)),
93
+ status: row.status,
94
+ attempts: Number(row.attempts),
95
+ lastAttemptAt: row.last_attempt_at == null ? null : Number(row.last_attempt_at),
96
+ httpStatus: row.http_status == null ? null : Number(row.http_status),
97
+ errorClass: row.error_class == null ? null : String(row.error_class),
98
+ nextAttemptAt: Number(row.next_attempt_at)
99
+ })
100
+ ).filter(
101
+ (d) => options.questId === void 0 || d.events.some((e) => e.questId === options.questId)
102
+ );
103
+ }
104
+
105
+ // src/hooks/list_hooks.ts
106
+ function listHooks(db) {
107
+ return db.prepare(`SELECT id, url, tag, events, min_gap, created_at, last_wake,
108
+ (SELECT COUNT(*) FROM hook_assignments a LEFT JOIN hook_deliveries d ON d.id = a.delivery_id WHERE a.target_id = t.id AND (a.delivery_id IS NULL OR d.status = 'pending')) AS pending,
109
+ (SELECT COUNT(*) FROM hook_deliveries d WHERE d.target_id = t.id AND d.status = 'failed') AS failed
110
+ FROM hook_targets t ORDER BY id`).all().map((row) => {
111
+ const url = new URL(String(row.url));
112
+ url.username = "";
113
+ url.password = "";
114
+ url.search = "";
115
+ url.hash = "";
116
+ return {
117
+ id: Number(row.id),
118
+ scope: row.tag == null ? "database" : "tag",
119
+ url: url.href,
120
+ tag: row.tag == null ? null : String(row.tag),
121
+ events: JSON.parse(String(row.events)),
122
+ minGap: Number(row.min_gap),
123
+ createdAt: Number(row.created_at),
124
+ lastWake: row.last_wake == null ? null : Number(row.last_wake),
125
+ pending: Number(row.pending),
126
+ failed: Number(row.failed)
127
+ };
128
+ });
129
+ }
130
+
131
+ // src/with_transaction.ts
132
+ var transactionDepth = /* @__PURE__ */ new WeakMap();
133
+ function withTransaction(db, fn) {
134
+ const depth = transactionDepth.get(db) ?? 0;
135
+ const savepoint = `questlog_${depth}`;
136
+ if (depth === 0) {
137
+ db.exec("BEGIN IMMEDIATE");
138
+ } else {
139
+ db.exec(`SAVEPOINT ${savepoint}`);
140
+ }
141
+ transactionDepth.set(db, depth + 1);
142
+ try {
143
+ const result = fn();
144
+ if (depth === 0) {
145
+ db.exec("COMMIT");
146
+ } else {
147
+ db.exec(`RELEASE SAVEPOINT ${savepoint}`);
148
+ }
149
+ transactionDepth.set(db, depth);
150
+ return result;
151
+ } catch (error) {
152
+ try {
153
+ if (depth === 0) {
154
+ db.exec("ROLLBACK");
155
+ } else {
156
+ db.exec(`ROLLBACK TO SAVEPOINT ${savepoint}`);
157
+ db.exec(`RELEASE SAVEPOINT ${savepoint}`);
158
+ }
159
+ } catch {
160
+ }
161
+ transactionDepth.set(db, depth);
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ // src/hooks/remove_hook.ts
167
+ function removeHook(db, id) {
168
+ withTransaction(db, () => {
169
+ db.prepare("DELETE FROM hook_assignments WHERE target_id = ?").run(id);
170
+ db.prepare("DELETE FROM hook_deliveries WHERE target_id = ?").run(id);
171
+ db.prepare("DELETE FROM hook_targets WHERE id = ?").run(id);
172
+ });
173
+ }
174
+
175
+ // src/version.ts
176
+ var questlogVersion = "0.10.1";
177
+
178
+ // src/hooks/send_hook_delivery.ts
179
+ async function sendHookDelivery(db, delivery, target, options) {
180
+ const now = options.now ?? options.clock?.() ?? Date.now();
181
+ const timestamp = String(Math.floor(now / 1e3));
182
+ const body = JSON.stringify({
183
+ type: "questlog.events",
184
+ db: hookLabel(db),
185
+ deliveryId: delivery.id,
186
+ sentAt: new Date(now).toISOString(),
187
+ events: delivery.events
188
+ });
189
+ const signature = createHmac("sha256", target.secret).update(`${timestamp}.${body}`).digest("hex");
190
+ let status = null;
191
+ let errorClass = null;
192
+ try {
193
+ const response = await (options.fetch ?? globalThis.fetch)(target.url, {
194
+ method: "POST",
195
+ redirect: "error",
196
+ headers: {
197
+ "content-type": "application/json",
198
+ "user-agent": `questlog/${questlogVersion}`,
199
+ "x-questlog-delivery": delivery.id,
200
+ "x-questlog-timestamp": timestamp,
201
+ "x-questlog-signature": `sha256=${signature}`
202
+ },
203
+ body,
204
+ signal: AbortSignal.timeout(Math.max(1, Math.min(options.timeoutMs ?? 5e3, 5e3)))
205
+ });
206
+ status = response.status;
207
+ await response.body?.cancel();
208
+ } catch (error) {
209
+ errorClass = error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name) ? error.name : "NetworkError";
210
+ }
211
+ const delivered = status != null && status >= 200 && status < 300;
212
+ const completedAt = options.now ?? options.clock?.() ?? Date.now();
213
+ withTransaction(db, () => {
214
+ if (!db.prepare("SELECT id FROM hook_targets WHERE id = ? AND claim = ?").get(target.id, target.claim))
215
+ return;
216
+ const delay = Math.min(36e5, 3e4 * 2 ** (delivery.attempts - 1));
217
+ const jitter = Number.parseInt(randomBytes(2).toString("hex"), 16) % 1e3;
218
+ db.prepare(
219
+ "UPDATE hook_deliveries SET status = ?, http_status = ?, error_class = ?, next_attempt_at = ? WHERE id = ?"
220
+ ).run(
221
+ delivered ? "delivered" : delivery.attempts >= 8 ? "failed" : "pending",
222
+ status,
223
+ errorClass,
224
+ completedAt + delay + jitter,
225
+ delivery.id
226
+ );
227
+ db.prepare(
228
+ "UPDATE hook_targets SET claim = NULL, lease_until = NULL WHERE id = ? AND claim = ?"
229
+ ).run(target.id, target.claim);
230
+ db.prepare(
231
+ "DELETE FROM hook_deliveries WHERE target_id = ? AND status = 'delivered' AND id NOT IN (SELECT id FROM hook_deliveries WHERE target_id = ? AND status = 'delivered' ORDER BY last_attempt_at DESC, id DESC LIMIT 500)"
232
+ ).run(target.id, target.id);
233
+ });
234
+ return delivered;
235
+ }
236
+
237
+ // src/hooks/test_hook.ts
238
+ async function testHook(db, id, options = {}) {
239
+ const now = options.now ?? options.clock?.() ?? Date.now();
240
+ const claim = randomBytes(16).toString("hex");
241
+ const delivery = {
242
+ id: `d_${randomBytes(16).toString("hex")}`,
243
+ targetId: id,
244
+ events: [
245
+ {
246
+ id: `e_test_${randomBytes(16).toString("hex")}`,
247
+ type: "hook.test",
248
+ occurredAt: new Date(now).toISOString()
249
+ }
250
+ ],
251
+ status: "pending",
252
+ attempts: 1,
253
+ lastAttemptAt: now,
254
+ httpStatus: null,
255
+ errorClass: null,
256
+ nextAttemptAt: now
257
+ };
258
+ const target = withTransaction(db, () => {
259
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(id);
260
+ if (!row) throw new Error("Hook not found");
261
+ if (row.lease_until != null && Number(row.lease_until) > now)
262
+ throw new Error("Hook delivery is in progress");
263
+ db.prepare(
264
+ "INSERT INTO hook_deliveries(id, target_id, events, status, attempts, last_attempt_at, next_attempt_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
265
+ ).run(delivery.id, id, JSON.stringify(delivery.events), "pending", 1, now, now);
266
+ db.prepare(
267
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
268
+ ).run(claim, now + 12e4, now, id);
269
+ return { id, url: String(row.url), secret: String(row.secret), claim };
270
+ });
271
+ return { id: delivery.id, delivered: await sendHookDelivery(db, delivery, target, options) };
272
+ }
273
+
274
+ // src/quests/map_quest_row.ts
275
+ function asBoolean(value) {
276
+ return Number(value) === 1;
277
+ }
278
+ function mapQuestRow(row) {
279
+ return {
280
+ id: Number(row.id),
281
+ questlineId: row.questline_id == null ? null : Number(row.questline_id),
282
+ sourceRumorId: row.source_rumor_id == null ? null : Number(row.source_rumor_id),
283
+ spawnedByQuestId: row.spawned_by_quest_id == null ? null : Number(row.spawned_by_quest_id),
284
+ spawnedFromRepeatableId: row.spawned_from_repeatable_id == null ? null : Number(row.spawned_from_repeatable_id),
285
+ spawnedForAt: row.spawned_for_at == null ? null : Number(row.spawned_for_at),
286
+ title: String(row.title),
287
+ objective: String(row.objective),
288
+ outcome: row.outcome == null ? null : String(row.outcome),
289
+ createdAt: Number(row.created_at),
290
+ updatedAt: Number(row.updated_at),
291
+ startedAt: row.started_at == null ? null : Number(row.started_at),
292
+ resolvedAt: row.resolved_at == null ? null : Number(row.resolved_at),
293
+ success: row.success == null ? null : asBoolean(row.success),
294
+ effortSeconds: Number(row.effort_seconds),
295
+ estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
296
+ notBeforeAt: row.not_before_at == null ? null : Number(row.not_before_at),
297
+ dueAt: row.due_at == null ? null : Number(row.due_at),
298
+ scheduledStartAt: row.scheduled_start_at == null ? null : Number(row.scheduled_start_at),
299
+ scheduledEndAt: row.scheduled_end_at == null ? null : Number(row.scheduled_end_at),
300
+ allDay: asBoolean(row.all_day),
301
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
302
+ };
303
+ }
304
+
305
+ // src/quests/get_quest_or_throw.ts
306
+ function getQuestOrThrow(db, questId) {
307
+ const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
308
+ if (!row) {
309
+ throw new Error(`Quest ${questId} was not found.`);
310
+ }
311
+ return mapQuestRow(row);
312
+ }
313
+
314
+ // src/resolve_now.ts
315
+ function resolveNow(now) {
316
+ return now ?? Date.now();
317
+ }
318
+
319
+ // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
320
+ function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
321
+ const effectiveNow = resolveNow(now);
322
+ const rows = db.prepare(
323
+ `SELECT kind, name, description, quantity
324
+ FROM repeatable_quest_rewards
325
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
326
+ ).all(repeatableQuestId);
327
+ for (const row of rows) {
328
+ db.prepare(
329
+ `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
330
+ VALUES (?, ?, ?, ?, ?, ?)`
331
+ ).run(
332
+ questId,
333
+ String(row.kind),
334
+ String(row.name),
335
+ row.description == null ? null : String(row.description),
336
+ row.quantity == null ? null : Number(row.quantity),
337
+ effectiveNow
338
+ );
339
+ }
340
+ }
341
+
342
+ // src/tags/copy_repeatable_quest_tags_to_quest.ts
343
+ function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
344
+ const effectiveNow = resolveNow(now);
345
+ const rows = db.prepare(
346
+ `SELECT tag_id
347
+ FROM repeatable_quest_tags
348
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
349
+ ).all(repeatableQuestId);
350
+ for (const row of rows) {
351
+ db.prepare(
352
+ `INSERT INTO quest_tags (quest_id, tag_id, created_at)
353
+ VALUES (?, ?, ?)`
354
+ ).run(questId, Number(row.tag_id), effectiveNow);
355
+ }
356
+ }
357
+
358
+ // src/repeatable_quests/map_repeatable_quest_row.ts
359
+ function asBoolean2(value) {
360
+ return Number(value) === 1;
361
+ }
362
+ function mapRepeatableQuestRow(row) {
363
+ return {
364
+ id: Number(row.id),
365
+ questlineId: row.questline_id == null ? null : Number(row.questline_id),
366
+ title: String(row.title),
367
+ objective: String(row.objective),
368
+ rrule: String(row.rrule),
369
+ anchorAt: Number(row.anchor_at),
370
+ notBeforeOffsetSeconds: row.not_before_offset_seconds == null ? null : Number(row.not_before_offset_seconds),
371
+ dueOffsetSeconds: row.due_offset_seconds == null ? null : Number(row.due_offset_seconds),
372
+ scheduledStartOffsetSeconds: row.scheduled_start_offset_seconds == null ? null : Number(row.scheduled_start_offset_seconds),
373
+ scheduledEndOffsetSeconds: row.scheduled_end_offset_seconds == null ? null : Number(row.scheduled_end_offset_seconds),
374
+ allDay: asBoolean2(row.all_day),
375
+ estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
376
+ createdAt: Number(row.created_at),
377
+ updatedAt: Number(row.updated_at),
378
+ archivedAt: row.archived_at == null ? null : Number(row.archived_at),
379
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
380
+ };
381
+ }
382
+
383
+ // src/repeatable_quests/get_repeatable_quest_or_throw.ts
384
+ function getRepeatableQuestOrThrow(db, repeatableQuestId) {
385
+ const row = db.prepare("SELECT * FROM repeatable_quests WHERE id = ? AND deleted_at IS NULL").get(repeatableQuestId);
386
+ if (!row) {
387
+ throw new Error(`Repeatable quest ${repeatableQuestId} was not found.`);
388
+ }
389
+ return mapRepeatableQuestRow(row);
390
+ }
391
+
392
+ // src/repeatable_quests/advance_anchor.ts
393
+ var WEEK_MS = 7 * 864e5;
394
+ function advanceAnchor(anchorAt, freq, interval) {
395
+ const date = new Date(anchorAt);
396
+ if (freq === "MONTHLY") {
397
+ date.setUTCMonth(date.getUTCMonth() + interval);
398
+ return date.getTime();
399
+ }
400
+ if (freq === "YEARLY") {
401
+ date.setUTCFullYear(date.getUTCFullYear() + interval);
402
+ return date.getTime();
403
+ }
404
+ return anchorAt + interval * WEEK_MS;
405
+ }
406
+
407
+ // src/repeatable_quests/parse_rrule.ts
408
+ var WEEKDAY = {
409
+ SU: 0,
410
+ MO: 1,
411
+ TU: 2,
412
+ WE: 3,
413
+ TH: 4,
414
+ FR: 5,
415
+ SA: 6
416
+ };
417
+ function parseRRule(rrule) {
418
+ const parts = Object.fromEntries(
419
+ rrule.split(";").map((part) => part.trim()).filter(Boolean).map((part) => {
420
+ const [key, value] = part.split("=");
421
+ return [key, value];
422
+ })
423
+ );
424
+ const freq = parts.FREQ;
425
+ if (freq !== "DAILY" && freq !== "WEEKLY" && freq !== "MONTHLY" && freq !== "YEARLY") {
426
+ throw new Error(`Unsupported RRULE FREQ: ${freq ?? "missing"}`);
427
+ }
428
+ const interval = parts.INTERVAL == null ? 1 : Number(parts.INTERVAL);
429
+ if (!Number.isFinite(interval) || interval < 1) {
430
+ throw new Error("RRULE INTERVAL must be a positive integer.");
431
+ }
432
+ const count = parts.COUNT == null ? null : Number(parts.COUNT);
433
+ if (count != null && (!Number.isFinite(count) || count < 1)) {
434
+ throw new Error("RRULE COUNT must be a positive integer.");
435
+ }
436
+ const until = parts.UNTIL == null ? null : Date.parse(parts.UNTIL);
437
+ if (parts.UNTIL != null && Number.isNaN(until)) {
438
+ throw new Error("RRULE UNTIL must be parseable as a date.");
439
+ }
440
+ const byDay = parts.BYDAY == null ? null : parts.BYDAY.split(",").map((token) => {
441
+ const value = WEEKDAY[token];
442
+ if (value == null) {
443
+ throw new Error(`Unsupported RRULE BYDAY token: ${token}`);
444
+ }
445
+ return value;
446
+ });
447
+ return { freq, interval, count, until, byDay };
448
+ }
449
+
450
+ // src/repeatable_quests/start_of_utc_day.ts
451
+ function startOfUtcDay(timestamp) {
452
+ const date = new Date(timestamp);
453
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
454
+ }
455
+
456
+ // src/repeatable_quests/start_of_utc_week.ts
457
+ var DAY_MS = 864e5;
458
+ function startOfUtcWeek(dayStart) {
459
+ const date = new Date(dayStart);
460
+ return dayStart - date.getUTCDay() * DAY_MS;
461
+ }
462
+
463
+ // src/repeatable_quests/generate_anchors_until.ts
464
+ var DAY_MS2 = 864e5;
465
+ var WEEK_MS2 = 7 * DAY_MS2;
466
+ function generateAnchorsUntil(repeatable, now) {
467
+ const rule = parseRRule(repeatable.rrule);
468
+ const anchors = [];
469
+ const until = rule.until == null ? now : Math.min(now, rule.until);
470
+ if (repeatable.anchorAt > until) {
471
+ return anchors;
472
+ }
473
+ if (rule.freq === "DAILY") {
474
+ let occurrence2 = 0;
475
+ for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
476
+ occurrence2 += 1;
477
+ if (rule.count != null && occurrence2 > rule.count) {
478
+ break;
479
+ }
480
+ anchors.push(current2);
481
+ }
482
+ return anchors;
483
+ }
484
+ if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
485
+ const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
486
+ const anchorWeekStart = startOfUtcWeek(anchorDayStart);
487
+ const timeOffset = repeatable.anchorAt - anchorDayStart;
488
+ let occurrence2 = 0;
489
+ for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
490
+ const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
491
+ if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
492
+ continue;
493
+ }
494
+ if (!rule.byDay.includes(new Date(day).getUTCDay())) {
495
+ continue;
496
+ }
497
+ const anchor = day + timeOffset;
498
+ if (anchor < repeatable.anchorAt || anchor > until) {
499
+ continue;
500
+ }
501
+ occurrence2 += 1;
502
+ if (rule.count != null && occurrence2 > rule.count) {
503
+ break;
504
+ }
505
+ anchors.push(anchor);
506
+ }
507
+ return anchors;
508
+ }
509
+ let occurrence = 0;
510
+ let current = repeatable.anchorAt;
511
+ while (current <= until) {
512
+ occurrence += 1;
513
+ if (rule.count != null && occurrence > rule.count) {
514
+ break;
515
+ }
516
+ anchors.push(current);
517
+ current = advanceAnchor(current, rule.freq, rule.interval);
518
+ }
519
+ return anchors;
520
+ }
521
+
522
+ // src/repeatable_quests/list_due_repeatable_quest_anchors.ts
523
+ function listDueRepeatableQuestAnchors(db, now) {
524
+ const repeatables = db.prepare(
525
+ `SELECT *
526
+ FROM repeatable_quests
527
+ WHERE deleted_at IS NULL
528
+ AND archived_at IS NULL`
529
+ ).all().map(mapRepeatableQuestRow);
530
+ const anchors = [];
531
+ if (repeatables.length === 0) {
532
+ return anchors;
533
+ }
534
+ const repeatableIds = repeatables.map((repeatable) => repeatable.id);
535
+ const maxAnchorAt = Math.max(
536
+ ...repeatables.map((repeatable) => Math.max(repeatable.anchorAt, now))
537
+ );
538
+ const existingRows = db.prepare(
539
+ `SELECT spawned_from_repeatable_id, spawned_for_at
540
+ FROM quests
541
+ WHERE spawned_from_repeatable_id IN (${repeatableIds.map(() => "?").join(", ")})
542
+ AND spawned_for_at IS NOT NULL
543
+ AND spawned_for_at <= ?`
544
+ ).all(...repeatableIds, maxAnchorAt);
545
+ const existingAnchors = new Set(
546
+ existingRows.map(
547
+ (row) => `${Number(row.spawned_from_repeatable_id)}:${Number(row.spawned_for_at)}`
548
+ )
549
+ );
550
+ for (const repeatable of repeatables) {
551
+ const dueAnchors = generateAnchorsUntil(repeatable, now);
552
+ for (const anchorAt of dueAnchors) {
553
+ if (!existingAnchors.has(`${repeatable.id}:${anchorAt}`)) {
554
+ anchors.push({
555
+ repeatableQuestId: repeatable.id,
556
+ anchorAt,
557
+ markerId: "attention.available.repeatable"
558
+ });
559
+ }
560
+ }
561
+ }
562
+ return anchors.sort(
563
+ (a, b) => a.anchorAt - b.anchorAt || a.repeatableQuestId - b.repeatableQuestId
564
+ );
565
+ }
566
+
567
+ // src/repeatable_quests/spawn_due_repeatable_quests.ts
568
+ function spawnDueRepeatableQuests(db, now) {
569
+ return withTransaction(db, () => {
570
+ const anchors = listDueRepeatableQuestAnchors(db, now);
571
+ const quests = [];
572
+ for (const anchor of anchors) {
573
+ const repeatable = getRepeatableQuestOrThrow(db, anchor.repeatableQuestId);
574
+ const created = db.prepare(
575
+ `INSERT INTO quests (
576
+ questline_id,
577
+ source_rumor_id,
578
+ spawned_by_quest_id,
579
+ spawned_from_repeatable_id,
580
+ spawned_for_at,
581
+ title,
582
+ objective,
583
+ created_at,
584
+ updated_at,
585
+ effort_seconds,
586
+ estimate_seconds,
587
+ not_before_at,
588
+ due_at,
589
+ scheduled_start_at,
590
+ scheduled_end_at,
591
+ all_day
592
+ ) VALUES (?, NULL, NULL, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
593
+ ).run(
594
+ repeatable.questlineId ?? null,
595
+ repeatable.id,
596
+ anchor.anchorAt,
597
+ repeatable.title,
598
+ repeatable.objective,
599
+ now,
600
+ now,
601
+ repeatable.estimateSeconds ?? null,
602
+ repeatable.notBeforeOffsetSeconds == null ? null : anchor.anchorAt + repeatable.notBeforeOffsetSeconds * 1e3,
603
+ repeatable.dueOffsetSeconds == null ? null : anchor.anchorAt + repeatable.dueOffsetSeconds * 1e3,
604
+ repeatable.scheduledStartOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledStartOffsetSeconds * 1e3,
605
+ repeatable.scheduledEndOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledEndOffsetSeconds * 1e3,
606
+ repeatable.allDay ? 1 : 0
607
+ );
608
+ const questId = Number(created.lastInsertRowid);
609
+ copyRepeatableQuestTagsToQuest(db, repeatable.id, questId, now);
610
+ copyRepeatableQuestRewardsToQuest(db, repeatable.id, questId, now);
611
+ quests.push(getQuestOrThrow(db, questId));
612
+ }
613
+ return quests;
614
+ });
615
+ }
616
+
617
+ // src/markers/derive_quest_marker_id.ts
618
+ function deriveQuestMarkerId({
619
+ state,
620
+ available,
621
+ hasUnclaimedReward,
622
+ notBeforeAt,
623
+ blockerCount,
624
+ now
625
+ }) {
626
+ if (state === "done") {
627
+ return hasUnclaimedReward ? "progress.complete" : null;
628
+ }
629
+ if (state === "abandoned") {
630
+ return null;
631
+ }
632
+ if (state === "in_progress") {
633
+ return "progress.incomplete";
634
+ }
635
+ if (available) {
636
+ return "attention.available";
637
+ }
638
+ if (notBeforeAt != null && notBeforeAt > now) {
639
+ return "attention.available.future";
640
+ }
641
+ if (blockerCount > 0) {
642
+ return "progress.incomplete";
643
+ }
644
+ return null;
645
+ }
646
+
647
+ // src/rewards/map_quest_reward_row.ts
648
+ function mapQuestRewardRow(row) {
649
+ return {
650
+ id: Number(row.id),
651
+ questId: Number(row.quest_id),
652
+ kind: String(row.kind),
653
+ name: String(row.name),
654
+ description: row.description == null ? null : String(row.description),
655
+ quantity: row.quantity == null ? null : Number(row.quantity),
656
+ createdAt: Number(row.created_at),
657
+ claimedAt: row.claimed_at == null ? null : Number(row.claimed_at),
658
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
659
+ };
660
+ }
661
+
662
+ // src/quests/derive_quest_state.ts
663
+ function deriveQuestState(quest) {
664
+ if (quest.resolvedAt != null && quest.success === true) {
665
+ return "done";
666
+ }
667
+ if (quest.resolvedAt != null && quest.success === false) {
668
+ return "abandoned";
669
+ }
670
+ if (quest.startedAt != null) {
671
+ return "in_progress";
672
+ }
673
+ return "open";
674
+ }
675
+
676
+ // src/quests/query_quest_detail_records.ts
677
+ function queryQuestDetailRecords(db, filters = {}, now = Date.now(), questIds) {
678
+ if (questIds && questIds.length === 0) {
679
+ return [];
680
+ }
681
+ const clauses = [];
682
+ const params = [];
683
+ if (!filters.includeDeleted) {
684
+ clauses.push("q.deleted_at IS NULL");
685
+ }
686
+ if (questIds && questIds.length > 0) {
687
+ clauses.push(`q.id IN (${questIds.map(() => "?").join(", ")})`);
688
+ params.push(...questIds);
689
+ }
690
+ if (filters.questlineId != null) {
691
+ clauses.push("q.questline_id = ?");
692
+ params.push(filters.questlineId);
693
+ }
694
+ if (filters.tagNames && filters.tagNames.length > 0) {
695
+ const normalized = [...new Set(filters.tagNames.map(normalizeTagName).filter(Boolean))];
696
+ for (const tag of normalized) {
697
+ clauses.push(
698
+ `EXISTS (
699
+ SELECT 1
700
+ FROM quest_tags qt
701
+ JOIN tags t ON t.id = qt.tag_id
702
+ WHERE qt.quest_id = q.id
703
+ AND qt.deleted_at IS NULL
704
+ AND t.deleted_at IS NULL
705
+ AND t.normalized_name = ?
706
+ )`
707
+ );
708
+ params.push(tag);
709
+ }
710
+ }
711
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
712
+ const rows = db.prepare(
713
+ `SELECT q.*,
714
+ COALESCE(q.due_at, ql.due_at) AS effective_due_at,
715
+ (
716
+ SELECT COUNT(*)
717
+ FROM quest_unlocks qu
718
+ JOIN quests blocker ON blocker.id = qu.from_quest_id
719
+ WHERE qu.to_quest_id = q.id
720
+ AND qu.deleted_at IS NULL
721
+ AND blocker.deleted_at IS NULL
722
+ AND NOT (blocker.resolved_at IS NOT NULL AND blocker.success = 1)
723
+ ) AS blocker_count
724
+ FROM quests q
725
+ LEFT JOIN questlines ql ON ql.id = q.questline_id AND ql.deleted_at IS NULL
726
+ ${where}
727
+ ORDER BY q.created_at DESC, q.id DESC`
728
+ ).all(...params);
729
+ if (rows.length === 0) {
730
+ return [];
731
+ }
732
+ const ids = rows.map((row) => Number(row.id));
733
+ const placeholders = ids.map(() => "?").join(", ");
734
+ const tagNamesByQuestId = /* @__PURE__ */ new Map();
735
+ const rewardsByQuestId = /* @__PURE__ */ new Map();
736
+ const unlocksByQuestId = /* @__PURE__ */ new Map();
737
+ const unlockedByQuestId = /* @__PURE__ */ new Map();
738
+ for (const row of db.prepare(
739
+ `SELECT qt.quest_id, t.name
740
+ FROM quest_tags qt
741
+ JOIN tags t ON t.id = qt.tag_id
742
+ WHERE qt.quest_id IN (${placeholders})
743
+ AND qt.deleted_at IS NULL
744
+ AND t.deleted_at IS NULL
745
+ ORDER BY qt.quest_id, t.name`
746
+ ).all(...ids)) {
747
+ const questId = Number(row.quest_id);
748
+ const tagNames = tagNamesByQuestId.get(questId) ?? [];
749
+ tagNames.push(String(row.name));
750
+ tagNamesByQuestId.set(questId, tagNames);
751
+ }
752
+ for (const row of db.prepare(
753
+ `SELECT *
754
+ FROM quest_rewards
755
+ WHERE quest_id IN (${placeholders})
756
+ AND deleted_at IS NULL
757
+ ORDER BY quest_id, created_at, id`
758
+ ).all(...ids)) {
759
+ const reward = mapQuestRewardRow(row);
760
+ const rewards = rewardsByQuestId.get(reward.questId) ?? [];
761
+ rewards.push(reward);
762
+ rewardsByQuestId.set(reward.questId, rewards);
763
+ }
764
+ for (const row of db.prepare(
765
+ `SELECT from_quest_id, to_quest_id
766
+ FROM quest_unlocks
767
+ WHERE from_quest_id IN (${placeholders})
768
+ AND deleted_at IS NULL
769
+ ORDER BY from_quest_id, to_quest_id`
770
+ ).all(...ids)) {
771
+ const questId = Number(row.from_quest_id);
772
+ const unlocks = unlocksByQuestId.get(questId) ?? [];
773
+ unlocks.push(Number(row.to_quest_id));
774
+ unlocksByQuestId.set(questId, unlocks);
775
+ }
776
+ for (const row of db.prepare(
777
+ `SELECT from_quest_id, to_quest_id
778
+ FROM quest_unlocks
779
+ WHERE to_quest_id IN (${placeholders})
780
+ AND deleted_at IS NULL
781
+ ORDER BY to_quest_id, from_quest_id`
782
+ ).all(...ids)) {
783
+ const questId = Number(row.to_quest_id);
784
+ const unlockedBy = unlockedByQuestId.get(questId) ?? [];
785
+ unlockedBy.push(Number(row.from_quest_id));
786
+ unlockedByQuestId.set(questId, unlockedBy);
787
+ }
788
+ return rows.map((row) => {
789
+ const quest = mapQuestRow(row);
790
+ const blockerCount = Number(row.blocker_count ?? 0);
791
+ const effectiveDueAt = row.effective_due_at == null ? null : Number(row.effective_due_at);
792
+ const rewards = rewardsByQuestId.get(quest.id) ?? [];
793
+ const state = deriveQuestState(quest);
794
+ const available = quest.deletedAt == null && quest.resolvedAt == null && (quest.notBeforeAt == null || quest.notBeforeAt <= now) && blockerCount === 0;
795
+ const markerId = deriveQuestMarkerId({
796
+ state,
797
+ available,
798
+ hasUnclaimedReward: rewards.some((reward) => reward.claimedAt == null),
799
+ notBeforeAt: quest.notBeforeAt,
800
+ blockerCount,
801
+ now
802
+ });
803
+ return {
804
+ detail: {
805
+ ...quest,
806
+ state,
807
+ markerId,
808
+ effectiveDueAt,
809
+ available,
810
+ tagNames: tagNamesByQuestId.get(quest.id) ?? [],
811
+ rewards,
812
+ unlocksQuestIds: unlocksByQuestId.get(quest.id) ?? [],
813
+ unlockedByQuestIds: unlockedByQuestId.get(quest.id) ?? []
814
+ },
815
+ blockerCount
816
+ };
817
+ });
818
+ }
819
+
820
+ // src/hooks/detect_hook_events.ts
821
+ function detectHookEvents(db, now) {
822
+ const events = [];
823
+ const add = (type, at, ids) => {
824
+ events.push({
825
+ id: `e_${type}_${ids.questId ?? ids.rumorId}_${ids.repeatableId ?? ""}_${at}`,
826
+ type,
827
+ ...ids,
828
+ occurredAt: new Date(at).toISOString()
829
+ });
830
+ };
831
+ for (const { detail: q } of queryQuestDetailRecords(db, {}, now)) {
832
+ if (q.resolvedAt == null && q.effectiveDueAt != null && q.effectiveDueAt <= now) {
833
+ add("quest.due", q.effectiveDueAt, { questId: q.id });
834
+ if (q.effectiveDueAt < now) add("quest.overdue", q.effectiveDueAt, { questId: q.id });
835
+ }
836
+ if (q.available) {
837
+ const prerequisites = db.prepare(
838
+ `SELECT p.id, p.resolved_at, u.created_at FROM quest_unlocks u JOIN quests p ON p.id = u.from_quest_id WHERE u.to_quest_id = ? AND u.deleted_at IS NULL AND p.deleted_at IS NULL AND p.success = 1 AND p.resolved_at IS NOT NULL`
839
+ ).all(q.id);
840
+ if (prerequisites.some((p) => Number(p.resolved_at) >= Number(p.created_at))) {
841
+ const at = Math.max(q.notBeforeAt ?? 0, ...prerequisites.map((p) => Number(p.resolved_at)));
842
+ if (at <= now) add("quest.unblocked", at, { questId: q.id });
843
+ }
844
+ }
845
+ if (q.spawnedFromRepeatableId != null && q.createdAt <= now)
846
+ add("repeatable.spawned", q.createdAt, {
847
+ questId: q.id,
848
+ repeatableId: q.spawnedFromRepeatableId
849
+ });
850
+ }
851
+ for (const row of db.prepare("SELECT id, created_at FROM rumors WHERE deleted_at IS NULL AND created_at <= ?").all(now))
852
+ add("rumor.captured", Number(row.created_at), { rumorId: Number(row.id) });
853
+ return events.sort(
854
+ (a, b) => a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
855
+ );
856
+ }
857
+
858
+ // src/hooks/tick_questlog.ts
859
+ async function tickQuestlog(db, options = {}) {
860
+ const now = options.now ?? options.clock?.() ?? Date.now();
861
+ const result = {
862
+ events: [],
863
+ batches: [],
864
+ sent: 0,
865
+ queued: 0,
866
+ retrying: 0,
867
+ failed: 0
868
+ };
869
+ const claims = [];
870
+ const collect = () => {
871
+ spawnDueRepeatableQuests(db, now);
872
+ const detected = detectHookEvents(db, now);
873
+ result.events = detected.filter(
874
+ (e) => !db.prepare("SELECT id FROM hook_events WHERE id = ?").get(e.id)
875
+ );
876
+ for (const event of result.events)
877
+ db.prepare("INSERT INTO hook_events(id, occurred_at, event) VALUES (?, ?, ?)").run(
878
+ event.id,
879
+ Date.parse(event.occurredAt),
880
+ JSON.stringify(event)
881
+ );
882
+ for (const target of listHooks(db)) {
883
+ const events = db.prepare(
884
+ "SELECT e.event FROM hook_events e WHERE occurred_at >= ? AND NOT EXISTS (SELECT 1 FROM hook_assignments a WHERE a.target_id = ? AND a.event_id = e.id) ORDER BY occurred_at, id"
885
+ ).all(target.createdAt, target.id).map((row2) => JSON.parse(String(row2.event))).filter((event) => {
886
+ if (!target.events.includes(event.type)) return false;
887
+ if (target.tag == null) return true;
888
+ return event.questId !== void 0 && db.prepare(
889
+ "SELECT 1 FROM quest_tags qt JOIN tags t ON t.id = qt.tag_id WHERE qt.quest_id = ? AND qt.deleted_at IS NULL AND t.deleted_at IS NULL AND t.normalized_name = ?"
890
+ ).get(event.questId, normalizeTagName(target.tag)) !== void 0;
891
+ });
892
+ for (const event of events)
893
+ db.prepare("INSERT INTO hook_assignments(target_id, event_id) VALUES (?, ?)").run(
894
+ target.id,
895
+ event.id
896
+ );
897
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(target.id);
898
+ if (!row || row.lease_until != null && Number(row.lease_until) > now) continue;
899
+ let pending = listDeliveries(db).find(
900
+ (d) => d.targetId === target.id && d.status === "pending"
901
+ );
902
+ const queued = db.prepare(
903
+ "SELECT e.event FROM hook_assignments a JOIN hook_events e ON e.id = a.event_id WHERE a.target_id = ? AND a.delivery_id IS NULL ORDER BY e.occurred_at, e.id"
904
+ ).all(target.id).map((r) => JSON.parse(String(r.event)));
905
+ if (!pending && queued.length) {
906
+ const id = `d_${randomBytes(16).toString("hex")}`;
907
+ db.prepare(
908
+ "INSERT INTO hook_deliveries(id, target_id, events, status, next_attempt_at) VALUES (?, ?, ?, 'pending', ?)"
909
+ ).run(
910
+ id,
911
+ target.id,
912
+ JSON.stringify(queued),
913
+ Math.max(now, (target.lastWake ?? -Infinity) + target.minGap * 1e3)
914
+ );
915
+ db.prepare(
916
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
917
+ ).run(id, target.id);
918
+ pending = listDeliveries(db).find((d) => d.id === id);
919
+ }
920
+ if (!pending) continue;
921
+ if (pending.attempts === 0 && queued.length && !queued.every((e) => pending?.events.some((p) => p.id === e.id))) {
922
+ pending.events.push(...queued);
923
+ db.prepare("UPDATE hook_deliveries SET events = ? WHERE id = ?").run(
924
+ JSON.stringify(pending.events),
925
+ pending.id
926
+ );
927
+ db.prepare(
928
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
929
+ ).run(pending.id, target.id);
930
+ }
931
+ if (pending.nextAttemptAt > now || target.lastWake != null && target.lastWake + target.minGap * 1e3 > now)
932
+ continue;
933
+ if (pending.attempts >= 8) {
934
+ db.prepare("UPDATE hook_deliveries SET status = 'failed' WHERE id = ?").run(pending.id);
935
+ continue;
936
+ }
937
+ const claim = randomBytes(16).toString("hex");
938
+ db.prepare(
939
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
940
+ ).run(claim, now + 12e4, now, target.id);
941
+ db.prepare(
942
+ "UPDATE hook_deliveries SET attempts = attempts + 1, last_attempt_at = ? WHERE id = ?"
943
+ ).run(now, pending.id);
944
+ pending.attempts++;
945
+ pending.lastAttemptAt = now;
946
+ result.batches.push({ targetId: target.id, events: pending.events });
947
+ claims.push({
948
+ delivery: pending,
949
+ target: { id: target.id, url: String(row.url), secret: String(row.secret), claim }
950
+ });
951
+ }
952
+ };
953
+ if (options.dryRun) {
954
+ const rollback = new Error("preview rollback");
955
+ try {
956
+ withTransaction(db, () => {
957
+ collect();
958
+ throw rollback;
959
+ });
960
+ } catch (error) {
961
+ if (error !== rollback) throw error;
962
+ }
963
+ } else withTransaction(db, collect);
964
+ if (!options.dryRun) {
965
+ const sent = await Promise.all(
966
+ claims.map((claim) => sendHookDelivery(db, claim.delivery, claim.target, options))
967
+ );
968
+ result.sent = sent.filter(Boolean).length;
969
+ }
970
+ const deliveries = listDeliveries(db);
971
+ result.queued = deliveries.filter((d) => d.status === "pending" && d.attempts === 0).length + Number(
972
+ db.prepare(
973
+ "SELECT COUNT(DISTINCT target_id) AS n FROM hook_assignments WHERE delivery_id IS NULL"
974
+ ).get()?.n ?? 0
975
+ );
976
+ result.retrying = deliveries.filter((d) => d.status === "pending" && d.attempts > 0).length;
977
+ result.failed = deliveries.filter((d) => d.status === "failed").length;
978
+ return result;
979
+ }
980
+
981
+ // src/hooks/watch_questlog.ts
982
+ async function watchQuestlog(db, options) {
983
+ const interval = options.interval ?? 60;
984
+ if (!Number.isFinite(interval) || interval < 5)
985
+ throw new Error("Interval must be at least 5 seconds");
986
+ while (!options.signal.aborted) {
987
+ options.onTick?.(await tickQuestlog(db, options));
988
+ if (options.signal.aborted) break;
989
+ await new Promise((resolve) => {
990
+ const finish = () => {
991
+ clearTimeout(timer);
992
+ options.signal.removeEventListener("abort", finish);
993
+ resolve();
994
+ };
995
+ const timer = setTimeout(finish, interval * 1e3);
996
+ options.signal.addEventListener("abort", finish, { once: true });
997
+ });
998
+ }
999
+ }
1000
+
1001
+ // src/hooks/init_hook_tables.ts
1002
+ function initHookTables(db) {
1003
+ db.exec(`
1004
+ CREATE TABLE IF NOT EXISTS hook_targets (
1005
+ id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, secret TEXT NOT NULL,
1006
+ tag TEXT, events TEXT NOT NULL, min_gap INTEGER NOT NULL, created_at INTEGER NOT NULL,
1007
+ last_wake INTEGER, lease_until INTEGER, claim TEXT);
1008
+ CREATE TABLE IF NOT EXISTS hook_events (
1009
+ id TEXT PRIMARY KEY, occurred_at INTEGER NOT NULL, event TEXT NOT NULL);
1010
+ CREATE TABLE IF NOT EXISTS hook_assignments (
1011
+ target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
1012
+ event_id TEXT NOT NULL REFERENCES hook_events(id), delivery_id TEXT,
1013
+ PRIMARY KEY(target_id, event_id));
1014
+ CREATE TABLE IF NOT EXISTS hook_deliveries (
1015
+ id TEXT PRIMARY KEY, target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
1016
+ events TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
1017
+ last_attempt_at INTEGER, http_status INTEGER, error_class TEXT,
1018
+ next_attempt_at INTEGER NOT NULL);
1019
+ CREATE INDEX IF NOT EXISTS idx_hook_deliveries_target ON hook_deliveries(target_id, status, next_attempt_at);
1020
+ CREATE TABLE IF NOT EXISTS hook_settings (id INTEGER PRIMARY KEY CHECK(id = 1), label TEXT NOT NULL);
1021
+ `);
1022
+ }
1023
+
7
1024
  // src/questlines/init_questline_tables.ts
8
1025
  function initQuestlineTables(db) {
9
1026
  db.exec(`
@@ -352,6 +1369,7 @@ function initQuestlogTables(db) {
352
1369
  initTagTables(db);
353
1370
  initQuestSearch(db);
354
1371
  initRumorSearch(db);
1372
+ initHookTables(db);
355
1373
  }
356
1374
 
357
1375
  // src/markers/index.ts
@@ -362,36 +1380,6 @@ __export(markers_exports, {
362
1380
  markerLookup: () => markerLookup
363
1381
  });
364
1382
 
365
- // src/markers/derive_quest_marker_id.ts
366
- function deriveQuestMarkerId({
367
- state,
368
- available,
369
- hasUnclaimedReward,
370
- notBeforeAt,
371
- blockerCount,
372
- now
373
- }) {
374
- if (state === "done") {
375
- return hasUnclaimedReward ? "progress.complete" : null;
376
- }
377
- if (state === "abandoned") {
378
- return null;
379
- }
380
- if (state === "in_progress") {
381
- return "progress.incomplete";
382
- }
383
- if (available) {
384
- return "attention.available";
385
- }
386
- if (notBeforeAt != null && notBeforeAt > now) {
387
- return "attention.available.future";
388
- }
389
- if (blockerCount > 0) {
390
- return "progress.incomplete";
391
- }
392
- return null;
393
- }
394
-
395
1383
  // src/markers/derive_rumor_marker_id.ts
396
1384
  function deriveRumorMarkerId({ state }) {
397
1385
  if (state === "open") {
@@ -479,11 +1467,6 @@ __export(read_exports, {
479
1467
  searchQuestlog: () => searchQuestlog
480
1468
  });
481
1469
 
482
- // src/resolve_now.ts
483
- function resolveNow(now) {
484
- return now ?? Date.now();
485
- }
486
-
487
1470
  // src/assert_non_empty.ts
488
1471
  function assertNonEmpty(value, label) {
489
1472
  const trimmed = value.trim();
@@ -493,41 +1476,6 @@ function assertNonEmpty(value, label) {
493
1476
  return trimmed;
494
1477
  }
495
1478
 
496
- // src/with_transaction.ts
497
- var transactionDepth = /* @__PURE__ */ new WeakMap();
498
- function withTransaction(db, fn) {
499
- const depth = transactionDepth.get(db) ?? 0;
500
- const savepoint = `questlog_${depth}`;
501
- if (depth === 0) {
502
- db.exec("BEGIN IMMEDIATE");
503
- } else {
504
- db.exec(`SAVEPOINT ${savepoint}`);
505
- }
506
- transactionDepth.set(db, depth + 1);
507
- try {
508
- const result = fn();
509
- if (depth === 0) {
510
- db.exec("COMMIT");
511
- } else {
512
- db.exec(`RELEASE SAVEPOINT ${savepoint}`);
513
- }
514
- transactionDepth.set(db, depth);
515
- return result;
516
- } catch (error) {
517
- try {
518
- if (depth === 0) {
519
- db.exec("ROLLBACK");
520
- } else {
521
- db.exec(`ROLLBACK TO SAVEPOINT ${savepoint}`);
522
- db.exec(`RELEASE SAVEPOINT ${savepoint}`);
523
- }
524
- } catch {
525
- }
526
- transactionDepth.set(db, depth);
527
- throw error;
528
- }
529
- }
530
-
531
1479
  // src/questlines/map_questline_row.ts
532
1480
  function mapQuestlineRow(row) {
533
1481
  return {
@@ -756,46 +1704,6 @@ function softDeleteQuestline(db, questlineId, deletedAt) {
756
1704
  ).run(now, now, questlineId);
757
1705
  }
758
1706
 
759
- // src/quests/map_quest_row.ts
760
- function asBoolean(value) {
761
- return Number(value) === 1;
762
- }
763
- function mapQuestRow(row) {
764
- return {
765
- id: Number(row.id),
766
- questlineId: row.questline_id == null ? null : Number(row.questline_id),
767
- sourceRumorId: row.source_rumor_id == null ? null : Number(row.source_rumor_id),
768
- spawnedByQuestId: row.spawned_by_quest_id == null ? null : Number(row.spawned_by_quest_id),
769
- spawnedFromRepeatableId: row.spawned_from_repeatable_id == null ? null : Number(row.spawned_from_repeatable_id),
770
- spawnedForAt: row.spawned_for_at == null ? null : Number(row.spawned_for_at),
771
- title: String(row.title),
772
- objective: String(row.objective),
773
- outcome: row.outcome == null ? null : String(row.outcome),
774
- createdAt: Number(row.created_at),
775
- updatedAt: Number(row.updated_at),
776
- startedAt: row.started_at == null ? null : Number(row.started_at),
777
- resolvedAt: row.resolved_at == null ? null : Number(row.resolved_at),
778
- success: row.success == null ? null : asBoolean(row.success),
779
- effortSeconds: Number(row.effort_seconds),
780
- estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
781
- notBeforeAt: row.not_before_at == null ? null : Number(row.not_before_at),
782
- dueAt: row.due_at == null ? null : Number(row.due_at),
783
- scheduledStartAt: row.scheduled_start_at == null ? null : Number(row.scheduled_start_at),
784
- scheduledEndAt: row.scheduled_end_at == null ? null : Number(row.scheduled_end_at),
785
- allDay: asBoolean(row.all_day),
786
- deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
787
- };
788
- }
789
-
790
- // src/quests/get_quest_or_throw.ts
791
- function getQuestOrThrow(db, questId) {
792
- const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
793
- if (!row) {
794
- throw new Error(`Quest ${questId} was not found.`);
795
- }
796
- return mapQuestRow(row);
797
- }
798
-
799
1707
  // src/quests/resolve_quest.ts
800
1708
  function resolveQuest(db, questId, success, outcome, resolvedAt) {
801
1709
  const current = getQuestOrThrow(db, questId);
@@ -897,11 +1805,6 @@ function replaceActiveQuestRewards(db, questId, rewards, now) {
897
1805
  }
898
1806
  }
899
1807
 
900
- // src/tags/normalize_tag_name.ts
901
- function normalizeTagName(name) {
902
- return name.trim().toLowerCase().replace(/\s+/g, " ");
903
- }
904
-
905
1808
  // src/tags/replace_active_quest_tags.ts
906
1809
  function getOrCreateTagId(db, name, now) {
907
1810
  const normalizedName = normalizeTagName(name);
@@ -998,215 +1901,42 @@ function createQuest(db, input) {
998
1901
  if (input.tags && input.tags.length > 0) {
999
1902
  replaceActiveQuestTags(db, questId, input.tags, now);
1000
1903
  }
1001
- if (input.rewards && input.rewards.length > 0) {
1002
- replaceActiveQuestRewards(db, questId, input.rewards, now);
1003
- }
1004
- return getQuestOrThrow(db, questId);
1005
- });
1006
- }
1007
-
1008
- // src/quests/abandon_quest_and_spawn_followups.ts
1009
- function abandonQuestAndSpawnFollowups(db, questId, outcome, followups, resolvedAt) {
1010
- return withTransaction(db, () => {
1011
- const abandonedQuest = abandonQuest(db, questId, outcome, resolvedAt);
1012
- const now = resolveNow(resolvedAt);
1013
- const followupQuests = followups.map(
1014
- (followup) => createQuest(db, {
1015
- ...followup,
1016
- questlineId: followup.questlineId ?? abandonedQuest.questlineId,
1017
- spawnedByQuestId: questId,
1018
- now
1019
- })
1020
- );
1021
- for (let i = 0; i < followups.length; i += 1) {
1022
- const followup = followups[i];
1023
- const created = followupQuests[i];
1024
- if (followup?.unlocksParent && created) {
1025
- addUnlock(db, created.id, questId, resolvedAt);
1026
- }
1027
- }
1028
- return { abandonedQuest, followupQuests };
1029
- });
1030
- }
1031
-
1032
- // src/quests/finish_quest.ts
1033
- function finishQuest(db, questId, outcome, resolvedAt) {
1034
- return resolveQuest(db, questId, true, outcome, resolvedAt);
1035
- }
1036
-
1037
- // src/rewards/map_quest_reward_row.ts
1038
- function mapQuestRewardRow(row) {
1039
- return {
1040
- id: Number(row.id),
1041
- questId: Number(row.quest_id),
1042
- kind: String(row.kind),
1043
- name: String(row.name),
1044
- description: row.description == null ? null : String(row.description),
1045
- quantity: row.quantity == null ? null : Number(row.quantity),
1046
- createdAt: Number(row.created_at),
1047
- claimedAt: row.claimed_at == null ? null : Number(row.claimed_at),
1048
- deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
1049
- };
1050
- }
1051
-
1052
- // src/quests/derive_quest_state.ts
1053
- function deriveQuestState(quest) {
1054
- if (quest.resolvedAt != null && quest.success === true) {
1055
- return "done";
1056
- }
1057
- if (quest.resolvedAt != null && quest.success === false) {
1058
- return "abandoned";
1059
- }
1060
- if (quest.startedAt != null) {
1061
- return "in_progress";
1062
- }
1063
- return "open";
1904
+ if (input.rewards && input.rewards.length > 0) {
1905
+ replaceActiveQuestRewards(db, questId, input.rewards, now);
1906
+ }
1907
+ return getQuestOrThrow(db, questId);
1908
+ });
1064
1909
  }
1065
1910
 
1066
- // src/quests/query_quest_detail_records.ts
1067
- function queryQuestDetailRecords(db, filters = {}, now = Date.now(), questIds) {
1068
- if (questIds && questIds.length === 0) {
1069
- return [];
1070
- }
1071
- const clauses = [];
1072
- const params = [];
1073
- if (!filters.includeDeleted) {
1074
- clauses.push("q.deleted_at IS NULL");
1075
- }
1076
- if (questIds && questIds.length > 0) {
1077
- clauses.push(`q.id IN (${questIds.map(() => "?").join(", ")})`);
1078
- params.push(...questIds);
1079
- }
1080
- if (filters.questlineId != null) {
1081
- clauses.push("q.questline_id = ?");
1082
- params.push(filters.questlineId);
1083
- }
1084
- if (filters.tagNames && filters.tagNames.length > 0) {
1085
- const normalized = [...new Set(filters.tagNames.map(normalizeTagName).filter(Boolean))];
1086
- for (const tag of normalized) {
1087
- clauses.push(
1088
- `EXISTS (
1089
- SELECT 1
1090
- FROM quest_tags qt
1091
- JOIN tags t ON t.id = qt.tag_id
1092
- WHERE qt.quest_id = q.id
1093
- AND qt.deleted_at IS NULL
1094
- AND t.deleted_at IS NULL
1095
- AND t.normalized_name = ?
1096
- )`
1097
- );
1098
- params.push(tag);
1911
+ // src/quests/abandon_quest_and_spawn_followups.ts
1912
+ function abandonQuestAndSpawnFollowups(db, questId, outcome, followups, resolvedAt) {
1913
+ return withTransaction(db, () => {
1914
+ const abandonedQuest = abandonQuest(db, questId, outcome, resolvedAt);
1915
+ const now = resolveNow(resolvedAt);
1916
+ const followupQuests = followups.map(
1917
+ (followup) => createQuest(db, {
1918
+ ...followup,
1919
+ questlineId: followup.questlineId ?? abandonedQuest.questlineId,
1920
+ spawnedByQuestId: questId,
1921
+ now
1922
+ })
1923
+ );
1924
+ for (let i = 0; i < followups.length; i += 1) {
1925
+ const followup = followups[i];
1926
+ const created = followupQuests[i];
1927
+ if (followup?.unlocksParent && created) {
1928
+ addUnlock(db, created.id, questId, resolvedAt);
1929
+ }
1099
1930
  }
1100
- }
1101
- const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
1102
- const rows = db.prepare(
1103
- `SELECT q.*,
1104
- COALESCE(q.due_at, ql.due_at) AS effective_due_at,
1105
- (
1106
- SELECT COUNT(*)
1107
- FROM quest_unlocks qu
1108
- JOIN quests blocker ON blocker.id = qu.from_quest_id
1109
- WHERE qu.to_quest_id = q.id
1110
- AND qu.deleted_at IS NULL
1111
- AND blocker.deleted_at IS NULL
1112
- AND NOT (blocker.resolved_at IS NOT NULL AND blocker.success = 1)
1113
- ) AS blocker_count
1114
- FROM quests q
1115
- LEFT JOIN questlines ql ON ql.id = q.questline_id AND ql.deleted_at IS NULL
1116
- ${where}
1117
- ORDER BY q.created_at DESC, q.id DESC`
1118
- ).all(...params);
1119
- if (rows.length === 0) {
1120
- return [];
1121
- }
1122
- const ids = rows.map((row) => Number(row.id));
1123
- const placeholders = ids.map(() => "?").join(", ");
1124
- const tagNamesByQuestId = /* @__PURE__ */ new Map();
1125
- const rewardsByQuestId = /* @__PURE__ */ new Map();
1126
- const unlocksByQuestId = /* @__PURE__ */ new Map();
1127
- const unlockedByQuestId = /* @__PURE__ */ new Map();
1128
- for (const row of db.prepare(
1129
- `SELECT qt.quest_id, t.name
1130
- FROM quest_tags qt
1131
- JOIN tags t ON t.id = qt.tag_id
1132
- WHERE qt.quest_id IN (${placeholders})
1133
- AND qt.deleted_at IS NULL
1134
- AND t.deleted_at IS NULL
1135
- ORDER BY qt.quest_id, t.name`
1136
- ).all(...ids)) {
1137
- const questId = Number(row.quest_id);
1138
- const tagNames = tagNamesByQuestId.get(questId) ?? [];
1139
- tagNames.push(String(row.name));
1140
- tagNamesByQuestId.set(questId, tagNames);
1141
- }
1142
- for (const row of db.prepare(
1143
- `SELECT *
1144
- FROM quest_rewards
1145
- WHERE quest_id IN (${placeholders})
1146
- AND deleted_at IS NULL
1147
- ORDER BY quest_id, created_at, id`
1148
- ).all(...ids)) {
1149
- const reward = mapQuestRewardRow(row);
1150
- const rewards = rewardsByQuestId.get(reward.questId) ?? [];
1151
- rewards.push(reward);
1152
- rewardsByQuestId.set(reward.questId, rewards);
1153
- }
1154
- for (const row of db.prepare(
1155
- `SELECT from_quest_id, to_quest_id
1156
- FROM quest_unlocks
1157
- WHERE from_quest_id IN (${placeholders})
1158
- AND deleted_at IS NULL
1159
- ORDER BY from_quest_id, to_quest_id`
1160
- ).all(...ids)) {
1161
- const questId = Number(row.from_quest_id);
1162
- const unlocks = unlocksByQuestId.get(questId) ?? [];
1163
- unlocks.push(Number(row.to_quest_id));
1164
- unlocksByQuestId.set(questId, unlocks);
1165
- }
1166
- for (const row of db.prepare(
1167
- `SELECT from_quest_id, to_quest_id
1168
- FROM quest_unlocks
1169
- WHERE to_quest_id IN (${placeholders})
1170
- AND deleted_at IS NULL
1171
- ORDER BY to_quest_id, from_quest_id`
1172
- ).all(...ids)) {
1173
- const questId = Number(row.to_quest_id);
1174
- const unlockedBy = unlockedByQuestId.get(questId) ?? [];
1175
- unlockedBy.push(Number(row.from_quest_id));
1176
- unlockedByQuestId.set(questId, unlockedBy);
1177
- }
1178
- return rows.map((row) => {
1179
- const quest = mapQuestRow(row);
1180
- const blockerCount = Number(row.blocker_count ?? 0);
1181
- const effectiveDueAt = row.effective_due_at == null ? null : Number(row.effective_due_at);
1182
- const rewards = rewardsByQuestId.get(quest.id) ?? [];
1183
- const state = deriveQuestState(quest);
1184
- const available = quest.deletedAt == null && quest.resolvedAt == null && (quest.notBeforeAt == null || quest.notBeforeAt <= now) && blockerCount === 0;
1185
- const markerId = deriveQuestMarkerId({
1186
- state,
1187
- available,
1188
- hasUnclaimedReward: rewards.some((reward) => reward.claimedAt == null),
1189
- notBeforeAt: quest.notBeforeAt,
1190
- blockerCount,
1191
- now
1192
- });
1193
- return {
1194
- detail: {
1195
- ...quest,
1196
- state,
1197
- markerId,
1198
- effectiveDueAt,
1199
- available,
1200
- tagNames: tagNamesByQuestId.get(quest.id) ?? [],
1201
- rewards,
1202
- unlocksQuestIds: unlocksByQuestId.get(quest.id) ?? [],
1203
- unlockedByQuestIds: unlockedByQuestId.get(quest.id) ?? []
1204
- },
1205
- blockerCount
1206
- };
1931
+ return { abandonedQuest, followupQuests };
1207
1932
  });
1208
1933
  }
1209
1934
 
1935
+ // src/quests/finish_quest.ts
1936
+ function finishQuest(db, questId, outcome, resolvedAt) {
1937
+ return resolveQuest(db, questId, true, outcome, resolvedAt);
1938
+ }
1939
+
1210
1940
  // src/quests/get_quest_detail.ts
1211
1941
  function getQuestDetail(db, questId, now = Date.now()) {
1212
1942
  const [record] = queryQuestDetailRecords(db, {}, now, [questId]);
@@ -1379,92 +2109,15 @@ function startQuest(db, questId, startedAt) {
1379
2109
  return current;
1380
2110
  }
1381
2111
  if (current.resolvedAt != null) {
1382
- throw new Error("Resolved quests cannot be started.");
1383
- }
1384
- const now = resolveNow(startedAt);
1385
- db.prepare(
1386
- `UPDATE quests
1387
- SET started_at = ?, updated_at = ?
1388
- WHERE id = ? AND deleted_at IS NULL`
1389
- ).run(now, now, questId);
1390
- return getQuestOrThrow(db, questId);
1391
- }
1392
-
1393
- // src/repeatable_quests/map_repeatable_quest_row.ts
1394
- function asBoolean2(value) {
1395
- return Number(value) === 1;
1396
- }
1397
- function mapRepeatableQuestRow(row) {
1398
- return {
1399
- id: Number(row.id),
1400
- questlineId: row.questline_id == null ? null : Number(row.questline_id),
1401
- title: String(row.title),
1402
- objective: String(row.objective),
1403
- rrule: String(row.rrule),
1404
- anchorAt: Number(row.anchor_at),
1405
- notBeforeOffsetSeconds: row.not_before_offset_seconds == null ? null : Number(row.not_before_offset_seconds),
1406
- dueOffsetSeconds: row.due_offset_seconds == null ? null : Number(row.due_offset_seconds),
1407
- scheduledStartOffsetSeconds: row.scheduled_start_offset_seconds == null ? null : Number(row.scheduled_start_offset_seconds),
1408
- scheduledEndOffsetSeconds: row.scheduled_end_offset_seconds == null ? null : Number(row.scheduled_end_offset_seconds),
1409
- allDay: asBoolean2(row.all_day),
1410
- estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
1411
- createdAt: Number(row.created_at),
1412
- updatedAt: Number(row.updated_at),
1413
- archivedAt: row.archived_at == null ? null : Number(row.archived_at),
1414
- deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
1415
- };
1416
- }
1417
-
1418
- // src/repeatable_quests/get_repeatable_quest_or_throw.ts
1419
- function getRepeatableQuestOrThrow(db, repeatableQuestId) {
1420
- const row = db.prepare("SELECT * FROM repeatable_quests WHERE id = ? AND deleted_at IS NULL").get(repeatableQuestId);
1421
- if (!row) {
1422
- throw new Error(`Repeatable quest ${repeatableQuestId} was not found.`);
1423
- }
1424
- return mapRepeatableQuestRow(row);
1425
- }
1426
-
1427
- // src/repeatable_quests/parse_rrule.ts
1428
- var WEEKDAY = {
1429
- SU: 0,
1430
- MO: 1,
1431
- TU: 2,
1432
- WE: 3,
1433
- TH: 4,
1434
- FR: 5,
1435
- SA: 6
1436
- };
1437
- function parseRRule(rrule) {
1438
- const parts = Object.fromEntries(
1439
- rrule.split(";").map((part) => part.trim()).filter(Boolean).map((part) => {
1440
- const [key, value] = part.split("=");
1441
- return [key, value];
1442
- })
1443
- );
1444
- const freq = parts.FREQ;
1445
- if (freq !== "DAILY" && freq !== "WEEKLY" && freq !== "MONTHLY" && freq !== "YEARLY") {
1446
- throw new Error(`Unsupported RRULE FREQ: ${freq ?? "missing"}`);
1447
- }
1448
- const interval = parts.INTERVAL == null ? 1 : Number(parts.INTERVAL);
1449
- if (!Number.isFinite(interval) || interval < 1) {
1450
- throw new Error("RRULE INTERVAL must be a positive integer.");
1451
- }
1452
- const count = parts.COUNT == null ? null : Number(parts.COUNT);
1453
- if (count != null && (!Number.isFinite(count) || count < 1)) {
1454
- throw new Error("RRULE COUNT must be a positive integer.");
1455
- }
1456
- const until = parts.UNTIL == null ? null : Date.parse(parts.UNTIL);
1457
- if (parts.UNTIL != null && Number.isNaN(until)) {
1458
- throw new Error("RRULE UNTIL must be parseable as a date.");
1459
- }
1460
- const byDay = parts.BYDAY == null ? null : parts.BYDAY.split(",").map((token) => {
1461
- const value = WEEKDAY[token];
1462
- if (value == null) {
1463
- throw new Error(`Unsupported RRULE BYDAY token: ${token}`);
1464
- }
1465
- return value;
1466
- });
1467
- return { freq, interval, count, until, byDay };
2112
+ throw new Error("Resolved quests cannot be started.");
2113
+ }
2114
+ const now = resolveNow(startedAt);
2115
+ db.prepare(
2116
+ `UPDATE quests
2117
+ SET started_at = ?, updated_at = ?
2118
+ WHERE id = ? AND deleted_at IS NULL`
2119
+ ).run(now, now, questId);
2120
+ return getQuestOrThrow(db, questId);
1468
2121
  }
1469
2122
 
1470
2123
  // src/repeatable_quests/update_repeatable_quest.ts
@@ -1625,138 +2278,6 @@ function createRepeatableQuest(db, input) {
1625
2278
  });
1626
2279
  }
1627
2280
 
1628
- // src/repeatable_quests/advance_anchor.ts
1629
- var WEEK_MS = 7 * 864e5;
1630
- function advanceAnchor(anchorAt, freq, interval) {
1631
- const date = new Date(anchorAt);
1632
- if (freq === "MONTHLY") {
1633
- date.setUTCMonth(date.getUTCMonth() + interval);
1634
- return date.getTime();
1635
- }
1636
- if (freq === "YEARLY") {
1637
- date.setUTCFullYear(date.getUTCFullYear() + interval);
1638
- return date.getTime();
1639
- }
1640
- return anchorAt + interval * WEEK_MS;
1641
- }
1642
-
1643
- // src/repeatable_quests/start_of_utc_day.ts
1644
- function startOfUtcDay(timestamp) {
1645
- const date = new Date(timestamp);
1646
- return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
1647
- }
1648
-
1649
- // src/repeatable_quests/start_of_utc_week.ts
1650
- var DAY_MS = 864e5;
1651
- function startOfUtcWeek(dayStart) {
1652
- const date = new Date(dayStart);
1653
- return dayStart - date.getUTCDay() * DAY_MS;
1654
- }
1655
-
1656
- // src/repeatable_quests/generate_anchors_until.ts
1657
- var DAY_MS2 = 864e5;
1658
- var WEEK_MS2 = 7 * DAY_MS2;
1659
- function generateAnchorsUntil(repeatable, now) {
1660
- const rule = parseRRule(repeatable.rrule);
1661
- const anchors = [];
1662
- const until = rule.until == null ? now : Math.min(now, rule.until);
1663
- if (repeatable.anchorAt > until) {
1664
- return anchors;
1665
- }
1666
- if (rule.freq === "DAILY") {
1667
- let occurrence2 = 0;
1668
- for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
1669
- occurrence2 += 1;
1670
- if (rule.count != null && occurrence2 > rule.count) {
1671
- break;
1672
- }
1673
- anchors.push(current2);
1674
- }
1675
- return anchors;
1676
- }
1677
- if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
1678
- const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
1679
- const anchorWeekStart = startOfUtcWeek(anchorDayStart);
1680
- const timeOffset = repeatable.anchorAt - anchorDayStart;
1681
- let occurrence2 = 0;
1682
- for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
1683
- const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
1684
- if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
1685
- continue;
1686
- }
1687
- if (!rule.byDay.includes(new Date(day).getUTCDay())) {
1688
- continue;
1689
- }
1690
- const anchor = day + timeOffset;
1691
- if (anchor < repeatable.anchorAt || anchor > until) {
1692
- continue;
1693
- }
1694
- occurrence2 += 1;
1695
- if (rule.count != null && occurrence2 > rule.count) {
1696
- break;
1697
- }
1698
- anchors.push(anchor);
1699
- }
1700
- return anchors;
1701
- }
1702
- let occurrence = 0;
1703
- let current = repeatable.anchorAt;
1704
- while (current <= until) {
1705
- occurrence += 1;
1706
- if (rule.count != null && occurrence > rule.count) {
1707
- break;
1708
- }
1709
- anchors.push(current);
1710
- current = advanceAnchor(current, rule.freq, rule.interval);
1711
- }
1712
- return anchors;
1713
- }
1714
-
1715
- // src/repeatable_quests/list_due_repeatable_quest_anchors.ts
1716
- function listDueRepeatableQuestAnchors(db, now) {
1717
- const repeatables = db.prepare(
1718
- `SELECT *
1719
- FROM repeatable_quests
1720
- WHERE deleted_at IS NULL
1721
- AND archived_at IS NULL`
1722
- ).all().map(mapRepeatableQuestRow);
1723
- const anchors = [];
1724
- if (repeatables.length === 0) {
1725
- return anchors;
1726
- }
1727
- const repeatableIds = repeatables.map((repeatable) => repeatable.id);
1728
- const maxAnchorAt = Math.max(
1729
- ...repeatables.map((repeatable) => Math.max(repeatable.anchorAt, now))
1730
- );
1731
- const existingRows = db.prepare(
1732
- `SELECT spawned_from_repeatable_id, spawned_for_at
1733
- FROM quests
1734
- WHERE spawned_from_repeatable_id IN (${repeatableIds.map(() => "?").join(", ")})
1735
- AND spawned_for_at IS NOT NULL
1736
- AND spawned_for_at <= ?`
1737
- ).all(...repeatableIds, maxAnchorAt);
1738
- const existingAnchors = new Set(
1739
- existingRows.map(
1740
- (row) => `${Number(row.spawned_from_repeatable_id)}:${Number(row.spawned_for_at)}`
1741
- )
1742
- );
1743
- for (const repeatable of repeatables) {
1744
- const dueAnchors = generateAnchorsUntil(repeatable, now);
1745
- for (const anchorAt of dueAnchors) {
1746
- if (!existingAnchors.has(`${repeatable.id}:${anchorAt}`)) {
1747
- anchors.push({
1748
- repeatableQuestId: repeatable.id,
1749
- anchorAt,
1750
- markerId: "attention.available.repeatable"
1751
- });
1752
- }
1753
- }
1754
- }
1755
- return anchors.sort(
1756
- (a, b) => a.anchorAt - b.anchorAt || a.repeatableQuestId - b.repeatableQuestId
1757
- );
1758
- }
1759
-
1760
2281
  // src/repeatable_quests/soft_delete_repeatable_quest.ts
1761
2282
  function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
1762
2283
  const now = resolveNow(deletedAt);
@@ -1768,95 +2289,6 @@ function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
1768
2289
  ).run(now, now, repeatableQuestId);
1769
2290
  }
1770
2291
 
1771
- // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
1772
- function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
1773
- const effectiveNow = resolveNow(now);
1774
- const rows = db.prepare(
1775
- `SELECT kind, name, description, quantity
1776
- FROM repeatable_quest_rewards
1777
- WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
1778
- ).all(repeatableQuestId);
1779
- for (const row of rows) {
1780
- db.prepare(
1781
- `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
1782
- VALUES (?, ?, ?, ?, ?, ?)`
1783
- ).run(
1784
- questId,
1785
- String(row.kind),
1786
- String(row.name),
1787
- row.description == null ? null : String(row.description),
1788
- row.quantity == null ? null : Number(row.quantity),
1789
- effectiveNow
1790
- );
1791
- }
1792
- }
1793
-
1794
- // src/tags/copy_repeatable_quest_tags_to_quest.ts
1795
- function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
1796
- const effectiveNow = resolveNow(now);
1797
- const rows = db.prepare(
1798
- `SELECT tag_id
1799
- FROM repeatable_quest_tags
1800
- WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
1801
- ).all(repeatableQuestId);
1802
- for (const row of rows) {
1803
- db.prepare(
1804
- `INSERT INTO quest_tags (quest_id, tag_id, created_at)
1805
- VALUES (?, ?, ?)`
1806
- ).run(questId, Number(row.tag_id), effectiveNow);
1807
- }
1808
- }
1809
-
1810
- // src/repeatable_quests/spawn_due_repeatable_quests.ts
1811
- function spawnDueRepeatableQuests(db, now) {
1812
- return withTransaction(db, () => {
1813
- const anchors = listDueRepeatableQuestAnchors(db, now);
1814
- const quests = [];
1815
- for (const anchor of anchors) {
1816
- const repeatable = getRepeatableQuestOrThrow(db, anchor.repeatableQuestId);
1817
- const created = db.prepare(
1818
- `INSERT INTO quests (
1819
- questline_id,
1820
- source_rumor_id,
1821
- spawned_by_quest_id,
1822
- spawned_from_repeatable_id,
1823
- spawned_for_at,
1824
- title,
1825
- objective,
1826
- created_at,
1827
- updated_at,
1828
- effort_seconds,
1829
- estimate_seconds,
1830
- not_before_at,
1831
- due_at,
1832
- scheduled_start_at,
1833
- scheduled_end_at,
1834
- all_day
1835
- ) VALUES (?, NULL, NULL, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
1836
- ).run(
1837
- repeatable.questlineId ?? null,
1838
- repeatable.id,
1839
- anchor.anchorAt,
1840
- repeatable.title,
1841
- repeatable.objective,
1842
- now,
1843
- now,
1844
- repeatable.estimateSeconds ?? null,
1845
- repeatable.notBeforeOffsetSeconds == null ? null : anchor.anchorAt + repeatable.notBeforeOffsetSeconds * 1e3,
1846
- repeatable.dueOffsetSeconds == null ? null : anchor.anchorAt + repeatable.dueOffsetSeconds * 1e3,
1847
- repeatable.scheduledStartOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledStartOffsetSeconds * 1e3,
1848
- repeatable.scheduledEndOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledEndOffsetSeconds * 1e3,
1849
- repeatable.allDay ? 1 : 0
1850
- );
1851
- const questId = Number(created.lastInsertRowid);
1852
- copyRepeatableQuestTagsToQuest(db, repeatable.id, questId, now);
1853
- copyRepeatableQuestRewardsToQuest(db, repeatable.id, questId, now);
1854
- quests.push(getQuestOrThrow(db, questId));
1855
- }
1856
- return quests;
1857
- });
1858
- }
1859
-
1860
2292
  // src/rumors/derive_rumor_state.ts
1861
2293
  function deriveRumorState(rumor) {
1862
2294
  if (rumor.dismissedAt != null) {
@@ -2862,8 +3294,16 @@ Failure handling:
2862
3294
  - Do not filter by tags and assume that is the same as a schedule or dependency review.`
2863
3295
  });
2864
3296
 
3297
+ // src/skills/webhooks.ts
3298
+ var webhooksSkill = defineQuestlogSkill({
3299
+ name: "webhooks",
3300
+ description: "Configure signed outbound event webhooks and verify deliveries.",
3301
+ content: '# Webhooks\n\nUse `questlog` to configure opt-in outbound automation. No server or scheduler is added.\nNo targets means no network calls. `manage_hooks` supports list, remove, tick with\n`dry_run`, and deliveries; add/test are CLI-only. `review_questlog` view `deliveries`\nand `questlog show <id>` expose pending/failed deliveries.\n\n```sh\nquestlog hook add https://example.org/wake --min-gap 60\nquestlog hook add https://example.org/team --tag work --events quest.due,quest.overdue --secret-stdin\nquestlog hook label work\nquestlog hook list\nquestlog tick --dry-run\nquestlog tick\nquestlog watch --interval 60\nquestlog hook test 1\nquestlog review deliveries\nquestlog show 12\nquestlog hook remove 1\n```\n\n`hook add` prints its random 32-byte signing secret once, also as `secret` in `--json`.\nSave it securely. `--secret-stdin` supplies one via stdin; there is no secret flag.\nList output redacts userinfo/query strings. Removal deletes the target and deliveries.\nDefault scope is the database; `--tag` matches quest tags, never rumors.\n`--events` defaults to all types. The DB label defaults to the filename without its\npath/extension (`questlog` in memory); set it to a name suitable for disclosure.\n\n```cron\n* * * * * questlog tick\n```\n\nCron\'s PATH may need `$HOME/.local/bin/questlog tick --db /path/to/quests.db`.\nWatch defaults to 60 seconds (minimum 5); SIGINT/SIGTERM finishes the current tick.\nTick exits 0 even when deliveries need retries. Dry-run records nothing and sends nothing.\n\nEvents are detected from the model at tick time:\n\n- `quest.due`: an unresolved, undeleted quest reaches its effective due time (own `due_at`, otherwise its undeleted questline\'s due time).\n- `quest.overdue`: that effective deadline is strictly earlier than now and the quest remains unresolved.\n- `quest.unblocked`: an unresolved quest is available, all active prerequisites have succeeded or been deleted, and at least one prerequisite succeeded after its unlock was installed. Occurrence time is the latest active prerequisite success or not-before time, whichever is later.\n- `repeatable.spawned`: a concrete repeatable instance was created; occurrence time is its creation time. Tick first materializes due anchors through the existing spawn operation.\n- `rumor.captured`: an undeleted rumor was created; occurrence time is its creation time, even if subsequently settled or dismissed.\n\nPersistent event keys contain type, entity ids, and occurrence time. Restarts and repeated\nticks do not repeat occurrences. Removed transitions between ticks cannot be reconstructed.\nOnly occurrences at/after target creation are assigned; tags are evaluated at assignment.\nTick materializes due repeatables using the existing spawn path, including during preview\nwith rollback. Batches contain only ids, event types, timestamps, and the DB label:\n\n```json\n{"type":"questlog.events","db":"work","deliveryId":"d_\u2026","sentAt":"2026-10-28T10:00:00.000Z","events":[{"id":"e_\u2026","type":"quest.due","questId":12,"occurredAt":"2026-10-28T09:59:00.000Z"}]}\n```\n\nHeaders are `content-type: application/json`, `user-agent: questlog/<version>`,\n`x-questlog-delivery: <deliveryId>`, `x-questlog-timestamp: <unix seconds>`, and\n`x-questlog-signature: sha256=<hex HMAC-SHA256(secret, timestamp + "." + rawBody)>`.\nNo titles, objectives, details, or tag text are sent. `hook test` sends a logged `hook.test`\nevent immediately, ignoring the min gap. Add and test are CLI-only in the tool facade;\n`manage_hooks` supports list, remove, tick (with `dry_run`), and deliveries.\n\n2xx delivers. Timeout is 5 seconds. Failures retry after 30 s, 1 m, 2 m, 4 m, doubling\nto 1 h plus <1 s jitter, subject to the target\'s min gap. Eight failures mark failed.\nRetries keep the delivery id/events; new events queue behind them. Keep the last 500\ndelivered log entries per target and all pending/failed entries. Transactional claims\nlease work for two minutes. A crash after receipt may retry: dedupe at the receiver.\n\n### Verifying a delivery\n\nCompute HMAC-SHA256 over `timestamp + "." + rawBody` with the secret and compare in constant\ntime. Reject timestamps older than 5 minutes (and timestamps too far in the future), then\ndedupe on `x-questlog-delivery`. Use durable deduplication storage in a production receiver.\nThis 15-line Node example uses an in-memory set:\n\n```js\nimport { createHmac, timingSafeEqual } from \'node:crypto\';\nimport { createServer } from \'node:http\';\nconst secret = process.env.WEBHOOK_SECRET, seen = new Set();\ncreateServer(async (req, res) => {\n const chunks = []; for await (const chunk of req) chunks.push(chunk);\n const rawBody = Buffer.concat(chunks), h = req.headers;\n const timestamp = h[\'x-questlog-timestamp\'], id = h[\'x-questlog-delivery\'];\n const age = Date.now() / 1000 - Number(timestamp);\n const expected = createHmac(\'sha256\', secret).update(timestamp + \'.\').update(rawBody).digest();\n const signature = String(h[\'x-questlog-signature\'] || \'\');\n const actual = Buffer.from(signature.slice(7), \'hex\');\n if (!id || !/^\\d+$/.test(timestamp) || age > 300 || age < -300 || !/^sha256=[a-f0-9]{64}$/.test(signature) || actual.length !== expected.length || !timingSafeEqual(actual, expected)) { res.writeHead(401).end(); return; }\n if (!seen.has(id)) { seen.add(id); console.log(JSON.parse(rawBody)); }\n res.writeHead(204).end();\n}).listen(8080, \'127.0.0.1\');\n```\n'
3302
+ });
3303
+
2865
3304
  // src/skills/skill_registry.ts
2866
3305
  var questlogSkills = [
3306
+ webhooksSkill,
2867
3307
  archiveDeleteAndPruneSkill,
2868
3308
  chooseWorkShapeSkill,
2869
3309
  clarifyAmbiguousRequestsSkill,
@@ -2969,6 +3409,8 @@ __export(tools_exports, {
2969
3409
  integerSchema: () => integerSchema,
2970
3410
  listQuestlogToolDefinitions: () => listQuestlogToolDefinitions,
2971
3411
  literalSchema: () => literalSchema,
3412
+ manageHooksTool: () => manageHooksTool,
3413
+ manageHooksToolName: () => manageHooksToolName,
2972
3414
  manageRepeatableTool: () => manageRepeatableTool,
2973
3415
  manageRepeatableToolHandler: () => manageRepeatableToolHandler,
2974
3416
  manageRepeatableToolName: () => manageRepeatableToolName,
@@ -3025,6 +3467,7 @@ var manageRepeatableToolName = "manage_repeatable";
3025
3467
  var tagWorkToolName = "tag_work";
3026
3468
  var rewardWorkToolName = "reward_work";
3027
3469
  var retireWorkToolName = "retire_work";
3470
+ var manageHooksToolName = "manage_hooks";
3028
3471
 
3029
3472
  // src/tools/tool_types.ts
3030
3473
  function withOptionalFields(result, options) {
@@ -3280,6 +3723,7 @@ function validateInput(schema, input, path = "$") {
3280
3723
 
3281
3724
  // src/tools/action_requirements.ts
3282
3725
  var actionRequirements = {
3726
+ manage_hooks: { remove: ["id"] },
3283
3727
  shape_work: {
3284
3728
  create_quest: ["quest"],
3285
3729
  create_questline: ["questline"],
@@ -3662,7 +4106,8 @@ function inspectQuestlogItemToolHandler(db, input) {
3662
4106
  detail: detailLevel === "full" ? detail : toQuestCompactDetail(detail)
3663
4107
  },
3664
4108
  related,
3665
- detailLevel
4109
+ detailLevel,
4110
+ deliveries: listDeliveries(db, { questId: detail.id })
3666
4111
  },
3667
4112
  { entities }
3668
4113
  );
@@ -3768,6 +4213,56 @@ var inspectQuestlogItemTool = defineQuestlogTool({
3768
4213
  handler: inspectQuestlogItemToolHandler
3769
4214
  });
3770
4215
 
4216
+ // src/tools/manage_hooks_tool.ts
4217
+ var manageHooksTool = defineQuestlogTool({
4218
+ name: "manage_hooks",
4219
+ description: "List or remove outbound webhook targets, run a tick, or inspect pending and failed deliveries.",
4220
+ whenToUse: "Use to operate configured outbound webhooks. Add and test targets with the CLI.",
4221
+ whenNotToUse: "Use quest tools to change work itself.",
4222
+ sideEffects: "writes_state",
4223
+ readOnly: false,
4224
+ supportsClarification: false,
4225
+ targetKinds: ["hook"],
4226
+ inputDescriptions: {
4227
+ action: "Operation to perform.",
4228
+ id: "Target id for removal.",
4229
+ dry_run: "Preview a tick without recording or sending."
4230
+ },
4231
+ outputDescription: "Returns redacted targets, delivery metadata, or a tick summary. Never returns signing secrets.",
4232
+ inputSchema: objectSchema(
4233
+ {
4234
+ action: enumSchema("Operation.", ["list", "remove", "tick", "deliveries"]),
4235
+ id: integerSchema("Target id."),
4236
+ dry_run: booleanSchema("Preview only.")
4237
+ },
4238
+ ["action"]
4239
+ ),
4240
+ handler: async (db, input) => {
4241
+ switch (input.action) {
4242
+ case "list":
4243
+ return toolSuccess("Webhook targets.", listHooks(db));
4244
+ case "deliveries":
4245
+ return toolSuccess("Pending and failed deliveries.", listDeliveries(db));
4246
+ case "remove":
4247
+ if (!Number.isSafeInteger(input.id) || Number(input.id) < 1)
4248
+ return toolFailure(
4249
+ "protocol",
4250
+ "invalid_input",
4251
+ "Target id required.",
4252
+ "Provide a positive target id.",
4253
+ { recovery: 'Pass {"action":"remove","id":1}' }
4254
+ );
4255
+ removeHook(db, Number(input.id));
4256
+ return toolSuccess("Webhook target removed.", {});
4257
+ case "tick":
4258
+ return toolSuccess(
4259
+ "Webhook tick completed.",
4260
+ await tickQuestlog(db, { dryRun: input.dry_run ?? false })
4261
+ );
4262
+ }
4263
+ }
4264
+ });
4265
+
3771
4266
  // src/tools/manage_repeatable_tool.ts
3772
4267
  function manageRepeatableToolHandler(db, input) {
3773
4268
  try {
@@ -4467,7 +4962,7 @@ function validateReviewInput(input) {
4467
4962
  'Use `filters.dayAt` only with `view: "quests.scheduled_for_day"`.'
4468
4963
  );
4469
4964
  }
4470
- if ((input.view === "rumors" || input.view === "questlines") && hasQuestFilters(input.filters)) {
4965
+ if ((input.view === "rumors" || input.view === "questlines" || input.view === "deliveries") && hasQuestFilters(input.filters)) {
4471
4966
  return toolFailure(
4472
4967
  "protocol",
4473
4968
  "invalid_input",
@@ -4535,6 +5030,15 @@ function reviewQuestlogToolHandler(db, input) {
4535
5030
  if (invalid) {
4536
5031
  return invalid;
4537
5032
  }
5033
+ if (input.view === "deliveries")
5034
+ return toolSuccess("Pending and failed deliveries.", {
5035
+ view: input.view,
5036
+ items: [],
5037
+ deliveries: listDeliveries(db),
5038
+ count: listDeliveries(db).length,
5039
+ appliedFilters: input.filters,
5040
+ evaluatedAt: input.now ?? Date.now()
5041
+ });
4538
5042
  const now = input.now ?? Date.now();
4539
5043
  let items = [];
4540
5044
  switch (input.view) {
@@ -4594,6 +5098,7 @@ var reviewQuestlogTool = defineQuestlogTool({
4594
5098
  inputSchema: objectSchema(
4595
5099
  {
4596
5100
  view: enumSchema("Which operational review surface to return.", [
5101
+ "deliveries",
4597
5102
  "questlines",
4598
5103
  "quests.active",
4599
5104
  "quests.available",
@@ -5795,6 +6300,7 @@ var tagWorkTool = defineQuestlogTool({
5795
6300
 
5796
6301
  // src/tools/tool_mapping.ts
5797
6302
  var questlogToolMappings = [
6303
+ { source: "tickQuestlog", tool: "manage_hooks", action: "tick" },
5798
6304
  { source: "searchQuestlog", tool: "search_questlog" },
5799
6305
  { source: "listRumors", tool: "review_questlog", action: "rumors" },
5800
6306
  { source: "listQuestlines", tool: "review_questlog", action: "questlines" },
@@ -5892,6 +6398,7 @@ var questlogToolMappings = [
5892
6398
 
5893
6399
  // src/tools/tool_registry.ts
5894
6400
  var questlogTools = [
6401
+ manageHooksTool,
5895
6402
  searchQuestlogTool,
5896
6403
  reviewQuestlogTool,
5897
6404
  inspectQuestlogItemTool,
@@ -5955,4 +6462,4 @@ __export(write_exports, {
5955
6462
  updateRumor: () => updateRumor
5956
6463
  });
5957
6464
 
5958
- export { initQuestlogTables, markers_exports as markers, read_exports as read, skills_exports as skills, soul_exports as soul, tools_exports as tools, write_exports as write };
6465
+ export { hooks_exports as hooks, initQuestlogTables, markers_exports as markers, read_exports as read, skills_exports as skills, soul_exports as soul, tools_exports as tools, write_exports as write };