pi-auto-unattended 0.7.0 → 0.8.1

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,24 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.8.1 (2026-12-05)
4
+
5
+ - 交接**冷却**:10 分钟内不重复发交接指令(`PI_AUTO_HANDOFF_COOLDOWN_MS` 可覆盖,0 = 关)。
6
+ 防的是「阈值配得比新会话基线还低」时的乒乓(交接出来的新会话一 settle 又超线 ⇒ 无限换会话);
7
+ 冷却期内按普通续轮走,audit `handoff-cooldown`。`handoffCoolingDown` 纯函数 + 4 条断言。
8
+ - 网络闸门(同日的 limbus-auto 交付,见那边仓):`tools/net-guard.py` 批前 `--check` + 批中 `--watch`。
9
+
10
+ ## 0.8.0 (2026-12-05)
11
+
12
+ - 修语义偏差(用户 2026-12-05):「off = 服务今天不会再拉起本目录」把 agent 的开关说成了**目录**级,
13
+ 而它实际关的是**本会话**。现在:
14
+ - `retired/<slug>.json` 记 `scope:"session"` + `sessionId` + `pid` + `boot` + `promptHash`,
15
+ 文案改为「本会话已收工:不再续轮。服务今天不再为这份需求拉起本目录(改 `projects[].prompt`、
16
+ 写今日补充、预约到点或 `pi-auto on` 才会重新拉起)」。
17
+ - 新增工单指纹 `jobFingerprint` = `sha1(projects[].prompt + "\n" + 作用域内 today.prompt)`(TS 与
18
+ `lib.sh:pi_job_fingerprint` 同口径、两边各自有测试):**指纹变了 ⇒ 当天的收工标记作废**
19
+ (`pi_retired_today` 返回「未收工」),服务可以重新拉起 —— 这样「agent 关掉自己」不会把目录整天锁死。
20
+ - legacy 标记(没有 `promptHash` 的旧文件)按已收工处理,升级不会把旧标记当成新活。
21
+ - 回归:`node --test` 31 → 32 条、`test/lib.test.sh` 新增 4 条(指纹一致/legacy/需求变更/今日补充变更)。
3
22
  ## 0.7.0 (2026-12-05)
4
23
 
5
24
  - 新增**交接线**(用户口径:全天候 agent = 一个 agent 做完本轮把活交给下一轮):`agent_before_settle`
package/README.md CHANGED
@@ -19,7 +19,7 @@ extensions/pi-auto.ts ──> state/auto/*.json (不 import bash/服务代
19
19
  服务/CLI ──写文件──> pi-mailbox inbox ──读/注入──> 会话
20
20
  ```
21
21
 
22
- - 扩展与服务只通过文件契约通信:`session-<pid>.json`(开关/轮次)、`retired/<slug>.json`(当天收工)、
22
+ - 扩展与服务只通过文件契约通信:`session-<pid>.json`(开关/轮次)、`retired/<slug>.json`(本会话当天收工 + 工单指纹)、
23
23
  `audit.log`(审计)。
24
24
  - 进上下文的话**只有一条通道**:`pi-mailbox`。本仓不实现 `send-keys`,也不自己调 `sendUserMessage`。
25
25
  - 代理探测仍是单向依赖 `~/bin/lib-proxy.sh`;没有反向调用。
@@ -162,7 +162,8 @@ auto_schedule({ action: "cancel", id: "sch-…" }) // 取消(id:"all"
162
162
  读数未知(刚压缩完)就什么都不做。回落到「阈值 −5」以下自动重新武装(audit `handoff-rearm`)。
163
163
  - `PI_AUTO_HANDOFF=off` 关掉;`remind`(默认)由模型写 brief,`auto` 由插件写 brief(要求 settings 里已装
164
164
  `pi-agent-handoff`,否则自动退回 `remind`)。
165
- - audit 关键字:`handoff-notify` / `handoff-remind` / `handoff-rearm` / `handoff-auto-pending` / `handoff-auto`。
165
+ - 冷却:10 分钟内不重复发交接(`PI_AUTO_HANDOFF_COOLDOWN_MS=0` 关掉)——防阈值低于新会话基线时的乒乓。
166
+ - audit 关键字:`handoff-notify` / `handoff-remind` / `handoff-rearm` / `handoff-cooldown` / `handoff-auto-pending` / `handoff-auto`。
166
167
  - 边界:交接由 `pi-agent-handoff` 完成会话替换(TUI-only);opencode 形态的 `--mode json` 会话不会被交接。
167
168
 
168
169
  ## 给 agent 的入口(三):`auto_timer` / `auto_bg`(等东西,但不空转)
@@ -272,7 +273,7 @@ systemd --user pi-auto.service
272
273
  - 无人值守会话(`PI_AUTO_SESSION_ID` / 兼容 `PI_BOOT_SESSION_ID` / `PI_RUN_DIR`)默认 **on**;
273
274
  用户手开会话默认 **off**(不许静默自己续轮)。
274
275
  - `on`:本轮结束后在 `agent_before_settle` 追加一条续轮草稿并 `continue: true`,**无轮次上限**。
275
- - `off`:唯一收工信号。写 `retired/<slug>.json` 后停;服务当天不再拉起。
276
+ - `off`:唯一收工信号。写 `retired/<slug>.json` 后停;服务当天不再为同一份需求拉起该目录。
276
277
  - `aborted`(Escape/断流)或 `error`(上游重试耗尽):不做硬续轮,而是延迟 15s/30s/1m/2m/5m
277
278
  往自己的 mailbox inbox 写一条轻推;`completed` 轮会重置退避计数。
278
279
  - 子代理/async runner 进程(`PI_SUBAGENT_*`、`PI_ASYNC_NATIVE_RUNNER`)直接不参与。
@@ -12,7 +12,8 @@
12
12
  *
13
13
  * 状态(`<agentDir>/state/auto/`,`PI_AUTO_STATE_DIR` 可覆盖):
14
14
  * session-<pid>.json { pid,cwd,slug,sessionId,boot,keepAlive,rounds,outcome,phase,updatedAt,... }
15
- * retired/<slug>.json { date,reason } 当天已收工(服务读它决定不再拉起)
15
+ * retired/<slug>.json { date,reason,scope,sessionId,pid,boot,promptHash }
16
+ * 本会话已收工 + 哪个工单收的(指纹变了 ⇒ 服务可重新拉起)
16
17
  * audit.log 一行一条 JSON
17
18
  */
18
19
  import crypto from "node:crypto";
@@ -42,6 +43,8 @@ export type AutoState = {
42
43
  handoffReminders?: number;
43
44
  /** 观测到的最高上下文百分比(审计用,便于事后核「为什么这时交接」)。 */
44
45
  contextPercentMax?: number | null;
46
+ /** 上次真正发交接指令的时刻(ISO):防「交接出来的新会话基线就超线」时的乒乓。 */
47
+ lastHandoffAt?: string | null;
45
48
  };
46
49
 
47
50
  const STATUS_KEY = "pi-auto";
@@ -108,10 +111,38 @@ export function retiredFile(cwd: string): string {
108
111
  return path.join(retiredRoot(), `${slugFor(cwd)}.json`);
109
112
  }
110
113
 
114
+ /**
115
+ * 「这份工单」的指纹 = sha1(projects[].prompt + "\n" + 作用域命中的 today.prompt)。
116
+ * 与 lib.sh:pi_job_fingerprint 同口径。收工标记记的是**哪个工单收的工**,
117
+ * 不是「这个目录今天不许再动」——需求变了就该重新拉起(2026-12-05 用户口径)。
118
+ */
119
+ export function jobFingerprint(cwd: string, now = new Date()): string {
120
+ const dir = resolveDir(cwd);
121
+ let prompt = "";
122
+ let today = "";
123
+ try {
124
+ const plan = readPlan();
125
+ const proj = plan.projects.find((p) => p.dir && resolveDir(p.dir) === dir);
126
+ prompt = proj?.prompt ?? "";
127
+ if (plan.today.date === localDate(now) && (!plan.today.dir || resolveDir(plan.today.dir) === dir)) {
128
+ today = plan.today.prompt ?? "";
129
+ }
130
+ } catch {
131
+ /* plan 读不到就按空指纹算(等价于 legacy 行为) */
132
+ }
133
+ return crypto.createHash("sha1").update(`${prompt}\n${today}`).digest("hex");
134
+ }
135
+
136
+ /**
137
+ * 今天是否已为**这份工单**收工。legacy(没有 promptHash 的旧文件)按「已收工」处理,
138
+ * 避免升级后把旧的收工标记当成新活。
139
+ */
111
140
  export function retiredToday(cwd: string, now = new Date()): boolean {
112
141
  try {
113
- const data = JSON.parse(fs.readFileSync(retiredFile(cwd), "utf8")) as { date?: string };
114
- return data.date === localDate(now);
142
+ const data = JSON.parse(fs.readFileSync(retiredFile(cwd), "utf8")) as { date?: string; promptHash?: string };
143
+ if (data.date !== localDate(now)) return false;
144
+ if (!data.promptHash) return true;
145
+ return data.promptHash === jobFingerprint(cwd, now);
115
146
  } catch {
116
147
  return false;
117
148
  }
@@ -122,11 +153,21 @@ function localDate(d: Date): string {
122
153
  return new Date(d.getTime() - off).toISOString().slice(0, 10);
123
154
  }
124
155
 
125
- export function retire(cwd: string, reason: string): void {
156
+ /** 收工 = 本会话停;顺带记下「哪份工单、哪个会话」收的,服务据此决定还要不要为同样的需求再拉起。 */
157
+ export function retire(cwd: string, reason: string, extra: { sessionId?: string; pid?: number; boot?: boolean } = {}): void {
126
158
  try {
127
159
  fs.mkdirSync(retiredRoot(), { recursive: true });
128
160
  const file = retiredFile(cwd);
129
- fs.writeFileSync(file, `${JSON.stringify({ date: localDate(new Date()), reason }, null, 2)}\n`);
161
+ const payload = {
162
+ date: localDate(new Date()),
163
+ reason,
164
+ scope: "session",
165
+ sessionId: extra.sessionId ?? "",
166
+ pid: extra.pid ?? process.pid,
167
+ boot: extra.boot ?? false,
168
+ promptHash: jobFingerprint(cwd),
169
+ };
170
+ fs.writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`);
130
171
  } catch {
131
172
  /* 收工标记写不进去不影响会话退出 */
132
173
  }
@@ -709,6 +750,18 @@ export function handoffMode(env: NodeJS.ProcessEnv = process.env): HandoffMode {
709
750
 
710
751
  /** 百分比掉回「阈值 − 5」以下才重新武装(压缩后不该一直催交接)。 */
711
752
  export const HANDOFF_REARM_DROP = 5;
753
+ /**
754
+ * 交接冷却:10 分钟内不重复交接。防的是「阈值配得比新会话基线还低」时的乒乓
755
+ * (每次交接出来的新会话一 settle 就又超线 ⇒ 无限换会话)。
756
+ */
757
+ export const HANDOFF_COOLDOWN_MS = 10 * 60_000;
758
+
759
+ export function handoffCoolingDown(lastHandoffAt: string | null | undefined, now = Date.now(), cooldownMs = HANDOFF_COOLDOWN_MS): boolean {
760
+ if (!lastHandoffAt) return false;
761
+ const at = Date.parse(lastHandoffAt);
762
+ if (!Number.isFinite(at)) return false;
763
+ return now - at < cooldownMs;
764
+ }
712
765
 
713
766
  /** 本轮要不要发交接提醒:0 = 不用,1 = 首次提醒,2 = 提醒过仍未交接(升级)。 */
714
767
  export function handoffStage(percent: number | null, threshold: number, reminded: number): 0 | 1 | 2 {
@@ -925,7 +978,9 @@ export default function (pi: ExtensionAPI) {
925
978
  const setKeepAlive = (ctx: ExtensionContext, enabled: boolean, by: "agent" | "command" | "retired", note?: string): AutoState => {
926
979
  const next = touch(ctx, { keepAlive: enabled });
927
980
  if (enabled) unretire(next.cwd);
928
- else if (next.boot) retire(next.cwd, note?.trim() || by);
981
+ else if (next.boot) {
982
+ retire(next.cwd, note?.trim() || by, { sessionId: next.sessionId, pid: next.pid, boot: next.boot });
983
+ }
929
984
  audit({ kind: enabled ? "on" : "off", by, cwd: next.cwd, note: note ?? null, rounds: next.rounds });
930
985
  return next;
931
986
  };
@@ -953,11 +1008,11 @@ export default function (pi: ExtensionAPI) {
953
1008
  label: "无人值守续轮开关",
954
1009
  description:
955
1010
  "pi-auto 的续轮开关:on = 本轮结束后自动接着推下一轮(无轮次上限,直到你自己 off);" +
956
- "off = 收工,不再自动续轮、服务当天也不会再拉起本目录;status = 看当前开关/轮次。",
1011
+ "off = 本会话收工(不再自动续轮;服务当天不再为这份需求拉起本目录,需求/今日补充/预约变了才重新拉起);status = 看当前开关/轮次。",
957
1012
  promptSnippet: "无人值守续轮开关(pi-auto):要接着干就 on,收工就 off",
958
1013
  promptGuidelines: [
959
1014
  "还有自己能做的活 → `auto_switch({action:\"on\"})`(无人值守会话默认已开);",
960
- "收工或只剩人工/审批/环境门 → `auto_switch({action:\"off\", note:\"原因\"})`:这是唯一的收工信号;",
1015
+ "收工或只剩人工/审批/环境门 → `auto_switch({action:\"off\", note:\"原因\"})`:这是唯一的收工信号(关的是**本会话**,服务当天不再为同一份需求拉起本目录);",
961
1016
  "等 CI/子代理/分钟级 ⇒ `auto_timer({after:\"25m\"})`;等一条长命令 ⇒ `auto_bg({command:…})`(都是调完就结束本轮,不要 `bash sleep`);",
962
1017
  ],
963
1018
  parameters: {
@@ -980,7 +1035,7 @@ export default function (pi: ExtensionAPI) {
980
1035
  type: "text" as const,
981
1036
  text:
982
1037
  `pi-auto:keepAlive=${next.keepAlive}(轮次 ${next.rounds})。` +
983
- (next.keepAlive ? "本轮结束后自动续下一轮;收工时记得 off。" : "已收工:不再自动续轮,服务今天不会再拉起本目录。"),
1038
+ (next.keepAlive ? "本轮结束后自动续下一轮;收工时记得 off。" : "本会话已收工:不再续轮。服务今天不再为这份需求拉起本目录(改 projects[].prompt、写今日补充、预约到点或 `pi-auto on` 才会重新拉起)。"),
984
1039
  },
985
1040
  ],
986
1041
  details: { state: next },
@@ -1565,7 +1620,12 @@ export default function (pi: ExtensionAPI) {
1565
1620
  audit({ kind: "handoff-rearm", percent: pct, threshold: hAt, cwd: now.cwd });
1566
1621
  }
1567
1622
  const stage = handoffStage(pct, hAt, now.handoffReminders ?? 0);
1568
- if (stage > 0) {
1623
+ const cooldownRaw = Number(process.env.PI_AUTO_HANDOFF_COOLDOWN_MS ?? "");
1624
+ const cooldown = Number.isFinite(cooldownRaw) && cooldownRaw >= 0 ? cooldownRaw : HANDOFF_COOLDOWN_MS;
1625
+ if (stage > 0 && handoffCoolingDown(now.lastHandoffAt, Date.now(), cooldown)) {
1626
+ // 刚交接完(同一进程换会话)就别再交一次:本轮按普通续轮走
1627
+ audit({ kind: "handoff-cooldown", percent: pct, threshold: hAt, lastHandoffAt: now.lastHandoffAt, cwd: now.cwd });
1628
+ } else if (stage > 0) {
1569
1629
  const round = now.rounds + 1;
1570
1630
  const auto = hMode === "auto" && handoffExtensionInstalled();
1571
1631
  const next = touch(ctx, {
@@ -1574,6 +1634,7 @@ export default function (pi: ExtensionAPI) {
1574
1634
  handoffStage: stage,
1575
1635
  handoffReminders: (now.handoffReminders ?? 0) + 1,
1576
1636
  handoffPercent: pct,
1637
+ lastHandoffAt: new Date().toISOString(),
1577
1638
  });
1578
1639
  nudgeAttempts = 0;
1579
1640
  audit({ kind: "handoff-remind", percent: pct, threshold: hAt, stage, mode: hMode, auto, round, cwd: next.cwd });
@@ -1694,7 +1755,9 @@ export default function (pi: ExtensionAPI) {
1694
1755
  if (!state) return;
1695
1756
  audit({ kind: "session-end", cwd: state.cwd, rounds: state.rounds, keepAlive: state.keepAlive, reason: event.reason });
1696
1757
  if (!state.keepAlive) {
1697
- if (state.boot) retire(state.cwd, `session_shutdown:${event.reason}`);
1758
+ if (state.boot) {
1759
+ retire(state.cwd, `session_shutdown:${event.reason}`, { sessionId: state.sessionId, pid: state.pid, boot: state.boot });
1760
+ }
1698
1761
  try {
1699
1762
  fs.rmSync(statePath(state.pid), { force: true });
1700
1763
  } catch {
package/lib.sh CHANGED
@@ -163,12 +163,40 @@ pi_sid_current() {
163
163
  # 由扩展在 auto_switch off / 正常退出时写,由本库读;服务据此当天不再拉起。
164
164
  pi_retired_file() { printf '%s/%s.json' "$PI_AUTO_RETIRED_DIR" "$(pi_slug_for "$1")"; }
165
165
 
166
- pi_retired_today() { # <目录>;返回 0 = 今天已收工
167
- local f d
168
- f="$(pi_retired_file "$1")"
166
+ # 「这份工单」的指纹 = sha1(projects[].prompt + "\n" + 作用域命中的 today.prompt)。
167
+ # 与 extensions/pi-auto.ts:jobFingerprint 同口径。收工标记记的是**哪个工单收的工**:
168
+ # 需求/今日补充一变,指纹就变 ⇒ 同一目录当天还能被重新拉起(2026-12-05 用户口径:
169
+ # agent 关掉的是**本会话**,不是「这个目录今天不许再动」)。
170
+ pi_plan_project_prompt() { # <目录>
171
+ local dir="${1:-}"
172
+ pi_plan_has || return 0
173
+ jq -r --arg home "$HOME" --arg d "$dir" '
174
+ [ .projects[]? | select((.dir // "") != "")
175
+ | (.dir as $x | (if ($x | startswith("~")) then ($home + ($x | sub("^~"; ""))) else $x end)) as $abs
176
+ | select($abs == $d) | (.prompt // "") ] | (first // "")' "$PI_AUTO_PLAN_FILE" 2>/dev/null | head -1
177
+ }
178
+
179
+ pi_job_fingerprint() { # <目录>
180
+ local dir prompt today
181
+ dir="$(realpath -m -- "${1:-$PWD}" 2>/dev/null || printf '%s' "${1:-$PWD}")"
182
+ prompt="$(pi_plan_project_prompt "$dir")"
183
+ today="$(pi_plan_today_for "$dir")"
184
+ pi_plan_hash "$prompt
185
+ $today"
186
+ }
187
+
188
+ pi_retired_today() { # <目录>;返回 0 = 这份工单今天已收工
189
+ local f dir d ph
190
+ dir="$(realpath -m -- "${1:-$PWD}" 2>/dev/null || printf '%s' "${1:-$PWD}")"
191
+ f="$(pi_retired_file "$dir")"
169
192
  [ -f "$f" ] || return 1
170
193
  d="$(jq -r '.date // empty' "$f" 2>/dev/null)"
171
- [ "$d" = "$(date +%F)" ]
194
+ [ "$d" = "$(date +%F)" ] || return 1
195
+ ph="$(jq -r '.promptHash // empty' "$f" 2>/dev/null)"
196
+ [ -n "$ph" ] || return 0 # legacy(升级前的收工标记)按已收工处理,避免被当成新活
197
+ [ "$ph" = "$(pi_job_fingerprint "$dir")" ] && return 0
198
+ pi_log "收工标记已过期(工单指纹变了):$dir ⇒ 视为未收工,可重新拉起"
199
+ return 1
172
200
  }
173
201
 
174
202
  pi_retired_set() { # <目录> <原因>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-auto-unattended",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
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",
package/pi-auto CHANGED
@@ -78,7 +78,7 @@ ensure_one() { # <目录> <常驻需求> [force] [一次性请求]
78
78
  pi_state_init "$session" "$PI_AUTO_DIR" "$PI_AUTO_TAG"
79
79
 
80
80
  if [ "$force" != "1" ] && pi_retired_today "$PI_AUTO_DIR"; then
81
- pi_log "跳过 $session:今天已收工(pi-auto on 可恢复)"
81
+ pi_log "跳过 $session:这份需求今天已收工(改 projects[].prompt / 写今日补充 / 预约到点 / pi-auto on 都会重新拉起)"
82
82
  return 0
83
83
  fi
84
84
 
package/test/lib.test.sh CHANGED
@@ -145,4 +145,38 @@ jq '.projects += [{"dir":"'"$HOME"'/expired","enabled":true,"prompt":"","until":
145
145
  # 锁用后不留痕迹
146
146
  [ ! -e "$PI_AUTO_PLAN_FILE.lockdir" ] || fail "plan.json 锁未释放"
147
147
 
148
+
149
+ # 收工标记绑定「这份工单」:指纹变了(projects[].prompt 或作用域内 today.prompt 变)⇒ 视为未收工
150
+ mkdir -p "$HOME/job"
151
+ cat >"$PI_AUTO_PLAN_FILE" <<JSON
152
+ {"version":2,"today":{"date":"$(date +%F)","dir":"","prompt":"今日补充A","hash":"x","deliveredTo":[]},
153
+ "projects":[{"dir":"$HOME/job","enabled":true,"prompt":"需求A"}],"schedules":[]}
154
+ JSON
155
+ fp="$(pi_job_fingerprint "$HOME/job")"
156
+ [ "${#fp}" = 40 ] || fail "job 指纹应是 sha1"
157
+ pi_retired_write() { # <promptHash|空>
158
+ mkdir -p "$PI_AUTO_RETIRED_DIR"
159
+ jq -n --arg d "$(date +%F)" --arg h "$1" --arg s "pi-auto-job-1" '{date:$d,reason:"agent off",scope:"session",sessionId:$s,pid:123,boot:true,promptHash:$h}' \
160
+ >"$(pi_retired_file "$HOME/job")"
161
+ }
162
+ pi_retired_write "$fp"
163
+ pi_retired_today "$HOME/job" || fail "指纹一致 ⇒ 应判已收工"
164
+ # legacy(没有 promptHash)仍按已收工处理
165
+ pi_retired_write ""
166
+ pi_retired_today "$HOME/job" || fail "legacy 收工标记应仍算已收工"
167
+ # 需求变了 ⇒ 视为未收工(同一目录当天要能重新拉起)
168
+ pi_retired_write "$fp"
169
+ jq '.projects[0].prompt="需求B"' "$PI_AUTO_PLAN_FILE" >"$PI_AUTO_PLAN_FILE.t" && mv "$PI_AUTO_PLAN_FILE.t" "$PI_AUTO_PLAN_FILE"
170
+ if pi_retired_today "$HOME/job"; then fail "projects[].prompt 变了仍判已收工"; fi
171
+ # 今日补充变了同样唤醒
172
+ cat >"$PI_AUTO_PLAN_FILE" <<JSON
173
+ {"version":2,"today":{"date":"$(date +%F)","dir":"$HOME/job","prompt":"今日补充A","hash":"x","deliveredTo":[]},
174
+ "projects":[{"dir":"$HOME/job","enabled":true,"prompt":"需求A"}],"schedules":[]}
175
+ JSON
176
+ pi_retired_write "$(pi_job_fingerprint "$HOME/job")"
177
+ pi_retired_today "$HOME/job" || fail "补充未变 ⇒ 已收工"
178
+ jq '.today.prompt="今日补充B"' "$PI_AUTO_PLAN_FILE" >"$PI_AUTO_PLAN_FILE.t" && mv "$PI_AUTO_PLAN_FILE.t" "$PI_AUTO_PLAN_FILE"
179
+ if pi_retired_today "$HOME/job"; then fail "今日补充变了仍判已收工"; fi
180
+ rm -f "$(pi_retired_file "$HOME/job")"
181
+
148
182
  echo "lib.sh gate: OK"
@@ -10,6 +10,7 @@ import register, {
10
10
  bgIndexPath,
11
11
  HANDOFF_DEFAULT_AT,
12
12
  handoffContinuationText,
13
+ handoffCoolingDown,
13
14
  handoffMode,
14
15
  handoffStage,
15
16
  handoffThreshold,
@@ -29,10 +30,12 @@ import register, {
29
30
  retire,
30
31
  retiredFile,
31
32
  retiredToday,
33
+ jobFingerprint,
32
34
  slugFor,
33
35
  statePath,
34
36
  timersPath,
35
37
  todayHash,
38
+ updatePlan,
36
39
  writeTimers,
37
40
  } from "../extensions/pi-auto.ts";
38
41
 
@@ -116,6 +119,7 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
116
119
  delete process.env.PI_AUTO_BG_POLL_MS;
117
120
  delete process.env.PI_AUTO_HANDOFF;
118
121
  delete process.env.PI_AUTO_HANDOFF_AT;
122
+ delete process.env.PI_AUTO_HANDOFF_COOLDOWN_MS;
119
123
  delete process.env.PI_BOOT_SESSION_ID;
120
124
  delete process.env.PI_RUN_DIR;
121
125
  rmSync(dir, { recursive: true, force: true });
@@ -677,6 +681,10 @@ test("handoff 判据:阈值默认 35、可环境覆盖;stage 只到线才提
677
681
  assert.match(handoffContinuationText(3, 36, 35, 1), /交接线/);
678
682
  assert.match(handoffContinuationText(3, 36, 35, 1), /36\.0%/);
679
683
  assert.match(handoffContinuationText(3, 36, 35, 2), /升级/);
684
+ assert.equal(handoffCoolingDown(null), false);
685
+ assert.equal(handoffCoolingDown(new Date().toISOString()), true, "刚交接完在冷却里");
686
+ assert.equal(handoffCoolingDown(new Date(Date.now() - 3_600_000).toISOString()), false, "一小时后不再冷却");
687
+ assert.equal(handoffCoolingDown("不是时间"), false);
680
688
  });
681
689
 
682
690
  test("mechanicalBrief:只写仓内可核实事实(指针/提交/工作树),不编状态", () => {
@@ -817,3 +825,62 @@ test("交接(reason=new)不丢计时器;真退出才清;死 pid 的孤
817
825
  host.cleanup();
818
826
  }
819
827
  });
828
+
829
+ test("收工标记绑的是会话+工单(不是目录):写 sessionId/scope/promptHash,需求变了当天还能重新拉起", async () => {
830
+ const host = createHost({ boot: true });
831
+ try {
832
+ await host.boot();
833
+ updatePlan((p) => {
834
+ p.projects = [{ dir: host.ctx.cwd, enabled: true, prompt: "需求A" }];
835
+ });
836
+ assert.match(jobFingerprint(host.ctx.cwd), /^[0-9a-f]{40}$/);
837
+ const off = await host.callTool("auto_switch", { action: "off", note: "做完了" });
838
+ assert.match(off.content[0].text, /本会话已收工/);
839
+ assert.match(off.content[0].text, /不再为这份需求拉起本目录/);
840
+
841
+ const raw = JSON.parse(readFileSync(retiredFile(host.ctx.cwd), "utf8"));
842
+ assert.equal(raw.scope, "session");
843
+ assert.equal(raw.sessionId, "sess-1");
844
+ assert.equal(raw.reason, "做完了");
845
+ assert.equal(raw.boot, true);
846
+ assert.match(raw.promptHash, /^[0-9a-f]{40}$/);
847
+ assert.equal(retiredToday(host.ctx.cwd), true);
848
+
849
+ // 同一目录换了工单 ⇒ 今天的收工标记不再算数(服务可以重新拉起)
850
+ updatePlan((p) => {
851
+ p.projects[0].prompt = "需求B";
852
+ });
853
+ assert.equal(retiredToday(host.ctx.cwd), false);
854
+
855
+ // legacy 标记(升级前写的、没有 promptHash)仍按已收工处理
856
+ writeFileSync(retiredFile(host.ctx.cwd), JSON.stringify({ date: new Date().toISOString().slice(0, 10), reason: "old" }));
857
+ assert.equal(retiredToday(host.ctx.cwd), true);
858
+ } finally {
859
+ host.cleanup();
860
+ }
861
+ });
862
+
863
+ test("交接冷却:刚交接完同一进程换会话不再乒乓(阈值低于新会话基线也不会无限换)", async () => {
864
+ const host = createHost({ boot: true });
865
+ try {
866
+ process.env.PI_AUTO_HANDOFF_COOLDOWN_MS = "600000";
867
+ await host.boot();
868
+ host.setPercent(36);
869
+ const first = await host.settle("completed");
870
+ assert.match(first.entries.at(-1).content, /交接线/);
871
+ assert.ok(host.state().lastHandoffAt, "要记下交接时刻");
872
+
873
+ // 交接出来的新会话:基线仍超线 ⇒ 冷却期内只走普通续轮,不再要求交接
874
+ const second = await host.settle("completed");
875
+ assert.match(second.entries.at(-1).content, /续轮/);
876
+ assert.doesNotMatch(second.entries.at(-1).content, /交接线/);
877
+ assert.match(host.audit(), /handoff-cooldown/);
878
+
879
+ // 冷却可以设 0(自测/调试口径)⇒ 立刻又能交接
880
+ process.env.PI_AUTO_HANDOFF_COOLDOWN_MS = "0";
881
+ const third = await host.settle("completed");
882
+ assert.match(third.entries.at(-1).content, /交接线/);
883
+ } finally {
884
+ host.cleanup();
885
+ }
886
+ });