pi-auto-unattended 0.5.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.7.0 (2026-12-05)
4
+
5
+ - 新增**交接线**(用户口径:全天候 agent = 一个 agent 做完本轮把活交给下一轮):`agent_before_settle`
6
+ 时用 `ctx.getContextUsage()` 读真实百分比(与 footer/`context_usage` 同一个数),到线(默认 **35%**,
7
+ `PI_AUTO_HANDOFF_AT` 可改)且本轮 idle:
8
+ - **无人值守会话(keepAlive)**:把「续轮草稿」换成「交接草稿」——本会话只写 brief 并
9
+ `session_handoff`,交接后新会话接着干(上下文回到 ~0)。提醒过一次还没交接 ⇒ 升级口径(本会话只做交接);
10
+ 百分比回落到「阈值 −5」以下自动重新武装(压缩后不再骚扰),audit `handoff-remind` / `handoff-rearm`。
11
+ - **手开会话**:只 `ui.notify` 提一句(不注入消息、不触发新一轮),同一条线只提一次,audit `handoff-notify`。
12
+ - **`PI_AUTO_HANDOFF=auto`(opt-in)**:插件按仓内可核实事实自己拼 mechanical brief(AGENTS/TODO/PLAN 指针 +
13
+ `git log --oneline -5` + `git status --short` 前 20 行 + 推进口径),settle 后直接派 `/handoff-new`,
14
+ 不需要模型再跑一轮;`handoff-auto` / `handoff-auto-pending`。检测到 settings 里没有 pi-agent-handoff ⇒
15
+ 自动退回提醒口径(不派不存在的命令)。
16
+ - 计时器跟着**进程**走:`/new`、交接(`session_shutdown.reason=new`)不再丢计时器,只有真退出才清;
17
+ 启动时清掉持有者 pid 已死的孤儿计时器文件(audit `timer-prune`)。
18
+ - 回归:`node --test` 23 → 31 条全 pass(判据纯函数、两档文案、到线换草稿/升级/重新武装、
19
+ 手开会话只 notify、auto 模式派 `/handoff-new` 且 brief 含仓内事实、未装 handoff 退回 remind、
20
+ 交接不丢计时器 + 孤儿清理)。
21
+ - 实测(remind 口径,真会话):`/tmp` e2e 会话在闸门触发后交出 brief → 新会话接 kickoff → 立刻 `auto_switch off`,
22
+ audit 依次 `session-start → continue → session-end(reason=new) → session-start`,无死循环。
23
+
24
+ ## 0.6.0 (2026-12-05)
25
+
26
+ - 新增工具 **`auto_timer`**:会话内自主预约「到点唤醒」。`auto_timer({after:"25m", note:"…"})` 调完
27
+ 直接结束本轮,到点由 pi-mailbox 递一条消息把会话叫起来;等待期间不烧 token、不占工具位。
28
+ 落 `state/auto/timers/<pid>.json`,支持 `list` / `cancel`;`agent_before_settle` 在有计时器时
29
+ **不再空转续轮**(audit `timer-wait`),到点 audit `timer-fired`。上限 7 天,跨天开工退回 `auto_schedule`。
30
+ - 新增工具 **`auto_bg`**:跑一条长命令并在**命令真的结束**时唤醒(不是按时长赌)。进程 `detached`
31
+ 脱离会话、输出进 `state/auto/bg/<id>/out.log`、子 shell 包一层保证 `exit N`/`set -e` 也拿得到 rc;
32
+ 会话内 5 s 轮询 rc(`PI_AUTO_BG_POLL_MS` 可调),落盘即经 pi-mailbox 带 rc + 日志尾叫醒
33
+ (audit `bg-done`);`list` / `tail` / `cancel`(杀进程组)。
34
+ - 动机(实测数字):2026-12-05 07:40 的 limbus 真机批会话 113 min 里 110 min 是 `bash sleep 1500`,
35
+ 一次 abort 整轮作废(0 收口)。`auto_switch` 的 `promptGuidelines` 相应改写:长等待不再建议轮内 `sleep`。
36
+ - 回归:`parseAfter` / set-list-cancel / 有计时器时 settle 不续轮 / 到点 mailbox / 重启后过期计时器立刻叫 /
37
+ `auto_bg` 完成带 rc=3 与日志尾且不重复叫醒 / cancel 真杀进程组;`node --test` 17 → 23 条全 pass。
38
+
3
39
  ## 0.5.0 (2026-12-05)
4
40
 
5
41
  - 新增工具 **`auto_today`**:agent 写今日补充(`today.prompt`)的唯一通道,作用域**默认 = 会话 cwd**
package/README.md CHANGED
@@ -147,6 +147,52 @@ auto_schedule({ action: "cancel", id: "sch-…" }) // 取消(id:"all"
147
147
  - 只写 plan.json,**不影响当前会话**(`auto_switch` 管续轮,预约管排班;两者正交)。
148
148
  - 落地时不需要装 systemd timer:daemon 每 60s 扫一次 `schedules`。
149
149
 
150
+ ## 交接线:上下文 30–40% 且本轮 idle ⇒ 交给下一轮
151
+
152
+ 「全天候 agent」的前提是**一个 agent 做完本轮把活交给下一轮**,而不是一路干到 80% 再崩。判据在
153
+ `agent_before_settle`(本轮真的 idle):
154
+
155
+ | 场景 | 行为 |
156
+ |---|---|
157
+ | 无人值守会话(keepAlive) | 把「续轮草稿」换成「**交接草稿**」:写自包含 brief + `session_handoff`,新会话接着干(上下文回 ~0);提醒过一次还没交接 ⇒ 升级口径(本会话只做交接) |
158
+ | 手开会话 | 只 `ui.notify` 提一句(不注入消息、不触发新一轮),同一条线只提一次 |
159
+ | `PI_AUTO_HANDOFF=auto` | 插件按仓内事实拼 mechanical brief,settle 后**直接派 `/handoff-new`**,不需要模型再跑一轮 |
160
+
161
+ - 阈值:默认 **35%**(`PI_AUTO_HANDOFF_AT=35`),读数用 `ctx.getContextUsage()`(与 footer/`context_usage` 同源);
162
+ 读数未知(刚压缩完)就什么都不做。回落到「阈值 −5」以下自动重新武装(audit `handoff-rearm`)。
163
+ - `PI_AUTO_HANDOFF=off` 关掉;`remind`(默认)由模型写 brief,`auto` 由插件写 brief(要求 settings 里已装
164
+ `pi-agent-handoff`,否则自动退回 `remind`)。
165
+ - audit 关键字:`handoff-notify` / `handoff-remind` / `handoff-rearm` / `handoff-auto-pending` / `handoff-auto`。
166
+ - 边界:交接由 `pi-agent-handoff` 完成会话替换(TUI-only);opencode 形态的 `--mode json` 会话不会被交接。
167
+
168
+ ## 给 agent 的入口(三):`auto_timer` / `auto_bg`(等东西,但不空转)
169
+
170
+ 2026-12-05 之前的口径是「等 CI/跑批就在轮内 `bash sleep 1500`」。limbus 那轮的真机批实证了代价:
171
+ 113 min 的会话里 110 min 是 `sleep`,一次 abort(用户登录后关掉 pane)整轮就白等,什么都没落地。
172
+ 现在给两个**调完就结束本轮**的入口,等的东西好了再由 pi-mailbox 把会话叫起来:
173
+
174
+ ```js
175
+ // 按钟点:25 分钟后叫醒我,去看批进度
176
+ auto_timer({ action: "set", after: "25m", note: "看 perf-stats 的 actions/ocr 计数" })
177
+ auto_timer({ action: "list" }) // 本会话排着的计时器
178
+ auto_timer({ action: "cancel", id: "tm-…" }) // 取消(id:"all" 清空)
179
+
180
+ // 按「命令真的结束」:跑一条长命令,结束时带 rc + 日志尾叫醒我
181
+ auto_bg({ action: "run", command: "timeout -k 60 9600 bash tools/aacl-run.sh tools/run-aalc-mirror.py --minutes 150" })
182
+ auto_bg({ action: "list" }) // 本会话的后台命令(running / rc=N)
183
+ auto_bg({ action: "tail", id: "bg-…" }) // 看日志尾
184
+ auto_bg({ action: "cancel", id: "bg-…" }) // 杀整个进程组
185
+ ```
186
+
187
+ - `auto_timer`:只吃相对时长(`25m` / `90s` / `2h` / `150分钟`,上限 7 天),落
188
+ `state/auto/timers/<pid>.json`;排着计时器时 `agent_before_settle` **不空转续轮**(audit `timer-wait`),
189
+ 到点写一条 pi-mailbox 消息(audit `timer-fired`)。跨天/跨进程开工仍用 `auto_schedule`。
190
+ - `auto_bg`:`/bin/bash -c` 起**脱离会话**的进程(`detached`,pi 退出不影响它),stdout/stderr 进
191
+ `state/auto/bg/<id>/out.log`,包一层子 shell 保证命令自己 `exit N`/`set -e` 也能拿到 rc;
192
+ 会话内每 5 s 轮询 rc 文件(`PI_AUTO_BG_POLL_MS` 可调),落盘即叫醒(audit `bg-done`)。
193
+ - 边界(诚实写清楚):两个都依赖**会话进程活着**——会话被 kill/`q` 掉,唤醒就没了(命令照样跑完),
194
+ 那种场景用 `auto_schedule` 预约到点回收;子代理进程不加载本插件,也就没有这两个工具。
195
+
150
196
  CLI(人用,等价入口):
151
197
 
152
198
  ```bash
@@ -221,7 +267,7 @@ systemd --user pi-auto.service
221
267
  扩展写 `retired/<slug>.json`,当天不再拉起,跨天自动恢复。
222
268
  - 不设夜间时段门禁、不观察桌面登录:服务只服从 `plan.json` 和「用户优先」这一条。
223
269
 
224
- ## 会话内:`auto_switch` 与 `auto_schedule`
270
+ ## 会话内:`auto_switch` / `auto_schedule` / `auto_timer` / `auto_bg` / 交接线
225
271
 
226
272
  - 无人值守会话(`PI_AUTO_SESSION_ID` / 兼容 `PI_BOOT_SESSION_ID` / `PI_RUN_DIR`)默认 **on**;
227
273
  用户手开会话默认 **off**(不许静默自己续轮)。
@@ -284,7 +330,7 @@ pi-auto service install # 或手抄 systemd/pi-aut
284
330
  cd ~/pi-plugins/pi-auto
285
331
  npm run validate # = node 单测 + lib.sh/schedule shell 门禁 + import check + pack --dry-run
286
332
  # 分开跑:
287
- node --test 'test/*.test.mjs' # 开关/续轮/retired/mailbox 轻推/auto_schedule 与 when 解析
333
+ node --test 'test/*.test.mjs' # 开关/续轮/retired/mailbox 轻推/auto_schedule 与 when 解析/auto_timer/auto_bg/交接线
288
334
  bash test/lib.test.sh # plan/retired/slug/prompt/预约判据
289
335
  bash test/schedule.test.sh # 预约端到端(dry-launch:once 消费即清理 / recurring 保留 prompt)
290
336
  ```
@@ -16,6 +16,7 @@
16
16
  * audit.log 一行一条 JSON
17
17
  */
18
18
  import crypto from "node:crypto";
19
+ import { execFileSync, spawn } from "node:child_process";
19
20
  import fs from "node:fs";
20
21
  import os from "node:os";
21
22
  import path from "node:path";
@@ -35,6 +36,12 @@ export type AutoState = {
35
36
  lastNudgeAt: string | null;
36
37
  startedAt: string;
37
38
  updatedAt: string;
39
+ /** 交接线状态:0 未到线 / 1 已提醒 / 2 提醒过仍未交接(升级口径)。 */
40
+ handoffStage?: number;
41
+ handoffPercent?: number | null;
42
+ handoffReminders?: number;
43
+ /** 观测到的最高上下文百分比(审计用,便于事后核「为什么这时交接」)。 */
44
+ contextPercentMax?: number | null;
38
45
  };
39
46
 
40
47
  const STATUS_KEY = "pi-auto";
@@ -519,6 +526,269 @@ export function checkTodayWrite(plan: PlanFile, scope: string, cwd: string, text
519
526
  return { needsConfirm: false };
520
527
  }
521
528
 
529
+ // ---------------------------------------------------------------- 计时器(会话内自主预约)
530
+ //
531
+ // 2026-12-05 事故:limbus 那轮 113 min 里有 110 min 是 `bash sleep 1500`(轮内阻塞等待),
532
+ // 一次 abort 就让整轮白等。改成「预约一个到点唤醒」:调完直接结束本轮,到点由 pi-mailbox
533
+ // 递一条消息把会话叫起来 —— 等待期间不烧 token、不占工具位、可 list/cancel。
534
+ //
535
+ // 落盘 `state/auto/timers/<pid>.json`(与 session-<pid>.json 分开,避免 touch() 覆盖它)。
536
+ // 进程死了就不再有唤醒(这是本工具与 auto_schedule 的分界:跨进程用 auto_schedule)。
537
+ export type TimerEntry = {
538
+ id: string;
539
+ dueAt: number;
540
+ note: string;
541
+ createdAt: string;
542
+ };
543
+
544
+ export function timersRoot(): string {
545
+ return path.join(autoRoot(), "timers");
546
+ }
547
+
548
+ export function timersPath(pid: number = process.pid): string {
549
+ return path.join(timersRoot(), `${pid}.json`);
550
+ }
551
+
552
+ export function readTimers(pid: number = process.pid): TimerEntry[] {
553
+ try {
554
+ const raw = JSON.parse(fs.readFileSync(timersPath(pid), "utf8"));
555
+ if (!Array.isArray(raw)) return [];
556
+ return raw.filter((t) => t && typeof t.dueAt === "number" && typeof t.id === "string") as TimerEntry[];
557
+ } catch {
558
+ return [];
559
+ }
560
+ }
561
+
562
+ /** 清掉「持有者 pid 已经不在了」的计时器文件(崩溃/重启留下的孤儿,不参与唤醒)。 */
563
+ export function pruneDeadTimerFiles(isAlive: (pid: number) => boolean = (pid) => {
564
+ try {
565
+ process.kill(pid, 0);
566
+ return true;
567
+ } catch (error) {
568
+ // EPERM = 进程在但不属于我们;只把 ESRCH 当死亡
569
+ return (error as NodeJS.ErrnoException)?.code === "EPERM";
570
+ }
571
+ }): number {
572
+ let removed = 0;
573
+ let files: string[] = [];
574
+ try {
575
+ files = fs.readdirSync(timersRoot());
576
+ } catch {
577
+ return 0;
578
+ }
579
+ for (const file of files) {
580
+ const m = /^(\d+)\.json$/.exec(file);
581
+ if (!m) continue;
582
+ const pid = Number(m[1]);
583
+ if (pid === process.pid) continue;
584
+ if (isAlive(pid)) continue;
585
+ try {
586
+ fs.rmSync(path.join(timersRoot(), file), { force: true });
587
+ removed += 1;
588
+ } catch {
589
+ /* ignore */
590
+ }
591
+ }
592
+ return removed;
593
+ }
594
+
595
+ export function writeTimers(list: TimerEntry[], pid: number = process.pid): void {
596
+ try {
597
+ fs.mkdirSync(timersRoot(), { recursive: true });
598
+ const file = timersPath(pid);
599
+ if (!list.length) {
600
+ fs.rmSync(file, { force: true });
601
+ return;
602
+ }
603
+ const tmp = `${file}.tmp`;
604
+ fs.writeFileSync(tmp, `${JSON.stringify(list, null, 2)}\n`);
605
+ fs.renameSync(tmp, file);
606
+ } catch {
607
+ /* 写不进去就少一次唤醒,不阻断会话 */
608
+ }
609
+ }
610
+
611
+ /**
612
+ * 认「多久之后」:25m / 90s / 2h / 150min / 25分钟 / 1天。
613
+ * 只吃相对时长;绝对时点归 auto_schedule(不要在会话里挂一个跨进程的钟)。
614
+ */
615
+ export function parseAfter(raw: string, now = new Date()): Date {
616
+ const s = String(raw ?? "")
617
+ .trim()
618
+ .replace(/[\uFF01-\uFF5E]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0))
619
+ .replace(/^\+/, "")
620
+ .toLowerCase();
621
+ const m = /^(\d+)\s*(秒钟|秒|分钟|分|小时|钟头|天|s|sec|secs|second|seconds|min|mins|minute|minutes|m|h|hr|hrs|hour|hours|d|day|days)$/.exec(s);
622
+ if (!m) throw new Error(`认不出时长:${raw}(例:25m / 90s / 2h / 150min)`);
623
+ const n = Number(m[1]);
624
+ const u = m[2];
625
+ const ms = /^(s|sec|second)/.test(u) || /秒/.test(u)
626
+ ? 1_000
627
+ : /^(m|min|minute)/.test(u) || /分/.test(u)
628
+ ? 60_000
629
+ : /^(h|hr|hour)/.test(u) || /小时|钟头/.test(u)
630
+ ? 3_600_000
631
+ : 86_400_000;
632
+ return new Date(now.getTime() + n * ms);
633
+ }
634
+
635
+ /** 计时器一律走 auto_schedule 的上限:会话内 setTimeout 只可靠到几小时~几天。 */
636
+ export const MAX_TIMER_MS = 7 * 86_400_000;
637
+
638
+ // ---------------------------------------------------------------- 后台命令(完成即唤醒)
639
+ //
640
+ // `auto_bg` = 「跑一条长命令,跑完叫我」:脱离会话起进程(pi 退出也不受影响),
641
+ // 命令结束时写 rc 文件,会话内 5 s 一轮的轻量轮询发现 rc 落盘 ⇒ 走 pi-mailbox 唤醒。
642
+ // 与 auto_timer 的区别:那个按钟点叫,这个按「命令真的结束」叫(跑批/编译/长测试)。
643
+ export type BgJob = {
644
+ id: string;
645
+ pid: number;
646
+ command: string;
647
+ cwd: string;
648
+ log: string;
649
+ rcFile: string;
650
+ startedAt: string;
651
+ };
652
+
653
+ export function bgRoot(): string {
654
+ return path.join(autoRoot(), "bg");
655
+ }
656
+
657
+ export function bgIndexPath(pid: number = process.pid): string {
658
+ return path.join(bgRoot(), `${pid}.json`);
659
+ }
660
+
661
+ export function readJobs(pid: number = process.pid): BgJob[] {
662
+ try {
663
+ const raw = JSON.parse(fs.readFileSync(bgIndexPath(pid), "utf8"));
664
+ return Array.isArray(raw) ? (raw as BgJob[]) : [];
665
+ } catch {
666
+ return [];
667
+ }
668
+ }
669
+
670
+ export function writeJobs(list: BgJob[], pid: number = process.pid): void {
671
+ try {
672
+ fs.mkdirSync(bgRoot(), { recursive: true });
673
+ const file = bgIndexPath(pid);
674
+ if (!list.length) {
675
+ fs.rmSync(file, { force: true });
676
+ return;
677
+ }
678
+ const tmp = `${file}.tmp`;
679
+ fs.writeFileSync(tmp, `${JSON.stringify(list, null, 2)}\n`);
680
+ fs.renameSync(tmp, file);
681
+ } catch {
682
+ /* ignore */
683
+ }
684
+ }
685
+
686
+ // ---------------------------------------------------------------- 交接线(上下文 30–40% 且本轮 idle)
687
+ //
688
+ // 2026-12-05 用户口径:「全天候 agent 自动化 = 一个 agent 做完本轮把活交给下一轮」。
689
+ // 所以交接不能只靠模型自己记得(规则 23 写在文档里,实测会话照样一路干到 80%+)。判据放在
690
+ // `agent_before_settle`(本轮真的 idle 了):
691
+ // - 无人值守会话(keepAlive):把「续轮草稿」换成「交接草稿」——本会话只写 brief 并
692
+ // `session_handoff`,交接后新会话接着干(上下文回到 ~0);
693
+ // - 手开会话:只 `ui.notify` 提一句,不注入消息、不触发新一轮;
694
+ // - `PI_AUTO_HANDOFF=auto`:插件按仓内事实自己拼 mechanical brief 并派 `/handoff-new`
695
+ // (默认 `remind`,auto 需要 pi-agent-handoff 已装)。
696
+ // 读数一律用 `ctx.getContextUsage()`(与 footer/context_usage 同一个数),unknown 就什么都不做。
697
+ export const HANDOFF_DEFAULT_AT = 35;
698
+ export type HandoffMode = "off" | "remind" | "auto";
699
+
700
+ export function handoffThreshold(env: NodeJS.ProcessEnv = process.env): number {
701
+ const raw = Number(env.PI_AUTO_HANDOFF_AT ?? "");
702
+ return Number.isFinite(raw) && raw > 0 && raw < 100 ? raw : HANDOFF_DEFAULT_AT;
703
+ }
704
+
705
+ export function handoffMode(env: NodeJS.ProcessEnv = process.env): HandoffMode {
706
+ const raw = String(env.PI_AUTO_HANDOFF ?? "").trim().toLowerCase();
707
+ return raw === "off" || raw === "auto" || raw === "remind" ? (raw as HandoffMode) : "remind";
708
+ }
709
+
710
+ /** 百分比掉回「阈值 − 5」以下才重新武装(压缩后不该一直催交接)。 */
711
+ export const HANDOFF_REARM_DROP = 5;
712
+
713
+ /** 本轮要不要发交接提醒:0 = 不用,1 = 首次提醒,2 = 提醒过仍未交接(升级)。 */
714
+ export function handoffStage(percent: number | null, threshold: number, reminded: number): 0 | 1 | 2 {
715
+ if (percent === null || !Number.isFinite(percent)) return 0;
716
+ if (percent < threshold) return 0;
717
+ return reminded >= 1 ? 2 : 1;
718
+ }
719
+
720
+ export function handoffContinuationText(round: number, percent: number, threshold: number, stage: number): string {
721
+ const pct = `${percent.toFixed(1)}%`;
722
+ if (stage >= 2) {
723
+ return (
724
+ `【pi-auto 交接线·升级】上下文 ${pct}(阈值 ${threshold}%),上一轮已经提醒过交接但还没交接。` +
725
+ "本会话**不要再开新活**:把手上状态写成自包含 brief(背景与已定决策、绝对路径、待办、验收判据)" +
726
+ "并立刻 `session_handoff({brief, goal})`。交接失败(brief 写不出来)比上下文耗尽便宜得多;" +
727
+ "确实已经全部收口、只剩人工门,才 `auto_switch({action:\"off\", note:\"…\"})` 收工。"
728
+ );
729
+ }
730
+ return (
731
+ `【pi-auto 续轮 #${round} · 交接线】上下文 ${pct}(阈值 ${threshold}%)。` +
732
+ "先把这单交给新会话再继续:调 `session_handoff({brief, goal})`,brief 必须自包含" +
733
+ "(背景与已定决策、绝对路径、待办、验收判据),因为新会话看不到这段对话;交接后新会话接着推进。" +
734
+ "不要把剩下的活继续压在本会话里。"
735
+ );
736
+ }
737
+
738
+ /** 机械 brief(`PI_AUTO_HANDOFF=auto` 用):只写仓内**可核实的事实**,不编状态。 */
739
+ export function mechanicalBrief(
740
+ cwd: string,
741
+ sessionId: string,
742
+ percent: number,
743
+ threshold: number,
744
+ exec: (file: string, args: string[]) => string = (file, args) =>
745
+ execFileSync(file, args, { cwd, timeout: 5_000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }),
746
+ ): string {
747
+ const git = (args: string[]): string => {
748
+ try {
749
+ return exec("git", args).trim();
750
+ } catch {
751
+ return "";
752
+ }
753
+ };
754
+ const commits = git(["log", "--oneline", "-5"]) || "(不是 git 仓或没有提交)";
755
+ const dirty = git(["status", "--short"]);
756
+ const dirtyLine = dirty ? dirty.split("\n").slice(0, 20).join("\n") : "(工作树干净)";
757
+ const candidates = ["AGENTS.md", "TODO.md", "PLAN.md", "BACKLOG.md", "ROADMAP.md", ".pi/plans"];
758
+ const found = candidates.filter((f) => {
759
+ try {
760
+ fs.statSync(path.join(cwd, f));
761
+ return true;
762
+ } catch {
763
+ return false;
764
+ }
765
+ });
766
+ const pointers = found.length ? found.map((f) => path.join(cwd, f)).join("\n - ") : "(仓内没找到 AGENTS/TODO/PLAN,向上游/记忆里找)";
767
+ return [
768
+ `# 自动交接(pi-auto:上下文 ${percent.toFixed(1)}% ≥ ${threshold}%)`,
769
+ "",
770
+ `上一个会话已经 idle,上下文到线 ⇒ 由 pi-auto 自动交接。来源会话 ${sessionId},cwd ${cwd}。`,
771
+ "",
772
+ "## 先读这些(单一出处,别凭这段 brief 猜)",
773
+ ` - ${pointers}`,
774
+ "",
775
+ "## 最近提交(git log --oneline -5)",
776
+ commits,
777
+ "",
778
+ "## 工作树(未提交改动,前 20 行)",
779
+ dirtyLine,
780
+ "",
781
+ "## 接下来怎么干",
782
+ "- 这是无人值守会话:不问问题、不等确认;按仓内 AGENTS/规则 18 分层推进,自己只做编排 + 复核。",
783
+ "- 先核现状(git status / 日志 / 子代理 / 待办文件),再决定这条线的下一步;口径不确定先查记忆/技能。",
784
+ "- 要等(批次/CI/长命令)用 `auto_timer` / `auto_bg`,不要轮内 `sleep`;做完或只剩人工门就 `auto_switch({action:\"off\", note:\"…\"})`。",
785
+ ].join("\n");
786
+ }
787
+
788
+ function shellQuote(value: string): string {
789
+ return `'${value.replace(/'/g, `'\\''`)}'`;
790
+ }
791
+
522
792
  export default function (pi: ExtensionAPI) {
523
793
  if (inChildProcess()) return;
524
794
  let state: AutoState | undefined;
@@ -529,6 +799,100 @@ export default function (pi: ExtensionAPI) {
529
799
  // 今日补充的跨项目二次确认:key = scope\u0000text,值为过期时刻(会话内有效,不跨进程)
530
800
  const pendingToday = new Map<string, number>();
531
801
  const TODAY_CONFIRM_TTL_MS = 10 * 60_000;
802
+ // 计时器/后台命令的运行期句柄(磁盘状态是权威,这里只是“到点提醒”的定时器)
803
+ const timerHandles = new Map<string, ReturnType<typeof setTimeout>>();
804
+ let bgPoller: ReturnType<typeof setInterval> | undefined;
805
+ // `PI_AUTO_HANDOFF=auto`:本轮 settle 时拼好的机械 brief,等 agent_settled 再派 /handoff-new
806
+ let pendingAutoBrief: string | undefined;
807
+
808
+ /** 与 footer / context_usage 同一个数;拿不到就是 null(不猜)。 */
809
+ const contextPercent = (ctx: ExtensionContext): number | null => {
810
+ try {
811
+ const usage = ctx.getContextUsage?.();
812
+ const pct = usage?.percent;
813
+ return typeof pct === "number" && Number.isFinite(pct) ? pct : null;
814
+ } catch {
815
+ return null;
816
+ }
817
+ };
818
+
819
+ /** auto 模式要求 pi-agent-handoff 已装:settings 里没有就当 remind,别派一个不存在的命令。 */
820
+ const handoffExtensionInstalled = (): boolean => {
821
+ try {
822
+ const raw = fs.readFileSync(path.join(agentDir(), "settings.json"), "utf8");
823
+ return /pi-agent-handoff/.test(raw);
824
+ } catch {
825
+ return false;
826
+ }
827
+ };
828
+
829
+ const fireTimer = (entry: TimerEntry): void => {
830
+ timerHandles.delete(entry.id);
831
+ writeTimers(readTimers().filter((t) => t.id !== entry.id));
832
+ const at = formatLocal(new Date(entry.dueAt));
833
+ enqueueMailbox(
834
+ `【pi-auto 计时器】到点(${at}):${entry.note}\n` +
835
+ "开关仍开就接着推进这单;等的东西还没好就再 `auto_timer` 排下一次,确实收工才 `auto_switch({action:\"off\"})`。",
836
+ );
837
+ audit({ kind: "timer-fired", id: entry.id, dueAt: at, note: entry.note.slice(0, 120) });
838
+ };
839
+
840
+ const armTimer = (entry: TimerEntry): void => {
841
+ const prev = timerHandles.get(entry.id);
842
+ if (prev) clearTimeout(prev);
843
+ const delay = Math.max(0, entry.dueAt - Date.now());
844
+ const handle = setTimeout(() => fireTimer(entry), delay);
845
+ (handle as unknown as { unref?: () => void }).unref?.();
846
+ timerHandles.set(entry.id, handle);
847
+ };
848
+
849
+ /** 后台任务完成轮询:只在有活任务时挂一个 5 s 的 unref 定时器。 */
850
+ const refreshBgPoller = (): void => {
851
+ if (bgPoller) {
852
+ clearInterval(bgPoller);
853
+ bgPoller = undefined;
854
+ }
855
+ if (!readJobs().length) return;
856
+ const pollMs = Number(process.env.PI_AUTO_BG_POLL_MS ?? "");
857
+ const interval = Number.isFinite(pollMs) && pollMs > 0 ? pollMs : 5_000;
858
+ bgPoller = setInterval(() => {
859
+ const jobs = readJobs();
860
+ if (!jobs.length) {
861
+ refreshBgPoller();
862
+ return;
863
+ }
864
+ let changed = false;
865
+ const keep: BgJob[] = [];
866
+ for (const job of jobs) {
867
+ let rc: string | undefined;
868
+ try {
869
+ rc = fs.readFileSync(job.rcFile, "utf8").trim();
870
+ } catch {
871
+ rc = undefined;
872
+ }
873
+ if (rc === undefined) {
874
+ keep.push(job);
875
+ continue;
876
+ }
877
+ changed = true;
878
+ let tail = "";
879
+ try {
880
+ tail = fs.readFileSync(job.log, "utf8").slice(-800).trim();
881
+ } catch {
882
+ tail = "(日志读不到)";
883
+ }
884
+ enqueueMailbox(
885
+ `【pi-auto 后台命令结束】${job.command}\n` +
886
+ ` rc=${rc} 日志:${job.log}\n` +
887
+ (tail ? ` 日志尾:\n${tail}\n` : "") +
888
+ "开关仍开就接着收这单(读数/收口/提交);做完才 `auto_switch({action:\"off\"})`。",
889
+ );
890
+ audit({ kind: "bg-done", id: job.id, rc, log: job.log, command: job.command.slice(0, 120) });
891
+ }
892
+ if (changed) writeJobs(keep);
893
+ }, interval);
894
+ (bgPoller as unknown as { unref?: () => void }).unref?.();
895
+ };
532
896
 
533
897
  const touch = (ctx: ExtensionContext, patch: Partial<AutoState> = {}): AutoState => {
534
898
  const now = new Date().toISOString();
@@ -594,7 +958,7 @@ export default function (pi: ExtensionAPI) {
594
958
  promptGuidelines: [
595
959
  "还有自己能做的活 → `auto_switch({action:\"on\"})`(无人值守会话默认已开);",
596
960
  "收工或只剩人工/审批/环境门 → `auto_switch({action:\"off\", note:\"原因\"})`:这是唯一的收工信号;",
597
- "等 CI/子代理/几分钟不要排轮,直接在轮内 `sleep`。",
961
+ "等 CI/子代理/分钟级 ⇒ `auto_timer({after:\"25m\"})`;等一条长命令 ⇒ `auto_bg({command:…})`(都是调完就结束本轮,不要 `bash sleep`);",
598
962
  ],
599
963
  parameters: {
600
964
  type: "object",
@@ -909,6 +1273,235 @@ export default function (pi: ExtensionAPI) {
909
1273
  },
910
1274
  });
911
1275
 
1276
+ // ---------------------------------------------------------------- 计时器入口
1277
+ pi.registerTool({
1278
+ name: "auto_timer",
1279
+ label: "会话内计时器",
1280
+ description:
1281
+ "给自己排一个到点唤醒(不阻塞、不烧 token):调完就结束这一轮,到点 pi-mailbox 把会话叫起来。" +
1282
+ "等几分钟到几小时都用它,代替 `bash sleep 600`(那个会把整轮堵死、被 abort 就白等)。" +
1283
+ "只吃相对时长(25m/90s/2h/150min);跨进程/明天到点开工用 auto_schedule。" +
1284
+ "action=set(需 after)| list | cancel(id 或 all)。",
1285
+ promptSnippet: "会话内计时器(pi-auto):auto_timer({after:\"25m\", note:\"继续看批\"}),然后直接结束这一轮",
1286
+ promptGuidelines: [
1287
+ "等批次/CI/外部作业几分钟以上 ⇒ `auto_timer({after:\"25m\", note:\"要接着看什么\"})` 然后本轮结束,**不要** `bash sleep 1500`。",
1288
+ "到点被叫起来后:先看读数再决定继续等还是收口;要再等就再排一次。",
1289
+ "等的是「命令真的结束」⇒ 用 `auto_bg`(按完成叫醒),不要拿固定时长去赌。",
1290
+ ],
1291
+ parameters: {
1292
+ type: "object",
1293
+ properties: {
1294
+ action: { type: "string", enum: ["set", "list", "cancel"], description: "set | list | cancel" },
1295
+ after: { type: "string", description: "多久之后:25m / 90s / 2h / 150min(最长 7 天)" },
1296
+ note: { type: "string", description: "到点时给自己看的一句话:该干什么/该看什么" },
1297
+ id: { type: "string", description: "cancel 的目标 id(或 all)" },
1298
+ },
1299
+ required: ["action"],
1300
+ additionalProperties: false,
1301
+ },
1302
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1303
+ const p = (params ?? {}) as { action?: string; after?: string; note?: string; id?: string };
1304
+ const action = String(p.action ?? "list");
1305
+ const fail = (text: string) => ({ content: [{ type: "text" as const, text }], isError: true });
1306
+ const describe = (t: TimerEntry) =>
1307
+ ` ${t.id} ${formatLocal(new Date(t.dueAt))}${t.dueAt <= Date.now() ? "(已到点,下一轮会叫)" : ""}\n ${t.note.replace(/\s+/g, " ").slice(0, 160)}`;
1308
+
1309
+ if (action === "list") {
1310
+ const list = readTimers();
1311
+ return {
1312
+ content: [
1313
+ {
1314
+ type: "text" as const,
1315
+ text: list.length
1316
+ ? `本会话计时器(${list.length} 个):\n${list.map(describe).join("\n")}`
1317
+ : "本会话没有计时器(auto_timer({action:\"set\", after:\"25m\"}) 排一个)",
1318
+ },
1319
+ ],
1320
+ details: { timers: list },
1321
+ };
1322
+ }
1323
+
1324
+ if (action === "cancel") {
1325
+ const id = String(p.id ?? "").trim();
1326
+ if (!id) return fail('cancel 需要 id(用 action="list" 查),或 id="all"');
1327
+ const before = readTimers();
1328
+ const after = id === "all" ? [] : before.filter((t) => t.id !== id);
1329
+ for (const t of before) {
1330
+ if (id === "all" || t.id === id) {
1331
+ const h = timerHandles.get(t.id);
1332
+ if (h) clearTimeout(h);
1333
+ timerHandles.delete(t.id);
1334
+ }
1335
+ }
1336
+ writeTimers(after);
1337
+ audit({ kind: "timer-cancel", id, removed: before.length - after.length, cwd: ctx.cwd });
1338
+ if (before.length === after.length) return fail(`没有这个计时器:${id}`);
1339
+ return { content: [{ type: "text" as const, text: `已取消 ${before.length - after.length} 个计时器(${id})` }], details: { id } };
1340
+ }
1341
+
1342
+ if (action !== "set") return fail(`未知 action:${action}(set | list | cancel)`);
1343
+ const raw = String(p.after ?? p.note ?? "").trim();
1344
+ if (!String(p.after ?? "").trim()) return fail('set 需要 after:多久之后叫醒(例:25m / 90s / 2h)');
1345
+ let due: Date;
1346
+ try {
1347
+ due = parseAfter(raw);
1348
+ } catch (error) {
1349
+ return fail(String((error as Error).message ?? error));
1350
+ }
1351
+ if (due.getTime() - Date.now() > MAX_TIMER_MS) {
1352
+ return fail(`计时器最长 ${MAX_TIMER_MS / 86_400_000} 天;跨天开工请用 auto_schedule(mode:\"once\", when:\"明天 07:40\")`);
1353
+ }
1354
+ const entry: TimerEntry = {
1355
+ id: `tm-${Date.now().toString(36)}-${crypto.randomBytes(2).toString("hex")}`,
1356
+ dueAt: due.getTime(),
1357
+ note: String(p.note ?? "接着推进手头这单").trim() || "接着推进手头这单",
1358
+ createdAt: new Date().toISOString(),
1359
+ };
1360
+ writeTimers([...readTimers(), entry]);
1361
+ armTimer(entry);
1362
+ audit({ kind: "timer-set", id: entry.id, dueAt: formatLocal(due), note: entry.note.slice(0, 120), cwd: ctx.cwd });
1363
+ return {
1364
+ content: [
1365
+ {
1366
+ type: "text" as const,
1367
+ text:
1368
+ `计时器已排:${entry.id} → ${formatLocal(due)}(约 ${Math.round((due.getTime() - Date.now()) / 60_000)} 分钟)\n` +
1369
+ ` 到点会以 pi-mailbox 消息叫醒:${entry.note}\n` +
1370
+ " 现在可以直接结束这一轮(不要再 `bash sleep`);开关仍开就 auto_switch 不管它。",
1371
+ },
1372
+ ],
1373
+ details: { timer: entry },
1374
+ };
1375
+ },
1376
+ });
1377
+
1378
+ // ---------------------------------------------------------------- 后台命令入口
1379
+ pi.registerTool({
1380
+ name: "auto_bg",
1381
+ label: "后台命令(完成即唤醒)",
1382
+ description:
1383
+ "跑一条长命令(跑批/编译/长测试),**命令真的结束**时用 pi-mailbox 叫醒本会话;不等进程数完就结束本轮。" +
1384
+ "命令进程与 pi 脱离(pi 退出不影响它),输出写 $PI_CODING_AGENT_DIR/state/auto/bg/<id>/out.log。" +
1385
+ "action=run(需 command)| list | tail(需 id)| cancel(id 或 all)。",
1386
+ promptSnippet: "后台命令(pi-auto):auto_bg({command:\"…\"}) 立即返回,命令结束时叫醒本会话",
1387
+ promptGuidelines: [
1388
+ "等一条长命令(真机批/全量测试/大编译,>5 min)⇒ `auto_bg({command:\"timeout -k 60 9600 bash tools/… \\| tee logs/…\"})`,然后本轮结束,**不要**守着 `sleep`。",
1389
+ "命令里必须自带 `timeout -k`(硬规则 14);被唤醒后先 `auto_bg({action:\"tail\", id})` 看尾巴再决定下一步。",
1390
+ "会话被 kill / 进程退出 ⇒ 唤醒丢失(命令照样跑完);那种场景用 `auto_schedule` 预约到点回收。",
1391
+ ],
1392
+ parameters: {
1393
+ type: "object",
1394
+ properties: {
1395
+ action: { type: "string", enum: ["run", "list", "tail", "cancel"], description: "run | list | tail | cancel" },
1396
+ command: { type: "string", description: "要跑的命令(bash -c;自带 timeout)" },
1397
+ id: { type: "string", description: "tail/cancel 的目标 id(cancel 接受 all)" },
1398
+ },
1399
+ required: ["action"],
1400
+ additionalProperties: false,
1401
+ },
1402
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1403
+ const p = (params ?? {}) as { action?: string; command?: string; id?: string };
1404
+ const action = String(p.action ?? "list");
1405
+ const fail = (text: string) => ({ content: [{ type: "text" as const, text }], isError: true });
1406
+ const state = (job: BgJob): string => {
1407
+ try {
1408
+ return `rc=${fs.readFileSync(job.rcFile, "utf8").trim()}`;
1409
+ } catch {
1410
+ return "running";
1411
+ }
1412
+ };
1413
+
1414
+ if (action === "list") {
1415
+ const jobs = readJobs();
1416
+ return {
1417
+ content: [
1418
+ {
1419
+ type: "text" as const,
1420
+ text: jobs.length
1421
+ ? `本会话后台命令(${jobs.length}):\n${jobs
1422
+ .map((j) => ` ${j.id} ${state(j)} ${j.startedAt.slice(11, 16)} ${j.command.slice(0, 100)}\n 日志:${j.log}`)
1423
+ .join("\n")}`
1424
+ : "本会话没有后台命令",
1425
+ },
1426
+ ],
1427
+ details: { jobs },
1428
+ };
1429
+ }
1430
+
1431
+ if (action === "tail" || action === "cancel") {
1432
+ const id = String(p.id ?? "").trim();
1433
+ if (!id) return fail(`${action} 需要 id(用 action="list" 查)`);
1434
+ const jobs = readJobs();
1435
+ const hit = jobs.filter((j) => (id === "all" ? true : j.id === id));
1436
+ if (!hit.length) return fail(`没有这个后台命令:${id}`);
1437
+ if (action === "tail") {
1438
+ const job = hit[0];
1439
+ let tail = "";
1440
+ try {
1441
+ tail = fs.readFileSync(job.log, "utf8").slice(-4000).trim();
1442
+ } catch {
1443
+ tail = "(日志还没生成)";
1444
+ }
1445
+ return {
1446
+ content: [{ type: "text" as const, text: `${job.id} ${state(job)} ${job.command}\n日志:${job.log}\n---\n${tail}` }],
1447
+ details: { job },
1448
+ };
1449
+ }
1450
+ for (const job of hit) {
1451
+ try {
1452
+ process.kill(-job.pid, "SIGTERM");
1453
+ } catch {
1454
+ /* 已经死了 */
1455
+ }
1456
+ }
1457
+ writeJobs(jobs.filter((j) => !hit.includes(j)));
1458
+ audit({ kind: "bg-cancel", id, removed: hit.length, cwd: ctx.cwd });
1459
+ return { content: [{ type: "text" as const, text: `已取消 ${hit.length} 条后台命令(${id})` }], details: { id } };
1460
+ }
1461
+
1462
+ if (action !== "run") return fail(`未知 action:${action}(run | list | tail | cancel)`);
1463
+ const command = String(p.command ?? "").trim();
1464
+ if (!command) return fail('run 需要 command');
1465
+ if (!fs.existsSync(ctx.cwd) || !fs.statSync(ctx.cwd).isDirectory()) return fail(`cwd 不存在:${ctx.cwd}`);
1466
+ const id = `bg-${Date.now().toString(36)}-${crypto.randomBytes(2).toString("hex")}`;
1467
+ const dir = path.join(bgRoot(), id);
1468
+ let job: BgJob;
1469
+ try {
1470
+ fs.mkdirSync(dir, { recursive: true });
1471
+ const log = path.join(dir, "out.log");
1472
+ const rcFile = path.join(dir, "rc");
1473
+ const fd = fs.openSync(log, "a");
1474
+ // 用子 shell 包住:命令自己 `exit N`/`set -e` 只退子 shell,不会跳过写 rc
1475
+ const child = spawn("/bin/bash", ["-c", `( ${command}\n) ; printf '%s' "$?" > ${shellQuote(rcFile)}`], {
1476
+ cwd: ctx.cwd,
1477
+ detached: true,
1478
+ stdio: ["ignore", fd, fd],
1479
+ env: process.env,
1480
+ });
1481
+ child.unref();
1482
+ fs.closeSync(fd);
1483
+ job = { id, pid: child.pid ?? -1, command, cwd: ctx.cwd, log, rcFile, startedAt: new Date().toISOString() };
1484
+ } catch (error) {
1485
+ return fail(`起后台命令失败:${String(error)}`);
1486
+ }
1487
+ writeJobs([...readJobs(), job]);
1488
+ refreshBgPoller();
1489
+ audit({ kind: "bg-start", id, pid: job.pid, command: command.slice(0, 160), cwd: ctx.cwd });
1490
+ return {
1491
+ content: [
1492
+ {
1493
+ type: "text" as const,
1494
+ text:
1495
+ `后台命令已起:${id}(pid=${job.pid},cwd=${job.cwd})\n` +
1496
+ ` 日志:${job.log}\n` +
1497
+ " 结束时会用 pi-mailbox 叫醒本会话(rc + 日志尾);现在可以结束这一轮。",
1498
+ },
1499
+ ],
1500
+ details: { job },
1501
+ };
1502
+ },
1503
+ });
1504
+
912
1505
  pi.registerCommand("auto", {
913
1506
  description: "pi-auto 开关:/auto on|off|status(无人值守会话默认 on,手开会话默认 off)",
914
1507
  handler: async (args, ctx) => {
@@ -936,7 +1529,26 @@ export default function (pi: ExtensionAPI) {
936
1529
  }
937
1530
  lastOutcome = event.outcome;
938
1531
  const now = touch(ctx, { phase: "settle", outcome: event.outcome });
1532
+ const pct = contextPercent(ctx);
1533
+ const hMode = handoffMode();
1534
+ const hAt = handoffThreshold();
1535
+ if (pct !== null) {
1536
+ touch(ctx, { handoffPercent: pct, contextPercentMax: Math.max(pct, now.contextPercentMax ?? 0) });
1537
+ }
939
1538
  if (!now.keepAlive) {
1539
+ // 手开会话:到线只提一句(不注入消息、不触发新一轮),同一条线只提醒一次
1540
+ if (hMode !== "off" && pct !== null && pct >= hAt && (now.handoffStage ?? 0) === 0) {
1541
+ touch(ctx, { handoffStage: 1, handoffReminders: 1 });
1542
+ try {
1543
+ ctx.ui?.notify?.(
1544
+ `上下文 ${pct.toFixed(1)}% ≥ ${hAt}%:按规则 23 该准备/执行交接(session_handoff),或把这一轮收口到可交接状态`,
1545
+ "info",
1546
+ );
1547
+ } catch {
1548
+ /* print/json 模式没有 UI */
1549
+ }
1550
+ audit({ kind: "handoff-notify", percent: pct, threshold: hAt, cwd: now.cwd });
1551
+ }
940
1552
  audit({ kind: "skip", reason: "off", cwd: now.cwd, rounds: now.rounds });
941
1553
  return;
942
1554
  }
@@ -946,6 +1558,64 @@ export default function (pi: ExtensionAPI) {
946
1558
  }
947
1559
  // error/aborted:不走 continue(aborted 会被宿主抑制),交给 agent_settled 用 mailbox 轻推
948
1560
  if (event.outcome !== "completed") return;
1561
+ // 交接线:上下文到线就把这一轮变成「交接轮」(计时器/后台命令先让位 —— 交接优先级最高)
1562
+ if (hMode !== "off" && pct !== null) {
1563
+ if (pct < hAt - HANDOFF_REARM_DROP && (now.handoffStage ?? 0) > 0) {
1564
+ touch(ctx, { handoffStage: 0, handoffReminders: 0 });
1565
+ audit({ kind: "handoff-rearm", percent: pct, threshold: hAt, cwd: now.cwd });
1566
+ }
1567
+ const stage = handoffStage(pct, hAt, now.handoffReminders ?? 0);
1568
+ if (stage > 0) {
1569
+ const round = now.rounds + 1;
1570
+ const auto = hMode === "auto" && handoffExtensionInstalled();
1571
+ const next = touch(ctx, {
1572
+ rounds: round,
1573
+ phase: "continue",
1574
+ handoffStage: stage,
1575
+ handoffReminders: (now.handoffReminders ?? 0) + 1,
1576
+ handoffPercent: pct,
1577
+ });
1578
+ nudgeAttempts = 0;
1579
+ audit({ kind: "handoff-remind", percent: pct, threshold: hAt, stage, mode: hMode, auto, round, cwd: next.cwd });
1580
+ if (auto) {
1581
+ // 直接自动化交接:brief 由插件按仓内事实拼,settle 后派 /handoff-new,不需要模型再跑一轮
1582
+ pendingAutoBrief = mechanicalBrief(
1583
+ ctx.cwd,
1584
+ ctx.sessionManager?.getSessionId?.() ?? "unknown",
1585
+ pct,
1586
+ hAt,
1587
+ );
1588
+ audit({ kind: "handoff-auto-pending", percent: pct, threshold: hAt, stage, briefBytes: Buffer.byteLength(pendingAutoBrief, "utf8") });
1589
+ return;
1590
+ }
1591
+ return {
1592
+ entries: [
1593
+ ...(event.entries ?? []),
1594
+ {
1595
+ type: "custom_message" as const,
1596
+ customType: "pi-auto-handoff",
1597
+ display: true,
1598
+ content: handoffContinuationText(round, pct, hAt, stage),
1599
+ },
1600
+ ],
1601
+ continue: true,
1602
+ };
1603
+ }
1604
+ }
1605
+ // 有排着的计时器/后台命令 ⇒ 不空转一轮:本轮收口,到点由 pi-mailbox 叫醒
1606
+ const pendingTimers = readTimers();
1607
+ const pendingJobs = readJobs();
1608
+ if (pendingTimers.length || pendingJobs.length) {
1609
+ const nextDue = pendingTimers.length ? Math.min(...pendingTimers.map((t) => t.dueAt)) : 0;
1610
+ audit({
1611
+ kind: "timer-wait",
1612
+ cwd: now.cwd,
1613
+ timers: pendingTimers.length,
1614
+ jobs: pendingJobs.length,
1615
+ next: nextDue ? formatLocal(new Date(nextDue)) : null,
1616
+ });
1617
+ return;
1618
+ }
949
1619
 
950
1620
  const round = now.rounds + 1;
951
1621
  const next = touch(ctx, { rounds: round, phase: "continue" });
@@ -969,6 +1639,17 @@ export default function (pi: ExtensionAPI) {
969
1639
  });
970
1640
 
971
1641
  pi.on("agent_settled", async (event, ctx) => {
1642
+ if (pendingAutoBrief) {
1643
+ const brief = pendingAutoBrief;
1644
+ pendingAutoBrief = undefined;
1645
+ try {
1646
+ pi.sendUserMessage(`/handoff-new ${brief}`, { expandPromptTemplates: true });
1647
+ audit({ kind: "handoff-auto", cwd: ctx.cwd, percent: contextPercent(ctx), briefBytes: Buffer.byteLength(brief, "utf8") });
1648
+ } catch (error) {
1649
+ audit({ kind: "handoff-auto-failed", cwd: ctx.cwd, error: String(error) });
1650
+ }
1651
+ return;
1652
+ }
972
1653
  const now = touch(ctx, { phase: "settled" });
973
1654
  if (!now.keepAlive) return;
974
1655
  if (retiredToday(now.cwd)) {
@@ -987,6 +1668,14 @@ export default function (pi: ExtensionAPI) {
987
1668
  pi.on("session_start", async (_event, ctx) => {
988
1669
  const now = touch(ctx, { phase: "start" });
989
1670
  audit({ kind: "session-start", cwd: now.cwd, boot: now.boot, keepAlive: now.keepAlive });
1671
+ // 恢复磁盘上的计时器(跨 /new、/resume 与崩溃重启);过期的立即叫一次
1672
+ const pruned = pruneDeadTimerFiles();
1673
+ if (pruned) audit({ kind: "timer-prune", removed: pruned, cwd: now.cwd });
1674
+ for (const t of readTimers()) {
1675
+ if (t.dueAt <= Date.now()) fireTimer(t);
1676
+ else armTimer(t);
1677
+ }
1678
+ refreshBgPoller();
990
1679
  });
991
1680
 
992
1681
  pi.on("session_shutdown", async (event, ctx) => {
@@ -994,6 +1683,14 @@ export default function (pi: ExtensionAPI) {
994
1683
  clearTimeout(nudgeTimer);
995
1684
  nudgeTimer = undefined;
996
1685
  }
1686
+ for (const h of timerHandles.values()) clearTimeout(h);
1687
+ timerHandles.clear();
1688
+ if (bgPoller) {
1689
+ clearInterval(bgPoller);
1690
+ bgPoller = undefined;
1691
+ }
1692
+ // 进程真退出才丢计时器;/new 或交接(reason=new)是同一进程换会话,计时器要留着
1693
+ if (event.reason !== "new") writeTimers([]);
997
1694
  if (!state) return;
998
1695
  audit({ kind: "session-end", cwd: state.cwd, rounds: state.rounds, keepAlive: state.keepAlive, reason: event.reason });
999
1696
  if (!state.keepAlive) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-auto-unattended",
3
- "version": "0.5.0",
4
- "description": "Unattended Pi sessions: tool-side extensions (auto_switch keep-alive, auto_schedule timed runs, auto_today project-scoped daily brief) plus a pi-auto CLI and systemd daemon that keeps one agent alive per selected folder and nudges them through pi-mailbox.",
3
+ "version": "0.7.0",
4
+ "description": "Unattended Pi sessions: tool-side extensions (auto_switch keep-alive, auto_schedule timed runs, auto_today project-scoped daily brief, auto_timer/auto_bg wait-without-blocking, context-threshold handoff at idle) plus a pi-auto CLI and systemd daemon that keeps one agent alive per selected folder and nudges them through pi-mailbox.",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi-extension",
package/prompt.md CHANGED
@@ -10,5 +10,7 @@ cwd 就是本项目根,只做本仓的活;需要人做的事(特权命令
10
10
  - 一轮把整个工单做完(含子代理验收):改完自测、提交、推送;口径不确定先查记忆/技能,别猜。
11
11
  - 要「明早/每天到点」自己开工:直接调 `auto_schedule`(`mode:"once"` 触发后 prompt 自动清理;
12
12
  `mode:"recurring"` 的 prompt 长期保留),不要手写 plan.json、也不要自己装 systemd timer。
13
+ - 要等(批次/CI/长命令)不要轮内 `sleep`:按小时点等 ⇒ `auto_timer({after:"25m", note:"…"})`;
14
+ 等一条命令跑完 ⇒ `auto_bg({command:"…"})`。两个都是调完就结束本轮,到点由 pi-mailbox 叫醒你。
13
15
  - 还有自己能做的活就保持 `auto_switch` 开着;做完了/只剩人工/审批/环境门就 `auto_switch({action:"off"})` 收工。
14
16
  服务当天不会因为 off 再拉起本目录,跨天自动恢复;要手动恢复用 `pi-auto on`。
@@ -1,18 +1,29 @@
1
1
  // pi-auto 门禁:开关语义、续轮不丢别人的草稿、无轮次上限、abort/error 走 mailbox 轻推、
2
2
  // retired 当天不再拉起、正常退出才删状态。
3
3
  import assert from "node:assert/strict";
4
- import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
4
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import test from "node:test";
8
8
 
9
9
  import register, {
10
+ bgIndexPath,
11
+ HANDOFF_DEFAULT_AT,
12
+ handoffContinuationText,
13
+ handoffMode,
14
+ handoffStage,
15
+ handoffThreshold,
16
+ mechanicalBrief,
10
17
  checkTodayWrite,
11
18
  continuationText,
12
19
  describeSchedule,
13
20
  inChildProcess,
14
21
  isBootSession,
22
+ MAX_TIMER_MS,
23
+ parseAfter,
24
+ readJobs,
15
25
  readPlan,
26
+ readTimers,
16
27
  planFile,
17
28
  parseWhen,
18
29
  retire,
@@ -20,7 +31,9 @@ import register, {
20
31
  retiredToday,
21
32
  slugFor,
22
33
  statePath,
34
+ timersPath,
23
35
  todayHash,
36
+ writeTimers,
24
37
  } from "../extensions/pi-auto.ts";
25
38
 
26
39
  function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } = {}) {
@@ -40,11 +53,16 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
40
53
  const tools = {};
41
54
  const commands = {};
42
55
  const status = {};
56
+ const sent = [];
57
+ const usage = { percent: null };
43
58
  const api = {
44
59
  registerTool: (def) => (tools[def.name] = def),
45
60
  registerCommand: (name, def) => (commands[name] = def),
46
61
  on: (event, handler) => ((events[event] ??= []).push(handler), undefined),
47
- sendUserMessage: () => Promise.resolve(),
62
+ sendUserMessage: (text, opts) => {
63
+ sent.push({ text, opts });
64
+ return Promise.resolve();
65
+ },
48
66
  };
49
67
  const ctx = {
50
68
  cwd,
@@ -52,6 +70,13 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
52
70
  sessionManager: { getSessionId: () => sessionId, getCwd: () => cwd },
53
71
  ui: { setStatus: (k, v) => (status[k] = v), notify: () => undefined },
54
72
  isIdle: () => true,
73
+ getContextUsage: () =>
74
+ usage.percent === null
75
+ ? { tokens: null, contextWindow: 200_000, percent: null }
76
+ : { tokens: Math.round((200_000 * usage.percent) / 100), contextWindow: 200_000, percent: usage.percent },
77
+ };
78
+ const setPercent = (p) => {
79
+ usage.percent = p;
55
80
  };
56
81
  register(api);
57
82
 
@@ -67,6 +92,8 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
67
92
  tools,
68
93
  commands,
69
94
  status,
95
+ sent,
96
+ setPercent,
70
97
  emit,
71
98
  callTool: (name, args) => tools[name].execute("call-1", args, undefined, undefined, ctx),
72
99
  boot: () => emit("session_start", {}),
@@ -86,6 +113,9 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
86
113
  delete process.env.PI_AUTO_MAILBOX_DIR;
87
114
  delete process.env.PI_AUTO_SESSION_ID;
88
115
  delete process.env.PI_AUTO_NUDGE_DELAY_MS;
116
+ delete process.env.PI_AUTO_BG_POLL_MS;
117
+ delete process.env.PI_AUTO_HANDOFF;
118
+ delete process.env.PI_AUTO_HANDOFF_AT;
89
119
  delete process.env.PI_BOOT_SESSION_ID;
90
120
  delete process.env.PI_RUN_DIR;
91
121
  rmSync(dir, { recursive: true, force: true });
@@ -485,3 +515,305 @@ test("auto_today:默认作用域=本会话 cwd;跨项目/广播第一次拦
485
515
  host.cleanup();
486
516
  }
487
517
  });
518
+
519
+ // ---------------------------------------------------------------- 计时器(auto_timer)
520
+ test("parseAfter:认 25m / 90s / 2h / 150分钟 / 1天,拒绝裸数字", () => {
521
+ const now = new Date("2026-12-05T10:00:00+08:00");
522
+ assert.equal(parseAfter("25m", now).toISOString(), new Date("2026-12-05T10:25:00+08:00").toISOString());
523
+ assert.equal(parseAfter("+90s", now).toISOString(), new Date("2026-12-05T10:01:30+08:00").toISOString());
524
+ assert.equal(parseAfter("2h", now).toISOString(), new Date("2026-12-05T12:00:00+08:00").toISOString());
525
+ assert.equal(parseAfter("150分钟", now).toISOString(), new Date("2026-12-05T12:30:00+08:00").toISOString());
526
+ assert.equal(parseAfter("1天", now).toISOString(), new Date("2026-12-06T10:00:00+08:00").toISOString());
527
+ for (const bad of ["25", "", "明天 07:40", "abc"]) assert.throws(() => parseAfter(bad, now));
528
+ });
529
+
530
+ test("auto_timer:set 落盘、list 看得到、cancel 清掉,超过 7 天退回 auto_schedule", async () => {
531
+ const host = createHost();
532
+ try {
533
+ await host.boot();
534
+ const set = await host.callTool("auto_timer", { action: "set", after: "25m", note: "看批" });
535
+ assert.equal(set.isError, undefined);
536
+ assert.equal(readTimers().length, 1);
537
+ assert.match(set.content[0].text, /计时器已排/);
538
+ assert.match(host.audit(), /timer-set/);
539
+
540
+ const list = await host.callTool("auto_timer", { action: "list" });
541
+ assert.match(list.content[0].text, /本会话计时器(1 个)/);
542
+ assert.match(list.content[0].text, /看批/);
543
+
544
+ const far = await host.callTool("auto_timer", { action: "set", after: "8天" });
545
+ assert.equal(far.isError, true);
546
+ assert.match(far.content[0].text, /auto_schedule/);
547
+ assert.ok(MAX_TIMER_MS === 7 * 86_400_000);
548
+
549
+ const id = readTimers()[0].id;
550
+ const cancel = await host.callTool("auto_timer", { action: "cancel", id });
551
+ assert.equal(cancel.isError, undefined);
552
+ assert.equal(readTimers().length, 0);
553
+ assert.equal(existsSync(timersPath()), false);
554
+ } finally {
555
+ host.cleanup();
556
+ }
557
+ });
558
+
559
+ test("计时器排着时 settle 不空转续轮(timer-wait),到点后走 mailbox 叫醒", async () => {
560
+ const host = createHost();
561
+ try {
562
+ await host.boot();
563
+ await host.callTool("auto_timer", { action: "set", after: "1s", note: "到点看读数" });
564
+ const settled = await host.settle("completed");
565
+ assert.equal(settled, undefined, "有计时器等 ⇒ 不该 continue");
566
+ assert.match(host.audit(), /timer-wait/);
567
+ assert.equal(host.inbox().length, 0);
568
+
569
+ await sleep(1400);
570
+ const inbox = host.inbox();
571
+ assert.equal(inbox.length, 1);
572
+ assert.match(inbox[0].text, /pi-auto 计时器/);
573
+ assert.match(inbox[0].text, /到点看读数/);
574
+ assert.equal(readTimers().length, 0, "触发后从磁盘清掉");
575
+ assert.match(host.audit(), /timer-fired/);
576
+
577
+ // 没有计时器后恢复正常续轮
578
+ const next = await host.settle("completed");
579
+ assert.ok(next && next.continue === true);
580
+ } finally {
581
+ host.cleanup();
582
+ }
583
+ });
584
+
585
+ test("重启/重启会话后:过期的计时器立刻叫一次,没到点的继续排着", async () => {
586
+ const host = createHost();
587
+ try {
588
+ writeTimers([
589
+ { id: "tm-past", dueAt: Date.now() - 60_000, note: "早就该醒了", createdAt: new Date().toISOString() },
590
+ { id: "tm-future", dueAt: Date.now() + 3_600_000, note: "还早", createdAt: new Date().toISOString() },
591
+ ]);
592
+ await host.boot();
593
+ const inbox = host.inbox();
594
+ assert.equal(inbox.length, 1);
595
+ assert.match(inbox[0].text, /早就该醒了/);
596
+ assert.deepEqual(readTimers().map((t) => t.id), ["tm-future"]);
597
+ await host.shutdown("quit");
598
+ assert.equal(readTimers().length, 0, "退出时清掉本进程的计时器");
599
+ } finally {
600
+ host.cleanup();
601
+ }
602
+ });
603
+
604
+ // ---------------------------------------------------------------- 后台命令(auto_bg)
605
+ test("auto_bg:run 脱离会话起进程,命令结束时 mailbox 带回 rc 与日志尾", async () => {
606
+ const host = createHost();
607
+ try {
608
+ process.env.PI_AUTO_BG_POLL_MS = "20";
609
+ host.ctx.cwd = host.dir; // 后台命令真的要 chdir,得用存在的目录
610
+ await host.boot();
611
+ const run = await host.callTool("auto_bg", { action: "run", command: "echo hello-bg; exit 3" });
612
+ assert.equal(run.isError, undefined);
613
+ assert.equal(readJobs().length, 1);
614
+ const job = readJobs()[0];
615
+ assert.ok(existsSync(job.log));
616
+ assert.match(host.audit(), /bg-start/);
617
+
618
+ for (let i = 0; i < 100 && host.inbox().length === 0; i++) await sleep(50);
619
+ const inbox = host.inbox();
620
+ assert.equal(inbox.length, 1, "命令结束应叫醒会话");
621
+ assert.match(inbox[0].text, /后台命令结束/);
622
+ assert.match(inbox[0].text, /rc=3/);
623
+ assert.match(inbox[0].text, /hello-bg/);
624
+ assert.equal(readJobs().length, 0, "完成后从索引里摘掉");
625
+ await sleep(100);
626
+ assert.equal(host.inbox().length, 1, "不许重复叫醒");
627
+ } finally {
628
+ host.cleanup();
629
+ }
630
+ });
631
+
632
+ test("auto_bg:list / tail / cancel(kill 整个进程组)", async () => {
633
+ const host = createHost();
634
+ try {
635
+ process.env.PI_AUTO_BG_POLL_MS = "1000";
636
+ host.ctx.cwd = host.dir;
637
+ await host.boot();
638
+ await host.callTool("auto_bg", { action: "run", command: "sleep 30; echo never" });
639
+ const job = readJobs()[0];
640
+ const list = await host.callTool("auto_bg", { action: "list" });
641
+ assert.match(list.content[0].text, /running/);
642
+ assert.equal(existsSync(bgIndexPath()), true);
643
+ const cancel = await host.callTool("auto_bg", { action: "cancel", id: job.id });
644
+ assert.equal(cancel.isError, undefined);
645
+ assert.equal(readJobs().length, 0);
646
+ await sleep(100);
647
+ let gone = false;
648
+ try {
649
+ process.kill(job.pid, 0);
650
+ } catch {
651
+ gone = true;
652
+ }
653
+ assert.equal(gone, true, "cancel 应真的杀掉进程");
654
+ const tail = await host.callTool("auto_bg", { action: "tail", id: job.id });
655
+ assert.equal(tail.isError, true, "取消后索引里没有它");
656
+ } finally {
657
+ host.cleanup();
658
+ }
659
+ });
660
+
661
+ // ---------------------------------------------------------------- 交接线(30–40% 且本轮 idle)
662
+ test("handoff 判据:阈值默认 35、可环境覆盖;stage 只到线才提醒、提醒过就升级", () => {
663
+ assert.equal(HANDOFF_DEFAULT_AT, 35);
664
+ assert.equal(handoffThreshold({}), 35);
665
+ assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "32" }), 32);
666
+ assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "abc" }), 35);
667
+ assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "0" }), 35);
668
+ assert.equal(handoffMode({}), "remind");
669
+ assert.equal(handoffMode({ PI_AUTO_HANDOFF: "auto" }), "auto");
670
+ assert.equal(handoffMode({ PI_AUTO_HANDOFF: "off" }), "off");
671
+ assert.equal(handoffMode({ PI_AUTO_HANDOFF: "乱写" }), "remind");
672
+
673
+ assert.equal(handoffStage(null, 35, 0), 0, "读数未知不催");
674
+ assert.equal(handoffStage(34.9, 35, 0), 0);
675
+ assert.equal(handoffStage(35, 35, 0), 1);
676
+ assert.equal(handoffStage(36, 35, 1), 2, "提醒过还没交接 ⇒ 升级");
677
+ assert.match(handoffContinuationText(3, 36, 35, 1), /交接线/);
678
+ assert.match(handoffContinuationText(3, 36, 35, 1), /36\.0%/);
679
+ assert.match(handoffContinuationText(3, 36, 35, 2), /升级/);
680
+ });
681
+
682
+ test("mechanicalBrief:只写仓内可核实事实(指针/提交/工作树),不编状态", () => {
683
+ const calls = [];
684
+ const brief = mechanicalBrief("/repo/x", "sess-9", 36.2, 35, (file, args) => {
685
+ calls.push([file, ...args].join(" "));
686
+ if (args[0] === "log") return "abc123 fix(a): x\ndef456 feat(b): y\n";
687
+ if (args[0] === "status") return " M tools/a.sh\n?? notes.md\n";
688
+ throw new Error("nope");
689
+ });
690
+ assert.match(brief, /上下文 36\.2% ≥ 35%/);
691
+ assert.match(brief, /abc123 fix\(a\): x/);
692
+ assert.match(brief, /M tools\/a\.sh/);
693
+ assert.match(brief, /sess-9/);
694
+ assert.match(brief, /自动交接/);
695
+ assert.ok(calls.some((c) => c.startsWith("git log --oneline -5")));
696
+ assert.ok(calls.some((c) => c.startsWith("git status --short")));
697
+ });
698
+
699
+ test("无人值守会话:上下文到线就把续轮换成交接指令(两次后升级)", async () => {
700
+ const host = createHost({ boot: true });
701
+ try {
702
+ await host.boot();
703
+ host.setPercent(20);
704
+ const normal = await host.settle("completed");
705
+ assert.ok(normal?.continue === true);
706
+ assert.match(normal.entries.at(-1).content, /续轮/);
707
+
708
+ host.setPercent(36);
709
+ const first = await host.settle("completed");
710
+ assert.ok(first?.continue === true, "第一次到线要 continue 给模型交接的机会");
711
+ assert.equal(first.entries.at(-1).customType, "pi-auto-handoff");
712
+ assert.match(first.entries.at(-1).content, /交接线/);
713
+ assert.match(host.audit(), /handoff-remind/);
714
+ assert.equal(host.state().handoffReminders, 1);
715
+
716
+ const second = await host.settle("completed");
717
+ assert.match(second.entries.at(-1).content, /升级/);
718
+ assert.equal(host.state().handoffReminders, 2);
719
+ } finally {
720
+ host.cleanup();
721
+ }
722
+ });
723
+
724
+ test("交接后缩回低水位:重新武装(不会一直催)", async () => {
725
+ const host = createHost({ boot: true });
726
+ try {
727
+ await host.boot();
728
+ host.setPercent(36);
729
+ await host.settle("completed");
730
+ host.setPercent(12);
731
+ await host.settle("completed");
732
+ assert.match(host.audit(), /handoff-rearm/);
733
+ assert.equal(host.state().handoffStage, 0);
734
+ assert.equal(host.state().handoffReminders, 0);
735
+ host.setPercent(40);
736
+ const again = await host.settle("completed");
737
+ assert.match(again.entries.at(-1).content, /交接线/);
738
+ } finally {
739
+ host.cleanup();
740
+ }
741
+ });
742
+
743
+ test("手开会话(keepAlive=off):只 ui.notify 提一句,不注入消息、不触发新一轮", async () => {
744
+ const host = createHost({ boot: false });
745
+ try {
746
+ await host.boot();
747
+ host.setPercent(45);
748
+ const out = await host.settle("completed");
749
+ assert.equal(out, undefined, "手开会话不许被插件续轮");
750
+ assert.equal(host.sent.length, 0, "不许注入消息");
751
+ assert.match(host.audit(), /handoff-notify/);
752
+ assert.equal(host.state().handoffReminders, 1);
753
+ // 同一条线只提醒一次
754
+ await host.settle("completed");
755
+ assert.equal((host.audit().match(/handoff-notify/g) ?? []).length, 1);
756
+ } finally {
757
+ host.cleanup();
758
+ }
759
+ });
760
+
761
+ test("PI_AUTO_HANDOFF=auto:插件自己拼 brief 并在 settle 后派 /handoff-new", async () => {
762
+ const host = createHost({ boot: true });
763
+ try {
764
+ writeFileSync(join(host.dir, "settings.json"), '{"packages":["npm:pi-agent-handoff"]}\n');
765
+ process.env.PI_AUTO_HANDOFF = "auto";
766
+ await host.boot();
767
+ host.setPercent(37);
768
+ const out = await host.settle("completed");
769
+ assert.equal(out, undefined, "auto 模式不跑额外一轮,直接 settle");
770
+ assert.match(host.audit(), /handoff-auto-pending/);
771
+ await host.settled(false);
772
+ assert.equal(host.sent.length, 1);
773
+ assert.match(host.sent[0].text, /^\/handoff-new /);
774
+ assert.match(host.sent[0].text, /自动交接/);
775
+ assert.equal(host.sent[0].opts.expandPromptTemplates, true);
776
+ assert.match(host.audit(), /handoff-auto/);
777
+ } finally {
778
+ host.cleanup();
779
+ }
780
+ });
781
+
782
+ test("auto 模式但没装 pi-agent-handoff ⇒ 退回提醒(不派不存在的命令)", async () => {
783
+ const host = createHost({ boot: true });
784
+ try {
785
+ writeFileSync(join(host.dir, "settings.json"), '{"packages":[]}\n');
786
+ process.env.PI_AUTO_HANDOFF = "auto";
787
+ await host.boot();
788
+ host.setPercent(37);
789
+ const out = await host.settle("completed");
790
+ assert.ok(out?.continue === true, "退回 remind:continue 让模型自己交接");
791
+ assert.match(out.entries.at(-1).content, /交接线/);
792
+ await host.settled(false);
793
+ assert.equal(host.sent.length, 0);
794
+ } finally {
795
+ host.cleanup();
796
+ }
797
+ });
798
+
799
+ test("交接(reason=new)不丢计时器;真退出才清;死 pid 的孤儿计时器会被清掉", async () => {
800
+ const host = createHost({ boot: true });
801
+ try {
802
+ writeTimers([{ id: "tm-keep", dueAt: Date.now() + 3_600_000, note: "交接后还要用", createdAt: new Date().toISOString() }]);
803
+ await host.boot();
804
+ assert.equal(readTimers().length, 1, "启动时恢复");
805
+ await host.shutdown("new");
806
+ assert.equal(readTimers().length, 1, "换会话不是退出,计时器留着");
807
+ await host.shutdown("quit");
808
+ assert.equal(readTimers().length, 0, "真退出清掉");
809
+
810
+ // 死 pid 的孤儿文件:写到别的 pid,重新 boot 应被清掉
811
+ const deadPid = 999_999;
812
+ writeTimers([{ id: "tm-orphan", dueAt: Date.now() + 60_000, note: "孤儿", createdAt: new Date().toISOString() }], deadPid);
813
+ await host.boot();
814
+ assert.equal(existsSync(join(host.dir, "state", "auto", "timers", `${deadPid}.json`)), false);
815
+ assert.match(host.audit(), /timer-prune/);
816
+ } finally {
817
+ host.cleanup();
818
+ }
819
+ });