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.
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import type { HistoryExchange, HistoryHost, HistoryNode, HistoryRecord, HistorySession, HistorySummary, RawHistory } from "../../model/history.js";
4
+ import { requireThat } from "../../common/validation.js";
5
+
6
+ /** Each native entry has one predecessor. A shortened observation can extend a known path, not erase its prefix. */
7
+ function mergeBranches(previous: string[][], observed: string[][], removed: Set<string>): string[][] {
8
+ const parents = new Map<string, string | undefined>();
9
+ for (const branch of [...previous, ...observed]) {
10
+ let parent: string | undefined;
11
+ for (const id of branch) {
12
+ if (removed.has(id)) { parent = undefined; continue; }
13
+ if (parent !== undefined || !parents.has(id)) parents.set(id, parent);
14
+ parent = id;
15
+ }
16
+ }
17
+ const internal = new Set(parents.values()), seen = new Set<string>(), branches: string[][] = [];
18
+ for (const tip of parents.keys()) {
19
+ if (internal.has(tip)) continue;
20
+ const path: string[] = [];
21
+ for (let id: string | undefined = tip; id !== undefined; id = parents.get(id)) {
22
+ requireThat(path.length < parents.size, "历史分支包含循环引用。");
23
+ path.push(id); seen.add(id);
24
+ }
25
+ branches.push(path.reverse());
26
+ }
27
+ requireThat(seen.size === parents.size, "历史分支包含循环引用。");
28
+ return branches;
29
+ }
30
+
31
+ /** Only a native observation can change exchanges or establish branch order. */
32
+ export function indexHistory(session: HistorySession, previous?: RawHistory, host: HistoryHost = previous?.host ?? "pi"): RawHistory {
33
+ requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
34
+ const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
35
+ const exchanges = new Map(previous?.exchanges.map(item => [item.id, item]));
36
+ const byEnd = new Map(previous?.exchanges.map(item => [item.entryIds.at(-1)!, item.id]));
37
+ const observed = new Map<string, HistoryExchange>();
38
+ const branches = session.branches.map(branch => branch.map(value => {
39
+ const end = value.entryIds.at(-1)!;
40
+ const key = byEnd.get(end) ?? `${id}:0:${end}`;
41
+ if (!observed.has(end)) {
42
+ observed.set(end, value);
43
+ const before = exchanges.get(key);
44
+ // Compaction can leave only the last inputs and answer of an already archived exchange.
45
+ if (!(before && value.entryIds.length < before.entryIds.length &&
46
+ value.entryIds.every((entry, i) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + i]))) {
47
+ exchanges.set(key, { ...value, entryIds: [...value.entryIds], id: key });
48
+ }
49
+ }
50
+ return key;
51
+ }));
52
+ const removed = new Set<string>();
53
+ for (const end of session.supersededEntryIds ?? []) {
54
+ const key = byEnd.get(end), item = key === undefined ? undefined : exchanges.get(key);
55
+ if (item && !item.completed && !observed.has(end) && [...observed.values()].some(value =>
56
+ item.entryIds.slice(0, -1).every(entry => value.entryIds.includes(entry)))) {
57
+ removed.add(item.id); exchanges.delete(item.id);
58
+ }
59
+ }
60
+ return { host, id, sessionId: session.sessionId, name: session.name, exchanges: [...exchanges.values()],
61
+ branches: mergeBranches(previous?.branches ?? [], branches, removed) };
62
+ }
63
+
64
+ function span(children: HistoryExchange[]) {
65
+ const first = children[0]!, last = children.at(-1)!;
66
+ return { entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], from: first.from, to: last.to, completed: children.every(child => child.completed) };
67
+ }
68
+
69
+ /** Retire results using changed inputs before publishing a native correction. New groups need no disk write. */
70
+ export function retainHistorySummaries(before: RawHistory, after: RawHistory, summaries: HistorySummary[]): HistorySummary[] {
71
+ const inputs = new Map<string, HistoryExchange>(after.exchanges.map(item => [item.id, item]));
72
+ const changed = new Set(before.exchanges.filter(item => !isDeepStrictEqual(item, inputs.get(item.id))).map(item => item.id));
73
+ if (!changed.size || !summaries.length) return summaries;
74
+ const retained = new Map<string, HistorySummary>();
75
+ for (const item of [...summaries].sort((a, b) => a.level - b.level)) {
76
+ const children = item.children.map(id => inputs.get(id));
77
+ if (!children.length || !children.every(child => child !== undefined)) { changed.add(item.id); continue; }
78
+ let summary = item;
79
+ if (item.children.some(id => changed.has(id))) {
80
+ summary = { ...item, ...span(children), text: "", ready: false }; changed.add(item.id);
81
+ }
82
+ retained.set(item.id, summary); inputs.set(item.id, summary);
83
+ }
84
+ return summaries.flatMap(item => retained.get(item.id) ?? []);
85
+ }
86
+
87
+ /** The four-way tree is a query view, never the source of native branch order. */
88
+ export function historyView(raw: RawHistory, saved: readonly HistorySummary[] | null = []): HistoryRecord {
89
+ const nodes = new Map<string, HistoryNode>(raw.exchanges.map(value => [value.id,
90
+ { ...value, kind: "exchange", level: 0, ready: true, children: [], parents: [] }]));
91
+ const stored = new Map(saved?.map(value => [value.id, value]));
92
+ const groups = new Map<string, Pick<HistorySummary, "id" | "level" | "children">>(stored);
93
+ for (const branch of raw.branches) {
94
+ let layer = branch.map(id => ({ id, end: nodes.get(id)!.entryIds.at(-1)! }));
95
+ for (let level = 1; layer.length >= 4; level++) {
96
+ const next: typeof layer = [];
97
+ for (let i = 0; i + 4 <= layer.length; i += 4) {
98
+ const end = layer[i + 3]!.end, id = `${raw.id}:${level}:${end}`;
99
+ groups.set(id, { id, level, children: layer.slice(i, i + 4).map(child => child.id) });
100
+ next.push({ id, end });
101
+ }
102
+ layer = next;
103
+ }
104
+ }
105
+ for (const group of [...groups.values()].sort((a, b) => a.level - b.level)) {
106
+ const children = group.children.map(id => nodes.get(id));
107
+ if (!children.length || !children.every(child => child !== undefined)) continue;
108
+ const old = stored.get(group.id);
109
+ const summary = old && isDeepStrictEqual(old.children, group.children) && (!old.ready || children.every(child => child.ready)) ? old :
110
+ { ...group, ...span(children), text: "", ready: false };
111
+ nodes.set(group.id, { ...summary, kind: "summary", parents: [] });
112
+ }
113
+ for (const node of nodes.values()) for (const child of node.children) nodes.get(child)!.parents.push(node.id);
114
+ const top = [...nodes.values()].filter(node => !node.parents.length).sort((a, b) => a.from.localeCompare(b.from));
115
+ for (const child of top) child.parents.push(raw.id);
116
+ const dates = raw.exchanges.flatMap(item => [item.from, item.to]).sort();
117
+ const name = raw.name || raw.exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "";
118
+ nodes.set(raw.id, { id: raw.id, kind: "session", level: -1, entryIds: [], text: name, ready: true,
119
+ completed: raw.exchanges.every(item => item.completed), from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [], children: top.map(node => node.id) });
120
+ return { host: raw.host, id: raw.id, sessionId: raw.sessionId, name, nodes: [...nodes.values()] };
121
+ }
122
+
123
+ export function historySummaries(record: HistoryRecord): HistorySummary[] {
124
+ return record.nodes.filter(node => node.kind === "summary").map(({ kind: _kind, parents: _parents, ...summary }) => summary);
125
+ }
@@ -1,76 +1,11 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { readFileSync } from "node:fs";
3
2
  import { join } from "node:path";
4
- import type { HistoryExchange, HistoryHost, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import type { HistoryArchive, HistoryHost, HistoryIdentity, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
5
5
  import type { HistoryFiles } from "../../storage/history-files.js";
6
6
  import { resourceRoot } from "../../common/paths.js";
7
7
  import { requireThat } from "../../common/validation.js";
8
-
9
- const exchangeSource = (value: HistoryExchange) => [value.entryIds, value.text, value.from, value.to, value.completed];
10
-
11
- /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
12
- export function indexHistory(session: HistorySession, previous?: HistoryRecord, host: HistoryHost = previous?.host ?? "pi"): HistoryRecord {
13
- requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
14
- const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
15
- const old = new Map(previous?.nodes.map(node => [node.id, node]));
16
- const nodes = new Map<string, HistoryNode>(previous?.nodes.filter(node => node.kind !== "session").map(node => [node.id, {
17
- ...node, entryIds: [...node.entryIds], children: [...node.children], parents: [],
18
- }] satisfies [string, HistoryNode]));
19
- const exchanges = session.branches.flat(), observedEnds = new Set(exchanges.map(value => value.entryIds.at(-1)));
20
- const replaced = new Set(session.supersededEntryIds);
21
- const superseded = new Set([...nodes.values()].filter(node => node.kind === "exchange" && !node.completed &&
22
- !observedEnds.has(node.entryIds.at(-1)) && replaced.has(node.entryIds.at(-1)!) &&
23
- exchanges.some(exchange => node.entryIds.slice(0, -1).every(entry => exchange.entryIds.includes(entry)))).map(node => node.id));
24
- // Native adapters identify replaced observations along the same branch/turn. Preserve
25
- // terminal forks and interrupted exchanges, then rebuild summaries that used old partials.
26
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
27
- if (node.children.some(id => superseded.has(id))) superseded.add(node.id);
28
- }
29
- for (const key of superseded) nodes.delete(key);
30
- const observed = new Set<string>(), changed = new Set<string>();
31
- const add = (value: HistoryExchange, level: number, children: string[] = []): HistoryNode => {
32
- const key = `${id}:${level}:${value.entryIds.at(-1)}`;
33
- if (observed.has(key)) return nodes.get(key)!;
34
- const before = old.get(key);
35
- if (!level && before && value.entryIds.length < before.entryIds.length &&
36
- value.entryIds.every((entry, index) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + index])) {
37
- observed.add(key); 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: HistoryNode = { ...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) changed.add(key);
44
- observed.add(key); nodes.set(key, node); return node;
45
- };
46
- for (const branch of session.branches) {
47
- let layer = branch.map(exchange => add(exchange, 0)), level = 1;
48
- while (layer.length >= 4) {
49
- const count = Math.floor(layer.length / 4) * 4, next: HistoryNode[] = [];
50
- for (let i = 0; i < count; i += 4) {
51
- const children = layer.slice(i, i + 4), first = children[0]!, last = children.at(-1)!;
52
- next.push(add({ entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], text: "", from: first.from, to: last.to,
53
- completed: children.every(node => node.completed) }, level, children.map(node => node.id)));
54
- }
55
- layer = next; level++;
56
- }
57
- }
58
- // Retained summaries can also depend on an observed prefix. Invalidate all affected ancestors.
59
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
60
- const children = node.children.map(id => nodes.get(id)!), first = children[0]!, last = children.at(-1)!;
61
- const value = { entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], from: first.from, to: last.to,
62
- completed: children.every(child => child.completed) };
63
- if (children.some(child => changed.has(child.id))) { node.text = ""; node.ready = false; changed.add(node.id); }
64
- Object.assign(node, value);
65
- }
66
- const dates = [...nodes.values()].flatMap(node => [node.from, node.to]).sort();
67
- const nested = new Set([...nodes.values()].flatMap(node => node.children));
68
- nodes.set(id, { id, kind: "session", level: -1, entryIds: [], text: session.name, ready: true, completed: [...nodes.values()].every(node => node.completed),
69
- from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [],
70
- children: [...nodes.keys()].filter(key => !nested.has(key)).sort((a, b) => nodes.get(a)!.from.localeCompare(nodes.get(b)!.from)) });
71
- for (const node of nodes.values()) for (const child of node.children) nodes.get(child)!.parents.push(node.id);
72
- return { host, id, sessionId: session.sessionId, name: session.name, nodes: [...nodes.values()] };
73
- }
8
+ import { historySummaries, historyView, indexHistory, retainHistorySummaries } from "./history-index.js";
74
9
 
75
10
  export interface HistoryQuery { host?: HistoryHost; query?: string; sessionId?: string; from?: string; to?: string; offset?: number; limit?: number }
76
11
  type LocatedRecord = { host: HistoryHost; record: HistoryRecord };
@@ -79,20 +14,38 @@ const page = <T>(values: T[], offset: number, limit: number) => ({ values: value
79
14
  nextOffset: offset + limit < values.length ? offset + limit : null });
80
15
  const brief = ({ host, record }: LocatedRecord, node: HistoryNode) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
81
16
  name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
82
- const rawSource = (record?: HistoryRecord) => record && JSON.stringify({ name: record.name,
83
- nodes: record.nodes.map(node => [node.id, node.kind, node.level, node.entryIds, node.children,
84
- node.kind === "summary" ? "" : node.text, node.from, node.to, node.completed]) });
17
+ const view = ({ raw, summaries }: HistoryArchive): LocatedRecord => ({ host: raw.host, record: historyView(raw, summaries) });
85
18
  const summarySource = (node: HistoryNode) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
86
19
 
87
- /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
88
- export function completeHistorySummary(record: HistoryRecord, expected: HistoryNode, children: readonly HistoryNode[], text: string) {
89
- const node = record.nodes.find(value => value.id === expected.id);
90
- if (!node || node.kind !== "summary" || node.ready || JSON.stringify(summarySource(node)) !== JSON.stringify(summarySource(expected)) ||
91
- JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id))) return false;
92
- const current = node.children.map(id => record.nodes.find(value => value.id === id));
93
- if (current.some(value => !value || !value.ready) || JSON.stringify(current.map(value => summarySource(value!))) !== JSON.stringify(children.map(summarySource))) return false;
94
- requireThat(text.trim(), "历史摘要为空。");
95
- node.text = text.trim(); node.ready = true; return true;
20
+ function nextSummary(archives: HistoryArchive[]) {
21
+ for (const { raw, summaries } of archives) {
22
+ if (summaries === null) continue;
23
+ const record = historyView(raw, summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
24
+ const node = record.nodes.find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id)!.ready));
25
+ if (node) return { record, node, children: node.children.map(id => lookup.get(id)!) };
26
+ }
27
+ }
28
+
29
+ /** Validate the exact target and ordered inputs under the source lock. Only publish the derived file. */
30
+ export function commitHistorySummary(files: Pick<HistoryFiles, "control" | "list" | "saveSummaries">, identity: HistoryIdentity,
31
+ expected: HistoryNode, children: readonly HistoryNode[], text: string, signal?: AbortSignal): HistoryRecord | undefined {
32
+ return files.control(() => {
33
+ signal?.throwIfAborted();
34
+ const current = files.list().find(({ raw }) => raw.host === identity.host && raw.id === identity.id && raw.sessionId === identity.sessionId);
35
+ if (!current || current.summaries === null) return;
36
+ const record = historyView(current.raw, current.summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
37
+ const node = lookup.get(expected.id);
38
+ if (!node || node.kind !== "summary" || node.ready || !isDeepStrictEqual(summarySource(node), summarySource(expected)) ||
39
+ !isDeepStrictEqual(node.children, children.map(child => child.id))) return;
40
+ for (const child of children) {
41
+ const input = lookup.get(child.id);
42
+ if (!input?.ready || !isDeepStrictEqual(summarySource(input), summarySource(child))) return;
43
+ }
44
+ requireThat(text.trim(), "历史摘要为空。");
45
+ node.text = text.trim(); node.ready = true;
46
+ files.saveSummaries(current.raw, historySummaries(record));
47
+ return record;
48
+ });
96
49
  }
97
50
 
98
51
  export class HistoryService {
@@ -126,10 +79,10 @@ export class HistoryService {
126
79
  this.check(); signal?.throwIfAborted();
127
80
  const warnings: string[] = [], records: LocatedRecord[] = [];
128
81
  const warning = (host: HistoryHost, error: unknown) => { this.check(); signal?.throwIfAborted(); warnings.push(host + ": " + String(error)); };
129
- let known: HistoryRecord[] = [];
82
+ let known: HistoryArchive[] = [];
130
83
  try {
131
- try { this.files.migrate(this.root); } finally { known = this.files.list(); }
132
- const before = known;
84
+ try { this.files.migrate(this.root); } finally { known = this.files.list(this.root); }
85
+ const before = new Map(known.map(({ raw }) => [raw.sessionId, raw]));
133
86
  let sessions: HistorySession[] = [];
134
87
  try {
135
88
  const scanned = await this.source.scan(location, signal); sessions = scanned.sessions;
@@ -139,25 +92,31 @@ export class HistoryService {
139
92
  if (sessions.length) {
140
93
  known = this.files.control(() => {
141
94
  this.check(); signal?.throwIfAborted();
142
- const latest = this.files.list(), current = new Map(latest.map(record => [record.sessionId, record]));
95
+ const current = new Map(this.files.list().map(archive => [archive.raw.sessionId, archive]));
143
96
  for (const session of sessions) {
144
- const previous = current.get(session.sessionId), captured = before.find(record => record.sessionId === session.sessionId);
145
- // An unreadable archive may own this session; avoid assigning it a second root ID.
146
- if (!previous && this.files.warnings.length) continue;
147
- // A concurrent source update must not be overwritten by this older scan. Summary-only updates remain reusable.
148
- if (captured && rawSource(captured) !== rawSource(previous)) continue;
149
- if (!captured && previous) continue;
150
- const value = indexHistory(session, previous, this.files.host);
151
- if (JSON.stringify(previous) !== JSON.stringify(value)) this.files.save(value);
152
- current.set(session.sessionId, value);
97
+ const previous = current.get(session.sessionId);
98
+ // A damaged raw file may own this session; a damaged summary cannot own a root ID.
99
+ if (!previous && this.files.rawWarnings.length) continue;
100
+ if (!isDeepStrictEqual(before.get(session.sessionId), previous?.raw)) continue;
101
+ const raw = indexHistory(session, previous?.raw, this.files.host);
102
+ if (isDeepStrictEqual(raw, previous?.raw)) continue;
103
+ let summaries = previous ? previous.summaries : [];
104
+ if (previous && summaries?.length) {
105
+ const retained = retainHistorySummaries(previous.raw, raw, summaries);
106
+ // Invalidate first: even an interrupted two-file update cannot attach old text to a corrected exchange.
107
+ if (!isDeepStrictEqual(summaries, retained)) this.files.saveSummaries(previous.raw, retained);
108
+ summaries = retained;
109
+ }
110
+ this.files.saveRaw(raw);
111
+ current.set(session.sessionId, { raw, summaries });
153
112
  }
154
113
  return [...current.values()];
155
114
  });
156
115
  }
157
116
  } catch (error) { warning(this.files.host, error); }
158
- records.push(...known.map(record => ({ host: record.host, record })));
117
+ records.push(...known.map(view));
159
118
  for (const files of this.otherFiles) {
160
- try { records.push(...files.list(this.root).map(record => ({ host: record.host, record }))); }
119
+ try { records.push(...files.list(this.root).map(view)); }
161
120
  catch (error) { warning(files.host, error); }
162
121
  }
163
122
  this.check(); signal?.throwIfAborted(); this.#records = records; this.#sourceWarnings = warnings; this.#loaded = true;
@@ -203,22 +162,13 @@ export class HistoryService {
203
162
  const run = async () => {
204
163
  for (;;) {
205
164
  this.check(); active.throwIfAborted();
206
- const pending = this.files.list().flatMap(record => {
207
- const lookup = new Map(record.nodes.map(node => [node.id, node]));
208
- 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));
209
- return node ? [{ record, node, children: node.children.map(id => lookup.get(id)!) }] : [];
210
- })[0];
165
+ const pending = nextSummary(this.files.list());
211
166
  if (!pending) return;
212
167
  const { record, node, children } = pending;
213
168
  const text = await summarize({ system: readFileSync(join(resourceRoot, "prompts/history-summary.md"), "utf8"), maxTokens: 2048,
214
169
  prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
215
170
  this.check(); active.throwIfAborted();
216
- const committed = this.files.control(() => {
217
- this.check(); active.throwIfAborted();
218
- const current = this.files.list().find(value => value.id === record.id && value.sessionId === record.sessionId);
219
- if (!current || !completeHistorySummary(current, node, children, text)) return;
220
- this.files.save(current); return current;
221
- });
171
+ const committed = commitHistorySummary(this.files, record, node, children, text, active);
222
172
  if (!committed) return;
223
173
  this.#records = this.#records.map(value => value.host === this.files.host && value.record.id === committed.id ? { host: value.host, record: committed } : value);
224
174
  }