SLOPSHOPPER

cc-sticky-notes

cc-sticky-notes: route curiosity questions to a side pane instead of the main conversation

panecommandtoaststatuspromptmodel
★ 1v0.0.4no licenseupdated 2026-10-21k7term1a/cc-sticky-notes
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cc-sticky-notes
│ ┃ sticky ✕ › fix the failing auth test and add an audit log call │ ┃ Sticky Notes 0 張 │ ┃ ⏺ Read(src/auth.ts) │ ┃ 還沒有便利貼。在主輸入框問「為什麼/是什麼」 ⎿ Read 6 lines │ ┃ ,或用 /sn new <問題>。 ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ╭──────────────────────────────────────────╮ ⏺ Bash(bun test) │ ┃ │ 專案脈絡 0 條 │ ⎿ 3 pass, 1 fail │ ┃ ╰──────────────────────────────────────────╯ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /sticky-note │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ cc-sticky-notes: 今日 Jev 0 次 · Claude 0

Draws

Pane · sticky
Sticky Notes 0 張 還沒有便利貼。在主輸入框問「為什麼/是什麼」,或用 /sn new <問題>。 ╭──────────────────────────────────────────────────────────╮ │ 專案脈絡 0 條 │ ╰──────────────────────────────────────────────────────────╯
README

cc-sticky-notes

一個 Claude Code mod:在專案 session 裡隨口問的「為什麼 / 這是什麼」不會進主線對話,而是變成「便利貼」,在背景回答、顯示在右側 pane,並存成一棵同專案所有 session 共用的樹。主線的 context 保持乾淨,追問也能一路掛在同一條旁支下。

版本 0.0.4,給朋友試用中。設計與決策:PLAN.md;Mods API 實測紀錄:PROBE.md;之後可能做的需求:REQUESTS.md。

0.0.4 新的地方

  • 多台電腦同步(選用):便利貼透過你自己的 Notion 資料庫在電腦之間同步,見下方「在多台電腦之間同步」。
  • 卡片時間前面有底色的類別標籤:Jev 對這個主題的判斷(知識旁問、專案疑問、主線任務)。
  • 刪除便利貼:問題旁的 ✕ 或 /sn rm,只刪這台電腦的。
  • Jev 的對話框 30 秒沒回應就自動送進主線(/sn timeout <秒> 調整,0 一直等)。對話框本身會留在畫面上,關掉就好。
  • 拿掉「結束追問」按鈕(改用 /sn back);舊的「這題在主線回答」便利貼會在開 session 時自動清掉。
  • /sn provider、/sn every、/sn notion 的設定改存在每台電腦自己的資料裡(之前在 Desktop 會設定失敗)。

0.0.3 新的地方

  • pane 改成卡片:一個主題一張卡,點開是一段對話(問題像 prompt 泡泡、答案在下面),多個追問用按鈕切換,卡片最下面直接回覆;滑鼠移到問題旁的 ✎ 可以換個問法再問一次。正在追問的那張是綠框。
  • 主線摘要與專案脈絡:每 3 個主線回合在背景統整一次(第一次讀整個 session),Jev 判斷時會參考;pane 最下面的「專案脈絡」卡片可以看、刪、加,或按「立即統整」。
  • 新指令:/sn provider claude|openai 切換統整層、/sn every <n> 調整統整頻率(0 關閉)、/sn ctx 看與編輯專案脈絡。
  • OpenAI 的 redacted 模式現在真的會先剝掉程式碼、路徑、金鑰再送出(之前沒有)。

0.0.2 新的地方

  • 對話框的〔接在「…」下〕改成 Jev 判斷最相關的那張便利貼(從最近 8 張裡挑),不再只能接目前追問的那張;多一個〔接在其他便利貼下…〕可以自己挑;在「其他」打標題的關鍵字也能找到便利貼。
  • 從另一台電腦或手機(Remote Control)打字不會跳便利貼的對話框,一律進主線。
  • Jev 判成「專案問題」的句子只進主線,不再在 pane 留下「在主線回答」的便利貼。
  • pane 的追問框送出後會清空。
  • 輸入框下方的狀態列改成顯示這個 mod 今天用掉的額度(Jev 次數、Claude / OpenAI token)。

需求

  • Claude Code 2.1.288 以上(Mods 是 early access,在 2.1.288 / 2.1.289、Windows 的 Claude Desktop Code 分頁與終端機測過)。
  • 選用:TypeSafe 的 Jev API key(自動分類用)、OpenAI API key(統整層可改用 OpenAI)。沒有也能用,見下方「金鑰」。

安裝

git clone https://github.com/k7term1a/cc-sticky-notes.git

終端機:每次啟動時帶上資料夾路徑。

claude --plugin-dir /path/to/cc-sticky-notes

Claude Desktop(Code 分頁):在 ~/.claude/settings.json 的 env 加上這個資料夾,之後開的 session 都會載入。

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "C:\\Users\\you\\cc-sticky-notes",
    "CLAUDE_CODE_PLUGIN_DIR_WATCH": "1"
  }
}
  • 改完要開新的 session(已經開著的 session 不會重新讀設定)。
  • CLAUDE_CODE_PLUGIN_DIR_WATCH 是選用的:設了之後,mod 的檔案一更新(例如 git pull),開著的 session 就會自動重載。
  • 裝好後在輸入框下方右側會看到 cc-sticky-note。打 /sn doctor 可以檢查金鑰有沒有讀到。

金鑰(選用)

建一個 ~/.claude/sticky-notes/.env(Windows 是 C:\Users\<你>\.claude\sticky-notes\.env):

TYPESAFE_API_KEY=apikey_...
OPENAI_API_KEY=sk-...
  • 依序找:環境變數 → ~/.claude/sticky-notes/.env → mod 資料夾裡的 .env。不會讀你專案自己的 .env(那裡常有那個專案自己的 OpenAI key)。
  • 金鑰值不會被印出、記錄或存進 store;/sn doctor 只告訴你找到沒有、從哪裡找到。
  • 沒有 Jev key:不做自動分類,所有輸入照常進主線,不會跳任何對話框。便利貼只能用 /sn new <問題> 或 pane 的追問框建立。
  • 沒有 OpenAI key:完全不影響,預設本來就用 Claude(你登入的訂閱)寫標題和摘要。

怎麼用

直接在輸入框問

像平常一樣打字。Jev 只決定「要不要問你」,不會自己把你的話收成便利貼:

  • 有把握的專案任務:照常送給 Claude,什麼都不會跳出來。
  • 知識旁問(例如「CRDT 是什麼?」),或 Jev 沒把握的句子(信心低於 60%):跳出一個對話框,問題會帶 Jev 的判斷與信心,例如「這句要怎麼處理?(Jev:知識旁問 96%)」:
  • 〔開新的便利貼〕:這句不會進主線,畫面上出現一張卡片:
    A hook blocked your prompt
    Prompt dropped by a hook: cc-sticky-note:新的便利貼「CRDT 是什麼?」

幾秒後答案出現在右側 pane(會自動打開),對話裡留一行灰字預覽。灰字和卡片 Claude 都讀不到。

  • 〔接在「<正在追問的題目>」下〕:只有在你正在追問某一則時才會出現,Jev 覺得是同一個話題時會排在第一個。
  • 〔送進主線〕:照常送給 Claude。關掉對話框也一樣送進主線,不會吞掉你的話。
  • 專案相關的疑問(「為什麼我們這裡用 X?」):照常問 Claude,不會建便利貼。

從另一台電腦用 Remote Control 打字不會跳便利貼的對話框,本來會問的句子一律進主線;便利貼、狀態列和 pane 只在跑 session 的那台電腦上用。

追問

輸入框下方右側的狀態列顯示這個 mod 今天用掉的額度,例如 cc-sticky-notes 今日 Jev 12 次 · Claude 35k(用過 OpenAI 才會出現 OpenAI;Claude 的數字不含讀 cache 的部分;所有專案、所有 session 合計,每天歸零)。接著再問相關的問題,對話框會把 Jev 判斷最相關的那張便利貼放在〔接在「…」下〕,選它就掛在那張下面;不是那張的話選〔接在其他便利貼下…〕,或在「其他」打標題的關鍵字。想結束追問,打 /sn back。

也可以直接用 pane 卡片最下面的回覆框(不經 Jev,直接接在卡片目前讀到的最後一則下面)。

右側 pane

打 /sn 開關。內容:

  • 一個主題一張卡片,最新的在最上面。收合時只有一行:標題、時間、這個主題共幾則(標題後的 … 表示還在回答)。點那一行就展開,點展開後的標題就收合。
  • 展開後是一段對話:你的問題畫成像 Desktop prompt 的泡泡(靠右),答案接在下面,不分層級。某則有多個追問時,答案下面列出各追問的標題(● 是目前讀的這條、○ 是其他),點了就換成那條往下讀。答案不是看得到專案的 Claude 回答時,下面會標「無專案脈絡」。
  • 刪除:滑鼠移到問題那一列,左邊的 ✕ 會先問一次,再刪掉那則和它底下的追問。只刪這台電腦的;有同步到 Notion 的會在 Notion 勾上「不同步」,其他電腦之後就不會再下載它(已經下載過的不會被刪)。也可以先點開那則,再打 /sn rm。
  • 改寫問題:滑鼠移到問題那一列,左邊會出現 ✎;改完按 ↵ 會在同一層多一個追問(改的是第一個問題就開一張新卡片),舊的留著,可以用上面的 ● / ○ 切換。
  • 回覆框:卡片最下面,接在目前讀到的最後一則下面。Desktop 的輸入框寬度固定,mod 改不了。
  • 類別:時間前面有底色的小標籤,是 Jev 對這個主題第一句的判斷(知識旁問、專案疑問、主線任務),和對話框裡顯示的一樣。用 /sn new 或回覆框建的、Jev 沒看過的便利貼沒有類別。
  • 綠色邊框:這個 session 正在追問的那張;其他卡片都是灰框。只是點開來看不會變成追問中。想結束追問打 /sn back。

主線摘要與專案脈絡

每 3 個主線回合(/sn every 可調),mod 會在背景請統整層(Claude haiku 或 OpenAI)讀最近幾輪對話,寫兩樣東西:

  • 主線摘要:這個 session 現在在做什麼、剛決定什麼、還卡在哪,200 字內。Jev 判斷新的一句要不要跳對話框、接在哪張時會讀它,比原本只看幾句原文準。
  • 專案脈絡:值得長期記住的事(決定、慣例、限制、踩過的坑),每次 0–3 條,所有 session 共用,只會自動增加。

兩者都在 pane 最下面的「專案脈絡」卡片:可以看、用 ✕ 刪、自己加一條,或按「立即統整」。用 OpenAI 時,送出去的對話會先依 openaiContextMode 剝掉程式碼、路徑等內容。每次統整大約 2–4k token,會算進狀態列的今日用量。

在多台電腦之間同步(Notion,選用)

每台電腦的便利貼可以同步到你自己 Notion 裡的一個資料庫:答好的便利貼自動上傳一列;session 開始時把其他電腦在同一個專案做的便利貼拉下來(專案用 git remote 對應,路徑不同也沒關係)。走的是你在 claude.ai 連好的 Notion connector,mod 不存任何 token。

  1. 在 Notion 建一個資料庫,欄位:標題(title)、問題、摘要、Note ID、上一層(文字)、專案、電腦、回答者(select)、建立時間(date)。
  2. 在 ~/.claude/settings.json 的 permissions.allow 加上 Notion connector 的四個工具:notion-fetch、notion-query-data-sources、notion-create-pages、notion-update-page(完整名稱是 mcp__<connector id>__notion-fetch 這種形式,/sn notion test 會印出 connector id)。沒加的話,auto 權限模式會擋下 mod 的呼叫。
  3. 每台電腦各打一次 /sn notion <collection://…>,再打 /sn notion test 確認四步都 ✓。
指令作用
/sn notion看同步到哪、上次同步的結果
/sn notion pull現在就下載其他電腦的便利貼
/sn notion push把這個專案還沒上傳的便利貼全部上傳(第一次設定時用)

只會新增,不會合併同一張便利貼的修改。

指令

/sn 和 /sticky-note 完全一樣,/sn 比較好打。

指令作用
/sn開 / 關右側 pane
/sn new <問題>手動開一張便利貼(不經 Jev)
/sn back結束追問,回到主線
/sn rm刪除 pane 裡點開的那則便利貼和它底下的追問(會先問)
/sn timeout <秒>Jev 的對話框幾秒沒回應就自動送進主線(預設 30,0 一直等)
`/sn feedback main\new\followup`上一句其實應該是:主線 / 新的便利貼 / 追問(也可以打「主線」「便利貼」「追問」)
/sn feedback good上一句現在這樣就對
/sn calibrate用你的選擇與回饋,看各門檻下 Jev 的表現
`/sn provider claude\openai`切換標題、摘要、背景統整用誰寫(不帶參數就顯示目前用哪個)
/sn every <n>每 n 個主線回合在背景統整一次主線摘要與專案脈絡;0 關閉(預設 3)
/sn ctx在對話裡列出這個 session 的主線摘要和專案脈絡(只有你看得到,Claude 讀不到)
/sn ctx add <文字>、/sn ctx rm <n>自己加一條、刪第 n 條專案脈絡
/sn ctx refresh現在就統整一次
/sn doctor檢查兩把金鑰找到沒有、從哪裡找到

幫忙測試

你在對話框的每一次選擇都會自動記下來(Jev 的判斷、信心、你的選擇,只存在你的電腦)。最有用的額外回饋是 Jev 沒問、直接送進主線,但其實你想要便利貼 的時候:打 /sn feedback new,再截圖給我。

設定

下列欄位可以在 Claude Code 的設定選單(/config,終端機)調整:

欄位預設說明
autoOpenPanetrue答案回來時自動打開 pane 並選中
routeThreshold0.6Jev 判成專案任務、且信心至少這麼高時才不問你
followupThreshold0.6對話框裡〔接在…下〕排第一的門檻
summaryProviderclaude標題、摘要、背景統整用誰寫:claude 或 openai(也可以用 /sn provider)
digestEvery3每幾個主線回合在背景統整一次;0 關閉(也可以用 /sn every)
claudeModel / claudeEfforthaiku / low寫標題摘要的 Claude 模型與 effort(旁答本身一律用主線的模型)
openaiModel / openaiReasoningEffortgpt-5-mini / minimalsummaryProvider = openai 時用

已知限制

  • 被攔下的那句,Desktop 一定會顯示那張「A hook blocked your prompt」卡片,標題改不掉。Claude 讀不到這句,但它仍會留在本機的 session 紀錄檔裡。
  • 旁答用的是主線同一個模型(Claude Code 的限制),算在你的訂閱用量裡;有 prompt cache,通常 1–3 秒。
  • 剛重開或 resume 一個 session、主線還沒跑過任何回合之前,旁答拿不到專案脈絡,pane 會標「無專案脈絡」。
  • Jev 會收到你最近 3 句主線 prompt 與最後一則回覆(各取前 300 字)、正在追問的題目,以及新的這句(判斷用)。介意的話不要設 Jev key。
  • 便利貼存在本機:~/.claude/plugins/store/cc-sticky-notes_*.json。用 --plugin-dir 載入和正式安裝可能是不同的檔。
  • 側邊欄外觀還很陽春,下一版會改。

開發

claude plugin validate .
claude plugin test .
npx -p typescript@5.6 tsc -p .

tsconfig.json extends .claude-plugin/types/tsconfig.json,那是引擎載入 mod 時寫出來的型別(已 git-ignore),所以第一次 type-check 前要先載入一次 mod。

  • hooks/register.tsx:所有 hook,以及 portsOf($)。只有這個檔碰 $(PROBE.md P1)。
  • hooks/tree.ts、route.ts、jev.ts、redact.ts、digest.ts、answer.ts:邏輯模組,純函式或吃 Ports。
  • hooks/notes.ts:流程(路由 → 便利貼 → 背景回答 → 路由樣本)。
  • hooks/feedback.ts:路由回饋紀錄(feedback:<root>:<id>)、/sn feedback、calibrate。
  • hooks/secrets.ts:金鑰從哪裡來。
  • hooks/pane.tsx:右側 pane 與輸入框下方的狀態列。
  • probes/m0/:M0 探針 mod(cc-sticky-probe),獨立的 plugin。
Source 20 files
hooks/register.tsx 343 lines
1// Entry point: the hooks, and portsOf — the one place `$` is turned into the
2// closures the logic modules use (ports.ts says why `$` itself cannot cross).
3import type { EngineInterface, HttpResponse, Register } from 'claude-code'
4import { atom, read, update } from 'claude-code'
5
6import { COMMAND, COMMAND_SPEC, maskNewArgs, runCommand, SHORT_COMMAND, SHORT_COMMAND_SPEC } from './commands'
7import { applyOptionOverrides, change, confirmDelete, digestNow, syncPull, optionKey, projectKey, explainDrop, prepare, readOptions, recordFeedback, routePrompt, startNote, type Options } from './notes'
8import { PANE_ID, PANE_TITLE, paneView } from './pane'
9import { addFacts, contextKey, readDigest, readFacts, type ContextFact } from './context'
10import type { Ports } from './ports'
11import { describeKey, findKey, keyFiles, resolveKey } from './secrets'
12import { setActive } from './tree'
13import { addUsage, claudeDelta, fetchDelta, readUsage, usageLine, type Usage } from './usage'
14
15// $.state values (types/index.d.ts). The loader reads atoms only from this file's own consts.
16const treeAtom = atom({ plugin: 'cc-sticky-notes', key: 'tree' } as const, null)
17const selectedAtom = atom({ plugin: 'cc-sticky-notes', key: 'selectedId' } as const, null)
18const editingAtom = atom({ plugin: 'cc-sticky-notes', key: 'editingId' } as const, null)
19const contextRevAtom = atom({ plugin: 'cc-sticky-notes', key: 'contextRev' } as const, 0)
20const digestStatusAtom = atom({ plugin: 'cc-sticky-notes', key: 'digestStatus' } as const, { running: false, at: null, result: null })
21const unreadAtom = atom({ plugin: 'cc-sticky-notes', key: 'unread' } as const, 0)
22const pendingAtom = atom({ plugin: 'cc-sticky-notes', key: 'pending' } as const, 0)
23const lastTurnAtom = atom({ plugin: 'cc-sticky-notes', key: 'lastTurnId' } as const, null)
24const turnsAtSidebarAtom = atom({ plugin: 'cc-sticky-notes', key: 'turnsAtLastSidebar' } as const, 0)
25const lastPromptAtom = atom({ plugin: 'cc-sticky-notes', key: 'lastPromptUuid' } as const, null)
26const lastSampleAtom = atom({ plugin: 'cc-sticky-notes', key: 'lastSampleId' } as const, null)
27
28/** Key files to try after the environment (secrets.ts says which and why). */
29async function keyFilesOf($: EngineInterface): Promise<string[]> {
30  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
31  return keyFiles(home, $.plugin.root)
32}
33
34const kvOf = ($: EngineInterface) => ({
35  get: (key: string) => $.store.get(key),
36  set: (key: string, value: never) => $.store.set(key, value),
37  delete: (key: string) => $.store.delete(key),
38  keys: () => $.store.keys(),
39})
40
41/**
42 * The status line under the prompt (PROBE.md「UI 能放在哪裡」 D): what this mod spent
43 * today (usage.ts), and the answers still pending. Desktop draws the plugin's name
44 * before it. Redrawn when a count, the tree or the pending number changes.
45 */
46async function refreshStatus($: EngineInterface) {
47  $.ui.status(usageLine(await readUsage(kvOf($), new Date()), await read($, pendingAtom)))
48}
49
50/** Adds one request's cost to today's count; a failure to count never fails the request. */
51function count($: EngineInterface, delta: Partial<Usage>) {
52  if (Object.keys(delta).length === 0) return
53  void addUsage(kvOf($), new Date(), delta)
54    .then(() => refreshStatus($))
55    .catch(() => {})
56}
57
58function portsOf($: EngineInterface): Ports {
59  const readText = (path: string) => $.fs.read(path) as Promise<string>
60  return {
61    sessionId: () => $.session.id(),
62    // PLAN.md: one tree per repo, shared by its worktrees; the session root outside a repo.
63    projectRoot: async () => (await $.session.repo())?.root ?? (await $.session.root()),
64    turns: () => $.session.turns(),
65    messages: async () => {
66      const list = await $.session.messages()
67      return Array.isArray(list) ? list : []
68    },
69    now: () => $.clock.now(),
70    later: fn => void $.clock.after(0, fn),
71    sleep: ms => $.clock.sleep(ms),
72    store: kvOf($),
73    // every request that costs a quota is counted as it leaves (usage.ts)
74    fetch: async (url, init) => {
75      let r: HttpResponse | null = null
76      try {
77        r = await $.http.fetch(url, init)
78        return r
79      } finally {
80        count($, fetchDelta(url, r))
81      }
82    },
83    fork: async prompt => {
84      const r = await $.model.fork({ prompt })
85      if ('usage' in r) count($, claudeDelta(r.usage))
86      return r
87    },
88    complete: async request => {
89      const r = await $.model.complete(request)
90      count($, claudeDelta(r.usage))
91      return r
92    },
93    keys: {
94      typesafe: async () => resolveKey('TYPESAFE_API_KEY', await $.env.get('TYPESAFE_API_KEY'), await keyFilesOf($), readText),
95      openai: async () => resolveKey('OPENAI_API_KEY', await $.env.get('OPENAI_API_KEY'), await keyFilesOf($), readText),
96      report: async () => {
97        const files = await keyFilesOf($)
98        return [
99          describeKey('TYPESAFE_API_KEY', await findKey('TYPESAFE_API_KEY', await $.env.get('TYPESAFE_API_KEY'), files, readText)),
100          describeKey('OPENAI_API_KEY', await findKey('OPENAI_API_KEY', await $.env.get('OPENAI_API_KEY'), files, readText)),
101          `key 檔查找順序:${files.join(' → ')}`,
102        ]
103      },
104    },
105    place: async () => ({
106      remote: (await $.session.repo())?.remote ?? null,
107      machine: (await $.env.get('COMPUTERNAME')) ?? (await $.env.get('HOSTNAME')) ?? (await $.env.get('USER')) ?? 'unknown',
108    }),
109    mcp: {
110      tools: async () => (await $.tool.list()).filter(t => t.mcp).map(t => t.name),
111      call: async (server, tool, args) => {
112        const r = await $.mcp.call(server, tool, args)
113        return { isError: r.isError, content: r.content as { type: string; text?: string }[] }
114      },
115    },
116    setOption: async (field, value) => {
117      try {
118        // the row of this plugin's own field: `cc-sticky-notes.<field>` (or `cc-sticky-notes@inline.<field>`)
119        // kept in this machine's store too, applied at session.start (applyOptionOverrides): a
120        // --plugin-dir mod's fields are not rows of /config (seen 10/14), so that is the one that holds
121        await $.store.set(optionKey(field), value)
122        const row = (await $.config.list()).find(r => /^cc-sticky-notes(@[^.]+)?\./.test(r.key) && r.key.endsWith(`.${field}`))
123        if (!row) return { ok: true }
124        const r = await $.config.set({ key: row.key, value: value as never })
125        if (r.deny !== undefined) $.ui.log(`sticky-notes: /config kept ${field} as it was (${r.deny}); this machine's own setting stands`, { to: 'debug' })
126        return { ok: true }
127      } catch (err) {
128        return { ok: false, reason: String(err).slice(0, 200) }
129      }
130    },
131    ui: {
132      log: (text, to) => $.ui.log(text, { to: to ?? 'transcript' }),
133      toast: text => $.ui.toast(text),
134      ask: (question, options, header) => $.ui.ask(question, { options, header }),
135      openPane: async () => {
136        await update($, unreadAtom, () => 0)
137        await $.ui.open({ id: PANE_ID, title: PANE_TITLE })
138      },
139      closePane: () => $.ui.close({ id: PANE_ID }),
140      isPaneOpen: async () => (await $.ui.panes()).some(pane => pane.id === PANE_ID),
141      status: text => $.ui.status(text),
142    },
143    state: {
144      publishTree: async tree => {
145        await update($, treeAtom, () => tree)
146        await refreshStatus($)
147      },
148      lastTurnId: () => read($, lastTurnAtom),
149      turnsAtLastSidebar: () => read($, turnsAtSidebarAtom),
150      setTurnsAtLastSidebar: async n => void (await update($, turnsAtSidebarAtom, () => n)),
151      addPending: async delta => {
152        await update($, pendingAtom, n => Math.max(0, n + delta))
153        await refreshStatus($)
154      },
155      addUnread: async delta => void (await update($, unreadAtom, n => Math.max(0, n + delta))),
156      lastPromptUuid: () => read($, lastPromptAtom),
157      lastSampleId: () => read($, lastSampleAtom),
158      setLastSampleId: async id => void (await update($, lastSampleAtom, () => id)),
159      setSelected: async id => void (await update($, selectedAtom, () => id)),
160      selected: () => read($, selectedAtom),
161      contextChanged: async () => void (await update($, contextRevAtom, n => n + 1)),
162      setDigestStatus: async (running, result) =>
163        void (await update($, digestStatusAtom, s => (running ? { ...s, running: true } : { running: false, at: Date.now(), result }))),
164    },
165  }
166}
167
168/**
169 * A card press: opens the card holding this note (null closes). Reading a card does not
170 * make it the one this session follows up (10/14): a reply does, or the dialog's pick.
171 */
172async function selectNode($: EngineInterface, id: string | null) {
173  await update($, editingAtom, () => null)
174  await update($, selectedAtom, () => id)
175}
176
177/** R4: what the project context card shows; read on each draw (contextRev makes it draw again). */
178async function contextData($: EngineInterface, opts: Options) {
179  await read($, contextRevAtom)
180  const how = { digestEvery: opts.digestEvery, provider: opts.summaryProvider, digestStatus: await read($, digestStatusAtom) }
181  try {
182    const p = portsOf($)
183    const root = await projectKey(p)
184    const facts = await readFacts(p.store, root)
185    const digest = (await readDigest(p.store, root, await p.sessionId()))?.text ?? null
186    return { ...how, digest, facts: facts.map(f => ({ id: f.id, text: f.text, source: f.source })) }
187  } catch {
188    // never let the context card refuse the whole pane
189    return { ...how, digest: null, facts: [] }
190  }
191}
192
193/** R4: the pane's edits to the project context. */
194async function editFacts($: EngineInterface, edit: (facts: ContextFact[]) => ContextFact[]) {
195  const p = portsOf($)
196  const root = await projectKey(p)
197  await p.store.set(contextKey(root), edit(await readFacts(p.store, root)))
198  await p.state.contextChanged()
199}
200
201
202/**
203 * ✎: a rewritten question is asked again beside the old one — a new follow-up of the
204 * same parent, so the parent's answer offers both; a first question starts a new topic.
205 */
206async function rewrite($: EngineInterface, opts: Options, nodeId: string, question: string) {
207  const tree = await read($, treeAtom)
208  const parentId = tree?.nodes[nodeId]?.parentId ?? null
209  if (parentId !== null) return followUp($, opts, parentId, question)
210  await startNote(portsOf($), opts, {
211    question,
212    attach: { kind: 'root' },
213    answerer: 'fork',
214    route: { label: 'sidebar_knowledge', confidence: 1, source: 'manual' },
215  })
216}
217
218/** The pane's reply box: straight to a note under that node, no Jev (PLAN.md). */
219async function followUp($: EngineInterface, opts: Options, parentId: string, question: string) {
220  await startNote(portsOf($), opts, {
221    question,
222    attach: { kind: 'under', parentId },
223    answerer: 'fork',
224    route: { label: 'sidebar_knowledge', confidence: 1, source: 'manual' },
225  })
226}
227
228export const register: Register = (on, options) => {
229  const opts = readOptions(options)
230
231  on('session.start', async ($, e, next) => {
232    await applyOptionOverrides(kvOf($), opts)
233    await $.command.register(COMMAND_SPEC)
234    await $.command.register(SHORT_COMMAND_SPEC)
235    const p = portsOf($)
236    await prepare(p)
237    // the notes other computers made in this project (Notion), in the background
238    if (opts.notionDataSource !== '') p.later(() => void syncPull(p, opts))
239    return next(e)
240  })
241
242  on('turn.start', async ($, e, next) => {
243    await update($, lastTurnAtom, () => e.turnId)
244    return next(e)
245  })
246
247  // R4: every digestEvery main turns, the main-line digest and the project context, in the background
248  on('turn.complete', async ($, e, next) => {
249    const r = await next(e)
250    if (e.agentId === undefined && e.reason === 'answer' && opts.digestEvery > 0) {
251      const p = portsOf($)
252      p.later(() => void digestNow(p, opts).catch(err => p.ui.log(`sticky-notes: main digest failed: ${String(err).slice(0, 200)}`, 'debug')))
253    }
254    return r
255  })
256
257  on('session.append', async ($, e, next) => {
258    if (e.agentId !== undefined) return next(e)
259    // anchor.messageId: the main-line user message a later sidebar question sits after (M2 badge).
260    if (e.door === 'prompt' && e.message.type === 'user' && !e.message.isMeta) {
261      await update($, lastPromptAtom, () => e.uuid)
262      return next(e)
263    }
264    // PROBE.md P10: `/sticky-note new <問題>` would leave the question in the main context.
265    if (e.door === 'command') {
266      let masked = false
267      const content = e.message.content.map(block => {
268        if (block.type !== 'text' || typeof block.text !== 'string') return block
269        const text = maskNewArgs(block.text)
270        if (text === null) return block
271        masked = true
272        return { ...block, text }
273      })
274      if (masked) return next({ ...e, message: { ...e.message, content } })
275    }
276    return next(e)
277  })
278
279  on('prompt.submit', async ($, e, next) => {
280    // Only the person's own typed prompts are routed; notifications, peers and plugins pass.
281    if (e.origin.kind !== 'composer' && e.origin.kind !== 'bridge') return next(e)
282    if (e.text.trim() === '' || e.text.trimStart().startsWith('/')) return next(e)
283
284    const p = portsOf($)
285    const routed = await routePrompt(p, opts, e.text, { remote: e.origin.kind === 'bridge' })
286    const keep = (nodeId: string | null) => p.later(() => void recordFeedback(p, opts, e.text, routed, nodeId))
287    const d = routed.decision
288    switch (d.kind) {
289      case 'main':
290      case 'ask':
291        keep(null)
292        return next(e)
293      case 'project_question':
294        // the main line answers it; no note (going to the main line means no note)
295        keep(null)
296        return next({ ...e, context: [...(e.context ?? []), d.context] })
297      case 'sidebar':
298        keep(
299          await startNote(p, opts, {
300            question: e.text,
301            attach: d.parentId !== undefined ? { kind: 'under', parentId: d.parentId } : { kind: d.attach },
302            answerer: d.answerer,
303            route: d.route,
304            tag: d.tag.kind === 'existing' ? d.tag.tag : undefined,
305          }),
306        )
307        // The drop reason is the transparency line (PROBE.md P2): who decided, how sure, where it went.
308        return { drop: explainDrop(e.text, routed) }
309    }
310  })
311
312  on('command.run', { command: COMMAND }, async ($, e) => runCommand(portsOf($), opts, e.args))
313  // /sn: the keyboard shortcut for the pane (the status line cannot be clicked; PROBE.md)
314  on('command.run', { command: SHORT_COMMAND }, async ($, e) => runCommand(portsOf($), opts, e.args))
315
316  on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
317    const data = {
318      tree: await read($, treeAtom),
319      selectedId: await read($, selectedAtom),
320      editingId: await read($, editingAtom),
321      sessionId: await $.session.id(),
322      pending: await read($, pendingAtom),
323      surface: e.surface,
324      ...(await contextData($, opts)),
325    }
326    return paneView($.ui.resolve(e), data, {
327      select: id => void selectNode($, id),
328      edit: id => void update($, editingAtom, () => id),
329      followUp: (parentId, question) => void followUp($, opts, parentId, question),
330      rewrite: (nodeId, question) => void rewrite($, opts, nodeId, question),
331      remove: nodeId => void confirmDelete(portsOf($), opts, nodeId),
332      addFact: text =>
333        void $.session.id().then(sessionId => editFacts($, facts => addFacts(facts, [{ id: crypto.randomUUID(), text, at: Date.now(), sessionId, source: 'manual' }]))),
334      removeFact: id => void editFacts($, facts => facts.filter(f => f.id !== id)),
335      // the card itself shows 統整中… and then the outcome (digestStatus)
336      refreshDigest: () => {
337        const p = portsOf($)
338        p.later(() => void digestNow(p, opts, true))
339      },
340    })
341  })
342}
343
hooks/commands.ts 209 lines
1// /sticky-note and its subcommands.
2// A command's `{ text }` is a transcript row the model also reads, so anything
3// long or private goes to $.ui.log / toast instead and the command returns {}.
4import type { CommandRunResult } from 'claude-code'
5
6import { addFacts, contextKey, readDigest, readFacts } from './context'
7import { calibrate, formatCalibration, listRecords, parseFeedback } from './feedback'
8import { notionProbe } from './notion'
9import { change, confirmDelete, digestNow, digestWords, dropReason, syncPull, syncPushAll, syncStatus, giveFeedback, projectKey, startNote, type Options } from './notes'
10import type { Ports } from './ports'
11import { setActive } from './tree'
12
13export const COMMAND = 'sticky-note'
14
15export const COMMAND_SPEC = {
16  name: COMMAND,
17  description: 'Sticky Notes: open/close the pane, or new | back | rm | timeout | provider | every | ctx | notion | feedback | calibrate | doctor',
18  argumentHint: '[new <問題> | back | provider claude|openai | every <n> | ctx [add <文字> | rm <n> | refresh] | feedback … | calibrate]',
19}
20
21const CHOICE_NAME = { main: '主線', new: '新的便利貼', followup: '追問' } as const
22
23/**
24 * /sn: the keyboard way to the pane. The status line cannot be clicked, a plugin
25 * button's hotkey works only while its site has the focus, and keybindings.json
26 * has no "run a command" action (PROBE.md), so a two-letter command is the shortcut.
27 * Takes the same subcommands as /sticky-note.
28 */
29export const SHORT_COMMAND = 'sn'
30
31export const SHORT_COMMAND_SPEC = {
32  name: SHORT_COMMAND,
33  description: 'Sticky Notes: open/close the pane (short for /sticky-note)',
34  argumentHint: '[new <問題> | back | provider claude|openai | every <n> | ctx …]',
35}
36
37const LATER: Record<string, string> = {
38  promote: 'M2',
39  outline: 'M3',
40  refresh: 'M3',
41  digest: 'M3',
42  export: 'M3',
43  mode: 'M4',
44  stats: 'M4',
45}
46
47export function parseArgs(args: string): { sub: string; rest: string } {
48  const m = /^\s*(\S*)\s*([\s\S]*)$/.exec(args)
49  return { sub: (m?.[1] ?? '').toLowerCase(), rest: (m?.[2] ?? '').trim() }
50}
51
52/** The args a /sticky-note new record keeps in the transcript (PROBE.md P10). */
53export const NEW_ARGS_MASK = 'new (sticky note)'
54
55/**
56 * Rewrites the transcript record of `/sticky-note new <問題>` so the question
57 * does not stay in the main context. Returns null when the text is not that record.
58 */
59export function maskNewArgs(text: string): string | null {
60  if (!text.includes(`<command-name>/${COMMAND}</command-name>`) && !text.includes(`<command-name>/${SHORT_COMMAND}</command-name>`)) return null
61  const re = /<command-args>\s*new\b[\s\S]*?<\/command-args>/
62  return re.test(text) ? text.replace(re, `<command-args>${NEW_ARGS_MASK}</command-args>`) : null
63}
64
65export async function runCommand(p: Ports, opts: Options, args: string): Promise<CommandRunResult> {
66  const { sub, rest } = parseArgs(args)
67  switch (sub) {
68    case '': {
69      if (await p.ui.isPaneOpen()) await p.ui.closePane()
70      else await p.ui.openPane()
71      return {}
72    }
73    case 'new': {
74      if (rest === '') return { text: '用法:/sticky-note new <問題>' }
75      await startNote(p, opts, {
76        question: rest,
77        attach: { kind: 'root' },
78        answerer: 'fork',
79        route: { label: 'sidebar_knowledge', confidence: 1, source: 'manual' },
80      })
81      p.ui.toast(dropReason(rest))
82      return {}
83    }
84    case 'rm': {
85      // the note the pane has open (its thread runs through it), as ✕ does
86      const id = await p.state.selected()
87      if (id === null || id === '__context__') return { text: '先在 pane 點開要刪的便利貼(或在問題旁按 ✕)' }
88      const n = await confirmDelete(p, opts, id)
89      return n > 0 ? {} : { text: '沒有刪除' }
90    }
91    case 'timeout': {
92      // seconds the Jev dialog waits before the prompt goes to the main line; 0 waits forever
93      if (rest === '') return { text: opts.askTimeout > 0 ? `對話框 ${opts.askTimeout} 秒沒回應就送進主線。調整:/sn timeout <秒>(0 = 一直等)` : '對話框會一直等到你回答。調整:/sn timeout <秒>' }
94      const n = Number(rest)
95      if (!Number.isInteger(n) || n < 0 || n > 600) return { text: '用法:/sn timeout <0–600 的整數秒數>(0 = 一直等)' }
96      const r = await p.setOption('askTimeout', n)
97      if (!r.ok) return { text: `沒有改成功:${r.reason}` }
98      opts.askTimeout = n
99      p.ui.toast(n > 0 ? `Sticky Notes:對話框 ${n} 秒沒回應就送進主線` : 'Sticky Notes:對話框會一直等')
100      return {}
101    }
102    case 'back': {
103      const sessionId = await p.sessionId()
104      await change(p, t => setActive(t, sessionId, null))
105      return {}
106    }
107    case 'feedback': {
108      const fb = parseFeedback(rest)
109      if (fb === null) return { text: '用法:/sn feedback main|new|followup(這句應該是什麼),或 good(現在這樣就對)' }
110      const record = await giveFeedback(p, fb)
111      p.ui.toast(record ? `已記下:上一句應該是 ${CHOICE_NAME[record.choice ?? 'main']}` : '這個 session 還沒有可以回饋的路由紀錄')
112      return {}
113    }
114    case 'notion': {
115      // /sn notion <collection://… or a database URL>: where the notes sync; /sn notion test: can the mod reach it
116      const [verb = ''] = rest.split(/\s+/)
117      if (verb === 'test') {
118        if (opts.notionDataSource === '') return { text: '還沒設定 Notion 資料庫:/sn notion <collection://…>' }
119        return { text: ['Notion 測試:', ...(await notionProbe(p, opts.notionDataSource))].join('\n') }
120      }
121      if (verb === 'pull' || verb === 'push') {
122        if (opts.notionDataSource === '') return { text: '還沒設定 Notion 資料庫:/sn notion <collection://…>' }
123        if (verb === 'pull') return { text: `Notion:${await syncPull(p, opts)}` }
124        const r = await syncPushAll(p, opts)
125        return { text: `Notion:上傳 ${r.pushed} 張${r.failed ? `,${r.failed} 張失敗(/sn notion 看原因)` : ''}` }
126      }
127      if (verb === '') {
128        if (opts.notionDataSource === '') return { text: '還沒設定 Notion 資料庫:/sn notion <collection://…>' }
129        return { text: `便利貼同步到:${opts.notionDataSource}\n上次:${(await syncStatus(p)) ?? '還沒同步過'}\n指令:/sn notion pull(下載)、/sn notion push(把這個專案還沒上傳的都上傳)、/sn notion test` }
130      }
131      if (!/^collection:\/\/[0-9a-f-]{32,36}$/.test(verb)) return { text: '用法:/sn notion <collection://…> | test | pull | push' }
132      const r = await p.setOption('notionDataSource', verb)
133      if (!r.ok) return { text: `沒有改成功:${r.reason}` }
134      opts.notionDataSource = verb
135      return { text: '已設定 Notion 資料庫。打 /sn notion test 確認 mod 連得到。' }
136    }
137    case 'doctor': {
138      for (const line of await p.keys.report()) p.ui.log(line)
139      return {}
140    }
141    case 'provider': {
142      // the summary layer: titles, summaries, the main digest (Claude subscription or OpenAI free tier)
143      const v = rest.toLowerCase()
144      if (v === '') return { text: `統整層目前用 ${opts.summaryProvider === 'openai' ? 'OpenAI' : 'Claude'}。切換:/sn provider claude 或 /sn provider openai` }
145      if (v !== 'claude' && v !== 'openai') return { text: '用法:/sn provider claude|openai' }
146      const r = await p.setOption('summaryProvider', v)
147      if (!r.ok) return { text: `沒有改成功:${r.reason}` }
148      opts.summaryProvider = v
149      p.ui.toast(`Sticky Notes:統整層改用 ${v === 'claude' ? 'Claude' : 'OpenAI'}`)
150      return {}
151    }
152    case 'every': {
153      // R4: the main-line digest and the project context every n main turns; 0 turns them off
154      if (rest === '') return { text: `目前${opts.digestEvery > 0 ? `每 ${opts.digestEvery} 回合背景統整一次` : '不做背景統整'}。調整:/sn every <回合數>(0 = 關閉)` }
155      const n = Number(rest)
156      if (!Number.isInteger(n) || n < 0 || n > 100) return { text: '用法:/sn every <0–100 的整數>(0 = 關閉)' }
157      const r = await p.setOption('digestEvery', n)
158      if (!r.ok) return { text: `沒有改成功:${r.reason}` }
159      opts.digestEvery = n
160      p.ui.toast(n > 0 ? `Sticky Notes:每 ${n} 回合背景統整一次` : 'Sticky Notes:背景統整已關閉')
161      return {}
162    }
163    case 'ctx': {
164      // R4: the project context (only ever added to by the summary layer) and this session's digest
165      const root = await projectKey(p)
166      const [verb = '', ...words] = rest.split(/\s+/)
167      const arg = words.join(' ').trim()
168      const facts = await readFacts(p.store, root)
169      if (verb === 'add') {
170        if (arg === '') return { text: '用法:/sn ctx add <一條專案脈絡>' }
171        const fact = { id: crypto.randomUUID(), text: [...arg].slice(0, 200).join(''), at: await p.now(), sessionId: await p.sessionId(), source: 'manual' as const }
172        await p.store.set(contextKey(root), addFacts(facts, [fact]))
173        await p.state.contextChanged()
174        p.ui.toast('Sticky Notes:已加入專案脈絡')
175        return {}
176      }
177      if (verb === 'rm') {
178        const i = Number(arg) - 1
179        if (!Number.isInteger(i) || i < 0 || i >= facts.length) return { text: `用法:/sn ctx rm <1–${facts.length}>` }
180        await p.store.set(contextKey(root), facts.filter((_, k) => k !== i))
181        await p.state.contextChanged()
182        p.ui.toast(`Sticky Notes:已刪除第 ${i + 1} 條`)
183        return {}
184      }
185      if (verb === 'refresh') {
186        p.ui.toast('Sticky Notes:背景統整中…(結果會顯示在 pane 的「專案脈絡」卡片)')
187        p.later(() => void digestNow(p, opts, true).then(r => p.ui.toast(`Sticky Notes:${digestWords(r)}`)))
188        return {}
189      }
190      if (verb !== '') return { text: '用法:/sn ctx [add <文字> | rm <n> | refresh]' }
191      // the list stays out of the transcript (a command's text is a row the model reads)
192      const digest = await readDigest(p.store, root, await p.sessionId())
193      p.ui.log(`主線摘要(這個 session):${digest?.text ?? '還沒有'}`)
194      if (facts.length === 0) p.ui.log('專案脈絡:還沒有。背景統整會自動加,或用 /sn ctx add <文字>')
195      facts.forEach((f, k) => p.ui.log(`${k + 1}. ${f.text}${f.source === 'manual' ? '(手動)' : ''}`))
196      return {}
197    }
198    case 'calibrate': {
199      const lines = formatCalibration(calibrate(await listRecords(p.store, await projectKey(p))))
200      for (const line of lines) p.ui.log(line)
201      return {}
202    }
203    default: {
204      const when = LATER[sub]
205      return { text: when ? `/sticky-note ${sub}:尚未實作(${when})` : `未知的子指令:${sub}` }
206    }
207  }
208}
209
hooks/notes.ts 615 lines
1// Orchestration between the hooks and the pure modules: where a prompt goes,
2// creating a note, answering it in the background, keeping the pane's state in
3// sync, and keeping the routing feedback records. Everything outside goes through Ports.
4import type { ModelEffort, PluginOptions } from 'claude-code'
5
6import type { AskChoice, FeedbackRecord, Tree, TreeNode } from '../types'
7import { answerSide } from './answer'
8import { digestDue, FACTS_FOR_JEV, lastExchanges, readDigest, readFacts, runDigest } from './context'
9import { titleAndSummary } from './digest'
10import { getRecord, listRecords, makeRecord, recordId, saveRecord, setChoice } from './feedback'
11import * as jev from './jev'
12import { markUnsynced, pullNotes, pushNote, type SyncPorts } from './notion'
13import type { Ports } from './ports'
14import { asEffort, claudeProvider } from './providers/claude'
15import { asContextMode, asReasoningEffort, openaiProvider, type OpenAIReasoningEffort } from './providers/openai'
16import { withFallback, type SummaryProvider } from './providers/types'
17import { askPrompt, choiceOf, decide, decideFromChoice, MAIN_LABEL, NEEDS_CTX_AT, pickPrompt, type Decision, type Suggested } from './route'
18import { addNode, removeNode, loadTree, migrateLegacy, mutateTree, normalizeRoot, sideHistory, updateNode, type Attach } from './tree'
19
20export type Options = {
21  routeThreshold: number
22  followupThreshold: number
23  summaryProvider: 'claude' | 'openai'
24  claudeModel: string
25  claudeEffort: ModelEffort
26  openaiModel: string
27  openaiReasoningEffort: OpenAIReasoningEffort
28  openaiContextMode: 'off' | 'redacted' | 'full'
29  autoOpenPane: boolean
30  /** R4: the main-line digest and the project context every this many main turns; 0 turns them off. */
31  digestEvery: number
32  /** The Notion data source the notes sync to (collection://…); '' turns the sync off. */
33  notionDataSource: string
34  /** Seconds the dialog waits before the prompt goes to the main line by itself; 0 waits forever. */
35  askTimeout: number
36}
37
38export function readOptions(o: PluginOptions): Options {
39  const num = (v: unknown, d: number) => (typeof v === 'number' && Number.isFinite(v) ? v : d)
40  const str = (v: unknown, d: string) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : d)
41  return {
42    routeThreshold: num(o.routeThreshold, 0.6),
43    followupThreshold: num(o.followupThreshold, 0.6),
44    summaryProvider: o.summaryProvider === 'openai' ? 'openai' : 'claude',
45    claudeModel: str(o.claudeModel, 'haiku'),
46    claudeEffort: asEffort(o.claudeEffort),
47    openaiModel: str(o.openaiModel, 'gpt-5-mini'),
48    openaiReasoningEffort: asReasoningEffort(o.openaiReasoningEffort),
49    openaiContextMode: asContextMode(o.openaiContextMode),
50    autoOpenPane: o.autoOpenPane !== false, // default on (the developer's pick, 10/07)
51    notionDataSource: typeof o.notionDataSource === 'string' ? o.notionDataSource.trim() : '',
52    askTimeout: Math.max(0, Math.floor(num(o.askTimeout, 30))), // 30 s (the developer, 10/14)
53    digestEvery: Math.max(0, Math.floor(num(o.digestEvery, 3))), // every 3 turns (the developer's pick, 10/14)
54  }
55}
56
57/** What /sn provider, /sn every and /sn notion set, kept per machine in $.store over the plugin settings. */
58export const OVERRIDABLE = ['summaryProvider', 'digestEvery', 'notionDataSource', 'askTimeout'] as const
59export const optionKey = (field: (typeof OVERRIDABLE)[number]) => 'option:' + field
60
61/** Puts this machine's own settings (optionKey) over the plugin's, in place. */
62export async function applyOptionOverrides(kv: { get(key: string): Promise<unknown> }, opts: Options): Promise<void> {
63  const provider = await kv.get(optionKey('summaryProvider'))
64  if (provider === 'claude' || provider === 'openai') opts.summaryProvider = provider
65  const every = await kv.get(optionKey('digestEvery'))
66  if (typeof every === 'number' && Number.isInteger(every) && every >= 0) opts.digestEvery = every
67  const notion = await kv.get(optionKey('notionDataSource'))
68  if (typeof notion === 'string') opts.notionDataSource = notion
69  const timeout = await kv.get(optionKey('askTimeout'))
70  if (typeof timeout === 'number' && Number.isInteger(timeout) && timeout >= 0) opts.askTimeout = timeout
71}
72
73/** The configured summary provider; openai without a key falls back to claude with one toast. */
74export function summaryProvider(p: Ports, opts: Options): SummaryProvider {
75  const log = (text: string) => p.ui.log(text, 'debug')
76  const claude = claudeProvider({ complete: p.complete, log }, { model: opts.claudeModel, effort: opts.claudeEffort })
77  if (opts.summaryProvider !== 'openai') return claude
78  const openai = openaiProvider(
79    { key: p.keys.openai, fetch: p.fetch, log },
80    { model: opts.openaiModel, contextMode: opts.openaiContextMode, reasoningEffort: opts.openaiReasoningEffort },
81  )
82  return withFallback(openai, claude, () => p.ui.toast('Sticky Notes:沒有 OPENAI_API_KEY,統整層改用 Claude'))
83}
84
85/** PLAN.md: the repo root (shared by every worktree), else the session root. */
86export async function projectKey(p: Ports): Promise<string> {
87  return normalizeRoot(await p.projectRoot())
88}
89
90export async function refresh(p: Ports): Promise<Tree> {
91  const tree = await loadTree(p.store, await projectKey(p))
92  await p.state.publishTree(tree)
93  return tree
94}
95
96/**
97 * The project_question bookmarks the mod kept until 10/12 (「這題在主線回答」): no answer,
98 * promoted at creation. The developer asked them gone (10/14); nothing makes them any more.
99 */
100export function isMainLineBookmark(n: TreeNode): boolean {
101  return n.promotedAt !== null && n.answer === '' && n.route.label === 'project_question' && n.children.length === 0
102}
103
104/** session.start: move a tree saved in the old one-key layout, drop the old bookmarks, then load. */
105export async function prepare(p: Ports): Promise<Tree> {
106  const root = await projectKey(p)
107  const moved = await migrateLegacy(p.store, root)
108  if (moved > 0) p.ui.log(`sticky-notes: moved ${moved} notes to the per-node store layout`, 'debug')
109  const tree = await loadTree(p.store, root)
110  const bookmarks = Object.values(tree.nodes).filter(isMainLineBookmark)
111  if (bookmarks.length > 0) {
112    await mutateTree(p.store, root, t => bookmarks.reduce((acc, n) => removeNode(acc, n.id), t))
113    p.ui.log(`sticky-notes: removed ${bookmarks.length} old 在主線回答 bookmarks`, 'debug')
114  }
115  // notes made before the card showed Jev's call: it is in their feedback record
116  const unknown = Object.values(tree.nodes).filter(n => n.route.jev === undefined && n.route.source !== 'manual')
117  if (unknown.length > 0) {
118    const byNode = new Map<string, string>()
119    for (const r of await listRecords(p.store, root)) if (r.nodeId) byNode.set(r.nodeId, r.jev.route)
120    const found = unknown.filter(n => byNode.has(n.id))
121    if (found.length > 0) {
122      await mutateTree(p.store, root, t => {
123        const nodes = { ...t.nodes }
124        for (const n of found) if (nodes[n.id]) nodes[n.id] = { ...nodes[n.id]!, route: { ...nodes[n.id]!.route, jev: byNode.get(n.id) } }
125        return { ...t, nodes }
126      })
127    }
128  }
129  return refresh(p)
130}
131
132export async function change(p: Ports, fn: (t: Tree) => Tree): Promise<Tree> {
133  const tree = await mutateTree(p.store, await projectKey(p), fn)
134  await p.state.publishTree(tree)
135  return tree
136}
137
138export function snippet(s: string, n: number): string {
139  const cps = [...s.replace(/\s+/g, ' ').trim()]
140  return cps.length > n ? cps.slice(0, n).join('') + '…' : cps.join('')
141}
142
143/** How much of the question the drop card quotes, and of the answer the log line previews (the developer: keep them short). */
144export const QUESTION_CHARS = 24
145export const PREVIEW_CHARS = 40
146
147/** Markdown flattened to one plain line (headings, emphasis, code, tables, list marks dropped), first n characters. */
148export function plainPreview(md: string, n: number): string {
149  const text = md
150    .replace(/```[\s\S]*?(```|$)/g, ' ')
151    .replace(/^\s*\|?[\s:|-]+\|[\s:|-]*$/gm, ' ') // table rules
152    .replace(/^\s{0,3}(#{1,6}|[-*+]|\d+\.)\s+/gm, '')
153    .replace(/[*_`|>#]+/g, ' ')
154    .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
155  return snippet(text, n)
156}
157
158/** The drop reason is the transparency line (PLAN.md / PROBE.md P2). */
159export function dropReason(question: string): string {
160  return `cc-sticky-note:便利貼「${snippet(question, QUESTION_CHARS)}」`
161}
162
163/**
164 * The reason under the desktop's own "A hook blocked your prompt" card (the card
165 * is the app's; the reason is ours): where the note went. Every note comes from
166 * the user's pick now, so there is no "Jev decided" wording.
167 */
168export function explainDrop(question: string, routed: Routed): string {
169  const where =
170    routed.decision.kind === 'sidebar' && routed.decision.attach === 'followup' && routed.parentTitle !== null
171      ? `接在「${routed.parentTitle}」下`
172      : '新的便利貼'
173  return `cc-sticky-note:${where}「${snippet(question, QUESTION_CHARS)}」`
174}
175
176/**
177 * A user message the person typed: not a slash-command record or caveat
178 * (`<command-name>…`, `<local-command-…>`), which $.session.messages() also lists.
179 */
180export function isTypedPrompt(m: { role: string; text: string }): boolean {
181  if (m.role !== 'user') return false
182  const t = m.text.trimStart()
183  return t !== '' && !/^<(command-|local-command-|system-reminder)/.test(t)
184}
185
186/** How many recent notes Jev is asked about (`continues`): enough to find the one, few enough to stay accurate. */
187export const CANDIDATES = 8
188
189/** The notes Jev may say a prompt continues: this session's activeThread first, then the newest. */
190export function recentNotes(tree: Tree, activeId: string | null, n = CANDIDATES): TreeNode[] {
191  const active = activeId ? tree.nodes[activeId] : undefined
192  const rest = Object.values(tree.nodes)
193    .filter(x => x.id !== active?.id)
194    .sort((a, b) => b.anchor.at - a.anchor.at)
195  return (active ? [active, ...rest] : rest).slice(0, n)
196}
197
198/**
199 * A note by a keyword typed under the dialog's "Other": the newest whose title
200 * or question holds it (brackets and case ignored), or whose title it holds.
201 */
202export function findNote(tree: Tree, typed: string): TreeNode | null {
203  const k = typed.replace(/[「」『』"']/g, '').trim().toLowerCase()
204  if (k === '') return null
205  const hits = Object.values(tree.nodes).filter(n => {
206    const title = n.title.toLowerCase()
207    return title.includes(k) || n.question.toLowerCase().includes(k) || ([...title].length >= 2 && k.includes(title))
208  })
209  return hits.sort((a, b) => b.anchor.at - a.anchor.at)[0] ?? null
210}
211
212/** Jev input from the session's own transcript (PLAN.md: raw 300-char clips until M4). */
213export async function jevInput(p: Ports, tree: Tree, sessionId: string, prompt: string, candidates: jev.Candidate[] = []): Promise<jev.JevInput> {
214  const list = await p.messages()
215  const active = tree.activeThread[sessionId] ?? null
216  const node = active ? tree.nodes[active] : undefined
217  const turns = await p.turns()
218  const at = await p.state.turnsAtLastSidebar()
219  const root = await projectKey(p)
220  return {
221    digest: (await readDigest(p.store, root, sessionId))?.text ?? null,
222    facts: (await readFacts(p.store, root)).slice(-FACTS_FOR_JEV).map(f => f.text),
223    recentUser: list.filter(isTypedPrompt).map(m => m.text).slice(-3),
224    lastAssistant: list.filter(m => m.role === 'assistant' && m.text !== '').at(-1)?.text ?? null,
225    activeTitle: node?.title ?? null,
226    activeLastQuestion: node?.question ?? null,
227    mainTurnsSinceLastSidebar: Math.max(0, turns - at),
228    prompt,
229    tags: tree.tags,
230    candidates,
231  }
232}
233
234export type Routed = {
235  decision: Decision
236  verdict: jev.JevVerdict | null
237  /** Whether the dialog was shown. */
238  asked: boolean
239  /** The user's pick in the dialogs; null when not asked, dismissed, or free text that found no note. */
240  choice: AskChoice | null
241  /** Title of the note a follow-up goes under; null otherwise. */
242  parentTitle: string | null
243}
244
245/**
246 * The note the dialog offers first: the one Jev says the prompt continues, else
247 * this session's activeThread (how likely: is_followup); none without either.
248 */
249function suggestionOf(verdict: jev.JevVerdict, keyed: readonly { key: string; node: TreeNode }[], active: TreeNode | undefined): Suggested | null {
250  const c = verdict.continues
251  const hit = c && c.label !== jev.NO_NOTE ? keyed.find(k => k.key === c.label) : undefined
252  if (hit && c) return { id: hit.node.id, title: hit.node.title, likely: c.confidence }
253  return active ? { id: active.id, title: active.title, likely: verdict.isFollowup } : null
254}
255
256/** The notes for the second dialog: all but the suggested one, likeliest first by Jev, then newest. */
257function othersOf(verdict: jev.JevVerdict, keyed: readonly { key: string; node: TreeNode }[], suggested: Suggested | null): TreeNode[] {
258  const prob = verdict.continues?.probabilities ?? {}
259  return keyed
260    .filter(k => k.node.id !== suggested?.id)
261    .map((k, i) => ({ node: k.node, score: prob[k.key] ?? 0, i }))
262    .sort((a, b) => b.score - a.score || a.i - b.i)
263    .map(x => x.node)
264}
265
266/** What the dialog race answers when askTimeout passed first (no label can be this). */
267const TIMED_OUT = '\u0000timed-out'
268
269/**
270 * Jev, then the decision table (route.ts). Jev never makes a note by itself:
271 * a confident main_task goes through, anything that might be a note asks.
272 * No Jev (no key, an error) → main line, no dialog. A Remote Control (bridge)
273 * prompt never gets the dialog: where it would ask, it goes to the main line.
274 *
275 * The dialog offers the note Jev says the prompt continues (else the activeThread);
276 * 〔接在其他便利貼下…〕 opens a second dialog of the other recent notes. In either,
277 * text typed under "Other" is a keyword for the note (findNote); none found, the
278 * prompt goes to the main line and a toast says so.
279 */
280export async function routePrompt(p: Ports, opts: Options, prompt: string, via: { remote?: boolean } = {}): Promise<Routed> {
281  const sessionId = await p.sessionId()
282  const tree = await refresh(p)
283  const activeId = tree.activeThread[sessionId] ?? null
284  const active = activeId === null ? undefined : tree.nodes[activeId]
285  const keyed = recentNotes(tree, activeId).map((node, i) => ({ key: `n${i + 1}`, node }))
286  const candidates = keyed.map(k => ({ key: k.key, title: k.node.title, question: k.node.question }))
287  const none = { asked: false, choice: null, parentTitle: null }
288  const r = await jev.classify({ key: await p.keys.typesafe(), fetch: p.fetch, now: p.now }, await jevInput(p, tree, sessionId, prompt, candidates))
289  if (!r.ok) {
290    if (r.reason !== 'no-key') p.ui.log(`sticky-notes: Jev unavailable (${r.reason}${r.status ? ` ${r.status}` : ''}); main line`, 'debug')
291    return { decision: { kind: 'main' }, verdict: null, ...none }
292  }
293  const verdict = r.verdict
294  const decision = decide(verdict, { route: opts.routeThreshold, followup: opts.followupThreshold })
295  if (decision.kind !== 'ask') return { decision, verdict, ...none }
296  if (via.remote) return { decision: { kind: 'main' }, verdict, ...none }
297
298  const suggested = suggestionOf(verdict, keyed, active)
299  const others = othersOf(verdict, keyed, suggested)
300  const dialog = askPrompt(verdict, { suggested, hasOthers: others.length > 0, followupThreshold: opts.followupThreshold })
301  /**
302   * The dialog, raced by askTimeout: unanswered by then, the prompt goes to the main line
303   * (TIMED_OUT). A mod cannot take an asked dialog down, so it stays on screen; a pick
304   * made in it afterwards changes nothing and says so.
305   */
306  const ask = async (question: string, labels: string[]): Promise<string> => {
307    const asked = p.ui.ask(question, labels, 'Sticky Notes')
308    if (opts.askTimeout <= 0) return asked
309    let late = false
310    const timer = p.sleep(opts.askTimeout * 1000).then(() => ((late = true), TIMED_OUT))
311    asked.then(
312      a => void (late && labels.includes(a) && a !== MAIN_LABEL && p.ui.toast('Sticky Notes:這句已經逾時送進主線了,這次的選擇沒有作用')),
313      () => {},
314    )
315    const first = await Promise.race([asked, timer])
316    if (first === TIMED_OUT) p.ui.toast(`Sticky Notes:${opts.askTimeout} 秒沒有回應,這句送進主線`)
317    return first
318  }
319  type Got = { choice: AskChoice | null; parent: TreeNode | null }
320  /** Free text under "Other": the note it names, or the main line with a toast. */
321  const byKeyword = (typed: string): Got => {
322    const hit = findNote(tree, typed)
323    if (hit === null) p.ui.toast(`Sticky Notes:找不到「${[...typed].slice(0, 20).join('')}」的便利貼,這句送進主線`)
324    return { choice: hit ? 'followup' : null, parent: hit }
325  }
326  try {
327    const answer = await ask(dialog.question, dialog.options.map(o => o.label))
328    if (answer === TIMED_OUT) return { decision: { kind: 'main' }, verdict, ...none, asked: true }
329    const picked = choiceOf(dialog, answer)
330    let got: Got
331    if (picked === 'pick') {
332      const second = pickPrompt(others)
333      const a2 = await ask(second.question, second.options.map(o => o.label))
334      if (a2 === TIMED_OUT) return { decision: { kind: 'main' }, verdict, ...none, asked: true }
335      const opt = second.options.find(o => o.label === a2)
336      got = opt === undefined ? byKeyword(a2) : opt.id === null ? { choice: 'main', parent: null } : { choice: 'followup', parent: tree.nodes[opt.id] ?? null }
337    } else if (picked === null) got = byKeyword(answer)
338    else got = { choice: picked, parent: picked === 'followup' && suggested ? (tree.nodes[suggested.id] ?? null) : null }
339    return {
340      decision: decideFromChoice(got.choice, verdict, tree.tags.length, got.parent?.id),
341      verdict,
342      asked: true,
343      choice: got.choice,
344      parentTitle: got.parent?.title ?? null,
345    }
346  } catch {
347    // dismissed, or headless (-p): never swallow the user's input
348    return { decision: { kind: 'main' }, verdict, ...none, asked: true }
349  }
350}
351
352/**
353 * R4: one digest run for this session (context.ts), through the summary provider.
354 * `force` runs it whatever digestEvery says (/sn ctx refresh).
355 */
356export async function digestNow(p: Ports, opts: Options, force = false): Promise<string> {
357  const root = await projectKey(p)
358  const sessionId = await p.sessionId()
359  const turns = await p.turns()
360  if (!force && !digestDue(opts.digestEvery, turns, await readDigest(p.store, root, sessionId))) return 'not due'
361  // the context card shows the run: 統整中… now, then how it ended (DIGEST_WORDS)
362  await p.state.setDigestStatus(true, null)
363  let out = 'error'
364  try {
365    const r = await runDigest(
366      { kv: p.store, provider: summaryProvider(p, opts), root, sessionId, turns, now: await p.now(), newId: () => crypto.randomUUID(), every: opts.digestEvery || 3 },
367      lastExchanges(await p.messages(), isTypedPrompt),
368    )
369    if (!r.ok) {
370      p.ui.log(`sticky-notes: main digest skipped (${r.reason})`, 'debug')
371      out = r.reason
372    } else out = r.added > 0 ? `digest written, ${r.added} new fact(s)` : 'digest written'
373  } catch (err) {
374    out = `error ${String(err).slice(0, 120)}`
375  } finally {
376    await p.state.setDigestStatus(false, digestWords(out))
377    await p.state.contextChanged()
378  }
379  return out
380}
381
382/** A digest run's outcome in the card's words. */
383export function digestWords(out: string): string {
384  const added = /^digest written, (\d+) new fact/.exec(out)
385  if (added) return `完成,新增 ${added[1]} 條脈絡`
386  if (out === 'digest written') return '完成,沒有新的脈絡'
387  if (out === 'no exchanges') return '沒有統整:主線還沒有對話'
388  if (out === 'malformed answer') return '沒有統整:統整層的回答格式不對'
389  return `沒有統整:${out}`
390}
391
392/** What a routed prompt became, in the record's words. */
393export function outcomeOf(d: Decision): FeedbackRecord['outcome'] {
394  if (d.kind === 'project_question') return 'project_question'
395  if (d.kind === 'sidebar') return d.attach === 'followup' ? 'followup' : 'new'
396  return 'main'
397}
398
399/**
400 * Keeps one feedback record (Jev's call, its confidence, the user's choice) at
401 * feedback:<root>:<id>. Prompts Jev never saw (no key) are not kept.
402 */
403export async function recordFeedback(p: Ports, opts: Options, prompt: string, routed: Routed, nodeId: string | null): Promise<string | null> {
404  if (routed.verdict === null) return null
405  const at = await p.now()
406  const id = recordId(at, crypto.randomUUID())
407  await saveRecord(
408    p.store,
409    await projectKey(p),
410    makeRecord({
411      id,
412      at,
413      sessionId: await p.sessionId(),
414      prompt,
415      verdict: routed.verdict,
416      thresholds: { route: opts.routeThreshold, followup: opts.followupThreshold, needsCtx: NEEDS_CTX_AT },
417      asked: routed.asked,
418      outcome: outcomeOf(routed.decision),
419      choice: routed.choice,
420      nodeId,
421    }),
422  )
423  await p.state.setLastSampleId(id)
424  return id
425}
426
427/**
428 * /sn feedback: the user's choice for this session's last record, said afterwards.
429 * `good` keeps what happened (a project question counts as the main line).
430 */
431export async function giveFeedback(p: Ports, fb: { choice: AskChoice } | { good: true }): Promise<FeedbackRecord | null> {
432  const id = await p.state.lastSampleId()
433  if (id === null) return null
434  const root = await projectKey(p)
435  if ('choice' in fb) return setChoice(p.store, root, id, fb.choice)
436  const record = await getRecord(p.store, root, id)
437  if (record === null) return null
438  return setChoice(p.store, root, id, record.outcome === 'project_question' ? 'main' : record.outcome)
439}
440
441export type NoteRequest = {
442  question: string
443  attach: Attach
444  answerer: 'fork' | 'summary-provider'
445  route: { label: string; confidence: number; source: 'jev' | 'ask' | 'manual'; jev?: string }
446  tag?: string
447}
448
449async function anchorFor(p: Ports) {
450  const sessionId = await p.sessionId()
451  const lastUser = (await p.messages()).filter(isTypedPrompt).at(-1)?.text ?? ''
452  return {
453    sessionId,
454    turnId: await p.state.lastTurnId(),
455    messageId: await p.state.lastPromptUuid(),
456    at: await p.now(),
457    mainSnippet: [...lastUser].slice(0, 120).join(''),
458  }
459}
460
461/**
462 * Writes the node now (answer pending) and answers it in the background.
463 * The caller drops the prompt with dropReason() as the visible line.
464 */
465export async function startNote(p: Ports, opts: Options, req: NoteRequest): Promise<string> {
466  const anchor = await anchorFor(p)
467  const id = crypto.randomUUID()
468  await change(p, t =>
469    addNode(
470      t,
471      anchor.sessionId,
472      {
473        id,
474        question: req.question,
475        anchor,
476        route: req.route,
477        answeredBy: req.answerer === 'fork' ? 'claude-fork' : opts.summaryProvider,
478        // the tag is the topic's: on a first question only (answerNote names one when Jev gave none)
479        tags: req.tag && req.attach.kind === 'root' ? [req.tag] : [],
480      },
481      req.attach,
482    ).tree,
483  )
484  await p.state.setTurnsAtLastSidebar(await p.turns())
485  await p.state.addPending(1)
486  // the pane follows the newest note of this session (its answer shows as it arrives)
487  await p.state.setSelected(id)
488
489  // Answered outside the prompt.submit dispatch (PROBE.md: works, and the
490  // drop line shows at once instead of after the 1–3 s fork). Nothing may
491  // escape a background job: a failure marks the note and says so.
492  p.later(() => {
493    answerNote(p, opts, id, req).catch(async (err: unknown) => {
494      p.ui.log(`sticky-notes: answering failed: ${String(err).slice(0, 200)}`, 'debug')
495      p.ui.toast('Sticky Notes:回答失敗')
496      await change(p, t => updateNode(t, id, { answer: '_(回答失敗)_' })).catch(() => {})
497    })
498  })
499  return id
500}
501
502export async function answerNote(p: Ports, opts: Options, id: string, req: NoteRequest): Promise<void> {
503  const provider = summaryProvider(p, opts)
504  try {
505    const tree = await refresh(p)
506    const history = sideHistory(tree, tree.nodes[id]?.parentId ?? null)
507    const a = await answerSide(p.fork, { question: req.question, history, answerer: req.answerer }, provider)
508    if (!a.ok) {
509      await change(p, t => updateNode(t, id, { answer: `_(沒有答案:${a.reason})_` }))
510      p.ui.toast(`Sticky Notes:回答失敗(${a.reason})`)
511      return
512    }
513    await change(p, t => updateNode(t, id, { answer: a.text, answeredBy: a.answeredBy }))
514    const ts = await titleAndSummary(provider, req.question, a.text)
515    await change(p, t => updateNode(t, id, { title: ts.title, summary: ts.summary }))
516    await p.state.addUnread(1)
517    // M1 (PLAN.md): the answer is shown with $.ui.log — a dim transcript line the model never reads.
518    // $.ui.log is plain text (no Markdown): one clean line here, the rendered answer in the pane.
519    p.ui.log(`cc-sticky-note ${ts.title}:${plainPreview(ts.summary ?? a.text, PREVIEW_CHARS)} /sn 看完整答案`)
520    p.ui.toast(`cc-sticky-note ${ts.title}`)
521    if (opts.autoOpenPane) await p.ui.openPane()
522    // the answered note goes to Notion for the other computers, in the background
523    if (opts.notionDataSource !== '') p.later(() => void syncPush(p, opts, id))
524  } finally {
525    await p.state.addPending(-1)
526  }
527}
528
529const syncPorts = (p: Ports): SyncPorts => ({ ...p, projectKey: () => projectKey(p) })
530const syncStatusKey = async (p: Ports) => `notion-status:${await projectKey(p)}`
531
532/**
533 * Deletes a note and the follow-ups under it, here only (the developer, 10/14). Their
534 * Notion rows, if any, are marked 不同步 so no other computer pulls them from now on;
535 * the notion:<root>:<id> keys stay, so this computer never pulls them back either.
536 */
537export async function deleteNote(p: Ports, opts: Options, id: string): Promise<number> {
538  const before = await refresh(p)
539  if (!before.nodes[id]) return 0
540  const gone: string[] = []
541  const walk = (nid: string) => {
542    gone.push(nid)
543    for (const c of before.nodes[nid]?.children ?? []) walk(c)
544  }
545  walk(id)
546  const parent = before.nodes[id]!.parentId
547  await change(p, t => removeNode(t, id))
548  const selected = await p.state.selected()
549  if (selected !== null && gone.includes(selected)) await p.state.setSelected(parent)
550  if (opts.notionDataSource !== '') p.later(() => void markUnsynced(syncPorts(p), opts.notionDataSource, gone))
551  return gone.length
552}
553
554/** ✕ and /sn rm: the dialog first (how much goes), then deleteNote. Dismissed, nothing goes. */
555export async function confirmDelete(p: Ports, opts: Options, id: string): Promise<number> {
556  const tree = await refresh(p)
557  const node = tree.nodes[id]
558  if (!node) return 0
559  let below = 0
560  const count = (nid: string) => (tree.nodes[nid]?.children ?? []).forEach(c => (below++, count(c)))
561  count(id)
562  const what = `「${node.title}」${below > 0 ? `和它底下 ${below} 則追問` : ''}`
563  try {
564    const a = await p.ui.ask(`刪除${what}?只刪這台電腦的,Notion 上會標成不同步。`, ['刪除', '取消'], 'Sticky Notes')
565    if (a !== '刪除') return 0
566  } catch {
567    return 0
568  }
569  const n = await deleteNote(p, opts, id)
570  p.ui.toast(`Sticky Notes:已刪除${what}`)
571  return n
572}
573
574/** One note to Notion; how it went is kept for /sn notion. */
575export async function syncPush(p: Ports, opts: Options, id: string): Promise<string> {
576  const node = (await refresh(p)).nodes[id]
577  if (!node) return 'gone'
578  const r = await pushNote(syncPorts(p), opts.notionDataSource, node)
579  if (r !== 'pushed' && r !== 'skipped') {
580    p.ui.log(`sticky-notes: Notion push failed (${r})`, 'debug')
581    await p.store.set(await syncStatusKey(p), `上傳失敗:${r}`)
582  }
583  return r
584}
585
586/** /sn notion push: every answered note of this project not yet in Notion. */
587export async function syncPushAll(p: Ports, opts: Options): Promise<{ pushed: number; failed: number }> {
588  const tree = await refresh(p)
589  let pushed = 0
590  let failed = 0
591  for (const node of Object.values(tree.nodes).sort((a, b) => a.anchor.at - b.anchor.at)) {
592    const r = await pushNote(syncPorts(p), opts.notionDataSource, node)
593    if (r === 'pushed') pushed++
594    else if (r !== 'skipped') failed++
595  }
596  await p.store.set(await syncStatusKey(p), `上傳 ${pushed} 張${failed ? `,${failed} 張失敗` : ''}(${new Date(await p.now()).toLocaleString()})`)
597  return { pushed, failed }
598}
599
600/** The other computers' notes of this project into the tree; a toast when any came. */
601export async function syncPull(p: Ports, opts: Options): Promise<string> {
602  const r = await pullNotes(syncPorts(p), opts.notionDataSource, fn => change(p, fn), await refresh(p))
603  const text = 'error' in r ? `下載失敗:${r.error}` : `下載 ${r.added} 張`
604  await p.store.set(await syncStatusKey(p), `${text}(${new Date(await p.now()).toLocaleString()})`)
605  if ('error' in r) p.ui.log(`sticky-notes: Notion pull failed (${r.error})`, 'debug')
606  else if (r.added > 0) p.ui.toast(`Sticky Notes:從其他電腦同步了 ${r.added} 張便利貼`)
607  return text
608}
609
610/** The last sync's outcome, for /sn notion. */
611export async function syncStatus(p: Ports): Promise<string | null> {
612  const s = await p.store.get(await syncStatusKey(p))
613  return typeof s === 'string' ? s : null
614}
615
hooks/pane.tsx 371 lines
1// The Sticky Notes pane: one card per topic (a root and all its follow-ups), the design
2// the developer settled with the card prototype (PROBE.md〇之六). Pure view: register.tsx
3// reads the state and hands in the surface's element table and the handlers.
4//
5//  Sticky Notes                                3 張 · 1 回答中
6//  ╭──────────────────────────────────────────────────╮   closed: one line, one press
7//  │ TCP 背壓 10/07 11:01                             │
8//  ╰──────────────────────────────────────────────────╯
9//  ╭──────────────────────────────────────────────────╮   open: the thread as a conversation,
10//  │ 樹載入原因               [知識旁問] 10/07 10:41 · 3 │   no Q/A words — the question is a
11//  │              ✎ ╭ 為什麼載入便利貼樹要讀… ╮       │   prompt bubble on the right (✎ under
12//  │ <answer>                                         │   the pointer rewrites it), the answer
13//  │ ● 為何全讀節點   ○ 存成一個 JSON                   │   under it; several follow-ups: pick
14//  │              ✎ ╭ 沒看懂,為什麼需要讀取… ╮       │   which one the thread continues by
15//  │ <answer>                                         │
16//  │ [回覆…        ] [↵]                              │   the reply follows up the last answer
17//  ╰──────────────────────────────────────────────────╯
18// The card this session follows up has a green border; every other is plain gray.
19import type { ElementTable, RenderElement, RenderSurface } from 'claude-code'
20
21import type { Tree, TreeNode } from '../types'
22import { ROUTE_NAME } from './route'
23import { pathTo, rootOf } from './tree'
24
25export const PANE_ID = 'sticky'
26export const PANE_TITLE = 'Sticky Notes'
27/** The selection that opens the project-context card (R4) instead of a topic. */
28export const CONTEXT_CARD = '__context__'
29
30/** P9: an answer that did not come from the fork had no project context. */
31export function contextMark(n: TreeNode): string {
32  return n.answeredBy === 'claude-fork' || n.answer === '' ? '' : '無專案脈絡'
33}
34
35const pad2 = (n: number) => String(n).padStart(2, '0')
36const when = (at: number) => {
37  const d = new Date(at)
38  return `${pad2(d.getMonth() + 1)}/${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
39}
40const clip = (s: string, n: number) => {
41  const cps = [...s.replace(/\s+/g, ' ').trim()]
42  return cps.length > n ? cps.slice(0, n).join('') + '…' : cps.join('')
43}
44const countAll = (tree: Tree, id: string): number => (tree.nodes[id]?.children ?? []).reduce((s, c) => s + 1 + countAll(tree, c), 0)
45
46/**
47 * A Text or Markdown holds at most 10000 characters, or the whole pane is refused
48 * and the engine draws its own (seen with an 11,810-character pasted question).
49 */
50export const QUESTION_SHOWN = 300
51export const ANSWER_SHOWN = 9000
52/**
53 * One drawing holds 100,000 characters in all: an open thread draws its answers whole
54 * from the newest back while this many remain, and the older ones as their summary.
55 */
56export const THREAD_BUDGET = 60000
57
58/** The question as the bubble shows it: one line, its first 300 characters, and the full length when cut. */
59export function shownQuestion(q: string): string {
60  const n = [...q].length
61  return n > QUESTION_SHOWN ? `${clip(q, QUESTION_SHOWN)}(共 ${n} 字)` : clip(q, QUESTION_SHOWN)
62}
63
64/** The answer as the card shows it: whole up to 9000 characters, newlines kept. */
65export function shownAnswer(a: string): string {
66  const cps = [...a]
67  return cps.length > ANSWER_SHOWN ? `${cps.slice(0, ANSWER_SHOWN).join('')}\n\n_(答案共 ${cps.length} 字,只顯示前 ${ANSWER_SHOWN} 字)_` : a
68}
69
70/** What a turn's answer area says: the answer, or why there is none yet. */
71function answerText(n: TreeNode, whole: boolean): string {
72  if (n.answer === '') return n.promotedAt !== null ? '_這題在主線回答。_' : '_回答中…_'
73  return whole ? shownAnswer(n.answer) : `${clip(n.summary ?? n.answer, 200)} _(較早的回答只顯示摘要)_`
74}
75
76/**
77 * The thread an open card reads: root → … → the picked note, then on down by the
78 * follow-up this session follows up, else the newest, until a note has none.
79 */
80export function threadOf(tree: Tree, pickedId: string, activeId: string | null): TreeNode[] {
81  const path = pathTo(tree, pickedId)
82  const onActive = activeId && tree.nodes[activeId] ? new Set(pathTo(tree, activeId).map(n => n.id)) : new Set<string>()
83  let cur = path.at(-1)
84  while (cur && cur.children.length > 0) {
85    const next = cur.children.find(c => onActive.has(c)) ?? cur.children.at(-1)!
86    cur = tree.nodes[next]
87    if (cur) path.push(cur)
88  }
89  return path
90}
91
92export type PaneData = {
93  tree: Tree | null
94  /** The note whose card is open (its thread runs through it); null, every card closed. */
95  selectedId: string | null
96  /** The question being rewritten in place, if any. */
97  editingId: string | null
98  sessionId: string
99  pending: number
100  surface: RenderSurface
101  /** R4: this session's main-line digest, the project facts, and how they are kept. */
102  digest: string | null
103  facts: readonly { id: string; text: string; source: 'auto' | 'manual' }[]
104  digestEvery: number
105  provider: 'claude' | 'openai'
106  /** The last digest run of this session: running, or when it ended and how (in words). */
107  digestStatus: { running: boolean; at: number | null; result: string | null }
108}
109
110export type PaneActions = {
111  /** Opens the card holding this note, its thread running through it; null closes. */
112  select(id: string | null): void
113  /** Starts (an id) or ends (null) rewriting a question in place. */
114  edit(id: string | null): void
115  /** The reply box: a follow-up under this note, not routed through Jev. */
116  followUp(parentId: string, question: string): void
117  /** A rewritten question: asked again beside the old one (a new topic for a first question). */
118  rewrite(nodeId: string, question: string): void
119  /** ✕: asks, then deletes this note and the follow-ups under it (this computer only). */
120  remove(nodeId: string): void
121  /** R4: the project context card's own edits, and a digest run now. */
122  addFact(text: string): void
123  removeFact(id: string): void
124  refreshDigest(): void
125}
126
127/**
128 * The card's category: what Jev called the first question (the developer, 10/14), in the
129 * dialog's words. Translucent backgrounds, legible on the dark theme and the light one.
130 */
131export const CATEGORY: Record<string, { name: string; color: string }> = {
132  sidebar_knowledge: { name: ROUTE_NAME.sidebar_knowledge, color: '#378ADD40' },
133  project_question: { name: ROUTE_NAME.project_question, color: '#1D9E7540' },
134  main_task: { name: ROUTE_NAME.main_task, color: '#BA751740' },
135}
136
137/** The category as a chip: its own background on Desktop; the terminal has no translucency, so it is dim. */
138function categoryChip(els: ElementTable, surface: RenderSurface, key: string, jev: string | undefined): RenderElement | null {
139  const { Text } = els
140  const c = jev ? CATEGORY[jev] : undefined
141  if (!c) return null
142  return surface === 'terminal' ? (
143    <Text key={key} dimColor>{`[${c.name}]`}</Text>
144  ) : (
145    <Text key={key} backgroundColor={c.color}>{` ${c.name} `}</Text>
146  )
147}
148
149/**
150 * The question drawn as the person's own prompt: Desktop's bubble look, on the right,
151 * with ✎ (ask again) and ✕ (delete) beside it while the pointer is over the row (a Box cannot be pressed, and a
152 * Button draws one clipped line, so the bubble itself is not the press). The terminal
153 * has no pointer to reveal it: there ✎ is always drawn.
154 */
155function bubble(els: ElementTable, surface: RenderSurface, node: TreeNode, act: PaneActions): RenderElement {
156  const { Box, Text, Button } = els
157  const look =
158    surface === 'terminal'
159      ? { borderStyle: 'round', borderDimColor: true }
160      : // translucent gray: reads as the prompt bubble on the dark theme and on the light one
161        { borderStyle: 'round', borderColor: '#80808040', backgroundColor: '#8080801f' }
162  return (
163    <Box key={`q:${node.id}`} alignSelf="flex-end" flexDirection="row" alignItems="center" columnGap={1} marginLeft={6} hover={{}}>
164      <Box {...(surface === 'terminal' ? {} : { display: 'none' as const, hover: { display: 'flex' as const } })}>
165        <Button key={`edit:${node.id}`} plain dimColor label="✎" onPress={() => act.edit(node.id)} />
166        <Button key={`remove:${node.id}`} plain dimColor label="✕" onPress={() => act.remove(node.id)} />
167      </Box>
168      <Box paddingX={1} {...look}>
169        <Text>{shownQuestion(node.question)}</Text>
170      </Box>
171    </Box>
172  )
173}
174
175/** ✎: the question in a field, to be asked again beside the old one. */
176function editor(els: ElementTable, node: TreeNode, act: PaneActions): RenderElement | null {
177  const { Box, Button } = els
178  const Input = 'Input' in els ? els.Input : undefined
179  if (!Input) return null
180  return (
181    <Box key={`editing:${node.id}`} flexDirection="column" alignItems="flex-end" gap={1}>
182      <Input
183        key={`edit-box:${node.id}`}
184        value={node.question}
185        submitLabel="↵"
186        onSubmit={v => {
187          act.edit(null)
188          if (v.trim() !== '' && v.trim() !== node.question.trim()) act.rewrite(node.id, v.trim())
189        }}
190      />
191      <Button key={`edit-cancel:${node.id}`} plain dimColor label="取消" onPress={() => act.edit(null)} />
192    </Box>
193  )
194}
195
196/**
197 * R4: the project context card, last in the pane. Closed, one line; open, this session's
198 * main-line digest, the facts (✕ deletes one), a box to add one, and a run now.
199 */
200function contextCard(els: ElementTable, d: PaneData, act: PaneActions): RenderElement {
201  const { Box, Text, Button } = els
202  const Input = 'Input' in els ? els.Input : undefined
203  const open = d.selectedId === CONTEXT_CARD
204  const label = `專案脈絡 ${d.facts.length} 條`
205  if (!open) {
206    return (
207      <Box key="card:context" borderStyle="round" borderDimColor paddingX={1}>
208        <Button key="open:context" plain dimColor label={label} onPress={() => act.select(CONTEXT_CARD)} />
209      </Box>
210    )
211  }
212  const how = d.digestEvery > 0 ? `每 ${d.digestEvery} 回合背景統整 · ${d.provider === 'openai' ? 'OpenAI' : 'Claude'}` : '背景統整已關閉(/sn every <n>)'
213  return (
214    <Box key="card:context" flexDirection="column" borderStyle="round" borderDimColor paddingX={1} gap={1}>
215      <Box justifyContent="space-between">
216        <Button key="close:context" plain label="專案脈絡" onPress={() => act.select(null)} />
217        <Text dimColor>{how}</Text>
218      </Box>
219      <Box flexDirection="column">
220        <Text dimColor>主線摘要(這個 session)</Text>
221        <Text>{d.digest ?? '還沒有:主線跑過幾個回合後會出現。'}</Text>
222      </Box>
223      <Box flexDirection="column">
224        <Text dimColor>專案脈絡(所有 session 共用;Jev 會看最新幾條)</Text>
225        {d.facts.length === 0 && <Text dimColor>還沒有。背景統整會自動加,也可以在下面自己加。</Text>}
226        {d.facts.map((f, i) => (
227          <Box key={`fact:${f.id}`} flexDirection="row" columnGap={1}>
228            <Text>{`${i + 1}. ${clip(f.text, 200)}${f.source === 'manual' ? '(手動)' : ''}`}</Text>
229            <Button key={`fact-rm:${f.id}`} plain dimColor label="✕" onPress={() => act.removeFact(f.id)} />
230          </Box>
231        ))}
232      </Box>
233      {Input && (
234        <Input
235          key={`fact-add:${d.facts.length}`}
236          value=""
237          placeholder="加一條專案脈絡…"
238          submitLabel="↵"
239          onSubmit={v => {
240            if (v.trim() !== '') act.addFact(v.trim())
241          }}
242        />
243      )}
244      <Box flexDirection="row" columnGap={2} alignItems="center">
245        {d.digestStatus.running ? (
246          <Text color="claude">統整中…</Text>
247        ) : (
248          <Button key="digest-now" plain dimColor label="立即統整" onPress={() => act.refreshDigest()} />
249        )}
250        {!d.digestStatus.running && d.digestStatus.at !== null && (
251          <Text dimColor>{`上次 ${when(d.digestStatus.at).slice(6)}:${d.digestStatus.result ?? ''}`}</Text>
252        )}
253      </Box>
254    </Box>
255  )
256}
257
258export function paneView(els: ElementTable, d: PaneData, act: PaneActions): RenderElement {
259  const { Box, Text, Button, Markdown } = els
260  // mobile draws no Input (Elements): the reply box is left out there
261  const Input = 'Input' in els ? els.Input : undefined
262  const tree = d.tree
263  const nodes = tree ? Object.keys(tree.nodes).length : 0
264  const active = tree?.activeThread[d.sessionId] ?? null
265  const activeRoot = tree && active && tree.nodes[active] ? rootOf(tree, active) : null
266  const picked = tree && d.selectedId && tree.nodes[d.selectedId] ? d.selectedId : null
267  const openRoot = tree && picked ? rootOf(tree, picked) : null
268
269  return (
270    <Box flexDirection="column" gap={1}>
271      <Box justifyContent="space-between">
272        <Text bold>Sticky Notes</Text>
273        <Text dimColor>{`${nodes} 張${d.pending > 0 ? ` · ${d.pending} 回答中` : ''}`}</Text>
274      </Box>
275
276      {(tree === null || tree.roots.length === 0) && (
277        <Text dimColor>還沒有便利貼。在主輸入框問「為什麼/是什麼」,或用 /sn new &lt;問題&gt;。</Text>
278      )}
279
280      {/* newest topic first */}
281      {tree &&
282        [...tree.roots].reverse().map(id => {
283          const root = tree.nodes[id]!
284          const open = id === openRoot
285          const following = id === activeRoot
286          const n = countAll(tree, id)
287          const meta = `${when(root.anchor.at)}${n > 0 ? ` · ${n + 1}` : ''}`
288          const frame = following ? { borderColor: 'success' } : { borderDimColor: true }
289          const tag = categoryChip(els, d.surface, `category:${id}`, root.route.jev)
290
291          if (!open) {
292            // closed: one line. A Button holds one plain string (no colored part), so the tag is its
293            // own chip between two presses that both open the card: the title, and the time
294            return (
295              <Box key={`card:${id}`} flexDirection="row" alignItems="center" columnGap={1} borderStyle="round" paddingX={1} {...frame}>
296                <Box flexGrow={1}>
297                  <Button key={`open:${id}`} plain label={`${root.title}${root.answer === '' && root.promotedAt === null ? ' …' : ''}`} onPress={() => act.select(id)} />
298                </Box>
299                {tag}
300                <Button key={`open-meta:${id}`} plain dimColor label={meta} onPress={() => act.select(id)} />
301              </Box>
302            )
303          }
304
305          const thread = threadOf(tree, picked!, active)
306          const last = thread.at(-1)!
307          // answers drawn whole from the newest back while the budget lasts (THREAD_BUDGET)
308          let budget = THREAD_BUDGET
309          const whole = new Set<string>()
310          for (const t of [...thread].reverse()) {
311            const size = Math.min([...t.answer].length, ANSWER_SHOWN) + Math.min([...t.question].length, QUESTION_SHOWN)
312            if (size > budget && whole.size > 0) break
313            budget -= size
314            whole.add(t.id)
315          }
316          return (
317            <Box key={`card:${id}`} flexDirection="column" borderStyle="round" paddingX={1} gap={1} {...frame}>
318              <Box flexDirection="row" alignItems="center" columnGap={1}>
319                <Box flexGrow={1}>
320                  <Button key={`close:${id}`} plain label={root.title} onPress={() => act.select(null)} />
321                </Box>
322                {tag}
323                <Text dimColor>{meta}</Text>
324              </Box>
325              {thread.map((node, i) => {
326                const next = thread[i + 1]
327                const mark = contextMark(node)
328                return (
329                  <Box key={`turn:${node.id}`} flexDirection="column" gap={1}>
330                    {node.id === d.editingId ? editor(els, node, act) : bubble(els, d.surface, node, act)}
331                    <Markdown text={answerText(node, whole.has(node.id))} />
332                    {mark !== '' && <Text dimColor>{mark}</Text>}
333                    {node.children.length > 1 && (
334                      // its own block (the developer, 10/14): native buttons in a dim frame, apart from the answer
335                      <Box key={`picks:${node.id}`} flexDirection="row" flexWrap="wrap" alignItems="center" gap={1} borderStyle="round" borderDimColor paddingX={1}>
336                        <Text dimColor>追問</Text>
337                        {node.children.map(c => (
338                          <Button
339                            key={`pick:${c}`}
340                            dimColor={c !== next?.id}
341                            label={`${c === next?.id ? '● ' : '○ '}${tree.nodes[c]?.title ?? ''}`}
342                            onPress={() => act.select(c)}
343                          />
344                        ))}
345                      </Box>
346                    )}
347                  </Box>
348                )
349              })}
350              {Input && (
351                // keyed by the note it follows up: a sent reply selects its new note, so the box is a
352                // fresh, empty one; Desktop draws its native field at a fixed width (PROBE.md〇之六)
353                <Input
354                  key={`reply:${last.id}`}
355                  value=""
356                  placeholder="回覆…"
357                  submitLabel="↵"
358                  onSubmit={v => {
359                    if (v.trim() !== '') act.followUp(last.id, v.trim())
360                  }}
361                />
362              )}
363            </Box>
364          )
365        })}
366
367      {contextCard(els, d, act)}
368    </Box>
369  )
370}
371
hooks/context.ts 187 lines
1// R4: the main-line digest (what this session is doing, for Jev) and the project
2// context (durable facts of the project, only ever added to by the summary layer,
3// pruned by hand). One summary-layer call every `digestEvery` main turns, in the
4// background after the turn ends (register.tsx turn.complete).
5//
6//   $.store digest:<root>:<sessionId>  → SessionDigest   (one per session: sessions do different things)
7//   $.store context:<root>             → ContextFact[]   (one per project, every session adds to it)
8import type { SummaryProvider } from './providers/types'
9import type { KV } from './ports'
10import { LANGUAGE_RULE } from './digest'
11
12export type SessionDigest = {
13  text: string
14  /** $.session.turns() when it was written: the next one is due digestEvery turns later. */
15  turns: number
16  /** How many typed prompts the main line had then: the next run reads the ones after it. */
17  prompts?: number
18  at: number
19}
20
21/** The first run reads the whole session: its earlier prompts, newest back, up to this many characters. */
22export const EARLIER_BUDGET = 12000
23/** Each later run reads the exchanges since the last one, at most this many. */
24export const SINCE_MAX = 10
25/** The exchanges read in detail (prompt and reply) on the first run. */
26export const RECENT_DETAIL = 3
27
28export type ContextFact = {
29  id: string
30  text: string
31  at: number
32  sessionId: string
33  source: 'auto' | 'manual'
34}
35
36export const DIGEST_MAX = 200
37export const FACT_MAX = 100
38export const FACTS_PER_RUN = 3
39/** What the project context keeps at most: beyond it the oldest automatic facts go first. */
40export const FACTS_KEPT = 60
41/** What Jev reads of the project context: the newest few, each short. */
42export const FACTS_FOR_JEV = 8
43
44export const digestKey = (root: string, sessionId: string) => `digest:${root}:${sessionId}`
45export const contextKey = (root: string) => `context:${root}`
46
47export async function readDigest(kv: KV, root: string, sessionId: string): Promise<SessionDigest | null> {
48  const d = (await kv.get(digestKey(root, sessionId))) as SessionDigest | undefined
49  return d && typeof d.text === 'string' ? d : null
50}
51
52export async function readFacts(kv: KV, root: string): Promise<ContextFact[]> {
53  const list = (await kv.get(contextKey(root))) as ContextFact[] | undefined
54  return Array.isArray(list) ? list : []
55}
56
57/** Whether a digest is due: digestEvery turns since the last one (0 turns it off). */
58export function digestDue(every: number, turns: number, last: SessionDigest | null): boolean {
59  if (every <= 0) return false
60  return turns - (last?.turns ?? 0) >= every
61}
62
63const clip = (s: string, n: number) => {
64  const cps = [...s.replace(/\s+/g, ' ').trim()]
65  return cps.length > n ? cps.slice(0, n).join('') + '…' : cps.join('')
66}
67/** A reply's head and tail: the conclusion is usually at the end. */
68const headTail = (s: string, n: number) => {
69  const cps = [...s.trim()]
70  return cps.length > 2 * n ? `${cps.slice(0, n).join('')}\n…\n${cps.slice(-n).join('')}` : cps.join('')
71}
72
73export type Exchange = { user: string; assistant: string }
74
75const DIGEST_SYSTEM =
76  'You keep two notes about a coding session for a router that decides where the next prompt goes. ' +
77  `(1) "digest": at most ${DIGEST_MAX} characters on what the main line is doing now, what was just decided, and what is still open; ` +
78  'rewrite it from the previous digest and the latest exchanges. ' +
79  `(2) "facts": 0–${FACTS_PER_RUN} durable facts about the project worth remembering beyond this session ` +
80  `(a decision, a convention, a constraint, a pitfall), each at most ${FACT_MAX} characters, none that the known facts already say; ` +
81  'an empty list when there is nothing new. ' +
82  `${LANGUAGE_RULE} Reply with JSON only: {"digest": "...", "facts": ["..."]}`
83
84/** What a run reads of the main line: on the first, the whole session's earlier prompts too. */
85export type DigestInput = { earlier: string[]; exchanges: Exchange[] }
86
87export function digestPrompt(previous: string | null, input: DigestInput, known: readonly string[]): string {
88  return [
89    `[previous digest]\n${previous ?? '(none)'}`,
90    `[known project facts]\n${known.length ? known.map(f => `- ${f}`).join('\n') : '(none)'}`,
91    ...(input.earlier.length > 0 ? [`[earlier prompts of this session, oldest first]\n${input.earlier.map(u => `- ${u}`).join('\n')}`] : []),
92    `[latest exchanges, oldest first]\n${input.exchanges.map(x => `user: ${clip(x.user, 600)}\nassistant: ${headTail(x.assistant, 600)}`).join('\n\n')}`,
93  ].join('\n\n')
94}
95
96/**
97 * What a run reads. With no digest yet, the whole session: every earlier prompt
98 * (200 characters each, newest back while EARLIER_BUDGET lasts) and the last three
99 * exchanges in detail. After that, the exchanges since the last run (by the prompt
100 * count it kept), at most SINCE_MAX; when the count no longer fits (a compaction
101 * shortened the transcript), the last `fallback`.
102 */
103export function digestInput(all: readonly Exchange[], previous: SessionDigest | null, fallback: number): DigestInput {
104  if (previous === null) {
105    const recent = all.slice(-RECENT_DETAIL)
106    const earlier: string[] = []
107    let budget = EARLIER_BUDGET
108    for (const x of all.slice(0, -RECENT_DETAIL).reverse()) {
109      const u = clip(x.user, 200)
110      if (u.length > budget) break
111      budget -= u.length
112      earlier.unshift(u)
113    }
114    return { earlier, exchanges: recent }
115  }
116  const since = previous.prompts !== undefined ? all.length - previous.prompts : -1
117  const n = since > 0 && since <= all.length ? Math.min(since, SINCE_MAX) : Math.max(1, Math.min(fallback, SINCE_MAX))
118  return { earlier: [], exchanges: all.slice(-n) }
119}
120
121/** Accepts a bare JSON object or one in a ```json fence; null when the shape is off. */
122export function parseDigest(text: string): { digest: string; facts: string[] } | null {
123  const m = /\{[\s\S]*\}/.exec(text)
124  if (!m) return null
125  try {
126    const o = JSON.parse(m[0]) as { digest?: unknown; facts?: unknown }
127    if (typeof o.digest !== 'string' || o.digest.trim() === '') return null
128    const facts = Array.isArray(o.facts) ? o.facts.filter((f): f is string => typeof f === 'string' && f.trim() !== '') : []
129    return { digest: clip(o.digest, DIGEST_MAX), facts: facts.slice(0, FACTS_PER_RUN).map(f => clip(f, FACT_MAX)) }
130  } catch {
131    return null
132  }
133}
134
135/** New facts not already there (the same text, spaces and case aside); over FACTS_KEPT the oldest automatic ones go. */
136export function addFacts(list: readonly ContextFact[], add: readonly ContextFact[]): ContextFact[] {
137  const norm = (s: string) => s.replace(/\s+/g, '').toLowerCase()
138  const seen = new Set(list.map(f => norm(f.text)))
139  const fresh = add.filter(f => !seen.has(norm(f.text)) && (seen.add(norm(f.text)), true))
140  const all = [...list, ...fresh]
141  if (all.length <= FACTS_KEPT) return all
142  // over the cap: the oldest automatic facts go; the ones added by hand stay
143  let drop = all.length - FACTS_KEPT
144  return all.filter(f => (drop > 0 && f.source === 'auto' ? (drop--, false) : true))
145}
146
147/**
148 * One digest run: the summary layer reads the previous digest, the known facts and
149 * the latest exchanges, and writes the new digest and any new facts. Never throws;
150 * a failed or malformed answer leaves both as they were and says why.
151 */
152export async function runDigest(
153  d: { kv: KV; provider: SummaryProvider; root: string; sessionId: string; turns: number; now: number; newId: () => string; every: number },
154  all: readonly Exchange[],
155): Promise<{ ok: true; digest: string; added: number } | { ok: false; reason: string }> {
156  if (all.length === 0) return { ok: false, reason: 'no exchanges' }
157  const previous = await readDigest(d.kv, d.root, d.sessionId)
158  const facts = await readFacts(d.kv, d.root)
159  const r = await d.provider.summarize('main-digest', {
160    system: DIGEST_SYSTEM,
161    prompt: digestPrompt(previous?.text ?? null, digestInput(all, previous, d.every), facts.map(f => f.text)),
162    maxTokens: 600,
163    hasProjectContent: true,
164  })
165  if (!r.ok) return { ok: false, reason: `${r.provider} ${r.reason}${r.detail ? ` ${r.detail}` : ''}` }
166  const parsed = parseDigest(r.text)
167  if (!parsed) return { ok: false, reason: 'malformed answer' }
168  await d.kv.set(digestKey(d.root, d.sessionId), { text: parsed.digest, turns: d.turns, prompts: all.length, at: d.now } satisfies SessionDigest)
169  const fresh = parsed.facts.map(text => ({ id: d.newId(), text, at: d.now, sessionId: d.sessionId, source: 'auto' as const }))
170  const next = addFacts(facts, fresh)
171  if (next.length !== facts.length || fresh.length > 0) await d.kv.set(contextKey(d.root), next)
172  return { ok: true, digest: parsed.digest, added: next.length - facts.length }
173}
174
175/** The main line as exchanges: each typed prompt with the reply after it; the last `n` (all by default). */
176export function lastExchanges(messages: readonly { role: string; text: string }[], isTyped: (m: { role: string; text: string }) => boolean, n = Infinity): Exchange[] {
177  const out: Exchange[] = []
178  for (let i = 0; i < messages.length; i++) {
179    const m = messages[i]!
180    if (!isTyped(m)) continue
181    let reply = ''
182    for (let j = i + 1; j < messages.length && !isTyped(messages[j]!); j++) if (messages[j]!.role === 'assistant' && messages[j]!.text !== '') reply = messages[j]!.text
183    out.push({ user: m.text, assistant: reply })
184  }
185  return n === Infinity ? out : out.slice(-n)
186}
187
hooks/ports.ts 82 lines
1// What the logic modules may do outside themselves.
2//
3// The engine's loader refuses `$` passed into a function imported from another
4// file ("$ is followed only into a function declared in this same file, never
5// across an import", PROBE.md). So register.ts builds these closures over its
6// hook's `$` (portsOf) and hands them down; nothing below register.ts sees `$`.
7import type { HttpInit, HttpResponse, ModelCompleteRequest, ModelCompleteResult, ModelForkResult, SessionMessage } from 'claude-code'
8
9import type { Tree } from '../types'
10
11export type KV = {
12  get(key: string): Promise<unknown>
13  set(key: string, value: unknown): Promise<void>
14  delete(key: string): Promise<void>
15  keys(): Promise<string[]>
16}
17
18export type Ports = {
19  sessionId(): Promise<string>
20  /** The project key: $.session.repo()?.root ?? $.session.root() (shared across worktrees). */
21  projectRoot(): Promise<string>
22  turns(): Promise<number>
23  messages(): Promise<readonly SessionMessage[]>
24  now(): Promise<number>
25  /** Runs fn outside the current dispatch ($.clock.after(0, fn)). */
26  later(fn: () => void): void
27  /** Resolves after ms ($.clock.sleep). */
28  sleep(ms: number): Promise<void>
29  store: KV
30  fetch(url: string, init?: HttpInit): Promise<HttpResponse>
31  fork(prompt: string): Promise<ModelForkResult>
32  complete(request: ModelCompleteRequest): Promise<ModelCompleteResult>
33  /** Env vars are read with string literals in register.ts; only their values cross. */
34  keys: {
35    typesafe(): Promise<string | undefined>
36    openai(): Promise<string | undefined>
37    /** One line per key: found or not, and where; never the value. */
38    report(): Promise<string[]>
39  }
40  ui: {
41    log(text: string, to?: 'transcript' | 'debug'): void
42    toast(text: string): void
43    /** Rejects when dismissed or headless. */
44    ask(question: string, options: readonly string[], header: string): Promise<string>
45    openPane(): Promise<void>
46    closePane(): Promise<void>
47    isPaneOpen(): Promise<boolean>
48    /** The plugin's one status line under the prompt; undefined clears it. */
49    status(text: string | undefined): void
50  }
51  state: {
52    publishTree(tree: Tree): Promise<void>
53    lastTurnId(): Promise<string | null>
54    turnsAtLastSidebar(): Promise<number>
55    setTurnsAtLastSidebar(n: number): Promise<void>
56    addPending(delta: number): Promise<void>
57    addUnread(delta: number): Promise<void>
58    lastPromptUuid(): Promise<string | null>
59    lastSampleId(): Promise<string | null>
60    setLastSampleId(id: string | null): Promise<void>
61    /** The node the pane shows. */
62    setSelected(id: string | null): Promise<void>
63    selected(): Promise<string | null>
64    /** The digest or the project context changed in the store: the pane draws them again. */
65    contextChanged(): Promise<void>
66    /** R4: a digest run started (`result` null) or ended with `result`, shown on the context card. */
67    setDigestStatus(running: boolean, result: string | null): Promise<void>
68  }
69  /**
70   * This plugin's own userConfig field, as the plugin settings show it: written to
71   * settings.json (pluginConfigs) through $.config.set; `deny` when the engine refused.
72   */
73  setOption(field: 'summaryProvider' | 'digestEvery' | 'notionDataSource' | 'askTimeout', value: string | number): Promise<{ ok: true } | { ok: false; reason: string }>
74  /** Where this runs, for the Notion rows: the repo's git remote, and the computer's name. */
75  place(): Promise<{ remote: string | null; machine: string }>
76  /** MCP servers the session has (the claude.ai connectors among them), by their tools' names. */
77  mcp: {
78    tools(): Promise<string[]>
79    call(server: string, tool: string, args: Record<string, unknown>): Promise<{ isError: boolean; content: { type: string; text?: string }[] }>
80  }
81}
82
hooks/secrets.ts 68 lines
1// Where the API keys come from (PLAN.md「金鑰」, as revised: no machine-wide
2// environment variables required). First hit wins:
3//   1. the process environment (a terminal, CI)
4//   2. ~/.claude/sticky-notes/.env   — per user, outside every repo
5//   3. <plugin root>/.env            — a development checkout (git-ignored)
6// The current project's own .env is never read: it often holds that app's own
7// OPENAI_API_KEY. Values are never logged or stored.
8
9export type KeyName = 'TYPESAFE_API_KEY' | 'OPENAI_API_KEY'
10
11/** KEY=value lines; tolerates a BOM, CRLF, `export `, quotes and comments. */
12export function parseDotenv(text: string): Record<string, string> {
13  const out: Record<string, string> = {}
14  for (const raw of text.replace(/^/, '').split(/\r?\n/)) {
15    const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(raw)
16    if (!m) continue
17    let v = m[2] ?? ''
18    const q = /^(['"])([\s\S]*)\1$/.exec(v)
19    if (q) v = q[2] ?? ''
20    else v = v.replace(/\s+#.*$/, '')
21    out[m[1]!] = v
22  }
23  return out
24}
25
26/** The key files, in the order they are tried. `home` is USERPROFILE / HOME. */
27export function keyFiles(home: string | undefined, pluginRoot: string): string[] {
28  const sep = pluginRoot.includes('\\') ? '\\' : '/'
29  const files: string[] = []
30  if (home) files.push([home.replace(/[\\/]+$/, ''), '.claude', 'sticky-notes', '.env'].join(sep))
31  files.push(`${pluginRoot.replace(/[\\/]+$/, '')}${sep}.env`)
32  return files
33}
34
35/** Where a key was found: 'env', a file path, or null when nowhere. */
36export type KeySource = { value: string; from: string } | null
37
38/** First non-empty value: the environment, then each file in order. */
39export async function findKey(
40  name: KeyName,
41  fromEnv: string | undefined,
42  files: readonly string[],
43  read: (path: string) => Promise<string>,
44): Promise<KeySource> {
45  if (fromEnv && fromEnv.trim() !== '') return { value: fromEnv.trim(), from: 'env' }
46  for (const f of files) {
47    let text: string
48    try {
49      text = await read(f)
50    } catch {
51      continue // missing or unreadable: try the next one
52    }
53    const v = parseDotenv(text)[name]
54    if (v && v.trim() !== '') return { value: v.trim(), from: f }
55  }
56  return null
57}
58
59export async function resolveKey(...args: Parameters<typeof findKey>): Promise<string | undefined> {
60  return (await findKey(...args))?.value
61}
62
63/** /sticky-note doctor: where each key comes from, never its value. */
64export function describeKey(name: KeyName, found: KeySource): string {
65  if (found === null) return `${name}:找不到(環境變數與 key 檔都沒有)`
66  return `${name}:有(${found.from === 'env' ? '環境變數' : found.from})`
67}
68
hooks/tree.ts 419 lines
1// Tree data model: pure operations on an in-memory Tree, plus the $.store layout.
2//
3// Layout (PLAN.md「資料模型」): one key per node, outline and session, so two
4// sessions writing at once never overwrite each other (PROBE.md P3):
5//   node:<root>:<id>  outline:<root>:<id>  active:<root>:<sessionId>  meta:<root>
6// `roots` and every node's `children` are derived from parentId on load, never
7// stored, so adding a child never rewrites its parent's key.
8import type { Anchor, AnsweredBy, MainDigest, Outline, RouteSource, Tree, TreeMeta, TreeNode } from '../types'
9import type { KV } from './ports'
10
11export const TITLE_MAX = 12
12
13export function emptyTree(): Tree {
14  return { nodes: {}, roots: [], outlines: {}, activeThread: {}, tags: [], mainDigest: null }
15}
16
17/**
18 * The project key: repo root (shared across worktrees) or session root, in one
19 * spelling — forward slashes, no trailing slash, lower-case drive letter — since
20 * $.session.repo().root and $.session.root() may spell the same folder differently.
21 */
22export function normalizeRoot(root: string): string {
23  return root
24    .replace(/\\/g, '/')
25    .replace(/\/+$/, '')
26    .replace(/^([A-Za-z]):/, (_, d: string) => `${d.toLowerCase()}:`)
27}
28
29export const keys = {
30  node: (root: string, id: string) => `node:${root}:${id}`,
31  outline: (root: string, id: string) => `outline:${root}:${id}`,
32  active: (root: string, sessionId: string) => `active:${root}:${sessionId}`,
33  meta: (root: string) => `meta:${root}`,
34}
35
36/** First TITLE_MAX characters (code points, so CJK and emoji are not split). */
37export function fallbackTitle(question: string): string {
38  return [...question.replace(/\s+/g, ' ').trim()].slice(0, TITLE_MAX).join('')
39}
40
41/** Depth-first rows for the pane: each node with its depth, children in anchor.at order. */
42export function flatten(tree: Tree, rootIds: readonly string[] = tree.roots): { node: TreeNode; depth: number }[] {
43  const out: { node: TreeNode; depth: number }[] = []
44  const walk = (id: string, depth: number) => {
45    const node = tree.nodes[id]
46    if (!node || depth > 64) return
47    out.push({ node, depth })
48    for (const c of node.children) walk(c, depth + 1)
49  }
50  for (const id of rootIds) walk(id, 0)
51  return out
52}
53
54/** Recomputes roots and children from parentId; a node whose parent is gone counts as a root. */
55export function derive(tree: Tree): Tree {
56  const byAt = (a: TreeNode, b: TreeNode) => a.anchor.at - b.anchor.at || a.id.localeCompare(b.id)
57  const all = Object.values(tree.nodes).sort(byAt)
58  const children: Record<string, string[]> = {}
59  const roots: string[] = []
60  for (const n of all) {
61    if (n.parentId !== null && tree.nodes[n.parentId]) (children[n.parentId] ??= []).push(n.id)
62    else roots.push(n.id)
63  }
64  const nodes: Tree['nodes'] = {}
65  for (const n of all) nodes[n.id] = { ...n, children: children[n.id] ?? [] }
66  return { ...tree, nodes, roots }
67}
68
69export type NewNode = {
70  id: string
71  question: string
72  anchor: Anchor
73  route: { label: string; confidence: number; source: RouteSource }
74  answeredBy: AnsweredBy
75  answer?: string
76  title?: string
77  tags?: string[]
78  /** Already promoted at creation (no caller since the project_question bookmark was removed, 10/12). */
79  promotedAt?: number | null
80  promotedIn?: string | null
81}
82
83export type Attach =
84  /** New root. */
85  | { kind: 'root' }
86  /** Under this session's activeThread; a root when it has none. */
87  | { kind: 'followup' }
88  /** Under an explicit parent (pane follow-up box). */
89  | { kind: 'under'; parentId: string }
90
91/**
92 * Adds a node. By default it becomes this session's activeThread;
93 * `makeActive: false` leaves the activeThread alone.
94 * A follow-up whose parent is gone becomes a root rather than failing.
95 */
96export function addNode(
97  tree: Tree,
98  sessionId: string,
99  input: NewNode,
100  attach: Attach,
101  opts: { makeActive?: boolean } = {},
102): { tree: Tree; node: TreeNode } {
103  if (tree.nodes[input.id]) throw new Error(`node ${input.id} already exists`)
104  const wanted =
105    attach.kind === 'under' ? attach.parentId : attach.kind === 'followup' ? (tree.activeThread[sessionId] ?? null) : null
106  const parentId = wanted !== null && tree.nodes[wanted] ? wanted : null
107
108  const node: TreeNode = {
109    id: input.id,
110    parentId,
111    outlineId: null,
112    anchor: input.anchor,
113    question: input.question,
114    answer: input.answer ?? '',
115    answeredBy: input.answeredBy,
116    title: input.title ?? fallbackTitle(input.question),
117    summary: null,
118    tags: input.tags ?? [],
119    route: input.route,
120    promotedAt: input.promotedAt ?? null,
121    promotedIn: input.promotedIn ?? null,
122    children: [],
123  }
124
125  const outlines = parentId === null ? tree.outlines : markStale(tree, rootOf(tree, parentId), input.anchor.at)
126  const activeThread = opts.makeActive === false ? tree.activeThread : { ...tree.activeThread, [sessionId]: node.id }
127  const next = derive({ ...tree, nodes: { ...tree.nodes, [node.id]: node }, outlines, activeThread })
128  return { tree: next, node: next.nodes[node.id]! }
129}
130
131/** A new follow-up under an outline member makes that outline stale. */
132function markStale(tree: Tree, rootId: string, at: number): Tree['outlines'] {
133  const outlineId = tree.nodes[rootId]?.outlineId
134  if (!outlineId) return tree.outlines
135  const outline = tree.outlines[outlineId]
136  if (!outline || outline.staleSince !== null) return tree.outlines
137  return { ...tree.outlines, [outlineId]: { ...outline, staleSince: at } }
138}
139
140export function rootOf(tree: Tree, id: string): string {
141  let cur = tree.nodes[id]
142  if (!cur) throw new Error(`no node ${id}`)
143  const seen = new Set<string>()
144  while (cur.parentId !== null) {
145    if (seen.has(cur.id)) throw new Error(`cycle at ${cur.id}`)
146    seen.add(cur.id)
147    const parent: TreeNode | undefined = tree.nodes[cur.parentId]
148    if (!parent) break
149    cur = parent
150  }
151  return cur.id
152}
153
154/** Root → … → id. */
155export function pathTo(tree: Tree, id: string): TreeNode[] {
156  const out: TreeNode[] = []
157  let cur = tree.nodes[id]
158  while (cur) {
159    out.unshift(cur)
160    cur = cur.parentId === null ? undefined : tree.nodes[cur.parentId]
161  }
162  return out
163}
164
165/** The Q/A chain a follow-up is asked over (answered nodes only). */
166export function sideHistory(tree: Tree, id: string | null): { question: string; answer: string }[] {
167  if (id === null || !tree.nodes[id]) return []
168  return pathTo(tree, id)
169    .filter(n => n.answer !== '')
170    .map(n => ({ question: n.question, answer: n.answer }))
171}
172
173/** Pane click / "回到主線" (null). Unknown ids are ignored. */
174export function setActive(tree: Tree, sessionId: string, id: string | null): Tree {
175  if (id !== null && !tree.nodes[id]) return tree
176  return { ...tree, activeThread: { ...tree.activeThread, [sessionId]: id } }
177}
178
179export type NodePatch = Partial<Pick<TreeNode, 'answer' | 'answeredBy' | 'title' | 'summary' | 'tags'>>
180
181export function updateNode(tree: Tree, id: string, patch: NodePatch): Tree {
182  const node = tree.nodes[id]
183  if (!node) return tree
184  const title = patch.title === undefined ? node.title : [...patch.title].slice(0, TITLE_MAX).join('') || node.title
185  return { ...tree, nodes: { ...tree.nodes, [id]: { ...node, ...patch, title } } }
186}
187
188/** 回流主線: promotion only ever goes into the session it was pressed in. */
189export function markPromoted(tree: Tree, id: string, sessionId: string, at: number): Tree {
190  const node = tree.nodes[id]
191  if (!node) return tree
192  return { ...tree, nodes: { ...tree.nodes, [id]: { ...node, promotedAt: at, promotedIn: sessionId } } }
193}
194
195/** Removes a node and its whole subtree (重新分類 sends the question to the main line instead). */
196export function removeNode(tree: Tree, id: string): Tree {
197  const node = tree.nodes[id]
198  if (!node) return tree
199  const gone = new Set<string>()
200  const walk = (nid: string) => {
201    gone.add(nid)
202    for (const c of tree.nodes[nid]?.children ?? []) walk(c)
203  }
204  walk(id)
205
206  const nodes: Tree['nodes'] = {}
207  for (const [k, v] of Object.entries(tree.nodes)) if (!gone.has(k)) nodes[k] = v
208
209  const outlines: Tree['outlines'] = {}
210  for (const [k, o] of Object.entries(tree.outlines)) {
211    const memberIds = o.memberIds.filter(m => !gone.has(m))
212    if (memberIds.length > 0) outlines[k] = { ...o, memberIds }
213  }
214
215  const activeThread: Tree['activeThread'] = {}
216  for (const [s, a] of Object.entries(tree.activeThread)) activeThread[s] = a !== null && gone.has(a) ? node.parentId : a
217
218  return derive({ ...tree, nodes, outlines, activeThread })
219}
220
221export type NewOutline = { id: string; title: string; outline: string; memberIds: string[]; createdAt: number }
222
223/**
224 * Groups roots under a new outline. Only roots may be members; a root already in
225 * another outline is moved (returned in `moved` so the UI can say so), and an
226 * outline left with no members is deleted.
227 */
228export function createOutline(tree: Tree, input: NewOutline): { tree: Tree; outline: Outline; moved: string[] } {
229  const members = [...new Set(input.memberIds)]
230  if (members.length === 0) throw new Error('an outline needs at least one root')
231  if (tree.outlines[input.id]) throw new Error(`outline ${input.id} already exists`)
232  for (const m of members) {
233    if (tree.outlines[m]) throw new Error('an outline cannot be a member of an outline')
234    const n = tree.nodes[m]
235    if (!n) throw new Error(`no node ${m}`)
236    if (n.parentId !== null) throw new Error(`node ${m} is not a root`)
237  }
238
239  const moved = members.filter(m => tree.nodes[m]!.outlineId !== null)
240  const outlines: Tree['outlines'] = {}
241  for (const [k, o] of Object.entries(tree.outlines)) {
242    const memberIds = o.memberIds.filter(m => !members.includes(m))
243    if (memberIds.length > 0) outlines[k] = { ...o, memberIds }
244  }
245  const outline: Outline = { ...input, memberIds: members, staleSince: null }
246  outlines[outline.id] = outline
247
248  const nodes = { ...tree.nodes }
249  for (const m of members) nodes[m] = { ...nodes[m]!, outlineId: outline.id }
250  return { tree: { ...tree, nodes, outlines }, outline, moved }
251}
252
253/** 重算: new outline text, clears the stale mark. */
254export function refreshOutline(tree: Tree, id: string, outlineText: string): Tree {
255  const o = tree.outlines[id]
256  if (!o) return tree
257  return { ...tree, outlines: { ...tree.outlines, [id]: { ...o, outline: outlineText, staleSince: null } } }
258}
259
260/** Deleting an outline breaks nothing: members just become ungrouped roots. */
261export function deleteOutline(tree: Tree, id: string): Tree {
262  const o = tree.outlines[id]
263  if (!o) return tree
264  const nodes = { ...tree.nodes }
265  for (const m of o.memberIds) if (nodes[m]) nodes[m] = { ...nodes[m]!, outlineId: null }
266  const outlines = { ...tree.outlines }
267  delete outlines[id]
268  return { ...tree, nodes, outlines }
269}
270
271export function addTag(tree: Tree, tag: string): Tree {
272  const t = tag.trim()
273  if (t === '' || tree.tags.includes(t)) return tree
274  return { ...tree, tags: [...tree.tags, t] }
275}
276
277export function setMainDigest(tree: Tree, digest: MainDigest): Tree {
278  return { ...tree, mainDigest: digest }
279}
280
281/** Roots for the pane, optionally only those asked in one session. */
282export function visibleRoots(tree: Tree, onlySessionId?: string): TreeNode[] {
283  return tree.roots
284    .map(id => tree.nodes[id])
285    .filter((n): n is TreeNode => n !== undefined)
286    .filter(n => onlySessionId === undefined || n.anchor.sessionId === onlySessionId)
287}
288
289export function countNodes(tree: Tree): number {
290  return Object.keys(tree.nodes).length
291}
292
293// ---- $.store layout ---------------------------------------------------------
294
295const isObj = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object'
296
297function readMeta(raw: unknown): TreeMeta {
298  if (!isObj(raw) || raw.version !== 2) return { version: 2, tags: [], mainDigest: null }
299  return {
300    version: 2,
301    tags: Array.isArray(raw.tags) ? raw.tags.filter((t): t is string => typeof t === 'string') : [],
302    mainDigest: (raw.mainDigest as MainDigest | null | undefined) ?? null,
303  }
304}
305
306/** Fills fields older versions did not write (messageId; promotedTo → promotedIn). */
307function upgradeNode(raw: Record<string, unknown>): TreeNode {
308  const n = raw as Partial<TreeNode> & { promotedTo?: string | null }
309  const { promotedTo, ...rest } = n
310  return {
311    ...(rest as TreeNode),
312    anchor: { ...(n.anchor as TreeNode['anchor']), messageId: n.anchor?.messageId ?? null },
313    promotedIn: n.promotedIn ?? promotedTo ?? null,
314    children: [],
315  }
316}
317
318/**
319 * Moves a tree saved by the first M0 build (one `tree:<root>` key) into the
320 * per-node layout, then deletes the old key. Returns how many nodes moved.
321 */
322export async function migrateLegacy(store: KV, root: string): Promise<number> {
323  const r = normalizeRoot(root)
324  let moved = 0
325  for (const key of await store.keys()) {
326    if (!key.startsWith('tree:') || normalizeRoot(key.slice(5)) !== r) continue
327    const raw = await store.get(key)
328    if (isObj(raw) && isObj(raw.nodes)) {
329      for (const n of Object.values(raw.nodes)) {
330        if (!isObj(n) || typeof n.id !== 'string') continue
331        if ((await store.get(keys.node(r, n.id))) === undefined) {
332          await store.set(keys.node(r, n.id), { ...upgradeNode(n), children: [] })
333          moved++
334        }
335      }
336      if (isObj(raw.activeThread)) {
337        for (const [sid, a] of Object.entries(raw.activeThread)) {
338          if ((await store.get(keys.active(r, sid))) === undefined) await store.set(keys.active(r, sid), typeof a === 'string' ? a : null)
339        }
340      }
341      if (isObj(raw.outlines)) {
342        for (const o of Object.values(raw.outlines)) if (isObj(o) && typeof o.id === 'string') await store.set(keys.outline(r, o.id), o)
343      }
344      if ((await store.get(keys.meta(r))) === undefined) {
345        const tags = Array.isArray(raw.tags) ? raw.tags.filter((t): t is string => typeof t === 'string') : []
346        const meta: TreeMeta = { version: 2, tags, mainDigest: (raw.mainDigest as MainDigest | null | undefined) ?? null }
347        await store.set(keys.meta(r), meta)
348      }
349    }
350    await store.delete(key)
351  }
352  return moved
353}
354
355/** Assembles one project's tree from its keys. */
356export async function loadTree(store: KV, root: string): Promise<Tree> {
357  const r = normalizeRoot(root)
358  const all = await store.keys()
359  const tree = emptyTree()
360  const meta = readMeta(await store.get(keys.meta(r)))
361  tree.tags = meta.tags
362  tree.mainDigest = meta.mainDigest
363  for (const key of all) {
364    if (key.startsWith(keys.node(r, ''))) {
365      const n = await store.get(key)
366      if (isObj(n) && typeof n.id === 'string') tree.nodes[n.id] = upgradeNode(n)
367    } else if (key.startsWith(keys.outline(r, ''))) {
368      const o = await store.get(key)
369      if (isObj(o) && typeof o.id === 'string') tree.outlines[o.id] = o as Outline
370    } else if (key.startsWith(keys.active(r, ''))) {
371      const a = await store.get(key)
372      tree.activeThread[key.slice(keys.active(r, '').length)] = typeof a === 'string' ? a : null
373    }
374  }
375  return derive(tree)
376}
377
378/** A node as stored: children are derived, so they are not kept. */
379const stored = (n: TreeNode) => JSON.stringify({ ...n, children: [] })
380
381/** Writes only the keys whose value changed between `before` and `after`; deletes the ones that went away. */
382export async function saveDiff(store: KV, root: string, before: Tree, after: Tree): Promise<number> {
383  const r = normalizeRoot(root)
384  let writes = 0
385  for (const [id, n] of Object.entries(after.nodes)) {
386    const old = before.nodes[id]
387    if (!old || stored(old) !== stored(n)) {
388      await store.set(keys.node(r, id), { ...n, children: [] })
389      writes++
390    }
391  }
392  for (const id of Object.keys(before.nodes)) if (!after.nodes[id]) await store.delete(keys.node(r, id)), writes++
393  for (const [id, o] of Object.entries(after.outlines)) {
394    if (JSON.stringify(before.outlines[id]) !== JSON.stringify(o)) await store.set(keys.outline(r, id), o), writes++
395  }
396  for (const id of Object.keys(before.outlines)) if (!after.outlines[id]) await store.delete(keys.outline(r, id)), writes++
397  for (const [sid, a] of Object.entries(after.activeThread)) {
398    if (before.activeThread[sid] !== a) await store.set(keys.active(r, sid), a), writes++
399  }
400  if (JSON.stringify(before.tags) !== JSON.stringify(after.tags) || JSON.stringify(before.mainDigest) !== JSON.stringify(after.mainDigest)) {
401    const meta: TreeMeta = { version: 2, tags: after.tags, mainDigest: after.mainDigest }
402    await store.set(keys.meta(r), meta)
403    writes++
404  }
405  return writes
406}
407
408/**
409 * Load, apply, write back only what changed. Two sessions changing different
410 * nodes never collide; only a simultaneous edit of the same node or outline
411 * is last-writer-wins.
412 */
413export async function mutateTree(store: KV, root: string, fn: (tree: Tree) => Tree): Promise<Tree> {
414  const before = await loadTree(store, root)
415  const after = derive(fn(before))
416  await saveDiff(store, root, before, after)
417  return after
418}
419
hooks/usage.ts 86 lines
1// What this mod spent today, for the status line: Jev calls, and the tokens of the
2// Claude and OpenAI requests it made. Counted where the requests leave (register.tsx
3// wraps the ports' fetch / fork / complete), one $.store key per day shared by every
4// session and project, since the quotas are the account's. Two sessions counting at the
5// same instant may lose one count (read-modify-write); a gauge, not a bill.
6import type { HttpResponse } from 'claude-code'
7
8import { JEV_URL } from './jev'
9import type { KV } from './ports'
10
11export type Usage = {
12  /** Jev classifications sent (answered or not). */
13  jev: number
14  /** Claude tokens in, out and cache-written; the fork's cache reads are kept apart. */
15  claude: number
16  /** Claude cache reads (the fork reads the main line's cached prefix): cheap, not shown. */
17  claudeCacheRead: number
18  /** OpenAI total_tokens. */
19  openai: number
20}
21
22export const EMPTY_USAGE: Usage = { jev: 0, claude: 0, claudeCacheRead: 0, openai: 0 }
23
24const pad2 = (n: number) => String(n).padStart(2, '0')
25
26/** `usage:2026-10-14`, the local date. */
27export function usageKey(at: Date): string {
28  return `usage:${at.getFullYear()}-${pad2(at.getMonth() + 1)}-${pad2(at.getDate())}`
29}
30
31export async function readUsage(kv: KV, at: Date): Promise<Usage> {
32  return { ...EMPTY_USAGE, ...((await kv.get(usageKey(at))) as Partial<Usage> | undefined) }
33}
34
35export async function addUsage(kv: KV, at: Date, delta: Partial<Usage>): Promise<Usage> {
36  const u = await readUsage(kv, at)
37  const next: Usage = {
38    jev: u.jev + (delta.jev ?? 0),
39    claude: u.claude + (delta.claude ?? 0),
40    claudeCacheRead: u.claudeCacheRead + (delta.claudeCacheRead ?? 0),
41    openai: u.openai + (delta.openai ?? 0),
42  }
43  await kv.set(usageKey(at), next)
44  return next
45}
46
47/** 1234 → 1.2k, 34567 → 35k. */
48export function shortCount(n: number): string {
49  if (n < 1000) return String(n)
50  return n < 10000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`
51}
52
53/**
54 * The status line (Desktop puts the plugin's name before it, so the text does not):
55 * "今日 Jev 12 次 · Claude 34k · OpenAI 8k", OpenAI only once it was used,
56 * and "· 2 則回答中" while answers are pending.
57 */
58export function usageLine(u: Usage, pending: number): string {
59  const parts = [`今日 Jev ${u.jev} 次`, `Claude ${shortCount(u.claude)}`]
60  if (u.openai > 0) parts.push(`OpenAI ${shortCount(u.openai)}`)
61  if (pending > 0) parts.push(`${pending} 則回答中`)
62  return parts.join(' · ')
63}
64
65type ModelUsage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
66
67/** What one Claude request (fork or complete) adds. */
68export function claudeDelta(usage: ModelUsage | undefined): Partial<Usage> {
69  if (!usage) return {}
70  return { claude: usage.input_tokens + usage.output_tokens + usage.cache_creation_input_tokens, claudeCacheRead: usage.cache_read_input_tokens }
71}
72
73/** What one fetch adds: a Jev call by its URL, OpenAI's total_tokens from its body. */
74export function fetchDelta(url: string, r: HttpResponse | null): Partial<Usage> {
75  if (url.startsWith(JEV_URL)) return { jev: 1 }
76  if (url.includes('api.openai.com') && r?.ok) {
77    try {
78      const tokens = (JSON.parse(r.text) as { usage?: { total_tokens?: number } }).usage?.total_tokens
79      return typeof tokens === 'number' ? { openai: tokens } : {}
80    } catch {
81      return {}
82    }
83  }
84  return {}
85}
86
hooks/feedback.ts 152 lines
1// Routing feedback: every prompt Jev saw is kept with Jev's call, its confidence
2// and the user's choice (the dialog's pick, or /sn feedback afterwards), so the
3// threshold can be tuned later (PROBE.md D15). calibrate() shows what each
4// threshold would do.
5//
6// $.store `feedback:<root>:<id>`, one key per record (no shared key to race on),
7// at most RECORD_CAP per project. Prompts stay in the local store only.
8import type { AskChoice, FeedbackRecord } from '../types'
9import type { JevVerdict } from './jev'
10import type { KV } from './ports'
11import { normalizeRoot } from './tree'
12
13export const RECORD_CAP = 500
14export const PROMPT_KEEP = 200
15
16const prefix = (root: string) => `feedback:${normalizeRoot(root)}:`
17
18/** Time-ordered id: base-36 epoch ms, zero-padded, so key order is time order. */
19export function recordId(at: number, rand: string): string {
20  return `${at.toString(36).padStart(9, '0')}-${rand.slice(0, 8)}`
21}
22
23export function makeRecord(a: {
24  id: string
25  at: number
26  sessionId: string
27  prompt: string
28  verdict: JevVerdict
29  thresholds: FeedbackRecord['thresholds']
30  asked: boolean
31  outcome: FeedbackRecord['outcome']
32  choice: AskChoice | null
33  nodeId: string | null
34}): FeedbackRecord {
35  return {
36    id: a.id,
37    at: a.at,
38    sessionId: a.sessionId,
39    prompt: [...a.prompt].slice(0, PROMPT_KEEP).join(''),
40    jev: {
41      route: a.verdict.route.label,
42      confidence: a.verdict.route.confidence,
43      isFollowup: a.verdict.isFollowup,
44      needsProjectCtx: a.verdict.needsProjectCtx,
45      tag: a.verdict.tag?.label ?? null,
46    },
47    thresholds: a.thresholds,
48    asked: a.asked,
49    outcome: a.outcome,
50    choice: a.choice,
51    choiceSource: a.choice === null ? null : 'ask',
52    nodeId: a.nodeId,
53  }
54}
55
56/** Stores a record and drops the oldest beyond the cap. */
57export async function saveRecord(store: KV, root: string, record: FeedbackRecord): Promise<void> {
58  await store.set(prefix(root) + record.id, record)
59  const mine = (await store.keys()).filter(k => k.startsWith(prefix(root))).sort()
60  for (const k of mine.slice(0, Math.max(0, mine.length - RECORD_CAP))) await store.delete(k)
61}
62
63export async function getRecord(store: KV, root: string, id: string): Promise<FeedbackRecord | null> {
64  return ((await store.get(prefix(root) + id)) as FeedbackRecord | undefined) ?? null
65}
66
67/** /sn feedback: the user's choice for a record, said afterwards. */
68export async function setChoice(store: KV, root: string, id: string, choice: AskChoice): Promise<FeedbackRecord | null> {
69  const raw = (await store.get(prefix(root) + id)) as FeedbackRecord | undefined
70  if (!raw) return null
71  const next: FeedbackRecord = { ...raw, choice, choiceSource: 'command' }
72  await store.set(prefix(root) + id, next)
73  return next
74}
75
76export async function listRecords(store: KV, root: string): Promise<FeedbackRecord[]> {
77  const out: FeedbackRecord[] = []
78  for (const k of (await store.keys()).filter(k => k.startsWith(prefix(root))).sort()) {
79    const r = (await store.get(k)) as FeedbackRecord | undefined
80    if (r) out.push(r)
81  }
82  return out
83}
84
85const CHOICES: Record<string, AskChoice> = {
86  main: 'main',
87  主線: 'main',
88  project: 'main',
89  new: 'new',
90  sidebar: 'new',
91  note: 'new',
92  旁支: 'new',
93  便利貼: 'new',
94  followup: 'followup',
95  追問: 'followup',
96}
97
98/**
99 * `/sn feedback <main|new|followup>`: what the last prompt should have been.
100 * `good` keeps what happened. Chinese labels work too (主線 / 便利貼 / 追問).
101 */
102export function parseFeedback(args: string): { choice: AskChoice } | { good: true } | null {
103  const word = args.trim().split(/\s+/)[0] ?? ''
104  if (word === 'good' || word === '對') return { good: true }
105  const choice = CHOICES[word.toLowerCase()]
106  return choice ? { choice } : null
107}
108
109/** Jev's route and the user's choice compared as main line vs. sticky note. */
110const isMain = (x: string) => x === 'main' || x === 'main_task' || x === 'project_question'
111
112export type CalibrationRow = {
113  threshold: number
114  /** Records Jev would let through to the main line without asking at this threshold. */
115  auto: number
116  /** …of which the user also wanted the main line. */
117  correct: number
118  /** correct / auto (null when nothing would go through unasked). */
119  accuracy: number | null
120  /** Share of the records that would show the dialog. */
121  askRate: number | null
122}
123
124/**
125 * Only main_task / project_question go through unasked (sidebar_knowledge always
126 * asks), so the threshold trades the dialogs shown against prompts wrongly sent
127 * to the main line. Records without a choice are left out.
128 */
129export function calibrate(records: readonly FeedbackRecord[], candidates: readonly number[] = [0.5, 0.6, 0.7, 0.8, 0.9]): { labeled: number; rows: CalibrationRow[] } {
130  const labeled = records.filter(r => r.choice !== null)
131  const rows = candidates.map(threshold => {
132    const auto = labeled.filter(r => isMain(r.jev.route) && r.jev.confidence >= threshold)
133    const correct = auto.filter(r => isMain(r.choice!)).length
134    return {
135      threshold,
136      auto: auto.length,
137      correct,
138      accuracy: auto.length ? correct / auto.length : null,
139      askRate: labeled.length ? 1 - auto.length / labeled.length : null,
140    }
141  })
142  return { labeled: labeled.length, rows }
143}
144
145export function formatCalibration(c: ReturnType<typeof calibrate>): string[] {
146  const pct = (x: number | null) => (x === null ? '—' : `${Math.round(x * 100)}%`)
147  return [
148    `路由校正:${c.labeled} 筆有你的選擇`,
149    ...c.rows.map(r => `門檻 ${r.threshold.toFixed(2)} · 不問直接進主線 ${r.auto} 筆,其中你也要主線 ${r.correct}(${pct(r.accuracy)})· 會跳對話框 ${pct(r.askRate)}`),
150  ]
151}
152
hooks/notion.ts 316 lines
1// Notion sync (REQUESTS.md R5 / remote, 10/14): the notes of every computer in one Notion
2// database, reached through the claude.ai Notion connector ($.mcp.call), so no token sits
3// in the mod; the permission rules for its four tools are the user's own (README).
4import type { Tree, TreeNode } from '../types'
5import type { Ports } from './ports'
6import { addNode, updateNode } from './tree'
7
8/** The claude.ai connector's server, by the spelling its tools carry: mcp__<server>__notion-fetch. */
9export function notionServer(toolNames: readonly string[]): string | null {
10  for (const n of toolNames) {
11    const m = /^mcp__(.+)__notion-fetch$/.exec(n)
12    if (m) return m[1]!
13  }
14  return null
15}
16
17/** The text of an MCP result, its text blocks joined. */
18export function resultText(r: { content: readonly { type: string; text?: string }[] }): string {
19  return r.content.map(b => (b.type === 'text' && typeof b.text === 'string' ? b.text : '')).join('\n')
20}
21
22/**
23 * /sn notion test: can this mod reach the Notion connector, read the database's
24 * schema, and write and read one row? Each step says how it went, short enough for
25 * a command's output (the only thing a Remote Control client sees).
26 */
27export async function notionProbe(p: Ports, dataSource: string): Promise<string[]> {
28  const out: string[] = []
29  const server = notionServer(await p.mcp.tools())
30  if (server === null) return ['✗ 找不到 Notion connector(mcp__*__notion-fetch)']
31  out.push(`✓ connector:${server}`)
32  try {
33    const schema = await p.mcp.call(server, 'notion-fetch', { id: dataSource })
34    const text = resultText(schema)
35    out.push(schema.isError ? `✗ 讀資料庫:${text.slice(0, 160)}` : `✓ 讀資料庫:${text.includes('Note ID') ? '欄位都在' : '欄位不對'}(${text.length} 字)`)
36    if (schema.isError) return out
37    const id = `probe-${Date.now()}`
38    const made = await p.mcp.call(server, 'notion-create-pages', {
39      parent: { data_source_id: dataSource.replace(/^collection:\/\//, '') },
40      allow_async: false,
41      pages: [{ properties: { 標題: '探針測試(可刪)', 'Note ID': id, 問題: 'mod 寫得進來嗎?' }, content: '這一列是 /sn notion test 寫的,可以刪掉。' }],
42    })
43    out.push(made.isError ? `✗ 寫一列:${resultText(made).slice(0, 160)}` : '✓ 寫一列')
44    if (made.isError) return out
45    const rows = await p.mcp.call(server, 'notion-query-data-sources', {
46      data: {
47        mode: 'rows',
48        data_source_url: dataSource,
49        filter: { type: 'group', operator: 'and', filters: [{ type: 'property', property: 'Note ID', propertyType: 'text', operator: 'string_is', value: { type: 'exact', value: id } }] },
50        limit: 5,
51      },
52    })
53    const back = resultText(rows)
54    out.push(rows.isError ? `✗ 讀回來:${back.slice(0, 160)}` : back.includes(id) ? '✓ 讀回來' : `✗ 讀回來找不到那一列:${back.slice(0, 160)}`)
55  } catch (err) {
56    out.push(`✗ 呼叫失敗:${String(err).slice(0, 200)}`)
57  }
58  return out
59}
60
61// ---- the sync (10/14): one Notion row per answered note; other computers' rows pulled in ----
62//
63//   push: answerNote → pushNote, once the answer and its title are in (one create-pages call)
64//   pull: session.start and /sn notion pull → pullNotes (one query, one fetch per new note)
65//   $.store notion:<root>:<nodeId> → the row's URL: pushed from here, or pulled from there
66//   $.store notion-pull:<root>      → the newest 建立時間 pulled, so the next query asks for newer only
67// Two computers never edit the same note (the developer, 10/14): no merging, a row is written once.
68
69/** The cross-computer name of a project: its git remote without scheme, user and .git; else the folder's name. */
70export function projectName(remote: string | null, root: string): string {
71  if (remote) {
72    const r = remote
73      .trim()
74      .replace(/^[a-z+]+:\/\//i, '')
75      .replace(/^[^@/]+@/, '')
76      .replace(/:(?!\d)/, '/')
77      .replace(/\.git$/i, '')
78      .replace(/\/+$/, '')
79      .toLowerCase()
80    if (r !== '') return r
81  }
82  return root.replace(/[\\/]+$/, '').split(/[\\/]/).at(-1) ?? root
83}
84
85const notionKey = (root: string, id: string) => `notion:${root}:${id}`
86const pullKey = (root: string) => `notion-pull:${root}`
87const cut = (s: string, n: number) => [...s].slice(0, n).join('')
88/** A rich-text property holds 2000 characters. */
89const PROP_MAX = 1900
90/** The answer as the page's content; long answers are cut with a note. */
91const BODY_MAX = 40000
92
93/** The JSON a tool answered with (its text, or the object a text holds). */
94function jsonOf(text: string): unknown {
95  try {
96    return JSON.parse(text)
97  } catch {
98    return null
99  }
100}
101
102/** The first Notion page URL in a create-pages answer. */
103export function pageUrl(text: string): string | null {
104  return /https:\/\/(?:app\.notion\.com|www\.notion\.so)\/[^\s"'<>)]+/.exec(text)?.[0]?.replace(/\?.*$/, '') ?? null
105}
106
107/** A fetched page's content: between <content> and </content>, in the fetch answer's `text`. */
108export function pageContent(text: string): string {
109  const o = jsonOf(text) as { text?: unknown } | null
110  const body = o && typeof o.text === 'string' ? o.text : text
111  const m = /<content>\n?([\s\S]*?)\n?<\/content>/.exec(body)
112  return m ? m[1]!.trim() : ''
113}
114
115export type NotionRow = {
116  url: string
117  noteId: string
118  parentId: string | null
119  title: string
120  question: string
121  summary: string
122  answeredBy: string
123  machine: string
124  at: number
125  /** 不同步: a computer deleted it; nobody pulls it any more. */
126  unsynced: boolean
127}
128
129/** A rows-mode query answer → its rows; rows without a Note ID (or the probe's) are left out. */
130export function parseRows(text: string): NotionRow[] {
131  const o = jsonOf(text) as { results?: unknown } | null
132  const list = o && Array.isArray(o.results) ? (o.results as Record<string, unknown>[]) : []
133  const s = (v: unknown) => (typeof v === 'string' ? v : '')
134  return list
135    .map(r => ({
136      url: s(r.url),
137      noteId: s(r['Note ID']),
138      parentId: s(r['上一層']) || null,
139      title: s(r['標題']),
140      question: s(r['問題']),
141      summary: s(r['摘要']),
142      answeredBy: s(r['回答者']),
143      machine: s(r['電腦']),
144      at: Date.parse(s(r['date:建立時間:start'])) || 0,
145      unsynced: r['不同步'] === true || r['不同步'] === '__YES__',
146    }))
147    .filter(r => r.noteId !== '' && !r.noteId.startsWith('probe-'))
148}
149
150export type SyncPorts = Ports & { place(): Promise<{ remote: string | null; machine: string }>; projectKey(): Promise<string> }
151
152async function serverOf(p: Ports): Promise<string | null> {
153  return notionServer(await p.mcp.tools())
154}
155
156/**
157 * Writes one answered note as a row (properties: the question and its metadata; content:
158 * the answer). Once per note: a note already pushed or pulled is left alone. Never throws.
159 */
160export async function pushNote(p: SyncPorts, dataSource: string, node: TreeNode): Promise<'pushed' | 'skipped' | string> {
161  if (dataSource === '' || node.answer === '') return 'skipped'
162  const root = await p.projectKey()
163  if ((await p.store.get(notionKey(root, node.id))) !== undefined) return 'skipped'
164  try {
165    const server = await serverOf(p)
166    if (server === null) return 'no connector'
167    const { remote, machine } = await p.place()
168    const answer = [...node.answer].length > BODY_MAX ? `${cut(node.answer, BODY_MAX)}\n\n(答案太長,只同步前 ${BODY_MAX} 字)` : node.answer
169    const r = await p.mcp.call(server, 'notion-create-pages', {
170      parent: { data_source_id: dataSource.replace(/^collection:\/\//, '') },
171      allow_async: false,
172      pages: [
173        {
174          properties: {
175            標題: node.title,
176            問題: cut(node.question, PROP_MAX),
177            摘要: cut(node.summary ?? '', PROP_MAX),
178            專案: projectName(remote, root),
179            'Note ID': node.id,
180            上一層: node.parentId ?? '',
181            電腦: machine,
182            回答者: node.answeredBy,
183            'date:建立時間:start': new Date(node.anchor.at).toISOString(),
184            'date:建立時間:is_datetime': 1,
185          },
186          content: answer,
187        },
188      ],
189    })
190    const text = resultText(r)
191    if (r.isError) return `error ${text.slice(0, 160)}`
192    await p.store.set(notionKey(root, node.id), pageUrl(text) ?? 'pushed')
193    return 'pushed'
194  } catch (err) {
195    return `error ${String(err).slice(0, 160)}`
196  }
197}
198
199/**
200 * Brings this project's rows from other computers into the tree, oldest first so a
201 * follow-up finds its parent; newer than the last pull only. Never throws.
202 */
203export async function pullNotes(p: SyncPorts, dataSource: string, change: (fn: (t: Tree) => Tree) => Promise<Tree>, tree: Tree): Promise<{ added: number } | { error: string }> {
204  if (dataSource === '') return { added: 0 }
205  try {
206    const server = await serverOf(p)
207    if (server === null) return { error: 'no connector' }
208    const root = await p.projectKey()
209    const { remote } = await p.place()
210    const since = (await p.store.get(pullKey(root))) as number | undefined
211    const filters: unknown[] = [
212      { type: 'property', property: '專案', propertyType: 'select', operator: 'enum_is', value: { type: 'exact', value: projectName(remote, root) } },
213    ]
214    if (typeof since === 'number' && since > 0) {
215      // a day's margin: a row written late by a slow computer is not missed (the Note ID check drops repeats)
216      filters.push({ type: 'property', property: '建立時間', propertyType: 'date', operator: 'date_is_on_or_after', value: { type: 'exact', value: new Date(since - 86400000).toISOString() } })
217    }
218    const q = await p.mcp.call(server, 'notion-query-data-sources', {
219      data: {
220        mode: 'rows',
221        data_source_url: dataSource,
222        filter: { type: 'group', operator: 'and', filters },
223        sort: [{ property: '建立時間', direction: 'ascending' }],
224        limit: 100,
225      },
226    })
227    if (q.isError) return { error: resultText(q).slice(0, 160) }
228    const rows = parseRows(resultText(q))
229    let added = 0
230    let newest = typeof since === 'number' ? since : 0
231    let t = tree
232    for (const row of rows) {
233      newest = Math.max(newest, row.at)
234      if (row.unsynced || t.nodes[row.noteId] || (await p.store.get(notionKey(root, row.noteId))) !== undefined) continue
235      const page = await p.mcp.call(server, 'notion-fetch', { id: row.url })
236      if (page.isError) continue
237      const answer = pageContent(resultText(page))
238      const answeredBy = (['claude-fork', 'claude', 'openai', 'manual'] as const).find(a => a === row.answeredBy) ?? 'claude'
239      t = await change(cur => {
240        if (cur.nodes[row.noteId]) return cur
241        const made = addNode(
242          cur,
243          `notion:${row.machine}`,
244          {
245            id: row.noteId,
246            question: row.question,
247            anchor: { sessionId: `notion:${row.machine}`, turnId: null, messageId: null, at: row.at || Date.now(), mainSnippet: '' },
248            route: { label: 'synced', confidence: 1, source: 'manual' },
249            answeredBy,
250            answer,
251            title: row.title || undefined,
252          },
253          row.parentId ? { kind: 'under', parentId: row.parentId } : { kind: 'root' },
254          { makeActive: false },
255        ).tree
256        return row.summary ? updateNode(made, row.noteId, { summary: row.summary }) : made
257      })
258      await p.store.set(notionKey(root, row.noteId), row.url)
259      added++
260    }
261    if (newest > 0) await p.store.set(pullKey(root), newest)
262    return { added }
263  } catch (err) {
264    return { error: String(err).slice(0, 160) }
265  }
266}
267
268/** The page id in a Notion page URL (its last 32 hex digits). */
269export function pageIdOf(url: string): string | null {
270  return /([0-9a-f]{32})(?:[?#].*)?$/i.exec(url.replace(/-/g, ''))?.[1] ?? null
271}
272
273/**
274 * Marks the rows of these notes 不同步 (deleted on a computer). A note never pushed or
275 * pulled has no row and is skipped; one pushed before its URL was kept is found by its
276 * Note ID. Never throws; returns how many rows it marked.
277 */
278export async function markUnsynced(p: SyncPorts, dataSource: string, ids: readonly string[]): Promise<number> {
279  if (dataSource === '' || ids.length === 0) return 0
280  try {
281    const server = await serverOf(p)
282    if (server === null) return 0
283    const root = await p.projectKey()
284    let marked = 0
285    for (const id of ids) {
286      const kept = await p.store.get(notionKey(root, id))
287      if (kept === undefined) continue
288      let url = typeof kept === 'string' ? kept : ''
289      if (pageIdOf(url) === null) {
290        const q = await p.mcp.call(server, 'notion-query-data-sources', {
291          data: {
292            mode: 'rows',
293            data_source_url: dataSource,
294            filter: { type: 'group', operator: 'and', filters: [{ type: 'property', property: 'Note ID', propertyType: 'text', operator: 'string_is', value: { type: 'exact', value: id } }] },
295            limit: 1,
296          },
297        })
298        url = q.isError ? '' : (parseRowsAll(resultText(q))[0]?.url ?? '')
299      }
300      const pageId = pageIdOf(url)
301      if (pageId === null) continue
302      const r = await p.mcp.call(server, 'notion-update-page', { page_id: pageId, command: 'update_properties', properties: { 不同步: '__YES__' } })
303      if (!r.isError) marked++
304    }
305    return marked
306  } catch {
307    return 0
308  }
309}
310
311/** Every row of a query answer with a URL, the probe's and the unsynced ones too. */
312function parseRowsAll(text: string): { url: string }[] {
313  const o = jsonOf(text) as { results?: unknown } | null
314  return o && Array.isArray(o.results) ? (o.results as Record<string, unknown>[]).map(r => ({ url: typeof r.url === 'string' ? r.url : '' })) : []
315}
316
hooks/answer.ts 73 lines
1// Side answers: $.model.fork when the question needs the project, else the summary provider.
2import type { ModelForkResult } from 'claude-code'
3
4import type { AnsweredBy } from '../types'
5import { LANGUAGE_RULE } from './digest'
6import type { SummaryProvider } from './providers/types'
7
8export type QA = { question: string; answer: string }
9
10const FORK_FRAME =
11  '[sticky-notes] The user asked this as an aside. Answer the aside directly and concisely; ' +
12  'do not continue, plan or change the main task, and do not call tools. ' +
13  LANGUAGE_RULE
14
15/**
16 * ModelForkRequest is `{ prompt }` only (no system, no extra messages), so the
17 * side thread's history is written into the prompt text. See PROBE.md.
18 */
19export function buildForkPrompt(history: readonly QA[], question: string): string {
20  const parts = [FORK_FRAME]
21  if (history.length > 0) {
22    parts.push('', '[side thread so far]')
23    history.forEach((qa, i) => parts.push(`Q${i + 1}: ${qa.question}`, `A${i + 1}: ${qa.answer}`))
24  }
25  parts.push('', '[question]', question)
26  return parts.join('\n')
27}
28
29export const KNOWLEDGE_SYSTEM =
30  'You answer short background-knowledge questions for a developer. Be accurate and concise; ' +
31  'use Markdown. You do not see their project, so do not guess about it. ' +
32  LANGUAGE_RULE
33
34export function buildKnowledgePrompt(history: readonly QA[], question: string): string {
35  const lines = history.flatMap((qa, i) => [`Q${i + 1}: ${qa.question}`, `A${i + 1}: ${qa.answer}`])
36  return (lines.length ? `Earlier in this thread:\n${lines.join('\n')}\n\n` : '') + `Question: ${question}`
37}
38
39export type SideAnswer =
40  | { ok: true; text: string; answeredBy: AnsweredBy }
41  | { ok: false; reason: string }
42
43export async function answerSide(
44  fork: (prompt: string) => Promise<ModelForkResult>,
45  q: { question: string; history: readonly QA[]; answerer: 'fork' | 'summary-provider' },
46  provider: SummaryProvider | null,
47): Promise<SideAnswer> {
48  if (q.answerer === 'summary-provider' && provider) {
49    const r = await provider.summarize('knowledge-answer', {
50      system: KNOWLEDGE_SYSTEM,
51      prompt: buildKnowledgePrompt(q.history, q.question),
52      maxTokens: 1500,
53      hasProjectContent: false,
54    })
55    if (r.ok) return { ok: true, text: r.text, answeredBy: r.provider }
56    // fall through to the fork: PLAN.md「缺 OpenAI → 全部走 $.model.fork」
57  }
58  const r = await fork(buildForkPrompt(q.history, q.question))
59  if (r.isAnswered) return { ok: true, text: r.text, answeredBy: 'claude-fork' }
60  if (r.reason === 'nothing-to-fork' && provider) {
61    // A brand-new session (or right after /clear) has no transcript to fork:
62    // answer without project context through the summary provider.
63    const c = await provider.summarize('knowledge-answer', {
64      system: KNOWLEDGE_SYSTEM,
65      prompt: buildKnowledgePrompt(q.history, q.question),
66      maxTokens: 1500,
67      hasProjectContent: false,
68    })
69    return c.ok ? { ok: true, text: c.text, answeredBy: c.provider } : { ok: false, reason: c.reason }
70  }
71  return { ok: false, reason: r.reason }
72}
73