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