@saltpub/agent-autoloop 0.0.0-stage → 0.1.3

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 (177) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/INSTALL.md +120 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +268 -0
  5. package/README.md +264 -2
  6. package/SECURITY.md +49 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/agents.js +14 -0
  9. package/dist/cli/backup.js +144 -0
  10. package/dist/cli/dashboard/app.js +424 -0
  11. package/dist/cli/dashboard/index.html +15 -0
  12. package/dist/cli/dashboard/style.css +629 -0
  13. package/dist/cli/dashboard.js +94 -0
  14. package/dist/cli/explain.js +84 -0
  15. package/dist/cli/main.js +1142 -0
  16. package/dist/cli/mcp.js +151 -0
  17. package/dist/cli/runs.js +40 -0
  18. package/dist/cli/spend.js +21 -0
  19. package/dist/cli/status.js +272 -0
  20. package/dist/cli/try.js +6 -0
  21. package/dist/cli/ui.js +75 -0
  22. package/dist/cli/uninstall.js +86 -0
  23. package/dist/cli/update.js +65 -0
  24. package/dist/cli/why.js +115 -0
  25. package/dist/host/background-launcher.js +12 -0
  26. package/dist/host/background.js +24 -0
  27. package/dist/host/channels.js +4 -0
  28. package/dist/host/command.js +98 -0
  29. package/dist/host/config.js +37 -0
  30. package/dist/host/files.js +22 -0
  31. package/dist/host/home.js +5 -0
  32. package/dist/host/http.js +45 -0
  33. package/dist/host/launcher.js +188 -0
  34. package/dist/host/lines.js +15 -0
  35. package/dist/host/node-path.js +33 -0
  36. package/dist/host/npm.js +28 -0
  37. package/dist/host/plugins.js +26 -0
  38. package/dist/host/program.js +14 -0
  39. package/dist/host/runtime.js +179 -0
  40. package/dist/host/server.js +159 -0
  41. package/dist/host/service.js +325 -0
  42. package/dist/host/state.js +203 -0
  43. package/dist/host/up.js +162 -0
  44. package/dist/host/update.js +286 -0
  45. package/dist/host/version.js +81 -0
  46. package/dist/kernel/card-page.js +54 -0
  47. package/dist/kernel/credentials.js +16 -0
  48. package/dist/kernel/cron.js +135 -0
  49. package/dist/kernel/decide.js +826 -0
  50. package/dist/kernel/due.js +73 -0
  51. package/dist/kernel/errors.js +9 -0
  52. package/dist/kernel/evolve.js +264 -0
  53. package/dist/kernel/http.js +357 -0
  54. package/dist/kernel/query.js +202 -0
  55. package/dist/kernel/rules.js +20 -0
  56. package/dist/kernel/store.js +52 -0
  57. package/dist/plugins/acp/agent.js +32 -0
  58. package/dist/plugins/acp/bridge.js +204 -0
  59. package/dist/plugins/claude/agent.js +113 -0
  60. package/dist/plugins/codex/agent.js +105 -0
  61. package/dist/plugins/command/agent.js +25 -0
  62. package/dist/plugins/delivery/action.js +25 -0
  63. package/dist/plugins/delivery/agent.js +13 -0
  64. package/dist/plugins/delivery/delivery.js +388 -0
  65. package/dist/plugins/delivery/github.js +201 -0
  66. package/dist/plugins/delivery/handoff.js +50 -0
  67. package/dist/plugins/delivery/input.js +47 -0
  68. package/dist/plugins/delivery/poll.js +72 -0
  69. package/dist/plugins/delivery/project.js +144 -0
  70. package/dist/plugins/delivery/review-ledger.js +82 -0
  71. package/dist/plugins/delivery/review-policy.js +99 -0
  72. package/dist/plugins/delivery/review.js +280 -0
  73. package/dist/plugins/delivery/run.js +204 -0
  74. package/dist/plugins/desktop/channel.js +94 -0
  75. package/dist/plugins/dsh/agent.js +116 -0
  76. package/dist/plugins/feishu/channel.js +245 -0
  77. package/dist/plugins/github/source.js +30 -0
  78. package/dist/plugins/gitlab/source.js +30 -0
  79. package/dist/plugins/omp/agent.js +3 -0
  80. package/dist/plugins/opencode/agent.js +88 -0
  81. package/dist/plugins/pi/agent.js +92 -0
  82. package/dist/plugins/webhook/channel.js +70 -0
  83. package/dist/plugins/webhook/templates.js +34 -0
  84. package/dist/plugins/xiaojiu/channel.js +410 -0
  85. package/dist/plugins/zcode/agent.js +102 -0
  86. package/dist/protocol/client.js +56 -0
  87. package/dist/protocol/conformance.js +184 -0
  88. package/dist/protocol/job.js +1 -0
  89. package/dist/protocol/rules.js +230 -0
  90. package/dist/protocol/schema.js +70 -0
  91. package/dist/protocol/schema.json +985 -0
  92. package/dist/protocol/validate.js +150 -0
  93. package/dist/worker/agents.js +47 -0
  94. package/dist/worker/contract.js +178 -0
  95. package/dist/worker/run.js +52 -0
  96. package/dist/worker/usage.js +45 -0
  97. package/dist/worker/windows.ps1 +48 -0
  98. package/dist/worker/worker.js +595 -0
  99. package/docs/architecture.en.svg +178 -0
  100. package/docs/architecture.svg +178 -0
  101. package/docs/auto-update.md +53 -0
  102. package/docs/plugins.md +139 -0
  103. package/docs/protocol.md +582 -0
  104. package/docs/state-machines.md +77 -0
  105. package/examples/channel.sh +15 -0
  106. package/examples/plugins/hello-agent/agent.ts +40 -0
  107. package/examples/plugins/hello-channel/channel.ts +54 -0
  108. package/examples/plugins/hello-source/source.ts +19 -0
  109. package/examples/recipes/browser-handoff/README.md +44 -0
  110. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  111. package/examples/recipes/browser-handoff/browser.json +10 -0
  112. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  113. package/examples/recipes/browser-handoff/rules.json +19 -0
  114. package/examples/recipes/feedback/README.md +34 -0
  115. package/examples/recipes/feedback/SKILL.md +22 -0
  116. package/examples/recipes/feedback/event.json +8 -0
  117. package/examples/recipes/feedback/rules.json +37 -0
  118. package/examples/recipes/feishu-brief/README.md +28 -0
  119. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  120. package/examples/recipes/feishu-brief/collect.ts +164 -0
  121. package/examples/recipes/feishu-brief/rules.json +57 -0
  122. package/examples/recipes/feishu-brief/sources.json +13 -0
  123. package/examples/recipes/github-issues/README.md +17 -0
  124. package/examples/recipes/github-issues/SKILL.md +18 -0
  125. package/examples/recipes/github-issues/rules.json +30 -0
  126. package/examples/recipes/inbox-triage/README.md +36 -0
  127. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  128. package/examples/recipes/inbox-triage/collect.ts +191 -0
  129. package/examples/recipes/inbox-triage/rules.json +57 -0
  130. package/examples/recipes/inbox-triage/sources.json +8 -0
  131. package/examples/recipes/morning-brief/README.md +17 -0
  132. package/examples/recipes/morning-brief/SKILL.md +17 -0
  133. package/examples/recipes/morning-brief/rules.json +16 -0
  134. package/examples/recipes/ops-alerts/README.md +18 -0
  135. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  136. package/examples/recipes/ops-alerts/restart.sh +5 -0
  137. package/examples/recipes/ops-alerts/rules.json +29 -0
  138. package/examples/recipes/website-watch/README.md +26 -0
  139. package/examples/recipes/website-watch/SKILL.md +19 -0
  140. package/examples/recipes/website-watch/check.ts +86 -0
  141. package/examples/recipes/website-watch/rules.json +56 -0
  142. package/examples/recipes/website-watch/site.json +6 -0
  143. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  144. package/examples/watch-github-issues.sh +23 -0
  145. package/examples/worker.sh +18 -0
  146. package/package.json +57 -4
  147. package/plugins/acp/agent.ts +31 -0
  148. package/plugins/acp/bridge.ts +190 -0
  149. package/plugins/claude/agent.ts +121 -0
  150. package/plugins/codex/agent.ts +103 -0
  151. package/plugins/command/agent.ts +25 -0
  152. package/plugins/delivery/action.ts +29 -0
  153. package/plugins/delivery/action.yml +28 -0
  154. package/plugins/delivery/agent.ts +15 -0
  155. package/plugins/delivery/delivery.ts +408 -0
  156. package/plugins/delivery/github.ts +207 -0
  157. package/plugins/delivery/handoff.ts +72 -0
  158. package/plugins/delivery/input.ts +55 -0
  159. package/plugins/delivery/poll.ts +65 -0
  160. package/plugins/delivery/project.ts +161 -0
  161. package/plugins/delivery/review-ledger.ts +90 -0
  162. package/plugins/delivery/review-policy.ts +126 -0
  163. package/plugins/delivery/review.ts +324 -0
  164. package/plugins/delivery/run.ts +219 -0
  165. package/plugins/desktop/channel.ts +100 -0
  166. package/plugins/dsh/agent.ts +100 -0
  167. package/plugins/feishu/channel.ts +243 -0
  168. package/plugins/github/source.ts +33 -0
  169. package/plugins/gitlab/source.ts +32 -0
  170. package/plugins/omp/agent.ts +4 -0
  171. package/plugins/opencode/agent.ts +78 -0
  172. package/plugins/pi/agent.ts +80 -0
  173. package/plugins/webhook/channel.ts +74 -0
  174. package/plugins/webhook/templates.ts +32 -0
  175. package/plugins/xiaojiu/channel.ts +426 -0
  176. package/plugins/zcode/agent.ts +96 -0
  177. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,73 @@
1
+ // The next moment each thing needs the clock: schedules, reviews, retries, card resends, a worker gone quiet, a lease
2
+ // run out. The shell keeps one timer, for the earliest of them, so nothing has to poll.
3
+ import { rows } from "./evolve.js";
4
+ import { configuration, waitingOn, workers } from "./query.js";
5
+ export const MINUTE = 60_000;
6
+ /** A worker seen this recently is really there, so a run it has stopped mentioning has really gone quiet. */
7
+ export const WORKER_FRESH = 2 * MINUTE;
8
+ /** How long a claimed run can go unmentioned by its worker before it's in doubt. */
9
+ export const RUN_LEASE = 5 * MINUTE;
10
+ /** How long work can wait on a worker that doesn't come before the owner hears. */
11
+ export const OFFLINE_AFTER = 10 * MINUTE;
12
+ /**
13
+ * How often being seen goes in the log. A worker asks every second with work in hand and a fact is a disk sync, so a stamp
14
+ * can be behind the last contact by this much. It has to stay under what reads it: with the 50 seconds between idle polls,
15
+ * under WORKER_FRESH; and under RUN_LEASE - WORKER_FRESH, or a run could look quiet while its worker still looks there.
16
+ */
17
+ export const SEEN_EVERY = MINUTE;
18
+ /**
19
+ * The card about a worker gone away, and whether it has said all there is to say: it's still open, or the owner closed it
20
+ * after everything now waiting had come in. Anything newer is news, or one closed card would hide it until the worker's back.
21
+ */
22
+ export function offlineCard(view, worker, waiting) {
23
+ const seen = view.get("seen", `worker:${worker}`);
24
+ const key = `worker:${worker}:offline:${seen ? seen.seen_at : "never"}`;
25
+ const card = rows(view, "cards", { key }, 1, true)[0];
26
+ const told = card && (card.state === "open" || waiting.every((run) => run.created_at <= card.closed_at));
27
+ return { key, told };
28
+ }
29
+ export function deadlines(view, now) {
30
+ const due = {};
31
+ const add = (kind, key, at) => {
32
+ due[`${kind}:${key}`] = { kind, key, at };
33
+ };
34
+ const scheduled = (rule) => configuration(view).rules.some((known) => known.name === rule && "cron" in known.when);
35
+ for (const schedule of rows(view, "schedules")) {
36
+ if (scheduled(schedule.rule))
37
+ add("cron", schedule.rule, Date.parse(schedule.next_at));
38
+ }
39
+ for (const pause of rows(view, "pauses")) {
40
+ if (pause.until !== null)
41
+ add("pause", pause.name, Date.parse(pause.until));
42
+ }
43
+ for (const timer of rows(view, "timers", { event_id: null }))
44
+ add("later", String(timer.id), Date.parse(timer.at));
45
+ for (const run of rows(view, "runs", { state: "queued" })) {
46
+ const notBefore = Date.parse(run.not_before);
47
+ if (notBefore > now)
48
+ add("retry", String(run.id), notBefore);
49
+ }
50
+ for (const delivery of rows(view, "deliveries", { given_up: 0, not_before: { not: null } })) {
51
+ const notBefore = Date.parse(delivery.not_before);
52
+ if (notBefore > now)
53
+ add("delivery", `${delivery.card_id}:${delivery.channel}`, notBefore);
54
+ }
55
+ for (const worker of workers(view)) {
56
+ const seen = view.get("seen", `worker:${worker}`);
57
+ const waiting = waitingOn(view, worker, now);
58
+ if (!waiting.length)
59
+ continue;
60
+ // The sweep acts strictly after each limit, hence the extra millisecond.
61
+ if (!offlineCard(view, worker, waiting).told) {
62
+ add("offline", worker, Math.max(now, Date.parse(seen?.seen_at ?? waiting[0].created_at) + OFFLINE_AFTER + 1));
63
+ }
64
+ if (!seen || now - Date.parse(seen.seen_at) > WORKER_FRESH)
65
+ continue;
66
+ for (const run of waiting.filter((run) => run.state === "claimed")) {
67
+ const at = Math.max(now, Date.parse(run.seen_at) + RUN_LEASE + 1);
68
+ if (at <= Date.parse(seen.seen_at) + WORKER_FRESH)
69
+ add("lease", String(run.id), at);
70
+ }
71
+ }
72
+ return due;
73
+ }
@@ -0,0 +1,9 @@
1
+ // What a door answers when it says no. Each maps to one HTTP status in http.ts.
2
+ export class InputError extends Error {
3
+ }
4
+ export class AuthError extends Error {
5
+ }
6
+ export class Conflict extends Error {
7
+ }
8
+ export class NotFound extends Error {
9
+ }
@@ -0,0 +1,264 @@
1
+ // A view reads an indexed projection. A decision owns only its overlay; evolve alone persists changes.
2
+ import { DatabaseSync } from "node:sqlite";
3
+ export const TABLES = [
4
+ "events",
5
+ "runs",
6
+ "run_events",
7
+ "cards",
8
+ "deliveries",
9
+ "timers",
10
+ "schedules",
11
+ "seen",
12
+ "keys",
13
+ "config",
14
+ "due",
15
+ "pauses",
16
+ ];
17
+ const NUMBERED = new Set(["events", "runs", "cards", "timers"]);
18
+ const indexes = {
19
+ events: [["source", "key"], ["routed", "id"], ["paused", "id"], ["id"]],
20
+ runs: [["state", "id"], ["rule", "lane", "state", "id"], ["id"], ["finished_at"]],
21
+ run_events: [["run_id"], ["event_id"]],
22
+ cards: [
23
+ ["key", "id"],
24
+ ["state", "id"],
25
+ ["rule", "lane", "state", "id"],
26
+ ["rule", "lane", "answer_event", "id"],
27
+ ["answer_event"],
28
+ ["run_id"],
29
+ ["id"],
30
+ ["fyi", "created_at"],
31
+ ],
32
+ timers: [
33
+ ["event_id", "id"],
34
+ ["rule", "lane", "key", "id"],
35
+ ["rule", "lane", "event_id", "id"],
36
+ ],
37
+ deliveries: [["channel"], ["card_id"]],
38
+ due: [["at"]],
39
+ };
40
+ const field = (name) => `json_extract(data,'$.${name}')`;
41
+ const statements = new WeakMap();
42
+ export function statement(db, sql) {
43
+ let cache = statements.get(db);
44
+ if (!cache)
45
+ statements.set(db, (cache = new Map()));
46
+ let stmt = cache.get(sql);
47
+ if (!stmt)
48
+ cache.set(sql, (stmt = db.prepare(sql)));
49
+ return stmt;
50
+ }
51
+ export function initialize(db) {
52
+ if (ready.has(db))
53
+ return;
54
+ db.exec(`CREATE TABLE IF NOT EXISTS facts(seq INTEGER PRIMARY KEY, fact TEXT NOT NULL);
55
+ CREATE TABLE IF NOT EXISTS projections(collection TEXT,key TEXT,data TEXT NOT NULL,PRIMARY KEY(collection,key));
56
+ CREATE TABLE IF NOT EXISTS projection_meta(id INTEGER PRIMARY KEY,seq INTEGER NOT NULL,next TEXT NOT NULL,format TEXT NOT NULL);
57
+ CREATE TABLE IF NOT EXISTS projection_refs(collection TEXT,key TEXT,seq INTEGER,PRIMARY KEY(collection,key,seq));
58
+ CREATE TABLE IF NOT EXISTS projection_pending(key TEXT PRIMARY KEY,card_id INTEGER,channel TEXT);
59
+ CREATE INDEX IF NOT EXISTS pending_channel ON projection_pending(channel,card_id);`);
60
+ indexProjection(db);
61
+ ready.add(db);
62
+ }
63
+ function indexProjection(db) {
64
+ // Including collection prevents the planner preferring a collection-wide primary-key scan for IN predicates.
65
+ db.exec("CREATE INDEX IF NOT EXISTS projection_delivery_due ON projections(collection,json_extract(data,'$.given_up'),key) WHERE collection='deliveries' AND json_extract(data,'$.not_before') IS NOT NULL");
66
+ for (const [table, groups] of Object.entries(indexes))
67
+ for (const [i, columns] of groups.entries()) {
68
+ const order = NUMBERED.has(table) ? field("id") : "key";
69
+ const indexed = columns.map(field);
70
+ if (!indexed.includes(order))
71
+ indexed.push(order);
72
+ db.exec(`CREATE INDEX IF NOT EXISTS projection_${table}_${i} ON projections(collection,${indexed.join(",")}) WHERE collection='${table}'`);
73
+ }
74
+ }
75
+ const freeze = (row) => {
76
+ for (const child of Object.values(row))
77
+ if (child && typeof child === "object" && !Object.isFrozen(child))
78
+ freeze(child);
79
+ return Object.freeze(row);
80
+ };
81
+ export class View {
82
+ seq;
83
+ next;
84
+ db;
85
+ format;
86
+ base;
87
+ changes = new Map();
88
+ // The biggest row there is, and every queued run asks for it. Facts bring a new view, so this can't go stale.
89
+ configs = new Map();
90
+ constructor(db, seq = 0, next = {}, format = "") {
91
+ this.db = db;
92
+ this.seq = seq;
93
+ this.next = { ...next };
94
+ this.format = format;
95
+ }
96
+ get(table, key) {
97
+ const id = String(key), changes = this.changes.get(table);
98
+ if (changes?.has(id))
99
+ return changes.get(id) ?? undefined;
100
+ if (this.base)
101
+ return this.base.get(table, id);
102
+ if (table === "config" && this.configs.has(id))
103
+ return this.configs.get(id);
104
+ const row = statement(this.db, "SELECT data FROM projections WHERE collection=? AND key=?").get(table, id);
105
+ const found = row ? freeze(JSON.parse(String(row.data))) : undefined;
106
+ if (table === "config")
107
+ this.configs.set(id, found);
108
+ return found;
109
+ }
110
+ select(table, match = {}, limit, reverse = false) {
111
+ const changed = this.changes.get(table);
112
+ if (this.base && changed?.size) {
113
+ const accepts = (row) => Object.entries(match).every(([key, value]) => Array.isArray(value)
114
+ ? value.includes(row[key] ?? null)
115
+ : value && typeof value === "object" && "not" in value
116
+ ? row[key] != null
117
+ : (row[key] ?? null) === value);
118
+ const found = this.base
119
+ .select(table, match, limit === undefined ? undefined : limit + changed.size, reverse)
120
+ .filter((row) => !changed.has(keyOf(table, row)));
121
+ for (const row of changed.values())
122
+ if (row && accepts(row))
123
+ found.push(row);
124
+ if (NUMBERED.has(table))
125
+ found.sort((a, b) => (reverse ? b.id - a.id : a.id - b.id));
126
+ else
127
+ found.sort((a, b) => (reverse ? -1 : 1) * Buffer.compare(Buffer.from(keyOf(table, a)), Buffer.from(keyOf(table, b))));
128
+ return limit === undefined ? found : found.slice(0, limit);
129
+ }
130
+ if (this.base)
131
+ return this.base.select(table, match, limit, reverse);
132
+ const params = [];
133
+ const conditions = Object.entries(match).map(([key, value]) => {
134
+ if (Array.isArray(value)) {
135
+ params.push(JSON.stringify(value));
136
+ return `${field(key)} IN (SELECT value FROM json_each(?))`;
137
+ }
138
+ if (value && typeof value === "object" && "not" in value)
139
+ return `${field(key)} IS NOT NULL`;
140
+ params.push(value);
141
+ return `${field(key)} IS ?`;
142
+ });
143
+ // With IN filters, sorting the matching rows avoids the planner scanning every historic ID in order.
144
+ const order = NUMBERED.has(table) ? `${Object.values(match).some(Array.isArray) ? "+" : ""}${field("id")}` : "key";
145
+ const sql = `SELECT key,data FROM projections WHERE collection='${table}'${conditions.map((c) => ` AND ${c}`).join("")} ORDER BY ${order} ${reverse ? "DESC" : "ASC"}${limit === undefined ? "" : " LIMIT ?"}`;
146
+ if (limit !== undefined)
147
+ params.push(limit);
148
+ return statement(this.db, sql)
149
+ .all(...params)
150
+ .map((item) => freeze(JSON.parse(String(item.data))));
151
+ }
152
+ *deliveryCandidates(channel, now) {
153
+ const sql = `SELECT c.data FROM (
154
+ SELECT ${field("id")} AS id FROM projections WHERE collection='cards' AND ${field("state")}='open'
155
+ UNION SELECT ${field("id")} FROM projections WHERE collection='cards' AND ${field("fyi")}=1 AND ${field("created_at")}>=?
156
+ UNION SELECT card_id FROM projection_pending WHERE channel=?
157
+ ) candidates JOIN projections c ON c.collection='cards' AND c.key=CAST(candidates.id AS TEXT) ORDER BY candidates.id`;
158
+ for (const row of statement(this.db, sql).iterate(iso(now - 86400_000), channel))
159
+ yield freeze(JSON.parse(String(row.data)));
160
+ }
161
+ fork() {
162
+ const result = new View(this.db, this.seq, this.next, this.format);
163
+ result.base = this;
164
+ return result;
165
+ }
166
+ set(table, key, row) {
167
+ let changed = this.changes.get(table);
168
+ if (!changed)
169
+ this.changes.set(table, (changed = new Map()));
170
+ changed.set(key, row ? freeze(row) : null);
171
+ if (typeof row?.id === "number")
172
+ this.next[table] = Math.max(this.next[table] ?? 0, row.id);
173
+ }
174
+ close() {
175
+ this.db.close();
176
+ }
177
+ }
178
+ export function keyOf(table, row) {
179
+ if (NUMBERED.has(table))
180
+ return String(row.id);
181
+ if (table === "run_events")
182
+ return `${row.run_id}:${row.event_id}`;
183
+ if (table === "deliveries")
184
+ return `${row.card_id}:${row.channel}`;
185
+ if (table === "schedules")
186
+ return row.rule;
187
+ if (table === "seen" || table === "keys")
188
+ return `${row.kind}:${row.name}`;
189
+ if (table === "due")
190
+ return `${row.kind}:${row.key}`;
191
+ if (table === "pauses")
192
+ return row.name;
193
+ return "rules";
194
+ }
195
+ export function empty(db = new DatabaseSync(":memory:")) {
196
+ initialize(db);
197
+ return new View(db);
198
+ }
199
+ export function evolve(view, facts, db = view.db, reset = false) {
200
+ initialize(db);
201
+ if (reset) {
202
+ for (const { name } of db
203
+ .prepare("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='projections' AND sql IS NOT NULL")
204
+ .all())
205
+ db.exec(`DROP INDEX "${String(name).replaceAll('"', '""')}"`);
206
+ db.exec("DELETE FROM projections");
207
+ db.exec("DELETE FROM projection_refs; DELETE FROM projection_pending");
208
+ indexProjection(db);
209
+ }
210
+ let seq = view.seq;
211
+ const next = { ...view.next };
212
+ const put = statement(db, "INSERT INTO projections VALUES (?,?,?) ON CONFLICT(collection,key) DO UPDATE SET data=excluded.data");
213
+ const remove = statement(db, "DELETE FROM projections WHERE collection=? AND key=?");
214
+ for (const fact of facts) {
215
+ seq = fact.seq;
216
+ const pending = new Map();
217
+ for (const change of fact.changes) {
218
+ pending.set(`${change.table}:${change.key}`, change);
219
+ if (typeof change.row?.id === "number")
220
+ next[change.table] = Math.max(next[change.table] ?? 0, change.row.id);
221
+ }
222
+ for (const { table, key, row } of pending.values()) {
223
+ if (["events", "runs", "cards"].includes(table))
224
+ statement(db, "INSERT OR IGNORE INTO projection_refs VALUES (?,?,?)").run(table, key, fact.seq);
225
+ if (row === null)
226
+ remove.run(table, key);
227
+ else {
228
+ const data = JSON.stringify(row);
229
+ put.run(table, key, data);
230
+ // A held run keeps the configuration it claimed, including through projection rebuilds.
231
+ if (table === "config" && key === "rules")
232
+ put.run(table, String(row.version), data);
233
+ }
234
+ }
235
+ const current = new View(db);
236
+ const deliveries = new Set();
237
+ for (const { table, key, row } of pending.values()) {
238
+ if (table === "cards")
239
+ for (const delivery of rows(current, "deliveries", { card_id: Number(key) }))
240
+ deliveries.add(keyOf("deliveries", delivery));
241
+ if (table === "deliveries")
242
+ deliveries.add(key);
243
+ }
244
+ for (const key of deliveries) {
245
+ statement(db, "DELETE FROM projection_pending WHERE key=?").run(key);
246
+ const delivery = current.get("deliveries", key);
247
+ const card = delivery && current.get("cards", delivery.card_id);
248
+ if (card && delivery.ref !== null && !delivery.given_up && delivery.version < card.version)
249
+ statement(db, "INSERT INTO projection_pending VALUES (?,?,?)").run(key, card.id, delivery.channel);
250
+ }
251
+ }
252
+ statement(db, "INSERT INTO projection_meta VALUES (1,?,?,?) ON CONFLICT(id) DO UPDATE SET seq=excluded.seq,next=excluded.next,format=excluded.format").run(seq, JSON.stringify(next), view.format);
253
+ return new View(db, seq, next, view.format);
254
+ }
255
+ const ready = new WeakSet();
256
+ export function snapshot(view) {
257
+ const tables = Object.fromEntries(TABLES.map((table) => [table, {}]));
258
+ for (const item of statement(view.db, "SELECT collection,key,data FROM projections").all()) {
259
+ tables[item.collection][String(item.key)] = JSON.parse(String(item.data));
260
+ }
261
+ return { seq: view.seq, tables, next: { ...view.next } };
262
+ }
263
+ export const rows = (view, table, match = {}, limit, reverse = false) => view.select(table, match, limit, reverse);
264
+ export const iso = (ms) => new Date(ms).toISOString();