@ghostpaw/questlog 0.9.2 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -2
- package/SKILL.md +27 -3
- package/dist/{chunk-UTUQPSGO.js → chunk-55JAQORX.js} +66 -588
- package/dist/{chunk-6KTQK3ZE.js → chunk-D2W5MYNO.js} +8 -0
- package/dist/chunk-GVD6A3RR.js +108 -0
- package/dist/{chunk-DKH623HU.js → chunk-IL2QRKZL.js} +1 -4
- package/dist/chunk-N7V7VUI5.js +982 -0
- package/dist/{chunk-3B6FMHZU.js → chunk-ZHTX64KD.js} +24 -0
- package/dist/cli.js +1 -1
- package/dist/{cli_main-XNZP4TY2.js → cli_main-7AIEZV75.js} +80 -118
- package/dist/index.cjs +1135 -627
- package/dist/index.d.cts +142 -11
- package/dist/index.d.ts +142 -11
- package/dist/index.js +1135 -628
- package/dist/mcp-server.js +821 -387
- package/dist/mcp.cjs +691 -321
- package/dist/mcp.js +692 -322
- package/dist/open_questlog_db-LAEH7UDM.js +2 -0
- package/dist/{questlog_skill_spec-EM6DGGVN.js → questlog_skill_spec-HEW2B6EB.js} +5 -3
- package/dist/run_hook_command-C42BQC36.js +95 -0
- package/dist/{serve_questlog_mcp-KFUYJB2P.js → serve_questlog_mcp-W3R63HW4.js} +4 -3
- package/package.json +1 -1
- package/skills/questlog/SKILL.md +27 -3
- package/skills/questlog/references/webhooks.md +91 -0
- package/dist/open_questlog_db-SH3DAU4C.js +0 -2
package/dist/mcp.js
CHANGED
|
@@ -1,9 +1,33 @@
|
|
|
1
1
|
import { mkdirSync } from 'node:fs';
|
|
2
|
-
import { dirname, join } from 'node:path';
|
|
2
|
+
import { basename, extname, dirname, join } from 'node:path';
|
|
3
|
+
import { randomBytes, createHmac } from 'node:crypto';
|
|
3
4
|
import { homedir } from 'node:os';
|
|
4
5
|
|
|
5
6
|
// src/surface/open_questlog_db.ts
|
|
6
7
|
|
|
8
|
+
// src/hooks/init_hook_tables.ts
|
|
9
|
+
function initHookTables(db) {
|
|
10
|
+
db.exec(`
|
|
11
|
+
CREATE TABLE IF NOT EXISTS hook_targets (
|
|
12
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, secret TEXT NOT NULL,
|
|
13
|
+
tag TEXT, events TEXT NOT NULL, min_gap INTEGER NOT NULL, created_at INTEGER NOT NULL,
|
|
14
|
+
last_wake INTEGER, lease_until INTEGER, claim TEXT);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS hook_events (
|
|
16
|
+
id TEXT PRIMARY KEY, occurred_at INTEGER NOT NULL, event TEXT NOT NULL);
|
|
17
|
+
CREATE TABLE IF NOT EXISTS hook_assignments (
|
|
18
|
+
target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
|
|
19
|
+
event_id TEXT NOT NULL REFERENCES hook_events(id), delivery_id TEXT,
|
|
20
|
+
PRIMARY KEY(target_id, event_id));
|
|
21
|
+
CREATE TABLE IF NOT EXISTS hook_deliveries (
|
|
22
|
+
id TEXT PRIMARY KEY, target_id INTEGER NOT NULL REFERENCES hook_targets(id) ON DELETE CASCADE,
|
|
23
|
+
events TEXT NOT NULL, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
|
|
24
|
+
last_attempt_at INTEGER, http_status INTEGER, error_class TEXT,
|
|
25
|
+
next_attempt_at INTEGER NOT NULL);
|
|
26
|
+
CREATE INDEX IF NOT EXISTS idx_hook_deliveries_target ON hook_deliveries(target_id, status, next_attempt_at);
|
|
27
|
+
CREATE TABLE IF NOT EXISTS hook_settings (id INTEGER PRIMARY KEY CHECK(id = 1), label TEXT NOT NULL);
|
|
28
|
+
`);
|
|
29
|
+
}
|
|
30
|
+
|
|
7
31
|
// src/questlines/init_questline_tables.ts
|
|
8
32
|
function initQuestlineTables(db) {
|
|
9
33
|
db.exec(`
|
|
@@ -352,6 +376,7 @@ function initQuestlogTables(db) {
|
|
|
352
376
|
initTagTables(db);
|
|
353
377
|
initQuestSearch(db);
|
|
354
378
|
initRumorSearch(db);
|
|
379
|
+
initHookTables(db);
|
|
355
380
|
}
|
|
356
381
|
|
|
357
382
|
// src/surface/open_questlog_db.ts
|
|
@@ -384,7 +409,7 @@ async function openQuestlogDb(path) {
|
|
|
384
409
|
}
|
|
385
410
|
|
|
386
411
|
// src/version.ts
|
|
387
|
-
var questlogVersion = "0.
|
|
412
|
+
var questlogVersion = "0.10.1";
|
|
388
413
|
|
|
389
414
|
// src/surface/questlog_mcp_instructions.ts
|
|
390
415
|
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.";
|
|
@@ -729,6 +754,7 @@ function validateInput(schema, input, path = "$") {
|
|
|
729
754
|
|
|
730
755
|
// src/tools/action_requirements.ts
|
|
731
756
|
var actionRequirements = {
|
|
757
|
+
manage_hooks: { remove: ["id"] },
|
|
732
758
|
shape_work: {
|
|
733
759
|
create_quest: ["quest"],
|
|
734
760
|
create_questline: ["questline"],
|
|
@@ -1020,6 +1046,27 @@ var captureRumorTool = defineQuestlogTool({
|
|
|
1020
1046
|
handler: captureRumorToolHandler
|
|
1021
1047
|
});
|
|
1022
1048
|
|
|
1049
|
+
// src/hooks/list_deliveries.ts
|
|
1050
|
+
function listDeliveries(db, options = {}) {
|
|
1051
|
+
return db.prepare(
|
|
1052
|
+
`SELECT * FROM hook_deliveries ${options.includeDelivered ? "" : "WHERE status <> 'delivered'"} ORDER BY target_id, next_attempt_at, id`
|
|
1053
|
+
).all().map(
|
|
1054
|
+
(row) => ({
|
|
1055
|
+
id: String(row.id),
|
|
1056
|
+
targetId: Number(row.target_id),
|
|
1057
|
+
events: JSON.parse(String(row.events)),
|
|
1058
|
+
status: row.status,
|
|
1059
|
+
attempts: Number(row.attempts),
|
|
1060
|
+
lastAttemptAt: row.last_attempt_at == null ? null : Number(row.last_attempt_at),
|
|
1061
|
+
httpStatus: row.http_status == null ? null : Number(row.http_status),
|
|
1062
|
+
errorClass: row.error_class == null ? null : String(row.error_class),
|
|
1063
|
+
nextAttemptAt: Number(row.next_attempt_at)
|
|
1064
|
+
})
|
|
1065
|
+
).filter(
|
|
1066
|
+
(d) => options.questId === void 0 || d.events.some((e) => e.questId === options.questId)
|
|
1067
|
+
);
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1023
1070
|
// src/questlines/map_questline_row.ts
|
|
1024
1071
|
function mapQuestlineRow(row) {
|
|
1025
1072
|
return {
|
|
@@ -1497,7 +1544,8 @@ function inspectQuestlogItemToolHandler(db, input) {
|
|
|
1497
1544
|
detail: detailLevel === "full" ? detail : toQuestCompactDetail(detail)
|
|
1498
1545
|
},
|
|
1499
1546
|
related,
|
|
1500
|
-
detailLevel
|
|
1547
|
+
detailLevel,
|
|
1548
|
+
deliveries: listDeliveries(db, { questId: detail.id })
|
|
1501
1549
|
},
|
|
1502
1550
|
{ entities }
|
|
1503
1551
|
);
|
|
@@ -1602,13 +1650,39 @@ var inspectQuestlogItemTool = defineQuestlogTool({
|
|
|
1602
1650
|
),
|
|
1603
1651
|
handler: inspectQuestlogItemToolHandler
|
|
1604
1652
|
});
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
return
|
|
1653
|
+
function hookLabel(db, name) {
|
|
1654
|
+
const saved = db.prepare("SELECT label FROM hook_settings WHERE id = 1").get();
|
|
1655
|
+
if (saved) return String(saved.label);
|
|
1656
|
+
const path = String(
|
|
1657
|
+
db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? ""
|
|
1658
|
+
);
|
|
1659
|
+
return path ? basename(path, extname(path)) : "questlog";
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
// src/hooks/list_hooks.ts
|
|
1663
|
+
function listHooks(db) {
|
|
1664
|
+
return db.prepare(`SELECT id, url, tag, events, min_gap, created_at, last_wake,
|
|
1665
|
+
(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,
|
|
1666
|
+
(SELECT COUNT(*) FROM hook_deliveries d WHERE d.target_id = t.id AND d.status = 'failed') AS failed
|
|
1667
|
+
FROM hook_targets t ORDER BY id`).all().map((row) => {
|
|
1668
|
+
const url = new URL(String(row.url));
|
|
1669
|
+
url.username = "";
|
|
1670
|
+
url.password = "";
|
|
1671
|
+
url.search = "";
|
|
1672
|
+
url.hash = "";
|
|
1673
|
+
return {
|
|
1674
|
+
id: Number(row.id),
|
|
1675
|
+
scope: row.tag == null ? "database" : "tag",
|
|
1676
|
+
url: url.href,
|
|
1677
|
+
tag: row.tag == null ? null : String(row.tag),
|
|
1678
|
+
events: JSON.parse(String(row.events)),
|
|
1679
|
+
minGap: Number(row.min_gap),
|
|
1680
|
+
createdAt: Number(row.created_at),
|
|
1681
|
+
lastWake: row.last_wake == null ? null : Number(row.last_wake),
|
|
1682
|
+
pending: Number(row.pending),
|
|
1683
|
+
failed: Number(row.failed)
|
|
1684
|
+
};
|
|
1685
|
+
});
|
|
1612
1686
|
}
|
|
1613
1687
|
|
|
1614
1688
|
// src/with_transaction.ts
|
|
@@ -1646,6 +1720,135 @@ function withTransaction(db, fn) {
|
|
|
1646
1720
|
}
|
|
1647
1721
|
}
|
|
1648
1722
|
|
|
1723
|
+
// src/hooks/remove_hook.ts
|
|
1724
|
+
function removeHook(db, id) {
|
|
1725
|
+
withTransaction(db, () => {
|
|
1726
|
+
db.prepare("DELETE FROM hook_assignments WHERE target_id = ?").run(id);
|
|
1727
|
+
db.prepare("DELETE FROM hook_deliveries WHERE target_id = ?").run(id);
|
|
1728
|
+
db.prepare("DELETE FROM hook_targets WHERE id = ?").run(id);
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
async function sendHookDelivery(db, delivery, target, options) {
|
|
1732
|
+
const now = options.now ?? options.clock?.() ?? Date.now();
|
|
1733
|
+
const timestamp = String(Math.floor(now / 1e3));
|
|
1734
|
+
const body = JSON.stringify({
|
|
1735
|
+
type: "questlog.events",
|
|
1736
|
+
db: hookLabel(db),
|
|
1737
|
+
deliveryId: delivery.id,
|
|
1738
|
+
sentAt: new Date(now).toISOString(),
|
|
1739
|
+
events: delivery.events
|
|
1740
|
+
});
|
|
1741
|
+
const signature = createHmac("sha256", target.secret).update(`${timestamp}.${body}`).digest("hex");
|
|
1742
|
+
let status = null;
|
|
1743
|
+
let errorClass = null;
|
|
1744
|
+
try {
|
|
1745
|
+
const response = await (options.fetch ?? globalThis.fetch)(target.url, {
|
|
1746
|
+
method: "POST",
|
|
1747
|
+
redirect: "error",
|
|
1748
|
+
headers: {
|
|
1749
|
+
"content-type": "application/json",
|
|
1750
|
+
"user-agent": `questlog/${questlogVersion}`,
|
|
1751
|
+
"x-questlog-delivery": delivery.id,
|
|
1752
|
+
"x-questlog-timestamp": timestamp,
|
|
1753
|
+
"x-questlog-signature": `sha256=${signature}`
|
|
1754
|
+
},
|
|
1755
|
+
body,
|
|
1756
|
+
signal: AbortSignal.timeout(Math.max(1, Math.min(options.timeoutMs ?? 5e3, 5e3)))
|
|
1757
|
+
});
|
|
1758
|
+
status = response.status;
|
|
1759
|
+
await response.body?.cancel();
|
|
1760
|
+
} catch (error) {
|
|
1761
|
+
errorClass = error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name) ? error.name : "NetworkError";
|
|
1762
|
+
}
|
|
1763
|
+
const delivered = status != null && status >= 200 && status < 300;
|
|
1764
|
+
const completedAt = options.now ?? options.clock?.() ?? Date.now();
|
|
1765
|
+
withTransaction(db, () => {
|
|
1766
|
+
if (!db.prepare("SELECT id FROM hook_targets WHERE id = ? AND claim = ?").get(target.id, target.claim))
|
|
1767
|
+
return;
|
|
1768
|
+
const delay = Math.min(36e5, 3e4 * 2 ** (delivery.attempts - 1));
|
|
1769
|
+
const jitter = Number.parseInt(randomBytes(2).toString("hex"), 16) % 1e3;
|
|
1770
|
+
db.prepare(
|
|
1771
|
+
"UPDATE hook_deliveries SET status = ?, http_status = ?, error_class = ?, next_attempt_at = ? WHERE id = ?"
|
|
1772
|
+
).run(
|
|
1773
|
+
delivered ? "delivered" : delivery.attempts >= 8 ? "failed" : "pending",
|
|
1774
|
+
status,
|
|
1775
|
+
errorClass,
|
|
1776
|
+
completedAt + delay + jitter,
|
|
1777
|
+
delivery.id
|
|
1778
|
+
);
|
|
1779
|
+
db.prepare(
|
|
1780
|
+
"UPDATE hook_targets SET claim = NULL, lease_until = NULL WHERE id = ? AND claim = ?"
|
|
1781
|
+
).run(target.id, target.claim);
|
|
1782
|
+
db.prepare(
|
|
1783
|
+
"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)"
|
|
1784
|
+
).run(target.id, target.id);
|
|
1785
|
+
});
|
|
1786
|
+
return delivered;
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
// src/quests/get_quest_or_throw.ts
|
|
1790
|
+
function getQuestOrThrow(db, questId) {
|
|
1791
|
+
const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
|
|
1792
|
+
if (!row) {
|
|
1793
|
+
throw new Error(`Quest ${questId} was not found.`);
|
|
1794
|
+
}
|
|
1795
|
+
return mapQuestRow(row);
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
// src/rewards/copy_repeatable_quest_rewards_to_quest.ts
|
|
1799
|
+
function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
|
|
1800
|
+
const effectiveNow = resolveNow(now);
|
|
1801
|
+
const rows = db.prepare(
|
|
1802
|
+
`SELECT kind, name, description, quantity
|
|
1803
|
+
FROM repeatable_quest_rewards
|
|
1804
|
+
WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
|
|
1805
|
+
).all(repeatableQuestId);
|
|
1806
|
+
for (const row of rows) {
|
|
1807
|
+
db.prepare(
|
|
1808
|
+
`INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
|
|
1809
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
1810
|
+
).run(
|
|
1811
|
+
questId,
|
|
1812
|
+
String(row.kind),
|
|
1813
|
+
String(row.name),
|
|
1814
|
+
row.description == null ? null : String(row.description),
|
|
1815
|
+
row.quantity == null ? null : Number(row.quantity),
|
|
1816
|
+
effectiveNow
|
|
1817
|
+
);
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// src/tags/copy_repeatable_quest_tags_to_quest.ts
|
|
1822
|
+
function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
|
|
1823
|
+
const effectiveNow = resolveNow(now);
|
|
1824
|
+
const rows = db.prepare(
|
|
1825
|
+
`SELECT tag_id
|
|
1826
|
+
FROM repeatable_quest_tags
|
|
1827
|
+
WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
|
|
1828
|
+
).all(repeatableQuestId);
|
|
1829
|
+
for (const row of rows) {
|
|
1830
|
+
db.prepare(
|
|
1831
|
+
`INSERT INTO quest_tags (quest_id, tag_id, created_at)
|
|
1832
|
+
VALUES (?, ?, ?)`
|
|
1833
|
+
).run(questId, Number(row.tag_id), effectiveNow);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
// src/repeatable_quests/advance_anchor.ts
|
|
1838
|
+
var WEEK_MS = 7 * 864e5;
|
|
1839
|
+
function advanceAnchor(anchorAt, freq, interval) {
|
|
1840
|
+
const date = new Date(anchorAt);
|
|
1841
|
+
if (freq === "MONTHLY") {
|
|
1842
|
+
date.setUTCMonth(date.getUTCMonth() + interval);
|
|
1843
|
+
return date.getTime();
|
|
1844
|
+
}
|
|
1845
|
+
if (freq === "YEARLY") {
|
|
1846
|
+
date.setUTCFullYear(date.getUTCFullYear() + interval);
|
|
1847
|
+
return date.getTime();
|
|
1848
|
+
}
|
|
1849
|
+
return anchorAt + interval * WEEK_MS;
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1649
1852
|
// src/repeatable_quests/parse_rrule.ts
|
|
1650
1853
|
var WEEKDAY = {
|
|
1651
1854
|
SU: 0,
|
|
@@ -1689,265 +1892,76 @@ function parseRRule(rrule) {
|
|
|
1689
1892
|
return { freq, interval, count, until, byDay };
|
|
1690
1893
|
}
|
|
1691
1894
|
|
|
1692
|
-
// src/repeatable_quests/
|
|
1693
|
-
function
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
const now = resolveNow(input.now);
|
|
1697
|
-
const rrule = input.rrule ?? current.rrule;
|
|
1698
|
-
parseRRule(rrule);
|
|
1699
|
-
db.prepare(
|
|
1700
|
-
`UPDATE repeatable_quests
|
|
1701
|
-
SET questline_id = ?,
|
|
1702
|
-
title = ?,
|
|
1703
|
-
objective = ?,
|
|
1704
|
-
rrule = ?,
|
|
1705
|
-
anchor_at = ?,
|
|
1706
|
-
not_before_offset_seconds = ?,
|
|
1707
|
-
due_offset_seconds = ?,
|
|
1708
|
-
scheduled_start_offset_seconds = ?,
|
|
1709
|
-
scheduled_end_offset_seconds = ?,
|
|
1710
|
-
all_day = ?,
|
|
1711
|
-
estimate_seconds = ?,
|
|
1712
|
-
archived_at = ?,
|
|
1713
|
-
updated_at = ?
|
|
1714
|
-
WHERE id = ? AND deleted_at IS NULL`
|
|
1715
|
-
).run(
|
|
1716
|
-
input.questlineId === void 0 ? current.questlineId : input.questlineId,
|
|
1717
|
-
input.title == null ? current.title : assertNonEmpty(input.title, "Repeatable quest title"),
|
|
1718
|
-
input.objective == null ? current.objective : assertNonEmpty(input.objective, "Repeatable quest objective"),
|
|
1719
|
-
rrule,
|
|
1720
|
-
input.anchorAt ?? current.anchorAt,
|
|
1721
|
-
input.notBeforeOffsetSeconds === void 0 ? current.notBeforeOffsetSeconds : assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
|
|
1722
|
-
input.dueOffsetSeconds === void 0 ? current.dueOffsetSeconds : assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
|
|
1723
|
-
input.scheduledStartOffsetSeconds === void 0 ? current.scheduledStartOffsetSeconds : input.scheduledStartOffsetSeconds,
|
|
1724
|
-
input.scheduledEndOffsetSeconds === void 0 ? current.scheduledEndOffsetSeconds : input.scheduledEndOffsetSeconds,
|
|
1725
|
-
input.allDay === void 0 ? current.allDay ? 1 : 0 : input.allDay ? 1 : 0,
|
|
1726
|
-
input.estimateSeconds === void 0 ? current.estimateSeconds : assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
|
|
1727
|
-
input.archivedAt === void 0 ? current.archivedAt : input.archivedAt,
|
|
1728
|
-
now,
|
|
1729
|
-
repeatableQuestId
|
|
1730
|
-
);
|
|
1731
|
-
return getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
1732
|
-
});
|
|
1895
|
+
// src/repeatable_quests/start_of_utc_day.ts
|
|
1896
|
+
function startOfUtcDay(timestamp) {
|
|
1897
|
+
const date = new Date(timestamp);
|
|
1898
|
+
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
|
|
1733
1899
|
}
|
|
1734
1900
|
|
|
1735
|
-
// src/repeatable_quests/
|
|
1736
|
-
|
|
1737
|
-
|
|
1901
|
+
// src/repeatable_quests/start_of_utc_week.ts
|
|
1902
|
+
var DAY_MS = 864e5;
|
|
1903
|
+
function startOfUtcWeek(dayStart) {
|
|
1904
|
+
const date = new Date(dayStart);
|
|
1905
|
+
return dayStart - date.getUTCDay() * DAY_MS;
|
|
1738
1906
|
}
|
|
1739
1907
|
|
|
1740
|
-
// src/
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1908
|
+
// src/repeatable_quests/generate_anchors_until.ts
|
|
1909
|
+
var DAY_MS2 = 864e5;
|
|
1910
|
+
var WEEK_MS2 = 7 * DAY_MS2;
|
|
1911
|
+
function generateAnchorsUntil(repeatable, now) {
|
|
1912
|
+
const rule = parseRRule(repeatable.rrule);
|
|
1913
|
+
const anchors = [];
|
|
1914
|
+
const until = rule.until == null ? now : Math.min(now, rule.until);
|
|
1915
|
+
if (repeatable.anchorAt > until) {
|
|
1916
|
+
return anchors;
|
|
1745
1917
|
}
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1918
|
+
if (rule.freq === "DAILY") {
|
|
1919
|
+
let occurrence2 = 0;
|
|
1920
|
+
for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
|
|
1921
|
+
occurrence2 += 1;
|
|
1922
|
+
if (rule.count != null && occurrence2 > rule.count) {
|
|
1923
|
+
break;
|
|
1924
|
+
}
|
|
1925
|
+
anchors.push(current2);
|
|
1926
|
+
}
|
|
1927
|
+
return anchors;
|
|
1752
1928
|
}
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1929
|
+
if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
|
|
1930
|
+
const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
|
|
1931
|
+
const anchorWeekStart = startOfUtcWeek(anchorDayStart);
|
|
1932
|
+
const timeOffset = repeatable.anchorAt - anchorDayStart;
|
|
1933
|
+
let occurrence2 = 0;
|
|
1934
|
+
for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
|
|
1935
|
+
const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
|
|
1936
|
+
if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
|
|
1937
|
+
continue;
|
|
1938
|
+
}
|
|
1939
|
+
if (!rule.byDay.includes(new Date(day).getUTCDay())) {
|
|
1940
|
+
continue;
|
|
1941
|
+
}
|
|
1942
|
+
const anchor = day + timeOffset;
|
|
1943
|
+
if (anchor < repeatable.anchorAt || anchor > until) {
|
|
1944
|
+
continue;
|
|
1945
|
+
}
|
|
1946
|
+
occurrence2 += 1;
|
|
1947
|
+
if (rule.count != null && occurrence2 > rule.count) {
|
|
1948
|
+
break;
|
|
1949
|
+
}
|
|
1950
|
+
anchors.push(anchor);
|
|
1951
|
+
}
|
|
1952
|
+
return anchors;
|
|
1953
|
+
}
|
|
1954
|
+
let occurrence = 0;
|
|
1955
|
+
let current = repeatable.anchorAt;
|
|
1956
|
+
while (current <= until) {
|
|
1957
|
+
occurrence += 1;
|
|
1958
|
+
if (rule.count != null && occurrence > rule.count) {
|
|
1959
|
+
break;
|
|
1960
|
+
}
|
|
1961
|
+
anchors.push(current);
|
|
1962
|
+
current = advanceAnchor(current, rule.freq, rule.interval);
|
|
1780
1963
|
}
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
// src/tags/replace_active_repeatable_quest_tags.ts
|
|
1784
|
-
function getOrCreateTagId(db, name, now) {
|
|
1785
|
-
const normalizedName = normalizeTagName(name);
|
|
1786
|
-
if (!normalizedName) {
|
|
1787
|
-
throw new Error("Tag name must not be empty.");
|
|
1788
|
-
}
|
|
1789
|
-
const existing = db.prepare("SELECT id FROM tags WHERE normalized_name = ? AND deleted_at IS NULL").get(normalizedName);
|
|
1790
|
-
if (existing) {
|
|
1791
|
-
return Number(existing.id);
|
|
1792
|
-
}
|
|
1793
|
-
const created = db.prepare(
|
|
1794
|
-
`INSERT INTO tags (name, normalized_name, created_at)
|
|
1795
|
-
VALUES (?, ?, ?)`
|
|
1796
|
-
).run(name.trim(), normalizedName, now);
|
|
1797
|
-
return Number(created.lastInsertRowid);
|
|
1798
|
-
}
|
|
1799
|
-
function replaceActiveRepeatableQuestTags(db, repeatableQuestId, tagNames, now) {
|
|
1800
|
-
const effectiveNow = resolveNow(now);
|
|
1801
|
-
db.prepare(
|
|
1802
|
-
"UPDATE repeatable_quest_tags SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
|
|
1803
|
-
).run(effectiveNow, repeatableQuestId);
|
|
1804
|
-
const uniqueNames = [...new Set(tagNames.map((tag) => tag.trim()).filter(Boolean))];
|
|
1805
|
-
for (const name of uniqueNames) {
|
|
1806
|
-
const tagId = getOrCreateTagId(db, name, effectiveNow);
|
|
1807
|
-
db.prepare(
|
|
1808
|
-
`INSERT INTO repeatable_quest_tags (repeatable_quest_id, tag_id, created_at)
|
|
1809
|
-
VALUES (?, ?, ?)`
|
|
1810
|
-
).run(repeatableQuestId, tagId, effectiveNow);
|
|
1811
|
-
}
|
|
1812
|
-
}
|
|
1813
|
-
|
|
1814
|
-
// src/repeatable_quests/create_repeatable_quest.ts
|
|
1815
|
-
function createRepeatableQuest(db, input) {
|
|
1816
|
-
return withTransaction(db, () => {
|
|
1817
|
-
const now = resolveNow(input.now);
|
|
1818
|
-
const title = assertNonEmpty(input.title, "Repeatable quest title");
|
|
1819
|
-
const objective = assertNonEmpty(input.objective, "Repeatable quest objective");
|
|
1820
|
-
parseRRule(input.rrule);
|
|
1821
|
-
if (input.questlineId != null) {
|
|
1822
|
-
assertActiveRowExists(db, "questlines", input.questlineId, "Questline");
|
|
1823
|
-
}
|
|
1824
|
-
const created = db.prepare(
|
|
1825
|
-
`INSERT INTO repeatable_quests (
|
|
1826
|
-
questline_id,
|
|
1827
|
-
title,
|
|
1828
|
-
objective,
|
|
1829
|
-
rrule,
|
|
1830
|
-
anchor_at,
|
|
1831
|
-
not_before_offset_seconds,
|
|
1832
|
-
due_offset_seconds,
|
|
1833
|
-
scheduled_start_offset_seconds,
|
|
1834
|
-
scheduled_end_offset_seconds,
|
|
1835
|
-
all_day,
|
|
1836
|
-
estimate_seconds,
|
|
1837
|
-
created_at,
|
|
1838
|
-
updated_at
|
|
1839
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
1840
|
-
).run(
|
|
1841
|
-
input.questlineId ?? null,
|
|
1842
|
-
title,
|
|
1843
|
-
objective,
|
|
1844
|
-
input.rrule,
|
|
1845
|
-
input.anchorAt,
|
|
1846
|
-
assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
|
|
1847
|
-
assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
|
|
1848
|
-
input.scheduledStartOffsetSeconds ?? null,
|
|
1849
|
-
input.scheduledEndOffsetSeconds ?? null,
|
|
1850
|
-
input.allDay ? 1 : 0,
|
|
1851
|
-
assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
|
|
1852
|
-
now,
|
|
1853
|
-
now
|
|
1854
|
-
);
|
|
1855
|
-
const repeatableQuestId = Number(created.lastInsertRowid);
|
|
1856
|
-
if (input.tags && input.tags.length > 0) {
|
|
1857
|
-
replaceActiveRepeatableQuestTags(db, repeatableQuestId, input.tags, now);
|
|
1858
|
-
}
|
|
1859
|
-
if (input.rewards && input.rewards.length > 0) {
|
|
1860
|
-
replaceActiveRepeatableQuestRewards(db, repeatableQuestId, input.rewards, now);
|
|
1861
|
-
}
|
|
1862
|
-
return getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
|
|
1866
|
-
// src/repeatable_quests/advance_anchor.ts
|
|
1867
|
-
var WEEK_MS = 7 * 864e5;
|
|
1868
|
-
function advanceAnchor(anchorAt, freq, interval) {
|
|
1869
|
-
const date = new Date(anchorAt);
|
|
1870
|
-
if (freq === "MONTHLY") {
|
|
1871
|
-
date.setUTCMonth(date.getUTCMonth() + interval);
|
|
1872
|
-
return date.getTime();
|
|
1873
|
-
}
|
|
1874
|
-
if (freq === "YEARLY") {
|
|
1875
|
-
date.setUTCFullYear(date.getUTCFullYear() + interval);
|
|
1876
|
-
return date.getTime();
|
|
1877
|
-
}
|
|
1878
|
-
return anchorAt + interval * WEEK_MS;
|
|
1879
|
-
}
|
|
1880
|
-
|
|
1881
|
-
// src/repeatable_quests/start_of_utc_day.ts
|
|
1882
|
-
function startOfUtcDay(timestamp) {
|
|
1883
|
-
const date = new Date(timestamp);
|
|
1884
|
-
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
|
|
1885
|
-
}
|
|
1886
|
-
|
|
1887
|
-
// src/repeatable_quests/start_of_utc_week.ts
|
|
1888
|
-
var DAY_MS = 864e5;
|
|
1889
|
-
function startOfUtcWeek(dayStart) {
|
|
1890
|
-
const date = new Date(dayStart);
|
|
1891
|
-
return dayStart - date.getUTCDay() * DAY_MS;
|
|
1892
|
-
}
|
|
1893
|
-
|
|
1894
|
-
// src/repeatable_quests/generate_anchors_until.ts
|
|
1895
|
-
var DAY_MS2 = 864e5;
|
|
1896
|
-
var WEEK_MS2 = 7 * DAY_MS2;
|
|
1897
|
-
function generateAnchorsUntil(repeatable, now) {
|
|
1898
|
-
const rule = parseRRule(repeatable.rrule);
|
|
1899
|
-
const anchors = [];
|
|
1900
|
-
const until = rule.until == null ? now : Math.min(now, rule.until);
|
|
1901
|
-
if (repeatable.anchorAt > until) {
|
|
1902
|
-
return anchors;
|
|
1903
|
-
}
|
|
1904
|
-
if (rule.freq === "DAILY") {
|
|
1905
|
-
let occurrence2 = 0;
|
|
1906
|
-
for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
|
|
1907
|
-
occurrence2 += 1;
|
|
1908
|
-
if (rule.count != null && occurrence2 > rule.count) {
|
|
1909
|
-
break;
|
|
1910
|
-
}
|
|
1911
|
-
anchors.push(current2);
|
|
1912
|
-
}
|
|
1913
|
-
return anchors;
|
|
1914
|
-
}
|
|
1915
|
-
if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
|
|
1916
|
-
const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
|
|
1917
|
-
const anchorWeekStart = startOfUtcWeek(anchorDayStart);
|
|
1918
|
-
const timeOffset = repeatable.anchorAt - anchorDayStart;
|
|
1919
|
-
let occurrence2 = 0;
|
|
1920
|
-
for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
|
|
1921
|
-
const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
|
|
1922
|
-
if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
|
|
1923
|
-
continue;
|
|
1924
|
-
}
|
|
1925
|
-
if (!rule.byDay.includes(new Date(day).getUTCDay())) {
|
|
1926
|
-
continue;
|
|
1927
|
-
}
|
|
1928
|
-
const anchor = day + timeOffset;
|
|
1929
|
-
if (anchor < repeatable.anchorAt || anchor > until) {
|
|
1930
|
-
continue;
|
|
1931
|
-
}
|
|
1932
|
-
occurrence2 += 1;
|
|
1933
|
-
if (rule.count != null && occurrence2 > rule.count) {
|
|
1934
|
-
break;
|
|
1935
|
-
}
|
|
1936
|
-
anchors.push(anchor);
|
|
1937
|
-
}
|
|
1938
|
-
return anchors;
|
|
1939
|
-
}
|
|
1940
|
-
let occurrence = 0;
|
|
1941
|
-
let current = repeatable.anchorAt;
|
|
1942
|
-
while (current <= until) {
|
|
1943
|
-
occurrence += 1;
|
|
1944
|
-
if (rule.count != null && occurrence > rule.count) {
|
|
1945
|
-
break;
|
|
1946
|
-
}
|
|
1947
|
-
anchors.push(current);
|
|
1948
|
-
current = advanceAnchor(current, rule.freq, rule.interval);
|
|
1949
|
-
}
|
|
1950
|
-
return anchors;
|
|
1964
|
+
return anchors;
|
|
1951
1965
|
}
|
|
1952
1966
|
|
|
1953
1967
|
// src/repeatable_quests/list_due_repeatable_quest_anchors.ts
|
|
@@ -1995,65 +2009,6 @@ function listDueRepeatableQuestAnchors(db, now) {
|
|
|
1995
2009
|
);
|
|
1996
2010
|
}
|
|
1997
2011
|
|
|
1998
|
-
// src/repeatable_quests/soft_delete_repeatable_quest.ts
|
|
1999
|
-
function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
|
|
2000
|
-
const now = resolveNow(deletedAt);
|
|
2001
|
-
getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
2002
|
-
db.prepare(
|
|
2003
|
-
`UPDATE repeatable_quests
|
|
2004
|
-
SET deleted_at = ?, updated_at = ?
|
|
2005
|
-
WHERE id = ? AND deleted_at IS NULL`
|
|
2006
|
-
).run(now, now, repeatableQuestId);
|
|
2007
|
-
}
|
|
2008
|
-
|
|
2009
|
-
// src/quests/get_quest_or_throw.ts
|
|
2010
|
-
function getQuestOrThrow(db, questId) {
|
|
2011
|
-
const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
|
|
2012
|
-
if (!row) {
|
|
2013
|
-
throw new Error(`Quest ${questId} was not found.`);
|
|
2014
|
-
}
|
|
2015
|
-
return mapQuestRow(row);
|
|
2016
|
-
}
|
|
2017
|
-
|
|
2018
|
-
// src/rewards/copy_repeatable_quest_rewards_to_quest.ts
|
|
2019
|
-
function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
|
|
2020
|
-
const effectiveNow = resolveNow(now);
|
|
2021
|
-
const rows = db.prepare(
|
|
2022
|
-
`SELECT kind, name, description, quantity
|
|
2023
|
-
FROM repeatable_quest_rewards
|
|
2024
|
-
WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
|
|
2025
|
-
).all(repeatableQuestId);
|
|
2026
|
-
for (const row of rows) {
|
|
2027
|
-
db.prepare(
|
|
2028
|
-
`INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
|
|
2029
|
-
VALUES (?, ?, ?, ?, ?, ?)`
|
|
2030
|
-
).run(
|
|
2031
|
-
questId,
|
|
2032
|
-
String(row.kind),
|
|
2033
|
-
String(row.name),
|
|
2034
|
-
row.description == null ? null : String(row.description),
|
|
2035
|
-
row.quantity == null ? null : Number(row.quantity),
|
|
2036
|
-
effectiveNow
|
|
2037
|
-
);
|
|
2038
|
-
}
|
|
2039
|
-
}
|
|
2040
|
-
|
|
2041
|
-
// src/tags/copy_repeatable_quest_tags_to_quest.ts
|
|
2042
|
-
function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
|
|
2043
|
-
const effectiveNow = resolveNow(now);
|
|
2044
|
-
const rows = db.prepare(
|
|
2045
|
-
`SELECT tag_id
|
|
2046
|
-
FROM repeatable_quest_tags
|
|
2047
|
-
WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
|
|
2048
|
-
).all(repeatableQuestId);
|
|
2049
|
-
for (const row of rows) {
|
|
2050
|
-
db.prepare(
|
|
2051
|
-
`INSERT INTO quest_tags (quest_id, tag_id, created_at)
|
|
2052
|
-
VALUES (?, ?, ?)`
|
|
2053
|
-
).run(questId, Number(row.tag_id), effectiveNow);
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
|
|
2057
2012
|
// src/repeatable_quests/spawn_due_repeatable_quests.ts
|
|
2058
2013
|
function spawnDueRepeatableQuests(db, now) {
|
|
2059
2014
|
return withTransaction(db, () => {
|
|
@@ -2104,6 +2059,410 @@ function spawnDueRepeatableQuests(db, now) {
|
|
|
2104
2059
|
});
|
|
2105
2060
|
}
|
|
2106
2061
|
|
|
2062
|
+
// src/hooks/detect_hook_events.ts
|
|
2063
|
+
function detectHookEvents(db, now) {
|
|
2064
|
+
const events = [];
|
|
2065
|
+
const add = (type, at, ids) => {
|
|
2066
|
+
events.push({
|
|
2067
|
+
id: `e_${type}_${ids.questId ?? ids.rumorId}_${ids.repeatableId ?? ""}_${at}`,
|
|
2068
|
+
type,
|
|
2069
|
+
...ids,
|
|
2070
|
+
occurredAt: new Date(at).toISOString()
|
|
2071
|
+
});
|
|
2072
|
+
};
|
|
2073
|
+
for (const { detail: q } of queryQuestDetailRecords(db, {}, now)) {
|
|
2074
|
+
if (q.resolvedAt == null && q.effectiveDueAt != null && q.effectiveDueAt <= now) {
|
|
2075
|
+
add("quest.due", q.effectiveDueAt, { questId: q.id });
|
|
2076
|
+
if (q.effectiveDueAt < now) add("quest.overdue", q.effectiveDueAt, { questId: q.id });
|
|
2077
|
+
}
|
|
2078
|
+
if (q.available) {
|
|
2079
|
+
const prerequisites = db.prepare(
|
|
2080
|
+
`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`
|
|
2081
|
+
).all(q.id);
|
|
2082
|
+
if (prerequisites.some((p) => Number(p.resolved_at) >= Number(p.created_at))) {
|
|
2083
|
+
const at = Math.max(q.notBeforeAt ?? 0, ...prerequisites.map((p) => Number(p.resolved_at)));
|
|
2084
|
+
if (at <= now) add("quest.unblocked", at, { questId: q.id });
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
if (q.spawnedFromRepeatableId != null && q.createdAt <= now)
|
|
2088
|
+
add("repeatable.spawned", q.createdAt, {
|
|
2089
|
+
questId: q.id,
|
|
2090
|
+
repeatableId: q.spawnedFromRepeatableId
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
for (const row of db.prepare("SELECT id, created_at FROM rumors WHERE deleted_at IS NULL AND created_at <= ?").all(now))
|
|
2094
|
+
add("rumor.captured", Number(row.created_at), { rumorId: Number(row.id) });
|
|
2095
|
+
return events.sort(
|
|
2096
|
+
(a, b) => a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
|
|
2097
|
+
);
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
// src/hooks/tick_questlog.ts
|
|
2101
|
+
async function tickQuestlog(db, options = {}) {
|
|
2102
|
+
const now = options.now ?? options.clock?.() ?? Date.now();
|
|
2103
|
+
const result = {
|
|
2104
|
+
events: [],
|
|
2105
|
+
batches: [],
|
|
2106
|
+
sent: 0,
|
|
2107
|
+
queued: 0,
|
|
2108
|
+
retrying: 0,
|
|
2109
|
+
failed: 0
|
|
2110
|
+
};
|
|
2111
|
+
const claims = [];
|
|
2112
|
+
const collect = () => {
|
|
2113
|
+
spawnDueRepeatableQuests(db, now);
|
|
2114
|
+
const detected = detectHookEvents(db, now);
|
|
2115
|
+
result.events = detected.filter(
|
|
2116
|
+
(e) => !db.prepare("SELECT id FROM hook_events WHERE id = ?").get(e.id)
|
|
2117
|
+
);
|
|
2118
|
+
for (const event of result.events)
|
|
2119
|
+
db.prepare("INSERT INTO hook_events(id, occurred_at, event) VALUES (?, ?, ?)").run(
|
|
2120
|
+
event.id,
|
|
2121
|
+
Date.parse(event.occurredAt),
|
|
2122
|
+
JSON.stringify(event)
|
|
2123
|
+
);
|
|
2124
|
+
for (const target of listHooks(db)) {
|
|
2125
|
+
const events = db.prepare(
|
|
2126
|
+
"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"
|
|
2127
|
+
).all(target.createdAt, target.id).map((row2) => JSON.parse(String(row2.event))).filter((event) => {
|
|
2128
|
+
if (!target.events.includes(event.type)) return false;
|
|
2129
|
+
if (target.tag == null) return true;
|
|
2130
|
+
return event.questId !== void 0 && db.prepare(
|
|
2131
|
+
"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 = ?"
|
|
2132
|
+
).get(event.questId, normalizeTagName(target.tag)) !== void 0;
|
|
2133
|
+
});
|
|
2134
|
+
for (const event of events)
|
|
2135
|
+
db.prepare("INSERT INTO hook_assignments(target_id, event_id) VALUES (?, ?)").run(
|
|
2136
|
+
target.id,
|
|
2137
|
+
event.id
|
|
2138
|
+
);
|
|
2139
|
+
const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(target.id);
|
|
2140
|
+
if (!row || row.lease_until != null && Number(row.lease_until) > now) continue;
|
|
2141
|
+
let pending = listDeliveries(db).find(
|
|
2142
|
+
(d) => d.targetId === target.id && d.status === "pending"
|
|
2143
|
+
);
|
|
2144
|
+
const queued = db.prepare(
|
|
2145
|
+
"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"
|
|
2146
|
+
).all(target.id).map((r) => JSON.parse(String(r.event)));
|
|
2147
|
+
if (!pending && queued.length) {
|
|
2148
|
+
const id = `d_${randomBytes(16).toString("hex")}`;
|
|
2149
|
+
db.prepare(
|
|
2150
|
+
"INSERT INTO hook_deliveries(id, target_id, events, status, next_attempt_at) VALUES (?, ?, ?, 'pending', ?)"
|
|
2151
|
+
).run(
|
|
2152
|
+
id,
|
|
2153
|
+
target.id,
|
|
2154
|
+
JSON.stringify(queued),
|
|
2155
|
+
Math.max(now, (target.lastWake ?? -Infinity) + target.minGap * 1e3)
|
|
2156
|
+
);
|
|
2157
|
+
db.prepare(
|
|
2158
|
+
"UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
|
|
2159
|
+
).run(id, target.id);
|
|
2160
|
+
pending = listDeliveries(db).find((d) => d.id === id);
|
|
2161
|
+
}
|
|
2162
|
+
if (!pending) continue;
|
|
2163
|
+
if (pending.attempts === 0 && queued.length && !queued.every((e) => pending?.events.some((p) => p.id === e.id))) {
|
|
2164
|
+
pending.events.push(...queued);
|
|
2165
|
+
db.prepare("UPDATE hook_deliveries SET events = ? WHERE id = ?").run(
|
|
2166
|
+
JSON.stringify(pending.events),
|
|
2167
|
+
pending.id
|
|
2168
|
+
);
|
|
2169
|
+
db.prepare(
|
|
2170
|
+
"UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
|
|
2171
|
+
).run(pending.id, target.id);
|
|
2172
|
+
}
|
|
2173
|
+
if (pending.nextAttemptAt > now || target.lastWake != null && target.lastWake + target.minGap * 1e3 > now)
|
|
2174
|
+
continue;
|
|
2175
|
+
if (pending.attempts >= 8) {
|
|
2176
|
+
db.prepare("UPDATE hook_deliveries SET status = 'failed' WHERE id = ?").run(pending.id);
|
|
2177
|
+
continue;
|
|
2178
|
+
}
|
|
2179
|
+
const claim = randomBytes(16).toString("hex");
|
|
2180
|
+
db.prepare(
|
|
2181
|
+
"UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
|
|
2182
|
+
).run(claim, now + 12e4, now, target.id);
|
|
2183
|
+
db.prepare(
|
|
2184
|
+
"UPDATE hook_deliveries SET attempts = attempts + 1, last_attempt_at = ? WHERE id = ?"
|
|
2185
|
+
).run(now, pending.id);
|
|
2186
|
+
pending.attempts++;
|
|
2187
|
+
pending.lastAttemptAt = now;
|
|
2188
|
+
result.batches.push({ targetId: target.id, events: pending.events });
|
|
2189
|
+
claims.push({
|
|
2190
|
+
delivery: pending,
|
|
2191
|
+
target: { id: target.id, url: String(row.url), secret: String(row.secret), claim }
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
};
|
|
2195
|
+
if (options.dryRun) {
|
|
2196
|
+
const rollback = new Error("preview rollback");
|
|
2197
|
+
try {
|
|
2198
|
+
withTransaction(db, () => {
|
|
2199
|
+
collect();
|
|
2200
|
+
throw rollback;
|
|
2201
|
+
});
|
|
2202
|
+
} catch (error) {
|
|
2203
|
+
if (error !== rollback) throw error;
|
|
2204
|
+
}
|
|
2205
|
+
} else withTransaction(db, collect);
|
|
2206
|
+
if (!options.dryRun) {
|
|
2207
|
+
const sent = await Promise.all(
|
|
2208
|
+
claims.map((claim) => sendHookDelivery(db, claim.delivery, claim.target, options))
|
|
2209
|
+
);
|
|
2210
|
+
result.sent = sent.filter(Boolean).length;
|
|
2211
|
+
}
|
|
2212
|
+
const deliveries = listDeliveries(db);
|
|
2213
|
+
result.queued = deliveries.filter((d) => d.status === "pending" && d.attempts === 0).length + Number(
|
|
2214
|
+
db.prepare(
|
|
2215
|
+
"SELECT COUNT(DISTINCT target_id) AS n FROM hook_assignments WHERE delivery_id IS NULL"
|
|
2216
|
+
).get()?.n ?? 0
|
|
2217
|
+
);
|
|
2218
|
+
result.retrying = deliveries.filter((d) => d.status === "pending" && d.attempts > 0).length;
|
|
2219
|
+
result.failed = deliveries.filter((d) => d.status === "failed").length;
|
|
2220
|
+
return result;
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
// src/tools/manage_hooks_tool.ts
|
|
2224
|
+
var manageHooksTool = defineQuestlogTool({
|
|
2225
|
+
name: "manage_hooks",
|
|
2226
|
+
description: "List or remove outbound webhook targets, run a tick, or inspect pending and failed deliveries.",
|
|
2227
|
+
whenToUse: "Use to operate configured outbound webhooks. Add and test targets with the CLI.",
|
|
2228
|
+
whenNotToUse: "Use quest tools to change work itself.",
|
|
2229
|
+
sideEffects: "writes_state",
|
|
2230
|
+
readOnly: false,
|
|
2231
|
+
supportsClarification: false,
|
|
2232
|
+
targetKinds: ["hook"],
|
|
2233
|
+
inputDescriptions: {
|
|
2234
|
+
action: "Operation to perform.",
|
|
2235
|
+
id: "Target id for removal.",
|
|
2236
|
+
dry_run: "Preview a tick without recording or sending."
|
|
2237
|
+
},
|
|
2238
|
+
outputDescription: "Returns redacted targets, delivery metadata, or a tick summary. Never returns signing secrets.",
|
|
2239
|
+
inputSchema: objectSchema(
|
|
2240
|
+
{
|
|
2241
|
+
action: enumSchema("Operation.", ["list", "remove", "tick", "deliveries"]),
|
|
2242
|
+
id: integerSchema("Target id."),
|
|
2243
|
+
dry_run: booleanSchema("Preview only.")
|
|
2244
|
+
},
|
|
2245
|
+
["action"]
|
|
2246
|
+
),
|
|
2247
|
+
handler: async (db, input) => {
|
|
2248
|
+
switch (input.action) {
|
|
2249
|
+
case "list":
|
|
2250
|
+
return toolSuccess("Webhook targets.", listHooks(db));
|
|
2251
|
+
case "deliveries":
|
|
2252
|
+
return toolSuccess("Pending and failed deliveries.", listDeliveries(db));
|
|
2253
|
+
case "remove":
|
|
2254
|
+
if (!Number.isSafeInteger(input.id) || Number(input.id) < 1)
|
|
2255
|
+
return toolFailure(
|
|
2256
|
+
"protocol",
|
|
2257
|
+
"invalid_input",
|
|
2258
|
+
"Target id required.",
|
|
2259
|
+
"Provide a positive target id.",
|
|
2260
|
+
{ recovery: 'Pass {"action":"remove","id":1}' }
|
|
2261
|
+
);
|
|
2262
|
+
removeHook(db, Number(input.id));
|
|
2263
|
+
return toolSuccess("Webhook target removed.", {});
|
|
2264
|
+
case "tick":
|
|
2265
|
+
return toolSuccess(
|
|
2266
|
+
"Webhook tick completed.",
|
|
2267
|
+
await tickQuestlog(db, { dryRun: input.dry_run ?? false })
|
|
2268
|
+
);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
});
|
|
2272
|
+
|
|
2273
|
+
// src/assert_non_negative_seconds.ts
|
|
2274
|
+
function assertNonNegativeSeconds(value, label) {
|
|
2275
|
+
if (value != null && value < 0) {
|
|
2276
|
+
throw new Error(`${label} must not be negative.`);
|
|
2277
|
+
}
|
|
2278
|
+
return value;
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
// src/repeatable_quests/update_repeatable_quest.ts
|
|
2282
|
+
function updateRepeatableQuest(db, repeatableQuestId, input) {
|
|
2283
|
+
return withTransaction(db, () => {
|
|
2284
|
+
const current = getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
2285
|
+
const now = resolveNow(input.now);
|
|
2286
|
+
const rrule = input.rrule ?? current.rrule;
|
|
2287
|
+
parseRRule(rrule);
|
|
2288
|
+
db.prepare(
|
|
2289
|
+
`UPDATE repeatable_quests
|
|
2290
|
+
SET questline_id = ?,
|
|
2291
|
+
title = ?,
|
|
2292
|
+
objective = ?,
|
|
2293
|
+
rrule = ?,
|
|
2294
|
+
anchor_at = ?,
|
|
2295
|
+
not_before_offset_seconds = ?,
|
|
2296
|
+
due_offset_seconds = ?,
|
|
2297
|
+
scheduled_start_offset_seconds = ?,
|
|
2298
|
+
scheduled_end_offset_seconds = ?,
|
|
2299
|
+
all_day = ?,
|
|
2300
|
+
estimate_seconds = ?,
|
|
2301
|
+
archived_at = ?,
|
|
2302
|
+
updated_at = ?
|
|
2303
|
+
WHERE id = ? AND deleted_at IS NULL`
|
|
2304
|
+
).run(
|
|
2305
|
+
input.questlineId === void 0 ? current.questlineId : input.questlineId,
|
|
2306
|
+
input.title == null ? current.title : assertNonEmpty(input.title, "Repeatable quest title"),
|
|
2307
|
+
input.objective == null ? current.objective : assertNonEmpty(input.objective, "Repeatable quest objective"),
|
|
2308
|
+
rrule,
|
|
2309
|
+
input.anchorAt ?? current.anchorAt,
|
|
2310
|
+
input.notBeforeOffsetSeconds === void 0 ? current.notBeforeOffsetSeconds : assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
|
|
2311
|
+
input.dueOffsetSeconds === void 0 ? current.dueOffsetSeconds : assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
|
|
2312
|
+
input.scheduledStartOffsetSeconds === void 0 ? current.scheduledStartOffsetSeconds : input.scheduledStartOffsetSeconds,
|
|
2313
|
+
input.scheduledEndOffsetSeconds === void 0 ? current.scheduledEndOffsetSeconds : input.scheduledEndOffsetSeconds,
|
|
2314
|
+
input.allDay === void 0 ? current.allDay ? 1 : 0 : input.allDay ? 1 : 0,
|
|
2315
|
+
input.estimateSeconds === void 0 ? current.estimateSeconds : assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
|
|
2316
|
+
input.archivedAt === void 0 ? current.archivedAt : input.archivedAt,
|
|
2317
|
+
now,
|
|
2318
|
+
repeatableQuestId
|
|
2319
|
+
);
|
|
2320
|
+
return getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
2321
|
+
});
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
// src/repeatable_quests/archive_repeatable_quest.ts
|
|
2325
|
+
function archiveRepeatableQuest(db, repeatableQuestId, archivedAt) {
|
|
2326
|
+
return updateRepeatableQuest(db, repeatableQuestId, { archivedAt: resolveNow(archivedAt) });
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
// src/assert_active_row_exists.ts
|
|
2330
|
+
function assertActiveRowExists(db, table, id, label) {
|
|
2331
|
+
const row = db.prepare(`SELECT id FROM ${table} WHERE id = ? AND deleted_at IS NULL`).get(id);
|
|
2332
|
+
if (!row) {
|
|
2333
|
+
throw new Error(`${label} ${id} was not found.`);
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
// src/assert_non_negative_number.ts
|
|
2338
|
+
function assertNonNegativeNumber(value, label) {
|
|
2339
|
+
if (value != null && value < 0) {
|
|
2340
|
+
throw new Error(`${label} must not be negative.`);
|
|
2341
|
+
}
|
|
2342
|
+
return value;
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2345
|
+
// src/rewards/replace_active_repeatable_quest_rewards.ts
|
|
2346
|
+
function replaceActiveRepeatableQuestRewards(db, repeatableQuestId, rewards, now) {
|
|
2347
|
+
const effectiveNow = resolveNow(now);
|
|
2348
|
+
db.prepare(
|
|
2349
|
+
"UPDATE repeatable_quest_rewards SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
|
|
2350
|
+
).run(effectiveNow, repeatableQuestId);
|
|
2351
|
+
for (const reward of rewards) {
|
|
2352
|
+
db.prepare(
|
|
2353
|
+
`INSERT INTO repeatable_quest_rewards (
|
|
2354
|
+
repeatable_quest_id,
|
|
2355
|
+
kind,
|
|
2356
|
+
name,
|
|
2357
|
+
description,
|
|
2358
|
+
quantity,
|
|
2359
|
+
created_at
|
|
2360
|
+
) VALUES (?, ?, ?, ?, ?, ?)`
|
|
2361
|
+
).run(
|
|
2362
|
+
repeatableQuestId,
|
|
2363
|
+
assertNonEmpty(reward.kind, "Reward kind"),
|
|
2364
|
+
assertNonEmpty(reward.name, "Reward name"),
|
|
2365
|
+
reward.description?.trim() || null,
|
|
2366
|
+
assertNonNegativeNumber(reward.quantity, "Reward quantity") ?? null,
|
|
2367
|
+
effectiveNow
|
|
2368
|
+
);
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
// src/tags/replace_active_repeatable_quest_tags.ts
|
|
2373
|
+
function getOrCreateTagId(db, name, now) {
|
|
2374
|
+
const normalizedName = normalizeTagName(name);
|
|
2375
|
+
if (!normalizedName) {
|
|
2376
|
+
throw new Error("Tag name must not be empty.");
|
|
2377
|
+
}
|
|
2378
|
+
const existing = db.prepare("SELECT id FROM tags WHERE normalized_name = ? AND deleted_at IS NULL").get(normalizedName);
|
|
2379
|
+
if (existing) {
|
|
2380
|
+
return Number(existing.id);
|
|
2381
|
+
}
|
|
2382
|
+
const created = db.prepare(
|
|
2383
|
+
`INSERT INTO tags (name, normalized_name, created_at)
|
|
2384
|
+
VALUES (?, ?, ?)`
|
|
2385
|
+
).run(name.trim(), normalizedName, now);
|
|
2386
|
+
return Number(created.lastInsertRowid);
|
|
2387
|
+
}
|
|
2388
|
+
function replaceActiveRepeatableQuestTags(db, repeatableQuestId, tagNames, now) {
|
|
2389
|
+
const effectiveNow = resolveNow(now);
|
|
2390
|
+
db.prepare(
|
|
2391
|
+
"UPDATE repeatable_quest_tags SET deleted_at = ? WHERE repeatable_quest_id = ? AND deleted_at IS NULL"
|
|
2392
|
+
).run(effectiveNow, repeatableQuestId);
|
|
2393
|
+
const uniqueNames = [...new Set(tagNames.map((tag) => tag.trim()).filter(Boolean))];
|
|
2394
|
+
for (const name of uniqueNames) {
|
|
2395
|
+
const tagId = getOrCreateTagId(db, name, effectiveNow);
|
|
2396
|
+
db.prepare(
|
|
2397
|
+
`INSERT INTO repeatable_quest_tags (repeatable_quest_id, tag_id, created_at)
|
|
2398
|
+
VALUES (?, ?, ?)`
|
|
2399
|
+
).run(repeatableQuestId, tagId, effectiveNow);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2403
|
+
// src/repeatable_quests/create_repeatable_quest.ts
|
|
2404
|
+
function createRepeatableQuest(db, input) {
|
|
2405
|
+
return withTransaction(db, () => {
|
|
2406
|
+
const now = resolveNow(input.now);
|
|
2407
|
+
const title = assertNonEmpty(input.title, "Repeatable quest title");
|
|
2408
|
+
const objective = assertNonEmpty(input.objective, "Repeatable quest objective");
|
|
2409
|
+
parseRRule(input.rrule);
|
|
2410
|
+
if (input.questlineId != null) {
|
|
2411
|
+
assertActiveRowExists(db, "questlines", input.questlineId, "Questline");
|
|
2412
|
+
}
|
|
2413
|
+
const created = db.prepare(
|
|
2414
|
+
`INSERT INTO repeatable_quests (
|
|
2415
|
+
questline_id,
|
|
2416
|
+
title,
|
|
2417
|
+
objective,
|
|
2418
|
+
rrule,
|
|
2419
|
+
anchor_at,
|
|
2420
|
+
not_before_offset_seconds,
|
|
2421
|
+
due_offset_seconds,
|
|
2422
|
+
scheduled_start_offset_seconds,
|
|
2423
|
+
scheduled_end_offset_seconds,
|
|
2424
|
+
all_day,
|
|
2425
|
+
estimate_seconds,
|
|
2426
|
+
created_at,
|
|
2427
|
+
updated_at
|
|
2428
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
2429
|
+
).run(
|
|
2430
|
+
input.questlineId ?? null,
|
|
2431
|
+
title,
|
|
2432
|
+
objective,
|
|
2433
|
+
input.rrule,
|
|
2434
|
+
input.anchorAt,
|
|
2435
|
+
assertNonNegativeSeconds(input.notBeforeOffsetSeconds, "Repeatable not-before offset") ?? null,
|
|
2436
|
+
assertNonNegativeSeconds(input.dueOffsetSeconds, "Repeatable due offset") ?? null,
|
|
2437
|
+
input.scheduledStartOffsetSeconds ?? null,
|
|
2438
|
+
input.scheduledEndOffsetSeconds ?? null,
|
|
2439
|
+
input.allDay ? 1 : 0,
|
|
2440
|
+
assertNonNegativeSeconds(input.estimateSeconds, "Repeatable estimate") ?? null,
|
|
2441
|
+
now,
|
|
2442
|
+
now
|
|
2443
|
+
);
|
|
2444
|
+
const repeatableQuestId = Number(created.lastInsertRowid);
|
|
2445
|
+
if (input.tags && input.tags.length > 0) {
|
|
2446
|
+
replaceActiveRepeatableQuestTags(db, repeatableQuestId, input.tags, now);
|
|
2447
|
+
}
|
|
2448
|
+
if (input.rewards && input.rewards.length > 0) {
|
|
2449
|
+
replaceActiveRepeatableQuestRewards(db, repeatableQuestId, input.rewards, now);
|
|
2450
|
+
}
|
|
2451
|
+
return getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
2452
|
+
});
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
// src/repeatable_quests/soft_delete_repeatable_quest.ts
|
|
2456
|
+
function softDeleteRepeatableQuest(db, repeatableQuestId, deletedAt) {
|
|
2457
|
+
const now = resolveNow(deletedAt);
|
|
2458
|
+
getRepeatableQuestOrThrow(db, repeatableQuestId);
|
|
2459
|
+
db.prepare(
|
|
2460
|
+
`UPDATE repeatable_quests
|
|
2461
|
+
SET deleted_at = ?, updated_at = ?
|
|
2462
|
+
WHERE id = ? AND deleted_at IS NULL`
|
|
2463
|
+
).run(now, now, repeatableQuestId);
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2107
2466
|
// src/tools/manage_repeatable_tool.ts
|
|
2108
2467
|
function manageRepeatableToolHandler(db, input) {
|
|
2109
2468
|
try {
|
|
@@ -3323,7 +3682,7 @@ function validateReviewInput(input) {
|
|
|
3323
3682
|
'Use `filters.dayAt` only with `view: "quests.scheduled_for_day"`.'
|
|
3324
3683
|
);
|
|
3325
3684
|
}
|
|
3326
|
-
if ((input.view === "rumors" || input.view === "questlines") && hasQuestFilters(input.filters)) {
|
|
3685
|
+
if ((input.view === "rumors" || input.view === "questlines" || input.view === "deliveries") && hasQuestFilters(input.filters)) {
|
|
3327
3686
|
return toolFailure(
|
|
3328
3687
|
"protocol",
|
|
3329
3688
|
"invalid_input",
|
|
@@ -3391,6 +3750,15 @@ function reviewQuestlogToolHandler(db, input) {
|
|
|
3391
3750
|
if (invalid) {
|
|
3392
3751
|
return invalid;
|
|
3393
3752
|
}
|
|
3753
|
+
if (input.view === "deliveries")
|
|
3754
|
+
return toolSuccess("Pending and failed deliveries.", {
|
|
3755
|
+
view: input.view,
|
|
3756
|
+
items: [],
|
|
3757
|
+
deliveries: listDeliveries(db),
|
|
3758
|
+
count: listDeliveries(db).length,
|
|
3759
|
+
appliedFilters: input.filters,
|
|
3760
|
+
evaluatedAt: input.now ?? Date.now()
|
|
3761
|
+
});
|
|
3394
3762
|
const now = input.now ?? Date.now();
|
|
3395
3763
|
let items = [];
|
|
3396
3764
|
switch (input.view) {
|
|
@@ -3450,6 +3818,7 @@ var reviewQuestlogTool = defineQuestlogTool({
|
|
|
3450
3818
|
inputSchema: objectSchema(
|
|
3451
3819
|
{
|
|
3452
3820
|
view: enumSchema("Which operational review surface to return.", [
|
|
3821
|
+
"deliveries",
|
|
3453
3822
|
"questlines",
|
|
3454
3823
|
"quests.active",
|
|
3455
3824
|
"quests.available",
|
|
@@ -4812,6 +5181,7 @@ var tagWorkTool = defineQuestlogTool({
|
|
|
4812
5181
|
|
|
4813
5182
|
// src/tools/tool_registry.ts
|
|
4814
5183
|
var questlogTools = [
|
|
5184
|
+
manageHooksTool,
|
|
4815
5185
|
searchQuestlogTool,
|
|
4816
5186
|
reviewQuestlogTool,
|
|
4817
5187
|
inspectQuestlogItemTool,
|