@nelsonlongxiang/dsh-prompt-templates 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,6 +29,9 @@ No Python toolchain required — since 0.3.0 the host half persists templates th
29
29
  - **Search & scroll** — filter the list as you type, reliable scrolling for long collections
30
30
  - **Drag to reposition, double-click to reset** — the panel remembers where you put it
31
31
  - **Durable by design** — templates persist in SQLite through a pure-TS store (`node:sqlite`) owned by the host plugin and closed with its lifecycle
32
+ - **Card library and intervention log** (0.16) — templates carry an effective version; version packs (`packs/`) import as stored versions without switching what is live; every time template content enters a session a durable record keeps id, version, text hash, session, turn and step, never the bodies. See [library packs](docs/library-packs.md)
33
+ - **Wrap-up self-check and card casting** (0.17) — the self-check adds one step before a working session would end its turn; it is on by default since the owner decision of 2026-11-21 (on master, not yet in a published package — the 0.17.0/0.18.0 packages ship it off); opt out with `selfCheck.enabled: false`. `cast.enabled` (off by default) lets named plugins cast one card into a session. See [the self-check contract](docs/self-check.md)
34
+ - **Lessons and handoff notice** (0.18) — lessons are on by default since the same 2026-11-21 decision (master only; the 0.18.0 package ships them off; opt out with `lessons.enabled: false`) and let a session write one- or two-sentence lessons (its own session templates under the 体会 category) that are recalled in matching situations; the handoff notice follows the event-reminder switches (off by default): once an episode exhausts its reminders and repeats, one notice asks the session to stop self-correcting and hand over. Details: `docs/spec-lesson-inject.md` and `docs/release-notes-0.18.0.md` in the source repository
32
35
 
33
36
  ## Sharing (cross-instance copy)
34
37
 
@@ -45,10 +48,10 @@ Each template (global or session-scoped) carries its own **switch + interval N**
45
48
 
46
49
  - The injected content arrives as one durable `<system-reminder>` user message recorded in the session log (source kind `prompt-template-schedule`), so replays and audits reconstruct exactly what the model saw
47
50
  - A boundary round is never injected twice, even across restarts or step retries
48
- - Config persists in the plugin's SQLite database (schema v6, including evolution enrollment); `injectEnabled: false` in the patch config silences **scheduled injection only** — event reminders (below) have their own independent master switch `eventInject.enabled`
51
+ - Config persists in the plugin's SQLite database (database schema v11 as of 0.18.0, including evolution enrollment; the gate is `SCHEMA_VERSION` in `src/store.ts`); `injectEnabled: false` in the patch config silences **scheduled injection only** — event reminders (below) have their own independent master switch `eventInject.enabled`
49
52
  - Each template picks a delivery mode: **silent** (default, model context only) or **visible in chat** (rendered as a normal user message with a ⚙️ scheduled-injection header)
50
53
 
51
- ## Atelier evolution checkpoint (unreleased)
54
+ ## Atelier evolution checkpoint (since 0.15.0)
52
55
 
53
56
  A session-scoped `工坊·演化自评估` template is provisioned once by default and scheduled every 100 user turns. Existing same-name global/session templates and user edits, disabling and deletion are preserved. This is a reminder, not migration execution or authorization. Set `evolutionAssessmentEnabled: false` to opt out. See [the lifecycle, counting and rollback contract](docs/evolution-default.md).
54
57
 
@@ -78,7 +81,7 @@ Placeholders `{{date}}` `{{time}}` `{{datetime}}` `{{weekday}}` `{{session}}` `{
78
81
  ```text
79
82
  src/ TypeScript plugin (host half + browser half)
80
83
  index.ts Host: owns the TS store, exposes the HTTP routes
81
- store.ts Pure-TS store over node:sqlite (database schema v6)
84
+ store.ts Pure-TS store over node:sqlite (database schema v11)
82
85
  inject.ts Host: scheduled auto-injection on the pre-step waterfall
83
86
  invariant.ts Host: registers the package's invariant companion
84
87
  cli/ The sync CLI (export/diff/merge/import) shipped as bin
@@ -93,7 +96,7 @@ The store is pure TS inside the host half; no child process is spawned.
93
96
 
94
97
  ## Security
95
98
 
96
- - Template **content** reaches a model request in exactly two ways: as ordinary user text the user chose to insert, or through scheduled auto-injection. User templates follow their saved switches; the unreleased Atelier default is enabled at once-per-session creation unless the deployment opts out, and remains editable/disableable/deletable by the user. Each delivered injection is a durable session event. Event reminders are a separate channel: they carry no template content, and their switch is independent of scheduled injection
99
+ - Template **content** reaches a model request in exactly two ways: as ordinary user text the user chose to insert, or through scheduled auto-injection. User templates follow their saved switches; the Atelier evolution default (shipped since 0.15.0) is enabled at once-per-session creation unless the deployment opts out, and remains editable/disableable/deletable by the user. Each delivered injection is a durable session event. The wrap-up self-check (`selfCheck.enabled`) and lessons (`lessons.enabled`) are further injection paths, on by default on master since 2026-11-21 and turned off with `false` in deployment config; card casting (`cast.enabled`) stays off by default. Event reminders are a separate channel: they carry no template content, and their switch is independent of scheduled injection
97
100
  - The panel talks to the host store over the Host's plugin routes only; no extra listener, no outbound network
98
101
 
99
102
  ## Database sync CLI
@@ -145,6 +148,8 @@ pnpm verify:release # alias of pnpm verify
145
148
 
146
149
  `pnpm verify` is the gate to run before pushing. It does not boot a DeepSeek Harness process. In order:
147
150
 
151
+ > **Windows: run it from Git Bash.** Under a PowerShell/cmd parent shell `bash` resolves to WSL first, which strips Windows env vars; the offline release-script suite (`tests/release-script.test.ts`) then skips itself with one explanatory line (`RELEASE_FIXTURE_STUBS` arrives empty, #31). From Git Bash all 40 run.
152
+
148
153
  1. **typecheck** — `tsc --noEmit` for the host project and the client project
149
154
  2. **test:cli** — `node:test` over `tests/*.test.ts`: CLI sync, store rules, schema migration, inject helpers, client filters, and an in-process host check. That check mounts `apply()` on Cordis with a stand-in web server, drives the `/plugins/dsh-prompt-templates` routes (including inject-status), and runs the `agent/pre-step` listener against a fake session log
150
155
  3. **build** — host `tsc`, client `tsc`, and the tsdown browser bundle
@@ -175,6 +180,8 @@ Pull-back verification uses ignored `tmp/release/run-*/` owned by this invocatio
175
180
 
176
181
  - **Session templates need a current session** — with no session open, only global templates are reachable
177
182
  - **Injections don't render in the chat transcript** — the DSH chat view omits injected context rows by design (they carry a non-`user` message source); see them in the trajectory tab. Templates with delivery mode **visible** are the exception: they render as ordinary user messages
183
+ - **Self-check, casting, lessons and handoff are not yet verified on a real host** — model behavior is NOT_RUN; since self-check and lessons now default on, validate in a separate `DSH_HOME` before upgrading a live host ([test plan](docs/test-plan-phase-c.md) §7)
184
+ - **Panel-sent cards record no turn or step** — intervention records from the panel's insert / send / interject keep `turn` and `step` null by design. Insert only places text in the composer and may never be sent, so it has no turn. For send and interject, the turn and step are known only once the host processes that message; the host exposes them only inside its pre-step event and has no per-session "current turn" lookup, so the record does not guess. Scheduled, event, cast and self-check records carry real turns
178
185
  - **Use the published npm build for normal installation** — Git/source installations run a `prepare` build and require the development toolchain and dependencies. The documented verification gate uses public `@deepseek-ai/*` packages and requires no harness source checkout; direct Git-URL installation is not verified by that gate. Use `dsh plugin --profile <name> add @nelsonlongxiang/dsh-prompt-templates` for a prebuilt package.
179
186
 
180
187
  ## License
package/README_zh.md CHANGED
@@ -29,6 +29,9 @@ dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
29
29
  - **搜索与滚动**——边输入边过滤,长列表滚动可靠
30
30
  - **拖拽定位、双击复位**——面板记住你放的位置
31
31
  - **设计即持久**——模板经纯 TS 存储(`node:sqlite`)落 SQLite,由 host 插件持有并随其生命周期关闭
32
+ - **卡库与介入记录**(0.16)——模板带生效版本;版本包(`packs/`)导入只存为新版本,不切换正在用的版本;模板内容每次进入会话都留一条持久记录(标识、版本、文字哈希、会话、轮、步),不记正文。见[卡库导入](docs/library-packs.md)
33
+ - **收尾自查与投卡**(0.17)——收尾自查让有活的会话在本来结束的一轮多走一步;属主 2026-11-21 裁定改为默认开(已在 master,尚未随包发布,0.17.0/0.18.0 包里仍默认关),写 `selfCheck.enabled: false` 关闭。`cast.enabled`(默认关)让点名的插件向会话投一张卡。见[收尾自查合同](docs/self-check.md)
34
+ - **体会与交接通知**(0.18)——体会按同一裁定改为默认开(仅 master,0.18.0 包里默认关;写 `lessons.enabled: false` 关闭),让会话写下一两句体会(存为它自己的会话模板,归「体会」分类),同类情境下带回;交接通知跟随事件提醒的开关(默认关):提醒次数用完后同一问题再重复,发一次通知,请会话停止自行反复修正、交给属主。细节见源码仓的 `docs/spec-lesson-inject.md` 与 `docs/release-notes-0.18.0.md`
32
35
 
33
36
  ## 分享(跨实例复制)
34
37
 
@@ -45,10 +48,10 @@ dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
45
48
 
46
49
  - 注入内容是一条持久的 `<system-reminder>` 用户消息,记入会话日志(source kind `prompt-template-schedule`),重放与审计可精确还原模型所见
47
50
  - 同一边界轮绝不重复注入——跨重启、跨步骤重试都不例外
48
- - 配置持久化在插件 SQLite 库(schema v6,含演化模板登记);patch 配置里的 `injectEnabled: false` 只关**定时注入**——事件提醒(见下)有独立总开关 `eventInject.enabled`,互不控制
51
+ - 配置持久化在插件 SQLite 库(0.18.0 起数据库 schema v11,含演化模板登记;以 `src/store.ts` 的 `SCHEMA_VERSION` 为准);patch 配置里的 `injectEnabled: false` 只关**定时注入**——事件提醒(见下)有独立总开关 `eventInject.enabled`,互不控制
49
52
  - 每条模板可选交付模式:**静默**(默认,只进模型上下文)或**对话流可见**(以普通用户消息渲染,带 ⚙️ 定时注入标记)
50
53
 
51
- ## Atelier 演化自评估(待发布)
54
+ ## Atelier 演化自评估(0.15.0 起)
52
55
 
53
56
  默认按会话补充 `工坊·演化自评估`,每100用户轮次调用 Agent Atelier 指引;已有同名模板、编辑、关闭和删除不被覆盖。仅提醒,不执行迁移或授予权限。可用 `evolutionAssessmentEnabled: false` 停用。首次历史边界不追补、升级/退出/回滚详见 [演化自评估合同](docs/evolution-default.md)。
54
57
 
@@ -78,7 +81,7 @@ dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
78
81
  ```text
79
82
  src/ TypeScript 插件(host 面 + 浏览器面)
80
83
  index.ts Host:持有 TS 存储,暴露 HTTP 路由
81
- store.ts 纯 TS 存储(node:sqlite,数据库 schema v6)
84
+ store.ts 纯 TS 存储(node:sqlite,数据库 schema v11)
82
85
  inject.ts Host:挂在 pre-step waterfall 上的定时注入
83
86
  invariant.ts Host:注册本包的 invariant 伴生插件
84
87
  cli/ 随 bin 发布的同步 CLI(export/diff/merge/import)
@@ -92,7 +95,7 @@ cordis.patch.yml Bundle patch:挂插件行
92
95
 
93
96
  ## 安全
94
97
 
95
- - 模板**内容**进入模型请求只有两条路:用户主动插入的普通用户文本,或经定时注入通道。用户模板按已保存的开关执行;本分支未发布的 Atelier 默认项在每会话首次创建时启用,可由部署退出,用户仍可编辑、关闭或删除。每次实际投递均记为持久会话事件。事件提醒是独立通道:不携带模板内容,开关也与定时注入互不控制
98
+ - 模板**内容**进入模型请求只有两条路:用户主动插入的普通用户文本,或经定时注入通道。用户模板按已保存的开关执行;0.15.0 起发布的 Atelier 演化默认项在每会话首次创建时启用,可由部署退出,用户仍可编辑、关闭或删除。每次实际投递均记为持久会话事件。收尾自查(`selfCheck.enabled`)与体会(`lessons.enabled`)是另外两条注入路径,master 上自 2026-11-21 起默认开,部署配置写 `false` 关闭;投卡(`cast.enabled`)仍默认关。事件提醒是独立通道:不携带模板内容,开关也与定时注入互不控制
96
99
  - 面板仅经 Host 的插件路由访问 host 存储;无额外监听、无外联网络
97
100
 
98
101
  ## 数据同步 CLI
@@ -144,6 +147,8 @@ pnpm verify:release # pnpm verify 的别名
144
147
 
145
148
  推送前跑 `pnpm verify`。它不启动 DeepSeek Harness 进程,顺序为:
146
149
 
150
+ > **Windows:从 Git Bash 运行。** 若父 shell 是 PowerShell/cmd,`bash` 会先解析到 WSL——WSL 剥掉 Windows 环境变量,release-script 离线套件(`tests/release-script.test.ts`)的夹具会因 `RELEASE_FIXTURE_STUBS` 为空而整套跳过并提示原因(#31);从 Git Bash 运行则 40 项全跑。
151
+
147
152
  1. **typecheck** — host 与 client 两个工程的 `tsc --noEmit`
148
153
  2. **test:cli** — `node:test` 跑 `tests/*.test.ts`:CLI 同步、store 规则、schema 迁移、注入纯函数、client 过滤,以及进程内 host 检查。该检查把 `apply()` 挂到 Cordis 上,用替身 web server 驱动 `/plugins/dsh-prompt-templates` 路由(含 inject-status),并对一份假会话日志跑 `agent/pre-step` 监听器
149
154
  3. **build** — host `tsc`、client `tsc`、tsdown 浏览器 bundle
@@ -174,6 +179,8 @@ GitHub Actions(`.github/workflows/verify.yml`)在指向 `master` 的 push /
174
179
 
175
180
  - **会话模板需要当前会话**——无会话打开时只能用全局模板
176
181
  - **注入不在对话流中渲染**——DSH 对话视图按设计省略注入的 context 行(消息 source 非 `user`);可在轨迹 tab 查看。交付模式为"对话流可见"的模板是例外:以普通用户消息渲染
182
+ - **自查、投卡、体会与交接通知尚未在真实宿主上验证**——模型行为 NOT_RUN;自查与体会已改为默认开,升级在用的宿主前先在独立 `DSH_HOME` 验证([测试计划](docs/test-plan-phase-c.md) §7)
183
+ - **面板手动发卡的记录没有轮和步**——面板的插入、直发、插话所写的介入记录,`turn`、`step` 按设计为空。插入只是把文字放进输入框,可能根本不发,本来就没有所属轮次;直发与插话落在哪一轮、哪一步,要等宿主处理到那条消息才知道,而宿主只在每一步开始前的事件里给出轮与步,没有按会话查当前轮的接口,所以记录不去猜。按轮次、按事件、投卡与收尾自查的记录都带真实轮次
177
184
  - **正式使用优先安装 npm 发布构建**——Git/源码安装会执行 `prepare` 构建,需要开发工具链和依赖。本仓所述验证门禁使用公网 `@deepseek-ai/*` 包,不需要 harness 源码检出;该门禁没有验证直接 Git-URL 安装。使用预构建包请运行 `dsh plugin --profile <name> add @nelsonlongxiang/dsh-prompt-templates`。
178
185
 
179
186
  ## 许可证
package/cordis.patch.yml CHANGED
@@ -35,3 +35,9 @@
35
35
  # maxAttempts: 3 — delivery attempts before a reminder is marked failed
36
36
  # observationWindow: 200 — redacted observations kept per session
37
37
  # ignoreTools: [] — tool names never observed
38
+ # Wrap-up self-check and lessons (ON by default since the 2026-11-21
39
+ # owner decision; write false to turn one off):
40
+ # selfCheck:
41
+ # enabled: true — selfcheck_write / selfcheck_conclude and the wrap-up check
42
+ # lessons:
43
+ # enabled: true — lesson_write, digest prompts and situational recall
@@ -23,7 +23,7 @@
23
23
 
24
24
  schema v6 新增 `evolution_defaults(session_id, template_id, source, version, enrolled_turn, disposition)`,不记录任务内容、提示词历史或私密材料。`BEGIN IMMEDIATE` + 会话主键保证多连接补充幂等;模板创建与登记同事务。v1–v5 单事务迁移,原模板不改;初始化或迁移失败会回滚并关闭本次连接,保留原错误,避免失败对象泄漏数据库句柄。CLI 兼容 v6,但模板导出不包含 enrollment/tombstone。
25
25
 
26
- 新默认项来源为 `agent-atelier/evolution-self-assessment@2`,写入登记及模板 description;v2 仅缩窄 A2A 角色/授权路由,不改变周期。旧 v1 登记与已有模板内容、启用状态、间隔、模式保持原样;新文案只用于未登记会话,绝不自动覆盖已有模板。日志继续沿用 `prompt-template-schedule` 的模板 ID/名称/间隔与 turn;描述可被用户改写,SQLite 登记才是来源事实。注入日志不是评估完成证据,更不是迁移成功证据。
26
+ (2026-11-21 起为 `@3`:首行改为「必读:本会话首次执行本卡或压缩后,必须先用 skill 工具加载 agent-atelier,按返回的基础目录读 references/evolution-self-assessment.md,再按它执行演化自评估;回复写明读了哪几处……」,末行加「本卡是属主预置的常设要求,适用即须执行;不扩大授权,不覆盖属主当下指令。」。原因:插件注入的文字不经技能加载,模型拿不到技能目录,原来的「按 agent-atelier 技能 references/… 执行」找不到文件。只影响新登记;已有会话的模板原文不改。)新默认项来源为 `agent-atelier/evolution-self-assessment@2`,写入登记及模板 description;v2 仅缩窄 A2A 角色/授权路由,不改变周期。旧 v1 登记与已有模板内容、启用状态、间隔、模式保持原样;新文案只用于未登记会话,绝不自动覆盖已有模板。日志继续沿用 `prompt-template-schedule` 的模板 ID/名称/间隔与 turn;描述可被用户改写,SQLite 登记才是来源事实。注入日志不是评估完成证据,更不是迁移成功证据。
27
27
 
28
28
  相同 turn 的耐久日志去重与进程内去重沿用原注入器。**未支持同一 DSH 会话由两个独立宿主并发执行**:本次并发保证针对 SQLite 模板补充,不声称跨宿主注入 exactly-once。技能不可用时提示词要求明确报告缺失,不自动安装或杜撰通过;这属于模型遵守的指令,并非宿主检测器。
29
29
 
@@ -31,7 +31,7 @@ schema v6 新增 `evolution_defaults(session_id, template_id, source, version, e
31
31
 
32
32
  - 本版本功能回滚:设置 `evolutionAssessmentEnabled:false`,仅停本功能补充/自动来源注入;不删模板,不改事件提醒。全部定时注入关闭用 `injectEnabled:false`。
33
33
  - 单会话关闭:面板关闭或删除生成模板,不会再补。
34
- - 包降级至仅支持 v5 的版本前,需停止写入并使用升级前的一致 SQLite 备份恢复;不得仅改 `user_version` 或删除表冒充回滚。模板 JSON 不是完整运行态备份。回滚/部署均需单独授权,本 PR 不执行。
34
+ - 包降级至仅支持 v5 的版本前,需停止写入并使用升级前的一致 SQLite 备份恢复;不得仅改 `user_version` 或删除表冒充回滚。模板 JSON 不是完整运行态备份。回滚/部署均需单独授权,本说明不执行也不授权。
35
35
  - 新宿主/全新数据库有独立登记。CLI JSON 只带模板/类目并保留其中的启用配置;经显式 dry-run/确认后,它能重建已删除模板(含原 ID),但不重置旧库登记,也不把登记复制到新库。在原库恢复相同 ID 后仍受自动来源总开关约束;在新库导入的行是显式用户配置,不因 description 文本变成受管理默认项。它不等于完整回退,也不能据此声称删除意图随 JSON 搬迁。
36
36
  - 剪贴板分享导入是另一入口:新增项默认关闭,同名覆盖保留目标开关。不要把它与保留配置的 CLI 快照导入混为一谈。跨机迁移需另核启用策略及授权。
37
37
 
@@ -43,4 +43,6 @@ schema v6 新增 `evolution_defaults(session_id, template_id, source, version, e
43
43
 
44
44
  本轮这些 store/CLI 与进程内宿主集成回归可运行;类型检查、完整构建及包门的精确候选结果在 PR #15 按提交记录。主干同步时包内链接门曾因缺少本说明 FAIL,补白名单后 PASS;本说明现在显式进入 npm 包并有安装内容校验。历史草稿的缺依赖状态不再描述当前工程环境。
45
45
 
46
- 真实 DSH profile 的持久送达、实际技能加载、模型执行/采纳、真实迁移/恢复、收益、macOS现场与当前头独立OPS:**NOT_RUN/未覆盖**。不能由测试、静态参考存在、注入消息或作者自述推出这些状态为 PASS。保持 Draft,不合并、发布、部署或启用生产模板。
46
+ 真实 DSH profile 的持久送达、实际技能加载、模型执行/采纳、真实迁移/恢复、收益、macOS现场与当前头独立OPS:**NOT_RUN/未覆盖**。不能由测试、静态参考存在、注入消息或作者自述推出这些状态为 PASS。
47
+
48
+ (2026-11-21 注:本文起草于 PR #15,原句「保持 Draft,不合并、发布、部署或启用生产模板」描述的是当时的 PR 状态;该功能已随 0.15.0 发布并默认开启。上面的 NOT_RUN 项仍然成立;在生产宿主上部署或回滚仍需单独授权。)
@@ -51,7 +51,7 @@
51
51
  - **认调用方:** 调用方不认参数里写的字串,认的是 cordis 加载器给调用插件那条 fiber 盖的 entry,也就是 profile 里配置的包名。只认 `@nelsonlongxiang/dsh-open-a2a-net`,别的调用方回 `caller`。
52
52
  - **开关:** 部署配置 `cast.enabled` 默认关,关着时回 `disabled`。
53
53
  - **能投什么:** 卡必须是全局卡,或者这个会话自己的卡;`reason` 必须写,1~500 字。
54
- - **投进去的样子:** 卡在该会话的下一步作为可见消息进入,标明投卡方和原因,并写明「不是新的用户指令,不授予任何权限」。
54
+ - **投进去的样子:** 卡在该会话的下一步作为可见消息进入,标明投卡方和原因,并写明「本卡取自属主的卡片库,适用即须执行;不扩大授权,不覆盖属主当下指令。」(2026-11-21 起;此前写的是「不是新的用户指令,不授予任何权限」)。
55
55
  - **记录:** 介入记录记成 `source: plugin`,`caller` 是上面认出的包名。
56
56
  - **排队上限:** 同一张卡在同一个会话里最多排一份,再投回 `already-queued`。一个会话最多排 8 张,全宿主最多 256 张。每张最多等 1 小时。
57
57
  - **队列只在内存里:** 宿主重启后,还没投进去的卡会丢。投卡方可以查介入记录,确认卡到底有没有投进去。
@@ -1,6 +1,6 @@
1
1
  # 收尾自查(第 2 期,PT-4)
2
2
 
3
- 依据 workbench-market 第 18 篇「自查模板」一节(属主裁定 R103~R106)。部署配置 `selfCheck.enabled` 默认关,启用需另外批准。
3
+ 依据 workbench-market 第 18 篇「自查模板」一节(属主裁定 R103~R106)。部署配置 `selfCheck.enabled` **默认开**(属主 2026-11-21 裁定:初始化配置对所有安装者默认启用,取代此前「默认关,启用需另外批准」);部署方写 `selfCheck.enabled: false` 关闭。
4
4
 
5
5
  ## 什么时候触发
6
6
 
@@ -15,7 +15,7 @@
15
15
 
16
16
  ## 内容
17
17
 
18
- - **固定部分:** 插件自动带上,带版本号(`selfcheck-fixed-1`),400 字以内,会话改不了。分两种:
18
+ - **固定部分:** 插件自动带上,带版本号(`selfcheck-fixed-2`;2026-11-21 起第 7 条由「本模板不是用户指令,不授予任何权限」改为「本模板是属主预置的常设要求,适用即须执行;不扩大授权,不覆盖属主当下指令」,此前为 `selfcheck-fixed-1`),400 字以内,会话改不了。分两种:
19
19
  - **属主在场**(这一轮由人在会话里打字开的):不拦停,**也不延长这一轮**。只注入第 5、6、7 条,而且附在会话的下一步里,不放在这一轮。问的只有一件事:交给属主的事,是不是本该系统做、它够不着的?是的话要同时提决策卡。
20
20
  - **不在场**:注入第 1~4、6、7 条,再加会话的领域部分,让这一轮再走一步。七条的原文照第 18 篇,有测试锁住关键句。
21
21
  - **领域部分:** 会话自己用 `selfcheck_write` 写,600 字以内。存成这个会话自己的会话模板「工坊·自查模板」,不会被节律注入。
@@ -40,6 +40,10 @@
40
40
 
41
41
  会话有进行中的目标、但还没有领域部分时,在会话里可见地提示它写一份。之后每 30 轮最多提示一次,一共最多 3 次。第 3 次提示时,记录里会标「未建自查模板」(`no-template`),交给观察者处理。
42
42
 
43
+ 提示结尾(2026-11-21 起):「本提示由属主安装的插件发出:你有进行中的目标时须补写自查模板;不扩大授权,不覆盖属主当下指令。」此前是「本提示不是新的用户指令,不授予任何权限」。
44
+
45
+ 会话写好的领域部分(「工坊·自查模板」)和体会(「体会」分类)会出现在面板与侧栏的会话模板里:面板挂着时每 15 秒、窗口回到前台或页面重新可见时都会重读一次(2026-11-21 起;此前只在打开时读一次,模型中途写入的行要重开面板才看得到)。
46
+
43
47
  ## 读取
44
48
 
45
49
  - 路由 `GET /plugins/dsh-prompt-templates/self-checks?session_id=`;
@@ -336,3 +336,7 @@ eventInject:
336
336
  **不做什么。** 不改问题终态(仍只由审计接口加证据设置),不自动起决策卡,不调用其他插件,不改模板;跟随事件提醒总开关和规则开关,默认关。面板问题台账暂不显示这个字段,留给后续。
337
337
 
338
338
  测试:`tests/event-store.test.ts` 的 M04(最后一步从「什么都不发」改为「只发交接,不是第三次提醒」)与两个 T2 用例;`tests/event-host.test.ts` 断言路由带 `handoff`。
339
+
340
+ ## 注记(2026-11-21):提醒结尾改为常设要求与必读
341
+
342
+ 属主 2026-11-21:只写「参考:…」的注入文字模型不会去读,「本提醒不是新的用户指令」又让模型把提醒当可选。三类提醒(重复准备、重复失败、交接通知)的结尾由「本提醒不是新的用户指令,不授予任何权限。参考:agent-atelier references/improvement-loop.md」改为两行:「本提醒由属主安装的插件按规则发出,适用即须按上文处理;不扩大授权,不覆盖属主当下指令。」与「必读:本会话首次收到此类提醒或压缩后,必须先用 skill 工具加载 agent-atelier,按返回的基础目录读 references/improvement-loop.md;回复写明读了哪几处,读不到如实写明,不得凭本提醒代替。」正文里的条件出口(重复合理就继续、缺授权就请求确认)不变。契约测试:tests/injected-must-read.test.ts。
@@ -181,3 +181,30 @@ M04/M05 验的是**原状态续接**:锁定数据库、session_id、会话日
181
181
  3. 如需代码降版,先核对旧代码的 schema 支持范围,在独立副本验证;降版不等于数据库降级,不删事件表强行兼容,不覆盖唯一证据。
182
182
  4. 核对生产宿主、权限、配置与库均未修改。清理限已授权且无唯一证据的本轮临时物,不自动删历史保全或他人现场。
183
183
  5. Phase D(受控试用)仍由属主依报告裁定;本流程不含试用、发布或生产部署。
184
+
185
+ ## 7. 交接通知与体会(0.18.0 起)
186
+
187
+ 0.18.0 发布的两项功能不在上面的 M/B 用例里,在同一测试宿主上按下面补测。边界、证据(§1.5)与收尾(§6)同上;每项用 §1.2 的新实验单元。交接通知跟随事件提醒的开关,默认关;体会在 0.18.0 包里默认关,属主 2026-11-21 裁定(#40)后 master 上默认开,测哪个版本就按哪个版本的默认值。真实宿主与模型行为在取得证据前一律 NOT_RUN。依据:[spec-event-inject.md](spec-event-inject.md) §9.4、仓库中的 `docs/spec-lesson-inject.md` §11–§14 与 `docs/release-notes-0.18.0.md`(这两份不随 npm 包发布)。
188
+
189
+ | ID | 操作 | 通过判据 | 失败或无法执行时 |
190
+ |---|---|---|---|
191
+ | H01 | 开事件提醒总开关与 `repeated-failure`;按 M02 的夹具让同一失败模式反复出现,直到该问题的提醒次数用完,过冷却后再出现一次 | 只发**一次**「【工坊·交接|…】」通知;`GET …/event-episodes` 中该问题的 `handoff` 依次经 `due`、`pending` 到 `sent`;之后不再就此出声;问题的提醒计数、冷却与状态不因交接改变 | 记 FAIL,附日志 |
192
+ | H02 | 同 H01,但在交接通知写入日志前停止宿主,再启动续接 | 重启后用同一个键重试并只送达一次;不重复发送 | 停机时机掌握不住记 NOT_RUN |
193
+ | L01 | 测 0.18.0 包时在测试 profile 设 `lessons.enabled: true`(含 #40 的版本不写这一项即为开);让同一目标先失败后成功 | 下一步出现消化提示;Agent 用 `lesson_write` 写下的「体会·N」出现在面板「体会」分类下,可见、可改、可删;不写也被允许 | 记 FAIL |
194
+ | L02 | 接 L01,制造同一工具、同样准备或同一目标的情境 | 下一次模型决策前带回那条体会;冷却内不重复唤起;不命中时不注入 | 记 FAIL |
195
+ | L03 | 用 `PATCH /plugins/dsh-prompt-templates/lessons/<template_id>`(`{"pinned": true}`)标常驻,再分别触发会话恢复与上下文压缩;最后用户主动清空上下文 | 恢复、压缩后各装载一次常驻体会(合计 ≤400 字、条数 ≤ `maxPinned`);清空上下文时不装载。本项同时核实宿主压缩后是否真的发出 `agent/created`(`source: compact`),目前只有类型声明为据 | 宿主不发该事件时记 FAIL 并附证据,这会改变 `lessons.enabled` 的启用前提;没有压缩入口记 NOT_RUN |
196
+ | D01 | 新单元,所有开关保持默认 | 交接通知零写入、零注入;0.18.0 包上体会也零写入、零注入(含 #40 的版本体会默认开,不在此判) | 记 FAIL |
197
+ | D02 | 新单元,部署配置写 `lessons.enabled: false` 与 `selfCheck.enabled: false` | 体会与自查的表、日志零写入、零注入;如 Agent 仍能看到并调用 `lesson_write`、`selfcheck_write`、`selfcheck_conclude`,调用也不产生写入(记下工具是否可见) | 记 FAIL |
198
+
199
+ ## 发版前检查:体会类型、RSI 轮次与工坊卡片轮次(2026-11-21,供 0.20.0)
200
+
201
+ **机器侧(CI 每次都跑)**:`tests/e2e-lessons-real-runtime.test.ts` 在真实 ToolRuntime 上,经 `execute` 调用全部模型工具,跑通:工坊卡注入带卡片轮次行 → 带类型写入关闭卡片轮 → 同类情境唤起开 RSI 轮 → 改写同类关闭(软覆盖、旧文进时间线)→ 下一次卡片轮用 `lesson_none` 关闭 → 提出自定类型、未批准时写入被拒、经路由批准后可写 → 时间线含全部事件 → 路由报出类型、批准状态与每卡产出。真实模型是否照做、面板实际显示不在其内。
202
+
203
+ **真机(属主,约 15 分钟)**:用含该改动的构建、新开会话,依次:
204
+
205
+ 1. 发「运行 ./check.sh,失败了就创建它(内容 echo ok)再运行」——应出现消化提示;模型写一条带类型的体会,面板「体会」分类里出现「体会·<类型>」。
206
+ 2. 再发「再做一次同样的事」——应出现「【工坊·体会·<类型>|RSI 一轮】」;模型改写这一类后,该行显示「RSI 1/1」。
207
+ 3. 发「用 lesson_type_propose 提一个新类型」——面板体会区顶部出现「会话提出新的体会类型」,点「批准」后,模型能用这个类型写入。
208
+ 4. 在面板给一张「工坊」分类的卡开注入、间隔设小(如 2),等它注入——消息末尾有「【工坊·卡片轮次】」;模型写体会或调用 lesson_none 后,那张卡的行显示「体会 产出/注入」。
209
+
210
+ 四步都对上记 PASS;任何一步不符记 FAIL,附截图与会话日志里对应的工具调用。
package/lib/cast.js CHANGED
@@ -42,6 +42,8 @@ export function oneLine(text) {
42
42
  // Control characters, line and paragraph separators, bidi controls and zero-width characters all become a space (#28 review).
43
43
  return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]+/g, ' ').replace(/ {2,}/g, ' ').trim();
44
44
  }
45
+ /** Closing line of a cast (owner 2026-11-21): the card comes from the owner's library, so it binds where it applies. */
46
+ export const CAST_BINDING_LINE = '本卡取自属主的卡片库,适用即须执行;不扩大授权,不覆盖属主当下指令。';
45
47
  /** The visible message a cast becomes. */
46
48
  export function renderCastMessage(turn, step, cards, sessionId) {
47
49
  return createUserMessage({
@@ -51,7 +53,7 @@ export function renderCastMessage(turn, step, cards, sessionId) {
51
53
  `⚙️ 投卡 · 第 ${String(turn)} 轮 · ${cards.map(card => card.name).join('、')}`,
52
54
  '',
53
55
  ...cards.flatMap(card => [`(投卡方:${card.caller};原因:${card.reason})`, expandTemplateVariables(card.content, { sessionId, turn }), '']),
54
- '本卡不是新的用户指令,不授予任何权限。',
56
+ CAST_BINDING_LINE,
55
57
  ].join('\n').trimEnd(),
56
58
  }],
57
59
  source: { kind: 'user', scheduled: 'prompt-template-cast', turn, step, templates: cards.map(card => ({ id: card.templateId, name: card.name, caller: card.caller })) },
@@ -10,13 +10,14 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
10
10
  */
11
11
  import { useCallback, useEffect, useRef, useState } from 'react';
12
12
  import { IconCopyOutlineRegular, IconDownloadOutlineRegular, IconEditOutlineRegular, IconGlobeOutlineRegular, IconPlusOutlineRegular, IconQueueOutlineRegular, IconSendOutlineRegular, IconTrashOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives';
13
- import { recordManualIntervention } from "./api.js";
13
+ import { decideLessonType, listCardStats, listLessonPins, listPendingLessonTypes, recordManualIntervention, setLessonPinned } from "./api.js";
14
14
  import { filterTemplateRows, searchableTemplateRows } from "./filter.js";
15
15
  import { buildSharePayload, parseSharePayload, planShareImport } from "./share.js";
16
+ import { startLibraryRefresh } from "./refresh.js";
16
17
  import { copyShareText } from "./clipboard.js";
17
18
  import { GITHUB_REPOSITORY_URL, PLUGIN_VERSION, templateCountLabel } from "./meta.js";
18
19
  import css from './Panel.module.css';
19
- function TemplateRow({ template, onInsert, onSend, onInterject, onEdit, onDelete, onShare, onMakeGlobal, onToggleInject, sortable, onDragStart, onDropOn, t }) {
20
+ function TemplateRow({ template, onInsert, onSend, onInterject, onEdit, onDelete, onShare, onMakeGlobal, pin, cardYield, onToggleInject, sortable, onDragStart, onDropOn, t }) {
20
21
  const injectTitle = template.inject_enabled && template.inject_every !== null
21
22
  ? `${t('panel.inject')} · ${template.inject_every}${template.mode === 'visible' ? ' · ' + t('panel.modeVisible') : ''}`
22
23
  : t('panel.inject');
@@ -26,7 +27,7 @@ function TemplateRow({ template, onInsert, onSend, onInterject, onEdit, onDelete
26
27
  e.preventDefault();
27
28
  e.stopPropagation();
28
29
  onDropOn(template.id);
29
- } }, children: [_jsxs("button", { type: "button", className: css.insert, onClick: () => { onInsert(template); }, title: t('panel.insert'), children: [_jsx("span", { className: css.name, children: template.name }), _jsx("span", { className: css.preview, children: template.content })] }), _jsxs("button", { type: "button", className: template.inject_enabled ? css.injectBtnActive : css.injectBtn, onClick: () => { onToggleInject(template); }, "aria-label": t('panel.inject'), "aria-pressed": template.inject_enabled, title: injectTitle, children: ["\u27F3", template.inject_enabled && template.inject_every !== null ? template.inject_every : ''] }), _jsx("button", { type: "button", className: css.interjectBtn, onClick: () => { onInterject(template); }, "aria-label": t('panel.interject'), title: t('panel.interject'), children: _jsx(IconQueueOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.sendBtn, onClick: () => { onSend(template); }, "aria-label": t('panel.sendNow'), title: t('panel.sendNow'), children: _jsx(IconSendOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.shareBtn, onClick: (event) => { onShare(template, event.currentTarget); }, "aria-label": t('panel.share'), title: t('panel.share'), children: _jsx(IconCopyOutlineRegular, { size: 12 }) }), onMakeGlobal !== undefined && (_jsx("button", { type: "button", className: css.globalBtn, onClick: () => { onMakeGlobal(template.id); }, "aria-label": t('panel.makeGlobal'), title: t('panel.makeGlobal'), children: _jsx(IconGlobeOutlineRegular, { size: 12 }) })), _jsx("button", { type: "button", className: css.editBtn, onClick: () => { onEdit(template.id); }, "aria-label": t('panel.edit'), title: t('panel.edit'), children: _jsx(IconEditOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.deleteBtn, onClick: () => { onDelete(template.id); }, "aria-label": t('panel.delete'), children: _jsx(IconTrashOutlineRegular, { size: 12 }) })] }));
30
+ } }, children: [_jsxs("button", { type: "button", className: css.insert, onClick: () => { onInsert(template); }, title: t('panel.insert'), children: [_jsx("span", { className: css.name, children: template.name }), _jsx("span", { className: css.preview, children: template.content })] }), _jsxs("button", { type: "button", className: template.inject_enabled ? css.injectBtnActive : css.injectBtn, onClick: () => { onToggleInject(template); }, "aria-label": t('panel.inject'), "aria-pressed": template.inject_enabled, title: injectTitle, children: ["\u27F3", template.inject_enabled && template.inject_every !== null ? template.inject_every : ''] }), _jsx("button", { type: "button", className: css.interjectBtn, onClick: () => { onInterject(template); }, "aria-label": t('panel.interject'), title: t('panel.interject'), children: _jsx(IconQueueOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.sendBtn, onClick: () => { onSend(template); }, "aria-label": t('panel.sendNow'), title: t('panel.sendNow'), children: _jsx(IconSendOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.shareBtn, onClick: (event) => { onShare(template, event.currentTarget); }, "aria-label": t('panel.share'), title: t('panel.share'), children: _jsx(IconCopyOutlineRegular, { size: 12 }) }), onMakeGlobal !== undefined && (_jsx("button", { type: "button", className: css.globalBtn, onClick: () => { onMakeGlobal(template.id); }, "aria-label": t('panel.makeGlobal'), title: t('panel.makeGlobal'), children: _jsx(IconGlobeOutlineRegular, { size: 12 }) })), pin !== undefined && (_jsx("button", { type: "button", className: pin.pinned ? css.injectBtnActive : css.injectBtn, onClick: () => { pin.onToggle(); }, "aria-label": pin.pinned ? t('panel.unpin') : t('panel.pin'), "aria-pressed": pin.pinned, title: pin.pinned ? t('panel.unpin') : t('panel.pin'), children: "\uD83D\uDCCC" })), cardYield !== undefined && cardYield.injected > 0 && (_jsxs("span", { className: css.injectBadge, title: t('panel.cardYield').replace('{injected}', String(cardYield.injected)).replace('{lessons}', String(cardYield.lessons)).replace('{none}', String(cardYield.none)).replace('{missed}', String(cardYield.missed)), children: ["\u4F53\u4F1A ", cardYield.lessons, "/", cardYield.injected] })), pin?.rounds !== undefined && pin.rounds.opened > 0 && (_jsxs("span", { className: css.injectBadge, title: t('panel.rounds').replace('{opened}', String(pin.rounds.opened)).replace('{closed}', String(pin.rounds.closed)).replace('{missed}', String(pin.rounds.missed)), children: ["RSI ", pin.rounds.closed, "/", pin.rounds.opened] })), _jsx("button", { type: "button", className: css.editBtn, onClick: () => { onEdit(template.id); }, "aria-label": t('panel.edit'), title: t('panel.edit'), children: _jsx(IconEditOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.deleteBtn, onClick: () => { onDelete(template.id); }, "aria-label": t('panel.delete'), children: _jsx(IconTrashOutlineRegular, { size: 12 }) })] }));
30
31
  }
31
32
  /** The template inline form: creation (with scope + category pickers) and in-place edit. */
32
33
  function TemplateForm({ initial, allowScope, sessionId, categories, t, submitLabel, onSubmit, onDone, onCancel }) {
@@ -142,6 +143,13 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
142
143
  void load();
143
144
  void loadCategories();
144
145
  }, [load, loadCategories]);
146
+ // Rows the agent writes with its own tools (selfcheck_write, lesson_write) land server-side while this library stays
147
+ // mounted; re-read rows and categories on a timer, on focus and on visibility, and whenever the target session changes.
148
+ useEffect(() => {
149
+ void load();
150
+ void loadCategories();
151
+ return startLibraryRefresh(() => { void load(); void loadCategories(); });
152
+ }, [load, loadCategories, sessionId]);
145
153
  // Toolbar badge `⟳N`: the target session's latest scheduled injection,
146
154
  // polled every 30s (and re-read whenever the target changes). null hides
147
155
  // the badge — the route is memory-only, so polling stays O(1).
@@ -247,6 +255,46 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
247
255
  setManualShare(null);
248
256
  return () => { shareRequest.current += 1; };
249
257
  }, [sessionId]);
258
+ // 体会 pins (phase 2): only the session's own lessons get the toggle; the host enforces the quota.
259
+ const [lessonPins, setLessonPins] = useState(new Map());
260
+ const [lessonRounds, setLessonRounds] = useState(new Map());
261
+ const loadLessonPins = useCallback(async () => {
262
+ if (sessionId === null) {
263
+ setLessonPins(new Map());
264
+ setLessonRounds(new Map());
265
+ return;
266
+ }
267
+ const items = await listLessonPins(sessionId);
268
+ setLessonPins(new Map(items.map(item => [item.id, item.pinned])));
269
+ setLessonRounds(new Map(items.map(item => [item.id, item.rounds])));
270
+ }, [sessionId]);
271
+ useEffect(() => { void loadLessonPins(); }, [loadLessonPins, templates]);
272
+ // Workshop-card yields in this session (card rounds): shown on the card rows.
273
+ const [cardYields, setCardYields] = useState(new Map());
274
+ const loadCardYields = useCallback(async () => {
275
+ setCardYields(new Map(sessionId === null ? [] : (await listCardStats(sessionId)).map(card => [card.template_id, card])));
276
+ }, [sessionId]);
277
+ useEffect(() => { void loadCardYields(); }, [loadCardYields, templates]);
278
+ // Lesson types the session proposed (lesson_type_propose): only the owner approves them, here.
279
+ const [pendingTypes, setPendingTypes] = useState([]);
280
+ const loadPendingTypes = useCallback(async () => {
281
+ setPendingTypes(sessionId === null ? [] : await listPendingLessonTypes(sessionId));
282
+ }, [sessionId]);
283
+ useEffect(() => { void loadPendingTypes(); }, [loadPendingTypes, templates]);
284
+ const handleDecideType = useCallback(async (name, approved) => {
285
+ if (sessionId === null)
286
+ return;
287
+ const result = await decideLessonType(sessionId, name, approved);
288
+ if (!result.ok)
289
+ setNotice(result.error.message);
290
+ await loadPendingTypes();
291
+ }, [sessionId, loadPendingTypes]);
292
+ const handleTogglePin = useCallback(async (id) => {
293
+ const result = await setLessonPinned(id, lessonPins.get(id) !== true);
294
+ if (!result.ok)
295
+ setNotice(result.error.code === 'pinned-full' ? t('panel.pinFull') : result.error.message);
296
+ await loadLessonPins();
297
+ }, [lessonPins, loadLessonPins, t]);
250
298
  useEffect(() => {
251
299
  if (notice === null)
252
300
  return;
@@ -455,7 +503,7 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
455
503
  });
456
504
  return result.ok;
457
505
  }, onDone: () => { setEditingId(null); void load(); }, onCancel: () => { setEditingId(null); } }, row.id))
458
- : (_jsx(TemplateRow, { template: row, onInsert: (c) => { handleInsert(c); }, onSend: (c) => { handleSend(c); }, onInterject: (c) => { handleInterject(c); }, onEdit: (id) => { setEditingId(id); }, onDelete: (id) => { void handleRemove(id); }, onShare: (tpl, trigger) => { void handleShareTemplate(tpl, trigger); }, onMakeGlobal: row.scope === 'session' ? (id) => { void handleMakeGlobal(id); } : undefined, onToggleInject: (tpl) => { void handleToggleInject(tpl); }, sortable: needle === '', onDragStart: (id) => { dragRowRef.current = id; }, onDropOn: (id) => { handleRowDrop(id); }, t: t }, row.id)));
506
+ : (_jsx(TemplateRow, { template: row, onInsert: (c) => { handleInsert(c); }, onSend: (c) => { handleSend(c); }, onInterject: (c) => { handleInterject(c); }, onEdit: (id) => { setEditingId(id); }, onDelete: (id) => { void handleRemove(id); }, onShare: (tpl, trigger) => { void handleShareTemplate(tpl, trigger); }, onMakeGlobal: row.scope === 'session' ? (id) => { void handleMakeGlobal(id); } : undefined, pin: lessonPins.has(row.id) ? { pinned: lessonPins.get(row.id) === true, onToggle: () => { void handleTogglePin(row.id); }, rounds: lessonRounds.get(row.id) } : undefined, cardYield: cardYields.get(row.id), onToggleInject: (tpl) => { void handleToggleInject(tpl); }, sortable: needle === '', onDragStart: (id) => { dragRowRef.current = id; }, onDropOn: (id) => { handleRowDrop(id); }, t: t }, row.id)));
459
507
  return (_jsxs("div", { className: css.library, "data-prompt-library": true, children: [_jsxs("div", { className: header !== undefined ? `${css.toolbar} ${css.toolbarDraggable}` : css.toolbar, title: header?.hint, onPointerDown: header?.onPointerDown, onPointerMove: header?.onPointerMove, onPointerUp: header?.onPointerUp, onDoubleClick: header?.onDoubleClick, children: [_jsxs("span", { className: css.titleGroup, children: [_jsx("span", { className: css.title, children: t('panel.title') }), _jsx("span", { className: css.countBadge, "data-template-count": true, title: needle !== '' ? t('panel.searchCount') : t('panel.tabCount'), children: countLabel }), injected !== null && (_jsxs("button", { type: "button", className: `${css.injectBadge} ${css.injectBadgeButton}`, "data-prompt-injected": true, title: `${t('panel.injectedAt')} ${injected.turn} · ${new Date(injected.at).toLocaleTimeString()} · ${injected.templates.join(', ')}`, "aria-label": t('panel.historyTitle'), "aria-expanded": historyOpen, onClick: () => { setHistoryOpen(open => !open); }, children: ["\u27F3", injected.turn] })), _jsx("button", { type: "button", className: css.importBtn, onClick: () => { setShowImport(v => !v); }, "aria-label": t('panel.import'), "aria-expanded": showImport, title: t('panel.import'), children: _jsx(IconDownloadOutlineRegular, { size: 12 }) }), _jsx("button", { type: "button", className: css.importBtn, "data-prompt-events-toggle": true, onClick: () => { setEventsOpen(open => !open); }, "aria-label": t('panel.eventsTitle'), "aria-expanded": eventsOpen, title: t('panel.eventsTitle'), children: "\u2699" })] }), headerExtra] }), notice !== null && _jsx("div", { className: css.notice, role: "status", children: notice }), manualShare !== null && (_jsxs("section", { className: css.importForm, "data-prompt-share-manual": true, "aria-label": t('panel.shareManualTitle'), children: [_jsxs("div", { role: "status", children: [t(manualShare.failure.kind === 'unavailable' ? 'panel.copyUnavailable'
460
508
  : manualShare.failure.kind === 'unfocused' ? 'panel.copyUnfocused'
461
509
  : manualShare.failure.kind === 'denied' ? 'panel.copyDenied'
@@ -478,7 +526,7 @@ export function TemplateLibrary({ sessionId, face, t, header, headerExtra }) {
478
526
  }
479
527
  })();
480
528
  }, children: "\u00D7" })] }, key));
481
- }), _jsx("button", { type: "button", className: css.tabAdd, "aria-label": t('panel.newCategory'), title: t('panel.newCategory'), onClick: () => { setShowCatForm(v => !v); }, children: _jsx(IconPlusOutlineRegular, { size: 10 }) })] }), showCatForm && (_jsx(CategoryForm, { sessionId: sessionId, createCategory: createCategory, t: t, onDone: () => { setShowCatForm(false); void loadCategories(); } })), _jsxs("div", { className: css.body, children: [rowError !== null && (_jsxs("div", { className: css.error, role: "alert", "data-prompt-row-error": true, children: [t('panel.error'), " \u00B7 ", rowError] })), tabRows.length === 0 && !showAdd && !showCatForm && (_jsx("div", { className: css.empty, children: needle !== '' ? t('panel.noMatch') : t('panel.empty') })), tabRows.length > 0 && (_jsx("div", { className: css.group, onDragOver: (e) => { e.preventDefault(); }, children: tabRows.map(row => renderTemplateRow(row)) })), showAdd && (_jsx(TemplateForm, { sessionId: sessionId, categories: visibleCategories, t: t, allowScope: true, submitLabel: t('panel.addSave'), onSubmit: async (name, content, scope, category, injectEnabled, injectEvery, mode) => {
529
+ }), _jsx("button", { type: "button", className: css.tabAdd, "aria-label": t('panel.newCategory'), title: t('panel.newCategory'), onClick: () => { setShowCatForm(v => !v); }, children: _jsx(IconPlusOutlineRegular, { size: 10 }) })] }), showCatForm && (_jsx(CategoryForm, { sessionId: sessionId, createCategory: createCategory, t: t, onDone: () => { setShowCatForm(false); void loadCategories(); } })), _jsxs("div", { className: css.body, children: [rowError !== null && (_jsxs("div", { className: css.error, role: "alert", "data-prompt-row-error": true, children: [t('panel.error'), " \u00B7 ", rowError] })), pendingTypes.map(type => (_jsxs("div", { className: css.notice, "data-prompt-lesson-type": type.name, children: [t('panel.typeProposed'), "\u300C", type.name, "\u300D\uFF1A", type.description, ' ', _jsx("button", { type: "button", onClick: () => { void handleDecideType(type.name, true); }, children: t('panel.typeApprove') }), ' ', _jsx("button", { type: "button", onClick: () => { void handleDecideType(type.name, false); }, children: t('panel.typeReject') })] }, type.name))), tabRows.length === 0 && !showAdd && !showCatForm && (_jsx("div", { className: css.empty, children: needle !== '' ? t('panel.noMatch') : t('panel.empty') })), tabRows.length > 0 && (_jsx("div", { className: css.group, onDragOver: (e) => { e.preventDefault(); }, children: tabRows.map(row => renderTemplateRow(row)) })), showAdd && (_jsx(TemplateForm, { sessionId: sessionId, categories: visibleCategories, t: t, allowScope: true, submitLabel: t('panel.addSave'), onSubmit: async (name, content, scope, category, injectEnabled, injectEvery, mode) => {
482
530
  const result = await create({
483
531
  name,
484
532
  content,
package/lib/client/api.js CHANGED
@@ -98,6 +98,60 @@ export async function eventEpisodes(sessionId) {
98
98
  const body = await response.json();
99
99
  return [...body.items ?? []];
100
100
  }
101
+ /** Load a session's lessons with their pin state (empty when none, unavailable, or the host predates lessons). */
102
+ export async function listLessonPins(sessionId) {
103
+ try {
104
+ const response = await fetch(`${BASE}/lessons?session_id=${encodeURIComponent(sessionId)}`, { cache: 'no-store' });
105
+ if (!response.ok)
106
+ return [];
107
+ const body = await response.json();
108
+ const n = (v) => typeof v === 'number' && Number.isFinite(v) ? v : 0;
109
+ return (body.items ?? []).filter(item => typeof item.id === 'string').map(item => ({
110
+ id: item.id, pinned: item.pinned === true,
111
+ rounds: { opened: n(item.rounds?.opened), closed: n(item.rounds?.closed), missed: n(item.rounds?.missed) },
112
+ }));
113
+ }
114
+ catch {
115
+ return [];
116
+ }
117
+ }
118
+ /** A session's workshop-card yields (empty when none, unavailable, or the host predates card rounds). */
119
+ export async function listCardStats(sessionId) {
120
+ try {
121
+ const response = await fetch(`${BASE}/lessons?session_id=${encodeURIComponent(sessionId)}`, { cache: 'no-store' });
122
+ if (!response.ok)
123
+ return [];
124
+ const body = await response.json();
125
+ const n = (v) => typeof v === 'number' && Number.isFinite(v) ? v : 0;
126
+ return (body.cards ?? []).filter(card => typeof card['template_id'] === 'string')
127
+ .map(card => ({ template_id: card['template_id'], injected: n(card['injected']), lessons: n(card['lessons']), none: n(card['none']), missed: n(card['missed']) }));
128
+ }
129
+ catch {
130
+ return [];
131
+ }
132
+ }
133
+ /** The session's proposed lesson types still waiting for the owner (empty when none or unavailable). */
134
+ export async function listPendingLessonTypes(sessionId) {
135
+ try {
136
+ const response = await fetch(`${BASE}/lessons?session_id=${encodeURIComponent(sessionId)}`, { cache: 'no-store' });
137
+ if (!response.ok)
138
+ return [];
139
+ const body = await response.json();
140
+ return (body.types ?? []).filter(type => type.builtin !== true && type.status === 'pending' && typeof type.name === 'string')
141
+ .map(type => ({ name: type.name, description: typeof type.description === 'string' ? type.description : '' }));
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ }
147
+ /** The owner approves or rejects a proposed lesson type of one session. */
148
+ export function decideLessonType(sessionId, name, approved) {
149
+ return mutate('PATCH', `/lesson-types/${encodeURIComponent(name)}?session_id=${encodeURIComponent(sessionId)}`, { approved });
150
+ }
151
+ /** The owner pins or unpins one lesson; a full pin quota settles as error code `pinned-full`. */
152
+ export function setLessonPinned(templateId, pinned) {
153
+ return mutate('PATCH', `/lessons/${encodeURIComponent(templateId)}`, { pinned });
154
+ }
101
155
  /** Run one mutating request and settle it into the action envelope. */
102
156
  async function mutate(method, path, body) {
103
157
  try {
@@ -32,6 +32,14 @@ export const zh = {
32
32
  'panel.delete': '删除',
33
33
  'panel.edit': '编辑',
34
34
  'panel.makeGlobal': '设为全局',
35
+ 'panel.pin': '设为常驻体会(会话开始、恢复和压缩后装载)',
36
+ 'panel.unpin': '取消常驻',
37
+ 'panel.pinFull': '常驻体会已达上限,先取消一条再设',
38
+ 'panel.rounds': 'RSI 轮次:唤起 {opened},已闭合 {closed},未闭合 {missed}',
39
+ 'panel.typeProposed': '会话提出新的体会类型',
40
+ 'panel.cardYield': '本会话里这张工坊卡:注入 {injected},产出体会 {lessons},无可记 {none},未闭合 {missed}',
41
+ 'panel.typeApprove': '批准',
42
+ 'panel.typeReject': '拒绝',
35
43
  'panel.inject': '定时注入',
36
44
  'panel.injectEvery': '注入间隔(轮)',
37
45
  'panel.variablesHint': '支持变量:{{date}} {{time}} {{datetime}} {{weekday}} {{session}} {{turn}}(发送/注入时展开,不可得时保留原文)',
@@ -110,6 +118,14 @@ export const en = {
110
118
  'panel.delete': 'Delete',
111
119
  'panel.edit': 'Edit',
112
120
  'panel.makeGlobal': 'Make global',
121
+ 'panel.pin': 'Pin this lesson (loaded at session start, resume and after compaction)',
122
+ 'panel.unpin': 'Unpin',
123
+ 'panel.pinFull': 'Pinned lessons are at the limit; unpin one first',
124
+ 'panel.rounds': 'RSI rounds: recalled {opened}, closed {closed}, missed {missed}',
125
+ 'panel.typeProposed': 'The session proposes a new lesson type',
126
+ 'panel.cardYield': 'This workshop card in this session: injected {injected}, lessons {lessons}, no entry {none}, missed {missed}',
127
+ 'panel.typeApprove': 'Approve',
128
+ 'panel.typeReject': 'Reject',
113
129
  'panel.inject': 'Auto-inject',
114
130
  'panel.injectEvery': 'Every (rounds)',
115
131
  'panel.variablesHint': 'Variables: {{date}} {{time}} {{datetime}} {{weekday}} {{session}} {{turn}} (expanded at delivery; unresolved stay literal)',
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Keep the template library current while it stays mounted (owner 2026-11-21: a self-check template or a lesson the
3
+ * model wrote with its tools never showed in the session tab). The library used to read the rows once on mount, and
4
+ * the sidebar tab stays mounted for the whole conversation, so rows the agent wrote server-side never arrived. This
5
+ * re-reads on a timer, when the window regains focus, and when the page becomes visible again.
6
+ * @module @nelsonlongxiang/dsh-prompt-templates/client/refresh
7
+ */
8
+ /** How often the mounted library re-reads its rows, in milliseconds. */
9
+ export const LIBRARY_REFRESH_MS = 15_000;
10
+ /**
11
+ * Start re-reading. `reload` is called on every tick, on window focus and when the document turns visible; never while
12
+ * it is hidden. Returns the stop function for an effect cleanup.
13
+ */
14
+ export function startLibraryRefresh(reload, targets = defaultTargets(), intervalMs = LIBRARY_REFRESH_MS) {
15
+ const doc = targets.document;
16
+ const visible = () => doc?.visibilityState === undefined || doc.visibilityState === 'visible';
17
+ const tick = () => { if (visible())
18
+ reload(); };
19
+ const onVisibility = () => { if (visible())
20
+ reload(); };
21
+ const set = targets.setInterval ?? ((fn, ms) => globalThis.setInterval(fn, ms));
22
+ const clear = targets.clearInterval ?? ((handle) => { globalThis.clearInterval(handle); });
23
+ const handle = set(tick, intervalMs);
24
+ targets.window?.addEventListener('focus', tick);
25
+ doc?.addEventListener('visibilitychange', onVisibility);
26
+ return () => {
27
+ clear(handle);
28
+ targets.window?.removeEventListener('focus', tick);
29
+ doc?.removeEventListener('visibilitychange', onVisibility);
30
+ };
31
+ }
32
+ function defaultTargets() {
33
+ const g = globalThis;
34
+ return { window: g.window, document: g.document };
35
+ }