personal-bot 0.2.16 → 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.
Files changed (35) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CONTEXT.md +13 -1
  4. package/README.md +2 -2
  5. package/README.zh-CN.md +2 -2
  6. package/docs/file-storage.md +9 -2
  7. package/docs/history.md +5 -7
  8. package/docs/technical-design.md +3 -3
  9. package/lib/dsh.js +4 -4
  10. package/lib/extension/dsh/acp-member.js +2 -1
  11. package/lib/extension/dsh/workspace.js +2 -1
  12. package/lib/integrations/dsh/history.js +1 -2
  13. package/lib/integrations/dsh/root-agents.d.ts +4 -0
  14. package/lib/integrations/dsh/root-agents.js +3 -0
  15. package/lib/model/history.d.ts +26 -7
  16. package/lib/services/history/history-index.d.ts +8 -0
  17. package/lib/services/history/history-index.js +134 -0
  18. package/lib/services/history/history-service.d.ts +3 -5
  19. package/lib/services/history/history-service.js +59 -124
  20. package/lib/storage/history-files.d.ts +9 -6
  21. package/lib/storage/history-files.js +297 -83
  22. package/lib/storage/history-format.d.ts +15 -0
  23. package/lib/storage/history-format.js +86 -0
  24. package/package.json +1 -1
  25. package/src/dsh.ts +3 -2
  26. package/src/extension/dsh/acp-member.ts +2 -1
  27. package/src/extension/dsh/workspace.ts +2 -1
  28. package/src/integrations/dsh/history.ts +1 -2
  29. package/src/integrations/dsh/root-agents.ts +5 -0
  30. package/src/integrations/pi/history.ts +1 -4
  31. package/src/model/history.ts +24 -7
  32. package/src/services/history/history-index.ts +125 -0
  33. package/src/services/history/history-service.ts +56 -106
  34. package/src/storage/history-files.ts +233 -74
  35. package/src/storage/history-format.ts +98 -0
@@ -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);
@@ -1,15 +1,18 @@
1
- import type { HistoryHost, HistoryRecord } from "../model/history.js";
1
+ import type { HistoryArchive, HistoryHost, HistoryIdentity, HistorySummary, RawHistory } from "../model/history.js";
2
2
  export declare class HistoryFiles {
3
3
  #private;
4
4
  readonly directory: string;
5
5
  readonly host: HistoryHost;
6
6
  constructor(directory: string, host?: HistoryHost);
7
7
  get warnings(): readonly string[];
8
- /** A peer can include its legacy directory without migrating or modifying either source. */
9
- list(legacyRoot?: string): HistoryRecord[];
10
- /** Publish each legacy archive with its directory's host before removing the old copy. */
11
- migrate(root: string): void;
8
+ get rawWarnings(): readonly string[];
9
+ list(legacyRoot?: string): HistoryArchive[];
12
10
  /** The callback is synchronous: no SDK reads or model work can hold this source's write lock. */
13
11
  control<T>(operation: () => T): T;
14
- save(value: HistoryRecord): void;
12
+ private writable;
13
+ saveRaw(raw: RawHistory): void;
14
+ saveSummaries(identity: HistoryIdentity, summaries: readonly HistorySummary[]): void;
15
+ private publishSummaries;
16
+ private migrateFile;
17
+ migrate(root: string): void;
15
18
  }