personal-bot 0.2.17 → 0.2.18

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.
@@ -6,12 +6,12 @@
6
6
  "plugins": [
7
7
  {
8
8
  "name": "personal-bot",
9
- "version": "0.2.17",
9
+ "version": "0.2.18",
10
10
  "description": "Workspace materials, skills, and native experts.",
11
11
  "source": {
12
12
  "source": "npm",
13
13
  "package": "personal-bot",
14
- "version": "0.2.17"
14
+ "version": "0.2.18"
15
15
  }
16
16
  }
17
17
  ]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "personal-bot",
3
- "version": "0.2.17",
3
+ "version": "0.2.18",
4
4
  "description": "Workspace materials, skills, and native experts.",
5
5
  "skills": [
6
6
  "./resources/skills",
package/CONTEXT.md CHANGED
@@ -14,7 +14,19 @@
14
14
 
15
15
  **工作区记忆**:跨会话查找、使用与修正资料的能力,同一主题维护一份当前正文。
16
16
 
17
- **历史消息树(history)**:Pi/dsh 提供的问答原文、分层摘要、父子关系和来源引用检索资料,兼容读取既有 Claude 归档。完整工具日志、图片与会话恢复由原生存储负责。
17
+ **原始问答**:用户输入(含人工补充)与最终答复组成的问答单元,不含工具调用、工具结果、推理和中间过程。
18
+ _Avoid_: 原始对话、完整会话
19
+
20
+ **原始问答归档**:Pi/dsh 保存的原始问答和已知的原生分支顺序,是摘要和记忆提取的基础资料。仅存于旧归档的问答也属于这份资料;只有原生来源的索引更新问答与分支。
21
+ _Avoid_: history 原文、原始文件
22
+
23
+ **派生摘要归档**:从原始问答归档生成、按提取类型分开保存的摘要资料;可以失效、重建和覆盖,不修改原始问答归档。
24
+ _Avoid_: 摘要原文、混合归档
25
+
26
+ **提取类型**:从原始问答归档生成的一类派生内容,例如当前的分层摘要;每类独立维护。
27
+ _Avoid_: 摘要维度、记忆层
28
+
29
+ **历史消息树(history)**:Pi/dsh 提供的原始问答归档、派生摘要归档、父子关系和来源引用检索资料,兼容读取既有 Claude 归档。完整工具日志、图片与会话恢复由原生存储负责。
18
30
 
19
31
  **资料维护**:根据任务进展更新相关说明,归集成果,提炼可复用的方法与口径。
20
32
 
package/README.md CHANGED
@@ -155,7 +155,7 @@ Use `pi --resume` to select the main session explicitly; `pi --continue` can sel
155
155
  | `AGENTS.md` | Navigation and working agreements |
156
156
  | `areas/`, `projects/` | Long-term goals, tasks, conclusions, and deliverables |
157
157
  | `knowledge/` | Reusable concepts, methods, and analysis definitions |
158
- | `.pbot/history/` | Pi/dsh exchanges, summaries, and node links; preserved Claude archives |
158
+ | `.pbot/history/` | Pi/dsh original exchanges in `raw/` and derived summaries in `summary/`; preserved Claude archives |
159
159
  | `providers/` | External tool guidance, data definitions, and sources |
160
160
  | `scratch/` | Temporary scripts, calculation data, downloads, and environments |
161
161
  | `agents/` | Role additions |
@@ -165,7 +165,7 @@ Existing layouts and agreements take precedence. Fetch queryable data when neede
165
165
 
166
166
  ## Updates and operating scope
167
167
 
168
- Current release: **0.2.17**. Update through the host's native package manager. For a local Pi source, update the checkout, run `npm ci --ignore-scripts` when dependencies change, then reload or restart. Stop active specialists before changing versions. Recreate specialists across compatibility lines; existing materials, history, and backups are preserved.
168
+ Current release: **0.2.18**. Update through the host's native package manager. For a local Pi source, update the checkout, run `npm ci --ignore-scripts` when dependencies change, then reload or restart. Stop active specialists before changing versions. Recreate specialists across compatibility lines; existing materials, history, and backups are preserved.
169
169
 
170
170
  Operations follow the user's request, existing agreements, and required confirmations. Bash, Python, MCP, and extensions use the actual account and credential permissions. Enforce hard limits through read-only credentials, service controls, or restricted environments. Trades, transfers, and ledger changes require authorization for those operations. After cancellation, timeout, or disconnection, query native status before retrying to avoid duplicate execution.
171
171
 
package/README.zh-CN.md CHANGED
@@ -155,7 +155,7 @@ Pi 主会话恢复用 `pi --resume` 明确选择;`pi --continue` 可能选中
155
155
  | `AGENTS.md` | 资料导航与工作约定 |
156
156
  | `areas/`、`projects/` | 长期目标、任务、结论与交付物 |
157
157
  | `knowledge/` | 可复用的概念、方法与口径 |
158
- | `.pbot/history/` | Pi/dsh 问答原文、摘要与节点关系,以及保留的 Claude 归档 |
158
+ | `.pbot/history/` | Pi/dsh 的 `raw/` 保存原始问答,`summary/` 保存派生摘要;既有 Claude 归档保留 |
159
159
  | `providers/` | 外部工具的使用说明、数据口径与来源 |
160
160
  | `scratch/` | 临时脚本、计算数据、下载与运行环境 |
161
161
  | `agents/` | 职责补充 |
@@ -165,7 +165,7 @@ Pi 主会话恢复用 `pi --resume` 明确选择;`pi --continue` 可能选中
165
165
 
166
166
  ## 更新与操作范围
167
167
 
168
- 当前版本为 **0.2.17**。通过宿主原生包管理更新;本地 Pi 来源更新源码,依赖变化后运行 `npm ci --ignore-scripts`,再重载或重启。更换版本前停止活动专家;不同兼容线的专家需重新创建,旧资料、历史和备份保留。
168
+ 当前版本为 **0.2.18**。通过宿主原生包管理更新;本地 Pi 来源更新源码,依赖变化后运行 `npm ci --ignore-scripts`,再重载或重启。更换版本前停止活动专家;不同兼容线的专家需重新创建,旧资料、历史和备份保留。
169
169
 
170
170
  操作按用户请求、已有约定和必要确认执行。Bash、Python、MCP 和扩展使用实际账户与凭据权限;硬限制应由只读凭据、服务端控制或受限环境提供。交易、转账和账本修改需要相应授权。取消、超时或断连后,先查原生状态再决定是否重试,避免重复执行。
171
171
 
@@ -77,9 +77,16 @@ I/O 失败后当前文件实例停止后续写入,不能因下一次读取成
77
77
 
78
78
  ## 历史索引
79
79
 
80
- 历史存档统一保存在工作区 `.pbot/history/`,按 host 与原生 session ID 关联会话。持久格式的顶层必填 host 继续接受 pi、dsh 或 claude,文件名与根 ID 一致。归档包含问答、来源消息 ID、分支内四叉摘要与父子关系,复用原子 JSON 写入。Pi/dsh 分别使用 `.write-pi`、`.write-dsh` 短锁,只更新自己的来源;既有 Claude 归档保持只读,旧 `.write-claude` 记录不由标准插件接管。
80
+ 工作区 `.pbot/history/` 按 `host` 与原生 `sessionId` 关联会话,使用已有根 `id` 命名文件。
81
81
 
82
- 原生会话不可用时仍可查询归档,复制到其他目录或机器后仍可读取。Pi/dsh 重新发现原生会话时复用原节点,缺失来源、compaction 或部分扫描不删除已归档分支与原文。Pi/dsh 迁移本来源的旧目录,并只读查询对方尚在旧目录的归档;不新增 Claude 配置或历史迁移。收录范围与查询见[历史对话](history.md)。
82
+ | 相对路径 | 内容 | 写入时机 |
83
+ | --- | --- | --- |
84
+ | `raw/<id>.json` | 原始问答归档:来源宿主、会话标识与名称、扁平的 `exchanges`,以及由问答 ID 组成的已知原生分支 `branches`。每条问答只含 ID、来源消息 ID、正文、起止时间和完成状态 | 首次纳入旧档,或原生索引发现变化 |
85
+ | `summary/<id>.json` | 分层摘要归档:摘要正文、状态、覆盖范围及有序子节点 ID,通过 ID 引用问答或下层摘要 | 承接旧摘要、保存新摘要或使受影响的摘要失效 |
86
+
87
+ `exchanges` 的排列不代表对话先后。按分支提取时读取 `branches`;只剩旧档时它可为空,逐条提取仍可使用全部问答。`raw/` 不保存派生字段。未命名会话的预览、会话根和反向导航在查询时生成。新提取类型使用与 `raw/` 同级的独立目录,例如未来的 `memory/<id>.json`;当前只写 `raw/` 和 `summary/` 两类归档。
88
+
89
+ Pi/dsh 分别使用 `.write-pi`、`.write-dsh` 短锁,只拆分和更新本来源;对方仍在旧目录或采用混合格式时照常只读查询。迁移先发布已有摘要,再发布原始问答;两者均已落盘才清理本来源的旧文件。顶层混合归档和先前顶层原文配 `hierarchical/` 的布局均按原 ID 迁移,文件冲突时保留待核对的资料。既有 Claude 混合归档和旧 `.write-claude` 不由标准插件接管。用户操作见[历史对话](history.md)。
83
90
 
84
91
  ## 历史与复制
85
92
 
package/docs/history.md CHANGED
@@ -41,14 +41,12 @@ Pi/dsh 读取这些现成归档,不扫描 Claude transcript 或团队文件,
41
41
 
42
42
  新人工输入、下一模型步骤、所属资源关闭或会话切换会取消当前整理。失败保留待处理内容与警告,下次正常交互结束再试。超长输入分段概括再合并,完整原文保留;摘要失败不妨碍原文查询。来源扫描错误与摘要错误分别保留,刷新成功不会掩盖尚未修复的摘要失败。
43
43
 
44
- 摘要产生额外模型调用。原生上下文、压缩、模型路由和认证继续由宿主管理。
44
+ 摘要产生额外模型调用。多个进程同时整理同一组时可能重复调用模型,提交时只保存仍匹配当前输入的结果。原生上下文、压缩、模型路由和认证继续由宿主管理。
45
45
 
46
- ## 存储与并发
46
+ ## 保存、迁移与复制
47
47
 
48
- 历史归档统一保存在 `.pbot/history/<id>.json`,顶层必填 `host` 标明 pi、dsh 或 claude。各来源共用格式,保存问答文本、来源 ID、节点关系与摘要,文件名与根 ID 一致。目录决定工作区,读取器按 host 筛选;Pi/dsh 只收录和整理自己的来源,Claude 来源保持只读。复制 `.pbot/history/` 即可查询现成内容;原生恢复仍需所属宿主的会话数据,工具日志和附件二进制不在归档内。
48
+ Pi/dsh 把原始问答保存在 `.pbot/history/raw/<id>.json`,分层摘要保存在 `.pbot/history/summary/<id>.json`。每条问答只保存一次,`raw/` 不含摘要、记忆或提取状态。生成、重算或丢失摘要都不会改写问答文件。摘要文件不可读时,查询会给出警告,问答原文仍可搜索和读取。
49
49
 
50
- Pi/dsh 分别使用独立短写锁 `.write-pi`、`.write-dsh`。原生扫描和模型调用在锁外,提交时重读最新归档;过时扫描不覆盖新原文,缺失来源或部分分支不删除已归档节点。整理调用在内存保留节点、子节点和原文快照,提交前核对精确结构与取消信号,过期或已取消结果不保存。多个进程可能产生重复模型调用,已提交摘要仍由短锁与提交核验保护。损坏文件单独警告,其他归档继续查询。
50
+ 首次刷新旧归档时,Pi/dsh 各自拆分本来源已保存的问答和摘要,不需要重新调用模型。即使只剩旧归档,问答仍纳入原始资料,原来的 ID、摘要正文和下级链接继续可用。旧归档没有完整记录原生分支顺序:保留既有分组,不按时间拼接问答。找回原生会话后再补齐观察到的分支,依赖顺序的新分组只使用已知分支。
51
51
 
52
- 服务位于 services/history,负责分组、查询、摘要准备与提交;integrations/pi、dsh 的历史适配负责原生投影,storage/history-files 负责校验、短锁与原子发布。Pi/dsh 迁移自身的旧历史目录,并只读查询对方仍在旧目录的归档;不新增 Claude 旧目录迁移。命令和工具调用同一服务;查询使用全文扫描,不增加数据库或向量索引。
53
-
54
- 这些归档是用户历史资料。原生数据还在时可以重新提取;原生数据已不可用时,删除归档会失去这份历史。复制前停止原工作区的活动写入,不支持多机同时写同步目录。
52
+ 搬迁或备份时,先停止原工作区的活动写入,再复制整个 `.pbot/history/`,以同时带走问答、各来源的摘要和旧归档。如需回退到只识别混合格式的版本,请在升级前备份。原生会话恢复仍需所属宿主的数据。原生来源已不可用时,归档可能是问答或旧摘要的唯一副本。文件布局见[文件存储](file-storage.md#历史索引)。
@@ -42,7 +42,7 @@ Claude command hook 是独立 Node 进程,只使用 Node 内置模块和共用
42
42
  | initializeWorkspace / prepareWorkspace | 初始化依次准备资料并写入共用启用配置;资料准备补建目录与根 AGENTS.md |
43
43
  | AgentService / AgentRun / AcpAgentRun | 专家实例、启动预约、代次、inbox、领取/进入/消费/完成与交付资格;ACP prompt 收尾、固定报告与确认关联;拒绝向被团队占用的成员发送私人任务 |
44
44
  | TeamService | Pi/dsh 的固定成员、公共消息、有限轮次、团队占用与暂停规则 |
45
- | HistoryService | 三来源问答索引、四叉摘要、查询、来源写锁与精确输入提交核验 |
45
+ | HistoryService | Pi/dsh 的原生问答索引、分层摘要与提交核验,跨来源查询 |
46
46
  | WorkspaceInstance / DshWorkspaces | Pi/dsh 工作区生命周期;dsh 按父会话装配,按工作区共享历史整理 |
47
47
 
48
48
  ## Claude 标准插件入口
@@ -94,9 +94,9 @@ Claude 根插件静态声明共用 skills、管理技能与 Markdown 原生专
94
94
 
95
95
  ## 历史查询
96
96
 
97
- Pi、dsh 共用 `.pbot/history/`,查询已有归档,各自只收录和整理本宿主来源。HistoryService 接收一个写来源及显式只读来源集合。顶层保存 `host`、`id`、`sessionId`、`name` 和 `nodes`;host 保留 pi、dsh、claude 数据兼容。Pi/dsh 分别使用 `.write-pi`、`.write-dsh` 短写锁,已有 Claude 归档可继续读取,Claude 插件不生成新归档。
97
+ Pi、dsh 的 HistoryService 各接收一个写来源和显式只读的其他来源。`indexHistory` 只合并原生问答与分支;观察到的后缀保留已有前缀,缺失来源不删除归档。查询视图把问答与独立保存的分层摘要组合起来,按已知分支规划四叉分组,补出会话根和反向导航。旧混合归档提供的摘要链接继续可查,但不作为原生分支证据。Claude 归档只读。布局见[文件存储](file-storage.md#历史索引)。
98
98
 
99
- 扫描与模型调用在短写锁外,提交时重读,拒绝过期原文或摘要覆盖。organize 在本次调用内保留节点与子节点的精确输入,提交前比较结构化数据并检查取消信号。查询不调用模型;正常主交互结束后在空闲阶段整理,新人工输入优先取消。来源消失或部分扫描不会删除已归档分支。有不可读归档时不为未识别会话重复分配根 ID,其他可读归档继续查询。实现与限制见[历史对话](history.md)。
99
+ 扫描与模型调用在来源短写锁外。索引提交时重读原始归档并比较扫描前的内容;若原文确有修订,先使依赖它的摘要及其上级失效,再发布修订后的问答。摘要提交持同一短锁,重读最新资料,逐项核对目标、子节点顺序和精确输入,检查取消信号,仅写派生文件。不可读的原始归档阻止为未识别会话另分配根 ID;单独的摘要文件损坏不阻止问答查询。查询不调用模型,后台整理触发时机见[历史对话](history.md)。
100
100
 
101
101
  ## 原生子会话存储
102
102
 
@@ -93,8 +93,7 @@ export function projectDshHistory(header, events, name = "") {
93
93
  finish(event.data.reason.kind === "completed");
94
94
  }
95
95
  finish();
96
- return { sessionId: header.id, name: name || exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "",
97
- branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
96
+ return { sessionId: header.id, name, branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
98
97
  }
99
98
  export class DshHistory {
100
99
  ctx;
@@ -12,18 +12,37 @@ export interface HistorySession {
12
12
  /** Earlier partial observations replaced along the same native branch or turn; never persisted. */
13
13
  supersededEntryIds?: string[];
14
14
  }
15
- export interface HistoryNode extends HistoryExchange {
15
+ export interface HistoryIdentity {
16
+ host: HistoryHost;
17
+ id: string;
18
+ sessionId: string;
19
+ }
20
+ export interface RawHistory extends HistoryIdentity {
21
+ name: string;
22
+ /** One entry per archived exchange; array order does not describe a conversation. */
23
+ exchanges: (HistoryExchange & {
24
+ id: string;
25
+ })[];
26
+ /** Ordered paths observed in the native source. Legacy exchanges can have no known path. */
27
+ branches: string[][];
28
+ }
29
+ export interface HistorySummary extends HistoryExchange {
16
30
  id: string;
17
- kind: "session" | "exchange" | "summary";
18
31
  level: number;
19
32
  children: string[];
20
- parents: string[];
21
33
  ready: boolean;
22
34
  }
23
- export interface HistoryRecord {
24
- host: HistoryHost;
25
- id: string;
26
- sessionId: string;
35
+ export interface HistoryArchive {
36
+ raw: RawHistory;
37
+ /** Empty if absent; null if the derived file is unreadable. */
38
+ summaries: HistorySummary[] | null;
39
+ }
40
+ export interface HistoryNode extends HistorySummary {
41
+ kind: "session" | "exchange" | "summary";
42
+ parents: string[];
43
+ }
44
+ /** Query view and legacy on-disk format. New writers persist raw exchanges and summaries separately. */
45
+ export interface HistoryRecord extends HistoryIdentity {
27
46
  name: string;
28
47
  nodes: HistoryNode[];
29
48
  }
@@ -0,0 +1,8 @@
1
+ import type { HistoryHost, HistoryRecord, HistorySession, HistorySummary, RawHistory } from "../../model/history.js";
2
+ /** Only a native observation can change exchanges or establish branch order. */
3
+ export declare function indexHistory(session: HistorySession, previous?: RawHistory, host?: HistoryHost): RawHistory;
4
+ /** Retire results using changed inputs before publishing a native correction. New groups need no disk write. */
5
+ export declare function retainHistorySummaries(before: RawHistory, after: RawHistory, summaries: HistorySummary[]): HistorySummary[];
6
+ /** The four-way tree is a query view, never the source of native branch order. */
7
+ export declare function historyView(raw: RawHistory, saved?: readonly HistorySummary[] | null): HistoryRecord;
8
+ export declare function historySummaries(record: HistoryRecord): HistorySummary[];
@@ -0,0 +1,134 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { requireThat } from "../../common/validation.js";
4
+ /** Each native entry has one predecessor. A shortened observation can extend a known path, not erase its prefix. */
5
+ function mergeBranches(previous, observed, removed) {
6
+ const parents = new Map();
7
+ for (const branch of [...previous, ...observed]) {
8
+ let parent;
9
+ for (const id of branch) {
10
+ if (removed.has(id)) {
11
+ parent = undefined;
12
+ continue;
13
+ }
14
+ if (parent !== undefined || !parents.has(id))
15
+ parents.set(id, parent);
16
+ parent = id;
17
+ }
18
+ }
19
+ const internal = new Set(parents.values()), seen = new Set(), branches = [];
20
+ for (const tip of parents.keys()) {
21
+ if (internal.has(tip))
22
+ continue;
23
+ const path = [];
24
+ for (let id = tip; id !== undefined; id = parents.get(id)) {
25
+ requireThat(path.length < parents.size, "历史分支包含循环引用。");
26
+ path.push(id);
27
+ seen.add(id);
28
+ }
29
+ branches.push(path.reverse());
30
+ }
31
+ requireThat(seen.size === parents.size, "历史分支包含循环引用。");
32
+ return branches;
33
+ }
34
+ /** Only a native observation can change exchanges or establish branch order. */
35
+ export function indexHistory(session, previous, host = previous?.host ?? "pi") {
36
+ requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
37
+ const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
38
+ const exchanges = new Map(previous?.exchanges.map(item => [item.id, item]));
39
+ const byEnd = new Map(previous?.exchanges.map(item => [item.entryIds.at(-1), item.id]));
40
+ const observed = new Map();
41
+ const branches = session.branches.map(branch => branch.map(value => {
42
+ const end = value.entryIds.at(-1);
43
+ const key = byEnd.get(end) ?? `${id}:0:${end}`;
44
+ if (!observed.has(end)) {
45
+ observed.set(end, value);
46
+ const before = exchanges.get(key);
47
+ // Compaction can leave only the last inputs and answer of an already archived exchange.
48
+ if (!(before && value.entryIds.length < before.entryIds.length &&
49
+ value.entryIds.every((entry, i) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + i]))) {
50
+ exchanges.set(key, { ...value, entryIds: [...value.entryIds], id: key });
51
+ }
52
+ }
53
+ return key;
54
+ }));
55
+ const removed = new Set();
56
+ for (const end of session.supersededEntryIds ?? []) {
57
+ const key = byEnd.get(end), item = key === undefined ? undefined : exchanges.get(key);
58
+ if (item && !item.completed && !observed.has(end) && [...observed.values()].some(value => item.entryIds.slice(0, -1).every(entry => value.entryIds.includes(entry)))) {
59
+ removed.add(item.id);
60
+ exchanges.delete(item.id);
61
+ }
62
+ }
63
+ return { host, id, sessionId: session.sessionId, name: session.name, exchanges: [...exchanges.values()],
64
+ branches: mergeBranches(previous?.branches ?? [], branches, removed) };
65
+ }
66
+ function span(children) {
67
+ const first = children[0], last = children.at(-1);
68
+ return { entryIds: [first.entryIds[0], last.entryIds.at(-1)], from: first.from, to: last.to, completed: children.every(child => child.completed) };
69
+ }
70
+ /** Retire results using changed inputs before publishing a native correction. New groups need no disk write. */
71
+ export function retainHistorySummaries(before, after, summaries) {
72
+ const inputs = new Map(after.exchanges.map(item => [item.id, item]));
73
+ const changed = new Set(before.exchanges.filter(item => !isDeepStrictEqual(item, inputs.get(item.id))).map(item => item.id));
74
+ if (!changed.size || !summaries.length)
75
+ return summaries;
76
+ const retained = new Map();
77
+ for (const item of [...summaries].sort((a, b) => a.level - b.level)) {
78
+ const children = item.children.map(id => inputs.get(id));
79
+ if (!children.length || !children.every(child => child !== undefined)) {
80
+ changed.add(item.id);
81
+ continue;
82
+ }
83
+ let summary = item;
84
+ if (item.children.some(id => changed.has(id))) {
85
+ summary = { ...item, ...span(children), text: "", ready: false };
86
+ changed.add(item.id);
87
+ }
88
+ retained.set(item.id, summary);
89
+ inputs.set(item.id, summary);
90
+ }
91
+ return summaries.flatMap(item => retained.get(item.id) ?? []);
92
+ }
93
+ /** The four-way tree is a query view, never the source of native branch order. */
94
+ export function historyView(raw, saved = []) {
95
+ const nodes = new Map(raw.exchanges.map(value => [value.id,
96
+ { ...value, kind: "exchange", level: 0, ready: true, children: [], parents: [] }]));
97
+ const stored = new Map(saved?.map(value => [value.id, value]));
98
+ const groups = new Map(stored);
99
+ for (const branch of raw.branches) {
100
+ let layer = branch.map(id => ({ id, end: nodes.get(id).entryIds.at(-1) }));
101
+ for (let level = 1; layer.length >= 4; level++) {
102
+ const next = [];
103
+ for (let i = 0; i + 4 <= layer.length; i += 4) {
104
+ const end = layer[i + 3].end, id = `${raw.id}:${level}:${end}`;
105
+ groups.set(id, { id, level, children: layer.slice(i, i + 4).map(child => child.id) });
106
+ next.push({ id, end });
107
+ }
108
+ layer = next;
109
+ }
110
+ }
111
+ for (const group of [...groups.values()].sort((a, b) => a.level - b.level)) {
112
+ const children = group.children.map(id => nodes.get(id));
113
+ if (!children.length || !children.every(child => child !== undefined))
114
+ continue;
115
+ const old = stored.get(group.id);
116
+ const summary = old && isDeepStrictEqual(old.children, group.children) && (!old.ready || children.every(child => child.ready)) ? old :
117
+ { ...group, ...span(children), text: "", ready: false };
118
+ nodes.set(group.id, { ...summary, kind: "summary", parents: [] });
119
+ }
120
+ for (const node of nodes.values())
121
+ for (const child of node.children)
122
+ nodes.get(child).parents.push(node.id);
123
+ const top = [...nodes.values()].filter(node => !node.parents.length).sort((a, b) => a.from.localeCompare(b.from));
124
+ for (const child of top)
125
+ child.parents.push(raw.id);
126
+ const dates = raw.exchanges.flatMap(item => [item.from, item.to]).sort();
127
+ const name = raw.name || raw.exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "";
128
+ nodes.set(raw.id, { id: raw.id, kind: "session", level: -1, entryIds: [], text: name, ready: true,
129
+ completed: raw.exchanges.every(item => item.completed), from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [], children: top.map(node => node.id) });
130
+ return { host: raw.host, id: raw.id, sessionId: raw.sessionId, name, nodes: [...nodes.values()] };
131
+ }
132
+ export function historySummaries(record) {
133
+ return record.nodes.filter(node => node.kind === "summary").map(({ kind: _kind, parents: _parents, ...summary }) => summary);
134
+ }
@@ -1,7 +1,5 @@
1
- import type { HistoryHost, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
1
+ import type { HistoryHost, HistoryIdentity, HistoryLocation, HistoryNode, HistoryRecord, HistorySource, HistorySummarizer } from "../../model/history.js";
2
2
  import type { HistoryFiles } from "../../storage/history-files.js";
3
- /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
4
- export declare function indexHistory(session: HistorySession, previous?: HistoryRecord, host?: HistoryHost): HistoryRecord;
5
3
  export interface HistoryQuery {
6
4
  host?: HistoryHost;
7
5
  query?: string;
@@ -12,8 +10,8 @@ export interface HistoryQuery {
12
10
  limit?: number;
13
11
  }
14
12
  type HistoryReader = Pick<HistoryFiles, "host" | "list" | "warnings">;
15
- /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
16
- export declare function completeHistorySummary(record: HistoryRecord, expected: HistoryNode, children: readonly HistoryNode[], text: string): boolean;
13
+ /** Validate the exact target and ordered inputs under the source lock. Only publish the derived file. */
14
+ export declare function commitHistorySummary(files: Pick<HistoryFiles, "control" | "list" | "saveSummaries">, identity: HistoryIdentity, expected: HistoryNode, children: readonly HistoryNode[], text: string, signal?: AbortSignal): HistoryRecord | undefined;
17
15
  export declare class HistoryService {
18
16
  #private;
19
17
  readonly root: string;
@@ -1,107 +1,48 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { readFileSync } from "node:fs";
3
2
  import { join } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
4
  import { resourceRoot } from "../../common/paths.js";
5
5
  import { requireThat } from "../../common/validation.js";
6
- const exchangeSource = (value) => [value.entryIds, value.text, value.from, value.to, value.completed];
7
- /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
8
- export function indexHistory(session, previous, host = previous?.host ?? "pi") {
9
- requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
10
- const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
11
- const old = new Map(previous?.nodes.map(node => [node.id, node]));
12
- const nodes = new Map(previous?.nodes.filter(node => node.kind !== "session").map(node => [node.id, {
13
- ...node, entryIds: [...node.entryIds], children: [...node.children], parents: [],
14
- }]));
15
- const exchanges = session.branches.flat(), observedEnds = new Set(exchanges.map(value => value.entryIds.at(-1)));
16
- const replaced = new Set(session.supersededEntryIds);
17
- const superseded = new Set([...nodes.values()].filter(node => node.kind === "exchange" && !node.completed &&
18
- !observedEnds.has(node.entryIds.at(-1)) && replaced.has(node.entryIds.at(-1)) &&
19
- exchanges.some(exchange => node.entryIds.slice(0, -1).every(entry => exchange.entryIds.includes(entry)))).map(node => node.id));
20
- // Native adapters identify replaced observations along the same branch/turn. Preserve
21
- // terminal forks and interrupted exchanges, then rebuild summaries that used old partials.
22
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
23
- if (node.children.some(id => superseded.has(id)))
24
- superseded.add(node.id);
25
- }
26
- for (const key of superseded)
27
- nodes.delete(key);
28
- const observed = new Set(), changed = new Set();
29
- const add = (value, level, children = []) => {
30
- const key = `${id}:${level}:${value.entryIds.at(-1)}`;
31
- if (observed.has(key))
32
- return nodes.get(key);
33
- const before = old.get(key);
34
- if (!level && before && value.entryIds.length < before.entryIds.length &&
35
- value.entryIds.every((entry, index) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + index])) {
36
- observed.add(key);
37
- return nodes.get(key);
38
- }
39
- const same = before && JSON.stringify(before.children) === JSON.stringify(children) &&
40
- JSON.stringify(exchangeSource({ ...before, text: level ? "" : before.text })) === JSON.stringify(exchangeSource(value));
41
- const node = { ...value, entryIds: [...value.entryIds], id: key, kind: level ? "summary" : "exchange", level, children, parents: [],
42
- text: level ? same ? before.text : "" : value.text, ready: level ? Boolean(same && before.ready) : true };
43
- if (!same)
44
- changed.add(key);
45
- observed.add(key);
46
- nodes.set(key, node);
47
- return node;
48
- };
49
- for (const branch of session.branches) {
50
- let layer = branch.map(exchange => add(exchange, 0)), level = 1;
51
- while (layer.length >= 4) {
52
- const count = Math.floor(layer.length / 4) * 4, next = [];
53
- for (let i = 0; i < count; i += 4) {
54
- const children = layer.slice(i, i + 4), first = children[0], last = children.at(-1);
55
- next.push(add({ entryIds: [first.entryIds[0], last.entryIds.at(-1)], text: "", from: first.from, to: last.to,
56
- completed: children.every(node => node.completed) }, level, children.map(node => node.id)));
57
- }
58
- layer = next;
59
- level++;
60
- }
61
- }
62
- // Retained summaries can also depend on an observed prefix. Invalidate all affected ancestors.
63
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
64
- const children = node.children.map(id => nodes.get(id)), first = children[0], last = children.at(-1);
65
- const value = { entryIds: [first.entryIds[0], last.entryIds.at(-1)], from: first.from, to: last.to,
66
- completed: children.every(child => child.completed) };
67
- if (children.some(child => changed.has(child.id))) {
68
- node.text = "";
69
- node.ready = false;
70
- changed.add(node.id);
71
- }
72
- Object.assign(node, value);
73
- }
74
- const dates = [...nodes.values()].flatMap(node => [node.from, node.to]).sort();
75
- const nested = new Set([...nodes.values()].flatMap(node => node.children));
76
- nodes.set(id, { id, kind: "session", level: -1, entryIds: [], text: session.name, ready: true, completed: [...nodes.values()].every(node => node.completed),
77
- from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [],
78
- children: [...nodes.keys()].filter(key => !nested.has(key)).sort((a, b) => nodes.get(a).from.localeCompare(nodes.get(b).from)) });
79
- for (const node of nodes.values())
80
- for (const child of node.children)
81
- nodes.get(child).parents.push(node.id);
82
- return { host, id, sessionId: session.sessionId, name: session.name, nodes: [...nodes.values()] };
83
- }
6
+ import { historySummaries, historyView, indexHistory, retainHistorySummaries } from "./history-index.js";
84
7
  const page = (values, offset, limit) => ({ values: values.slice(offset, offset + limit),
85
8
  nextOffset: offset + limit < values.length ? offset + limit : null });
86
9
  const brief = ({ host, record }, node) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
87
10
  name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
88
- const rawSource = (record) => record && JSON.stringify({ name: record.name,
89
- nodes: record.nodes.map(node => [node.id, node.kind, node.level, node.entryIds, node.children,
90
- node.kind === "summary" ? "" : node.text, node.from, node.to, node.completed]) });
11
+ const view = ({ raw, summaries }) => ({ host: raw.host, record: historyView(raw, summaries) });
91
12
  const summarySource = (node) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
92
- /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
93
- export function completeHistorySummary(record, expected, children, text) {
94
- const node = record.nodes.find(value => value.id === expected.id);
95
- if (!node || node.kind !== "summary" || node.ready || JSON.stringify(summarySource(node)) !== JSON.stringify(summarySource(expected)) ||
96
- JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id)))
97
- return false;
98
- const current = node.children.map(id => record.nodes.find(value => value.id === id));
99
- if (current.some(value => !value || !value.ready) || JSON.stringify(current.map(value => summarySource(value))) !== JSON.stringify(children.map(summarySource)))
100
- return false;
101
- requireThat(text.trim(), "历史摘要为空。");
102
- node.text = text.trim();
103
- node.ready = true;
104
- return true;
13
+ function nextSummary(archives) {
14
+ for (const { raw, summaries } of archives) {
15
+ if (summaries === null)
16
+ continue;
17
+ const record = historyView(raw, summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
18
+ const node = record.nodes.find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id).ready));
19
+ if (node)
20
+ return { record, node, children: node.children.map(id => lookup.get(id)) };
21
+ }
22
+ }
23
+ /** Validate the exact target and ordered inputs under the source lock. Only publish the derived file. */
24
+ export function commitHistorySummary(files, identity, expected, children, text, signal) {
25
+ return files.control(() => {
26
+ signal?.throwIfAborted();
27
+ const current = files.list().find(({ raw }) => raw.host === identity.host && raw.id === identity.id && raw.sessionId === identity.sessionId);
28
+ if (!current || current.summaries === null)
29
+ return;
30
+ const record = historyView(current.raw, current.summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
31
+ const node = lookup.get(expected.id);
32
+ if (!node || node.kind !== "summary" || node.ready || !isDeepStrictEqual(summarySource(node), summarySource(expected)) ||
33
+ !isDeepStrictEqual(node.children, children.map(child => child.id)))
34
+ return;
35
+ for (const child of children) {
36
+ const input = lookup.get(child.id);
37
+ if (!input?.ready || !isDeepStrictEqual(summarySource(input), summarySource(child)))
38
+ return;
39
+ }
40
+ requireThat(text.trim(), "历史摘要为空。");
41
+ node.text = text.trim();
42
+ node.ready = true;
43
+ files.saveSummaries(current.raw, historySummaries(record));
44
+ return record;
45
+ });
105
46
  }
106
47
  export class HistoryService {
107
48
  root;
@@ -153,9 +94,9 @@ export class HistoryService {
153
94
  this.files.migrate(this.root);
154
95
  }
155
96
  finally {
156
- known = this.files.list();
97
+ known = this.files.list(this.root);
157
98
  }
158
- const before = known;
99
+ const before = new Map(known.map(({ raw }) => [raw.sessionId, raw]));
159
100
  let sessions = [];
160
101
  try {
161
102
  const scanned = await this.source.scan(location, signal);
@@ -171,21 +112,27 @@ export class HistoryService {
171
112
  known = this.files.control(() => {
172
113
  this.check();
173
114
  signal?.throwIfAborted();
174
- const latest = this.files.list(), current = new Map(latest.map(record => [record.sessionId, record]));
115
+ const current = new Map(this.files.list().map(archive => [archive.raw.sessionId, archive]));
175
116
  for (const session of sessions) {
176
- const previous = current.get(session.sessionId), captured = before.find(record => record.sessionId === session.sessionId);
177
- // An unreadable archive may own this session; avoid assigning it a second root ID.
178
- if (!previous && this.files.warnings.length)
117
+ const previous = current.get(session.sessionId);
118
+ // A damaged raw file may own this session; a damaged summary cannot own a root ID.
119
+ if (!previous && this.files.rawWarnings.length)
179
120
  continue;
180
- // A concurrent source update must not be overwritten by this older scan. Summary-only updates remain reusable.
181
- if (captured && rawSource(captured) !== rawSource(previous))
121
+ if (!isDeepStrictEqual(before.get(session.sessionId), previous?.raw))
182
122
  continue;
183
- if (!captured && previous)
123
+ const raw = indexHistory(session, previous?.raw, this.files.host);
124
+ if (isDeepStrictEqual(raw, previous?.raw))
184
125
  continue;
185
- const value = indexHistory(session, previous, this.files.host);
186
- if (JSON.stringify(previous) !== JSON.stringify(value))
187
- this.files.save(value);
188
- current.set(session.sessionId, value);
126
+ let summaries = previous ? previous.summaries : [];
127
+ if (previous && summaries?.length) {
128
+ const retained = retainHistorySummaries(previous.raw, raw, summaries);
129
+ // Invalidate first: even an interrupted two-file update cannot attach old text to a corrected exchange.
130
+ if (!isDeepStrictEqual(summaries, retained))
131
+ this.files.saveSummaries(previous.raw, retained);
132
+ summaries = retained;
133
+ }
134
+ this.files.saveRaw(raw);
135
+ current.set(session.sessionId, { raw, summaries });
189
136
  }
190
137
  return [...current.values()];
191
138
  });
@@ -194,10 +141,10 @@ export class HistoryService {
194
141
  catch (error) {
195
142
  warning(this.files.host, error);
196
143
  }
197
- records.push(...known.map(record => ({ host: record.host, record })));
144
+ records.push(...known.map(view));
198
145
  for (const files of this.otherFiles) {
199
146
  try {
200
- records.push(...files.list(this.root).map(record => ({ host: record.host, record })));
147
+ records.push(...files.list(this.root).map(view));
201
148
  }
202
149
  catch (error) {
203
150
  warning(files.host, error);
@@ -253,11 +200,7 @@ export class HistoryService {
253
200
  for (;;) {
254
201
  this.check();
255
202
  active.throwIfAborted();
256
- const pending = this.files.list().flatMap(record => {
257
- const lookup = new Map(record.nodes.map(node => [node.id, node]));
258
- const node = [...record.nodes].sort((a, b) => a.level - b.level).find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id).ready));
259
- return node ? [{ record, node, children: node.children.map(id => lookup.get(id)) }] : [];
260
- })[0];
203
+ const pending = nextSummary(this.files.list());
261
204
  if (!pending)
262
205
  return;
263
206
  const { record, node, children } = pending;
@@ -265,15 +208,7 @@ export class HistoryService {
265
208
  prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
266
209
  this.check();
267
210
  active.throwIfAborted();
268
- const committed = this.files.control(() => {
269
- this.check();
270
- active.throwIfAborted();
271
- const current = this.files.list().find(value => value.id === record.id && value.sessionId === record.sessionId);
272
- if (!current || !completeHistorySummary(current, node, children, text))
273
- return;
274
- this.files.save(current);
275
- return current;
276
- });
211
+ const committed = commitHistorySummary(this.files, record, node, children, text, active);
277
212
  if (!committed)
278
213
  return;
279
214
  this.#records = this.#records.map(value => value.host === this.files.host && value.record.id === committed.id ? { host: value.host, record: committed } : value);