@ghostpaw/questlog 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +144 -4
  2. package/SKILL.md +95 -40
  3. package/dist/chunk-7KTRNXTU.js +21 -0
  4. package/dist/chunk-D6EGZCT7.js +23 -0
  5. package/dist/chunk-GVD6A3RR.js +108 -0
  6. package/dist/{chunk-6KTQK3ZE.js → chunk-I2AMIXGP.js} +8 -0
  7. package/dist/{chunk-3B6FMHZU.js → chunk-IA2GVCZS.js} +35 -2
  8. package/dist/{chunk-DKH623HU.js → chunk-IL2QRKZL.js} +1 -4
  9. package/dist/{chunk-UTUQPSGO.js → chunk-KOWIVBG6.js} +68 -588
  10. package/dist/chunk-NBCCA6AX.js +31 -0
  11. package/dist/chunk-QK3H2AL5.js +36 -0
  12. package/dist/chunk-RBGQK5WP.js +949 -0
  13. package/dist/cli.js +1 -1
  14. package/dist/{cli_main-XNZP4TY2.js → cli_main-TEG3QTDP.js} +147 -128
  15. package/dist/index.cjs +1152 -627
  16. package/dist/index.d.cts +142 -11
  17. package/dist/index.d.ts +142 -11
  18. package/dist/index.js +1152 -628
  19. package/dist/list_deliveries-WJEJUZIQ.js +2 -0
  20. package/dist/list_hooks-C5CAA2C7.js +2 -0
  21. package/dist/mcp-server.js +840 -389
  22. package/dist/mcp.cjs +709 -322
  23. package/dist/mcp.js +711 -324
  24. package/dist/open_questlog_db-6NS6BVBC.js +2 -0
  25. package/dist/{questlog_skill_spec-EM6DGGVN.js → questlog_skill_spec-ILTCTRYS.js} +16 -8
  26. package/dist/run_hook_command-BOENYNDT.js +155 -0
  27. package/dist/{serve_questlog_mcp-KFUYJB2P.js → serve_questlog_mcp-X524X34F.js} +6 -3
  28. package/dist/{skill_markdown-HXYQ3K6U.js → skill_markdown-EGKYZ3W2.js} +4 -20
  29. package/dist/text_output-X7F3K23Q.js +2 -0
  30. package/package.json +1 -1
  31. package/skills/questlog/SKILL.md +95 -40
  32. package/skills/questlog/references/webhooks.md +94 -0
  33. package/dist/open_questlog_db-SH3DAU4C.js +0 -2
package/dist/index.js CHANGED
@@ -1,9 +1,1043 @@
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))
47
+ throw new Error(`unsupported scheme ${url.protocol}; use http or https`);
48
+ if (url.username || url.password)
49
+ throw new Error(
50
+ "URL userinfo is not supported; use a custom header (--header or --header-stdin) or a query key instead"
51
+ );
52
+ const minGap = input.minGap ?? 60;
53
+ if (!Number.isSafeInteger(minGap) || minGap < 0)
54
+ throw new Error("Min gap must be a nonnegative integer");
55
+ const events = input.events ?? [...hookEventTypes];
56
+ if (!events.length || events.some((e) => !hookEventTypes.includes(e)))
57
+ throw new Error(
58
+ `unknown event ${events.find((e) => !hookEventTypes.includes(e)) ?? "(empty)"}; valid: ${hookEventTypes.join(", ")}`
59
+ );
60
+ if (input.tag !== void 0 && !normalizeTagName(input.tag))
61
+ throw new Error("Expected a tag name");
62
+ const secret = input.secret ?? randomBytes(32).toString("hex");
63
+ if (!secret.trim()) throw new Error("Expected a nonempty signing secret");
64
+ const result = db.prepare(
65
+ "INSERT INTO hook_targets(url, secret, tag, events, min_gap, created_at) VALUES (?, ?, ?, ?, ?, ?)"
66
+ ).run(
67
+ url.href,
68
+ secret,
69
+ input.tag === void 0 ? null : normalizeTagName(input.tag),
70
+ JSON.stringify(events),
71
+ minGap,
72
+ input.now ?? Date.now()
73
+ );
74
+ return { id: Number(result.lastInsertRowid), secret };
75
+ }
76
+ function hookLabel(db, name) {
77
+ if (name !== void 0) {
78
+ if (!name.trim()) throw new Error("Expected a nonempty database label");
79
+ db.prepare(
80
+ "INSERT INTO hook_settings(id, label) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET label = excluded.label"
81
+ ).run(name);
82
+ }
83
+ const saved = db.prepare("SELECT label FROM hook_settings WHERE id = 1").get();
84
+ if (saved) return String(saved.label);
85
+ const path = String(
86
+ db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? ""
87
+ );
88
+ return path ? basename(path, extname(path)) : "questlog";
89
+ }
90
+
91
+ // src/hooks/list_deliveries.ts
92
+ function listDeliveries(db, options = {}) {
93
+ return db.prepare(
94
+ `SELECT * FROM hook_deliveries ${options.includeDelivered ? "" : "WHERE status <> 'delivered'"} ORDER BY target_id, next_attempt_at, id`
95
+ ).all().map(
96
+ (row) => ({
97
+ id: String(row.id),
98
+ targetId: Number(row.target_id),
99
+ events: JSON.parse(String(row.events)),
100
+ status: row.status,
101
+ attempts: Number(row.attempts),
102
+ lastAttemptAt: row.last_attempt_at == null ? null : Number(row.last_attempt_at),
103
+ httpStatus: row.http_status == null ? null : Number(row.http_status),
104
+ errorClass: row.error_class == null ? null : String(row.error_class),
105
+ nextAttemptAt: Number(row.next_attempt_at)
106
+ })
107
+ ).filter(
108
+ (d) => options.questId === void 0 || d.events.some((e) => e.questId === options.questId)
109
+ );
110
+ }
111
+
112
+ // src/hooks/list_hooks.ts
113
+ function listHooks(db) {
114
+ return db.prepare(`SELECT id, url, headers, tag, events, min_gap, created_at, last_wake,
115
+ (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,
116
+ (SELECT COUNT(*) FROM hook_deliveries d WHERE d.target_id = t.id AND d.status = 'failed') AS failed
117
+ FROM hook_targets t ORDER BY id`).all().map((row) => {
118
+ const url = new URL(String(row.url));
119
+ url.username = "";
120
+ url.password = "";
121
+ url.search = "";
122
+ url.hash = "";
123
+ return {
124
+ id: Number(row.id),
125
+ headers: Object.fromEntries(
126
+ Object.keys(JSON.parse(String(row.headers))).map((name) => [name, "***"])
127
+ ),
128
+ scope: row.tag == null ? "database" : "tag",
129
+ url: url.href,
130
+ tag: row.tag == null ? null : String(row.tag),
131
+ events: JSON.parse(String(row.events)),
132
+ minGap: Number(row.min_gap),
133
+ createdAt: Number(row.created_at),
134
+ lastWake: row.last_wake == null ? null : Number(row.last_wake),
135
+ pending: Number(row.pending),
136
+ failed: Number(row.failed)
137
+ };
138
+ });
139
+ }
140
+
141
+ // src/with_transaction.ts
142
+ var transactionDepth = /* @__PURE__ */ new WeakMap();
143
+ function withTransaction(db, fn) {
144
+ const depth = transactionDepth.get(db) ?? 0;
145
+ const savepoint = `questlog_${depth}`;
146
+ if (depth === 0) {
147
+ db.exec("BEGIN IMMEDIATE");
148
+ } else {
149
+ db.exec(`SAVEPOINT ${savepoint}`);
150
+ }
151
+ transactionDepth.set(db, depth + 1);
152
+ try {
153
+ const result = fn();
154
+ if (depth === 0) {
155
+ db.exec("COMMIT");
156
+ } else {
157
+ db.exec(`RELEASE SAVEPOINT ${savepoint}`);
158
+ }
159
+ transactionDepth.set(db, depth);
160
+ return result;
161
+ } catch (error) {
162
+ try {
163
+ if (depth === 0) {
164
+ db.exec("ROLLBACK");
165
+ } else {
166
+ db.exec(`ROLLBACK TO SAVEPOINT ${savepoint}`);
167
+ db.exec(`RELEASE SAVEPOINT ${savepoint}`);
168
+ }
169
+ } catch {
170
+ }
171
+ transactionDepth.set(db, depth);
172
+ throw error;
173
+ }
174
+ }
175
+
176
+ // src/hooks/remove_hook.ts
177
+ function removeHook(db, id) {
178
+ withTransaction(db, () => {
179
+ db.prepare("DELETE FROM hook_assignments WHERE target_id = ?").run(id);
180
+ db.prepare("DELETE FROM hook_deliveries WHERE target_id = ?").run(id);
181
+ db.prepare("DELETE FROM hook_targets WHERE id = ?").run(id);
182
+ });
183
+ }
184
+
185
+ // src/version.ts
186
+ var questlogVersion = "0.11.0";
187
+
188
+ // src/hooks/send_hook_delivery.ts
189
+ async function sendHookDelivery(db, delivery, target, options) {
190
+ const now = options.now ?? options.clock?.() ?? Date.now();
191
+ const timestamp = String(Math.floor(now / 1e3));
192
+ const body = JSON.stringify({
193
+ type: "questlog.events",
194
+ db: hookLabel(db),
195
+ deliveryId: delivery.id,
196
+ sentAt: new Date(now).toISOString(),
197
+ events: delivery.events
198
+ });
199
+ const signature = createHmac("sha256", target.secret).update(`${timestamp}.${body}`).digest("hex");
200
+ let status = null;
201
+ let errorClass = null;
202
+ try {
203
+ const response = await (options.fetch ?? globalThis.fetch)(target.url, {
204
+ method: "POST",
205
+ redirect: "error",
206
+ headers: {
207
+ "user-agent": `questlog/${questlogVersion}`,
208
+ ...JSON.parse(
209
+ String(
210
+ db.prepare("SELECT headers FROM hook_targets WHERE id = ?").get(target.id)?.headers ?? "{}"
211
+ )
212
+ ),
213
+ "content-type": "application/json",
214
+ "x-questlog-delivery": delivery.id,
215
+ "x-questlog-timestamp": timestamp,
216
+ "x-questlog-signature": `sha256=${signature}`
217
+ },
218
+ body,
219
+ signal: AbortSignal.timeout(Math.max(1, Math.min(options.timeoutMs ?? 5e3, 5e3)))
220
+ });
221
+ status = response.status;
222
+ await response.body?.cancel();
223
+ } catch (error) {
224
+ errorClass = error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name) ? error.name : "NetworkError";
225
+ }
226
+ const delivered = status != null && status >= 200 && status < 300;
227
+ const completedAt = options.now ?? options.clock?.() ?? Date.now();
228
+ withTransaction(db, () => {
229
+ if (!db.prepare("SELECT id FROM hook_targets WHERE id = ? AND claim = ?").get(target.id, target.claim))
230
+ return;
231
+ const delay = Math.min(36e5, 3e4 * 2 ** (delivery.attempts - 1));
232
+ const jitter = Number.parseInt(randomBytes(2).toString("hex"), 16) % 1e3;
233
+ db.prepare(
234
+ "UPDATE hook_deliveries SET status = ?, http_status = ?, error_class = ?, next_attempt_at = ? WHERE id = ?"
235
+ ).run(
236
+ delivered ? "delivered" : delivery.attempts >= 8 ? "failed" : "pending",
237
+ status,
238
+ errorClass,
239
+ completedAt + delay + jitter,
240
+ delivery.id
241
+ );
242
+ db.prepare(
243
+ "UPDATE hook_targets SET claim = NULL, lease_until = NULL WHERE id = ? AND claim = ?"
244
+ ).run(target.id, target.claim);
245
+ db.prepare(
246
+ "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)"
247
+ ).run(target.id, target.id);
248
+ });
249
+ return delivered;
250
+ }
251
+
252
+ // src/hooks/test_hook.ts
253
+ async function testHook(db, id, options = {}) {
254
+ const now = options.now ?? options.clock?.() ?? Date.now();
255
+ const claim = randomBytes(16).toString("hex");
256
+ const delivery = {
257
+ id: `d_${randomBytes(16).toString("hex")}`,
258
+ targetId: id,
259
+ events: [
260
+ {
261
+ id: `e_test_${randomBytes(16).toString("hex")}`,
262
+ type: "hook.test",
263
+ occurredAt: new Date(now).toISOString()
264
+ }
265
+ ],
266
+ status: "pending",
267
+ attempts: 1,
268
+ lastAttemptAt: now,
269
+ httpStatus: null,
270
+ errorClass: null,
271
+ nextAttemptAt: now
272
+ };
273
+ const target = withTransaction(db, () => {
274
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(id);
275
+ if (!row) throw new Error("Hook not found");
276
+ if (row.lease_until != null && Number(row.lease_until) > now)
277
+ throw new Error("Hook delivery is in progress");
278
+ db.prepare(
279
+ "INSERT INTO hook_deliveries(id, target_id, events, status, attempts, last_attempt_at, next_attempt_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
280
+ ).run(delivery.id, id, JSON.stringify(delivery.events), "pending", 1, now, now);
281
+ db.prepare(
282
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
283
+ ).run(claim, now + 12e4, now, id);
284
+ return { id, url: String(row.url), secret: String(row.secret), claim };
285
+ });
286
+ return { id: delivery.id, delivered: await sendHookDelivery(db, delivery, target, options) };
287
+ }
288
+
289
+ // src/quests/map_quest_row.ts
290
+ function asBoolean(value) {
291
+ return Number(value) === 1;
292
+ }
293
+ function mapQuestRow(row) {
294
+ return {
295
+ id: Number(row.id),
296
+ questlineId: row.questline_id == null ? null : Number(row.questline_id),
297
+ sourceRumorId: row.source_rumor_id == null ? null : Number(row.source_rumor_id),
298
+ spawnedByQuestId: row.spawned_by_quest_id == null ? null : Number(row.spawned_by_quest_id),
299
+ spawnedFromRepeatableId: row.spawned_from_repeatable_id == null ? null : Number(row.spawned_from_repeatable_id),
300
+ spawnedForAt: row.spawned_for_at == null ? null : Number(row.spawned_for_at),
301
+ title: String(row.title),
302
+ objective: String(row.objective),
303
+ outcome: row.outcome == null ? null : String(row.outcome),
304
+ createdAt: Number(row.created_at),
305
+ updatedAt: Number(row.updated_at),
306
+ startedAt: row.started_at == null ? null : Number(row.started_at),
307
+ resolvedAt: row.resolved_at == null ? null : Number(row.resolved_at),
308
+ success: row.success == null ? null : asBoolean(row.success),
309
+ effortSeconds: Number(row.effort_seconds),
310
+ estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
311
+ notBeforeAt: row.not_before_at == null ? null : Number(row.not_before_at),
312
+ dueAt: row.due_at == null ? null : Number(row.due_at),
313
+ scheduledStartAt: row.scheduled_start_at == null ? null : Number(row.scheduled_start_at),
314
+ scheduledEndAt: row.scheduled_end_at == null ? null : Number(row.scheduled_end_at),
315
+ allDay: asBoolean(row.all_day),
316
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
317
+ };
318
+ }
319
+
320
+ // src/quests/get_quest_or_throw.ts
321
+ function getQuestOrThrow(db, questId) {
322
+ const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
323
+ if (!row) {
324
+ throw new Error(`Quest ${questId} was not found.`);
325
+ }
326
+ return mapQuestRow(row);
327
+ }
328
+
329
+ // src/resolve_now.ts
330
+ function resolveNow(now) {
331
+ return now ?? Date.now();
332
+ }
333
+
334
+ // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
335
+ function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
336
+ const effectiveNow = resolveNow(now);
337
+ const rows = db.prepare(
338
+ `SELECT kind, name, description, quantity
339
+ FROM repeatable_quest_rewards
340
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
341
+ ).all(repeatableQuestId);
342
+ for (const row of rows) {
343
+ db.prepare(
344
+ `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
345
+ VALUES (?, ?, ?, ?, ?, ?)`
346
+ ).run(
347
+ questId,
348
+ String(row.kind),
349
+ String(row.name),
350
+ row.description == null ? null : String(row.description),
351
+ row.quantity == null ? null : Number(row.quantity),
352
+ effectiveNow
353
+ );
354
+ }
355
+ }
356
+
357
+ // src/tags/copy_repeatable_quest_tags_to_quest.ts
358
+ function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
359
+ const effectiveNow = resolveNow(now);
360
+ const rows = db.prepare(
361
+ `SELECT tag_id
362
+ FROM repeatable_quest_tags
363
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
364
+ ).all(repeatableQuestId);
365
+ for (const row of rows) {
366
+ db.prepare(
367
+ `INSERT INTO quest_tags (quest_id, tag_id, created_at)
368
+ VALUES (?, ?, ?)`
369
+ ).run(questId, Number(row.tag_id), effectiveNow);
370
+ }
371
+ }
372
+
373
+ // src/repeatable_quests/map_repeatable_quest_row.ts
374
+ function asBoolean2(value) {
375
+ return Number(value) === 1;
376
+ }
377
+ function mapRepeatableQuestRow(row) {
378
+ return {
379
+ id: Number(row.id),
380
+ questlineId: row.questline_id == null ? null : Number(row.questline_id),
381
+ title: String(row.title),
382
+ objective: String(row.objective),
383
+ rrule: String(row.rrule),
384
+ anchorAt: Number(row.anchor_at),
385
+ notBeforeOffsetSeconds: row.not_before_offset_seconds == null ? null : Number(row.not_before_offset_seconds),
386
+ dueOffsetSeconds: row.due_offset_seconds == null ? null : Number(row.due_offset_seconds),
387
+ scheduledStartOffsetSeconds: row.scheduled_start_offset_seconds == null ? null : Number(row.scheduled_start_offset_seconds),
388
+ scheduledEndOffsetSeconds: row.scheduled_end_offset_seconds == null ? null : Number(row.scheduled_end_offset_seconds),
389
+ allDay: asBoolean2(row.all_day),
390
+ estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
391
+ createdAt: Number(row.created_at),
392
+ updatedAt: Number(row.updated_at),
393
+ archivedAt: row.archived_at == null ? null : Number(row.archived_at),
394
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
395
+ };
396
+ }
397
+
398
+ // src/repeatable_quests/get_repeatable_quest_or_throw.ts
399
+ function getRepeatableQuestOrThrow(db, repeatableQuestId) {
400
+ const row = db.prepare("SELECT * FROM repeatable_quests WHERE id = ? AND deleted_at IS NULL").get(repeatableQuestId);
401
+ if (!row) {
402
+ throw new Error(`Repeatable quest ${repeatableQuestId} was not found.`);
403
+ }
404
+ return mapRepeatableQuestRow(row);
405
+ }
406
+
407
+ // src/repeatable_quests/advance_anchor.ts
408
+ var WEEK_MS = 7 * 864e5;
409
+ function advanceAnchor(anchorAt, freq, interval) {
410
+ const date = new Date(anchorAt);
411
+ if (freq === "MONTHLY") {
412
+ date.setUTCMonth(date.getUTCMonth() + interval);
413
+ return date.getTime();
414
+ }
415
+ if (freq === "YEARLY") {
416
+ date.setUTCFullYear(date.getUTCFullYear() + interval);
417
+ return date.getTime();
418
+ }
419
+ return anchorAt + interval * WEEK_MS;
420
+ }
421
+
422
+ // src/repeatable_quests/parse_rrule.ts
423
+ var WEEKDAY = {
424
+ SU: 0,
425
+ MO: 1,
426
+ TU: 2,
427
+ WE: 3,
428
+ TH: 4,
429
+ FR: 5,
430
+ SA: 6
431
+ };
432
+ function parseRRule(rrule) {
433
+ const parts = Object.fromEntries(
434
+ rrule.split(";").map((part) => part.trim()).filter(Boolean).map((part) => {
435
+ const [key, value] = part.split("=");
436
+ return [key, value];
437
+ })
438
+ );
439
+ const freq = parts.FREQ;
440
+ if (freq !== "DAILY" && freq !== "WEEKLY" && freq !== "MONTHLY" && freq !== "YEARLY") {
441
+ throw new Error(`Unsupported RRULE FREQ: ${freq ?? "missing"}`);
442
+ }
443
+ const interval = parts.INTERVAL == null ? 1 : Number(parts.INTERVAL);
444
+ if (!Number.isFinite(interval) || interval < 1) {
445
+ throw new Error("RRULE INTERVAL must be a positive integer.");
446
+ }
447
+ const count = parts.COUNT == null ? null : Number(parts.COUNT);
448
+ if (count != null && (!Number.isFinite(count) || count < 1)) {
449
+ throw new Error("RRULE COUNT must be a positive integer.");
450
+ }
451
+ const until = parts.UNTIL == null ? null : Date.parse(parts.UNTIL);
452
+ if (parts.UNTIL != null && Number.isNaN(until)) {
453
+ throw new Error("RRULE UNTIL must be parseable as a date.");
454
+ }
455
+ const byDay = parts.BYDAY == null ? null : parts.BYDAY.split(",").map((token) => {
456
+ const value = WEEKDAY[token];
457
+ if (value == null) {
458
+ throw new Error(`Unsupported RRULE BYDAY token: ${token}`);
459
+ }
460
+ return value;
461
+ });
462
+ return { freq, interval, count, until, byDay };
463
+ }
464
+
465
+ // src/repeatable_quests/start_of_utc_day.ts
466
+ function startOfUtcDay(timestamp) {
467
+ const date = new Date(timestamp);
468
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
469
+ }
470
+
471
+ // src/repeatable_quests/start_of_utc_week.ts
472
+ var DAY_MS = 864e5;
473
+ function startOfUtcWeek(dayStart) {
474
+ const date = new Date(dayStart);
475
+ return dayStart - date.getUTCDay() * DAY_MS;
476
+ }
477
+
478
+ // src/repeatable_quests/generate_anchors_until.ts
479
+ var DAY_MS2 = 864e5;
480
+ var WEEK_MS2 = 7 * DAY_MS2;
481
+ function generateAnchorsUntil(repeatable, now) {
482
+ const rule = parseRRule(repeatable.rrule);
483
+ const anchors = [];
484
+ const until = rule.until == null ? now : Math.min(now, rule.until);
485
+ if (repeatable.anchorAt > until) {
486
+ return anchors;
487
+ }
488
+ if (rule.freq === "DAILY") {
489
+ let occurrence2 = 0;
490
+ for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
491
+ occurrence2 += 1;
492
+ if (rule.count != null && occurrence2 > rule.count) {
493
+ break;
494
+ }
495
+ anchors.push(current2);
496
+ }
497
+ return anchors;
498
+ }
499
+ if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
500
+ const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
501
+ const anchorWeekStart = startOfUtcWeek(anchorDayStart);
502
+ const timeOffset = repeatable.anchorAt - anchorDayStart;
503
+ let occurrence2 = 0;
504
+ for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
505
+ const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
506
+ if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
507
+ continue;
508
+ }
509
+ if (!rule.byDay.includes(new Date(day).getUTCDay())) {
510
+ continue;
511
+ }
512
+ const anchor = day + timeOffset;
513
+ if (anchor < repeatable.anchorAt || anchor > until) {
514
+ continue;
515
+ }
516
+ occurrence2 += 1;
517
+ if (rule.count != null && occurrence2 > rule.count) {
518
+ break;
519
+ }
520
+ anchors.push(anchor);
521
+ }
522
+ return anchors;
523
+ }
524
+ let occurrence = 0;
525
+ let current = repeatable.anchorAt;
526
+ while (current <= until) {
527
+ occurrence += 1;
528
+ if (rule.count != null && occurrence > rule.count) {
529
+ break;
530
+ }
531
+ anchors.push(current);
532
+ current = advanceAnchor(current, rule.freq, rule.interval);
533
+ }
534
+ return anchors;
535
+ }
536
+
537
+ // src/repeatable_quests/list_due_repeatable_quest_anchors.ts
538
+ function listDueRepeatableQuestAnchors(db, now) {
539
+ const repeatables = db.prepare(
540
+ `SELECT *
541
+ FROM repeatable_quests
542
+ WHERE deleted_at IS NULL
543
+ AND archived_at IS NULL`
544
+ ).all().map(mapRepeatableQuestRow);
545
+ const anchors = [];
546
+ if (repeatables.length === 0) {
547
+ return anchors;
548
+ }
549
+ const repeatableIds = repeatables.map((repeatable) => repeatable.id);
550
+ const maxAnchorAt = Math.max(
551
+ ...repeatables.map((repeatable) => Math.max(repeatable.anchorAt, now))
552
+ );
553
+ const existingRows = db.prepare(
554
+ `SELECT spawned_from_repeatable_id, spawned_for_at
555
+ FROM quests
556
+ WHERE spawned_from_repeatable_id IN (${repeatableIds.map(() => "?").join(", ")})
557
+ AND spawned_for_at IS NOT NULL
558
+ AND spawned_for_at <= ?`
559
+ ).all(...repeatableIds, maxAnchorAt);
560
+ const existingAnchors = new Set(
561
+ existingRows.map(
562
+ (row) => `${Number(row.spawned_from_repeatable_id)}:${Number(row.spawned_for_at)}`
563
+ )
564
+ );
565
+ for (const repeatable of repeatables) {
566
+ const dueAnchors = generateAnchorsUntil(repeatable, now);
567
+ for (const anchorAt of dueAnchors) {
568
+ if (!existingAnchors.has(`${repeatable.id}:${anchorAt}`)) {
569
+ anchors.push({
570
+ repeatableQuestId: repeatable.id,
571
+ anchorAt,
572
+ markerId: "attention.available.repeatable"
573
+ });
574
+ }
575
+ }
576
+ }
577
+ return anchors.sort(
578
+ (a, b) => a.anchorAt - b.anchorAt || a.repeatableQuestId - b.repeatableQuestId
579
+ );
580
+ }
581
+
582
+ // src/repeatable_quests/spawn_due_repeatable_quests.ts
583
+ function spawnDueRepeatableQuests(db, now) {
584
+ return withTransaction(db, () => {
585
+ const anchors = listDueRepeatableQuestAnchors(db, now);
586
+ const quests = [];
587
+ for (const anchor of anchors) {
588
+ const repeatable = getRepeatableQuestOrThrow(db, anchor.repeatableQuestId);
589
+ const created = db.prepare(
590
+ `INSERT INTO quests (
591
+ questline_id,
592
+ source_rumor_id,
593
+ spawned_by_quest_id,
594
+ spawned_from_repeatable_id,
595
+ spawned_for_at,
596
+ title,
597
+ objective,
598
+ created_at,
599
+ updated_at,
600
+ effort_seconds,
601
+ estimate_seconds,
602
+ not_before_at,
603
+ due_at,
604
+ scheduled_start_at,
605
+ scheduled_end_at,
606
+ all_day
607
+ ) VALUES (?, NULL, NULL, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
608
+ ).run(
609
+ repeatable.questlineId ?? null,
610
+ repeatable.id,
611
+ anchor.anchorAt,
612
+ repeatable.title,
613
+ repeatable.objective,
614
+ now,
615
+ now,
616
+ repeatable.estimateSeconds ?? null,
617
+ repeatable.notBeforeOffsetSeconds == null ? null : anchor.anchorAt + repeatable.notBeforeOffsetSeconds * 1e3,
618
+ repeatable.dueOffsetSeconds == null ? null : anchor.anchorAt + repeatable.dueOffsetSeconds * 1e3,
619
+ repeatable.scheduledStartOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledStartOffsetSeconds * 1e3,
620
+ repeatable.scheduledEndOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledEndOffsetSeconds * 1e3,
621
+ repeatable.allDay ? 1 : 0
622
+ );
623
+ const questId = Number(created.lastInsertRowid);
624
+ copyRepeatableQuestTagsToQuest(db, repeatable.id, questId, now);
625
+ copyRepeatableQuestRewardsToQuest(db, repeatable.id, questId, now);
626
+ quests.push(getQuestOrThrow(db, questId));
627
+ }
628
+ return quests;
629
+ });
630
+ }
631
+
632
+ // src/markers/derive_quest_marker_id.ts
633
+ function deriveQuestMarkerId({
634
+ state,
635
+ available,
636
+ hasUnclaimedReward,
637
+ notBeforeAt,
638
+ blockerCount,
639
+ now
640
+ }) {
641
+ if (state === "done") {
642
+ return hasUnclaimedReward ? "progress.complete" : null;
643
+ }
644
+ if (state === "abandoned") {
645
+ return null;
646
+ }
647
+ if (state === "in_progress") {
648
+ return "progress.incomplete";
649
+ }
650
+ if (available) {
651
+ return "attention.available";
652
+ }
653
+ if (notBeforeAt != null && notBeforeAt > now) {
654
+ return "attention.available.future";
655
+ }
656
+ if (blockerCount > 0) {
657
+ return "progress.incomplete";
658
+ }
659
+ return null;
660
+ }
661
+
662
+ // src/rewards/map_quest_reward_row.ts
663
+ function mapQuestRewardRow(row) {
664
+ return {
665
+ id: Number(row.id),
666
+ questId: Number(row.quest_id),
667
+ kind: String(row.kind),
668
+ name: String(row.name),
669
+ description: row.description == null ? null : String(row.description),
670
+ quantity: row.quantity == null ? null : Number(row.quantity),
671
+ createdAt: Number(row.created_at),
672
+ claimedAt: row.claimed_at == null ? null : Number(row.claimed_at),
673
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
674
+ };
675
+ }
676
+
677
+ // src/quests/derive_quest_state.ts
678
+ function deriveQuestState(quest) {
679
+ if (quest.resolvedAt != null && quest.success === true) {
680
+ return "done";
681
+ }
682
+ if (quest.resolvedAt != null && quest.success === false) {
683
+ return "abandoned";
684
+ }
685
+ if (quest.startedAt != null) {
686
+ return "in_progress";
687
+ }
688
+ return "open";
689
+ }
690
+
691
+ // src/quests/query_quest_detail_records.ts
692
+ function queryQuestDetailRecords(db, filters = {}, now = Date.now(), questIds) {
693
+ if (questIds && questIds.length === 0) {
694
+ return [];
695
+ }
696
+ const clauses = [];
697
+ const params = [];
698
+ if (!filters.includeDeleted) {
699
+ clauses.push("q.deleted_at IS NULL");
700
+ }
701
+ if (questIds && questIds.length > 0) {
702
+ clauses.push(`q.id IN (${questIds.map(() => "?").join(", ")})`);
703
+ params.push(...questIds);
704
+ }
705
+ if (filters.questlineId != null) {
706
+ clauses.push("q.questline_id = ?");
707
+ params.push(filters.questlineId);
708
+ }
709
+ if (filters.tagNames && filters.tagNames.length > 0) {
710
+ const normalized = [...new Set(filters.tagNames.map(normalizeTagName).filter(Boolean))];
711
+ for (const tag of normalized) {
712
+ clauses.push(
713
+ `EXISTS (
714
+ SELECT 1
715
+ FROM quest_tags qt
716
+ JOIN tags t ON t.id = qt.tag_id
717
+ WHERE qt.quest_id = q.id
718
+ AND qt.deleted_at IS NULL
719
+ AND t.deleted_at IS NULL
720
+ AND t.normalized_name = ?
721
+ )`
722
+ );
723
+ params.push(tag);
724
+ }
725
+ }
726
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
727
+ const rows = db.prepare(
728
+ `SELECT q.*,
729
+ COALESCE(q.due_at, ql.due_at) AS effective_due_at,
730
+ (
731
+ SELECT COUNT(*)
732
+ FROM quest_unlocks qu
733
+ JOIN quests blocker ON blocker.id = qu.from_quest_id
734
+ WHERE qu.to_quest_id = q.id
735
+ AND qu.deleted_at IS NULL
736
+ AND blocker.deleted_at IS NULL
737
+ AND NOT (blocker.resolved_at IS NOT NULL AND blocker.success = 1)
738
+ ) AS blocker_count
739
+ FROM quests q
740
+ LEFT JOIN questlines ql ON ql.id = q.questline_id AND ql.deleted_at IS NULL
741
+ ${where}
742
+ ORDER BY q.created_at DESC, q.id DESC`
743
+ ).all(...params);
744
+ if (rows.length === 0) {
745
+ return [];
746
+ }
747
+ const ids = rows.map((row) => Number(row.id));
748
+ const placeholders = ids.map(() => "?").join(", ");
749
+ const tagNamesByQuestId = /* @__PURE__ */ new Map();
750
+ const rewardsByQuestId = /* @__PURE__ */ new Map();
751
+ const unlocksByQuestId = /* @__PURE__ */ new Map();
752
+ const unlockedByQuestId = /* @__PURE__ */ new Map();
753
+ for (const row of db.prepare(
754
+ `SELECT qt.quest_id, t.name
755
+ FROM quest_tags qt
756
+ JOIN tags t ON t.id = qt.tag_id
757
+ WHERE qt.quest_id IN (${placeholders})
758
+ AND qt.deleted_at IS NULL
759
+ AND t.deleted_at IS NULL
760
+ ORDER BY qt.quest_id, t.name`
761
+ ).all(...ids)) {
762
+ const questId = Number(row.quest_id);
763
+ const tagNames = tagNamesByQuestId.get(questId) ?? [];
764
+ tagNames.push(String(row.name));
765
+ tagNamesByQuestId.set(questId, tagNames);
766
+ }
767
+ for (const row of db.prepare(
768
+ `SELECT *
769
+ FROM quest_rewards
770
+ WHERE quest_id IN (${placeholders})
771
+ AND deleted_at IS NULL
772
+ ORDER BY quest_id, created_at, id`
773
+ ).all(...ids)) {
774
+ const reward = mapQuestRewardRow(row);
775
+ const rewards = rewardsByQuestId.get(reward.questId) ?? [];
776
+ rewards.push(reward);
777
+ rewardsByQuestId.set(reward.questId, rewards);
778
+ }
779
+ for (const row of db.prepare(
780
+ `SELECT from_quest_id, to_quest_id
781
+ FROM quest_unlocks
782
+ WHERE from_quest_id IN (${placeholders})
783
+ AND deleted_at IS NULL
784
+ ORDER BY from_quest_id, to_quest_id`
785
+ ).all(...ids)) {
786
+ const questId = Number(row.from_quest_id);
787
+ const unlocks = unlocksByQuestId.get(questId) ?? [];
788
+ unlocks.push(Number(row.to_quest_id));
789
+ unlocksByQuestId.set(questId, unlocks);
790
+ }
791
+ for (const row of db.prepare(
792
+ `SELECT from_quest_id, to_quest_id
793
+ FROM quest_unlocks
794
+ WHERE to_quest_id IN (${placeholders})
795
+ AND deleted_at IS NULL
796
+ ORDER BY to_quest_id, from_quest_id`
797
+ ).all(...ids)) {
798
+ const questId = Number(row.to_quest_id);
799
+ const unlockedBy = unlockedByQuestId.get(questId) ?? [];
800
+ unlockedBy.push(Number(row.from_quest_id));
801
+ unlockedByQuestId.set(questId, unlockedBy);
802
+ }
803
+ return rows.map((row) => {
804
+ const quest = mapQuestRow(row);
805
+ const blockerCount = Number(row.blocker_count ?? 0);
806
+ const effectiveDueAt = row.effective_due_at == null ? null : Number(row.effective_due_at);
807
+ const rewards = rewardsByQuestId.get(quest.id) ?? [];
808
+ const state = deriveQuestState(quest);
809
+ const available = quest.deletedAt == null && quest.resolvedAt == null && (quest.notBeforeAt == null || quest.notBeforeAt <= now) && blockerCount === 0;
810
+ const markerId = deriveQuestMarkerId({
811
+ state,
812
+ available,
813
+ hasUnclaimedReward: rewards.some((reward) => reward.claimedAt == null),
814
+ notBeforeAt: quest.notBeforeAt,
815
+ blockerCount,
816
+ now
817
+ });
818
+ return {
819
+ detail: {
820
+ ...quest,
821
+ state,
822
+ markerId,
823
+ effectiveDueAt,
824
+ available,
825
+ tagNames: tagNamesByQuestId.get(quest.id) ?? [],
826
+ rewards,
827
+ unlocksQuestIds: unlocksByQuestId.get(quest.id) ?? [],
828
+ unlockedByQuestIds: unlockedByQuestId.get(quest.id) ?? []
829
+ },
830
+ blockerCount
831
+ };
832
+ });
833
+ }
834
+
835
+ // src/hooks/detect_hook_events.ts
836
+ function detectHookEvents(db, now) {
837
+ const events = [];
838
+ const add = (type, at, ids) => {
839
+ events.push({
840
+ id: `e_${type}_${ids.questId ?? ids.rumorId}_${ids.repeatableId ?? ""}_${at}`,
841
+ type,
842
+ ...ids,
843
+ occurredAt: new Date(at).toISOString()
844
+ });
845
+ };
846
+ for (const { detail: q } of queryQuestDetailRecords(db, {}, now)) {
847
+ if (q.resolvedAt == null && q.effectiveDueAt != null && q.effectiveDueAt <= now) {
848
+ add("quest.due", q.effectiveDueAt, { questId: q.id });
849
+ if (q.effectiveDueAt < now) add("quest.overdue", q.effectiveDueAt, { questId: q.id });
850
+ }
851
+ if (q.available) {
852
+ const prerequisites = db.prepare(
853
+ `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`
854
+ ).all(q.id);
855
+ if (prerequisites.some((p) => Number(p.resolved_at) >= Number(p.created_at))) {
856
+ const at = Math.max(q.notBeforeAt ?? 0, ...prerequisites.map((p) => Number(p.resolved_at)));
857
+ if (at <= now) add("quest.unblocked", at, { questId: q.id });
858
+ }
859
+ }
860
+ if (q.spawnedFromRepeatableId != null && q.createdAt <= now)
861
+ add("repeatable.spawned", q.createdAt, {
862
+ questId: q.id,
863
+ repeatableId: q.spawnedFromRepeatableId
864
+ });
865
+ }
866
+ for (const row of db.prepare("SELECT id, created_at FROM rumors WHERE deleted_at IS NULL AND created_at <= ?").all(now))
867
+ add("rumor.captured", Number(row.created_at), { rumorId: Number(row.id) });
868
+ return events.sort(
869
+ (a, b) => a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
870
+ );
871
+ }
872
+
873
+ // src/hooks/tick_questlog.ts
874
+ async function tickQuestlog(db, options = {}) {
875
+ const now = options.now ?? options.clock?.() ?? Date.now();
876
+ const result = {
877
+ events: [],
878
+ batches: [],
879
+ sent: 0,
880
+ queued: 0,
881
+ retrying: 0,
882
+ failed: 0
883
+ };
884
+ const claims = [];
885
+ const collect = () => {
886
+ spawnDueRepeatableQuests(db, now);
887
+ const detected = detectHookEvents(db, now);
888
+ result.events = detected.filter(
889
+ (e) => !db.prepare("SELECT id FROM hook_events WHERE id = ?").get(e.id)
890
+ );
891
+ for (const event of result.events)
892
+ db.prepare("INSERT INTO hook_events(id, occurred_at, event) VALUES (?, ?, ?)").run(
893
+ event.id,
894
+ Date.parse(event.occurredAt),
895
+ JSON.stringify(event)
896
+ );
897
+ for (const target of listHooks(db)) {
898
+ const events = db.prepare(
899
+ "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"
900
+ ).all(target.createdAt, target.id).map((row2) => JSON.parse(String(row2.event))).filter((event) => {
901
+ if (!target.events.includes(event.type)) return false;
902
+ if (target.tag == null) return true;
903
+ return event.questId !== void 0 && db.prepare(
904
+ "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 = ?"
905
+ ).get(event.questId, normalizeTagName(target.tag)) !== void 0;
906
+ });
907
+ for (const event of events)
908
+ db.prepare("INSERT INTO hook_assignments(target_id, event_id) VALUES (?, ?)").run(
909
+ target.id,
910
+ event.id
911
+ );
912
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(target.id);
913
+ if (!row || row.lease_until != null && Number(row.lease_until) > now) continue;
914
+ let pending = listDeliveries(db).find(
915
+ (d) => d.targetId === target.id && d.status === "pending"
916
+ );
917
+ const queued = db.prepare(
918
+ "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"
919
+ ).all(target.id).map((r) => JSON.parse(String(r.event)));
920
+ if (!pending && queued.length) {
921
+ const id = `d_${randomBytes(16).toString("hex")}`;
922
+ db.prepare(
923
+ "INSERT INTO hook_deliveries(id, target_id, events, status, next_attempt_at) VALUES (?, ?, ?, 'pending', ?)"
924
+ ).run(
925
+ id,
926
+ target.id,
927
+ JSON.stringify(queued),
928
+ Math.max(now, (target.lastWake ?? -Infinity) + target.minGap * 1e3)
929
+ );
930
+ db.prepare(
931
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
932
+ ).run(id, target.id);
933
+ pending = listDeliveries(db).find((d) => d.id === id);
934
+ }
935
+ if (!pending) continue;
936
+ if (pending.attempts === 0 && queued.length && !queued.every((e) => pending?.events.some((p) => p.id === e.id))) {
937
+ pending.events.push(...queued);
938
+ db.prepare("UPDATE hook_deliveries SET events = ? WHERE id = ?").run(
939
+ JSON.stringify(pending.events),
940
+ pending.id
941
+ );
942
+ db.prepare(
943
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
944
+ ).run(pending.id, target.id);
945
+ }
946
+ if (pending.nextAttemptAt > now || target.lastWake != null && target.lastWake + target.minGap * 1e3 > now)
947
+ continue;
948
+ if (pending.attempts >= 8) {
949
+ db.prepare("UPDATE hook_deliveries SET status = 'failed' WHERE id = ?").run(pending.id);
950
+ continue;
951
+ }
952
+ const claim = randomBytes(16).toString("hex");
953
+ db.prepare(
954
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
955
+ ).run(claim, now + 12e4, now, target.id);
956
+ db.prepare(
957
+ "UPDATE hook_deliveries SET attempts = attempts + 1, last_attempt_at = ? WHERE id = ?"
958
+ ).run(now, pending.id);
959
+ pending.attempts++;
960
+ pending.lastAttemptAt = now;
961
+ result.batches.push({ targetId: target.id, events: pending.events });
962
+ claims.push({
963
+ delivery: pending,
964
+ target: { id: target.id, url: String(row.url), secret: String(row.secret), claim }
965
+ });
966
+ }
967
+ };
968
+ if (options.dryRun) {
969
+ const rollback = new Error("preview rollback");
970
+ try {
971
+ withTransaction(db, () => {
972
+ collect();
973
+ throw rollback;
974
+ });
975
+ } catch (error) {
976
+ if (error !== rollback) throw error;
977
+ }
978
+ } else withTransaction(db, collect);
979
+ if (!options.dryRun) {
980
+ const sent = await Promise.all(
981
+ claims.map((claim) => sendHookDelivery(db, claim.delivery, claim.target, options))
982
+ );
983
+ result.sent = sent.filter(Boolean).length;
984
+ }
985
+ const deliveries = listDeliveries(db);
986
+ result.queued = deliveries.filter((d) => d.status === "pending" && d.attempts === 0).length + Number(
987
+ db.prepare(
988
+ "SELECT COUNT(DISTINCT target_id) AS n FROM hook_assignments WHERE delivery_id IS NULL"
989
+ ).get()?.n ?? 0
990
+ );
991
+ result.retrying = deliveries.filter((d) => d.status === "pending" && d.attempts > 0).length;
992
+ result.failed = deliveries.filter((d) => d.status === "failed").length;
993
+ return result;
994
+ }
995
+
996
+ // src/hooks/watch_questlog.ts
997
+ async function watchQuestlog(db, options) {
998
+ const interval = options.interval ?? 60;
999
+ if (!Number.isFinite(interval) || interval < 5)
1000
+ throw new Error("Interval must be at least 5 seconds");
1001
+ while (!options.signal.aborted) {
1002
+ options.onTick?.(await tickQuestlog(db, options));
1003
+ if (options.signal.aborted) break;
1004
+ await new Promise((resolve) => {
1005
+ const finish = () => {
1006
+ clearTimeout(timer);
1007
+ options.signal.removeEventListener("abort", finish);
1008
+ resolve();
1009
+ };
1010
+ const timer = setTimeout(finish, interval * 1e3);
1011
+ options.signal.addEventListener("abort", finish, { once: true });
1012
+ });
1013
+ }
1014
+ }
1015
+
1016
+ // src/hooks/init_hook_tables.ts
1017
+ function initHookTables(db) {
1018
+ db.exec(`
1019
+ CREATE TABLE IF NOT EXISTS hook_targets (
1020
+ id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, secret TEXT NOT NULL,
1021
+ tag TEXT, events TEXT NOT NULL, min_gap INTEGER NOT NULL, created_at INTEGER NOT NULL,
1022
+ last_wake INTEGER, lease_until INTEGER, claim TEXT);
1023
+ CREATE TABLE IF NOT EXISTS hook_events (
1024
+ id TEXT PRIMARY KEY, occurred_at INTEGER NOT NULL, event TEXT NOT NULL);
1025
+ CREATE TABLE IF NOT EXISTS hook_assignments (
1026
+ target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
1027
+ event_id TEXT NOT NULL REFERENCES hook_events(id), delivery_id TEXT,
1028
+ PRIMARY KEY(target_id, event_id));
1029
+ CREATE TABLE IF NOT EXISTS hook_deliveries (
1030
+ id TEXT PRIMARY KEY, target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
1031
+ events TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
1032
+ last_attempt_at INTEGER, http_status INTEGER, error_class TEXT,
1033
+ next_attempt_at INTEGER NOT NULL);
1034
+ CREATE INDEX IF NOT EXISTS idx_hook_deliveries_target ON hook_deliveries(target_id, status, next_attempt_at);
1035
+ CREATE TABLE IF NOT EXISTS hook_settings (id INTEGER PRIMARY KEY CHECK(id = 1), label TEXT NOT NULL);
1036
+ `);
1037
+ if (!db.prepare("PRAGMA table_info(hook_targets)").all().some((row) => row.name === "headers"))
1038
+ db.exec("ALTER TABLE hook_targets ADD COLUMN headers TEXT NOT NULL DEFAULT '{}'");
1039
+ }
1040
+
7
1041
  // src/questlines/init_questline_tables.ts
8
1042
  function initQuestlineTables(db) {
9
1043
  db.exec(`
@@ -352,6 +1386,7 @@ function initQuestlogTables(db) {
352
1386
  initTagTables(db);
353
1387
  initQuestSearch(db);
354
1388
  initRumorSearch(db);
1389
+ initHookTables(db);
355
1390
  }
356
1391
 
357
1392
  // src/markers/index.ts
@@ -362,36 +1397,6 @@ __export(markers_exports, {
362
1397
  markerLookup: () => markerLookup
363
1398
  });
364
1399
 
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
1400
  // src/markers/derive_rumor_marker_id.ts
396
1401
  function deriveRumorMarkerId({ state }) {
397
1402
  if (state === "open") {
@@ -479,11 +1484,6 @@ __export(read_exports, {
479
1484
  searchQuestlog: () => searchQuestlog
480
1485
  });
481
1486
 
482
- // src/resolve_now.ts
483
- function resolveNow(now) {
484
- return now ?? Date.now();
485
- }
486
-
487
1487
  // src/assert_non_empty.ts
488
1488
  function assertNonEmpty(value, label) {
489
1489
  const trimmed = value.trim();
@@ -493,41 +1493,6 @@ function assertNonEmpty(value, label) {
493
1493
  return trimmed;
494
1494
  }
495
1495
 
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
1496
  // src/questlines/map_questline_row.ts
532
1497
  function mapQuestlineRow(row) {
533
1498
  return {
@@ -756,46 +1721,6 @@ function softDeleteQuestline(db, questlineId, deletedAt) {
756
1721
  ).run(now, now, questlineId);
757
1722
  }
758
1723
 
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
1724
  // src/quests/resolve_quest.ts
800
1725
  function resolveQuest(db, questId, success, outcome, resolvedAt) {
801
1726
  const current = getQuestOrThrow(db, questId);
@@ -897,11 +1822,6 @@ function replaceActiveQuestRewards(db, questId, rewards, now) {
897
1822
  }
898
1823
  }
899
1824
 
900
- // src/tags/normalize_tag_name.ts
901
- function normalizeTagName(name) {
902
- return name.trim().toLowerCase().replace(/\s+/g, " ");
903
- }
904
-
905
1825
  // src/tags/replace_active_quest_tags.ts
906
1826
  function getOrCreateTagId(db, name, now) {
907
1827
  const normalizedName = normalizeTagName(name);
@@ -998,215 +1918,42 @@ function createQuest(db, input) {
998
1918
  if (input.tags && input.tags.length > 0) {
999
1919
  replaceActiveQuestTags(db, questId, input.tags, now);
1000
1920
  }
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";
1921
+ if (input.rewards && input.rewards.length > 0) {
1922
+ replaceActiveQuestRewards(db, questId, input.rewards, now);
1923
+ }
1924
+ return getQuestOrThrow(db, questId);
1925
+ });
1064
1926
  }
1065
1927
 
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);
1928
+ // src/quests/abandon_quest_and_spawn_followups.ts
1929
+ function abandonQuestAndSpawnFollowups(db, questId, outcome, followups, resolvedAt) {
1930
+ return withTransaction(db, () => {
1931
+ const abandonedQuest = abandonQuest(db, questId, outcome, resolvedAt);
1932
+ const now = resolveNow(resolvedAt);
1933
+ const followupQuests = followups.map(
1934
+ (followup) => createQuest(db, {
1935
+ ...followup,
1936
+ questlineId: followup.questlineId ?? abandonedQuest.questlineId,
1937
+ spawnedByQuestId: questId,
1938
+ now
1939
+ })
1940
+ );
1941
+ for (let i = 0; i < followups.length; i += 1) {
1942
+ const followup = followups[i];
1943
+ const created = followupQuests[i];
1944
+ if (followup?.unlocksParent && created) {
1945
+ addUnlock(db, created.id, questId, resolvedAt);
1946
+ }
1099
1947
  }
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
- };
1948
+ return { abandonedQuest, followupQuests };
1207
1949
  });
1208
1950
  }
1209
1951
 
1952
+ // src/quests/finish_quest.ts
1953
+ function finishQuest(db, questId, outcome, resolvedAt) {
1954
+ return resolveQuest(db, questId, true, outcome, resolvedAt);
1955
+ }
1956
+
1210
1957
  // src/quests/get_quest_detail.ts
1211
1958
  function getQuestDetail(db, questId, now = Date.now()) {
1212
1959
  const [record] = queryQuestDetailRecords(db, {}, now, [questId]);
@@ -1379,92 +2126,15 @@ function startQuest(db, questId, startedAt) {
1379
2126
  return current;
1380
2127
  }
1381
2128
  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 };
2129
+ throw new Error("Resolved quests cannot be started.");
2130
+ }
2131
+ const now = resolveNow(startedAt);
2132
+ db.prepare(
2133
+ `UPDATE quests
2134
+ SET started_at = ?, updated_at = ?
2135
+ WHERE id = ? AND deleted_at IS NULL`
2136
+ ).run(now, now, questId);
2137
+ return getQuestOrThrow(db, questId);
1468
2138
  }
1469
2139
 
1470
2140
  // src/repeatable_quests/update_repeatable_quest.ts
@@ -1625,138 +2295,6 @@ function createRepeatableQuest(db, input) {
1625
2295
  });
1626
2296
  }
1627
2297
 
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
2298
  // src/repeatable_quests/soft_delete_repeatable_quest.ts
1761
2299
  function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
1762
2300
  const now = resolveNow(deletedAt);
@@ -1768,95 +2306,6 @@ function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
1768
2306
  ).run(now, now, repeatableQuestId);
1769
2307
  }
1770
2308
 
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
2309
  // src/rumors/derive_rumor_state.ts
1861
2310
  function deriveRumorState(rumor) {
1862
2311
  if (rumor.dismissedAt != null) {
@@ -2862,8 +3311,16 @@ Failure handling:
2862
3311
  - Do not filter by tags and assume that is the same as a schedule or dependency review.`
2863
3312
  });
2864
3313
 
3314
+ // src/skills/webhooks.ts
3315
+ var webhooksSkill = defineQuestlogSkill({
3316
+ name: "webhooks",
3317
+ description: "Configure signed outbound event webhooks and verify deliveries.",
3318
+ 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.\nSecrets and custom header values are stored in the DB. New POSIX DB/WAL/SHM files use 0600 and created directories use 0700; existing DB modes are preserved. Windows uses existing access controls.\nUse repeatable `--header "Name: value"` or `--header-stdin` (one line per header, avoiding shell history). Headers are sent on every delivery and test; output shows names with `***` values. HTTP token names are required; host, content-length, content-type, and x-questlog-* are reserved. Change headers by removing and adding the hook again. Use --header-stdin and --secret-stdin separately. URL userinfo is rejected; use a custom header or query key.\n`questlog show d_\u2026` displays delivery status, attempts, HTTP status, next attempt, redacted target URL and event ids. Text is the default; --json prints JSON. Missing hook remove/test targets exit 3; missing quests/deliveries exit 1. hook label names the database.\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'
3319
+ });
3320
+
2865
3321
  // src/skills/skill_registry.ts
2866
3322
  var questlogSkills = [
3323
+ webhooksSkill,
2867
3324
  archiveDeleteAndPruneSkill,
2868
3325
  chooseWorkShapeSkill,
2869
3326
  clarifyAmbiguousRequestsSkill,
@@ -2969,6 +3426,8 @@ __export(tools_exports, {
2969
3426
  integerSchema: () => integerSchema,
2970
3427
  listQuestlogToolDefinitions: () => listQuestlogToolDefinitions,
2971
3428
  literalSchema: () => literalSchema,
3429
+ manageHooksTool: () => manageHooksTool,
3430
+ manageHooksToolName: () => manageHooksToolName,
2972
3431
  manageRepeatableTool: () => manageRepeatableTool,
2973
3432
  manageRepeatableToolHandler: () => manageRepeatableToolHandler,
2974
3433
  manageRepeatableToolName: () => manageRepeatableToolName,
@@ -3025,6 +3484,7 @@ var manageRepeatableToolName = "manage_repeatable";
3025
3484
  var tagWorkToolName = "tag_work";
3026
3485
  var rewardWorkToolName = "reward_work";
3027
3486
  var retireWorkToolName = "retire_work";
3487
+ var manageHooksToolName = "manage_hooks";
3028
3488
 
3029
3489
  // src/tools/tool_types.ts
3030
3490
  function withOptionalFields(result, options) {
@@ -3280,6 +3740,7 @@ function validateInput(schema, input, path = "$") {
3280
3740
 
3281
3741
  // src/tools/action_requirements.ts
3282
3742
  var actionRequirements = {
3743
+ manage_hooks: { remove: ["id"] },
3283
3744
  shape_work: {
3284
3745
  create_quest: ["quest"],
3285
3746
  create_questline: ["questline"],
@@ -3662,7 +4123,8 @@ function inspectQuestlogItemToolHandler(db, input) {
3662
4123
  detail: detailLevel === "full" ? detail : toQuestCompactDetail(detail)
3663
4124
  },
3664
4125
  related,
3665
- detailLevel
4126
+ detailLevel,
4127
+ deliveries: listDeliveries(db, { questId: detail.id })
3666
4128
  },
3667
4129
  { entities }
3668
4130
  );
@@ -3768,6 +4230,56 @@ var inspectQuestlogItemTool = defineQuestlogTool({
3768
4230
  handler: inspectQuestlogItemToolHandler
3769
4231
  });
3770
4232
 
4233
+ // src/tools/manage_hooks_tool.ts
4234
+ var manageHooksTool = defineQuestlogTool({
4235
+ name: "manage_hooks",
4236
+ description: "List or remove outbound webhook targets, run a tick, or inspect pending and failed deliveries.",
4237
+ whenToUse: "Use to operate configured outbound webhooks. Add and test targets with the CLI.",
4238
+ whenNotToUse: "Use quest tools to change work itself.",
4239
+ sideEffects: "writes_state",
4240
+ readOnly: false,
4241
+ supportsClarification: false,
4242
+ targetKinds: ["hook"],
4243
+ inputDescriptions: {
4244
+ action: "Operation to perform.",
4245
+ id: "Target id for removal.",
4246
+ dry_run: "Preview a tick without recording or sending."
4247
+ },
4248
+ outputDescription: "Returns redacted targets, delivery metadata, or a tick summary. Never returns signing secrets.",
4249
+ inputSchema: objectSchema(
4250
+ {
4251
+ action: enumSchema("Operation.", ["list", "remove", "tick", "deliveries"]),
4252
+ id: integerSchema("Target id."),
4253
+ dry_run: booleanSchema("Preview only.")
4254
+ },
4255
+ ["action"]
4256
+ ),
4257
+ handler: async (db, input) => {
4258
+ switch (input.action) {
4259
+ case "list":
4260
+ return toolSuccess("Webhook targets.", listHooks(db));
4261
+ case "deliveries":
4262
+ return toolSuccess("Pending and failed deliveries.", listDeliveries(db));
4263
+ case "remove":
4264
+ if (!Number.isSafeInteger(input.id) || Number(input.id) < 1)
4265
+ return toolFailure(
4266
+ "protocol",
4267
+ "invalid_input",
4268
+ "Target id required.",
4269
+ "Provide a positive target id.",
4270
+ { recovery: 'Pass {"action":"remove","id":1}' }
4271
+ );
4272
+ removeHook(db, Number(input.id));
4273
+ return toolSuccess("Webhook target removed.", {});
4274
+ case "tick":
4275
+ return toolSuccess(
4276
+ "Webhook tick completed.",
4277
+ await tickQuestlog(db, { dryRun: input.dry_run ?? false })
4278
+ );
4279
+ }
4280
+ }
4281
+ });
4282
+
3771
4283
  // src/tools/manage_repeatable_tool.ts
3772
4284
  function manageRepeatableToolHandler(db, input) {
3773
4285
  try {
@@ -4467,7 +4979,7 @@ function validateReviewInput(input) {
4467
4979
  'Use `filters.dayAt` only with `view: "quests.scheduled_for_day"`.'
4468
4980
  );
4469
4981
  }
4470
- if ((input.view === "rumors" || input.view === "questlines") && hasQuestFilters(input.filters)) {
4982
+ if ((input.view === "rumors" || input.view === "questlines" || input.view === "deliveries") && hasQuestFilters(input.filters)) {
4471
4983
  return toolFailure(
4472
4984
  "protocol",
4473
4985
  "invalid_input",
@@ -4535,6 +5047,15 @@ function reviewQuestlogToolHandler(db, input) {
4535
5047
  if (invalid) {
4536
5048
  return invalid;
4537
5049
  }
5050
+ if (input.view === "deliveries")
5051
+ return toolSuccess("Pending and failed deliveries.", {
5052
+ view: input.view,
5053
+ items: [],
5054
+ deliveries: listDeliveries(db),
5055
+ count: listDeliveries(db).length,
5056
+ appliedFilters: input.filters,
5057
+ evaluatedAt: input.now ?? Date.now()
5058
+ });
4538
5059
  const now = input.now ?? Date.now();
4539
5060
  let items = [];
4540
5061
  switch (input.view) {
@@ -4594,6 +5115,7 @@ var reviewQuestlogTool = defineQuestlogTool({
4594
5115
  inputSchema: objectSchema(
4595
5116
  {
4596
5117
  view: enumSchema("Which operational review surface to return.", [
5118
+ "deliveries",
4597
5119
  "questlines",
4598
5120
  "quests.active",
4599
5121
  "quests.available",
@@ -5795,6 +6317,7 @@ var tagWorkTool = defineQuestlogTool({
5795
6317
 
5796
6318
  // src/tools/tool_mapping.ts
5797
6319
  var questlogToolMappings = [
6320
+ { source: "tickQuestlog", tool: "manage_hooks", action: "tick" },
5798
6321
  { source: "searchQuestlog", tool: "search_questlog" },
5799
6322
  { source: "listRumors", tool: "review_questlog", action: "rumors" },
5800
6323
  { source: "listQuestlines", tool: "review_questlog", action: "questlines" },
@@ -5892,6 +6415,7 @@ var questlogToolMappings = [
5892
6415
 
5893
6416
  // src/tools/tool_registry.ts
5894
6417
  var questlogTools = [
6418
+ manageHooksTool,
5895
6419
  searchQuestlogTool,
5896
6420
  reviewQuestlogTool,
5897
6421
  inspectQuestlogItemTool,
@@ -5955,4 +6479,4 @@ __export(write_exports, {
5955
6479
  updateRumor: () => updateRumor
5956
6480
  });
5957
6481
 
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 };
6482
+ 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 };