@cold777/dsh-takeover 0.1.0 → 0.2.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/lib/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import "node:module";
2
- import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { execFile, execFileSync } from "node:child_process";
3
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, scryptSync } from "node:crypto";
4
+ import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
5
  import { homedir, hostname } from "node:os";
5
- import { join } from "node:path";
6
- import { execFileSync } from "node:child_process";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { gunzipSync, gzipSync } from "node:zlib";
8
+ import { promisify } from "node:util";
7
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
10
  //#region \0rolldown/runtime.js
9
11
  var __defProp = Object.defineProperty;
@@ -734,6 +736,8 @@ function listDirCards(d) {
734
736
  }
735
737
  /** 列 pending/ 并附坏卡清单(inboxList/state 用它暴露 skipped 计数) */
736
738
  const listPendingReport = (dir) => listDirCards(pendingDir(dir));
739
+ /** 列 archived/ 并附坏卡清单 */
740
+ const listArchivedReport = (dir) => listDirCards(archivedDir(dir));
737
741
  /**
738
742
  * 消费即弃(语义 3):pending → archived,返回卡片。
739
743
  * 二次取件同一 id 报错「收件箱无此待取件」。
@@ -818,7 +822,7 @@ function trimArchived(ad) {
818
822
  /** 同步跑 git,失败抛错(由调用方降级为 UNAVAILABLE,不往外 throw)。
819
823
  * `-c core.fsmonitor=false`:卡片 cwd 是外来输入,仓库本地 fsmonitor 钩子是卡片作者
820
824
  * 可布置的命令执行面(读一张卡 = 执行一段卡片作者的 shell)——快照与核验一律禁用。 */
821
- function git(cwd, args) {
825
+ function git$1(cwd, args) {
822
826
  return execFileSync("git", [
823
827
  "-C",
824
828
  cwd,
@@ -847,8 +851,8 @@ function porcelainPaths(out) {
847
851
  function collectGitSnapshot(cwd) {
848
852
  try {
849
853
  return {
850
- branch: git(cwd, ["branch", "--show-current"]),
851
- changed: porcelainPaths(git(cwd, [
854
+ branch: git$1(cwd, ["branch", "--show-current"]),
855
+ changed: porcelainPaths(git$1(cwd, [
852
856
  "-c",
853
857
  "core.quotePath=false",
854
858
  "status",
@@ -876,8 +880,8 @@ function verifyGit(card) {
876
880
  let branch;
877
881
  let changed;
878
882
  try {
879
- branch = git(cwd, ["branch", "--show-current"]);
880
- changed = porcelainPaths(git(cwd, [
883
+ branch = git$1(cwd, ["branch", "--show-current"]);
884
+ changed = porcelainPaths(git$1(cwd, [
881
885
  "-c",
882
886
  "core.quotePath=false",
883
887
  "status",
@@ -907,13 +911,13 @@ const PATCH_MAX_BYTES = 524288;
907
911
  * 卡片 cwd 是外来输入,本地钩子是卡片作者可布置的命令执行面。 */
908
912
  function collectPatch(cwd, maxBytes = PATCH_MAX_BYTES) {
909
913
  try {
910
- git(cwd, ["rev-parse", "--is-inside-work-tree"]);
914
+ git$1(cwd, ["rev-parse", "--is-inside-work-tree"]);
911
915
  } catch {
912
916
  return null;
913
917
  }
914
918
  let patch = "";
915
919
  try {
916
- patch = git(cwd, [
920
+ patch = git$1(cwd, [
917
921
  "-c",
918
922
  "core.quotePath=false",
919
923
  "diff",
@@ -924,7 +928,7 @@ function collectPatch(cwd, maxBytes = PATCH_MAX_BYTES) {
924
928
  }
925
929
  let untracked = [];
926
930
  try {
927
- untracked = git(cwd, [
931
+ untracked = git$1(cwd, [
928
932
  "-c",
929
933
  "core.quotePath=false",
930
934
  "ls-files",
@@ -955,6 +959,314 @@ function collectPatch(cwd, maxBytes = PATCH_MAX_BYTES) {
955
959
  untracked
956
960
  };
957
961
  }
962
+ /** gzip 分块字节(480KB):低于 core 512KB 硬限留出余量,每块独立落盘 */
963
+ const PATCH_CHUNK_BYTES = 491520;
964
+ /** 自采 diff 单命令超时(毫秒):与 tools.ts 基线采集同口径——挂死的 git / 慢盘不拖垮寄存 */
965
+ const GIT_DIFF_TIMEOUT_MS = 15e3;
966
+ /** gzip magic 识别(前 2 字节 = 1f 8b):按字节判形态,不依赖扩展名 */
967
+ function isGzipBytes(buf) {
968
+ return buf.byteLength >= 2 && buf[0] === 31 && buf[1] === 139;
969
+ }
970
+ /**
971
+ * 手拼「新增文件 unified diff」:格式逐行对齐 git intent-to-add 的输出
972
+ *(git diff HEAD 对已 add -N 文件的形态),git apply / --check / -3way 实测可消费:
973
+ * - 空文件 = 仅扩展头无 hunk(git 同款);
974
+ * - 末行无换行 = hunk 后跟 `` 标记;
975
+ * - index 行带全量 blob sha1(git apply --3way 依赖 blob 哈希做三方合并)。
976
+ * 模式固定 100644:Windows 源机上可执行位本就不可知,跨机还原后如需 +x 由接手方补
977
+ *(卡片内容一律 HISTORY_REPORTED,模式漂移不算静默失真)。
978
+ * 换行原样保留(CRLF 文件字节级还原);git apply 侧的 eol 转换(autocrlf)是 git
979
+ * 自身对一切 diff 的语义,不是本函数引入的失真。
980
+ */
981
+ function newFileDiffBlock(file, content) {
982
+ const blobSha = createHash("sha1").update(`blob ${content.byteLength}\0`).update(content).digest("hex");
983
+ const head = [
984
+ `diff --git a/${file} b/${file}`,
985
+ "new file mode 100644",
986
+ `index 0000000000000000000000000000000000000000..${blobSha}`
987
+ ];
988
+ const text = content.toString("utf-8");
989
+ if (text === "") return `${head.join("\n")}\n`;
990
+ const hasTrailingNl = text.endsWith("\n");
991
+ const lines = text.split("\n");
992
+ if (hasTrailingNl) lines.pop();
993
+ const parts = [
994
+ ...head,
995
+ "--- /dev/null",
996
+ `+++ b/${file}`,
997
+ `@@ -0,0 +1,${lines.length} @@`,
998
+ ...lines.map((l) => `+${l}`)
999
+ ];
1000
+ if (!hasTrailingNl) parts.push("\");
1001
+ return `${parts.join("\n")}\n`;
1002
+ }
1003
+ /** 内联路径安全闸:绝对路径 / 上跳 / 引号(git C-quoted 输出歧义面)/ 换行一律不内联 */
1004
+ function unsafeRelPath(file) {
1005
+ return file.startsWith("/") || file.includes("..") || file.includes("\"") || file.includes("\n") || file.includes("\r");
1006
+ }
1007
+ /**
1008
+ * 把 untracked 清单中的小文件手拼 diff 追加进补丁全文。
1009
+ * base 传推送侧解析出的补丁全文(vendor 超 512KB 拒带时调用方已自采;非 git 仓传空串
1010
+ * 且清单为空);清单为空或全部放弃时返回 base 原文。追加处以换行衔接:vendor patch
1011
+ * 经 trim 尾部无换行,直接拼接会把两段粘成一行。
1012
+ */
1013
+ function augmentPatchWithUntracked(cwd, base, untracked) {
1014
+ const inlined = [];
1015
+ const leftOut = [];
1016
+ const blocks = [];
1017
+ for (const u of untracked) {
1018
+ if (u.bytes >= 65536) {
1019
+ leftOut.push({
1020
+ ...u,
1021
+ reason: "size"
1022
+ });
1023
+ continue;
1024
+ }
1025
+ if (unsafeRelPath(u.file)) {
1026
+ leftOut.push({
1027
+ ...u,
1028
+ reason: "unsafe"
1029
+ });
1030
+ continue;
1031
+ }
1032
+ let buf;
1033
+ try {
1034
+ if (!statSync(join(cwd, u.file)).isFile()) {
1035
+ leftOut.push({
1036
+ ...u,
1037
+ reason: "unreadable"
1038
+ });
1039
+ continue;
1040
+ }
1041
+ buf = readFileSync(join(cwd, u.file));
1042
+ } catch {
1043
+ leftOut.push({
1044
+ ...u,
1045
+ reason: "unreadable"
1046
+ });
1047
+ continue;
1048
+ }
1049
+ if (buf.byteLength >= 65536) {
1050
+ leftOut.push({
1051
+ ...u,
1052
+ reason: "size"
1053
+ });
1054
+ continue;
1055
+ }
1056
+ if (buf.includes(0)) {
1057
+ leftOut.push({
1058
+ ...u,
1059
+ reason: "binary"
1060
+ });
1061
+ continue;
1062
+ }
1063
+ let text;
1064
+ try {
1065
+ text = new TextDecoder("utf-8", { fatal: true }).decode(buf);
1066
+ } catch {
1067
+ leftOut.push({
1068
+ ...u,
1069
+ reason: "binary"
1070
+ });
1071
+ continue;
1072
+ }
1073
+ blocks.push(newFileDiffBlock(u.file, Buffer.from(text, "utf-8")));
1074
+ inlined.push({
1075
+ file: u.file,
1076
+ bytes: buf.byteLength
1077
+ });
1078
+ }
1079
+ const appended = blocks.join("");
1080
+ return {
1081
+ patch: base === "" ? appended : base.endsWith("\n") ? base + appended : `${base}\n${appended}`,
1082
+ inlined,
1083
+ leftOut
1084
+ };
1085
+ }
1086
+ /** 自采 diff 缓冲上限(64MB):vendor git() 用默认 1MB maxBuffer,diff 超限时它自己
1087
+ * 先崩(抛错被吞成空串);本侧自采必须撑住被 vendor 判「超限拒带」的 512KB~1MB 区间,
1088
+ * 也顺带兜住 >1MB 的假干净。64MB 是显式推送动作下可接受的内存峰值;再大的 diff
1089
+ * 属病理场景,自采失败走「自采失败未随卡」的诚实降级而非静默。 */
1090
+ const GIT_DIFF_MAX_BUFFER_BYTES = 67108864;
1091
+ /**
1092
+ * vendor collectPatch 超 PATCH_MAX_BYTES 时整份拒带(patch 为空串)——这里以 core 同款
1093
+ * 口径(fsmonitor=false + quotePath=false + trim)自采 diff 全文,交给 gzip/分块管线带走。
1094
+ * 拿不到(git 失败/unborn)回 null,调用方如实降级,绝不假称已带。
1095
+ */
1096
+ function collectFullDiff(cwd) {
1097
+ try {
1098
+ return execFileSync("git", [
1099
+ "-C",
1100
+ cwd,
1101
+ "-c",
1102
+ "core.fsmonitor=false",
1103
+ "-c",
1104
+ "core.quotePath=false",
1105
+ "diff",
1106
+ "HEAD"
1107
+ ], {
1108
+ encoding: "utf-8",
1109
+ timeout: GIT_DIFF_TIMEOUT_MS,
1110
+ maxBuffer: GIT_DIFF_MAX_BUFFER_BYTES,
1111
+ stdio: [
1112
+ "ignore",
1113
+ "pipe",
1114
+ "pipe"
1115
+ ]
1116
+ }).trim();
1117
+ } catch {
1118
+ return null;
1119
+ }
1120
+ }
1121
+ /**
1122
+ * collectPatch 结果 → 推送侧补丁全文。vendor 的 patch 空串是二义的:真空树、
1123
+ * unborn、diff 命令失败/超 1MB maxBuffer 崩掉的「假干净」都长一个样——空串时
1124
+ * 一律自采一次 diff 全文复核(真空树这次调用毫秒级秒回),只为不静默丢补丁;
1125
+ * vendor 给了非空且未拒带的 patch 才直接沿用(正常脏仓不多花一次进程)。
1126
+ */
1127
+ function resolvePatchText(cwd, bundle) {
1128
+ if (bundle === null) return "";
1129
+ if (bundle.patch !== "" && !bundle.truncated) return bundle.patch;
1130
+ return collectFullDiff(cwd) ?? "";
1131
+ }
1132
+ /**
1133
+ * 补丁边车落盘(写侧唯一入口,pushHandoff 在密钥扫描通过后调用):
1134
+ * ≤512KB 纯文本 <id>.patch(旧格式零改动);超限 gzipSync 后 ≤512KB 写单块 <id>.patch.gz;
1135
+ * 仍超按 480KB 等分 <id>.patch.NNN.gz——同一条 gzip 流按字节切块,取件侧按序拼接一次解压。
1136
+ */
1137
+ function writePatchSidecar(id, patch, dir) {
1138
+ const pend = pendingDir(dir);
1139
+ const plainBytes = Buffer.byteLength(patch, "utf-8");
1140
+ if (plainBytes <= 524288) {
1141
+ const p = join(pend, `${id}.patch`);
1142
+ writeFileSync(p, patch, "utf-8");
1143
+ return {
1144
+ format: "plain",
1145
+ chunks: 0,
1146
+ files: [p],
1147
+ writtenBytes: plainBytes
1148
+ };
1149
+ }
1150
+ const gz = gzipSync(Buffer.from(patch, "utf-8"));
1151
+ if (gz.byteLength <= 524288) {
1152
+ const p = join(pend, `${id}.patch.gz`);
1153
+ writeFileSync(p, gz);
1154
+ return {
1155
+ format: "gzip",
1156
+ chunks: 1,
1157
+ files: [p],
1158
+ writtenBytes: gz.byteLength
1159
+ };
1160
+ }
1161
+ const total = Math.ceil(gz.byteLength / PATCH_CHUNK_BYTES);
1162
+ const files = [];
1163
+ for (let i = 0; i < total; i++) {
1164
+ const p = join(pend, `${id}.patch.${String(i + 1).padStart(3, "0")}.gz`);
1165
+ writeFileSync(p, gz.subarray(i * PATCH_CHUNK_BYTES, Math.min((i + 1) * PATCH_CHUNK_BYTES, gz.byteLength)));
1166
+ files.push(p);
1167
+ }
1168
+ return {
1169
+ format: "gzip-chunked",
1170
+ chunks: total,
1171
+ files,
1172
+ writtenBytes: gz.byteLength
1173
+ };
1174
+ }
1175
+ /** gzip 分块名尾段正则:<id>.patch.NNN.gz(单块 .patch.gz 无序号段,不匹配) */
1176
+ const CHUNK_NAME_RE = /\.patch\.(\d+)\.gz$/;
1177
+ /** pending/ 下按序号升序收集某卡的 gzip 分块;序号断档(不连续)按损坏处理回 null */
1178
+ function listPatchChunks(id, dir) {
1179
+ let names;
1180
+ try {
1181
+ names = readdirSync(pendingDir(dir));
1182
+ } catch {
1183
+ return null;
1184
+ }
1185
+ const parts = [];
1186
+ for (const f of names) {
1187
+ if (!f.startsWith(`${id}.patch.`) || !f.endsWith(".gz")) continue;
1188
+ const m = CHUNK_NAME_RE.exec(f);
1189
+ if (m === null) continue;
1190
+ parts.push({
1191
+ n: Number(m[1]),
1192
+ name: f
1193
+ });
1194
+ }
1195
+ if (parts.length === 0) return null;
1196
+ parts.sort((a, b) => a.n - b.n);
1197
+ for (let i = 0; i < parts.length; i++) if (parts[i]?.n !== i + 1) return null;
1198
+ return {
1199
+ paths: parts.map((p) => join(pendingDir(dir), p.name)),
1200
+ total: parts.length
1201
+ };
1202
+ }
1203
+ /**
1204
+ * 取件还原:pending/ 里的压缩形态(单块 .patch.gz 或分块 .patch.NNN.gz)→ 按序拼接 →
1205
+ * gzip magic 校验 → gunzip → 写归档 <id>.patch(git apply 指引路径与旧格式一致);
1206
+ * 压缩块原样搬去 archived/ 留审计轨迹。旧纯文本 .patch 不走本函数(consumePatch 先判)。
1207
+ */
1208
+ function restoreGzipPatch(id, dir) {
1209
+ const single = join(pendingDir(dir), `${id}.patch.gz`);
1210
+ const chunks = listPatchChunks(id, dir);
1211
+ let sources;
1212
+ let format;
1213
+ if (existsQuiet(single)) {
1214
+ sources = [single];
1215
+ format = "gzip";
1216
+ } else if (chunks !== null) {
1217
+ sources = chunks.paths;
1218
+ format = "gzip-chunked";
1219
+ } else return;
1220
+ const chunkCount = sources.length;
1221
+ const arch = archivedDir(dir);
1222
+ const bufs = [];
1223
+ for (const src of sources) try {
1224
+ bufs.push(readFileSync(src));
1225
+ } catch (e) {
1226
+ return { warn: `压缩块读取失败(${baseName(src)}):${e instanceof Error ? e.message : String(e)}` };
1227
+ }
1228
+ const merged = Buffer.concat(bufs);
1229
+ if (!isGzipBytes(merged)) {
1230
+ archiveParts(arch, sources);
1231
+ return { warn: "压缩流缺 gzip magic(1f 8b),可能损坏或被篡改——压缩块已原样归档" };
1232
+ }
1233
+ let plain;
1234
+ try {
1235
+ plain = gunzipSync(merged);
1236
+ } catch (e) {
1237
+ archiveParts(arch, sources);
1238
+ return { warn: `gzip 解压失败(${e instanceof Error ? e.message : String(e)})——压缩块已原样归档,可手工 gunzip 修复` };
1239
+ }
1240
+ const dest = join(arch, `${id}.patch`);
1241
+ try {
1242
+ writeFileSync(dest, plain);
1243
+ } catch (e) {
1244
+ return { warn: `解压后补丁落盘失败:${e instanceof Error ? e.message : String(e)}` };
1245
+ }
1246
+ archiveParts(arch, sources);
1247
+ return {
1248
+ path: dest,
1249
+ bytes: plain.byteLength,
1250
+ format,
1251
+ chunks: chunkCount
1252
+ };
1253
+ }
1254
+ /** 压缩块原样搬 archived(审计轨迹);搬移失败容忍——残留块由伴生孤儿清扫兜底 */
1255
+ function archiveParts(arch, sources) {
1256
+ for (const src of sources) try {
1257
+ renameSync(src, join(arch, basename(src)));
1258
+ } catch {}
1259
+ }
1260
+ function existsQuiet(p) {
1261
+ try {
1262
+ return statSync(p).isFile();
1263
+ } catch {
1264
+ return false;
1265
+ }
1266
+ }
1267
+ function baseName(p) {
1268
+ return basename(p);
1269
+ }
958
1270
  //#endregion
959
1271
  //#region src/lifecycle.ts
960
1272
  /**
@@ -979,8 +1291,10 @@ function collectPatch(cwd, maxBytes = PATCH_MAX_BYTES) {
979
1291
  const LIFECYCLE_REASONS = [
980
1292
  "secret_gate",
981
1293
  "skeleton_gate",
1294
+ "lifeboat",
982
1295
  "oversize",
983
1296
  "parse_error",
1297
+ "memory-absorbed",
984
1298
  "drift_mismatch",
985
1299
  "git_unavailable",
986
1300
  "sig_tampered",
@@ -1145,6 +1459,1034 @@ function verifyEnvelopeSig(data, dir, actualCardSha256) {
1145
1459
  return "ok";
1146
1460
  }
1147
1461
  //#endregion
1462
+ //#region src/sync.ts
1463
+ /**
1464
+ * 换机上下文同步(0.2.0):HANDOFF_HOME 的卡(pending/archived + 信封侧车)与
1465
+ * 签名密钥经 git 仓库端点跨机同步。
1466
+ *
1467
+ * 设计三原则(迭代计划 0.2.0):
1468
+ * 1. git-native、零存储凭据——传输端点 = 用户配置的 git 仓库;凭据完全交给系统 git
1469
+ * (credential helper / ssh),插件不存任何密钥;remote URL 保存时拒绝 userinfo
1470
+ * 形态(user:pass@),展示只出红折形态。secretscan 对 URL 内嵌凭据零覆盖,从入口堵死。
1471
+ * 2. HANDOFF_HOME 即工作树——启用同步 = home 内 git init(已仓则收编)+ 设 remote;
1472
+ * 同步范围 = pending/ + archived/(罩住 <id>.envelope.json)+ .signing-key.json +
1473
+ * sync.json;.gitignore 排除 lifecycle.jsonl / relay/ / config.json / *.claim
1474
+ * (机器本地记录,避免 append-only JSONL 两机同写必冲突)。
1475
+ * 3. 消费即弃跨机 = archived/ 当 tombstone——A 机取件 push,B 机 pull 后 pending
1476
+ * 消失且 archived/ 出现 → 不重放;合并冲突 → abort + 诚实报错,本地文件不动。
1477
+ *
1478
+ * 安全边界(THREAT-MODEL T6 修订):插件唯一的网络出口 = 本模块经系统 git 与用户
1479
+ * 显式配置的 remote 通信;GIT_TERMINAL_PROMPT=0 + 超时(默认 30s,可注入)保证
1480
+ * 永不挂死在凭据交互或不可达网络上。仓库本地强制 core.autocrlf=false——卡字节是
1481
+ * 信封签名面(cardSha256),checkout 行尾漂移会让全部卡 tampered(见 signing.ts)。
1482
+ *
1483
+ * state 路径零网络:buildState 读 sync.json + sync-state.json(上次同步的
1484
+ * ahead/behind/lastSyncAt/lastError,动作完成后写回),30s 轮询不碰任何网络。
1485
+ */
1486
+ const execFile$1 = promisify(execFile);
1487
+ /** 同步范围:卡的宇宙 + 签名密钥 + 同步配置(远端 URL 随目录走)+ 环境备份包(append-only,无合并冲突) */
1488
+ const SYNC_PATHS = [
1489
+ "pending",
1490
+ "archived",
1491
+ ".signing-key.json",
1492
+ "sync.json",
1493
+ "env-backup"
1494
+ ];
1495
+ /** GITIGNORE:机器本地记录不入库(生命周期日志/取件溯源/插件开关各自为本机事实) */
1496
+ const SYNC_GITIGNORE = [
1497
+ "# dsh-takeover 换机同步:机器本地记录不入库",
1498
+ "lifecycle.jsonl",
1499
+ "relay/",
1500
+ "config.json",
1501
+ "pending/*.claim",
1502
+ "*.tmp",
1503
+ "sync-state.json"
1504
+ ].join("\n");
1505
+ /** sync.json 路径(HANDOFF_HOME 内,随同步分发——B 机启用时可直接采纳同地址) */
1506
+ function syncConfigPath(dir) {
1507
+ return join(resolveHome(dir), "sync.json");
1508
+ }
1509
+ /** 读同步配置:文件缺失/损坏 fail-open 回未启用(同 loadSwitches 纪律),损坏必 console.warn */
1510
+ function loadSyncConfig(dir) {
1511
+ const p = syncConfigPath(dir);
1512
+ if (!existsSync(p)) return {
1513
+ enabled: false,
1514
+ remote: ""
1515
+ };
1516
+ try {
1517
+ const raw = JSON.parse(readFileSync(p, "utf-8"));
1518
+ return {
1519
+ enabled: raw.enabled === true,
1520
+ remote: typeof raw.remote === "string" ? raw.remote : ""
1521
+ };
1522
+ } catch (e) {
1523
+ console.warn(`[dsh-takeover] sync.json 损坏,按未配置处理:${e instanceof Error ? e.message : String(e)}`);
1524
+ return {
1525
+ enabled: false,
1526
+ remote: ""
1527
+ };
1528
+ }
1529
+ }
1530
+ /** 写同步配置:tmp + rename 原子替换(saveSwitches 同模板);写入前校验地址 */
1531
+ function saveSyncConfig(cfg, dir) {
1532
+ const remote = cfg.remote.trim();
1533
+ if (cfg.enabled && remote === "") throw new Error("启用同步前必须先填仓库地址");
1534
+ if (remote !== "") validateRemoteUrl(remote);
1535
+ const target = syncConfigPath(dir);
1536
+ const tmp = `${target}.${process.pid}.tmp`;
1537
+ try {
1538
+ writeFileSync(tmp, JSON.stringify({
1539
+ enabled: cfg.enabled,
1540
+ remote
1541
+ }, null, 2) + "\n", "utf-8");
1542
+ renameSync(tmp, target);
1543
+ } catch (e) {
1544
+ try {
1545
+ rmSync(tmp, { force: true });
1546
+ } catch {}
1547
+ throw e instanceof Error ? e : new Error(String(e));
1548
+ }
1549
+ }
1550
+ /**
1551
+ * 仓库地址校验:拒绝 userinfo 形态(`user:pass@`)——secretscan 对 URL 内嵌凭据
1552
+ * 零覆盖,插件也永不存储凭据,凭据交给系统 git credential helper / ssh agent。
1553
+ * 允许:https://、ssh://、git://、file://、git@host:path(scp 形态)、本地路径。
1554
+ * 返回 trim 后的地址;不合法抛中文错。
1555
+ */
1556
+ function validateRemoteUrl(url) {
1557
+ const u = url.trim();
1558
+ if (u === "") throw new Error("仓库地址不能为空");
1559
+ if (/^[A-Za-z0-9._~-]+:[^@/\\]+@[A-Za-z0-9._~-]+:/.test(u)) throw new Error("仓库地址不得内嵌凭据(user:pass@ 形态)——请改用 ssh key 或 credential helper");
1560
+ const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\//.exec(u);
1561
+ if (m !== null) {
1562
+ const scheme = m[1].toLowerCase();
1563
+ if (scheme !== "https" && scheme !== "ssh" && scheme !== "git" && scheme !== "file") throw new Error(`不支持的仓库协议:${scheme}(支持 https / ssh / git / 本地路径)`);
1564
+ const rest = u.slice(m[0].length);
1565
+ if (/^[^/@:]+:[^@/]*@/.test(rest)) throw new Error("仓库地址不得内嵌凭据(user:pass@ 形态)——请改用 ssh key 或 credential helper");
1566
+ return u;
1567
+ }
1568
+ return u;
1569
+ }
1570
+ /** 红折展示:userinfo 段打码(防御性——保存时已拒绝,展示仍再折一次) */
1571
+ function redactRemote(url) {
1572
+ return url.replace(/^([a-z]+):\/\/[^/@]+:[^@/]+@/i, "$1://***@").replace(/^([A-Za-z0-9._~-]+):[^@/\\]+@/, "$1:***@");
1573
+ }
1574
+ /** git 命令统一入口:参数数组不走 shell;禁交互(GIT_TERMINAL_PROMPT=0);超时硬杀 */
1575
+ async function git(args, opts) {
1576
+ const timeoutMs = opts.timeoutMs ?? 3e4;
1577
+ try {
1578
+ return (await execFile$1("git", [
1579
+ "-C",
1580
+ opts.cwd,
1581
+ "-c",
1582
+ "core.fsmonitor=false",
1583
+ "-c",
1584
+ "protocol.file.allow=always",
1585
+ "-c",
1586
+ "user.name=dsh-takeover",
1587
+ "-c",
1588
+ "user.email=dsh-takeover@local",
1589
+ ...args
1590
+ ], {
1591
+ encoding: "utf-8",
1592
+ timeout: timeoutMs,
1593
+ killSignal: "SIGKILL",
1594
+ env: {
1595
+ ...process.env,
1596
+ GIT_TERMINAL_PROMPT: "0"
1597
+ },
1598
+ windowsHide: true,
1599
+ maxBuffer: 16777216
1600
+ })).stdout;
1601
+ } catch (e) {
1602
+ const err = e;
1603
+ if (err.killed === true) throw new Error(`git ${String(args[0])} 超时(${(timeoutMs / 1e3).toFixed(1)}s)——网络不可达或凭据交互被禁`);
1604
+ const detail = (err.stderr ?? err.message ?? String(e)).trim();
1605
+ throw new Error(`git ${String(args[0])} 失败:${detail.slice(0, 400)}`);
1606
+ }
1607
+ }
1608
+ function homeOf(dir) {
1609
+ return resolveHome(dir);
1610
+ }
1611
+ /** 确保 home 是仓库(已仓收编)+ 强制行尾配置 + .gitignore + remote 对齐 */
1612
+ async function ensureRepo(cfg, dir, timeoutMs) {
1613
+ const home = homeOf(dir);
1614
+ if (!existsSync(join(home, ".git"))) {
1615
+ mkdirSync(home, { recursive: true });
1616
+ await git([
1617
+ "init",
1618
+ "-b",
1619
+ "main"
1620
+ ], {
1621
+ cwd: home,
1622
+ timeoutMs
1623
+ });
1624
+ }
1625
+ await git([
1626
+ "config",
1627
+ "core.autocrlf",
1628
+ "false"
1629
+ ], {
1630
+ cwd: home,
1631
+ timeoutMs
1632
+ });
1633
+ await git([
1634
+ "config",
1635
+ "core.eol",
1636
+ "lf"
1637
+ ], {
1638
+ cwd: home,
1639
+ timeoutMs
1640
+ });
1641
+ writeFileSync(join(home, ".gitignore"), SYNC_GITIGNORE + "\n", "utf-8");
1642
+ if ((await git(["remote"], {
1643
+ cwd: home,
1644
+ timeoutMs
1645
+ })).trim().split("\n").map((s) => s.trim()).includes("origin")) await git([
1646
+ "remote",
1647
+ "set-url",
1648
+ "origin",
1649
+ cfg.remote
1650
+ ], {
1651
+ cwd: home,
1652
+ timeoutMs
1653
+ });
1654
+ else await git([
1655
+ "remote",
1656
+ "add",
1657
+ "origin",
1658
+ cfg.remote
1659
+ ], {
1660
+ cwd: home,
1661
+ timeoutMs
1662
+ });
1663
+ return home;
1664
+ }
1665
+ /** 提交同步范围内的本地变化(无变化不提交;不存在的路径自动跳过) */
1666
+ async function commitLocal(home, timeoutMs) {
1667
+ await git([
1668
+ "add",
1669
+ "--",
1670
+ ".gitignore",
1671
+ ...SYNC_PATHS.filter((p) => existsSync(join(home, p)))
1672
+ ], {
1673
+ cwd: home,
1674
+ timeoutMs
1675
+ });
1676
+ if ((await git([
1677
+ "diff",
1678
+ "--cached",
1679
+ "--name-only"
1680
+ ], {
1681
+ cwd: home,
1682
+ timeoutMs
1683
+ })).trim() === "") return false;
1684
+ await git([
1685
+ "commit",
1686
+ "-m",
1687
+ "dsh-takeover 换机同步:收发件箱快照"
1688
+ ], {
1689
+ cwd: home,
1690
+ timeoutMs
1691
+ });
1692
+ return true;
1693
+ }
1694
+ /** fetch 远端并计数(远端空仓回 null;调用契约:本地 main 已存在——commitLocal 先行) */
1695
+ async function fetchOrigin(home, timeoutMs) {
1696
+ try {
1697
+ await git(["fetch", "origin"], {
1698
+ cwd: home,
1699
+ timeoutMs
1700
+ });
1701
+ } catch (e) {
1702
+ const msg = e instanceof Error ? e.message : String(e);
1703
+ if (/couldn't find remote ref|Repository is empty|does not appear to be a git repository|No such file or directory/i.test(msg)) return null;
1704
+ throw e;
1705
+ }
1706
+ if (!await git([
1707
+ "rev-parse",
1708
+ "--verify",
1709
+ "--quiet",
1710
+ "origin/main"
1711
+ ], {
1712
+ cwd: home,
1713
+ timeoutMs
1714
+ }).then(() => true, () => false)) return null;
1715
+ const count = (range) => git([
1716
+ "rev-list",
1717
+ "--count",
1718
+ range
1719
+ ], {
1720
+ cwd: home,
1721
+ timeoutMs
1722
+ }).then((s) => Number(s.trim()) || 0, () => 0);
1723
+ return {
1724
+ ahead: await count("origin/main..main"),
1725
+ behind: await count("main..origin/main")
1726
+ };
1727
+ }
1728
+ /** 合并远端:冲突即 abort + 中文诚实报错(本地文件不动)。契约:commitLocal 已先行。 */
1729
+ async function mergeRemote(home, timeoutMs) {
1730
+ if (!await git([
1731
+ "rev-parse",
1732
+ "--verify",
1733
+ "--quiet",
1734
+ "origin/main"
1735
+ ], {
1736
+ cwd: home,
1737
+ timeoutMs
1738
+ }).then(() => true, () => false)) return "none";
1739
+ if (await git([
1740
+ "rev-list",
1741
+ "--count",
1742
+ "main..origin/main"
1743
+ ], {
1744
+ cwd: home,
1745
+ timeoutMs
1746
+ }).then((s) => Number(s.trim()) || 0, () => 0) === 0) return "none";
1747
+ try {
1748
+ await git([
1749
+ "merge",
1750
+ "--no-edit",
1751
+ "--allow-unrelated-histories",
1752
+ "origin/main"
1753
+ ], {
1754
+ cwd: home,
1755
+ timeoutMs
1756
+ });
1757
+ } catch (e) {
1758
+ await git(["merge", "--abort"], {
1759
+ cwd: home,
1760
+ timeoutMs
1761
+ }).catch(() => {});
1762
+ throw new Error(`同步合并冲突(两侧都改过同一批文件)——已中止合并,本地文件原样保留。处理:在本机确认要保留的版本后重新寄存,或换一个全新仓库地址。git 原因:${e instanceof Error ? e.message : String(e)}`.slice(0, 400));
1763
+ }
1764
+ return "merged";
1765
+ }
1766
+ function readSyncStateFile(home) {
1767
+ try {
1768
+ return JSON.parse(readFileSync(join(home, "sync-state.json"), "utf-8"));
1769
+ } catch {
1770
+ return {};
1771
+ }
1772
+ }
1773
+ function writeSyncState(home, patch) {
1774
+ const next = {
1775
+ ...readSyncStateFile(home),
1776
+ ...patch,
1777
+ at: (/* @__PURE__ */ new Date()).toISOString()
1778
+ };
1779
+ const target = join(home, "sync-state.json");
1780
+ const tmp = `${target}.${process.pid}.tmp`;
1781
+ try {
1782
+ writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n", "utf-8");
1783
+ renameSync(tmp, target);
1784
+ } catch {
1785
+ try {
1786
+ rmSync(tmp, { force: true });
1787
+ } catch {}
1788
+ }
1789
+ }
1790
+ /** 动作统一收尾:失败也如实写状态,面板才能「一眼知道当前什么状态需要干嘛」 */
1791
+ async function runAction(action, dir, opts, body) {
1792
+ const cfg = loadSyncConfig(dir);
1793
+ if (!cfg.enabled || cfg.remote.trim() === "") return {
1794
+ ok: false,
1795
+ action,
1796
+ error: "换机同步未启用:先在设置卡「换机」页填仓库地址并启用"
1797
+ };
1798
+ const home = homeOf(dir);
1799
+ try {
1800
+ await ensureRepo(cfg, dir, opts?.timeoutMs);
1801
+ await commitLocal(home, opts?.timeoutMs);
1802
+ const result = await body(home, opts?.timeoutMs);
1803
+ writeSyncState(home, {
1804
+ ahead: result.ahead,
1805
+ behind: result.behind,
1806
+ ok: true,
1807
+ error: void 0
1808
+ });
1809
+ return {
1810
+ ok: true,
1811
+ action,
1812
+ detail: result.detail,
1813
+ ahead: result.ahead,
1814
+ behind: result.behind
1815
+ };
1816
+ } catch (e) {
1817
+ const error = e instanceof Error ? e.message : String(e);
1818
+ writeSyncState(home, {
1819
+ ok: false,
1820
+ error
1821
+ });
1822
+ return {
1823
+ ok: false,
1824
+ action,
1825
+ error
1826
+ };
1827
+ }
1828
+ }
1829
+ /** 启用同步:init/收编 + remote + 本地先提交 + 远端非空先合并再推(远端空仓直接首推) */
1830
+ async function syncSetup(url, dir, opts) {
1831
+ const remote = validateRemoteUrl(url);
1832
+ saveSyncConfig({
1833
+ enabled: true,
1834
+ remote
1835
+ }, dir);
1836
+ return runAction("setup", dir, opts, async (home, timeoutMs) => {
1837
+ const counts = await fetchOrigin(home, timeoutMs);
1838
+ await mergeRemote(home, timeoutMs);
1839
+ await git([
1840
+ "push",
1841
+ "-u",
1842
+ "origin",
1843
+ "main"
1844
+ ], {
1845
+ cwd: home,
1846
+ timeoutMs
1847
+ });
1848
+ const after = await fetchOrigin(home, timeoutMs);
1849
+ const ahead = after?.ahead ?? 0;
1850
+ const behind = after?.behind ?? 0;
1851
+ return {
1852
+ detail: counts === null ? `已启用换机同步(${redactRemote(remote)}):远端空仓,本地已完成首推` : `已启用换机同步(${redactRemote(remote)}):已与远端对齐并推送`,
1853
+ ahead,
1854
+ behind
1855
+ };
1856
+ });
1857
+ }
1858
+ /** pull:本地先提交 → fetch → 合并(冲突 abort 诚实报错) */
1859
+ async function syncPull(dir, opts) {
1860
+ return runAction("pull", dir, opts, async (home, timeoutMs) => {
1861
+ const counts = await fetchOrigin(home, timeoutMs);
1862
+ if (counts === null) return {
1863
+ detail: "远端为空仓库:本地已是最新",
1864
+ ahead: 0,
1865
+ behind: 0
1866
+ };
1867
+ const merged = await mergeRemote(home, timeoutMs);
1868
+ const after = await fetchOrigin(home, timeoutMs);
1869
+ const ahead = after?.ahead ?? 0;
1870
+ const behind = after?.behind ?? 0;
1871
+ return {
1872
+ detail: merged === "merged" ? `已拉取远端 ${counts.behind} 个提交` : "已与远端对齐",
1873
+ ahead,
1874
+ behind
1875
+ };
1876
+ });
1877
+ }
1878
+ /** push:本地提交 + 推送 */
1879
+ async function syncPush(dir, opts) {
1880
+ return runAction("push", dir, opts, async (home, timeoutMs) => {
1881
+ const committed = await commitLocal(home, timeoutMs);
1882
+ await git([
1883
+ "push",
1884
+ "origin",
1885
+ "main"
1886
+ ], {
1887
+ cwd: home,
1888
+ timeoutMs
1889
+ });
1890
+ const after = await fetchOrigin(home, timeoutMs);
1891
+ const ahead = after?.ahead ?? 0;
1892
+ const behind = after?.behind ?? 0;
1893
+ return {
1894
+ detail: committed ? "已提交并推送" : "无本地变化,已推送确认",
1895
+ ahead,
1896
+ behind
1897
+ };
1898
+ });
1899
+ }
1900
+ /** 立即同步 = pull(拿别人的)→ push(给别人的),一步到位 */
1901
+ async function syncNow(dir, opts) {
1902
+ const pulled = await syncPull(dir, opts);
1903
+ if (!pulled.ok) return pulled;
1904
+ return syncPush(dir, opts);
1905
+ }
1906
+ /** 组装同步状态(buildState 调用;未启用 → undefined,客户端整个块不渲染) */
1907
+ function syncStatusOf(dir) {
1908
+ const cfg = loadSyncConfig(dir);
1909
+ if (!cfg.enabled || cfg.remote.trim() === "") return void 0;
1910
+ const home = homeOf(dir);
1911
+ const repoReady = existsSync(join(home, ".git"));
1912
+ const stateFile = readSyncStateFile(home);
1913
+ let dirtyFiles = 0;
1914
+ if (repoReady) try {
1915
+ const out = execFileSync("git", [
1916
+ "-C",
1917
+ home,
1918
+ "-c",
1919
+ "core.fsmonitor=false",
1920
+ "status",
1921
+ "--porcelain",
1922
+ "--",
1923
+ ...SYNC_PATHS
1924
+ ], {
1925
+ encoding: "utf-8",
1926
+ timeout: 5e3,
1927
+ windowsHide: true,
1928
+ stdio: [
1929
+ "ignore",
1930
+ "pipe",
1931
+ "pipe"
1932
+ ]
1933
+ });
1934
+ dirtyFiles = out.trim() === "" ? 0 : out.trim().split("\n").length;
1935
+ } catch {}
1936
+ return {
1937
+ enabled: true,
1938
+ remote: redactRemote(cfg.remote),
1939
+ ahead: stateFile.ahead ?? 0,
1940
+ behind: stateFile.behind ?? 0,
1941
+ lastSyncAt: stateFile.at,
1942
+ lastError: stateFile.error,
1943
+ dirtyFiles,
1944
+ repoReady
1945
+ };
1946
+ }
1947
+ /** 工具侧状态行(zh 直出,与其他工具错误文案同语种纪律;面板侧用词典组自己的行) */
1948
+ function syncStatusLine(st) {
1949
+ const parts = [`远端 ${st.remote}`];
1950
+ if (st.behind > 0) parts.push(`落后 ${st.behind} 个提交(执行 now 拉取)`);
1951
+ if (st.ahead > 0) parts.push(`领先 ${st.ahead} 个提交(待推送)`);
1952
+ if (st.dirtyFiles > 0) parts.push(`${st.dirtyFiles} 个本地文件待提交`);
1953
+ if (st.lastError !== void 0) parts.push(`上次同步出错:${st.lastError}`);
1954
+ if (st.lastSyncAt !== void 0) parts.push(`上次同步 ${st.lastSyncAt.slice(0, 16).replace("T", " ")}`);
1955
+ return parts.join(" · ");
1956
+ }
1957
+ //#endregion
1958
+ //#region src/envbackup.ts
1959
+ /**
1960
+ * 环境备份/恢复(0.2.0 wave2):DSH 全家桶(settings/插件登记/会话/skills/工作区登记)
1961
+ * 打包成单个加密文件,随换机同步跨机,新机器解密 → dry-run diff → 确认落盘 → 可回滚。
1962
+ *
1963
+ * 安全三原则(THREAT-MODEL T7):
1964
+ * 1. 密钥类文件(.credentials.yaml / typesafe-key / zcode 凭据)只存在于加密包内——
1965
+ * API 没有明文备份路径,加密不可跳过;包体落 <HANDOFF_HOME>/env-backup/(随卡同步)。
1966
+ * 2. 口令派生(scrypt)+ AES-256-GCM 认证加密:口令永不落盘、永不进日志;错口令 =
1967
+ * GCM 校验失败 = 诚实报错,不吐半个字节。
1968
+ * 3. 恢复是「写 ~/.handoff 之外」的破例动作:必须先 dry-run 出 diff(新建/覆盖/相同),
1969
+ * 再显式确认才落盘;落盘前把被覆盖原物快照进 checkpoint,回滚一键还原。
1970
+ * 路径全走相对 user home 的白名单清单 + 穿越校验(..、绝对路径、盘符一律拒收)。
1971
+ *
1972
+ * 容器格式(纯 node,无子进程——没有 tar 就没有 tar-slip 面):
1973
+ * MAGIC 'DSHENV1' | salt(16) | iv(12) | tag(16) |
1974
+ * 密文 = manifestLen(u32 LE) + manifest JSON({files:[{path,bytes,sha256,category}],...})+ blobs
1975
+ */
1976
+ const MAGIC = Buffer.from("DSHENV1", "ascii");
1977
+ const SALT_LEN = 16;
1978
+ const IV_LEN = 12;
1979
+ const TAG_LEN = 16;
1980
+ /** scrypt N=2^14:内存 ~16MB,交互式口令够用且不拖垮面板 */
1981
+ const SCRYPT_N = 16384;
1982
+ /** 测绘结论:node_modules/缓存/日志/热 sqlite 全部排除(可重植),只备不可再生的登记与数据 */
1983
+ const SCOPE = [
1984
+ {
1985
+ category: "dsh-core",
1986
+ pattern: ".dsh/.credentials.yaml",
1987
+ secret: true
1988
+ },
1989
+ {
1990
+ category: "dsh-core",
1991
+ pattern: ".dsh/typesafe-key",
1992
+ secret: true
1993
+ },
1994
+ {
1995
+ category: "dsh-core",
1996
+ pattern: ".dsh/settings.yaml.imported"
1997
+ },
1998
+ {
1999
+ category: "dsh-core",
2000
+ pattern: ".dsh/mystery-root.json"
2001
+ },
2002
+ {
2003
+ category: "dsh-core",
2004
+ pattern: ".dsh/dsh-opencli-state.json"
2005
+ },
2006
+ {
2007
+ category: "dsh-profile",
2008
+ pattern: ".dsh/profiles/*/cordis.yml"
2009
+ },
2010
+ {
2011
+ category: "dsh-profile",
2012
+ pattern: ".dsh/profiles/*/cordis.patch.yml"
2013
+ },
2014
+ {
2015
+ category: "dsh-profile",
2016
+ pattern: ".dsh/profiles/*/package.json"
2017
+ },
2018
+ {
2019
+ category: "dsh-profile",
2020
+ pattern: ".dsh/profiles/*/pnpm-lock.yaml"
2021
+ },
2022
+ {
2023
+ category: "dsh-profile",
2024
+ pattern: ".dsh/profiles/*/pnpm-workspace.yaml"
2025
+ },
2026
+ {
2027
+ category: "dsh-sessions",
2028
+ pattern: ".dsh/sessions/**"
2029
+ },
2030
+ {
2031
+ category: "dsh-sessions",
2032
+ pattern: ".dsh/storages/**"
2033
+ },
2034
+ {
2035
+ category: "dsh-registries",
2036
+ pattern: ".dsh/dsh-intelhub/workspaces.json"
2037
+ },
2038
+ {
2039
+ category: "dsh-registries",
2040
+ pattern: ".dsh/dsh-intelhub/registry.json"
2041
+ },
2042
+ {
2043
+ category: "dsh-registries",
2044
+ pattern: ".dsh/dsh-intelhub/schedules.json"
2045
+ },
2046
+ {
2047
+ category: "dsh-registries",
2048
+ pattern: ".dsh/dsh-zvec-kb/registry.json"
2049
+ },
2050
+ {
2051
+ category: "agents-skills",
2052
+ pattern: ".agents/skills/**"
2053
+ },
2054
+ {
2055
+ category: "agents-skills",
2056
+ pattern: ".agents/.skill-lock.json"
2057
+ },
2058
+ {
2059
+ category: "zcode-core",
2060
+ pattern: ".zcode/AGENTS.md"
2061
+ },
2062
+ {
2063
+ category: "zcode-core",
2064
+ pattern: ".zcode/cli/AGENTS.md"
2065
+ },
2066
+ {
2067
+ category: "zcode-core",
2068
+ pattern: ".zcode/cli/config.json"
2069
+ },
2070
+ {
2071
+ category: "zcode-core",
2072
+ pattern: ".zcode/cli/plugins/known_marketplaces.json"
2073
+ },
2074
+ {
2075
+ category: "zcode-core",
2076
+ pattern: ".zcode/v2/setting.json"
2077
+ },
2078
+ {
2079
+ category: "zcode-core",
2080
+ pattern: ".zcode/v2/config.json"
2081
+ },
2082
+ {
2083
+ category: "zcode-core",
2084
+ pattern: ".zcode/v2/provider_config.json"
2085
+ },
2086
+ {
2087
+ category: "zcode-secret",
2088
+ pattern: ".zcode/v2/credentials.json",
2089
+ secret: true
2090
+ }
2091
+ ];
2092
+ /** 收集/恢复的目录黑名单(防未来 scope 改动把可重植巨物卷进来) */
2093
+ const PRUNE_DIRS = /* @__PURE__ */ new Set([
2094
+ "node_modules",
2095
+ ".git",
2096
+ "hf-cache",
2097
+ "logs",
2098
+ "crash",
2099
+ "cache"
2100
+ ]);
2101
+ /** 相对路径合法性:正斜杠、无 .. 段、非绝对、无盘符(恢复路径的穿越硬闸) */
2102
+ function validateRelPath(p) {
2103
+ const norm = p.split("\\").join("/");
2104
+ if (norm.startsWith("/") || /^[a-zA-Z]:/.test(norm)) throw new Error(`非法备份路径(绝对路径):${p}`);
2105
+ const segs = norm.split("/").filter((s) => s !== "");
2106
+ if (segs.length === 0) throw new Error("非法备份路径(空路径)");
2107
+ if (segs.some((s) => s === "..")) throw new Error(`非法备份路径(含 .. 穿越):${p}`);
2108
+ return segs.join("/");
2109
+ }
2110
+ /** 段式 glob:* 段内通配;尾部 /** 吃整子树;其余字面 */
2111
+ function matchGlob(rel, pattern) {
2112
+ if (pattern.endsWith("/**")) {
2113
+ const prefix = pattern.slice(0, -3);
2114
+ return rel === prefix || rel.startsWith(prefix + "/");
2115
+ }
2116
+ const ps = pattern.split("/");
2117
+ const xs = rel.split("/");
2118
+ if (ps.length !== xs.length) return false;
2119
+ return ps.every((seg, i) => seg === "*" || seg === xs[i]);
2120
+ }
2121
+ function walkCollect(root, rel, out) {
2122
+ let entries;
2123
+ try {
2124
+ entries = readdirSync(join(root, rel));
2125
+ } catch {
2126
+ return;
2127
+ }
2128
+ for (const e of entries) {
2129
+ if (PRUNE_DIRS.has(e)) continue;
2130
+ const child = `${rel}/${e}`;
2131
+ let st;
2132
+ try {
2133
+ st = statSync(join(root, child));
2134
+ } catch {
2135
+ continue;
2136
+ }
2137
+ if (st.isDirectory()) walkCollect(root, child, out);
2138
+ else out.push(child);
2139
+ }
2140
+ }
2141
+ /** 收集备份清单:scope 命中且磁盘上真实存在的文件(缺失容错——没有就跳过,不算错) */
2142
+ function collectScopeFiles(root) {
2143
+ const userHome = root ?? homedir();
2144
+ const onDisk = /* @__PURE__ */ new Set();
2145
+ for (const rule of SCOPE) if (rule.pattern.endsWith("/**")) {
2146
+ const base = rule.pattern.slice(0, -3);
2147
+ if (existsSync(join(userHome, base))) {
2148
+ const out = [];
2149
+ walkCollect(userHome, base, out);
2150
+ for (const p of out) onDisk.add(p);
2151
+ }
2152
+ } else if (rule.pattern.includes("*")) {
2153
+ const segs = rule.pattern.split("/");
2154
+ const starIdx = segs.findIndex((seg) => seg.includes("*"));
2155
+ const prefix = segs.slice(0, starIdx).join("/");
2156
+ const suffix = segs.slice(starIdx + 1).join("/");
2157
+ let entries;
2158
+ try {
2159
+ entries = readdirSync(join(userHome, prefix));
2160
+ } catch {
2161
+ continue;
2162
+ }
2163
+ for (const e of entries) {
2164
+ const candidate = suffix === "" ? `${prefix}/${e}` : `${prefix}/${e}/${suffix}`;
2165
+ try {
2166
+ if (!statSync(join(userHome, candidate)).isFile()) continue;
2167
+ } catch {
2168
+ continue;
2169
+ }
2170
+ if (matchGlob(candidate, rule.pattern)) onDisk.add(candidate);
2171
+ }
2172
+ } else if (existsSync(join(userHome, rule.pattern))) onDisk.add(rule.pattern);
2173
+ const files = [];
2174
+ for (const rel of onDisk) {
2175
+ const rule = SCOPE.find((r) => matchGlob(rel, r.pattern));
2176
+ if (rule === void 0) continue;
2177
+ let bytes = 0;
2178
+ try {
2179
+ bytes = statSync(join(userHome, rel)).size;
2180
+ } catch {
2181
+ continue;
2182
+ }
2183
+ files.push({
2184
+ path: rel,
2185
+ category: rule.category,
2186
+ secret: rule.secret === true,
2187
+ bytes
2188
+ });
2189
+ }
2190
+ return files.sort((a, b) => a.path.localeCompare(b.path));
2191
+ }
2192
+ function deriveKey(passphrase, salt) {
2193
+ return scryptSync(passphrase, salt, 32, {
2194
+ N: SCRYPT_N,
2195
+ r: 8,
2196
+ maxmem: 268435456
2197
+ });
2198
+ }
2199
+ /** 打包 + 加密 → 单个 .dshenv 缓冲(口令永不落盘) */
2200
+ function packEncrypted(files, root, passphrase) {
2201
+ const entries = [];
2202
+ const blobs = [];
2203
+ let secretCount = 0;
2204
+ let secretHits = 0;
2205
+ for (const f of files) {
2206
+ const raw = readFileSync(join(root, f.path));
2207
+ const sha = createHash("sha256").update(raw).digest("hex");
2208
+ entries.push({
2209
+ path: f.path,
2210
+ bytes: raw.length,
2211
+ sha256: sha,
2212
+ category: f.category
2213
+ });
2214
+ if (f.secret) secretCount += 1;
2215
+ if (!f.secret && raw.length <= 2097152) try {
2216
+ secretHits += scanSecrets({ config: raw.toString("utf-8") }).length;
2217
+ } catch {}
2218
+ blobs.push(raw);
2219
+ }
2220
+ const manifest = {
2221
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2222
+ host: hostname(),
2223
+ secretCount,
2224
+ secretHits,
2225
+ files: entries
2226
+ };
2227
+ const manifestJson = Buffer.from(JSON.stringify(manifest), "utf-8");
2228
+ const body = Buffer.concat([
2229
+ Buffer.alloc(4),
2230
+ manifestJson,
2231
+ ...blobs
2232
+ ]);
2233
+ body.writeUInt32LE(manifestJson.length, 0);
2234
+ const salt = randomBytes(SALT_LEN);
2235
+ const iv = randomBytes(IV_LEN);
2236
+ const cipher = createCipheriv("aes-256-gcm", deriveKey(passphrase, salt), iv);
2237
+ const enc = Buffer.concat([cipher.update(body), cipher.final()]);
2238
+ const tag = cipher.getAuthTag();
2239
+ return {
2240
+ buf: Buffer.concat([
2241
+ MAGIC,
2242
+ salt,
2243
+ iv,
2244
+ tag,
2245
+ enc
2246
+ ]),
2247
+ manifest
2248
+ };
2249
+ }
2250
+ /** 解包:错口令 = GCM 认证失败 = 诚实报错,不吐半个字节 */
2251
+ function unpackEncrypted(buf, passphrase) {
2252
+ if (buf.length < MAGIC.length + SALT_LEN + IV_LEN + TAG_LEN + 4 || !buf.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error("不是 dsh-takeover 环境备份包(魔数不符)");
2253
+ let off = MAGIC.length;
2254
+ const salt = buf.subarray(off, off + SALT_LEN);
2255
+ off += SALT_LEN;
2256
+ const iv = buf.subarray(off, off + IV_LEN);
2257
+ off += IV_LEN;
2258
+ const tag = buf.subarray(off, off + TAG_LEN);
2259
+ off += TAG_LEN;
2260
+ let body;
2261
+ try {
2262
+ const decipher = createDecipheriv("aes-256-gcm", deriveKey(passphrase, salt), iv);
2263
+ decipher.setAuthTag(tag);
2264
+ body = Buffer.concat([decipher.update(buf.subarray(off)), decipher.final()]);
2265
+ } catch {
2266
+ throw new Error("解密失败:口令不对或包已损坏(GCM 认证未通过,未泄露任何内容)");
2267
+ }
2268
+ const manifestLen = body.readUInt32LE(0);
2269
+ return {
2270
+ ...JSON.parse(body.subarray(4, 4 + manifestLen).toString("utf-8")),
2271
+ body,
2272
+ manifestLen
2273
+ };
2274
+ }
2275
+ function blobAt(m, i) {
2276
+ let off = 4 + m.manifestLen;
2277
+ for (let k = 0; k < i; k++) off += m.files[k].bytes;
2278
+ return m.body.subarray(off, off + m.files[i].bytes);
2279
+ }
2280
+ function envBackupDir(dir) {
2281
+ return join(resolveHome(dir), "env-backup");
2282
+ }
2283
+ /** 列备份文件(只读目录,不解密) */
2284
+ function listBackups(dir) {
2285
+ const d = envBackupDir(dir);
2286
+ if (!existsSync(d)) return [];
2287
+ const rows = [];
2288
+ for (const f of readdirSync(d)) {
2289
+ if (!f.endsWith(".dshenv")) continue;
2290
+ try {
2291
+ rows.push({
2292
+ file: f,
2293
+ bytes: statSync(join(d, f)).size,
2294
+ at: f.slice(0, 13)
2295
+ });
2296
+ } catch {}
2297
+ }
2298
+ return rows.sort((a, b) => b.file.localeCompare(a.file));
2299
+ }
2300
+ /** 只保留最新 N 个备份(换机仓库不被备份史撑爆) */
2301
+ function pruneBackups(keep = 3, dir) {
2302
+ const d = envBackupDir(dir);
2303
+ if (!existsSync(d)) return 0;
2304
+ const rows = readdirSync(d).filter((f) => f.endsWith(".dshenv")).sort();
2305
+ let pruned = 0;
2306
+ while (rows.length > keep) {
2307
+ const victim = rows.shift();
2308
+ if (victim === void 0) break;
2309
+ try {
2310
+ rmSync(join(d, victim), { force: true });
2311
+ pruned += 1;
2312
+ } catch {
2313
+ break;
2314
+ }
2315
+ }
2316
+ return pruned;
2317
+ }
2318
+ /**
2319
+ * 读一份备份的加密清单:口令解密容器取 manifest,**不触碰任何 blob 内容**——
2320
+ * 配置轴出卡(handoff_env action=card / pushConfigCard)只把清单+指针写上卡,
2321
+ * 密文 blob 原样留在 env-backup/。错口令 = GCM 认证失败诚实报错(同解包口径)。
2322
+ */
2323
+ function readBackupManifest(file, passphrase, dir) {
2324
+ const name = basenameSafe(file);
2325
+ if (!name.endsWith(".dshenv")) throw new Error("备份文件名不合法(须为 .dshenv)");
2326
+ const buf = readFileSync(join(envBackupDir(dir), name));
2327
+ const m = unpackEncrypted(buf, passphrase);
2328
+ return {
2329
+ ok: true,
2330
+ file: name,
2331
+ bytes: buf.length,
2332
+ createdAt: m.createdAt,
2333
+ host: m.host,
2334
+ secretCount: m.secretCount,
2335
+ secretHits: m.secretHits,
2336
+ files: m.files.map((f) => ({ ...f }))
2337
+ };
2338
+ }
2339
+ /** 立即备份:收集 → 加密 → 落 env-backup/ → 修剪留 3 */
2340
+ function createBackup(passphrase, dir, root) {
2341
+ if (typeof passphrase !== "string" || passphrase.length < 8) throw new Error("口令至少 8 位(它保护凭据类文件,且永不落盘——忘了就救不回备份)");
2342
+ const userHome = root ?? homedir();
2343
+ const files = collectScopeFiles(root);
2344
+ if (files.length === 0) throw new Error("备份范围内没有找到任何文件(全家桶未安装?)");
2345
+ const { buf, manifest } = packEncrypted(files, userHome, passphrase);
2346
+ const d = envBackupDir(dir);
2347
+ mkdirSync(d, { recursive: true });
2348
+ const file = `${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:]/g, "").replace("T", "-")}-${manifest.host}.dshenv`;
2349
+ writeFileSync(join(d, file), buf);
2350
+ const pruned = pruneBackups(3, dir);
2351
+ return {
2352
+ ok: true,
2353
+ file,
2354
+ bytes: buf.length,
2355
+ files: manifest.files.length,
2356
+ secretCount: manifest.secretCount,
2357
+ secretHits: manifest.secretHits,
2358
+ detail: `已备份 ${manifest.files.length} 个文件(${(buf.length / 1024 / 1024).toFixed(1)} MB,含凭据类 ${manifest.secretCount} 个${manifest.secretHits > 0 ? `;配置扫描疑似密钥 ${manifest.secretHits} 处` : ""})——包已 AES-256-GCM 加密,口令未落盘${pruned > 0 ? `;已修剪 ${pruned} 个旧备份(保留 3 个)` : ""}`
2359
+ };
2360
+ }
2361
+ /** 还原预演:解密 + 与磁盘逐文件比对(三态:新建/覆盖/相同)——不写任何盘 */
2362
+ function dryRunRestore(file, passphrase, dir, root) {
2363
+ const name = basenameSafe(file);
2364
+ if (!name.endsWith(".dshenv")) throw new Error("备份文件名不合法(须为 .dshenv)");
2365
+ const m = unpackEncrypted(readFileSync(join(envBackupDir(dir), name)), passphrase);
2366
+ const userHome = root ?? homedir();
2367
+ const diff = m.files.map((f) => {
2368
+ const rel = validateRelPath(f.path);
2369
+ const abs = join(userHome, rel);
2370
+ if (!existsSync(abs)) return {
2371
+ path: rel,
2372
+ action: "create",
2373
+ category: f.category,
2374
+ packBytes: f.bytes
2375
+ };
2376
+ const disk = readFileSync(abs);
2377
+ return {
2378
+ path: rel,
2379
+ action: createHash("sha256").update(disk).digest("hex") === f.sha256 ? "same" : "overwrite",
2380
+ category: f.category,
2381
+ diskBytes: disk.length,
2382
+ packBytes: f.bytes
2383
+ };
2384
+ });
2385
+ return {
2386
+ ok: true,
2387
+ file: basenameSafe(file),
2388
+ createdAt: m.createdAt,
2389
+ host: m.host,
2390
+ secretCount: m.secretCount,
2391
+ diff,
2392
+ creates: diff.filter((r) => r.action === "create").length,
2393
+ overwrites: diff.filter((r) => r.action === "overwrite").length,
2394
+ same: diff.filter((r) => r.action === "same").length
2395
+ };
2396
+ }
2397
+ /** 取末段文件名(不含目录),仅拒绝空值;.dshenv 后缀在备份文件入口单独校验 */
2398
+ function basenameSafe(file) {
2399
+ const base = file.split("\\").join("/").split("/").pop() ?? "";
2400
+ if (base === "") throw new Error("备份文件名不合法");
2401
+ return base;
2402
+ }
2403
+ /** 确认还原:checkpoint 被覆盖原物 → 逐文件 tmp+rename 落盘 → 报告 */
2404
+ function applyRestore(file, passphrase, dir, root) {
2405
+ const name = basenameSafe(file);
2406
+ if (!name.endsWith(".dshenv")) throw new Error("备份文件名不合法(须为 .dshenv)");
2407
+ const m = unpackEncrypted(readFileSync(join(envBackupDir(dir), name)), passphrase);
2408
+ const userHome = root ?? homedir();
2409
+ const toWrite = [];
2410
+ for (const f of m.files) {
2411
+ const rel = validateRelPath(f.path);
2412
+ const abs = join(userHome, rel);
2413
+ if (!existsSync(abs)) {
2414
+ toWrite.push({ path: rel });
2415
+ continue;
2416
+ }
2417
+ if (createHash("sha256").update(readFileSync(abs)).digest("hex") !== f.sha256) toWrite.push({ path: rel });
2418
+ }
2419
+ if (toWrite.length === 0) return {
2420
+ ok: true,
2421
+ file: basenameSafe(file),
2422
+ applied: 0,
2423
+ checkpointDir: "",
2424
+ detail: "磁盘已是备份内容(全部相同),未动任何文件"
2425
+ };
2426
+ const ckptName = `restore-checkpoint-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:]/g, "").replace("T", "-")}`;
2427
+ const ckpt = join(envBackupDir(dir), ckptName);
2428
+ mkdirSync(ckpt, { recursive: true });
2429
+ const overwritten = [];
2430
+ for (const f of toWrite) {
2431
+ const abs = join(userHome, f.path);
2432
+ if (existsSync(abs)) {
2433
+ const cAbs = join(ckpt, f.path);
2434
+ mkdirSync(dirname(cAbs), { recursive: true });
2435
+ copyFileSync(abs, cAbs);
2436
+ overwritten.push(f.path);
2437
+ }
2438
+ }
2439
+ let applied = 0;
2440
+ for (const f of toWrite) {
2441
+ const abs = join(userHome, f.path);
2442
+ mkdirSync(dirname(abs), { recursive: true });
2443
+ const data = blobAt(m, m.files.findIndex((x) => x.path === f.path));
2444
+ const tmp = `${abs}.${process.pid}.tmp`;
2445
+ writeFileSync(tmp, data);
2446
+ renameSync(tmp, abs);
2447
+ applied += 1;
2448
+ }
2449
+ writeFileSync(join(ckpt, "checkpoint-manifest.json"), JSON.stringify({
2450
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2451
+ from: basenameSafe(file),
2452
+ overwritten
2453
+ }, null, 2), "utf-8");
2454
+ return {
2455
+ ok: true,
2456
+ file: basenameSafe(file),
2457
+ applied,
2458
+ checkpointDir: join("env-backup", ckptName),
2459
+ detail: `已还原 ${applied} 个文件(新建 ${toWrite.length - overwritten.length} / 覆盖 ${overwritten.length})。被覆盖原物已存 checkpoint(env-backup/${ckptName})——不满意可 rollback`
2460
+ };
2461
+ }
2462
+ /** 回滚:把 checkpoint 里的原物写回去 */
2463
+ function rollbackRestore(checkpointDir, dir, root) {
2464
+ const base = basenameSafe(checkpointDir);
2465
+ if (!base.startsWith("restore-checkpoint-")) throw new Error("回滚目标必须是 restore-checkpoint-* 目录");
2466
+ const ckpt = join(envBackupDir(dir), base);
2467
+ const manifestPath = join(ckpt, "checkpoint-manifest.json");
2468
+ if (!existsSync(manifestPath)) throw new Error("checkpoint 目录不完整(缺 checkpoint-manifest.json)");
2469
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
2470
+ const userHome = root ?? homedir();
2471
+ let restored = 0;
2472
+ for (const rel of manifest.overwritten) {
2473
+ validateRelPath(rel);
2474
+ const src = join(ckpt, rel);
2475
+ if (!existsSync(src)) continue;
2476
+ const abs = join(userHome, rel);
2477
+ mkdirSync(dirname(abs), { recursive: true });
2478
+ const tmp = `${abs}.${process.pid}.tmp`;
2479
+ copyFileSync(src, tmp);
2480
+ renameSync(tmp, abs);
2481
+ restored += 1;
2482
+ }
2483
+ return {
2484
+ ok: true,
2485
+ restored,
2486
+ detail: `已回滚 ${restored} 个文件到还原前状态(${base})`
2487
+ };
2488
+ }
2489
+ //#endregion
1148
2490
  //#region src/collect.ts
1149
2491
  const truncate$1 = (s, n) => {
1150
2492
  const str = typeof s === "string" ? s : String(s ?? "");
@@ -1428,6 +2770,83 @@ function renderCoverageLine(coverage) {
1428
2770
  if (c === void 0) return null;
1429
2771
  return `账本覆盖:${c.marked}/${c.statements} 条已标注状态(${c.unmarked} 条未标——取件方按 HISTORY_REPORTED 处理)`;
1430
2772
  }
2773
+ /** 基线采集单命令超时(毫秒):cwd 是外来输入,挂死的 git / 慢盘不能拖垮寄存主流程 */
2774
+ const GIT_BASELINE_TIMEOUT_MS = 15e3;
2775
+ /**
2776
+ * 基线采集:origin URL 与 HEAD commit。两条命令各自 try/catch + 15s 超时,
2777
+ * 失败/空输出如实 null,绝不 throw(基线拿不到不阻塞寄存)。
2778
+ * `-c core.fsmonitor=false` 与 core 同款纪律:卡片 cwd 是外来输入,仓库本地
2779
+ * fsmonitor 钩子是卡片作者可布置的命令执行面,基线采集一样不豁免。
2780
+ */
2781
+ function collectRepoBaseline(cwd) {
2782
+ const one = (args) => {
2783
+ try {
2784
+ const out = execFileSync("git", [
2785
+ "-C",
2786
+ cwd,
2787
+ "-c",
2788
+ "core.fsmonitor=false",
2789
+ ...args
2790
+ ], {
2791
+ encoding: "utf-8",
2792
+ timeout: GIT_BASELINE_TIMEOUT_MS,
2793
+ stdio: [
2794
+ "ignore",
2795
+ "pipe",
2796
+ "pipe"
2797
+ ]
2798
+ }).trim();
2799
+ return out === "" ? null : out;
2800
+ } catch {
2801
+ return null;
2802
+ }
2803
+ };
2804
+ return {
2805
+ remote: one([
2806
+ "remote",
2807
+ "get-url",
2808
+ "origin"
2809
+ ]),
2810
+ head: one(["rev-parse", "HEAD"])
2811
+ };
2812
+ }
2813
+ /** 从卡片 extras 防御式取基线(core parseCard 把顶层未知键收进 extras;外来卡/坏数据一律 undefined) */
2814
+ function baselineFromExtras(extras) {
2815
+ if (extras === null || typeof extras !== "object") return void 0;
2816
+ const b = extras.baseline;
2817
+ if (b === null || typeof b !== "object" || Array.isArray(b)) return void 0;
2818
+ const { remote, head, branch } = b;
2819
+ if (typeof remote !== "string" && remote !== null) return void 0;
2820
+ if (typeof head !== "string" && head !== null) return void 0;
2821
+ if (typeof branch !== "string") return void 0;
2822
+ return {
2823
+ remote,
2824
+ head,
2825
+ branch
2826
+ };
2827
+ }
2828
+ /** 从卡片 extras 防御式取四轴标记(闭集外/坏数据一律 undefined——外来卡无 axis 按旧卡处理) */
2829
+ function axisFromExtras(extras) {
2830
+ if (extras === null || typeof extras !== "object") return void 0;
2831
+ const a = extras["axis"];
2832
+ return a === "session" || a === "memory" || a === "config" ? a : void 0;
2833
+ }
2834
+ /** 恢复指引单值净化:控制字符压成空格 + 截断——多行/超长的外来值不打碎四步行结构 */
2835
+ function guidanceValue(v) {
2836
+ return v.replace(/[\r\n\u0000-\u001F]+/g, " ").slice(0, 300);
2837
+ }
2838
+ /** 「🧭 基线恢复指引」四步(clone → checkout → apply 补丁 → 跑测试)。
2839
+ * baseline 与 patch/testCommand 任一缺席都如实降级为说明行,不渲染空壳步骤。 */
2840
+ function renderBaselineGuidance(baseline, patchPath, testCommand) {
2841
+ const lines = ["🧭 基线恢复指引(extras.baseline):"];
2842
+ const remote = typeof baseline.remote === "string" && baseline.remote !== "" ? guidanceValue(baseline.remote) : null;
2843
+ lines.push(remote !== null ? ` 1. git clone ${remote} <目标目录>` : " 1. git clone:卡片未带 origin 远端(remote 缺省),先向寄存方要仓库地址");
2844
+ const head = typeof baseline.head === "string" && baseline.head !== "" ? guidanceValue(baseline.head) : null;
2845
+ lines.push(head !== null ? ` 2. git checkout ${head}(寄存时刻 HEAD)` : " 2. git checkout:卡片未带 HEAD(unborn 分支或采集失败),clone 后按分支看工作区");
2846
+ lines.push(patchPath !== void 0 ? ` 3. git apply ${patchPath}(复原未提交改动)` : " 3. git apply:本卡无随卡补丁,跳过");
2847
+ lines.push(typeof testCommand === "string" && testCommand !== "" ? ` 4. 跑测试(${testCommand})对比寄存基线,漂移即 MISMATCH 处理` : " 4. 跑测试:信封未带基线测试命令,按项目惯例自跑并记录");
2848
+ return lines;
2849
+ }
1431
2850
  /** 基线测试提示:源目录 package.json 有 test 脚本 → 信封记录命令(取件方先跑基线再对比,漂移即警告) */
1432
2851
  function testHint(cwd) {
1433
2852
  try {
@@ -1515,16 +2934,27 @@ function consumeEnvelope(id, dir) {
1515
2934
  function patchPath(id, dir) {
1516
2935
  return join(pendingDir(dir), `${id}.patch`);
1517
2936
  }
1518
- /** 取件时同步消费补丁:pending → archived(与 .md 同步搬),返回归档后路径供 apply 指引 */
2937
+ /**
2938
+ * 取件时同步消费补丁:pending → archived(与 .md 同步搬),返回归档后路径供 apply 指引。
2939
+ * 0.4.x 物质层补全:gzip 单块(<id>.patch.gz)与 gzip 分块(<id>.patch.NNN.gz)按
2940
+ * gzip magic(1f 8b)识别,多块按序重组解压后写归档 <id>.patch——apply 指引路径不变;
2941
+ * 解压失败时压缩块原样归档并回 warn(绝不静默丢弃材料)。旧纯文本 .patch 原样搬移。
2942
+ */
1519
2943
  function consumePatch(id, dir) {
1520
2944
  try {
1521
2945
  const src = patchPath(id, dir);
1522
- if (!existsSync(src)) return void 0;
1523
- const dest = join(archivedDir(dir), `${id}.patch`);
1524
- try {
1525
- renameSync(src, dest);
1526
- return dest;
1527
- } catch {}
2946
+ if (existsSync(src)) {
2947
+ const dest = join(archivedDir(dir), `${id}.patch`);
2948
+ try {
2949
+ renameSync(src, dest);
2950
+ return {
2951
+ path: dest,
2952
+ bytes: statSync(dest).size
2953
+ };
2954
+ } catch {}
2955
+ return;
2956
+ }
2957
+ return restoreGzipPatch(id, dir);
1528
2958
  } catch {}
1529
2959
  }
1530
2960
  /** 渲染:execute 返回规范值对象,render 包成中文 text block(导出仅为单测) */
@@ -1558,26 +2988,45 @@ function renderInbox(_args, value) {
1558
2988
  type: "text",
1559
2989
  text: "📭 收件箱为空(~/.handoff/pending/ 无待取件)"
1560
2990
  }];
1561
- const lines = cards.map((c, i) => `${i + 1}. ${c.id}|来自 ${c.from}|项目 ${c.project || "(无)"}|${c.pushed_at || "(无时间)"}`);
2991
+ const lines = cards.map((c, i) => `${i + 1}. ${c.id}|来自 ${c.from ?? "(未知来源)"}|项目 ${c.project || "(无)"}|${c.pushed_at || "(无时间)"}`);
1562
2992
  if (typeof v.skipped === "number" && v.skipped > 0) lines.push(`(另有 ${v.skipped} 张坏卡被跳过,详见宿主日志)`);
1563
2993
  return [{
1564
2994
  type: "text",
1565
2995
  text: `📬 待取件 ${cards.length} 张:\n${lines.join("\n")}\n\n取件:handoff_inbox({ action: "load", id: "<id>" })`
1566
2996
  }];
1567
2997
  }
2998
+ if (v.action === "history") {
2999
+ const cards = v.cards ?? [];
3000
+ if (cards.length === 0) return [{
3001
+ type: "text",
3002
+ text: "🗂️ 卡链历史为空(archived/ 无匹配卡——用 project / cwd 缩小或放宽过滤)"
3003
+ }];
3004
+ const lines = cards.map((c, i) => `${i + 1}. ${c.id}|${c.title || "(无标题)"}|${c.pushed_at || "(无时间)"}${typeof c.supersedes === "string" && c.supersedes !== "" ? `|接替 ${c.supersedes}` : ""}\n 停在:${c.stopped || "(无停点记录)"}`);
3005
+ return [{
3006
+ type: "text",
3007
+ text: `🕘 卡链历史(archived/ 匹配 ${typeof v.total === "number" ? v.total : cards.length} 张,时间正序取尾 ${cards.length} 张):\n${lines.join("\n")}`
3008
+ }];
3009
+ }
1568
3010
  const lines = [
1569
3011
  "📥 已取件(消费即弃,卡片已归档):",
1570
3012
  "",
1571
3013
  v.text ?? ""
1572
3014
  ];
3015
+ if (v.axis === "memory") lines.push("🧠 记忆已随卡注入,按建议加载段吸收");
1573
3016
  const patchPath = typeof v.patchPath === "string" ? v.patchPath : void 0;
1574
3017
  if (patchPath !== void 0) {
1575
3018
  const kb = typeof v.patchBytes === "number" ? `${Math.max(1, Math.round(v.patchBytes / 1024))} KB` : "? KB";
1576
3019
  lines.push(`🩹 补丁随卡归档(${kb} 未提交改动):先 \"git apply --check ${patchPath}\" 验证可干净应用,再 \"git apply ${patchPath}\" 复原;--check 失败(目标仓已前进)时用 \"git apply -3 ${patchPath}\" 三方合并尝试自助解决冲突`);
3020
+ if (v.patchFormat === "gzip" || v.patchFormat === "gzip-chunked") {
3021
+ const n = typeof v.patchChunks === "number" && v.patchChunks > 1 ? `${v.patchChunks} 块已按序重组,` : "";
3022
+ lines.push(`🧯 补丁以 gzip 压缩形态随卡(${n}取件时已自动解压为纯文本)——上方 git apply 指引针对解压后的归档补丁`);
3023
+ }
1577
3024
  }
3025
+ if (typeof v.patchWarn === "string" && v.patchWarn !== "") lines.push(`⚠️ 补丁还原降级:${v.patchWarn}`);
1578
3026
  if (typeof v.testCommand === "string" && v.testCommand !== "") lines.push(`🧪 基线测试提示(来自寄存方信封):接手后先跑 \"${v.testCommand}\" 对比寄存时状态,漂移即 MISMATCH 处理`);
1579
3027
  if (typeof v.supersedes === "string" && v.supersedes !== "") lines.push(`🔗 本卡接替前置卡 ${v.supersedes}(接力链)`);
1580
3028
  if (v.crossOS !== void 0) lines.push(`🖥️ 跨 OS 接手:源卡来自 ${v.crossOS.source},本机是 ${v.crossOS.local}——卡内路径需人工映射后才能执行`);
3029
+ if (v.baseline !== void 0) lines.push("", ...renderBaselineGuidance(v.baseline, patchPath, typeof v.testCommand === "string" ? v.testCommand : void 0));
1581
3030
  const coverageLine = renderCoverageLine(v.coverage);
1582
3031
  if (coverageLine !== null) lines.push("", coverageLine);
1583
3032
  if (typeof v.envelopeChars === "number" && v.envelopeChars >= 0) lines.push("", `机器信封已随卡归档(${v.envelopeChars} chars)`);
@@ -1646,6 +3095,8 @@ function factsToSections(facts, skipped, note) {
1646
3095
  * 外来段落净化(ANSI/控制字符剥离、伪标题解除形态)并限量(单段 128K 字符,
1647
3096
  * 标量 500)——共享收件箱的卡会被 inboxList/buildState 每次全量重读,不设上限
1648
3097
  * 就是把宿主内存/CPU 交给任意一次 push。
3098
+ * opts.extras 是插件侧内部出卡通道(pushMemoryCard 等程序化调用方覆盖 axis/payload
3099
+ * 立约缺省):不进 handoff_push 工具入参面,模型输入到不了 extras,密钥闸不旁路。
1649
3100
  */
1650
3101
  function pushHandoff(session, args, opts) {
1651
3102
  try {
@@ -1677,6 +3128,14 @@ function pushHandoff(session, args, opts) {
1677
3128
  return clean.length > 500 ? clean.slice(0, 500) : clean;
1678
3129
  };
1679
3130
  const patchBundle = collectPatch(cwd);
3131
+ const fullPatch = resolvePatchText(cwd, patchBundle);
3132
+ const inline = patchBundle !== null ? augmentPatchWithUntracked(cwd, fullPatch, patchBundle.untracked) : {
3133
+ patch: "",
3134
+ inlined: [],
3135
+ leftOut: []
3136
+ };
3137
+ const finalPatch = inline.patch;
3138
+ const finalPatchBytes = Buffer.byteLength(finalPatch, "utf-8");
1680
3139
  const sections = {
1681
3140
  goal: section(args.goal, fallback.goal),
1682
3141
  files: section(args.files, fallback.files),
@@ -1698,7 +3157,7 @@ ${honest}`;
1698
3157
  title: args.title,
1699
3158
  to: args.to,
1700
3159
  project: args.project
1701
- }), ...patchBundle !== null && patchBundle.patch !== "" ? scanSecrets({ patch: patchBundle.patch }) : []];
3160
+ }), ...finalPatch !== "" ? scanSecrets({ patch: finalPatch }) : []];
1702
3161
  if (secretHits.length > 0 && args.allowSecrets !== true) {
1703
3162
  const detail = secretHits.map((h) => `${h.rule}@${h.section}(${h.masked})`).join(";");
1704
3163
  recordLifecycleEvent({
@@ -1742,6 +3201,13 @@ ${honest}`;
1742
3201
  };
1743
3202
  }
1744
3203
  const coverage = coverageOfDone(sections.done);
3204
+ const gitSnapshot = collectGitSnapshot(cwd);
3205
+ const baselineSrc = collectRepoBaseline(cwd);
3206
+ const baseline = baselineSrc.remote !== null || baselineSrc.head !== null ? {
3207
+ remote: baselineSrc.remote,
3208
+ head: baselineSrc.head,
3209
+ branch: gitSnapshot.branch
3210
+ } : void 0;
1745
3211
  const card = {
1746
3212
  handoff: 1,
1747
3213
  id: generateId(),
@@ -1754,25 +3220,40 @@ ${honest}`;
1754
3220
  project: scalar(args.project, ""),
1755
3221
  cwd,
1756
3222
  pushed_at: localIso(/* @__PURE__ */ new Date()),
1757
- git: collectGitSnapshot(cwd),
3223
+ git: gitSnapshot,
1758
3224
  tasks: todoToTasks(facts).filter((t) => true),
1759
3225
  sections,
1760
3226
  extras: {
3227
+ axis: "session",
1761
3228
  coverage,
1762
- ...secretHits.length > 0 && args.allowSecrets === true ? { secretsBypass: secretHits.map((h) => `${h.rule}@${h.section}`) } : {}
3229
+ ...secretHits.length > 0 && args.allowSecrets === true ? { secretsBypass: secretHits.map((h) => `${h.rule}@${h.section}`) } : {},
3230
+ ...baseline !== void 0 ? { baseline } : {},
3231
+ ...typeof args.supersedes === "string" && args.supersedes.trim() !== "" ? { supersedes: args.supersedes.trim() } : {},
3232
+ ...opts?.extras ?? {}
1763
3233
  }
1764
3234
  };
1765
3235
  const path = writeCard(card, opts?.dir);
1766
3236
  const patchNotes = [];
1767
3237
  let patchInfo;
1768
- if (patchBundle !== null && patchBundle.patch !== "") try {
1769
- writeFileSync(join(pendingDir(opts?.dir), `${card.id}.patch`), patchBundle.patch, "utf-8");
1770
- patchInfo = {
1771
- bytes: patchBundle.bytes,
3238
+ if (finalPatch !== "") try {
3239
+ const packed = writePatchSidecar(card.id, finalPatch, opts?.dir);
3240
+ patchInfo = packed.format === "gzip-chunked" ? {
3241
+ bytes: finalPatchBytes,
3242
+ truncated: false,
3243
+ sidecar: true,
3244
+ patchFormat: "gzip",
3245
+ chunks: packed.chunks
3246
+ } : packed.format === "gzip" ? {
3247
+ bytes: finalPatchBytes,
3248
+ truncated: false,
3249
+ sidecar: true,
3250
+ patchFormat: "gzip"
3251
+ } : {
3252
+ bytes: finalPatchBytes,
1772
3253
  truncated: false,
1773
3254
  sidecar: true
1774
3255
  };
1775
- patchNotes.push(`补丁随卡(${Math.max(1, Math.round(patchBundle.bytes / 1024))} KB 未提交改动):取件时会给出 git apply 指引`);
3256
+ patchNotes.push(packed.format === "gzip-chunked" ? `未提交 diff 过大(${Math.round(finalPatchBytes / 1024)} KB),gzip 分 ${packed.chunks} 块随卡(.patch.001.gz…):取件侧自动重组解压后给出 git apply 指引` : packed.format === "gzip" ? `未提交 diff 过大(${Math.round(finalPatchBytes / 1024)} KB),gzip 压缩后单块随卡(${Math.max(1, Math.round(packed.writtenBytes / 1024))} KB .patch.gz):取件侧自动解压后给出 git apply 指引` : `补丁随卡(${Math.max(1, Math.round(finalPatchBytes / 1024))} KB 未提交改动):取件时会给出 git apply 指引`);
1776
3257
  } catch (e) {
1777
3258
  patchNotes.push(`补丁随卡失败(卡片本体已寄存):${readableError(e)}`);
1778
3259
  }
@@ -1782,11 +3263,14 @@ ${honest}`;
1782
3263
  truncated: true,
1783
3264
  sidecar: false
1784
3265
  };
1785
- patchNotes.push(`未提交 diff 过大(${Math.round(patchBundle.bytes / 1024)} KB 超上限)未随卡——请自行 git commit/push 携带`);
3266
+ patchNotes.push(`未提交 diff 过大(${Math.round(patchBundle.bytes / 1024)} KB 超上限)且自采失败未随卡——请自行 git commit/push 携带`);
1786
3267
  }
1787
3268
  if (patchBundle !== null && patchBundle.untracked.length > 0) {
1788
- const names = patchBundle.untracked.slice(0, 5).map((u) => u.file).join("、");
1789
- patchNotes.push(`未跟踪新文件 ${patchBundle.untracked.length} 个不随卡${patchBundle.untracked.length > 5 ? `(前 5:${names}…)` : `(${names})`}——请自行提交或携带`);
3269
+ const total = patchBundle.untracked.length;
3270
+ const names = inline.leftOut.slice(0, 5).map((u) => u.file).join("、");
3271
+ if (inline.leftOut.length === 0) patchNotes.push(`未跟踪新文件 ${total} 个已随补丁携带(单文件 <64KB 手拼新增 diff)——清单仍进机器信封备核`);
3272
+ else if (inline.inlined.length > 0) patchNotes.push(`未跟踪新文件 ${total} 个中 ${inline.inlined.length} 个小文件已随补丁携带,${inline.leftOut.length} 个超大/二进制不随卡${inline.leftOut.length > 5 ? `(前 5:${names}…)` : `(${names})`}——请自行提交或携带`);
3273
+ else patchNotes.push(`未跟踪新文件 ${total} 个不随卡${total > 5 ? `(前 5:${names}…)` : `(${names})`}——请自行提交或携带`);
1790
3274
  }
1791
3275
  let envelopeNote = "";
1792
3276
  try {
@@ -1862,6 +3346,45 @@ function inboxList(opts) {
1862
3346
  };
1863
3347
  }
1864
3348
  }
3349
+ /** 卡链历史单卡上限条数(与 core ARCHIVED_KEEP=50 同量级——再早的已被滚动归档淘汰) */
3350
+ const HISTORY_TAIL_MAX = 50;
3351
+ /** stopped 摘要截断(够辨认停点,不把卡正文搬进返回值) */
3352
+ const HISTORY_STOPPED_MAX = 120;
3353
+ /**
3354
+ * 卡链检索:按 project 或 cwd 查 archived/ 已归档卡(复用 core listArchivedReport,
3355
+ * 坏卡照旧跳过并忽略)。时间正序(pushed_at 字典序——同机卡共享时区口径),取尾
3356
+ * HISTORY_TAIL_MAX 条;两个过滤条件都给 = AND,都不给 = 全量回查。
3357
+ * supersedes 取自卡面 extras(寄存时随 extras 持久化——信封取件即弃,卡面才是持久通道)。
3358
+ */
3359
+ function inboxHistory(opts) {
3360
+ try {
3361
+ const project = typeof opts?.project === "string" ? opts.project.trim() : "";
3362
+ const cwd = typeof opts?.cwd === "string" ? opts.cwd.trim() : "";
3363
+ const rows = listArchivedReport(opts?.dir).cards.filter((c) => (project === "" || c.project === project) && (cwd === "" || c.cwd === cwd)).map((c) => {
3364
+ const sup = c.extras?.["supersedes"];
3365
+ return {
3366
+ id: c.id,
3367
+ title: c.from.title,
3368
+ pushed_at: c.pushed_at,
3369
+ stopped: stripControlChars(c.sections.stopped ?? "").slice(0, 120),
3370
+ ...typeof sup === "string" && sup !== "" ? { supersedes: sup } : {}
3371
+ };
3372
+ }).sort((a, b) => a.pushed_at.localeCompare(b.pushed_at));
3373
+ return {
3374
+ ok: true,
3375
+ action: "history",
3376
+ cards: rows.slice(-50),
3377
+ total: rows.length,
3378
+ ...project !== "" ? { project } : {},
3379
+ ...cwd !== "" ? { cwd } : {}
3380
+ };
3381
+ } catch (e) {
3382
+ return {
3383
+ ok: false,
3384
+ error: readableError(e)
3385
+ };
3386
+ }
3387
+ }
1865
3388
  /** 取件(消费即弃):pending → archived,附 verifyGit 的 MISMATCH/UNAVAILABLE 警告 */
1866
3389
  function inboxLoad(id, opts) {
1867
3390
  const trimmed = (id ?? "").trim();
@@ -1882,6 +3405,14 @@ function inboxLoad(id, opts) {
1882
3405
  const env = envelope?.data ?? {};
1883
3406
  const patchArchived = consumePatch(trimmed, opts?.dir);
1884
3407
  const coverage = coverageFromExtras(card.extras);
3408
+ const baseline = baselineFromExtras(card.extras);
3409
+ const axis = axisFromExtras(card.extras);
3410
+ if (axis === "memory") recordLifecycleEvent({
3411
+ stage: "read",
3412
+ reason: "memory-absorbed",
3413
+ target: card.id,
3414
+ detail: "memory 轴卡已取件,按建议加载段吸收"
3415
+ }, opts?.dir);
1885
3416
  const sigVerdict = envelope?.data !== void 0 ? verifyEnvelopeSig(envelope.data, opts?.dir, cardShaBeforeLoad) : "unsigned";
1886
3417
  if (sigVerdict === "tampered") recordLifecycleEvent({
1887
3418
  stage: "pickup",
@@ -1910,13 +3441,22 @@ function inboxLoad(id, opts) {
1910
3441
  target: card.id,
1911
3442
  detail: check.unavailable.slice(0, 120)
1912
3443
  }, opts?.dir);
3444
+ if (axis !== void 0) out.axis = axis;
1913
3445
  if (coverage !== void 0) out.coverage = coverage;
3446
+ if (baseline !== void 0) out.baseline = baseline;
1914
3447
  if (envelopeChars !== void 0) out.envelopeChars = envelopeChars;
1915
3448
  if (patchArchived !== void 0) {
1916
- out.patchPath = patchArchived;
1917
- try {
1918
- out.patchBytes = statSync(patchArchived).size;
1919
- } catch {}
3449
+ if (patchArchived.path !== void 0) {
3450
+ out.patchPath = patchArchived.path;
3451
+ try {
3452
+ out.patchBytes = patchArchived.bytes ?? statSync(patchArchived.path).size;
3453
+ } catch {}
3454
+ }
3455
+ if (patchArchived.format !== void 0) {
3456
+ out.patchFormat = patchArchived.format;
3457
+ out.patchChunks = patchArchived.chunks;
3458
+ }
3459
+ if (patchArchived.warn !== void 0) out.patchWarn = patchArchived.warn;
1920
3460
  }
1921
3461
  if (typeof env["test"] === "object" && env["test"] !== null) {
1922
3462
  const cmd = env["test"]["command"];
@@ -1999,7 +3539,7 @@ function safeUserQuestions(ctx) {
1999
3539
  function registerPushTool(ctx) {
2000
3540
  ctx.tools.register(defineTool({
2001
3541
  name: "handoff_push",
2002
- description: "把当前 DSH 会话寄存为一张 handoff: 1 交接卡片到共享收件箱 ~/.handoff/pending/(任何 agent 可取件)。六段文本(goal/files/done/remaining/stopped/warnings)+ 可选 suggested(建议加载段,非协议段)可选传入;留空段从会话事件流确定性兜底,不调 LLM。内置两道守门:密钥扫描(云厂商 key/私钥头/高熵赋值,命中拒绝并回喂理由,allowSecrets 留痕旁路)与空壳卡守门(六段全是兜底占位时拒绝,confirmSkeleton 旁路)。若源目录是 git 仓库且有未提交改动,同步落补丁 <id>.patch(取件方 git apply 可复原;diff 超上限整体拒带不截断)。另落机器信封 <id>.envelope.json(含源机标识/未跟踪清单/基线测试提示,协议扩展提案)并对 done 段产出四态覆盖率统计 coverage(只统计不强制)。返回 { ok, id, path, coverage, patch? } 规范值。",
3542
+ description: "把当前 DSH 会话寄存为一张 handoff: 1 交接卡片到共享收件箱 ~/.handoff/pending/(任何 agent 可取件)。六段文本(goal/files/done/remaining/stopped/warnings)+ 可选 suggested(建议加载段,非协议段)可选传入;留空段从会话事件流确定性兜底,不调 LLM。内置两道守门:密钥扫描(云厂商 key/私钥头/高熵赋值,命中拒绝并回喂理由,allowSecrets 留痕旁路;扫描覆盖补丁全文含未跟踪小文件的手拼新增 diff)与空壳卡守门(六段全是兜底占位时拒绝,confirmSkeleton 旁路)。若源目录是 git 仓库且有未提交改动,同步落补丁 <id>.patch(取件方 git apply 可复原;diff 超 512KB 先 gzip 压缩随卡、压缩后仍超则 480KB 分块 .patch.NNN.gz,取件侧按 gzip magic 自动解压重组;未跟踪清单里单文件 <64KB 的小文件手拼新增 diff 随补丁携带,超大/二进制仍只列清单)。另落机器信封 <id>.envelope.json(含源机标识/未跟踪清单/基线测试提示,协议扩展提案)并对 done 段产出四态覆盖率统计 coverage(只统计不强制)。卡片 extras 带四轴立约标记 axis(本工具恒为 session)与仓库基线 baseline(origin/HEAD/分支,拿不到如实缺省)。返回 { ok, id, path, coverage, patch? } 规范值。",
2003
3543
  parameters: {
2004
3544
  goal: {
2005
3545
  type: "string",
@@ -2106,17 +3646,29 @@ function registerPushTool(ctx) {
2106
3646
  function registerInboxTool(ctx) {
2107
3647
  ctx.tools.register(defineTool({
2108
3648
  name: "handoff_inbox",
2109
- description: "交接卡片收件箱:action=list 列 ~/.handoff/pending/ 待取件(id/来源/项目/时间);action=load + id 取件(消费即弃,卡片移到 archived/,随卡消费机器信封,附 git 核验 MISMATCH/UNAVAILABLE 警告与四态覆盖率)。返回 { ok, ... } 规范值。",
3649
+ description: "交接卡片收件箱:action=list 列 ~/.handoff/pending/ 待取件(id/来源/项目/时间);action=load + id 取件(消费即弃,卡片移到 archived/,随卡消费机器信封,附 git 核验 MISMATCH/UNAVAILABLE 警告与四态覆盖率;卡带仓库基线 baseline 时输出 clone → checkout → apply → 跑测试四步恢复指引;memory 轴卡输出「记忆已随卡注入」吸收提示);action=history 按 project 或 cwd 回查 archived/ 已归档卡(卡链检索:id/标题/寄存时刻/停点摘要/接替 supersedes,时间正序尾 50 条)。返回 { ok, ... } 规范值。",
2110
3650
  parameters: {
2111
3651
  action: {
2112
3652
  type: "string",
2113
3653
  required: true,
2114
- enum: ["list", "load"],
2115
- description: "list 列待取件;load 取件(消费即弃)"
3654
+ enum: [
3655
+ "list",
3656
+ "load",
3657
+ "history"
3658
+ ],
3659
+ description: "list 列待取件;load 取件(消费即弃);history 卡链检索(查 archived/)"
2116
3660
  },
2117
3661
  id: {
2118
3662
  type: "string",
2119
3663
  description: "load 必填:卡片 id"
3664
+ },
3665
+ project: {
3666
+ type: "string",
3667
+ description: "history:按项目名过滤 archived/ 卡(与 cwd 同时给则为 AND)"
3668
+ },
3669
+ cwd: {
3670
+ type: "string",
3671
+ description: "history:按工作目录过滤 archived/ 卡(与 project 同时给则为 AND)"
2120
3672
  }
2121
3673
  },
2122
3674
  output: {
@@ -2134,7 +3686,11 @@ function registerInboxTool(ctx) {
2134
3686
  },
2135
3687
  cards: {
2136
3688
  type: "json",
2137
- description: "list:待取件摘要数组"
3689
+ description: "list:待取件摘要数组;history:卡链历史数组 [{ id, title, pushed_at, stopped, supersedes? }]"
3690
+ },
3691
+ total: {
3692
+ type: "number",
3693
+ description: "history:过滤命中的总数(返回值为时间正序尾 50 条)"
2138
3694
  },
2139
3695
  id: {
2140
3696
  type: "string",
@@ -2156,58 +3712,702 @@ function registerInboxTool(ctx) {
2156
3712
  type: "json",
2157
3713
  description: "load:卡片 extras.coverage 的四态覆盖率统计(无则缺省)"
2158
3714
  },
3715
+ baseline: {
3716
+ type: "json",
3717
+ description: "load:卡片 extras.baseline 的仓库基线 { remote, head, branch }(无则缺省)"
3718
+ },
2159
3719
  envelopeChars: {
2160
3720
  type: "number",
2161
3721
  description: "load:随卡消费的机器信封 JSON 字符数(卡无信封时缺省)"
2162
3722
  },
2163
3723
  error: {
2164
- type: "json",
3724
+ type: "json",
3725
+ description: "失败原因"
3726
+ }
3727
+ }
3728
+ },
3729
+ render: renderInbox
3730
+ },
3731
+ async execute(args, exec) {
3732
+ if (args.action === "list") return inboxList();
3733
+ if (args.action === "history") return inboxHistory({
3734
+ project: args.project,
3735
+ cwd: args.cwd
3736
+ });
3737
+ if (args.action === "load") {
3738
+ const result = inboxLoad(args.id ?? "");
3739
+ if (result.ok) handoffHostNotice(safeUserQuestions(ctx), "load", result.id, exec, (m) => ctx.logger.info(m)).catch(() => {});
3740
+ return result;
3741
+ }
3742
+ return {
3743
+ ok: false,
3744
+ error: `未知 action:${String(args.action)}(支持 list / load / history)`
3745
+ };
3746
+ }
3747
+ }));
3748
+ }
3749
+ /**
3750
+ * 换机上下文同步(0.2.0):HANDOFF_HOME 的卡与签名密钥经 git 仓库端点跨机同步。
3751
+ * setup 启用(url 必填);now = pull→push 一步闭环;status 只读零网络。
3752
+ * 凭据永不入参不入盘(userinfo 形态 URL 直接拒收),凭据走系统 git。
3753
+ */
3754
+ function registerSyncTool(ctx) {
3755
+ ctx.tools.register(defineTool({
3756
+ name: "handoff_sync",
3757
+ description: "换机上下文同步:把 ~/.handoff 的待取件/已归档卡与签名密钥经用户配置的 git 仓库跨机同步(A 机寄存+now,B 机 now 后 /inbox 取件即接续)。action=setup 首次启用(url 必填,https / ssh / 本地裸仓库路径,拒绝 user:pass@ 形态);action=now 拉推一步到位;push / pull 单向;status 只读状态(零网络)。返回 { ok, ... } 规范值。",
3758
+ parameters: {
3759
+ action: {
3760
+ type: "string",
3761
+ required: true,
3762
+ enum: [
3763
+ "setup",
3764
+ "now",
3765
+ "push",
3766
+ "pull",
3767
+ "status"
3768
+ ],
3769
+ description: "setup 首次启用(url 必填);now 拉推闭环;push/pull 单向;status 只读"
3770
+ },
3771
+ url: {
3772
+ type: "string",
3773
+ description: "setup 必填:git 仓库地址(https://… / git@host:path / 本地裸仓库路径)"
3774
+ }
3775
+ },
3776
+ output: {
3777
+ schema: {
3778
+ type: "object",
3779
+ additionalProperties: true,
3780
+ properties: {
3781
+ ok: {
3782
+ type: "boolean",
3783
+ description: "操作是否成功"
3784
+ },
3785
+ action: {
3786
+ type: "string",
3787
+ description: "实际执行的动作"
3788
+ },
3789
+ detail: {
3790
+ type: "string",
3791
+ description: "动作后状态摘要"
3792
+ },
3793
+ ahead: {
3794
+ type: "number",
3795
+ description: "待推送提交数"
3796
+ },
3797
+ behind: {
3798
+ type: "number",
3799
+ description: "待拉取提交数"
3800
+ },
3801
+ status: {
3802
+ type: "json",
3803
+ description: "同步状态对象(每次返回都附最新)"
3804
+ },
3805
+ error: {
3806
+ type: "string",
3807
+ description: "失败原因"
3808
+ }
3809
+ }
3810
+ },
3811
+ render: renderSync
3812
+ },
3813
+ async execute(args) {
3814
+ const action = args.action ?? "status";
3815
+ try {
3816
+ if (action === "setup") return withSyncStatus(await syncSetup(args.url ?? ""));
3817
+ if (action === "now") return withSyncStatus(await syncNow());
3818
+ if (action === "push") return withSyncStatus(await syncPush());
3819
+ if (action === "pull") return withSyncStatus(await syncPull());
3820
+ if (action === "status") {
3821
+ const st = syncStatusOf();
3822
+ if (st === void 0) return {
3823
+ ok: false,
3824
+ action,
3825
+ error: "换机同步未启用:先执行 action=setup 并给 url"
3826
+ };
3827
+ return {
3828
+ ok: true,
3829
+ action,
3830
+ status: st,
3831
+ detail: syncStatusLine(st)
3832
+ };
3833
+ }
3834
+ return {
3835
+ ok: false,
3836
+ action,
3837
+ error: `未知 action:${action}(支持 setup / now / push / pull / status)`
3838
+ };
3839
+ } catch (e) {
3840
+ return {
3841
+ ok: false,
3842
+ action,
3843
+ error: e instanceof Error ? e.message : String(e)
3844
+ };
3845
+ }
3846
+ }
3847
+ }));
3848
+ }
3849
+ /** 动作结果附最新状态(工具返回面统一带 status,agent 一次调用看全貌) */
3850
+ function withSyncStatus(r) {
3851
+ const st = syncStatusOf();
3852
+ return {
3853
+ ok: r.ok,
3854
+ action: r.action,
3855
+ detail: r.detail ?? (st !== void 0 ? syncStatusLine(st) : void 0),
3856
+ ahead: r.ahead,
3857
+ behind: r.behind,
3858
+ error: r.error,
3859
+ ...st !== void 0 ? { status: st } : {}
3860
+ };
3861
+ }
3862
+ function renderSync(_args, value) {
3863
+ const v = value;
3864
+ const lines = [v.ok === true ? `[handoff_sync ${String(v.action)}] ok` : `[handoff_sync ${String(v.action)}] 失败`];
3865
+ if (typeof v.detail === "string" && v.detail !== "") lines.push(v.detail);
3866
+ if (typeof v.error === "string" && v.error !== "") lines.push(v.error);
3867
+ return [{
3868
+ type: "text",
3869
+ text: lines.join("\n")
3870
+ }];
3871
+ }
3872
+ /**
3873
+ * 配置轴出卡核心(handoff_env action=card / 换机面板共用):把最近一次备份的
3874
+ * 清单(files[{path,sha256,category}] + backupFile + bytes)写成 axis='config'
3875
+ * 载荷卡——writeCard + 机器信封签名全套纪律(cardSha256 进签名面,与 pushHandoff
3876
+ * 同款尽力签名:密钥缺席信封照落、落盘失败不回滚卡片)。密文 blob 仍在
3877
+ * env-backup/(卡只带清单+指针,随 HANDOFF_HOME 同步盘走);口令只用于读加密
3878
+ * 清单,永不进卡六段与 extras。args.file 缺省取最近一次备份(listBackups 首项)。
3879
+ */
3880
+ function pushConfigCard(args, opts) {
3881
+ try {
3882
+ const passphrase = typeof args.passphrase === "string" ? args.passphrase : "";
3883
+ if (passphrase.length < 8) return {
3884
+ ok: false,
3885
+ error: "口令至少 8 位(读加密清单必需;口令永不进卡,也永不落盘)"
3886
+ };
3887
+ const explicit = typeof args.file === "string" ? args.file.trim().split("\\").join("/").split("/").pop() ?? "" : "";
3888
+ const name = explicit !== "" ? explicit : listBackups(opts?.dir)[0]?.file ?? "";
3889
+ if (name === "") return {
3890
+ ok: false,
3891
+ error: "没有可出卡的环境备份:先 handoff_env action=backup 生成 .dshenv 加密包"
3892
+ };
3893
+ const m = readBackupManifest(name, passphrase, opts?.dir);
3894
+ const kb = (n) => n >= 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${n} B`;
3895
+ const truncated = [];
3896
+ const section = (v) => {
3897
+ const clean = defuseHeadingLines(stripControlChars(v));
3898
+ if (clean.length <= 131072) return clean;
3899
+ truncated.push(`「${clean.slice(0, 12)}…」段超 ${MAX_SECTION_CHARS} 字符已截断`);
3900
+ return `${clean.slice(0, MAX_SECTION_CHARS)}\n…(超长截断)`;
3901
+ };
3902
+ const list = m.files.map((f) => `- ${f.path}|${f.category}|sha256=${f.sha256}`).join("\n");
3903
+ const sections = {
3904
+ goal: section([`环境配置交接:把源机(${m.host})于 ${m.createdAt} 备份的 DSH 全家桶清单带给取件方。`, `密文包 ${m.file}(${kb(m.bytes)},含凭据类 ${m.secretCount} 个)留在 env-backup/ 随 HANDOFF_HOME 同步盘走,本卡只带清单与指针。`].join("\n")),
3905
+ files: section(`备份清单 ${m.files.length} 个文件(path|category|sha256 指纹,不含内容):\n${list}`),
3906
+ done: section(`(资料卡:无可蒸馏的完成项。清单共 ${m.files.length} 个文件、密文包 ${kb(m.bytes)},全部 HISTORY_REPORTED。)`),
3907
+ remaining: section([`取件方:确认 env-backup/${m.file} 已随同步盘到达本机 HANDOFF_HOME(缺失先 handoff_sync now 拉取)。`, `然后 handoff_env action=dry file=${m.file} passphrase=<你的口令,永不随卡> 预演三态 diff,确认后 action=apply confirm:true 落盘(不满意可 action=rollback 回滚)。`].join("\n")),
3908
+ stopped: section(`停在备份时刻(${m.createdAt},源机 ${m.host})。最安全的第一步:先 dry 预演核对三态 diff,再决定是否 apply。`),
3909
+ warnings: section(["清单只含路径/类别/内容指纹(sha256),不含文件内容;密文包本体仍在 env-backup/(AES-256-GCM,口令永不随卡)。", "全部清单按 HISTORY_REPORTED 处理:是备份时刻的快照,源机此后可能已改动。"].join("\n")),
3910
+ suggested: section([
3911
+ "恢复三步:",
3912
+ `1. handoff_env action=dry file=${m.file} passphrase=<口令>——先看 will-create/overwrite/same 三态 diff,不写盘`,
3913
+ `2. 确认无误后 handoff_env action=apply file=${m.file} passphrase=<口令> confirm:true——被覆盖原物先进 checkpoint`,
3914
+ "3. 不满意可 handoff_env action=rollback file=<restore-checkpoint-*> 回滚到还原前"
3915
+ ].join("\n"))
3916
+ };
3917
+ const secretHits = scanSecrets({
3918
+ ...sections,
3919
+ title: args.title
3920
+ });
3921
+ if (secretHits.length > 0) {
3922
+ const detail = secretHits.map((h) => `${h.rule}@${h.section}(${h.masked})`).join(";");
3923
+ return {
3924
+ ok: false,
3925
+ error: `密钥闸:发现 ${secretHits.length} 处疑似密钥——${detail}。清单不应含密钥值,请核对备份内容后重试。`
3926
+ };
3927
+ }
3928
+ const titleSrc = typeof args.title === "string" && args.title.trim() !== "" ? args.title.trim() : `环境配置备份 · ${m.file}`;
3929
+ const card = {
3930
+ handoff: 1,
3931
+ id: generateId(),
3932
+ from: {
3933
+ agent: "dsh",
3934
+ session: "",
3935
+ title: stripControlChars(titleSrc).slice(0, 500)
3936
+ },
3937
+ to: "any",
3938
+ project: "",
3939
+ cwd: "",
3940
+ pushed_at: localIso(/* @__PURE__ */ new Date()),
3941
+ git: {
3942
+ branch: "",
3943
+ changed: []
3944
+ },
3945
+ tasks: [],
3946
+ sections,
3947
+ extras: {
3948
+ axis: "config",
3949
+ payload: "manifest",
3950
+ coverage: coverageOfDone(sections.done),
3951
+ config: {
3952
+ backupFile: m.file,
3953
+ bytes: m.bytes,
3954
+ createdAt: m.createdAt,
3955
+ host: m.host,
3956
+ secretCount: m.secretCount,
3957
+ files: m.files.map((f) => ({
3958
+ path: f.path,
3959
+ sha256: f.sha256,
3960
+ category: f.category
3961
+ }))
3962
+ }
3963
+ }
3964
+ };
3965
+ const path = writeCard(card, opts?.dir);
3966
+ let envelopeNote = "";
3967
+ try {
3968
+ const key = loadOrCreateSigningKey(opts?.dir);
3969
+ const env = buildEnvelope(card, { cardSha256: fileSha256(join(pendingDir(opts?.dir), `${card.id}.md`)) });
3970
+ writeFileSync(envelopePath(card.id, opts?.dir), JSON.stringify(key === null ? env : signEnvelope(env, key)), "utf-8");
3971
+ } catch (e) {
3972
+ envelopeNote = `机器信封落盘失败(卡片本体已寄存):${readableError(e)}`;
3973
+ }
3974
+ const note = [...truncated, envelopeNote].filter(Boolean).join(";");
3975
+ return {
3976
+ ok: true,
3977
+ id: card.id,
3978
+ path,
3979
+ file: m.file,
3980
+ bytes: m.bytes,
3981
+ files: m.files.length,
3982
+ ...note !== "" ? { note } : {}
3983
+ };
3984
+ } catch (e) {
3985
+ return {
3986
+ ok: false,
3987
+ error: readableError(e)
3988
+ };
3989
+ }
3990
+ }
3991
+ /**
3992
+ * 环境备份/恢复(0.2.0 wave2):DSH 全家桶单文件加密备份 + 跨机还原。
3993
+ * apply 必须先 dry 预演再 confirm(覆盖性动作两步确认);口令永不落盘(工具入参会
3994
+ * 进会话转录,敏感场景用面板输入)。凭据类文件只存在于加密包内。
3995
+ * 配置轴转正(2026-11 裁决 D5):action=card 把最近备份清单写成 axis='config'
3996
+ * 载荷卡(清单+指针),密文 blob 仍在 env-backup/。
3997
+ */
3998
+ function registerEnvBackupTool(ctx) {
3999
+ ctx.tools.register(defineTool({
4000
+ name: "handoff_env",
4001
+ description: "环境备份/恢复:把 DSH 全家桶(settings/插件登记/会话库/用户 skills/工作区登记)打包成单个 AES-256-GCM 加密文件(口令 scrypt 派生,口令不落盘),随换机同步跨机;新机器 dry 预演(新建/覆盖/相同三态 diff)→ confirm 还原 → 可 rollback 回滚到还原前。凭据类文件(credentials/typesafe-key 等)只存在于加密包内。action=card 配置轴出卡:把最近一次备份的清单(files[{path,sha256,category}] + backupFile + bytes)写成 axis='config' 载荷卡寄存进共享收件箱(writeCard + 信封签名全套纪律;密文 blob 仍在 env-backup/,卡只带清单+指针,口令永不进卡)。返回 { ok, ... } 规范值。",
4002
+ parameters: {
4003
+ action: {
4004
+ type: "string",
4005
+ required: true,
4006
+ enum: [
4007
+ "backup",
4008
+ "dry",
4009
+ "apply",
4010
+ "rollback",
4011
+ "list",
4012
+ "card"
4013
+ ],
4014
+ description: "backup 打包加密备份(passphrase 必填 ≥8 位);dry 还原预演(file+passphrase);apply 确认还原(file+passphrase+confirm:true);rollback 回滚 checkpoint(file=checkpoint 目录名);list 列备份;card 备份清单出配置轴卡(passphrase 必填;file 缺省取最近一次)"
4015
+ },
4016
+ passphrase: {
4017
+ type: "string",
4018
+ description: "backup/dry/apply/card 必填:加密口令(≥8 位,永不落盘;注意会进本会话转录——敏感场景用面板输入)"
4019
+ },
4020
+ file: {
4021
+ type: "string",
4022
+ description: "dry/apply/card:备份文件名(card 缺省取最近一次);rollback:checkpoint 目录名(restore-checkpoint-*)"
4023
+ },
4024
+ confirm: {
4025
+ type: "boolean",
4026
+ description: "apply 必须显式 true(覆盖性动作的两步确认)"
4027
+ }
4028
+ },
4029
+ output: {
4030
+ schema: {
4031
+ type: "object",
4032
+ additionalProperties: true,
4033
+ properties: {
4034
+ ok: {
4035
+ type: "boolean",
4036
+ description: "操作是否成功"
4037
+ },
4038
+ action: {
4039
+ type: "string",
4040
+ description: "实际执行的动作"
4041
+ },
4042
+ detail: {
4043
+ type: "string",
4044
+ description: "结果摘要"
4045
+ },
4046
+ file: {
4047
+ type: "string",
4048
+ description: "备份文件名 / checkpoint 目录名"
4049
+ },
4050
+ id: {
4051
+ type: "string",
4052
+ description: "card:配置轴载荷卡 id"
4053
+ },
4054
+ path: {
4055
+ type: "string",
4056
+ description: "card:载荷卡落盘路径"
4057
+ },
4058
+ creates: {
4059
+ type: "number",
4060
+ description: "dry:将新建的文件数"
4061
+ },
4062
+ overwrites: {
4063
+ type: "number",
4064
+ description: "dry:将覆盖的文件数"
4065
+ },
4066
+ same: {
4067
+ type: "number",
4068
+ description: "dry:内容相同的文件数"
4069
+ },
4070
+ diff: {
4071
+ type: "json",
4072
+ description: "dry:三态 diff 明细"
4073
+ },
4074
+ applied: {
4075
+ type: "number",
4076
+ description: "apply:实际落盘文件数"
4077
+ },
4078
+ checkpointDir: {
4079
+ type: "string",
4080
+ description: "apply:checkpoint 目录(回滚入口)"
4081
+ },
4082
+ backups: {
4083
+ type: "json",
4084
+ description: "list:备份清单"
4085
+ },
4086
+ error: {
4087
+ type: "string",
2165
4088
  description: "失败原因"
2166
4089
  }
2167
4090
  }
2168
4091
  },
2169
- render: renderInbox
4092
+ render: renderEnv
2170
4093
  },
2171
- async execute(args, exec) {
2172
- if (args.action === "list") return inboxList();
2173
- if (args.action === "load") {
2174
- const result = inboxLoad(args.id ?? "");
2175
- if (result.ok) handoffHostNotice(safeUserQuestions(ctx), "load", result.id, exec, (m) => ctx.logger.info(m)).catch(() => {});
2176
- return result;
4094
+ async execute(args) {
4095
+ const action = args.action ?? "list";
4096
+ try {
4097
+ if (action === "backup") {
4098
+ const r = createBackup(args.passphrase ?? "");
4099
+ return {
4100
+ ok: true,
4101
+ action,
4102
+ file: r.file,
4103
+ detail: r.detail
4104
+ };
4105
+ }
4106
+ if (action === "dry") {
4107
+ const r = dryRunRestore(args.file ?? "", args.passphrase ?? "");
4108
+ return {
4109
+ ok: true,
4110
+ action,
4111
+ file: r.file,
4112
+ creates: r.creates,
4113
+ overwrites: r.overwrites,
4114
+ same: r.same,
4115
+ diff: r.diff,
4116
+ detail: `预演:将新建 ${r.creates} / 覆盖 ${r.overwrites} / 相同 ${r.same}(备份来自 ${r.host},${r.createdAt.slice(0, 16)})——确认无误后带 confirm:true 执行 apply`
4117
+ };
4118
+ }
4119
+ if (action === "apply") {
4120
+ if (args.confirm !== true) return {
4121
+ ok: false,
4122
+ action,
4123
+ error: "还原是覆盖性动作:先 dry 预演,确认 diff 后带 confirm:true 再执行"
4124
+ };
4125
+ const r = applyRestore(args.file ?? "", args.passphrase ?? "");
4126
+ return {
4127
+ ok: true,
4128
+ action,
4129
+ file: r.file,
4130
+ applied: r.applied,
4131
+ checkpointDir: r.checkpointDir,
4132
+ detail: r.detail
4133
+ };
4134
+ }
4135
+ if (action === "rollback") return {
4136
+ ok: true,
4137
+ action,
4138
+ detail: rollbackRestore(args.file ?? "").detail
4139
+ };
4140
+ if (action === "list") return {
4141
+ ok: true,
4142
+ action,
4143
+ backups: listBackups(),
4144
+ detail: `共 ${listBackups().length} 个备份(保留最新 3 个)`
4145
+ };
4146
+ if (action === "card") {
4147
+ const r = pushConfigCard({
4148
+ file: args.file,
4149
+ passphrase: args.passphrase
4150
+ });
4151
+ if (!r.ok) return {
4152
+ ok: false,
4153
+ action,
4154
+ error: r.error
4155
+ };
4156
+ return {
4157
+ ok: true,
4158
+ action,
4159
+ id: r.id,
4160
+ path: r.path,
4161
+ file: r.file,
4162
+ detail: `配置轴载荷卡已寄存:${r.id}(清单 ${r.files} 个文件 + 密文包指针 ${r.file},${Math.max(1, Math.round(r.bytes / 1024))} KB——密文 blob 仍在 env-backup/,口令未进卡)${r.note !== void 0 ? `;${r.note}` : ""}`
4163
+ };
4164
+ }
4165
+ return {
4166
+ ok: false,
4167
+ action,
4168
+ error: `未知 action:${action}(支持 backup / dry / apply / rollback / list / card)`
4169
+ };
4170
+ } catch (e) {
4171
+ return {
4172
+ ok: false,
4173
+ action,
4174
+ error: e instanceof Error ? e.message : String(e)
4175
+ };
2177
4176
  }
2178
- return {
2179
- ok: false,
2180
- error: `未知 action:${String(args.action)}(支持 list / load)`
2181
- };
2182
4177
  }
2183
4178
  }));
2184
4179
  }
4180
+ function renderEnv(_args, value) {
4181
+ const v = value;
4182
+ const lines = [v.ok === true ? `[handoff_env ${String(v.action)}] ok` : `[handoff_env ${String(v.action)}] 失败`];
4183
+ if (typeof v.detail === "string" && v.detail !== "") lines.push(v.detail);
4184
+ if (typeof v.error === "string" && v.error !== "") lines.push(v.error);
4185
+ return [{
4186
+ type: "text",
4187
+ text: lines.join("\n")
4188
+ }];
4189
+ }
2185
4190
  //#endregion
2186
- //#region src/foreign.ts
2187
- /** 面向用户的九家提供方名 → readers 适配器名(claude 是 claude-code 的别名) */
2188
- const FOREIGN_PROVIDERS = [
2189
- "claude",
2190
- "codex",
2191
- "opencode",
2192
- "zcode",
2193
- "pi",
2194
- "workbuddy",
2195
- "cursor",
2196
- "grok",
2197
- "gemini"
4191
+ //#region src/providers.ts
4192
+ const PROVIDERS = [
4193
+ {
4194
+ name: "claude",
4195
+ adapter: "claude-code",
4196
+ label: "Claude Code",
4197
+ outboundEligible: true,
4198
+ icon: {
4199
+ kind: "mark",
4200
+ mark: {
4201
+ viewBox: "0 0 24 24",
4202
+ tile: "#D97757",
4203
+ paths: [{
4204
+ d: "m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",
4205
+ fill: "#fff"
4206
+ }]
4207
+ }
4208
+ },
4209
+ resume: {
4210
+ id: "resume-claude",
4211
+ product: "Claude Code",
4212
+ description: "把一条 Claude Code 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4213
+ recoveryBoundary: "读取器全量读取本地记录(含被替换/放弃分支的条目,thinking 块以 [thinking] 标记保留);不复活 CLI、不回放工具调用。"
4214
+ }
4215
+ },
4216
+ {
4217
+ name: "codex",
4218
+ adapter: "codex",
4219
+ label: "Codex CLI",
4220
+ outboundEligible: true,
4221
+ icon: {
4222
+ kind: "mark",
4223
+ mark: {
4224
+ viewBox: "0 0 24 24",
4225
+ tile: "#0f0f0f",
4226
+ paths: [{
4227
+ d: "M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z",
4228
+ fill: "#fff"
4229
+ }]
4230
+ }
4231
+ },
4232
+ resume: {
4233
+ id: "resume-codex",
4234
+ product: "Codex",
4235
+ description: "把一条 Codex 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4236
+ recoveryBoundary: "读取器排除 Codex 的 system / developer / reasoning / world-state / 跨 agent 记录。"
4237
+ }
4238
+ },
4239
+ {
4240
+ name: "opencode",
4241
+ adapter: "opencode",
4242
+ label: "OpenCode",
4243
+ outboundEligible: true,
4244
+ icon: {
4245
+ kind: "mark",
4246
+ mark: {
4247
+ viewBox: "0 0 512 512",
4248
+ tile: "#131010",
4249
+ paths: [{
4250
+ d: "M384 416H128V96H384V416ZM320 160H192V352H320V160Z",
4251
+ fill: "#fff"
4252
+ }]
4253
+ }
4254
+ },
4255
+ resume: {
4256
+ id: "resume-opencode",
4257
+ product: "OpenCode",
4258
+ description: "把一条 OpenCode 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id 或标题关键词。",
4259
+ recoveryBoundary: "读取器只读 OpenCode 本地存储的会话记录;不复活进程、不回放存储的调用。"
4260
+ }
4261
+ },
4262
+ {
4263
+ name: "zcode",
4264
+ adapter: "zcode",
4265
+ label: "ZCode",
4266
+ outboundEligible: true,
4267
+ icon: {
4268
+ kind: "mark",
4269
+ mark: {
4270
+ viewBox: "0 0 30 30",
4271
+ tile: "#2D2D2D",
4272
+ paths: [
4273
+ {
4274
+ d: "M15.47,7.1l-1.3,1.85c-0.2,0.29-0.54,0.47-0.9,0.47h-7.1V7.09C6.16,7.1,15.47,7.1,15.47,7.1z",
4275
+ fill: "#fff"
4276
+ },
4277
+ {
4278
+ d: "M24.3 7.1L13.14 22.91L5.7 22.91L16.86 7.1Z",
4279
+ fill: "#fff"
4280
+ },
4281
+ {
4282
+ d: "M14.53,22.91l1.31-1.86c0.2-0.29,0.54-0.47,0.9-0.47h7.09v2.33H14.53z",
4283
+ fill: "#fff"
4284
+ }
4285
+ ]
4286
+ }
4287
+ },
4288
+ resume: {
4289
+ id: "resume-zcode",
4290
+ product: "ZCode",
4291
+ description: "把一条 ZCode 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id(支持短前缀)或标题关键词。",
4292
+ recoveryBoundary: "读取器只读 ZCode 的 sqlite 库(readonly、随开随关,需 Node ≥22);不回放调用、不复活 CLI;压缩段只是摘要标记,仍在库里的旧行保留。"
4293
+ }
4294
+ },
4295
+ {
4296
+ name: "pi",
4297
+ adapter: "pi",
4298
+ label: "Pi",
4299
+ outboundEligible: true,
4300
+ icon: {
4301
+ kind: "mark",
4302
+ mark: {
4303
+ viewBox: "0 0 800 800",
4304
+ tile: "#27272a",
4305
+ paths: [
4306
+ {
4307
+ d: "M165.29 165.29H517.36V400H400V282.65H165.29Z",
4308
+ fill: "#F09082"
4309
+ },
4310
+ {
4311
+ d: "M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z",
4312
+ fill: "#4D9ABF"
4313
+ },
4314
+ {
4315
+ d: "M517.36 400H634.72V634.72H517.36Z",
4316
+ fill: "#F1BE58"
4317
+ }
4318
+ ]
4319
+ }
4320
+ },
4321
+ resume: {
4322
+ id: "resume-pi",
4323
+ product: "Pi",
4324
+ description: "把一条 Pi 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、JSONL 路径或标题关键词。",
4325
+ recoveryBoundary: "读取器只沿 Pi 当前活跃叶子读取,排除 thinking、hooks、system 消息与扩展注入的记录。"
4326
+ }
4327
+ },
4328
+ {
4329
+ name: "workbuddy",
4330
+ adapter: "workbuddy",
4331
+ label: "WorkBuddy",
4332
+ outboundEligible: true,
4333
+ icon: {
4334
+ kind: "full",
4335
+ svg: "<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g clip-path=\"url(#clip0_542_3370)\">\n<rect width=\"40\" height=\"40\" rx=\"20\" fill=\"url(#paint0_linear_542_3370)\"/>\n<g filter=\"url(#filter0_f_542_3370)\">\n<circle cx=\"31.3411\" cy=\"43.6183\" r=\"12.8704\" fill=\"#FFE355\" fill-opacity=\"0.49\" style=\"fill:#FFE355;fill:color(display-p3 1.0000 0.8891 0.3348);fill-opacity:0.49;\"/>\n</g>\n<path d=\"M28.5931 3.12762C28.9853 2.77585 29.0091 2.76226 29.2968 2.74499C29.7628 2.71096 30.1894 2.93488 30.916 3.59634C32.6132 5.13875 34.9769 8.30904 36.4462 11.0168L37.0138 12.0682L37.8156 12.4668C38.5896 12.8579 39.8593 13.6593 40.3898 14.0895C40.6297 14.2878 40.6638 14.2925 40.9133 14.1954C42.0388 13.7572 43.6506 14.3382 45.0727 15.7024C46.3529 16.9294 47.5794 19.026 48.0491 20.7757C48.1177 21.0574 48.2087 21.6628 48.2419 22.1134C48.349 23.6964 47.8414 24.9608 46.8637 25.5331C46.664 25.6484 46.6505 25.6795 46.6561 26.1774C46.7011 28.5481 46.0621 30.9144 44.7785 33.2221C43.3293 35.8133 40.7489 38.4945 37.2566 41.0199C35.3813 42.3846 30.9445 44.9701 28.9382 45.8778C24.1324 48.0414 20.2794 48.8709 16.9329 48.4609C14.9368 48.219 12.6769 47.44 11.34 46.5355C10.9885 46.2925 10.9325 46.2774 10.6637 46.3543C9.2327 46.7651 7.35867 45.9207 5.76659 44.1535C5.13165 43.4471 4.1065 41.7127 3.77404 40.7843C3.0054 38.6118 3.15852 36.6506 4.18236 35.4799C4.44671 35.1785 4.45511 35.1658 4.39735 34.6589C4.30195 33.8289 4.25837 32.6008 4.30192 31.808L4.33666 31.0674L3.22502 29.101C1.5033 26.0375 0.409325 23.4645 -0.012563 21.4992C-0.235219 20.4218 -0.221193 19.9436 0.0522186 19.5899C0.21871 19.3763 0.764928 19.1545 1.42322 19.0329C3.08041 18.742 6.69466 19.0056 10.7155 19.7155L11.1329 19.788L12.0511 18.976C13.5747 17.6264 14.587 16.8696 16.4531 15.706C18.3981 14.4891 20.5929 13.4877 23.0648 12.695L23.8577 12.4414L24.2939 11.2964C25.8547 7.17615 27.4533 4.13844 28.5931 3.12762ZM15.5182 24.243C13.7542 25.2615 12.8718 25.7706 12.2236 26.3413C9.59893 28.6526 8.61811 32.3134 9.73545 35.6274C10.0114 36.4457 10.5201 37.3283 11.5386 39.0923C12.5571 40.8564 13.0671 41.7383 13.6378 42.3864C15.9491 45.0112 19.6103 45.9929 22.9243 44.8755C23.7426 44.5995 24.6249 44.0899 26.3888 43.0714L36.5375 37.2121C38.3016 36.1936 39.184 35.6845 39.8321 35.1137C42.4568 32.8024 43.4373 29.1409 42.3198 25.8269C42.0438 25.0086 41.5342 24.1264 40.5158 22.3624C39.4973 20.5983 38.9882 19.7159 38.4175 19.0678C36.1062 16.4432 32.4454 15.4622 29.1314 16.5796C28.3131 16.8556 27.431 17.3651 25.6669 18.3836L15.5182 24.243Z\" fill=\"url(#paint1_linear_542_3370)\"/>\n<rect x=\"16.4961\" y=\"31.3344\" width=\"4.00904\" height=\"8.32646\" rx=\"2.00452\" transform=\"rotate(-30 16.4961 31.3344)\" fill=\"white\" style=\"fill:white;fill-opacity:1;\"/>\n<rect x=\"27.3125\" y=\"25.0894\" width=\"4.00904\" height=\"8.32646\" rx=\"2.00452\" transform=\"rotate(-30 27.3125 25.0894)\" fill=\"white\" style=\"fill:white;fill-opacity:1;\"/>\n</g>\n<defs>\n<filter id=\"filter0_f_542_3370\" x=\"7.47033\" y=\"19.7475\" width=\"47.742\" height=\"47.7416\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feGaussianBlur stdDeviation=\"5.50019\" result=\"effect1_foregroundBlur_542_3370\"/>\n</filter>\n<linearGradient id=\"paint0_linear_542_3370\" x1=\"20\" y1=\"0\" x2=\"20\" y2=\"40\" gradientUnits=\"userSpaceOnUse\">\n<stop stop-color=\"#0EC8A9\" style=\"stop-color:#0EC8A9;stop-color:color(display-p3 0.0565 0.7837 0.6625);stop-opacity:1;\"/>\n<stop offset=\"1\" stop-color=\"#01C886\" style=\"stop-color:#01C886;stop-color:color(display-p3 0.0021 0.7858 0.5246);stop-opacity:1;\"/>\n</linearGradient>\n<linearGradient id=\"paint1_linear_542_3370\" x1=\"14.6642\" y1=\"11.0783\" x2=\"33.3762\" y2=\"43.4885\" gradientUnits=\"userSpaceOnUse\">\n<stop stop-color=\"white\" stop-opacity=\"0.8\" style=\"stop-color:white;stop-opacity:0.8;\"/>\n<stop offset=\"0.437689\" stop-color=\"white\" style=\"stop-color:white;stop-opacity:1;\"/>\n</linearGradient>\n<clipPath id=\"clip0_542_3370\">\n<rect width=\"40\" height=\"40\" rx=\"20\" fill=\"white\" style=\"fill:white;fill-opacity:1;\"/>\n</clipPath>\n</defs>\n</svg>"
4336
+ },
4337
+ resume: {
4338
+ id: "resume-workbuddy",
4339
+ product: "WorkBuddy",
4340
+ description: "把一条 WorkBuddy 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4341
+ recoveryBoundary: "读取器只导入受支持的 WorkBuddy transcript / 存储记录,永不回放存储的调用。"
4342
+ }
4343
+ },
4344
+ {
4345
+ name: "cursor",
4346
+ adapter: "cursor",
4347
+ label: "Cursor",
4348
+ outboundEligible: true,
4349
+ icon: {
4350
+ kind: "mark",
4351
+ mark: {
4352
+ viewBox: "0 0 24 24",
4353
+ tile: "#1a1a1a",
4354
+ paths: [{
4355
+ d: "M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23",
4356
+ fill: "#fff"
4357
+ }]
4358
+ }
4359
+ },
4360
+ resume: {
4361
+ id: "resume-cursor",
4362
+ product: "Cursor",
4363
+ description: "把一条 Cursor 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4364
+ recoveryBoundary: "读取器只导入受支持的 Cursor transcript / store 记录,永不回放存储的调用。"
4365
+ }
4366
+ },
4367
+ {
4368
+ name: "grok",
4369
+ adapter: "grok",
4370
+ label: "Grok CLI",
4371
+ outboundEligible: true,
4372
+ icon: {
4373
+ kind: "mark",
4374
+ mark: {
4375
+ viewBox: "0 0 256 246",
4376
+ tile: "#111111",
4377
+ paths: [{
4378
+ d: "M63.8307299,56.8426545 C91.2989169,29.362978 131.465298,21.9776085 165.542128,34.9726459 L167.855892,35.8902557 C175.501463,38.7335174 182.164746,42.7796414 187.363427,46.5414469 L158.506099,59.882758 C131.637157,48.5973415 100.857492,56.2740175 82.0711204,75.0832754 C56.6656274,100.496833 51.5320736,144.566967 81.3069473,173.04336 L-1.42108547e-14,245.764227 C4.29613789,239.840925 9.45698399,234.190695 14.7493257,228.586421 L20.5645541,222.456072 L23.1726477,219.681571 C38.703877,203.027306 51.983468,185.912092 43.6693415,162.973056 L42.9033683,160.992465 C28.3109637,125.495663 36.8086459,83.896995 63.8307299,56.8426545 Z M220.785826,35.2560304 L256,0 L245.871984,14.068605 C224.778304,43.78544 215.415895,62.4930162 224.761831,102.727911 L224.69655,102.66263 C231.927394,133.390838 224.194269,167.466048 199.225391,192.464878 C167.746834,224.002573 117.372848,231.022982 75.8893821,202.634909 L104.811992,189.227703 C131.287711,199.638122 160.254097,195.066907 181.071863,174.224565 C201.890397,153.381454 206.565294,123.024196 196.101882,97.7634735 C194.113496,92.9733751 188.149873,91.7706665 183.977257,94.8542395 L98.8698734,157.755289 L220.785826,35.1466653 L220.785826,35.2560304 Z",
4379
+ fill: "#fff"
4380
+ }]
4381
+ }
4382
+ },
4383
+ resume: {
4384
+ id: "resume-grok",
4385
+ product: "Grok",
4386
+ description: "把一条 Grok 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、会话目录、记录路径或标题关键词。",
4387
+ recoveryBoundary: "读取器只用 Grok 可见的 updates.jsonl 流,永不读 chat_history.jsonl 原始模型上下文。"
4388
+ }
4389
+ },
4390
+ {
4391
+ name: "gemini",
4392
+ adapter: "gemini",
4393
+ label: "Gemini CLI",
4394
+ outboundEligible: false,
4395
+ icon: { kind: "none" },
4396
+ resume: {
4397
+ id: "resume-gemini",
4398
+ product: "Gemini CLI",
4399
+ description: "把一条 Gemini CLI 会话拉进当前会话,生成六段交接卡接手工作;本地记录是新旧双格式 JSONL/JSON,子代理会话单独存盘,可附会话 id(记录路径)、记录路径或标题关键词。",
4400
+ recoveryBoundary: "读取器只读 Gemini CLI 本地 chats/ 下的会话文件(JSONL 新格式 / 整块 JSON 旧格式,含子代理会话目录);info/error/warning CLI 提示与斜杠命令行不进对话流;只读不写、不复活 Gemini CLI 进程。"
4401
+ }
4402
+ }
2198
4403
  ];
2199
- /** 面向用户的 provider 名 → readers 适配器名(设置卡支持矩阵同用) */
2200
- const PROVIDER_TO_ADAPTER = {
2201
- claude: "claude-code",
2202
- codex: "codex",
2203
- opencode: "opencode",
2204
- zcode: "zcode",
2205
- pi: "pi",
2206
- workbuddy: "workbuddy",
2207
- cursor: "cursor",
2208
- grok: "grok",
2209
- gemini: "gemini"
2210
- };
4404
+ PROVIDERS.map((p) => p.name);
4405
+ //#endregion
4406
+ //#region src/foreign.ts
4407
+ /** 面向用户的九家提供方名(providers.ts 注册表派生,顺序即注册表声明序) */
4408
+ const FOREIGN_PROVIDERS = PROVIDERS.map((p) => p.name);
4409
+ /** 面向用户的 provider 名 → readers 适配器名(注册表派生;claude 是 claude-code 的别名,设置卡支持矩阵同用) */
4410
+ const PROVIDER_TO_ADAPTER = Object.fromEntries(PROVIDERS.map((p) => [p.name, p.adapter]));
2211
4411
  let realReaders = null;
2212
4412
  /** 默认读取层:惰性加载 readers(模块级环境变量覆盖在首次调用前生效) */
2213
4413
  function defaultForeignReaders() {
@@ -2773,13 +4973,19 @@ function registerForeignTool(ctx, env) {
2773
4973
  * 扫描只读、清单确定(已知路径逐个 existsSync,绝不猜测目录内容);
2774
4974
  * 出卡走 pushHandoff(密钥闸/空壳守门/覆盖率/机器信封整套纪律原样生效),
2775
4975
  * 卡的「建议加载」段装记忆正文,取件方按卡吸收进自己的记忆文件。
4976
+ * 四轴 IR 立约:本轴卡 extras.axis='memory'、extras.payload='files'(原文件正文随卡)。
4977
+ * 记忆库掏取契约:二进制/引擎型记忆库(hippo 等)走通用 MEMORY_STORES 注册表——
4978
+ * 每项 { id, label, entriesFile?, guidance },条目 JSONL(每行 {text, tags?})在场就
4979
+ * 实际读条目(64KB 截断口径内)进「建议加载」段,不在场退回该 store 的指引文案;
4980
+ * 不再有任何 store 的代码特例(hippo 只是注册表里的一项)。
2776
4981
  * @module dsh-takeover/memory
2777
4982
  */
2778
4983
  /** 已知记忆文件清单(用户级全局 + 项目级常用约定文件)。
2779
4984
  * 只列有公开文档惯例的路径;没列入的家不是不支持,是路径无公开惯例。
2780
4985
  * hippo-db 特殊行:dsh-hippo(伴侣智能体长期记忆插件)的记忆库——v0.1.9 起是
2781
4986
  * <数据目录>/memories/ 的 zvec 原生目录(proxima 向量索引 + rocksdb FTS),二进制
2782
- * 不随卡直带,存在性照报(UI 提示装了记忆库),出卡时正文替换为 export/import 指引。 */
4987
+ * 不随卡直带,存在性照报(UI 提示装了记忆库);出卡正文走 MEMORY_STORES 通用
4988
+ * 掏取契约(条目 JSONL 在场掏条目、缺席退回指引),这里只管「探测到没有」。 */
2783
4989
  const MEMORY_SOURCES = [
2784
4990
  {
2785
4991
  key: "claude-user",
@@ -2859,6 +5065,66 @@ const SUGGESTED_TOTAL_MAX = 12e4;
2859
5065
  function toIso(ms) {
2860
5066
  return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : "";
2861
5067
  }
5068
+ /** 记忆库 store 注册表(hippo 在册——不再是代码特例;新库 = 在这里加一项) */
5069
+ const MEMORY_STORES = [{
5070
+ id: "hippo-db",
5071
+ label: "dsh-hippo 记忆库",
5072
+ entriesFile: (row) => join(dirname(row.path), "hippo-memory.jsonl"),
5073
+ guidance: [
5074
+ "(dsh-hippo 记忆库是 zvec 原生目录(proxima 向量索引 + rocksdb FTS),二进制不随卡直带。官方互通通路走 hippo CLI 的 JSONL 导出/导入:",
5075
+ "- 源机:`hippo export -f jsonl -o hippo-memory.jsonl`(在 hippo 数据目录下执行)导出全库 JSONL 快照到约定路径 <数据目录>/hippo-memory.jsonl——重新出卡即自动按条目随卡携带;",
5076
+ "- 取件方若装了 dsh-hippo:`hippo import hippo-memory.jsonl` 幂等导入(自动重嵌入;重复条目强化合并、不覆盖已有记录)。",
5077
+ "本卡先携带来源清单与交接意图,JSONL 快照按上面两步补齐。)"
5078
+ ].join("\n")
5079
+ }];
5080
+ /**
5081
+ * 读一份条目 JSONL(纯读;64KB 截断口径由渲染侧执行,这里只解析):
5082
+ * 每行一个 JSON 对象取 text 与 tags(非字符串 tags 项丢弃),坏行/空行/缺 text 行跳过。
5083
+ * 文件不在场 / 读失败 / 零有效条目 → undefined(调用方退回指引文案)。
5084
+ */
5085
+ function readStoreEntries(file) {
5086
+ let raw;
5087
+ try {
5088
+ raw = readFileSync(file, "utf-8");
5089
+ } catch {
5090
+ return;
5091
+ }
5092
+ const entries = [];
5093
+ for (const line of raw.split(/\r?\n/)) {
5094
+ const t = line.trim();
5095
+ if (t === "") continue;
5096
+ try {
5097
+ const o = JSON.parse(t);
5098
+ const text = typeof o["text"] === "string" ? o["text"] : "";
5099
+ if (text === "") continue;
5100
+ const tags = Array.isArray(o["tags"]) ? o["tags"].filter((x) => typeof x === "string") : void 0;
5101
+ entries.push(tags !== void 0 && tags.length > 0 ? {
5102
+ text,
5103
+ tags
5104
+ } : { text });
5105
+ } catch {}
5106
+ }
5107
+ if (entries.length === 0) return void 0;
5108
+ return {
5109
+ entries,
5110
+ rawChars: raw.length
5111
+ };
5112
+ }
5113
+ /** 条目 → 卡正文 bullet 列表(64KB 截断口径与文件正文一致,超限截断并注明) */
5114
+ function renderStoreEntries(entries) {
5115
+ const body = entries.map((e) => `- ${e.text}${e.tags !== void 0 ? ` [${e.tags.join(", ")}]` : ""}`).join("\n");
5116
+ if (body.length <= FILE_BODY_MAX) return body;
5117
+ return `${body.slice(0, FILE_BODY_MAX)}\n…(超 ${FILE_BODY_MAX} 字符截断,完整条目见条目 JSONL)`;
5118
+ }
5119
+ /** store 行的卡正文:条目 JSONL 在场就掏条目,不在场退回该 store 的指引文案 */
5120
+ function storeBody(row, store) {
5121
+ const file = store.entriesFile?.(row);
5122
+ if (file !== void 0) {
5123
+ const read = readStoreEntries(file);
5124
+ if (read !== void 0) return renderStoreEntries(read.entries);
5125
+ }
5126
+ return store.guidance;
5127
+ }
2862
5128
  /** 扫描已知记忆文件(纯读;deps.home/cwd 可注入,缺省真实 home / 无项目级) */
2863
5129
  function scanMemorySources(deps) {
2864
5130
  const home = deps?.home ?? homedir();
@@ -2934,17 +5200,12 @@ function scanMemorySources(deps) {
2934
5200
  }
2935
5201
  return rows;
2936
5202
  }
2937
- /** 读一份记忆文件进卡正文(超限截断并注明;读失败如实写 UNAVAILABLE。
2938
- * hippo 记忆库是二进制例外:不读内容,写 export/import 互通指引——
2939
- * dsh-hippo 官方通路(v0.1.9+ zvec 引擎):`hippo export -f jsonl` 导出 JSONL
2940
- * 快照,取件方 `hippo import <file>` 幂等合并导入) */
2941
- function fileBody(row) {
2942
- if (row.key === "hippo-db") return [
2943
- "(dsh-hippo 记忆库是 zvec 原生目录(proxima 向量索引 + rocksdb FTS),二进制不随卡直带。官方互通通路走 hippo CLI 的 JSONL 导出/导入:",
2944
- "- 源机:`hippo export -f jsonl -o hippo-memory.jsonl` 导出全库 JSONL 快照,把该 JSONL 随同步盘带给对方(或作为记忆来源重新出卡);",
2945
- "- 取件方若装了 dsh-hippo:`hippo import hippo-memory.jsonl` 幂等导入(自动重嵌入;重复条目强化合并、不覆盖已有记录)。",
2946
- "本卡先携带来源清单与交接意图,JSONL 快照按上面两步补齐。)"
2947
- ].join("\n");
5203
+ /** 读一份记忆文件进卡正文(超限截断并注明;读失败如实写 UNAVAILABLE)。
5204
+ * store 在册的行(hippo 等引擎型记忆库)不走文件读取,改走通用掏取契约:
5205
+ * 条目 JSONL 在场掏条目、不在场退回该 store 的指引文案(MEMORY_STORES 查表)。 */
5206
+ function fileBody(row, stores) {
5207
+ const store = stores.find((s) => s.id === row.key);
5208
+ if (store !== void 0) return storeBody(row, store);
2948
5209
  try {
2949
5210
  const text = readFileSync(row.path, "utf-8");
2950
5211
  if (text.length <= FILE_BODY_MAX) return text;
@@ -2953,13 +5214,25 @@ function fileBody(row) {
2953
5214
  return `(读取失败,UNAVAILABLE:${e instanceof Error ? e.message : String(e)})`;
2954
5215
  }
2955
5216
  }
2956
- /** 记忆卡六段组装(全部 History_Reported 口径:记忆是历史快照不是当下事实) */
2957
- function memorySections(picks, meta) {
5217
+ /** 记忆卡六段组装(全部 History_Reported 口径:记忆是历史快照不是当下事实)。
5218
+ * deps.stores 可注入 store 注册表(缺省 MEMORY_STORES)——测试用假 store 验证
5219
+ * 条目 JSONL 在场/缺席两态,不必真装 hippo。 */
5220
+ function memorySections(picks, meta, deps) {
5221
+ const stores = deps?.stores ?? MEMORY_STORES;
2958
5222
  const kb = (n) => n >= 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${n} B`;
2959
5223
  const list = picks.map((r) => `- [${r.agent}] ${r.path}(${kb(r.bytes)}${r.mtime !== "" ? `,${r.mtime.slice(0, 10)}` : ""})`).join("\n");
2960
- const bodies = picks.map((r) => `## ${r.path}\n\n${fileBody(r)}`).join("\n\n");
5224
+ const bodies = picks.map((r) => `## ${r.path}\n\n${fileBody(r, stores)}`).join("\n\n");
2961
5225
  const total = picks.reduce((s, r) => {
2962
- if (r.key === "hippo-db") return s + r.bytes;
5226
+ const store = stores.find((x) => x.id === r.key);
5227
+ if (store !== void 0) {
5228
+ const ef = store.entriesFile?.(r);
5229
+ if (ef === void 0) return s;
5230
+ try {
5231
+ return s + statSync(ef).size;
5232
+ } catch {
5233
+ return s;
5234
+ }
5235
+ }
2963
5236
  try {
2964
5237
  return s + readFileSync(r.path, "utf-8").length;
2965
5238
  } catch {
@@ -3011,7 +5284,13 @@ function pushMemoryCard(args, deps) {
3011
5284
  title,
3012
5285
  to: target,
3013
5286
  project: ""
3014
- }, { dir: deps?.dir });
5287
+ }, {
5288
+ dir: deps?.dir,
5289
+ extras: {
5290
+ axis: "memory",
5291
+ payload: "files"
5292
+ }
5293
+ });
3015
5294
  if (!result.ok) return result;
3016
5295
  return {
3017
5296
  ok: true,
@@ -3140,6 +5419,15 @@ function renderMemory(_args, value) {
3140
5419
  }
3141
5420
  //#endregion
3142
5421
  //#region src/browser-view.ts
5422
+ /**
5423
+ * 外部会话浏览器的纯函数层(client 面板与服务端共享语义,零 DOM / 零 cordis 依赖):
5424
+ * - 会话行的即时过滤(标题 / 目录 / id 子串,大小写不敏感);
5425
+ * - 相对时间(行内扫读友好:刚刚 / N分钟前 / …;超 30 天回退绝对日期);
5426
+ * - 接管 / 寄存指令生成——/resume-* 的引用解析在首个换行前截断(skills/resume 同轮修订),
5427
+ * 所以寄存指令是「引用行 + 指示行」两行式:一行塞尾巴会把尾巴吞进引用导致解析失败。
5428
+ * 不碰会话内容本体——浏览是只读的,接管与蒸馏都在会话里由模型完成。
5429
+ * @module dsh-takeover/browser-view
5430
+ */
3143
5431
  /** 接管指令:/resume-* 的引用 = slash token 之后首个换行前的文本(skills/resume 纪律) */
3144
5432
  function takeoverCommand(provider, id) {
3145
5433
  return `/resume-${provider} ${id}`;
@@ -3148,56 +5436,20 @@ function takeoverCommand(provider, id) {
3148
5436
  function depositTail(lang) {
3149
5437
  return lang === "en" ? "When the takeover is done, deposit the six-section handoff card into the shared inbox." : "接管完成后,把六段交接卡寄存进共享收件箱。";
3150
5438
  }
3151
- /** 交接出去的接收方(any = 不指定,任何 agent 可取) */
3152
- const OUTBOUND_TARGETS = [
3153
- "any",
3154
- "claude",
3155
- "codex",
3156
- "opencode",
3157
- "zcode",
3158
- "pi",
3159
- "workbuddy",
3160
- "cursor",
3161
- "grok"
3162
- ];
3163
- /** 接收方展示名(与 PROVIDER_LABEL 同风格;any 是协议词不是 provider) */
5439
+ /** 交接出去的接收方(any = 不指定,任何 agent 可取)——providers.ts 注册表派生:
5440
+ * outboundEligible 的 provider 依声明序排在 any 之后。交接目标与读取器两轴独立
5441
+ * (gemini 是读取器但不进交接目标,注册表显式声明)。 */
5442
+ const OUTBOUND_TARGETS = ["any", ...PROVIDERS.filter((p) => p.outboundEligible).map((p) => p.name)];
5443
+ /** 接收方展示名(注册表 label 派生,与 PROVIDER_LABEL 同源;any 是协议词不是 provider) */
3164
5444
  const OUTBOUND_LABELS = {
3165
5445
  any: {
3166
5446
  zh: "任意 agent",
3167
5447
  en: "Any agent"
3168
5448
  },
3169
- claude: {
3170
- zh: "Claude Code",
3171
- en: "Claude Code"
3172
- },
3173
- codex: {
3174
- zh: "Codex CLI",
3175
- en: "Codex CLI"
3176
- },
3177
- opencode: {
3178
- zh: "OpenCode",
3179
- en: "OpenCode"
3180
- },
3181
- zcode: {
3182
- zh: "ZCode",
3183
- en: "ZCode"
3184
- },
3185
- pi: {
3186
- zh: "Pi",
3187
- en: "Pi"
3188
- },
3189
- workbuddy: {
3190
- zh: "WorkBuddy",
3191
- en: "WorkBuddy"
3192
- },
3193
- cursor: {
3194
- zh: "Cursor",
3195
- en: "Cursor"
3196
- },
3197
- grok: {
3198
- zh: "Grok CLI",
3199
- en: "Grok CLI"
3200
- }
5449
+ ...Object.fromEntries(PROVIDERS.filter((p) => p.outboundEligible).map((p) => [p.name, {
5450
+ zh: p.label,
5451
+ en: p.label
5452
+ }]))
3201
5453
  };
3202
5454
  /** 投进当前会话的寄存指令(queue 模式打给本会话的 agent)。
3203
5455
  * 两行式(同 depositCommand 的换行纪律):引用/命令行在前,指示行在后;
@@ -3290,6 +5542,8 @@ async function appendRelayRecord(session, kind, data) {
3290
5542
  * 任何一步失败都回规范值 / 降级值,绝不抛出。
3291
5543
  * @module dsh-takeover/settings
3292
5544
  */
5545
+ /** 补丁 gzip 分块文件名尾段(<id>.patch.NNN.gz);单块 <id>.patch.gz 无序号段不匹配 */
5546
+ const PATCH_CHUNK_GZ_RE = /\.patch\.(\d+)\.gz$/;
3293
5547
  /** config.json 路径(HANDOFF_HOME 优先,否则 ~/.handoff) */
3294
5548
  function switchesPath(dir) {
3295
5549
  return join(resolveHome(dir), "config.json");
@@ -3420,8 +5674,9 @@ function buildState(readers, dir) {
3420
5674
  if (pdExists) {
3421
5675
  const supersedesByOwner = /* @__PURE__ */ new Map();
3422
5676
  for (const f of readdirSync(pd)) {
3423
- if (!f.endsWith(".envelope.json") && !f.endsWith(".patch")) continue;
3424
- const ownerId = f.endsWith(".envelope.json") ? f.slice(0, -14) : f.slice(0, -6);
5677
+ const gzChunk = PATCH_CHUNK_GZ_RE.exec(f);
5678
+ if (!f.endsWith(".envelope.json") && !f.endsWith(".patch") && !f.endsWith(".patch.gz") && gzChunk === null) continue;
5679
+ const ownerId = f.endsWith(".envelope.json") ? f.slice(0, -14) : gzChunk !== null ? f.slice(0, f.length - gzChunk[0].length) : f.endsWith(".patch.gz") ? f.slice(0, -9) : f.slice(0, -6);
3425
5680
  const hasMd = existsSync(join(pd, `${ownerId}.md`));
3426
5681
  try {
3427
5682
  if (!hasMd) {
@@ -3483,6 +5738,8 @@ function buildState(readers, dir) {
3483
5738
  persisted: persistedAll.slice(-50),
3484
5739
  persistedTotal: persistedAll.length
3485
5740
  } : void 0;
5741
+ const syncStatus = syncStatusOf(dir);
5742
+ const backups = listBackups(dir);
3486
5743
  return {
3487
5744
  home: resolveHome(dir),
3488
5745
  pending,
@@ -3493,7 +5750,9 @@ function buildState(readers, dir) {
3493
5750
  coverage,
3494
5751
  envelopeChars,
3495
5752
  providers,
3496
- ...rejections !== void 0 ? { rejections } : {}
5753
+ ...rejections !== void 0 ? { rejections } : {},
5754
+ ...syncStatus !== void 0 ? { syncStatus } : {},
5755
+ ...backups.length > 0 ? { envBackup: { backups } } : {}
3497
5756
  };
3498
5757
  }
3499
5758
  /** archived 计数:按目录枚举+stat,不逐卡解析(此前为个数全量 parse 每张归档卡) */
@@ -3549,7 +5808,8 @@ function dismissPending(id, dir) {
3549
5808
  for (const ext of [
3550
5809
  ".md",
3551
5810
  ".envelope.json",
3552
- ".patch"
5811
+ ".patch",
5812
+ ".patch.gz"
3553
5813
  ]) {
3554
5814
  const src = join(home, "pending", safe + ext);
3555
5815
  if (!existsSync(src)) continue;
@@ -3563,6 +5823,22 @@ function dismissPending(id, dir) {
3563
5823
  };
3564
5824
  }
3565
5825
  }
5826
+ try {
5827
+ const prefix = `${safe}.patch.`;
5828
+ for (const f of readdirSync(join(home, "pending"))) {
5829
+ if (!f.startsWith(prefix) || !f.endsWith(".gz")) continue;
5830
+ if (!/^\d+\.gz$/.test(f.slice(prefix.length))) continue;
5831
+ try {
5832
+ renameSync(join(home, "pending", f), join(home, "archived", f));
5833
+ moved += 1;
5834
+ } catch (e) {
5835
+ return {
5836
+ ok: false,
5837
+ error: `移动失败:${f}(${e instanceof Error ? e.message : String(e)})`
5838
+ };
5839
+ }
5840
+ }
5841
+ } catch {}
3566
5842
  if (moved === 0) return {
3567
5843
  ok: false,
3568
5844
  error: `pending 里没有这张卡:${safe}(可能已被取件)`
@@ -4160,7 +6436,186 @@ function registerTakeoverRoutes(ctx, opts) {
4160
6436
  });
4161
6437
  return;
4162
6438
  }
4163
- sendJson(response, 404, { error: `未知路由:/dsh-takeover/${sub}(支持 state / sessions / session-preview / takeover / provider / clear-archived / dismiss-pending)` });
6439
+ if (sub === "sync") {
6440
+ if (request.method !== "POST") {
6441
+ response.writeHead(405, { allow: "POST" });
6442
+ response.end();
6443
+ return;
6444
+ }
6445
+ if (!sameOrigin(request)) {
6446
+ sendJson(response, 403, { error: "仅接受同源请求" });
6447
+ return;
6448
+ }
6449
+ readJsonBody(request).then((body) => {
6450
+ providerWriteQueue = providerWriteQueue.then(async () => {
6451
+ try {
6452
+ const action = String(body["action"] ?? "now");
6453
+ const url = typeof body["url"] === "string" ? body["url"] : "";
6454
+ let r;
6455
+ if (action === "setup") r = await syncSetup(url);
6456
+ else if (action === "now") r = await syncNow();
6457
+ else if (action === "push") r = await syncPush();
6458
+ else if (action === "pull") r = await syncPull();
6459
+ else r = {
6460
+ ok: false,
6461
+ action,
6462
+ error: `未知动作:${action}(支持 setup / now / push / pull)`
6463
+ };
6464
+ sendJson(response, r.ok ? 200 : 400, {
6465
+ ...r,
6466
+ state: await stateBody()
6467
+ });
6468
+ } catch (e) {
6469
+ sendJson(response, 500, {
6470
+ ok: false,
6471
+ error: e instanceof Error ? e.message : String(e)
6472
+ });
6473
+ }
6474
+ });
6475
+ }, (error) => {
6476
+ sendJson(response, 400, {
6477
+ ok: false,
6478
+ error: error instanceof Error ? error.message : String(error)
6479
+ });
6480
+ });
6481
+ return;
6482
+ }
6483
+ if (sub === "env-backup") {
6484
+ if (request.method !== "POST") {
6485
+ response.writeHead(405, { allow: "POST" });
6486
+ response.end();
6487
+ return;
6488
+ }
6489
+ if (!sameOrigin(request)) {
6490
+ sendJson(response, 403, { error: "仅接受同源请求" });
6491
+ return;
6492
+ }
6493
+ readJsonBody(request).then((body) => {
6494
+ providerWriteQueue = providerWriteQueue.then(async () => {
6495
+ const action = String(body["action"] ?? "");
6496
+ const passphrase = String(body["passphrase"] ?? "");
6497
+ const file = String(body["file"] ?? "");
6498
+ try {
6499
+ if (action === "create") sendJson(response, 200, {
6500
+ ...createBackup(passphrase),
6501
+ backups: listBackups()
6502
+ });
6503
+ else if (action === "dry") sendJson(response, 200, dryRunRestore(file, passphrase));
6504
+ else if (action === "apply") {
6505
+ if (body["confirm"] !== true) {
6506
+ sendJson(response, 400, {
6507
+ ok: false,
6508
+ error: "还原是覆盖性动作:先 dry 预演,再带 confirm:true 落盘"
6509
+ });
6510
+ return;
6511
+ }
6512
+ sendJson(response, 200, {
6513
+ ...applyRestore(file, passphrase),
6514
+ backups: listBackups()
6515
+ });
6516
+ } else if (action === "rollback") sendJson(response, 200, rollbackRestore(file));
6517
+ else if (action === "list") sendJson(response, 200, {
6518
+ ok: true,
6519
+ backups: listBackups()
6520
+ });
6521
+ else sendJson(response, 400, {
6522
+ ok: false,
6523
+ error: `未知动作:${action}(支持 create / dry / apply / rollback / list)`
6524
+ });
6525
+ } catch (e) {
6526
+ sendJson(response, 400, {
6527
+ ok: false,
6528
+ error: e instanceof Error ? e.message : String(e)
6529
+ });
6530
+ }
6531
+ });
6532
+ }, (error) => {
6533
+ sendJson(response, 400, {
6534
+ ok: false,
6535
+ error: error instanceof Error ? error.message : String(error)
6536
+ });
6537
+ });
6538
+ return;
6539
+ }
6540
+ if (sub === "lifeboat") {
6541
+ if (request.method !== "POST") {
6542
+ response.writeHead(405, { allow: "POST" });
6543
+ response.end();
6544
+ return;
6545
+ }
6546
+ if (!sameOrigin(request)) {
6547
+ sendJson(response, 403, { error: "仅接受同源请求" });
6548
+ return;
6549
+ }
6550
+ readJsonBody(request).then((body) => {
6551
+ (async () => {
6552
+ try {
6553
+ const sessionId = String(body["sessionId"] ?? "").trim();
6554
+ if (sessionId === "") {
6555
+ sendJson(response, 200, {
6556
+ ok: false,
6557
+ error: "缺少 sessionId(老宿主座位不带当前会话 id,面板不出救生艇按钮)"
6558
+ });
6559
+ return;
6560
+ }
6561
+ const sessions = rootSessionsOf();
6562
+ let session;
6563
+ try {
6564
+ session = sessions?.get?.(sessionId);
6565
+ } catch {}
6566
+ if (session === void 0 || session === null) {
6567
+ sendJson(response, 200, {
6568
+ ok: false,
6569
+ error: `会话 ${sessionId} 不在场(宿主会话服务未挂载或会话已关闭)——救生艇需要活的会话事件流`
6570
+ });
6571
+ return;
6572
+ }
6573
+ const result = pushHandoff(session, { confirmSkeleton: true });
6574
+ if (!result.ok) {
6575
+ sendJson(response, 200, result);
6576
+ return;
6577
+ }
6578
+ recordLifecycleEvent({
6579
+ stage: "write",
6580
+ reason: "lifeboat",
6581
+ target: result.id,
6582
+ detail: result.skipped ? "事件流降级——兜底骨架卡(空壳闸放行)" : "面板一键抢出(不经模型)"
6583
+ });
6584
+ let synced;
6585
+ if (loadSyncConfig().enabled) {
6586
+ const queued = providerWriteQueue.then(async () => {
6587
+ synced = await syncNow();
6588
+ }).catch(() => {});
6589
+ providerWriteQueue = queued;
6590
+ await queued;
6591
+ }
6592
+ let state;
6593
+ try {
6594
+ state = await stateBody();
6595
+ } catch {}
6596
+ sendJson(response, 200, {
6597
+ ok: true,
6598
+ id: result.id,
6599
+ detail: result.note,
6600
+ ...synced !== void 0 ? { synced } : {},
6601
+ ...state !== void 0 ? { state } : {}
6602
+ });
6603
+ } catch (e) {
6604
+ sendJson(response, 500, {
6605
+ ok: false,
6606
+ error: e instanceof Error ? e.message : String(e)
6607
+ });
6608
+ }
6609
+ })();
6610
+ }, (error) => {
6611
+ sendJson(response, 400, {
6612
+ ok: false,
6613
+ error: error instanceof Error ? error.message : String(error)
6614
+ });
6615
+ });
6616
+ return;
6617
+ }
6618
+ sendJson(response, 404, { error: `未知路由:/dsh-takeover/${sub}(支持 state / sessions / session-preview / takeover / provider / clear-archived / dismiss-pending / sync / env-backup / lifeboat)` });
4164
6619
  }
4165
6620
  }));
4166
6621
  });
@@ -4274,72 +6729,14 @@ function inboxSkillRegistration() {
4274
6729
  }
4275
6730
  //#endregion
4276
6731
  //#region skills/resume.ts
4277
- /** 九家注册规格:单一出处,content 由模板函数生成 */
4278
- const RESUME_SKILL_SPECS = [
4279
- {
4280
- name: "resume-claude",
4281
- provider: "claude",
4282
- product: "Claude Code",
4283
- description: "把一条 Claude Code 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4284
- recoveryBoundary: "读取器全量读取本地记录(含被替换/放弃分支的条目,thinking 块以 [thinking] 标记保留);不复活 CLI、不回放工具调用。"
4285
- },
4286
- {
4287
- name: "resume-codex",
4288
- provider: "codex",
4289
- product: "Codex",
4290
- description: "把一条 Codex 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4291
- recoveryBoundary: "读取器排除 Codex 的 system / developer / reasoning / world-state / 跨 agent 记录。"
4292
- },
4293
- {
4294
- name: "resume-opencode",
4295
- provider: "opencode",
4296
- product: "OpenCode",
4297
- description: "把一条 OpenCode 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id 或标题关键词。",
4298
- recoveryBoundary: "读取器只读 OpenCode 本地存储的会话记录;不复活进程、不回放存储的调用。"
4299
- },
4300
- {
4301
- name: "resume-zcode",
4302
- provider: "zcode",
4303
- product: "ZCode",
4304
- description: "把一条 ZCode 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id(支持短前缀)或标题关键词。",
4305
- recoveryBoundary: "读取器只读 ZCode 的 sqlite 库(readonly、随开随关,需 Node ≥22);不回放调用、不复活 CLI;压缩段只是摘要标记,仍在库里的旧行保留。"
4306
- },
4307
- {
4308
- name: "resume-pi",
4309
- provider: "pi",
4310
- product: "Pi",
4311
- description: "把一条 Pi 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、JSONL 路径或标题关键词。",
4312
- recoveryBoundary: "读取器只沿 Pi 当前活跃叶子读取,排除 thinking、hooks、system 消息与扩展注入的记录。"
4313
- },
4314
- {
4315
- name: "resume-workbuddy",
4316
- provider: "workbuddy",
4317
- product: "WorkBuddy",
4318
- description: "把一条 WorkBuddy 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4319
- recoveryBoundary: "读取器只导入受支持的 WorkBuddy transcript / 存储记录,永不回放存储的调用。"
4320
- },
4321
- {
4322
- name: "resume-cursor",
4323
- provider: "cursor",
4324
- product: "Cursor",
4325
- description: "把一条 Cursor 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、记录路径或标题关键词。",
4326
- recoveryBoundary: "读取器只导入受支持的 Cursor transcript / store 记录,永不回放存储的调用。"
4327
- },
4328
- {
4329
- name: "resume-grok",
4330
- provider: "grok",
4331
- product: "Grok",
4332
- description: "把一条 Grok 会话拉进当前会话,生成六段交接卡接手工作;可附会话 id、会话目录、记录路径或标题关键词。",
4333
- recoveryBoundary: "读取器只用 Grok 可见的 updates.jsonl 流,永不读 chat_history.jsonl 原始模型上下文。"
4334
- },
4335
- {
4336
- name: "resume-gemini",
4337
- provider: "gemini",
4338
- product: "Gemini CLI",
4339
- description: "把一条 Gemini CLI 会话拉进当前会话,生成六段交接卡接手工作;本地记录是新旧双格式 JSONL/JSON,子代理会话单独存盘,可附会话 id(记录路径)、记录路径或标题关键词。",
4340
- recoveryBoundary: "读取器只读 Gemini CLI 本地 chats/ 下的会话文件(JSONL 新格式 / 整块 JSON 旧格式,含子代理会话目录);info/error/warning CLI 提示与斜杠命令行不进对话流;只读不写、不复活 Gemini CLI 进程。"
4341
- }
4342
- ];
6732
+ /** 九家注册规格:providers.ts 注册表 × 本文件模板函数生成(顺序即注册表声明序) */
6733
+ const RESUME_SKILL_SPECS = PROVIDERS.map((p) => ({
6734
+ name: p.resume.id,
6735
+ provider: p.name,
6736
+ product: p.resume.product,
6737
+ description: p.resume.description,
6738
+ recoveryBoundary: p.resume.recoveryBoundary
6739
+ }));
4343
6740
  /** 单条 skill 内容模板:九条共用一个模板函数 */
4344
6741
  function resumeSkillContent(spec) {
4345
6742
  const slash = `/${spec.name}`;
@@ -4439,7 +6836,7 @@ function resumeSkillRegistration(spec) {
4439
6836
  content: resumeSkillContent(spec)
4440
6837
  };
4441
6838
  }
4442
- /** 九条注册项(数组驱动,与 RESUME_SKILL_SPECS 一一对应) */
6839
+ /** 九条注册项(注册表驱动,与 RESUME_SKILL_SPECS 一一对应) */
4443
6840
  function resumeSkillRegistrations() {
4444
6841
  return RESUME_SKILL_SPECS.map(resumeSkillRegistration);
4445
6842
  }
@@ -4462,11 +6859,13 @@ function apply(ctx) {
4462
6859
  registerInboxTool(ctx);
4463
6860
  registerForeignTool(ctx, { isEnabled: (p) => isProviderEnabled(p) });
4464
6861
  registerMemoryTool(ctx);
6862
+ registerSyncTool(ctx);
6863
+ registerEnvBackupTool(ctx);
4465
6864
  registerTakeoverRoutes(ctx);
4466
6865
  for (const reg of skillRegistrations()) ctx.skills.register(reg);
4467
- ctx.logger.info("dsh-takeover: 会话接管已加载(工具 handoff_push / handoff_inbox / handoff_memory / foreign_session_read + slash /handoff /inbox /resume-*×8 + 设置卡 API /dsh-takeover/*)");
6866
+ ctx.logger.info("dsh-takeover: 会话接管已加载(工具 handoff_push / handoff_inbox / handoff_memory / handoff_sync / handoff_env / foreign_session_read + slash /handoff /inbox /resume-*×8 + 设置卡 API /dsh-takeover/*)");
4468
6867
  }
4469
6868
  //#endregion
4470
- export { FOREIGN_PROVIDERS, MEMORY_SOURCES, OUTBOUND_LABELS, OUTBOUND_TARGETS, PROVIDER_TO_ADAPTER, RESUME_SKILL_SPECS, admitTakeover, apply, buildState, clearArchived, collectFacts, disabledError, dismissPending, factsToSections, foreignResolveOne, foreignSessionPreview, foreignSessionRead, foreignSessionsList, handoffHostNotice, handoffSkillRegistration, humanChars, inboxList, inboxLoad, inboxSkillRegistration, inject, isProviderEnabled, loadSwitches, name, outboundCommand, pickupCommand, probeSessionEvents, pushHandoff, pushMemoryCard, registerForeignTool, registerMemoryTool, registerTakeoverRoutes, renderForeign, renderMemory, resumeSkillContent, resumeSkillRegistrations, saveSwitches, scanMemorySources, sessionControllerOf, setProviderEnabled, skillRegistrations, summarizeTurns, switchesPath, todoToTasks };
6869
+ export { FOREIGN_PROVIDERS, HISTORY_STOPPED_MAX, HISTORY_TAIL_MAX, MEMORY_SOURCES, MEMORY_STORES, OUTBOUND_LABELS, OUTBOUND_TARGETS, PROVIDER_TO_ADAPTER, RESUME_SKILL_SPECS, admitTakeover, apply, applyRestore, axisFromExtras, baselineFromExtras, buildState, clearArchived, collectFacts, collectScopeFiles, createBackup, disabledError, dismissPending, dryRunRestore, envBackupDir, factsToSections, foreignResolveOne, foreignSessionPreview, foreignSessionRead, foreignSessionsList, handoffHostNotice, handoffSkillRegistration, humanChars, inboxHistory, inboxList, inboxLoad, inboxSkillRegistration, inject, isProviderEnabled, listBackups, loadSwitches, loadSyncConfig, name, outboundCommand, pickupCommand, probeSessionEvents, pushConfigCard, pushHandoff, pushMemoryCard, readBackupManifest, readStoreEntries, redactRemote, registerForeignTool, registerMemoryTool, registerTakeoverRoutes, renderBaselineGuidance, renderForeign, renderMemory, resumeSkillContent, resumeSkillRegistrations, rollbackRestore, saveSwitches, saveSyncConfig, scanMemorySources, sessionControllerOf, setProviderEnabled, skillRegistrations, summarizeTurns, switchesPath, syncConfigPath, syncNow, syncPull, syncPush, syncSetup, syncStatusOf, todoToTasks, validateRelPath, validateRemoteUrl };
4471
6870
 
4472
6871
  //# sourceMappingURL=index.js.map