@christang/keel 5.84.0 → 5.85.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.
@@ -0,0 +1,453 @@
1
+ "use strict";
2
+
3
+ // `keel chat` (issue #187): the host-neutral command line every session and
4
+ // the owner use. Any agent that can run a shell command can take part; no
5
+ // host integration is needed to post or read.
6
+
7
+ const fs = require("fs");
8
+ const path = require("path");
9
+ const store = require("./store");
10
+ const { displayRecords, formatLine, parseSince, since } = require("./view");
11
+ const { migrateIfNeeded } = require("./migrate");
12
+ const notice = require("./notice");
13
+ const { relativeAge } = require("./view");
14
+
15
+ const { ChatError } = store;
16
+
17
+ const USAGE = [
18
+ "keel chat role [--set <name>] [--alias <alias>] [--json]",
19
+ "keel chat group create <group> [--member <role>]...",
20
+ "keel chat group add|remove <group> <role>",
21
+ "keel chat group archive <group>",
22
+ "keel chat group list [--all] [--json] (also: keel chat list)",
23
+ "keel chat post <group> <text...> [--reply-to <id>] [--json] (also: keel chat <group> <text...>)",
24
+ "keel chat dm <role> <text...> [--json]",
25
+ "keel chat <group> [--since <90s|15m|2h|3d|date>] [--follow] [--peek] [--json] (view; advances your read position unless --peek)",
26
+ "keel chat unread [--json]",
27
+ "keel chat read [<group>] [--json]",
28
+ "keel chat show <id> [--json]",
29
+ "keel chat todo <group> --assignee <role> [--issue <n>] <text...> [--json]",
30
+ "keel chat todos [<group>] [--mine] [--json]",
31
+ "keel chat done <id>",
32
+ "keel chat edit <id> <text...>",
33
+ "keel chat retract <id>",
34
+ "keel chat search <text...> [--group <group>] [--json]",
35
+ "keel chat archive sync|pull [--json] (keep the chat on this repository's orphan keel-chat branch)",
36
+ "keel chat bridge add|remove [--repo <path>] (list or unlist this project for this machine's Slack bridge)",
37
+ "keel chat bridge run [--once] (the bridge process; --once sends what is pending and exits; Node 22+)",
38
+ "keel chat bridge install|uninstall|start|stop (the macOS login item that keeps the bridge running)",
39
+ "keel chat bridge pause <30m|2h|1d> | resume",
40
+ "keel chat bridge status [--json]",
41
+ "keel chat notice (what is unread and addressed to you, for any host; always exits 0)",
42
+ "keel chat hook session-start|user-prompt-submit|file-changed|session-end (Claude Code hook; JSON on stdin)",
43
+ "Every command takes --repo <path> to act on another repository.",
44
+ ];
45
+
46
+ const VALUED = {
47
+ "--set": "set",
48
+ "--alias": "alias",
49
+ "--reply-to": "replyTo",
50
+ "--repo": "repo",
51
+ "--assignee": "assignee",
52
+ "--issue": "issue",
53
+ "--group": "group",
54
+ "--since": "since",
55
+ };
56
+ const REPEATED = { "--member": "members" };
57
+ const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail" };
58
+
59
+ function parseChatArgs(argv) {
60
+ const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false };
61
+ for (const key of Object.values(VALUED)) options[key] = null;
62
+ for (let index = 0; index < argv.length; index += 1) {
63
+ const arg = argv[index];
64
+ if (arg === "--") {
65
+ options.positionals.push(...argv.slice(index + 1));
66
+ break;
67
+ }
68
+ if (arg in SWITCHES) {
69
+ options[SWITCHES[arg]] = true;
70
+ continue;
71
+ }
72
+ const eq = arg.indexOf("=");
73
+ const flag = arg.startsWith("--") && eq > 0 ? arg.slice(0, eq) : arg;
74
+ if (flag in VALUED || flag in REPEATED) {
75
+ let value;
76
+ if (flag !== arg) {
77
+ value = arg.slice(eq + 1);
78
+ } else {
79
+ index += 1;
80
+ if (index >= argv.length) throw new ChatError(`${arg} requires a value.`);
81
+ value = argv[index];
82
+ }
83
+ if (flag in REPEATED) {
84
+ options[REPEATED[flag]].push(value);
85
+ continue;
86
+ }
87
+ const key = VALUED[flag];
88
+ if (options[key] !== null) throw new ChatError(`${flag} was provided more than once.`);
89
+ options[key] = value;
90
+ continue;
91
+ }
92
+ if (arg.startsWith("--")) throw new ChatError(`Unknown option for keel chat: ${arg}`);
93
+ options.positionals.push(arg);
94
+ }
95
+ return options;
96
+ }
97
+
98
+ function out(text) {
99
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
100
+ }
101
+
102
+ function readStdin() {
103
+ if (process.stdin.isTTY) return "";
104
+ try {
105
+ return fs.readFileSync(0, "utf8");
106
+ } catch {
107
+ return "";
108
+ }
109
+ }
110
+
111
+ function publicRecord(record) {
112
+ const { refs, ...rest } = record;
113
+ return refs && refs.length ? record : rest;
114
+ }
115
+
116
+ // A mentioned member that is offline gets the record when it next starts;
117
+ // nothing launches it (D10), so the poster is told.
118
+ function offlineMentions(where, record) {
119
+ return (record.mentions || [])
120
+ .filter((role) => role !== store.ALL && !role.includes("/") && role !== record.from)
121
+ .filter((role) => notice.presenceOf(where, role).state === "offline");
122
+ }
123
+
124
+ function postResult(where, record, json) {
125
+ const offline = offlineMentions(where, record);
126
+ if (json) {
127
+ out(JSON.stringify({ id: record.id, group: record.group, from: record.from, mentions: record.mentions, offline }));
128
+ return;
129
+ }
130
+ const lines = [`Posted ${record.id} to ${record.group}.`];
131
+ for (const role of offline) lines.push(`Queued for ${role}: offline; it will see this when its session next starts.`);
132
+ out(lines.join("\n"));
133
+ }
134
+
135
+ function textFrom(words) {
136
+ const text = words.join(" ");
137
+ return text.trim() ? text : readStdin();
138
+ }
139
+
140
+ function runGroup(where, options) {
141
+ const [action, group, member] = options.positionals.slice(1);
142
+ if (action === "list" || action === undefined) {
143
+ const groups = store.listGroups(where, { includeArchived: options.all });
144
+ if (options.json) out(JSON.stringify({ groups }));
145
+ else if (!groups.length) out("No groups. Create one with `keel chat group create <group>`.");
146
+ else out(groups.map((g) => `${g.name}${g.archived ? " (archived)" : ""}: ${g.members.join(", ")}`).join("\n"));
147
+ return 0;
148
+ }
149
+ const actor = store.requireRole(where);
150
+ if (!group) throw new ChatError(`keel chat group ${action} needs a group name.`);
151
+ switch (action) {
152
+ case "create": {
153
+ const members = store.createGroup(where, actor, group, options.members);
154
+ out(options.json ? JSON.stringify({ group, members }) : `Created ${group}: ${members.join(", ")}.`);
155
+ return 0;
156
+ }
157
+ case "add":
158
+ case "remove": {
159
+ if (!member) throw new ChatError(`keel chat group ${action} needs a role.`);
160
+ store.changeMember(where, actor, group, member, action === "add" ? "join" : "leave");
161
+ out(`${action === "add" ? "Added" : "Removed"} ${member} ${action === "add" ? "to" : "from"} ${group}.`);
162
+ return 0;
163
+ }
164
+ case "archive":
165
+ store.archiveGroup(where, actor, group);
166
+ out(`Archived ${group}. Its history stays readable.`);
167
+ return 0;
168
+ default:
169
+ throw new ChatError(`Unknown keel chat group action ${JSON.stringify(action)}: use create, add, remove, archive, or list.`);
170
+ }
171
+ }
172
+
173
+ function presenceLine(where, members) {
174
+ const now = Date.now();
175
+ const parts = [...members].sort().map((role) => {
176
+ const { state, last_active: last } = notice.presenceOf(where, role, now);
177
+ if (!last) return `${role} (offline, never seen)`;
178
+ return state === "online" ? `${role} (online)` : `${role} (${state}, ${relativeAge(last, now)})`;
179
+ });
180
+ return `Members: ${parts.join(", ") || "none"}`;
181
+ }
182
+
183
+ function runView(where, group, options) {
184
+ const role = store.currentRole(where);
185
+ let threshold = null;
186
+ if (options.since !== null) {
187
+ threshold = parseSince(options.since);
188
+ if (threshold === null) throw new ChatError(`--since ${JSON.stringify(options.since)} is not a duration (90s, 15m, 2h, 3d) or a date.`);
189
+ }
190
+ const { records: raw, state } = store.view(where, role, group, { peek: options.peek });
191
+ const records = since(displayRecords(raw), threshold);
192
+ if (options.json) {
193
+ out(JSON.stringify({ group, members: [...state.members].sort(), records: records.map(publicRecord) }));
194
+ } else {
195
+ out([`# ${group}${state.archived ? " (archived)" : ""}`, presenceLine(where, state.members), ...records.map((record) => formatLine(record))].join("\n"));
196
+ }
197
+ if (options.follow) follow(where, role, group, raw, options);
198
+ return 0;
199
+ }
200
+
201
+ // Keeps printing records as they arrive until interrupted. Polling the log
202
+ // directory, rather than a file watcher, behaves the same on every platform
203
+ // and over a synced folder.
204
+ function follow(where, role, group, initial, options) {
205
+ let last = initial.length ? initial[initial.length - 1].id : "";
206
+ const timer = setInterval(() => {
207
+ const records = store.readLog(where, group);
208
+ const fresh = displayRecords(records).filter((record) => record.id > last);
209
+ if (!fresh.length) return;
210
+ for (const record of fresh) out(options.json ? JSON.stringify(publicRecord(record)) : formatLine(record));
211
+ last = records[records.length - 1].id;
212
+ if (!options.peek && role) store.advanceCursor(where, role, group, last);
213
+ }, 500);
214
+ const stop = () => {
215
+ clearInterval(timer);
216
+ process.exitCode = 0;
217
+ };
218
+ process.once("SIGINT", stop);
219
+ process.once("SIGTERM", stop);
220
+ }
221
+
222
+ function dispatch(where, options) {
223
+ const [command, ...rest] = options.positionals;
224
+ switch (command) {
225
+ case "role": {
226
+ let role = store.currentRole(where);
227
+ if (options.set !== null) role = store.setRole(where, options.set);
228
+ if (options.alias !== null) {
229
+ if (!role) throw new ChatError("Bind a role before adding an alias: `keel chat role --set <name>`.");
230
+ store.addAlias(where, role, options.alias);
231
+ }
232
+ const aliases = role ? store.readMember(where.root, role).aliases : [];
233
+ if (options.json) out(JSON.stringify({ role, aliases, worktree: where.worktree, store: where.root }));
234
+ else out(role ? `Chat role: ${role}${aliases.length ? ` (aliases: ${aliases.join(", ")})` : ""}` : "This worktree has no chat role. Bind one with `keel chat role --set <name>`.");
235
+ return 0;
236
+ }
237
+ case "group":
238
+ return runGroup(where, options);
239
+ case "list":
240
+ return runGroup(where, { ...options, positionals: ["group", "list"] });
241
+ case "post": {
242
+ const [group, ...words] = rest;
243
+ if (!group) throw new ChatError("keel chat post needs a group.");
244
+ postResult(where, store.post(where, { group, text: textFrom(words), replyTo: options.replyTo }), options.json);
245
+ return 0;
246
+ }
247
+ case "dm": {
248
+ const [target, ...words] = rest;
249
+ if (!target) throw new ChatError("keel chat dm needs a role.");
250
+ postResult(where, store.directPost(where, target, textFrom(words)), options.json);
251
+ return 0;
252
+ }
253
+ case "unread": {
254
+ const role = store.requireRole(where);
255
+ const records = store.unread(where, role);
256
+ if (options.json) out(JSON.stringify({ role, unread: records.map(publicRecord) }));
257
+ else out(records.length ? records.map((r) => `${r.group} ${formatLine(r)}`).join("\n") : `keel chat: nothing unread for role \`${role}\`.`);
258
+ return 0;
259
+ }
260
+ case "read": {
261
+ const role = store.requireRole(where);
262
+ const records = store.readGroups(where, role, rest[0] || null);
263
+ if (options.json) out(JSON.stringify({ role, notice: store.DATA_NOTICE, records: records.map(publicRecord) }));
264
+ else if (!records.length) out(`keel chat: nothing unread for role \`${role}\`.`);
265
+ else out([`> ${store.DATA_NOTICE}`, "", ...records.map((r) => `${r.group} ${formatLine(r)}`)].join("\n"));
266
+ return 0;
267
+ }
268
+ case "show": {
269
+ const id = rest[0];
270
+ if (!id) throw new ChatError("keel chat show needs a record id.");
271
+ const record = store.findRecord(where, id);
272
+ if (!record) throw new ChatError(`No record ${id}.`);
273
+ const readers = store.readersOf(where, record);
274
+ if (options.json) out(JSON.stringify({ record: publicRecord(record), readers }));
275
+ else out([`${record.group} ${formatLine(record)}`, `read by: ${readers.join(", ") || "nobody yet"}`].join("\n"));
276
+ return 0;
277
+ }
278
+ case "todo": {
279
+ const [group, ...words] = rest;
280
+ if (!group) throw new ChatError("keel chat todo needs a group.");
281
+ if (options.assignee === null) throw new ChatError("keel chat todo needs --assignee <role>.");
282
+ postResult(where, store.todo(where, { group, assignee: options.assignee, issue: options.issue, text: textFrom(words), replyTo: options.replyTo }), options.json);
283
+ return 0;
284
+ }
285
+ case "todos": {
286
+ const assignee = options.mine ? store.requireRole(where) : null;
287
+ const todos = store.openTodos(where, { group: rest[0] || null, assignee });
288
+ if (options.json) out(JSON.stringify({ todos: todos.map(publicRecord) }));
289
+ else out(todos.length ? todos.map((r) => `${r.group} ${formatLine(r)}`).join("\n") : "No open todos.");
290
+ return 0;
291
+ }
292
+ case "done": {
293
+ if (!rest[0]) throw new ChatError("keel chat done needs a todo id.");
294
+ const record = store.done(where, rest[0]);
295
+ out(options.json ? JSON.stringify({ id: record.id, target: record.target }) : `Closed todo ${record.target}.`);
296
+ return 0;
297
+ }
298
+ case "edit":
299
+ case "retract": {
300
+ const [id, ...words] = rest;
301
+ if (!id) throw new ChatError(`keel chat ${command} needs a record id.`);
302
+ const record = store.amend(where, id, command, command === "edit" ? textFrom(words) : "");
303
+ out(options.json ? JSON.stringify({ id: record.id, target: record.target }) : `${command === "edit" ? "Edited" : "Retracted"} ${id}; the original record is kept.`);
304
+ return 0;
305
+ }
306
+ case "search": {
307
+ const results = store.search(where, rest.join(" "), { group: options.group });
308
+ if (options.json) out(JSON.stringify({ results: results.map(publicRecord) }));
309
+ else out(results.length ? results.map((r) => `${r.group} ${formatLine(r)}`).join("\n") : "No matches.");
310
+ return 0;
311
+ }
312
+ case "notice": {
313
+ const role = store.currentRole(where);
314
+ const text = role ? notice.noticeText(where, role) : "";
315
+ if (options.json) out(JSON.stringify({ role, notice: text }));
316
+ else if (text) out(text);
317
+ return 0;
318
+ }
319
+ case "bridge":
320
+ return runBridge(where, rest, options);
321
+ case "archive": {
322
+ const archive = require("./archive");
323
+ if (rest[0] === "sync") {
324
+ const result = archive.sync(where);
325
+ if (options.json) out(JSON.stringify(result));
326
+ else {
327
+ const lines = [`keel chat archive: ${result.changed ? "committed" : "already up to date at"} ${result.commit ? result.commit.slice(0, 12) : "nothing"} on keel-chat${result.imported ? `; imported ${result.imported} file${result.imported === 1 ? "" : "s"} from ${result.remote}` : ""}${result.pushed ? `; pushed to ${result.remote}` : ""}.`];
328
+ if (result.refused) lines.push(result.refused);
329
+ if (result.conflicts.length) lines.push(`These records differ between this machine and the archive; the local copy was kept: ${result.conflicts.join(", ")}`);
330
+ out(lines.join("\n"));
331
+ }
332
+ return 0;
333
+ }
334
+ if (rest[0] === "pull") {
335
+ const result = archive.pull(where);
336
+ out(options.json ? JSON.stringify(result) : `keel chat archive: restored ${result.imported} file${result.imported === 1 ? "" : "s"} from the keel-chat archive.`);
337
+ return 0;
338
+ }
339
+ throw new ChatError("keel chat archive needs sync or pull.");
340
+ }
341
+ case "help":
342
+ case undefined:
343
+ out(`Usage:\n ${USAGE.join("\n ")}`);
344
+ return 0;
345
+ default: {
346
+ // `keel chat <group>` views; `keel chat <group> <text...>` posts.
347
+ if (rest.length) {
348
+ postResult(where, store.post(where, { group: command, text: rest.join(" "), replyTo: options.replyTo }), options.json);
349
+ return 0;
350
+ }
351
+ return runView(where, command, options);
352
+ }
353
+ }
354
+ }
355
+
356
+ function runBridge(where, rest, options) {
357
+ const bridge = require("./bridge");
358
+ const lifecycle = require("./lifecycle");
359
+ const [action] = rest;
360
+ if (action !== "status") bridge.requireWebSocket();
361
+ switch (action) {
362
+ case "add": {
363
+ const added = bridge.addProject(where);
364
+ out(`This machine's bridge will serve ${added} when keel/chat.json sets slack.enabled to true.`);
365
+ return 0;
366
+ }
367
+ case "remove":
368
+ out(`This machine's bridge no longer serves ${bridge.removeProject(where)}.`);
369
+ return 0;
370
+ case "status": {
371
+ const status = bridge.fullStatus();
372
+ if (options.json) {
373
+ out(JSON.stringify(status));
374
+ return 0;
375
+ }
376
+ const lines = [`keel chat bridge: ${status.installed ? "installed as a login item" : "not installed"}; ${status.running ? `running (pid ${status.pid}), ${status.connected ? "connected" : "not connected"}` : "not running"}${status.paused ? `, paused until ${status.paused_until}` : ""}.`];
377
+ if (status.running) lines.push(`Serving ${status.projects.length} project${status.projects.length === 1 ? "" : "s"}; last event ${status.last_event || "none yet"}; ${status.unposted} waiting to send; ${status.ignored} ignored from unregistered senders.`);
378
+ else lines.push("Slack messages are not reaching this machine's sessions; local chat still works and nothing is lost.");
379
+ out(lines.join("\n"));
380
+ return 0;
381
+ }
382
+ case "install":
383
+ out(`Installed ${lifecycle.install()}; the bridge now starts at login and restarts if it stops. See it under System Settings > General > Login Items.`);
384
+ return 0;
385
+ case "uninstall":
386
+ out(`Removed ${lifecycle.uninstall()}; the bridge no longer runs on this machine.`);
387
+ return 0;
388
+ case "start":
389
+ lifecycle.start();
390
+ out("Started the bridge.");
391
+ return 0;
392
+ case "stop":
393
+ lifecycle.stop();
394
+ out("Stopped the bridge until `keel chat bridge start` or your next login. Messages wait; nothing is lost.");
395
+ return 0;
396
+ case "pause": {
397
+ const until = lifecycle.pause(rest[1]);
398
+ out(`Paused the bridge until ${until.toISOString()}. Messages wait and are delivered afterwards. \`keel chat bridge resume\` ends it early.`);
399
+ return 0;
400
+ }
401
+ case "resume":
402
+ lifecycle.resume();
403
+ out("Resumed the bridge.");
404
+ return 0;
405
+ case "run": {
406
+ const log = (line) => process.stderr.write(`keel chat bridge: ${line}\n`);
407
+ (options.once ? bridge.runOnce(log) : bridge.run(log)).then(
408
+ (code) => { process.exitCode = code; },
409
+ (error) => {
410
+ process.stderr.write(`keel chat: ${error.message}\n`);
411
+ process.exitCode = error instanceof ChatError ? 2 : 1;
412
+ }
413
+ );
414
+ return undefined;
415
+ }
416
+ default:
417
+ throw new ChatError(`Unknown keel chat bridge action ${JSON.stringify(action)}: use add, remove, install, uninstall, start, stop, pause, resume, status, or run.`);
418
+ }
419
+ }
420
+
421
+ function runChat(argv) {
422
+ try {
423
+ const options = parseChatArgs(argv);
424
+ const cwd = path.resolve(options.repo || process.cwd());
425
+ if (!options.positionals.length || options.positionals[0] === "help") {
426
+ out(`Usage:\n ${USAGE.join("\n ")}`);
427
+ return 0;
428
+ }
429
+ if (options.positionals[0] === "hook") {
430
+ const result = notice.hook(options.positionals[1], readStdin(), { mail: options.mail });
431
+ if (result.stdout) process.stdout.write(result.stdout);
432
+ if (result.stderr) process.stderr.write(result.stderr);
433
+ return result.code;
434
+ }
435
+ // A notice is read by hosts on every prompt: outside a repository it says
436
+ // nothing and still exits 0.
437
+ if (options.positionals[0] === "notice" && !store.locate(cwd)) return 0;
438
+ const where = store.requireLocation(cwd);
439
+ migrateIfNeeded(where);
440
+ const role = store.currentRole(where);
441
+ if (role) notice.touchPresence(where, role);
442
+ return dispatch(where, options);
443
+ } catch (error) {
444
+ if (!(error instanceof ChatError)) throw error;
445
+ process.stderr.write(`keel chat: ${error.message}\n`);
446
+ return 2;
447
+ }
448
+ }
449
+
450
+ module.exports = {
451
+ CHAT_USAGE: USAGE,
452
+ runChat,
453
+ };
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+
3
+ // Per-project chat settings (issue #187, design D13): a committed
4
+ // `keel/chat.json`, kept apart from `keel/config.yaml` because that reader is
5
+ // flat on purpose and the chat needs nested maps (Slack user -> role, group ->
6
+ // channel). An absent file is local chat with no Slack and no archive. A file
7
+ // that does not parse turns Slack and archive off and says why; local chat
8
+ // keeps working, because a typo in an integration setting must not silence
9
+ // the sessions that never used it.
10
+
11
+ const fs = require("fs");
12
+ const path = require("path");
13
+
14
+ const CHAT_CONFIG_RELATIVE_PATH = path.join("keel", "chat.json");
15
+
16
+ function loadChatConfig(worktree) {
17
+ const file = path.join(worktree, CHAT_CONFIG_RELATIVE_PATH);
18
+ let text;
19
+ try {
20
+ text = fs.readFileSync(file, "utf8");
21
+ } catch {
22
+ return { config: {}, error: null, file };
23
+ }
24
+ try {
25
+ const parsed = JSON.parse(text);
26
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
27
+ return { config: {}, error: `${CHAT_CONFIG_RELATIVE_PATH} is not a JSON object.`, file };
28
+ }
29
+ return { config: parsed, error: null, file };
30
+ } catch (error) {
31
+ return { config: {}, error: `${CHAT_CONFIG_RELATIVE_PATH} does not parse: ${error.message}`, file };
32
+ }
33
+ }
34
+
35
+ function stringMap(value) {
36
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
37
+ const map = {};
38
+ for (const [key, entry] of Object.entries(value)) {
39
+ if (typeof entry === "string" && entry) map[key] = entry;
40
+ }
41
+ return map;
42
+ }
43
+
44
+ // The Slack half of `keel/chat.json`. A project is relayed only when it says
45
+ // `slack.enabled: true` in so many words (D14); anything else — absent,
46
+ // unparsable, `"yes"` — leaves it local.
47
+ function slackSettings(worktree) {
48
+ const { config, error } = loadChatConfig(worktree);
49
+ const slack = (config && typeof config.slack === "object" && config.slack) || {};
50
+ return {
51
+ enabled: !error && slack.enabled === true,
52
+ error,
53
+ owner: typeof slack.owner === "string" ? slack.owner : null,
54
+ members: stringMap(slack.members),
55
+ channels: stringMap(slack.channels),
56
+ icons: stringMap(slack.icons),
57
+ };
58
+ }
59
+
60
+ module.exports = {
61
+ CHAT_CONFIG_RELATIVE_PATH,
62
+ loadChatConfig,
63
+ slackSettings,
64
+ };
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ // Loop guards (issue #187, design D11). Agents that answer each other can keep
4
+ // answering for ever, and a woken session that posts can wake another. Two
5
+ // checks stop that without a person watching:
6
+ //
7
+ // rate a role other than `owner` may post at most `limits.rate`
8
+ // records per `limits.window_minutes` across the project
9
+ // (default 20 per 10).
10
+ // ping-pong when the last `limits.pingpong` messages of a group (default 8)
11
+ // alternate between the same two roles other than `owner`, the
12
+ // next post there by either is refused, and Keel calls the owner
13
+ // with one `system` record. Any other member's post clears it.
14
+ //
15
+ // Both refuse by name, so an agent reading its error knows what stopped it.
16
+
17
+ const { loadChatConfig } = require("./config");
18
+
19
+ const DEFAULTS = { rate: 20, window_minutes: 10, pingpong: 8 };
20
+ const SYSTEM_SENDER = "keel";
21
+
22
+ function positiveInteger(value, fallback) {
23
+ return Number.isInteger(value) && value > 0 ? value : fallback;
24
+ }
25
+
26
+ function limitsFor(where) {
27
+ const { config } = loadChatConfig(where.worktree);
28
+ const limits = (config && typeof config.limits === "object" && config.limits) || {};
29
+ return {
30
+ rate: positiveInteger(limits.rate, DEFAULTS.rate),
31
+ window_minutes: positiveInteger(limits.window_minutes, DEFAULTS.window_minutes),
32
+ pingpong: positiveInteger(limits.pingpong, DEFAULTS.pingpong),
33
+ };
34
+ }
35
+
36
+ // The two roles a group's recent messages alternate between, or null.
37
+ function pingPongPair(records, length) {
38
+ const messages = records.filter((record) => record.kind === "message").slice(-length);
39
+ if (messages.length < length) return null;
40
+ const pair = [messages[0].from, messages[1].from];
41
+ if (pair[0] === pair[1] || pair.includes("owner")) return null;
42
+ for (let index = 0; index < messages.length; index += 1) {
43
+ if (messages[index].from !== pair[index % 2]) return null;
44
+ }
45
+ return pair;
46
+ }
47
+
48
+ function postedSince(store, where, role, since) {
49
+ let count = 0;
50
+ for (const group of store.listGroupNames(where)) {
51
+ for (const record of store.readLog(where, group)) {
52
+ if (record.from !== role || (record.kind !== "message" && record.kind !== "todo")) continue;
53
+ const time = Date.parse(record.created);
54
+ if (!Number.isNaN(time) && time >= since) count += 1;
55
+ }
56
+ }
57
+ return count;
58
+ }
59
+
60
+ // Throws the store's error when `role` may not post to `group` now.
61
+ function checkPost(store, where, role, group, records) {
62
+ if (role === "owner") return;
63
+ const limits = limitsFor(where);
64
+ const pair = pingPongPair(records, limits.pingpong);
65
+ if (pair && pair.includes(role)) {
66
+ const last = records[records.length - 1];
67
+ if (!(last && last.kind === "system" && last.from === SYSTEM_SENDER)) {
68
+ store.writeRecord(where, {
69
+ group,
70
+ kind: "system",
71
+ from: SYSTEM_SENDER,
72
+ mentions: ["owner"],
73
+ text: `@owner ${pair[0]} and ${pair[1]} have answered each other ${limits.pingpong} times in a row in ${group}; `
74
+ + "the loop guard holds their next posts here until someone else posts.",
75
+ });
76
+ }
77
+ throw new store.ChatError(
78
+ `The loop guard stopped this post: ${pair[0]} and ${pair[1]} have alternated the last ${limits.pingpong} `
79
+ + `messages in ${group}. The owner has been called; any other member's post clears it.`
80
+ );
81
+ }
82
+ const since = Date.now() - limits.window_minutes * 60 * 1000;
83
+ const posted = postedSince(store, where, role, since);
84
+ if (posted >= limits.rate) {
85
+ throw new store.ChatError(
86
+ `The loop guard stopped this post: ${role} posted ${posted} records in the last ${limits.window_minutes} `
87
+ + `minutes, the limit set by limits.rate in keel/chat.json (default ${DEFAULTS.rate}).`
88
+ );
89
+ }
90
+ }
91
+
92
+ module.exports = {
93
+ DEFAULTS,
94
+ SYSTEM_SENDER,
95
+ checkPost,
96
+ };