@yottameta/yotta-memory 0.24.3 → 0.24.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.24.5 (2026-11-24)
4
+
5
+ - Electron 宿主识别与开机自启测试切换为 `YottaWeave`,不再保留 `yottacode` 兼容标识。
6
+ - 活跃文档、身份示例、任务路径与测试夹具统一使用 `yottaweave` / `YottaWeave`。
7
+ - 不改变记忆格式、索引格式、命令参数或既有数据目录。
8
+
9
+ ## v0.24.4 (2026-11-20)
10
+
11
+ - **Windows 多用户自启隔离**:计划任务名改为 `YottaMemoryServe-<SHA-256(大写 SID) 前 16 位>`;`lan enable / status / disable` 与 runtime 受管重启统一使用当前用户 SID,并在操作前验证目标任务主体归属。其他用户或归属未知的任务不会被覆盖、删除、停止或运行。
12
+ - **旧任务安全迁移**:新 SID 任务创建成功后才查询旧固定任务 `YottaMemoryServe`;只有任务 XML 能证明属于当前用户时才删除,foreign / unknown 一律保留。
13
+ - **profile 兼容**:`serve-profile.json` 保持 schema 1,新增可选 `userSid`;`lan status` 检查 profile SID、当前 SID 与派生任务名的一致性。
14
+ - **跨平台边界**:Windows 专用 SID 探测与 `schtasks` 路径不影响 Linux / macOS;SID 缺失或非法时 fail-closed,不回退固定任务名。
15
+
3
16
  ## v0.24.3 (2026-11-14)
4
17
 
5
18
  - **CI 精度回归**:将命中打点后的 mtime 断言收紧到 Node 原生精度边界内(纳秒偏差 < 5µs)并保留可见毫秒不变;避免 Linux 上 `utimesSync` 的亚微秒浮点误差把正确行为误判为失败。
package/README.zh-CN.md CHANGED
@@ -185,7 +185,7 @@
185
185
 
186
186
  - **记忆库即引擎**:`serve` 把记忆目录挂成 MCP 服务,目录随盘走;引擎主机只需装 CLI 当存放点,无需装任何 AI 智能体。
187
187
  - **双模式可并存**:本地 `serve --stdio` 零进程(客户端按需拉起);局域网 streamable HTTP(默认 `0.0.0.0:8787`)+ 每智能体 token 鉴权。
188
- - **开机自启**:`lan enable` 注册开机自启——Windows 优先计划任务(v0.22.4 起 S4U 主体后台静默、不弹窗口;默认登录自启,`--onstart` 开机即启、无登录会话也可启动,计划任务注册需管理员),非管理员自动降级为**用户级 Startup 静默自启**(免管理员,启动脚本内联启动命令、被清理也会在开机时自动重建,v0.6.3 起不再弹 80070002);**v0.22.5 起 Electron 宿主(如 YottaCode)自动注入 ELECTRON_RUN_AS_NODE,任务不再拉起 GUI**;Linux 优先 **systemd 用户单元**(`systemctl --user`,登录自启;`--onstart` 附加 `loginctl enable-linger` 开机即启),systemd 不可用时自动降级**用户 crontab @reboot**(v0.6.4);`lan disable` 移除,`lan status` 查询。
188
+ - **开机自启**:`lan enable` 注册开机自启——Windows 优先计划任务(v0.22.4 起 S4U 主体后台静默、不弹窗口;默认登录自启,`--onstart` 开机即启、无登录会话也可启动,计划任务注册需管理员),非管理员自动降级为**用户级 Startup 静默自启**(免管理员,启动脚本内联启动命令、被清理也会在开机时自动重建,v0.6.3 起不再弹 80070002);**v0.22.5 起 Electron 宿主(如 YottaWeave)自动注入 ELECTRON_RUN_AS_NODE,任务不再拉起 GUI**;Linux 优先 **systemd 用户单元**(`systemctl --user`,登录自启;`--onstart` 附加 `loginctl enable-linger` 开机即启),systemd 不可用时自动降级**用户 crontab @reboot**(v0.6.4);`lan disable` 移除,`lan status` 查询。
189
189
  - **安全边界**:管理动作(init / config / token / lan / serve)不进 MCP,token 不远程暴露;远程智能体只能读写记忆,且路径限记忆库内(export/import 的 out/src 必须落在库内)、distill 不支持 `--model`(仅本地 CLI),不能改配置、不能管 token。
190
190
  - 完整操作步骤见上文「局域网多机共享」章节与 [USER_GUIDE.md](USER_GUIDE.md)。
191
191
 
package/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: yotta-memory
3
3
  description: 元忆 —— 有权限边界的文件式智能体记忆。文件式、零依赖、可 diff/可回滚:让任何 AI 智能体活过会话,开工 recall 恢复上下文、重要信息 remember 落盘、收工归档。类型体系 FACT(公共共享)/ PREF / BOUND / COMMIT(私密隔离)。触发:记住、别忘了、记一笔、记忆、remember、recall、跨会话、上次说到、续测、交接、归档、记忆盘、共享记忆、局域网记忆、画像、开工上下文、长期理解摘要、近期走廊、会话闭环、记忆守则、profile、context、越用越懂、语义检索、反馈、维护、蒸馏、feedback、maintain、distill、explain、自我学习、自我进化、自我提升、查看平台分页、recall 候选预过滤、任务相关记忆、--focus、--embedding、压缩遗忘、consolidate、周期摘要、自动合并、分类型衰减、回滚、备份、backup、防误删、doctor、事务快照、基线探针、恢复演练、记忆库安全扫描、scan、命中打点、容量水位、--capacity、--propose、上下文压缩审计、context --audit
4
- version: 0.24.3
4
+ version: 0.24.5
5
5
  license: MIT
6
6
  ---
7
7
 
@@ -18,6 +18,10 @@ license: MIT
18
18
  `serve-profile.json`,Windows 计划任务、Startup 兜底、systemd 与 crontab
19
19
  均显式引用该 profile;`serve --profile <文件>` 固化 memory_home / runtime_home /
20
20
  config_dir,避免 S4U 或无用户环境启动时 `os.homedir()` 漂移为空库并导致远端 401。
21
+ - **Windows 多用户自启隔离(v0.24.4)**:计划任务名按当前用户 SID 的 SHA-256
22
+ 前 16 位派生;`lan enable / status / disable` 与 runtime 受管重启在操作前验证任务
23
+ 主体归属。旧固定任务只在新任务创建成功且归属可证明时迁移;其他用户或未知主体
24
+ 一律保留。`serve-profile.json` 保持 schema 1,并新增可选 `userSid`。
21
25
 
22
26
  ## 这是什么
23
27
 
@@ -74,7 +78,7 @@ AI 更新流程:先运行 `yotta-memory --version` 记录当前引擎版本;
74
78
  2. **进行中落盘**:出现事实 / 偏好 / 边界 / 纠正 / 承诺信号时立即 `yotta-memory remember <type> <subject> <statement> --verify`,不攒到收工。
75
79
  3. **收工归档**:收工前复盘本轮,检查是否留下 COMMIT / 会话小结;有关键结论但未落盘时补写并 `recall` 回读,无长期价值不硬凑。旧记录定期 `yotta-memory maintain --apply`(单条低效用归档)+ 记忆多了先 `yotta-memory consolidate`(propose 报告)→ 确认后 `yotta-memory consolidate --apply --yes`(非交互;同主题压缩成带溯源摘要,`--undo` 可回滚)。上下文被宿主压缩过、担心有决策只留在对话里时,把压缩内容喂给 `yotta-memory context --audit --from <文件>` 核对。
76
80
  4. **多智能体纪律**:FACT 写入公共区,PREF / BOUND / COMMIT 只写本智能体私密区;不读取其他智能体私密区。**一切读写一律走 `yotta-memory` CLI / MCP 工具**——禁止用 shell(`Get-ChildItem` / `Get-Content` / `cat` / `ls` / `type` 等)直接读或改记忆库目录下的 `.md` / `index.json` / `tokens.json` / `agents.json` / `grants.json` 等文件,否则会绕过权限边界、读到别的智能体私密内容。
77
- 5. **身份自检(v0.22.1,防串号)**:跨宿主环境(Codex / YottaCode / DSH / OpenCode / 多 MCP)里,任何写入都必须显式声明身份:CLI 传 `--agent <id> --agent-key-file <文件>`,stdio MCP 传 `--agent-id <id> --agent-key-file <文件>`;不要依赖宿主发现。每次 `remember` / `forget` 的结果都会回显 `[身份] agent_id: …;来源: …`——**回显的 ID 不是本会话身份就立即停写并报告用户**;出现 `[注意] 检测到宿主身份环境 YOTTA_MEMORY_AGENT_HOME=…` 时按同样规则核对,必要时显式覆盖后重试。
81
+ 5. **身份自检(v0.22.1,防串号)**:跨宿主环境(Codex / YottaWeave / DSH / OpenCode / 多 MCP)里,任何写入都必须显式声明身份:CLI 传 `--agent <id> --agent-key-file <文件>`,stdio MCP 传 `--agent-id <id> --agent-key-file <文件>`;不要依赖宿主发现。每次 `remember` / `forget` 的结果都会回显 `[身份] agent_id: …;来源: …`——**回显的 ID 不是本会话身份就立即停写并报告用户**;出现 `[注意] 检测到宿主身份环境 YOTTA_MEMORY_AGENT_HOME=…` 时按同样规则核对,必要时显式覆盖后重试。
78
82
 
79
83
  ## 会话闭环契约(v0.14.0,AI 必做)
80
84
 
@@ -346,7 +350,7 @@ yotta-memory doctor --json
346
350
  | `yotta-memory token new --agent <id> [--force]` / `token list` / `token revoke --agent <id>` | 每智能体访问 token:生成 / 列出 / 吊销(登记 `<记忆库>/.server/tokens.json`;同 ID 已被其它来源占用需 `--force` 覆盖,防不同智能体合流)|
347
351
  | `yotta-memory serve [--host 0.0.0.0] [--port 8787] [--no-auth] [--stdio] [--tools core|full]` | 启动 MCP 记忆引擎(streamable HTTP 局域网 / --stdio 本地零进程模式;Bearer token + X-Agent-Id + X-Agent-Key 鉴权;工具分组默认 full)|
348
352
  | `yotta-memory runtime list / install <tarball|版本> [--from-current] [--force] / use <版本> [--restart] / rollback [--restart] / status` | 运行时稳定入口(runtime.json + versions + current;安装 / 切换 / 回滚 / 查看漂移;`--restart` 尝试重启受管 server,失败自动切回旧版本);漂移诊断用 `doctor --runtime` |
349
- | `yotta-memory lan enable [--onstart] / disable / status` | 开机自启管理(Windows:任务计划程序,S4U 主体后台静默——v0.22.4 起不弹窗口,`--onstart` 无登录会话也可启动;任务 XML 注册,去电池限制与 72h 时限;非管理员自动降级用户级 Startup 静默自启,v0.6.3 起 VBS 自愈不弹 80070002;v0.22.5 起 Electron 宿主(如 YottaCode)自动注入 ELECTRON_RUN_AS_NODE,不再拉起 GUI;Linux:systemd 用户单元,不可用时自动降级用户 crontab @reboot)|
353
+ | `yotta-memory lan enable [--onstart] / disable / status` | 开机自启管理(Windows:任务计划程序,S4U 主体后台静默——v0.22.4 起不弹窗口,`--onstart` 无登录会话也可启动;任务 XML 注册,去电池限制与 72h 时限;非管理员自动降级用户级 Startup 静默自启,v0.6.3 起 VBS 自愈不弹 80070002;v0.22.5 起 Electron 宿主(如 YottaWeave)自动注入 ELECTRON_RUN_AS_NODE,不再拉起 GUI;Linux:systemd 用户单元,不可用时自动降级用户 crontab @reboot)|
350
354
  | `yotta-memory feedback <文件|主题> --useful|--useless [--reason <原因>] [--undo]` | 显式使用反馈(v0.8.0 自我学习闭环:useful → weight×1.2 / useless → weight×0.8,confidence / feedback_net 同步演化;`--undo` 回滚最近一次;审计写 `.archive/feedback-<日期>.jsonl`)|
351
355
  | `yotta-memory maintain [--dry-run] [--apply] [--purge] [--threshold N] [--age N] [--dedup] [--dedup --apply] [--merge A,B] [--rules]` | 记忆自组织(v0.8.0 自我进化 + v0.10.0 自动合并):默认 dry-run 预览;`--apply` 执行归档(immutable / BOUND 豁免;私密归档入 `.archive/private/<owner>/<type>/`),`--purge` 才真删遗忘候选;`--dedup` 查重并给**置信度分档**(≥0.85 高置信 / 0.65–0.85 建议手动 / 其余忽略),`--dedup --apply` 自动合并同归属高置信组(写批次审计可回滚;与归档互斥,不误归档);`--merge A,B` 手动合并两条;`--rules` 只读输出重复踩坑 → 建议升级为规则的清单(阈值 `maintain_rule_min_hits`,默认 3;只给建议不写 BOUND);审计写 `.archive/audit-<日期>.jsonl`)|
352
356
  | `yotta-memory consolidate [--min-age N] [--min-idle N] [--max-utility N] [--min-group N] [--period N] [--type T] [--model <cmd>] [--apply] [--undo <batch>] [--batches]` | 周期摘要压缩(v0.10.0 压缩遗忘 + v0.18.0 提案闸门 + v0.18.1 日期 / 标记:把超龄 + 长期闲置 + 低效用的同主题旧记忆归纳成**带溯源**的周期摘要并留在活跃区,原文整体进 `.archive/`;摘要正文按条目 `created` 把「昨天 / 上周 / 本月 / 今年」等绝对化,归档副本追加一行巩固标记;默认 dry-run;immutable / BOUND 豁免,活跃 / 高效用记忆不动;`--apply` 执行并写批次审计,`--undo <batch>` 剥离标记并回滚(幂等),`--batches` 查近期批次;`--model` 仅本地 CLI)|
package/USER_GUIDE.md CHANGED
@@ -366,7 +366,7 @@ yotta-memory init --dir /srv/yotta-memory # 新库:初始化(
366
366
  ```bash
367
367
  # Windows:内置命令(优先计划任务——v0.22.4 起 S4U 主体后台静默、不弹窗口;
368
368
  # 非管理员自动降级用户级 Startup 静默自启;v0.6.3 起启动脚本自愈——启动文件被清理也会在开机时自动重建;
369
- # v0.22.5 起 Electron 宿主(如 YottaCode)自动注入 ELECTRON_RUN_AS_NODE,不再拉起 GUI)
369
+ # v0.22.5 起 Electron 宿主(如 YottaWeave)自动注入 ELECTRON_RUN_AS_NODE,不再拉起 GUI)
370
370
  yotta-memory lan enable # 登录后自动启动(默认)
371
371
  yotta-memory lan enable --onstart # 开机即启、无登录会话也可启动(计划任务注册需管理员)
372
372
  yotta-memory lan status # 查看状态
@@ -26,7 +26,7 @@ const zlib = require('zlib');
26
26
  const child_process = require('child_process');
27
27
  const { AsyncLocalStorage } = require('async_hooks');
28
28
 
29
- const VERSION = '0.24.3';
29
+ const VERSION = '0.24.5';
30
30
  const CLI_VALUE_OPTS = new Set(['--type', '--limit', '--days', '--out', '--owner', '--agent', '--agent-id', '--agent-key', '--agent-key-file', '--plugin-data', '--threshold', '--scope', '--host', '--port', '--dir', '--name', '--user', '--relationship', '--source', '--weight', '--budget', '--password', '--new-password', '--recovery-key', '--recovery-key-out', '--reason', '--merge', '--model', '--subject', '--embedding', '--focus', '--embedding-timeout', '--min-age', '--min-idle', '--max-utility', '--min-group', '--period', '--to', '--id', '--time', '--tools', '--mcp-config', '--skill-dir', '--year', '--evalset', '--k', '--seed', '--bootstrap', '--gate', '--against', '--template', '--path', '--from', '--from-plan', '--batch', '--profile']);
31
31
  const CLI_FLAG_OPTS = new Set(['--project', '--all', '--unsafe', '--no-auth', '--stdio', '--onstart', '--from-current', '--restart', '--force', '--attach', '--allow-same-volume', '--verify', '--no-hint', '--encrypt', '--no-encrypt', '--password-stdin', '--json', '--manual', '--skip-schedule', '--useful', '--useless', '--undo', '--dry-run', '--apply', '--purge', '--dedup', '--batches', '--propose', '--audit', '--capacity', '--rules', '--explain', '--semantic', '--runtime', '--ablate', '--timing', '--baseline', '--probe', '--quarantine', '--restore', '--no-usage', '--yes', '--keep-memories', '--keep-identity', '--stats', '--include-flat', '--no-policy', '--policy-candidates']);
32
32
 
@@ -953,15 +953,40 @@ function runtimeEnsureForManagedTask() {
953
953
  }
954
954
  return runtimeInstallFromCurrent({ force: false });
955
955
  }
956
- function runtimeRestartManagedServer() {
957
- const platform = lanPlatform();
956
+ function runtimeRestartManagedServer(opts) {
957
+ opts = opts || {};
958
+ const platform = opts.platform || lanPlatform();
958
959
  if (platform === 'win32') {
959
- const query = child_process.spawnSync('schtasks', ['/query', '/tn', LAN_TASK_NAME, '/fo', 'LIST'], { encoding: 'utf8' });
960
- if (query.status !== 0) return { error: true, text: '未检测到受管计划任务 ' + LAN_TASK_NAME + '。' };
961
- const end = child_process.spawnSync('schtasks', ['/end', '/tn', LAN_TASK_NAME], { encoding: 'utf8' });
962
- const run = child_process.spawnSync('schtasks', ['/run', '/tn', LAN_TASK_NAME], { encoding: 'utf8' });
960
+ const sidResult = lanWindowsTaskSid(opts);
961
+ if (sidResult.error) return { error: true, text: sidResult.text };
962
+ const taskName = lanWindowsTaskName({ sid: sidResult.sid });
963
+ const query = lanWindowsTaskQuery(opts, taskName);
964
+ if (query.status !== 'found') {
965
+ const legacy = lanWindowsTaskQuery(opts, LAN_TASK_NAME_LEGACY);
966
+ if (legacy.status === 'found') {
967
+ const ownership = lanWindowsTaskOwnership({
968
+ xml: legacy.xml,
969
+ taskSid: sidResult.sid,
970
+ currentUser: lanWindowsTaskUser(opts),
971
+ });
972
+ if (ownership.status === 'current') {
973
+ return { error: true, text: '未检测到当前用户的 SID 任务 ' + taskName + ';旧任务需要迁移,请执行 yotta-memory lan enable。' };
974
+ }
975
+ }
976
+ return { error: true, text: '未检测到受管计划任务 ' + taskName + '。' };
977
+ }
978
+ const ownership = lanWindowsTaskOwnership({
979
+ xml: query.xml,
980
+ taskSid: sidResult.sid,
981
+ currentUser: lanWindowsTaskUser(opts),
982
+ });
983
+ if (ownership.status !== 'current') {
984
+ return { error: true, text: '受管计划任务 ' + taskName + ' 的归属无法证明属于当前用户,拒绝重启。' + (ownership.text ? ' ' + ownership.text : '') };
985
+ }
986
+ const end = lanWindowsRunSchtasks(opts, ['/end', '/tn', taskName]);
987
+ const run = lanWindowsRunSchtasks(opts, ['/run', '/tn', taskName]);
963
988
  if (run.status !== 0) return { error: true, text: '计划任务重启失败: ' + String(run.stderr || run.stdout || '').trim() };
964
- return { error: false, text: '已重启计划任务 ' + LAN_TASK_NAME + (end.status === 0 ? '' : '(原任务未在运行)') };
989
+ return { error: false, text: '已重启计划任务 ' + taskName + (end.status === 0 ? '' : '(原任务未在运行)') };
965
990
  }
966
991
  if (platform === 'linux') {
967
992
  const unit = lanLinuxUnitPath();
@@ -3628,7 +3653,7 @@ function backupWindowsTaskXml(opts) {
3628
3653
  ? '<Principal id="Author"><UserId>' + xmlEscape(userId) + '</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal>'
3629
3654
  : '<Principal id="Author"><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal>';
3630
3655
  const cmdPath = opts.cmdPath || process.env.ComSpec || 'cmd.exe';
3631
- // v0.22.5: Electron 宿主(如 YottaCode shim)下 process.execPath 是 Electron 可执行文件,
3656
+ // v0.22.5: Electron 宿主(如 YottaWeave shim)下 process.execPath 是 Electron 可执行文件,
3632
3657
  // 任务需经 cmd /c + ELECTRON_RUN_AS_NODE=1 包装,否则拉起的是桌面程序本体而非 Node。
3633
3658
  const action = lanElectronHost(opts)
3634
3659
  ? '<Actions Context="Author"><Exec><Command>' + xmlEscape(cmdPath) + '</Command><Arguments>/c "set "ELECTRON_RUN_AS_NODE=1" &amp;&amp; "' + xmlEscape(nodePath) + '" "' + xmlEscape(scriptPath) + '" backup ensure-daily"</Arguments></Exec></Actions>'
@@ -11689,13 +11714,165 @@ function cmdServeStdio(opts) {
11689
11714
  // Linux (v0.6.4): (1) systemd user unit (systemctl --user enable/start, login autostart; --onstart
11690
11715
  // additionally runs loginctl enable-linger for boot autostart); (2) auto-fallback to user crontab
11691
11716
  // @reboot when no systemd user session is available.
11692
- const LAN_TASK_NAME = 'YottaMemoryServe';
11717
+ const LAN_TASK_NAME_LEGACY = 'YottaMemoryServe';
11718
+ const LAN_TASK_NAME_PREFIX = 'YottaMemoryServe-';
11693
11719
  const LAN_GEN_MARKER = 'Generated by yotta-memory lan enable';
11694
11720
  const LAN_UNIT_NAME = 'yotta-memory-serve.service';
11695
11721
  const LAN_CRONTAB_MARKER = '#YTM_LAN:yotta-memory-serve';
11696
11722
  const SERVE_PROFILE_FILE = 'serve-profile.json';
11697
11723
  const SERVE_PROFILE_SCHEMA = 1;
11698
11724
 
11725
+ function canonicalWindowsSid(value) {
11726
+ const sid = String(value || '').trim().toUpperCase();
11727
+ return /^S-\d+(?:-\d+){2,}$/.test(sid) ? sid : '';
11728
+ }
11729
+
11730
+ function lanWindowsTaskName(opts) {
11731
+ opts = opts || {};
11732
+ const sid = canonicalWindowsSid(opts.sid || opts.taskSid);
11733
+ if (!sid) throw new Error('Windows 用户标识 SID 缺失或格式非法,拒绝回退到固定任务名。');
11734
+ const hash = crypto.createHash('sha256').update(sid).digest('hex').slice(0, 16);
11735
+ return LAN_TASK_NAME_PREFIX + hash;
11736
+ }
11737
+
11738
+ function lanWindowsTaskSid(opts) {
11739
+ opts = opts || {};
11740
+ const explicit = opts.taskSid !== undefined ? opts.taskSid : opts.sid;
11741
+ if (explicit !== undefined && String(explicit).trim() !== '') {
11742
+ const sid = canonicalWindowsSid(explicit);
11743
+ if (!sid) return { error: true, text: 'Windows 用户标识 SID 格式非法: ' + String(explicit) };
11744
+ return { error: false, sid: sid };
11745
+ }
11746
+ const envSid = process.env.YOTTA_LAN_TASK_SID;
11747
+ if (envSid !== undefined && String(envSid).trim() !== '') {
11748
+ const sid = canonicalWindowsSid(envSid);
11749
+ if (!sid) return { error: true, text: 'YOTTA_LAN_TASK_SID 格式非法: ' + String(envSid) };
11750
+ return { error: false, sid: sid };
11751
+ }
11752
+ try {
11753
+ const r = typeof opts.whoamiFn === 'function'
11754
+ ? opts.whoamiFn()
11755
+ : lanSpawn('whoami', ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
11756
+ const status = r && typeof r.status === 'number' ? r.status : (r && r.error ? 1 : 0);
11757
+ const text = String((r && (r.stdout || r.stderr)) || '');
11758
+ if (status !== 0) return { error: true, text: '无法取得 Windows 用户 SID: ' + text.trim() };
11759
+ const match = text.match(/\b(S-\d+(?:-\d+){2,})\b/i);
11760
+ const sid = canonicalWindowsSid(match && match[1]);
11761
+ if (!sid) return { error: true, text: 'whoami 输出中没有可用的 Windows 用户 SID: ' + text.trim() };
11762
+ return { error: false, sid: sid };
11763
+ } catch (e) {
11764
+ return { error: true, text: '无法取得 Windows 用户 SID: ' + String((e && e.message) || e) };
11765
+ }
11766
+ }
11767
+
11768
+ function xmlUnescapeText(value) {
11769
+ return String(value || '')
11770
+ .replace(/&lt;/g, '<')
11771
+ .replace(/&gt;/g, '>')
11772
+ .replace(/&quot;/g, '"')
11773
+ .replace(/&apos;/g, "'")
11774
+ .replace(/&amp;/g, '&');
11775
+ }
11776
+
11777
+ function lanWindowsTaskOwnership(opts) {
11778
+ opts = opts || {};
11779
+ const xml = String(opts.xml || '');
11780
+ const principals = /<Principals(?:\s[^>]*)?>([\s\S]*?)<\/Principals>/i.exec(xml);
11781
+ if (!principals) return { status: 'unknown', userId: '', text: '任务 XML 未提供 Principals。' };
11782
+ const principalBlock = /<Principal(?:\s[^>]*)?>([\s\S]*?)<\/Principal>/i.exec(principals[1]);
11783
+ if (!principalBlock) return { status: 'unknown', userId: '', text: '任务 XML 未提供 Principal。' };
11784
+ const match = /<UserId(?:\s[^>]*)?>([\s\S]*?)<\/UserId>/i.exec(principalBlock[1]);
11785
+ if (!match) return { status: 'unknown', userId: '', text: '任务 Principal 未提供 UserId。' };
11786
+ const principal = xmlUnescapeText(match[1]).trim();
11787
+ if (!principal) return { status: 'unknown', userId: '', text: '任务 XML 的 UserId 为空。' };
11788
+ const currentSid = canonicalWindowsSid(opts.taskSid || opts.sid || '');
11789
+ const principalSid = canonicalWindowsSid(principal);
11790
+ if (principalSid) {
11791
+ if (!currentSid) return { status: 'unknown', userId: principal, text: '当前 SID 未解析,无法证明任务归属。' };
11792
+ return {
11793
+ status: principalSid === currentSid ? 'current' : 'foreign',
11794
+ userId: principal,
11795
+ text: principalSid === currentSid ? '任务归属于当前 SID。' : '任务归属于其他 SID。',
11796
+ };
11797
+ }
11798
+ const currentUser = String(opts.currentUser || opts.userId || lanWindowsTaskUser(opts) || '').trim();
11799
+ if (!currentUser) return { status: 'unknown', userId: principal, text: '当前用户名未解析,无法证明任务归属。' };
11800
+ const same = principal.toLowerCase() === currentUser.toLowerCase();
11801
+ return {
11802
+ status: same ? 'current' : 'foreign',
11803
+ userId: principal,
11804
+ text: same ? '任务归属于当前用户名。' : '任务归属于其他用户名。',
11805
+ };
11806
+ }
11807
+
11808
+ function isSchtasksTaskMissing(value) {
11809
+ const msg = typeof value === 'string' ? value : String((value && (value.stderr || value.stdout || value.message)) || value || '');
11810
+ return /cannot find the (path|file|task)|系统找不到指定的文件|没有找到|找不到|不存在|does not exist/i.test(msg);
11811
+ }
11812
+
11813
+ function decodeWindowsConsoleOutput(value) {
11814
+ if (!Buffer.isBuffer(value)) return String(value || '');
11815
+ if (value.length === 0) return '';
11816
+ const utf8 = value.toString('utf8');
11817
+ if (!utf8.includes('\uFFFD')) return utf8;
11818
+ try {
11819
+ // Windows console programs commonly emit the active OEM/ANSI code page.
11820
+ // Keep the raw buffer until after capture so localized errors stay classifiable.
11821
+ const gbk = new TextDecoder('gbk').decode(value);
11822
+ return gbk || utf8;
11823
+ } catch (_) {
11824
+ return utf8;
11825
+ }
11826
+ }
11827
+
11828
+ function lanWindowsTaskQuery(opts, taskName) {
11829
+ const r = lanWindowsRunSchtasks(opts, ['/query', '/tn', taskName, '/xml']);
11830
+ const text = String(r.stderr || r.stdout || '');
11831
+ if (r.status === 0) return { status: 'found', xml: String(r.stdout || ''), text: text };
11832
+ if (isSchtasksTaskMissing(text)) return { status: 'missing', xml: '', text: text };
11833
+ return { status: 'unknown', xml: '', text: text || ('schtasks 退出码 ' + r.status) };
11834
+ }
11835
+
11836
+ function lanWindowsTargetTaskCheck(opts, taskName, taskSid) {
11837
+ const query = lanWindowsTaskQuery(opts, taskName);
11838
+ if (query.status === 'missing') return { error: false, mode: 'task', exists: false };
11839
+ if (query.status === 'found') {
11840
+ const ownership = lanWindowsTaskOwnership({
11841
+ xml: query.xml,
11842
+ taskSid: taskSid,
11843
+ currentUser: lanWindowsTaskUser(opts),
11844
+ });
11845
+ if (ownership.status === 'current') return { error: false, mode: 'task', exists: true, ownership: ownership };
11846
+ return {
11847
+ error: true,
11848
+ text: '目标计划任务 ' + taskName + ' 已存在,但归属无法证明属于当前用户;拒绝覆盖。' + (ownership.text ? ' ' + ownership.text : ''),
11849
+ };
11850
+ }
11851
+ if (isSchtasksAccessDenied(query.text)) {
11852
+ return { error: false, mode: 'startup', accessDenied: true, reason: query.text };
11853
+ }
11854
+ return {
11855
+ error: true,
11856
+ text: '无法确认目标计划任务 ' + taskName + ' 的归属;拒绝覆盖。' + (query.text ? ' ' + query.text : ''),
11857
+ };
11858
+ }
11859
+
11860
+ function lanWindowsMigrateLegacyTask(opts, taskSid) {
11861
+ const query = lanWindowsTaskQuery(opts, LAN_TASK_NAME_LEGACY);
11862
+ if (query.status === 'missing') return { status: 'none', text: '未发现旧固定任务。' };
11863
+ if (query.status === 'unknown') return { status: 'retained-unknown', text: '旧固定任务归属无法确认,已保留。' };
11864
+ const ownership = lanWindowsTaskOwnership({
11865
+ xml: query.xml,
11866
+ taskSid: taskSid,
11867
+ currentUser: lanWindowsTaskUser(opts),
11868
+ });
11869
+ if (ownership.status === 'foreign') return { status: 'retained-foreign', text: '旧固定任务属于其他用户,已保留。' };
11870
+ if (ownership.status !== 'current') return { status: 'retained-unknown', text: '旧固定任务归属无法确认,已保留。' };
11871
+ const del = lanWindowsRunSchtasks(opts, ['/delete', '/tn', LAN_TASK_NAME_LEGACY, '/f']);
11872
+ if (del.status === 0) return { status: 'migrated', text: '已迁移旧固定任务。' };
11873
+ return { status: 'retained-unknown', text: '旧固定任务已确认归属,但删除失败,已保留: ' + String(del.stderr || del.stdout || '').trim() };
11874
+ }
11875
+
11699
11876
  function resolveProfilePath(value) {
11700
11877
  const text = String(value || '');
11701
11878
  if (!text) return '';
@@ -11740,6 +11917,11 @@ function lanWriteServeProfile(opts) {
11740
11917
  if (!fs.existsSync(memoryHome) || !fs.statSync(memoryHome).isDirectory()) {
11741
11918
  return { error: true, text: '记忆库不存在或不是目录: ' + memoryHome + '。请先初始化或修正 memory_home。' };
11742
11919
  }
11920
+ const rawUserSid = String(opts.userSid || opts.taskSid || '').trim();
11921
+ const userSid = canonicalWindowsSid(rawUserSid);
11922
+ if (rawUserSid && !userSid) {
11923
+ return { error: true, text: 'profile userSid 格式非法: ' + rawUserSid };
11924
+ }
11743
11925
  const profile = {
11744
11926
  schemaVersion: SERVE_PROFILE_SCHEMA,
11745
11927
  generatedAt: new Date().toISOString(),
@@ -11750,6 +11932,7 @@ function lanWriteServeProfile(opts) {
11750
11932
  host: String(opts.host || '0.0.0.0'),
11751
11933
  port: parseInt(opts.port, 10) || 8787,
11752
11934
  };
11935
+ if (userSid) profile.userSid = userSid;
11753
11936
  fs.mkdirSync(path.dirname(profilePath), { recursive: true });
11754
11937
  atomicWriteFileSync(profilePath, JSON.stringify(profile, null, 2) + '\n', 'utf8');
11755
11938
  return { error: false, profilePath: profilePath, profile: profile };
@@ -11842,8 +12025,8 @@ function lanSpawn(bin, args, spawnOpts) {
11842
12025
  }
11843
12026
  // platform override for testing/advanced use (YOTTA_LAN_PLATFORM=linux/win32/...)
11844
12027
  function lanPlatform() { return process.env.YOTTA_LAN_PLATFORM || process.platform; }
11845
- // ---- v0.22.5: Electron 宿主(YottaCode shim)适配 ----
11846
- // 背景:宿主运行时为 Electron 时(如 YottaCode.exe 以 ELECTRON_RUN_AS_NODE=1 当 Node 运行本脚本),
12028
+ // ---- v0.22.5: Electron 宿主(YottaWeave shim)适配 ----
12029
+ // 背景:宿主运行时为 Electron 时(如 YottaWeave.exe 以 ELECTRON_RUN_AS_NODE=1 当 Node 运行本脚本),
11847
12030
  // process.execPath 指向 Electron 可执行文件;自启 / 定时任务环境不带 ELECTRON_RUN_AS_NODE=1 时,
11848
12031
  // 拉起的是桌面程序本体而非 Node 服务(0.22.4 后新机首例实测)。生成任务 / 兜底 / 定时配置时统一注入。
11849
12032
  function lanElectronHost(opts) {
@@ -11857,7 +12040,7 @@ function lanElectronHost(opts) {
11857
12040
  function lanTaskCommandNeedsElectronEnv(text) {
11858
12041
  const t = String(text || '');
11859
12042
  if (!t || /ELECTRON_RUN_AS_NODE/.test(t)) return false;
11860
- if (/electron|yottacode/i.test(t)) return true;
12043
+ if (/electron|yottaweave/i.test(t)) return true;
11861
12044
  if (lanElectronHost({})) {
11862
12045
  const exe = String(process.execPath || '');
11863
12046
  if (exe && t.toLowerCase().indexOf(exe.toLowerCase()) !== -1) return true;
@@ -11994,11 +12177,11 @@ function lanWindowsRunSchtasks(opts, args) {
11994
12177
  };
11995
12178
  }
11996
12179
  }
11997
- const r = lanSpawn(lanSchTasksBin(), args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
12180
+ const r = lanSpawn(lanSchTasksBin(), args, { encoding: 'buffer', stdio: ['ignore', 'pipe', 'pipe'] });
11998
12181
  return {
11999
12182
  status: r.error ? 1 : r.status,
12000
- stdout: String(r.stdout || ''),
12001
- stderr: String(r.stderr || (r.error && r.error.message) || ''),
12183
+ stdout: decodeWindowsConsoleOutput(r.stdout),
12184
+ stderr: decodeWindowsConsoleOutput(r.stderr || (r.error && r.error.message) || ''),
12002
12185
  };
12003
12186
  }
12004
12187
  function lanWindowsTaskUser(opts) {
@@ -12029,7 +12212,7 @@ function lanWindowsTaskXml(opts) {
12029
12212
  // 让 node/脚本/日志路径里的空格与中文都能安全传递;S4U 非交互会话下不弹窗口。
12030
12213
  // 注意:重定向 `2>&1` 的 & 在 XML 文本里必须写成 &amp;(DOM 解码后仍是 2>&1),
12031
12214
  // 否则 schtasks 报 "The task XML is malformed"。
12032
- // v0.22.5: Electron 宿主(YottaCode shim)下先 set ELECTRON_RUN_AS_NODE=1,
12215
+ // v0.22.5: Electron 宿主(YottaWeave shim)下先 set ELECTRON_RUN_AS_NODE=1,
12033
12216
  // 否则任务会拉起桌面程序本体(GUI)而不是 Node 服务。
12034
12217
  const envPrefix = lanElectronHost(opts) ? 'set "ELECTRON_RUN_AS_NODE=1" &amp;&amp; ' : '';
12035
12218
  const inner = envPrefix + '"' + xmlEscape(nodePath) + '" "' + xmlEscape(scriptPath) + '" serve --profile "' + xmlEscape(profilePath) + '" --host ' + host + ' --port ' + port
@@ -12067,7 +12250,21 @@ function lanWindowsTaskXml(opts) {
12067
12250
  }
12068
12251
  function lanWindowsEnableCore(opts) {
12069
12252
  opts = opts || {};
12070
- const profileResult = lanWriteServeProfile(opts);
12253
+ const sidResult = lanWindowsTaskSid(opts);
12254
+ if (sidResult.error) return { error: true, phase: 'sid', text: sidResult.text };
12255
+ const taskSid = sidResult.sid;
12256
+ let taskName = '';
12257
+ try {
12258
+ taskName = lanWindowsTaskName({ sid: taskSid });
12259
+ } catch (e) {
12260
+ return { error: true, phase: 'sid', text: String((e && e.message) || e) };
12261
+ }
12262
+ const targetCheck = lanWindowsTargetTaskCheck(opts, taskName, taskSid);
12263
+ if (targetCheck.error) return { error: true, phase: 'target', taskName: taskName, userSid: taskSid, text: targetCheck.text };
12264
+ const profileResult = lanWriteServeProfile(Object.assign({}, opts, {
12265
+ userId: lanWindowsTaskUser(opts),
12266
+ userSid: taskSid,
12267
+ }));
12071
12268
  if (profileResult.error) return { error: true, phase: 'profile', text: profileResult.text };
12072
12269
  const trigger = opts.onstart ? 'onstart' : 'onlogon';
12073
12270
  const host = opts.host || '0.0.0.0';
@@ -12076,15 +12273,45 @@ function lanWindowsEnableCore(opts) {
12076
12273
  const scriptPath = opts.scriptPath || runtimeManagedScript();
12077
12274
  const logPath = lanLogPath(opts);
12078
12275
  const userId = lanWindowsTaskUser(opts);
12276
+ if (targetCheck.mode === 'startup') {
12277
+ try {
12278
+ lanInstallStartup(Object.assign({}, opts, { profilePath: profileResult.profilePath }));
12279
+ } catch (e) {
12280
+ return {
12281
+ error: true,
12282
+ mode: 'startup',
12283
+ phase: 'startup',
12284
+ taskName: taskName,
12285
+ userSid: taskSid,
12286
+ reason: targetCheck.reason,
12287
+ accessDenied: !!targetCheck.accessDenied,
12288
+ text: String((e && e.message) || e),
12289
+ };
12290
+ }
12291
+ return {
12292
+ error: false,
12293
+ mode: 'startup',
12294
+ taskName: taskName,
12295
+ userSid: taskSid,
12296
+ trigger: trigger,
12297
+ reason: targetCheck.reason,
12298
+ accessDenied: !!targetCheck.accessDenied,
12299
+ legacyMigration: 'none',
12300
+ vbsPath: lanVbsPath(opts),
12301
+ cmdPath: lanAutostartCmdPath(opts),
12302
+ logPath: logPath,
12303
+ profilePath: profileResult.profilePath,
12304
+ };
12305
+ }
12079
12306
  const xml = lanWindowsTaskXml({ trigger: trigger, host: host, port: port, nodePath: nodePath, scriptPath: scriptPath, logPath: logPath, profilePath: profileResult.profilePath, userId: userId, electronHost: opts.electronHost });
12080
12307
  const xmlDir = opts.xmlDir || process.env.YOTTA_LAN_TASK_XML_DIR || os.tmpdir();
12081
- const xmlPath = opts.xmlPath || path.join(xmlDir, LAN_TASK_NAME + '-task-' + process.pid + '-' + Date.now() + '.xml');
12308
+ const xmlPath = opts.xmlPath || path.join(xmlDir, taskName + '-task-' + process.pid + '-' + Date.now() + '.xml');
12082
12309
  let failure = null;
12083
12310
  try {
12084
12311
  fs.mkdirSync(path.dirname(xmlPath), { recursive: true });
12085
12312
  // UTF-16LE + BOM:与 schtasks /query /xml 导出格式一致,schtasks /create /xml 必然可读
12086
12313
  fs.writeFileSync(xmlPath, '\ufeff' + xml, 'utf16le');
12087
- const r = lanWindowsRunSchtasks(opts, ['/create', '/tn', LAN_TASK_NAME, '/xml', xmlPath, '/f']);
12314
+ const r = lanWindowsRunSchtasks(opts, ['/create', '/tn', taskName, '/xml', xmlPath, '/f']);
12088
12315
  if (r.status !== 0) failure = String(r.stderr || r.stdout || '').trim() || ('schtasks 退出码 ' + r.status);
12089
12316
  } catch (e) {
12090
12317
  failure = String((e && e.message) || e);
@@ -12092,21 +12319,36 @@ function lanWindowsEnableCore(opts) {
12092
12319
  try { fs.unlinkSync(xmlPath); } catch (e) { /* 临时 XML 清理尽力而为 */ }
12093
12320
  }
12094
12321
  if (!failure) {
12322
+ const migration = lanWindowsMigrateLegacyTask(opts, taskSid);
12095
12323
  let removedStartup = [];
12096
12324
  try { removedStartup = lanRemoveStartupFiles(opts); } catch (e) { removedStartup = []; }
12097
- return { error: false, mode: 'task', taskName: LAN_TASK_NAME, trigger: trigger, logPath: logPath, profilePath: profileResult.profilePath, removedStartup: removedStartup };
12325
+ return {
12326
+ error: false,
12327
+ mode: 'task',
12328
+ taskName: taskName,
12329
+ userSid: taskSid,
12330
+ trigger: trigger,
12331
+ logPath: logPath,
12332
+ profilePath: profileResult.profilePath,
12333
+ removedStartup: removedStartup,
12334
+ legacyMigration: migration.status,
12335
+ legacyMigrationText: migration.text,
12336
+ };
12098
12337
  }
12099
12338
  try {
12100
- lanInstallStartup(opts);
12339
+ lanInstallStartup(Object.assign({}, opts, { profilePath: profileResult.profilePath }));
12101
12340
  } catch (e2) {
12102
- return { error: true, mode: 'startup', reason: failure, text: String((e2 && e2.message) || e2) };
12341
+ return { error: true, mode: 'startup', taskName: taskName, userSid: taskSid, reason: failure, text: String((e2 && e2.message) || e2) };
12103
12342
  }
12104
12343
  return {
12105
12344
  error: false,
12106
12345
  mode: 'startup',
12346
+ taskName: taskName,
12347
+ userSid: taskSid,
12107
12348
  trigger: trigger,
12108
12349
  reason: failure,
12109
12350
  accessDenied: isSchtasksAccessDenied(failure),
12351
+ legacyMigration: 'none',
12110
12352
  vbsPath: lanVbsPath(opts),
12111
12353
  cmdPath: lanAutostartCmdPath(opts),
12112
12354
  logPath: logPath,
@@ -12343,17 +12585,28 @@ function cmdLanWinEnable(opts) {
12343
12585
  if (result.mode === 'task') {
12344
12586
  opts = Object.assign({}, opts, { profilePath: result.profilePath });
12345
12587
  const triggerText = result.trigger === 'onstart' ? '开机触发(无需登录)' : '登录触发';
12346
- console.log('已注册开机自启: 计划任务 ' + LAN_TASK_NAME + '(' + triggerText + ',后台静默运行,不弹窗口)');
12588
+ console.log('已注册开机自启: 计划任务 ' + result.taskName + '(' + triggerText + ',后台静默运行,不弹窗口)');
12347
12589
  console.log('运行命令: ' + lanTaskRunCmd(opts));
12348
12590
  console.log('服务 profile: ' + result.profilePath);
12349
12591
  console.log('日志: ' + result.logPath);
12350
12592
  if (result.removedStartup && result.removedStartup.length) {
12351
12593
  console.log('已清理旧 Startup 兜底文件 ' + result.removedStartup.length + ' 个(避免双份自启)');
12352
12594
  }
12595
+ if (result.legacyMigration === 'migrated') console.log('已迁移旧固定任务 ' + LAN_TASK_NAME_LEGACY);
12596
+ else if (result.legacyMigration === 'retained-foreign') console.log('保留旧固定任务 ' + LAN_TASK_NAME_LEGACY + '(属于其他用户)');
12597
+ else if (result.legacyMigration === 'retained-unknown') console.log('保留旧固定任务 ' + LAN_TASK_NAME_LEGACY + '(归属无法确认或迁移未完成)');
12353
12598
  console.log('备注: 服务不会立刻启动,需重启/重新登录后自动启动;如需现在运行请执行 yotta-memory serve');
12354
12599
  return;
12355
12600
  }
12356
12601
  if (result.error) {
12602
+ if (result.phase === 'sid') {
12603
+ console.error('无法确定当前 Windows 用户 SID,拒绝注册开机自启: ' + String(result.text || '').split(/\r?\n/)[0]);
12604
+ process.exit(1);
12605
+ }
12606
+ if (result.phase === 'target') {
12607
+ console.error('目标计划任务归属校验失败,拒绝注册开机自启: ' + String(result.text || '').split(/\r?\n/)[0]);
12608
+ process.exit(1);
12609
+ }
12357
12610
  if (result.phase === 'profile') {
12358
12611
  console.error('服务 profile 写入失败,拒绝注册开机自启: ' + String(result.text || '').split(/\r?\n/)[0]);
12359
12612
  process.exit(1);
@@ -12380,25 +12633,79 @@ function cmdLanWinDisable() {
12380
12633
  console.error('lan 命令当前仅支持 Windows(计划任务 / Startup 自启);本机平台: ' + lanPlatform());
12381
12634
  process.exit(2);
12382
12635
  }
12636
+ const sidResult = lanWindowsTaskSid({});
12637
+ if (sidResult.error) {
12638
+ console.error('无法确定当前 Windows 用户 SID,拒绝删除计划任务: ' + sidResult.text);
12639
+ process.exit(1);
12640
+ }
12641
+ const taskName = lanWindowsTaskName({ sid: sidResult.sid });
12383
12642
  let sawError = false;
12384
12643
  let removedAny = false;
12385
- const del = lanWindowsRunSchtasks({}, ['/delete', '/tn', LAN_TASK_NAME, '/f']);
12386
- if (del.status === 0) {
12387
- console.log('已移除开机自启计划任务 ' + LAN_TASK_NAME);
12388
- removedAny = true;
12389
- } else {
12390
- const msg = String(del.stderr || del.stdout || '');
12391
- if (!/cannot find the (path|file)|没有找到|找不到|不存在/i.test(msg)) {
12392
- console.error('移除计划任务失败: ' + msg.split(/\r?\n/)[0]);
12393
- if (isSchtasksAccessDenied(msg)) console.error('(当前非管理员,无法移除管理员注册的计划任务;请用管理员终端执行 yotta-memory lan disable)');
12644
+ let retainedAny = false;
12645
+ const target = lanWindowsTaskQuery({}, taskName);
12646
+ if (target.status === 'found') {
12647
+ const targetOwnership = lanWindowsTaskOwnership({
12648
+ xml: target.xml,
12649
+ taskSid: sidResult.sid,
12650
+ currentUser: lanWindowsTaskUser({}),
12651
+ });
12652
+ if (targetOwnership.status === 'current') {
12653
+ const del = lanWindowsRunSchtasks({}, ['/delete', '/tn', taskName, '/f']);
12654
+ if (del.status === 0) {
12655
+ console.log('已移除开机自启计划任务 ' + taskName);
12656
+ removedAny = true;
12657
+ } else {
12658
+ const msg = String(del.stderr || del.stdout || '');
12659
+ if (!isSchtasksTaskMissing(msg)) {
12660
+ console.error('移除计划任务失败: ' + msg.split(/\r?\n/)[0]);
12661
+ if (isSchtasksAccessDenied(msg)) console.error('(当前非管理员,无法移除管理员注册的计划任务;请用管理员终端执行 yotta-memory lan disable)');
12662
+ sawError = true;
12663
+ }
12664
+ }
12665
+ } else {
12666
+ console.error('拒绝删除计划任务 ' + taskName + ':归属无法证明属于当前用户' + (targetOwnership.status === 'foreign' ? '(属于其他用户)' : '') + '。');
12394
12667
  sawError = true;
12395
12668
  }
12669
+ } else if (target.status === 'unknown') {
12670
+ console.error('移除计划任务失败: ' + String(target.text || '').split(/\r?\n/)[0]);
12671
+ if (isSchtasksAccessDenied(target.text)) console.error('(当前非管理员,无法移除管理员注册的计划任务;请用管理员终端执行 yotta-memory lan disable)');
12672
+ sawError = true;
12673
+ }
12674
+ const legacy = lanWindowsTaskQuery({}, LAN_TASK_NAME_LEGACY);
12675
+ if (legacy.status === 'found') {
12676
+ const ownership = lanWindowsTaskOwnership({
12677
+ xml: legacy.xml,
12678
+ taskSid: sidResult.sid,
12679
+ currentUser: lanWindowsTaskUser({}),
12680
+ });
12681
+ if (ownership.status === 'current') {
12682
+ const legacyDel = lanWindowsRunSchtasks({}, ['/delete', '/tn', LAN_TASK_NAME_LEGACY, '/f']);
12683
+ if (legacyDel.status === 0) {
12684
+ console.log('已移除旧固定计划任务 ' + LAN_TASK_NAME_LEGACY);
12685
+ removedAny = true;
12686
+ } else {
12687
+ const msg = String(legacyDel.stderr || legacyDel.stdout || '');
12688
+ if (!isSchtasksTaskMissing(msg)) {
12689
+ console.error('移除旧固定计划任务失败: ' + msg.split(/\r?\n/)[0]);
12690
+ sawError = true;
12691
+ }
12692
+ }
12693
+ } else if (ownership.status === 'foreign') {
12694
+ console.log('保留旧固定计划任务 ' + LAN_TASK_NAME_LEGACY + '(属于其他用户)');
12695
+ retainedAny = true;
12696
+ } else {
12697
+ console.log('保留旧固定计划任务 ' + LAN_TASK_NAME_LEGACY + '(归属无法确认)');
12698
+ retainedAny = true;
12699
+ }
12700
+ } else if (legacy.status === 'unknown') {
12701
+ console.log('旧固定计划任务归属无法确认,已保留');
12702
+ retainedAny = true;
12396
12703
  }
12397
12704
  for (const f of lanRemoveStartupFiles()) {
12398
12705
  console.log('已移除 Startup 自启文件: ' + f);
12399
12706
  removedAny = true;
12400
12707
  }
12401
- if (!removedAny && !sawError) console.log('未启用: 未发现任何自启配置(计划任务与 Startup 文件均不存在)');
12708
+ if (!removedAny && !retainedAny && !sawError) console.log('未启用: 未发现任何自启配置(计划任务与 Startup 文件均不存在)');
12402
12709
  if (sawError) process.exit(1);
12403
12710
  }
12404
12711
  function cmdLanWinStatus() {
@@ -12406,51 +12713,100 @@ function cmdLanWinStatus() {
12406
12713
  console.log('lan 命令当前仅支持 Windows(计划任务 / Startup 自启);本机平台: ' + lanPlatform());
12407
12714
  return;
12408
12715
  }
12716
+ const sidResult = lanWindowsTaskSid({});
12717
+ const taskSid = sidResult.error ? '' : sidResult.sid;
12718
+ const taskName = taskSid ? lanWindowsTaskName({ sid: taskSid }) : '';
12409
12719
  let taskFound = false;
12720
+ let taskKnown = false;
12721
+ let legacyPresent = false;
12410
12722
  const profilePath = lanServeProfilePath();
12411
- const q = lanWindowsRunSchtasks({}, ['/query', '/tn', LAN_TASK_NAME, '/fo', 'LIST', '/v']);
12412
- if (q.status === 0) {
12413
- taskFound = true;
12414
- const xmlQ = lanWindowsRunSchtasks({}, ['/query', '/tn', LAN_TASK_NAME, '/xml']);
12415
- const xmlSaysS4U = xmlQ.status === 0 && /<LogonType>\s*S4U\s*<\/LogonType>/i.test(String(xmlQ.stdout || ''));
12416
- console.log('计划任务 ' + LAN_TASK_NAME + ': 已启用');
12417
- const re = /^(状态|Status|登录模式|Logon Mode|上次运行时间|Last Run Time|上次结果|Last Result|要运行的任务|Task To Run)\s*[:=]\s*(.+)$/;
12418
- let logonMode = '';
12419
- let taskRun = '';
12420
- for (const line of String(q.stdout).split(/\r?\n/)) {
12421
- const m = re.exec(line.trim());
12422
- if (!m) continue;
12423
- console.log(' ' + m[1] + ': ' + m[2]);
12424
- if (/^(登录模式|Logon Mode)$/.test(m[1])) logonMode = m[2];
12425
- if (/^(要运行的任务|Task To Run)$/.test(m[1])) taskRun = m[2];
12426
- }
12427
- if (/interactive|交互式/i.test(logonMode) && !xmlSaysS4U) {
12428
- console.log(' 提示: 登录模式为交互式(仅登录时运行,且在登录会话会弹窗口)——这是旧版任务;请重新执行 yotta-memory lan enable 修复为后台静默');
12429
- }
12430
- if (lanTaskCommandNeedsElectronEnv(taskRun)) {
12431
- console.log(' 警告: 任务命令指向 Electron 可执行文件(如 YottaCode.exe)但缺少 ELECTRON_RUN_AS_NODE —— 开机将拉起桌面程序而非服务;请重新执行 yotta-memory lan enable 修复');
12432
- }
12433
- if (taskRun && !/--profile(?:\s|$)/.test(taskRun)) {
12434
- console.log(' 警告: 任务命令未固定服务 profile,S4U / 无用户环境启动可能落到错误记忆库;请重新执行 yotta-memory lan enable 修复');
12435
- }
12436
- if (fs.existsSync(profilePath)) {
12437
- console.log(' 服务 profile: ' + profilePath);
12438
- const loaded = loadServeProfile(profilePath);
12439
- if (loaded.error) {
12440
- console.log(' 警告: ' + loaded.text);
12441
- } else {
12442
- console.log(' 记忆库: ' + loaded.profile.memoryHome);
12443
- console.log(' 运行时: ' + loaded.profile.runtimeHome);
12444
- const drift = serveProfileDrift(loaded.profile);
12445
- if (drift.length) {
12446
- console.log(' 警告: 服务 profile 与当前配置漂移(' + drift.join(', ') + '),请重新执行 yotta-memory lan enable');
12447
- }
12723
+ if (sidResult.error) {
12724
+ console.log('计划任务: 无法确定当前 Windows 用户 SID,未执行任务查询。' + sidResult.text);
12725
+ } else {
12726
+ const q = lanWindowsRunSchtasks({}, ['/query', '/tn', taskName, '/fo', 'LIST', '/v']);
12727
+ const qText = String(q.stderr || q.stdout || '');
12728
+ if (q.status === 0) {
12729
+ taskKnown = true;
12730
+ taskFound = true;
12731
+ const xmlQ = lanWindowsTaskQuery({}, taskName);
12732
+ const xmlSaysS4U = xmlQ.status === 'found' && /<LogonType>\s*S4U\s*<\/LogonType>/i.test(String(xmlQ.xml || ''));
12733
+ const targetOwnership = lanWindowsTaskOwnership({
12734
+ xml: xmlQ.status === 'found' ? xmlQ.xml : '',
12735
+ taskSid: taskSid,
12736
+ currentUser: lanWindowsTaskUser({}),
12737
+ });
12738
+ console.log('计划任务 ' + taskName + ': 已启用');
12739
+ if (targetOwnership.status !== 'current') {
12740
+ console.log(' 警告: 计划任务归属无法证明属于当前用户' + (targetOwnership.status === 'foreign' ? '(属于其他用户)' : '') + ',请勿覆盖或停止该任务');
12741
+ }
12742
+ const re = /^(状态|Status|登录模式|Logon Mode|上次运行时间|Last Run Time|上次结果|Last Result|要运行的任务|Task To Run)\s*[:=]\s*(.+)$/;
12743
+ let logonMode = '';
12744
+ let taskRun = '';
12745
+ for (const line of String(q.stdout).split(/\r?\n/)) {
12746
+ const m = re.exec(line.trim());
12747
+ if (!m) continue;
12748
+ console.log(' ' + m[1] + ': ' + m[2]);
12749
+ if (/^(登录模式|Logon Mode)$/.test(m[1])) logonMode = m[2];
12750
+ if (/^(要运行的任务|Task To Run)$/.test(m[1])) taskRun = m[2];
12448
12751
  }
12752
+ if (/interactive|交互式/i.test(logonMode) && !xmlSaysS4U) {
12753
+ console.log(' 提示: 登录模式为交互式(仅登录时运行,且在登录会话会弹窗口)——这是旧版任务;请重新执行 yotta-memory lan enable 修复为后台静默');
12754
+ }
12755
+ if (lanTaskCommandNeedsElectronEnv(taskRun)) {
12756
+ console.log(' 警告: 任务命令指向 Electron 可执行文件(如 YottaWeave.exe)但缺少 ELECTRON_RUN_AS_NODE —— 开机将拉起桌面程序而非服务;请重新执行 yotta-memory lan enable 修复');
12757
+ }
12758
+ if (taskRun && !/--profile(?:\s|$)/.test(taskRun)) {
12759
+ console.log(' 警告: 任务命令未固定服务 profile,S4U / 无用户环境启动可能落到错误记忆库;请重新执行 yotta-memory lan enable 修复');
12760
+ }
12761
+ } else if (isSchtasksTaskMissing(qText)) {
12762
+ taskKnown = true;
12763
+ console.log('计划任务 ' + taskName + ': 未启用');
12764
+ } else {
12765
+ console.log('计划任务 ' + taskName + ': 状态未知(' + qText.split(/\r?\n/)[0] + ')');
12766
+ }
12767
+ }
12768
+ if (fs.existsSync(profilePath)) {
12769
+ console.log('服务 profile: ' + profilePath);
12770
+ const loaded = loadServeProfile(profilePath);
12771
+ if (loaded.error) {
12772
+ console.log(' 警告: ' + loaded.text);
12449
12773
  } else {
12450
- console.log(' 警告: 服务 profile 不存在: ' + profilePath + ';请重新执行 yotta-memory lan enable');
12774
+ console.log(' 记忆库: ' + loaded.profile.memoryHome);
12775
+ console.log(' 运行时: ' + loaded.profile.runtimeHome);
12776
+ const profileSid = canonicalWindowsSid(loaded.profile.userSid);
12777
+ if (!profileSid) {
12778
+ console.log(' 警告: 服务 profile 缺少 userSid,请重新执行 yotta-memory lan enable');
12779
+ } else if (taskSid && profileSid !== taskSid) {
12780
+ console.log(' 警告: 服务 profile userSid 与当前用户不一致,请重新执行 yotta-memory lan enable');
12781
+ } else if (taskName && lanWindowsTaskName({ sid: profileSid }) !== taskName) {
12782
+ console.log(' 警告: 服务 profile userSid 派生任务名与当前任务名不一致,请重新执行 yotta-memory lan enable');
12783
+ }
12784
+ const drift = serveProfileDrift(loaded.profile);
12785
+ if (drift.length) {
12786
+ console.log(' 警告: 服务 profile 与当前配置漂移(' + drift.join(', ') + '),请重新执行 yotta-memory lan enable');
12787
+ }
12451
12788
  }
12452
12789
  } else {
12453
- console.log('计划任务 ' + LAN_TASK_NAME + ': 未启用');
12790
+ console.log(' 警告: 服务 profile 不存在: ' + profilePath + ';请重新执行 yotta-memory lan enable');
12791
+ }
12792
+ const legacy = lanWindowsTaskQuery({}, LAN_TASK_NAME_LEGACY);
12793
+ if (legacy.status === 'found') {
12794
+ legacyPresent = true;
12795
+ const ownership = lanWindowsTaskOwnership({
12796
+ xml: legacy.xml,
12797
+ taskSid: taskSid,
12798
+ currentUser: lanWindowsTaskUser({}),
12799
+ });
12800
+ if (ownership.status === 'current') {
12801
+ console.log('旧固定计划任务 ' + LAN_TASK_NAME_LEGACY + ': 属于当前用户,请重新执行 yotta-memory lan enable 迁移');
12802
+ } else if (ownership.status === 'foreign') {
12803
+ console.log('旧固定计划任务 ' + LAN_TASK_NAME_LEGACY + ': 属于其他用户,保留不动');
12804
+ } else {
12805
+ console.log('旧固定计划任务 ' + LAN_TASK_NAME_LEGACY + ': 归属无法确认,保留不动');
12806
+ }
12807
+ } else if (legacy.status === 'unknown') {
12808
+ legacyPresent = true;
12809
+ console.log('旧固定计划任务 ' + LAN_TASK_NAME_LEGACY + ': 状态无法确认,保留不动');
12454
12810
  }
12455
12811
  const vbsOk = lanFileHasMarker(lanVbsPath());
12456
12812
  const cmdOk = lanFileHasMarker(lanAutostartCmdPath());
@@ -12469,7 +12825,7 @@ function cmdLanWinStatus() {
12469
12825
  } else {
12470
12826
  console.log('Startup 静默自启(免管理员): 未启用');
12471
12827
  }
12472
- if (!taskFound && !vbsOk && !cmdOk) console.log('未启用任何开机自启(可用 yotta-memory lan enable 注册)');
12828
+ if (taskKnown && !taskFound && !vbsOk && !cmdOk && !legacyPresent) console.log('未启用任何开机自启(可用 yotta-memory lan enable 注册)');
12473
12829
  }
12474
12830
 
12475
12831
  function cmdLanEnable(opts) {
@@ -13716,6 +14072,11 @@ module.exports = {
13716
14072
  runtimeDoctorCore: runtimeDoctorCore,
13717
14073
  runtimeEnsureForManagedTask: runtimeEnsureForManagedTask,
13718
14074
  runtimeRestartManagedServer: runtimeRestartManagedServer,
14075
+ canonicalWindowsSid: canonicalWindowsSid,
14076
+ lanWindowsTaskSid: lanWindowsTaskSid,
14077
+ lanWindowsTaskName: lanWindowsTaskName,
14078
+ lanWindowsTaskOwnership: lanWindowsTaskOwnership,
14079
+ lanWindowsTaskQuery: lanWindowsTaskQuery,
13719
14080
  lanServeProfilePath: lanServeProfilePath,
13720
14081
  resolveProfilePath: resolveProfilePath,
13721
14082
  lanWriteServeProfile: lanWriteServeProfile,
@@ -13733,7 +14094,9 @@ module.exports = {
13733
14094
  lanInstallStartup: lanInstallStartup,
13734
14095
  lanRemoveStartupFiles: lanRemoveStartupFiles,
13735
14096
  lanFileHasMarker: lanFileHasMarker,
14097
+ isSchtasksTaskMissing: isSchtasksTaskMissing,
13736
14098
  isSchtasksAccessDenied: isSchtasksAccessDenied,
14099
+ decodeWindowsConsoleOutput: decodeWindowsConsoleOutput,
13737
14100
  lanServeArgs: lanServeArgs,
13738
14101
  lanSpawn: lanSpawn,
13739
14102
  lanPlatform: lanPlatform,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yottameta/yotta-memory",
3
- "version": "0.24.3",
3
+ "version": "0.24.5",
4
4
  "description": "Yuanyi (元忆) — boundary-aware, file-based memory for AI agents. File-based, zero-dependency, diff/rollback-able; FACT/PREF/BOUND/COMMIT types (public shared / private isolated), user-level + project-level storage; v0.12 reliability baseline (init guard, trash-based deletion, independent-volume backup/list/doctor/restore, start-of-work doctor, transactional snapshots before destructive writes), v0.10 consolidation (periodic summaries with provenance, near-duplicate auto-merge, per-type decay, batch audit + rollback), v0.9 recall quality + context focus + optional local embedding plugin, plus v0.8 semantic search, feedback loop, self-organization and distillation.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -3,7 +3,7 @@
3
3
  "slug": "yotta-memory",
4
4
  "name": "元忆",
5
5
  "package": "@yottameta/yotta-memory",
6
- "version": "0.24.3",
6
+ "version": "0.24.5",
7
7
  "trust": "yottameta",
8
8
  "install": {
9
9
  "idempotent": true