@supa-media/tex-contract 0.13.0 → 0.16.22

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.
@@ -169,6 +169,8 @@ const KEYWORDS = {
169
169
  "contacts:": { name: "list_contacts", action: "contacts", copy: ["limit"] },
170
170
  "activity:": { name: "read_activity", action: "activity", copy: ["limit"] },
171
171
  "changes:": { name: "list_changes", action: "changes", copy: ["limit", "reads"] },
172
+ // The comments for this connection's person (`apps/mcp/src/tools/commentsList.js`): args { filter, limit }.
173
+ "comments:": { name: "list_comments", action: "comments", copy: ["filter", "limit"] },
172
174
  "links:": { name: "list_links", action: "links", copy: [] },
173
175
  "vault:": { name: "vault_list", action: "vault", copy: [] },
174
176
  "plugins:": { name: "list_plugins", action: "plugins", copy: [] },
@@ -260,9 +262,12 @@ function translateFetch(call, app = {}) {
260
262
  return target(label, a, { name: "read_email", action: "email", fixed: { id }, copy: ["attachment", "start", "summary"], others: ATTACHMENT_ONLY });
261
263
  }
262
264
 
263
- // A chat's history file reads as the note it is, with that note's access.
265
+ // A chat's history file reads as the note it is, with that note's access. A long one (a group chat's view runs to
266
+ // tens of thousands of lines) comes back as its first part with a `more: lines: "<a>-<b>"` line (`readCapped.js`),
267
+ // so it takes the line reads every long note takes, or that line led nowhere: Grok Bot read the first ~660 lines of
268
+ // a group chat's history and every `lines` past them was refused (2026-12-01).
264
269
  if (HISTORY_FILE_ID.test(id)) {
265
- return target(label, a, { name: "read_note", action: "note", fixed: { path: id }, copy: ["before", "job"] });
270
+ return target(label, a, { name: "read_note", action: "note", fixed: { path: id }, copy: ["before", "job", "lines", "section", "outline", "full"] });
266
271
  }
267
272
 
268
273
  // A message anchor from search (`<note>.md#<anchor>`) reads that one message; `<note>.md#Plan#Risks` reads one
@@ -294,7 +299,7 @@ function translateFetch(call, app = {}) {
294
299
  if (named !== null && a.section === undefined && a.lines === undefined && a.outline === undefined && a.mail === undefined) {
295
300
  return target(label, a, { name: "read_note", action: "note", fixed: { path: note, section: named }, copy: [], others: NOTE_READS });
296
301
  }
297
- return target(label, a, { name: "read_note", action: "note", fixed: { path: note }, copy: ["mail", "outline", "section", "lines", "full"], others: NOTE_READS });
302
+ return target(label, a, { name: "read_note", action: "note", fixed: { path: note }, copy: ["mail", "outline", "section", "lines", "full", "versions", "version"], others: NOTE_READS });
298
303
  }
299
304
 
300
305
  // A sheet (a `.csv` with typed columns): its rows as a table, filtered and sorted by its args (`readSheet.js`).
@@ -32,11 +32,14 @@
32
32
  const NOTE = "note";
33
33
  const SHEET = "sheet";
34
34
  const FILE = "file";
35
+ /** A live mock: a page of HTML a note embeds with `![[name.html]]` (`docs/decisions/app-and-console/live-mocks.md`). */
36
+ const MOCK = "mock";
35
37
 
36
38
  /** The text kinds, by lowercased extension. One line adds one. */
37
39
  const TEXT_KINDS = Object.freeze({
38
40
  ".md": NOTE,
39
41
  ".csv": SHEET,
42
+ ".html": MOCK,
40
43
  });
41
44
 
42
45
  /** The extensions Context reads and writes as text, in `TEXT_KINDS` order. */
@@ -79,12 +82,17 @@ function isNotePath(path) {
79
82
  return kindOf(path) === NOTE;
80
83
  }
81
84
 
85
+ /** A live mock (`.html`). @param {unknown} path */
86
+ function isMockPath(path) {
87
+ return kindOf(path) === MOCK;
88
+ }
89
+
82
90
  /** A sheet (`.csv`). @param {unknown} path */
83
91
  function isSheetPath(path) {
84
92
  return kindOf(path) === SHEET;
85
93
  }
86
94
 
87
- /** Text Context reads and writes itself: a note or a sheet. @param {unknown} path */
95
+ /** Text Context reads and writes itself: a note, a sheet or a mock. @param {unknown} path */
88
96
  function isTextFilePath(path) {
89
97
  return kindOf(path) !== FILE;
90
98
  }
@@ -98,18 +106,23 @@ function withoutTextExtension(name) {
98
106
  return isTextFilePath(name) ? name.slice(0, -extensionOf(name).length) : name;
99
107
  }
100
108
 
109
+ /** The extensions the privacy parsers match, as written. A mock is not one: it takes its folder's visibility. */
110
+ const EXACT_OVERRIDE_EXTENSIONS = Object.freeze([".md", ".csv"]);
111
+
101
112
  /**
102
- * Text whose extension is written exactly as `TEXT_KINDS` lists it, the only
103
- * paths the privacy parsers take an exact override for. `Budget.CSV` is a
104
- * sheet, but it takes its folder's visibility. @param {unknown} path
113
+ * Text whose extension is written exactly as the privacy parsers match it, the
114
+ * only paths they take an exact override for. `Budget.CSV` is a sheet, but it
115
+ * takes its folder's visibility, and so does every `.html` mock: one line the
116
+ * parsers refuse makes the whole manifest unreadable. @param {unknown} path
105
117
  */
106
118
  function takesExactOverride(path) {
107
- return Object.prototype.hasOwnProperty.call(TEXT_KINDS, writtenExtensionOf(path));
119
+ return EXACT_OVERRIDE_EXTENSIONS.includes(writtenExtensionOf(path));
108
120
  }
109
121
 
110
122
  module.exports = {
111
123
  NOTE,
112
124
  SHEET,
125
+ MOCK,
113
126
  FILE,
114
127
  TEXT_KINDS,
115
128
  TEXT_EXTENSIONS,
@@ -117,6 +130,7 @@ module.exports = {
117
130
  kindOf,
118
131
  isNotePath,
119
132
  isSheetPath,
133
+ isMockPath,
120
134
  isTextFilePath,
121
135
  takesExactOverride,
122
136
  withoutTextExtension,
@@ -54,6 +54,12 @@ const DAY = /^\d{4}-\d{2}-\d{2}$/;
54
54
  * },
55
55
  */
56
56
  const FLAGS = Object.freeze({
57
+ "areas.metrics-in-browser": {
58
+ label: "Area metrics in the browser",
59
+ description: "The Areas page works its metrics out in the browser from the sheets, as before the gateway served them: the rollback while the gateway's readings settle in.",
60
+ added: "2026-12-01",
61
+ expires: "2026-12-15",
62
+ },
57
63
  "mail.in-notes": {
58
64
  label: "Mail in notes",
59
65
  description: "Gmail is copied into the person's notes again, so new mail starts a Tex check-in at once.",
@@ -67,13 +73,6 @@ const FLAGS = Object.freeze({
67
73
  expires: "2027-02-21",
68
74
  staff: true,
69
75
  },
70
- "files.app-reads-in-objects": {
71
- label: "App reads in objects",
72
- description: "The app's previews, peeks, mail and admin note reads go through the gateway to the workspace object, not through Convex.",
73
- added: "2026-11-29",
74
- expires: "2027-02-26",
75
- staff: true,
76
- },
77
76
  "files.app-trash-list-in-objects": {
78
77
  label: "Trash list in objects",
79
78
  description: "The app's Trash page lists the trash from the workspace object through the gateway, not from Convex.",
@@ -104,6 +103,13 @@ const FLAGS = Object.freeze({
104
103
  added: "2026-11-29",
105
104
  expires: "2027-02-26",
106
105
  },
106
+ "projects.redesign": {
107
+ label: "Projects page redesign",
108
+ description: "The Projects page leads with how many projects there are and where, each Board column says its count, and every project shows its rank, percent and owner.",
109
+ added: "2026-12-04",
110
+ expires: "2027-01-03",
111
+ staff: false,
112
+ },
107
113
  });
108
114
 
109
115
  const FLAG_MODES = Object.freeze(["off", "people", "everyone"]);
@@ -63,11 +63,25 @@ const EVERYONE = "everyone";
63
63
  const NAME = "[a-z0-9][a-z0-9-]{0,23}";
64
64
  const NAME_RE = new RegExp(`^${NAME}$`);
65
65
  const PERSON = "@[a-z0-9][a-z0-9-]{0,63}";
66
- const MAIL_KINDS = ["note", "ask", "interrupt"];
66
+ const MAIL_KINDS = ["note", "ask", "interrupt", "ack", "close", "topic"];
67
67
  /** The kinds written with a tag; a note is written without one. */
68
- const TAGGED_KINDS = ["ask", "interrupt"];
68
+ const TAGGED_KINDS = ["ask", "interrupt", "ack", "close", "topic"];
69
+ /**
70
+ * Lines that are about a thread rather than a message in it (`projects/mail-threading`, draft 3, 2026-12-02): `ack`
71
+ * ("noted", "thanks"), `close` and `topic` (an opener's new topic). They wake nobody, answer nobody and are never
72
+ * scored; each names its thread with `[re <at>]`.
73
+ */
74
+ const SILENT_KINDS = ["ack", "close", "topic"];
75
+ /**
76
+ * A thread opener's topic, at the very start of its text: `[topic: Memory to staging] The ask itself`. It is part of
77
+ * the text, not a tag, so every reader built before threads (an app in a store, Tex's copy of this file) still reads
78
+ * the line, topic and all.
79
+ */
80
+ const TOPIC_RE = /^\[topic: ([^\]\n]{1,80})\](?: |$)/;
81
+ /** The longest topic, in characters. */
82
+ const MAX_TOPIC = 80;
69
83
  const LINE_RE = new RegExp(
70
- `^- (\\S+) (${NAME}|${PERSON})(?: \\(([^()\\n]{1,40})\\))? (?:(joined)|to (${NAME})(?: \\[(ask|interrupt)\\])?(?: \\[used (\\d{1,3})%\\])?(?: \\[re (\\S+?)\\])?: ?(.*))$`
84
+ `^- (\\S+) (${NAME}|${PERSON})(?: \\(([^()\\n]{1,40})\\))? (?:(joined|left)|to (${NAME})(?: \\[(ask|interrupt|ack|close|topic)\\])?(?: \\[used (\\d{1,3})%\\])?(?: \\[re (\\S+?)\\])?: ?(.*))$`
71
85
  );
72
86
  /** The most a `[used N%]` tag says: a bot's whole week. */
73
87
  const MAX_USED = 100;
@@ -86,9 +100,11 @@ function findMailBlock(text) {
86
100
  }
87
101
 
88
102
  /**
89
- * Every entry, oldest first: `{ at, from, app, kind: "joined" | "mail", to,
103
+ * Every entry, oldest first: `{ at, from, app, kind: "joined" | "left" | "mail", to,
90
104
  * mailKind, text, start, end }`, where `mailKind` is `"note" | "ask" |
91
- * "interrupt"` on a mail and null on a join. Lines the parser does not
105
+ * "interrupt"` on a mail and null on a join or a leave. A `left` line is written when
106
+ * an agent leaves the note's mail (`write { action: "mail", args: { leave: true } }`);
107
+ * a parser from before it skips the line, as it skips any line it does not know. Lines the parser does not
92
108
  * recognise are skipped: people may edit the file by hand.
93
109
  */
94
110
  function parseMail(text) {
@@ -113,7 +129,7 @@ function parseMail(text) {
113
129
  at: match[1],
114
130
  from: match[2],
115
131
  app: match[3] ?? null,
116
- kind: match[4] ? "joined" : "mail",
132
+ kind: match[4] ?? "mail",
117
133
  to: match[4] ? null : match[5],
118
134
  mailKind: match[4] ? null : match[6] ?? "note",
119
135
  used: match[4] || match[7] === undefined || Number(match[7]) > MAX_USED ? null : Number(match[7]),
@@ -134,9 +150,56 @@ function parseMail(text) {
134
150
  blanks = 0;
135
151
  last = null;
136
152
  }
153
+ nameThreads(events);
137
154
  return { block, events };
138
155
  }
139
156
 
157
+ /**
158
+ * A thread's id from its opener's time: `t_` and four letters or digits, stable for as long as the line is there, so
159
+ * nothing extra is written to the note and every line ever sent already has one. FNV-1a, which is plenty for the
160
+ * few hundred threads one note holds; two openers that land on one id are told apart by order (`nameThreads`).
161
+ */
162
+ function threadIdOf(at, salt = 0) {
163
+ let hash = 0x811c9dc5;
164
+ const source = salt === 0 ? String(at) : `${at}#${salt}`;
165
+ for (let index = 0; index < source.length; index += 1) {
166
+ hash ^= source.charCodeAt(index);
167
+ hash = Math.imul(hash, 0x01000193) >>> 0;
168
+ }
169
+ return `t_${(hash % 1679616).toString(36).padStart(4, "0")}`;
170
+ }
171
+
172
+ /** The topic at the start of a message's text, or null. */
173
+ function topicOf(text) {
174
+ const match = TOPIC_RE.exec(typeof text === "string" ? text : "");
175
+ return match === null ? null : match[1].trim() || null;
176
+ }
177
+
178
+ /**
179
+ * Each mail line's `thread` (its own id when it opens one, its opener's when it answers one) and an opener's `topic`.
180
+ * A reply whose opener is not in the note (edited away by hand) opens a thread of its own, so no line is lost.
181
+ */
182
+ function nameThreads(events) {
183
+ const byAt = new Map();
184
+ const taken = new Set();
185
+ for (const event of events) {
186
+ if (event.kind !== "mail") continue;
187
+ const root = event.replyTo === null ? undefined : byAt.get(event.replyTo);
188
+ if (root !== undefined) {
189
+ event.thread = root.thread;
190
+ event.topic = null;
191
+ continue;
192
+ }
193
+ let salt = 0;
194
+ let id = threadIdOf(event.at);
195
+ while (taken.has(id)) id = threadIdOf(event.at, (salt += 1));
196
+ taken.add(id);
197
+ event.thread = id;
198
+ event.topic = SILENT_KINDS.includes(event.mailKind) ? null : topicOf(event.text);
199
+ if (!byAt.has(event.at)) byAt.set(event.at, event);
200
+ }
201
+ }
202
+
140
203
  /**
141
204
  * A name an agent may join as: lower case, spaces become dashes, anything
142
205
  * else dropped; `null` when nothing usable is left or it is `everyone`.
@@ -223,8 +286,8 @@ function appendMail(text, entry) {
223
286
  const app = entry?.app ? appName(entry.app) : null;
224
287
  const who = app ? `${from} (${app})` : from;
225
288
  let line;
226
- if (entry?.kind === "joined") {
227
- line = `- ${at} ${who} joined`;
289
+ if (entry?.kind === "joined" || entry?.kind === "left") {
290
+ line = `- ${at} ${who} ${entry.kind}`;
228
291
  } else {
229
292
  const to = entry?.to ?? EVERYONE;
230
293
  if (!NAME_RE.test(to)) return { error: `mail.to must be "${EVERYONE}" or a name that joined` };
@@ -319,10 +382,24 @@ function newFor(events, name, since) {
319
382
  );
320
383
  }
321
384
 
385
+ /**
386
+ * The names in the note's mail now: everyone whose newest join or leave line is a join, in the order they first joined.
387
+ * A name that left and joined again is in; one that left is out (Grok Bot, 2026-12-04: a left join stops counting).
388
+ */
389
+ function joinedNames(events) {
390
+ const last = new Map();
391
+ for (const event of Array.isArray(events) ? events : []) {
392
+ if (event?.kind === "joined" || event?.kind === "left") last.set(event.from, event.kind);
393
+ }
394
+ const order = [];
395
+ for (const event of Array.isArray(events) ? events : []) if (event?.kind === "joined" && !order.includes(event.from)) order.push(event.from);
396
+ return order.filter((name) => last.get(name) === "joined");
397
+ }
398
+
322
399
  /** One entry as an agent reads it. */
323
400
  function describeEntry(event) {
324
401
  const who = event.app ? `${event.from} (${event.app})` : event.from;
325
- if (event.kind === "joined") return `- ${event.at} ${who} joined`;
402
+ if (event.kind === "joined" || event.kind === "left") return `- ${event.at} ${who} ${event.kind}`;
326
403
  const body = event.text.split("\n").join(`\n${CONTINUATION}`);
327
404
  const tag = TAGGED_KINDS.includes(event.mailKind) ? ` [${event.mailKind}]` : "";
328
405
  const used = typeof event.used === "number" ? ` [used ${event.used}%]` : "";
@@ -349,7 +426,7 @@ function askDepth(events, from) {
349
426
  const openFor = (ask, who) => ask.from !== who && (ask.to === who || ask.to === EVERYONE) && !ask.answeredBy.has(who);
350
427
  const deepestOpenFor = (who) => asks.reduce((max, ask) => (openFor(ask, who) ? Math.max(max, ask.depth) : max), 0);
351
428
  for (const event of events) {
352
- if (event.kind !== "mail") continue;
429
+ if (event.kind !== "mail" || SILENT_KINDS.includes(event.mailKind)) continue;
353
430
  const sender = event.from;
354
431
  // The depth comes from what was open when the ask was sent, so it is read before this message closes anything.
355
432
  const depth = 1 + deepestOpenFor(sender);
@@ -369,7 +446,12 @@ function askDepth(events, from) {
369
446
  function openAsk(events) {
370
447
  const open = [];
371
448
  for (const event of events) {
372
- if (event.kind !== "mail") continue;
449
+ // An ask to a name that left the note's mail waits on nobody any more.
450
+ if (event.kind === "left") {
451
+ for (let index = open.length - 1; index >= 0; index -= 1) if (open[index].to === event.from) open.splice(index, 1);
452
+ continue;
453
+ }
454
+ if (event.kind !== "mail" || SILENT_KINDS.includes(event.mailKind)) continue;
373
455
  for (let index = open.length - 1; index >= 0; index -= 1) {
374
456
  const ask = open[index];
375
457
  const fromAsked = ask.to === EVERYONE ? event.from !== ask.from : event.from === ask.to;
@@ -382,6 +464,11 @@ function openAsk(events) {
382
464
 
383
465
  module.exports = {
384
466
  openAsk,
467
+ joinedNames,
468
+ SILENT_KINDS,
469
+ MAX_TOPIC,
470
+ threadIdOf,
471
+ topicOf,
385
472
  MAIL_INFO,
386
473
  EVERYONE,
387
474
  MAIL_KINDS,
@@ -2,7 +2,8 @@
2
2
 
3
3
  import type { CommentChange, CommentsBlock } from "./comments.cjs";
4
4
 
5
- export type MailKind = "note" | "ask" | "interrupt";
5
+ /** `ack`, `close` and `topic` are about a thread (`SILENT_KINDS`): they wake nobody and answer nobody. */
6
+ export type MailKind = "note" | "ask" | "interrupt" | "ack" | "close" | "topic";
6
7
 
7
8
  export interface MailEvent {
8
9
  at: string;
@@ -10,8 +11,9 @@ export interface MailEvent {
10
11
  from: string;
11
12
  /** The app an agent wrote from, or null for a person. */
12
13
  app: string | null;
13
- kind: "joined" | "mail";
14
- /** `everyone` or a joined name; null for a join. */
14
+ /** `left`: the name left the note's mail (`write { action: "mail", args: { leave: true } }`). */
15
+ kind: "joined" | "left" | "mail";
16
+ /** `everyone` or a joined name; null for a join or a leave. */
15
17
  to: string | null;
16
18
  /** `note` when untagged; null for a join. */
17
19
  mailKind: MailKind | null;
@@ -19,6 +21,10 @@ export interface MailEvent {
19
21
  used: number | null;
20
22
  /** The time of the message this one answers, `[re <at>]`: its thread's root; null when it answers nobody. */
21
23
  replyTo: string | null;
24
+ /** The thread a mail line is in (`t_8f2`): its own id when it opens one; absent on a join. */
25
+ thread?: string;
26
+ /** An opener's topic (`[topic: …]` at the start of its text); null on a reply or an opener without one. */
27
+ topic?: string | null;
22
28
  text: string;
23
29
  /** The entry's lines in the file, `[start, end)`. */
24
30
  start: number;
@@ -27,7 +33,11 @@ export interface MailEvent {
27
33
 
28
34
  export declare const MAIL_INFO: "mail";
29
35
  export declare const EVERYONE: "everyone";
30
- export declare const MAIL_KINDS: readonly ["note", "ask", "interrupt"];
36
+ export declare const MAIL_KINDS: readonly ["note", "ask", "interrupt", "ack", "close", "topic"];
37
+ export declare const SILENT_KINDS: readonly ["ack", "close", "topic"];
38
+ export declare const MAX_TOPIC: 80;
39
+ export declare function threadIdOf(at: string, salt?: number): string;
40
+ export declare function topicOf(text: string): string | null;
31
41
  export declare const MAX_ASK_DEPTH: 3;
32
42
  export declare const MAX_PER_PAIR_PER_HOUR: 20;
33
43
  export declare const MAX_USED: 100;
@@ -39,11 +49,13 @@ export declare function appWithOwner(raw: unknown, owner: unknown): string | nul
39
49
  export declare function splitApp(signed: unknown): { app: string | null; owner: string | null };
40
50
  export declare function appendMail(
41
51
  text: string,
42
- entry: { at?: string; from: string; app?: string | null; kind: "joined" | "mail"; to?: string; text?: string; mailKind?: MailKind; used?: number | null; replyTo?: string | null },
52
+ entry: { at?: string; from: string; app?: string | null; kind: "joined" | "left" | "mail"; to?: string; text?: string; mailKind?: MailKind; used?: number | null; replyTo?: string | null },
43
53
  ): { changes: CommentChange[]; error?: undefined } | { error: string; changes?: undefined };
44
54
  export declare function stripMail(text: string): string;
45
55
  export declare function newFor(events: MailEvent[], name: string, since: string | null): MailEvent[];
46
56
  export declare function describeEntry(event: MailEvent): string;
57
+ /** The names in the note's mail now: whose newest join or leave line is a join. */
58
+ export declare function joinedNames(events: readonly MailEvent[]): string[];
47
59
  export declare function pairCount(
48
60
  events: MailEvent[],
49
61
  from: string,
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Mail threads: where each thread in one mail note stands (`projects/mail-threading/about.md`, draft 3, approved
3
+ * 2026-12-02 by Sayo through Billy and by Seyi through Grok Bot).
4
+ *
5
+ * A thread is an opener and its replies (`[re <opener's time>]`, one level, `mail.cjs`). Its id is `t_` and four
6
+ * characters taken from the opener's time (`mail.cjs` `threadIdOf`), so nothing is stored beside the note: every
7
+ * state below is read again from the note's own lines, and the note stays the record.
8
+ *
9
+ * - An opener to one named reader is an **ask**: it waits on that reader. An opener to everyone is a **note**: nobody
10
+ * owes a reply and it is never scored (Billy's rule, 2026-12-01).
11
+ * - A reply from the reader the thread waits on, back to the asker or to everyone, sets it **answered**.
12
+ * - A reply that names another reader (`to: <bot>`) sets it **waiting** on that reader.
13
+ * - A `close` line sets it **closed**; a later reply (not an ack) opens it again.
14
+ * - An `ack` reply changes nothing and wakes nobody. A `topic` line from the opener renames the thread, the old topic
15
+ * kept in the note above it (Q1).
16
+ * - A note thread, or an answered one, with no new line for 24 hours is closed by itself (Q2). An ask still waiting
17
+ * never is: it shows as the longest wait instead.
18
+ *
19
+ * - At launch, old mail is sorted (Dev2, 2026-12-03: "categorize old messages and rethread them, or archive them"): an
20
+ * ask with no topic, opened before `THREADS_LAUNCH_AT` and quiet for a day (`ARCHIVE_QUIET_MS`, as notes close themselves), is **closed as archived**
21
+ * (`archived: true`); one that moved more recently is carried over and keeps waiting as a thread. The note's lines
22
+ * are never changed: this is a reading, so the whole history stays in the note.
23
+ *
24
+ * Every state carries the time it was reached (`since`), so a roll-up can say how long a thread has waited.
25
+ *
26
+ * Pure, CommonJS with its types beside it, read by the gateway, the app and Tex's copy of the shared code.
27
+ */
28
+
29
+ "use strict";
30
+
31
+ const mail = require("./mail.cjs");
32
+
33
+ const { EVERYONE, MAX_TOPIC, SILENT_KINDS } = mail;
34
+
35
+ /** How long a note thread or an answered one stays open with nothing new (Seyi, 2026-12-02: was 7 days). */
36
+ const AUTO_CLOSE_MS = 24 * 60 * 60 * 1000;
37
+ /** When threads launched: an untitled ask opened before this is old mail, sorted by `archiveOld`. */
38
+ const THREADS_LAUNCH_AT = "2026-12-03T15:47:00.000Z";
39
+ /** How long an old untitled ask must have been quiet to be archived rather than carried over. */
40
+ const ARCHIVE_QUIET_MS = 24 * 60 * 60 * 1000;
41
+ /** How many open threads a refusal names, newest first, before "N more" (Hermes, 2026-12-02). */
42
+ const REFUSAL_LIST = 5;
43
+
44
+ const isName = (to) => typeof to === "string" && to !== "" && to !== EVERYONE;
45
+
46
+ /**
47
+ * Every thread in a note's parsed mail (`parseMail(...).events`), oldest opener first:
48
+ * `{ id, at, from, to, kind: "ask"|"note", topic, excerpt, state: "open"|"waiting"|"answered"|"closed", waitingOn,
49
+ * since, lastAt, replies, closedBy, reason, auto, answeredAt }`. `answeredAt` is when an ask was first answered (null
50
+ * until then), for the time-to-answer metric. `excerpt` is the opener's first words, for a thread from before
51
+ * topics. `now` is a time in milliseconds, for the auto-close.
52
+ */
53
+ function threadsOf(events, now = Date.now()) {
54
+ const threads = new Map();
55
+ for (const event of Array.isArray(events) ? events : []) {
56
+ // A name that left the note's mail is waited on no longer: its threads stay open, for their opener to close or send
57
+ // on, and stop counting as waiting in every check-in and roster (Grok Bot, 2026-12-04).
58
+ if (event?.kind === "left") {
59
+ for (const thread of threads.values()) {
60
+ if (thread.state === "waiting" && thread.waitingOn === event.from) Object.assign(thread, { state: "open", waitingOn: null, since: event.at });
61
+ }
62
+ continue;
63
+ }
64
+ if (event?.kind !== "mail" || typeof event.thread !== "string") continue;
65
+ let thread = threads.get(event.thread);
66
+ if (thread === undefined) {
67
+ const ask = isName(event.to);
68
+ thread = {
69
+ id: event.thread,
70
+ at: event.at,
71
+ from: event.from,
72
+ to: event.to,
73
+ kind: ask ? "ask" : "note",
74
+ topic: event.topic ?? null,
75
+ excerpt: excerptOf(event.text),
76
+ state: ask ? "waiting" : "open",
77
+ waitingOn: ask ? event.to : null,
78
+ since: event.at,
79
+ lastAt: event.at,
80
+ replies: 0,
81
+ closedBy: null,
82
+ reason: null,
83
+ auto: false,
84
+ answeredAt: null,
85
+ };
86
+ threads.set(event.thread, thread);
87
+ // A silent line that opens a thread of its own (its opener edited away) is listed, closed, and changes nothing.
88
+ if (SILENT_KINDS.includes(event.mailKind)) Object.assign(thread, { state: "closed", waitingOn: null, closedBy: event.from });
89
+ continue;
90
+ }
91
+ step(thread, event);
92
+ }
93
+ const list = [...threads.values()];
94
+ for (const thread of list) autoClose(thread, now);
95
+ for (const thread of list) archiveOld(thread, now);
96
+ return list;
97
+ }
98
+
99
+ /** One reply moves its thread. */
100
+ function step(thread, event) {
101
+ thread.lastAt = later(thread.lastAt, event.at);
102
+ if (event.mailKind === "ack") return;
103
+ if (event.mailKind === "topic") {
104
+ // Only the opener renames a thread (Q1); anybody else's line is kept in the note and changes nothing.
105
+ if (event.from === thread.from) thread.topic = topicText(event.text) ?? thread.topic;
106
+ return;
107
+ }
108
+ if (event.mailKind === "close") {
109
+ Object.assign(thread, { state: "closed", waitingOn: null, since: event.at, closedBy: event.from, reason: event.text || null, auto: false });
110
+ return;
111
+ }
112
+ thread.replies += 1;
113
+ const reopened = thread.state === "closed";
114
+ if (reopened) Object.assign(thread, { closedBy: null, reason: null, auto: false });
115
+ const set = (state, waitingOn) => {
116
+ if (state === "answered" && thread.answeredAt === null) thread.answeredAt = event.at;
117
+ if (thread.state === state && thread.waitingOn === waitingOn && !reopened) return;
118
+ Object.assign(thread, { state, waitingOn, since: event.at });
119
+ };
120
+ const fromAwaited = thread.waitingOn !== null && event.from === thread.waitingOn;
121
+ if (isName(event.to)) {
122
+ if (fromAwaited && event.to === thread.from) return set("answered", null);
123
+ if (event.to !== event.from) return set("waiting", event.to);
124
+ } else if (fromAwaited) {
125
+ return set("answered", null);
126
+ }
127
+ if (reopened) set(thread.waitingOn === null ? "open" : "waiting", thread.waitingOn);
128
+ }
129
+
130
+ function autoClose(thread, now) {
131
+ if (thread.state !== "open" && thread.state !== "answered") return;
132
+ const quietSince = Date.parse(thread.lastAt);
133
+ if (!Number.isFinite(quietSince) || !Number.isFinite(now) || now - quietSince < AUTO_CLOSE_MS) return;
134
+ Object.assign(thread, { state: "closed", waitingOn: null, since: new Date(quietSince + AUTO_CLOSE_MS).toISOString(), auto: true, closedBy: null, reason: "no new message for 24 hours" });
135
+ }
136
+
137
+ /** An untitled ask from before threads, quiet for `ARCHIVE_QUIET_MS`: closed as archived. (3 days left 2,200 open at 9:14 AM ET Dec 3.) */
138
+ function archiveOld(thread, now) {
139
+ if (thread.kind !== "ask" || thread.state !== "waiting" || thread.topic) return;
140
+ const opened = Date.parse(thread.at);
141
+ const quietSince = Date.parse(thread.lastAt);
142
+ if (!Number.isFinite(opened) || !Number.isFinite(quietSince) || !Number.isFinite(now)) return;
143
+ if (opened >= Date.parse(THREADS_LAUNCH_AT) || now - quietSince < ARCHIVE_QUIET_MS) return;
144
+ Object.assign(thread, { state: "closed", waitingOn: null, since: new Date(quietSince + ARCHIVE_QUIET_MS).toISOString(), auto: true, closedBy: null, reason: "archived: an untitled ask from before threads, quiet a day", archived: true });
145
+ }
146
+
147
+ const later = (a, b) => (Date.parse(b) > Date.parse(a) ? b : a);
148
+
149
+ /** A message's first words, for a thread with no topic: one line, at most `MAX_TOPIC` characters. */
150
+ function excerptOf(text) {
151
+ const line = String(text ?? "")
152
+ .replace(/^\[topic: [^\]\n]*\] ?/, "")
153
+ .split("\n")[0]
154
+ .replace(/\s+/g, " ")
155
+ .trim();
156
+ if (line.length <= MAX_TOPIC) return line;
157
+ const cut = line.slice(0, MAX_TOPIC - 1);
158
+ const space = cut.lastIndexOf(" ");
159
+ return `${(space > MAX_TOPIC / 2 ? cut.slice(0, space) : cut).trim()}…`;
160
+ }
161
+
162
+ /** A thread's name to show: its topic, else its opener's first words. */
163
+ const titleOf = (thread) => thread.topic ?? thread.excerpt;
164
+
165
+ /**
166
+ * A topic a sender passed, cleaned: one line, no brackets, at most `MAX_TOPIC`; or `{ error }` saying how to fix it.
167
+ */
168
+ function cleanTopic(raw) {
169
+ if (typeof raw !== "string") return { error: 'mail.topic is one line saying what this is about, such as "Memory to staging"' };
170
+ const topic = raw.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, " ").replace(/[[\]]/g, "").replace(/\s+/g, " ").trim();
171
+ if (topic === "") return { error: 'mail.topic is empty: say in a few words what this is about, such as "Memory to staging"' };
172
+ if (topic.length > MAX_TOPIC) return { error: `mail.topic is ${topic.length} characters; keep it to ${MAX_TOPIC}, one line` };
173
+ return { topic };
174
+ }
175
+
176
+ /** A topic line's text as the topic it sets, or null. */
177
+ function topicText(text) {
178
+ const found = cleanTopic(String(text ?? "").split("\n")[0]);
179
+ return found.error ? null : found.topic;
180
+ }
181
+
182
+ /** The open thread already called `topic` (case and spacing aside), or undefined: topics are unique among open threads. */
183
+ function openWithTopic(threads, topic) {
184
+ const key = (value) => String(value ?? "").toLowerCase().replace(/\s+/g, " ").trim();
185
+ return threads.find((thread) => thread.state !== "closed" && thread.topic !== null && key(thread.topic) === key(topic));
186
+ }
187
+
188
+ /** The open thread whose name shares the most words with `text`, when it shares at least two; else null. A suggestion only. */
189
+ function likelyThread(threads, text) {
190
+ const words = (value) => new Set(String(value ?? "").toLowerCase().match(/[a-z0-9][a-z0-9'-]{2,}/g) ?? []);
191
+ const said = words(text);
192
+ let best = null;
193
+ let bestScore = 1;
194
+ for (const thread of threads) {
195
+ if (thread.state === "closed") continue;
196
+ let score = 0;
197
+ for (const word of words(titleOf(thread))) if (said.has(word)) score += 1;
198
+ if (score > bestScore) {
199
+ best = thread;
200
+ bestScore = score;
201
+ }
202
+ }
203
+ return best;
204
+ }
205
+
206
+ /** `reply_to: "t_8f2" (Memory to staging)`, a thread as a refusal names it. */
207
+ const replyHint = (thread) => `reply_to: "${thread.id}" (${titleOf(thread)})`;
208
+
209
+ /**
210
+ * Why a new line with neither a topic nor a thread is refused, with the fix in the same words (draft 3, §2): the
211
+ * newest open threads in this note, at most five, then how many more; and the thread its words look like, if any.
212
+ */
213
+ function refusalText(threads, text) {
214
+ const open = threads.filter((thread) => thread.state !== "closed").sort((a, b) => Date.parse(b.lastAt) - Date.parse(a.lastAt));
215
+ const shown = open.slice(0, REFUSAL_LIST);
216
+ const more = open.length - shown.length;
217
+ const reply = shown.length === 0 ? "" : `, or reply in an open thread: ${shown.map(replyHint).join(", ")}${more > 0 ? `, and ${more} more (read them with fetch { args: { mail: "all" } })` : ""}`;
218
+ const likely = likelyThread(open, text);
219
+ const hint = likely === null ? "" : ` It looks like ${likely.id} (${titleOf(likely)}): pass reply_to: "${likely.id}" to file it there.`;
220
+ return `refused: every message in agent mail opens a thread or answers one. Add topic: "<what this is about>"${reply}, then send again.${hint}`;
221
+ }
222
+
223
+ module.exports = { AUTO_CLOSE_MS, ARCHIVE_QUIET_MS, THREADS_LAUNCH_AT, REFUSAL_LIST, threadsOf, titleOf, excerptOf, cleanTopic, openWithTopic, likelyThread, refusalText };
@@ -0,0 +1,41 @@
1
+ /** Types for `mailThreads.cjs`; see that file for the states and the reasons. */
2
+
3
+ import type { MailEvent } from "./mail.cjs";
4
+
5
+ export interface MailThread {
6
+ id: string;
7
+ /** The opener's time. */
8
+ at: string;
9
+ from: string;
10
+ to: string | null;
11
+ kind: "ask" | "note";
12
+ topic: string | null;
13
+ /** The opener's first words, for a thread with no topic. */
14
+ excerpt: string;
15
+ state: "open" | "waiting" | "answered" | "closed";
16
+ waitingOn: string | null;
17
+ /** When the thread reached its state. */
18
+ since: string;
19
+ lastAt: string;
20
+ replies: number;
21
+ closedBy: string | null;
22
+ reason: string | null;
23
+ /** Closed by itself after 24 quiet hours. */
24
+ auto: boolean;
25
+ /** When an ask was first answered; null until then. */
26
+ answeredAt: string | null;
27
+ /** Closed at launch as old mail: an untitled ask from before threads, quiet a day. */
28
+ archived?: boolean;
29
+ }
30
+
31
+ export declare const AUTO_CLOSE_MS: number;
32
+ export declare const ARCHIVE_QUIET_MS: number;
33
+ export declare const THREADS_LAUNCH_AT: string;
34
+ export declare const REFUSAL_LIST: number;
35
+ export declare function threadsOf(events: readonly MailEvent[], now?: number): MailThread[];
36
+ export declare function titleOf(thread: MailThread): string;
37
+ export declare function excerptOf(text: string): string;
38
+ export declare function cleanTopic(raw: unknown): { topic: string; error?: undefined } | { error: string; topic?: undefined };
39
+ export declare function openWithTopic(threads: readonly MailThread[], topic: string): MailThread | undefined;
40
+ export declare function likelyThread(threads: readonly MailThread[], text: string): MailThread | null;
41
+ export declare function refusalText(threads: readonly MailThread[], text: string): string;