@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.
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { mkdirSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
3
+ import { basename, extname, dirname, join } from 'node:path';
4
+ import { randomBytes, createHmac } from 'node:crypto';
4
5
  import { homedir } from 'node:os';
5
6
 
6
7
  var __defProp = Object.defineProperty;
@@ -323,6 +324,33 @@ var init_mcp_stdio = __esm({
323
324
  }
324
325
  });
325
326
 
327
+ // src/hooks/init_hook_tables.ts
328
+ function initHookTables(db) {
329
+ db.exec(`
330
+ CREATE TABLE IF NOT EXISTS hook_targets (
331
+ id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, secret TEXT NOT NULL,
332
+ tag TEXT, events TEXT NOT NULL, min_gap INTEGER NOT NULL, created_at INTEGER NOT NULL,
333
+ last_wake INTEGER, lease_until INTEGER, claim TEXT);
334
+ CREATE TABLE IF NOT EXISTS hook_events (
335
+ id TEXT PRIMARY KEY, occurred_at INTEGER NOT NULL, event TEXT NOT NULL);
336
+ CREATE TABLE IF NOT EXISTS hook_assignments (
337
+ target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
338
+ event_id TEXT NOT NULL REFERENCES hook_events(id), delivery_id TEXT,
339
+ PRIMARY KEY(target_id, event_id));
340
+ CREATE TABLE IF NOT EXISTS hook_deliveries (
341
+ id TEXT PRIMARY KEY, target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
342
+ events TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
343
+ last_attempt_at INTEGER, http_status INTEGER, error_class TEXT,
344
+ next_attempt_at INTEGER NOT NULL);
345
+ CREATE INDEX IF NOT EXISTS idx_hook_deliveries_target ON hook_deliveries(target_id, status, next_attempt_at);
346
+ CREATE TABLE IF NOT EXISTS hook_settings (id INTEGER PRIMARY KEY CHECK(id = 1), label TEXT NOT NULL);
347
+ `);
348
+ }
349
+ var init_init_hook_tables = __esm({
350
+ "src/hooks/init_hook_tables.ts"() {
351
+ }
352
+ });
353
+
326
354
  // src/questlines/init_questline_tables.ts
327
355
  function initQuestlineTables(db) {
328
356
  db.exec(`
@@ -707,9 +735,11 @@ function initQuestlogTables(db) {
707
735
  initTagTables(db);
708
736
  initQuestSearch(db);
709
737
  initRumorSearch(db);
738
+ initHookTables(db);
710
739
  }
711
740
  var init_init_questlog_tables = __esm({
712
741
  "src/init_questlog_tables.ts"() {
742
+ init_init_hook_tables();
713
743
  init_init_questline_tables();
714
744
  init_init_quest_search();
715
745
  init_init_quest_tables();
@@ -758,7 +788,7 @@ var init_open_questlog_db = __esm({
758
788
  var questlogVersion;
759
789
  var init_version = __esm({
760
790
  "src/version.ts"() {
761
- questlogVersion = "0.9.2";
791
+ questlogVersion = "0.10.1";
762
792
  }
763
793
  });
764
794
 
@@ -1065,6 +1095,7 @@ var actionRequirements;
1065
1095
  var init_action_requirements = __esm({
1066
1096
  "src/tools/action_requirements.ts"() {
1067
1097
  actionRequirements = {
1098
+ manage_hooks: { remove: ["id"] },
1068
1099
  shape_work: {
1069
1100
  create_quest: ["quest"],
1070
1101
  create_questline: ["questline"],
@@ -1398,6 +1429,31 @@ var init_capture_rumor_tool = __esm({
1398
1429
  }
1399
1430
  });
1400
1431
 
1432
+ // src/hooks/list_deliveries.ts
1433
+ function listDeliveries(db, options = {}) {
1434
+ return db.prepare(
1435
+ `SELECT * FROM hook_deliveries ${options.includeDelivered ? "" : "WHERE status <> 'delivered'"} ORDER BY target_id, next_attempt_at, id`
1436
+ ).all().map(
1437
+ (row) => ({
1438
+ id: String(row.id),
1439
+ targetId: Number(row.target_id),
1440
+ events: JSON.parse(String(row.events)),
1441
+ status: row.status,
1442
+ attempts: Number(row.attempts),
1443
+ lastAttemptAt: row.last_attempt_at == null ? null : Number(row.last_attempt_at),
1444
+ httpStatus: row.http_status == null ? null : Number(row.http_status),
1445
+ errorClass: row.error_class == null ? null : String(row.error_class),
1446
+ nextAttemptAt: Number(row.next_attempt_at)
1447
+ })
1448
+ ).filter(
1449
+ (d) => options.questId === void 0 || d.events.some((e) => e.questId === options.questId)
1450
+ );
1451
+ }
1452
+ var init_list_deliveries = __esm({
1453
+ "src/hooks/list_deliveries.ts"() {
1454
+ }
1455
+ });
1456
+
1401
1457
  // src/questlines/map_questline_row.ts
1402
1458
  function mapQuestlineRow(row) {
1403
1459
  return {
@@ -1944,7 +2000,8 @@ function inspectQuestlogItemToolHandler(db, input) {
1944
2000
  detail: detailLevel === "full" ? detail : toQuestCompactDetail(detail)
1945
2001
  },
1946
2002
  related,
1947
- detailLevel
2003
+ detailLevel,
2004
+ deliveries: listDeliveries(db, { questId: detail.id })
1948
2005
  },
1949
2006
  { entities }
1950
2007
  );
@@ -2014,6 +2071,7 @@ function inspectQuestlogItemToolHandler(db, input) {
2014
2071
  var inspectQuestlogItemTool;
2015
2072
  var init_inspect_questlog_item_tool = __esm({
2016
2073
  "src/tools/inspect_questlog_item_tool.ts"() {
2074
+ init_list_deliveries();
2017
2075
  init_get_questline_detail();
2018
2076
  init_get_quest_detail();
2019
2077
  init_get_repeatable_quest_or_throw();
@@ -2064,16 +2122,46 @@ var init_inspect_questlog_item_tool = __esm({
2064
2122
  });
2065
2123
  }
2066
2124
  });
2067
-
2068
- // src/assert_non_negative_seconds.ts
2069
- function assertNonNegativeSeconds(value, label) {
2070
- if (value != null && value < 0) {
2071
- throw new Error(`${label} must not be negative.`);
2125
+ function hookLabel(db, name) {
2126
+ const saved = db.prepare("SELECT label FROM hook_settings WHERE id = 1").get();
2127
+ if (saved) return String(saved.label);
2128
+ const path = String(
2129
+ db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? ""
2130
+ );
2131
+ return path ? basename(path, extname(path)) : "questlog";
2132
+ }
2133
+ var init_hook_label = __esm({
2134
+ "src/hooks/hook_label.ts"() {
2072
2135
  }
2073
- return value;
2136
+ });
2137
+
2138
+ // src/hooks/list_hooks.ts
2139
+ function listHooks(db) {
2140
+ return db.prepare(`SELECT id, url, tag, events, min_gap, created_at, last_wake,
2141
+ (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,
2142
+ (SELECT COUNT(*) FROM hook_deliveries d WHERE d.target_id = t.id AND d.status = 'failed') AS failed
2143
+ FROM hook_targets t ORDER BY id`).all().map((row) => {
2144
+ const url = new URL(String(row.url));
2145
+ url.username = "";
2146
+ url.password = "";
2147
+ url.search = "";
2148
+ url.hash = "";
2149
+ return {
2150
+ id: Number(row.id),
2151
+ scope: row.tag == null ? "database" : "tag",
2152
+ url: url.href,
2153
+ tag: row.tag == null ? null : String(row.tag),
2154
+ events: JSON.parse(String(row.events)),
2155
+ minGap: Number(row.min_gap),
2156
+ createdAt: Number(row.created_at),
2157
+ lastWake: row.last_wake == null ? null : Number(row.last_wake),
2158
+ pending: Number(row.pending),
2159
+ failed: Number(row.failed)
2160
+ };
2161
+ });
2074
2162
  }
2075
- var init_assert_non_negative_seconds = __esm({
2076
- "src/assert_non_negative_seconds.ts"() {
2163
+ var init_list_hooks = __esm({
2164
+ "src/hooks/list_hooks.ts"() {
2077
2165
  }
2078
2166
  });
2079
2167
 
@@ -2117,6 +2205,167 @@ var init_with_transaction = __esm({
2117
2205
  }
2118
2206
  });
2119
2207
 
2208
+ // src/hooks/remove_hook.ts
2209
+ function removeHook(db, id) {
2210
+ withTransaction(db, () => {
2211
+ db.prepare("DELETE FROM hook_assignments WHERE target_id = ?").run(id);
2212
+ db.prepare("DELETE FROM hook_deliveries WHERE target_id = ?").run(id);
2213
+ db.prepare("DELETE FROM hook_targets WHERE id = ?").run(id);
2214
+ });
2215
+ }
2216
+ var init_remove_hook = __esm({
2217
+ "src/hooks/remove_hook.ts"() {
2218
+ init_with_transaction();
2219
+ }
2220
+ });
2221
+ async function sendHookDelivery(db, delivery, target, options) {
2222
+ const now = options.now ?? options.clock?.() ?? Date.now();
2223
+ const timestamp = String(Math.floor(now / 1e3));
2224
+ const body = JSON.stringify({
2225
+ type: "questlog.events",
2226
+ db: hookLabel(db),
2227
+ deliveryId: delivery.id,
2228
+ sentAt: new Date(now).toISOString(),
2229
+ events: delivery.events
2230
+ });
2231
+ const signature = createHmac("sha256", target.secret).update(`${timestamp}.${body}`).digest("hex");
2232
+ let status = null;
2233
+ let errorClass = null;
2234
+ try {
2235
+ const response = await (options.fetch ?? globalThis.fetch)(target.url, {
2236
+ method: "POST",
2237
+ redirect: "error",
2238
+ headers: {
2239
+ "content-type": "application/json",
2240
+ "user-agent": `questlog/${questlogVersion}`,
2241
+ "x-questlog-delivery": delivery.id,
2242
+ "x-questlog-timestamp": timestamp,
2243
+ "x-questlog-signature": `sha256=${signature}`
2244
+ },
2245
+ body,
2246
+ signal: AbortSignal.timeout(Math.max(1, Math.min(options.timeoutMs ?? 5e3, 5e3)))
2247
+ });
2248
+ status = response.status;
2249
+ await response.body?.cancel();
2250
+ } catch (error) {
2251
+ errorClass = error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name) ? error.name : "NetworkError";
2252
+ }
2253
+ const delivered = status != null && status >= 200 && status < 300;
2254
+ const completedAt = options.now ?? options.clock?.() ?? Date.now();
2255
+ withTransaction(db, () => {
2256
+ if (!db.prepare("SELECT id FROM hook_targets WHERE id = ? AND claim = ?").get(target.id, target.claim))
2257
+ return;
2258
+ const delay = Math.min(36e5, 3e4 * 2 ** (delivery.attempts - 1));
2259
+ const jitter = Number.parseInt(randomBytes(2).toString("hex"), 16) % 1e3;
2260
+ db.prepare(
2261
+ "UPDATE hook_deliveries SET status = ?, http_status = ?, error_class = ?, next_attempt_at = ? WHERE id = ?"
2262
+ ).run(
2263
+ delivered ? "delivered" : delivery.attempts >= 8 ? "failed" : "pending",
2264
+ status,
2265
+ errorClass,
2266
+ completedAt + delay + jitter,
2267
+ delivery.id
2268
+ );
2269
+ db.prepare(
2270
+ "UPDATE hook_targets SET claim = NULL, lease_until = NULL WHERE id = ? AND claim = ?"
2271
+ ).run(target.id, target.claim);
2272
+ db.prepare(
2273
+ "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)"
2274
+ ).run(target.id, target.id);
2275
+ });
2276
+ return delivered;
2277
+ }
2278
+ var init_send_hook_delivery = __esm({
2279
+ "src/hooks/send_hook_delivery.ts"() {
2280
+ init_version();
2281
+ init_with_transaction();
2282
+ init_hook_label();
2283
+ }
2284
+ });
2285
+
2286
+ // src/quests/get_quest_or_throw.ts
2287
+ function getQuestOrThrow(db, questId) {
2288
+ const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
2289
+ if (!row) {
2290
+ throw new Error(`Quest ${questId} was not found.`);
2291
+ }
2292
+ return mapQuestRow(row);
2293
+ }
2294
+ var init_get_quest_or_throw = __esm({
2295
+ "src/quests/get_quest_or_throw.ts"() {
2296
+ init_map_quest_row();
2297
+ }
2298
+ });
2299
+
2300
+ // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
2301
+ function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
2302
+ const effectiveNow = resolveNow(now);
2303
+ const rows = db.prepare(
2304
+ `SELECT kind, name, description, quantity
2305
+ FROM repeatable_quest_rewards
2306
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
2307
+ ).all(repeatableQuestId);
2308
+ for (const row of rows) {
2309
+ db.prepare(
2310
+ `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
2311
+ VALUES (?, ?, ?, ?, ?, ?)`
2312
+ ).run(
2313
+ questId,
2314
+ String(row.kind),
2315
+ String(row.name),
2316
+ row.description == null ? null : String(row.description),
2317
+ row.quantity == null ? null : Number(row.quantity),
2318
+ effectiveNow
2319
+ );
2320
+ }
2321
+ }
2322
+ var init_copy_repeatable_quest_rewards_to_quest = __esm({
2323
+ "src/rewards/copy_repeatable_quest_rewards_to_quest.ts"() {
2324
+ init_resolve_now();
2325
+ }
2326
+ });
2327
+
2328
+ // src/tags/copy_repeatable_quest_tags_to_quest.ts
2329
+ function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
2330
+ const effectiveNow = resolveNow(now);
2331
+ const rows = db.prepare(
2332
+ `SELECT tag_id
2333
+ FROM repeatable_quest_tags
2334
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
2335
+ ).all(repeatableQuestId);
2336
+ for (const row of rows) {
2337
+ db.prepare(
2338
+ `INSERT INTO quest_tags (quest_id, tag_id, created_at)
2339
+ VALUES (?, ?, ?)`
2340
+ ).run(questId, Number(row.tag_id), effectiveNow);
2341
+ }
2342
+ }
2343
+ var init_copy_repeatable_quest_tags_to_quest = __esm({
2344
+ "src/tags/copy_repeatable_quest_tags_to_quest.ts"() {
2345
+ init_resolve_now();
2346
+ }
2347
+ });
2348
+
2349
+ // src/repeatable_quests/advance_anchor.ts
2350
+ function advanceAnchor(anchorAt, freq, interval) {
2351
+ const date = new Date(anchorAt);
2352
+ if (freq === "MONTHLY") {
2353
+ date.setUTCMonth(date.getUTCMonth() + interval);
2354
+ return date.getTime();
2355
+ }
2356
+ if (freq === "YEARLY") {
2357
+ date.setUTCFullYear(date.getUTCFullYear() + interval);
2358
+ return date.getTime();
2359
+ }
2360
+ return anchorAt + interval * WEEK_MS;
2361
+ }
2362
+ var WEEK_MS;
2363
+ var init_advance_anchor = __esm({
2364
+ "src/repeatable_quests/advance_anchor.ts"() {
2365
+ WEEK_MS = 7 * 864e5;
2366
+ }
2367
+ });
2368
+
2120
2369
  // src/repeatable_quests/parse_rrule.ts
2121
2370
  function parseRRule(rrule) {
2122
2371
  const parts = Object.fromEntries(
@@ -2165,290 +2414,46 @@ var init_parse_rrule = __esm({
2165
2414
  }
2166
2415
  });
2167
2416
 
2168
- // src/repeatable_quests/update_repeatable_quest.ts
2169
- function updateRepeatableQuest(db, repeatableQuestId, input) {
2170
- return withTransaction(db, () => {
2171
- const current = getRepeatableQuestOrThrow(db, repeatableQuestId);
2172
- const now = resolveNow(input.now);
2173
- const rrule = input.rrule ?? current.rrule;
2174
- parseRRule(rrule);
2175
- db.prepare(
2176
- `UPDATE repeatable_quests
2177
- SET questline_id = ?,
2178
- title = ?,
2179
- objective = ?,
2180
- rrule = ?,
2181
- anchor_at = ?,
2182
- not_before_offset_seconds = ?,
2183
- due_offset_seconds = ?,
2184
- scheduled_start_offset_seconds = ?,
2185
- scheduled_end_offset_seconds = ?,
2186
- all_day = ?,
2187
- estimate_seconds = ?,
2188
- archived_at = ?,
2189
- updated_at = ?
2190
- WHERE id = ? AND deleted_at IS NULL`
2191
- ).run(
2192
- input.questlineId === void 0 ? current.questlineId : input.questlineId,
2193
- input.title == null ? current.title : assertNonEmpty(input.title, "Repeatable quest title"),
2194
- input.objective == null ? current.objective : assertNonEmpty(input.objective, "Repeatable quest objective"),
2195
- rrule,
2196
- input.anchorAt ?? current.anchorAt,
2197
- input.notBeforeOffsetSeconds === void 0 ? current.notBeforeOffsetSeconds : assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
2198
- input.dueOffsetSeconds === void 0 ? current.dueOffsetSeconds : assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
2199
- input.scheduledStartOffsetSeconds === void 0 ? current.scheduledStartOffsetSeconds : input.scheduledStartOffsetSeconds,
2200
- input.scheduledEndOffsetSeconds === void 0 ? current.scheduledEndOffsetSeconds : input.scheduledEndOffsetSeconds,
2201
- input.allDay === void 0 ? current.allDay ? 1 : 0 : input.allDay ? 1 : 0,
2202
- input.estimateSeconds === void 0 ? current.estimateSeconds : assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
2203
- input.archivedAt === void 0 ? current.archivedAt : input.archivedAt,
2204
- now,
2205
- repeatableQuestId
2206
- );
2207
- return getRepeatableQuestOrThrow(db, repeatableQuestId);
2208
- });
2209
- }
2210
- var init_update_repeatable_quest = __esm({
2211
- "src/repeatable_quests/update_repeatable_quest.ts"() {
2212
- init_assert_non_empty();
2213
- init_assert_non_negative_seconds();
2214
- init_resolve_now();
2215
- init_with_transaction();
2216
- init_get_repeatable_quest_or_throw();
2217
- init_parse_rrule();
2218
- }
2219
- });
2220
-
2221
- // src/repeatable_quests/archive_repeatable_quest.ts
2222
- function archiveRepeatableQuest(db, repeatableQuestId, archivedAt) {
2223
- return updateRepeatableQuest(db, repeatableQuestId, { archivedAt: resolveNow(archivedAt) });
2417
+ // src/repeatable_quests/start_of_utc_day.ts
2418
+ function startOfUtcDay(timestamp) {
2419
+ const date = new Date(timestamp);
2420
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
2224
2421
  }
2225
- var init_archive_repeatable_quest = __esm({
2226
- "src/repeatable_quests/archive_repeatable_quest.ts"() {
2227
- init_resolve_now();
2228
- init_update_repeatable_quest();
2422
+ var init_start_of_utc_day = __esm({
2423
+ "src/repeatable_quests/start_of_utc_day.ts"() {
2229
2424
  }
2230
2425
  });
2231
2426
 
2232
- // src/assert_active_row_exists.ts
2233
- function assertActiveRowExists(db, table, id, label) {
2234
- const row = db.prepare(`SELECT id FROM ${table} WHERE id = ? AND deleted_at IS NULL`).get(id);
2235
- if (!row) {
2236
- throw new Error(`${label} ${id} was not found.`);
2237
- }
2427
+ // src/repeatable_quests/start_of_utc_week.ts
2428
+ function startOfUtcWeek(dayStart) {
2429
+ const date = new Date(dayStart);
2430
+ return dayStart - date.getUTCDay() * DAY_MS;
2238
2431
  }
2239
- var init_assert_active_row_exists = __esm({
2240
- "src/assert_active_row_exists.ts"() {
2432
+ var DAY_MS;
2433
+ var init_start_of_utc_week = __esm({
2434
+ "src/repeatable_quests/start_of_utc_week.ts"() {
2435
+ DAY_MS = 864e5;
2241
2436
  }
2242
2437
  });
2243
2438
 
2244
- // src/assert_non_negative_number.ts
2245
- function assertNonNegativeNumber(value, label) {
2246
- if (value != null && value < 0) {
2247
- throw new Error(`${label} must not be negative.`);
2439
+ // src/repeatable_quests/generate_anchors_until.ts
2440
+ function generateAnchorsUntil(repeatable, now) {
2441
+ const rule = parseRRule(repeatable.rrule);
2442
+ const anchors = [];
2443
+ const until = rule.until == null ? now : Math.min(now, rule.until);
2444
+ if (repeatable.anchorAt > until) {
2445
+ return anchors;
2248
2446
  }
2249
- return value;
2250
- }
2251
- var init_assert_non_negative_number = __esm({
2252
- "src/assert_non_negative_number.ts"() {
2253
- }
2254
- });
2255
-
2256
- // src/rewards/replace_active_repeatable_quest_rewards.ts
2257
- function replaceActiveRepeatableQuestRewards(db, repeatableQuestId, rewards, now) {
2258
- const effectiveNow = resolveNow(now);
2259
- db.prepare(
2260
- "UPDATE repeatable_quest_rewards SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
2261
- ).run(effectiveNow, repeatableQuestId);
2262
- for (const reward of rewards) {
2263
- db.prepare(
2264
- `INSERT INTO repeatable_quest_rewards (
2265
- repeatable_quest_id,
2266
- kind,
2267
- name,
2268
- description,
2269
- quantity,
2270
- created_at
2271
- ) VALUES (?, ?, ?, ?, ?, ?)`
2272
- ).run(
2273
- repeatableQuestId,
2274
- assertNonEmpty(reward.kind, "Reward kind"),
2275
- assertNonEmpty(reward.name, "Reward name"),
2276
- reward.description?.trim() || null,
2277
- assertNonNegativeNumber(reward.quantity, "Reward quantity") ?? null,
2278
- effectiveNow
2279
- );
2280
- }
2281
- }
2282
- var init_replace_active_repeatable_quest_rewards = __esm({
2283
- "src/rewards/replace_active_repeatable_quest_rewards.ts"() {
2284
- init_assert_non_empty();
2285
- init_assert_non_negative_number();
2286
- init_resolve_now();
2287
- }
2288
- });
2289
-
2290
- // src/tags/replace_active_repeatable_quest_tags.ts
2291
- function getOrCreateTagId(db, name, now) {
2292
- const normalizedName = normalizeTagName(name);
2293
- if (!normalizedName) {
2294
- throw new Error("Tag name must not be empty.");
2295
- }
2296
- const existing = db.prepare("SELECT id FROM tags WHERE normalized_name = ? AND deleted_at IS NULL").get(normalizedName);
2297
- if (existing) {
2298
- return Number(existing.id);
2299
- }
2300
- const created = db.prepare(
2301
- `INSERT INTO tags (name, normalized_name, created_at)
2302
- VALUES (?, ?, ?)`
2303
- ).run(name.trim(), normalizedName, now);
2304
- return Number(created.lastInsertRowid);
2305
- }
2306
- function replaceActiveRepeatableQuestTags(db, repeatableQuestId, tagNames, now) {
2307
- const effectiveNow = resolveNow(now);
2308
- db.prepare(
2309
- "UPDATE repeatable_quest_tags SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
2310
- ).run(effectiveNow, repeatableQuestId);
2311
- const uniqueNames = [...new Set(tagNames.map((tag) => tag.trim()).filter(Boolean))];
2312
- for (const name of uniqueNames) {
2313
- const tagId = getOrCreateTagId(db, name, effectiveNow);
2314
- db.prepare(
2315
- `INSERT INTO repeatable_quest_tags (repeatable_quest_id, tag_id, created_at)
2316
- VALUES (?, ?, ?)`
2317
- ).run(repeatableQuestId, tagId, effectiveNow);
2318
- }
2319
- }
2320
- var init_replace_active_repeatable_quest_tags = __esm({
2321
- "src/tags/replace_active_repeatable_quest_tags.ts"() {
2322
- init_resolve_now();
2323
- init_normalize_tag_name();
2324
- }
2325
- });
2326
-
2327
- // src/repeatable_quests/create_repeatable_quest.ts
2328
- function createRepeatableQuest(db, input) {
2329
- return withTransaction(db, () => {
2330
- const now = resolveNow(input.now);
2331
- const title = assertNonEmpty(input.title, "Repeatable quest title");
2332
- const objective = assertNonEmpty(input.objective, "Repeatable quest objective");
2333
- parseRRule(input.rrule);
2334
- if (input.questlineId != null) {
2335
- assertActiveRowExists(db, "questlines", input.questlineId, "Questline");
2336
- }
2337
- const created = db.prepare(
2338
- `INSERT INTO repeatable_quests (
2339
- questline_id,
2340
- title,
2341
- objective,
2342
- rrule,
2343
- anchor_at,
2344
- not_before_offset_seconds,
2345
- due_offset_seconds,
2346
- scheduled_start_offset_seconds,
2347
- scheduled_end_offset_seconds,
2348
- all_day,
2349
- estimate_seconds,
2350
- created_at,
2351
- updated_at
2352
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
2353
- ).run(
2354
- input.questlineId ?? null,
2355
- title,
2356
- objective,
2357
- input.rrule,
2358
- input.anchorAt,
2359
- assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
2360
- assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
2361
- input.scheduledStartOffsetSeconds ?? null,
2362
- input.scheduledEndOffsetSeconds ?? null,
2363
- input.allDay ? 1 : 0,
2364
- assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
2365
- now,
2366
- now
2367
- );
2368
- const repeatableQuestId = Number(created.lastInsertRowid);
2369
- if (input.tags && input.tags.length > 0) {
2370
- replaceActiveRepeatableQuestTags(db, repeatableQuestId, input.tags, now);
2371
- }
2372
- if (input.rewards && input.rewards.length > 0) {
2373
- replaceActiveRepeatableQuestRewards(db, repeatableQuestId, input.rewards, now);
2374
- }
2375
- return getRepeatableQuestOrThrow(db, repeatableQuestId);
2376
- });
2377
- }
2378
- var init_create_repeatable_quest = __esm({
2379
- "src/repeatable_quests/create_repeatable_quest.ts"() {
2380
- init_assert_active_row_exists();
2381
- init_assert_non_empty();
2382
- init_assert_non_negative_seconds();
2383
- init_resolve_now();
2384
- init_replace_active_repeatable_quest_rewards();
2385
- init_replace_active_repeatable_quest_tags();
2386
- init_with_transaction();
2387
- init_get_repeatable_quest_or_throw();
2388
- init_parse_rrule();
2389
- }
2390
- });
2391
-
2392
- // src/repeatable_quests/advance_anchor.ts
2393
- function advanceAnchor(anchorAt, freq, interval) {
2394
- const date = new Date(anchorAt);
2395
- if (freq === "MONTHLY") {
2396
- date.setUTCMonth(date.getUTCMonth() + interval);
2397
- return date.getTime();
2398
- }
2399
- if (freq === "YEARLY") {
2400
- date.setUTCFullYear(date.getUTCFullYear() + interval);
2401
- return date.getTime();
2402
- }
2403
- return anchorAt + interval * WEEK_MS;
2404
- }
2405
- var WEEK_MS;
2406
- var init_advance_anchor = __esm({
2407
- "src/repeatable_quests/advance_anchor.ts"() {
2408
- WEEK_MS = 7 * 864e5;
2409
- }
2410
- });
2411
-
2412
- // src/repeatable_quests/start_of_utc_day.ts
2413
- function startOfUtcDay(timestamp) {
2414
- const date = new Date(timestamp);
2415
- return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
2416
- }
2417
- var init_start_of_utc_day = __esm({
2418
- "src/repeatable_quests/start_of_utc_day.ts"() {
2419
- }
2420
- });
2421
-
2422
- // src/repeatable_quests/start_of_utc_week.ts
2423
- function startOfUtcWeek(dayStart) {
2424
- const date = new Date(dayStart);
2425
- return dayStart - date.getUTCDay() * DAY_MS;
2426
- }
2427
- var DAY_MS;
2428
- var init_start_of_utc_week = __esm({
2429
- "src/repeatable_quests/start_of_utc_week.ts"() {
2430
- DAY_MS = 864e5;
2431
- }
2432
- });
2433
-
2434
- // src/repeatable_quests/generate_anchors_until.ts
2435
- function generateAnchorsUntil(repeatable, now) {
2436
- const rule = parseRRule(repeatable.rrule);
2437
- const anchors = [];
2438
- const until = rule.until == null ? now : Math.min(now, rule.until);
2439
- if (repeatable.anchorAt > until) {
2440
- return anchors;
2441
- }
2442
- if (rule.freq === "DAILY") {
2443
- let occurrence2 = 0;
2444
- for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
2445
- occurrence2 += 1;
2446
- if (rule.count != null && occurrence2 > rule.count) {
2447
- break;
2448
- }
2449
- anchors.push(current2);
2450
- }
2451
- return anchors;
2447
+ if (rule.freq === "DAILY") {
2448
+ let occurrence2 = 0;
2449
+ for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
2450
+ occurrence2 += 1;
2451
+ if (rule.count != null && occurrence2 > rule.count) {
2452
+ break;
2453
+ }
2454
+ anchors.push(current2);
2455
+ }
2456
+ return anchors;
2452
2457
  }
2453
2458
  if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
2454
2459
  const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
@@ -2550,143 +2555,559 @@ var init_list_due_repeatable_quest_anchors = __esm({
2550
2555
  }
2551
2556
  });
2552
2557
 
2553
- // src/repeatable_quests/soft_delete_repeatable_quest.ts
2554
- function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
2555
- const now = resolveNow(deletedAt);
2556
- getRepeatableQuestOrThrow(db, repeatableQuestId);
2557
- db.prepare(
2558
- `UPDATE repeatable_quests
2559
- SET deleted_at = ?, updated_at = ?
2560
- WHERE id = ? AND deleted_at IS NULL`
2561
- ).run(now, now, repeatableQuestId);
2558
+ // src/repeatable_quests/spawn_due_repeatable_quests.ts
2559
+ function spawnDueRepeatableQuests(db, now) {
2560
+ return withTransaction(db, () => {
2561
+ const anchors = listDueRepeatableQuestAnchors(db, now);
2562
+ const quests = [];
2563
+ for (const anchor of anchors) {
2564
+ const repeatable = getRepeatableQuestOrThrow(db, anchor.repeatableQuestId);
2565
+ const created = db.prepare(
2566
+ `INSERT INTO quests (
2567
+ questline_id,
2568
+ source_rumor_id,
2569
+ spawned_by_quest_id,
2570
+ spawned_from_repeatable_id,
2571
+ spawned_for_at,
2572
+ title,
2573
+ objective,
2574
+ created_at,
2575
+ updated_at,
2576
+ effort_seconds,
2577
+ estimate_seconds,
2578
+ not_before_at,
2579
+ due_at,
2580
+ scheduled_start_at,
2581
+ scheduled_end_at,
2582
+ all_day
2583
+ ) VALUES (?, NULL, NULL, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
2584
+ ).run(
2585
+ repeatable.questlineId ?? null,
2586
+ repeatable.id,
2587
+ anchor.anchorAt,
2588
+ repeatable.title,
2589
+ repeatable.objective,
2590
+ now,
2591
+ now,
2592
+ repeatable.estimateSeconds ?? null,
2593
+ repeatable.notBeforeOffsetSeconds == null ? null : anchor.anchorAt + repeatable.notBeforeOffsetSeconds * 1e3,
2594
+ repeatable.dueOffsetSeconds == null ? null : anchor.anchorAt + repeatable.dueOffsetSeconds * 1e3,
2595
+ repeatable.scheduledStartOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledStartOffsetSeconds * 1e3,
2596
+ repeatable.scheduledEndOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledEndOffsetSeconds * 1e3,
2597
+ repeatable.allDay ? 1 : 0
2598
+ );
2599
+ const questId = Number(created.lastInsertRowid);
2600
+ copyRepeatableQuestTagsToQuest(db, repeatable.id, questId, now);
2601
+ copyRepeatableQuestRewardsToQuest(db, repeatable.id, questId, now);
2602
+ quests.push(getQuestOrThrow(db, questId));
2603
+ }
2604
+ return quests;
2605
+ });
2606
+ }
2607
+ var init_spawn_due_repeatable_quests = __esm({
2608
+ "src/repeatable_quests/spawn_due_repeatable_quests.ts"() {
2609
+ init_get_quest_or_throw();
2610
+ init_copy_repeatable_quest_rewards_to_quest();
2611
+ init_copy_repeatable_quest_tags_to_quest();
2612
+ init_with_transaction();
2613
+ init_get_repeatable_quest_or_throw();
2614
+ init_list_due_repeatable_quest_anchors();
2615
+ }
2616
+ });
2617
+
2618
+ // src/hooks/detect_hook_events.ts
2619
+ function detectHookEvents(db, now) {
2620
+ const events = [];
2621
+ const add = (type, at, ids) => {
2622
+ events.push({
2623
+ id: `e_${type}_${ids.questId ?? ids.rumorId}_${ids.repeatableId ?? ""}_${at}`,
2624
+ type,
2625
+ ...ids,
2626
+ occurredAt: new Date(at).toISOString()
2627
+ });
2628
+ };
2629
+ for (const { detail: q } of queryQuestDetailRecords(db, {}, now)) {
2630
+ if (q.resolvedAt == null && q.effectiveDueAt != null && q.effectiveDueAt <= now) {
2631
+ add("quest.due", q.effectiveDueAt, { questId: q.id });
2632
+ if (q.effectiveDueAt < now) add("quest.overdue", q.effectiveDueAt, { questId: q.id });
2633
+ }
2634
+ if (q.available) {
2635
+ const prerequisites = db.prepare(
2636
+ `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`
2637
+ ).all(q.id);
2638
+ if (prerequisites.some((p) => Number(p.resolved_at) >= Number(p.created_at))) {
2639
+ const at = Math.max(q.notBeforeAt ?? 0, ...prerequisites.map((p) => Number(p.resolved_at)));
2640
+ if (at <= now) add("quest.unblocked", at, { questId: q.id });
2641
+ }
2642
+ }
2643
+ if (q.spawnedFromRepeatableId != null && q.createdAt <= now)
2644
+ add("repeatable.spawned", q.createdAt, {
2645
+ questId: q.id,
2646
+ repeatableId: q.spawnedFromRepeatableId
2647
+ });
2648
+ }
2649
+ for (const row of db.prepare("SELECT id, created_at FROM rumors WHERE deleted_at IS NULL AND created_at <= ?").all(now))
2650
+ add("rumor.captured", Number(row.created_at), { rumorId: Number(row.id) });
2651
+ return events.sort(
2652
+ (a, b) => a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
2653
+ );
2654
+ }
2655
+ var init_detect_hook_events = __esm({
2656
+ "src/hooks/detect_hook_events.ts"() {
2657
+ init_query_quest_detail_records();
2658
+ }
2659
+ });
2660
+ async function tickQuestlog(db, options = {}) {
2661
+ const now = options.now ?? options.clock?.() ?? Date.now();
2662
+ const result = {
2663
+ events: [],
2664
+ batches: [],
2665
+ sent: 0,
2666
+ queued: 0,
2667
+ retrying: 0,
2668
+ failed: 0
2669
+ };
2670
+ const claims = [];
2671
+ const collect = () => {
2672
+ spawnDueRepeatableQuests(db, now);
2673
+ const detected = detectHookEvents(db, now);
2674
+ result.events = detected.filter(
2675
+ (e) => !db.prepare("SELECT id FROM hook_events WHERE id = ?").get(e.id)
2676
+ );
2677
+ for (const event of result.events)
2678
+ db.prepare("INSERT INTO hook_events(id, occurred_at, event) VALUES (?, ?, ?)").run(
2679
+ event.id,
2680
+ Date.parse(event.occurredAt),
2681
+ JSON.stringify(event)
2682
+ );
2683
+ for (const target of listHooks(db)) {
2684
+ const events = db.prepare(
2685
+ "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"
2686
+ ).all(target.createdAt, target.id).map((row2) => JSON.parse(String(row2.event))).filter((event) => {
2687
+ if (!target.events.includes(event.type)) return false;
2688
+ if (target.tag == null) return true;
2689
+ return event.questId !== void 0 && db.prepare(
2690
+ "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 = ?"
2691
+ ).get(event.questId, normalizeTagName(target.tag)) !== void 0;
2692
+ });
2693
+ for (const event of events)
2694
+ db.prepare("INSERT INTO hook_assignments(target_id, event_id) VALUES (?, ?)").run(
2695
+ target.id,
2696
+ event.id
2697
+ );
2698
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(target.id);
2699
+ if (!row || row.lease_until != null && Number(row.lease_until) > now) continue;
2700
+ let pending = listDeliveries(db).find(
2701
+ (d) => d.targetId === target.id && d.status === "pending"
2702
+ );
2703
+ const queued = db.prepare(
2704
+ "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"
2705
+ ).all(target.id).map((r) => JSON.parse(String(r.event)));
2706
+ if (!pending && queued.length) {
2707
+ const id = `d_${randomBytes(16).toString("hex")}`;
2708
+ db.prepare(
2709
+ "INSERT INTO hook_deliveries(id, target_id, events, status, next_attempt_at) VALUES (?, ?, ?, 'pending', ?)"
2710
+ ).run(
2711
+ id,
2712
+ target.id,
2713
+ JSON.stringify(queued),
2714
+ Math.max(now, (target.lastWake ?? -Infinity) + target.minGap * 1e3)
2715
+ );
2716
+ db.prepare(
2717
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
2718
+ ).run(id, target.id);
2719
+ pending = listDeliveries(db).find((d) => d.id === id);
2720
+ }
2721
+ if (!pending) continue;
2722
+ if (pending.attempts === 0 && queued.length && !queued.every((e) => pending?.events.some((p) => p.id === e.id))) {
2723
+ pending.events.push(...queued);
2724
+ db.prepare("UPDATE hook_deliveries SET events = ? WHERE id = ?").run(
2725
+ JSON.stringify(pending.events),
2726
+ pending.id
2727
+ );
2728
+ db.prepare(
2729
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
2730
+ ).run(pending.id, target.id);
2731
+ }
2732
+ if (pending.nextAttemptAt > now || target.lastWake != null && target.lastWake + target.minGap * 1e3 > now)
2733
+ continue;
2734
+ if (pending.attempts >= 8) {
2735
+ db.prepare("UPDATE hook_deliveries SET status = 'failed' WHERE id = ?").run(pending.id);
2736
+ continue;
2737
+ }
2738
+ const claim = randomBytes(16).toString("hex");
2739
+ db.prepare(
2740
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
2741
+ ).run(claim, now + 12e4, now, target.id);
2742
+ db.prepare(
2743
+ "UPDATE hook_deliveries SET attempts = attempts + 1, last_attempt_at = ? WHERE id = ?"
2744
+ ).run(now, pending.id);
2745
+ pending.attempts++;
2746
+ pending.lastAttemptAt = now;
2747
+ result.batches.push({ targetId: target.id, events: pending.events });
2748
+ claims.push({
2749
+ delivery: pending,
2750
+ target: { id: target.id, url: String(row.url), secret: String(row.secret), claim }
2751
+ });
2752
+ }
2753
+ };
2754
+ if (options.dryRun) {
2755
+ const rollback = new Error("preview rollback");
2756
+ try {
2757
+ withTransaction(db, () => {
2758
+ collect();
2759
+ throw rollback;
2760
+ });
2761
+ } catch (error) {
2762
+ if (error !== rollback) throw error;
2763
+ }
2764
+ } else withTransaction(db, collect);
2765
+ if (!options.dryRun) {
2766
+ const sent = await Promise.all(
2767
+ claims.map((claim) => sendHookDelivery(db, claim.delivery, claim.target, options))
2768
+ );
2769
+ result.sent = sent.filter(Boolean).length;
2770
+ }
2771
+ const deliveries = listDeliveries(db);
2772
+ result.queued = deliveries.filter((d) => d.status === "pending" && d.attempts === 0).length + Number(
2773
+ db.prepare(
2774
+ "SELECT COUNT(DISTINCT target_id) AS n FROM hook_assignments WHERE delivery_id IS NULL"
2775
+ ).get()?.n ?? 0
2776
+ );
2777
+ result.retrying = deliveries.filter((d) => d.status === "pending" && d.attempts > 0).length;
2778
+ result.failed = deliveries.filter((d) => d.status === "failed").length;
2779
+ return result;
2780
+ }
2781
+ var init_tick_questlog = __esm({
2782
+ "src/hooks/tick_questlog.ts"() {
2783
+ init_spawn_due_repeatable_quests();
2784
+ init_normalize_tag_name();
2785
+ init_with_transaction();
2786
+ init_detect_hook_events();
2787
+ init_list_deliveries();
2788
+ init_list_hooks();
2789
+ init_send_hook_delivery();
2790
+ }
2791
+ });
2792
+
2793
+ // src/hooks/index.ts
2794
+ var init_hooks = __esm({
2795
+ "src/hooks/index.ts"() {
2796
+ init_list_deliveries();
2797
+ init_list_hooks();
2798
+ init_remove_hook();
2799
+ init_tick_questlog();
2800
+ }
2801
+ });
2802
+
2803
+ // src/tools/manage_hooks_tool.ts
2804
+ var manageHooksTool;
2805
+ var init_manage_hooks_tool = __esm({
2806
+ "src/tools/manage_hooks_tool.ts"() {
2807
+ init_hooks();
2808
+ init_tool_metadata();
2809
+ init_tool_types();
2810
+ manageHooksTool = defineQuestlogTool({
2811
+ name: "manage_hooks",
2812
+ description: "List or remove outbound webhook targets, run a tick, or inspect pending and failed deliveries.",
2813
+ whenToUse: "Use to operate configured outbound webhooks. Add and test targets with the CLI.",
2814
+ whenNotToUse: "Use quest tools to change work itself.",
2815
+ sideEffects: "writes_state",
2816
+ readOnly: false,
2817
+ supportsClarification: false,
2818
+ targetKinds: ["hook"],
2819
+ inputDescriptions: {
2820
+ action: "Operation to perform.",
2821
+ id: "Target id for removal.",
2822
+ dry_run: "Preview a tick without recording or sending."
2823
+ },
2824
+ outputDescription: "Returns redacted targets, delivery metadata, or a tick summary. Never returns signing secrets.",
2825
+ inputSchema: objectSchema(
2826
+ {
2827
+ action: enumSchema("Operation.", ["list", "remove", "tick", "deliveries"]),
2828
+ id: integerSchema("Target id."),
2829
+ dry_run: booleanSchema("Preview only.")
2830
+ },
2831
+ ["action"]
2832
+ ),
2833
+ handler: async (db, input) => {
2834
+ switch (input.action) {
2835
+ case "list":
2836
+ return toolSuccess("Webhook targets.", listHooks(db));
2837
+ case "deliveries":
2838
+ return toolSuccess("Pending and failed deliveries.", listDeliveries(db));
2839
+ case "remove":
2840
+ if (!Number.isSafeInteger(input.id) || Number(input.id) < 1)
2841
+ return toolFailure(
2842
+ "protocol",
2843
+ "invalid_input",
2844
+ "Target id required.",
2845
+ "Provide a positive target id.",
2846
+ { recovery: 'Pass {"action":"remove","id":1}' }
2847
+ );
2848
+ removeHook(db, Number(input.id));
2849
+ return toolSuccess("Webhook target removed.", {});
2850
+ case "tick":
2851
+ return toolSuccess(
2852
+ "Webhook tick completed.",
2853
+ await tickQuestlog(db, { dryRun: input.dry_run ?? false })
2854
+ );
2855
+ }
2856
+ }
2857
+ });
2858
+ }
2859
+ });
2860
+
2861
+ // src/assert_non_negative_seconds.ts
2862
+ function assertNonNegativeSeconds(value, label) {
2863
+ if (value != null && value < 0) {
2864
+ throw new Error(`${label} must not be negative.`);
2865
+ }
2866
+ return value;
2867
+ }
2868
+ var init_assert_non_negative_seconds = __esm({
2869
+ "src/assert_non_negative_seconds.ts"() {
2870
+ }
2871
+ });
2872
+
2873
+ // src/repeatable_quests/update_repeatable_quest.ts
2874
+ function updateRepeatableQuest(db, repeatableQuestId, input) {
2875
+ return withTransaction(db, () => {
2876
+ const current = getRepeatableQuestOrThrow(db, repeatableQuestId);
2877
+ const now = resolveNow(input.now);
2878
+ const rrule = input.rrule ?? current.rrule;
2879
+ parseRRule(rrule);
2880
+ db.prepare(
2881
+ `UPDATE repeatable_quests
2882
+ SET questline_id = ?,
2883
+ title = ?,
2884
+ objective = ?,
2885
+ rrule = ?,
2886
+ anchor_at = ?,
2887
+ not_before_offset_seconds = ?,
2888
+ due_offset_seconds = ?,
2889
+ scheduled_start_offset_seconds = ?,
2890
+ scheduled_end_offset_seconds = ?,
2891
+ all_day = ?,
2892
+ estimate_seconds = ?,
2893
+ archived_at = ?,
2894
+ updated_at = ?
2895
+ WHERE id = ? AND deleted_at IS NULL`
2896
+ ).run(
2897
+ input.questlineId === void 0 ? current.questlineId : input.questlineId,
2898
+ input.title == null ? current.title : assertNonEmpty(input.title, "Repeatable quest title"),
2899
+ input.objective == null ? current.objective : assertNonEmpty(input.objective, "Repeatable quest objective"),
2900
+ rrule,
2901
+ input.anchorAt ?? current.anchorAt,
2902
+ input.notBeforeOffsetSeconds === void 0 ? current.notBeforeOffsetSeconds : assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
2903
+ input.dueOffsetSeconds === void 0 ? current.dueOffsetSeconds : assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
2904
+ input.scheduledStartOffsetSeconds === void 0 ? current.scheduledStartOffsetSeconds : input.scheduledStartOffsetSeconds,
2905
+ input.scheduledEndOffsetSeconds === void 0 ? current.scheduledEndOffsetSeconds : input.scheduledEndOffsetSeconds,
2906
+ input.allDay === void 0 ? current.allDay ? 1 : 0 : input.allDay ? 1 : 0,
2907
+ input.estimateSeconds === void 0 ? current.estimateSeconds : assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
2908
+ input.archivedAt === void 0 ? current.archivedAt : input.archivedAt,
2909
+ now,
2910
+ repeatableQuestId
2911
+ );
2912
+ return getRepeatableQuestOrThrow(db, repeatableQuestId);
2913
+ });
2914
+ }
2915
+ var init_update_repeatable_quest = __esm({
2916
+ "src/repeatable_quests/update_repeatable_quest.ts"() {
2917
+ init_assert_non_empty();
2918
+ init_assert_non_negative_seconds();
2919
+ init_resolve_now();
2920
+ init_with_transaction();
2921
+ init_get_repeatable_quest_or_throw();
2922
+ init_parse_rrule();
2923
+ }
2924
+ });
2925
+
2926
+ // src/repeatable_quests/archive_repeatable_quest.ts
2927
+ function archiveRepeatableQuest(db, repeatableQuestId, archivedAt) {
2928
+ return updateRepeatableQuest(db, repeatableQuestId, { archivedAt: resolveNow(archivedAt) });
2562
2929
  }
2563
- var init_soft_delete_repeatable_quest = __esm({
2564
- "src/repeatable_quests/soft_delete_repeatable_quest.ts"() {
2930
+ var init_archive_repeatable_quest = __esm({
2931
+ "src/repeatable_quests/archive_repeatable_quest.ts"() {
2565
2932
  init_resolve_now();
2566
- init_get_repeatable_quest_or_throw();
2933
+ init_update_repeatable_quest();
2567
2934
  }
2568
2935
  });
2569
2936
 
2570
- // src/quests/get_quest_or_throw.ts
2571
- function getQuestOrThrow(db, questId) {
2572
- const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
2937
+ // src/assert_active_row_exists.ts
2938
+ function assertActiveRowExists(db, table, id, label) {
2939
+ const row = db.prepare(`SELECT id FROM ${table} WHERE id = ? AND deleted_at IS NULL`).get(id);
2573
2940
  if (!row) {
2574
- throw new Error(`Quest ${questId} was not found.`);
2941
+ throw new Error(`${label} ${id} was not found.`);
2575
2942
  }
2576
- return mapQuestRow(row);
2577
2943
  }
2578
- var init_get_quest_or_throw = __esm({
2579
- "src/quests/get_quest_or_throw.ts"() {
2580
- init_map_quest_row();
2944
+ var init_assert_active_row_exists = __esm({
2945
+ "src/assert_active_row_exists.ts"() {
2581
2946
  }
2582
2947
  });
2583
2948
 
2584
- // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
2585
- function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
2949
+ // src/assert_non_negative_number.ts
2950
+ function assertNonNegativeNumber(value, label) {
2951
+ if (value != null && value < 0) {
2952
+ throw new Error(`${label} must not be negative.`);
2953
+ }
2954
+ return value;
2955
+ }
2956
+ var init_assert_non_negative_number = __esm({
2957
+ "src/assert_non_negative_number.ts"() {
2958
+ }
2959
+ });
2960
+
2961
+ // src/rewards/replace_active_repeatable_quest_rewards.ts
2962
+ function replaceActiveRepeatableQuestRewards(db, repeatableQuestId, rewards, now) {
2586
2963
  const effectiveNow = resolveNow(now);
2587
- const rows = db.prepare(
2588
- `SELECT kind, name, description, quantity
2589
- FROM repeatable_quest_rewards
2590
- WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
2591
- ).all(repeatableQuestId);
2592
- for (const row of rows) {
2964
+ db.prepare(
2965
+ "UPDATE repeatable_quest_rewards SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
2966
+ ).run(effectiveNow, repeatableQuestId);
2967
+ for (const reward of rewards) {
2593
2968
  db.prepare(
2594
- `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
2595
- VALUES (?, ?, ?, ?, ?, ?)`
2969
+ `INSERT INTO repeatable_quest_rewards (
2970
+ repeatable_quest_id,
2971
+ kind,
2972
+ name,
2973
+ description,
2974
+ quantity,
2975
+ created_at
2976
+ ) VALUES (?, ?, ?, ?, ?, ?)`
2596
2977
  ).run(
2597
- questId,
2598
- String(row.kind),
2599
- String(row.name),
2600
- row.description == null ? null : String(row.description),
2601
- row.quantity == null ? null : Number(row.quantity),
2978
+ repeatableQuestId,
2979
+ assertNonEmpty(reward.kind, "Reward kind"),
2980
+ assertNonEmpty(reward.name, "Reward name"),
2981
+ reward.description?.trim() || null,
2982
+ assertNonNegativeNumber(reward.quantity, "Reward quantity") ?? null,
2602
2983
  effectiveNow
2603
2984
  );
2604
2985
  }
2605
2986
  }
2606
- var init_copy_repeatable_quest_rewards_to_quest = __esm({
2607
- "src/rewards/copy_repeatable_quest_rewards_to_quest.ts"() {
2987
+ var init_replace_active_repeatable_quest_rewards = __esm({
2988
+ "src/rewards/replace_active_repeatable_quest_rewards.ts"() {
2989
+ init_assert_non_empty();
2990
+ init_assert_non_negative_number();
2608
2991
  init_resolve_now();
2609
2992
  }
2610
2993
  });
2611
2994
 
2612
- // src/tags/copy_repeatable_quest_tags_to_quest.ts
2613
- function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
2995
+ // src/tags/replace_active_repeatable_quest_tags.ts
2996
+ function getOrCreateTagId(db, name, now) {
2997
+ const normalizedName = normalizeTagName(name);
2998
+ if (!normalizedName) {
2999
+ throw new Error("Tag name must not be empty.");
3000
+ }
3001
+ const existing = db.prepare("SELECT id FROM tags WHERE normalized_name = ? AND deleted_at IS NULL").get(normalizedName);
3002
+ if (existing) {
3003
+ return Number(existing.id);
3004
+ }
3005
+ const created = db.prepare(
3006
+ `INSERT INTO tags (name, normalized_name, created_at)
3007
+ VALUES (?, ?, ?)`
3008
+ ).run(name.trim(), normalizedName, now);
3009
+ return Number(created.lastInsertRowid);
3010
+ }
3011
+ function replaceActiveRepeatableQuestTags(db, repeatableQuestId, tagNames, now) {
2614
3012
  const effectiveNow = resolveNow(now);
2615
- const rows = db.prepare(
2616
- `SELECT tag_id
2617
- FROM repeatable_quest_tags
2618
- WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
2619
- ).all(repeatableQuestId);
2620
- for (const row of rows) {
3013
+ db.prepare(
3014
+ "UPDATE repeatable_quest_tags SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
3015
+ ).run(effectiveNow, repeatableQuestId);
3016
+ const uniqueNames = [...new Set(tagNames.map((tag) => tag.trim()).filter(Boolean))];
3017
+ for (const name of uniqueNames) {
3018
+ const tagId = getOrCreateTagId(db, name, effectiveNow);
2621
3019
  db.prepare(
2622
- `INSERT INTO quest_tags (quest_id, tag_id, created_at)
3020
+ `INSERT INTO repeatable_quest_tags (repeatable_quest_id, tag_id, created_at)
2623
3021
  VALUES (?, ?, ?)`
2624
- ).run(questId, Number(row.tag_id), effectiveNow);
3022
+ ).run(repeatableQuestId, tagId, effectiveNow);
2625
3023
  }
2626
3024
  }
2627
- var init_copy_repeatable_quest_tags_to_quest = __esm({
2628
- "src/tags/copy_repeatable_quest_tags_to_quest.ts"() {
3025
+ var init_replace_active_repeatable_quest_tags = __esm({
3026
+ "src/tags/replace_active_repeatable_quest_tags.ts"() {
2629
3027
  init_resolve_now();
3028
+ init_normalize_tag_name();
2630
3029
  }
2631
3030
  });
2632
3031
 
2633
- // src/repeatable_quests/spawn_due_repeatable_quests.ts
2634
- function spawnDueRepeatableQuests(db, now) {
3032
+ // src/repeatable_quests/create_repeatable_quest.ts
3033
+ function createRepeatableQuest(db, input) {
2635
3034
  return withTransaction(db, () => {
2636
- const anchors = listDueRepeatableQuestAnchors(db, now);
2637
- const quests = [];
2638
- for (const anchor of anchors) {
2639
- const repeatable = getRepeatableQuestOrThrow(db, anchor.repeatableQuestId);
2640
- const created = db.prepare(
2641
- `INSERT INTO quests (
2642
- questline_id,
2643
- source_rumor_id,
2644
- spawned_by_quest_id,
2645
- spawned_from_repeatable_id,
2646
- spawned_for_at,
2647
- title,
2648
- objective,
2649
- created_at,
2650
- updated_at,
2651
- effort_seconds,
2652
- estimate_seconds,
2653
- not_before_at,
2654
- due_at,
2655
- scheduled_start_at,
2656
- scheduled_end_at,
2657
- all_day
2658
- ) VALUES (?, NULL, NULL, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
2659
- ).run(
2660
- repeatable.questlineId ?? null,
2661
- repeatable.id,
2662
- anchor.anchorAt,
2663
- repeatable.title,
2664
- repeatable.objective,
2665
- now,
2666
- now,
2667
- repeatable.estimateSeconds ?? null,
2668
- repeatable.notBeforeOffsetSeconds == null ? null : anchor.anchorAt + repeatable.notBeforeOffsetSeconds * 1e3,
2669
- repeatable.dueOffsetSeconds == null ? null : anchor.anchorAt + repeatable.dueOffsetSeconds * 1e3,
2670
- repeatable.scheduledStartOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledStartOffsetSeconds * 1e3,
2671
- repeatable.scheduledEndOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledEndOffsetSeconds * 1e3,
2672
- repeatable.allDay ? 1 : 0
2673
- );
2674
- const questId = Number(created.lastInsertRowid);
2675
- copyRepeatableQuestTagsToQuest(db, repeatable.id, questId, now);
2676
- copyRepeatableQuestRewardsToQuest(db, repeatable.id, questId, now);
2677
- quests.push(getQuestOrThrow(db, questId));
3035
+ const now = resolveNow(input.now);
3036
+ const title = assertNonEmpty(input.title, "Repeatable quest title");
3037
+ const objective = assertNonEmpty(input.objective, "Repeatable quest objective");
3038
+ parseRRule(input.rrule);
3039
+ if (input.questlineId != null) {
3040
+ assertActiveRowExists(db, "questlines", input.questlineId, "Questline");
2678
3041
  }
2679
- return quests;
3042
+ const created = db.prepare(
3043
+ `INSERT INTO repeatable_quests (
3044
+ questline_id,
3045
+ title,
3046
+ objective,
3047
+ rrule,
3048
+ anchor_at,
3049
+ not_before_offset_seconds,
3050
+ due_offset_seconds,
3051
+ scheduled_start_offset_seconds,
3052
+ scheduled_end_offset_seconds,
3053
+ all_day,
3054
+ estimate_seconds,
3055
+ created_at,
3056
+ updated_at
3057
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
3058
+ ).run(
3059
+ input.questlineId ?? null,
3060
+ title,
3061
+ objective,
3062
+ input.rrule,
3063
+ input.anchorAt,
3064
+ assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
3065
+ assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
3066
+ input.scheduledStartOffsetSeconds ?? null,
3067
+ input.scheduledEndOffsetSeconds ?? null,
3068
+ input.allDay ? 1 : 0,
3069
+ assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
3070
+ now,
3071
+ now
3072
+ );
3073
+ const repeatableQuestId = Number(created.lastInsertRowid);
3074
+ if (input.tags && input.tags.length > 0) {
3075
+ replaceActiveRepeatableQuestTags(db, repeatableQuestId, input.tags, now);
3076
+ }
3077
+ if (input.rewards && input.rewards.length > 0) {
3078
+ replaceActiveRepeatableQuestRewards(db, repeatableQuestId, input.rewards, now);
3079
+ }
3080
+ return getRepeatableQuestOrThrow(db, repeatableQuestId);
2680
3081
  });
2681
3082
  }
2682
- var init_spawn_due_repeatable_quests = __esm({
2683
- "src/repeatable_quests/spawn_due_repeatable_quests.ts"() {
2684
- init_get_quest_or_throw();
2685
- init_copy_repeatable_quest_rewards_to_quest();
2686
- init_copy_repeatable_quest_tags_to_quest();
3083
+ var init_create_repeatable_quest = __esm({
3084
+ "src/repeatable_quests/create_repeatable_quest.ts"() {
3085
+ init_assert_active_row_exists();
3086
+ init_assert_non_empty();
3087
+ init_assert_non_negative_seconds();
3088
+ init_resolve_now();
3089
+ init_replace_active_repeatable_quest_rewards();
3090
+ init_replace_active_repeatable_quest_tags();
2687
3091
  init_with_transaction();
2688
3092
  init_get_repeatable_quest_or_throw();
2689
- init_list_due_repeatable_quest_anchors();
3093
+ init_parse_rrule();
3094
+ }
3095
+ });
3096
+
3097
+ // src/repeatable_quests/soft_delete_repeatable_quest.ts
3098
+ function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
3099
+ const now = resolveNow(deletedAt);
3100
+ getRepeatableQuestOrThrow(db, repeatableQuestId);
3101
+ db.prepare(
3102
+ `UPDATE repeatable_quests
3103
+ SET deleted_at = ?, updated_at = ?
3104
+ WHERE id = ? AND deleted_at IS NULL`
3105
+ ).run(now, now, repeatableQuestId);
3106
+ }
3107
+ var init_soft_delete_repeatable_quest = __esm({
3108
+ "src/repeatable_quests/soft_delete_repeatable_quest.ts"() {
3109
+ init_resolve_now();
3110
+ init_get_repeatable_quest_or_throw();
2690
3111
  }
2691
3112
  });
2692
3113
 
@@ -4256,7 +4677,7 @@ function validateReviewInput(input) {
4256
4677
  'Use `filters.dayAt` only with `view: "quests.scheduled_for_day"`.'
4257
4678
  );
4258
4679
  }
4259
- if ((input.view === "rumors" || input.view === "questlines") && hasQuestFilters(input.filters)) {
4680
+ if ((input.view === "rumors" || input.view === "questlines" || input.view === "deliveries") && hasQuestFilters(input.filters)) {
4260
4681
  return toolFailure(
4261
4682
  "protocol",
4262
4683
  "invalid_input",
@@ -4324,6 +4745,15 @@ function reviewQuestlogToolHandler(db, input) {
4324
4745
  if (invalid) {
4325
4746
  return invalid;
4326
4747
  }
4748
+ if (input.view === "deliveries")
4749
+ return toolSuccess("Pending and failed deliveries.", {
4750
+ view: input.view,
4751
+ items: [],
4752
+ deliveries: listDeliveries(db),
4753
+ count: listDeliveries(db).length,
4754
+ appliedFilters: input.filters,
4755
+ evaluatedAt: input.now ?? Date.now()
4756
+ });
4327
4757
  const now = input.now ?? Date.now();
4328
4758
  let items = [];
4329
4759
  switch (input.view) {
@@ -4368,6 +4798,7 @@ function reviewQuestlogToolHandler(db, input) {
4368
4798
  var reviewQuestlogTool;
4369
4799
  var init_review_questlog_tool = __esm({
4370
4800
  "src/tools/review_questlog_tool.ts"() {
4801
+ init_list_deliveries();
4371
4802
  init_list_questlines();
4372
4803
  init_quests();
4373
4804
  init_get_repeatable_quest_or_throw();
@@ -4396,6 +4827,7 @@ var init_review_questlog_tool = __esm({
4396
4827
  inputSchema: objectSchema(
4397
4828
  {
4398
4829
  view: enumSchema("Which operational review surface to return.", [
4830
+ "deliveries",
4399
4831
  "questlines",
4400
4832
  "quests.active",
4401
4833
  "quests.available",
@@ -5966,6 +6398,7 @@ var init_tool_registry = __esm({
5966
6398
  "src/tools/tool_registry.ts"() {
5967
6399
  init_capture_rumor_tool();
5968
6400
  init_inspect_questlog_item_tool();
6401
+ init_manage_hooks_tool();
5969
6402
  init_manage_repeatable_tool();
5970
6403
  init_organize_work_tool();
5971
6404
  init_plan_quest_tool();
@@ -5977,6 +6410,7 @@ var init_tool_registry = __esm({
5977
6410
  init_shape_work_tool();
5978
6411
  init_tag_work_tool();
5979
6412
  questlogTools = [
6413
+ manageHooksTool,
5980
6414
  searchQuestlogTool,
5981
6415
  reviewQuestlogTool,
5982
6416
  inspectQuestlogItemTool,