@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/mcp.cjs CHANGED
@@ -2,10 +2,36 @@
2
2
 
3
3
  var node_fs = require('node:fs');
4
4
  var node_path = require('node:path');
5
+ var node_crypto = require('node:crypto');
5
6
  var node_os = require('node:os');
6
7
 
7
8
  // src/surface/open_questlog_db.ts
8
9
 
10
+ // src/hooks/init_hook_tables.ts
11
+ function initHookTables(db) {
12
+ db.exec(`
13
+ CREATE TABLE IF NOT EXISTS hook_targets (
14
+ id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, secret TEXT NOT NULL,
15
+ tag TEXT, events TEXT NOT NULL, min_gap INTEGER NOT NULL, created_at INTEGER NOT NULL,
16
+ last_wake INTEGER, lease_until INTEGER, claim TEXT);
17
+ CREATE TABLE IF NOT EXISTS hook_events (
18
+ id TEXT PRIMARY KEY, occurred_at INTEGER NOT NULL, event TEXT NOT NULL);
19
+ CREATE TABLE IF NOT EXISTS hook_assignments (
20
+ target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
21
+ event_id TEXT NOT NULL REFERENCES hook_events(id), delivery_id TEXT,
22
+ PRIMARY KEY(target_id, event_id));
23
+ CREATE TABLE IF NOT EXISTS hook_deliveries (
24
+ id TEXT PRIMARY KEY, target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
25
+ events TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
26
+ last_attempt_at INTEGER, http_status INTEGER, error_class TEXT,
27
+ next_attempt_at INTEGER NOT NULL);
28
+ CREATE INDEX IF NOT EXISTS idx_hook_deliveries_target ON hook_deliveries(target_id, status, next_attempt_at);
29
+ CREATE TABLE IF NOT EXISTS hook_settings (id INTEGER PRIMARY KEY CHECK(id = 1), label TEXT NOT NULL);
30
+ `);
31
+ if (!db.prepare("PRAGMA table_info(hook_targets)").all().some((row) => row.name === "headers"))
32
+ db.exec("ALTER TABLE hook_targets ADD COLUMN headers TEXT NOT NULL DEFAULT '{}'");
33
+ }
34
+
9
35
  // src/questlines/init_questline_tables.ts
10
36
  function initQuestlineTables(db) {
11
37
  db.exec(`
@@ -354,6 +380,7 @@ function initQuestlogTables(db) {
354
380
  initTagTables(db);
355
381
  initQuestSearch(db);
356
382
  initRumorSearch(db);
383
+ initHookTables(db);
357
384
  }
358
385
 
359
386
  // src/surface/open_questlog_db.ts
@@ -372,7 +399,14 @@ async function openQuestlogDb(path) {
372
399
  } finally {
373
400
  process.emitWarning = original;
374
401
  }
375
- if (path !== ":memory:") node_fs.mkdirSync(node_path.dirname(path), { recursive: true });
402
+ if (path !== ":memory:") {
403
+ node_fs.mkdirSync(node_path.dirname(path), { recursive: true, mode: 448 });
404
+ try {
405
+ node_fs.closeSync(node_fs.openSync(path, "wx", 384));
406
+ } catch (error) {
407
+ if (error.code !== "EEXIST") throw error;
408
+ }
409
+ }
376
410
  const db = new sqlite.DatabaseSync(path);
377
411
  try {
378
412
  db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;");
@@ -386,7 +420,7 @@ async function openQuestlogDb(path) {
386
420
  }
387
421
 
388
422
  // src/version.ts
389
- var questlogVersion = "0.9.2";
423
+ var questlogVersion = "0.11.0";
390
424
 
391
425
  // src/surface/questlog_mcp_instructions.ts
392
426
  var questlogMcpInstructions = "Questlog manages local tasks, calendar commitments, and recurring work. Search before creating work, inspect before changing it, and keep uncertain work as rumors. Use unlock prerequisites to sequence work. run_quest refuses blocked starts unless force is true. Review commitments and resolve work with an honest outcome.";
@@ -731,6 +765,7 @@ function validateInput(schema, input, path = "$") {
731
765
 
732
766
  // src/tools/action_requirements.ts
733
767
  var actionRequirements = {
768
+ manage_hooks: { remove: ["id"] },
734
769
  shape_work: {
735
770
  create_quest: ["quest"],
736
771
  create_questline: ["questline"],
@@ -1022,6 +1057,27 @@ var captureRumorTool = defineQuestlogTool({
1022
1057
  handler: captureRumorToolHandler
1023
1058
  });
1024
1059
 
1060
+ // src/hooks/list_deliveries.ts
1061
+ function listDeliveries(db, options = {}) {
1062
+ return db.prepare(
1063
+ `SELECT * FROM hook_deliveries ${options.includeDelivered ? "" : "WHERE status <> 'delivered'"} ORDER BY target_id, next_attempt_at, id`
1064
+ ).all().map(
1065
+ (row) => ({
1066
+ id: String(row.id),
1067
+ targetId: Number(row.target_id),
1068
+ events: JSON.parse(String(row.events)),
1069
+ status: row.status,
1070
+ attempts: Number(row.attempts),
1071
+ lastAttemptAt: row.last_attempt_at == null ? null : Number(row.last_attempt_at),
1072
+ httpStatus: row.http_status == null ? null : Number(row.http_status),
1073
+ errorClass: row.error_class == null ? null : String(row.error_class),
1074
+ nextAttemptAt: Number(row.next_attempt_at)
1075
+ })
1076
+ ).filter(
1077
+ (d) => options.questId === void 0 || d.events.some((e) => e.questId === options.questId)
1078
+ );
1079
+ }
1080
+
1025
1081
  // src/questlines/map_questline_row.ts
1026
1082
  function mapQuestlineRow(row) {
1027
1083
  return {
@@ -1499,7 +1555,8 @@ function inspectQuestlogItemToolHandler(db, input) {
1499
1555
  detail: detailLevel === "full" ? detail : toQuestCompactDetail(detail)
1500
1556
  },
1501
1557
  related,
1502
- detailLevel
1558
+ detailLevel,
1559
+ deliveries: listDeliveries(db, { questId: detail.id })
1503
1560
  },
1504
1561
  { entities }
1505
1562
  );
@@ -1604,13 +1661,42 @@ var inspectQuestlogItemTool = defineQuestlogTool({
1604
1661
  ),
1605
1662
  handler: inspectQuestlogItemToolHandler
1606
1663
  });
1607
-
1608
- // src/assert_non_negative_seconds.ts
1609
- function assertNonNegativeSeconds(value, label) {
1610
- if (value != null && value < 0) {
1611
- throw new Error(`${label} must not be negative.`);
1612
- }
1613
- return value;
1664
+ function hookLabel(db, name) {
1665
+ const saved = db.prepare("SELECT label FROM hook_settings WHERE id = 1").get();
1666
+ if (saved) return String(saved.label);
1667
+ const path = String(
1668
+ db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? ""
1669
+ );
1670
+ return path ? node_path.basename(path, node_path.extname(path)) : "questlog";
1671
+ }
1672
+
1673
+ // src/hooks/list_hooks.ts
1674
+ function listHooks(db) {
1675
+ return db.prepare(`SELECT id, url, headers, tag, events, min_gap, created_at, last_wake,
1676
+ (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,
1677
+ (SELECT COUNT(*) FROM hook_deliveries d WHERE d.target_id = t.id AND d.status = 'failed') AS failed
1678
+ FROM hook_targets t ORDER BY id`).all().map((row) => {
1679
+ const url = new URL(String(row.url));
1680
+ url.username = "";
1681
+ url.password = "";
1682
+ url.search = "";
1683
+ url.hash = "";
1684
+ return {
1685
+ id: Number(row.id),
1686
+ headers: Object.fromEntries(
1687
+ Object.keys(JSON.parse(String(row.headers))).map((name) => [name, "***"])
1688
+ ),
1689
+ scope: row.tag == null ? "database" : "tag",
1690
+ url: url.href,
1691
+ tag: row.tag == null ? null : String(row.tag),
1692
+ events: JSON.parse(String(row.events)),
1693
+ minGap: Number(row.min_gap),
1694
+ createdAt: Number(row.created_at),
1695
+ lastWake: row.last_wake == null ? null : Number(row.last_wake),
1696
+ pending: Number(row.pending),
1697
+ failed: Number(row.failed)
1698
+ };
1699
+ });
1614
1700
  }
1615
1701
 
1616
1702
  // src/with_transaction.ts
@@ -1648,6 +1734,140 @@ function withTransaction(db, fn) {
1648
1734
  }
1649
1735
  }
1650
1736
 
1737
+ // src/hooks/remove_hook.ts
1738
+ function removeHook(db, id) {
1739
+ withTransaction(db, () => {
1740
+ db.prepare("DELETE FROM hook_assignments WHERE target_id = ?").run(id);
1741
+ db.prepare("DELETE FROM hook_deliveries WHERE target_id = ?").run(id);
1742
+ db.prepare("DELETE FROM hook_targets WHERE id = ?").run(id);
1743
+ });
1744
+ }
1745
+ async function sendHookDelivery(db, delivery, target, options) {
1746
+ const now = options.now ?? options.clock?.() ?? Date.now();
1747
+ const timestamp = String(Math.floor(now / 1e3));
1748
+ const body = JSON.stringify({
1749
+ type: "questlog.events",
1750
+ db: hookLabel(db),
1751
+ deliveryId: delivery.id,
1752
+ sentAt: new Date(now).toISOString(),
1753
+ events: delivery.events
1754
+ });
1755
+ const signature = node_crypto.createHmac("sha256", target.secret).update(`${timestamp}.${body}`).digest("hex");
1756
+ let status = null;
1757
+ let errorClass = null;
1758
+ try {
1759
+ const response = await (options.fetch ?? globalThis.fetch)(target.url, {
1760
+ method: "POST",
1761
+ redirect: "error",
1762
+ headers: {
1763
+ "user-agent": `questlog/${questlogVersion}`,
1764
+ ...JSON.parse(
1765
+ String(
1766
+ db.prepare("SELECT headers FROM hook_targets WHERE id = ?").get(target.id)?.headers ?? "{}"
1767
+ )
1768
+ ),
1769
+ "content-type": "application/json",
1770
+ "x-questlog-delivery": delivery.id,
1771
+ "x-questlog-timestamp": timestamp,
1772
+ "x-questlog-signature": `sha256=${signature}`
1773
+ },
1774
+ body,
1775
+ signal: AbortSignal.timeout(Math.max(1, Math.min(options.timeoutMs ?? 5e3, 5e3)))
1776
+ });
1777
+ status = response.status;
1778
+ await response.body?.cancel();
1779
+ } catch (error) {
1780
+ errorClass = error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name) ? error.name : "NetworkError";
1781
+ }
1782
+ const delivered = status != null && status >= 200 && status < 300;
1783
+ const completedAt = options.now ?? options.clock?.() ?? Date.now();
1784
+ withTransaction(db, () => {
1785
+ if (!db.prepare("SELECT id FROM hook_targets WHERE id = ? AND claim = ?").get(target.id, target.claim))
1786
+ return;
1787
+ const delay = Math.min(36e5, 3e4 * 2 ** (delivery.attempts - 1));
1788
+ const jitter = Number.parseInt(node_crypto.randomBytes(2).toString("hex"), 16) % 1e3;
1789
+ db.prepare(
1790
+ "UPDATE hook_deliveries SET status = ?, http_status = ?, error_class = ?, next_attempt_at = ? WHERE id = ?"
1791
+ ).run(
1792
+ delivered ? "delivered" : delivery.attempts >= 8 ? "failed" : "pending",
1793
+ status,
1794
+ errorClass,
1795
+ completedAt + delay + jitter,
1796
+ delivery.id
1797
+ );
1798
+ db.prepare(
1799
+ "UPDATE hook_targets SET claim = NULL, lease_until = NULL WHERE id = ? AND claim = ?"
1800
+ ).run(target.id, target.claim);
1801
+ db.prepare(
1802
+ "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)"
1803
+ ).run(target.id, target.id);
1804
+ });
1805
+ return delivered;
1806
+ }
1807
+
1808
+ // src/quests/get_quest_or_throw.ts
1809
+ function getQuestOrThrow(db, questId) {
1810
+ const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
1811
+ if (!row) {
1812
+ throw new Error(`Quest ${questId} was not found.`);
1813
+ }
1814
+ return mapQuestRow(row);
1815
+ }
1816
+
1817
+ // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
1818
+ function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
1819
+ const effectiveNow = resolveNow(now);
1820
+ const rows = db.prepare(
1821
+ `SELECT kind, name, description, quantity
1822
+ FROM repeatable_quest_rewards
1823
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
1824
+ ).all(repeatableQuestId);
1825
+ for (const row of rows) {
1826
+ db.prepare(
1827
+ `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
1828
+ VALUES (?, ?, ?, ?, ?, ?)`
1829
+ ).run(
1830
+ questId,
1831
+ String(row.kind),
1832
+ String(row.name),
1833
+ row.description == null ? null : String(row.description),
1834
+ row.quantity == null ? null : Number(row.quantity),
1835
+ effectiveNow
1836
+ );
1837
+ }
1838
+ }
1839
+
1840
+ // src/tags/copy_repeatable_quest_tags_to_quest.ts
1841
+ function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
1842
+ const effectiveNow = resolveNow(now);
1843
+ const rows = db.prepare(
1844
+ `SELECT tag_id
1845
+ FROM repeatable_quest_tags
1846
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
1847
+ ).all(repeatableQuestId);
1848
+ for (const row of rows) {
1849
+ db.prepare(
1850
+ `INSERT INTO quest_tags (quest_id, tag_id, created_at)
1851
+ VALUES (?, ?, ?)`
1852
+ ).run(questId, Number(row.tag_id), effectiveNow);
1853
+ }
1854
+ }
1855
+
1856
+ // src/repeatable_quests/advance_anchor.ts
1857
+ var WEEK_MS = 7 * 864e5;
1858
+ function advanceAnchor(anchorAt, freq, interval) {
1859
+ const date = new Date(anchorAt);
1860
+ if (freq === "MONTHLY") {
1861
+ date.setUTCMonth(date.getUTCMonth() + interval);
1862
+ return date.getTime();
1863
+ }
1864
+ if (freq === "YEARLY") {
1865
+ date.setUTCFullYear(date.getUTCFullYear() + interval);
1866
+ return date.getTime();
1867
+ }
1868
+ return anchorAt + interval * WEEK_MS;
1869
+ }
1870
+
1651
1871
  // src/repeatable_quests/parse_rrule.ts
1652
1872
  var WEEKDAY = {
1653
1873
  SU: 0,
@@ -1691,265 +1911,76 @@ function parseRRule(rrule) {
1691
1911
  return { freq, interval, count, until, byDay };
1692
1912
  }
1693
1913
 
1694
- // src/repeatable_quests/update_repeatable_quest.ts
1695
- function updateRepeatableQuest(db, repeatableQuestId, input) {
1696
- return withTransaction(db, () => {
1697
- const current = getRepeatableQuestOrThrow(db, repeatableQuestId);
1698
- const now = resolveNow(input.now);
1699
- const rrule = input.rrule ?? current.rrule;
1700
- parseRRule(rrule);
1701
- db.prepare(
1702
- `UPDATE repeatable_quests
1703
- SET questline_id = ?,
1704
- title = ?,
1705
- objective = ?,
1706
- rrule = ?,
1707
- anchor_at = ?,
1708
- not_before_offset_seconds = ?,
1709
- due_offset_seconds = ?,
1710
- scheduled_start_offset_seconds = ?,
1711
- scheduled_end_offset_seconds = ?,
1712
- all_day = ?,
1713
- estimate_seconds = ?,
1714
- archived_at = ?,
1715
- updated_at = ?
1716
- WHERE id = ? AND deleted_at IS NULL`
1717
- ).run(
1718
- input.questlineId === void 0 ? current.questlineId : input.questlineId,
1719
- input.title == null ? current.title : assertNonEmpty(input.title, "Repeatable quest title"),
1720
- input.objective == null ? current.objective : assertNonEmpty(input.objective, "Repeatable quest objective"),
1721
- rrule,
1722
- input.anchorAt ?? current.anchorAt,
1723
- input.notBeforeOffsetSeconds === void 0 ? current.notBeforeOffsetSeconds : assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
1724
- input.dueOffsetSeconds === void 0 ? current.dueOffsetSeconds : assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
1725
- input.scheduledStartOffsetSeconds === void 0 ? current.scheduledStartOffsetSeconds : input.scheduledStartOffsetSeconds,
1726
- input.scheduledEndOffsetSeconds === void 0 ? current.scheduledEndOffsetSeconds : input.scheduledEndOffsetSeconds,
1727
- input.allDay === void 0 ? current.allDay ? 1 : 0 : input.allDay ? 1 : 0,
1728
- input.estimateSeconds === void 0 ? current.estimateSeconds : assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
1729
- input.archivedAt === void 0 ? current.archivedAt : input.archivedAt,
1730
- now,
1731
- repeatableQuestId
1732
- );
1733
- return getRepeatableQuestOrThrow(db, repeatableQuestId);
1734
- });
1914
+ // src/repeatable_quests/start_of_utc_day.ts
1915
+ function startOfUtcDay(timestamp) {
1916
+ const date = new Date(timestamp);
1917
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
1735
1918
  }
1736
1919
 
1737
- // src/repeatable_quests/archive_repeatable_quest.ts
1738
- function archiveRepeatableQuest(db, repeatableQuestId, archivedAt) {
1739
- return updateRepeatableQuest(db, repeatableQuestId, { archivedAt: resolveNow(archivedAt) });
1920
+ // src/repeatable_quests/start_of_utc_week.ts
1921
+ var DAY_MS = 864e5;
1922
+ function startOfUtcWeek(dayStart) {
1923
+ const date = new Date(dayStart);
1924
+ return dayStart - date.getUTCDay() * DAY_MS;
1740
1925
  }
1741
1926
 
1742
- // src/assert_active_row_exists.ts
1743
- function assertActiveRowExists(db, table, id, label) {
1744
- const row = db.prepare(`SELECT id FROM ${table} WHERE id = ? AND deleted_at IS NULL`).get(id);
1745
- if (!row) {
1746
- throw new Error(`${label} ${id} was not found.`);
1927
+ // src/repeatable_quests/generate_anchors_until.ts
1928
+ var DAY_MS2 = 864e5;
1929
+ var WEEK_MS2 = 7 * DAY_MS2;
1930
+ function generateAnchorsUntil(repeatable, now) {
1931
+ const rule = parseRRule(repeatable.rrule);
1932
+ const anchors = [];
1933
+ const until = rule.until == null ? now : Math.min(now, rule.until);
1934
+ if (repeatable.anchorAt > until) {
1935
+ return anchors;
1747
1936
  }
1748
- }
1749
-
1750
- // src/assert_non_negative_number.ts
1751
- function assertNonNegativeNumber(value, label) {
1752
- if (value != null && value < 0) {
1753
- throw new Error(`${label} must not be negative.`);
1937
+ if (rule.freq === "DAILY") {
1938
+ let occurrence2 = 0;
1939
+ for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
1940
+ occurrence2 += 1;
1941
+ if (rule.count != null && occurrence2 > rule.count) {
1942
+ break;
1943
+ }
1944
+ anchors.push(current2);
1945
+ }
1946
+ return anchors;
1754
1947
  }
1755
- return value;
1756
- }
1757
-
1758
- // src/rewards/replace_active_repeatable_quest_rewards.ts
1759
- function replaceActiveRepeatableQuestRewards(db, repeatableQuestId, rewards, now) {
1760
- const effectiveNow = resolveNow(now);
1761
- db.prepare(
1762
- "UPDATE repeatable_quest_rewards SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
1763
- ).run(effectiveNow, repeatableQuestId);
1764
- for (const reward of rewards) {
1765
- db.prepare(
1766
- `INSERT INTO repeatable_quest_rewards (
1767
- repeatable_quest_id,
1768
- kind,
1769
- name,
1770
- description,
1771
- quantity,
1772
- created_at
1773
- ) VALUES (?, ?, ?, ?, ?, ?)`
1774
- ).run(
1775
- repeatableQuestId,
1776
- assertNonEmpty(reward.kind, "Reward kind"),
1777
- assertNonEmpty(reward.name, "Reward name"),
1778
- reward.description?.trim() || null,
1779
- assertNonNegativeNumber(reward.quantity, "Reward quantity") ?? null,
1780
- effectiveNow
1781
- );
1948
+ if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
1949
+ const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
1950
+ const anchorWeekStart = startOfUtcWeek(anchorDayStart);
1951
+ const timeOffset = repeatable.anchorAt - anchorDayStart;
1952
+ let occurrence2 = 0;
1953
+ for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
1954
+ const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
1955
+ if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
1956
+ continue;
1957
+ }
1958
+ if (!rule.byDay.includes(new Date(day).getUTCDay())) {
1959
+ continue;
1960
+ }
1961
+ const anchor = day + timeOffset;
1962
+ if (anchor < repeatable.anchorAt || anchor > until) {
1963
+ continue;
1964
+ }
1965
+ occurrence2 += 1;
1966
+ if (rule.count != null && occurrence2 > rule.count) {
1967
+ break;
1968
+ }
1969
+ anchors.push(anchor);
1970
+ }
1971
+ return anchors;
1972
+ }
1973
+ let occurrence = 0;
1974
+ let current = repeatable.anchorAt;
1975
+ while (current <= until) {
1976
+ occurrence += 1;
1977
+ if (rule.count != null && occurrence > rule.count) {
1978
+ break;
1979
+ }
1980
+ anchors.push(current);
1981
+ current = advanceAnchor(current, rule.freq, rule.interval);
1782
1982
  }
1783
- }
1784
-
1785
- // src/tags/replace_active_repeatable_quest_tags.ts
1786
- function getOrCreateTagId(db, name, now) {
1787
- const normalizedName = normalizeTagName(name);
1788
- if (!normalizedName) {
1789
- throw new Error("Tag name must not be empty.");
1790
- }
1791
- const existing = db.prepare("SELECT id FROM tags WHERE normalized_name = ? AND deleted_at IS NULL").get(normalizedName);
1792
- if (existing) {
1793
- return Number(existing.id);
1794
- }
1795
- const created = db.prepare(
1796
- `INSERT INTO tags (name, normalized_name, created_at)
1797
- VALUES (?, ?, ?)`
1798
- ).run(name.trim(), normalizedName, now);
1799
- return Number(created.lastInsertRowid);
1800
- }
1801
- function replaceActiveRepeatableQuestTags(db, repeatableQuestId, tagNames, now) {
1802
- const effectiveNow = resolveNow(now);
1803
- db.prepare(
1804
- "UPDATE repeatable_quest_tags SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
1805
- ).run(effectiveNow, repeatableQuestId);
1806
- const uniqueNames = [...new Set(tagNames.map((tag) => tag.trim()).filter(Boolean))];
1807
- for (const name of uniqueNames) {
1808
- const tagId = getOrCreateTagId(db, name, effectiveNow);
1809
- db.prepare(
1810
- `INSERT INTO repeatable_quest_tags (repeatable_quest_id, tag_id, created_at)
1811
- VALUES (?, ?, ?)`
1812
- ).run(repeatableQuestId, tagId, effectiveNow);
1813
- }
1814
- }
1815
-
1816
- // src/repeatable_quests/create_repeatable_quest.ts
1817
- function createRepeatableQuest(db, input) {
1818
- return withTransaction(db, () => {
1819
- const now = resolveNow(input.now);
1820
- const title = assertNonEmpty(input.title, "Repeatable quest title");
1821
- const objective = assertNonEmpty(input.objective, "Repeatable quest objective");
1822
- parseRRule(input.rrule);
1823
- if (input.questlineId != null) {
1824
- assertActiveRowExists(db, "questlines", input.questlineId, "Questline");
1825
- }
1826
- const created = db.prepare(
1827
- `INSERT INTO repeatable_quests (
1828
- questline_id,
1829
- title,
1830
- objective,
1831
- rrule,
1832
- anchor_at,
1833
- not_before_offset_seconds,
1834
- due_offset_seconds,
1835
- scheduled_start_offset_seconds,
1836
- scheduled_end_offset_seconds,
1837
- all_day,
1838
- estimate_seconds,
1839
- created_at,
1840
- updated_at
1841
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
1842
- ).run(
1843
- input.questlineId ?? null,
1844
- title,
1845
- objective,
1846
- input.rrule,
1847
- input.anchorAt,
1848
- assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
1849
- assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
1850
- input.scheduledStartOffsetSeconds ?? null,
1851
- input.scheduledEndOffsetSeconds ?? null,
1852
- input.allDay ? 1 : 0,
1853
- assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
1854
- now,
1855
- now
1856
- );
1857
- const repeatableQuestId = Number(created.lastInsertRowid);
1858
- if (input.tags && input.tags.length > 0) {
1859
- replaceActiveRepeatableQuestTags(db, repeatableQuestId, input.tags, now);
1860
- }
1861
- if (input.rewards && input.rewards.length > 0) {
1862
- replaceActiveRepeatableQuestRewards(db, repeatableQuestId, input.rewards, now);
1863
- }
1864
- return getRepeatableQuestOrThrow(db, repeatableQuestId);
1865
- });
1866
- }
1867
-
1868
- // src/repeatable_quests/advance_anchor.ts
1869
- var WEEK_MS = 7 * 864e5;
1870
- function advanceAnchor(anchorAt, freq, interval) {
1871
- const date = new Date(anchorAt);
1872
- if (freq === "MONTHLY") {
1873
- date.setUTCMonth(date.getUTCMonth() + interval);
1874
- return date.getTime();
1875
- }
1876
- if (freq === "YEARLY") {
1877
- date.setUTCFullYear(date.getUTCFullYear() + interval);
1878
- return date.getTime();
1879
- }
1880
- return anchorAt + interval * WEEK_MS;
1881
- }
1882
-
1883
- // src/repeatable_quests/start_of_utc_day.ts
1884
- function startOfUtcDay(timestamp) {
1885
- const date = new Date(timestamp);
1886
- return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
1887
- }
1888
-
1889
- // src/repeatable_quests/start_of_utc_week.ts
1890
- var DAY_MS = 864e5;
1891
- function startOfUtcWeek(dayStart) {
1892
- const date = new Date(dayStart);
1893
- return dayStart - date.getUTCDay() * DAY_MS;
1894
- }
1895
-
1896
- // src/repeatable_quests/generate_anchors_until.ts
1897
- var DAY_MS2 = 864e5;
1898
- var WEEK_MS2 = 7 * DAY_MS2;
1899
- function generateAnchorsUntil(repeatable, now) {
1900
- const rule = parseRRule(repeatable.rrule);
1901
- const anchors = [];
1902
- const until = rule.until == null ? now : Math.min(now, rule.until);
1903
- if (repeatable.anchorAt > until) {
1904
- return anchors;
1905
- }
1906
- if (rule.freq === "DAILY") {
1907
- let occurrence2 = 0;
1908
- for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
1909
- occurrence2 += 1;
1910
- if (rule.count != null && occurrence2 > rule.count) {
1911
- break;
1912
- }
1913
- anchors.push(current2);
1914
- }
1915
- return anchors;
1916
- }
1917
- if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
1918
- const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
1919
- const anchorWeekStart = startOfUtcWeek(anchorDayStart);
1920
- const timeOffset = repeatable.anchorAt - anchorDayStart;
1921
- let occurrence2 = 0;
1922
- for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
1923
- const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
1924
- if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
1925
- continue;
1926
- }
1927
- if (!rule.byDay.includes(new Date(day).getUTCDay())) {
1928
- continue;
1929
- }
1930
- const anchor = day + timeOffset;
1931
- if (anchor < repeatable.anchorAt || anchor > until) {
1932
- continue;
1933
- }
1934
- occurrence2 += 1;
1935
- if (rule.count != null && occurrence2 > rule.count) {
1936
- break;
1937
- }
1938
- anchors.push(anchor);
1939
- }
1940
- return anchors;
1941
- }
1942
- let occurrence = 0;
1943
- let current = repeatable.anchorAt;
1944
- while (current <= until) {
1945
- occurrence += 1;
1946
- if (rule.count != null && occurrence > rule.count) {
1947
- break;
1948
- }
1949
- anchors.push(current);
1950
- current = advanceAnchor(current, rule.freq, rule.interval);
1951
- }
1952
- return anchors;
1983
+ return anchors;
1953
1984
  }
1954
1985
 
1955
1986
  // src/repeatable_quests/list_due_repeatable_quest_anchors.ts
@@ -1997,65 +2028,6 @@ function listDueRepeatableQuestAnchors(db, now) {
1997
2028
  );
1998
2029
  }
1999
2030
 
2000
- // src/repeatable_quests/soft_delete_repeatable_quest.ts
2001
- function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
2002
- const now = resolveNow(deletedAt);
2003
- getRepeatableQuestOrThrow(db, repeatableQuestId);
2004
- db.prepare(
2005
- `UPDATE repeatable_quests
2006
- SET deleted_at = ?, updated_at = ?
2007
- WHERE id = ? AND deleted_at IS NULL`
2008
- ).run(now, now, repeatableQuestId);
2009
- }
2010
-
2011
- // src/quests/get_quest_or_throw.ts
2012
- function getQuestOrThrow(db, questId) {
2013
- const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
2014
- if (!row) {
2015
- throw new Error(`Quest ${questId} was not found.`);
2016
- }
2017
- return mapQuestRow(row);
2018
- }
2019
-
2020
- // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
2021
- function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
2022
- const effectiveNow = resolveNow(now);
2023
- const rows = db.prepare(
2024
- `SELECT kind, name, description, quantity
2025
- FROM repeatable_quest_rewards
2026
- WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
2027
- ).all(repeatableQuestId);
2028
- for (const row of rows) {
2029
- db.prepare(
2030
- `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
2031
- VALUES (?, ?, ?, ?, ?, ?)`
2032
- ).run(
2033
- questId,
2034
- String(row.kind),
2035
- String(row.name),
2036
- row.description == null ? null : String(row.description),
2037
- row.quantity == null ? null : Number(row.quantity),
2038
- effectiveNow
2039
- );
2040
- }
2041
- }
2042
-
2043
- // src/tags/copy_repeatable_quest_tags_to_quest.ts
2044
- function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
2045
- const effectiveNow = resolveNow(now);
2046
- const rows = db.prepare(
2047
- `SELECT tag_id
2048
- FROM repeatable_quest_tags
2049
- WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
2050
- ).all(repeatableQuestId);
2051
- for (const row of rows) {
2052
- db.prepare(
2053
- `INSERT INTO quest_tags (quest_id, tag_id, created_at)
2054
- VALUES (?, ?, ?)`
2055
- ).run(questId, Number(row.tag_id), effectiveNow);
2056
- }
2057
- }
2058
-
2059
2031
  // src/repeatable_quests/spawn_due_repeatable_quests.ts
2060
2032
  function spawnDueRepeatableQuests(db, now) {
2061
2033
  return withTransaction(db, () => {
@@ -2106,6 +2078,410 @@ function spawnDueRepeatableQuests(db, now) {
2106
2078
  });
2107
2079
  }
2108
2080
 
2081
+ // src/hooks/detect_hook_events.ts
2082
+ function detectHookEvents(db, now) {
2083
+ const events = [];
2084
+ const add = (type, at, ids) => {
2085
+ events.push({
2086
+ id: `e_${type}_${ids.questId ?? ids.rumorId}_${ids.repeatableId ?? ""}_${at}`,
2087
+ type,
2088
+ ...ids,
2089
+ occurredAt: new Date(at).toISOString()
2090
+ });
2091
+ };
2092
+ for (const { detail: q } of queryQuestDetailRecords(db, {}, now)) {
2093
+ if (q.resolvedAt == null && q.effectiveDueAt != null && q.effectiveDueAt <= now) {
2094
+ add("quest.due", q.effectiveDueAt, { questId: q.id });
2095
+ if (q.effectiveDueAt < now) add("quest.overdue", q.effectiveDueAt, { questId: q.id });
2096
+ }
2097
+ if (q.available) {
2098
+ const prerequisites = db.prepare(
2099
+ `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`
2100
+ ).all(q.id);
2101
+ if (prerequisites.some((p) => Number(p.resolved_at) >= Number(p.created_at))) {
2102
+ const at = Math.max(q.notBeforeAt ?? 0, ...prerequisites.map((p) => Number(p.resolved_at)));
2103
+ if (at <= now) add("quest.unblocked", at, { questId: q.id });
2104
+ }
2105
+ }
2106
+ if (q.spawnedFromRepeatableId != null && q.createdAt <= now)
2107
+ add("repeatable.spawned", q.createdAt, {
2108
+ questId: q.id,
2109
+ repeatableId: q.spawnedFromRepeatableId
2110
+ });
2111
+ }
2112
+ for (const row of db.prepare("SELECT id, created_at FROM rumors WHERE deleted_at IS NULL AND created_at <= ?").all(now))
2113
+ add("rumor.captured", Number(row.created_at), { rumorId: Number(row.id) });
2114
+ return events.sort(
2115
+ (a, b) => a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
2116
+ );
2117
+ }
2118
+
2119
+ // src/hooks/tick_questlog.ts
2120
+ async function tickQuestlog(db, options = {}) {
2121
+ const now = options.now ?? options.clock?.() ?? Date.now();
2122
+ const result = {
2123
+ events: [],
2124
+ batches: [],
2125
+ sent: 0,
2126
+ queued: 0,
2127
+ retrying: 0,
2128
+ failed: 0
2129
+ };
2130
+ const claims = [];
2131
+ const collect = () => {
2132
+ spawnDueRepeatableQuests(db, now);
2133
+ const detected = detectHookEvents(db, now);
2134
+ result.events = detected.filter(
2135
+ (e) => !db.prepare("SELECT id FROM hook_events WHERE id = ?").get(e.id)
2136
+ );
2137
+ for (const event of result.events)
2138
+ db.prepare("INSERT INTO hook_events(id, occurred_at, event) VALUES (?, ?, ?)").run(
2139
+ event.id,
2140
+ Date.parse(event.occurredAt),
2141
+ JSON.stringify(event)
2142
+ );
2143
+ for (const target of listHooks(db)) {
2144
+ const events = db.prepare(
2145
+ "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"
2146
+ ).all(target.createdAt, target.id).map((row2) => JSON.parse(String(row2.event))).filter((event) => {
2147
+ if (!target.events.includes(event.type)) return false;
2148
+ if (target.tag == null) return true;
2149
+ return event.questId !== void 0 && db.prepare(
2150
+ "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 = ?"
2151
+ ).get(event.questId, normalizeTagName(target.tag)) !== void 0;
2152
+ });
2153
+ for (const event of events)
2154
+ db.prepare("INSERT INTO hook_assignments(target_id, event_id) VALUES (?, ?)").run(
2155
+ target.id,
2156
+ event.id
2157
+ );
2158
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(target.id);
2159
+ if (!row || row.lease_until != null && Number(row.lease_until) > now) continue;
2160
+ let pending = listDeliveries(db).find(
2161
+ (d) => d.targetId === target.id && d.status === "pending"
2162
+ );
2163
+ const queued = db.prepare(
2164
+ "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"
2165
+ ).all(target.id).map((r) => JSON.parse(String(r.event)));
2166
+ if (!pending && queued.length) {
2167
+ const id = `d_${node_crypto.randomBytes(16).toString("hex")}`;
2168
+ db.prepare(
2169
+ "INSERT INTO hook_deliveries(id, target_id, events, status, next_attempt_at) VALUES (?, ?, ?, 'pending', ?)"
2170
+ ).run(
2171
+ id,
2172
+ target.id,
2173
+ JSON.stringify(queued),
2174
+ Math.max(now, (target.lastWake ?? -Infinity) + target.minGap * 1e3)
2175
+ );
2176
+ db.prepare(
2177
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
2178
+ ).run(id, target.id);
2179
+ pending = listDeliveries(db).find((d) => d.id === id);
2180
+ }
2181
+ if (!pending) continue;
2182
+ if (pending.attempts === 0 && queued.length && !queued.every((e) => pending?.events.some((p) => p.id === e.id))) {
2183
+ pending.events.push(...queued);
2184
+ db.prepare("UPDATE hook_deliveries SET events = ? WHERE id = ?").run(
2185
+ JSON.stringify(pending.events),
2186
+ pending.id
2187
+ );
2188
+ db.prepare(
2189
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
2190
+ ).run(pending.id, target.id);
2191
+ }
2192
+ if (pending.nextAttemptAt > now || target.lastWake != null && target.lastWake + target.minGap * 1e3 > now)
2193
+ continue;
2194
+ if (pending.attempts >= 8) {
2195
+ db.prepare("UPDATE hook_deliveries SET status = 'failed' WHERE id = ?").run(pending.id);
2196
+ continue;
2197
+ }
2198
+ const claim = node_crypto.randomBytes(16).toString("hex");
2199
+ db.prepare(
2200
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
2201
+ ).run(claim, now + 12e4, now, target.id);
2202
+ db.prepare(
2203
+ "UPDATE hook_deliveries SET attempts = attempts + 1, last_attempt_at = ? WHERE id = ?"
2204
+ ).run(now, pending.id);
2205
+ pending.attempts++;
2206
+ pending.lastAttemptAt = now;
2207
+ result.batches.push({ targetId: target.id, events: pending.events });
2208
+ claims.push({
2209
+ delivery: pending,
2210
+ target: { id: target.id, url: String(row.url), secret: String(row.secret), claim }
2211
+ });
2212
+ }
2213
+ };
2214
+ if (options.dryRun) {
2215
+ const rollback = new Error("preview rollback");
2216
+ try {
2217
+ withTransaction(db, () => {
2218
+ collect();
2219
+ throw rollback;
2220
+ });
2221
+ } catch (error) {
2222
+ if (error !== rollback) throw error;
2223
+ }
2224
+ } else withTransaction(db, collect);
2225
+ if (!options.dryRun) {
2226
+ const sent = await Promise.all(
2227
+ claims.map((claim) => sendHookDelivery(db, claim.delivery, claim.target, options))
2228
+ );
2229
+ result.sent = sent.filter(Boolean).length;
2230
+ }
2231
+ const deliveries = listDeliveries(db);
2232
+ result.queued = deliveries.filter((d) => d.status === "pending" && d.attempts === 0).length + Number(
2233
+ db.prepare(
2234
+ "SELECT COUNT(DISTINCT target_id) AS n FROM hook_assignments WHERE delivery_id IS NULL"
2235
+ ).get()?.n ?? 0
2236
+ );
2237
+ result.retrying = deliveries.filter((d) => d.status === "pending" && d.attempts > 0).length;
2238
+ result.failed = deliveries.filter((d) => d.status === "failed").length;
2239
+ return result;
2240
+ }
2241
+
2242
+ // src/tools/manage_hooks_tool.ts
2243
+ var manageHooksTool = defineQuestlogTool({
2244
+ name: "manage_hooks",
2245
+ description: "List or remove outbound webhook targets, run a tick, or inspect pending and failed deliveries.",
2246
+ whenToUse: "Use to operate configured outbound webhooks. Add and test targets with the CLI.",
2247
+ whenNotToUse: "Use quest tools to change work itself.",
2248
+ sideEffects: "writes_state",
2249
+ readOnly: false,
2250
+ supportsClarification: false,
2251
+ targetKinds: ["hook"],
2252
+ inputDescriptions: {
2253
+ action: "Operation to perform.",
2254
+ id: "Target id for removal.",
2255
+ dry_run: "Preview a tick without recording or sending."
2256
+ },
2257
+ outputDescription: "Returns redacted targets, delivery metadata, or a tick summary. Never returns signing secrets.",
2258
+ inputSchema: objectSchema(
2259
+ {
2260
+ action: enumSchema("Operation.", ["list", "remove", "tick", "deliveries"]),
2261
+ id: integerSchema("Target id."),
2262
+ dry_run: booleanSchema("Preview only.")
2263
+ },
2264
+ ["action"]
2265
+ ),
2266
+ handler: async (db, input) => {
2267
+ switch (input.action) {
2268
+ case "list":
2269
+ return toolSuccess("Webhook targets.", listHooks(db));
2270
+ case "deliveries":
2271
+ return toolSuccess("Pending and failed deliveries.", listDeliveries(db));
2272
+ case "remove":
2273
+ if (!Number.isSafeInteger(input.id) || Number(input.id) < 1)
2274
+ return toolFailure(
2275
+ "protocol",
2276
+ "invalid_input",
2277
+ "Target id required.",
2278
+ "Provide a positive target id.",
2279
+ { recovery: 'Pass {"action":"remove","id":1}' }
2280
+ );
2281
+ removeHook(db, Number(input.id));
2282
+ return toolSuccess("Webhook target removed.", {});
2283
+ case "tick":
2284
+ return toolSuccess(
2285
+ "Webhook tick completed.",
2286
+ await tickQuestlog(db, { dryRun: input.dry_run ?? false })
2287
+ );
2288
+ }
2289
+ }
2290
+ });
2291
+
2292
+ // src/assert_non_negative_seconds.ts
2293
+ function assertNonNegativeSeconds(value, label) {
2294
+ if (value != null && value < 0) {
2295
+ throw new Error(`${label} must not be negative.`);
2296
+ }
2297
+ return value;
2298
+ }
2299
+
2300
+ // src/repeatable_quests/update_repeatable_quest.ts
2301
+ function updateRepeatableQuest(db, repeatableQuestId, input) {
2302
+ return withTransaction(db, () => {
2303
+ const current = getRepeatableQuestOrThrow(db, repeatableQuestId);
2304
+ const now = resolveNow(input.now);
2305
+ const rrule = input.rrule ?? current.rrule;
2306
+ parseRRule(rrule);
2307
+ db.prepare(
2308
+ `UPDATE repeatable_quests
2309
+ SET questline_id = ?,
2310
+ title = ?,
2311
+ objective = ?,
2312
+ rrule = ?,
2313
+ anchor_at = ?,
2314
+ not_before_offset_seconds = ?,
2315
+ due_offset_seconds = ?,
2316
+ scheduled_start_offset_seconds = ?,
2317
+ scheduled_end_offset_seconds = ?,
2318
+ all_day = ?,
2319
+ estimate_seconds = ?,
2320
+ archived_at = ?,
2321
+ updated_at = ?
2322
+ WHERE id = ? AND deleted_at IS NULL`
2323
+ ).run(
2324
+ input.questlineId === void 0 ? current.questlineId : input.questlineId,
2325
+ input.title == null ? current.title : assertNonEmpty(input.title, "Repeatable quest title"),
2326
+ input.objective == null ? current.objective : assertNonEmpty(input.objective, "Repeatable quest objective"),
2327
+ rrule,
2328
+ input.anchorAt ?? current.anchorAt,
2329
+ input.notBeforeOffsetSeconds === void 0 ? current.notBeforeOffsetSeconds : assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
2330
+ input.dueOffsetSeconds === void 0 ? current.dueOffsetSeconds : assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
2331
+ input.scheduledStartOffsetSeconds === void 0 ? current.scheduledStartOffsetSeconds : input.scheduledStartOffsetSeconds,
2332
+ input.scheduledEndOffsetSeconds === void 0 ? current.scheduledEndOffsetSeconds : input.scheduledEndOffsetSeconds,
2333
+ input.allDay === void 0 ? current.allDay ? 1 : 0 : input.allDay ? 1 : 0,
2334
+ input.estimateSeconds === void 0 ? current.estimateSeconds : assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
2335
+ input.archivedAt === void 0 ? current.archivedAt : input.archivedAt,
2336
+ now,
2337
+ repeatableQuestId
2338
+ );
2339
+ return getRepeatableQuestOrThrow(db, repeatableQuestId);
2340
+ });
2341
+ }
2342
+
2343
+ // src/repeatable_quests/archive_repeatable_quest.ts
2344
+ function archiveRepeatableQuest(db, repeatableQuestId, archivedAt) {
2345
+ return updateRepeatableQuest(db, repeatableQuestId, { archivedAt: resolveNow(archivedAt) });
2346
+ }
2347
+
2348
+ // src/assert_active_row_exists.ts
2349
+ function assertActiveRowExists(db, table, id, label) {
2350
+ const row = db.prepare(`SELECT id FROM ${table} WHERE id = ? AND deleted_at IS NULL`).get(id);
2351
+ if (!row) {
2352
+ throw new Error(`${label} ${id} was not found.`);
2353
+ }
2354
+ }
2355
+
2356
+ // src/assert_non_negative_number.ts
2357
+ function assertNonNegativeNumber(value, label) {
2358
+ if (value != null && value < 0) {
2359
+ throw new Error(`${label} must not be negative.`);
2360
+ }
2361
+ return value;
2362
+ }
2363
+
2364
+ // src/rewards/replace_active_repeatable_quest_rewards.ts
2365
+ function replaceActiveRepeatableQuestRewards(db, repeatableQuestId, rewards, now) {
2366
+ const effectiveNow = resolveNow(now);
2367
+ db.prepare(
2368
+ "UPDATE repeatable_quest_rewards SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
2369
+ ).run(effectiveNow, repeatableQuestId);
2370
+ for (const reward of rewards) {
2371
+ db.prepare(
2372
+ `INSERT INTO repeatable_quest_rewards (
2373
+ repeatable_quest_id,
2374
+ kind,
2375
+ name,
2376
+ description,
2377
+ quantity,
2378
+ created_at
2379
+ ) VALUES (?, ?, ?, ?, ?, ?)`
2380
+ ).run(
2381
+ repeatableQuestId,
2382
+ assertNonEmpty(reward.kind, "Reward kind"),
2383
+ assertNonEmpty(reward.name, "Reward name"),
2384
+ reward.description?.trim() || null,
2385
+ assertNonNegativeNumber(reward.quantity, "Reward quantity") ?? null,
2386
+ effectiveNow
2387
+ );
2388
+ }
2389
+ }
2390
+
2391
+ // src/tags/replace_active_repeatable_quest_tags.ts
2392
+ function getOrCreateTagId(db, name, now) {
2393
+ const normalizedName = normalizeTagName(name);
2394
+ if (!normalizedName) {
2395
+ throw new Error("Tag name must not be empty.");
2396
+ }
2397
+ const existing = db.prepare("SELECT id FROM tags WHERE normalized_name = ? AND deleted_at IS NULL").get(normalizedName);
2398
+ if (existing) {
2399
+ return Number(existing.id);
2400
+ }
2401
+ const created = db.prepare(
2402
+ `INSERT INTO tags (name, normalized_name, created_at)
2403
+ VALUES (?, ?, ?)`
2404
+ ).run(name.trim(), normalizedName, now);
2405
+ return Number(created.lastInsertRowid);
2406
+ }
2407
+ function replaceActiveRepeatableQuestTags(db, repeatableQuestId, tagNames, now) {
2408
+ const effectiveNow = resolveNow(now);
2409
+ db.prepare(
2410
+ "UPDATE repeatable_quest_tags SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
2411
+ ).run(effectiveNow, repeatableQuestId);
2412
+ const uniqueNames = [...new Set(tagNames.map((tag) => tag.trim()).filter(Boolean))];
2413
+ for (const name of uniqueNames) {
2414
+ const tagId = getOrCreateTagId(db, name, effectiveNow);
2415
+ db.prepare(
2416
+ `INSERT INTO repeatable_quest_tags (repeatable_quest_id, tag_id, created_at)
2417
+ VALUES (?, ?, ?)`
2418
+ ).run(repeatableQuestId, tagId, effectiveNow);
2419
+ }
2420
+ }
2421
+
2422
+ // src/repeatable_quests/create_repeatable_quest.ts
2423
+ function createRepeatableQuest(db, input) {
2424
+ return withTransaction(db, () => {
2425
+ const now = resolveNow(input.now);
2426
+ const title = assertNonEmpty(input.title, "Repeatable quest title");
2427
+ const objective = assertNonEmpty(input.objective, "Repeatable quest objective");
2428
+ parseRRule(input.rrule);
2429
+ if (input.questlineId != null) {
2430
+ assertActiveRowExists(db, "questlines", input.questlineId, "Questline");
2431
+ }
2432
+ const created = db.prepare(
2433
+ `INSERT INTO repeatable_quests (
2434
+ questline_id,
2435
+ title,
2436
+ objective,
2437
+ rrule,
2438
+ anchor_at,
2439
+ not_before_offset_seconds,
2440
+ due_offset_seconds,
2441
+ scheduled_start_offset_seconds,
2442
+ scheduled_end_offset_seconds,
2443
+ all_day,
2444
+ estimate_seconds,
2445
+ created_at,
2446
+ updated_at
2447
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
2448
+ ).run(
2449
+ input.questlineId ?? null,
2450
+ title,
2451
+ objective,
2452
+ input.rrule,
2453
+ input.anchorAt,
2454
+ assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
2455
+ assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
2456
+ input.scheduledStartOffsetSeconds ?? null,
2457
+ input.scheduledEndOffsetSeconds ?? null,
2458
+ input.allDay ? 1 : 0,
2459
+ assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
2460
+ now,
2461
+ now
2462
+ );
2463
+ const repeatableQuestId = Number(created.lastInsertRowid);
2464
+ if (input.tags && input.tags.length > 0) {
2465
+ replaceActiveRepeatableQuestTags(db, repeatableQuestId, input.tags, now);
2466
+ }
2467
+ if (input.rewards && input.rewards.length > 0) {
2468
+ replaceActiveRepeatableQuestRewards(db, repeatableQuestId, input.rewards, now);
2469
+ }
2470
+ return getRepeatableQuestOrThrow(db, repeatableQuestId);
2471
+ });
2472
+ }
2473
+
2474
+ // src/repeatable_quests/soft_delete_repeatable_quest.ts
2475
+ function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
2476
+ const now = resolveNow(deletedAt);
2477
+ getRepeatableQuestOrThrow(db, repeatableQuestId);
2478
+ db.prepare(
2479
+ `UPDATE repeatable_quests
2480
+ SET deleted_at = ?, updated_at = ?
2481
+ WHERE id = ? AND deleted_at IS NULL`
2482
+ ).run(now, now, repeatableQuestId);
2483
+ }
2484
+
2109
2485
  // src/tools/manage_repeatable_tool.ts
2110
2486
  function manageRepeatableToolHandler(db, input) {
2111
2487
  try {
@@ -3325,7 +3701,7 @@ function validateReviewInput(input) {
3325
3701
  'Use `filters.dayAt` only with `view: "quests.scheduled_for_day"`.'
3326
3702
  );
3327
3703
  }
3328
- if ((input.view === "rumors" || input.view === "questlines") && hasQuestFilters(input.filters)) {
3704
+ if ((input.view === "rumors" || input.view === "questlines" || input.view === "deliveries") && hasQuestFilters(input.filters)) {
3329
3705
  return toolFailure(
3330
3706
  "protocol",
3331
3707
  "invalid_input",
@@ -3393,6 +3769,15 @@ function reviewQuestlogToolHandler(db, input) {
3393
3769
  if (invalid) {
3394
3770
  return invalid;
3395
3771
  }
3772
+ if (input.view === "deliveries")
3773
+ return toolSuccess("Pending and failed deliveries.", {
3774
+ view: input.view,
3775
+ items: [],
3776
+ deliveries: listDeliveries(db),
3777
+ count: listDeliveries(db).length,
3778
+ appliedFilters: input.filters,
3779
+ evaluatedAt: input.now ?? Date.now()
3780
+ });
3396
3781
  const now = input.now ?? Date.now();
3397
3782
  let items = [];
3398
3783
  switch (input.view) {
@@ -3452,6 +3837,7 @@ var reviewQuestlogTool = defineQuestlogTool({
3452
3837
  inputSchema: objectSchema(
3453
3838
  {
3454
3839
  view: enumSchema("Which operational review surface to return.", [
3840
+ "deliveries",
3455
3841
  "questlines",
3456
3842
  "quests.active",
3457
3843
  "quests.available",
@@ -4814,6 +5200,7 @@ var tagWorkTool = defineQuestlogTool({
4814
5200
 
4815
5201
  // src/tools/tool_registry.ts
4816
5202
  var questlogTools = [
5203
+ manageHooksTool,
4817
5204
  searchQuestlogTool,
4818
5205
  reviewQuestlogTool,
4819
5206
  inspectQuestlogItemTool,