SLOPSHOPPER

session-nametag

Names and colors each Claude Code session when it starts (folder, branch, instance number, machine, model, start time), so many sessions are easy to tell…

commandtimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-nametag
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /nametag ⎿ session-nametag: This session is not tagged. /nametag force tags it. ⎿ session-nametag: Naming: preset "full". Color: auto. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

session-nametag

A Claude Code mod that names and colors every session when it starts, so a desktop full of sessions (and the Remote Control list on your phone) is easy to tell apart.

/rename [Opus 5.5] hess-laundry/fix/backfill #2 · fix the backfill script @ LUIS-DESKTOP Wed Oct 7th, 2026 9:05 am
/color pink
  • Name from a template: model, folder, git branch, instance number, machine, start time. Change the style with /nametag <preset>.
  • Topic you set: /nametag topic fix the backfill script puts what you are working on in the name.
  • Color per folder: each folder hashes to one of the eight /color colors, and moves to the next free one if another live session has it.
  • Stays current: after a turn that switched branches, a /model, or a ! cd you type into another folder, the name is updated. A /rename you type yourself stops that for the session.
  • Resume aware: a session reopened with --resume or /relaunch gets its number and color back. A session it never tagged (an older resume, or one already running when you install the mod) keeps its name and color until you run /nametag force.

Install

/plugin install session-nametag --marketplace lperezmo/session-nametag

Mods need CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1.

Presets

#2 only shows when a second session is open in the same folder, and the branch only shows inside git.

PresetExample
compacthess-laundry #2
branchhess-laundry/fix/backfill #2
status🧺 hess-laundry/fix/backfill #2 · fix the backfill script
hosthess-laundry/fix/backfill #2 @ LUIS-DESKTOP
model[Opus 5.5] hess-laundry/fix/backfill #2 @ LUIS-DESKTOP
timed[Opus 5.5] hess-laundry/fix/backfill #2 @ LUIS-DESKTOP Wed 9:05 am
full (default)[Opus 5.5] hess-laundry/fix/backfill #2 · fix the backfill script @ LUIS-DESKTOP Wed Oct 7th, 2026 9:05 am

Your own template

/nametag template {folder}{/branch}{ #nth}{ · topic}

/nametag help lists every token.

TokenExample
modelOpus 5.5
familyOpus
folderhess-laundry (the repository, so worktrees and subfolders share it)
dirthe folder the session started in
remotelperezmo/hess-laundry
branchfix/backfill
nth2 (hidden for the first session in a folder)
num1 (always shown)
hostLUIS-DESKTOP
topicfix the backfill script (set with /nametag topic)
codenamebrisk-otter (fixed for the session)
sigil🧺 (an emoji per folder)
todaycount7 (the 7th session started today on this machine)
datetimeWed Oct 7th, 2026 9:05 am
dateOct 7th, 2026
dayWed
time9:05 am
updated2:14 pm, or Thu 2:14 pm on a later day
updateddatetimeThu Oct 8th, 2026 11:00 am
updateddateOct 8th, 2026

The date tokens are when the session started and never move, even when a branch switch renames it. The updated tokens are when the name last changed. Each {...} group is dropped when one of its tokens is empty, so {/branch} disappears outside git.

Commands

CommandWhat it does
/nametagThis session's tag and the other live sessions
/nametag presetsPreview every preset for this session
/nametag <preset>Use a preset from now on and rename this session
/nametag defaultBack to the default preset (full); reset works too
/nametag template <text>Use your own template
/nametag save <name> [text]Keep the template in use (or the one given) under a name
/nametag <name>Switch to a saved template
/nametag delete <name>Forget a saved template
/nametag topic <text>Set what this session is about; off clears it
/nametag sigil <emoji>Pick this folder's emoji; auto goes back to the one it was given
/nametag forceTag this session for the folder you are in now (after a cd), even a resumed or renamed one
/nametag color <c>auto (per folder), off, or a fixed color
/nametag off [here]Stop tagging new sessions, everywhere or in this folder
/nametag on [here]Start again

To switch it off for a whole project, team included, set NAMETAG_OFF=1 in the project's .claude/settings.json env.

What it does on your machine

Nothing leaves your machine. The mod makes no network calls and sends no data anywhere; everything below stays local.

  • Slash commands it runs: /rename and /color, in this session only, when the session starts, when the name changes (branch switch, /model, topic, a /nametag command) and never otherwise. Each leaves one short line in the transcript. A mod cannot set the name silently: the built-in security mod keeps classic hook events such as SessionStart away from installed mods.
  • Programs it starts: none. Git is read from its files, not by running git.
  • What it reads: the repository's .git/HEAD (the branch) and, only when your template uses remote, .git/config (the origin URL); the host name (COMPUTERNAME, HOSTNAME, /etc/hostname, or on macOS /Library/Preferences/SystemConfiguration/preferences.plist); the NAMETAG_OFF variable; the session's folder, model and start time. It never reads your prompts or the conversation: topic is only what you type after /nametag topic. No tokens, keys or credentials.
  • Hooks: session.start registers /nametag and tags the session; turn.start only marks that a turn is running (the prompt is not read), so a cd Claude makes is not followed; turn.complete re-checks git after each turn; every 2 seconds it looks at the shell's folder to follow a ! cd you type; command.run handles /nametag, notices a manual /rename or /color and refreshes after /model; session.end keeps the name across /clear and /relaunch.
  • What it stores: a small record per session in the mod's own store on this machine: session id, folder path, number, color, name, topic, last heartbeat; plus your settings and saved templates. Ended sessions are forgotten after 30 days.

License

MIT

Source 3 files
hooks/register.ts 1007 lines
1/**
2 * session-nametag: names and colors each Claude Code session when it starts,
3 * so a desktop full of sessions (and the Remote Control list on a phone) can
4 * be told apart at a glance.
5 *
6 * - The name comes from a template (`/nametag <preset>` or `/nametag
7 *   template ...`) and is set by running /rename. After each turn and each
8 *   /model it is worked out again, and renamed only when it changed (a branch
9 *   switch, a new model). A /rename typed by the person stops that.
10 * - The color is set by running /color. A folder hashes to one of the eight
11 *   colors, moving to the next free one when another live session holds it.
12 * - Live sessions keep an entry in the shared store with a heartbeat; that is
13 *   where the per-folder instance number and the taken colors come from.
14 * - A resumed session the mod tagged before (a /relaunch, a plain --resume)
15 *   gets its number and color back and keeps updating. A resumed session it
16 *   never tagged keeps its name. /nametag force renames either.
17 *
18 * Why /rename and not the SessionStart hook's `sessionTitle`: the built-in
19 * security mod passes every classic hook event past user-installed mods, so
20 * a mod cannot answer it. /rename and /color each leave one short line.
21 *
22 * Every `$.noun.verb(...)` is written literally; the loader inventories them.
23 */
24
25import type { EngineInterface, On } from 'claude-code'
26
27import {
28  asConfig,
29  asLive,
30  asSeen,
31  assign,
32  baseName,
33  CONFIG_KEY,
34  folderKey,
35  HEARTBEAT_MS,
36  isAlive,
37  isPreset,
38  isWithin,
39  LIVE_PREFIX,
40  MAX_SAVED,
41  modelLabel,
42  mustYield,
43  parseArgs,
44  PRESET_ORDER,
45  render,
46  resolveTemplate,
47  SEEN_PREFIX,
48  SEEN_TTL_MS,
49  USAGE,
50  type Config,
51  type LiveEntry,
52  type TagValues,
53  type Token,
54  usedTokens,
55} from './tag'
56import {
57  branchFromHead,
58  codenameFor,
59  dayKey,
60  gitDirFromFile,
61  macHostName,
62  originFromConfig,
63  remoteSlug,
64  shorten,
65  sigilFor,
66} from './extras'
67
68const COMMAND_NAME = 'nametag'
69
70/** The first tag waits for the prompt to mount, then retries while it is busy. */
71const START_DELAY_MS = 800
72const RUN_RETRIES = 20
73const RUN_RETRY_MS = 500
74
75/** `$.command.run` inside a hook that holds a turn or command is refused, so it waits a beat. */
76const DEFER_MS = 300
77
78/** This session's live entry; null when the mod is not tagging it. */
79let me: LiveEntry | null = null
80
81let isHeartbeat = false
82
83/** How often the shell's folder is looked at, to follow a `!cd` you type. */
84const FOLLOW_MS = 2000
85
86/** The shell's folder when last looked at; null until the first look. */
87let shellAt: string | null = null
88
89/** True while a main-loop turn runs: a cd then is Claude's, not yours. */
90let isTurn = false
91
92/** The host and the start time never change mid-session, so they are read once. */
93let fixed: { host: string; startedAt: number } | null = null
94
95async function readConfig($: EngineInterface): Promise<Config> {
96  return asConfig(await $.store.get(CONFIG_KEY))
97}
98
99async function save($: EngineInterface, entry: LiveEntry) {
100  await $.store.set(`${LIVE_PREFIX}${entry.id}`, entry)
101}
102
103/**
104 * Every other live session's entry. Stale ones (a crash, a killed terminal)
105 * are deleted on the way, and so are remembered sessions past their time.
106 *
107 * @param $ the engine interface
108 * @param selfId this session's id, left out of the answer
109 */
110async function others($: EngineInterface, selfId: string): Promise<LiveEntry[]> {
111  const now = await $.clock.now()
112  const keys = await $.store.keys()
113  const live: LiveEntry[] = []
114
115  for (const key of keys) {
116    if (key.startsWith(LIVE_PREFIX)) {
117      const entry = asLive(await $.store.get(key))
118
119      if (!entry || !isAlive(entry, now)) {
120        await $.store.delete(key)
121      } else if (entry.id !== selfId) {
122        live.push(entry)
123      }
124    } else if (key.startsWith(SEEN_PREFIX)) {
125      const seen = asSeen(await $.store.get(key))
126
127      if (!seen || now - seen.at > SEEN_TTL_MS) {
128        await $.store.delete(key)
129      }
130    } else if (key.startsWith('day.') && key !== dayKey(now)) {
131      await $.store.delete(key)
132    }
133  }
134
135  return live
136}
137
138/**
139 * The machine's name: the environment first, then /etc/hostname, then the
140 * macOS system configuration; empty when none has it, and the host group hides.
141 *
142 * @param $ the engine interface
143 */
144async function hostName($: EngineInterface): Promise<string> {
145  const fromEnv = (await $.env.get('COMPUTERNAME')) ?? (await $.env.get('HOSTNAME'))
146
147  if (fromEnv) {
148    return fromEnv.trim()
149  }
150
151  try {
152    const text = await $.fs.read('/etc/hostname', { as: 'text' })
153
154    if (typeof text === 'string' && text.trim()) {
155      return text.trim()
156    }
157  } catch {
158    // Not Linux, or not readable.
159  }
160
161  // macOS keeps the name in the system configuration file.
162  const plist = await readText($, '/Library/Preferences/SystemConfiguration/preferences.plist')
163
164  return macHostName(plist)
165}
166
167/** A git repository as its files show it: its top folder and its git folder. */
168type Repo = { top: string; gitDir: string }
169
170/**
171 * A file's text, or empty when it is missing or not a file.
172 *
173 * @param $ the engine interface
174 * @param path the file
175 */
176async function readText($: EngineInterface, path: string): Promise<string> {
177  try {
178    const text = await $.fs.read(path, { as: 'text' })
179
180    return typeof text === 'string' ? text : ''
181  } catch {
182    return ''
183  }
184}
185
186/**
187 * The git repository holding a folder, found by walking up to the nearest
188 * `.git`; null outside git. Reads files only: no git program runs.
189 *
190 * @param $ the engine interface
191 * @param folder the folder
192 */
193async function findRepo($: EngineInterface, folder: string): Promise<Repo | null> {
194  let dir = folder.replace(/[\\/]+$/, '')
195
196  while (dir) {
197    const dotGit = dir + '/.git'
198
199    if (await $.fs.exists(dotGit)) {
200      // A folder in a plain clone; a file pointing elsewhere in a worktree.
201      const text = await readText($, dotGit)
202      const gitDir = text ? gitDirFromFile(text, dir) : dotGit
203
204      return gitDir ? { top: dir, gitDir } : null
205    }
206
207    const up = dir.replace(/[\\/][^\\/]*$/, '')
208
209    if (up === dir) {
210      break
211    }
212
213    dir = up
214  }
215
216  return null
217}
218
219/**
220 * The branch checked out, from the repository's HEAD file.
221 *
222 * @param $ the engine interface
223 * @param repo the repository
224 */
225async function readBranch($: EngineInterface, repo: Repo): Promise<string> {
226  return branchFromHead(await readText($, repo.gitDir + '/HEAD'))
227}
228
229/**
230 * The origin remote's URL, from the repository's config file (a worktree's
231 * config lives in the main repository, named by its commondir file).
232 *
233 * @param $ the engine interface
234 * @param repo the repository
235 */
236async function readOrigin($: EngineInterface, repo: Repo): Promise<string> {
237  const common = (await readText($, repo.gitDir + '/commondir')).trim()
238  const shared = !common ? repo.gitDir : /^([a-z]:)?[\\/]/i.test(common) ? common : repo.gitDir + '/' + common
239
240  return originFromConfig(await readText($, shared + '/config'))
241}
242
243/**
244 * What the template is filled from, for this session right now, and the key
245 * of its folder (the repository's main folder, so worktrees and subfolders
246 * count as the project they belong to).
247 *
248 * @param $ the engine interface
249 * @param n the instance number
250 * @param at the folder to name it after; absent, the folder /nametag force
251 *   pinned, else the folder the session started in
252 * @param isAll work out every token, not only the ones the template uses
253 *   (the presets preview)
254 */
255async function values(
256  $: EngineInterface,
257  n: number,
258  at?: string,
259  isAll = false,
260): Promise<{ v: TagValues; key: string }> {
261  const config = await readConfig($)
262  const used = usedTokens(resolveTemplate(config.template, config.saved))
263  const wants = (...tokens: Token[]) => isAll || tokens.some((t) => used.has(t))
264  const root = at ?? me?.root ?? (await $.session.root())
265  const repo = await $.session.repo()
266  // The repository follows the shell's current folder, which moves when a
267  // tool cds somewhere; only one that holds the session's own folder counts.
268  const isShellRepo = repo !== null && isWithin(root, repo.root)
269  // The session's own repository, from its files.
270  const found = await findRepo($, root)
271  const project = isShellRepo && repo ? repo.root : (found?.top ?? root)
272
273  if (!fixed) {
274    fixed = { host: await hostName($), startedAt: (await $.session.usage()).startedAt }
275  }
276
277  const key = folderKey(project)
278  const branch = found && wants('branch') ? await readBranch($, found) : ''
279  let remote = ''
280
281  if (found && wants('remote')) {
282    // The engine's remote is for the shell's repository; trust it only when that is this one.
283    const url = repo && folderKey(repo.root) === key && repo.remote ? repo.remote : await readOrigin($, found)
284
285    remote = url ? remoteSlug(url) : ''
286  }
287
288  const v: TagValues = {
289    model: modelLabel(await $.session.model()),
290    folder: baseName(project),
291    dir: baseName(root),
292    branch,
293    remote,
294    n,
295    host: fixed.host,
296    startedAt: fixed.startedAt,
297    updatedAt: me?.updatedAt ?? fixed.startedAt,
298    topic: me?.topic ?? '',
299    codename: me?.codename ?? codenameFor(await $.session.id()),
300    sigil: sigilFor(key, config.sigils),
301    today: me?.today ?? 0,
302  }
303
304  return { v, key }
305}
306
307/**
308 * Whether the mod should leave this session alone: switched off, off for the
309 * folder, or off through NAMETAG_OFF (a project's settings `env` or the shell).
310 *
311 * @param $ the engine interface
312 * @param config the person's choices
313 * @param key the folder key
314 */
315async function isOff($: EngineInterface, config: Config, key: string): Promise<boolean> {
316  const env = (await $.env.get('NAMETAG_OFF')) ?? ''
317
318  return !config.isOn || config.offFolders.includes(key) || (env !== '' && env !== '0' && env.toLowerCase() !== 'false')
319}
320
321/**
322 * Runs /rename and then /color (either may be left out) once nothing holds
323 * the prompt, retrying while the session is still mounting or busy.
324 *
325 * @param $ the engine interface
326 * @param title the new name, or null to leave it
327 * @param color the new color, or null to leave it
328 * @param delayMs the wait before the first try
329 * @param tries attempts left
330 */
331function runSoon(
332  $: EngineInterface,
333  title: string | null,
334  color: string | null,
335  delayMs = DEFER_MS,
336  tries = RUN_RETRIES,
337) {
338  if (!title && !color) {
339    return
340  }
341
342  $.clock.after(delayMs, async () => {
343    try {
344      if (title) {
345        await $.command.run({ command: 'rename', args: title })
346      }
347
348      if (color) {
349        await $.command.run({ command: 'color', args: color })
350      }
351    } catch (error) {
352      if (tries > 1) {
353        runSoon($, title, color, RUN_RETRY_MS, tries - 1)
354      } else {
355        $.ui.log(
356          `session-nametag could not tag this session: ${error instanceof Error ? error.message : String(error)}`,
357        )
358      }
359    }
360  })
361}
362
363/**
364 * Takes a number and a color for this session, writes its live entry, and
365 * moves to the next number if another session starting at the same moment
366 * took the same one and wins the tie.
367 *
368 * @param $ the engine interface
369 * @param id this session's id
370 * @param key the folder key
371 * @param config the person's choices
372 * @param keep a color to keep instead of picking one (a resume), or undefined
373 * @param preferN the number to keep when it is still free (a resume)
374 */
375async function claim(
376  $: EngineInterface,
377  id: string,
378  key: string,
379  config: Config,
380  keep?: string | null,
381  preferN?: number,
382): Promise<LiveEntry> {
383  const now = await $.clock.now()
384  let live = await others($, id)
385  const picked = assign(key, live, config.color)
386  const isFree = preferN !== undefined && !live.some((o) => o.key === key && o.n === preferN)
387  const entry: LiveEntry = {
388    id,
389    key,
390    n: isFree ? preferN : picked.n,
391    color: keep === undefined ? picked.color : keep,
392    at: now,
393    title: null,
394    isManual: false,
395    codename: codenameFor(id),
396  }
397
398  await save($, entry)
399
400  for (let i = 0; i < 5; i++) {
401    live = await others($, id)
402
403    if (!mustYield(entry, live)) {
404      break
405    }
406
407    entry.n = assign(key, live, 'off').n
408    await save($, entry)
409  }
410
411  return entry
412}
413
414/**
415 * Counts this session among the ones started today on this machine.
416 *
417 * @param $ the engine interface
418 */
419async function countToday($: EngineInterface): Promise<number> {
420  const key = dayKey(await $.clock.now())
421  const before = await $.store.get(key)
422  const count = (typeof before === 'number' ? before : 0) + 1
423
424  await $.store.set(key, count)
425
426  return count
427}
428
429/**
430 * Tags the session once it has started. A session with turns already in it
431 * was resumed or forked: one this mod tagged before gets its number and color
432 * back; any other keeps its name and only gets a color.
433 *
434 * @param $ the engine interface
435 */
436async function tagAtStart($: EngineInterface) {
437  const config = await readConfig($)
438  const id = await $.session.id()
439  const { key } = await values($, 1)
440
441  if (await isOff($, config, key)) {
442    return
443  }
444
445  const seen = asSeen(await $.store.get(`${SEEN_PREFIX}${id}`))
446  // A resume (a /relaunch) keeps its place in today's count; anything else takes the next one.
447  const today = seen?.today ?? (await countToday($))
448
449  if (seen) {
450    me = await claim($, id, key, config, seen.color, seen.n)
451    me = {
452      ...me,
453      today,
454      ...(seen.codename ? { codename: seen.codename } : {}),
455      ...(seen.topic ? { topic: seen.topic } : {}),
456      ...(seen.isTopicSet ? { isTopicSet: true } : {}),
457      title: seen.title,
458      isManual: seen.isManual,
459      ...(seen.updatedAt ? { updatedAt: seen.updatedAt } : {}),
460      ...(seen.root ? { root: seen.root } : {}),
461    }
462
463    const { v } = await values($, me.n)
464    let title = me.isManual ? null : render(resolveTemplate(config.template, config.saved), v)
465    const isRename = title !== null && title !== seen.title
466
467    if (title && isRename) {
468      const now = await $.clock.now()
469
470      title = render(resolveTemplate(config.template, config.saved), { ...v, updatedAt: now })
471      me = { ...me, title, updatedAt: now }
472    }
473
474    await save($, me)
475    runSoon($, isRename ? title : null, me.color, START_DELAY_MS)
476
477    return
478  }
479
480  if ((await $.session.turns()) > 0) {
481    // Resumed, forked, or the mod was just installed into a running session:
482    // its name and color may be the person's own, and neither can be read, so
483    // leave both. It still holds a number; /nametag force tags it.
484    me = await claim($, id, key, config, null)
485    me = { ...me, isManual: true, today }
486    await save($, me)
487
488    return
489  }
490
491  me = { ...(await claim($, id, key, config)), today }
492
493  const { v } = await values($, me.n)
494  const title = render(resolveTemplate(config.template, config.saved), v)
495
496  me = { ...me, title }
497  await save($, me)
498  runSoon($, title, me.color, START_DELAY_MS)
499}
500
501/**
502 * Works the name out again and renames when it changed: a branch switch, a
503 * /model, a new template.
504 *
505 * @param $ the engine interface
506 */
507async function refresh($: EngineInterface) {
508  if (!me || me.isManual || !me.title) {
509    return
510  }
511
512  const config = await readConfig($)
513  const { v } = await values($, me.n)
514  const title = render(resolveTemplate(config.template, config.saved), v)
515
516  if (title === me.title) {
517    return
518  }
519
520  // Something real changed: that is the moment the `updated` token shows.
521  const now = await $.clock.now()
522  const updated = render(resolveTemplate(config.template, config.saved), { ...v, updatedAt: now })
523
524  me = { ...me, title: updated, updatedAt: now }
525  await save($, me)
526  runSoon($, updated, null)
527}
528
529/**
530 * Follows a `!cd` you typed: when the shell's folder moved while no turn ran,
531 * the session is named for the new folder, as /nametag force would. A cd
532 * Claude runs during a turn is taken in when the turn ends and never renames.
533 *
534 * @param $ the engine interface
535 */
536async function followShell($: EngineInterface) {
537  if (isTurn) {
538    return
539  }
540
541  const cwd = await $.session.cwd()
542
543  if (shellAt === null || cwd === shellAt) {
544    shellAt = cwd
545
546    return
547  }
548
549  shellAt = cwd
550
551  if (!me || me.isManual || !me.title) {
552    return
553  }
554
555  const config = await readConfig($)
556  const { key } = await values($, me.n, cwd)
557
558  if (await isOff($, config, key)) {
559    return
560  }
561
562  const colorBefore = me.color
563
564  if (me.key !== key) {
565    const picked = assign(key, await others($, await $.session.id()), config.color)
566
567    me = { ...me, key, n: picked.n, color: me.color && config.color !== 'auto' ? me.color : picked.color }
568  }
569
570  me = { ...me, root: cwd }
571  await save($, me)
572  await refresh($)
573
574  if (me.color && me.color !== colorBefore) {
575    runSoon($, null, me.color)
576  }
577}
578
579/**
580 * Names and colors this session now, whatever its state: /nametag force and
581 * a preset change use it.
582 *
583 * @param $ the engine interface
584 */
585async function applyNow($: EngineInterface, isPin = false): Promise<string> {
586  const id = await $.session.id()
587  const config = await readConfig($)
588  const colorBefore = me?.color ?? null
589
590  if (isPin) {
591    // /nametag force: follow the shell to wherever it is now, and keep the
592    // session there; later re-checks use this folder, not the starting one.
593    const here = await $.session.cwd()
594    const { key } = await values($, 1, here)
595
596    if (!me || me.key !== key) {
597      const live = await others($, id)
598      const picked = assign(key, live, config.color)
599      const color = me?.color && config.color !== 'auto' ? me.color : picked.color
600
601      me = me ? { ...me, key, n: picked.n, color } : await claim($, id, key, config)
602    }
603
604    me = { ...me, root: here }
605  }
606
607  if (!me) {
608    const { key } = await values($, 1)
609
610    me = await claim($, id, key, config)
611  }
612
613  if (!me.color && config.color !== 'off') {
614    me = { ...me, color: assign(me.key, await others($, id), config.color).color }
615  }
616
617  const now = await $.clock.now()
618  const { v } = await values($, me.n)
619  const title = render(resolveTemplate(config.template, config.saved), { ...v, updatedAt: now })
620
621  me = { ...me, title, isManual: false, at: now, updatedAt: now }
622  await save($, me)
623  // A preset or template change keeps the color; only force, or a color that
624  // actually changed, runs /color again.
625  runSoon($, title, isPin || me.color !== colorBefore ? me.color : null)
626
627  return title
628}
629
630/**
631 * Forgets this session's live entry and remembers its number, name and color
632 * for a later resume.
633 *
634 * @param $ the engine interface
635 * @param entry the session's entry
636 */
637async function retire($: EngineInterface, entry: LiveEntry) {
638  await $.store.delete(`${LIVE_PREFIX}${entry.id}`)
639  await $.store.set(`${SEEN_PREFIX}${entry.id}`, {
640    id: entry.id,
641    n: entry.n,
642    color: entry.color,
643    title: entry.title,
644    isManual: entry.isManual,
645    at: await $.clock.now(),
646    updatedAt: entry.updatedAt,
647    root: entry.root,
648    topic: entry.topic,
649    isTopicSet: entry.isTopicSet,
650    codename: entry.codename,
651    today: entry.today,
652  })
653}
654
655/**
656 * After a /clear the process goes on under a new id and the color is reset:
657 * carry the entry over and set the name and color again.
658 *
659 * @param $ the engine interface
660 * @param before the entry from before the clear
661 */
662async function afterClear($: EngineInterface, before: LiveEntry) {
663  const id = await $.session.id()
664
665  me = { ...before, id, at: await $.clock.now() }
666  await save($, me)
667  runSoon($, me.isManual ? null : me.title, me.color)
668}
669
670/**
671 * The answer to a bare /nametag: this session's tag and the live sessions.
672 *
673 * @param $ the engine interface
674 */
675async function status($: EngineInterface): Promise<string> {
676  const config = await readConfig($)
677  const id = await $.session.id()
678  const live = await others($, id)
679  const template = isPreset(config.template)
680    ? `preset "${config.template}"`
681    : config.saved[config.template] !== undefined
682      ? `saved "${config.template}" (${config.saved[config.template] ?? ''})`
683      : `template ${config.template}`
684  const lines = [
685    me
686      ? `This session: ${me.title ?? '(name left as is)'}${me.color ? `, ${me.color}` : ''}${me.isManual ? ', name kept as you set it' : ''}`
687      : 'This session is not tagged. /nametag force tags it.',
688    `Naming: ${template}. Color: ${config.color}.${config.isOn ? '' : ' Off for new sessions.'}${config.offFolders.length ? ` Off in ${config.offFolders.length} folder(s).` : ''}`,
689  ]
690
691  if (live.length) {
692    lines.push('Other live sessions:')
693
694    for (const o of live) {
695      lines.push(`  ${o.title ?? baseName(o.key)}${o.color ? ` (${o.color})` : ''}`)
696    }
697  }
698
699  return lines.join('\n')
700}
701
702export function register(on: On) {
703  on('session.start', async ($, e, next) => {
704    const result = await next(e)
705
706    if (!e.isInteractive) {
707      return result
708    }
709
710    await $.command.register({
711      name: COMMAND_NAME,
712      description: 'Name and color this session: presets, topic, templates, force, color, off',
713      argumentHint: '[preset|default|topic|template|save|force|color|sigil|off|on|presets|help]',
714    })
715
716    if (!isHeartbeat) {
717      isHeartbeat = true
718      $.clock.every(HEARTBEAT_MS, async () => {
719        if (me) {
720          me = { ...me, at: await $.clock.now() }
721          await save($, me)
722        }
723      })
724      $.clock.every(FOLLOW_MS, () => followShell($))
725    }
726
727    // A hot reload starts the module over mid-session: pick the entry back up
728    // instead of tagging again.
729    const existing = asLive(await $.store.get(`${LIVE_PREFIX}${await $.session.id()}`))
730
731    if (existing) {
732      me = existing
733
734      return result
735    }
736
737    $.clock.after(0, () => {
738      tagAtStart($).catch((error: unknown) => {
739        $.ui.log(
740          `session-nametag could not tag this session: ${error instanceof Error ? error.message : String(error)}`,
741        )
742      })
743    })
744
745    return result
746  })
747
748  // A folder change found as a turn starts happened before it: a `!cd` you
749  // typed. Then the turn is marked, so a cd Claude makes in it is not
750  // followed. The prompt itself is never read.
751  on('turn.start', async ($, e, next) => {
752    if (!isTurn) {
753      await followShell($)
754    }
755
756    isTurn = true
757
758    return next(e)
759  })
760
761  on('turn.complete', async ($, e, next) => {
762    const result = await next(e)
763
764    if (!e.agentId) {
765      isTurn = false
766      shellAt = await $.session.cwd()
767      await refresh($)
768    }
769
770    return result
771  })
772
773  on('command.run', async ($, e, next) => {
774    const isPlugin = e.origin?.kind === 'plugin'
775
776    if (e.command === 'rename' && !isPlugin && me) {
777      me = { ...me, isManual: true }
778      await save($, me)
779    }
780
781    if (e.command === 'color' && !isPlugin && me) {
782      me = { ...me, color: null }
783      await save($, me)
784    }
785
786    if (e.command === 'model') {
787      const result = await next(e)
788
789      $.clock.after(DEFER_MS, () => {
790        refresh($).catch(() => undefined)
791      })
792
793      return result
794    }
795
796    if (e.command !== COMMAND_NAME) {
797      return next(e)
798    }
799
800    const parsed = parseArgs(e.args)
801
802    switch (parsed.kind) {
803      case 'show':
804        return { text: await status($) }
805      case 'help':
806        return { text: USAGE }
807      case 'error':
808        return { text: parsed.text }
809      case 'presets': {
810        const { v } = await values($, me?.n ?? 1, undefined, true)
811        const config = await readConfig($)
812        const names = [...PRESET_ORDER, ...Object.keys(config.saved).sort()]
813        const width = Math.max(8, ...names.map((name) => name.length))
814        const lines = names.map(
815          (name) =>
816            `${name === config.template ? '>' : ' '} ${name.padEnd(width)} ${render(resolveTemplate(name, config.saved), v)}`,
817        )
818        const custom =
819          isPreset(config.template) || config.saved[config.template] !== undefined
820            ? []
821            : [`> ${'(yours)'.padEnd(width)} ${render(config.template, v)}   /nametag save <name> keeps it`]
822
823        return {
824          text: ['Presets for this session (> is in use; /nametag <name> picks one):', ...lines, ...custom].join('\n'),
825        }
826      }
827      case 'preset':
828      case 'template': {
829        const config = await readConfig($)
830        const template = parsed.kind === 'preset' ? parsed.name : parsed.template
831
832        await $.store.set(CONFIG_KEY, { ...config, template })
833        const title = await applyNow($)
834
835        return { text: `New sessions will be named like this one: ${title}` }
836      }
837      case 'named': {
838        const config = await readConfig($)
839
840        if (config.saved[parsed.name] === undefined) {
841          return {
842            text: `No preset or saved template called "${parsed.name}". /nametag presets lists them; /nametag help lists the options.`,
843          }
844        }
845
846        await $.store.set(CONFIG_KEY, { ...config, template: parsed.name })
847        const title = await applyNow($)
848
849        return { text: `Using "${parsed.name}": ${title}` }
850      }
851      case 'save': {
852        const config = await readConfig($)
853        const text = parsed.template ?? resolveTemplate(config.template, config.saved)
854        const isNew = config.saved[parsed.name] === undefined
855
856        if (isNew && Object.keys(config.saved).length >= MAX_SAVED) {
857          return { text: `You have ${MAX_SAVED} saved templates already; /nametag delete <name> makes room.` }
858        }
859
860        await $.store.set(CONFIG_KEY, {
861          ...config,
862          saved: { ...config.saved, [parsed.name]: text },
863          template: parsed.name,
864        })
865
866        if (parsed.template) {
867          const title = await applyNow($)
868
869          return { text: `Saved "${parsed.name}" and using it: ${title}` }
870        }
871
872        return {
873          text: `${isNew ? 'Saved' : 'Updated'} "${parsed.name}": ${text}. /nametag ${parsed.name} brings it back.`,
874        }
875      }
876      case 'topic': {
877        if (!me) {
878          return { text: 'This session is not tagged. /nametag force tags it.' }
879        }
880
881        if (parsed.mode === 'show') {
882          return { text: me.topic ? `Topic: ${me.topic}` : 'No topic yet. /nametag topic <text> sets one.' }
883        }
884
885        me =
886          parsed.mode === 'set'
887            ? { ...me, topic: shorten(parsed.text, 40), isTopicSet: true }
888            : { ...me, topic: '', isTopicSet: true }
889        await save($, me)
890        await refresh($)
891
892        return { text: parsed.mode === 'set' ? `Topic: ${me.topic}` : 'No topic for this session.' }
893      }
894      case 'sigil': {
895        const config = await readConfig($)
896        const { key } = await values($, me?.n ?? 1)
897        const sigils = { ...config.sigils }
898
899        if (parsed.emoji) {
900          sigils[key] = parsed.emoji
901        } else {
902          delete sigils[key]
903        }
904
905        await $.store.set(CONFIG_KEY, { ...config, sigils })
906        await refresh($)
907
908        return { text: `This folder's emoji: ${sigilFor(key, sigils)}` }
909      }
910      case 'delete': {
911        const config = await readConfig($)
912
913        if (config.saved[parsed.name] === undefined) {
914          return { text: `No saved template called "${parsed.name}".` }
915        }
916
917        const saved = { ...config.saved }
918        const text = saved[parsed.name] ?? ''
919
920        delete saved[parsed.name]
921
922        // Deleting the one in use keeps its text as the template, so nothing renames.
923        const template = config.template === parsed.name ? text : config.template
924
925        await $.store.set(CONFIG_KEY, { ...config, saved, template })
926
927        return { text: `Deleted "${parsed.name}".` }
928      }
929      case 'apply': {
930        const title = await applyNow($, true)
931
932        return { text: `Tagged: ${title}` }
933      }
934      case 'color': {
935        const config = await readConfig($)
936
937        await $.store.set(CONFIG_KEY, { ...config, color: parsed.color })
938
939        if (me && parsed.color !== 'off') {
940          const live = await others($, me.id)
941          const color = assign(me.key, live, parsed.color).color
942
943          me = { ...me, color }
944          await save($, me)
945          runSoon($, null, color)
946
947          return {
948            text: `Color: ${parsed.color}${color && color !== parsed.color ? ` (${color} for this session)` : ''}.`,
949          }
950        }
951
952        if (me && parsed.color === 'off') {
953          me = { ...me, color: null }
954          await save($, me)
955        }
956
957        return { text: `Color: ${parsed.color}. New sessions follow it.` }
958      }
959      case 'power': {
960        const config = await readConfig($)
961
962        if (parsed.isHere) {
963          const { key } = await values($, 1)
964          const offFolders = parsed.isOn
965            ? config.offFolders.filter((k) => k !== key)
966            : [...new Set([...config.offFolders, key])]
967
968          await $.store.set(CONFIG_KEY, { ...config, offFolders })
969
970          return { text: `New sessions in this folder will ${parsed.isOn ? 'be tagged again' : 'be left alone'}.` }
971        }
972
973        await $.store.set(CONFIG_KEY, { ...config, isOn: parsed.isOn })
974
975        return {
976          text: parsed.isOn
977            ? 'New sessions will be tagged again.'
978            : 'New sessions will be left alone. /nametag on turns it back on.',
979        }
980      }
981    }
982  })
983    // A failure here must never cost the person their command.
984    .catch(($, e, next) => next(e))
985
986  on('session.end', async ($, e, next) => {
987    const result = await next(e)
988
989    if (me) {
990      const before = me
991
992      me = null
993
994      if (e.reason === 'clear') {
995        await $.store.delete(`${LIVE_PREFIX}${before.id}`)
996        $.clock.after(DEFER_MS, () => {
997          afterClear($, before).catch(() => undefined)
998        })
999      } else {
1000        await retire($, before)
1001      }
1002    }
1003
1004    return result
1005  })
1006}
1007
hooks/tag.ts 987 lines
1/**
2 * Pure helpers for session-nametag: templates and presets, the date and model
3 * labels, color and instance-number picking, the live-session registry rules
4 * and the /nametag argument parser. Nothing here takes `$`, so the tests run
5 * it directly.
6 */
7
8/** The eight colors `/color` accepts, in the order a folder's hash walks them. */
9export const COLORS = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'cyan'] as const
10
11export type ColorName = (typeof COLORS)[number]
12
13/** Named templates, from compact to detailed. `full` is the default. */
14export const PRESET_ORDER = ['compact', 'branch', 'status', 'host', 'model', 'timed', 'full'] as const
15
16export type PresetName = (typeof PRESET_ORDER)[number]
17
18export const PRESETS: Record<PresetName, string> = {
19  compact: '{folder}{ #nth}',
20  branch: '{folder}{/branch}{ #nth}',
21  status: '{sigil }{folder}{/branch}{ #nth}{ · topic}',
22  host: '{folder}{/branch}{ #nth}{ @ host}',
23  model: '{[model] }{folder}{/branch}{ #nth}{ @ host}',
24  timed: '{[model] }{folder}{/branch}{ #nth}{ @ host}{ day time}',
25  full: '{[model] }{folder}{/branch}{ #nth}{ · topic}{ @ host}{ datetime}',
26}
27
28/**
29 * Whether a name is one of the presets.
30 *
31 * @param name a word the person typed or the config holds
32 */
33export function isPreset(name: string): name is PresetName {
34  return (PRESET_ORDER as readonly string[]).includes(name)
35}
36
37export const DEFAULT_PRESET = 'full'
38
39/** Longest title the mod sets; the session list truncates long ones anyway. */
40export const MAX_TITLE = 120
41
42/** A live entry older than this is a session that died without saying so. */
43export const STALE_MS = 3 * 60_000
44
45/** How often a session refreshes its own live entry. */
46export const HEARTBEAT_MS = 60_000
47
48/** How long a session's remembered name and color outlive it, for resume. */
49export const SEEN_TTL_MS = 30 * 24 * 60 * 60_000
50
51export const LIVE_PREFIX = 'live.'
52export const SEEN_PREFIX = 'seen.'
53export const CONFIG_KEY = 'config'
54
55/** What a template's tokens are filled from. Empty strings drop their group. */
56export type TagValues = {
57  model: string
58  folder: string
59  dir: string
60  branch: string
61  /** The instance number among live sessions in the same folder, from 1. */
62  n: number
63  host: string
64  /** When the session first started, in epoch milliseconds. */
65  startedAt: number
66  /** When the name last changed for a reason other than this time itself. */
67  updatedAt: number
68  /** What the session is about, set by /nametag topic. */
69  topic?: string
70  /** The origin remote as owner/name. */
71  remote?: string
72  /** Two words that stay with the session for life. */
73  codename?: string
74  /** The folder's emoji. */
75  sigil?: string
76  /** This session's place among the sessions opened today on this machine. */
77  today?: number
78}
79
80/** The token names a template may use. */
81export const TOKENS = [
82  'model',
83  'family',
84  'folder',
85  'dir',
86  'remote',
87  'branch',
88  'num',
89  'nth',
90  'host',
91  'topic',
92  'codename',
93  'sigil',
94  'todaycount',
95  'datetime',
96  'date',
97  'day',
98  'time',
99  'updated',
100  'updateddatetime',
101  'updateddate',
102] as const
103
104export type Token = (typeof TOKENS)[number]
105
106/** What each token is, for /nametag help and the typeahead. */
107export const TOKEN_HELP: Record<Token, string> = {
108  model: 'model and version, e.g. Opus 5.5',
109  family: 'model without the version, e.g. Opus',
110  folder: 'the repository (worktrees and subfolders share it)',
111  dir: 'the folder the session started in',
112  branch: 'git branch; the group hides outside git',
113  remote: 'the origin remote, e.g. lperezmo/hess-trading',
114  nth: 'instance number; hidden for the first session in a folder',
115  topic: 'what the session is about, set with /nametag topic <text>',
116  codename: 'two words that stay with the session, e.g. brisk-otter',
117  sigil: 'the folder emoji (/nametag sigil <emoji> picks one)',
118  todaycount: 'which session this is today on this machine, e.g. 7',
119  num: 'instance number, always shown',
120  host: "this machine's name",
121  datetime: 'session start, e.g. Wed Oct 7th, 2026 9:05 am',
122  date: 'session start date, e.g. Oct 7th, 2026',
123  day: 'session start weekday, e.g. Wed',
124  time: 'session start time, e.g. 9:05 am',
125  updated: 'when the name last changed, e.g. 2:14 pm (Thu 2:14 pm on a later day)',
126  updateddatetime: 'when the name last changed, e.g. Thu Oct 8th, 2026 11:00 am',
127  updateddate: 'the day the name last changed, e.g. Oct 8th, 2026',
128}
129
130/** Groups with their usual punctuation, offered first in the typeahead. */
131export const SNIPPETS: readonly { text: string; token: Token }[] = [
132  { text: '{[model] }', token: 'model' },
133  { text: '{[family] }', token: 'family' },
134  { text: '{/branch}', token: 'branch' },
135  { text: '{ #nth}', token: 'nth' },
136  { text: '{ · topic}', token: 'topic' },
137  { text: '{sigil }', token: 'sigil' },
138  { text: '{ #todaycount today}', token: 'todaycount' },
139  { text: '{ @ host}', token: 'host' },
140  { text: '{ · updated}', token: 'updated' },
141]
142
143const TOKEN_RE = new RegExp('(?<![A-Za-z])(' + TOKENS.join('|') + ')(?![A-Za-z])', 'g')
144
145const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
146const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
147
148/**
149 * The English ordinal of a day of the month: 1st, 2nd, 3rd, 4th, 11th, 22nd.
150 *
151 * @param day the day of the month
152 */
153export function ordinal(day: number): string {
154  const tens = day % 100
155
156  if (tens >= 11 && tens <= 13) {
157    return `${day}th`
158  }
159
160  const suffix = ['th', 'st', 'nd', 'rd'][day % 10] ?? 'th'
161
162  return `${day}${day % 10 > 3 ? 'th' : suffix}`
163}
164
165/**
166 * The clock time as `9:00 am`.
167 *
168 * @param d the moment, read in local time
169 */
170export function clockTime(d: Date): string {
171  const h = d.getHours()
172  const m = String(d.getMinutes()).padStart(2, '0')
173
174  return `${h % 12 === 0 ? 12 : h % 12}:${m} ${h < 12 ? 'am' : 'pm'}`
175}
176
177/**
178 * The parts the date tokens render, from one moment in local time.
179 *
180 * @param ms epoch milliseconds
181 */
182export function dateParts(ms: number): { datetime: string; date: string; day: string; time: string } {
183  const d = new Date(ms)
184  const day = DAYS[d.getDay()] ?? ''
185  const date = `${MONTHS[d.getMonth()] ?? ''} ${ordinal(d.getDate())}, ${d.getFullYear()}`
186  const time = clockTime(d)
187
188  return { datetime: `${day} ${date} ${time}`, date, day, time }
189}
190
191/**
192 * When the name last changed: the clock time on the day the session started
193 * (`2:14 pm`), the weekday too on a later day (`Thu 2:14 pm`).
194 *
195 * @param startedAt when the session started
196 * @param updatedAt when the name last changed
197 */
198export function updatedLabel(startedAt: number, updatedAt: number): string {
199  const start = new Date(startedAt)
200  const d = new Date(updatedAt)
201  const isSameDay =
202    start.getFullYear() === d.getFullYear() && start.getMonth() === d.getMonth() && start.getDate() === d.getDate()
203
204  return isSameDay ? clockTime(d) : `${DAYS[d.getDay()] ?? ''} ${clockTime(d)}`
205}
206
207/**
208 * A model id as a person says it: `claude-opus-5-5` reads `Opus 5.5`,
209 * `claude-sonnet-4-5-20250929[1m]` reads `Sonnet 4.5`. Unknown ids pass
210 * through with only the `claude-` prefix and bracket suffix removed.
211 *
212 * @param id the model id or alias the session runs on
213 */
214export function modelLabel(id: string): string {
215  const s = id
216    .trim()
217    .toLowerCase()
218    .replace(/\[[^\]]*\]/g, '')
219    .replace(/^claude-/, '')
220    .replace(/-\d{8}$/, '')
221  const match = /^([a-z]+)(?:-(\d+))?(?:-(\d+))?$/.exec(s)
222
223  const name = match?.[1]
224
225  if (!match || !name) {
226    return s
227  }
228
229  const family = name.charAt(0).toUpperCase() + name.slice(1)
230  const version = [match[2], match[3]].filter(Boolean).join('.')
231
232  return version ? `${family} ${version}` : family
233}
234
235/**
236 * The last segment of a path, either separator: `D:\Python\foo` reads
237 * `foo`, a drive root `D:\` reads `D:`.
238 *
239 * @param path an absolute path
240 */
241export function baseName(path: string): string {
242  const parts = path.split(/[\\/]+/).filter(Boolean)
243
244  return parts[parts.length - 1] ?? path
245}
246
247/**
248 * The key two sessions share when they run on the same project: the folder's
249 * path, lowercased with one separator style, since Windows paths are
250 * case-insensitive.
251 *
252 * @param path the repository root or working directory
253 */
254export function folderKey(path: string): string {
255  return path.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
256}
257
258/**
259 * The tokens a template uses, so only those values are worked out (each git
260 * call costs a little on every turn).
261 *
262 * @param template the template text
263 */
264export function usedTokens(template: string): Set<Token> {
265  const used = new Set<Token>()
266
267  for (const group of template.matchAll(/\{([^{}]*)\}/g)) {
268    for (const m of (group[1] ?? '').matchAll(new RegExp(TOKEN_RE.source, 'g'))) {
269      used.add(m[1] as Token)
270    }
271  }
272
273  return used
274}
275
276/**
277 * Whether a folder is the other one or inside it, either separator, any case.
278 *
279 * @param child the folder that may be inside
280 * @param parent the folder that may hold it
281 */
282export function isWithin(child: string, parent: string): boolean {
283  const c = folderKey(child)
284  const p = folderKey(parent)
285
286  return c === p || c.startsWith(`${p}/`)
287}
288
289/**
290 * Fills a template. Each `{...}` group holds one or more tokens plus any
291 * literal text around them, and the whole group is dropped when one of its
292 * tokens is empty: `{/branch}` vanishes outside git, `{ #n}` vanishes for the
293 * first session in a folder (`num` always shows). Text outside groups is kept.
294 *
295 * @param template the template text
296 * @param v the values
297 */
298export function render(template: string, v: TagValues): string {
299  const when = dateParts(v.startedAt)
300  const value = (token: string): string => {
301    switch (token) {
302      case 'model':
303        return v.model
304      case 'folder':
305        return v.folder
306      case 'dir':
307        return v.dir
308      case 'branch':
309        return v.branch
310      case 'nth':
311        return v.n > 1 ? String(v.n) : ''
312      case 'remote':
313        return v.remote ?? ''
314      case 'topic':
315        return v.topic ?? ''
316      case 'codename':
317        return v.codename ?? ''
318      case 'sigil':
319        return v.sigil ?? ''
320      case 'todaycount':
321        return v.today ? String(v.today) : ''
322      case 'num':
323        return String(v.n)
324      case 'host':
325        return v.host
326      case 'family':
327        return v.model.split(' ')[0] ?? ''
328      case 'datetime':
329        return when.datetime
330      case 'date':
331        return when.date
332      case 'day':
333        return when.day
334      case 'time':
335        return when.time
336      case 'updated':
337        return updatedLabel(v.startedAt, v.updatedAt)
338      case 'updateddatetime':
339        return dateParts(v.updatedAt).datetime
340      case 'updateddate':
341        return dateParts(v.updatedAt).date
342      default:
343        return ''
344    }
345  }
346
347  const out = template.replace(/\{([^{}]*)\}/g, (whole, inner: string) => {
348    let isEmpty = false
349    let isToken = false
350    const filled = inner.replace(TOKEN_RE, (token: string) => {
351      isToken = true
352      const text = value(token)
353
354      if (!text) {
355        isEmpty = true
356      }
357
358      return text
359    })
360
361    if (!isToken) {
362      return whole
363    }
364
365    return isEmpty ? '' : filled
366  })
367
368  const title = out.replace(/\s+/g, ' ').trim()
369
370  return title.length > MAX_TITLE ? `${title.slice(0, MAX_TITLE - 1).trimEnd()}…` : title
371}
372
373/**
374 * A preset's or saved template's text, or the text itself when it names
375 * neither.
376 *
377 * @param template a preset name, a saved name, or a template
378 * @param saved the person's saved templates by name
379 */
380export function resolveTemplate(template: string, saved: Readonly<Record<string, string>> = {}): string {
381  if (isPreset(template)) {
382    return PRESETS[template]
383  }
384
385  return Object.prototype.hasOwnProperty.call(saved, template) ? (saved[template] ?? template) : template
386}
387
388/** Words a saved template may not be called: the presets and the options. */
389export const RESERVED = [
390  'presets',
391  'list',
392  'preview',
393  'template',
394  'force',
395  'apply',
396  'now',
397  'color',
398  'colour',
399  'off',
400  'on',
401  'help',
402  'save',
403  'delete',
404  'remove',
405  'topic',
406  'sigil',
407  'default',
408  'reset',
409] as const
410
411/** How many saved templates the store keeps. */
412export const MAX_SAVED = 20
413
414/**
415 * Why a name cannot be used for a saved template, or null when it can.
416 *
417 * @param name the name the person typed
418 */
419export function badName(name: string): string | null {
420  if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(name)) {
421    return 'Names are 1 to 24 lowercase letters, digits, - or _, starting with a letter or digit.'
422  }
423
424  if (isPreset(name) || (RESERVED as readonly string[]).includes(name)) {
425    return `"${name}" is taken by a built-in preset or option; pick another name.`
426  }
427
428  return null
429}
430
431/**
432 * FNV-1a, 32 bit: a stable small hash for picking a folder's color.
433 *
434 * @param text what to hash
435 */
436export function hash(text: string): number {
437  let h = 0x811c9dc5
438
439  for (let i = 0; i < text.length; i++) {
440    h ^= text.charCodeAt(i)
441    h = Math.imul(h, 0x01000193) >>> 0
442  }
443
444  return h
445}
446
447/**
448 * The folder's own color, or the next one along that no other live session
449 * holds. With all eight taken, the folder's own color repeats.
450 *
451 * @param key the folder key
452 * @param taken colors other live sessions hold
453 */
454export function pickColor(key: string, taken: readonly string[]): ColorName {
455  const start = hash(key) % COLORS.length
456
457  for (let i = 0; i < COLORS.length; i++) {
458    const color = COLORS[(start + i) % COLORS.length]
459
460    if (color && !taken.includes(color)) {
461      return color
462    }
463  }
464
465  return COLORS[start] ?? 'blue'
466}
467
468/**
469 * The lowest instance number from 1 that no other live session in the same
470 * folder holds.
471 *
472 * @param taken numbers other live sessions in the folder hold
473 */
474export function pickNumber(taken: readonly number[]): number {
475  let n = 1
476
477  while (taken.includes(n)) {
478    n++
479  }
480
481  return n
482}
483
484/** One running session as the shared store records it. */
485export type LiveEntry = {
486  id: string
487  key: string
488  n: number
489  /** The color this mod set, or null when it set none. */
490  color: string | null
491  /** The last heartbeat, epoch milliseconds. */
492  at: number
493  /** The title this mod last set, so a manual rename can be told apart. */
494  title: string | null
495  /** True once the person renamed the session themselves. */
496  isManual: boolean
497  /** When the name last changed, for the `updated` token; absent until it does. */
498  updatedAt?: number
499  /** The folder /nametag force pinned the session to; absent, where it started. */
500  root?: string
501  /** What the session is about, set by /nametag topic. */
502  topic?: string
503  /** True once /nametag topic set it by hand (or switched it off). */
504  isTopicSet?: boolean
505  /** Two words that stay with the session for life. */
506  codename?: string
507  /** Its place among the sessions opened that day on this machine. */
508  today?: number
509}
510
511/** A session's name and color, kept after it ends so a resume can restore them. */
512export type SeenEntry = {
513  id: string
514  n: number
515  color: string | null
516  title: string | null
517  isManual: boolean
518  at: number
519  updatedAt?: number
520  root?: string
521  /** What the session is about, set by /nametag topic. */
522  topic?: string
523  /** True once /nametag topic set it by hand (or switched it off). */
524  isTopicSet?: boolean
525  /** Two words that stay with the session for life. */
526  codename?: string
527  /** Its place among the sessions opened that day on this machine. */
528  today?: number
529}
530
531/** The person's choices, shared by every session on the machine. */
532export type Config = {
533  /** A preset name or a custom template. */
534  template: string
535  /** `auto` picks per folder, `off` sets none, a color name pins one. */
536  color: string
537  /** False stops naming new sessions everywhere. */
538  isOn: boolean
539  /** Folder keys where new sessions are left alone. */
540  offFolders: string[]
541  /** The person's own templates by name (`/nametag save`). */
542  saved: Record<string, string>
543  /** Emoji the person picked per folder key (`/nametag sigil`). */
544  sigils: Record<string, string>
545}
546
547export const DEFAULT_CONFIG: Config = {
548  template: DEFAULT_PRESET,
549  color: 'auto',
550  isOn: true,
551  offFolders: [],
552  saved: {},
553  sigils: {},
554}
555
556/**
557 * A stored value as a Config, defaults filling whatever is missing or wrong.
558 *
559 * @param raw what the store held
560 */
561export function asConfig(raw: unknown): Config {
562  const o = (raw && typeof raw === 'object' ? raw : {}) as Partial<Config>
563
564  return {
565    template: typeof o.template === 'string' && o.template.trim() ? o.template : DEFAULT_CONFIG.template,
566    color: typeof o.color === 'string' ? o.color : DEFAULT_CONFIG.color,
567    isOn: typeof o.isOn === 'boolean' ? o.isOn : DEFAULT_CONFIG.isOn,
568    offFolders: Array.isArray(o.offFolders) ? o.offFolders.filter((x): x is string => typeof x === 'string') : [],
569    saved: asSaved(o.saved),
570    sigils: asStrings(o.sigils),
571  }
572}
573
574/**
575 * A stored value as saved templates, keeping only well-formed entries.
576 *
577 * @param raw what the store held
578 */
579function asStrings(raw: unknown): Record<string, string> {
580  const out: Record<string, string> = {}
581
582  if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
583    for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
584      if (typeof v === 'string' && v.trim()) {
585        out[k] = v
586      }
587    }
588  }
589
590  return out
591}
592
593function asSaved(raw: unknown): Record<string, string> {
594  const out: Record<string, string> = {}
595
596  if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
597    for (const [name, text] of Object.entries(raw as Record<string, unknown>)) {
598      if (typeof text === 'string' && text.trim() && badName(name) === null) {
599        out[name] = text
600      }
601    }
602  }
603
604  return out
605}
606
607/**
608 * A stored value as a LiveEntry, or null when it is not one.
609 *
610 * @param raw what the store held
611 */
612export function asLive(raw: unknown): LiveEntry | null {
613  if (!raw || typeof raw !== 'object') {
614    return null
615  }
616
617  const o = raw as Partial<LiveEntry>
618
619  if (typeof o.id !== 'string' || typeof o.key !== 'string' || typeof o.n !== 'number' || typeof o.at !== 'number') {
620    return null
621  }
622
623  return {
624    id: o.id,
625    key: o.key,
626    n: o.n,
627    at: o.at,
628    color: typeof o.color === 'string' ? o.color : null,
629    title: typeof o.title === 'string' ? o.title : null,
630    isManual: o.isManual === true,
631    ...(typeof o.updatedAt === 'number' ? { updatedAt: o.updatedAt } : {}),
632    ...(typeof o.root === 'string' ? { root: o.root } : {}),
633    ...(typeof o.topic === 'string' ? { topic: o.topic } : {}),
634    ...(o.isTopicSet === true ? { isTopicSet: true } : {}),
635    ...(typeof o.codename === 'string' ? { codename: o.codename } : {}),
636    ...(typeof o.today === 'number' ? { today: o.today } : {}),
637  }
638}
639
640/**
641 * A stored value as a SeenEntry, or null when it is not one.
642 *
643 * @param raw what the store held
644 */
645export function asSeen(raw: unknown): SeenEntry | null {
646  if (!raw || typeof raw !== 'object') {
647    return null
648  }
649
650  const o = raw as Partial<SeenEntry>
651
652  if (typeof o.id !== 'string' || typeof o.at !== 'number') {
653    return null
654  }
655
656  return {
657    id: o.id,
658    n: typeof o.n === 'number' ? o.n : 1,
659    at: o.at,
660    color: typeof o.color === 'string' ? o.color : null,
661    title: typeof o.title === 'string' ? o.title : null,
662    isManual: o.isManual === true,
663    ...(typeof o.updatedAt === 'number' ? { updatedAt: o.updatedAt } : {}),
664    ...(typeof o.root === 'string' ? { root: o.root } : {}),
665    ...(typeof o.topic === 'string' ? { topic: o.topic } : {}),
666    ...(o.isTopicSet === true ? { isTopicSet: true } : {}),
667    ...(typeof o.codename === 'string' ? { codename: o.codename } : {}),
668    ...(typeof o.today === 'number' ? { today: o.today } : {}),
669  }
670}
671
672/**
673 * Whether a live entry's session still beats.
674 *
675 * @param entry the entry
676 * @param now epoch milliseconds
677 */
678export function isAlive(entry: LiveEntry, now: number): boolean {
679  return now - entry.at < STALE_MS
680}
681
682/**
683 * The number and color a new session should take, given the other live ones.
684 * When two sessions start at the same moment and pick the same number, the
685 * one whose id sorts later moves on, which `settle` decides after both wrote.
686 *
687 * @param key this session's folder key
688 * @param others the other sessions' live entries, stale ones already dropped
689 * @param colorChoice the config's color: auto, off, or a pinned name
690 */
691export function assign(
692  key: string,
693  others: readonly LiveEntry[],
694  colorChoice: string,
695): { n: number; color: string | null } {
696  const n = pickNumber(others.filter((o) => o.key === key).map((o) => o.n))
697  const color =
698    colorChoice === 'off'
699      ? null
700      : (COLORS as readonly string[]).includes(colorChoice)
701        ? colorChoice
702        : pickColor(
703            key,
704            others.map((o) => o.color).filter((c): c is string => c !== null),
705          )
706
707  return { n, color }
708}
709
710/**
711 * Whether this session must give up its number because another live session
712 * in the same folder took it too and wins the tie (earlier id).
713 *
714 * @param me this session's entry
715 * @param others the other sessions' live entries
716 */
717export function mustYield(me: LiveEntry, others: readonly LiveEntry[]): boolean {
718  return others.some((o) => o.key === me.key && o.n === me.n && o.id < me.id)
719}
720
721export type Parsed =
722  | { kind: 'show' }
723  | { kind: 'help' }
724  | { kind: 'presets' }
725  | { kind: 'preset'; name: string }
726  | { kind: 'template'; template: string }
727  | { kind: 'apply' }
728  | { kind: 'color'; color: string }
729  | { kind: 'power'; isOn: boolean; isHere: boolean }
730  | { kind: 'save'; name: string; template: string | null }
731  | { kind: 'delete'; name: string }
732  | { kind: 'named'; name: string }
733  | { kind: 'topic'; mode: 'set' | 'off' | 'show'; text: string }
734  | { kind: 'sigil'; emoji: string | null }
735  | { kind: 'error'; text: string }
736
737export const USAGE = [
738  'Usage: /nametag [preset|default|topic|template|save|delete|force|color|sigil|off|on|presets|help]',
739  "  /nametag                  show this session's tag and the live sessions",
740  '  /nametag presets          preview every preset for this session',
741  `  /nametag <preset>         use a preset from now on: ${PRESET_ORDER.join(', ')}`,
742  `  /nametag default          back to the default preset (${DEFAULT_PRESET}); reset works too`,
743  '  /nametag template <text>  use your own template, e.g. {folder}{/branch}{ #nth}',
744  '  /nametag save <name>      keep the template in use under a name; /nametag <name> brings it back',
745  '  /nametag save <name> <text>  save that template under the name and use it',
746  '  /nametag delete <name>    forget a saved template',
747  '  /nametag topic <text>     set what this session is about (topic off: none)',
748  '  /nametag sigil <emoji>    pick the emoji for this folder (sigil auto: back to the one it was given)',
749  '  /nametag force            tag this session for the folder the shell is in now, even a resumed or renamed one',
750  '  /nametag color <c>        auto (per folder), off, or one of: ' + COLORS.join(', '),
751  '  /nametag off [here]       stop naming new sessions (here = only in this folder)',
752  '  /nametag on [here]        start again',
753  'Tokens:',
754  ...TOKENS.map((t) => '  ' + t.padEnd(9) + ' ' + TOKEN_HELP[t]),
755  'A {group} with an empty token disappears, so {/branch} hides outside git and { #n} hides for the first session in a folder.',
756].join('\n')
757
758/** The first word after /nametag, with what it does, for the typeahead. */
759export const SUBCOMMANDS: readonly { name: string; description: string }[] = [
760  { name: 'presets', description: 'preview every preset for this session' },
761  ...PRESET_ORDER.map((name) => ({ name, description: `preset: ${PRESETS[name]}` })),
762  { name: 'default', description: `back to the default preset (${DEFAULT_PRESET})` },
763  { name: 'template', description: 'your own template; type { for the tokens' },
764  { name: 'save', description: 'keep the template in use under a name' },
765  { name: 'delete', description: 'forget a saved template' },
766  { name: 'topic', description: 'set what this session is about (off clears it)' },
767  { name: 'sigil', description: 'pick this folder emoji (auto)' },
768  { name: 'force', description: 'tag this session for the folder you are in now' },
769  { name: 'color', description: 'auto, off, or a fixed color' },
770  { name: 'off', description: 'stop tagging new sessions (add "here" for this folder only)' },
771  { name: 'on', description: 'start tagging again (add "here" for this folder only)' },
772  { name: 'help', description: 'commands and tokens' },
773]
774
775export type Suggestion = { text: string; label?: string; description?: string }
776
777const COMMAND_PREFIX = '/nametag '
778
779/**
780 * The typeahead rows for the word at the cursor while /nametag is typed: its
781 * options first, a color or "here" after the option that takes one, and in a
782 * template the tokens as soon as a `{` is typed.
783 *
784 * @param text the whole prompt box
785 * @param token the run of non-space characters that ends at the cursor
786 * @param start where that run begins in `text`
787 * @param saved the person's saved templates by name
788 */
789export function suggest(
790  text: string,
791  token: string,
792  start: number,
793  saved: Readonly<Record<string, string>> = {},
794): Suggestion[] {
795  if (!text.toLowerCase().startsWith(COMMAND_PREFIX) || start < COMMAND_PREFIX.length) {
796    return []
797  }
798
799  const words = text
800    .slice(COMMAND_PREFIX.length, start)
801    .trim()
802    .split(/\s+/)
803    .filter(Boolean)
804    .map((w) => w.toLowerCase())
805  const typed = token.toLowerCase()
806  const brace = token.lastIndexOf('{')
807
808  const isTemplateArg = words[0] === 'template' || (words[0] === 'save' && words.length >= 2)
809
810  if (brace >= 0 && (words.length === 0 || isTemplateArg)) {
811    const before = token.slice(0, brace)
812    const partial = token.slice(brace + 1).toLowerCase()
813    const letters = partial.replace(/[^a-z]/g, '')
814    const rows: Suggestion[] = []
815
816    for (const s of SNIPPETS) {
817      if (s.text.toLowerCase().startsWith(`{${partial}`) || (letters && s.token.startsWith(letters))) {
818        rows.push({ text: before + s.text, label: s.text, description: TOKEN_HELP[s.token] })
819      }
820    }
821
822    // Punctuation typed after the { asks for a group like {/branch}; plain
823    // tokens only follow letters.
824    const isPlain = partial === letters
825
826    for (const t of TOKENS) {
827      if (isPlain && t.startsWith(letters) && !rows.some((r) => r.label === `{${t}}`)) {
828        rows.push({ text: `${before}{${t}}`, label: `{${t}}`, description: TOKEN_HELP[t] })
829      }
830    }
831
832    return rows
833  }
834
835  const mine = Object.keys(saved)
836    .sort()
837    .map((name) => ({ name, description: `saved: ${saved[name] ?? ''}` }))
838
839  if (words.length === 0) {
840    return [...SUBCOMMANDS, ...mine]
841      .filter((c) => c.name.startsWith(typed))
842      .map((c) => ({ text: c.name, description: c.description }))
843  }
844
845  if (words.length === 1 && (words[0] === 'delete' || words[0] === 'remove')) {
846    return mine.filter((c) => c.name.startsWith(typed)).map((c) => ({ text: c.name, description: c.description }))
847  }
848
849  if (words.length === 1 && (words[0] === 'color' || words[0] === 'colour')) {
850    return ['auto', 'off', ...COLORS]
851      .filter((c) => c.startsWith(typed))
852      .map((c) => ({
853        text: c,
854        description:
855          c === 'auto' ? 'each folder its own color' : c === 'off' ? 'leave colors alone' : 'every session this color',
856      }))
857  }
858
859  if (words.length === 1 && (words[0] === 'off' || words[0] === 'on') && 'here'.startsWith(typed)) {
860    return [{ text: 'here', description: 'only sessions in this folder' }]
861  }
862
863  return []
864}
865
866/**
867 * Reads what followed `/nametag`.
868 *
869 * @param args the command's arguments as typed
870 */
871export function parseArgs(args: string): Parsed {
872  const text = args.trim()
873  const [first = '', ...rest] = text.split(/\s+/)
874  const word = first.toLowerCase()
875  const tail = text.slice(first.length).trim()
876
877  if (!word) {
878    return { kind: 'show' }
879  }
880
881  if (word === 'help' || word === '?' || word === '--help') {
882    return { kind: 'help' }
883  }
884
885  if (word === 'presets' || word === 'list' || word === 'preview') {
886    return { kind: 'presets' }
887  }
888
889  if (isPreset(word)) {
890    return { kind: 'preset', name: word }
891  }
892
893  if (word === 'default' || word === 'reset') {
894    return { kind: 'preset', name: DEFAULT_PRESET }
895  }
896
897  if (word === 'template') {
898    return tail
899      ? { kind: 'template', template: tail }
900      : { kind: 'error', text: 'Give the template after the word, e.g. /nametag template {folder}{/branch}{ #n}' }
901  }
902
903  if (word === 'force' || word === 'apply' || word === 'now') {
904    return { kind: 'apply' }
905  }
906
907  if (word === 'color' || word === 'colour') {
908    const color = (rest[0] ?? '').toLowerCase()
909
910    if (color === 'auto' || color === 'off' || (COLORS as readonly string[]).includes(color)) {
911      return { kind: 'color', color }
912    }
913
914    return { kind: 'error', text: `Color must be auto, off, or one of: ${COLORS.join(', ')}` }
915  }
916
917  if (word === 'off' || word === 'on') {
918    const where = (rest[0] ?? '').toLowerCase()
919
920    if (where && where !== 'here') {
921      return { kind: 'error', text: `/nametag ${word} takes nothing or "here"` }
922    }
923
924    return { kind: 'power', isOn: word === 'on', isHere: where === 'here' }
925  }
926
927  if (word === 'save') {
928    const name = (rest[0] ?? '').toLowerCase()
929
930    if (!name) {
931      return { kind: 'error', text: 'Give a name, e.g. /nametag save work' }
932    }
933
934    const why = badName(name)
935
936    if (why) {
937      return { kind: 'error', text: why }
938    }
939
940    const template = tail.slice(rest[0]?.length ?? 0).trim()
941
942    return { kind: 'save', name, template: template || null }
943  }
944
945  if (word === 'topic') {
946    const lower = tail.toLowerCase()
947
948    if (!tail) {
949      return { kind: 'topic', mode: 'show', text: '' }
950    }
951
952    if (lower === 'off') {
953      return { kind: 'topic', mode: 'off', text: '' }
954    }
955
956    return { kind: 'topic', mode: 'set', text: tail }
957  }
958
959  if (word === 'sigil') {
960    if (!tail) {
961      return { kind: 'error', text: 'Give an emoji, e.g. /nametag sigil 🦀, or auto' }
962    }
963
964    return { kind: 'sigil', emoji: tail.toLowerCase() === 'auto' ? null : tail }
965  }
966
967  if (word === 'delete' || word === 'remove') {
968    const name = (rest[0] ?? '').toLowerCase()
969
970    return name ? { kind: 'delete', name } : { kind: 'error', text: 'Give the saved name, e.g. /nametag delete work' }
971  }
972
973  if (text.includes('{')) {
974    return { kind: 'template', template: text }
975  }
976
977  // Maybe one of the person's saved templates; the command knows which exist.
978  if (!rest.length && badName(word) === null) {
979    return { kind: 'named', name: word }
980  }
981
982  return {
983    kind: 'error',
984    text: `Unknown option "${first}". ${PRESET_ORDER.join(', ')} are the presets; /nametag help lists the rest.`,
985  }
986}
987
hooks/extras.ts 309 lines
1/**
2 * Pure helpers for the tokens beyond place and time: git files, remote,
3 * codename, sigil and today's count. Nothing here takes `$`.
4 */
5
6import { hash } from './tag'
7
8/**
9 * Cuts text to a length on a word boundary, with an ellipsis when it was cut.
10 *
11 * @param text the text
12 * @param max the most characters to keep
13 */
14export function shorten(text: string, max: number): string {
15  const t = text.replace(/\s+/g, ' ').trim()
16
17  if (t.length <= max) {
18    return t
19  }
20
21  const cut = t.slice(0, max - 1)
22  const space = cut.lastIndexOf(' ')
23
24  return `${(space > max / 2 ? cut.slice(0, space) : cut).trimEnd()}…`
25}
26
27/**
28 * The branch named by a repository's HEAD file: the branch, or the short
29 * commit when detached; empty when HEAD says neither.
30 *
31 * @param head the HEAD file's text
32 */
33export function branchFromHead(head: string): string {
34  const text = head.trim()
35  const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(text)
36
37  if (ref) {
38    return (ref[1] ?? '').trim()
39  }
40
41  return /^[0-9a-f]{7,}$/i.test(text) ? text.slice(0, 7) : ''
42}
43
44/**
45 * Where a `.git` file points: a worktree's or submodule's `.git` is a file
46 * reading `gitdir: <path>`, relative to the folder holding it or absolute.
47 * Empty when the text is not that.
48 *
49 * @param text the `.git` file's text
50 * @param dir the folder holding the `.git` file
51 */
52export function gitDirFromFile(text: string, dir: string): string {
53  const match = /^gitdir:\s*(.+)$/m.exec(text)
54  const target = (match?.[1] ?? '').trim()
55
56  if (!target) {
57    return ''
58  }
59
60  return /^([a-z]:)?[\\/]/i.test(target) ? target : dir + '/' + target
61}
62
63/**
64 * The `origin` remote's URL from a repository's config file; empty when it
65 * has none.
66 *
67 * @param config the config file's text
68 */
69export function originFromConfig(config: string): string {
70  let isOrigin = false
71
72  for (const raw of config.split(/\r?\n/)) {
73    const line = raw.trim()
74
75    if (line.startsWith('[')) {
76      isOrigin = /^\[remote\s+"origin"\]$/.test(line)
77    } else if (isOrigin) {
78      const match = /^url\s*=\s*(.+)$/.exec(line)
79
80      if (match) {
81        return (match[1] ?? '').trim()
82      }
83    }
84  }
85
86  return ''
87}
88
89/**
90 * The Mac's name from its system configuration plist: LocalHostName (the
91 * network name, e.g. Luiss-MacBook-Pro), else ComputerName; empty when the
92 * file is missing or not XML.
93 *
94 * @param plist the preferences.plist text
95 */
96export function macHostName(plist: string): string {
97  for (const name of ['LocalHostName', 'ComputerName']) {
98    const match = new RegExp('<key>' + name + '</key>\\s*<string>([^<]+)</string>').exec(plist)
99
100    if (match) {
101      return (match[1] ?? '').trim()
102    }
103  }
104
105  return ''
106}
107
108/**
109 * A remote URL as owner/name: scp style `git@host:owner/x.git`,
110 * `https://host/owner/x` and `ssh://host/a/owner/x.git` all work.
111 *
112 * @param url the remote's URL
113 */
114export function remoteSlug(url: string): string {
115  const path = url
116    .trim()
117    .replace(/\/+$/, '')
118    .replace(/\.git$/, '')
119    .replace(/^[a-z+]+:\/\/[^/]+\//i, '')
120    .replace(/^[^@/]+@[^:]+:/, '')
121  const parts = path.split('/').filter(Boolean)
122
123  return parts.length >= 2 ? parts.slice(-2).join('/') : (parts[0] ?? '')
124}
125
126const ADJECTIVES = [
127  'amber',
128  'brisk',
129  'calm',
130  'clever',
131  'cosmic',
132  'crisp',
133  'daring',
134  'dusty',
135  'eager',
136  'fancy',
137  'fuzzy',
138  'gentle',
139  'giddy',
140  'glossy',
141  'golden',
142  'happy',
143  'hasty',
144  'humble',
145  'icy',
146  'jolly',
147  'keen',
148  'lively',
149  'lucky',
150  'mellow',
151  'mighty',
152  'misty',
153  'nimble',
154  'noble',
155  'odd',
156  'plucky',
157  'polite',
158  'proud',
159  'quick',
160  'quiet',
161  'rapid',
162  'rusty',
163  'shiny',
164  'silly',
165  'sleepy',
166  'snappy',
167  'sneaky',
168  'sunny',
169  'swift',
170  'tidy',
171  'tiny',
172  'vivid',
173  'witty',
174  'zesty',
175]
176
177const ANIMALS = [
178  'otter',
179  'badger',
180  'beaver',
181  'bison',
182  'camel',
183  'crane',
184  'dingo',
185  'eagle',
186  'ferret',
187  'finch',
188  'gecko',
189  'heron',
190  'ibis',
191  'koala',
192  'lemur',
193  'llama',
194  'lynx',
195  'marmot',
196  'moose',
197  'newt',
198  'ocelot',
199  'orca',
200  'owl',
201  'panda',
202  'pelican',
203  'puffin',
204  'quokka',
205  'raven',
206  'robin',
207  'salmon',
208  'seal',
209  'shrew',
210  'sloth',
211  'squid',
212  'stoat',
213  'swan',
214  'tapir',
215  'toucan',
216  'turtle',
217  'walrus',
218  'weasel',
219  'whale',
220  'wombat',
221  'yak',
222  'zebra',
223  'magpie',
224  'mole',
225  'goose',
226]
227
228/**
229 * Two words picked from the session id, the same every time for that id.
230 *
231 * @param id the session id
232 */
233export function codenameFor(id: string): string {
234  const h = hash(id)
235
236  return `${ADJECTIVES[h % ADJECTIVES.length] ?? 'brisk'}-${ANIMALS[Math.floor(h / ADJECTIVES.length) % ANIMALS.length] ?? 'otter'}`
237}
238
239/** Emoji a folder's hash picks from: plain, single-glyph, no flags or skin tones. */
240export const SIGILS = [
241  '🦀',
242  '🐙',
243  '🦊',
244  '🐢',
245  '🦉',
246  '🐝',
247  '🦋',
248  '🐳',
249  '🦜',
250  '🐸',
251  '🦔',
252  '🐧',
253  '🦦',
254  '🦥',
255  '🐌',
256  '🦩',
257  '🌵',
258  '🍄',
259  '🌻',
260  '🌲',
261  '🍀',
262  '🌊',
263  '🔥',
264  '⚡',
265  '🌙',
266  '⭐',
267  '🪐',
268  '☄️',
269  '🌈',
270  '❄️',
271  '🚂',
272  '🚀',
273  '⛵',
274  '🛸',
275  '🎈',
276  '🎲',
277  '🧩',
278  '🔭',
279  '🧪',
280  '🧭',
281  '🔧',
282  '📦',
283  '🗿',
284  '🏔️',
285  '🍉',
286  '🍋',
287]
288
289/**
290 * The folder's emoji: the one the person set for it, or the one its hash picks.
291 *
292 * @param folder the folder key
293 * @param chosen emoji the person set per folder key
294 */
295export function sigilFor(folder: string, chosen: Readonly<Record<string, string>> = {}): string {
296  return chosen[folder] ?? SIGILS[hash('sigil:' + folder) % SIGILS.length] ?? '📦'
297}
298
299/**
300 * The local calendar day of a moment, as the key today's count is kept under.
301 *
302 * @param ms epoch milliseconds
303 */
304export function dayKey(ms: number): string {
305  const d = new Date(ms)
306
307  return `day.${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
308}
309