Pins and names each client thread with what is due, links every thread working on a client, and keeps a side pane open with the client's tasks, tracked time…

The plugins every Massmarket teammate runs in Claude Code. They update themselves: once installed, each new release reaches your computer on its own (Claude Code checks for updates when a session starts, and the new version loads the next time you open it).
| Plugin | What it does |
|---|---|
mm-hooks | Keeps the Massmarket worklog hook on this computer current. It only updates a hook the installer already set up; it never installs one, and never touches your token, your tracked folders or your settings. It also keeps the time tracker extension current in Google Chrome: when a session starts it writes the published release it carries into the folder Chrome loads the tracker from, and the tracker (0.11.5 and later) reloads itself within 5 minutes. It writes only into a folder Chrome lists as the tracker's unpacked install, only when that folder holds the tracker (its exact key) at a lower version, never into a git working copy, and never where a profile that loads it has Developer mode off; manifest.json goes last, and nothing in the folder is deleted. At most once a day it also tells Claude when a work Chrome profile (one signed in with an @massmarket.ai account) used in the last 7 days has no tracker installed, naming it by that address, and when Developer mode is off where the tracker is loaded. A profile with no @massmarket.ai account is never named or counted, and no address is written anywhere. It reads Chrome's settings on this computer only and sends nothing anywhere. It also keeps both Massmarket plugins current where Claude Code's own plugin auto-update is off: at most every 6 hours, in the background after a session starts, it reads each plugin's latest version from this repository and, for a plugin installed at user scope that is behind, runs claude plugin marketplace update massmarket and then claude plugin update <plugin> --scope user. Where Claude Code's auto-update is fully on it leaves the update to Claude Code and steps in only after the same new version has waited 2 hours. It never installs a plugin you do not have, never turns on one you turned off, never downgrades, never accepts a marketplace-declared install command, and never writes your settings; it records what it did in ~/.claude/mm-hooks/plugin-sync.json and plugin-update.log. Set MM_PLUGIN_SELF_UPDATE=0 to turn it off. |
mm-bridge | It shows who needs you in a strip above the prompt in every thread and in a side pane (and says who holds a client's reply drafts once someone has picked them up), names and pins each client's thread, and never sends anything to a client. A client's thread is pinned while something of it is due within the next 24 business hours, and unpinned once it is clear. Each client has one chip: in its own thread when it has one (Do it here), otherwise in the thread you are working in; the strip in the other threads says where it is. When something new arrives for one of your clients, the bridge updates that client's thread for you, the same way Update thread does, except that it never picks up the reply drafts: it shows them, and a teammate can still take them. It waits until it has seen the same thing for 10 minutes, and until the reply drafts are ready or two hours have passed since it first saw the client's message. It never sends into a thread you used in the last 10 minutes, sends at most 3 such updates at a time and 12 an hour, and sends none on a computer whose time-tracking hook is older than 0.11.5. A client whose thread has been quiet for more than 7 business days gets its update in that same thread: no new thread is started for it. Right after Claude is asked to start a new thread for that client, its old thread is left alone while the new one starts. A client keeps its thread until you archive or delete that thread. If you use two Claude profiles on this computer, a client whose thread is in the other profile keeps it: in this profile its row offers Start thread, and nothing is started or sent for it by itself until you are back in that profile. A client with no linked thread first gets back the newest open thread that began with its own [mm-link] marker; a thread whose title only looks like the client never counts. Type /mm auto off to stop these updates. A client with no thread waits for you to press Start. A thread that gets long is compacted by Claude Code instead of being replaced. Starting a new thread always takes your own words: Start on a client's row and typing /mm start <client> put "Start <client>'s thread" in your prompt box, and Start missing threads (or /mm start all) puts "Start the missing client threads" there; press Enter to send it, or type those words yourself. Claude then starts each thread, and the app asks you to allow each one. A draft already in your prompt box is never written over: the button tells you what to send instead. No cards are put up, and nothing starts a thread by itself. Each request starts at most 8 threads, without picking up their reply drafts, and the new thread links to its client by the [mm-link] marker its first message opens with. The strip's button is Start missing threads; with none missing it reads All threads started. The pane has the same button when two or more clients need a thread. Type /mm to open the list. Open thread and Update thread take you to the thread by opening its link with your computer's own link opener. A client whose reply drafts a teammate holds is listed under "With a teammate" and is not pinned. A client whose only items were due before Wednesday, October 14, 2026 is listed under "Older", so nothing drops off the list without a trace; everything still open since then stays on the list until it is closed. A pin you take off by hand stays off until something new arrives for that client, or until what it is for goes overdue: then the thread is pinned again, once (take it off again after that and it stays off). After you send or discard a reply draft, the list updates within seconds. A press whose refresh meets a server error from the Onboarding Wizard, or no answer, asks once more before it says it couldn't refresh the list. A thread linked automatically stays linked once you send or close a reply through its pane or a route in that thread; anything else, type /mm link <client> in it. A thread the bridge linked by itself moves to the client's newest thread (one that opened for that client, or whose sessions worked on that client alone); a thread you linked yourself stays linked. Claude can relink a client when you ask, as long as the bridge (not you) made the old link. For the founder, a reply that waits for his OK is on his list whoever owns the client. For the founder and the PMs, the pane also lists "New people" above it: someone who wrote to us and whom no project matched, newest first, with what to check first and a Source link. Route to project (pick the project, then Route), Start project and Not client mail (for a HighLevel Directory lead: Mark handled and Not client mail) each make one call to the Onboarding Wizard; the person leaves the list once it answers, otherwise the row says what it answered. Nothing of theirs goes to Claude, and an Onboarding Wizard that does not send them yet shows no such section. Type /mm rc on to give each pinned thread Remote Control automatically, and take it off again when the thread is unpinned if the bridge turned it on; off unless you turn it on. Since 0.6.0 every thread you work on a client in is linked to that client: the client's first thread is its primary thread (pinned and named as above), and any other is a second thread, never pinned, renamed or sent anything, whose pane says which thread holds the reply package. A thread is linked when it loads the client's project skill, opens with the client's [mm-link] marker, or you link it; a skill load never takes a client from another thread. The side pane opens by itself in each such thread, and again on each surface you open the thread on, with a Tracking part at the top: the task the thread declared, the client's tasks and threads today, the time tracked to the client across all of them today and this week (the week is refreshed every 30 minutes), and leverage when the Onboarding Wizard shows it to you. Close the pane and it stays closed in that thread until the thread moves to another project. It never opens by itself in a run with MM_UNATTENDED=1 or one whose first prompt begins SINGLE-SESSION, and opening it never picks up, claims or holds a reply package. The status line shows the client, the task and this thread's time today. A thread that has had two of your prompts without a client shows a strip with Track to <client> (when its title names one), Massmarket internal and Not client work; the first two leave a note for Claude to load the right skill. The time numbers appear once the Onboarding Wizard serves them; until then the pane says they are not available yet. Since 0.7.0 the Tracking part also says which line of the client's quote the thread's work counts toward, lists the lines worked on today, and, when the work matches no line, shows a strip with the closest lines, New scope, Hour bank and Not now, and asks Claude once to ask you. /mm line <key>, /mm propose <title> -- <why> and /mm bank record the answer; a new line itself is added only when the client says yes. |
Run the Massmarket installer from the time tracker extension. It adds this marketplace, installs both plugins and turns on auto-update. By hand, in a terminal:
claude plugin marketplace add Massmarket-AI/claude-plugins
claude plugin install mm-hooks@massmarket
claude plugin install mm-bridge@massmarket
then set "autoUpdate": true on extraKnownMarketplaces.massmarket in ~/.claude/settings.json. Without it, mm-hooks 1.0.11 and later still bring both plugins up to date on their own, within about 6 hours of a release.
Anyone on the pms or web-builders team can release. A release runs on every teammate's computer at their next session, so treat it like a deploy: test it on your own machine first.
node scripts/release.mjs copies the worklog hook from the onboarding-wizard origin/main, bumps the version of each plugin that changed, validates, runs the bridge's tests, scans for secrets, commits and pushes. --dry-run does everything but the commit and push. A push that does not bump a version reaches nobody: the version number is the release.
With MM_EXT_TOKEN set to your own time tracker token, it also carries the published time tracker release: it asks GET /api/ext/version what is published, downloads that zip, and keeps it only if its manifest names exactly that version under the tracker's key (scripts/carry-extension.mjs). Without the token the carried build stays as it is. Publish the extension first (tools/publish.mjs in the massmarket-time-tracker repository), then release the plugin.
main keeps its full history: force pushes and deleting main are blocked (the org's "Keep history on main" rule), so every release stays on record and any version can be restored with a normal commit.
hooks/register.tsx 7099 lines1import type { Elements, EngineInterface, Register } from 'claude-code'
2
3import type { MmBand, MmFolds, MmLineAsk, MmLineChoice, MmNotice, MmPeople, MmPerson, MmProject, MmQueue, MmSession, MmSuggestion, MmTrack, MmView } from '../types'
4
5import {
6 INTERNAL_OPS, INTERNAL_PROJECTS, buildLists, byDue, isNewerVersion, isVersion, checkingTitle, internalProjects, cleanName, cleanTitle, clearedTitle, clientInTitle, clientMarkdown, clockText, feedClients, fastState, holdBanner, isClosingRoute, isUuid, mailLookbackHours, needsLine, noteText, pinsNow,
7 peopleRows, routeChoices, routePage, routedText, sourceLink, threadTitle, threadTitleShort, titleFor, withHolder,
8 asksMarkdown, heldInternal, openAsks, shownText,
9} from './queue'
10import type { Feed, FeedThread, KnownClient, QueueItem } from './queue'
11import {
12 LABEL, PANE_SENTENCE, THREAD_ID, autoLinkFate, autoLinkFor, bandWords, buttonLabel, claimText, clientThreads, declaredOther, foldGroups, hasWaiting, isStillOpenRow, kickoffText, onlyClients,
13 newerThreadFor, openCommand, ownerOf, platformOf, recommend, rowButtons, rowDetail, rowFor, rowGroups, sharedThreads, signatureOf, secondThreadSentence, startKickoff, threadLink, titleLooksLike, titleSuggestion,
14 REFRESH_FAILED, asksForPrep, autoUpdatable, autoUpdateDue, autoUpdateTarget, bandText, chipTitle, ownPackage, seenNow, waitingText,
15 START_ALL_MAX, startAllKickoff, startAllLabel, startMissingLabel, AWAY_REASON, markedThreads, START_ALL_WORDS, startWords, startFillSaid, kickoffsAnswer,
16} from './threads'
17import type { AppThread, Fold, Kickoff, Pairs, Recommendation, Replaced, Row, RowButton, RowState, FirstSeen, Sent } from './threads'
18import {
19 INTERNAL_NAME, INTERNAL_NOTE, NUDGE_AFTER, NUDGE_INTERNAL, NUDGE_NONE, NUDGE_TEXT, SKILL_KEY, afterPersonClose, clientName, displayName, kindOf, mergeCurrent, mergeTime, opensBySelf,
20 parseClientTime, parseSkillMap, pressNote, secondLine, skillName, taskFrom, thisThread, titleForClaude, trackLabel, trackLines, trackStatus, weekIsDue,
21 LINE_BANK, LINE_CHOICES, LINE_KEY, LINE_LATER, LINE_NEW, TICKET8, askNote, asksForLine, asksInSession, bankLine, bankNote, declareLineText, forClaude, lineAskKey, lineAskText,
22 lineButton, lineNote, lineOfThread, linkedText, newScopeNote, noBankText, proposalArgs, proposedText, statusLineTitle, taskLabel, ticketOf,
23} from './track'
24import type { ClientTime, Current, How, ProjectKind, ScopeLine, SkillEntry, ThreadLine, TimeProject, TimeRecord } from './track'
25
26// The Massmarket bridge.
27// Pinned threads are each person's to-do list: a client's thread pins itself and its name says what is
28// due and when; opening it shows the drafts in a side pane and leaves a short note for Claude.
29//
30// Rob, 2026-10-12: "There should be a process that should already be looking to see what threads exist and
31// deciding whether we should start a new one or not, and then making it really easy to pick up." So a
32// client's existing thread links itself (a thread whose Claude Code session declared that client), each row
33// of the Needs-you pane carries a recommendation, and its buttons act on it.
34//
35// Rob, 2026-10-12, on seeing it: "I think it should be 'update thread', 'open thread', or 'start thread'...
36// depending on whether you know what we should do." So a row has ONE action, chosen by its state: Start
37// (no thread, or the existing one is old or long), Update (the thread lacks what is waiting now), or Open
38// (it already has it). And: "How do we open this panel up in other threads where it's not already open?"
39// So every desktop thread carries one line above the prompt with a button that opens the list.
40// (0.5.14, Rob 2026-10-16: "I don't really think we even need to be able to open list. We just need to be able to
41// start missing threads or start all threads. It should just pretty much always be 'start missing threads.'") So
42// that button is Start missing threads now, always drawn; /mm still opens the list.
43//
44// ⛔ NEVER BY ITSELF. Linking, pinning and renaming are the only things a sync does (0.6.0: and opening this thread's
45// pane for its current project, read only; see "(0.6.0) every client thread linked" further down). A message goes into a
46// thread only from a button the person pressed in the pane or a /mm command the person typed: updateThread
47// and claimThread, reached from `press` and from `runCommand` when it runs for the person. That message
48// starts a model turn in the client's thread: the one paid moment the bridge causes, and the person asked
49// for it. (0.5.2, R4/R5, Rob 2026-10-13) A chip is minted by itself too, in every running thread, for a
50// client that needs a new thread (`autoChips`): a chip starts nothing until the person clicks it.
51// ⛔ (0.5.11, Rob 10-15: "I think we should start updating threads automatically") ONE exception, and only while
52// auto is on (/mm auto, the switch auto-start has had since 0.5.7): after each sync, a client on the person's own
53// list whose linked thread lacks what is waiting gets Update's message (in words that never take the package:
54// kickoffText's `auto`, the marker first), through Update's own send and guards, once this bridge has seen the
55// client unchanged for AUTO_QUIET_MS and its drafts are ready (or AUTO_NO_DRAFTS_MS have passed since it first saw
56// the mail waiting), within AUTO_UPDATES_PER_SYNC from one sync and AUTO_UPDATES_PER_HOUR and AUTO_UPDATES_PER_DAY
57// on this computer, never into a thread the person used in the last AUTO_IDLE_MS, never from a thread into itself,
58// and only where the time-tracking hook counts it as automatic (`autoUpdates`). It stamps nothing and claims
59// nothing: an automatic send is nobody's act (R11).
60// (0.5.23, Rob 2026-10-21: "change auto-starts to update the older thread") A linked thread older than 7 business
61// days, whose row says Start, gets the same update by itself, under the same guards: by itself, an old thread is
62// updated, never replaced. (0.5.24) A client with no linked thread got its Start card by itself, and a
63// person's Start put that card up too; (0.5.25) no card at all: see below.
64// (0.5.23, the cause of the refusals of 10-19 and 10-20) Those starts were for clients whose thread was there all
65// along: the person works in two Claude profiles on this computer, the app answers "not found" for a thread of the
66// other profile, and the sync dropped the link. A link now ends only when its thread is archived or deleted: a
67// "not found" is checked against the app's own record of the thread on disk (`recordOf`). A thread of another
68// profile stays linked, and in this profile its client's row offers Start and nothing is started or sent by
69// itself (`away`). And a client with no linked thread gets back the newest open thread that opened with its own
70// [mm-link] marker (`markedThreads`), before anything is started for it.
71// ⛔ (0.5.24, Rob 2026-10-21: "build mm-bridge 0.5.24 so Start presses and automatic starts put up the Start card
72// directly, with no approval prompt first") The bridge never asks the app to start a thread (start_session
73// `user_asked`). The app starts one that way only on the person's own typed words to the model, and asked from
74// the bridge it raised an approval prompt and then refused. A Start press, /mm start, Start missing threads and a
75// client with no thread all put up the client's Start card (start_session `own_initiative`; spawn_task's chip
76// where the app has that): it starts nothing until the person clicks Start on it.
77// ⛔ (0.5.25, Rob 2026-10-22: "There's no point in having the 'Start missing threads' button if it generates a card
78// where clicking 'Claim' doesn't work... Maybe clicking the button just types 'start missing threads' into the
79// command line") No card any more. A Start press, Start missing threads, /mm start and /mm start all put the
80// person's own words in the prompt box (`fillStart`: "Start <client>'s thread", "Start the missing client
81// threads"); the person sends them, and on that turn the model asks the mm tool for the threads' `kickoffs` and
82// starts each with start_session `user_asked`. The bridge itself never calls start_session, and puts up no card by
83// itself: a client with no thread waits on its row's Start. `kickoffs` starts and sends nothing, so the model may
84// ask for it on any turn; the app lets start_session `user_asked` through only on a turn the person typed, and a
85// prompt a mod submits is not one (Claude.app 3.1623: its turn is not the person's), so Start never submits.
86// ⛔ CLAUDE CANNOT DO EITHER. The model can call the `mm` tool, and the tool runs the same `runCommand`:
87// there, and for a /mm command that did not come from the person's own prompt (a message from another
88// session, a scheduled task, a channel, another plugin), `update` and `start` are refused before
89// anything is read, called or written. The same for `link` in a thread that is already another
90// client's: only the person moves a thread from one client to another.
91// ⛔ A thread is one client's. Update never sends one client's kickoff into a thread linked to another,
92// and a thread that ran sessions for more than one client is never linked by itself, to either.
93// ⛔ A press acts on the thread its row showed, or on none. A link, an unlink record and a stamp are
94// written only after the message went.
95// ⛔ It only touches threads linked to a client. (0.5.2) A pin means "needs you" (R1): a client's thread is
96// pinned while something of it must be acted on within the next 24 business hours, with no cap; when the
97// client is clear its thread is unpinned whoever pinned it (R14), once per clear (0.5.3, `mm.cleared`: a
98// thread the person pins again after its client cleared stays pinned). Otherwise it only unpins a thread
99// it pinned itself, and never an internal project's thread (R18).
100// (0.5.19, Rob 10-20) One exception, only on a computer where the person typed /mm rc on: Remote Control
101// follows the pin on any thread (`rcFollowsPin`). It never switches off Remote Control it did not switch on.
102// ⛔ A thread the person unlinked never links itself again, and gets its own name back.
103// ⛔ A thread that linked itself gets the pin and the name, nothing more, until the person acts on it (0.6.0: its
104// pane also opens and draws its client part, read only, with no note for Claude and no pickup); and
105// the link is undone once (B3) its session declares another project too, unless the link was used for a
106// send (R11). (0.5.23) The feed no longer listing that thread's session is not enough: the feed lists only
107// the last 14 days.
108// ⛔ Where the app's thread list is not there (a terminal session, or an answer that is not a list of
109// threads), nothing about threads is changed and there is nothing for Update to act on.
110// ⛔ A link is never dropped only because its thread is missing from the app's list (the 60 most recent):
111// the app is asked for that thread by id, and only "no such thread" or "archived" drops it. An empty
112// list is this thread alone (the list leaves the calling thread out) and drops nothing at all.
113// (0.5.23) And "no such thread" drops it only where the app's own record of the thread agrees: none on disk,
114// or one that says archived, or one in this profile's own folder.
115// ⛔ Feed text and thread titles are data: ids must be uuids, names and titles are cleaned (./queue.ts). A
116// 200 that is not a feed is a failed call. The [mm-link] marker is the person's own prompt's alone.
117// ⛔ A client's link moves from one thread to another in two ways only: the person's /mm link, and a new
118// thread started from the bridge's own chip for that client (Start thread, /mm start). Never otherwise.
119// (0.6.0) A skill load or a band press links a thread only to a client that has no linked thread: it never moves one.
120// ⛔ A session reads its OWN context window, at most once in five minutes, and never another thread's.
121// ⛔ The band above the prompt draws from what is stored: it makes no feed call and no app call.
122// ⛔ The bridge reads nothing of a thread: no transcript, no events. A new thread that takes over from an
123// old one is asked, in its kickoff, to read that thread's last three messages itself.
124// ⛔ To take the person to a thread, ONE program is started: the system's own opener, with the app's own
125// link to that thread as its only argument besides the opener's own, and only because the person
126// pressed Open thread or Update thread or typed /mm update (openThread).
127//
128// Rob, 2026-10-13: "it takes quite a long time for anything to happen after we click a button to open the
129// list or update threads or anything." Every press waited on the feed (an HTTPS call to OW whose route reads
130// many tables) and a whole pass over the app's threads, some presses on two. So (0.5.1, S2) a press draws
131// its answer AT ONCE from what the row was drawn from: the last sync stored, the store, and the row's own
132// thread. The feed and the app are asked AFTER that, and the list is drawn again when they answer. A press
133// may take a feed this session read less than FEED_REUSE_MS ago, and a refresh that fails says so in one
134// line (L3). Update and Open ask the app one thing first: whether the row's thread is still there
135// (`storedPass`). Update refuses when the client's link, read from the store, is now another thread. And
136// Update, the one press that sends, reads the feed once before every send, drawing `Checking…` meanwhile
137// (M1): with no feed it sends nothing, with nothing waiting now it sends nothing, and otherwise its kickoff
138// is the client as the feed has it now; on a thread the bridge linked by itself, or one its row offered
139// with no link, that feed also says whether B3 has let the thread go, or a newer thread of the client's has
140// taken it (`updateThread`, `takenOver`). ⛔ Nothing that guards a send moved: a press acts on the thread its
141// row showed or on none, B3, a thread taken over and the second-send guards are asked before the send as
142// before, and every write is made over a fresh copy and checked again.
143
144const EXT = 'https://onboarding-wizard.massmarket.ai/api/ext'
145// Keep equal to .claude-plugin/plugin.json; scripts/release.mjs checks it.
146const VERSION = '0.7.0'
147/** The version that changes the person's thread list view once per machine (R15): it is recorded with the change. */
148const VIEW_VERSION = '0.5.2'
149const CLIENT_HEADER = { 'X-MM-Client': `mm-bridge/${VERSION}` }
150const VIEW = { plugin: 'mm-bridge', key: 'view' } as const
151const QUEUE = { plugin: 'mm-bridge', key: 'queue' } as const
152const NOTICE = { plugin: 'mm-bridge', key: 'notice' } as const
153const BAND = { plugin: 'mm-bridge', key: 'band' } as const
154const FOLDS = { plugin: 'mm-bridge', key: 'folds' } as const
155/** (New people) This thread's own presses on `New people`: the open picker, presses in flight, what OW refused. */
156const PEOPLE = { plugin: 'mm-bridge', key: 'people' } as const
157/** (0.6.0) This thread's Tracking part of the pane: its current project, the pane's title, the lines. */
158const TRACK = { plugin: 'mm-bridge', key: 'track' } as const
159/** (0.6.0) This session's own record: the person's prompts, a pane they closed, a SINGLE-SESSION run. */
160const SESS = { plugin: 'mm-bridge', key: 'sess' } as const
161/** (0.6.0) The band's line for a thread not tracked to a client yet. */
162const NUDGE = { plugin: 'mm-bridge', key: 'nudge' } as const
163/** (0.7.0) The band's line for a client's thread whose work matches no line on the quote. */
164const LINE = { plugin: 'mm-bridge', key: 'lineAsk' } as const
165const PANE_VIEW = 'mm-view'
166const PANE_QUEUE = 'mm-queue'
167const SYNC_MS = 5 * 60_000
168const TICK_MS = 60_000
169/** (0.5.3) How often a thread withdraws its own chips that are no longer wanted, from the store alone (`chipsPass`). */
170const CHIPS_PASS_MS = 15_000
171const LEASE_MS = 150_000
172const MAX_WRITES = 24
173const DAY_MS = 24 * 3_600_000
174/** A session's own pair (Claude Code session id → app thread) is kept this long after it last ran. */
175const PAIR_KEEP_MS = 30 * DAY_MS
176/** The most threads the store remembers an original title, or an unlink, for. */
177const REMEMBER_MAX = 300
178/** A link the person made or used stays pinned this long, ahead of the cap. Real hours: this is not a client's clock. */
179const ACTED_MS = DAY_MS
180/** The desktop app's own record of a thread is read only when it changed in this long. */
181const RECORD_MAX_AGE_MS = 30 * DAY_MS
182/** `local_<id>.json`: one record per thread, named by the app's thread id. */
183const RECORD_FILE = /^(local_[A-Za-z0-9_-]{1,100})\.json$/
184/** The most record files opened in one sync. */
185const RECORDS_PER_SYNC = 40
186const SESSION_ID = /^[A-Za-z0-9_-]{1,100}$/
187// (0.5.23) AUTO_MISSES and MISS_GAP_MS are gone: a link the bridge made by itself is no longer undone because the
188// feed's threads (the last 14 days) stop listing its thread. Its record keeps `miss` (always 0) for older versions.
189/** The most threads asked for by id in one sync: linked or pinned threads the app's list (its 60 most recent) left out. */
190const LOOKUPS_PER_SYNC = 10
191/** A chip the bridge minted is remembered this long: a thread started from it later than that is a thread like any other. */
192const CHIP_KEEP_MS = 30 * DAY_MS
193/** The most chips remembered at once. */
194const CHIPS_MAX = 250
195/** The most chips one thread mints by itself, soonest due first. */
196const AUTO_CHIPS_MAX = 5
197/**
198 * (0.5.4, C1-C3) The chips a thread mints by itself from this version on carry this mark. One without it (0.5.3's
199 * copy in every running thread) is withdrawn by the thread that minted it on its first pass (C6).
200 */
201const CHIP_GEN = 4
202/** (0.5.4, C3) A thread whose tick ran no longer ago than this is running: it can hold a chip. */
203const ALIVE_MS = 5 * 60_000
204/** (0.5.4, C3) A no-thread client's chip moves to the thread the person works in once they have worked elsewhere this long. */
205const HANDOVER_MS = 10 * 60_000
206/** (0.5.7) How long a session goes by its last look at which session tools the app gives it (`sessionTools`). */
207const TOOLS_EVERY_MS = 5 * 60_000
208/** (0.5.12) A client whose thread is being started is that session's alone this long (`mm.starting`); (0.5.25) claimed by `kickoffs`. */
209const STARTING_MS = 2 * 60_000
210/** (0.5.25) How long a kickoff the mm tool handed Claude (`mm.kickoffs`) can still link the thread that opens with it. */
211const HANDED_KEEP_MS = DAY_MS
212/** (0.5.25) The most handed kickoffs on record. */
213const HANDED_MAX = 100
214/**
215 * (0.5.11, Rob 10-15: update threads by itself) The most client threads this machine updates by itself in an hour, and in a day.
216 * (0.5.13, Rob 10-15: "12 updates an hour") The hour's was 6.
217 */
218const AUTO_UPDATES_PER_HOUR = 12
219const AUTO_UPDATES_PER_DAY = 40
220/**
221 * (0.5.13) The line saying a client was not updated because the hour's or the day's cap is reached is written to the
222 * notice log at most once per client in this long, across every running thread (`capNotice`, `mm.capLogged`).
223 */
224const CAP_LOG_EVERY_MS = 3_600_000
225/** (0.5.11) An update a session is about to send by itself is that session's alone this long (`mm.updating`). */
226const UPDATING_MS = 2 * 60_000
227/** (0.5.11, review of PR #15, F1) The most updates sent by itself from one sync: the rest wait for the next sync. */
228const AUTO_UPDATES_PER_SYNC = 3
229/** (0.5.11, review of PR #15, F5) A thread the person used this recently is not updated by itself: the next sync tries again. */
230const AUTO_IDLE_MS = 10 * 60_000
231/** (0.5.11, review of PR #15, F4) A session reads what the time-tracking hook is no more often than this. */
232const HOOK_CHECK_MS = 10 * 60_000
233/** (0.5.7) A band note (what a Start all came to; 0.5.7 to 0.5.23 also a thread started by itself) shows in every thread this long. */
234const NOTE_SHOW_MS = 15 * 60_000
235/**
236 * (0.5.7) What start_session's `background` carries, which a "fresh" session requires (at least 80 characters, the
237 * app's own schema): the brief itself is the client's kickoff, unchanged.
238 */
239const START_BACKGROUND =
240 'Opened by the Massmarket bridge (mm-bridge) for one client on the Needs-you list. The brief is the kickoff the bridge sends that client\'s thread; its [mm-link] marker links this thread to the client.'
241/** R10: how long a press, or a chip minted by itself, waits for the app before it says so. */
242const APP_WAIT_MS = 15_000
243/** R10: after the app did not answer a chip, or refused one, this thread mints none by itself for this long (or until its next turn). */
244const MINT_PAUSE_MS = 10 * 60_000
245/** (R9) A sync on record older than this is not a read the band may call all clear from. */
246const STALE_SYNC_MS = 3 * SYNC_MS
247/** A chip whose withdrawal fails this many times is forgotten. */
248const DISMISS_TRIES = 5
249/** A press on a row's button is in flight no longer than this: after it, the row takes a press again. */
250const PRESS_HOLD_MS = 30_000
251/** The system's opener is given this long to take a thread's link. */
252const OPEN_WAIT_MS = 10_000
253/**
254 * After a route call that can close something in this thread (R6), one sync runs this long after the last
255 * such call: at once (Rob, 2026-10-13), and calls made within the same second still make one sync.
256 */
257const ASK_WAIT_MS = 1_000
258/** A feed this session read may be taken for a press's refresh while it is younger than this (S2). */
259const FEED_REUSE_MS = 60_000
260/** A pickup view this session read is drawn at once, while it is read again, when it is younger than this. */
261const PICKUP_REUSE_MS = 60_000
262/** The most pickup views remembered. */
263const PICKUPS_MAX = 20
264/** What the pane says while it has nothing to draw yet: the list, or a client's pickup view. */
265const CHECKING = 'Checking…'
266/**
267 * (New people) Someone a press resolved stays off this computer's `New people` this long (`mm.peopleDone`), whatever
268 * a feed read before the press still says. Real time: it is not a client's clock. Past it, a person OW still lists
269 * as open is shown again.
270 */
271const PEOPLE_DONE_MS = 30 * 60_000
272/** (New people) The picker's first option: no project picked yet. */
273const PICK_NONE = 'none'
274/** (New people) The picker's options that turn to the page before or after this one (`routePage`): never a project's id. */
275const PICK_PREV = 'page-prev'
276const PICK_NEXT = 'page-next'
277/** (New people) The surfaces whose element table has a Select (the engine's `Elements`): the mobile app's has none yet. */
278const PICKER_SURFACES: ReadonlySet<string> = new Set(['terminal', 'desktop', 'vscode'])
279/**
280 * (New people) What a person can do with someone under `New people`, as OW's resolve route names it: `route`,
281 * `bootstrap` and `not_client` for an email; `handled` and `not_client` for a HighLevel Directory lead (OW refuses
282 * `route` and `bootstrap` for one).
283 */
284type PersonAction = 'route' | 'bootstrap' | 'handled' | 'not_client'
285/** (New people) The verb a refused press's line starts with: `Couldn't route: ...`. */
286const PERSON_VERB: Readonly<Record<PersonAction, string>> = { route: 'route', bootstrap: 'start a project', handled: 'mark it handled', not_client: 'mark it not client mail' }
287
288/**
289 * `[mm-link <project id>]`, counted only at the very start of a prompt: the message itself, or (0.5.8) the task
290 * the app's wrapper carries (`promptOf`). Never anywhere else in the text.
291 */
292const MARKER = /^\[mm-link ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]/
293/**
294 * (0.5.8) How the app hands a thread its first message when another session started it (read from the app's own
295 * code, 10-14; the hook builder saw the first form in a real thread):
296 * - a fresh thread, from start_session or from a card the person started:
297 * `Background (from the session that started this one):\n<background>\n\nTask:\n<prompt>`;
298 * - a fork: `Task (from the session that started this one):\n<prompt>`; an offer's brief has the fresh form inside that;
299 * - after the prompt, its notes line: `\n\nShared notes folder for this group of sessions (…): <path>`.
300 * Each wrapper counts only where the message begins.
301 */
302const WRAP_TASK = /^Task \([^)\n]{1,200}\):\n/
303const WRAP_BACKGROUND = /^Background \([^)\n]{1,200}\):\n[\s\S]*?\n\nTask:\n/
304const WRAP_NOTES = /\n\nShared notes folder for this group of sessions \([^\n]*$/
305/**
306 * (0.5.9) The app's own notes, put in front of a message it sends: each `<system-reminder>\n…\n</system-reminder>`,
307 * one per line, then a blank line, then the message (read from the app's own code, 10-15). A thread started while
308 * the session that started it already has linked sessions opens with one, `Linked sessions now (status, not an
309 * instruction): …`. On 10-15 a dozen threads started together: the first opened without it and its marker counted;
310 * every later one opened with it, before the wrapper, and none of their markers did.
311 */
312const NOTE_OPEN = '<system-reminder>\n'
313const NOTE_CLOSE = '</system-reminder>'
314/** (0.5.10) A note's close tag at the start of a line. */
315const LINE_CLOSE = /(?:^|\n)<\/system-reminder>/
316/** The most app notes taken off the front of one message. */
317const APP_NOTES_MAX = 10
318/**
319 * (0.5.9) The message after the app's notes in front of it. ⛔ Fails closed (review of 54a0437d, L4): each note runs
320 * from `<system-reminder>\n` to the FIRST `</system-reminder>`, which must begin a line and be followed by a blank
321 * line (then the message) or at once by the next note. Anything else (a close tag inside a line, a second open tag
322 * inside the note, CRLF, no close tag, more than APP_NOTES_MAX notes) gives the message back as it is: it begins
323 * with `<system-reminder>`, so neither the wrapper nor a marker is read in it.
324 * ⛔ (0.5.10, review of 0.5.9, finding 2) So does a message that, after its notes, still has a `</system-reminder>`
325 * at the start of a line: what looked like the message may be the rest of a note (probe D: a marker inside a
326 * note's body, after a line-start close tag and a blank line).
327 */
328function afterAppNotes(text: string): string {
329 let rest = text
330 for (let n = 0; n < APP_NOTES_MAX && rest.startsWith(NOTE_OPEN); n++) {
331 const close = rest.indexOf(NOTE_CLOSE)
332 if (close < 0 || rest[close - 1] !== '\n') return text
333 if (rest.slice(NOTE_OPEN.length, close).includes('<system-reminder>')) return text
334 const after = rest.slice(close + NOTE_CLOSE.length)
335 if (after.startsWith('\n\n')) return LINE_CLOSE.test(after.slice(2)) ? text : after.slice(2)
336 if (!after.startsWith(`\n${NOTE_OPEN}`)) return text
337 rest = after.slice(1)
338 }
339 return text
340}
341/**
342 * (0.5.8) The prompt a message carries: the message itself, or, when it begins with the app's wrapper, the task
343 * after it, its notes line taken off. `task`: it began `Task (…):`, the form the app sends as `auto-continuation`.
344 * (0.5.9) The app's own notes in front of it are taken off first: the message begins after them (`afterAppNotes`).
345 */
346function promptOf(text: string): { prompt: string; task: boolean } {
347 const body = afterAppNotes(text)
348 const task = WRAP_TASK.exec(body)
349 let rest = task ? body.slice(task[0].length) : body
350 const background = WRAP_BACKGROUND.exec(rest)
351 if (background) rest = rest.slice(background[0].length)
352 if (!task && !background) return { prompt: body, task: false }
353 return { prompt: rest.replace(WRAP_NOTES, ''), task: task !== null }
354}
355/**
356 * Where a prompt or a /mm command is the person's own: typed here (`composer`), sent from their phone or
357 * the web (`bridge`), or the app's own turn for them, as when it starts a thread from a chip (`sdk`).
358 * ⛔ Nothing else: not another Claude session's message (`peer`), a schedule, a channel or a plugin.
359 */
360const PERSON_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge', 'sdk'])
361/**
362 * (0.5.8) The app's own delivery of a started thread's first task, for a fork or an offer's brief. It counts for
363 * the marker only in the app's `Task (…):` wrapper (`promptOf`), and for nothing else.
364 */
365const STARTED_TASK_ORIGIN = 'auto-continuation'
366
367const NO_THREAD_LIST = 'The app\'s thread list is not available here.'
368/** What `link` from anything but the person says of a client the person linked to another thread (F4). */
369const alreadyHas = (client: string) => `${client} already has a thread. Only the person can move it: they type /mm link ${client} in the thread that should have it.`
370/** R10: what a press that makes a chip says before it asks the app for anything (the app before 10-14: spawn_task). */
371const MAKING_CHIP = (client: string) => `Making a chip for ${client}…`
372/** R10: what it says when the app does not answer that in APP_WAIT_MS. */
373const NO_ANSWER = (client: string) => `The app did not answer in 15 seconds, so no chip was made. Type /mm start ${client} in any thread.`
374/** (fix round 1, L10) What a second message to a client says while the first is still going out. */
375const STILL_GOING = (client: string) => `A message to ${client}'s thread is still going out. Check that thread before pressing again.`
376/** R10 (Opus, 10-13, decision 1): what Update or Claim says when the app has not confirmed its message in APP_WAIT_MS. */
377const NOT_CONFIRMED = (client: string) => `The app has not confirmed the message to ${client}'s thread yet. Check that thread before pressing again.`
378/** R15: said once in the pane, the time the thread list's view is changed on this machine. */
379const VIEW_NOTICE = 'Your thread list is now grouped by date, newest activity first, with pinned threads on top. Change it any time from the sidebar\'s filter menu.'
380const THREAD_GONE = 'That thread is no longer available. The list has been refreshed.'
381/** What Claude is told when it calls the tool with a verb only the person may use. */
382const ONLY_THE_PERSON = {
383 update: 'Only the person can do this: press Update thread in the pane or type /mm update <client>.',
384 start: 'Only the person starts a thread: they press Start thread in the pane or type /mm start <client>, which puts their words in the prompt box. On a turn the person typed to ask for it, call mm with "kickoffs <client>" (or "kickoffs" for every missing thread) and start each with start_session as it says.',
385} as const
386
387type Mcp = { content?: Array<{ type: string; text?: string }>; isError?: boolean }
388/** `internal` (0.5.2, R18): the pin is on an internal project's thread, which the bridge never unpins. */
389type Pin = { projectId: string; client: string; byUs: boolean; internal?: true }
390type Last = {
391 at: number
392 member: string
393 /** The clients that need the person now: what pins, and what the header and the band count. */
394 items: QueueItem[]
395 /** Clients whose reply drafts a teammate holds, and clients whose only items were due before the list's floor (LIST_FLOOR_MS, Wed 2026-10-14): listed, never pinned, never counted. */
396 teammate?: QueueItem[]
397 older?: QueueItem[]
398 /** (0.5.2, R8) Clients whose package waits for the server's check of our newer send: off the list, not pinned, not counted. */
399 checking?: QueueItem[]
400 pinned: number
401 recs: Record<string, Recommendation>
402 /** Every project id the last feed carried: the only ids an [mm-link] marker may name. */
403 projects?: string[]
404 error?: string
405 /** (New people) For the founder and a PM: who wrote to us with no project matched, newest first, worded at `at`. Absent: none. */
406 people?: MmPerson[]
407 /** (New people) What Route to project offers: kept only while somebody is under `New people`. */
408 routeTo?: MmProject[]
409}
410/** Every client the last sync listed, in any of its lists: what a button, a command or a thread's own pane may be about. */
411const listedIn = (last: Last | null | undefined): QueueItem[] => [
412 ...(Array.isArray(last?.items) ? last.items : []),
413 ...(Array.isArray(last?.teammate) ? last.teammate : []),
414 ...(Array.isArray(last?.older) ? last.older : []),
415 ...(Array.isArray(last?.checking) ? last.checking : []),
416]
417/**
418 * A pin the person took off a thread the bridge had pinned: when, and the newest time of each kind of
419 * thing its client had then. The thread is not pinned again until one of them is newer, or (0.5.14) until the
420 * client's act-by time passes when it was still ahead with the pin on. `seen`: the sync before the one that found
421 * the pin off, when the pin was still on as far as the bridge knew (a record an older version made has none: `at`
422 * stands in).
423 */
424type Unpinned = { at: number; mail: number; pkg: number; task: number; seen?: number }
425/**
426 * (0.5.3) The person went on in the client's linked thread while a chip for a new thread (R3, or R8's long-thread
427 * one) was waiting: in which thread, when, and the newest time of each kind of thing the client had then. Until
428 * something newer than both comes for the client, or its link moves, those chips are spent and none is minted.
429 */
430type ClaimedHere = { sid: string; at: number; newest?: { mail: number; pkg: number; task: number } }
431
432/**
433 * (0.5.3) Whether a claim in place still holds: the client is still linked to the thread it was made in, and
434 * nothing newer has come for the client since (each kind measured against the later of the claim and what the
435 * client had then: a task's time can be its due time, still ahead).
436 */
437function claimHolds(claim: ClaimedHere | undefined, projectId: string, links: Readonly<Record<string, string>>, last: Last | null): claim is ClaimedHere {
438 if (!claim || typeof claim !== 'object' || typeof claim.sid !== 'string' || !Number.isFinite(claim.at)) return false
439 if (links[projectId] !== claim.sid) return false
440 const it = listedIn(last).find(i => i.projectId === projectId)
441 if (!it) return true
442 for (const kind of ['mail', 'pkg', 'task'] as const) {
443 if ((Number(it.newest?.[kind]) || 0) > Math.max(Number(claim.newest?.[kind]) || 0, claim.at)) return false
444 }
445 return true
446}
447
448/**
449 * (0.5.3) A chip for a new thread that replaces the client's thread `sid`: R3's (minted while the client had it), or
450 * R8's long-thread one. Never R4's, for a client with no thread, and (0.5.4) never a `Do it here` chip.
451 */
452const replacesThread = (c: Chip, sid: string): boolean => c.need !== 'here' && (c.had === sid || c.need === 'long')
453/**
454 * (0.5.4, C3) What each running thread last said of itself: when its tick last ran, and when the person last wrote
455 * in it (their own prompt). The thread the person is working in now holds a no-thread client's chip.
456 */
457type Seen = Record<string, { tick: number; human?: number }>
458type Verb = RowButton
459/** A link the person made or used: which thread, and when. */
460type Acted = Record<string, { sid: string; at: number }>
461/**
462 * A chip the bridge minted for a client and the person has not started yet. A chip shows only in the
463 * thread that minted it, and only that thread's session can withdraw it, so the record says which.
464 * One live chip per client: minting another marks the earlier one `superseded`.
465 */
466type Chip = {
467 projectId: string
468 /** What its prompt carries (signatureOf): the thread started from it already has this. */
469 signature: string
470 /** The app's id for the chip, from its answer to the mint; '' when it gave none (it cannot be withdrawn then). */
471 taskId: string
472 /** The thread it was minted in. */
473 threadId: string
474 at: number
475 /** Its prompt exactly as minted: the thread that opens with this prompt was started from this chip. */
476 prompt: string
477 /** The thread the client was linked to when it was minted, if any: a link to any other thread since means the client has moved on. */
478 had?: string
479 superseded?: true
480 /** Withdrawals that failed so far. */
481 tries?: number
482 /** (0.5.2, R5) Minted by the thread itself, not from a press: withdrawn once the need it was minted for is gone. */
483 auto?: true
484 /**
485 * (0.5.2) What it was minted for: a new thread (`start`, R3/R4), or a new thread for a client still open after our
486 * reply whose thread is long (`long`, R8); (0.5.4, C1) or the client's kickoff run in its own thread (`here`).
487 */
488 need?: 'start' | 'long' | 'here'
489 /** (0.5.4) CHIP_GEN on a chip this version minted by itself. */
490 gen?: number
491 /** (0.5.4, C2/C3) The thread it is in, as the band names it (`threadTitleShort`), from that thread's title when it was minted. */
492 place?: string
493}
494/**
495 * A link the bridge made by itself and the person has not acted on: its thread, how many syncs in a row
496 * the feed has not listed it, and when the last of those was counted.
497 */
498type Auto = Record<string, { sid: string; miss: number; at?: number; made?: number }>
499/** What the app's record of a thread said when it was opened: its modified time then, and the session id if it gave one. */
500type Records = Record<string, { m: number; cli?: string }>
501/**
502 * The app's threads as one sync sees them. `complete` is false for an empty list (the app's list leaves the
503 * calling thread out, so a person with one open thread gets none): this thread is then the whole list, and
504 * ⛔ nothing may be dropped on its word.
505 */
506type Listed = { threads: AppThread[]; complete: boolean }
507/**
508 * One pass over a feed. `listed` is false where the app's thread list could not be had. `unseen` holds the
509 * linked or pinned threads the list left out and the app did not answer for: kept, and not acted on.
510 * `stored`: no pass was made. A press's answer drawn from what the last sync stored, `live` holding at most
511 * the row's own thread as the app answered for it by id (`storedPass`, S2).
512 */
513type Pass = { last: Last; live: Map<string, AppThread>; pairs: Pairs; listed: boolean; unseen: ReadonlySet<string>; stored?: true }
514/** Who ran a /mm command: the person, or anything else (the model through the tool, another session, a schedule, a plugin). */
515type By = 'person' | 'other'
516
517/**
518 * This session's thread, as the app answered `get_session self`, by the session's own id. In the app one
519 * module serves one session, so this holds one entry; keyed by the session, several sessions run against
520 * one store in a test (concurrency.test.ts) each know their own thread.
521 */
522const selves = new Map<string, string>()
523/**
524 * The presses in flight in this session, by client: when each began. A second press for a client whose
525 * first has not returned does nothing (Rob pressed Update, saw nothing happen, pressed again, and the
526 * thread got two messages).
527 */
528const pressing = new Map<string, number>()
529let pressCount = 0
530/** The one sync this session owes after a reply draft was sent or discarded in it (askSync): its timer, or none. */
531let askTimer: { cancel: () => void } | null = null
532/**
533 * What this session's Update sent into a thread, by client and thread: the kickoff's signature. Asked before
534 * every Update beside what is stored, so a second press never sends the same kickoff into the same thread,
535 * even when the store refused every write after the first went (review of 79cbc596, F2).
536 */
537const sentHere = new Map<string, string>()
538/**
539 * The chips this session minted whose record the store refused, by client, thread and what they carry: a
540 * second press mints none while the store cannot say the chip is there. Forgotten once the record is written,
541 * or the client has moved on (M1).
542 */
543const mintedHere = new Set<string>()
544/** The chip mints in flight in this session (thread, client, signature): a second is not started while one waits for the app. */
545const minting = new Set<string>()
546/**
547 * Fix round 1, F4: every chip this session minted, by thread, client, id and time (`chipKey`), as this session
548 * knows it, whatever the store lost to another session's write: a record missing from the store is written back
549 * (the 1 to 3 second check, and every tick), never minted again, and still withdrawn. Forgotten once withdrawn.
550 */
551const ownChips = new Map<string, Chip>()
552const chipKey = (c: Chip): string => `${c.threadId}\n${c.projectId}\n${c.taskId}\n${c.at}`
553/**
554 * R10, by session: no chip is minted by itself before `until` (the app did not answer one, or refused it), and
555 * `atTurn`, the next turn in the thread tries again (the app did not answer one outside a turn). (Keyed by the
556 * session as `selves` is: several sessions run against one module in a test.)
557 */
558const mintPause = new Map<string, { until: number; atTurn: boolean }>()
559/** R15: the sessions that tried the view change already. */
560const viewTried = new Set<string>()
561/** The clients whose message (Update, Claim) is in flight in this session: their press stays held until the app answers it. */
562const sending = new Set<string>()
563/**
564 * The feed this session read last: when, and the sync record the pass over it stored (`wrote`, as stored). A
565 * press takes it again only while it is younger than FEED_REUSE_MS AND the store still holds that very
566 * record: no other session has synced since, so the list drawn from it is the list drawn now (S2).
567 */
568let recent: { at: number; feed: Feed; wrote: string } | null = null
569/** The pickup views this session read, by package: drawn at once for a press while they are read again. */
570const pickups = new Map<string, { at: number; text: string }>()
571/** (0.5.28, internal asks) The ask pages this session read, by ask: drawn at once for a press while they are read again, as `pickups`. */
572const askViews = new Map<string, { at: number; text: string }>()
573/** Each session's newest draw of its client part: an older one still reading its view draws nothing over it. */
574const viewDraws = new Map<string, number>()
575
576/**
577 * A write that failed after the person's act went (an Update's message, a chip): noted where the bridge's
578 * other errors go, the heartbeat file the timer's and registration's errors go to. Never swallowed silently.
579 */
580async function noteFailure($: EngineInterface, what: string, err: unknown): Promise<void> {
581 await beat($, { ok: false, writeError: short(`${what}: ${errorText(err)}`, 300) })
582}
583
584const textOf = (r: Mcp) => (r.content ?? []).filter(c => c.type === 'text').map(c => c.text ?? '').join('\n')
585const short = (s: string, n = 200) => s.replace(/\s+/g, ' ').slice(0, n)
586const errorText = (err: unknown) => short(err instanceof Error ? err.message : String(err), 300)
587/** The member's address as the feed gave it, kept to what an address is made of. */
588const memberText = (member: unknown) => (typeof member === 'string' ? member : '').replace(/[^A-Za-z0-9._%+@-]/g, '').slice(0, 120)
589/** A thread name the bridge wrote itself: never anybody's original title. */
590const isOurTitle = (title: string) => /^(?:🔴|🟡|✓)\s/u.test(title)
591
592async function mcpJson($: EngineInterface, server: string, tool: string, args: Record<string, unknown>): Promise<unknown> {
593 const r = (await $.mcp.call(server, tool, args)) as Mcp
594 const text = textOf(r)
595 if (r.isError) throw new Error(`${server}.${tool}: ${short(text)}`)
596 try {
597 return JSON.parse(text.slice(text.search(/[[{]/)))
598 } catch {
599 return text
600 }
601}
602
603/**
604 * R10 (Rob, 2026-10-13: Start on a client said nothing at all, and no chip came): an app call given at most `ms`
605 * to answer. `{ ok: false }` when it has not by then. The call itself goes on (nothing on `$` stops it): a caller
606 * that must know how it ended takes `work` itself later. A call that fails before then rejects as it would have.
607 */
608async function within<T>($: EngineInterface, work: Promise<T>, ms = APP_WAIT_MS): Promise<{ ok: true; value: T } | { ok: false }> {
609 const timer: { cancel?: () => void } = {}
610 const timeout = new Promise<{ ok: false }>(resolve => {
611 try {
612 const t = $.clock.after(ms, () => resolve({ ok: false }))
613 timer.cancel = () => t.cancel()
614 } catch {
615 // no timer here: the call is waited for, as in 0.5.1
616 }
617 })
618 const answered = work.then(value => ({ ok: true as const, value }))
619 // a call that fails after the wait ended has nobody left to tell
620 answered.catch(() => {})
621 try {
622 return await Promise.race([answered, timeout])
623 } finally {
624 timer.cancel?.()
625 }
626}
627
628/** mcpJson given at most APP_WAIT_MS: what the app answered, or `null` when it did not answer in time. */
629async function mcpJsonWithin($: EngineInterface, server: string, tool: string, args: Record<string, unknown>): Promise<unknown> {
630 const r = await within($, mcpJson($, server, tool, args))
631 return r.ok ? r.value : null
632}
633
634async function home($: EngineInterface): Promise<string> {
635 return (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
636}
637
638// ---------------------------------------------------------------- (0.5.5) a newer mod installed on this machine
639
640/** How often a thread looks for a newer mod. */
641const VERSION_EVERY_MS = 5 * 60_000
642/** The newest mm-bridge on this machine, by session, when it is later than this thread's own VERSION ('' otherwise), and when that was looked for. */
643const newerMod = new Map<string, { version: string; at: number }>()
644
645/**
646 * (0.5.5, Rob 10-14: the band "could also say when there's an update and they need to restart their Claude Code")
647 * Whether a later mm-bridge than the one this thread runs (VERSION) is installed on this machine. Two ways, both
648 * read, the later version wins:
649 * (a) the plugin cache: the version folders beside this plugin's own (`$.plugin.root`, the engine's word for the
650 * directory holding plugin.json, whose parent holds one folder per installed version), listed with `$.fs.list`;
651 * else `~/.claude/plugins/cache/massmarket/mm-bridge`;
652 * (b) the store: each running thread writes the version it runs (`mm.versions`); any reported in the last day.
653 * At most once in VERSION_EVERY_MS for a session. Nothing is called on the app.
654 */
655async function checkVersions($: EngineInterface): Promise<void> {
656 const now = await $.clock.now()
657 const id = await instanceId($)
658 const was = newerMod.get(id)
659 if (was && now - was.at < VERSION_EVERY_MS) return
660 const me = await knownSelf($)
661 const versions = await storeGet<Record<string, { version?: unknown; at?: unknown }>>($, 'mm.versions', {})
662 if (me && (versions[me]?.version !== VERSION || !(now - Number(versions[me]?.at) < DAY_MS / 24))) {
663 await patchStore<Record<string, { version?: unknown; at?: unknown }>>($, 'mm.versions', {}, fresh => {
664 fresh[me] = { version: VERSION, at: now }
665 for (const [sid, v] of Object.entries(fresh)) if (!v || !(now - Number(v.at) <= DAY_MS)) delete fresh[sid]
666 }).catch(() => {})
667 }
668 let newest = VERSION
669 for (const v of await installedVersions($)) if (isNewerVersion(v, newest)) newest = v
670 for (const v of Object.values(versions)) if (v && now - Number(v.at) <= DAY_MS && isNewerVersion(v.version, newest)) newest = String(v.version)
671 newerMod.set(id, { version: newest === VERSION ? '' : newest, at: now })
672}
673
674/** (0.5.5, way (a)) The versions of mm-bridge in the plugin cache: the folder names that are versions. [] when it cannot be listed. */
675async function installedVersions($: EngineInterface): Promise<string[]> {
676 const dirs: string[] = []
677 try {
678 const root = String($.plugin.root ?? '')
679 const last = root.split(/[\\/]/).pop() ?? ''
680 if (isVersion(last)) dirs.push(root.slice(0, root.length - last.length - 1))
681 } catch {
682 // no word on this plugin's own folder: the usual place below
683 }
684 const h = await home($)
685 if (h) dirs.push(`${h}/.claude/plugins/cache/massmarket/mm-bridge`)
686 for (const dir of dirs) {
687 try {
688 return (await $.fs.list(dir)).filter(e => e.kind === 'dir' && isVersion(e.name)).map(e => e.name)
689 } catch {
690 // the next place
691 }
692 }
693 return []
694}
695
696async function token($: EngineInterface): Promise<string> {
697 try {
698 const t = (await $.fs.read(`${await home($)}/.claude/mm-hooks/token`)).trim()
699 if (t) return t
700 } catch {
701 // no token file: handled below
702 }
703 throw new Error('not set up on this computer: no tracker token. Run the Massmarket installer from the time tracker extension.')
704}
705
706// The desktop app's session tools (list, rename, pin) exist only in its Code tab. Elsewhere (a terminal
707// session) the bridge still answers /mm, it just has no threads to pin or rename.
708async function desktopOnly<T>(work: () => Promise<T>, fallback: T): Promise<T> {
709 try {
710 return await work()
711 } catch {
712 return fallback
713 }
714}
715
716async function selfId($: EngineInterface): Promise<string> {
717 const cli = await instanceId($)
718 const known = selves.get(cli)
719 if (known) return known
720 // (R10: an app that does not answer in time leaves this thread unknown for now, as no app at all does)
721 const me = await desktopOnly(async () => (await mcpJsonWithin($, 'ccd_session_mgmt', 'get_session', { session_id: 'self' })) as AppThread | null, null)
722 if (!me?.sessionId) return ''
723 selves.set(cli, me.sessionId)
724 return me.sessionId
725}
726
727/** This thread's id as the timer already learnt it, or '': no app call is made to find it out. */
728async function knownSelf($: EngineInterface): Promise<string> {
729 return selves.get(await instanceId($)) ?? ''
730}
731
732async function instanceId($: EngineInterface): Promise<string> {
733 return String((await $.session.id()) ?? '')
734}
735
736/** A thread as the app answered it, kept to the fields the bridge uses; null for anything that is not an open thread. */
737function asThread(raw: unknown): AppThread | null {
738 const t = raw as Partial<AppThread> | null | undefined
739 if (!t || typeof t !== 'object' || typeof t.sessionId !== 'string' || !t.sessionId || t.isArchived) return null
740 // the app's own link to the thread, kept only when it is exactly that thread's (threadLink)
741 const link = threadLink(t as { sessionId: string; link?: unknown })
742 return {
743 sessionId: t.sessionId,
744 title: typeof t.title === 'string' ? t.title : '',
745 pinned: Boolean(t.pinned),
746 isArchived: false,
747 ...(typeof t.lastActivityAt === 'string' ? { lastActivityAt: t.lastActivityAt } : {}),
748 ...(link ? { link } : {}),
749 }
750}
751
752/**
753 * The app's open threads, or null where the list cannot be had: no app to ask (a terminal session), a call
754 * that failed, or an answer that is not a list. ⛔ null is "unknown", never "none".
755 *
756 * The app's list leaves the calling thread out, so a person with one open thread gets an empty list. An
757 * empty list from a call that worked, in a session that knows its own thread, is a list of one: this
758 * thread may link, pin and name itself. It is marked not `complete`: ⛔ an empty answer never drops a
759 * link, a pin, a title or a record, because it cannot be told from the app answering nothing by mistake.
760 */
761async function sessions($: EngineInterface): Promise<Listed | null> {
762 return desktopOnly<Listed | null>(async () => {
763 // (R10: an app that does not answer in time is no list: unknown, never none)
764 const others = await mcpJsonWithin($, 'ccd_session_mgmt', 'list_sessions', { limit: 60 })
765 if (!Array.isArray(others)) return null
766 const me = asThread(await mcpJsonWithin($, 'ccd_session_mgmt', 'get_session', { session_id: 'self' }))
767 if (others.length === 0) return me ? { threads: [me], complete: false } : null
768 const threads: AppThread[] = []
769 for (const raw of [me, ...others]) {
770 const t = asThread(raw)
771 if (t && !threads.some(x => x.sessionId === t.sessionId)) threads.push(t)
772 }
773 return { threads, complete: true }
774 }, null)
775}
776
777/**
778 * One thread, asked for by id: for a linked or pinned thread the app's list left out (the list holds its 60
779 * most recent). The thread when it is open; 'gone' ONLY when the app says there is no such thread or shows
780 * it archived; 'unknown' for any error, any other answer, or no app to ask. ⛔ Only 'gone' may drop a link,
781 * and (0.5.23) the sync's own pass drops one only on `askApp`'s finer answer, checked against the app's record.
782 */
783async function lookup($: EngineInterface, sid: string): Promise<AppThread | 'gone' | 'unknown'> {
784 const found = await askApp($, sid)
785 return found === 'archived' || found === 'notfound' ? 'gone' : found
786}
787
788/**
789 * (0.5.23) `lookup`, with its 'gone' told apart: 'archived' when the app shows the thread archived, 'notfound' when
790 * the app says it has no such thread. The app answers "not found" for a thread of the person's OTHER Claude profile
791 * on this computer as well (checked 2026-10-21: a thread open in one profile is "not found" from a session in the
792 * other), so the sync checks a 'notfound' against the app's own record of the thread before it drops anything.
793 */
794async function askApp($: EngineInterface, sid: string): Promise<AppThread | 'archived' | 'notfound' | 'unknown'> {
795 const noSuchThread = (text: string) => text.includes(sid) && /\bnot found\b/i.test(text)
796 try {
797 // (R10: no answer in time says nothing about the thread)
798 const asked = await within($, $.mcp.call('ccd_session_mgmt', 'get_session', { session_id: sid }) as Promise<Mcp>)
799 if (!asked.ok) return 'unknown'
800 const r = asked.value
801 const text = textOf(r)
802 if (r.isError) return noSuchThread(text) ? 'notfound' : 'unknown'
803 let raw: Partial<AppThread> | null
804 try {
805 raw = JSON.parse(text.slice(text.search(/[[{]/))) as Partial<AppThread> | null
806 } catch {
807 return 'unknown' // an answer that is not a thread says nothing about this one
808 }
809 if (!raw || typeof raw !== 'object' || raw.sessionId !== sid) return 'unknown'
810 return raw.isArchived ? 'archived' : (asThread(raw) ?? 'unknown')
811 } catch (err) {
812 // the call itself was refused: "no such thread" only when that is what the app said, about this thread
813 return noSuchThread(errorText(err)) ? 'notfound' : 'unknown'
814 }
815}
816
817/** Every project id a feed carries, uuids only: what an [mm-link] marker may name. */
818function feedProjects(feed: Feed): string[] {
819 const ids = new Set<string>()
820 const add = (id: unknown) => {
821 if (isUuid(id) && ids.size < 500) ids.add(id)
822 }
823 for (const m of feed.mail ?? []) add(m.project_id)
824 for (const d of feed.drafts ?? []) add(d.project_id)
825 // (fix round 1, F5) `start_now` too
826 for (const k of [feed.tickets?.overdue, feed.tickets?.due_today, feed.tickets?.due_soon, feed.tickets?.start_now]) for (const t of k ?? []) add(t.project_id)
827 for (const t of Array.isArray(feed.threads) ? feed.threads : []) add(t?.project_id)
828 // (0.5.28, internal asks) the project of each of the caller's asks: a thread that opens with its kickoff links to it
829 for (const a of Array.isArray(feed.asks) ? feed.asks : []) add(a?.project_id)
830 return [...ids]
831}
832
833/** The feed's `threads` rows that are usable: a uuid project and a session id the worklog hook could have sent. */
834function feedThreadsOf(feed: Feed): FeedThread[] {
835 return (Array.isArray(feed.threads) ? feed.threads : []).filter(t => t && isUuid(t.project_id) && typeof t.session_id === 'string' && SESSION_ID.test(t.session_id))
836}
837
838/** (0.5.17) A feed read that failed. `retryable`: OW answered 5xx, or the call got no answer at all. */
839class FeedReadError extends Error {
840 constructor(message: string, readonly retryable: boolean) {
841 super(message)
842 }
843}
844
845async function fetchFeed($: EngineInterface): Promise<Feed> {
846 const init = { headers: { Authorization: `Bearer ${await token($)}`, ...CLIENT_HEADER } }
847 // Mail back to 24 business hours before the list's floor, at least 168 and at most 720 business hours
848 // (mailLookbackHours, from this fetch's own now): it asks for 168 until Thu 2026-10-22 12:00 AM ET, and more
849 // only after that, once OW takes up to 720 (an OW that still caps at 168 answers 400)
850 const now = await $.clock.now()
851 const r = await $.http.fetch(`${EXT}/closeout?mail_hours=${mailLookbackHours(now)}`, init).catch((err: unknown) => {
852 throw new FeedReadError(errorText(err), true)
853 })
854 const failed = () => new FeedReadError(`closeout HTTP ${r.status}: ${short(r.text, 160)}`, r.status >= 500)
855 if (!r.ok) throw failed()
856 const feed = JSON.parse(r.text) as Feed | null
857 // ⛔ A 200 that is not a feed (neither `tickets` nor `mail` in it) is a failed call, not "nobody needs
858 // you": read as an empty feed it would take every pin off and rename every thread "clear".
859 if (!feed || typeof feed !== 'object' || !('tickets' in feed || 'mail' in feed)) throw failed()
860 recent = { at: await $.clock.now(), feed, wrote: '' }
861 return feed
862}
863
864/**
865 * The feed for a press's refresh (S2): the one this session read last, while it is younger than
866 * FEED_REUSE_MS and the store still holds the sync record made from it; else OW is asked again, with one
867 * more try (`fetchFeedTwice`).
868 */
869async function recentFeed($: EngineInterface): Promise<Feed> {
870 const r = recent
871 if (r?.wrote && (await $.clock.now()) - r.at < FEED_REUSE_MS && JSON.stringify(await storeGet<Last | null>($, 'mm.last', null)) === r.wrote) return r.feed
872 return fetchFeedTwice($)
873}
874
875/**
876 * (0.5.17; Rob, 10-19: OW's closeout feed answered 500 now and then, and a press that met one
877 * drew "Couldn't refresh the list") A press's refresh asks OW ONE more time, at once, when the first read got
878 * a 5xx or no answer at all. Anything else (a 4xx, a 200 that is not a feed, no tracker token) is not tried
879 * again, and neither is the second read: its failure is the press's, as before. Only `recentFeed` reads
880 * through here: ⛔ the timer's sync, and the reads that guard a send (Update, Claim, an update sent by
881 * itself), read once, as before.
882 */
883async function fetchFeedTwice($: EngineInterface): Promise<Feed> {
884 try {
885 return await fetchFeed($)
886 } catch (err) {
887 if (!(err instanceof FeedReadError && err.retryable)) throw err
888 return fetchFeed($)
889 }
890}
891
892async function storeGet<T>($: EngineInterface, key: string, fallback: T): Promise<T> {
893 const v = await $.store.get(key)
894 return (v === undefined || v === null ? fallback : v) as T
895}
896
897/** Keeps the newest `max` entries of a record the store holds (insertion order). */
898function capped<T>(record: Record<string, T>, max = REMEMBER_MAX): Record<string, T> {
899 const keys = Object.keys(record)
900 for (const k of keys.slice(0, Math.max(0, keys.length - max))) delete record[k]
901 return record
902}
903
904/**
905 * ⛔ THE ONE WAY a map or a list that sessions share is written to the store (B1, 2026-10-13: of fifteen
906 * threads started within a minute or two, two lost the link their [mm-link] marker wrote).
907 *
908 * Every desktop thread is a process of its own. The engine reads the store's file afresh on each get and
909 * writes ONE key on each set, under a lock (its own source, 2.1.295), so a set never touches another key.
910 * But a key is written whole: a session that writes back a map it read earlier takes away whatever another
911 * session put into it since (a dozen threads linking themselves; a sync whose pass takes seconds of app
912 * calls between its reads and its writes). So the key is read again immediately before the write, `change`
913 * makes ONLY its caller's own change to that fresh copy, and it is written at once: nothing is awaited
914 * between the read and the write. `change` answers false to write nothing; `stored` tells it whether the
915 * store held the key at all. A value of the wrong shape (an older version's, a damaged file) is read as
916 * `empty`.
917 * The store has no compare-and-set, so two sessions can still meet between that read and that write; what
918 * the person's own act wrote is checked again a moment later (`settleLater`).
919 */
920async function patchStore<T extends object>($: EngineInterface, key: string, empty: T, change: (fresh: T, stored: boolean) => boolean | void): Promise<T> {
921 const v = await $.store.get(key)
922 const shaped = v !== null && typeof v === 'object' && Array.isArray(v) === Array.isArray(empty)
923 const fresh = (shaped ? v : empty) as T
924 if (change(fresh, v !== undefined) === false) return fresh
925 await $.store.set(key, fresh)
926 return fresh
927}
928
929const sameValue = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)
930/** A copy of what a pass read, to tell later what the pass itself changed. */
931const copyOf = <T,>(v: T): T => JSON.parse(JSON.stringify(v ?? null)) ?? v
932
933/**
934 * What a pass changed in a map, entry by entry, made on the store's fresh copy (`patchStore`): `before` is
935 * the map as the pass read it, `after` as the pass left it. An entry the pass did not change is left as the
936 * store has it now, and so is one another session changed since the pass read it: a sync never takes back a
937 * link, a pin or a record written while it ran (it sees it on its next pass). Answers whether it changed
938 * anything. `only` makes just the entries it set (`set`) or just the ones it removed (`delete`): a record
939 * another depends on is written before it and removed after it (F2).
940 */
941function applyChanges<V>(fresh: Record<string, V>, before: Readonly<Record<string, V>>, after: Readonly<Record<string, V>>, only?: 'set' | 'delete'): boolean {
942 let changed = false
943 for (const k of new Set([...Object.keys(before), ...Object.keys(after)])) {
944 const had = Object.hasOwn(before, k) ? before[k] : undefined
945 const has = Object.hasOwn(after, k) ? after[k] : undefined
946 if (sameValue(had, has)) continue
947 if ((only === 'set' && has === undefined) || (only === 'delete' && has !== undefined)) continue
948 const now = Object.hasOwn(fresh, k) ? fresh[k] : undefined
949 if (!sameValue(now, had)) continue
950 if (has === undefined) delete fresh[k]
951 else fresh[k] = has as V
952 changed = true
953 }
954 return changed
955}
956
957/**
958 * (0.5.9, review of 54a0437d, L2) `applyChanges` for the links, where ⛔ a thread is one client's: a client this pass
959 * links to a thread that another client holds in the store's fresh copy (another session linked it while this pass
960 * ran) keeps what the store has for it.
961 */
962function applyLinkChanges(fresh: Record<string, string>, before: Readonly<Record<string, string>>, after: Readonly<Record<string, string>>): boolean {
963 const prior = { ...fresh }
964 applyChanges(fresh, before, after)
965 for (const [pid, sid] of Object.entries(fresh)) {
966 if (prior[pid] === sid) continue
967 if (!Object.entries(fresh).some(([other, held]) => other !== pid && held === sid)) continue
968 if (prior[pid] === undefined) delete fresh[pid]
969 else fresh[pid] = prior[pid] as string
970 }
971 return !sameValue(fresh, prior)
972}
973
974/** The same for a list of thread ids: what the pass took off it comes off, what it added goes on, the rest is the store's. */
975function applyListChanges(fresh: string[], before: readonly string[], after: readonly string[]): boolean {
976 const off = before.filter(x => !after.includes(x))
977 const on = after.filter(x => !before.includes(x) && !fresh.includes(x))
978 const kept = fresh.filter(x => !off.includes(x))
979 if (kept.length === fresh.length && !on.length) return false
980 fresh.splice(0, fresh.length, ...kept, ...on)
981 return true
982}
983
984/** 1 to 3 seconds, spread by the thread's own id: a dozen threads that start together do not check again together. */
985function settleMs(id: string): number {
986 // FNV-1a, then mixed, so ids that differ in one character land far apart
987 let h = 0x811c9dc5
988 for (const c of id) h = Math.imul(h ^ c.charCodeAt(0), 0x01000193) >>> 0
989 h = Math.imul(h ^ (h >>> 16), 0x45d9f3b) >>> 0
990 h = (h ^ (h >>> 16)) >>> 0
991 return 1_000 + (h % 2_001)
992}
993
994/**
995 * Once, 1 to 3 seconds after a write the person's own act made (a marker's link, a session's own pair), it is
996 * read again and written again if it is gone: what two sessions meeting between a read and a write can still
997 * lose (patchStore), and what a set the engine could not lock in time never wrote. Anything going wrong here
998 * is swallowed: the next sync is the fallback.
999 */
1000function settleLater($: EngineInterface, id: string, check: () => Promise<void>): void {
1001 try {
1002 $.clock.after(settleMs(id), () => void check().catch(() => {}))
1003 } catch {
1004 // no timer here: nothing is checked again
1005 }
1006}
1007
1008/**
1009 * The app's list of threads does not say which Claude Code session runs in each, and the feed names a
1010 * thread by that session id (it is what the worklog hook sends). So every session writes down its own
1011 * pair, and the session that syncs reads them all: a thread opened since this version was installed can
1012 * be matched to the client its session declared.
1013 */
1014async function recordSelf($: EngineInterface): Promise<void> {
1015 const app = await selfId($)
1016 const cli = await instanceId($)
1017 if (!app || !cli) return
1018 const now = await $.clock.now()
1019 const mine = (await storeGet<Pairs>($, 'mm.threads', {}))[cli]
1020 if (mine && mine.app === app && now - mine.at < DAY_MS) return
1021 const write = () =>
1022 patchStore<Pairs>($, 'mm.threads', {}, pairs => {
1023 // (0.5.9) when the pair was first written for this thread: written with every first write, and kept through
1024 // the daily rewrite. It is the thread's start for R1b (`threadStart`), so a thread the person goes back to is
1025 // not made newer by it. ⛔ A pair written before 0.5.9 has none and gets none (M1): its `at` is its last
1026 // rewrite, not when the thread started, and its thread's start stays unknown.
1027 const was = pairs[cli]
1028 if (!was || was.app !== app) pairs[cli] = { app, at: now, since: now }
1029 else pairs[cli] = typeof was.since === 'number' && Number.isFinite(was.since) ? { app, at: now, since: was.since } : { app, at: now }
1030 for (const [k, v] of Object.entries(pairs)) if (!v || now - v.at > PAIR_KEEP_MS) delete pairs[k]
1031 })
1032 // gone a moment later (another session's write met this one, or this one was never made): written again.
1033 // A pair the app's own record has since given another thread is the app's word, and is left.
1034 settleLater($, app, async () => {
1035 if (!(await storeGet<Pairs>($, 'mm.threads', {}))[cli]) await write()
1036 })
1037 await write()
1038}
1039
1040/** A thread linked by the person (a command, a button, a chip's first message) may link itself again later. */
1041async function forgetUnlink($: EngineInterface, sid: string): Promise<void> {
1042 await patchStore<Record<string, number>>($, 'mm.unlinked', {}, unlinked => {
1043 if (!(sid in unlinked)) return false
1044 delete unlinked[sid]
1045 })
1046}
1047
1048/** Where the desktop app keeps its record of each thread, by platform. The first folder that lists is used. */
1049async function recordRoots($: EngineInterface): Promise<string[]> {
1050 const roots: string[] = []
1051 const appData = await $.env.get('APPDATA')
1052 if (appData) roots.push(`${appData.replace(/[\\/]+$/, '')}\\Claude\\claude-code-sessions`)
1053 const h = await home($)
1054 if (h) roots.push(`${h}/Library/Application Support/Claude/claude-code-sessions`, `${h}/.config/Claude/claude-code-sessions`)
1055 return roots
1056}
1057
1058/**
1059 * The second source for "which Claude Code session runs in which thread": the desktop app's own records,
1060 * the `local_<id>.json` files under its `claude-code-sessions` folder. They exist for every thread, so a thread links itself without
1061 * having to be opened again first (Rob, 2026-10-12: "Why are none of them linked?").
1062 *
1063 * ⛔ READ-ONLY, through the plugin's own file access. From each record ONLY two things are taken: the
1064 * thread id and `cliSessionId`. Nothing else in a record is kept, logged or sent anywhere, and nothing
1065 * from these files leaves this computer: the pairs are only compared with the feed's session ids here.
1066 *
1067 * ⛔ IT OPENS ONLY WHAT IT NEEDS. A record is opened only when it is the record of a thread the app listed
1068 * in this sync, not archived, that has no pair in the store yet; at most RECORDS_PER_SYNC in one sync, the
1069 * most recently modified first; never one not modified in 30 days. What a record said (its session id, or
1070 * that it gave none) is remembered with its modified time, so it is not opened again until it changes,
1071 * and each pair found goes into the store with the pairs the sessions wrote. The folder is listed, not
1072 * read, to find those files. Any error at all (no such folder, a file that cannot be read or parsed, a
1073 * different shape) is swallowed: what each session wrote down about itself is then the only source.
1074 */
1075async function readRecords($: EngineInterface, now: number, live: ReadonlyMap<string, AppThread>, pairs: Pairs): Promise<void> {
1076 const paired = new Set(Object.values(pairs).map(p => p?.app))
1077 const need = new Set<string>()
1078 for (const s of live.values()) if (!s.isArchived && !paired.has(s.sessionId)) need.add(s.sessionId)
1079 if (!need.size) return
1080 const seen = await storeGet<Records>($, 'mm.records', {})
1081 /** What this pass learnt from the records it opened: the only entries it writes. */
1082 const learnt: Records = {}
1083 const found: Pairs = {}
1084 let opened = 0
1085 for (const root of await recordRoots($)) {
1086 const sep = root.includes('\\') ? '\\' : '/'
1087 /** The newest record on disk for each thread that needs one. */
1088 const newest = new Map<string, { path: string; mtimeMs: number }>()
1089 const walk = async (dir: string, depth: number): Promise<void> => {
1090 for (const entry of await $.fs.list(dir)) {
1091 const path = `${dir}${sep}${entry.name}`
1092 if (entry.kind === 'dir') {
1093 // records sit two folders down today; one more level is allowed for
1094 if (depth < 3) await walk(path, depth + 1).catch(() => {})
1095 continue
1096 }
1097 const app = entry.kind === 'file' ? RECORD_FILE.exec(entry.name)?.[1] : undefined
1098 if (!app || !need.has(app) || now - entry.mtimeMs > RECORD_MAX_AGE_MS) continue
1099 const had = newest.get(app)
1100 if (!had || entry.mtimeMs > had.mtimeMs) newest.set(app, { path, mtimeMs: entry.mtimeMs })
1101 }
1102 }
1103 try {
1104 await walk(root, 0)
1105 } catch {
1106 continue // this platform's folder is not here: try the next
1107 }
1108 const unread = [...newest].filter(([app, file]) => seen[app]?.m !== file.mtimeMs).sort((a, b) => b[1].mtimeMs - a[1].mtimeMs)
1109 const said: Array<{ app: string; cli: string; mtimeMs: number }> = []
1110 for (const [app, file] of unread.slice(0, RECORDS_PER_SYNC)) {
1111 let cli = ''
1112 try {
1113 const record = JSON.parse(await $.fs.read(file.path)) as { sessionId?: unknown; cliSessionId?: unknown }
1114 // the record must be this thread's own, and name a session id the hook could have sent
1115 if ((record.sessionId === undefined || record.sessionId === app) && typeof record.cliSessionId === 'string' && SESSION_ID.test(record.cliSessionId)) {
1116 cli = record.cliSessionId
1117 }
1118 } catch {
1119 // unreadable, not JSON, too large: this record gives no pair
1120 }
1121 opened++
1122 learnt[app] = seen[app] = cli ? { m: file.mtimeMs, cli } : { m: file.mtimeMs }
1123 if (cli) said.push({ app, cli, mtimeMs: file.mtimeMs })
1124 }
1125 // A record just opened is the app's own word: it wins over a pair a session wrote down. Oldest first,
1126 // so where two records name one session the more recently modified thread has it.
1127 // (0.5.9, M1) dated the day it was found, with no `since`: when its thread started is not known from it
1128 for (const r of said.sort((a, b) => a.mtimeMs - b.mtimeMs)) found[r.cli] = { app: r.app, at: now }
1129 // A record opened earlier whose pair has since dropped out of the store gives it back without being
1130 // opened again, unless another thread has that session by now.
1131 for (const [app, file] of newest) {
1132 const was = seen[app]
1133 if (was?.cli && was.m === file.mtimeMs && !pairs[was.cli] && !found[was.cli]) found[was.cli] = { app, at: now }
1134 }
1135 break
1136 }
1137 if (opened) {
1138 await patchStore<Records>($, 'mm.records', {}, records => {
1139 // each written last, so the cap keeps the records most recently opened
1140 for (const [app, said] of Object.entries(learnt)) {
1141 delete records[app]
1142 records[app] = said
1143 }
1144 capped(records)
1145 })
1146 }
1147 if (Object.keys(found).length) {
1148 Object.assign(pairs, found)
1149 // over a fresh copy: another session may have recorded itself since this pass began
1150 await patchStore<Pairs>($, 'mm.threads', {}, fresh => void Object.assign(fresh, found))
1151 }
1152}
1153
1154/**
1155 * Every known pair: what each session wrote down about itself, and what the app's records gave. The
1156 * records are looked at only when the feed names at least one session to match.
1157 */
1158async function allPairs($: EngineInterface, now: number, live: ReadonlyMap<string, AppThread>, feedThreads: readonly FeedThread[]): Promise<Pairs> {
1159 const pairs = await storeGet<Pairs>($, 'mm.threads', {})
1160 if (!feedThreads.length) return pairs
1161 try {
1162 await readRecords($, now, live, pairs)
1163 } catch {
1164 // no pairs from the app: the pairs each session records are the only source
1165 }
1166 return pairs
1167}
1168
1169/** (0.5.23) One of the app's record files on disk: where it is, its folder (one per Claude profile), when it last changed. */
1170type RecordFile = { path: string; dir: string; mtimeMs: number }
1171
1172/**
1173 * (0.5.23) The app's record files, listed (not read) once in a sync, and only when the sync needs one: for each thread
1174 * id, its files modified in the last RECORD_MAX_AGE_MS, newest first. Null when no platform's folder lists.
1175 */
1176async function listRecords($: EngineInterface, now: number): Promise<Map<string, RecordFile[]> | null> {
1177 for (const root of await recordRoots($)) {
1178 const sep = root.includes('\\') ? '\\' : '/'
1179 const found = new Map<string, RecordFile[]>()
1180 const walk = async (dir: string, depth: number): Promise<void> => {
1181 for (const entry of await $.fs.list(dir)) {
1182 const path = `${dir}${sep}${entry.name}`
1183 if (entry.kind === 'dir') {
1184 // records sit two folders down today (one folder per profile); one more level is allowed for
1185 if (depth < 3) await walk(path, depth + 1).catch(() => {})
1186 continue
1187 }
1188 const app = entry.kind === 'file' ? RECORD_FILE.exec(entry.name)?.[1] : undefined
1189 if (!app || now - entry.mtimeMs > RECORD_MAX_AGE_MS) continue
1190 const all = found.get(app) ?? []
1191 all.push({ path, dir, mtimeMs: entry.mtimeMs })
1192 found.set(app, all)
1193 }
1194 }
1195 try {
1196 await walk(root, 0)
1197 } catch {
1198 continue // this platform's folder is not here: try the next
1199 }
1200 for (const all of found.values()) all.sort((a, b) => b.mtimeMs - a.mtimeMs)hooks/queue.ts 1456 lines1// Pure queue logic for the Massmarket bridge: no `$`, so tests can call it directly.
2//
3// What is listed (Rob, 2026-10-20: "everything since last Thursday that wasn't closed should always show up
4// now, and we can keep it clean going forward"): everything still open whose due time is on or after
5// LIST_FLOOR_MS (Wed 2026-10-14 12:00 AM ET), however overdue, and everything not due yet, however far ahead.
6// (Until 2026-10-20 the cut was 3 business days back; Rob replaced it with LIST_FLOOR_MS.) That is:
7// - an unanswered client message (its reply is due 24 business hours after it arrived)
8// - a prepared reply package (drafts ready)
9// - a reply package the viewer picked up, with a draft not sent, like a prepared one
10// - a ticket with a date WE committed to (clients never set dates; SLA and phase dates are not promises
11// and do not list)
12// - for the founder alone: a reply package flagged for his OK, whoever owns the client (kind `ok`); one a
13// teammate sends only once its reply is due (0.5.1, R2: until then it is theirs to decide)
14// - (0.5.28, internal asks) an internal ask of the viewer's: a teammate's Discord message that asks them for
15// something, on the item of the client it is about (or of the internal-ops project), due 24 business hours after
16// it was asked, internal or not (kind `ask` when nothing else lists the client)
17// A listed client pins while what it must act by is past or within the next 24 business hours (`pinsNow`).
18// Work that must start now at 1.5 h a day waits for real hour estimates (quote line items).
19//
20// Two more lists are built beside that one (buildLists), and neither pins or is counted: clients whose
21// reply drafts a teammate holds (not the viewer's to act on), and clients whose only items were due before
22// the floor (so that nothing drops off silently).
23//
24// Every client clock here counts business time (Rob, 2026-10-12: "the weekends don't count as days towards
25// the 24-hour response time... We're only counting business days in our timelines for clients"): Saturday
26// and Sunday, America/New_York, contribute zero. See ./business-time.ts.
27
28import type { MmPerson, MmProject } from '../types'
29
30import { businessDaysBetween, businessDeadline, businessMsBetween, subtractBusinessMs } from './business-time'
31
32export type FeedMail = {
33 message_id_key: string
34 received_at: string
35 sender?: string
36 subject?: string
37 snippet?: string
38 project_id: string | null
39 project_name: string | null
40 reply_status: string
41 /** (0.5.2, R17) `null`: no reply time (internal work, unless a person set one). Absent: 24 business hours after it arrived, as before. */
42 reply_due_at?: string | null
43 project_owner_email?: string | null
44 /** (0.5.2, R18) The project is internal (Massmarket's own, a test or a template), when the feed says so. */
45 internal?: boolean
46 /** (0.5.2, R8) Our newest send to the client, when the feed gives it: what tells the bridge a reply went. */
47 last_outbound_at?: string | null
48}
49
50export type FeedDraft = {
51 package_id: string
52 project_id: string
53 project_name: string
54 status: string
55 covers_through?: string
56 /** When the package was last changed, when the feed gives it: part of what tells a thread it has the latest. */
57 updated_at?: string
58 drafts_ready?: number
59 /** Drafts not sent yet (ready, edited, sending, failed). Absent on a server that does not send it yet. */
60 drafts_unsent?: number
61 flagged_for_rob?: boolean
62 picked_up_by?: string | null
63 picked_up_at?: string | null
64 project_owner_email?: string | null
65 /**
66 * (0.5.2, R8) What the server's check of our latest send to the client found, when the feed gives it: the
67 * items it left open (team-safe short strings), the ones it answered, when it checked, and the time of the
68 * send it checked. Absent on a server that does not send them yet: the package is read as in 0.5.1.
69 */
70 still_open?: unknown
71 answered?: unknown
72 /** (0.5.2, R17) `null`: the package has no reply time (internal work). Absent: 24 business hours after what it covers, as before. */
73 due_at?: string | null
74 /** (0.5.2, R18) The project is internal, when the feed says so. */
75 internal?: boolean
76 checked_at?: string | null
77 checked_send_at?: string | null
78 last_outbound_at?: string | null
79}
80
81export type FeedTicket = {
82 ticket_id: string
83 project_id: string
84 project_name: string
85 title: string
86 /** (0.5.2, R17) `null`: no due time (internal work, unless a person set one). */
87 due_at: string | null
88 due_source?: string | null
89 assignee_email?: string | null
90 /** When the task was created, when the feed gives it. */
91 created_at?: string | null
92 /**
93 * (0.5.2, R1) When the work has to start to finish by its due time: OW's `start_by_at`, the due time less
94 * the ticket's estimate (`est_hours`) at 1.5 hours of work a business day (OW src/lib/start-by.ts). Null or
95 * absent with no estimate: the task acts by its due time.
96 */
97 start_by_at?: string | null
98 last_outbound_at?: string | null
99 /** (0.5.2, R18) The project is internal, when the feed says so. */
100 internal?: boolean
101}
102
103/**
104 * One of the caller's own Claude Code sessions that declared a client: the feed's `threads` field. The
105 * session id is what `$.session.id()` answers in that thread. Absent on a server that does not send it yet.
106 * `rows` is how many worklog rows that session wrote for that project in the feed's window: the thread's
107 * length when nothing better is known. Absent on a server that does not send it yet.
108 * `sole` is OW's word on whether the session declared no other project of any kind in the window: OW lists
109 * a session under one project at most, and only a project in the feed, so a session that also declared the
110 * internal-ops project, or a client outside the feed, shows here as that one row alone. `false`: it did
111 * (2026-10-13, the Pipeline-speed thread). Absent on a server that does not send it yet: the row is read
112 * as it always was.
113 */
114export type FeedThread = { project_id: string; session_id: string; last_activity_at: string; rows?: number; sole?: boolean }
115
116/**
117 * (New people, OW ticket 549944b0, spec A7) Someone who wrote to us and whom no project matched: an open row of
118 * OW's `inbound_person_alerts`. OW sends these to the founder and the PMs only. `source` is `gmail_unmatched`
119 * (an email) or `hl_directory` (a HighLevel Directory lead: no address). Every field but `id` and `received_at`
120 * may be missing or null. Absent on a server that does not send them yet.
121 */
122export type FeedPersonAlert = {
123 id: string
124 source?: string | null
125 sender_name?: string | null
126 sender_email?: string | null
127 company?: string | null
128 subject?: string | null
129 received_at: string
130 due_at?: string | null
131 mailboxes?: string[] | null
132 warnings?: string[] | null
133 relationship_summary?: string | null
134 source_link?: string | null
135 shadow_bootstrap_candidate?: boolean | null
136}
137
138/**
139 * (0.5.28, internal asks; Rob, 2026-10-23: "i think that should also trigger a 24 hr reply not just for me but for anyone
140 * asked to do something internally. it should show up in my brige thread for creg with my draft reply to him") One of
141 * the caller's open internal asks: a teammate's Discord message that asks this person for something (OW's `team_asks`,
142 * one row per message and person asked; the feed's `asks`, oldest due first). `project_id` is the client the message is
143 * about, or the internal-ops project (INTERNAL_OPS) when it is about Massmarket itself. Its reply is due `due_at`, 24
144 * business hours after it was asked, internal or not. `snippet` is the first 240 characters of the message, mentions
145 * shown as @Name. Every field but the ids, the asked address and the times may be missing or null. Absent on a server
146 * that does not send them yet: nothing changes.
147 */
148export type FeedAsk = {
149 ask_id: string
150 project_id: string
151 project_name: string
152 internal?: boolean
153 asker_name?: string | null
154 asker_email?: string | null
155 asked_email: string
156 asked_at: string
157 due_at: string | null
158 channel_name?: string | null
159 message_link?: string | null
160 snippet?: string | null
161 has_draft?: boolean
162 draft_sha256?: string | null
163 updated_at?: string | null
164}
165
166/**
167 * (0.5.28, internal asks) An open ask as a client's item keeps it: its id (a lower-case uuid: it goes into the kickoff
168 * and the page request), who asked (cleaned: it goes into the kickoff), when it was asked and when its reply is due (ms),
169 * its snippet (drawn, never handed to Claude), whether a reply is drafted and that draft's hash, and the link to the
170 * message (https only, or '').
171 */
172export type AskRef = { id: string; asker: string; askedAt: number; dueAt: number; snippet: string; hasDraft: boolean; link: string; draftSha: string | null }
173
174/** One of the feed's projects (OW's `projects`; for the founder and a PM, every active project they may see). */
175export type FeedProject = { project_id: string; name: string }
176
177/** (New people) One project OW's resolve route accepts for `route`: the feed's `route_projects` (founder and PMs, uncapped). */
178export type FeedRouteProject = { id: string; name: string }
179
180export type Feed = {
181 member: string
182 role: string
183 mail?: FeedMail[]
184 drafts?: FeedDraft[]
185 /** `start_now` (0.5.2, R1): committed tickets due after the due-soon window whose start-by time has come or is within 24 business hours. */
186 tickets?: { overdue?: FeedTicket[]; due_today?: FeedTicket[]; due_soon?: FeedTicket[]; start_now?: FeedTicket[] }
187 threads?: FeedThread[]
188 /** The feed's projects: what Route offers when the feed gives no `route_projects` (an OW before them). */
189 projects?: FeedProject[]
190 /** (New people) Exactly the projects OW's resolve route accepts for `route`, uncapped: what Route offers when present. */
191 route_projects?: FeedRouteProject[]
192 /** (New people) Open alerts, founder and PMs only. */
193 person_alerts?: FeedPersonAlert[]
194 /** (0.5.28, internal asks) The caller's open internal asks. Absent on a server that does not send them yet. */
195 asks?: FeedAsk[]
196}
197
198/**
199 * The client's open reply package when it is not simply "ready for you" (Rob, 2026-10-12: a thread that
200 * held the drafts was told none were prepared).
201 * held_by_me the viewer picked it up and a draft is not sent yet
202 * held_by_other a teammate picked it up; `by` is their name
203 * stale drafts exist but are marked out of date, and nobody holds it; for the founder, `by` is the
204 * teammate it is with when it is a teammate's (R1, 0.5.1), else ''
205 * prepared drafts are ready, but the client does not pin for the viewer on them (another owner's
206 * client, or a package due before the list's floor)
207 * `unsent` is the drafts not sent on a held package, the drafts ready otherwise. `newer` is the client
208 * messages that arrived after a package the viewer holds was written.
209 */
210export type OpenPackage = {
211 id: string
212 state: 'held_by_me' | 'held_by_other' | 'stale' | 'prepared'
213 by: string
214 at: string | null
215 unsent: number
216 newer: number
217}
218
219/**
220 * A package that is a teammate's and not the viewer's to pick up or rebuild: one a teammate holds, and (for
221 * the founder) a stale one a teammate has (R1: `by` names them). The kickoff and the bridge note word the
222 * two alike: show what is waiting, run no prep, draft no second reply (Opus, 10-13, M2).
223 */
224export const withHolder = (o: OpenPackage): boolean => o.state === 'held_by_other' || (o.state === 'stale' && o.by !== '')
225
226/** The newest time of each kind of thing a client has for the viewer, in ms (0: none): a message received, the mail a package covers, a task created (or due, where the feed gives no creation time). */
227export type Newest = { mail: number; pkg: number; task: number }
228
229/** Who sends a package that waits for the founder's OK, when the feed names no owner for the client. */
230export const NOBODY = 'nobody on record'
231
232export type QueueItem = {
233 projectId: string
234 projectName: string
235 client: string
236 dueAt: number
237 /**
238 * `ok`: for the founder alone, a package flagged for his OK that somebody else sends. (0.5.28, internal asks) `ask`:
239 * listed by the viewer's internal asks alone (no client message, no package of theirs, no task): its title says
240 * `internal ask` where a task's says `task`. A client with any of those as well keeps that kind, and its asks beside it.
241 */
242 kind: 'ready' | 'reply' | 'task' | 'ok' | 'ask'
243 messages: number
244 tasks: number
245 packageId: string | null
246 coversThrough: string | null
247 /** The package's `updated_at` as the feed gave it, or null. Compared, never shown. */
248 packageUpdatedAt: string | null
249 flagged: boolean
250 mail: Array<{ at: string; sender: string; subject: string; snippet: string }>
251 taskTitles: string[]
252 open: OpenPackage | null
253 /** Set with kind `ok`: who sends the package once the founder has given his OK (the owner on record, cleaned, or NOBODY). Every read is `it.ok ?? null`. */
254 ok: { sends: string } | null
255 /** What "something new arrived" is measured against. Every read is `it.newest ?? …`: an item an older version stored has none. */
256 newest: Newest
257 /**
258 * For the founder alone: the teammate a client's package is with when it is theirs to see through, not his
259 * (0.5.1). R1: a stale package a teammate sends, with a client message waiting after its drafts. R2: a
260 * current package flagged for his OK that a teammate sends, until its reply is due. The client then lists
261 * under With a teammate. Absent otherwise, and on an item an older version stored.
262 */
263 theirs?: string
264 /**
265 * (0.5.2, R1) The soonest time something of the client's must be acted on: a reply's due time, a package's,
266 * a task's start-by time when the feed gives one, else its due time. Its thread is pinned while this is past
267 * or within the next 24 business hours. Every read is `it.actBy ?? it.dueAt`: an item an older version
268 * stored has none.
269 */
270 actBy?: number
271 /** (0.5.2, R8) Our newest send to the client in the feed, in ms (0: none given). */
272 lastOut?: number
273 /** (0.5.2, R8) The server's check of our latest send, on the client's own package: absent when the feed gives none. */
274 check?: PackageCheck | null
275 /**
276 * (0.5.2, R17) True when the client is listed for something with no due time (internal work, unless a person
277 * set one): its `dueAt` is then Infinity (stored as null), it is listed last, shows no clock, never pins and
278 * never gets a no-thread chip.
279 */
280 noDue?: true
281 /** (0.5.2, R18) An internal project (Massmarket's own, a test or a template): its thread is never unpinned by the bridge. */
282 internal?: true
283 /**
284 * (0.5.28, internal asks) The viewer's open internal asks about this client, oldest due first: each one's reply is due,
285 * and it pins, like a client message's, and the kickoff and the pane carry one paragraph each. Absent when there are
286 * none, and on an item an older version stored: every read is `openAsks(it)`.
287 */
288 asks?: AskRef[]
289}
290
291/**
292 * (0.5.28, internal asks; Rob, 2026-10-23: "there should be massmarket internal thread in bridge as well") Massmarket's
293 * internal-ops project, "Massmarket AI": where an internal ask about Massmarket itself is listed, and the client of the
294 * Massmarket internal thread.
295 */
296export const INTERNAL_OPS = 'e6deffc3-2713-4def-a11d-b75a1efba9c1'
297
298/**
299 * (0.5.2, R18) The projects that are internal by id, while the feed carries no internal flag: Massmarket's
300 * internal-ops project and the Massmarket Core Snapshot. A feed row with `internal: true` makes any project so.
301 */
302export const INTERNAL_PROJECTS: ReadonlySet<string> = new Set([INTERNAL_OPS, '3e439f40-a17f-48e2-bcfe-723af5b741fc'])
303
304/** (0.5.28, internal asks) A client's open asks as its item holds them: none on an item an older version stored. */
305export const openAsks = (it: Pick<QueueItem, 'asks'>): AskRef[] => (Array.isArray(it.asks) ? it.asks : [])
306
307/**
308 * (0.5.28, internal asks; spec 2026-10-23: "When it has an open ask it can be kicked off and chipped like a client (it
309 * still is never auto-unpinned)") The Massmarket internal thread's item while it has an open ask: chipped, kicked off
310 * and updated by itself as a client's is. Its pins follow R18 as before: the bridge takes off only a pin it put there.
311 */
312export const internalAskThread = (it: Pick<QueueItem, 'projectId' | 'asks'>): boolean => it.projectId === INTERNAL_OPS && openAsks(it).length > 0
313
314/**
315 * (fix round 1, L8) An internal project's item, which gets no chip and no update by itself and no thread started by
316 * itself: every internal one but (0.5.28, internal asks) the Massmarket internal thread's while it has an open ask
317 * (`internalAskThread`).
318 */
319export const heldInternal = (it: Pick<QueueItem, 'projectId' | 'asks' | 'internal'>): boolean => it.internal === true && !internalAskThread(it)
320
321/** (R17) Whether a client has a due time at all (an item stored by the bridge keeps Infinity as null). */
322export const hasDue = (it: Pick<QueueItem, 'dueAt'>): boolean => typeof it.dueAt === 'number' && Number.isFinite(it.dueAt)
323
324/** Soonest due first; a client with no due time last (R17). */
325export const byDue = (a: Pick<QueueItem, 'dueAt'>, b: Pick<QueueItem, 'dueAt'>): number => {
326 const x = hasDue(a) ? a.dueAt : Infinity
327 const y = hasDue(b) ? b.dueAt : Infinity
328 return x === y ? 0 : x < y ? -1 : 1
329}
330
331/**
332 * (0.5.2, R8) What the server's check found on the client's package: the time of the send it checked
333 * (`checked_send_at`, ms, 0 for none), what it left open, and what the package covers through (ms, 0 unknown).
334 */
335export type PackageCheck = { sendAt: number; stillOpen: string[]; covers: number }
336
337/**
338 * What a row under With a teammate adds to its sentence when the package there is flagged for the founder's
339 * OK (R2, Opus's words): the teammate decides whether it needs him (client-reply-prep §1 rule 13, §5.2).
340 */
341export const MAY_NEED_OK = 'may need your OK'
342
343/** (the founder, R2) What such a row's title and waiting text say in place of `needs your OK · <X> sends`, before its reply is due (Opus's words). */
344export const decidesText = (who: string): string => `${MAY_NEED_OK} · ${who} decides`
345
346const HOUR = 3_600_000
347const DAY = 24 * HOUR
348/**
349 * The list's floor (Rob, 2026-10-20: "everything since last Thursday that wasn't closed should always show up
350 * now, and we can keep it clean going forward"). Replaces the rolling 3-business-day cut of 2026-10-08. Anything
351 * still open whose due time is on or after it stays on the Needs-you list however overdue; only what was due
352 * before it goes under Older. Wed 2026-10-14 12:00 AM ET: the week the team installed the bridge.
353 * (Until 2026-10-21 the floor was Thu 2026-10-15; Rob moved it to Wed 2026-10-14: "it should actually be last Wednesday".)
354 */
355export const LIST_FLOOR_MS = Date.parse('2026-10-14T04:00:00Z')
356/**
357 * The pin's window, in business time: 24 business hours ahead (`pinsNow`). A client's thread pins while
358 * something of it must be acted on within them, or already should have been. (0.5.2, R1) The list itself holds
359 * everything not due yet, however far ahead.
360 */
361export const WINDOW_AHEAD_MS = DAY
362/**
363 * The 2026-10-08 cut (3 business days back), kept only as the list's least reach: the floor widens the list
364 * and never narrows it. From Sat 2026-10-17 12:00 AM ET on, everything due before the floor is more than 3
365 * business days overdue, so this decides nothing and the floor alone is the cut; it only keeps a clock before
366 * that day (the tests' fixed early-October dates) reading as it did. (Until 2026-10-20 the cut was 3 business
367 * days back; Rob replaced it with LIST_FLOOR_MS.)
368 */
369export const WINDOW_BACK_MS = 3 * DAY
370/**
371 * (0.5.2, R8) How long a send waits for the server's check before the client is listed as it was: a check that
372 * never lands does not keep a client off the list. Real time (it is not a client's clock).
373 */
374export const CHECK_WAIT_MS = 2 * HOUR
375export const MAX_PINS = 8
376/** The least mail look-back asked of OW, in business hours (Rob, 2026-10-13: "expanding that to 7 days"). */
377export const MAIL_LOOKBACK_MIN_HOURS = 168
378/** The most: OW's `mail_hours` cap from 2026-10-20 (it took 1 to 168 before). */
379export const MAIL_LOOKBACK_MAX_HOURS = 720
380
381/**
382 * Business hours of mail to ask OW for: back to 24 business hours before the floor (mail due on the floor arrived then), at least 168, at most 720 (OW's cap from 2026-10-20).
383 *
384 * A reply is due 24 business hours after a message, so every message whose reply is due on or after the floor
385 * arrived on or after `subtractBusinessMs(LIST_FLOOR_MS, DAY)` (Tue 2026-10-13 12:00 AM ET). Mail OW sends from
386 * further back is read the same way, and goes under Older. The 168 (the look-back since 2026-10-13, review of
387 * 79cbc596, F1) is the least: it is what this asks for until Thu 2026-10-22 12:00 AM ET, so it is safe to ship
388 * before OW's 720 cap deploys; from then on it asks for more than 168, which an OW that still caps at 168
389 * refuses (HTTP 400). Past 720 (from Tue 2026-11-24) mail due just after the floor starts to fall out of the
390 * look-back; "keep it clean going forward" is what keeps that list short.
391 */
392export function mailLookbackHours(now: number): number {
393 const from = subtractBusinessMs(LIST_FLOOR_MS, DAY)
394 // a stretch too long to hold 720 business hours is not walked day by day (businessWithin)
395 if (!businessWithin(from, now, MAIL_LOOKBACK_MAX_HOURS * HOUR)) return MAIL_LOOKBACK_MAX_HOURS
396 const since = businessMsBetween(from, now)
397 return Math.min(MAIL_LOOKBACK_MAX_HOURS, Math.max(MAIL_LOOKBACK_MIN_HOURS, Math.ceil(since / HOUR)))
398}
399
400const ms = (iso: string | null | undefined): number => {
401 const t = iso ? Date.parse(iso) : NaN
402 return Number.isFinite(t) ? t : NaN
403}
404
405// ---------------------------------------------------------------- feed text is data
406// A project's name and id come from the feed, and a thread's title from the app. Both end up in places
407// Claude reads (a kickoff, a tool result, a thread's name), so neither is ever passed on as written.
408
409const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
410/** A lower-case uuid: the only shape of project id (or package id) the bridge acts on. */
411export const isUuid = (id: unknown): id is string => typeof id === 'string' && UUID.test(id)
412
413/**
414 * Text kept to letters, digits, spaces and . , & ' ( ) / - : every other character (a line break, a
415 * bracket, a quote, a symbol) becomes a space, runs of spaces collapse, and it is cut at `max`.
416 */
417export function cleanText(text: unknown, max: number): string {
418 const kept = (typeof text === 'string' ? text : '').normalize('NFC').replace(/[^\p{L}\p{N} .,&'()/-]/gu, ' ')
419 return kept.replace(/ +/g, ' ').trim().slice(0, max).trim()
420}
421/** A client or project name, as it may go into a kickoff, a result, a thread title or a tool argument. */
422export const cleanName = (name: unknown): string => cleanText(name, 80)
423/** A thread's title, as it may be shown in a sentence. */
424export const cleanTitle = (title: unknown): string => cleanText(title, 60)
425
426/** A teammate's name as it may be shown or passed on: the part of their address before the @, cleaned. */
427export function holderName(address: unknown): string {
428 const local = (typeof address === 'string' ? address : '').split('@')[0] ?? ''
429 const name = cleanText(local.replace(/[._-]+/g, ' '), 40).replace(/(^|\s)\p{L}/gu, c => c.toUpperCase())
430 return name || 'a teammate'
431}
432
433/** The client's short name: the project name before " — ", " - " or " (", cleaned. */
434export function shortName(projectName: string): string {
435 const cut = projectName.split(/\s+[—–-]\s+|\s+\(/)[0] ?? projectName
436 const name = cleanName(cut) || cleanName(projectName)
437 return name.length > 32 ? `${name.slice(0, 31)}…` : name
438}
439
440function isMine(owner: string | null | undefined, feed: Feed): boolean {
441 if (owner) return owner.toLowerCase() === feed.member.toLowerCase()
442 return feed.role === 'founder' // unowned clients are Rob's until someone owns them
443}
444
445/**
446 * businessMsBetween(fromMs, toMs) <= limit, without walking the calendar when real time already settles it.
447 * Business time never exceeds real time, so a stretch no longer than `limit` is within it. Each weekend
448 * adds at most 49 real hours (a 25-hour Sunday when the clocks go back) and a stretch holding `limit` of
449 * business time touches at most floor(limit / 5 days) + 1 weekends, so a longer stretch than that is not.
450 * Only what lies in between is measured, which keeps a far-off date in the feed from costing a long walk.
451 */
452function businessWithin(fromMs: number, toMs: number, limit: number): boolean {
453 const real = toMs - fromMs
454 if (real <= limit) return true
455 if (real > limit + (Math.floor(limit / (5 * DAY)) + 1) * (2 * DAY + HOUR)) return false
456 return businessMsBetween(fromMs, toMs) <= limit
457}
458
459/**
460 * Every client the feed has something of the viewer's for, in the three lists the pane draws. A client is
461 * in exactly one.
462 * queue needs the viewer now: what pins and what the header counts. Soonest due first.
463 * teammate a teammate holds its reply drafts and the viewer has no task of their own due there: not the
464 * viewer's to act on (Rob, 2026-10-12: "They should only be seeing theirs... when you pass it
465 * to somebody else, it should show up for only the person who's passed it"). Never pinned,
466 * never counted. The pane lists them under `With a teammate (n)`.
467 * older its only items were due before the floor, LIST_FLOOR_MS (Rob, 2026-10-12: two clients with
468 * unanswered mail from ten and six days ago were not shown at all). Never pinned, never
469 * counted. The pane lists them last, under `Older (n)`, most overdue first. (Until 2026-10-20
470 * the cut was 3 business days back; Rob replaced it with LIST_FLOOR_MS.)
471 */
472export type Lists = { queue: QueueItem[]; teammate: QueueItem[]; older: QueueItem[]; checking: QueueItem[] }
473
474/**
475 * A teammate holds this client's reply drafts and nothing else keeps it in the viewer's list: no committed
476 * task of the viewer's own due there, and (for the founder) no package waiting for his OK. For the founder
477 * too: a client whose package a teammate sends and that is theirs to see through (`theirs`, R1 and R2).
478 * (0.5.28, internal asks) An open ask of the viewer's keeps the client in their list as a task of theirs does: it was
479 * asked of them, whoever holds the client's drafts.
480 */
481export const withTeammate = (it: QueueItem): boolean =>
482 it.tasks === 0 && openAsks(it).length === 0 && (Boolean(it.theirs) || ((it.open ?? null)?.state === 'held_by_other' && it.kind !== 'ok'))
483
484export function buildLists(feed: Feed, now: number): Lists {
485 const current = build(feed, now, false)
486 const inCurrent = new Set(current.map(i => i.projectId))
487 const past = build(feed, now, true).filter(i => !inCurrent.has(i.projectId))
488 // (0.5.2, R8) a client whose package waits for the server's check of our newer send is in none of the
489 // three lists: off the Needs-you list, not pinned, not counted. Its thread is named for it (`checkingTitle`).
490 const checks = (i: QueueItem): boolean => fastState(i, now)?.state === 'checking'
491 return {
492 queue: current.filter(i => !withTeammate(i) && !checks(i)),
493 teammate: [...current, ...past].filter(withTeammate),
494 older: past.filter(i => !withTeammate(i) && !checks(i)),
495 checking: [...current, ...past].filter(i => !withTeammate(i) && checks(i)),
496 }
497}
498
499// ---------------------------------------------------------------- 0.5.2: what pins, and a send being checked
500
501/**
502 * R1 (Rob, 2026-10-13: "Pinned is something the server recognized needs to be done within the next 24 hours,
503 * whether it's a reply or work that must be started within 24 hours to finish by an ETA"): whether a client on
504 * the Needs-you list pins now. Its act-by time (a reply's due time, a task's start-by time, else its due
505 * time) is past, or within the next 24 BUSINESS hours (weekends do not count: Friday 3 PM to Monday 3 PM is 24).
506 */
507export function pinsNow(it: Pick<QueueItem, 'dueAt'> & { actBy?: number }, now: number): boolean {
508 const at = Number.isFinite(it.actBy) ? (it.actBy as number) : it.dueAt
509 if (!Number.isFinite(at)) return false
510 return at <= now || businessWithin(now, at, WINDOW_AHEAD_MS)
511}
512
513/**
514 * (R18) The internal projects. Every project a feed row marks `internal: true`; and (fix round 1, L9)
515 * INTERNAL_PROJECTS only while no row of the feed carries the flag at all (a boolean either way): once OW sends
516 * it, the feed alone says.
517 */
518export function internalProjects(feed: Feed): Set<string> {
519 const flagged = new Set<string>()
520 let carries = false
521 const add = (row: { project_id?: string | null; internal?: boolean } | null | undefined): void => {
522 if (!row || typeof row.internal !== 'boolean') return
523 carries = true
524 if (row.internal && isUuid(row.project_id)) flagged.add(row.project_id)
525 }
526 for (const m of feed.mail ?? []) add(m)
527 for (const d of feed.drafts ?? []) add(d)
528 const t = feed.tickets ?? {}
529 for (const k of [t.overdue ?? [], t.due_today ?? [], t.due_soon ?? [], t.start_now ?? []]) for (const tk of k) add(tk)
530 const out = carries ? flagged : new Set(INTERNAL_PROJECTS)
531 // (0.5.28, internal asks) an ask row the feed marks internal adds its project; ask rows alone never decide whether the
532 // feed carries the flag (L9), so the other internal projects are read exactly as they were
533 for (const a of Array.isArray(feed.asks) ? feed.asks : []) if (a && a.internal === true && isUuid(a.project_id)) out.add(a.project_id)
534 return out
535}
536
537/** Every client's newest `last_outbound_at`, from every row of it the feed gives one on, in ms. */
538function lastOutbound(feed: Feed): Map<string, number> {
539 const out = new Map<string, number>()
540 const add = (pid: unknown, at: unknown): void => {
541 const t = typeof at === 'string' ? ms(at) : NaN
542 if (!isUuid(pid) || !Number.isFinite(t)) return
543 out.set(pid, Math.max(out.get(pid) ?? 0, t))
544 }
545 for (const m of feed.mail ?? []) add(m?.project_id, m?.last_outbound_at)
546 for (const d of feed.drafts ?? []) add(d?.project_id, d?.last_outbound_at)
547 const t = feed.tickets ?? {}
548 for (const k of [t.overdue ?? [], t.due_today ?? [], t.due_soon ?? [], t.start_now ?? []]) for (const tk of k) add(tk?.project_id, tk?.last_outbound_at)
549 return out
550}
551
552/** At most this many items of what a check left open are kept, each cut to this length (team-safe short strings: OW keeps them under 120). */
553const STILL_OPEN_MAX = 8
554const STILL_OPEN_LEN = 120
555
556/** A package row's check, as the bridge keeps it: what is still open is server text, cleaned like any (it goes into a message Claude reads). */
557function checkOf(d: FeedDraft): PackageCheck {
558 const raw = Array.isArray(d.still_open) ? (d.still_open as unknown[]) : []
559 const stillOpen = raw.map(x => cleanText(x, STILL_OPEN_LEN)).filter(Boolean).slice(0, STILL_OPEN_MAX)
560 const sendAt = ms(d.checked_send_at)
561 const covers = ms(d.covers_through)
562 return { sendAt: Number.isFinite(sendAt) ? sendAt : 0, stillOpen, covers: Number.isFinite(covers) ? covers : 0 }
563}
564
565/** What R8 makes of a client: our newer send is being checked, or the check found something still open after it. */
566export type Fast = { state: 'checking'; at: number } | { state: 'still_open'; at: number; items: string[] }
567
568/**
569 * R8 (Rob, 2026-10-13, "yes fast close"), from the client's package and our newest send, both the feed's:
570 * checking our send is newer than the last check of the package (`last_outbound_at` > `checked_send_at`)
571 * and newer than what the package covers, and no older than CHECK_WAIT_MS
572 * still_open the check of our send has landed (`checked_send_at` >= our newest send) and left items open
573 * null otherwise: no package, no check, nothing open, or a feed that gives none of these fields (0.5.1).
574 */
575export function fastOf(c: PackageCheck | null | undefined, lastOut: number, now: number): Fast | null {
576 if (!c) return null
577 const out = Number(lastOut) || 0
578 const checked = Number(c.sendAt) || 0
579 if (out > 0 && out > checked && out > (Number(c.covers) || 0)) return now - out <= CHECK_WAIT_MS ? { state: 'checking', at: out } : null
580 const items = Array.isArray(c.stillOpen) ? c.stillOpen : []
581 if (checked > 0 && items.length && !(out > checked)) return { state: 'still_open', at: checked, items }
582 return null
583}
584
585/**
586 * fastOf for a client as the lists hold it. (The founder's package that waits for his OK is somebody else's
587 * send: never.) Fix round 1, F3: never `checking` while something else of the client's still needs the person
588 * whatever our send answered: a client message that arrived after it, a committed task, or a package they hold
589 * with a draft not sent. (0.5.28, internal asks) Or an open internal ask of theirs, as a task.
590 */
591export function fastState(it: QueueItem, now: number): Fast | null {
592 if (it.kind === 'ok') return null
593 const fast = fastOf(it.check ?? null, Number(it.lastOut) || 0, now)
594 if (fast?.state !== 'checking') return fast
595 const o = it.open ?? null
596 const newerMail = (Number(it.newest?.mail) || 0) > fast.at
597 if (newerMail || it.tasks > 0 || openAsks(it).length > 0 || (o?.state === 'held_by_me' && o.unsent > 0)) return null
598 return fast
599}
600
601/** R8: the thread's name while the server checks our send: `✓ Acme Legal · sent 3 PM · checking`. */
602export function checkingTitle(client: string, at: number, now: number): string {
603 return `✓ ${client} · sent ${clockText(at, now)} · checking`
604}
605
606/** R8: the thread's name once the check found something still open: `🟡 Acme Legal · still open after your reply`. */
607export function stillOpenTitle(client: string): string {
608 return `🟡 ${client} · still open after your reply`
609}
610
611/** R4: the row of a client on the Needs-you list with no thread at all: `🔴 NO THREAD · Acme Legal · due 3 PM`. */
612export function noThreadTitle(it: QueueItem, now: number): string {
613 return `🔴 NO THREAD · ${it.client} · due ${clockText(it.dueAt, now)}`
614}
615
616/** The name a client's linked thread is given: still open after our reply (R8), else what is due (titleFor). */
617export function threadTitle(it: QueueItem, now: number): string {
618 return fastState(it, now)?.state === 'still_open' && !withTeammate(it) ? stillOpenTitle(it.client) : titleFor(it, now)
619}
620
621/** The clients that need the viewer now: what pins. Soonest due first. */
622export function buildQueue(feed: Feed, now: number): QueueItem[] {
623 return buildLists(feed, now).queue
624}
625
626/** A client as a name or an id may mean it: its id, its project's name and its short name, both cleaned. */
627export type KnownClient = Pick<QueueItem, 'projectId' | 'projectName' | 'client'>
628
629/**
630 * Every client the feed names, whether or not anything of it is waiting on the viewer: each project on a
631 * mail row, a reply package or a ticket (all three buckets), with the name that row gives it. What `/mm link`
632 * may mean beyond the three lists (Rob, 2026-10-13: a client with nothing waiting could not be linked).
633 * ⛔ The same rule as the lists: a lower-case uuid and a name with something left once cleaned, or nothing.
634 * The feed's `threads` carry no name: a project known only there is named by its id (register.tsx).
635 */
636export function feedClients(feed: Feed): KnownClient[] {
637 const out = new Map<string, KnownClient>()
638 const add = (projectId: unknown, projectName: unknown) => {
639 if (!isUuid(projectId) || out.has(projectId) || cleanName(projectName) === '') return
640 out.set(projectId, { projectId, projectName: cleanName(projectName), client: shortName(projectName as string) })
641 }
642 for (const m of feed.mail ?? []) add(m?.project_id, m?.project_name)
643 for (const d of feed.drafts ?? []) add(d?.project_id, d?.project_name)
644 const t = feed.tickets ?? {}
645 // (fix round 1, F5) `start_now` too: a client listed only by a task that must start now is a client the feed names
646 for (const k of [t.overdue ?? [], t.due_today ?? [], t.due_soon ?? [], t.start_now ?? []]) for (const tk of k) add(tk?.project_id, tk?.project_name)
647 // (0.5.28, internal asks) and the project of each of the caller's asks: the Massmarket internal thread's among them
648 for (const a of Array.isArray(feed.asks) ? feed.asks : []) add(a?.project_id, a?.project_name)
649 return [...out.values()]
650}
651
652// ---------------------------------------------------------------- New people (OW ticket 549944b0)
653// Someone wrote to us and no project matched (a real RFP sat unseen for four business days, 2026-10-16). OW lists
654// each open one in the feed's `person_alerts`, for the founder and the PMs; the pane shows them under `New
655// people`, newest first, each with Route to project, Start project and Not client mail; a HighLevel Directory lead with
656// Mark handled and Not client mail (register.tsx).
657// ⛔ The pane alone shows them: nothing of theirs goes into a thread's name, a kickoff, a note, the band or an
658// answer to the `mm` tool. Their text is a stranger's, so it is drawn as text and never handed to Claude.
659
660/** (New people) The roles OW sends `person_alerts` to: the founder (Rob) and the PMs. Nobody else is shown any. */
661export const seesPeople = (feed: Pick<Feed, 'role'>): boolean => feed.role === 'founder' || feed.role === 'pm'
662
663/** (New people) The words for each warning OW puts on an alert (spec A5's labels). A code not here is not shown. */
664export const WARNING_LABELS: Readonly<Record<string, string>> = {
665 blank_body: 'blank body',
666 bcc_only: "Bcc'd",
667 attachment_only: 'attachment only',
668 spam_label: 'Gmail marked a copy spam',
669 dmarc_fail: 'sender authentication failed',
670}
671
672/**
673 * Text of a stranger's as the pane draws it: control and format characters (line breaks, bidirectional
674 * overrides, zero-width marks) become spaces, runs of spaces collapse, and it is cut at `max` with an ellipsis.
675 * Lighter than `cleanText` because it is only ever drawn, never handed to Claude: a subject keeps its `:` and `?`.
676 */
677export function shownText(text: unknown, max: number): string {
678 const one = (typeof text === 'string' ? text : '').normalize('NFC').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').replace(/\s+/g, ' ').trim()
679 return one.length > max ? `${one.slice(0, max - 1).trim()}…` : one
680}
681
682/**
683 * A link the pane may draw as `Source`: https only, no spaces, no user name or password before the host, at most
684 * 2,048 characters (what a Link may carry). An `@` after the host is written `%40`: a surface draws a link whose
685 * address holds a raw `@` as plain text (the engine, 2.1.304), and OW's Gmail links name the mailbox in the path
686 * (`/mail/u/<mailbox>/#all/<id>`).
687 */
688export function sourceLink(link: unknown): string {
689 if (typeof link !== 'string' || /\s/.test(link)) return ''
690 try {
691 const url = new URL(link)
692 if (url.protocol !== 'https:' || url.username || url.password) return ''
693 // (with no user name or password, the address as URL writes it starts with its origin)
694 const safe = url.origin + url.href.slice(url.origin.length).replace(/@/g, '%40')
695 return url.href.startsWith(url.origin) && safe.length <= 2048 ? safe : ''
696 } catch {
697 return ''
698 }
699}
700
701/** `Fri Oct 16, 9:12 AM` in New York. */
702export function dateText(t: number): string {
703 try {
704 const d = new Date(t)
705 const day = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', weekday: 'short', month: 'short', day: 'numeric' }).format(d)
706 const time = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', hour: 'numeric', minute: '2-digit' }).format(d)
707 return `${day.replace(',', '')}, ${time}`
708 } catch {
709 // No Intl time zones: Eastern daylight time, as etParts
710 const d = new Date(t - 4 * HOUR)
711 const h = d.getUTCHours()
712 const mm = String(d.getUTCMinutes()).padStart(2, '0')
713 const day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getUTCDay()] ?? ''
714 const month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getUTCMonth()] ?? ''
715 return `${day} ${month} ${d.getUTCDate()}, ${h % 12 || 12}:${mm} ${h < 12 ? 'AM' : 'PM'}`
716 }
717}
718
719/** How long someone has waited, in whole business days completed (weekends do not count), as the row says it. */
720export function waitedText(receivedAt: number, now: number): string {
721 if (!Number.isFinite(receivedAt)) return ''
722 const n = businessDaysBetween(receivedAt, now)
723 return n < 1 ? 'under 1 business day waiting' : `${n} business day${n === 1 ? '' : 's'} waiting`
724}
725
726/**
727 * (New people) The feed's open alerts as the pane's rows, newest first: for the founder and a PM only, and none
728 * from a feed that has no `person_alerts` (an OW that does not send them yet). An alert whose id is not a
729 * lower-case uuid is dropped: the id is what a press sends back to OW. One whose time cannot be read is kept, last.
730 * The row is worded at `now`, the sync's own moment.
731 */
732export function peopleRows(feed: Feed, now: number): MmPerson[] {
733 if (!seesPeople(feed) || !Array.isArray(feed.person_alerts)) return []
734 const seen = new Set<string>()
735 const rows: Array<{ at: number; row: MmPerson }> = []
736 for (const a of feed.person_alerts) {
737 if (!a || typeof a !== 'object' || !isUuid(a.id) || seen.has(a.id)) continue
738 seen.add(a.id)
739 const at = ms(a.received_at)
740 const directory = a.source === 'hl_directory'
741 const name = shownText(a.sender_name, 80) || shownText(a.sender_email, 120) || 'Unknown sender'
742 const company = shownText(a.company, 80)
743 const title = [name, company, directory ? 'via HighLevel Directory' : ''].filter(Boolean).join(' · ')
744 const subject = shownText(a.subject, 160)
745 const warnings = (Array.isArray(a.warnings) ? a.warnings : []).map(w => (typeof w === 'string' ? WARNING_LABELS[w] : undefined)).filter((w, i, all): w is string => Boolean(w) && all.indexOf(w) === i)
746 const known = shownText(a.relationship_summary, 160)
747 const when = Number.isFinite(at) ? `Received ${dateText(at)} ET · ${waitedText(at, now)}` : 'Received at a time the feed did not give'
748 const row: MmPerson = {
749 id: a.id, name, title, subject: subject ? `Subject: ${subject}` : '(no subject)', when, warnings, known: known ? `We know them: ${known}` : '', link: sourceLink(a.source_link),
750 // (a Directory lead has no email: OW refuses route and bootstrap for it, so its row offers Mark handled and Not client mail only)
751 ...(directory ? { directory: true as const } : {}),
752 }
753 rows.push({ at: Number.isFinite(at) ? at : -Infinity, row })
754 }
755 return rows.sort((x, y) => y.at - x.at).map(r => r.row)
756}
757
758/**
759 * (New people) The projects a person may route someone to, by name: the feed's `route_projects` when it gives them
760 * (exactly the projects OW's resolve route accepts, uncapped), every one of them; else, from an OW before them, its
761 * `projects` (for the founder and a PM, every active project they may see). Uuids and names with something left once
762 * cleaned. None for anyone else.
763 */
764export function routeChoices(feed: Feed): MmProject[] {
765 if (!seesPeople(feed)) return []
766 const rows: Array<{ id: unknown; name: unknown }> = Array.isArray(feed.route_projects)
767 ? feed.route_projects.map(p => ({ id: p?.id, name: p?.name }))
768 : Array.isArray(feed.projects) ? feed.projects.map(p => ({ id: p?.project_id, name: p?.name })) : []
769 const out = new Map<string, MmProject>()
770 for (const p of rows) {
771 if (!isUuid(p.id) || out.has(p.id) || cleanName(p.name) === '') continue
772 out.set(p.id, { projectId: p.id, name: cleanName(p.name) })
773 }
774 return [...out.values()].sort((a, b) => a.name.localeCompare(b.name))
775}
776
777/**
778 * (New people) The most projects one page of the Route picker lists. The engine (2.1.304) refuses a whole pane whose
779 * Select holds more than 64 options, and a founder's or PM's feed can offer more projects than that (150 and up), so
780 * the picker shows them a page at a time: `Choose a project`, at most this many projects, and an option to each
781 * neighbouring page. Every project is on some page.
782 */
783export const ROUTE_PAGE = 50
784
785/**
786 * (New people) One page of the Route picker, by name as `routeChoices` sorts them: its projects, where it starts, and
787 * the projects of the page before and after it (null when there is none). A page past the ends is the nearest one.
788 */
789export function routePage(projects: readonly MmProject[], page: number): { page: number; pages: number; from: number; items: MmProject[]; prev: MmProject[] | null; next: MmProject[] | null } {
790 const pages = Math.max(1, Math.ceil(projects.length / ROUTE_PAGE))
791 const at = Math.min(pages - 1, Math.max(0, Number.isInteger(page) ? page : 0))
792 const slice = (n: number): MmProject[] => projects.slice(n * ROUTE_PAGE, (n + 1) * ROUTE_PAGE)
793 return { page: at, pages, from: at * ROUTE_PAGE, items: slice(at), prev: at > 0 ? slice(at - 1) : null, next: at < pages - 1 ? slice(at + 1) : null }
794}
795
796/**
797 * (New people) The notice after a Route OW answered 200, by its `requeued_count` (how many of the person's emails it
798 * filed to the project). A count the answer does not give (an OW before it): the project alone.
799 */
800export function routedText(project: string, requeued: unknown): string {
801 const n = typeof requeued === 'number' && Number.isInteger(requeued) && requeued >= 0 ? requeued : null
802 if (n === null) return `Routed to ${project}.`
803 return n === 0 ? `Routed to ${project}. No emails were filed, they may already be on it.` : `Routed to ${project}. ${n} email${n === 1 ? '' : 's'} filed.`
804}
805
806// ---------------------------------------------------------------- (0.5.28) internal asks
807
808/** (0.5.28, internal asks) The most characters of an ask's snippet the pane draws: the feed's own cut (240). */
809const ASK_SNIPPET_MAX = 240
810/** (0.5.28, internal asks) The most characters of an asker's name, as it goes into the kickoff and the pane. */
811const ASKER_MAX = 40
812/** A draft's sha256, as OW gives it: 64 lower-case hex characters. */
813const SHA256 = /^[0-9a-f]{64}$/
814
815/**
816 * (0.5.28, internal asks) Who asked, as the kickoff and the pane name them: the feed's name for them, cleaned (it goes
817 * into a message Claude reads), else the part of their address before the @ (`holderName`, 'a teammate' with none).
818 */
819export const askerName = (name: unknown, email: unknown): string => cleanText(name, ASKER_MAX) || holderName(email)
820
821/** (0.5.28, internal asks) An ask of the feed's as its client's item keeps it (AskRef): every text cleaned or checked. */
822function askRefOf(a: FeedAsk, askedAt: number, dueAt: number): AskRef {
823 return {
824 id: a.ask_id,
825 asker: askerName(a.asker_name, a.asker_email),
826 askedAt: Number.isFinite(askedAt) ? askedAt : 0,
827 dueAt,
828 snippet: shownText(a.snippet, ASK_SNIPPET_MAX),
829 hasDraft: a.has_draft === true,
830 link: sourceLink(a.message_link),
831 draftSha: typeof a.draft_sha256 === 'string' && SHA256.test(a.draft_sha256) ? a.draft_sha256 : null,
832 }
833}
834
835/** (0.5.28, internal asks) An open ask's line in the pane (spec, 2026-10-23): `Ask from Shezan · due Mon 3:11 PM`. */
836export const askLine = (a: Pick<AskRef, 'asker' | 'dueAt'>, now: number): string => `Ask from ${a.asker} · due ${clockText(a.dueAt, now)}`
837
838/**
839 * (0.5.28, internal asks) A client's open asks in its part of the pane: each one's line and snippet, and under them the
840 * ask's page (`/team-ask?id=<id>&format=pickup`) when it was read (`pages`, by ask id). '' for a client with none. A
841 * page that could not be read leaves the line and the snippet alone: never an error in its place.
842 */
843export function asksMarkdown(it: Pick<QueueItem, 'asks'>, now: number, pages: Readonly<Record<string, string>> = {}): string {
844 const asks = openAsks(it).filter(a => isUuid(a?.id) && Number.isFinite(a?.dueAt))
845 if (!asks.length) return ''
846 const out = [`### Internal asks (${asks.length})`]
847 for (const a of asks) {
848 out.push('', `- ${askLine({ asker: cleanText(a.asker, ASKER_MAX) || 'a teammate', dueAt: a.dueAt }, now)}`)
849 const snippet = shownText(a.snippet, ASK_SNIPPET_MAX)
850 if (snippet) out.push(` > ${snippet}`)
851 const page = typeof pages[a.id] === 'string' ? (pages[a.id] as string).trim() : ''
852 if (page) out.push('', page)
853 }
854 return out.join('\n')
855}
856
857/**
858 * One pass over the feed. `older` false: everything still open that was due on or after the floor
859 * (LIST_FLOOR_MS), however overdue, and everything not due yet, however far ahead. `older` true: only what was
860 * due before the floor, by the same rules of whose it is. (Until 2026-10-20 the cut was 3 business days back;
861 * Rob replaced it with LIST_FLOOR_MS.)
862 */
863function build(feed: Feed, now: number, older: boolean): QueueItem[] {
864 // Under Older: due before the floor, and more than 3 business days ago (WINDOW_BACK_MS: from Sat 2026-10-17
865 // 12:00 AM ET on, everything due before the floor is, so the floor alone decides)
866 const tooOld = (due: number): boolean => due < now && due < LIST_FLOOR_MS && !businessWithin(due, now, WINDOW_BACK_MS)
867 // (0.5.2, R1) everything else with a due time is the current pass's: overdue since the floor, or not due yet
868 // however far ahead; whether it pins is `pinsNow`
869 const inWindow = (due: number): boolean => Number.isFinite(due) && (older ? tooOld(due) : !tooOld(due))
870 /** (R8) Our newest send to each client, from every row of it the feed gives one on. */
871 const lastOut = lastOutbound(feed)
872 /** (R18) The internal projects: by the feed's own flag on any row, else by id. */
873 const internal = internalProjects(feed)
874 const founder = feed.role === 'founder'
875 const byProject = new Map<string, QueueItem>()
876 // ⛔ A row whose project id is not a lower-case uuid, or whose name has nothing left once cleaned, is
877 // dropped: the id goes into the [mm-link] marker and the name into the kickoff, both read by Claude.
878 const usable = (projectId: unknown, projectName: unknown): boolean => isUuid(projectId) && cleanName(projectName) !== ''
879 const item = (projectId: string, projectName: string): QueueItem => {
880 let it = byProject.get(projectId)
881 if (!it) {
882 it = {
883 projectId, projectName: cleanName(projectName), client: shortName(projectName), dueAt: Infinity, kind: 'task',
884 messages: 0, tasks: 0, packageId: null, coversThrough: null, packageUpdatedAt: null, flagged: false, mail: [], taskTitles: [], open: null,
885 ok: null, newest: { mail: 0, pkg: 0, task: 0 }, actBy: Infinity, lastOut: lastOut.get(projectId) ?? 0, check: null,
886 ...(internal.has(projectId) ? { internal: true as const } : {}),
887 }
888 byProject.set(projectId, it)
889 }
890 return it
891 }
892 /** The newest time of each kind of thing a client has: what "something new arrived" is measured against. */
893 const seen = (it: QueueItem, kind: keyof Newest, at: number): void => {
894 if (Number.isFinite(at) && at > it.newest[kind]) it.newest[kind] = at
895 }
896 /** (R1) The soonest something of the client's must be acted on. */
897 const act = (it: QueueItem, at: number): void => {
898 if (Number.isFinite(at)) it.actBy = Math.min(it.actBy ?? Infinity, at)
899 }
900
901 /** The mail rows counted for the viewer: a message is counted once. */
902 const counted = new Set<FeedMail>()
903 /**
904 * The feed's reply time is trusted when it gives one; otherwise 24 business hours after the message arrived.
905 * (R17, R18) None at all, Infinity, when the feed gives `null` or the project is internal: nobody set one.
906 */
907 const replyDue = (m: FeedMail): number =>
908 m.reply_due_at === null || internal.has(m.project_id ?? '') ? Infinity : Number.isFinite(ms(m.reply_due_at)) ? ms(m.reply_due_at as string) : businessDeadline(ms(m.received_at), DAY)
909 /** (R17) A row with no due time is listed in the current pass only (it is never overdue), and marks its client. */
910 const undated = (it: QueueItem): void => {
911 it.noDue = true
912 }
913 /** A client message waiting on our reply, on the client's item. */
914 const countMail = (it: QueueItem, m: FeedMail, due: number): void => {
915 counted.add(m)
916 it.messages += 1
917 it.dueAt = Math.min(it.dueAt, due)
918 act(it, due)
919 if (it.kind === 'task') it.kind = 'reply'
920 it.mail.push({ at: m.received_at, sender: m.sender ?? '?', subject: m.subject ?? '', snippet: m.snippet ?? '' })
921 seen(it, 'mail', ms(m.received_at))
922 }
923 for (const m of feed.mail ?? []) {
924 if (m.reply_status !== 'unanswered' || !m.project_id || !m.project_name) continue
925 if (!usable(m.project_id, m.project_name)) continue
926 if (!isMine(m.project_owner_email, feed)) continue
927 const due = replyDue(m)
928 if (due === Infinity) {
929 if (older) continue
930 const it = item(m.project_id, m.project_name)
931 countMail(it, m, due)
932 undated(it)
933 continue
934 }
935 if (!inWindow(due)) continue
936 countMail(item(m.project_id, m.project_name), m, due)
937 }
938
939 const me = typeof feed.member === 'string' ? feed.member.toLowerCase() : ''
940 /** (the founder) The clients whose row is a package that waits for his OK and that a teammate sends (R2). */
941 const okTheirs = new Set<string>()
942 /** (the founder) The teammate who sends a stale package of the client's, where a client message waits after its drafts (R1). */
943 const staleTheirs = new Map<string, string>()
944 /**
945 * (the founder) For each client with a stale package a teammate has: that teammate, and the client messages
946 * waiting after its drafts, on this pass's side of the floor. Counted only for the client's place under With
947 * a teammate, once nothing else of the founder's lists the client (below).
948 */
949 const staleMail = new Map<string, { name: string; mail: Array<{ m: FeedMail; due: number }> }>()
950 for (const d of feed.drafts ?? []) {
951 // the package id goes into the kickoff and the pickup request: a lower-case uuid or nothing
952 if (!usable(d.project_id, d.project_name) || !isUuid(d.package_id)) continue
953 const holder = (d.picked_up_by ?? '').toLowerCase()
954 const held = d.status === 'picked_up'
955 const ready = d.drafts_ready ?? 0
956 // R12 (0.5.2): the feed lists a picked-up package only while a draft of it is not sent (OW #455), whatever
957 // state that draft is in (`edited`, `sending`, `failed` are not `ready`): with no `drafts_unsent` given, a
958 // held package still has one. It is never read as "no drafts".
959 const unsent = typeof d.drafts_unsent === 'number' && Number.isFinite(d.drafts_unsent) ? d.drafts_unsent : held ? Math.max(1, ready) : ready
960 // What counts: a held package with a draft not sent, or a prepared or stale one with a draft ready.
961 if (held ? unsent < 1 || holder === '' : (d.status !== 'prepared' && d.status !== 'stale') || ready < 1) continue
962 // (the founder) A teammate has this package to see through (Opus, 10-13): the teammate who holds it, whoever
963 // owns the client; with nobody holding it, the owner on record when that is a teammate. ⛔ A package he
964 // holds is his, and so is one with no holder on a client with no owner on record (R3).
965 const sender = typeof d.project_owner_email === 'string' ? d.project_owner_email.toLowerCase() : ''
966 const mates = founder && (held ? holder !== me : sender !== '' && sender !== me)
967 // ⛔ R1 (0.5.1): a stale package a teammate has never puts a row on the founder's list, flagged or not
968 // (Rob's 16 rows, 10-13: four such clients were answered by hand; the owner's stale reminder
969 // carries what is still open). So it is never a package that waits for his OK. (A stale package is held
970 // by nobody: it is the owner's on record.)
971 const staleTheirsHere = mates && d.status === 'stale'
972 const forOk = founder && d.flagged_for_rob === true && !staleTheirsHere
973 const heldByMe = held && holder === me
974 const it = item(d.project_id, d.project_name)
975 // (R17, R18) no reply time for a package the feed gives none, or on an internal project: Infinity
976 const noDue = d.due_at === null || internal.has(d.project_id)
977 const due = noDue ? Infinity : typeof d.due_at === 'string' && Number.isFinite(ms(d.due_at)) ? ms(d.due_at) : Number.isFinite(ms(d.covers_through)) ? businessDeadline(ms(d.covers_through), DAY) : now
978 // (this pass's side of the floor: its reply time on or after LIST_FLOOR_MS, or only what was due before it)
979 const inReach = noDue ? !older : older ? tooOld(due) : !tooOld(due)
980 // `by`: the teammate who holds it; for the founder, also the teammate a stale package is with (R1), so
981 // that its pane names them instead of inviting him to pick it up
982 const open = (state: OpenPackage['state']): OpenPackage => ({
983 id: d.package_id, state, by: state === 'held_by_other' ? holderName(holder) : state === 'stale' && staleTheirsHere ? holderName(sender) : '',
984 at: held ? d.picked_up_at ?? null : null, unsent: held ? unsent : ready, newer: 0,
985 })
986 // ⛔ The holder is asked first, the owner second: a package the viewer holds is theirs to finish whoever
987 // owns the client (Rob, 2026-10-12: a client owned by a teammate, picked up and sent by the founder,
988 // never appeared on the founder's list). A prepared one is theirs when the client is.
989 const readyForMe = d.status === 'prepared' && (holder === '' || holder === me) && isMine(d.project_owner_email, feed) && inReach
990 if (heldByMe || readyForMe) {
991 it.kind = 'ready'
992 it.packageId = d.package_id
993 it.coversThrough = d.covers_through ?? null
994 it.packageUpdatedAt = typeof d.updated_at === 'string' ? d.updated_at : null
995 it.flagged = Boolean(d.flagged_for_rob)
996 it.ok = null
997 // (R8) what the server's check of our latest send found on this package
998 it.check = checkOf(d)
999 if (inReach) {
1000 it.dueAt = Math.min(it.dueAt, due)
1001 act(it, due)
1002 if (noDue) undated(it)
1003 seen(it, 'pkg', ms(d.covers_through))
1004 }
1005 it.open = heldByMe ? open('held_by_me') : null
1006 continue
1007 }
1008 // Any other open package never pins by itself: it only changes what the client's row, pane and note say.
1009 if (it.packageId) continue
1010 // ⛔ (the founder) A client listed for a package that waits for his OK keeps that package as its own: a
1011 // later package of the client's that is not flagged (or that a teammate sends and is stale, R1) does not
1012 // take its place on the row, in the pane or in the kickoff (B4, 2026-10-13).
1013 if (it.kind === 'ok' && !forOk) continue
1014 it.open = open(held ? 'held_by_other' : d.status === 'stale' ? 'stale' : 'prepared')
1015 // (0.5.2, R8) A stale package of the viewer's own (nobody holds it, the client is theirs, no teammate sends
1016 // it): while our latest send waits for the server's check, or the check left something open, the client is
1017 // listed by it, so its thread is named for that and pins again on what is still open. Otherwise it changes
1018 // nothing here, as before (M1: a stale package alone lists nothing).
1019 if (d.status === 'stale' && !held && !staleTheirsHere && !forOk && isMine(d.project_owner_email, feed)) {
1020 const c = checkOf(d)
1021 it.check = c
1022 if (fastOf(c, it.lastOut ?? 0, now) && inReach) {
1023 it.dueAt = Math.min(it.dueAt, due)
1024 act(it, due)
1025 seen(it, 'pkg', ms(d.covers_through))
1026 }
1027 }
1028 // R1: with a client message waiting after its drafts were built, the client lists under With a teammate,
1029 // like any reply a teammate holds; with none, it is not listed. The messages are only noted here: they are
1030 // counted after the tasks, and only where they are all that lists the client (Opus, 10-13, B1).
1031 if (staleTheirsHere) {
1032 const after = ms(d.covers_through)
1033 const waiting = staleMail.get(d.project_id) ?? { name: holderName(sender), mail: [] }
1034 for (const m of feed.mail ?? []) {
1035 if (m.project_id !== d.project_id || m.reply_status !== 'unanswered' || waiting.mail.some(w => w.m === m)) continue
1036 if (Number.isFinite(after) && !(ms(m.received_at) > after)) continue
1037 const due = replyDue(m)
1038 if (inWindow(due)) waiting.mail.push({ m, due })
1039 }
1040 if (waiting.mail.length) staleMail.set(d.project_id, waiting)
1041 continue
1042 }
1043 // ⛔ With one exception, for the founder alone: a package flagged for his OK is listed whoever owns the
1044 // client, as its own kind (Rob, 2026-10-12: six such packages were missing from his panel). It is due
1045 // when a prepared one would be. Somebody else sends it: the owner on record.
1046 // ⛔ Not the founder's own client's (or an unowned client's) STALE flagged package: with no client
1047 // message waiting it lists nothing, and that stays so (Rob's 10-13 morning meeting, finding M1: 12 of
1048 // 102 packages in 14 days went stale because we had already replied by hand; listing them would invite
1049 // a second reply, and OW's fix will close such packages). With a message waiting, the message lists it.
1050 if (forOk && (held || !isMine(d.project_owner_email, feed))) {
1051 it.kind = 'ok'
1052 it.ok = { sends: d.project_owner_email ? holderName(d.project_owner_email) : NOBODY }
1053 // R2: one a teammate sends is theirs to decide until its reply is due (below)
1054 if (mates) okTheirs.add(d.project_id)
1055 else okTheirs.delete(d.project_id)
1056 if (inReach) {
1057 it.dueAt = Math.min(it.dueAt, due)
1058 act(it, due)
1059 seen(it, 'pkg', ms(d.covers_through))
1060 }
1061 }
1062 }
1063
1064 const t = feed.tickets ?? {}
1065 // (0.5.2, R1) `start_now` too: committed tasks due further out whose work must start within 24 business hours
1066 const counting = new Set<string>()
1067 for (const k of [t.overdue ?? [], t.due_today ?? [], t.due_soon ?? [], t.start_now ?? []]) {
1068 for (const tk of k) {
1069 // (R17) a ticket with no due time (internal work nobody dated) has no due source either: it lists, undated
1070 const undatedRow = tk.due_at === null
1071 if (tk.due_source !== 'commitment' && !(undatedRow && (tk.due_source === null || tk.due_source === undefined))) continue
1072 if (!usable(tk.project_id, tk.project_name)) continue
1073 if ((tk.assignee_email ?? '').toLowerCase() !== feed.member.toLowerCase()) continue
1074 // a ticket is in one of the feed's lists only; counted once whatever a feed sends
1075 if (typeof tk.ticket_id === 'string' && counting.has(tk.ticket_id)) continue
1076 const due = undatedRow ? Infinity : ms(tk.due_at)
1077 if (undatedRow ? older : !inWindow(due)) continue
1078 if (typeof tk.ticket_id === 'string') counting.add(tk.ticket_id)
1079 const it = item(tk.project_id, tk.project_name)
1080 it.tasks += 1
1081 it.dueAt = Math.min(it.dueAt, due)
1082 // R1: a task acts by its start-by time when the feed gives one (OW's `start_by_at`, from the ticket's
1083 // estimate), else by its due time
1084 const startBy = ms(tk.start_by_at)
1085 act(it, Number.isFinite(startBy) && startBy < due ? startBy : due)
1086 if (undatedRow) undated(it)
1087 it.taskTitles.push(tk.title)
1088 seen(it, 'task', Number.isFinite(ms(tk.created_at)) ? ms(tk.created_at) : due)
1089 }
1090 }
1091
1092 // (0.5.28, internal asks; Rob, 2026-10-23: "it should route to whatever client bridge thread the question relates to,
1093 // if internal, ... there should be massmarket internal thread in bridge as well") Each of the viewer's open asks lists
1094 // on its project's item: a client's, or the internal-ops project's (INTERNAL_OPS). Its reply is due at its `due_at`
1095 // (24 business hours after it was asked, OW's clock; with none given, the same counted here), and that is what the
1096 // client acts by, so it pins on R1's rule. ⛔ An internal project's ask KEEPS its clock (R17's no-clock rule is for
1097 // mail, packages and tickets). ⛔ Only an ask of the viewer's own (`asked_email`, any case): one a teammate was asked
1098 // is theirs. ⛔ The ask id goes into the kickoff and the page request: a lower-case uuid, or the row is dropped, as a
1099 // package's is; the project, as any row's (`usable`). An ask alone makes no package. Its time counts as a task's for
1100 // "something new arrived" (`newest.task`): it is work the person was asked for.
1101 const askIds = new Set<string>()
1102 for (const a of Array.isArray(feed.asks) ? feed.asks : []) {
1103 if (!a || typeof a !== 'object' || !isUuid(a.ask_id) || askIds.has(a.ask_id)) continue
1104 if (!usable(a.project_id, a.project_name)) continue
1105 if (me === '' || typeof a.asked_email !== 'string' || a.asked_email.toLowerCase() !== me) continue
1106 const asked = ms(a.asked_at)
1107 const due = Number.isFinite(ms(a.due_at)) ? ms(a.due_at as string) : Number.isFinite(asked) ? businessDeadline(asked, DAY) : NaN
1108 if (!inWindow(due)) continue
1109 askIds.add(a.ask_id)
1110 const it = item(a.project_id, a.project_name)
1111 it.dueAt = Math.min(it.dueAt, due)
1112 act(it, due)
1113 // listed by its asks alone: what its title and chip call it (a client message, a package or a task keeps its own)
1114 if (it.kind === 'task' && it.tasks === 0) it.kind = 'ask'
1115 it.asks = [...openAsks(it), askRefOf(a, asked, due)].sort((x, y) => x.dueAt - y.dueAt)
1116 seen(it, 'task', Number.isFinite(asked) ? asked : due)
1117 }
1118
1119 // How many client messages arrived after the drafts of a package the viewer holds were written.
1120 for (const it of byProject.values()) {
1121 const through = ms(it.coversThrough)
1122 if (it.open?.state !== 'held_by_me' || !Number.isFinite(through)) continue
1123 const after = (feed.mail ?? []).filter(m => m.project_id === it.projectId && m.reply_status === 'unanswered' && ms(m.received_at) > through)
1124 it.open.newer = after.length
1125 // (they are new for this client whoever owns it: the package is the viewer's to finish)
1126 for (const m of after) seen(it, 'mail', ms(m.received_at))
1127 }
1128
1129 // (the founder) Whose a client is to see through, when it is a teammate's (0.5.1). ⛔ A package of his own,
1130 // or one he holds, is his (R3).
1131 // R2: a current package flagged for his OK that a teammate sends is theirs to decide, the person holding it
1132 // approving it with a one-line reason or asking him (Rob, 10-07: client-reply-prep §1 rule 13, §5.2),
1133 // until its reply is due: the due time its row shows, in business time. From then it is in his list,
1134 // as the `ok` kind always was. With a teammate: whoever holds it, else the one who sends it.
1135 // R1: a stale package a teammate sends, with a client message waiting after its drafts. ⛔ Those messages
1136 // place the client under With a teammate and nothing more: where anything of his own lists the client
1137 // (a task of his, his own mail, a package of his or one that waits for his OK), his row is for that, and
1138 // they are not added to it (Opus, 10-13, B1: his task row was turned into a reply and pinned as one).
1139 // (0.5.28, internal asks) An ask of his is his own too: its kind `ask` is not `task`, and an ask is never counted as a message.
1140 if (founder) {
1141 for (const [pid, waiting] of staleMail) {
1142 const it = byProject.get(pid)
1143 if (!it || it.tasks > 0 || it.messages > 0 || it.kind !== 'task' || openAsks(it).length > 0 || it.packageId) continue
1144 for (const { m, due } of waiting.mail) if (!counted.has(m)) countMail(it, m, due)
1145 if (it.messages > 0) staleTheirs.set(pid, waiting.name)
1146 }
1147 for (const it of byProject.values()) {
1148 const o = it.open ?? null
1149 const name =
1150 it.kind === 'ok'
1151 ? okTheirs.has(it.projectId) && it.dueAt > now ? (o?.state === 'held_by_other' ? o.by : (it.ok ?? null)?.sends) : undefined
1152 : it.kind === 'ready' ? undefined : staleTheirs.get(it.projectId)
1153 if (name) it.theirs = name
1154 }
1155 }
1156
1157 // (R17) a client with nothing dated is listed too, in the current pass, last
1158 return [...byProject.values()]
1159 .filter(i => Number.isFinite(i.dueAt) || (!older && i.noDue === true))
1160 .sort(byDue)
1161}
1162
1163// ---------------------------------------------------------------- names
1164
1165function etParts(t: number): { day: string; date: string; time: string } {
1166 try {
1167 const d = new Date(t)
1168 const date = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit' }).format(d)
1169 const day = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', weekday: 'short' }).format(d)
1170 const time = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', hour: 'numeric', minute: '2-digit' })
1171 .format(d)
1172 .replace(':00', '')
1173 return { day, date, time }
1174 } catch {
1175 // No Intl time zones: Eastern daylight time, which covers the weeks this ships in.
1176 const d = new Date(t - 4 * HOUR)
1177 const h = d.getUTCHours()
1178 const mm = d.getUTCMinutes()
1179 const time = `${h % 12 || 12}${mm ? `:${String(mm).padStart(2, '0')}` : ''} ${h < 12 ? 'AM' : 'PM'}`
1180 return { day: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getUTCDay()] ?? '', date: d.toISOString().slice(0, 10), time }
1181 }
1182}
1183
1184export function whenText(due: number, now: number): string {
1185 if (due < now) {
1186 const late = businessMsBetween(due, now) // weekends do not count toward how late
1187 // R16 (0.5.2): whole business days COMPLETED, so 1.5 days late is `1d` everywhere, never `2d` in one place
1188 return late < DAY ? `overdue ${Math.max(1, Math.round(late / HOUR))}h` : `overdue ${Math.floor(late / DAY)}d`
1189 }
1190 const a = etParts(due)
1191 const today = etParts(now)
1192 const tomorrow = etParts(now + DAY)
1193 if (a.date === today.date) return `due ${a.time}`
1194 if (a.date === tomorrow.date) return `due tomorrow ${a.time}`
1195 return `due ${a.day} ${a.time}`
1196}
1197
1198export function isRed(it: QueueItem, now: number): boolean {
1199 // (R17) nothing due: never red
1200 if (!hasDue(it)) return falsehooks/threads.ts 1198 lines1// Pure thread logic for the Massmarket bridge: no `$`, so tests can call it directly.
2//
3// Rob, 2026-10-12: "There should be a process that should already be looking to see what threads exist and
4// deciding whether we should start a new one or not, and then making it really easy to pick up... it
5// should be based on a real recommendation." And: "Why are none of them linked? Shouldn't they all be linked?"
6//
7// A client's threads are found three ways:
8// (i) a thread already linked to the client (by hand, from a chip, or by an earlier sync)
9// (ii) a thread whose Claude Code sessions declared the client and no other project: the feed's
10// `threads` rows, matched to the app's threads through the pairs each session records about itself
11// (iii) a thread whose title merely looks like the client
12// (i) and (ii) link themselves. (iii) never does: it is only offered on the row as a suggestion. A thread
13// whose sessions also declared another project is none of these, for either client (`onlyClients`).
14//
15// ⛔ A thread is one client's. A thread linked to one client is never another client's thread, whatever
16// session or title matched it: it is not linked to a second, and it is never the thread Update acts on
17// for a second (`ownerOf`).
18
19import { businessMsBetween } from './business-time'
20import type { MmRow } from '../types'
21
22import { MAY_NEED_OK, NOBODY, checkingTitle, cleanText, cleanTitle, clockText, decidesText, fastState, hasDue, heldInternal, holdSentence, isUuid, noThreadTitle, openAsks, pinsNow, stillOpenTitle, titleFor, titleNames, withHolder, withTeammate } from './queue'
23import type { AskRef, FeedThread, QueueItem } from './queue'
24
25const HOUR = 3_600_000
26const DAY = 24 * HOUR
27const TZ = 'America/New_York'
28
29/** A thread counts as current for a client when its last activity is within this much business time. */
30export const RECENT_THREAD_MS = 7 * DAY
31/** Last activity further back than this is old, decided without counting business time (no calendar walk for a date years back). */
32export const OLD_THREAD_MS = 60 * DAY
33
34// (0.5.11, Rob 10-15: "Can you just automatically compress context at 60% instead of 100% to save tokens?") A thread's
35// length decides nothing any more: Claude Code compacts a long thread (CLAUDE_AUTOCOMPACT_PCT_OVERRIDE), so it is
36// never one to replace, and its row offers Claim whatever its length.
37
38/** A thread as the desktop app lists it. `link` is the app's own link to it, kept only when it is that thread's. */
39export type AppThread = { sessionId: string; title?: string; pinned?: boolean; isArchived?: boolean; lastActivityAt?: string; link?: string }
40
41/**
42 * Claude Code session id → the app thread it runs in, as each session records about itself. `at` is when the
43 * pair was last written (a session writes it again once a day, and a pair not written for 30 days is
44 * forgotten); `since` (0.5.9) is when it was first written for that thread, written with every first write and
45 * kept through those rewrites. A pair with no `since` (written before 0.5.9, or found late in the app's records
46 * and dated then) says nothing about when its thread started.
47 */
48export type Pairs = Record<string, { app: string; at: number; since?: number }>
49
50export type ClientThread = { sid: string; title: string; lastAt: number; source: 'linked' | 'matched' }
51
52export type Target = { sid: string; title: string; suggested: boolean }
53
54/** `start`: a new thread. `update`: the thread exists and lacks what is waiting. `current`: it has it. */
55export type RowState = 'start' | 'update' | 'current'
56
57export type Recommendation = {
58 state: RowState
59 /** Why, in a few words: shown on the row beside the action. For `current`, the whole phrase: `Thread updated 3 PM`. */
60 reason: string
61 /** The client's thread: what Update or Open acts on, and what a new thread takes over from. Absent when there is none. */
62 target?: Target
63 /** True when the client has no thread of any kind: the rows to notice first. (Kept when the thread is merely not visible now.) */
64 fresh?: true
65 /**
66 * (0.5.23) True when the client's linked thread is in the person's other Claude profile on this computer: the link
67 * is kept, and here the row offers Start (the person's press opens a thread here) while nothing is started or sent
68 * by itself. Start missing threads counts such a client as one with no thread here.
69 */
70 away?: true
71}
72
73/** (0.5.23) A client's row when its linked thread is in another Claude profile: Start, and why. */
74export const AWAY_REASON = 'its thread is in another Claude profile'
75
76/**
77 * What Update last put into a client's thread: which thread, the signature of what it carried, and when.
78 * (0.5.11, review of PR #15, F3) `prep`: it went by itself and asked the thread to build the client's package
79 * (kickoff case 6, `asksForPrep`): the package that then appears is the thread's own work, not something new for it.
80 */
81export type Sent = { sid: string; sig: string; at: number; prep?: true }
82
83/** The client a thread is linked to: the first project whose link is that thread. */
84export function ownerOf(sid: string, links: Readonly<Record<string, string>>): string | undefined {
85 for (const [projectId, linked] of Object.entries(links)) if (linked === sid) return projectId
86 return undefined
87}
88
89const ms = (iso: string | null | undefined): number => {
90 const t = iso ? Date.parse(iso) : NaN
91 return Number.isFinite(t) ? t : NaN
92}
93
94function fmt(t: number, opts: Intl.DateTimeFormatOptions): string {
95 try {
96 // some runtimes put a narrow no-break space before AM and PM
97 return new Intl.DateTimeFormat('en-US', { timeZone: TZ, ...opts }).format(new Date(t)).replace(/\u202f/g, ' ')
98 } catch {
99 // No Intl time zones: the UTC date, which is the same day for most of the working day.
100 return new Date(t).toISOString().slice(0, 10)
101 }
102}
103
104/** `Oct 12` */
105export const monthDay = (t: number): string => fmt(t, { month: 'short', day: 'numeric' })
106/** `Mon, Oct 12` */
107export const weekdayMonthDay = (t: number): string => fmt(t, { weekday: 'short', month: 'short', day: 'numeric' })
108/** `Mon, Oct 12 3 PM ET` */
109export function dueText(t: number): string {
110 const time = fmt(t, { hour: 'numeric', minute: '2-digit' }).replace(':00', '')
111 return `${weekdayMonthDay(t)} ${time} ET`
112}
113
114const slug = (s: string): string => s.toLowerCase().replace(/…$/, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
115
116/** A title looks like a client when it reads `client:<slug>`, or, stripped of our marks, starts with the client's name. */
117export function titleLooksLike(title: string, client: string): boolean {
118 const tagged = /^client:\s*(\S+)/i.exec(title.trim())
119 if (tagged && slug(tagged[1] ?? '') === slug(client) && slug(client) !== '') return true
120 return titleNames(title, client)
121}
122
123/**
124 * The feed's threads for one client that are open in the app now, most recently active first.
125 * A session the app does not know (another computer, a headless run, opened before this plugin) is skipped.
126 * ⛔ So is a thread linked to a different client: one app thread can have run sessions for two clients (a
127 * /clear, a resume), and it stays the client's it is linked to.
128 * "Last activity" is the app's own for the thread; the feed's time stands in only when the app gives none.
129 */
130function matchedThreads(
131 projectId: string,
132 links: Readonly<Record<string, string>>,
133 feedThreads: readonly FeedThread[],
134 pairs: Pairs,
135 live: ReadonlyMap<string, AppThread>,
136): ClientThread[] {
137 const out: ClientThread[] = []
138 for (const t of feedThreads) {
139 if (t.project_id !== projectId) continue
140 const app = pairs[t.session_id]?.app
141 const s = app ? live.get(app) : undefined
142 if (!s || s.isArchived || out.some(o => o.sid === s.sessionId)) continue
143 const owner = ownerOf(s.sessionId, links)
144 if (owner !== undefined && owner !== projectId) continue
145 const at = ms(s.lastActivityAt)
146 out.push({ sid: s.sessionId, title: s.title ?? '', lastAt: Number.isFinite(at) ? at : ms(t.last_activity_at), source: 'matched' })
147 }
148 return out.sort((a, b) => (Number.isFinite(b.lastAt) ? b.lastAt : -Infinity) - (Number.isFinite(a.lastAt) ? a.lastAt : -Infinity))
149}
150
151/**
152 * The app threads reached by sessions of more than one client: one thread that ran a session for one
153 * client and, after a /clear or a resume, a session for another. ⛔ Such a thread is nobody's by itself: it
154 * is never linked automatically, to either, and neither client's row offers it (`clientThreads`). The person
155 * can still type /mm link in it.
156 */
157export function sharedThreads(feedThreads: readonly FeedThread[], pairs: Pairs): Set<string> {
158 const clients = new Map<string, Set<string>>()
159 for (const t of feedThreads) {
160 const app = pairs[t.session_id]?.app
161 if (!app) continue
162 const of = clients.get(app) ?? new Set<string>()
163 of.add(t.project_id)
164 clients.set(app, of)
165 }
166 return new Set([...clients].filter(([, of]) => of.size > 1).map(([app]) => app))
167}
168
169/**
170 * The one client a thread's sessions declared in the feed's window: the project EVERY feed row of every
171 * session that runs in the thread names. Undefined when there is no such row, when the rows name two or
172 * more projects, whichever they are (the internal-ops project counts like any other), or when OW says one
173 * of those sessions declared another project too, one the feed does not list (`sole: false`). B3,
174 * 2026-10-13: a pipeline thread that loaded one client's skill for reference was linked to that client,
175 * pinned and named as its thread, so that client's Update would have sent into it.
176 */
177export function soleClient(sid: string, feedThreads: readonly FeedThread[], pairs: Pairs): string | undefined {
178 let only: string | undefined
179 for (const t of feedThreads) {
180 if (pairs[t.session_id]?.app !== sid) continue
181 if (t.sole === false) return undefined
182 if (only !== undefined && only !== t.project_id) return undefined
183 only = t.project_id
184 }
185 return only
186}
187
188/**
189 * Whether a thread is, by the feed or by its own marker, another client's as well as or instead of this
190 * one's: a row of its sessions names another project, OW says such a session declared another project too
191 * (`sole: false`), or the thread opened with an [mm-link] marker for another client (`marked`: the project
192 * each thread's marker named). A row with no `sole` (an older OW) is read as it always was.
193 */
194export function declaredOther(projectId: string, sid: string, feedThreads: readonly FeedThread[], pairs: Pairs, marked: Readonly<Record<string, string>> = {}): boolean {
195 if (marked[sid] !== undefined && marked[sid] !== projectId) return true
196 return feedThreads.some(t => pairs[t.session_id]?.app === sid && (t.project_id !== projectId || t.sole === false))
197}
198
199/**
200 * Whether a thread is this client's alone: what the bridge may link by itself, keep linked by itself, and
201 * offer on the client's row. Every feed row of its sessions names that client (`soleClient`), and nothing
202 * makes it another's (`declaredOther`). A thread the feed lists for nobody is not; whether a link the
203 * bridge made to such a thread is undone is not decided by the feed (0.5.23: only by its thread's archive or deletion, or B3).
204 */
205export function onlyClients(projectId: string, sid: string, feedThreads: readonly FeedThread[], pairs: Pairs, marked: Readonly<Record<string, string>> = {}): boolean {
206 return !declaredOther(projectId, sid, feedThreads, pairs, marked) && soleClient(sid, feedThreads, pairs) === projectId
207}
208
209/**
210 * What becomes of a link the bridge made by itself, by this sync's feed (0.5.23: `unlisted` no longer undoes it; the
211 * sync sets its count of misses back to 0):
212 * stays its thread's sessions declared this client alone (`onlyClients`), or (0.5.9) the feed lists
213 * none of them and the thread opened with this client's own [mm-link] marker
214 * goes something makes the thread another client's too (`declaredOther`: a row for another project,
215 * a row OW marks `sole: false`, a marker for another client): let go on this sync (B3)
216 * unlisted the feed lists none of its sessions: (until 0.5.22) the sync counted a miss; (0.5.23) it stays
217 * (0.5.9) A thread that opened with this client's marker said so itself, and that does not age out of the
218 * feed's window: a link R1b moved to such a thread is not undone by misses and then taken again (a loop).
219 */
220export function autoLinkFate(projectId: string, sid: string, feedThreads: readonly FeedThread[], pairs: Pairs, marked: Readonly<Record<string, string>> = {}): 'stays' | 'goes' | 'unlisted' {
221 if (declaredOther(projectId, sid, feedThreads, pairs, marked)) return 'goes'
222 if (feedThreads.some(t => pairs[t.session_id]?.app === sid)) return 'stays'
223 return marked[sid] === projectId ? 'stays' : 'unlisted'
224}
225
226/**
227 * (0.5.9) When a thread started, as far as the bridge knows: the earliest any Claude Code session was first
228 * recorded running in it (each pair's `since`). Undefined, START-UNKNOWN, when no session of the thread has a pair,
229 * or when any of its pairs has no `since` (review of 54a0437d, M1: a pair written before 0.5.9 carries its last
230 * daily rewrite, and one the app's records gave late carries the day it was found; neither is when the thread
231 * started). ⛔ Never its last activity: typing in a thread later does not make it newer.
232 */
233export function threadStart(sid: string, pairs: Pairs): number | undefined {
234 let start: number | undefined
235 for (const p of Object.values(pairs)) {
236 if (!p || p.app !== sid) continue
237 if (typeof p.since !== 'number' || !Number.isFinite(p.since)) return undefined
238 if (start === undefined || p.since < start) start = p.since
239 }
240 return start
241}
242
243/**
244 * R1b (0.5.9, Rob 2026-10-15: "Can we have it update to attach to the most recent thread for each client?"): the
245 * thread a link the bridge made by itself moves to, when the client has a newer one. A candidate is open in the
246 * app's list, not archived, not the linked thread, linked to no client, not one the person unlinked, not one a
247 * client was moved off (`released`), not reached by sessions of more than one client (`shared`), not
248 * another client's by the feed or by its marker (`declaredOther`), and it opened with this client's own marker
249 * or its sessions declared this client alone (`onlyClients`). Its start (`threadStart`) must be known, and LATER
250 * than both the linked thread's start and its last activity (M1: whichever of them is known and later; neither
251 * known, nothing moves). The newest start wins. ⛔ A candidate whose start is unknown is never one.
252 * ⛔ (0.5.10) And only on evidence dated at or after its own start: the marker recorded then or later (`markedAt`;
253 * a marker with no time on record never counts here), or a feed row of its sessions for this client whose last
254 * activity is then or later. An old thread reopened (paired again, so it looks new) is not this client's newest
255 * thread on what its sessions did for the client before (review of 0.5.9, probe 240: X's link, pin and name landed
256 * on a thread the person was using for client Y until the feed caught up).
257 * ⛔ The newest thread, never the most recently active: typing in the old thread later never pulls the link back.
258 * ⛔ Only for a link the bridge made by itself: the caller never asks this for a link the person made.
259 */
260export function newerThreadFor(
261 projectId: string,
262 linked: string,
263 links: Readonly<Record<string, string>>,
264 feedThreads: readonly FeedThread[],
265 pairs: Pairs,
266 live: ReadonlyMap<string, AppThread>,
267 skip: {
268 unlinked?: Readonly<Record<string, unknown>>
269 released?: readonly string[]
270 marked?: Readonly<Record<string, string>>
271 /** (0.5.10) When each thread's marker was recorded, where that is known. */
272 markedAt?: Readonly<Record<string, number>>
273 shared?: ReadonlySet<string>
274 } = {},
275): string | undefined {
276 const marked = skip.marked ?? {}
277 const unlinked = skip.unlinked ?? {}
278 const released = skip.released ?? []
279 const shared = skip.shared ?? sharedThreads(feedThreads, pairs)
280 const known = [threadStart(linked, pairs), ms(live.get(linked)?.lastActivityAt)].filter((t): t is number => typeof t === 'number' && Number.isFinite(t))
281 if (!known.length) return undefined
282 const from = Math.max(...known)
283 let best: { sid: string; start: number } | undefined
284 for (const s of live.values()) {
285 const sid = s.sessionId
286 if (s.isArchived || sid === linked || ownerOf(sid, links) !== undefined) continue
287 if (sid in unlinked || released.includes(sid) || shared.has(sid)) continue
288 // ⛔ a thread whose marker names another client, or that the feed gives to another, never qualifies
289 if (declaredOther(projectId, sid, feedThreads, pairs, marked)) continue
290 const start = threadStart(sid, pairs)
291 if (start === undefined || start <= from) continue
292 // (0.5.10) this client's, on evidence dated at or after the thread's start
293 const markedAt = skip.markedAt?.[sid]
294 const byMarker = marked[sid] === projectId && typeof markedAt === 'number' && Number.isFinite(markedAt) && markedAt >= start
295 const byFeed =
296 soleClient(sid, feedThreads, pairs) === projectId &&
297 feedThreads.some(t => t.project_id === projectId && pairs[t.session_id]?.app === sid && ms(t.last_activity_at) >= start)
298 if (!byMarker && !byFeed) continue
299 if (!best || start > best.start) best = { sid, start }
300 }
301 return best?.sid
302}
303
304/**
305 * (0.5.23) The threads that opened with this client's own [mm-link] marker, as the bridge recorded each one when its
306 * opening message came in (`mm.marked`, with when: `mm.markedAt`): the threads a client with no linked thread takes
307 * back, newest first (when its marker was recorded; for a marker with no time on record, when its thread started; else
308 * last). The app's records hold no thread's opening message, and the bridge reads no transcript, so this record of
309 * its own is the only place the marker can be read from.
310 * ⛔ Never a thread linked to any client, one the person unlinked, one a client was moved off (`released`), one reached
311 * by sessions of more than one client (`shared`), or one the feed or a marker gives to another client (`declaredOther`).
312 * ⛔ Only the marker counts: a title never does, and a session's declaration is R1's (`autoLinkFor`).
313 * Whether each is still open (not archived, not deleted) is the caller's to find out.
314 */
315export function markedThreads(
316 projectId: string,
317 links: Readonly<Record<string, string>>,
318 feedThreads: readonly FeedThread[],
319 pairs: Pairs,
320 skip: {
321 unlinked?: Readonly<Record<string, unknown>>
322 released?: readonly string[]
323 marked?: Readonly<Record<string, string>>
324 markedAt?: Readonly<Record<string, number>>
325 shared?: ReadonlySet<string>
326 } = {},
327): string[] {
328 const marked = skip.marked ?? {}
329 const unlinked = skip.unlinked ?? {}
330 const released = skip.released ?? []
331 const shared = skip.shared ?? sharedThreads(feedThreads, pairs)
332 const out: Array<{ sid: string; at: number }> = []
333 for (const [sid, pid] of Object.entries(marked)) {
334 if (pid !== projectId || !THREAD_ID.test(sid)) continue
335 if (ownerOf(sid, links) !== undefined || sid in unlinked || released.includes(sid) || shared.has(sid)) continue
336 if (declaredOther(projectId, sid, feedThreads, pairs, marked)) continue
337 const at = skip.markedAt?.[sid]
338 out.push({ sid, at: typeof at === 'number' && Number.isFinite(at) ? at : (threadStart(sid, pairs) ?? -Infinity) })
339 }
340 return out.sort((a, b) => (b.at === a.at ? (a.sid < b.sid ? -1 : 1) : b.at > a.at ? 1 : -1)).map(o => o.sid)
341}
342
343/**
344 * R1: the thread a client links itself to when it has none: the most recently active thread whose Claude
345 * Code sessions declared that client and no other (`onlyClients`). A thread already linked to another
346 * client is left alone, a thread the person unlinked is never linked again by itself (`unlinked`), a
347 * thread that ran sessions for more than one client, or opened with a marker for another, is never linked
348 * by itself, and a title match is never enough.
349 */
350export function autoLinkFor(
351 projectId: string,
352 links: Readonly<Record<string, string>>,
353 feedThreads: readonly FeedThread[],
354 pairs: Pairs,
355 live: ReadonlyMap<string, AppThread>,
356 unlinked: Readonly<Record<string, unknown>> = {},
357 marked: Readonly<Record<string, string>> = {},
358): string | undefined {
359 if (links[projectId]) return undefined
360 const taken = new Set(Object.values(links))
361 return matchedThreads(projectId, links, feedThreads, pairs, live).find(t => !taken.has(t.sid) && !(t.sid in unlinked) && onlyClients(projectId, t.sid, feedThreads, pairs, marked))?.sid
362}
363
364/**
365 * A client's known threads, what its row may offer (Open, Update, the thread a new one takes over from):
366 * the thread linked to it, and every thread whose sessions declared that client alone (`onlyClients`), each
367 * once, newest first.
368 * ⛔ Never a thread linked to a different client, and never one whose sessions also declared another
369 * project or that opened with a marker for another client (Opus, 2026-10-13: the Pipeline-speed thread, once
370 * its link was let go, was still offered for Update on that client's row).
371 */
372export function clientThreads(
373 projectId: string,
374 links: Readonly<Record<string, string>>,
375 feedThreads: readonly FeedThread[],
376 pairs: Pairs,
377 live: ReadonlyMap<string, AppThread>,
378 marked: Readonly<Record<string, string>> = {},
379): ClientThread[] {
380 const out = matchedThreads(projectId, links, feedThreads, pairs, live).filter(t => onlyClients(projectId, t.sid, feedThreads, pairs, marked))
381 const linked = links[projectId] ? live.get(links[projectId] as string) : undefined
382 if (linked && !linked.isArchived && ownerOf(linked.sessionId, links) === projectId) {
383 const same = out.find(t => t.sid === linked.sessionId)
384 if (same) same.source = 'linked'
385 else out.push({ sid: linked.sessionId, title: linked.title ?? '', lastAt: ms(linked.lastActivityAt), source: 'linked' })
386 }
387 return out.filter(t => Number.isFinite(t.lastAt)).sort((a, b) => b.lastAt - a.lastAt)
388}
389
390/**
391 * R1 (iii): the most recently active open thread, linked to nobody, whose title looks like this client.
392 * ⛔ Not one `other` says is another client's (`declaredOther`): a title never brings back a thread the feed
393 * or its marker gives to another client.
394 */
395export function titleSuggestion(client: string, links: Readonly<Record<string, string>>, live: ReadonlyMap<string, AppThread>, other: (sid: string) => boolean = () => false): Target | undefined {
396 const taken = new Set(Object.values(links))
397 let best: AppThread | undefined
398 for (const s of live.values()) {
399 if (s.isArchived || taken.has(s.sessionId) || !s.title || !titleLooksLike(s.title, client) || other(s.sessionId)) continue
400 if (!best || (ms(s.lastActivityAt) || 0) > (ms(best.lastActivityAt) || 0)) best = s
401 }
402 return best ? { sid: best.sessionId, title: best.title ?? '', suggested: true } : undefined
403}
404
405/**
406 * What a thread must already hold to be up to date: the kickoff that would be sent now (without Update's
407 * first line), and the package's `covers_through` and `updated_at` when the feed gives them. A new client
408 * message, another package, a package that changed: each makes it a different text.
409 */
410export function signatureOf(it: QueueItem): string {
411 const o = it.open ?? null
412 const mine = o?.state === 'held_by_me'
413 // A package is read as it was before anyone picked it up, and without how many of its drafts are left:
414 // picking it up or sending one of its drafts is not something new for the thread that has it.
415 const plain: QueueItem = mine ? { ...it, open: null } : o ? { ...it, open: { ...o, unsent: 0 } } : it
416 return [kickoffText(plain), it.coversThrough ?? '', mine ? `held:${o.newer}` : (it.packageUpdatedAt ?? '')].join('\n')
417}
418
419/**
420 * Whether a thread that was given `had` (the signature stored when Update went, or the chip's) already has
421 * what is waiting on `it` now. The same signature, or: a package the viewer holds, with nothing from the
422 * client since its drafts were written, in the thread that was given that package. The package's own
423 * `updated_at` is not asked then: while the viewer holds it, a change to it is their own doing.
424 */
425export function hasWaiting(had: string, it: QueueItem): boolean {
426 const want = signatureOf(it)
427 if (had === want) return true
428 const o = it.open ?? null
429 if (o?.state !== 'held_by_me' || o.newer > 0) return false
430 const head = (s: string): string => s.slice(0, Math.max(0, s.lastIndexOf('\n')))
431 return head(had) === head(want)
432}
433
434// ---------------------------------------------------------------- (0.5.11) Update by itself
435
436/**
437 * (0.5.11) Something new for a client goes into its thread by itself only once this bridge has seen it, unchanged,
438 * for this long (review of PR #15, F3: measured from when the bridge first saw it, `FirstSeen`, never from the feed's
439 * times: the live feed gives no time for a package's drafts, and a message's time says nothing of them).
440 */
441export const AUTO_QUIET_MS = 10 * 60_000
442/**
443 * (0.5.11, review of PR #15, F3) With client mail waiting and no reply drafts ready, it goes once this bridge first
444 * saw the oldest waiting message this long ago, unless drafts are ready sooner. OW holds its own notice 120 minutes,
445 * and Lane-2 aims to have the drafts ready in 60: the thread is not asked to build them while Lane-2 still may.
446 */
447export const AUTO_NO_DRAFTS_MS = 120 * 60_000
448
449/**
450 * (0.5.11, review of PR #15, F3) What this bridge has seen of a client on the person's own list, as the syncs had it
451 * (`mm.firstSeen`): what it has now (`sig`, a short hash of its signature), since when this bridge has seen exactly that
452 * (`at`), and since when client mail has been waiting without a break (`mail`; 0: none waits).
453 */
454export type FirstSeen = { sig: string; at: number; mail: number }
455
456/** (0.5.11, review of PR #15, F3) `FirstSeen` for a client as a sync at `at` has it, from what was seen before. */
457export function seenNow(prev: FirstSeen | undefined, it: QueueItem, sig: string, at: number): FirstSeen {
458 const kept = (t: unknown): number => (typeof t === 'number' && Number.isFinite(t) && t > 0 && t <= at ? t : 0)
459 const since = prev && prev.sig === sig ? kept(prev.at) : 0
460 const mail = it.messages > 0 ? kept(prev?.mail) || at : 0
461 return { sig, at: since || at, mail }
462}
463
464/**
465 * (0.5.11, review of PR #15, F3) Kickoff case 6: client mail waiting and no package at all, so the thread is asked
466 * to build one (prep). Sent by itself, the package that then appears is the thread's own work (`Sent.prep`).
467 */
468export const asksForPrep = (it: QueueItem): boolean => it.messages > 0 && !it.packageId && !(it.open ?? null) && it.kind !== 'ok'
469
470/**
471 * (0.5.11, Rob 10-15: "I think we should start updating threads automatically") Whether a client on the person's
472 * own list is one whose thread may be updated by itself: never one a teammate has (`withTeammate`; the founder's
473 * `theirs`), never one whose package someone else holds (`withHolder`), never one whose reply the server is
474 * checking or found still open (R8: Claim is the person's press), and never an internal project's (as no thread
475 * is started by itself for one). (0.5.28, internal asks) Except the Massmarket internal thread's while it has an open
476 * ask (`heldInternal`): it is updated like a client's.
477 */
478export function autoUpdatable(it: QueueItem, now: number): boolean {
479 const o = it.open ?? null
480 return !heldInternal(it) && !it.theirs && !withTeammate(it) && !(o && withHolder(o)) && fastState(it, now) === null
481}
482
483/**
484 * (0.5.23, Rob 2026-10-21: "change auto-starts to update the older thread") The thread an update sent by itself goes
485 * to, from the client's recommendation as the last sync stored it (`rec`) and the client's linked thread (`linked`):
486 * update the row says Update: its thread
487 * older the row says Start because the thread is older than RECENT_THREAD_MS (`last thread is from Oct 2`):
488 * that same thread is updated, and no new one is started by itself. `older` is the row's reason, for the
489 * notice log. (Auto-compaction keeps an old thread small, so updating it is safe.)
490 * ⛔ Only ever the client's LINKED thread, and never one its row only suggests by a title: every guard of an update
491 * sent by itself still applies (`autoUpdates`). A client with no thread gets none here (its thread is started by
492 * itself, as before), and so does a client whose old thread is not its linked one (the person unlinked it): that
493 * client's thread is still started by itself, with the hand-over from the old one. A person's Start, Start missing
494 * threads and /mm start are not decided here: they open a fresh thread as before.
495 */
496export function autoUpdateTarget(rec: Recommendation | undefined, linked: string | undefined): { sid: string; older?: string } | undefined {
497 const target = rec?.target
498 if (!rec || !target || target.suggested || !THREAD_ID.test(target.sid) || target.sid !== linked) return undefined
499 if (rec.state === 'update') return { sid: target.sid }
500 if (rec.state === 'start') return { sid: target.sid, older: rec.reason }
501 return undefined
502}
503
504/**
505 * (0.5.11, Rob 10-15: "[A client]'s call ended a little while back... I don't understand why it
506 * hasn't already handed the new context there so the draft is ready when I open the thread up") Whether it is time
507 * to update a client's thread by itself, from what this bridge has seen of the client (`seen`, for what it has
508 * NOW: the caller gives the record of this signature only). (Review of PR #15, F3) The bridge has seen it, unchanged,
509 * for AUTO_QUIET_MS; and then no client message waits (tasks only), or reply drafts are ready (a package prepared for
510 * the person, or one they hold), or the bridge first saw the oldest waiting message AUTO_NO_DRAFTS_MS ago. Never
511 * the feed's own times.
512 */
513export function autoUpdateDue(it: QueueItem, now: number, seen: FirstSeen | undefined): boolean {
514 if (!seen || !(now - seen.at >= AUTO_QUIET_MS)) return false
515 if (it.messages === 0) return true
516 const o = it.open ?? null
517 const ready = it.kind === 'ready' || o?.state === 'prepared' || o?.state === 'held_by_me'
518 return ready || (seen.mail > 0 && now - seen.mail >= AUTO_NO_DRAFTS_MS)
519}
520
521/**
522 * (0.5.11, review of PR #15, F3) After an update that went by itself and asked the thread to build the client's
523 * package (`Sent.prep`), the package that appears is that thread's own work: not something new to send it. So it is
524 * while the client has a package now, in that thread, with no client message received since the send.
525 */
526export function ownPackage(given: Sent | undefined, sid: string, it: QueueItem): boolean {
527 if (!given?.prep || given.sid !== sid || asksForPrep(it)) return false
528 if (!it.packageId && !(it.open ?? null)) return false
529 return !((Number(it.newest?.mail) || 0) > given.at)
530}
531
532/**
533 * What to do about a client's thread, and why. ONE action per client:
534 *
535 * start Start thread · no thread yet
536 * Start thread · last thread is from Oct 2 the thread is older than 7 business days
537 * ((0.5.23) by itself, a linked one is updated
538 * instead: `autoUpdateTarget`)
539 * update Update thread · thread from Mon, Oct 12 exists a thread exists and has not been given this
540 * Update thread · new since this thread was updated the bridge updated it before, with less
541 * Update thread · "<title>" looks like this client no known thread, but a title matches
542 * current Thread updated 3 PM the thread already has what is waiting now
543 *
544 * The thread is the client's linked one when it has one, else the most recently active matched one.
545 * `current` is decided by `sent`: the thread and the signature the bridge stored when Update last went.
546 * (0.5.11, Rob 10-15) A thread's length is no reason for a new one: Claude Code compacts it instead.
547 */
548export function recommend(
549 threads: readonly ClientThread[],
550 suggestion: Target | undefined,
551 now: number,
552 known: { sent?: Sent | undefined; signature?: string } = {},
553): Recommendation {
554 const own = threads.filter(t => t.source === 'linked')
555 const thread = [...(own.length ? own : threads)].sort((a, b) => b.lastAt - a.lastAt)[0]
556 if (thread) {
557 const target = { sid: thread.sid, title: thread.title, suggested: false }
558 // More than 60 days back is old whatever the weekends were: business time is only counted inside that.
559 const recent = now - thread.lastAt <= OLD_THREAD_MS && businessMsBetween(thread.lastAt, now) <= RECENT_THREAD_MS
560 if (!recent) return { state: 'start', reason: `last thread is from ${monthDay(thread.lastAt)}`, target }
561 const sent = known.sent && known.sent.sid === thread.sid ? known.sent : undefined
562 if (sent && known.signature !== undefined && sent.sig === known.signature) return { state: 'current', reason: `Thread updated ${clockText(sent.at, now)}`, target }
563 return { state: 'update', reason: sent ? 'new since this thread was updated' : `thread from ${weekdayMonthDay(thread.lastAt)} exists`, target }
564 }
565 // the title is the thread's own text: cleaned and cut before it is shown
566 if (suggestion) return { state: 'update', reason: `"${cleanTitle(suggestion.title)}" looks like this client`, target: suggestion }
567 return { state: 'start', reason: 'no thread yet', fresh: true }
568}
569
570/** What is waiting on a client, as its row shows it: `2 messages waiting, 1 task due`, or `drafts ready`. */
571export function waitingText(it: QueueItem): string {
572 const o = it.open ?? null
573 const drafts = !o ? '' : o.state === 'held_by_me' ? `${o.unsent} draft${o.unsent === 1 ? '' : 's'} not sent` : o.state === 'held_by_other' ? `drafts with ${o.by}` : o.state === 'stale' ? 'drafts out of date' : 'drafts ready'
574 // for the founder, a package that waits for his OK: that first, and who sends it once he has given it; one a
575 // teammate decides on, before its reply is due, says so instead (R2)
576 const ok = it.kind === 'ok' ? (it.theirs ? decidesText(it.theirs) : `needs your OK · ${(it.ok ?? null)?.sends ?? NOBODY} sends`) : ''
577 const parts = [ok, it.messages ? `${it.messages} message${it.messages > 1 ? 's' : ''} waiting` : '', it.tasks ? `${it.tasks} task${it.tasks > 1 ? 's' : ''} due` : '', drafts]
578 const base = parts.filter(Boolean).join(', ')
579 // (0.5.28, internal asks) and then the viewer's open asks, `1 internal ask`: after what the client has otherwise (a
580 // package of theirs with nothing else waiting is still `drafts ready`), or alone for a client listed by its asks alone
581 const n = openAsks(it).length
582 if (!n) return base || 'drafts ready'
583 const asked = `${n} internal ask${n > 1 ? 's' : ''}`
584 return base ? `${base}, ${asked}` : it.packageId ? `drafts ready, ${asked}` : asked
585}
586
587/**
588 * (0.5.28, internal asks) The asks a kickoff carries: each one's id a lower-case uuid and its due time a time, and who
589 * asked cleaned again (an item an older version stored, or a store edited by hand, is read like the feed: as data).
590 */
591function kickoffAsks(it: QueueItem): AskRef[] {
592 return openAsks(it)
593 .filter(a => a && typeof a === 'object' && isUuid(a.id) && typeof a.dueAt === 'number' && Number.isFinite(a.dueAt))
594 .map(a => ({ ...a, asker: cleanText(a.asker, 40) || 'a teammate' }))
595}
596
597/**
598 * (0.5.28, internal asks; spec 2026-10-23, verbatim, values substituted) The paragraph a kickoff and an Update carry
599 * for each open ask: who asked, its short id and due time (as the kickoff writes due times, `dueText`), how to print its
600 * page, to draft the reply first when none is stored, and to wait for the person's go. ⛔ It never posts: the post goes
601 * from the thread, after the go, through `/team-ask/post`.
602 */
603export function askParagraph(a: Pick<AskRef, 'id' | 'asker' | 'dueAt'>): string {
604 return `Internal ask from ${a.asker} (ask ${a.id.slice(0, 8)}, due ${dueText(a.dueAt)}): print it with node ~/.claude/skills/team-api-gateway/scripts/mm-api.mjs ext GET "/team-ask?id=${a.id}&format=pickup". If it has no reply drafted, draft my reply first (client-reply-prep §9.1c, discord-posting) and store it with /team-ask/draft. Then show me the whole page and wait for my go. Post nothing without my go.`
605}
606
607/**
608 * R5: the one message that starts a client's reply in a thread. The Start chip carries it as its prompt and
609 * Update sends it into the existing thread, with a first line saying what is new. Seven cases, the first
610 * that holds (and, for the founder alone, an eighth between 2 and 3: a package that waits for his OK and
611 * that somebody else sends, `okKickoff`):
612 * 1. a package the person already picked up, with a draft not sent: carry on with it
613 * 2. a prepared package that is theirs to pick up
614 * 3. a package a teammate picked up: show what is waiting, run no prep, draft no second reply (and, for
615 * the founder, a stale package a teammate has, not held: the same, in words of its own)
616 * 4. client messages waiting and a package marked out of date: pick it up and rebuild the drafts
617 * 5. client messages waiting and a prepared package older than the window: pick it up
618 * 6. client messages with no package yet
619 * 7. committed tasks only (a package that is out of date, or another owner's, changes nothing here:
620 * the client is in the list for the task)
621 * ⛔ (0.5.11) `auto`: the message an update sent by itself carries (`autoUpdate`), which no person pressed for (with
622 * `update`, the marker comes first: F4 below). It
623 * never takes the package (client-reply-prep §9.1's pickup call): taken by a send nobody pressed for, OW would
624 * show it held by the person, teammates would be refused it (409 held_by_another), and the 24-hour "nobody
625 * picked this up" warning would stop counting it. Cases 2, 4, 5 and 6 then have words of their own (Opus's,
626 * 10-15, verbatim); 1, 3, 7 and the founder's OK are as pressed. A pressed Update's text is unchanged.
627 * (0.5.28, internal asks) A client listed by the viewer's internal asks alone (no package, no client message, no task)
628 * has a case of its own in 7's place: a first line that names the client, as 7's does. In every case the body is
629 * followed by one paragraph per open ask (`askParagraph`, the spec's words verbatim), before any hand-over. An ask
630 * is not a package and its paragraph takes nothing, so a send by itself carries the same words.
631 */
632export function kickoffText(it: QueueItem, opts: { update?: boolean; replaces?: Replaced | undefined; auto?: boolean } = {}): string {
633 const id = it.projectId
634 const who = `${it.projectName} (OW project ${id})`
635 // (R17) nothing due: the kickoff says no due time (the clause is left out, never "due Invalid Date")
636 const due = hasDue(it) ? dueText(it.dueAt) : ''
637 const replyDue = due ? `, reply due ${due}` : ''
638 const tasksDue = due ? ` due ${due}` : ''
639 const o = it.open ?? null
640 /** (0.5.28, internal asks) The viewer's open asks, each checked again before its paragraph goes in. */
641 const asks = kickoffAsks(it)
642 // (0.5.11, Opus 10-15, verbatim) cases 2 and 5 sent by itself: the pickup view, and no pickup call
643 const notTaken = (pkg: string): string =>
644 `[mm-link ${id}] The reply drafts for ${who} are ready in package ${pkg}. Load the client's project skill first, then follow client-reply-prep §9 to show the five-part pickup view for that package, but do not take it: no pickup call until I answer here, so the team can still pick it up. Then wait for me. Send nothing without my go.`
645 const lead =
646 o?.state === 'held_by_me' && it.packageId
647 ? `[mm-link ${id}] Carry on with the reply drafts for ${who}. I already picked up package ${it.packageId.slice(0, 8)}: ${o.unsent} draft(s) not sent yet${o.newer > 0 ? `, and ${o.newer} client message(s) arrived since` : ''}. Load the client's project skill first, then follow client-reply-prep §9: read the package again, show the five-part pickup view and wait for me. Send nothing without my go.`
648 : it.packageId
649 ? opts.auto
650 ? notTaken(it.packageId.slice(0, 8))
651 : `[mm-link ${id}] Pick up the reply drafts for ${who}. Load the client's project skill first, then follow client-reply-prep §9: show the five-part pickup view for package ${it.packageId.slice(0, 8)} and wait for me. Send nothing without my go.`
652 : it.kind === 'ok' && o
653 ? okKickoff(it, o)
654 : o?.state === 'held_by_other'
655 ? `[mm-link ${id}] ${who}: ${o.by} picked up the reply drafts (package ${o.id.slice(0, 8)}) and has ${o.unsent} not sent yet. Load the client's project skill first, then show me what the client sent and what is due, and wait for me. Do not run prep and do not draft a second reply. Send nothing without my go.`
656 : o && withHolder(o)
657 ? // (the founder) a stale package a teammate has, not held: Opus's words, 10-13
658 `[mm-link ${id}] ${who}: ${o.by} has the reply drafts (package ${o.id.slice(0, 8)}), and they are marked out of date. Load the client's project skill first, then show me what the client sent and what is due, and wait for me. Do not run prep and do not draft a second reply. Send nothing without my go.`
659 : o?.state === 'stale' && it.messages > 0
660 ? opts.auto
661 ? // (0.5.11, Opus 10-15, verbatim) case 4 sent by itself
662 `[mm-link ${id}] ${who} needs a reply: ${it.messages} client message(s) waiting${replyDue}. Package ${o.id.slice(0, 8)} is marked out of date. Load the client's project skill first, then show me what the client sent, the current drafts and what is due, and wait for me. Do not take the package or rebuild the drafts until I answer here. Send nothing without my go.`
663 : `[mm-link ${id}] ${who} needs a reply: ${it.messages} client message(s) waiting${replyDue}. Load the client's project skill first, then follow client-reply-prep §9: package ${o.id.slice(0, 8)} exists but is marked out of date, so pick it up, rebuild the drafts, then show the five-part pickup view and wait for me. Send nothing without my go.`
664 : o?.state === 'prepared' && it.messages > 0
665 ? opts.auto
666 ? notTaken(o.id.slice(0, 8))
667 : `[mm-link ${id}] Pick up the reply drafts for ${who}. Load the client's project skill first, then follow client-reply-prep §9: show the five-part pickup view for package ${o.id.slice(0, 8)} and wait for me. Send nothing without my go.`
668 : it.messages > 0
669 ? opts.auto
670 ? // (0.5.11, Opus 10-15, verbatim) case 6 sent by itself
671 `[mm-link ${id}] ${who} needs a reply: ${it.messages} client message(s) waiting${replyDue}. Load the client's project skill first, then follow client-reply-prep: no package exists yet, so run prep (§2) to build one, then show the five-part pickup view without taking the package: no pickup call until I answer here. Then wait for me. Send nothing without my go.`
672 : `[mm-link ${id}] ${who} needs a reply: ${it.messages} client message(s) waiting${replyDue}. Load the client's project skill first, then follow client-reply-prep §9: no package exists yet, so run prep first, then show the five-part pickup view and wait for me. Send nothing without my go.`
673 : it.tasks === 0 && asks.length
674 ? // (0.5.28, internal asks) listed by its asks alone: a first line that names the client, then each ask's paragraph
675 `[mm-link ${id}] ${who} has ${asks.length} internal ask(s) waiting on my reply. Load the client's project skill first.`
676 : `[mm-link ${id}] ${who} has ${it.tasks} committed task(s)${tasksDue}. Load the client's project skill first, then show me what is due and wait for me. Send nothing without my go.`
677 // (0.5.28, internal asks) once per open ask, after the body and before any hand-over: `askParagraph`, verbatim
678 const body = asks.length ? [lead, ...asks.map(askParagraph)].join('\n\n') : lead
679 const news = `New since this thread last worked on this client: ${waitingText(it)}.`
680 // ⛔ (0.5.11, review of PR #15, F4) sent by itself: the marker first, at the very start of the text, as every hook
681 // that tells the person's time from the bridge's reads it (a time-tracking hook too old to read the app's own
682 // `peer` stamp counts a turn that opens with the marker as automatic). Then the first line, then the body
683 // without its own marker. A pressed Update's text is as it was.
684 const marker = `[mm-link ${id}] `
685 if (opts.update && opts.auto) return `${marker}${news}\n${body.startsWith(marker) ? body.slice(marker.length) : body}`
686 if (opts.update) return `${news}\n${body}`
687 const handover = opts.replaces ? handoverText(it, opts.replaces) : ''
688 return handover ? `${body}\n\n${handover}` : body
689}
690
691/**
692 * The kickoff for a package that waits for the founder's OK and that somebody else sends (kind `ok`): he
693 * is shown the package and what needs his OK. He does not pick it up, and nothing is drafted or sent.
694 */
695function okKickoff(it: QueueItem, o: NonNullable<QueueItem['open']>): string {
696 const who = `${it.projectName} (OW project ${it.projectId})`
697 const sends = (it.ok ?? null)?.sends ?? NOBODY
698 return `[mm-link ${it.projectId}] ${who}: reply package ${o.id.slice(0, 8)} is flagged for my OK${o.state === 'stale' ? ' and is marked out of date' : ''}, and ${sends} sends it. Load the client's project skill first, then follow client-reply-prep §9: show the five-part pickup view for that package and what needs my OK, and wait for me. Do not pick the package up and do not draft a second reply. Send nothing without my go.`
699}
700
701/** The thread a new one takes over from: the app's id for it and its own title. */
702export type Replaced = { sid: string; title: string }
703
704/**
705 * R8 (Rob, 2026-10-13): what Claim in this thread sends into the client's thread, in Rob's words: what the
706 * server's check of our reply found still open. `at` is the time of that reply. The items are the feed's,
707 * cleaned (queue.ts, checkOf).
708 */
709export function claimText(client: string, at: number, items: readonly string[], now: number): string {
710 return `Still open for ${client} after our reply of ${clockText(at, now)}: ${items.join('; ')}. Load the client's project skill first, then follow client-reply-prep §9: show me what is still open and the drafts for it, and wait for me. Send nothing without my go.`
711}
712
713/** (fix round 1, L13) A chip's title is at most this many characters. */
714export const CHIP_TITLE_MAX = 60
715/** A chip's title, cut to CHIP_TITLE_MAX characters (the last one an ellipsis when it was cut). */
716export const chipTitle = (title: string): string => (title.length > CHIP_TITLE_MAX ? `${title.slice(0, CHIP_TITLE_MAX - 1)}…` : title)
717
718/**
719 * (0.6.0, spec 2026-10-25, verbatim; R5's sentence until 0.5.28) What a kickoff carries when the client already has a
720 * linked (primary) thread other than the one starting: this thread stays the client's as a second thread, and leaves
721 * the reply package to the primary. `title` is the primary thread's name; `skill` the client's skill from OW's skill
722 * map, else the kickoff's own words for it (the client's project skill).
723 */
724export function secondThreadSentence(client: string, title: string, skill?: string): string {
725 const load = skill ? `load the ${skill} skill` : "load the client's project skill"
726 return `Another thread of yours already holds ${client}'s reply package ("${title}"). Do not run prep and do not pick up the package here. This thread stays linked to ${client} as a second thread: ${load} and then wait for the person.`
727}
728
729/**
730 * The kickoff of a new thread for a client (Start, a chip): 0.5.1's start kickoff, with the hand-over from the
731 * client's old thread. One case 0.5.1 never listed (R8): a stale package of the viewer's whose check left items
732 * open, with no client message and no task (and, 0.5.28, no internal ask); its kickoff is the Claim message behind the
733 * client's marker.
734 */
735export function startKickoff(it: QueueItem, replaces: Replaced | undefined, now: number): string {
736 const fast = fastState(it, now)
737 const o = it.open ?? null
738 if (fast?.state === 'still_open' && !it.packageId && it.messages === 0 && it.tasks === 0 && openAsks(it).length === 0 && !(o && withHolder(o))) {
739 const body = `[mm-link ${it.projectId}] ${claimText(it.client, fast.at, fast.items, now)}`
740 const handover = replaces ? handoverText(it, replaces) : ''
741 return handover ? `${body}\n\n${handover}` : body
742 }
743 return kickoffText(it, { replaces })
744}
745
746// ---------------------------------------------------------------- (0.5.12) Start all
747
748/**
749 * (0.5.12, Rob 10-15: no clicks at all; the app starts a thread only on the person's own words or press, so a new
750 * client's thread needs one person action) The most threads one Start all opens: the rest wait for a second press.
751 */
752export const START_ALL_MAX = 8
753
754/**
755 * (0.5.12) The Start all button, with how many clients need a new thread now. (0.5.14, Rob 10-16: "It should just
756 * pretty much always be 'start missing threads.'") Named for what it does, in the pane and on the band alike; the
757 * typed command is still /mm start all.
758 */
759export const startAllLabel = (n: number): string => `Start missing threads (${n})`
760
761/** (0.5.14) The band's Start missing threads button when no client needs a new thread: drawn dim, and a press only checks again. */
762export const ALL_STARTED = 'All threads started'
763
764/**
765 * (0.5.14) The band's one button, always drawn (it took Open list's place): Start missing threads with how many, or
766 * All threads started when there are none. Either way a press is Start all's (`pressStartAll`).
767 */
768export const startMissingLabel = (n: number): string => (n > 0 ? startAllLabel(n) : ALL_STARTED)
769
770/**
771 * (0.5.12) The first message of a thread Start all opens: the new-thread kickoff (`startKickoff`) in the words that never
772 * take the package (kickoffText's `auto`, with no Update line, so the client's marker is first: cases 2, 4, 5 and 6
773 * show the drafts and make no pickup call until the person answers), with the hand-over from the client's old thread
774 * as a single Start has it. A client still open after our reply, with nothing else, opens with its Claim words, as
775 * Start has them. A single Start's own kickoff is unchanged.
776 */
777export function startAllKickoff(it: QueueItem, replaces: Replaced | undefined, now: number): string {
778 const fast = fastState(it, now)
779 const o = it.open ?? null
780 if (fast?.state === 'still_open' && !it.packageId && it.messages === 0 && it.tasks === 0 && openAsks(it).length === 0 && !(o && withHolder(o))) return startKickoff(it, replaces, now)
781 return kickoffText(it, { replaces, auto: true })
782}
783
784/**
785 * (0.5.16, Rob 10-19: "When it says it actually has to be started by me saying it here in the thread, that causes
786 * issues.") The app's answer when it will not start a thread from this turn: it starts one (`user_asked`) only on the
787 * person's own typed words in this thread, and a press in a thread that some other session started, or that an
788 * automatic Update woke last, is not that. Its sentence: `Start sessions only on the user's own words to you here;
789 * this turn runs an automated event, ... Propose the session instead (initiation "own_initiative")`. Told by its two
790 * stable parts and nothing broader, so that any other refusal still reads as the error it is.
791 */
792export const needsCard = (text: string): boolean => /\buser['’]s own words\b|\bpropose the session instead\b/i.test(text)
793
794/** (0.5.16) What a press says when the app wants the person's own words and a card was made instead (`needsCard`). */
795export const cardReady = (client: string): string => `A Start card for ${client} is ready here: click Start on it.`
796
797/**
798 * (0.5.12) The one line a Start all leaves, in the band of every thread and above the list: the threads it started,
799 * the ones the app did not start and why, the ones it skipped (a thread or another start got there first), and how
800 * many still need a thread after the cap (START_ALL_MAX) for a second press. (0.5.16) And how many wait as Start cards
801 * in this thread, where the app wanted the person's own words (`needsCard`): a count, never the app's sentence.
802 */
803export function startAllSummary(started: readonly string[], failed: ReadonlyArray<{ client: string; why: string }>, skipped: ReadonlyArray<{ client: string; why: string }>, left: number, cards = 0): string {
804 const out: string[] = []
805 if (started.length) out.push(`Started ${started.length} thread${started.length === 1 ? '' : 's'}: ${started.join(', ')}.`)
806 if (cards > 0) out.push(`${cards} ready to start here: click Start on ${cards === 1 ? 'its card' : 'each card'}.`)
807 if (failed.length) out.push(`Not started: ${failed.map(f => `${f.client} (${f.why})`).join('; ')}.`)
808 if (skipped.length) out.push(`Skipped: ${skipped.map(f => `${f.client} (${f.why})`).join('; ')}.`)
809 if (left > 0) out.push(`${left} more need${left === 1 ? 's' : ''} a thread: press Start missing threads again.`)
810 return out.join(' ') || 'No client needs a new thread now.'
811}
812
813// ---------------------------------------------------------------- (0.5.25) Start on the person's own words
814
815/**
816 * (0.5.25, Rob 10-22: "I'm still having a hard time starting missing threads unless I type it... Maybe clicking the
817 * button just types 'start missing threads' into the command line") Claude.app starts a thread (start_session
818 * `user_asked`) only on a turn the person typed, and since 3.1623 asks the person to allow every start_session call; a
819 * Start card the bridge made never opened for him. So a Start press puts the person's own words in the prompt box, they
820 * send them with Enter, and the model starts each thread with what the mm tool's `kickoffs` gives it. What Start missing
821 * threads (and /mm start all) puts there:
822 */
823export const START_ALL_WORDS = 'Start the missing client threads'
824
825/** (0.5.25) What a row's Start, and /mm start <client>, puts there. */
826export const startWords = (client: string): string => `Start ${client}'s thread`
827
828/**
829 * (0.5.25) What a press says: its words are in the prompt box (`filled`); the box held a draft of the person's, which
830 * is never written over (`draft`); or no box took them (`none`: a surface with none, or one that refused).
831 */
832export function startFillSaid(words: string, all: boolean, how: 'filled' | 'draft' | 'none'): string {
833 const then = all ? 'Claude starts each missing thread, and the app asks you to allow each one.' : 'Claude starts the thread, and the app asks you to allow it.'
834 if (how === 'filled') return `"${words}" is in the prompt box: press Enter to send it. ${then}`
835 if (how === 'draft') return `Your prompt box has a draft, so it was left as it is. Send "${words}" when you are ready: ${then}`
836 return `Type "${words}" and send it: ${then}`
837}
838
839/** (0.5.25) One thread for the model to start: the client, and start_session's arguments exactly as the bridge would pass them. */
840export type Kickoff = { client: string; args: Record<string, unknown> }
841
842/**
843 * (0.5.25) What the mm tool's `kickoffs` answers: how to use what follows, the threads to start (one JSON line), the
844 * clients it skipped and why, and how many more need a thread after START_ALL_MAX.
845 */
846export function kickoffsAnswer(kicks: readonly Kickoff[], skipped: ReadonlyArray<{ client: string; why: string }>, left: number): string {
847 const out: string[] = []
848 if (kicks.length) {
849 out.push(
850 `Only if the person asked for this in their own message on this turn: start ${kicks.length === 1 ? 'this thread' : `these ${kicks.length} threads`} with one start_session call each, one after another, passing "arguments" exactly as given. The [mm-link] marker at the start of each prompt links the new thread to its client: send nothing else into it. On any other turn, start nothing and tell the person to press Start in the pane.`,
851 )
852 out.push(JSON.stringify(kicks.map(k => ({ client: k.client, arguments: k.args }))))
853 }
854 if (skipped.length) out.push(`Skipped: ${skipped.map(s => `${s.client} (${s.why})`).join('; ')}.`)
855 if (left > 0) out.push(`${left} more need${left === 1 ? 's' : ''} a thread: once these have started, call mm with "kickoffs" again.`)
856 return out.join('\n') || 'No client needs a new thread now.'
857}
858
859/** `local_<id>`: the app's id for a thread, which is what the session tools take. */
860export const THREAD_ID = /^local_[A-Za-z0-9_-]{1,100}$/
861
862/**
863 * The second paragraph of a kickoff that starts a new thread while the client already has one (Rob,
864 * 2026-10-12: "inspect the recent context of an existing thread for anything unreconciled before creating
865 * the new one"). The NEW thread's Claude reads the old thread's last three messages; the bridge reads
866 * nothing of it. '' when the old thread's id is not an app thread id.
867 * ⛔ The title is the thread's own text: cleaned to one line and cut at 60 before it goes in.
868 */
869export function handoverText(it: QueueItem, old: Replaced): string {
870 if (!THREAD_ID.test(old.sid)) return ''
871 // (a kickoff that shows no pickup view: tasks only, or a package a teammate holds or, stale, has)
872 const o = it.open ?? null
873 const before = it.packageId || it.kind === 'ok' || (it.messages > 0 && !(o && withHolder(o))) ? 'Before the pickup view' : 'Before showing me what is due'
874 return `This thread replaces "${cleanTitle(old.title)}" (thread ${old.sid}) for ${it.projectName}. ${before}, and without reading that thread in full: read only its last three messages with the session tools (list_events, a small limit) and list anything left open in it: a question waiting on me, something promised and not done, a draft that was not sent. Keep that list to ten lines, then carry on.`
875}
876
877/**
878 * The link that opens a thread in the app, as the app's own list gives it. ⛔ Only this exact shape, and
879 * only for the thread it names: `claude://claude.ai/epitaxy/<that thread's id>`. Anything else is no link.
880 */
881export function threadLink(thread: { sessionId: string; link?: unknown } | undefined): string | undefined {
882 if (!thread || typeof thread.link !== 'string' || !THREAD_ID.test(thread.sessionId)) return undefined
883 return thread.link === `claude://claude.ai/epitaxy/${thread.sessionId}` ? thread.link : undefined
884}
885
886/**
887 * The system's own opener on each platform: the program, and what stands before the link. The app gives a
888 * plugin no call that opens a thread, so this is the one way a button can take the person to it.
889 * ⛔ These three programs and no other. `rundll32 url.dll,FileProtocolHandler` on Windows, not `cmd /c
890 * start`: no shell reads the link.
891 */
892export const OPENERS = {
893 mac: ['open'],
894 windows: ['rundll32', 'url.dll,FileProtocolHandler'],
895 linux: ['xdg-open'],
896} as const
897export type Platform = keyof typeof OPENERS
898
899/**
900 * Which platform this computer is, from its environment: Windows sets `OS` to `Windows_NT`; a home folder
901 * under `/Users/` is a Mac's and one under `/home/` is Linux's. Undefined when it cannot be told: nothing
902 * is started then.
903 */
904export function platformOf(env: { OS?: string | null | undefined; HOME?: string | null | undefined }): Platform | undefined {
905 if (env.OS === 'Windows_NT') return 'windows'
906 const home = typeof env.HOME === 'string' ? env.HOME : ''
907 if (home.startsWith('/Users/')) return 'mac'
908 if (home.startsWith('/home/')) return 'linux'
909 return undefined
910}
911
912/**
913 * The one command that opens a thread, as an argument array: the platform's opener, then the thread's link
914 * as its last argument, alone. Undefined when the thread has no link that is exactly its own (threadLink),
915 * or the platform is not known: nothing is started then.
916 * ⛔ Never a string for a shell, and nothing is ever joined into an argument.
917 */
918export function openCommand(thread: { sessionId: string; link?: unknown } | undefined, platform: Platform | undefined): readonly string[] | undefined {
919 const link = threadLink(thread)
920 if (!link || !platform || !Object.hasOwn(OPENERS, platform)) return undefined
921 return [...OPENERS[platform], link]
922}
923
924// ---------------------------------------------------------------- the pane
925
926export const LABEL = { update: 'Update thread', start: 'Start thread', open: 'Open thread', drafts: 'Drafts', claim: 'Claim in this thread' } as const
927export type RowButton = keyof typeof LABEL
928
929/** R8: the sentence under the list. */
930export const PANE_SENTENCE =
931 'Pins: overdue (anything still open since Wed Oct 14), or due within the next 24 business hours. Weekends do not count. Threads for these clients link themselves; use Update or Start on a row to pick one up.'
932
933/** A row of the Needs-you pane (the plugin's state contract holds the shape). */
934export type Row = MmRow
935
936/** A row's state, also for a row an older version of the bridge drew (it called it `action`). */
937export const rowState = (row: Row): RowState => {
938 const state = row.state ?? (row as { action?: unknown }).action
939 return state === 'update' || state === 'current' ? state : 'start'
940}
941
942/**
943 * How a row is drawn beyond its recommendation (0.5.2): `needsYou` for a row of the Needs-you list (R4 names a
944 * client there with no thread at all). (0.5.11: no context reading any more; R8's Claim shows whatever the
945 * thread's length.)
946 */
947export type RowOptions = { needsYou?: boolean }
948
949export function rowFor(it: QueueItem, rec: Recommendation, now: number, opts: RowOptions = {}): Row {
950 // a client whose drafts a teammate holds, and that is not the viewer's to act on: who to ask, and no action
951 const withMate = withTeammate(it)
952 // R8: the check of our reply left items open, and the client has a thread to claim them in
953 const fast = withMate ? null : fastState(it, now)
954 const still = fast?.state === 'still_open' && rec.target && !rec.target.suggested ? fast : null
955 // R4: on the Needs-you list, no thread of any kind, and due within the pin's window
956 const noThread = !withMate && opts.needsYou === true && rec.fresh === true && pinsNow(it, now)
957 // R8: the server is checking our reply: the row is named as its thread is
958 const checking = !withMate && fast?.state === 'checking' ? fast : null
959 const title = checking ? checkingTitle(it.client, checking.at, now) : noThread ? noThreadTitle(it, now) : still ? stillOpenTitle(it.client) : titleFor(it, now)
960 // (the founder) a package flagged for his OK that a teammate has, theirs to decide until its reply is due:
961 // the row's sentence is followed by Opus's words, R2. A row with no sentence (a prepared package) gets no
962 // line of them alone: its title and waiting text already say it (Opus, 10-13).
963 const hold = withMate ? holdSentence(it) : ''
964 const note = hold && it.theirs && it.kind === 'ok' ? `${hold} · ${MAY_NEED_OK}` : hold
965 return {
966 projectId: it.projectId, client: it.client, title, waiting: waitingText(it), state: rec.state, reason: rec.reason,
967 // no thread of any kind: the row goes in the first group, marked
968 fresh: rec.fresh === true,
969 // the thread this row's button acts on: a press acts on this one or on none
970 ...(rec.target ? { target: rec.target.sid } : {}),
971 ...(note ? { note } : {}),
972 // (the founder's alone, 0.5.1) a teammate's to see through: no action, with a sentence or without one
973 ...(withMate && it.theirs ? { theirs: true } : {}),
974 // R8: what is still open, drawn under the row, and its one action, Claim in this thread ((0.5.11, Opus 10-15)
975 // whatever the thread's length: a long thread is compacted, not replaced)
976 ...(still ? { stillOpen: [...still.items], claim: true } : {}),
977 ...(checking ? { checking: true as const } : {}),
978 }
979}
980
981/** R8: a row whose client's reply left items open (the server's check). */
982export const isStillOpenRow = (row: Row): boolean => Array.isArray(row.stillOpen) && row.stillOpen.length > 0
983
984/** A row under `With a teammate`, or (R8) under `Checking your reply`: not the viewer's to act on now. */
985const notMine = (row: Row): boolean => Boolean(row.note) || row.theirs === true || row.checking === true
986
987/**
988 * The buttons on a row: ONE action, chosen by its state, then Drafts (Rob, 2026-10-12: "it should be
989 * 'update thread', 'open thread', or 'start thread'... depending on whether you know what we should do").
990 * A row under `With a teammate` is not the viewer's to act on: Drafts alone.
991 */
992export function rowButtons(row: Row): RowButton[] {
993 if (notMine(row)) return ['drafts']
994 // R8: Claim in this thread ((0.5.11) whatever the thread's length; a row an older version drew with no Claim keeps none)
995 if (isStillOpenRow(row)) return row.claim ? ['claim', 'drafts'] : ['drafts']
996 const state = rowState(row)
997 return [state === 'current' ? 'open' : state, 'drafts']
998}
999
1000/**
1001 * The second line of a row: what is waiting, then the action and its reason, or when the thread was updated. A row with no action: what is waiting.
1002 * `here` (0.5.5): the thread drawing the pane. A reason that says "this thread" says so only there: anywhere else it names the client's thread.
1003 */
1004export function rowDetail(row: Row, here?: string): string {
1005 if (notMine(row) || isStillOpenRow(row)) return row.waiting
1006 const state = rowState(row)
1007 const reason = row.reason === UPDATED_HERE && !isHere(row, here) ? `new since ${row.client}'s thread was updated` : row.reason
1008 return state === 'current' ? `${row.waiting} · ${reason}` : `${row.waiting} · ${LABEL[state]}: ${reason}`
1009}
1010
1011/** The reason recommend gives a thread that was updated before and has something newer since. */
1012const UPDATED_HERE = 'new since this thread was updated'
1013/** (0.5.5) Whether the thread a row acts on is the thread drawing the pane. */
1014const isHere = (row: Row, here: string | undefined): boolean => Boolean(here) && row.target === here
1015/** (0.5.5) The most characters of a button's label. */
1016export const LABEL_MAX = 40
1017
1018/**
1019 * (0.5.5, Rob 10-14: in one client's thread pane, another client's row offered "Claim in this thread", as if it would
1020 * claim that client there) A row's button as it is drawn in the thread `here`: `Claim in this thread` only in the thread it
1021 * acts on; in any other, `Claim in <client>'s thread`, the client's name cut to keep the label within LABEL_MAX.
1022 */
1023export function buttonLabel(verb: RowButton, row: Row, here: string | undefined): string {
1024 if (verb !== 'claim' || isHere(row, here)) return LABEL[verb]
1025 const room = LABEL_MAX - "Claim in 's thread".length
1026 const client = row.client.length > room ? `${row.client.slice(0, room - 1).trimEnd()}…` : row.client
1027 return `Claim in ${client}'s thread`
1028}
1029
1030/**
1031 * The band's line as it is drawn: as it is beside its button, and with how to open the list where the
1032 * band can carry no button. (On this build the band is raised on the terminal and desktop surfaces only,
1033 * and both draw a Button.) (0.5.14) The band's button is Start missing threads now, not Open list: /mm opens the
1034 * list, from the band of a surface with no button as from any other.
1035 */
1036export const bandWords = (text: string, hasButton: boolean): string => (hasButton ? text : `${text} · type /mm to open the list`)
1037
1038/** A row for a client that has no thread at all: the ones to notice first (not a client whose thread is old or long). */
1039export const isNewRow = (row: Row): boolean => row.fresh ?? (rowState(row) === 'start' && !row.target)
1040
1041/** The mark before the number of a row with no thread yet. */
1042export const NEW_MARK = '◆ '
1043
1044/**
1045 * The list in the two groups it is drawn in (Rob, 2026-10-12: clients "that have sent a message and don't
1046 * have a thread yet should be highlighted somehow in the list"): first the clients with no thread yet,
1047 * then the ones in a thread. Each keeps the order it came in (soonest due first), and a group with nobody
1048 * in it is not drawn. `n` is the row's number in the whole list.
1049 */
1050export function rowGroups(rows: readonly Row[]): Array<{ heading: string; rows: Array<{ row: Row; n: number; mark: string }> }> {
1051 const fresh = rows.filter(isNewRow)
1052 const threaded = rows.filter(r => !isNewRow(r))
1053 const numbered = (group: readonly Row[], from: number, mark: string) => group.map((row, i) => ({ row, n: from + i + 1, mark }))
1054 return [
1055 { heading: `New: no thread yet (${fresh.length})`, rows: numbered(fresh, 0, NEW_MARK) },
1056 { heading: `In a thread (${threaded.length})`, rows: numbered(threaded, fresh.length, '') },
1057 ].filter(g => g.rows.length > 0)
1058}
1059
1060export type Fold = 'checking' | 'teammate' | 'older'
1061
1062/** The groups under the list as a pane holds them. */
1063export type Folds = { checking?: readonly Row[]; teammate?: readonly Row[]; older?: readonly Row[] }
1064
1065/**
1066 * The groups under the list, in the order they are drawn: (0.5.2, R8, Opus decision 2) `Checking your reply
1067 * (n)`, then `With a teammate (n)`, then `Older (n)`. Each is closed until the person opens it, and one with
1068 * nobody in it is not drawn. Their rows are numbered on from the list's. Nobody in them is pinned, and the
1069 * header does not count them.
1070 */
1071export function foldGroups(queue: { rows: readonly Row[] } & Folds): Array<{ key: Fold; heading: string; rows: Array<{ row: Row; n: number }> }> {
1072 const checking = Array.isArray(queue.checking) ? queue.checking : []
1073 const teammate = Array.isArray(queue.teammate) ? queue.teammate : []
1074 const older = Array.isArray(queue.older) ? queue.older : []
1075 const numbered = (group: readonly Row[], from: number) => group.map((row, i) => ({ row, n: from + i + 1 }))
1076 const groups: Array<{ key: Fold; heading: string; rows: Array<{ row: Row; n: number }> }> = [
1077 { key: 'checking', heading: `Checking your reply (${checking.length})`, rows: numbered(checking, queue.rows.length) },
1078 { key: 'teammate', heading: `With a teammate (${teammate.length})`, rows: numbered(teammate, queue.rows.length + checking.length) },
1079 { key: 'older', heading: `Older (${older.length})`, rows: numbered(older, queue.rows.length + checking.length + teammate.length) },
1080 ]
1081 return groups.filter(g => g.rows.length > 0)
1082}
1083
1084/**
1085 * The pane as plain text, one line per thing drawn: for tests and for a surface that draws no buttons. `folds` are the groups under the list, each drawn open.
1086 * `here` (0.5.5): the thread drawing it, as for `rowDetail` and `buttonLabel`.
1087 */
1088export function paneText(rows: readonly Row[], header: string, note: string, folds: Folds = {}, here?: string): string {
1089 const out = [header]
1090 const draw = (row: Row, lead: string): void => {
1091 out.push('', `${lead} ${row.title}`, ` ${rowDetail(row, here)}`)
1092 if (row.note) out.push(` ${row.note}`)
1093 for (const item of isStillOpenRow(row) ? (row.stillOpen as string[]) : []) out.push(` - ${item}`)
1094 out.push(` ${rowButtons(row).map(b => `[ ${buttonLabel(b, row, here)} ]`).join(' ')}`)
1095 }
1096 for (const group of rowGroups(rows)) {
1097 out.push('', group.heading)
1098 for (const { row, n, mark } of group.rows) draw(row, `${mark}${n}.`)
1099 }
1100 for (const group of foldGroups({ rows, ...folds })) {
1101 out.push('', group.heading)
1102 for (const { row, n } of group.rows) draw(row, `${n}.`)
1103 }
1104 out.push('', note)
1105 return out.join('\n')
1106}
1107
1108// ---------------------------------------------------------------- the band (R9)
1109
1110/** The pane's one line when the refresh after a press failed (Opus, 10-13, L3): until the next sync that works. Also the band's, when the last read failed (R9). */
1111export const REFRESH_FAILED = 'Couldn\'t refresh the list. Showing what was last loaded.'
1112
1113/** The band's words for what it carries, in the order R9 sets: its first line, then the alert that is most specific. */
1114export type BandFacts = {
1115 /** Threads the last sync pinned. */
1116 pinned: number
1117 /** Whether anything on the list pins now (past, or within the next 24 business hours). */
1118 pinsNow: boolean
1119 /**
1120 * R4: clients on the list due within that window with no thread at all, soonest first, with their due times, and
1121 * (0.5.4, C3) the thread their one chip is in, as `threadTitleShort` names it, when there is one.
1122 */
1123 noThread: Array<{ client: string; due: string; chipIn?: string | undefined; chipHere?: boolean | undefined }>
1124 /** (0.5.4, C2) The other threads that hold a chip for a client of the person's with a thread, one entry each, by name. */
1125 chipsElsewhere?: string[]
1126 /** (0.5.5) A later mm-bridge installed on this machine than the one this thread runs: its version. */
1127 newer?: string | undefined
1128 /** (0.5.7) Lines the band shows in every thread for a while: a thread started by itself, the hourly cap reached. */
1129 notes?: string[]
1130 /** R8: the first client still open after our reply, with a thread to claim it in. */
1131 stillOpen?: string | undefined
1132 /** R9: the first client whose pinned thread has an update ready to claim. */
1133 update?: string | undefined
1134 /** The last sync failed, or is older than STALE_SYNC_MS: never an all-clear from it. */
1135 stale: boolean
1136 /** (fix round 1, F6) The person's own clients listed under Older: their only items were due before the list's floor, Wed 2026-10-14 (until 2026-10-20 the cut was 3 business days back; Rob replaced it with LIST_FLOOR_MS). */
1137 older?: number
1138}
1139
1140/**
1141 * R9 (Rob, 2026-10-13: "the band line is the alert"; and "yes band": the line always states the full truth, so an
1142 * empty Pinned list can never read as all clear while someone still needs the person). Its words, verbatim:
1143 * something pinned, no client without a thread `Needs you: <n> pinned.`
1144 * clients without a thread (R4) `Needs you: <n> pinned · <m> with no thread: <names>.`, and for
1145 * one client, R9's open-a-thread line after it
1146 * a client still open after our reply (R8) ` · <client> still open after your reply.` on the first line
1147 * an update ready on a pinned thread R9's line after the first
1148 * nothing within 24 business hours, no client `Nothing needs you in the next 24 hours.`
1149 * without a thread
1150 * the last read failed or is stale 0.5.1's refresh-failed line, and never the all-clear one
1151 * (0.5.4, Rob 10-14 "yes chips", verbatim) A client's chip is in one thread only:
1152 * chips of clients with a thread, elsewhere (C2) ` · a chip is ready in <thread>` on the first line, or
1153 * ` · chips ready in <n> threads` for more than one
1154 * a client with no thread whose chip exists (C3) `🔴 <client> has no thread (due <due>): its chip is in <thread>.`,
1155 * in every thread, for each such client; (0.5.6) in any thread but
1156 * that one, followed by ` Press Start thread in the pane to bring it here.`
1157 * (0.5.5, Rob 10-14, verbatim) A later mod installed than this thread runs: ` · A newer Claude mod (<version>) is
1158 * installed: quit and reopen Claude to load it.` at the end of the first line (of the last, when there is no first).
1159 */
1160export function bandText(f: BandFacts): string {
1161 const out: string[] = []
1162 const older = Number(f.older) || 0
1163 const elsewhere = f.chipsElsewhere ?? []
1164 let first = ''
1165 if (f.noThread.length) first = `Needs you: ${f.pinned} pinned · ${f.noThread.length} with no thread: ${f.noThread.map(n => n.client).join(', ')}.`
1166 else if (f.pinsNow || f.pinned > 0 || f.stillOpen) first = `Needs you: ${f.pinned} pinned.`
1167 // (fix round 1, F6) never all clear while the person's own clients wait under Older
1168 else if (!f.stale) first = older > 0 ? `Nothing due in the next 24 hours · ${older} older overdue.` : 'Nothing needs you in the next 24 hours.'
1169 // R8, when no client without a thread comes before it
1170 if (first && !f.noThread.length && f.stillOpen) first = `${first.replace(/\.$/, '')} · ${f.stillOpen} still open after your reply.`
1171 // F6: the other forms say how many wait under Older
1172 if (first.startsWith('Needs you:') && older > 0) first = `${first.replace(/\.$/, '')} · ${older} older overdue.`
1173 // (0.5.4, C2) where the chips of the person's clients with a thread are, when not here
1174 if (first.startsWith('Needs you:') && elsewhere.length) first = `${first.replace(/\.$/, '')} · ${elsewhere.length === 1 ? `a chip is ready in ${elsewhere[0]}` : `chips ready in ${elsewhere.length} threads`}.`
1175 // (0.5.5) a later mod installed on this machine
1176 const newer = f.newer ? `A newer Claude mod (${f.newer}) is installed: quit and reopen Claude to load it.` : ''
1177 if (first && newer) first = `${first.replace(/\.$/, '')} · ${newer}`
1178 if (first) out.push(first)
1179 // (0.5.4, C3) each client with no thread whose one chip exists: where it is; (0.5.6) and, in any other thread
1180 // than that one, that Start thread brings it here
1181 for (const n of f.noThread) {
1182 if (!n.chipIn) continue
1183 out.push(`🔴 ${n.client} has no thread (due ${n.due}): its chip is in ${n.chipIn}.${n.chipHere ? '' : ' Press Start thread in the pane to bring it here.'}`)
1184 }
1185 const one = f.noThread.length === 1 ? f.noThread[0] : undefined
1186 if (one && !one.chipIn) out.push(`Open a thread for ${one.client} (due ${one.due}): type /mm start ${one.client}.`)
1187 else if (!f.noThread.length && !f.stillOpen && f.update) out.push(`An update is ready to claim in the ${f.update} thread.`)
1188 // (0.5.7) a thread started by itself, the hourly cap reached: for a while, in every thread
1189 for (const note of f.notes ?? []) out.push(note)
1190 if (f.stale) out.push(REFRESH_FAILED)
1191 // (with no first line, after the last one there is)
1192 if (newer && !first) {
1193 const tail = out.pop()
1194 out.push(tail ? `${tail.replace(/\.$/, '')} · ${newer}` : newer)
1195 }
1196 return out.join(' ')
1197}
1198hooks/track.ts 731 lines1// Pure tracking logic for the Massmarket bridge (0.6.0): no `$`, so tests can call it directly.
2//
3// Rob, 2026-10-25: "I think we need the side panel to be open on all bridge-connected threads... anytime a team
4// member is talking about a client, the bridge connects, even if there's more than one thread per client... mainly
5// I'm wanting there to always be a side panel if there's any work being done for a client where it shows the tasks
6// that are being worked on and how much time is tracked to each of them across all their threads... It also gives
7// them confirmation that their current work is being tracked."
8//
9// So each thread on this machine has a CURRENT PROJECT (`mm.current`), whatever told the bridge last: a skill the
10// thread loaded, the feed's rows for its sessions, a marker kickoff, /mm link, the person's press on the band, or the
11// thread being the client's linked (primary) thread. The pane shows the time OW tracked to that project today and
12// this week, across every thread of it (`/api/ext/client-time`), and the status line says the thread is counted.
13//
14// ⛔ Everything drawn here is drawn only: names, titles and task labels are the person's or OW's text, kept to one
15// line (`shownText`). Only `noteFor`'s words go to Claude, and those carry a cleaned client name and a skill key that
16// matched SKILL_KEY.
17
18import type { MmTrackLine } from '../types'
19
20import { INTERNAL_OPS, cleanText, cleanTitle, isUuid, shortName, shownText } from './queue'
21
22const MINUTE = 60_000
23
24/** What OW says a project is, for the time tracker's labels: a client, Massmarket's internal ops, or its own sales and marketing. */
25export type ProjectKind = 'client' | 'internal_ops' | 'self_funnel'
26
27/** One skill the time tracker knows, as `GET /api/ext/skill-map` answers it. */
28export type SkillEntry = { skill_key: string; project_id: string; name: string; kind: ProjectKind }
29
30/** What set a thread's current project (`Current.how`). */
31export type How = 'skill' | 'feed' | 'marker' | 'link' | 'press' | 'primary'
32
33/**
34 * (0.6.0) A thread's current project on this machine (`mm.current`, by the app's thread id, or `cli:<session id>` for
35 * a terminal session): which project, what set it and when (`at`: the latest source wins), the task the thread
36 * declared for it (`--task`), when the sync last saw the thread in the app's list (`seen`), its last activity there
37 * (`act`), when the sync last asked the app whether it was archived (`chk`), and the clients it has declared (the
38 * hub check: a thread that declared another client is never made a client's primary by a skill load or a press).
39 */
40export type Current = { pid: string; how: How; at: number; task?: string; seen?: number; act?: number; chk?: number; declared?: string[] }
41
42/** The most clients one thread's `declared` remembers. */
43const DECLARED_MAX = 8
44
45/** A skill key as the bridge accepts one from OW: what a skill folder is named. */
46export const SKILL_KEY = /^[a-z0-9][a-z0-9-]{0,80}$/
47
48/**
49 * The skill's own name from what the Skill tool was called with: anything up to the last `:` is its plugin or its
50 * folder (`plugin:skill`, `apps/web:deploy`), and goes.
51 */
52export function skillName(raw: unknown): string {
53 const s = typeof raw === 'string' ? raw.trim() : ''
54 return s.slice(s.lastIndexOf(':') + 1).trim().toLowerCase()
55}
56
57const KINDS: ReadonlySet<string> = new Set(['client', 'internal_ops', 'self_funnel'])
58
59/** OW's skill map, checked: each entry a known kind, a uuid project and a skill key of the right shape. Null for an answer that is not one. */
60export function parseSkillMap(raw: unknown): { asOf: string; skills: SkillEntry[] } | null {
61 const o = raw as { as_of?: unknown; skills?: unknown } | null
62 if (!o || typeof o !== 'object' || !Array.isArray(o.skills)) return null
63 const skills: SkillEntry[] = []
64 for (const s of o.skills.slice(0, 2_000) as Array<Partial<SkillEntry> | null>) {
65 if (!s || typeof s !== 'object' || typeof s.skill_key !== 'string' || !SKILL_KEY.test(s.skill_key) || !isUuid(s.project_id) || !KINDS.has(String(s.kind))) continue
66 // (the name as OW writes it, one line: the client's short name is cut from it where it is shown, `clientName`)
67 skills.push({ skill_key: s.skill_key, project_id: s.project_id, name: shownText(s.name, 120), kind: s.kind as ProjectKind })
68 }
69 return { asOf: typeof o.as_of === 'string' ? o.as_of.slice(0, 40) : '', skills }
70}
71
72// ---------------------------------------------------------------- deliverable lines (0.7.0, OW `with=lines`)
73//
74// Rob, 2026-10-26: "I want the live panel not just to show what clients are being tracked, but also the task that it
75// thinks we're working on. Maybe even separately, it could show which specific deliverable line those hours are being
76// added for. If it's something that's a new scope, it would be showing up on a new line. That probably should trigger
77// the thread to ask for approval to create the new line, or ask if it would be reconciled."
78//
79// So OW's client-time answer carries, with `&with=lines`, each project's quote lines (`lines`) and its proposed new
80// lines (`proposals`), each thread's line (`thread.line`: what its minutes count toward, and when they match none, the
81// lines they could be) and each task's line (`task.line_key`). An OW that does not have them yet answers as before:
82// every new field is optional here, and a field that is absent or of another shape draws nothing (0.6.0's pane).
83
84/** What a line of a client's quote is: a deliverable, the fixes line, Rob's own time, or an hour bank. */
85export type LineType = 'deliverable' | 'fixes' | 'rob_time' | 'bank'
86/**
87 * One line of a project's quote. `minutes`: this period's counted minutes on it; null when the viewer may not see them
88 * (an estimated line, for anyone but a PM or the founder).
89 */
90export type ScopeLine = { line_key: string; title: string; line_type: LineType; status: string; estimate_hours: number | null; minutes: number | null }
91/** A proposed new line: an OW ticket waiting for the client's yes. */
92export type ScopeProposal = { ticket_id8: string; title: string; created_at: string }
93/** What OW makes of a thread's minutes. */
94export type LineSignal = 'on_line' | 'account_work' | 'fix' | 'unmatched' | 'maybe_new_scope' | 'no_quote' | 'proposed'
95/** How a thread's line was found: the line its task label declared, its ticket's line, the hour bank, or none. */
96export type LineVia = 'declared' | 'ticket' | 'bank' | 'none'
97export type LineRef = { line_key: string; title: string; line_type: LineType }
98/** (0.7.0) A thread's line as OW gives it (`thread.line`). */
99export type ThreadLine = {
100 via: LineVia
101 line_key: string | null
102 title: string | null
103 line_type: LineType | null
104 estimate_hours: number | null
105 signal: LineSignal
106 candidates: LineRef[]
107 proposal: { ticket_id8: string; title: string } | null
108}
109
110/** A line's key as OW writes it (`L-1a2b3c4d`), in characters that are safe in a sentence for Claude and in a shell command. */
111export const LINE_KEY = /^L-[0-9A-Za-z]{4,32}$/
112/** An OW ticket's short id: its first 8 hex digits. */
113export const TICKET8 = /^[0-9a-f]{8}$/i
114/** The most lines, proposals and candidates kept from an answer. */
115export const LINE_ROWS = { lines: 40, proposals: 10, candidates: 5 } as const
116
117const LINE_TYPES: ReadonlySet<string> = new Set(['deliverable', 'fixes', 'rob_time', 'bank'])
118const SIGNALS: ReadonlySet<string> = new Set(['on_line', 'account_work', 'fix', 'unmatched', 'maybe_new_scope', 'no_quote', 'proposed'])
119const VIAS: ReadonlySet<string> = new Set(['declared', 'ticket', 'bank', 'none'])
120
121const objOf = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {})
122/** A number OW may leave out: a finite number of zero or more, else null. */
123const optNum = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null)
124
125function scopeLine(raw: unknown): ScopeLine | null {
126 const o = objOf(raw)
127 if (typeof o.line_key !== 'string' || !LINE_KEY.test(o.line_key) || !LINE_TYPES.has(String(o.line_type))) return null
128 return {
129 line_key: o.line_key, title: shownText(o.title, 120) || o.line_key, line_type: o.line_type as LineType, status: shownText(o.status, 40),
130 estimate_hours: optNum(o.estimate_hours), minutes: optNum(o.minutes),
131 }
132}
133
134function lineRef(raw: unknown): LineRef | null {
135 const o = objOf(raw)
136 if (typeof o.line_key !== 'string' || !LINE_KEY.test(o.line_key)) return null
137 return { line_key: o.line_key, title: shownText(o.title, 120) || o.line_key, line_type: LINE_TYPES.has(String(o.line_type)) ? (o.line_type as LineType) : 'deliverable' }
138}
139
140function scopeProposal(raw: unknown): ScopeProposal | null {
141 const o = objOf(raw)
142 if (typeof o.ticket_id8 !== 'string' || !TICKET8.test(o.ticket_id8)) return null
143 return { ticket_id8: o.ticket_id8.toLowerCase(), title: shownText(o.title, 120) || o.ticket_id8.toLowerCase(), created_at: shownText(o.created_at, 40) }
144}
145
146/** (0.7.0) A thread's line, checked: undefined for one that is absent or whose signal OW does not use. */
147export function parseThreadLine(raw: unknown): ThreadLine | undefined {
148 if (!raw || typeof raw !== 'object') return undefined
149 const o = objOf(raw)
150 if (!SIGNALS.has(String(o.signal))) return undefined
151 const proposal = objOf(o.proposal)
152 return {
153 via: VIAS.has(String(o.via)) ? (o.via as LineVia) : 'none',
154 line_key: typeof o.line_key === 'string' && LINE_KEY.test(o.line_key) ? o.line_key : null,
155 title: optStr(o.title, 120),
156 line_type: LINE_TYPES.has(String(o.line_type)) ? (o.line_type as LineType) : null,
157 estimate_hours: optNum(o.estimate_hours),
158 signal: o.signal as LineSignal,
159 candidates: (Array.isArray(o.candidates) ? o.candidates : []).slice(0, 20).map(lineRef).filter((x): x is LineRef => x !== null).slice(0, LINE_ROWS.candidates),
160 proposal: typeof proposal.ticket_id8 === 'string' && TICKET8.test(proposal.ticket_id8) ? { ticket_id8: proposal.ticket_id8.toLowerCase(), title: shownText(proposal.title, 120) } : null,
161 }
162}
163
164/** (0.7.0) A project's lines or proposals: undefined when OW sent no list (it does not have them yet), else the entries of the right shape. */
165function listOf<T>(raw: unknown, each: (x: unknown) => T | null, max: number): T[] | undefined {
166 if (!Array.isArray(raw)) return undefined
167 return raw.slice(0, 200).map(each).filter((x): x is T => x !== null).slice(0, max)
168}
169
170// ---------------------------------------------------------------- client time (OW's /api/ext/client-time)
171
172export type TimePerson = { email: string; name: string; minutes: number }
173/** (0.7.0) `line_key`: the line the task's minutes count toward, when OW says. */
174export type TimeTask = { task: string | null; ticket_id: string | null; minutes: number; thread_count: number; people: string[]; last_activity_at: string; active_now: boolean; line_key?: string }
175export type TimePeriod = {
176 client_minutes: number
177 by_source: { claude_code: number; timer: number; browser: number; meeting: number }
178 thread_minutes: number
179 parallel: number | null
180 jarvis_minutes: number
181 people: TimePerson[]
182 tasks: TimeTask[]
183}
184/** (0.7.0) `line`: what OW makes of the thread's minutes (`thread.line`), when it says. */
185export type TimeThread = { session_id: string; title: string | null; member_email: string; member_name: string; task: string | null; ticket_id: string | null; minutes_today: number; last_activity_at: string; active_now: boolean; line?: ThreadLine }
186export type TimeLeverage = { ratio: number | null; build_hours: number; actual_hours: number; window: string; note: string }
187/**
188 * One project's time. A period OW was not asked for (`periods=today`) is null; `threads` come with today alone and
189 * `leverage` with the week alone. (0.7.0) `lines` and `proposals` come with today too, only from an OW that has them
190 * (`with=lines`): absent, not empty, when it does not.
191 */
192export type TimeProject = { project_id: string; name: string; today: TimePeriod | null; week: TimePeriod | null; threads: TimeThread[]; leverage: TimeLeverage | null; lines?: ScopeLine[]; proposals?: ScopeProposal[] }
193export type ClientTime = { asOf: string; day: string; weekStart: string; viewer: { email: string; canSeeLeverage: boolean }; skipped: string[]; projects: TimeProject[] }
194
195/** The most rows of each list kept from an answer, so the store stays far under its cap. */
196export const TIME_ROWS = { threads: 30, tasks: 20, people: 20 } as const
197
198const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0)
199const str = (v: unknown, max: number): string => shownText(v, max)
200const optStr = (v: unknown, max: number): string | null => (typeof v === 'string' && v.trim() ? shownText(v, max) : null)
201
202function period(raw: unknown): TimePeriod {
203 const p = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>
204 const src = (p.by_source && typeof p.by_source === 'object' ? p.by_source : {}) as Record<string, unknown>
205 const people = (Array.isArray(p.people) ? p.people : []).slice(0, TIME_ROWS.people).map(x => {
206 const o = (x && typeof x === 'object' ? x : {}) as Record<string, unknown>
207 return { email: str(o.email, 120), name: str(o.name, 60), minutes: num(o.minutes) }
208 })
209 const tasks = (Array.isArray(p.tasks) ? p.tasks : []).slice(0, TIME_ROWS.tasks).map(x => {
210 const o = (x && typeof x === 'object' ? x : {}) as Record<string, unknown>
211 return {
212 task: optStr(o.task, 120), ticket_id: optStr(o.ticket_id, 60), minutes: num(o.minutes), thread_count: num(o.thread_count),
213 people: (Array.isArray(o.people) ? o.people : []).slice(0, 10).map(e => str(e, 120)).filter(Boolean),
214 last_activity_at: str(o.last_activity_at, 40), active_now: o.active_now === true,
215 ...(typeof o.line_key === 'string' && LINE_KEY.test(o.line_key) ? { line_key: o.line_key } : {}),
216 }
217 })
218 const parallel = typeof p.parallel === 'number' && Number.isFinite(p.parallel) && p.parallel >= 0 ? p.parallel : null
219 return {
220 client_minutes: num(p.client_minutes),
221 by_source: { claude_code: num(src.claude_code), timer: num(src.timer), browser: num(src.browser), meeting: num(src.meeting) },
222 thread_minutes: num(p.thread_minutes), parallel, jarvis_minutes: num(p.jarvis_minutes), people, tasks,
223 }
224}
225
226/**
227 * OW's client-time answer, checked and trimmed (TIME_ROWS): each project a uuid, every number a number, every text one
228 * line. Null for an answer that is not one (a 200 with another shape is a failed read, never "no time").
229 */
230export function parseClientTime(raw: unknown): ClientTime | null {
231 const o = raw as Record<string, unknown> | null
232 if (!o || typeof o !== 'object' || !Array.isArray(o.projects)) return null
233 const viewer = (o.viewer && typeof o.viewer === 'object' ? o.viewer : {}) as Record<string, unknown>
234 const projects: TimeProject[] = []
235 for (const x of o.projects.slice(0, 40) as unknown[]) {
236 const p = (x && typeof x === 'object' ? x : {}) as Record<string, unknown>
237 if (!isUuid(p.project_id)) continue
238 const lev = p.leverage && typeof p.leverage === 'object' ? (p.leverage as Record<string, unknown>) : null
239 // (0.7.0) only from an OW that sends them: absent stays absent
240 const lines = listOf(p.lines, scopeLine, LINE_ROWS.lines)
241 const proposals = listOf(p.proposals, scopeProposal, LINE_ROWS.proposals)
242 projects.push({
243 project_id: p.project_id, name: str(p.name, 80), today: p.today == null ? null : period(p.today), week: p.week == null ? null : period(p.week),
244 threads: (Array.isArray(p.threads) ? p.threads : []).slice(0, TIME_ROWS.threads).map(t => {
245 const r = (t && typeof t === 'object' ? t : {}) as Record<string, unknown>
246 const line = parseThreadLine(r.line)
247 return {
248 session_id: str(r.session_id, 100), title: optStr(r.title, 80), member_email: str(r.member_email, 120), member_name: str(r.member_name, 60),
249 task: optStr(r.task, 120), ticket_id: optStr(r.ticket_id, 60), minutes_today: num(r.minutes_today), last_activity_at: str(r.last_activity_at, 40), active_now: r.active_now === true,
250 ...(line ? { line } : {}),
251 }
252 }),
253 leverage: lev
254 ? { ratio: typeof lev.ratio === 'number' && Number.isFinite(lev.ratio) && lev.ratio >= 0 ? lev.ratio : null, build_hours: num(lev.build_hours), actual_hours: num(lev.actual_hours), window: str(lev.window, 60), note: str(lev.note, 200) }
255 : null,
256 ...(lines ? { lines } : {}),
257 ...(proposals ? { proposals } : {}),
258 })
259 }
260 return {
261 asOf: typeof o.as_of === 'string' ? o.as_of.slice(0, 40) : '',
262 day: typeof o.day === 'string' ? o.day.slice(0, 20) : '',
263 weekStart: typeof o.week_start === 'string' ? o.week_start.slice(0, 20) : '',
264 viewer: { email: str(viewer.email, 120), canSeeLeverage: viewer.can_see_leverage === true },
265 skipped: (Array.isArray(o.skipped) ? o.skipped : []).filter(isUuid).slice(0, 40),
266 projects,
267 }
268}
269
270// ---------------------------------------------------------------- a thread's current project
271
272/**
273 * (0.6.0) A source's word on a thread's current project, merged with what is on record: the latest source wins (by
274 * `at`). The same project keeps its task (a new one replaces it); another project starts with the task given, or
275 * none. Null when nothing changes: an older source than the one on record, or the same word again.
276 */
277export function mergeCurrent(prev: Current | undefined, next: { pid: string; how: How; at: number; task?: string | undefined }, client: boolean): Current | null {
278 if (!isUuid(next.pid) || !Number.isFinite(next.at)) return null
279 const had = prev && typeof prev === 'object' && isUuid(prev.pid) ? prev : undefined
280 if (had && Number(had.at) > next.at) return null
281 const declared = [...(had?.declared ?? []).filter(isUuid)]
282 if (client && !declared.includes(next.pid)) declared.push(next.pid)
283 const kept = declared.slice(-DECLARED_MAX)
284 const extra = { ...(had?.seen ? { seen: had.seen } : {}), ...(had?.act ? { act: had.act } : {}), ...(had?.chk ? { chk: had.chk } : {}), ...(kept.length ? { declared: kept } : {}) }
285 if (had && had.pid === next.pid) {
286 const task = next.task ?? had.task
287 const merged: Current = { pid: next.pid, how: next.how, at: next.at, ...(task ? { task } : {}), ...extra }
288 return JSON.stringify(merged) === JSON.stringify(had) ? null : merged
289 }
290 return { pid: next.pid, how: next.how, at: next.at, ...(next.task ? { task: next.task } : {}), ...extra }
291}
292
293/** The task label a worklog-hook command declares (`--task "<label>"` or `--task=<label>`), as typed, at most 120 characters; '' when it declares none. */
294export function taskFrom(command: unknown): string {
295 if (typeof command !== 'string' || command.length > 20_000 || !/worklog-hook\.js\b/.test(command)) return ''
296 const m = /worklog-hook\.js\b[^\n]*?\s--task(?:=|\s+)(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([^\s"'][^\s]*))/.exec(command)
297 if (!m) return ''
298 const label = (m[1] ?? m[2] ?? m[3] ?? '').replace(/\\(.)/g, '$1')
299 return taskLabel(label)
300}
301
302/** A task label as it is kept: one line, its first 120 characters. */
303export function taskLabel(text: unknown): string {
304 const one = (typeof text === 'string' ? text : '').normalize('NFC').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').replace(/\s+/g, ' ').trim()
305 return one.slice(0, 120).trim()
306}
307
308// ---------------------------------------------------------------- what is shown
309
310/** (0.6.0) The pane's title and the name a thread's project goes by: internal ops and self-funnel by their own words. */
311export const INTERNAL_NAME = 'Massmarket internal'
312export const SELF_FUNNEL_NAME = 'Massmarket sales and marketing'
313
314export function displayName(kind: ProjectKind, name: string): string {
315 return kind === 'internal_ops' ? INTERNAL_NAME : kind === 'self_funnel' ? SELF_FUNNEL_NAME : name
316}
317
318/** A project's kind when OW's skill map does not say: Massmarket's internal-ops project by its id, any other a client. */
319export const kindOf = (pid: string, skills: readonly SkillEntry[]): ProjectKind => skills.find(s => s.project_id === pid)?.kind ?? (pid === INTERNAL_OPS ? 'internal_ops' : 'client')
320
321/** A client's name from the skill map's or OW's project name: the short name the bridge gives clients everywhere. */
322export const clientName = (name: string): string => (name ? shortName(name) : '')
323
324/** `42m`, `1h 05m`. */
325export function fmtMin(m: number): string {
326 const t = Math.max(0, Math.round(Number(m) || 0))
327 return t < 60 ? `${t}m` : `${Math.floor(t / 60)}h ${String(t % 60).padStart(2, '0')}m`
328}
329
330/** Hours with one decimal: `1.3`. */
331export const fmtHours = (m: number): string => (Math.max(0, Number(m) || 0) / 60).toFixed(1)
332
333/** A number of hours as OW gives them, with one decimal. */
334const fmtH = (h: number): string => Math.max(0, Number(h) || 0).toFixed(1)
335
336/** Two significant digits: `1.3`, `12`, `0.46`. */
337export function fmtX(x: number): string {
338 const v = Number(x)
339 if (!Number.isFinite(v) || v <= 0) return '0'
340 if (v >= 100) return String(Math.round(v))
341 const s = v.toPrecision(2)
342 return s.includes('e') ? String(Math.round(v)) : s
343}
344
345/** A moment as the person's own clock writes it: `2:14 PM`. */
346export function localClock(t: number): string {
347 try {
348 return new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit' }).format(new Date(t)).replace(/ /g, ' ')
349 } catch {
350 return new Date(t).toISOString().slice(11, 16)
351 }
352}
353
354/** Someone's first name, or the part of their address before the @ when OW gives no name. */
355export function firstName(name: string, email: string): string {
356 const first = (name || '').trim().split(/\s+/)[0] ?? ''
357 return first || (email.split('@')[0] ?? '') || 'someone'
358}
359
360/**
361 * What a thread has on record of its project's time (`mm.time`): the project as last read, today's read (`at`, `asOf`)
362 * and the week's (`weekAt`, `weekAsOf`) each with its own time, and a read that failed after them.
363 */
364export type TimeRecord = { at?: number; asOf?: string; weekAt?: number; weekAsOf?: string; p?: TimeProject; failedAt?: number; skipped?: true }
365
366/** (0.6.0, OW contract 2026-10-25) A project's week (and leverage) is asked for at most this often; today on every read. */
367export const WEEK_EVERY_MS = 30 * 60_000
368
369/** (0.6.0) Whether a read of this project asks for the week too: on its first read, and once WEEK_EVERY_MS has passed. */
370export const weekIsDue = (rec: TimeRecord | undefined, now: number): boolean => !(now - (Number(rec?.weekAt) || 0) < WEEK_EVERY_MS)
371
372/**
373 * (0.6.0) An answer for one project merged into its record: today (and its threads) from this read when it carries
374 * today, the week (and its leverage) from this read when the week was asked for and came, and otherwise each kept as
375 * last read, with that read's own as-of. A failure noted before is cleared.
376 */
377export function mergeTime(prev: TimeRecord | undefined, got: TimeProject, at: number, asOf: string, askedWeek: boolean): TimeRecord {
378 const old = prev?.p
379 const todayCame = got.today !== null
380 const weekCame = askedWeek && got.week !== null
381 // (0.7.0) the lines and proposals come with today, as the threads do
382 const lines = todayCame ? got.lines : old?.lines
383 const proposals = todayCame ? got.proposals : old?.proposals
384 const p: TimeProject = {
385 project_id: got.project_id,
386 name: got.name || old?.name || '',
387 today: todayCame ? got.today : (old?.today ?? null),
388 week: weekCame ? got.week : (old?.week ?? null),
389 threads: todayCame ? got.threads : (old?.threads ?? []),
390 leverage: weekCame ? got.leverage : (old?.leverage ?? null),
391 ...(lines ? { lines } : {}),
392 ...(proposals ? { proposals } : {}),
393 }
394 const rec: TimeRecord = {
395 at: todayCame || prev?.at === undefined ? at : prev.at,
396 asOf: todayCame || prev?.asOf === undefined ? asOf : prev.asOf,
397 p,
398 }
399 if (askedWeek) rec.weekAt = at
400 else if (prev?.weekAt !== undefined) rec.weekAt = prev.weekAt
401 if (weekCame) rec.weekAsOf = asOf
402 else if (prev?.weekAsOf !== undefined) rec.weekAsOf = prev.weekAsOf
403 return rec
404}
405
406export type TrackInput = {
407 /** The project's name as shown (`displayName`). */
408 client: string
409 task?: string | undefined
410 time?: TimeRecord | undefined
411 /** OW answered 404 for the route in the last 30 minutes. */
412 missing: boolean
413 canSeeLeverage: boolean
414 /** Whether a session id is one of this thread's own. */
415 mine: (sessionId: string) => boolean
416 /** The app thread a row's press opens, when it is another thread on this machine. */
417 openable?: (sessionId: string) => string | undefined
418}
419
420/** (0.6.0, verbatim) What the dim explanation under the numbers says. */
421export const numbersNote = (client: string): string =>
422 `Tracked counts each minute once per person. In threads counts every thread in full. Parallel is the second divided by the first. Jarvis is work done for ${client} with nobody in the thread.`
423
424export const NOT_AVAILABLE = 'Time numbers are not available yet.'
425export const CHECKING_TIME = 'Checking…'
426export const COULD_NOT_REFRESH = ' · could not refresh; showing the last numbers'
427
428const threads = (n: number): string => `${n} thread${n === 1 ? '' : 's'}`
429
430/** This thread's minutes today, and whether its session is in the numbers at all. */
431export function thisThread(p: TimeProject | undefined, mine: (sid: string) => boolean): { minutes: number; counted: boolean } {
432 const rows = (p?.threads ?? []).filter(t => mine(t.session_id))
433 return { minutes: rows.reduce((sum, t) => sum + t.minutes_today, 0), counted: rows.length > 0 }
434}
435
436function numbersLine(label: string, p: TimePeriod): string {
437 const parallel = p.parallel === null ? '' : ` · parallel ${fmtX(p.parallel)}×`
438 return `${label}: ${fmtHours(p.client_minutes)} h tracked · ${fmtHours(p.thread_minutes)} h in threads${parallel} · Jarvis ${fmtHours(p.jarvis_minutes)} h`
439}
440
441/**
442 * (0.6.0) The Tracking part of the pane, line by line, in the words of the spec (2026-10-25, verbatim labels): the
443 * heading, this thread and the client today, the tasks today, the threads today, the numbers, and when they are from.
444 */
445export function trackLines(t: TrackInput): MmTrackLine[] {
446 const out: MmTrackLine[] = []
447 out.push({ text: `Tracking to ${t.client} · ${t.task ? t.task : 'no task declared yet'}`, bold: true })
448 const rec = t.time
449 const p = rec?.p
450 const day = p?.today
451 if (!p || !day) {
452 out.push({ text: rec?.skipped || rec?.failedAt || t.missing ? NOT_AVAILABLE : CHECKING_TIME, dim: true })
453 return out
454 }
455 // (0.7.0) what this thread's minutes count toward, under the heading; nothing from an OW that does not say
456 const line = lineOfThread(p, t.mine)?.line
457 if (line) out.push({ text: countsToward(line, p, t.client) })
458 const here = thisThread(p, t.mine)
459 const today = `${t.client} today: ${fmtMin(day.client_minutes)} tracked across ${threads(p.threads.length)}`
460 out.push({ text: here.counted ? `This thread: ${fmtMin(here.minutes)} today · ${today}` : `This thread: not in the numbers yet (they refresh every 5 minutes) · ${today}`, dim: true })
461
462 out.push({ text: 'Tasks today', bold: true })
463 if (!day.tasks.length) out.push({ text: `Nothing tracked to ${t.client} yet today.`, dim: true })
464 const names = new Map(day.people.map(x => [x.email.toLowerCase(), x.name]))
465 for (const task of day.tasks) {
466 const who = task.people.map(e => firstName(names.get(e.toLowerCase()) ?? '', e)).join(', ')
467 // (0.7.0) the line the task counts toward, when it is one of the project's lines
468 const onLine = task.line_key ? lineByKey(p, task.line_key) : undefined
469 out.push({ text: `${task.active_now ? '● ' : ' '}${task.task ?? 'No task declared'} · ${fmtMin(task.minutes)}${who ? ` · ${who}` : ''}${onLine ? ` → ${shownText(onLine.title, 28)}` : ''}` })
470 }
471
472 // (0.7.0) the lines that took minutes today (those the viewer may see), then the new lines proposed
473 const counted = (p.lines ?? []).filter(l => l.minutes !== null && l.minutes > 0)
474 const proposed = p.proposals ?? []
475 if (counted.length || proposed.length) {
476 out.push({ text: LINES_TODAY, bold: true })
477 for (const l of counted) out.push({ text: `${l.title} · ${fmtMin(l.minutes ?? 0)}${l.estimate_hours !== null && l.minutes !== null ? ` · est ${fmtEst(l.estimate_hours)} h` : ''}` })
478 for (const pr of proposed) out.push({ text: `Proposed: ${pr.title} · waiting for yes` })
479 }
480
481 if (p.threads.length) {
482 out.push({ text: 'Threads today', bold: true })
483 for (const th of p.threads) {
484 const mine = t.mine(th.session_id)
485 const name = th.member_name || (th.member_email.split('@')[0] ?? '') || 'someone'
486 const row = `${th.active_now ? '● ' : ' '}${th.title ?? 'Untitled thread'} ${name} · ${th.task ?? 'no task'} · ${fmtMin(th.minutes_today)}${mine ? ' (this thread)' : ''}`
487 const open = mine ? undefined : t.openable?.(th.session_id)
488 out.push(open ? { text: row, open } : { text: row })
489 }
490 }
491
492 out.push({ text: 'Numbers', bold: true })
493 out.push({ text: numbersLine('Today', day) })
494 // a week never read yet is not loaded: no line, never zeros
495 if (p.week) out.push({ text: numbersLine('This week', p.week) })
496 const lev = p.leverage
497 if (t.canSeeLeverage && lev) {
498 if (lev.ratio !== null) out.push({ text: `Leverage: ${fmtX(lev.ratio)}× (${fmtH(lev.build_hours)} quoted hours done in ${fmtH(lev.actual_hours)} h, last 20 business days)` })
499 else if (lev.note) out.push({ text: `Leverage: ${lev.note}` })
500 }
501 out.push({ text: numbersNote(t.client), dim: true })
502
503 const asOf = Date.parse(rec?.asOf ?? '')
504 const when = Number.isFinite(asOf) ? asOf : Number(rec?.at) || 0
505 const failed = Number(rec?.failedAt) > (Number(rec?.at) || 0)
506 out.push({ text: `As of ${localClock(when)}${failed ? COULD_NOT_REFRESH : ''}`, dim: true })
507 return out
508}
509
510/**
511 * (0.6.0, verbatim) The status line: what this thread is counted to, or that it is not counted yet. Undefined clears it.
512 * (0.7.0) A thread on a line names it after the task: `→ <line title>`, at most 24 characters.
513 */
514export function trackStatus(o: { client?: string | undefined; task?: string | undefined; minutes?: number | undefined; counted?: boolean; nudge?: boolean; line?: string | undefined }): string | undefined {
515 if (o.client) {
516 if (o.counted) return `⏱ ${o.client}${o.task ? ` · ${o.task}` : ''}${o.line ? ` → ${shownText(o.line, 24)}` : ''} · this thread ${fmtMin(o.minutes ?? 0)} today`
517 return `⏱ Tracking to ${o.client}`
518 }
519 return o.nudge ? '⏱ Not tracked to a client yet' : undefined
520}
521
522// ---------------------------------------------------------------- (0.7.0) the line a thread counts toward
523
524/** (0.7.0) The heading of the pane's part that lists the lines that took minutes today. */
525export const LINES_TODAY = 'Lines today'
526
527/** Hours as an estimate is written: `12`, `1.5`. */
528export function fmtEst(h: number): string {
529 const r = Math.round(Math.max(0, Number(h) || 0) * 10) / 10
530 return String(r)
531}
532
533/** A project line by its key. */
534export const lineByKey = (p: TimeProject | undefined, key: string | null | undefined): ScopeLine | undefined => (key ? (p?.lines ?? []).find(l => l.line_key === key) : undefined)
535
536/** A line status that says it no longer takes time. */
537const ENDED = /^(closed|done|complete|completed|cancelled|canceled|archived|exhausted|inactive|declined|rejected)$/i
538
539/** (0.7.0) The project's hour bank: its most recent active bank line (the last OW lists), or undefined. */
540export function bankLine(p: TimeProject | undefined): ScopeLine | undefined {
541 const banks = (p?.lines ?? []).filter(l => l.line_type === 'bank' && !ENDED.test(l.status))
542 const active = banks.filter(l => /^active$/i.test(l.status))
543 return (active.length ? active : banks).at(-1)
544}
545
546/**
547 * (0.7.0) This thread's line: from the newest of its own sessions' rows that carries one, with the task label that
548 * row was counted under (a line OW worked out for an older label is not this label's).
549 */
550export function lineOfThread(p: TimeProject | undefined, mine: (sessionId: string) => boolean): { line: ThreadLine; task: string } | undefined {
551 const rows = (p?.threads ?? []).filter(t => t.line && mine(t.session_id))
552 rows.sort((a, b) => (Date.parse(b.last_activity_at) || 0) - (Date.parse(a.last_activity_at) || 0))
553 const row = rows[0]
554 return row?.line ? { line: row.line, task: row.task ?? '' } : undefined
555}
556
557/** (0.7.0) Whether the thread's minutes count toward a line: on one, or a fix on one. */
558export const onALine = (l: ThreadLine): boolean => l.signal === 'on_line' || (l.signal === 'fix' && l.via !== 'none' && Boolean(l.title || l.line_key))
559
560/** The title of the line a thread counts toward: OW's, else the project line's, else its key. */
561const titleOf = (l: ThreadLine, p: TimeProject | undefined): string => l.title || lineByKey(p, l.line_key)?.title || l.line_key || ''
562
563/** (0.7.0) The line's title the status line names, when the thread is on one. */
564export const statusLineTitle = (l: ThreadLine | undefined, p: TimeProject | undefined): string | undefined => (l && onALine(l) ? titleOf(l, p) || undefined : undefined)
565
566/** (0.7.0, verbatim) The line under the Tracking heading: what this thread's minutes count toward. */
567export function countsToward(l: ThreadLine, p: TimeProject | undefined, client: string): string {
568 switch (l.signal) {
569 case 'on_line':
570 case 'fix': {
571 if (!onALine(l)) return 'Counts toward: no line yet (a fix)'
572 const title = titleOf(l, p) || 'a line on the quote'
573 if (l.via === 'bank') return `Counts toward: ${title} (hour bank)`
574 const line = lineByKey(p, l.line_key)
575 const est = l.estimate_hours ?? line?.estimate_hours ?? null
576 const today = line && line.minutes !== null && line.minutes > 0 ? ` · ${fmtMin(line.minutes)} today` : ''
577 return `Counts toward: ${title}${est !== null ? ` · est ${fmtEst(est)} h` : ''}${today}`
578 }
579 case 'account_work': {
580 if (l.via !== 'bank') return 'Counts toward: account work'
581 const bank = l.title || lineByKey(p, l.line_key)?.title || bankLine(p)?.title
582 return bank ? `Counts toward: account work · ${bank} (hour bank)` : 'Counts toward: account work (hour bank)'
583 }
584 case 'proposed':
585 return `Proposed new line: ${l.proposal?.title || l.title || 'new scope'} · waiting for ${client}'s yes`
586 case 'no_quote':
587 return `Counts toward: no quote on record for ${client}`
588 default:
589 return 'Counts toward: no line yet'
590 }
591}
592
593// ---------------------------------------------------------------- (0.7.0) the line band and the notes for Claude
594
595/** The signals the thread asks about: its minutes match no line on the quote. */
596export const asksForLine = (l: ThreadLine | undefined): l is ThreadLine => l?.signal === 'unmatched' || l?.signal === 'maybe_new_scope'
597
598/** The most candidate lines the band and the thread's note offer. */
599export const LINE_CHOICES = 3
600
601/** (0.7.0) The key the band and the thread's note go by: once per project and task label in a session. */
602export const lineAskKey = (pid: string, task: string | undefined): string => `${pid}|${task ?? ''}`
603
604/** (0.7.0) Whether the line band and the thread's note may show: a client's thread in a person's session that is not a SINGLE-SESSION run or MM_UNATTENDED=1. */
605export const asksInSession = (s: { single?: boolean }, unattended: boolean, client: boolean): boolean => client && !s.single && !unattended
606
607/** (0.7.0, verbatim) The band's words. */
608export const lineAskText = (client: string, signal: LineSignal): string =>
609 signal === 'maybe_new_scope' ? `${client}: this doesn't match a line on the quote.` : `${client}: which line does this work count toward?`
610export const LINE_NEW = 'New scope'
611export const LINE_BANK = 'Hour bank'
612export const LINE_LATER = 'Not now'
613/** A candidate's button: its title, at most 28 characters. */
614export const lineButton = (title: string): string => shownText(title, 28)
615
616/** Text from OW or the person as it may go into a sentence for Claude or a shell command: letters, digits and . , & ' ( ) / - only. */
617export const forClaude = (text: unknown, max = 120): string => cleanText(text, max)
618
619/** (0.7.0, verbatim) The note a press on a candidate adds for Claude. */
620export const lineNote = (client: string, title: string, key: string): string =>
621 `[mm-bridge] The person says this thread's work counts toward ${client}'s line "${title}". Before your next step, call the mm tool with "line ${key}" and do what it returns.`
622
623/** (0.7.0, verbatim) The note a press on New scope adds for Claude. */
624export const newScopeNote = (client: string): string =>
625 `[mm-bridge] The person says this thread's work is new scope for ${client}. Before your next step, write a short title for it (the words the client would see on a quote) and one line on why, then call the mm tool with "propose <title> -- <why>" and do what it returns. The line itself is added only when the client says yes.`
626
627/** (0.7.0, verbatim) The note a press on Hour bank adds for Claude. */
628export const bankNote = (client: string): string =>
629 `[mm-bridge] The person says this thread's work is a quick fix inside ${client}'s hour bank. Before your next step, call the mm tool with "bank" and do what it returns.`
630
631/** `a`, `a or b`, `a, b or c`. */
632const orList = (items: readonly string[]): string => (items.length < 2 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} or ${items[items.length - 1]}`)
633
634/**
635 * (0.7.0, verbatim) The one note a thread gets the first time its work matches no line (per session and task label):
636 * Claude asks the person where it counts, and keeps working. Only the candidates that exist are named; with no hour
637 * bank its clause (and "bank") goes, and with no candidates the "does it count toward" clause (and "line") goes.
638 */
639export function askNote(o: { client: string; task: string; candidates: readonly { line_key: string; title: string }[]; bank: boolean }): string {
640 const cands = o.candidates.slice(0, LINE_CHOICES).map(c => `"${c.title}" (${c.line_key})`)
641 const asks = [
642 ...(cands.length ? [`does it count toward ${orList(cands)}`] : []),
643 'is it new scope (Massmarket proposes a new line and tells the client before billing it)',
644 ...(o.bank ? ['is it a quick fix inside the hour bank'] : []),
645 ]
646 const question = asks.length > 1 ? `${asks.slice(0, -1).join(', ')}, or ${asks[asks.length - 1]}` : asks[0]
647 const acts = orList([...(cands.length ? ['"line <line_key>"'] : []), '"propose <title> -- <why>"', ...(o.bank ? ['"bank"'] : [])])
648 const work = o.task ? `this thread's work ("${o.task}")` : 'this thread\'s work'
649 return `[mm-bridge] Massmarket time tracking: ${work} does not match a line on ${o.client}'s quote yet, so its minutes are not counted to a deliverable. In your next reply, ask the person one short question: ${question}? Then act on the answer with the mm tool: ${acts}. Keep working while you wait for the answer.`
650}
651
652// ---------------------------------------------------------------- (0.7.0) what `mm line`, `propose` and `bank` answer
653
654/** The OW ticket a task label works, by the 8 hex digits it starts with; '' when it starts with none. */
655export function ticketOf(task: string | undefined): string {
656 const m = /^([0-9a-f]{8})(?![0-9a-z])/i.exec((task ?? '').trim())
657 return m ? (m[1] ?? '').toLowerCase() : ''
658}
659
660/** A task label without the line key or ticket id it starts with. */
661export const withoutPrefix = (task: string | undefined): string => (task ?? '').trim().replace(/^(?:L-[0-9A-Za-z]{4,32}|[0-9a-f]{8})(?![0-9A-Za-z])[\s:-]*/i, '').trim()
662
663/** (0.7.0) The time-tracking hook's command that declares a task label, as the person runs it; on Windows, PowerShell's form after it. */
664export function hookCommand(label: string, windows: boolean): string {
665 const unix = `node ~/.claude/mm-hooks/worklog-hook.js --task "${label}"`
666 return windows ? `${unix} (Windows PowerShell: node "$env:USERPROFILE\\.claude\\mm-hooks\\worklog-hook.js" --task "${label}")` : unix
667}
668
669/** (0.7.0, verbatim) `mm line` on a thread that works no ticket: the command that counts its work to the line from now on. */
670export function declareLineText(o: { key: string; title: string; task: string | undefined; windows: boolean }): string {
671 const rest = forClaude(withoutPrefix(o.task), 100) || forClaude(o.title, 100)
672 return `Run this to count this thread's work to ${forClaude(o.title)} from now on: ${hookCommand(`${o.key} ${rest}`.trim(), o.windows)}`
673}
674
675/** (0.7.0, verbatim) `mm line` on a thread working a ticket, after OW linked it. */
676export const linkedText = (id8: string, title: string): string => `Linked ticket ${id8} to ${forClaude(title)}; its time counts there now.`
677
678/** (0.7.0, verbatim) `mm propose`, after OW recorded the proposal. */
679export function proposedText(o: { title: string; client: string; id8: string; existing: boolean; windows: boolean }): string {
680 const title = forClaude(o.title, 100)
681 return `${o.existing ? 'Already proposed' : 'Proposed'} "${title}" for ${o.client} (ticket ${o.id8}). Run this so the work counts to the proposal: ${hookCommand(`${o.id8} ${title}`, o.windows)}`
682}
683
684/** (0.7.0, verbatim) `mm bank` for a client with no hour bank. */
685export const noBankText = (client: string): string => `${client} has no hour bank on record; ask the person which line, or propose new scope.`
686
687/** (0.7.0) `mm propose <title> -- <why>`, split: the title (1 to 120 characters) and why (at most 500); null when there is no title. */
688export function proposalArgs(arg: string): { title: string; why: string } | null {
689 const at = arg.indexOf(' -- ')
690 const head = (at >= 0 ? arg.slice(0, at) : arg.replace(/\s--\s*$/, '')).trim()
691 const why = at >= 0 ? arg.slice(at + 4).trim() : ''
692 const title = shownText(head, 120)
693 return title ? { title, why: shownText(why, 500) } : null
694}
695
696// ---------------------------------------------------------------- the pane opening by itself (§4)
697
698/** What the opening rule reads of the session's own record. */
699export type PaneSession = { single?: boolean; closed?: string; handled?: string }
700
701/**
702 * (0.6.0) Whether the pane may open by itself for `pid`: never in a SINGLE-SESSION run or under MM_UNATTENDED=1, and
703 * not for the project whose pane the person closed in this session (another project opens it again).
704 */
705export const opensBySelf = (s: PaneSession, pid: string, unattended: boolean): boolean => !s.single && !unattended && !(s.closed !== undefined && s.closed === pid)
706
707/** (0.6.0) The person closed the pane: what the session keeps, the project it was drawn for (none yet: ''). */
708export const afterPersonClose = (s: PaneSession): { closed: string } => ({ closed: s.handled ?? '' })
709
710// ---------------------------------------------------------------- the band (§5) and the notes for Claude
711
712export const NUDGE_TEXT = 'This thread is not tracked to a client yet.'
713export const NUDGE_INTERNAL = 'Massmarket internal'
714export const NUDGE_NONE = 'Not client work'
715export const trackLabel = (client: string): string => `Track to ${client}`
716/** The person's prompts after which a thread with no current project says so. */
717export const NUDGE_AFTER = 2
718
719/** (0.6.0, verbatim) The note a Track to <Client> press adds for Claude. */
720export const pressNote = (client: string, skill: string): string =>
721 `[mm-bridge] The person marked this thread as ${client}'s work. Before your next step, load the ${skill} skill with the Skill tool so the time tracker counts this thread's time to ${client}.`
722
723/** (0.6.0, verbatim) The note a Massmarket internal press adds for Claude. */
724export const INTERNAL_NOTE = '[mm-bridge] The person marked this thread as Massmarket internal work. Before your next step, load the massmarket-internal-ops skill with the Skill tool so the time tracker counts it.'
725
726/** (0.6.0, verbatim) The line above the client part in a second thread. */
727export const secondLine = (client: string, title: string): string => `This is a second thread for ${client}. The reply package is picked up in "${title}".`
728
729/** A thread title as it may go into a sentence for Claude. */
730export const titleForClaude = (title: string): string => cleanTitle(title) || 'another thread'
731hooks/business-time.ts 170 lines1// Business time for client clocks (Rob, 2026-10-12: "the weekends don't count as days towards the
2// 24-hour response time... We're only counting business days in our timelines for clients").
3//
4// Saturday and Sunday contribute zero time; nothing else changes. The clock is paused from Saturday 00:00
5// to Monday 00:00 America/New_York. No hours-of-day window and no holidays.
6// Friday 3 PM + 24 h = Monday 3 PM (9 h Friday + 15 h Monday)
7// Saturday 10 AM + 24 h = the clock runs Monday 00:00 to Tuesday 00:00, read as Monday 11:59 PM
8//
9// Pure: Intl.DateTimeFormat and arithmetic only (a hooks module has no Node and no DOM), no imports.
10// A plugin cannot import from another repo, so this is the plugin's own copy of the business-time module
11// the onboarding-wizard server uses (src/lib/business-time.ts there). Keep the logic and the test vectors
12// (business-time.test.ts) the same in both.
13
14export const BUSINESS_TZ = 'America/New_York'
15/** ISO weekdays that never count: 6 = Saturday, 7 = Sunday. */
16export const BUSINESS_REST_DAYS: ReadonlySet<number> = new Set([6, 7])
17
18const HOUR = 3_600_000
19
20type Parts = { y: number; m: number; d: number; h: number; mi: number; s: number }
21type Day = { start: number; end: number; rest: boolean }
22
23const FMT = new Map<string, Intl.DateTimeFormat>()
24function fmt(tz: string): Intl.DateTimeFormat {
25 let f = FMT.get(tz)
26 if (!f) {
27 f = new Intl.DateTimeFormat('en-US', {
28 timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
29 })
30 FMT.set(tz, f)
31 }
32 return f
33}
34
35function localParts(ms: number, tz: string): Parts {
36 const p = fmt(tz).formatToParts(new Date(ms))
37 const g = (t: Intl.DateTimeFormatPartTypes): number => Number(p.find(x => x.type === t)?.value)
38 return { y: g('year'), m: g('month'), d: g('day'), h: g('hour'), mi: g('minute'), s: g('second') }
39}
40
41/** The instant local 00:00 begins on calendar date (y, m, d) in tz. Exact on DST change days. */
42function localMidnight(y: number, m: number, d: number, tz: string): number {
43 const guess = Date.UTC(y, m - 1, d) // 00:00 UTC of that date
44 const want = new Date(guess)
45 // every real UTC offset is inside this range
46 for (let off = -14; off <= 14; off++) {
47 const c = guess + off * HOUR
48 const a = localParts(c, tz)
49 const b = localParts(c - 1, tz)
50 if (a.y === want.getUTCFullYear() && a.m === want.getUTCMonth() + 1 && a.d === want.getUTCDate() && a.h === 0 && a.mi === 0 && a.s === 0 && b.d !== a.d) return c
51 }
52 // half-hour zones: fall back to a minute walk
53 for (let c = guess - 14 * HOUR; c <= guess + 14 * HOUR; c += 60_000) {
54 const a = localParts(c, tz)
55 const b = localParts(c - 1, tz)
56 if (a.d === want.getUTCDate() && a.h === 0 && a.mi === 0 && b.d !== a.d) return c
57 }
58 return guess
59}
60
61function isoDow(y: number, m: number, d: number): number {
62 const js = new Date(Date.UTC(y, m - 1, d, 12)).getUTCDay()
63 return js === 0 ? 7 : js
64}
65
66/** [start, end) of the local calendar day containing ms, plus whether it is a rest day. */
67function dayOf(ms: number, tz: string, rest: ReadonlySet<number>): Day {
68 const p = localParts(ms, tz)
69 const start = localMidnight(p.y, p.m, p.d, tz)
70 const n = new Date(Date.UTC(p.y, p.m - 1, p.d + 1))
71 const end = localMidnight(n.getUTCFullYear(), n.getUTCMonth() + 1, n.getUTCDate(), tz)
72 return { start, end, rest: rest.has(isoDow(p.y, p.m, p.d)) }
73}
74
75/** True when `ms` falls on a business day (Monday to Friday in tz). False when `ms` is not finite. */
76export function isBusinessTime(ms: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): boolean {
77 if (!Number.isFinite(ms)) return false
78 return !dayOf(ms, tz, rest).rest
79}
80
81/** `ms` itself on a business day; otherwise 00:00 local of the next business day. NaN when `ms` is not finite. */
82export function nextBusinessStart(ms: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): number {
83 if (!Number.isFinite(ms)) return NaN
84 let t = ms
85 for (let i = 0; i < 8; i++) {
86 const d = dayOf(t, tz, rest)
87 if (!d.rest) return t
88 t = d.end
89 }
90 return t
91}
92
93/** Elapsed ms from `fromMs` to `toMs` with rest days contributing zero. 0 when toMs <= fromMs or either is not finite. */
94export function businessMsBetween(fromMs: number, toMs: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): number {
95 if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || toMs <= fromMs) return 0
96 let total = 0
97 let t = fromMs
98 while (t < toMs) {
99 const d = dayOf(t, tz, rest)
100 const stop = Math.min(d.end, toMs)
101 if (!d.rest) total += stop - t
102 t = stop
103 }
104 return total
105}
106
107/**
108 * The instant at which `durationMs` of business time has elapsed since `startMs`. A start on a rest day
109 * begins at 00:00 local of the next business day. Exact inverse of businessMsBetween from
110 * nextBusinessStart(startMs). NaN when either argument is not finite.
111 */
112export function addBusinessMs(startMs: number, durationMs: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): number {
113 if (!Number.isFinite(startMs) || !Number.isFinite(durationMs)) return NaN
114 let t = nextBusinessStart(startMs, tz, rest)
115 let left = Math.max(0, durationMs)
116 for (let i = 0; i < 4000; i++) {
117 const d = dayOf(t, tz, rest)
118 if (d.rest) {
119 t = d.end
120 continue
121 }
122 const room = d.end - t
123 if (left < room) return t + left // strictly inside this business day
124 if (left === room) return d.end // lands exactly on the day's end (Monday 24:00 = Tuesday 00:00)
125 left -= room
126 t = d.end
127 }
128 return t
129}
130
131/** Whole business days elapsed: floor(businessMsBetween / 24 h). For "Nd overdue", "Nd past", "waiting Nd". */
132export function businessDaysBetween(fromMs: number, toMs: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): number {
133 return Math.floor(businessMsBetween(fromMs, toMs, tz, rest) / (24 * HOUR))
134}
135
136/**
137 * The latest instant t with businessMsBetween(t, endMs) === durationMs. For look-back windows
138 * ("the last 48 business hours"). NaN when either argument is not finite.
139 */
140export function subtractBusinessMs(endMs: number, durationMs: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): number {
141 if (!Number.isFinite(endMs) || !Number.isFinite(durationMs)) return NaN
142 let t = endMs
143 let left = Math.max(0, durationMs)
144 for (let i = 0; i < 4000; i++) {
145 const d = dayOf(t - 1, tz, rest) // the day that contains the instant just before t
146 if (d.rest) {
147 t = d.start
148 continue
149 }
150 const room = t - d.start
151 if (left <= room) return t - left
152 left -= room
153 t = d.start
154 }
155 return t
156}
157
158/**
159 * A deadline a person reads: addBusinessMs, except that a result landing exactly on local midnight
160 * (a weekend arrival, or a duration that ends with the business day) is given as 23:59 of the business
161 * day that just ended, so no surface prints "Tue 12:00 AM" or "Sat 12:00 AM". NaN when either argument
162 * is not finite.
163 */
164export function businessDeadline(startMs: number, durationMs: number, tz: string = BUSINESS_TZ, rest: ReadonlySet<number> = BUSINESS_REST_DAYS): number {
165 const due = addBusinessMs(startMs, durationMs, tz, rest)
166 if (!Number.isFinite(due)) return NaN
167 const p = localParts(due, tz)
168 return p.h === 0 && p.mi === 0 && p.s === 0 && due > startMs ? due - 60_000 : due
169}
170types/index.d.ts 219 lines1export type MmMarkdown = string
2
3/**
4 * The client part of the pane, drawn above the list: a client's prepared drafts when there is a package,
5 * else the messages waiting on our reply and the tasks due; under either, (0.5.28) the viewer's open internal asks
6 * about the client, each with its page once read. `heading` is `This thread: <client>` when it
7 * is the client of the thread the pane is in, and empty for another client's (shown from its row's Drafts
8 * button). An empty `text` draws no client part.
9 */
10export type MmView = { text: MmMarkdown; heading: string }
11
12/** One client on the Needs-you pane: what is due, what is waiting, and the one thing to do about its thread. */
13export type MmRow = {
14 projectId: string
15 client: string
16 /** The thread name the bridge would give it: what is due and when. */
17 title: string
18 waiting: string
19 /**
20 * `start`: a new thread (none yet, or the existing one is old or long). `update`: the thread exists and
21 * has not been given what is waiting now. `current`: it already has it.
22 */
23 state: 'start' | 'update' | 'current'
24 /** Why, in a few words. For `current`, the whole phrase: when the thread was updated. */
25 reason: string
26 /** True when the client has no thread of any kind: the row is drawn in the first group, marked. Absent on a row an older version drew. */
27 fresh?: boolean
28 /** The app thread the row's button acts on, as this row was drawn. A press acts on this thread or on none. */
29 target?: string
30 /**
31 * Set on a row under `With a teammate`: who holds the client's reply drafts, and to ask them before
32 * writing a second reply. Such a row is not the viewer's to act on: it carries this sentence and the
33 * Drafts button, and no action. For the founder, on a package flagged for his OK that a teammate holds,
34 * the sentence is followed by ` · may need your OK`.
35 */
36 note?: string
37 /**
38 * For the founder alone: true on a row under `With a teammate` whose client's package a teammate sends
39 * and sees through (0.5.1). Like a row with a `note`, it has the Drafts button and no action, sentence or not.
40 */
41 theirs?: boolean
42 /**
43 * (0.5.2, R8) What the server's check of our reply to the client found still open: drawn under the row. A
44 * row with these is named `🟡 <client> · still open after your reply`.
45 */
46 stillOpen?: string[]
47 /** (0.5.2, R8) With `stillOpen`: true when the row's one action is Claim in this thread (its thread is under 60% of its context). */
48 claim?: boolean
49 /** (0.5.2, R8) The server is checking our reply to this client: the row is under `Checking your reply`, named as its thread is, with Drafts alone. */
50 checking?: true
51}
52
53/**
54 * `rows` are the clients that need the viewer now. `teammate` and `older` are the two groups under them,
55 * closed until the person opens one: clients whose drafts a teammate holds, and clients whose only items
56 * were due before the list's floor, Wed 2026-10-14 (until 2026-10-20 the cut was 3 business days back; Rob
57 * replaced it with LIST_FLOOR_MS). Neither is pinned or counted in the header.
58 */
59export type MmQueue = {
60 header: string
61 rows: MmRow[]
62 note: string
63 teammate?: MmRow[]
64 older?: MmRow[]
65 /** (0.5.2, R8) Clients whose reply the server is checking: a closed group `Checking your reply (n)`, never pinned or counted. */
66 checking?: MmRow[]
67 /**
68 * One line under the header when the refresh after a press failed: the list shown is the one last loaded.
69 * Gone with the next list drawn from a sync that worked. `warnedAt` is when it failed.
70 */
71 warning?: string
72 warnedAt?: number
73 /** (0.5.4) The sync the list was drawn from: a thread drawn from an older one than the store holds draws it again. */
74 syncedAt?: number
75 /**
76 * (New people, OW ticket 549944b0) For the founder and a PM: people who wrote to us and whom no project matched,
77 * newest first, drawn above the list under `New people (n)`. Absent when there are none (or the feed has none).
78 */
79 people?: MmPerson[]
80 /** (New people) The projects Route to project offers, by name. */
81 routeTo?: MmProject[]
82}
83
84/**
85 * (New people) One person under `New people`: who, what they wrote about, when, what to check first, what we
86 * already know of them, and the link to where they wrote. Every text is drawn as given; none goes to Claude.
87 */
88export type MmPerson = {
89 /** OW's alert id (a uuid): what a press sends back. */
90 id: string
91 /** Who it is, as the notice after a press names them. */
92 name: string
93 /** `Isaac Gonzalez · True North Interiors`, and ` · via HighLevel Directory` for a Directory lead. */
94 title: string
95 /** `Subject: RFP for the Plano office`, or `(no subject)`. */
96 subject: string
97 /** `Received Fri Oct 16, 9:12 AM ET · 4 business days waiting`. */
98 when: string
99 /** The warnings, in words (`blank body`, `Bcc'd`, ...): drawn as small labels. */
100 warnings: string[]
101 /** `We know them: 1 recorded call (Feb 2026) · HighLevel contact`, or '' when the feed gives no summary. */
102 known: string
103 /** The Gmail or Directory link (https only), or ''. */
104 link: string
105 /**
106 * A HighLevel Directory lead (`source` `hl_directory`): it has no email to route or start a project from, so OW
107 * refuses `route` and `bootstrap` for it. Its row offers Mark handled (`handled`) and Not client mail only. Absent on
108 * any other row.
109 */
110 directory?: true
111}
112
113/** (New people) A project Route to project can send someone to. */
114export type MmProject = { projectId: string; name: string }
115
116/**
117 * (New people) What this thread's pane shows of the person's own presses on `New people`: whose project picker is
118 * open, which of its pages it shows and what is picked in it, which rows have a press in flight (since when), and what OW answered a press that
119 * did not go through, by alert id.
120 */
121export type MmPeople = { open?: string; pick?: string; page?: number; busy?: Record<string, number>; errors?: Record<string, string> }
122
123/** Which of the two groups under the list the person has opened. */
124export type MmFolds = { teammate?: boolean; older?: boolean; checking?: boolean }
125
126/** What the last button press did, shown above the list. */
127export type MmNotice = { text: string; at: number }
128
129/**
130 * The one line above the prompt: how many clients need the person, and this thread's client. An empty
131 * `text` draws nothing. `drafts` is true in a thread that is a waiting client's: the line then carries a
132 * second button that opens that client's pane.
133 */
134/**
135 * `at` (0.5.4): the sync the line was worked out from. `missing` (0.5.14): how many clients need a new thread now, for
136 * the band's Start missing threads button, which is always drawn (0 or absent: All threads started). (0.5.12's
137 * `startAll` is no longer written or read.)
138 */
139export type MmBand = { text: string; drafts?: boolean; at?: number; missing?: number }
140
141/**
142 * (0.6.0) One line of the pane's Tracking part. `open`: the app thread (`local_…`) a press on the line opens, on a
143 * row of `Threads today` that is another thread on this computer; such a line is drawn as a button.
144 */
145export type MmTrackLine = { text: string; dim?: boolean; bold?: boolean; open?: string }
146
147/**
148 * (0.6.0) What this thread's pane shows of its current project: which project (`pid`, '' when none), the pane's
149 * title, the Tracking part line by line, and in a second thread of a client the dim line above the client part
150 * (`second`). `client`: the project's name as shown.
151 */
152export type MmTrack = { pid: string; client: string; title: string; lines: MmTrackLine[]; second?: string }
153
154/**
155 * (0.6.0) This session's own record, for the pane and the band: the person's prompts so far, whether its first
156 * prompt began `SINGLE-SESSION`, whether the person pressed Not client work, whether it runs for a person
157 * (`interactive`) or unattended (`MM_UNATTENDED=1`), the project whose pane the person closed (`closed`) and the one
158 * the pane was last opened for by itself (`opened`), the project the pane last drew (`handled`), and when this
159 * session last asked OW for its project's time (`asked`).
160 */
161export type MmSession = {
162 prompts: number
163 /** Its first prompt has been seen. */
164 first?: boolean
165 single?: boolean
166 notClient?: boolean
167 interactive?: boolean
168 unattended?: boolean
169 closed?: string
170 opened?: string
171 handled?: string
172 asked?: number
173 /** (0.7.0) The project and task labels (`lineAskKey`) whose line band the person answered or put off (Not now). */
174 lineDone?: string[]
175 /** (0.7.0) The project and task labels whose one note to Claude (no line matched) was added. */
176 lineNoted?: string[]
177}
178
179/** (0.6.0) A client the band offers to track this thread to: its project, its name, and the skill that counts it. */
180export type MmSuggestion = { pid: string; client: string; skill: string }
181
182/** (0.6.0) The band's line for a thread with no current project after the person's second prompt, and what it offers. */
183export type MmNudge = { show: boolean; suggest: MmSuggestion[] }
184
185/** (0.7.0) A line of a client's quote the band offers: its key and its title. */
186export type MmLineChoice = { line_key: string; title: string }
187
188/**
189 * (0.7.0) The band's line for a client's thread whose work matches no line on the quote: the project, its name as
190 * shown, the project and task label it was worked out for (`key`), whether nothing matched (`unmatched`) or the work
191 * looks like new scope (`maybe_new_scope`), the candidate lines (at most 3) and the hour bank, when the client has one.
192 */
193export type MmLineAsk = {
194 show: boolean
195 pid?: string
196 client?: string
197 key?: string
198 signal?: 'unmatched' | 'maybe_new_scope'
199 candidates?: MmLineChoice[]
200 bank?: MmLineChoice | null
201}
202
203declare module 'claude-code' {
204 interface PluginState {
205 'mm-bridge': {
206 view: MmView
207 queue: MmQueue
208 notice: MmNotice
209 band: MmBand
210 folds: MmFolds
211 people: MmPeople
212 track: MmTrack
213 sess: MmSession
214 nudge: MmNudge
215 lineAsk: MmLineAsk
216 }
217 }
218}
219