SLOPSHOPPER

ops-dash

Every session with LIFE_ROLE publishes its status; the ops session's /dash pane shows plan usage, every session, a one-week calendar and the shared task list.

panebandguardcommandstatusprocess
v0.2.0no licenseupdated 2026-10-1838kta-lab/dotfile/mods/ops-dash
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ops-dash
│ ┃ fig ✕ › fix the failing auth test and add an audit log call │ ┃ fig r: 更新 │ ┃ 仮の図はまだありません(/Users/dev/.local/sh ⏺ Read(src/auth.ts) │ ┃ are/life/preview/ に png ⎿ Read 6 lines │ ┃ を置く。figstyle.preview(fig, "名前")) ⏺ 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 │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · fig
fig r: 更新 仮の図はまだありません(/Users/dev/.local/share/life/preview / に png を置く。figstyle.preview(fig, "名前"))
Pane · alert
alert r: 更新 ─ Gmail 未処理 0 件(未読 0)・一斉配信 0 件 取得 — ── 読み込んでいます…(最初の取得は 15 秒ほど) ─ Slack 読み込んでいます… ───────────────────────────── DM・グループ DM 0 件の会話・0 件 新しいものは無い チャンネル 0 件の会話・0 件 新しいものは無い Slack を更新 w: チャンネルを選ぶ
Pane · threads
threads 未読 0 ─ 相手 ───────────────────────────────────────────────── まだ返事は届いていません(peer の返事が ops に届くと、ここに相手ごとに並びます) ──────────────────────────────────────────────────────── r: 返事 a: 既読 j: 次の相手 k: 前の相手 n: 次の返事 p:
Pane · notes
notes hub に nas_code / nas_data がある PJ(目次は選んでから読む) 見つかりません
Pane · hubs
hubs 0 件 r: 更新 hub の場所が未設定(pluginConfigs の life_repo) slug status 更新 次の Milestone 次の手順
Pane · peers
c: calendar r: trend k: tasks ─ system usage ───────────────────────────────────────── まだ計測なし ─ sessions ───────────────────────────────────────────── まだ状態を書いたセッションなし ─ calendar ─────────────────────────────────────────── 9木 10金 11土 12日 13月 14火 15水 終 08 · · · · · · · 09 · · · · · · · 10 · · · · · · · 11 · · · · · · · 12 · · · · · · · 13 · · · · · · · 14 · · · · · · · 15 · · · · · · · 16 · · · · · · · 17 · · · · · · · 18 · · · · · · · 19 · · · · · · · 20 · · · · · · · この先の予定なし ─ trend ────────────────────────────────────────────── ─ tasks ──────────────────────────────────────────────── タスク未設定(pluginConfigs の life_repo)
README

dotfile

Personal dotfiles for zsh, WezTerm, and global Codex / Claude Code Skills.

Initialization

./init.sh

init.sh は idempotent。以下のいずれかをやったら再実行する:

  • skills/<name>/ を追加した (新 skill)
  • skills/<name>/ を削除した (broken symlink が link_skills で自動 cleanup)
  • zsh/, wezterm/, nvim/, git/, lazygit/, czg/, cz-git/, starship/ の構成を変えた

Bootstrap (new machine)

./bootstrap.sh

Then run:

gh auth login
gh auth refresh -s project
git config --global ghq.root "$HOME/src"
mkdir -p "$HOME/.config/zsh" "$HOME/.config/wezterm" "$HOME/.config/codex/skills" "$HOME/.claude/skills"
./init.sh

既にあるマシンへ 追加分だけ 取り込むときは --no-upgrade を付ける。 付けないと brew bundle は古い formula をまとめて upgrade する。

git pull && brew bundle --file=./Brewfile --no-upgrade

./bootstrap.sh also installs Miniforge3 into ~/miniforge3 when missing. ./init.sh links zsh/env.zsh, which loads conda shell support without auto-activating base.

Manual bootstrap (no script)

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
echo "" >> "$HOME/.zprofile"
echo 'eval "$(/opt/homebrew/bin/brew shellenv zsh)"' >> "$HOME/.zprofile"
eval "$(/opt/homebrew/bin/brew shellenv zsh)"
# 公式以外の tap は Homebrew 7 から明示的な信頼が要る(~/.homebrew/trust.json, マシンごと)
brew trust olets/tap
# パッケージの一覧は Brewfile が正本(個別の brew install をここに増やさない)
brew bundle --file=./Brewfile
npm install -g git-cz czg cz-git
npx -y czg --api-key="sk-XXXX"

Clone this repo with ghq, then install:

gh auth login
gh auth refresh -s project
git config --global ghq.root "$HOME/src"
mkdir -p "$HOME/.config/zsh" "$HOME/.config/wezterm" "$HOME/.config/codex/skills" "$HOME/.claude/skills"
ghq get https://github.com/38kta-lab/dotfile
cd "$(ghq root)/github.com/38kta-lab/dotfile"
./install_miniforge.sh
./init.sh

gh auth refresh -s project is required on each machine where Codex or gh updates GitHub Projects, such as the Life project Status field.

Codex / Antigravity (Gemini) CLI

# Codex CLI
npm install -g @openai/codex
mkdir -p ~/.config/codex
mv ~/.codex/* ~/.config/codex/
codex sign-in

Antigravity CLI (agy) — Gemini CLI の後継

Google は 2026-06-18 に個人 Google アカウント向けの Gemini CLI ログインを サーバ側で打ち切った(This client is no longer supported for Gemini Code Assist for individuals エラー)。後継の Antigravity CLI (agy) に移行する。

# 旧 gemini CLI が残っていれば削除
npm uninstall -g @google/gemini-cli 2>/dev/null; rm -rf ~/.gemini

# Antigravity CLI をインストール (Go 製 single binary、~/.local/bin/agy)
curl -fsSL https://antigravity.google/cli/install.sh | bash

# 初回起動でブラウザ認証 (要 Google アカウント。Pro 系モデルはサブスク必要)
agy
  • ~/.local/bin は zsh/env.zsh で既に PATH 追加済み → 追加設定不要。
  • 使い方: 対話 agy / 非対話 agy -p "プロンプト" / モデル指定 agy --model <id> -p ... / 一覧 agy models / 継続 agy -c。
  • 認証は初回ブラウザ OAuth のみ、以降は OS keyring から自動サインイン。

Miniforge / Conda

Miniforge3 is installed under:

~/miniforge3

Install or verify it:

./install_miniforge.sh

Use a pinned Miniforge release when needed:

MINIFORGE_VERSION=25.11.0-0 ./install_miniforge.sh

The installer supports Apple Silicon and Intel macOS by selecting the matching installer from the official conda-forge/miniforge GitHub releases:

https://github.com/conda-forge/miniforge/releases

base should not auto-activate:

conda config --set auto_activate_base false

For per-repo environments, prefer environment.yml in that repo:

conda env create -f environment.yml
conda activate <env-name>

If an environment already exists:

conda env update -f environment.yml --prune

Google Calendar Credentials

For Codex-assisted Calendar reads in the life repo, place the OAuth desktop client JSON at:

~/.config/life/google-calendar-credentials.json

Copy this file between personal Macs using a private secure channel. Do not commit it to git, and do not create a public/shared link.

On a new Mac:

mkdir -p "$HOME/.config/life"
mv "$HOME/Downloads/google-calendar-credentials.json" "$HOME/.config/life/google-calendar-credentials.json"
chmod 600 "$HOME/.config/life/google-calendar-credentials.json"

If the downloaded file has a client_secret_*.json name:

mkdir -p "$HOME/.config/life"
mv "$HOME/Downloads"/client_secret_*.json "$HOME/.config/life/google-calendar-credentials.json"
chmod 600 "$HOME/.config/life/google-calendar-credentials.json"

Do not copy this token between Macs:

~/.config/life/google-calendar-read-token.json

Generate that token separately on each Mac by running the Calendar reader from the life repo after activating its conda environment:

conda activate life
python scripts/google_calendar_read.py --format json

Skills (Codex / Claude Code)

Global user Skills are managed in this repo under:

skills/

./init.sh links each directory under skills/ into both:

~/.config/codex/skills/
~/.claude/skills/

System Skills under ~/.config/codex/skills/.system/ are not managed here. Claude Code's auto memory under ~/.claude/projects/.../memory/ is also not managed here.

PR Workflow (squash)

Use PRs with squash merge to keep main clean and reduce cross-machine conflicts. Rule of thumb: update main, but do not work directly on it.

Branch naming (one branch per machine):

  • work/<hostname> (example: work/kta38-mini-lab)

Get <hostname> with:

hostname -s

Initial setup (first time on a machine):

HOST="$(hostname -s)"
git switch main
git pull --rebase
git switch -c "work/$HOST"
git push -u origin "work/$HOST"

Flow (manual):

# start work (every time)
git switch main
git pull --rebase
git switch work/<hostname>
git rebase main

# work + commit
git add -A
git commit -m "feat: ..."
git push -u origin work/<hostname>

Create a PR from work/<hostname> to main:

gh pr create --base main --head work/<hostname> --fill

Then Squash and merge it on GitHub, or with gh:

gh pr merge <PR_NUMBER> --squash

Merge commit (no squash):

gh pr merge <PR_NUMBER> --merge

Aliases (see zsh/alias.zsh):

winit   # initial setup: create/push work/<hostname> branch
wmain   # update main only (before switching)
wstart  # start work: update main -> switch work/<hostname> -> rebase
wrebase # rebase current work branch onto main
prc     # gh pr create --base main --head work/<hostname> --fill
prs     # gh pr merge --squash
prm     # gh pr merge --merge

Then on other machines:

git switch main
git pull --rebase

Notes:

  • Keep work/<hostname> rebased onto main to avoid long-lived divergence.
  • Squash keeps history clean; use merge commits only when you need full commit history preserved.
  • Avoid pushing directly to main.

Notes

  • WezTerm keybinds are managed at wezterm/keybinds.lua and linked to ~/.config/wezterm/keybinds.lua.
  • Global Skills are managed under skills/ and linked to both ~/.config/codex/skills/ and ~/.claude/skills/.
  • ~/.config/.czrc is not committed; see czrc/.czrc.example for a template.

Mac Setup Checklist

Keyboard

  • Input source: 日本語 - ローマ字入力
  • Input mode: 英字
  • Caps Lock: オフの時「英字」を入力

Trackpad

  • Tracking speed: Max
  • Tap to click: オン

Pointer

  • Size: 1つ大きくする
  • Fill: #D05654
  • Outline: #464758

iCloud

  • Desktop and Documents sync: オン

Desktop

  • スタックを使用
  • 表示オプションを表示
  • テキストサイズ: 10
  • 並べ替え: 種類
  • 表示順序: 名前
  • アイコン: 36x36
  • グリッド間隔: 下から4番目

Dock

  • Position: 左
  • Automatically show/hide: オン
  • Size/zoom: いい感じに

Default browser

  • Chrome

Mac app

  • Zoom: Download is here
  • Microsoft: Word, Excel, Powerpoint
  • Magnet: Download is here
  • Gmail, Google calender
  • Google drive for mac: Download is here
  • ChimeraX: Download is here
Source 6 files
hooks/register.tsx 2328 lines
1import type { Register } from 'claude-code'
2
3import { consultText, parseHub, sectionMarkdown, sortHubs, TABS } from './hubs'
4import type { Hub } from './hubs'
5import { bytesToBase64, entryLines, frontValue, imageRows, isBase64, pngList, tocRows } from './notes'
6import type { TocRow } from './notes'
7import { latestTrendFile, parseTrend, starText, topItems } from './trend'
8import type { Trend, TrendItem } from './trend'
9import { bodyArgv, readArgv, calendarArgv, calendarTitle, detailPrompt, doneArgv, mailLine, parseBody, parseSlack, slackConversations, slackSelectedIds, slackDetailPrompt, parseSlackMcp, slackDoneArgv, parseChannels, nextWatch, setWatchArgv, channelsArgv, WATCH_LABEL, parseFeed, parseWhen, shortDate, splitMail } from './alert'
10import type { MailBody, MailFeed, MailItem } from './alert'
11import { fileOf, label, nextNumber, numbered, parsePeer, parseRows, peerOf, readBefore, replyPrompt, rowsText, splitAnswer, threadOrder, unread, wrapCells } from './threads'
12import type { ThreadRow } from './threads'
13
14// Each session started with LIFE_ROLE writes one record about itself to the
15// store every session on this machine shares. The ops session reads them all.
16// Sessions without a role (cron runs, ad-hoc sessions) write nothing.
17
18export type SessionRecord = {
19  name: string
20  role: string
21  pj?: string
22  busy: boolean
23  turnStartedAt?: number
24  lastTurnEndAt?: number
25  contextPercent?: number
26  costUsd?: number
27  lastReportAt?: number
28  // A question waiting for the person (a guard's dialog, the model's
29  // AskUserQuestion): its first words and since when. Cleared when answered.
30  waiting?: string
31  waitingSince?: number
32  updatedAt: number
33}
34
35export type Dispatch = { at: number; line: string }
36export type Limits = { at: number; windows: { kind: string; percentUsed: number; resetsAt?: string }[] }
37
38const PREFIX = 'ops-dash:session:'
39const DISPATCH = 'ops-dash:dispatch:'
40const LIMITS = 'ops-dash:limits'
41const PANE = 'peers'
42// `/peers` is the built-in alias of /list-agents, so the command is /dash.
43const COMMAND = 'dash'
44// Every pane opens at one width, so switching tabs does not move the edge (user 10/13).
45const PANE_COLUMNS = 84
46
47type Me = { name: string; role: string; pj?: string }
48
49async function whoAmI($: any): Promise<Me | undefined> {
50  const role = await $.env.get('LIFE_ROLE')
51  if (!role) return undefined
52  const pj = await $.env.get('LIFE_PJ')
53  const name = (await $.env.get('LIFE_NAME')) ?? (role === 'ops' ? 'ops' : pj ? `pj-${pj}` : role)
54  return { name, role, pj: pj || undefined }
55}
56
57// Recording status must never break the session: a failed write is dropped.
58async function write($: any, me: Me, change: Partial<SessionRecord>): Promise<void> {
59  try {
60    await writeOnce($, me, change)
61  } catch {
62    // the next event writes again
63  }
64}
65
66async function writeOnce($: any, me: Me, change: Partial<SessionRecord>): Promise<void> {
67  const key = PREFIX + me.name
68  const old = ((await $.store.get(key)) as SessionRecord | undefined) ?? { name: me.name, role: me.role, busy: false, updatedAt: 0 }
69  const now = await $.clock.now()
70  await $.store.set(key, { ...old, name: me.name, role: me.role, pj: me.pj, ...change, updatedAt: now })
71}
72
73export function hhmm(ms?: number): string {
74  if (!ms) return '—'
75  const d = new Date(ms)
76  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
77}
78
79// "47分前" / "2時間05分前"
80export function ago(now: number, ms?: number): string {
81  if (!ms) return ''
82  const m = Math.max(0, Math.round((now - ms) / 60000))
83  return m < 60 ? `${m}分前` : `${Math.floor(m / 60)}時間${String(m % 60).padStart(2, '0')}分前`
84}
85
86export function elapsed(now: number, ms?: number): string {
87  if (!ms) return ''
88  const m = Math.max(0, Math.round((now - ms) / 60000))
89  return m < 60 ? `${m}分` : `${Math.floor(m / 60)}時間${m % 60}分`
90}
91
92// Terminal cells a string takes: CJK and full-width forms take two.
93export function cells(text: string): number {
94  let n = 0
95  for (const ch of text) n += /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/.test(ch) ? 2 : 1
96  return n
97}
98
99export function pad(text: string, width: number): string {
100  return text + ' '.repeat(Math.max(0, width - cells(text)))
101}
102
103export function bar(percent: number, width = 16): string {
104  const filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
105  return '█'.repeat(filled) + '░'.repeat(width - filled)
106}
107
108export function tone(percent: number): string {
109  return percent >= 80 ? 'red' : percent >= 50 ? 'yellow' : 'green'
110}
111
112// "16:10 リセット" today, "明日 09:00 リセット" tomorrow, else "10/14 09:00 リセット".
113export function resetLabel(now: number, iso?: string): string {
114  if (!iso) return ''
115  const t = Date.parse(iso)
116  if (Number.isNaN(t)) return ''
117  const a = new Date(now), b = new Date(t)
118  const day = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
119  const diff = Math.round((day(b) - day(a)) / 86400000)
120  const when = diff === 0 ? hhmm(t) : diff === 1 ? `明日 ${hhmm(t)}` : `${b.getMonth() + 1}/${b.getDate()} ${hhmm(t)}`
121  return `${when} リセット`
122}
123
124const WINDOW_LABEL: Record<string, string> = { five_hour: '5時間枠', seven_day: '週間枠' }
125
126export type LimitRow = { label: string; percent: number; reset: string }
127export function limitRows(l: Limits | undefined, now: number): LimitRow[] {
128  return (l?.windows ?? []).map(w => ({ label: WINDOW_LABEL[w.kind] ?? w.kind, percent: w.percentUsed, reset: resetLabel(now, w.resetsAt) }))
129}
130
131export type Card = {
132  name: string
133  pj?: string
134  busy: boolean
135  state: string
136  context?: number
137  meta: string
138}
139
140export function cardsOf(records: SessionRecord[], dispatches: Record<string, Dispatch>, now: number, width: number): Card[] {
141  const sorted = [...records].sort((a, b) => (a.role === 'ops' ? -1 : b.role === 'ops' ? 1 : a.name.localeCompare(b.name)))
142  return sorted.map(r => {
143    const parts: string[] = []
144    if (r.lastTurnEndAt) parts.push(`ターン ${hhmm(r.lastTurnEndAt)}(${ago(now, r.lastTurnEndAt)})`)
145    if (r.role !== 'ops' && r.lastReportAt) parts.push(`報告 ${hhmm(r.lastReportAt)}`)
146    const d = dispatches[r.name]
147    if (d) parts.push(`依頼 ${hhmm(d.at)} ${d.line}`)
148    let meta = parts.length ? parts.join(' · ') : 'まだターンなし'
149    const room = width - 3
150    if (cells(meta) > room) {
151      let cut = ''
152      for (const ch of meta) {
153        if (cells(cut + ch) > room - 1) break
154        cut += ch
155      }
156      meta = cut + '…'
157    }
158    return {
159      name: r.name,
160      pj: r.pj,
161      busy: r.busy,
162      state: r.busy ? `作業中 ${elapsed(now, r.turnStartedAt)}` : '待機',
163      context: r.contextPercent,
164      meta,
165    }
166  })
167}
168
169
170// ---- calendar: one week, fixed height ----------------------------------
171
172export type CalEvent = {
173  title: string
174  start: string
175  end: string
176  calendarId: string
177  location?: string
178  description?: string
179  meetingUrl?: string
180  htmlLink?: string
181}
182
183export const HOUR_FIRST = 8
184export const HOUR_LAST = 20 // the last row is 20:00–21:00
185const WEEKDAY = ['日', '月', '火', '水', '木', '金', '土']
186
187export function isAllDay(ev: CalEvent): boolean {
188  return !ev.start.includes('T')
189}
190
191// "[22_R] note と hub の整理 [status:focus]" → "22_R"; untagged → the title's start.
192// A meeting names the person, not the project: "[21_Q][22_R] 【MTG】山田さん 打ち合わせ"
193// → "山田さん 打ち合わせ" (a tag alone read as the meeting before it, 10/12).
194export function shortTitle(title: string): string {
195  const mtg = title.match(/【MTG】\s*(.+)$/)
196  if (mtg) {
197    const name = mtg[1].replace(/\[[^\]]*\]/g, '').replace(/【[^】]*】/g, '').trim()
198    if (name) return name
199  }
200  const tag = title.match(/^\[([^\]]+)\]/)
201  if (tag && !tag[1].startsWith('status:')) return tag[1]
202  return title.replace(/\[status:[^\]]+\]/g, '').replace(/【[^】]*】/g, '').trim()
203}
204
205export function eventColor(ev: CalEvent): string {
206  const t = ev.title
207  if (/\[status:focus\]/.test(t)) return 'green'
208  if (/\[status:meeting\]/.test(t) || /【MTG】/.test(t)) return 'blue'
209  if (/\[status:experiment\]/.test(t)) return 'magenta'
210  if (/\[status:break\]/.test(t)) return 'gray'
211  if (!ev.calendarId.startsWith('c_')) return 'blue'
212  return 'cyan'
213}
214
215function dayStart(ms: number): number {
216  const d = new Date(ms)
217  return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
218}
219
220// all-day events: "2026-10-14" … end exclusive
221function allDayCovers(ev: CalEvent, day: number): boolean {
222  const [ys, ms, ds] = ev.start.slice(0, 10).split('-').map(Number)
223  const [ye, me, de] = ev.end.slice(0, 10).split('-').map(Number)
224  const s = new Date(ys, ms - 1, ds).getTime()
225  const e = new Date(ye, me - 1, de).getTime()
226  return day >= s && day < e
227}
228
229export type Cell = { text: string; color?: string }
230export type Week = { days: { label: string; isToday: boolean }[]; allDay: Cell[]; hours: { label: string; isNow: boolean; cells: Cell[] }[] }
231
232// The grid is always 1 header + 1 all-day row + 12 hour rows, whatever the events.
233export function weekGrid(events: CalEvent[], now: number, dayWidth: number): Week {
234  const today = dayStart(now)
235  const days = Array.from({ length: 7 }, (_, i) => {
236    const d = new Date(today + i * 86400000 + 3600000) // +1h guards DST-free JST anyway
237    const start = dayStart(d.getTime())
238    return { start, label: `${d.getDate()}${WEEKDAY[d.getDay()]}`, isToday: i === 0 }
239  })
240  const fit = (t: string) => {
241    let out = ''
242    for (const ch of t) {
243      if (cells(out + ch) > dayWidth - 1) break
244      out += ch
245    }
246    return pad(out, dayWidth - 1) + ' '
247  }
248  const blank = { text: ' '.repeat(dayWidth) }
249
250  const allDay = days.map(d => {
251    const ev = events.find(e => isAllDay(e) && allDayCovers(e, d.start))
252    if (!ev) return blank
253    const first = allDayCovers(ev, d.start - 86400000) && d.start !== today ? '' : shortTitle(ev.title)
254    return { text: fit(first), color: eventColor(ev) }
255  })
256
257  const nowHour = new Date(now).getHours()
258  const hours = []
259  for (let h = HOUR_FIRST; h <= HOUR_LAST; h++) {
260    const cellsRow = days.map(d => {
261      const from = d.start + h * 3600000
262      const to = from + 3600000
263      // An event that starts within this hour wins over one still running
264      // into it (13:00–14:30 then 14:30–17:30: the 14:00 row is the second,
265      // with its name); with none starting, the running one's band goes on.
266      const overlapping = events.filter(e => !isAllDay(e) && Date.parse(e.start) < to && Date.parse(e.end) > from)
267      const starting = overlapping.filter(e => Date.parse(e.start) >= from).sort((a, b) => Date.parse(a.start) - Date.parse(b.start))
268      const ev = starting[0] ?? overlapping[0]
269      if (!ev) return blank
270      const startsHere = Date.parse(ev.start) >= from || h === HOUR_FIRST
271      return { text: fit(startsHere ? shortTitle(ev.title) : ''), color: eventColor(ev) }
272    })
273    hours.push({ label: String(h).padStart(2, '0'), isNow: h === nowHour, cells: cellsRow })
274  }
275  return { days: days.map(d => ({ label: d.label, isToday: d.isToday })), allDay, hours }
276}
277
278// ---- tasks: ideas/task-review/tasks.md ---------------------------------
279// A line is "- ⬜ [PJ] what — @owner — MM/DD(deadline note)". Only lines
280// under a "## " heading count, so the file's own preamble is never a task.
281
282export type Task = {
283  done: boolean
284  tag: string
285  title: string // short: the first part up to its first "(" or ":"
286  full: string // the whole line after the tag, as written
287  owner: string
288  who: string // the owner part as written ("@user・@ops")
289  created?: string
290  note?: string // the parenthetical that ends the line
291  deadline?: { month: number; day: number }
292}
293export type TaskSection = { title: string; tasks: Task[] }
294
295// ---- the next events, and one event's detail ----------------------------
296
297// Timed events not yet over, soonest first; all-day events covering today
298// come first. At most `n`.
299export function upcoming(events: CalEvent[], now: number, n: number): CalEvent[] {
300  const today = dayStart(now)
301  const allDay = events.filter(e => isAllDay(e) && allDayCovers(e, today))
302  const timed = events
303    .filter(e => !isAllDay(e) && Date.parse(e.end) > now)
304    .sort((a, b) => Date.parse(a.start) - Date.parse(b.start))
305  return [...allDay, ...timed].slice(0, n)
306}
307
308// The next timed event that has not started yet (all-day ones are not "next").
309export function nextEvent(events: CalEvent[], now: number): CalEvent | undefined {
310  return events
311    .filter(e => !isAllDay(e) && Date.parse(e.start) > now)
312    .sort((a, b) => Date.parse(a.start) - Date.parse(b.start))[0]
313}
314
315// "あと 45分" / "あと 2時間5分" / "あと 1日3時間"
316export function untilLabel(ms: number): string {
317  const m = Math.max(0, Math.round(ms / 60000))
318  if (m < 60) return `あと ${m}分`
319  const h = Math.floor(m / 60)
320  if (h < 24) return `あと ${h}時間${m % 60 ? `${m % 60}分` : ''}`
321  return `あと ${Math.floor(h / 24)}日${h % 24 ? `${h % 24}時間` : ''}`
322}
323
324// The band above the prompt: counts and the time to the next event. Counts
325// only (no sender, no subject), so it says nothing more than a toast would.
326export function bandParts(gmail: number | undefined, slack: number | undefined, events: CalEvent[], now: number, titleWidth = 20): string[] {
327  const ev = nextEvent(events, now)
328  return [
329    `Gmail ${gmail ?? '–'}`,
330    `Slack ${slack ?? '–'}`,
331    ev ? `次 ${hhmm(Date.parse(ev.start))} ${clip(shortTitle(ev.title), titleWidth)} ${untilLabel(Date.parse(ev.start) - now)}` : '次の予定なし',
332  ]
333}
334
335// "今日 14:30–16:30" / "明日 10:00–12:00" / "10/14(水) 終日"
336export function whenLabel(ev: CalEvent, now: number): string {
337  const today = dayStart(now)
338  const dayOf = (iso: string) => (isAllDay({ ...ev, start: iso }) ? (() => { const [y, m, d] = iso.slice(0, 10).split('-').map(Number); return new Date(y, m - 1, d).getTime() })() : dayStart(Date.parse(iso)))
339  const start = dayOf(ev.start)
340  const diff = Math.round((start - today) / 86400000)
341  const d = new Date(start)
342  const day = diff === 0 ? '今日' : diff === 1 ? '明日' : `${d.getMonth() + 1}/${d.getDate()}(${WEEKDAY[d.getDay()]})`
343  if (isAllDay(ev)) return `${day} 終日`
344  return `${day} ${hhmm(Date.parse(ev.start))}–${hhmm(Date.parse(ev.end))}`
345}
346
347// The hub an event belongs to, by the "[PJ]" tag at the start of its title.
348// A hub's code is "22_R" in "22_R_sample-genome", "Z90" in "Z90-slides"; a tag
349// naming two ("21_Q/22_R") goes to the first.
350export function hubOfTag(tag: string, slugs: readonly string[]): string | undefined {
351  const first = tag.split('/')[0].trim()
352  if (!first || first.startsWith('status:')) return undefined
353  return slugs.find(s => s.match(/^(\d{2}_[A-Z]|[A-Z]\d{2})/)?.[1] === first)
354}
355
356export function hubOfEvent(ev: CalEvent, slugs: readonly string[]): string | undefined {
357  const tag = ev.title.match(/^\[([^\]]+)\]/)?.[1]
358  return tag ? hubOfTag(tag, slugs) : undefined
359}
360
361// "学会 A の参加登録(ポスターのみ)" → "学会 A の参加登録". Only at "(": a colon
362// often leaves just a label ("解析 8"). A cut leaving under 4 characters keeps the whole.
363export function shortTaskTitle(title: string): string {
364  const m = title.match(/^(.+?)(/)
365  return m && cells(m[1].trim()) >= 4 ? m[1].trim() : title
366}
367
368function plain(text: string): string {
369  return text.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1').trim()
370}
371
372export function parseTask(done: boolean, body: string): Task {
373  let rest = plain(body)
374  let tag = ''
375  const t = rest.match(/^\[([^\]]+)\]\s*/)
376  if (t) {
377    tag = t[1]
378    rest = rest.slice(t[0].length)
379  }
380  // the deadline note is the parenthetical that ends the line, after the parts
381  let deadline: Task['deadline']
382  const tail = rest.match(/(([^()]*))$/)
383  // " — " separates the parts; tasks.md also writes ")— " with no space before it
384  const parts = rest.split(/\s?— /)
385  const full = parts[0].trim()
386  let owner = ''
387  let ownerText = ''
388  let created: string | undefined
389  for (const part of parts.slice(1)) {
390    const c = part.trim().match(/^(\d{1,2}\/\d{1,2})/)
391    if (c && created === undefined) created = c[1]
392    const at = part.match(/@([A-Za-z0-9_\-・@]+)/)
393    if (at) {
394      ownerText = part.trim()
395      const names = part.match(/@[A-Za-z0-9_\-]+/g) ?? []
396      const others = names.map(n => n.slice(1)).filter(n => n !== 'user')
397      owner = others.map(n => n.replace(/^claude-/, '')).join('・')
398      if (/未依頼/.test(part)) owner += owner ? ' 未依頼' : ''
399    }
400  }
401  if (tail && parts.length > 1) {
402    const d = tail[1].match(/(\d{1,2})\/(\d{1,2})/)
403    if (d) deadline = { month: Number(d[1]), day: Number(d[2]) }
404  }
405  return { done, tag, title: shortTaskTitle(full), full, owner, who: ownerText, created, note: tail && parts.length > 1 ? tail[1] : undefined, deadline }
406}
407
408export function parseTasks(md: string): TaskSection[] {
409  const out: TaskSection[] = []
410  for (const raw of md.split('\n')) {
411    const h = raw.match(/^## (.+)$/)
412    if (h) {
413      out.push({ title: h[1].trim(), tasks: [] })
414      continue
415    }
416    const t = raw.match(/^- (⬜|✅) (.+)$/)
417    if (t && out.length > 0) out[out.length - 1].tasks.push(parseTask(t[1] === '✅', t[2]))
418  }
419  return out
420}
421
422// days from today to the deadline (this year, or next year if it is long past)
423export function daysLeft(now: number, d: { month: number; day: number }): number {
424  const today = new Date(dayStart(now))
425  let target = new Date(today.getFullYear(), d.month - 1, d.day)
426  if (target.getTime() < today.getTime() - 180 * 86400000) target = new Date(today.getFullYear() + 1, d.month - 1, d.day)
427  return Math.round((target.getTime() - today.getTime()) / 86400000)
428}
429
430export function tagColor(tag: string): string {
431  if (/^\d\d_[A-Z]/.test(tag)) return 'cyan'
432  if (/^[A-Z]\d\d/.test(tag)) return 'magenta'
433  return 'gray'
434}
435
436export function shortTag(tag: string, width: number): string {
437  const first = tag.split('/')[0]
438  const t = tag.includes('/') ? `${first}+` : first
439  return pad(cells(t) > width ? clip(t, width) : t, width)
440}
441
442export function clip(text: string, width: number): string {
443  if (cells(text) <= width) return text
444  let out = ''
445  for (const ch of text) {
446    if (cells(out + ch) > width - 1) break
447    out += ch
448  }
449  return out + '…'
450}
451
452async function readAll($: any): Promise<{ records: SessionRecord[]; dispatches: Record<string, Dispatch>; limits?: Limits }> {
453  const keys: string[] = await $.store.keys()
454  const records: SessionRecord[] = []
455  const dispatches: Record<string, Dispatch> = {}
456  for (const k of keys) {
457    if (k.startsWith(PREFIX)) records.push((await $.store.get(k)) as SessionRecord)
458    else if (k.startsWith(DISPATCH)) dispatches[k.slice(DISPATCH.length)] = (await $.store.get(k)) as Dispatch
459  }
460  return { records, dispatches, limits: (await $.store.get(LIMITS)) as Limits | undefined }
461}
462
463// ---- alert pane: Gmail (and later Slack), headers only, every 5 minutes ----
464
465const ALERT = 'alert'
466const MAIL_ROWS = 12
467export const MAIL_DAYS = 21
468const MAIL_ERR = /できなかった|取れなかった|渡しません|日時は|ありません/
469const NOTE_MS = 15000
470// What the pane says after an action: a failure stays until the next action;
471// "Done にした" and the like go after 15 s (user 10/12: it stayed on for good).
472// The time a note first shows is taken from the mod's clock at render (Date.now
473// in a mod is not the wall clock, 10/13), keyed by the note's set count.
474const noteFirstShown = new Map<string, { seq: number; at: number }>()
475export function noteShown(key: string, note: string, seq: number, now: number, err: RegExp): string {
476  if (!note) return ''
477  const seen = noteFirstShown.get(key)
478  if (!seen || seen.seq !== seq) {
479    noteFirstShown.set(key, { seq, at: now })
480    return note
481  }
482  return err.test(note) || now - seen.at < NOTE_MS ? note : ''
483}
484let mailFeed: MailFeed | undefined
485let mailNote = ''
486let mailNoteSeq = 0 // bumped each time mailNote is set
487let mailSeen: Set<string> | undefined
488const mailDone = new Set<string>()
489let mailSel = new Set<string>()
490let mailBulkOpen = false
491let mailPage = 0
492let mailMode: { kind: 'list' } | { kind: 'ask' } | { kind: 'cal-title'; item: MailItem } | { kind: 'cal-when'; item: MailItem; title: string } = { kind: 'list' }
493let mailBusy = false
494// One mail opened from the list: its body, fetched when opened, not kept.
495let mailView: { kind: 'list' } | { kind: 'body'; item: MailItem; body?: MailBody; full: boolean } = { kind: 'list' }
496const MAIL_BODY_LINES = 40
497
498async function mailOpen($: any, python: string, repo: string, item: MailItem): Promise<void> {
499  mailView = { kind: 'body', item, full: false }
500  $.ui.invalidate('ui.render')
501  try {
502    const r = await $.process.run(bodyArgv(python, repo, item.id), { cwd: repo, timeoutMs: 60000 })
503    const body = parseBody(String(r.stdout ?? ''), item.id)
504    if (mailView.kind === 'body' && mailView.item.id === item.id) mailView = { ...mailView, body }
505    // The body came, so it was seen: mark it read in Gmail (a failure only leaves it unread).
506    if (!body.error && item.unread) {
507      const m = await $.process.run(readArgv(python, repo, item.id), { cwd: repo, timeoutMs: 60000 })
508      if (m.exitCode === 0) item.unread = false
509    }
510  } catch (err) {
511    if (mailView.kind === 'body' && mailView.item.id === item.id) mailView = { ...mailView, body: { id: item.id, error: String(err).slice(0, 80) } }
512  }
513  $.ui.invalidate('ui.render')
514}
515
516// Headers only (scripts/gmail/alert_feed.py); nothing here reaches the model.
517// ---- Slack in the alert pane (scripts/slack/slack_feed.py, every 5 minutes) ----
518let slackFeed: ReturnType<typeof parseSlack> | undefined
519let slackNote = ''
520let slackNoteSeq = 0
521let slackBusy = false
522let slackSel = new Set<string>() // row keys
523// One message at a time (user 10/16: to answer each in its own thread), next to the whole conversation.
524let slackMsgSel = new Set<string>() // message ids
525let slackMode: 'list' | 'ask' = 'list'
526const slackDone = new Set<string>() // ids marked 済み this session (the script keeps them too)
527let slackPage = 0 // DMs
528let slackPageCh = 0 // channels
529const SLACK_CONVS = 4 // conversations per page, in each of the two parts (DM / channels)
530// The channel chooser (user 10/12): channels of every workspace, one mark each,
531// pressed to cycle 見る → メンションだけ → 件数だけ → 見ない. Names stay on the terminal.
532let chanView: { page: number; list?: import('./alert').SlackChannel[]; def: string; note: string } | undefined
533const CHAN_ROWS = 14
534
535async function chanLoad($: any, python: string, repo: string): Promise<void> {
536  try {
537    const r = await $.process.run(channelsArgv(python, repo), { cwd: repo, timeoutMs: 30000 })
538    const d = parseChannels(String(r.stdout ?? ''))
539    chanView = { page: chanView?.page ?? 0, list: d.channels, def: d.default, note: d.error ? `一覧を読めなかった(${d.error.slice(0, 60)})` : '' }
540  } catch (err) {
541    chanView = { page: 0, list: [], def: 'mention', note: `一覧を読めなかった(${String(err).slice(0, 60)})` }
542  }
543  $.ui.invalidate('ui.render')
544}
545
546async function chanSet($: any, python: string, repo: string, id: string, watch: string): Promise<void> {
547  try {
548    const r = await $.process.run(setWatchArgv(python, repo, id, watch), { cwd: repo, timeoutMs: 30000 })
549    if (r.exitCode === 0 && chanView?.list) {
550      chanView.list = chanView.list.map(c => (c.id === id ? { ...c, watch, effective: watch } : c))
551      chanView.note = ''
552    } else if (chanView) chanView.note = `書き換えられなかった(exit ${r.exitCode})`
553  } catch (err) {
554    if (chanView) chanView.note = `書き換えられなかった(${String(err).slice(0, 60)})`
555  }
556  $.ui.invalidate('ui.render')
557}
558const SLACK_MSGS = 3 // newest messages under each
559
560async function fetchSlack($: any, python: string, repo: string): Promise<void> {
561  if (!python || !repo || slackBusy) return
562  slackBusy = true
563  try {
564    const r = await $.process.run([python, `${repo}/scripts/slack/slack_feed.py`], { cwd: repo, timeoutMs: 240000 })
565    const feed = parseSlack(String(r.stdout ?? ''))
566    if (feed.error) { slackNoteSeq++; slackNote = `Slack を取れなかった(${feed.error.slice(0, 80)})`; return }
567    slackFeed = feed
568    // A fetch clears only its own earlier failure, not what an action said (済みにした …).
569    if (feed.errors.length) { slackNoteSeq++; slackNote = `取れなかった workspace・チャンネルあり: ${feed.errors.length}(${feed.errors[0].slice(0, 50)})` }
570    else if (/取れなかった/.test(slackNote)) { slackNoteSeq++; slackNote = '' }
571  } catch (err) {
572    slackNoteSeq++; slackNote = `Slack を取れなかった(${String(err).slice(0, 60)})`
573  } finally {
574    slackBusy = false
575    $.ui.invalidate('ui.render')
576  }
577}
578
579export function slackCount(): number | undefined {
580  if (!slackFeed) return undefined
581  return slackFeed.items.filter(x => !slackDone.has(x.id)).length
582}
583
584async function slackMarkDone($: any, python: string, repo: string, ids: string[]): Promise<void> {
585  if (ids.length === 0) return
586  try {
587    const r = await $.process.run(slackDoneArgv(python, repo, ids), { cwd: repo, timeoutMs: 30000 })
588    if (r.exitCode === 0) {
589      for (const id of ids) slackDone.add(id)
590      slackSel = new Set(); slackMsgSel = new Set()
591      slackNoteSeq++; slackNote = `済みにした: ${ids.length} 件(手元の記録だけ。Slack の未読はそのまま)`
592    } else {
593      slackNoteSeq++; slackNote = `済みにできなかった(exit ${r.exitCode})`
594    }
595  } catch (err) {
596    slackNoteSeq++; slackNote = `済みにできなかった(${String(err).slice(0, 60)})`
597  }
598  $.ui.invalidate('ui.render')
599}
600
601// workspace → Slack MCP server name, from pluginConfigs (machine-specific, not in this repo).
602let slackMcp: Record<string, string> = {}
603
604
605async function slackAsk($: any, ids: string[], ask: string): Promise<void> {
606  const text = slackDetailPrompt(slackFeed?.items ?? [], ids, ask, slackMcp)
607  if (!text) {
608    slackNoteSeq++; slackNote = '件数だけのチャンネルを含むので、モデルには渡しません'
609  } else {
610    const r = await $.prompt.fill({ text })
611    slackNoteSeq++; slackNote = r.isFilled ? 'プロンプトに下書きを入れた(直して送ると、選んだメッセージだけを読みます)' : `プロンプトに入れられなかった(${r.reason ?? '理由不明'})`
612    if (r.isFilled) { slackSel = new Set(); slackMsgSel = new Set() }
613  }
614  slackMode = 'list'
615  $.ui.invalidate('ui.render')
616}
617
618async function fetchMail($: any, python: string, repo: string): Promise<void> {
619  if (!python || !repo || mailBusy) return
620  mailBusy = true
621  try {
622    // Three weeks back, not three days: what is not Done yet stays on the list
623    // until it is (user 10/12; about 200 headers, cached after the first look).
624    const r = await $.process.run([python, `${repo}/scripts/gmail/alert_feed.py`, '--days', String(MAIL_DAYS), '--max', '500'], { cwd: repo, timeoutMs: 180000 })
625    const feed = parseFeed(String(r.stdout ?? ''))
626    if (feed.error) {
627      mailNoteSeq++; mailNote = `Gmail を取れなかった(${feed.error.slice(0, 80)})`
628      return
629    }
630    mailSeen = new Set(feed.items.map(x => x.id))
631    mailFeed = feed
632    for (const id of [...mailSel]) if (!mailSeen.has(id)) mailSel.delete(id)
633    for (const id of [...mailDone]) if (!mailSeen.has(id)) mailDone.delete(id)
634    // A fetch clears only its own earlier failure, not what an action said.
635    if (mailNote.startsWith('Gmail を取れなかった')) mailNote = ''
636  } catch (err) {
637    mailNoteSeq++; mailNote = `Gmail を取れなかった(${String(err).slice(0, 60)})`
638  } finally {
639    mailBusy = false
640    $.ui.invalidate('ui.render')
641  }
642}
643
644function mailSelected(): MailItem[] {
645  return (mailFeed?.items ?? []).filter(x => mailSel.has(x.id))
646}
647
648async function mailMarkDone($: any, python: string, repo: string): Promise<void> {
649  const items = mailSelected()
650  if (items.length === 0) return
651  mailNoteSeq++; mailNote = `Done のラベルを付けています(${items.length} 件)…`
652  $.ui.invalidate('ui.render')
653  try {
654    const r = await $.process.run(doneArgv(python, repo, items.map(x => x.id)), { cwd: repo, timeoutMs: 60000 })
655    if (r.exitCode === 0) {
656      for (const x of items) mailDone.add(x.id)
657      mailSel = new Set()
658      mailNoteSeq++; mailNote = `Done にした: ${items.length} 件`
659    } else {
660      mailNoteSeq++; mailNote = `Done にできなかった(exit ${r.exitCode}: ${String(r.stderr ?? '').trim().slice(-80)})`
661    }
662  } catch (err) {
663    mailNoteSeq++; mailNote = `Done にできなかった(${String(err).slice(0, 60)})`
664  }
665  $.ui.invalidate('ui.render')
666}
667
668async function mailAsk($: any, ask: string): Promise<void> {
669  const text = detailPrompt(mailSelected(), ask)
670  if (!text) {
671    mailNoteSeq++; mailNote = '人事などの区分を含むので、モデルには渡しません'
672  } else {
673    const r = await $.prompt.fill({ text })
674    mailNoteSeq++; mailNote = r.isFilled ? 'プロンプトに下書きを入れた(直して送ると、選んだメールだけを読みます)' : `プロンプトに入れられなかった(${r.reason ?? '理由不明'})`
675    if (r.isFilled) mailSel = new Set()
676  }
677  mailMode = { kind: 'list' }
678  $.ui.invalidate('ui.render')
679}
680
681async function mailCalendar($: any, python: string, repo: string, title: string, whenText: string): Promise<void> {
682  const when = parseWhen(whenText)
683  if ('error' in when) {
684    mailNoteSeq++; mailNote = when.error
685    $.ui.invalidate('ui.render')
686    return
687  }
688  mailNoteSeq++; mailNote = 'カレンダーに入れています…'
689  mailMode = { kind: 'list' }
690  $.ui.invalidate('ui.render')
691  try {
692    const r = await $.process.run(calendarArgv(python, repo, title, when), { cwd: repo, timeoutMs: 60000 })
693    mailNoteSeq++; mailNote = r.exitCode === 0 ? `カレンダーに入れた: ${when.start.replace('T', ' ').slice(0, 16)}  ${title}` : `カレンダーに入れられなかった(exit ${r.exitCode})`
694    if (r.exitCode === 0) {
695      mailSel = new Set()
696      await fetchCalendar($, python, repo)
697    }
698  } catch (err) {
699    mailNoteSeq++; mailNote = `カレンダーに入れられなかった(${String(err).slice(0, 60)})`
700  }
701  $.ui.invalidate('ui.render')
702}
703
704// The ops session's calendar, fetched every 10 minutes.
705let calendar: CalEvent[] = []
706let calendarNote = ''
707
708async function fetchCalendar($: any, python: string, repo: string): Promise<void> {
709  if (!python || !repo) {
710    calendarNote = 'カレンダー未設定(pluginConfigs の python / life_repo)'
711    return
712  }
713  const now = await $.clock.now()
714  const d0 = new Date(dayStart(now))
715  const d7 = new Date(dayStart(now) + 7 * 86400000 + 3600000)
716  const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
717  try {
718    const r = await $.process.run(
719      [python, `${repo}/scripts/google_calendar_read.py`, '--start', iso(d0), '--end', iso(d7), '--format', 'json', '--details', '--max-results', '200'],
720      { cwd: repo, timeoutMs: 60000 },
721    )
722    if (r.exitCode !== 0) {
723      calendarNote = `カレンダー取得に失敗(exit ${r.exitCode})`
724      return
725    }
726    const list = JSON.parse(r.stdout) as {
727      title: string; start: string; end: string; calendar_id: string
728      location?: string; description?: string; meeting_url?: string; html_link?: string
729    }[]
730    calendar = list.map(e => ({
731      title: e.title, start: e.start, end: e.end, calendarId: e.calendar_id,
732      location: e.location || undefined, description: e.description || undefined,
733      meetingUrl: e.meeting_url || undefined, htmlLink: e.html_link || undefined,
734    }))
735    calendarNote = `更新 ${hhmm(now)}`
736  } catch (err) {
737    calendarNote = `カレンダー取得に失敗(${String(err).slice(0, 40)})`
738  }
739}
740
741// ---- hubs pane: read project hubs, a list then one hub by section ----------
742
743const HUBS = 'hubs'
744let hubs: Hub[] = []
745let hubsLoadedAt = 0
746let hubsNote = ''
747let view: { kind: 'list' } | { kind: 'hub'; slug: string; tab: number } = { kind: 'list' }
748let back: { slug: string; tab: number }[] = []
749let consultNote = ''
750
751// One event's detail, drawn in place of the dash (b goes back). Not a pane of
752// its own: a pane opened from a press in another pane never gets the keys.
753let detail: CalEvent | undefined
754let taskDetail: { task: Task; section: string } | undefined
755
756// The daily trend under the calendar: the newest ideas/daily/md/*-trend.md,
757// read again every 10 minutes. A fixed 5 rows on the dash; `t` lists all.
758const TREND_ROWS = 5
759let trend: Trend | undefined
760let trendNote = ''
761let trendLoadedAt = 0
762let trendItem: TrendItem | undefined
763let trendList: { minStars: number } | undefined
764let trendFiles: string[] = [] // every *-trend.md, newest first
765let trendPast = false // the list of days is open
766let trendShown: Trend | undefined // a past day chosen from that list
767let queued = new Set<string>() // URLs already in the reading queue
768let queueNote = ''
769
770// The reading list: ideas/to-read.md in the life repo, one paper a line.
771// A URL already there is not added again.
772export function toReadLine(it: TrendItem, day: string, today: string): string {
773  const clean = (t: string) => t.replace(/\s+/g, ' ').replace(/[\[\]]/g, '').trim()
774  return `- ⬜ ${today} ${'★'.repeat(it.stars) || '☆'} [${clean(it.ja || it.title)}](${it.url}) — ${clean(it.title)}(${it.source}・trend ${day})`
775}
776
777export function toReadUrls(md: string): Set<string> {
778  return new Set([...md.matchAll(/\]\((https?:\/\/[^)\s]+)\)/g)].map(m => m[1]))
779}
780
781const TO_READ_HEAD = '# 読みたい\n\ndash の trend から「読みたい」で足した論文・記事(ops-dash が末尾に追記)。読んだら ✅、やめたら行を消す。\n\n'
782
783async function refreshQueued($: any, repo: string): Promise<void> {
784  if (!repo) return
785  try {
786    queued = toReadUrls(String(await $.fs.read(`${repo}/ideas/to-read.md`)))
787  } catch {
788    queued = new Set()
789  }
790}
791
792async function addToQueue($: any, repo: string, it: TrendItem, day: string): Promise<void> {
793  const path = `${repo}/ideas/to-read.md`
794  try {
795    let md = ''
796    try {
797      md = String(await $.fs.read(path))
798    } catch {
799      md = TO_READ_HEAD
800    }
801    if (toReadUrls(md).has(it.url)) {
802      queued.add(it.url)
803      queueNote = 'もう読みたいリストに入っています'
804    } else {
805      const now = new Date(await $.clock.now())
806      const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
807      await $.fs.write(path, md.replace(/\n*$/, '\n') + toReadLine(it, day, today) + '\n')
808      queued.add(it.url)
809      queueNote = '読みたいリスト(ideas/to-read.md)に入れました'
810    }
811  } catch (err) {
812    queueNote = `入れられませんでした(${String(err).slice(0, 50)})`
813  }
814  $.ui.invalidate('ui.render')
815}
816
817async function openPastTrend($: any, repo: string, file: string): Promise<void> {
818  try {
819    trendShown = parseTrend(String(await $.fs.read(`${repo}/ideas/daily/md/${file}`)))
820    trendPast = false
821    trendList = { minStars: 0 }
822  } catch (err) {
823    trendNote = `trend を読めない(${String(err).slice(0, 40)})`
824  }
825  $.ui.invalidate('ui.render')
826}
827
828async function loadTrend($: any, repo: string, now: number): Promise<void> {
829  if (!repo || now - trendLoadedAt < 600000) return
830  trendLoadedAt = now
831  try {
832    const dir = `${repo}/ideas/daily/md`
833    const names = ((await $.fs.list(dir)) as any[]).filter(f => f.kind === 'file').map(f => String(f.name))
834    trendFiles = names.filter(n => /^\d{4}-\d{2}-\d{2}-trend\.md$/.test(n)).sort().reverse()
835    const file = latestTrendFile(names)
836    if (!file) {
837      trend = undefined
838      trendNote = 'trend の md がまだ無い'
839      return
840    }
841    trend = parseTrend(String(await $.fs.read(`${dir}/${file}`)))
842    trendNote = ''
843  } catch (err) {
844    trendNote = `trend を読めない(${String(err).slice(0, 40)})`
845  }
846}
847let copied = ''
848const NEXT_EVENTS = 5
849
850async function loadHubs($: any, repo: string): Promise<void> {
851  if (!repo) {
852    hubsNote = 'hub の場所が未設定(pluginConfigs の life_repo)'
853    return
854  }
855  const dir = `${repo}/projects/active`
856  try {
857    const now = await $.clock.now()
858    const entries = await $.fs.list(dir)
859    const files = entries.filter((f: any) => f.kind === 'file' && f.name.endsWith('.md') && f.name !== 'README.md')
860    const out: Hub[] = []
861    for (const f of files) {
862      out.push(parseHub(f.name.replace(/\.md$/, ''), String(await $.fs.read(`${dir}/${f.name}`)), now))
863    }
864    hubs = sortHubs(out)
865    hubsLoadedAt = now
866    hubsNote = ''
867  } catch (err) {
868    hubsNote = `hub を読めない(${String(err).slice(0, 60)})`
869  }
870}
871
872function openHub(slug: string, tab = 0): void {
873  consultNote = ''
874  if (view.kind === 'hub') back.push({ slug: view.slug, tab: view.tab })
875  view = { kind: 'hub', slug, tab }
876}
877
878function goBack(): void {
879  const prev = back.pop()
880  view = prev ? { kind: 'hub', slug: prev.slug, tab: prev.tab } : { kind: 'list' }
881}
882
883function openTask($: any, task: Task, section: string): void {
884  taskDetail = { task, section }
885  detail = undefined
886  $.ui.invalidate('ui.render')
887}
888
889function closeTask($: any): void {
890  taskDetail = undefined
891  $.ui.invalidate('ui.render')
892}
893
894function openEvent($: any, ev: CalEvent): void {
895  taskDetail = undefined
896  detail = ev
897  copied = ''
898  $.ui.invalidate('ui.render')
899}
900
901function closeEvent($: any): void {
902  detail = undefined
903  copied = ''
904  $.ui.invalidate('ui.render')
905}
906
907async function copyText($: any, label: string, text: string, press: any): Promise<void> {
908  const r = await $.ui.copy({ text, surface: press?.surface })
909  copied = r.isCopied ? `${label}をコピーしました` : `コピーできませんでした(${r.reason ?? '理由不明'})`
910  $.ui.invalidate('ui.render')
911}
912
913async function goToHub($: any, slug: string): Promise<void> {
914  openHub(slug)
915  taskDetail = undefined
916  closeEvent($)
917  await $.ui.open({ id: HUBS, title: 'hubs', columns: PANE_COLUMNS, focus: true })
918}
919
920// ---- notes pane: a project's note → its contents → a number's pictures ----
921
922const NOTES = 'notes'
923type NotePj = { slug: string; title: string; code: string; data: string }
924let notePjs: NotePj[] = []
925let notesView:
926  | { kind: 'list' }
927  | { kind: 'toc'; pj: NotePj; rows: TocRow[] }
928  | { kind: 'pngs'; pj: NotePj; rows: TocRow[]; row: TocRow; files: string[]; deep?: boolean; body?: string[]; full?: boolean }
929  | { kind: 'image'; pj: NotePj; rows: TocRow[]; row: TocRow; files: string[]; file: string; src?: string; w?: number; h?: number; body?: string[] } = { kind: 'list' }
930const BODY_LINES = 20
931let notesNote = ''
932const THUMB = '/tmp/ops-dash-notes-view.png'
933const MAX_B64 = 2700000 // Image takes at most 2 MiB of picture
934
935// The list comes from the hubs alone (nas_code and nas_data): nothing is read
936// from the NAS until a project is chosen.
937async function notesLoad($: any, repo: string): Promise<void> {
938  if (hubs.length === 0) await loadHubs($, repo)
939  const out: NotePj[] = []
940  for (const h of hubs) {
941    const code = frontValue(h.text, 'nas_code')
942    const data = frontValue(h.text, 'nas_data')
943    if (code && data) out.push({ slug: h.slug, title: h.title, code, data })
944  }
945  notePjs = out
946}
947
948// Only the head of note.md, up to the end of its contents (a note can be
949// 10,000+ lines on a slow NAS): awk stops reading there.
950async function notesOpenToc($: any, pj: NotePj): Promise<void> {
951  notesView = { kind: 'toc', pj, rows: [] }
952  notesNote = `${pj.code}/note/note.md の目次を読んでいます…`
953  $.ui.invalidate('ui.render')
954  try {
955    const r = await $.process.run(['awk', '{ print } /<!-- TOC:END -->/ { exit }', `${pj.code}/note/note.md`], { timeoutMs: 20000 })
956    const rows = tocRows(String(r.stdout ?? ''))
957    notesView = { kind: 'toc', pj, rows }
958    notesNote = rows.length > 0 ? '' : r.exitCode === 0 ? 'この note には目次がありません(scripts/note_toc.py で作る)' : `note を読めない(exit ${r.exitCode})`
959  } catch (err) {
960    notesNote = `note を読めない(${String(err).slice(0, 60)})`
961  }
962  $.ui.invalidate('ui.render')
963}
964
965// First the quick look: <number>/out/*.png only, no walking
966// down the tree (the NAS is slow to walk). `deep` walks it, on request.
967// The entry itself, read alongside: awk prints from the number's heading to
968// the next "## " heading and stops there, not reading the rest of the note.
969async function notesReadEntry($: any, pj: NotePj, id: string): Promise<string[]> {
970  try {
971    const prog = '$0 ~ "^## " id " — " { p = 1 } p && /^## / && $0 !~ "^## " id " — " { exit } p { print }'
972    const r = await $.process.run(['awk', '-v', `id=${id}`, prog, `${pj.code}/note/note.md`], { timeoutMs: 20000 })
973    return entryLines(String(r.stdout ?? ''), id)
974  } catch {
975    return []
976  }
977}
978
979async function notesOpenPngs($: any, pj: NotePj, rows: TocRow[], row: TocRow, deep = false, body?: string[]): Promise<void> {
980  const dir = `${pj.data}/${row.id}`
981  notesView = { kind: 'pngs', pj, rows, row, files: [], deep, body }
982  const bodyRead = body ? Promise.resolve(body) : notesReadEntry($, pj, row.id)
983  notesNote = deep ? `${dir} の下の階層も探しています…` : `${dir}/out を見ています…`
984  $.ui.invalidate('ui.render')
985  try {
986    const argv = deep
987      ? ['find', dir, '-maxdepth', '6', '-type', 'f', '-iname', '*.png']
988      : ['/bin/sh', '-c', 'for f in "$1"/out/*.png "$1"/out/*.PNG; do [ -f "$f" ] && echo "$f"; done; exit 0', 'sh', dir]
989    const [r, lines] = await Promise.all([$.process.run(argv, { timeoutMs: deep ? 60000 : 15000 }), bodyRead])
990    const files = pngList(String(r.stdout ?? ''), dir)
991    notesView = { kind: 'pngs', pj, rows, row, files, deep, body: lines }
992    const where = deep ? '下の階層まで探して' : 'out/ に'
993    notesNote = files.length === 0 ? (r.exitCode === 0 ? `${where} png はありません` : `探せなかった(exit ${r.exitCode})`) : `${where} ${files.length} 件${files.length >= 200 ? '(先頭 200 件)' : ''}`
994  } catch (err) {
995    notesNote = `探せなかった(${String(err).slice(0, 60)})`
996  }
997  $.ui.invalidate('ui.render')
998}
999
1000async function notesOpenImage($: any, v: { pj: NotePj; rows: TocRow[]; row: TocRow; files: string[] }, file: string): Promise<void> {
1001  const path = `${v.pj.data}/${v.row.id}/${file}`
1002  notesView = { ...v, kind: 'image', file }
1003  notesNote = '読み込んでいます…'
1004  $.ui.invalidate('ui.render')
1005  try {
1006    const dims = await $.process.run(['sips', '-g', 'pixelWidth', '-g', 'pixelHeight', path], { timeoutMs: 20000 })
1007    const w = Number(String(dims.stdout).match(/pixelWidth:\s*(\d+)/)?.[1] ?? 0)
1008    const h = Number(String(dims.stdout).match(/pixelHeight:\s*(\d+)/)?.[1] ?? 0)
1009    let src = bytesToBase64(await $.fs.read(path, { as: 'bytes' }))
1010    if (src.length > MAX_B64) {
1011      await $.process.run(['sips', '-Z', '1600', path, '--out', THUMB], { timeoutMs: 30000 })
1012      src = bytesToBase64(await $.fs.read(THUMB, { as: 'bytes' }))
1013    }
1014    if (!isBase64(src) || src.length > MAX_B64) {
1015      notesNote = '画像を読めなかった(大きすぎるか、png でない)'
1016      notesView = { ...v, kind: 'image', file }
1017    } else {
1018      notesView = { ...v, kind: 'image', file, src, w, h }
1019      notesNote = w && h ? `${w} × ${h} px` : ''
1020    }
1021  } catch (err) {
1022    notesNote = `画像を読めなかった(${String(err).slice(0, 60)})`
1023  }
1024  $.ui.invalidate('ui.render')
1025}
1026
1027// ---- fig pane: a draft figure any session drops in a folder, and the palette ----
1028
1029// Any session puts a PNG in ~/.local/share/life/preview/ (figstyle.preview does
1030// it in one line); /fig shows the newest at once, the rest as a list, and the
1031// shared palette's sample always first.
1032const FIG = 'fig'
1033type FigEntry = { label: string; path: string }
1034let figList: FigEntry[] = []
1035let figView: { kind: 'list' } | { kind: 'image'; entry: FigEntry; src?: string; w?: number; h?: number } = { kind: 'list' }
1036let figNote = ''
1037const FIG_MAX = 15
1038
1039async function loadPicture($: any, path: string): Promise<{ src?: string; w?: number; h?: number; note: string }> {
1040  try {
1041    const dims = await $.process.run(['sips', '-g', 'pixelWidth', '-g', 'pixelHeight', path], { timeoutMs: 20000 })
1042    const w = Number(String(dims.stdout).match(/pixelWidth:\s*(\d+)/)?.[1] ?? 0)
1043    const h = Number(String(dims.stdout).match(/pixelHeight:\s*(\d+)/)?.[1] ?? 0)
1044    let src = bytesToBase64(await $.fs.read(path, { as: 'bytes' }))
1045    if (src.length > MAX_B64) {
1046      await $.process.run(['sips', '-Z', '1600', path, '--out', THUMB], { timeoutMs: 30000 })
1047      src = bytesToBase64(await $.fs.read(THUMB, { as: 'bytes' }))
1048    }
1049    if (!isBase64(src) || src.length > MAX_B64) return { note: '画像を読めなかった(大きすぎるか、png でない)' }
1050    return { src, w, h, note: w && h ? `${w} × ${h} px` : '' }
1051  } catch (err) {
1052    return { note: `画像を読めなかった(${String(err).slice(0, 60)})` }
1053  }
1054}
1055
1056async function figLoad($: any, repo: string): Promise<void> {
1057  const home = String((await $.env.get('HOME')) ?? '')
1058  const dir = `${home}/.local/share/life/preview`
1059  const out: FigEntry[] = []
1060  if (repo) out.push({ label: '共通 12 色の見本(figstyle.GLOBAL)', path: `${repo}/assets/figstyle/palette.png` })
1061  try {
1062    const r = await $.process.run(['/bin/sh', '-c', 'ls -t "$1"/*.png 2>/dev/null | head -n "$2"; exit 0', 'sh', dir, String(FIG_MAX)], { timeoutMs: 10000 })
1063    for (const line of String(r.stdout ?? '').split('\n').map((l: string) => l.trim()).filter(Boolean)) {
1064      out.push({ label: line.slice(dir.length + 1), path: line })
1065    }
1066    figNote = out.length > 1 ? '' : `仮の図はまだありません(${dir}/ に png を置く。figstyle.preview(fig, "名前"))`
1067  } catch (err) {
1068    figNote = `仮の図の場所を読めない(${String(err).slice(0, 60)})`
1069  }
1070  figList = out
1071}
1072
1073async function figOpen($: any, entry: FigEntry): Promise<void> {
1074  figView = { kind: 'image', entry }
1075  figNote = '読み込んでいます…'
1076  $.ui.invalidate('ui.render')
1077  const p = await loadPicture($, entry.path)
1078  figView = { kind: 'image', entry, src: p.src, w: p.w, h: p.h }
1079  figNote = p.note
1080  $.ui.invalidate('ui.render')
1081}
1082
1083function notesBack($: any): void {
1084  const v = notesView
1085  if (v.kind === 'image') notesView = { kind: 'pngs', pj: v.pj, rows: v.rows, row: v.row, files: v.files, deep: true, body: v.body }
1086  else if (v.kind === 'pngs') notesView = { kind: 'toc', pj: v.pj, rows: v.rows }
1087  else notesView = { kind: 'list' }
1088  notesNote = ''
1089  $.ui.invalidate('ui.render')
1090}
1091
1092export function hubLine(h: Hub, width: number): string {
1093  const age = h.daysSinceUpdate === undefined ? '—' : h.daysSinceUpdate === 0 ? '今日' : `${h.daysSinceUpdate}日前`
1094  const ms = h.next ? `★${h.next.date} ${h.next.daysLeft}日` : '—'
1095  const next = h.openNext > 0 ? `次${h.openNext}` : ''
1096  const head = `${pad(h.slug.split('_').slice(0, 2).join('_').replace(/-.*/, ''), 6)} ${pad(h.status, 8)} ${pad(age, 7)} ${pad(ms, 13)} ${pad(next, 4)} `
1097  return clip(head + h.title.replace(/\s*\([^)]*\)\s*$/, ''), width)
1098}
1099
1100// ---- threads: peers' replies to ops, by sender (threads.ts) ----------------
1101
1102const THREADS = 'threads'
1103
1104// LIFE_THREADS_DIR moves the files for a trial run; the real place is outside the repo.
1105async function threadsDir($: any): Promise<string> {
1106  const set = await $.env.get('LIFE_THREADS_DIR')
1107  if (set) return String(set)
1108  return `${String((await $.env.get('HOME')) ?? '')}/.local/share/life/threads`
1109}
1110
1111async function threadRows($: any, path: string): Promise<ThreadRow[]> {
1112  try {
1113    return parseRows(String(await $.fs.read(path)))
1114  } catch {
1115    return []
1116  }
1117}
1118
1119// One write at a time: two replies landing together must not take one number.
1120let threadWrites: Promise<unknown> = Promise.resolve()
1121function serially<T>(work: () => Promise<T>): Promise<T> {
1122  const run = threadWrites.then(work, work)
1123  threadWrites = run.catch(() => undefined)
1124  return run
1125}
1126
1127async function threadAppend($: any, name: string, row: Omit<ThreadRow, 'n'>, numberIt: boolean): Promise<number | undefined> {
1128  const path = fileOf(await threadsDir($), name)
1129  return serially(async () => {
1130    const rows = await threadRows($, path)
1131    const n = numberIt ? nextNumber(rows) : undefined
1132    await $.fs.write(path, rowsText([...rows, n === undefined ? row : { ...row, n }]))
1133    return n
1134  })
1135}
1136
1137// Replies read in the running turn, waiting for what ops says of them.
1138let threadPending: { name: string; n: number; seen?: boolean }[] = []
1139function blockText(content: unknown): string {
1140  if (typeof content === 'string') return content
1141  if (!Array.isArray(content)) return ''
1142  return content.map((b: any) => (typeof b?.text === 'string' ? b.text : typeof b?.content === 'string' ? b.content : '')).join('\n')
1143}
1144
1145// Who sits at which socket, as replies said: a send to a `uds:` address is filed under the name.
1146const threadSocks = new Map<string, string>()
1147
1148// The tab: every peer's file, read again only when it changed.
1149type ThreadFile = { name: string; rows: ThreadRow[] }
1150const threadCache = new Map<string, { stamp: string; rows: ThreadRow[] }>()
1151
1152async function loadThreads($: any): Promise<ThreadFile[]> {
1153  const dir = await threadsDir($)
1154  let entries: any[] = []
1155  try {
1156    entries = await $.fs.list(dir)
1157  } catch {
1158    return []
1159  }
1160  const out: ThreadFile[] = []
1161  for (const f of entries) {
1162    const name = String(f.name)
1163    if (f.kind !== 'file' || !name.endsWith('.jsonl')) continue
1164    const path = `${dir}/${name}`
1165    const stamp = `${f.mtimeMs}:${f.size}`
1166    let c = threadCache.get(path)
1167    if (!c || c.stamp !== stamp) {
1168      c = { stamp, rows: await threadRows($, path) }
1169      threadCache.set(path, c)
1170    }
1171    out.push({ name: name.replace(/\.jsonl$/, ''), rows: c.rows })
1172  }
1173  return out
1174}
1175
1176async function threadMarkRead($: any, name: string): Promise<void> {
1177  const path = fileOf(await threadsDir($), name)
1178  try {
1179    await serially(async () => {
1180      const rows = await threadRows($, path)
1181      if (unread(rows) === 0) return
1182      await $.fs.write(path, rowsText(rows.map(r => (r.dir === 'in' ? { ...r, read: true } : r))))
1183    })
1184    thrNote = ''
1185  } catch (err) {
1186    thrNote = `既読にできなかった(${String(err).slice(0, 60)})`
1187  }
1188  $.ui.invalidate('ui.render')
1189}
1190
1191// The reply goes to ops, not to the peer (user 10/19): ops reads it and tells the peer.
1192async function threadsReply($: any, name: string, row: ThreadRow | undefined, text: string): Promise<void> {
1193  if (!text.trim()) {
1194    thrNote = '空なので送りませんでした'
1195  } else {
1196    try {
1197      const r = await $.prompt.submit({ text: replyPrompt(name, row, text), asUser: true })
1198      if (r?.drop !== undefined) thrNote = `ops に送れなかった(${String(r.drop).slice(0, 60)})`
1199      else {
1200        thrNote = `ops に送りました(ops が ${name} に伝えます)`
hooks/hubs.ts 206 lines
1// Reading project hubs (projects/active/<slug>.md) for the hubs pane.
2// Pure functions: no engine calls, so the tests can feed them text.
3
4export type Milestone = { date: string; label: string; daysLeft: number }
5
6export type Hub = {
7  slug: string
8  title: string
9  summary: string
10  status: string
11  updated: string
12  daysSinceUpdate?: number
13  next?: Milestone
14  openNext: number
15  related: string[]
16  sections: { name: string; body: string }[]
17  text: string
18}
19
20const DAY = 86400000
21
22function dayOf(ms: number): number {
23  const d = new Date(ms)
24  return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
25}
26
27function parseDate(s: string): number | undefined {
28  const m = s.match(/(\d{4})-(\d{2})-(\d{2})/)
29  return m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime() : undefined
30}
31
32function frontmatter(text: string): Record<string, string> {
33  const out: Record<string, string> = {}
34  const m = text.match(/^---\n([\s\S]*?)\n---/)
35  if (!m) return out
36  for (const line of m[1].split('\n')) {
37    const kv = line.match(/^([A-Za-z_]+):\s*(.*)$/)
38    if (kv) out[kv[1]] = kv[2].replace(/^"(.*)"$/, '$1').trim()
39  }
40  return out
41}
42
43// "## " sections, ignoring "## " lines inside code fences.
44export function sections(text: string): { name: string; body: string }[] {
45  const out: { name: string; body: string }[] = []
46  let fence = false
47  let current: { name: string; lines: string[] } | undefined
48  for (const line of text.split('\n')) {
49    if (/^\s*(```|~~~)/.test(line)) fence = !fence
50    if (!fence && line.startsWith('## ')) {
51      if (current) out.push({ name: current.name, body: current.lines.join('\n').trim() })
52      current = { name: line.slice(3).trim(), lines: [] }
53      continue
54    }
55    if (current) current.lines.push(line)
56  }
57  if (current) out.push({ name: current.name, body: current.lines.join('\n').trim() })
58  return out
59}
60
61const plainCell = (s: string) => s.replace(/\*\*/g, '').replace(/[★⭐]/g, '').trim()
62
63// The nearest milestone on or after today, from the Milestones table.
64// Struck-through rows (~~...~~) do not count.
65export function nextMilestone(body: string, now: number): Milestone | undefined {
66  const today = dayOf(now)
67  let best: Milestone | undefined
68  for (const row of body.split('\n')) {
69    if (!row.startsWith('|') || /^\|\s*-/.test(row) || row.includes('~~')) continue
70    const cells = row.split('|').slice(1, -1)
71    if (cells.length < 2) continue
72    const t = parseDate(cells[0])
73    if (t === undefined || t < today) continue
74    const daysLeft = Math.round((t - today) / DAY)
75    if (!best || daysLeft < best.daysLeft) {
76      best = { date: cells[0].match(/\d{4}-(\d{2})-(\d{2})/)![0].slice(5).replace('-', '/').replace(/^0/, ''), label: plainCell(cells[1]), daysLeft }
77    }
78  }
79  return best
80}
81
82export function openActions(body: string): number {
83  return body.split('\n').filter(l => /^\s*(?:-|\d+\.)\s*(?:⬜|\[ \])/.test(l)).length
84}
85
86export function parseHub(slug: string, text: string, now: number): Hub {
87  const fm = frontmatter(text)
88  const secs = sections(text)
89  const find = (pred: (n: string) => boolean) => secs.find(s => pred(s.name))
90  const milestones = find(n => n.startsWith('Milestones'))
91  const nextActions = find(n => n.startsWith('Next Actions'))
92  const updatedAt = parseDate(fm.updated ?? '')
93  const related = (fm.related ?? '')
94    .replace(/^\[|\]$/g, '')
95    .split(',')
96    .map(s => s.trim().split('/').pop()!.replace(/\.md$/, ''))
97    .filter(Boolean)
98  return {
99    slug,
100    title: (text.match(/^# (.+)$/m)?.[1] ?? slug).trim(),
101    summary: fm.summary ?? '',
102    status: fm.status ?? '',
103    updated: fm.updated ?? '',
104    daysSinceUpdate: updatedAt === undefined ? undefined : Math.round((dayOf(now) - updatedAt) / DAY),
105    next: milestones ? nextMilestone(milestones.body, now) : undefined,
106    openNext: nextActions ? openActions(nextActions.body) : 0,
107    related,
108    sections: secs,
109    text,
110  }
111}
112
113const STATUS_ORDER = ['active', 'pending', 'blocked', 'standing', 'done', 'archived']
114
115export function sortHubs(hubs: Hub[]): Hub[] {
116  const rank = (s: string) => (STATUS_ORDER.indexOf(s) === -1 ? 99 : STATUS_ORDER.indexOf(s))
117  return [...hubs].sort((a, b) => rank(a.status) - rank(b.status) || (a.daysSinceUpdate ?? 9999) - (b.daysSinceUpdate ?? 9999) || a.slug.localeCompare(b.slug))
118}
119
120// The tabs of the detail view, and how each finds its section.
121export const TABS: { key: string; label: string; pick: (h: Hub) => { name: string; body: string } | undefined }[] = [
122  {
123    key: '1',
124    label: 'Current State',
125    // older hubs append dated "Current State" sections; the last one is the newest
126    pick: h => [...h.sections].reverse().find(s => s.name.includes('Current State')),
127  },
128  { key: '2', label: 'Milestones', pick: h => h.sections.find(s => s.name.startsWith('Milestones')) },
129  { key: '3', label: 'Next Actions', pick: h => h.sections.find(s => s.name.startsWith('Next Actions')) },
130  { key: '4', label: '会議', pick: h => h.sections.find(s => s.name.startsWith('Meetings')) },
131  { key: '5', label: '置き場', pick: h => h.sections.find(s => s.name.startsWith('Repositories')) },
132  { key: '6', label: '全文', pick: h => ({ name: '全文', body: h.text }) },
133]
134
135// Tables wrap badly in a pane, so every table is drawn as a list: the first
136// cell bold, the second beside it, the rest as "column: value" lines below.
137// Code fences are left as they are.
138const cellsOf = (row: string) => row.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim())
139const isRule = (row: string) => /^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(row.trim())
140
141export function tablesToLists(md: string): string {
142  const lines = md.split('\n')
143  const out: string[] = []
144  let fence = false
145  for (let i = 0; i < lines.length; i++) {
146    const line = lines[i]
147    if (/^\s*(```|~~~)/.test(line)) fence = !fence
148    const startsTable = !fence && line.trim().startsWith('|') && i + 1 < lines.length && isRule(lines[i + 1])
149    if (!startsTable) {
150      out.push(line)
151      continue
152    }
153    const head = cellsOf(line)
154    i += 2
155    while (i < lines.length && lines[i].trim().startsWith('|')) {
156      const c = cellsOf(lines[i])
157      const first = c[0] ? `**${c[0].replace(/\*\*/g, '')}**` : ''
158      out.push(`- ${[first, c[1]].filter(Boolean).join(' — ')}`)
159      for (let k = 2; k < c.length; k++) {
160        if (c[k] && c[k] !== '—' && c[k] !== '-') out.push(`  - ${head[k] ? `${head[k]}: ` : ''}${c[k]}`)
161      }
162      i++
163    }
164    i--
165    out.push('')
166  }
167  return out.join('\n')
168}
169
170export const MAX_CHARS = 90000
171
172export function sectionMarkdown(h: Hub, tab: number): string {
173  const t = TABS[tab]
174  const s = t.pick(h)
175  if (!s) return `_この hub には「${t.label}」の節がありません。_`
176  const body = tablesToLists(s.name === '全文' ? s.body : `## ${s.name}\n\n${s.body}`)
177  if (body.length <= MAX_CHARS) return body
178  return body.slice(0, MAX_CHARS) + `\n\n_(${body.length.toLocaleString()} 字のうち先頭 ${MAX_CHARS.toLocaleString()} 字まで。続きは節ごとに見てください)_`
179}
180
181// The draft put in the ops prompt by "次の一手を相談": where the hub is, its
182// current state and its first open next actions, then the ask. The person
183// reads it, edits it if they like, and sends it; nothing is sent from here.
184export function consultText(h: Hub, path: string, maxState = 1500): string {
185  const state = TABS[0].pick(h)
186  let body = (state?.body ?? '').trim()
187  if (body.length > maxState) body = body.slice(0, maxState) + '\n…(続きは hub)'
188  const next = h.sections.find(s => s.name.startsWith('Next Actions'))
189  const open = (next?.body ?? '')
190    .split('\n')
191    .filter(l => /^\s*(?:-|\d+\.)\s*(?:⬜|\[ \])/.test(l))
192    .slice(0, 3)
193    .map(l => l.trim())
194  return [
195    `hub「${h.slug}」(${h.title})の次の一手を一緒に考えたい。全文は ${path}`,
196    '',
197    `## ${state?.name ?? 'Current State'}`,
198    body || '(書かれていない)',
199    '',
200    '## Next Actions(まだ済んでいない上から 3 つ)',
201    ...(open.length ? open : ['(無い)']),
202    '',
203    'これを踏まえて、次にやるべきことを 1〜3 個、理由つきで提案して。締切と、誰がやるか(user / ops / peer)も添えて。',
204  ].join('\n')
205}
206
hooks/notes.ts 92 lines
1// Reading a research repo's note/note.md table of contents (written by the
2// life repo's scripts/note_toc.py) and choosing pictures under a number's
3// data folder, for the notes pane. Pure functions: the tests feed them text.
4
5export type TocRow = { id: string; date: string; title: string; conclusion: string; state: string }
6
7const cellsOf = (row: string) => row.trim().replace(/^\|/, '').replace(/\|$/, '').split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'))
8
9// The rows of the table between <!-- TOC:START --> and <!-- TOC:END -->.
10export function tocRows(md: string): TocRow[] {
11  const start = md.indexOf('<!-- TOC:START -->')
12  const end = md.indexOf('<!-- TOC:END -->')
13  if (start < 0 || end < start) return []
14  const out: TocRow[] = []
15  for (const line of md.slice(start, end).split('\n')) {
16    if (!/^\|\s*KM_[A-Z]\d{4}\s*\|/.test(line)) continue
17    const c = cellsOf(line)
18    if (c.length < 5) continue
19    out.push({ id: c[0], date: c[1], title: c[2], conclusion: c[3], state: c[4] })
20  }
21  return out
22}
23
24// A hub's frontmatter value, the inline comment after "  #" dropped.
25export function frontValue(md: string, key: string): string | undefined {
26  const fm = md.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? ''
27  const line = fm.split('\n').find(l => l.startsWith(`${key}:`))
28  if (!line) return undefined
29  return line.slice(key.length + 1).replace(/\s+#.*$/, '').trim() || undefined
30}
31
32// `find` output → picture paths relative to the number's folder, sorted, at most `max`.
33export function pngList(findOut: string, base: string, max = 200): string[] {
34  const root = base.replace(/\/+$/, '') + '/'
35  return findOut
36    .split('\n')
37    .map(l => l.trim())
38    .filter(l => l.toLowerCase().endsWith('.png') && l.startsWith(root))
39    .map(l => l.slice(root.length))
40    .sort((a, b) => a.localeCompare(b))
41    .slice(0, max)
42}
43
44// Terminal rows for a picture `columns` wide: a cell is about twice as tall as wide.
45export function imageRows(width: number, height: number, columns: number, maxRows = 40): number {
46  if (!width || !height) return Math.min(maxRows, Math.round(columns / 2))
47  return Math.max(4, Math.min(maxRows, Math.round((columns * height) / width / 2)))
48}
49
50const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
51
52// Standard padded base64: what Image's `png` must be.
53export function base64(u8: Uint8Array): string {
54  let out = ''
55  for (let i = 0; i < u8.length; i += 3) {
56    const a = u8[i], b = i + 1 < u8.length ? u8[i + 1] : 0, c = i + 2 < u8.length ? u8[i + 2] : 0
57    const n = (a << 16) | (b << 8) | c
58    out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63]
59    out += i + 1 < u8.length ? B64[(n >> 6) & 63] : '='
60    out += i + 2 < u8.length ? B64[n & 63] : '='
61  }
62  return out
63}
64
65// What $.fs.read(path, { as: 'bytes' }) gave, as base64: a session hands
66// { base64 }, a test hands bytes (or an object of them).
67export function bytesToBase64(r: any): string {
68  if (typeof r?.base64 === 'string') return r.base64
69  const raw = r?.bytes ?? r
70  const u8 = raw instanceof Uint8Array ? raw : Array.isArray(raw) ? Uint8Array.from(raw) : raw && typeof raw === 'object' ? Uint8Array.from(Object.values(raw) as number[]) : new Uint8Array(0)
71  return base64(u8)
72}
73
74export const isBase64 = (s: string) => s.length > 0 && s.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(s)
75
76// One number's entry in note.md: the lines under its "## <id> — …" heading,
77// up to the next "## " heading. `awk` hands over just that span (heading
78// included); the whole note works too. No such heading: nothing.
79export function entryLines(md: string, id: string): string[] {
80  const lines = md.split('\n')
81  const at = lines.findIndex(l => l.startsWith(`## ${id} — `))
82  if (at < 0) return []
83  const out: string[] = []
84  for (let i = at + 1; i < lines.length; i++) {
85    if (lines[i].startsWith('## ')) break
86    out.push(lines[i])
87  }
88  while (out.length && !out[out.length - 1].trim()) out.pop()
89  while (out.length && !out[0].trim()) out.shift()
90  return out
91}
92
hooks/trend.ts 75 lines
1// Reading the daily search-trend digest (ideas/daily/md/YYYY-MM-DD-trend.md):
2// tables of papers and news, each row a linked original title, its Japanese
3// rendering and an interest rating in stars. Pure functions: the tests feed
4// them text.
5
6export type TrendItem = {
7  source: string // the "### " heading the table sits under
8  short: string // a few letters for the one-line view
9  title: string
10  url: string
11  ja: string
12  stars: number
13  category: string
14  order: number // position in the file, for stable sorting
15}
16
17export type Trend = { date: string; items: TrendItem[] }
18
19const SHORT: [RegExp, string][] = [
20  [/pubmed/i, 'PM'],
21  [/biorxiv|europe\s*pmc/i, 'bR'],
22  [/nature/i, 'Nat'],
23  [/science|aaas/i, 'Sci'],
24  [/ナゾロジー/, 'ナゾ'],
25]
26
27export function shortSource(source: string): string {
28  return SHORT.find(([r]) => r.test(source))?.[1] ?? source.slice(0, 4)
29}
30
31const cellsOf = (row: string) =>
32  row.trim().replace(/^\|/, '').replace(/\|$/, '').split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'))
33
34export function parseTrend(md: string): Trend {
35  const date = md.match(/^# .*?(\d{4}-\d{2}-\d{2})/m)?.[1] ?? ''
36  const items: TrendItem[] = []
37  let source = ''
38  for (const line of md.split('\n')) {
39    const h = line.match(/^###\s+(.+)$/)
40    if (h) {
41      source = h[1].trim()
42      continue
43    }
44    if (!source || !line.trim().startsWith('|') || /^\|\s*-/.test(line.trim())) continue
45    const c = cellsOf(line)
46    const link = c[0]?.match(/^\[(.+)\]\((\S+)\)$/)
47    if (!link) continue // the header row and anything else without a linked title
48    items.push({
49      source,
50      short: shortSource(source),
51      title: link[1],
52      url: link[2],
53      ja: c[1] ?? '',
54      stars: (c[2]?.match(/★/g) ?? []).length,
55      category: c[3] ?? '',
56      order: items.length,
57    })
58  }
59  return { date, items }
60}
61
62// Highest rated first; equal ratings keep the file's order.
63export function topItems(items: readonly TrendItem[], n: number): TrendItem[] {
64  return [...items].sort((a, b) => b.stars - a.stars || a.order - b.order).slice(0, n)
65}
66
67export function starText(n: number): string {
68  return '★'.repeat(n) + '☆'.repeat(Math.max(0, 5 - n))
69}
70
71// The newest "YYYY-MM-DD-trend.md" among file names.
72export function latestTrendFile(names: readonly string[]): string | undefined {
73  return names.filter(n => /^\d{4}-\d{2}-\d{2}-trend\.md$/.test(n)).sort().pop()
74}
75
hooks/alert.ts 290 lines
1// The alert pane's pure parts: the Gmail feed's items, how a row reads, and the
2// commands a selection turns into. No engine calls, so tests can feed them.
3//
4// What reaches the model: nothing, until the person presses 詳しく and sends
5// the draft it puts in the prompt. A message in a sensitive class (人事・成績・
6// 査読 …, decided on the machine in ~/.config/life/alert.json) never gets 詳しく:
7// it can be marked Done or put on the calendar, both run here without the model.
8
9export type MailItem = {
10  id: string
11  thread_id?: string
12  from: string
13  from_name: string
14  subject: string
15  date: string
16  labels: string[]
17  unread: boolean
18  bulk: boolean
19  sensitive?: string
20}
21
22export type MailFeed = { fetched_at: string; items: MailItem[]; error?: string; fetched_new?: number }
23
24export const DONE_LABEL = '9. Done/Triage'
25
26export function parseFeed(stdout: string): MailFeed {
27  try {
28    const d = JSON.parse(stdout)
29    return { fetched_at: String(d.fetched_at ?? ''), items: Array.isArray(d.items) ? d.items : [], error: d.error, fetched_new: d.fetched_new }
30  } catch {
31    return { fetched_at: '', items: [], error: '取得の結果を読めなかった' }
32  }
33}
34
35// Ids in `items` not in `seen`: what came since the last look.
36export function newIds(seen: ReadonlySet<string> | undefined, items: readonly MailItem[]): string[] {
37  if (!seen) return []
38  return items.filter(x => !seen.has(x.id)).map(x => x.id)
39}
40
41// "10/08 14:32" in the machine's zone.
42export function shortDate(iso: string): string {
43  const t = Date.parse(iso)
44  if (Number.isNaN(t)) return '     '
45  const d = new Date(t)
46  const two = (n: number) => String(n).padStart(2, '0')
47  return `${d.getMonth() + 1}/${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`
48}
49
50// Personal mail first, newest first; bulk mail (a list-unsubscribe header) after.
51export function splitMail(items: readonly MailItem[], done: ReadonlySet<string>): { personal: MailItem[]; bulk: MailItem[] } {
52  const live = items.filter(x => !done.has(x.id)).sort((a, b) => Date.parse(b.date) - Date.parse(a.date))
53  return { personal: live.filter(x => !x.bulk), bulk: live.filter(x => x.bulk) }
54}
55
56// A row's text; the ☐ / ☑ that selects it is a button of its own before it
57// (pressing the row opens the mail).
58export function mailLine(item: MailItem): string {
59  const dot = item.unread ? '●' : ' '
60  const tag = item.sensitive ? `[${item.sensitive}]` : ''
61  return `${dot} ${shortDate(item.date)}  ${item.from_name}  ${tag}${item.subject}`
62}
63
64// One mail with its body, from `alert_feed.py --body` (the pane's own call; the
65// model is kept from it by ops-rules). Shown on the terminal, never stored.
66export type MailBody = { id: string; from?: string; date?: string; subject?: string; sensitive?: string | null; body?: string; error?: string }
67
68export function bodyArgv(python: string, repo: string, id: string): string[] {
69  return [python, `${repo}/scripts/gmail/alert_feed.py`, '--body', id]
70}
71
72export function parseBody(stdout: string, id: string): MailBody {
73  try {
74    const d = JSON.parse(stdout)
75    return { id, ...d }
76  } catch {
77    return { id, error: '本文を読めなかった' }
78  }
79}
80
81// Opening a mail in the pane marks it read in Gmail too (user 10/12).
82export function readArgv(python: string, repo: string, id: string): string[] {
83  return [python, `${repo}/scripts/gmail_label.py`, '--message-id', id, '--remove-label', 'UNREAD']
84}
85
86export function doneArgv(python: string, repo: string, ids: readonly string[]): string[] {
87  return [python, `${repo}/scripts/gmail_label.py`, ...ids.flatMap(id => ['--message-id', id]), '--add-label', DONE_LABEL]
88}
89
90// "2026-10-15 17:00" or "2026-10-15" (then 09:00); a 30-minute block that
91// ends at the deadline's time would hide it, so the block starts there.
92export function parseWhen(text: string): { start: string; end: string } | { error: string } {
93  const m = text.trim().match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?$/)
94  if (!m) return { error: '日時は 2026-10-15 17:00 か 2026-10-15 の形で' }
95  const [y, mo, d, h, mi] = [m[1], m[2], m[3], m[4] ?? '9', m[5] ?? '00'].map(Number)
96  const start = new Date(y, mo - 1, d, h, mi)
97  if (start.getMonth() !== mo - 1 || start.getDate() !== d || h > 23 || mi > 59) return { error: 'その日時はありません' }
98  const end = new Date(start.getTime() + 30 * 60000)
99  const iso = (t: Date) => `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}T${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}:00`
100  return { start: iso(start), end: iso(end) }
101}
102
103export function calendarArgv(python: string, repo: string, title: string, when: { start: string; end: string }): string[] {
104  return [python, `${repo}/scripts/google_calendar_create.py`, '--title', title, '--start', when.start, '--end', when.end, '--execute']
105}
106
107// A sensitive message's default title says only its class, never its subject
108// (a subject can carry the matter itself).
109export function calendarTitle(item: MailItem): string {
110  return item.sensitive ? `[${item.sensitive}]締切` : `〆 ${item.subject}`
111}
112
113// The draft 詳しく puts in the prompt: the ids to read, and what to do. Only
114// the person's send hands it to the model; sensitive mail is refused here too.
115export function detailPrompt(items: readonly MailItem[], ask: string): string | undefined {
116  if (items.length === 0 || items.some(x => x.sensitive)) return undefined
117  const lines = items.map(x => `- id ${x.id} — ${shortDate(x.date)} ${x.from_name}「${x.subject}」`)
118  return [
119    'Gmail の次のメールを読んで、頼んだことをしてください。本文は life repo で `python scripts/gmail/alert_feed.py --show <id>` で 1 通ずつ取る(読むだけ。返信・削除はしない)。',
120    ...lines,
121    '',
122    `頼むこと: ${ask.trim() || '要点と、私がすべきことを短く'}`,
123  ].join('\n')
124}
125
126// ---- Slack: what scripts/slack/slack_feed.py prints for the pane ----------
127// A count-only channel (a careful one) has no sender and no text: the pane
128// shows how many, never what.
129
130export type SlackItem = {
131  id: string // "<workspace>:<channel id>:<ts>"
132  workspace: string
133  kind: string // public / private / dm / group-dm
134  channel: string // "#name" is not added: dm names start with "@"
135  date: string
136  count_only: boolean
137  from_name?: string
138  head?: string
139  label?: string // the workspace name to show (an org-wide DM may name the org instead)
140  mention?: boolean // from a channel watched for mentions of the person only
141}
142export type SlackFeed = { fetched_at: string; items: SlackItem[]; errors: string[]; watched: number; error?: string }
143
144export function parseSlack(stdout: string): SlackFeed {
145  try {
146    const d = JSON.parse(stdout)
147    return { fetched_at: String(d.fetched_at ?? ''), items: Array.isArray(d.items) ? d.items : [], errors: Array.isArray(d.errors) ? d.errors : [], watched: Number(d.watched ?? 0), error: d.error }
148  } catch {
149    return { fetched_at: '', items: [], errors: [], watched: 0, error: '取得の結果を読めなかった' }
150  }
151}
152
153export function slackPlace(x: SlackItem): string {
154  return x.kind === 'dm' || x.kind === 'group-dm' ? x.channel : `#${x.channel}`
155}
156
157// The rows: messages one by one; a count-only channel folded into one row
158// "(件数だけ)ws #channel n 件" with all its ids.
159export type SlackRow = { key: string; ids: string[]; text: string; date: string; countOnly: boolean }
160
161export function slackRows(items: readonly SlackItem[], done: ReadonlySet<string>): SlackRow[] {
162  const live = items.filter(x => !done.has(x.id)).sort((a, b) => Date.parse(b.date) - Date.parse(a.date))
163  const rows: SlackRow[] = []
164  const folded = new Map<string, SlackRow>()
165  for (const x of live) {
166    if (x.count_only) {
167      const k = `${x.workspace}:${x.channel}`
168      const r = folded.get(k)
169      if (r) { r.ids.push(x.id); r.text = `(件数だけ)${x.workspace} ${slackPlace(x)} ${r.ids.length} 件`; continue }
170      const row = { key: `cnt-${k}`, ids: [x.id], text: `(件数だけ)${x.workspace} ${slackPlace(x)} 1 件`, date: x.date, countOnly: true }
171      folded.set(k, row)
172      rows.push(row)
173      continue
174    }
175    rows.push({ key: x.id, ids: [x.id], text: `${shortDate(x.date)} ${x.workspace} ${slackPlace(x)} ${x.from_name ?? ''}: ${x.head ?? ''}`, date: x.date, countOnly: false })
176  }
177  return rows
178}
179
180export function slackDoneArgv(python: string, repo: string, ids: readonly string[]): string[] {
181  return [python, `${repo}/scripts/slack/slack_feed.py`, '--done', ...ids]
182}
183
184// Slack grouped by conversation, the latest conversation first: one heading
185// (where, how many, when) and its newest messages under it. A count-only
186// channel keeps only its heading.
187export type SlackConv = {
188  key: string // "<workspace>:<channel id>"
189  workspace: string
190  place: string
191  ids: string[]
192  latest: string
193  countOnly: boolean
194  mention: boolean
195  isDm: boolean // a DM or group DM (the pane lists them apart from channels)
196  msgs: { id: string; when: string; from: string; head: string }[] // newest first
197}
198
199export function slackConversations(items: readonly SlackItem[], done: ReadonlySet<string>, now: number): SlackConv[] {
200  const today = new Date(now).toDateString()
201  const when = (iso: string) => (new Date(Date.parse(iso)).toDateString() === today ? shortDate(iso).slice(-5) : shortDate(iso))
202  const by = new Map<string, SlackConv>()
203  const live = items.filter(x => !done.has(x.id)).sort((a, b) => Date.parse(b.date) - Date.parse(a.date))
204  for (const x of live) {
205    const key = x.id.split(':').slice(0, 2).join(':')
206    let c = by.get(key)
207    if (!c) {
208      c = { key, workspace: x.label || x.workspace, place: slackPlace(x), ids: [], latest: x.date, countOnly: x.count_only, mention: !!x.mention, isDm: x.kind === 'dm' || x.kind === 'group-dm', msgs: [] }
209      by.set(key, c)
210    }
211    c.ids.push(x.id)
212    if (!x.count_only) c.msgs.push({ id: x.id, when: when(x.date), from: x.from_name ?? '', head: x.head ?? '' })
213  }
214  return [...by.values()]
215}
216
217// The ids the person chose: every id of a ticked conversation, plus each ticked message by itself.
218export function slackSelectedIds(convs: readonly SlackConv[], convSel: ReadonlySet<string>, msgSel: ReadonlySet<string>): string[] {
219  return [...new Set([...convs.filter(c => convSel.has(c.key)).flatMap(c => c.ids), ...convs.flatMap(c => c.msgs.map(m => m.id)).filter(id => msgSel.has(id))])]
220}
221
222// "team-a=slack-a, team-b=slack-b" → { 'team-a': 'slack-a', ... }. userConfig takes strings only:
223// an object here makes the whole options block fail to load (calendar and tasks vanished, 10/16).
224export function parseSlackMcp(text: string): Record<string, string> {
225  const out: Record<string, string> = {}
226  for (const pair of text.split(',')) {
227    const [w, srv] = pair.split('=').map(x => x.trim())
228    if (w && srv) out[w] = srv
229  }
230  return out
231}
232
233// The draft 詳しく puts in the prompt for Slack (user 10/14): the chosen
234// messages' ids and heads, and what to do. Only the person's send hands it to
235// the model, which reads each body with `slack_feed.py --show <id>`. A
236// count-only channel never gets 詳しく (its messages have no head to show).
237export function slackDetailPrompt(items: readonly SlackItem[], ids: readonly string[], ask: string, mcp: Readonly<Record<string, string>> = {}): string | undefined {
238  const want = new Set(ids)
239  const chosen = items.filter(x => want.has(x.id)).sort((a, b) => Date.parse(a.date) - Date.parse(b.date))
240  if (chosen.length === 0 || chosen.some(x => x.count_only)) return undefined
241  const lines = chosen.map(x => `- id ${x.id} — ${shortDate(x.date)} ${x.label || x.workspace} ${slackPlace(x)} ${x.from_name ?? ''}: ${x.head ?? ''}`)
242  // A workspace the person also connected as a Slack MCP server (pluginConfigs
243  // slack_mcp: workspace → server name) may be read through it: the thread,
244  // files and canvases too (user 10/16). The others stay on --show.
245  // "slack-a@T0123": a workspace inside an Enterprise Grid, where the server opens the
246  // person's default workspace unless the team_id is passed (user 10/16).
247  const viaMcp = [...new Set(chosen.map(x => x.workspace))].filter(w => mcp[w]).map(w => {
248    const [srv, team] = mcp[w].split('@')
249    return team ? `${w} は MCP の ${srv}(team_id ${team}。list_user_channels などには必ず team_id を渡す)` : `${w} は MCP の ${srv}`
250  })
251  return [
252    'Slack の次のメッセージを読んで、頼んだことをしてください。本文は life repo で `python scripts/slack/slack_feed.py --show <id>` で取る(読むだけ。返信・投稿はしない)。',
253    ...(viaMcp.length ? [`ただし ${viaMcp.join('、')} で読んでよい(スレッド・添付・キャンバスまで。読むだけ。返信・投稿はしない)。`] : []),
254    ...lines,
255    '',
256    `頼むこと: ${ask.trim() || '要点と、私がすべきことを短く'}`,
257  ].join('\n')
258}
259
260// ---- choosing the channels (the feed script's --channels / --set-watch) ----
261
262export type SlackChannel = { id: string; workspace: string; kind: string; name: string; watch: string; effective: string }
263
264export function parseChannels(stdout: string): { channels: SlackChannel[]; default: string; error?: string } {
265  try {
266    const d = JSON.parse(stdout)
267    if (d.error) return { channels: [], default: 'mention', error: String(d.error) }
268    return { channels: Array.isArray(d.channels) ? d.channels : [], default: String(d.default ?? 'mention') }
269  } catch {
270    return { channels: [], default: 'mention', error: '一覧を読めなかった' }
271  }
272}
273
274export const WATCH_LABEL: Record<string, string> = { y: '見る', count: '件数だけ', mention: 'メンションだけ', n: '見ない' }
275const CYCLE = ['y', 'mention', 'count', 'n']
276
277// The next mark when the person presses a channel's mark: 見る → メンションだけ → 件数だけ → 見ない → 見る
278export function nextWatch(effective: string): string {
279  const i = CYCLE.indexOf(effective)
280  return CYCLE[(i + 1) % CYCLE.length]
281}
282
283export function setWatchArgv(python: string, repo: string, id: string, watch: string): string[] {
284  return [python, `${repo}/scripts/slack/slack_feed.py`, '--set-watch', id, watch]
285}
286
287export function channelsArgv(python: string, repo: string): string[] {
288  return [python, `${repo}/scripts/slack/slack_feed.py`, '--channels']
289}
290
hooks/threads.ts 180 lines
1// threads: the replies peers send to ops, kept by sender, numbered, with what
2// ops sent them and what ops made of each reply. One file per peer under
3// ~/.local/share/life/threads/ (outside this repo), one JSON row a line.
4
5// in: a peer's reply to ops. out: what ops sent the peer. ops: what ops told the
6// person in the turn that read reply `ref`.
7export type ThreadRow = {
8  dir: 'in' | 'out' | 'ops'
9  at: number
10  text: string
11  n?: number // in: the peer's own count, from 1, never reset
12  read?: boolean // in
13  ref?: number // ops: the reply it is about
14}
15
16export type Peer = { name: string; sock?: string; body: string }
17
18// `<cross-session-message from="uds:…sock" from-name="peer-a" …>\nbody\n</cross-session-message>`
19const ENVELOPE = /^\s*<cross-session-message\b([^>]*)>\n?([\s\S]*?)\n?<\/cross-session-message>\s*$/
20
21function attr(attrs: string, name: string): string | undefined {
22  const m = attrs.match(new RegExp(`(?:^|\\s)${name}="([^"]*)"`))
23  return m ? m[1] : undefined
24}
25
26export function parsePeer(text: string): Peer | undefined {
27  const m = text.match(ENVELOPE)
28  if (!m) return undefined
29  const sock = attr(m[1], 'from')
30  const name = attr(m[1], 'from-name') || (sock ? sock.replace(/^.*\//, '').replace(/\.sock$/, '') : '')
31  if (!name) return undefined
32  return { name, sock, body: m[2] }
33}
34
35// "claude-worker-b [b43449]" → "claude-worker-b": the name ListAgents prints, with its ref dropped.
36export function peerOf(to: string): string {
37  return to.replace(/ \[[0-9a-f]+\]$/, '').trim()
38}
39
40// The short form a number carries: "claude-worker-b" → "worker-b", "claude-peer-a" → "peer-a".
41export function shortName(name: string): string {
42  return name.replace(/^claude-/, '')
43}
44
45export function label(name: string, n: number): string {
46  return `${shortName(name)}-${n}`
47}
48
49// The number goes at the head of the body, inside the envelope, so the message
50// still reads as the peer's (its sender and address stay as they came).
51export function numbered(text: string, tag: string): string {
52  return text.replace(/^(\s*<cross-session-message\b[^>]*>\n?)/, `$1【${tag}】`)
53}
54
55export function fileOf(dir: string, name: string): string {
56  return `${dir.replace(/\/+$/, '')}/${name.replace(/[^A-Za-z0-9._-]/g, '_')}.jsonl`
57}
58
59export function parseRows(text: string): ThreadRow[] {
60  const out: ThreadRow[] = []
61  for (const line of text.split('\n')) {
62    if (!line.trim()) continue
63    try {
64      const r = JSON.parse(line)
65      if (r && (r.dir === 'in' || r.dir === 'out' || r.dir === 'ops') && typeof r.text === 'string') out.push(r)
66    } catch {
67      // a torn line is skipped, the rest still read
68    }
69  }
70  return out
71}
72
73export function rowsText(rows: readonly ThreadRow[]): string {
74  return rows.map(r => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : '')
75}
76
77export function nextNumber(rows: readonly ThreadRow[]): number {
78  return rows.reduce((m, r) => (r.dir === 'in' && typeof r.n === 'number' && r.n > m ? r.n : m), 0) + 1
79}
80
81function escape(text: string): string {
82  return text.replace(/[.*+?^$()|[\]\\{}]/g, '\\$&')
83}
84
85// What ops wrote in a turn, cut for each reply it read: with one reply, the
86// whole answer; with several, the part under each reply's heading (a line that
87// begins with 【b-3】, after any #, * or -). Text above the first heading goes
88// with every part. A reply with no heading gets the whole answer: nothing is lost.
89export function splitAnswer(answer: string, tags: readonly string[]): Map<string, string> {
90  const out = new Map<string, string>()
91  const whole = answer.trim()
92  if (tags.length <= 1) {
93    for (const t of tags) out.set(t, whole)
94    return out
95  }
96  const lines = answer.split('\n')
97  const heads: { tag: string; line: number; rest: string }[] = []
98  lines.forEach((l, i) => {
99    for (const t of tags) {
100      const m = l.match(new RegExp(`^[\\s#*>-]*【${escape(t)}】[\\s*::]*(.*)$`))
101      if (m) heads.push({ tag: t, line: i, rest: m[1].replace(/\*+\s*$/, '').trim() })
102    }
103  })
104  if (heads.length === 0) {
105    for (const t of tags) out.set(t, whole)
106    return out
107  }
108  const pre = lines.slice(0, heads[0].line).join('\n').trim()
109  heads.forEach((h, k) => {
110    const end = k + 1 < heads.length ? heads[k + 1].line : lines.length
111    const body = [h.rest, ...lines.slice(h.line + 1, end)].join('\n').trim()
112    const part = [pre, body].filter(Boolean).join('\n\n')
113    out.set(h.tag, out.has(h.tag) ? `${out.get(h.tag)}\n\n${body}` : part)
114  })
115  for (const t of tags) if (!out.has(t)) out.set(t, whole)
116  return out
117}
118
119// Whether the reply numbered `tag` reached the model before its last answer:
120// the delivery (a user row holding 【tag】) comes before the last assistant row.
121export function readBefore(messages: readonly { role: string; text: string }[], tag: string): boolean {
122  const mark = `【${tag}】`
123  let got = -1
124  let answered = -1
125  messages.forEach((m, i) => {
126    if (m.role === 'user' && m.text.includes(mark)) got = i
127    if (m.role === 'assistant') answered = i
128  })
129  return got >= 0 && got < answered
130}
131
132// The order a thread reads in: by time, with what ops made of a reply right
133// under that reply (its own sends in that turn come after).
134export function threadOrder(rows: readonly ThreadRow[]): ThreadRow[] {
135  const main = rows.filter(r => r.dir !== 'ops').sort((a, b) => a.at - b.at)
136  const ops = rows.filter(r => r.dir === 'ops')
137  const placed = new Set<ThreadRow>()
138  const out: ThreadRow[] = []
139  for (const r of main) {
140    out.push(r)
141    if (r.dir === 'in') for (const o of ops.filter(o => o.ref === r.n)) { out.push(o); placed.add(o) }
142  }
143  for (const o of ops) if (!placed.has(o)) out.push(o)
144  return out
145}
146
147export function unread(rows: readonly ThreadRow[]): number {
148  return rows.filter(r => r.dir === 'in' && !r.read).length
149}
150
151// The text ops gets from the tab's input: the reply, then the first line of
152// what it answers.
153export function replyPrompt(peer: string, row: ThreadRow | undefined, reply: string): string {
154  if (!row || row.dir !== 'in' || row.n === undefined) return `【threads ${peer} への返事】${reply.trim()}`
155  const first = row.text.split('\n').find(l => l.trim())?.trim() ?? ''
156  return `【threads ${label(peer, row.n)} への返事】${reply.trim()}\n> ${label(peer, row.n)}: ${first}`
157}
158
159// Terminal cells a character takes: CJK and full-width forms take two.
160function wide(ch: string): boolean {
161  return /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/.test(ch)
162}
163
164// The text as the lines it takes at `width` cells, each line cut where it fills.
165export function wrapCells(text: string, width: number): string[] {
166  const out: string[] = []
167  for (const raw of text.replace(/\s+$/, '').split('\n')) {
168    let line = ''
169    let n = 0
170    for (const ch of raw) {
171      const w = wide(ch) ? 2 : 1
172      if (n + w > width) { out.push(line); line = ''; n = 0 }
173      line += ch
174      n += w
175    }
176    out.push(line)
177  }
178  return out
179}
180