personal-bot 0.3.0 → 0.3.2

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 (256) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +1 -1
  4. package/README.zh-CN.md +1 -1
  5. package/bin/pbot-pi-acp.mjs +27 -11
  6. package/bin/pbot.mjs +1 -1
  7. package/docs/README.md +1 -1
  8. package/docs/architecture/design.md +23 -10
  9. package/docs/architecture/extensibility.md +20 -18
  10. package/docs/architecture/model-context.md +2 -2
  11. package/docs/architecture/principles.md +4 -3
  12. package/docs/guides/capabilities.md +3 -3
  13. package/docs/guides/history.md +50 -16
  14. package/docs/guides/workspace-configuration.md +31 -6
  15. package/docs/hosts/antigravity.md +2 -0
  16. package/docs/hosts/claude-code.md +1 -1
  17. package/docs/hosts/dsh.md +1 -1
  18. package/docs/hosts/pi.md +1 -1
  19. package/hooks/hooks.json +3 -0
  20. package/lib/antigravity-plugin/hooks.json +7 -0
  21. package/lib/antigravity-plugin/lib/claude.js +2 -2
  22. package/lib/antigravity-plugin/lib/extension/acp-worker.js +156 -11
  23. package/lib/antigravity-plugin/lib/extension/{plugin-runtime.d.ts → hosts/plugin-runtime.d.ts} +2 -2
  24. package/lib/antigravity-plugin/lib/extension/{plugin-runtime.js → hosts/plugin-runtime.js} +34 -8
  25. package/lib/antigravity-plugin/lib/extension/mcp.js +1113 -78
  26. package/lib/antigravity-plugin/lib/integrations/agent-resources.d.ts +1 -0
  27. package/lib/antigravity-plugin/lib/integrations/agent-resources.js +5 -1
  28. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity/adapter.d.ts +6 -0
  29. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity/adapter.js +171 -0
  30. package/lib/antigravity-plugin/lib/integrations/hosts/{claude.d.ts → claude/adapter.d.ts} +1 -1
  31. package/lib/antigravity-plugin/lib/integrations/hosts/{claude.js → claude/adapter.js} +32 -4
  32. package/lib/antigravity-plugin/lib/integrations/hosts/{registry.js → plugin-registry.js} +2 -2
  33. package/lib/antigravity-plugin/lib/model/history.d.ts +169 -0
  34. package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +26 -0
  35. package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +25 -0
  36. package/lib/antigravity-plugin/lib/plugin.js +2 -2
  37. package/lib/antigravity-plugin/lib/services/history/history-capture.d.ts +4 -0
  38. package/lib/antigravity-plugin/lib/services/history/history-capture.js +86 -0
  39. package/lib/antigravity-plugin/lib/services/history/history-index.d.ts +17 -0
  40. package/lib/antigravity-plugin/lib/services/history/history-index.js +112 -0
  41. package/lib/antigravity-plugin/lib/services/history/history-migrate.d.ts +12 -0
  42. package/lib/antigravity-plugin/lib/services/history/history-migrate.js +88 -0
  43. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/monthly.d.ts +7 -0
  44. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/monthly.js +121 -0
  45. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/session.d.ts +7 -0
  46. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/session.js +124 -0
  47. package/lib/antigravity-plugin/lib/services/history/summary-registry.d.ts +7 -0
  48. package/lib/antigravity-plugin/lib/services/history/summary-registry.js +36 -0
  49. package/lib/antigravity-plugin/lib/services/history/summary-runner.d.ts +37 -0
  50. package/lib/antigravity-plugin/lib/services/history/summary-runner.js +301 -0
  51. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.d.ts +5 -1
  52. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +75 -4
  53. package/lib/antigravity-plugin/lib/storage/file-access.d.ts +2 -0
  54. package/lib/antigravity-plugin/lib/storage/file-access.js +26 -0
  55. package/lib/antigravity-plugin/lib/storage/history-files.d.ts +54 -0
  56. package/lib/antigravity-plugin/lib/storage/history-files.js +467 -0
  57. package/lib/antigravity-plugin/lib/storage/history-format.d.ts +6 -0
  58. package/lib/antigravity-plugin/lib/storage/history-format.js +62 -0
  59. package/lib/antigravity-plugin/package.json +1 -1
  60. package/lib/antigravity-plugin/plugin.json +1 -1
  61. package/lib/antigravity-plugin/skills/provider-connections/SKILL.md +22 -12
  62. package/lib/claude.js +2 -2
  63. package/lib/client.js +21 -11
  64. package/lib/dsh.js +4 -4
  65. package/lib/extension/{acp-member.d.ts → acp/member.d.ts} +5 -5
  66. package/lib/extension/{acp-member.js → acp/member.js} +6 -6
  67. package/lib/extension/acp/worker.d.ts +1 -0
  68. package/lib/extension/acp/worker.js +384 -0
  69. package/lib/extension/acp-worker.js +156 -11
  70. package/lib/extension/{dsh → hosts/dsh}/acp-member.js +8 -8
  71. package/lib/extension/hosts/dsh/command.js +92 -0
  72. package/lib/extension/{dsh → hosts/dsh}/files.js +3 -3
  73. package/lib/extension/hosts/dsh/history.d.ts +4 -0
  74. package/lib/extension/hosts/dsh/history.js +62 -0
  75. package/lib/extension/{dsh → hosts/dsh}/management.d.ts +1 -1
  76. package/lib/extension/{dsh → hosts/dsh}/management.js +12 -10
  77. package/lib/extension/{dsh → hosts/dsh}/workspace.d.ts +3 -9
  78. package/lib/extension/{dsh → hosts/dsh}/workspace.js +32 -70
  79. package/lib/extension/{plugin-runtime.d.ts → hosts/plugin-runtime.d.ts} +2 -2
  80. package/lib/extension/{plugin-runtime.js → hosts/plugin-runtime.js} +34 -8
  81. package/lib/extension/{mcp-bridge.d.ts → mcp/bridge.d.ts} +1 -1
  82. package/lib/extension/{mcp-bridge.js → mcp/bridge.js} +4 -4
  83. package/lib/extension/{mcp-workers.d.ts → mcp/workers.d.ts} +222 -2
  84. package/lib/extension/{mcp-workers.js → mcp/workers.js} +229 -63
  85. package/lib/extension/mcp.js +1113 -78
  86. package/lib/extension/{setup-cli.js → setup/cli.js} +9 -9
  87. package/lib/integrations/acp/connection.d.ts +11 -10
  88. package/lib/integrations/acp/connection.js +6 -0
  89. package/lib/integrations/acp/harnesses/claude.js +1 -1
  90. package/lib/integrations/acp/harnesses/dsh.js +1 -1
  91. package/lib/integrations/acp/history-summary.d.ts +17 -0
  92. package/lib/integrations/acp/history-summary.js +100 -0
  93. package/lib/integrations/agent-resources.d.ts +1 -0
  94. package/lib/integrations/agent-resources.js +5 -1
  95. package/lib/integrations/hosts/antigravity/adapter.d.ts +6 -0
  96. package/lib/integrations/hosts/antigravity/adapter.js +171 -0
  97. package/lib/integrations/hosts/{claude.d.ts → claude/adapter.d.ts} +1 -1
  98. package/lib/integrations/hosts/{claude.js → claude/adapter.js} +32 -4
  99. package/lib/integrations/{dsh → hosts/dsh}/mcp.d.ts +1 -1
  100. package/lib/integrations/{dsh → hosts/dsh}/resources.d.ts +1 -1
  101. package/lib/integrations/{dsh → hosts/dsh}/resources.js +4 -4
  102. package/lib/integrations/{dsh → hosts/dsh}/schema.js +1 -1
  103. package/lib/integrations/{dsh → hosts/dsh}/skills.js +1 -1
  104. package/lib/integrations/hosts/{registry.js → plugin-registry.js} +2 -2
  105. package/lib/integrations/installation/pi-setup.js +1 -1
  106. package/lib/model/history.d.ts +133 -34
  107. package/lib/model/plugin-host.d.ts +26 -0
  108. package/lib/model/workspace-config.d.ts +25 -0
  109. package/lib/plugin.js +2 -2
  110. package/lib/services/agents/agent-run.d.ts +1 -1
  111. package/lib/services/history/history-capture.d.ts +4 -0
  112. package/lib/services/history/history-capture.js +86 -0
  113. package/lib/services/history/history-index.d.ts +16 -7
  114. package/lib/services/history/history-index.js +48 -70
  115. package/lib/services/history/history-migrate.d.ts +12 -0
  116. package/lib/services/history/history-migrate.js +88 -0
  117. package/lib/services/history/history-query.d.ts +51 -0
  118. package/lib/services/history/history-query.js +371 -0
  119. package/lib/services/history/summary-command.d.ts +20 -0
  120. package/lib/services/history/summary-command.js +68 -0
  121. package/lib/services/history/summary-dimensions/monthly.d.ts +7 -0
  122. package/lib/services/history/summary-dimensions/monthly.js +121 -0
  123. package/lib/services/history/summary-dimensions/session.d.ts +7 -0
  124. package/lib/services/history/summary-dimensions/session.js +124 -0
  125. package/lib/services/history/summary-registry.d.ts +7 -0
  126. package/lib/services/history/summary-registry.js +36 -0
  127. package/lib/services/history/summary-runner.d.ts +37 -0
  128. package/lib/services/history/summary-runner.js +301 -0
  129. package/lib/services/workspace/workspace-config.d.ts +5 -1
  130. package/lib/services/workspace/workspace-config.js +75 -4
  131. package/lib/storage/history-files.d.ts +45 -9
  132. package/lib/storage/history-files.js +373 -247
  133. package/lib/storage/history-format.d.ts +3 -12
  134. package/lib/storage/history-format.js +26 -50
  135. package/lib/tools/history/actions.d.ts +3 -68
  136. package/lib/tools/history/actions.js +7 -5
  137. package/lib/tools/history/contract.d.ts +14 -7
  138. package/lib/tools/history/contract.js +58 -18
  139. package/lib/tools/history/dsh-tool.d.ts +1 -2
  140. package/lib/tools/history/dsh-tool.js +11 -5
  141. package/lib/ui/dsh/management.js +18 -5
  142. package/package.json +1 -1
  143. package/resources/prompts/history-coordinator.md +1 -1
  144. package/resources/prompts/history-monthly-summary.md +13 -0
  145. package/resources/prompts/history-summary.md +10 -4
  146. package/resources/skills/provider-connections/SKILL.md +22 -12
  147. package/src/claude.ts +2 -2
  148. package/src/dsh.ts +4 -4
  149. package/src/extension/{acp-member.ts → acp/member.ts} +7 -7
  150. package/src/extension/{acp-worker.ts → acp/worker.ts} +131 -17
  151. package/src/extension/{dsh → hosts/dsh}/acp-member.ts +9 -9
  152. package/src/extension/hosts/dsh/command.ts +92 -0
  153. package/src/extension/{dsh → hosts/dsh}/files.ts +3 -3
  154. package/src/extension/hosts/dsh/history.ts +67 -0
  155. package/src/extension/{dsh → hosts/dsh}/management.ts +11 -9
  156. package/src/extension/{dsh → hosts/dsh}/workspace.ts +31 -50
  157. package/src/extension/{pi-acp-member.ts → hosts/pi/acp-member.ts} +9 -9
  158. package/src/extension/hosts/pi/command.ts +158 -0
  159. package/src/extension/{events.ts → hosts/pi/events.ts} +14 -4
  160. package/src/extension/hosts/pi/history.ts +45 -0
  161. package/src/extension/{lifecycle.ts → hosts/pi/lifecycle.ts} +7 -11
  162. package/src/extension/{plugin-runtime.ts → hosts/plugin-runtime.ts} +29 -9
  163. package/src/extension/{mcp-bridge.ts → mcp/bridge.ts} +5 -5
  164. package/src/extension/{mcp-workers.ts → mcp/workers.ts} +237 -64
  165. package/src/extension/{setup-cli.ts → setup/cli.ts} +11 -11
  166. package/src/integrations/acp/connection.ts +6 -0
  167. package/src/integrations/acp/harnesses/claude.ts +1 -1
  168. package/src/integrations/acp/harnesses/dsh.ts +1 -1
  169. package/src/integrations/acp/history-summary.ts +108 -0
  170. package/src/integrations/agent-resources.ts +6 -0
  171. package/src/integrations/hosts/antigravity/adapter.ts +161 -0
  172. package/src/integrations/hosts/{claude.ts → claude/adapter.ts} +28 -5
  173. package/src/integrations/{dsh → hosts/dsh}/mcp.ts +1 -1
  174. package/src/integrations/{dsh → hosts/dsh}/resources.ts +5 -5
  175. package/src/integrations/{dsh → hosts/dsh}/schema.ts +1 -1
  176. package/src/integrations/{dsh → hosts/dsh}/session.ts +2 -2
  177. package/src/integrations/{dsh → hosts/dsh}/skills.ts +1 -1
  178. package/src/integrations/{pi → hosts/pi}/mcp.ts +1 -1
  179. package/src/integrations/{pi → hosts/pi}/skills.ts +1 -1
  180. package/src/integrations/hosts/{registry.ts → plugin-registry.ts} +2 -2
  181. package/src/integrations/installation/pi-setup.ts +1 -1
  182. package/src/mcp.ts +1 -1
  183. package/src/model/history.ts +151 -26
  184. package/src/model/plugin-host.ts +26 -2
  185. package/src/model/workspace-config.ts +30 -0
  186. package/src/pbot.ts +13 -22
  187. package/src/plugin.ts +2 -2
  188. package/src/services/history/history-capture.ts +83 -0
  189. package/src/services/history/history-index.ts +48 -62
  190. package/src/services/history/history-migrate.ts +89 -0
  191. package/src/services/history/history-query.ts +415 -0
  192. package/src/services/history/summary-command.ts +69 -0
  193. package/src/services/history/summary-dimensions/monthly.ts +139 -0
  194. package/src/services/history/summary-dimensions/session.ts +149 -0
  195. package/src/services/history/summary-registry.ts +44 -0
  196. package/src/services/history/summary-runner.ts +352 -0
  197. package/src/services/workspace/workspace-config.ts +93 -5
  198. package/src/storage/history-files.ts +408 -188
  199. package/src/storage/history-format.ts +46 -60
  200. package/src/tools/history/actions.ts +8 -6
  201. package/src/tools/history/contract.ts +65 -20
  202. package/src/tools/history/dsh-tool.ts +17 -8
  203. package/src/tools/history/pi-tool.ts +21 -0
  204. package/src/tools/register.ts +3 -4
  205. package/src/ui/dsh/management.ts +27 -11
  206. package/src/ui/{confirmation.ts → pi/confirmation.ts} +1 -1
  207. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.d.ts +0 -4
  208. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.js +0 -79
  209. package/lib/extension/dsh/command.js +0 -50
  210. package/lib/extension/dsh/history.d.ts +0 -15
  211. package/lib/extension/dsh/history.js +0 -87
  212. package/lib/integrations/dsh/history-summary.d.ts +0 -11
  213. package/lib/integrations/dsh/history-summary.js +0 -36
  214. package/lib/integrations/dsh/history.d.ts +0 -16
  215. package/lib/integrations/dsh/history.js +0 -167
  216. package/lib/integrations/history-summary.d.ts +0 -4
  217. package/lib/integrations/history-summary.js +0 -32
  218. package/lib/integrations/hosts/antigravity.d.ts +0 -4
  219. package/lib/integrations/hosts/antigravity.js +0 -79
  220. package/lib/services/history/history-service.d.ts +0 -106
  221. package/lib/services/history/history-service.js +0 -242
  222. package/lib/storage/acp-history.d.ts +0 -10
  223. package/lib/storage/acp-history.js +0 -57
  224. package/src/extension/command.ts +0 -76
  225. package/src/extension/dsh/command.ts +0 -54
  226. package/src/extension/dsh/history.ts +0 -74
  227. package/src/extension/history.ts +0 -26
  228. package/src/integrations/dsh/history-summary.ts +0 -39
  229. package/src/integrations/dsh/history.ts +0 -84
  230. package/src/integrations/history-summary.ts +0 -30
  231. package/src/integrations/hosts/antigravity.ts +0 -83
  232. package/src/integrations/pi/history.ts +0 -99
  233. package/src/services/history/history-service.ts +0 -195
  234. package/src/storage/acp-history.ts +0 -49
  235. package/src/tools/history/tool.ts +0 -19
  236. /package/lib/antigravity-plugin/lib/integrations/hosts/{registry.d.ts → plugin-registry.d.ts} +0 -0
  237. /package/lib/{extension/acp-worker.d.ts → antigravity-plugin/lib/model/history.js} +0 -0
  238. /package/lib/extension/{dsh → hosts/dsh}/acp-member.d.ts +0 -0
  239. /package/lib/extension/{dsh → hosts/dsh}/command.d.ts +0 -0
  240. /package/lib/extension/{dsh → hosts/dsh}/files.d.ts +0 -0
  241. /package/lib/extension/{setup-guard.js → setup/guard.js} +0 -0
  242. /package/lib/integrations/acp/{claude.d.ts → claude-settings.d.ts} +0 -0
  243. /package/lib/integrations/acp/{claude.js → claude-settings.js} +0 -0
  244. /package/lib/integrations/{dsh → hosts/dsh}/mcp.js +0 -0
  245. /package/lib/integrations/{dsh → hosts/dsh}/messages.d.ts +0 -0
  246. /package/lib/integrations/{dsh → hosts/dsh}/messages.js +0 -0
  247. /package/lib/integrations/{dsh → hosts/dsh}/root-agents.d.ts +0 -0
  248. /package/lib/integrations/{dsh → hosts/dsh}/root-agents.js +0 -0
  249. /package/lib/integrations/{dsh → hosts/dsh}/schema.d.ts +0 -0
  250. /package/lib/integrations/{dsh → hosts/dsh}/skills.d.ts +0 -0
  251. /package/lib/integrations/hosts/{registry.d.ts → plugin-registry.d.ts} +0 -0
  252. /package/src/extension/{setup-guard.ts → setup/guard.ts} +0 -0
  253. /package/src/integrations/acp/{claude.ts → claude-settings.ts} +0 -0
  254. /package/src/integrations/{dsh → hosts/dsh}/messages.ts +0 -0
  255. /package/src/integrations/{dsh → hosts/dsh}/root-agents.ts +0 -0
  256. /package/src/integrations/{pi → hosts/pi}/agent-tools.ts +0 -0
@@ -1,23 +1,38 @@
1
- import { linkSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmdirSync, unlinkSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
1
+ import { spawnSync } from "node:child_process";
2
+ import { linkSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, unlinkSync } from "node:fs";
3
+ import { basename, dirname, join, relative, resolve } from "node:path";
3
4
  import { isDeepStrictEqual } from "node:util";
4
- import { object } from "../common/json.js";
5
5
  import { requireThat } from "../common/validation.js";
6
- import type { HistoryArchive, HistoryHost, HistoryIdentity, HistoryRecord, HistorySummary, RawHistory } from "../model/history.js";
6
+ import type { HistoryHost, HistoryLayout, RawHistory, SummaryArtifact } from "../model/history.js";
7
7
  import { internalPath, readJsonFile, syncDirectory, writeJsonFile } from "./atomic-json.js";
8
8
  import { fileId, privateDirectory } from "./file-access.js";
9
- import { hierarchicalHistory, isHistoryHost, legacyHistory, matchIdentity, rawHistory, splitLegacy, summaryData } from "./history-format.js";
9
+ import { isHistoryHost, isSummaryDimension, matchIdentity, rawHistory, summaryArtifact } from "./history-format.js";
10
+
11
+ const yearPattern = /^\d{4}$/;
12
+ const monthPattern = /^(?:0[1-9]|1[0-2])$/;
13
+ const monthlyIdPattern = /^(\d{4})-(0[1-9]|1[0-2])$/;
14
+ const monthlyRelativeJsonPattern = /^(?:\d{4}\/(?:0[1-9]|1[0-2])|unknown)\/[^/]+\.json$/;
15
+ const yearlyRelativeJsonPattern = /^(?:\d{4}|unknown)\/[^/]+\.json$/;
16
+ export const unknownHistoryBucket = "unknown";
17
+ type BucketDepth = "month" | "year";
10
18
 
11
19
  function ordinaryDirectory(path: string) {
12
20
  const stat = lstatSync(path, { throwIfNoEntry: false });
13
21
  if (!stat) return false;
14
- requireThat(stat.isDirectory(), "历史目录必须使用普通目录:" + path);
22
+ requireThat(stat.isDirectory() && !stat.isSymbolicLink(), "历史目录必须使用普通目录:" + path);
15
23
  return true;
16
24
  }
25
+
26
+ function ordinaryFile(path: string) {
27
+ const stat = lstatSync(path, { throwIfNoEntry: false });
28
+ return Boolean(stat && stat.isFile() && !stat.isSymbolicLink());
29
+ }
30
+
17
31
  function sharedDirectory(path: string) {
18
32
  const parent = dirname(path);
19
33
  return (basename(parent) !== ".pbot" || ordinaryDirectory(parent)) && ordinaryDirectory(path);
20
34
  }
35
+
21
36
  function ensureDirectory(path: string) {
22
37
  if (sharedDirectory(path)) return;
23
38
  const first = mkdirSync(path, { recursive: true, mode: 0o700 });
@@ -29,228 +44,433 @@ function ensureDirectory(path: string) {
29
44
  }
30
45
  }
31
46
  }
32
- function legacyDirectory(root: string, host: HistoryHost) {
33
- const source = join(root, "." + host), parent = join(source, "pbot"), directory = join(parent, "history");
34
- return ordinaryDirectory(source) && ordinaryDirectory(parent) && ordinaryDirectory(directory) ? directory : undefined;
47
+
48
+ export function earliestTimestamp(values: readonly (string | undefined)[]): string | undefined {
49
+ let bestMs: number | undefined;
50
+ let bestValue: string | undefined;
51
+ for (const value of values) {
52
+ if (!value) continue;
53
+ const ms = Date.parse(value);
54
+ if (Number.isNaN(ms)) continue;
55
+ if (bestMs === undefined || ms < bestMs) {
56
+ bestMs = ms;
57
+ bestValue = value;
58
+ }
59
+ }
60
+ return bestValue;
61
+ }
62
+
63
+ /** Resolve UTC YYYY/MM bucket from an ISO timestamp, falling back to "unknown". */
64
+ export function historyBucketFromTimestamp(timestamp?: string): string {
65
+ if (!timestamp) return unknownHistoryBucket;
66
+ const ms = Date.parse(timestamp);
67
+ if (Number.isNaN(ms)) return unknownHistoryBucket;
68
+ const date = new Date(ms);
69
+ const year = String(date.getUTCFullYear()).padStart(4, "0");
70
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
71
+ return `${year}/${month}`;
72
+ }
73
+
74
+ export function rawHistoryBucket(raw: Pick<RawHistory, "exchanges">): string {
75
+ const earliest = earliestTimestamp(raw.exchanges.map(item => item.from))
76
+ ?? earliestTimestamp(raw.exchanges.map(item => item.to));
77
+ return historyBucketFromTimestamp(earliest);
78
+ }
79
+
80
+ export function summaryArtifactBucket(artifact: Pick<SummaryArtifact, "id" | "dimension" | "from" | "to">): string {
81
+ if (artifact.dimension === "monthly") {
82
+ const match = monthlyIdPattern.exec(artifact.id);
83
+ if (match) return match[1]!;
84
+ const bucket = historyBucketFromTimestamp(artifact.from || artifact.to);
85
+ return bucket === unknownHistoryBucket ? unknownHistoryBucket : bucket.slice(0, 4);
86
+ }
87
+ return historyBucketFromTimestamp(artifact.from || artifact.to);
88
+ }
89
+
90
+ const topLevelJsonNames = (directory: string) =>
91
+ readdirSync(directory, { withFileTypes: true })
92
+ .filter(entry => entry.isFile() && !entry.isSymbolicLink() && entry.name.endsWith(".json"))
93
+ .map(entry => entry.name)
94
+ .sort();
95
+
96
+ function bucketDirs(directory: string, depth: BucketDepth): string[] {
97
+ if (!ordinaryDirectory(directory)) return [];
98
+ const buckets: string[] = [];
99
+ const entries = readdirSync(directory, { withFileTypes: true });
100
+ const years = entries
101
+ .filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && yearPattern.test(entry.name))
102
+ .map(entry => entry.name)
103
+ .sort((a, b) => b.localeCompare(a));
104
+ if (depth === "year") {
105
+ buckets.push(...years);
106
+ } else {
107
+ for (const year of years) {
108
+ const yearDir = join(directory, year);
109
+ const months = readdirSync(yearDir, { withFileTypes: true })
110
+ .filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && monthPattern.test(entry.name))
111
+ .map(entry => entry.name)
112
+ .sort((a, b) => b.localeCompare(a));
113
+ for (const month of months) buckets.push(`${year}/${month}`);
114
+ }
115
+ }
116
+ if (entries.some(entry => entry.isDirectory() && !entry.isSymbolicLink() && entry.name === unknownHistoryBucket)) {
117
+ buckets.push(unknownHistoryBucket);
118
+ }
119
+ return buckets;
120
+ }
121
+
122
+ function listLayoutJsonFiles(directory: string, layout: HistoryLayout, depth: BucketDepth = "month"): string[] {
123
+ if (!ordinaryDirectory(directory)) return [];
124
+ if (layout === "flat") return topLevelJsonNames(directory);
125
+ const results: string[] = [];
126
+ for (const bucket of bucketDirs(directory, depth)) {
127
+ const dir = join(directory, bucket);
128
+ for (const name of topLevelJsonNames(dir)) {
129
+ results.push(`${bucket}/${name}`);
130
+ }
131
+ }
132
+ return results;
35
133
  }
36
- function removeEmptyDirectory(directory: string) {
37
- try { rmdirSync(directory); syncDirectory(dirname(directory)); }
38
- catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
134
+
135
+ function locateLayoutFile(directory: string, name: string, layout: HistoryLayout, depth: BucketDepth = "month"): string | undefined {
136
+ if (!ordinaryDirectory(directory)) return undefined;
137
+ if (layout === "flat") {
138
+ return ordinaryFile(join(directory, name)) ? name : undefined;
139
+ }
140
+ for (const bucket of bucketDirs(directory, depth)) {
141
+ if (ordinaryFile(join(directory, bucket, name))) return `${bucket}/${name}`;
142
+ }
143
+ return undefined;
39
144
  }
40
- const names = (directory: string) => readdirSync(directory).filter(name => name.endsWith(".json"));
145
+
41
146
  const filename = (id: string) => fileId(id) + ".json";
42
147
  const diagnostic = (path: string, error: unknown) => path + ": " + String(error);
148
+
43
149
  function optional<T>(read: () => T): T | undefined {
44
150
  try { return read(); }
45
151
  catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
46
152
  }
47
- function namedRaw(value: unknown, name: string): RawHistory {
153
+
154
+ function namedRaw(value: unknown, relPath: string): RawHistory {
48
155
  const raw = rawHistory(value);
49
- requireThat(name === filename(raw.id), "历史文件名与根 ID 不匹配。");
156
+ requireThat(basename(relPath) === filename(raw.id), "历史文件名与根 ID 不匹配。");
50
157
  return raw;
51
158
  }
52
- const readRaw = (directory: string, name: string) => readJsonFile(directory, "raw/" + name, value => namedRaw(value, name));
53
- const readSummaries = (directory: string, layer: "summary" | "hierarchical", raw: RawHistory) =>
54
- optional(() => readJsonFile(directory, layer + "/" + filename(raw.id), value => hierarchicalHistory(value, raw)));
55
-
56
- type OldFile = { raw: RawHistory; mixed?: HistoryRecord; summaries?: HistorySummary[] };
57
- function oldFile(value: unknown, name: string, privateHost?: HistoryHost): OldFile {
58
- if (privateHost === undefined && object(value) && !("nodes" in value)) return { raw: namedRaw(value, name) };
59
- const mixed = legacyHistory(value, privateHost);
60
- requireThat(name === filename(mixed.id), "历史文件名与根 ID 不匹配。");
61
- return { ...splitLegacy(mixed), mixed };
159
+
160
+ function namedSummary(value: unknown, relPath: string, dimension: string): SummaryArtifact {
161
+ const artifact = summaryArtifact(value, dimension);
162
+ requireThat(basename(relPath) === filename(artifact.id), "历史摘要文件名与 ID 不匹配。");
163
+ return artifact;
164
+ }
165
+
166
+ /**
167
+ * Use ripgrep when available to pre-filter candidate JSON files containing a literal query.
168
+ * Queries containing JSON-escaped characters fall back to direct Node reading to avoid false negatives.
169
+ */
170
+ function canPrefilterWithRg(query: string): boolean {
171
+ return query.length > 0 && !/["\\\n\r\t]/.test(query);
62
172
  }
63
- /** Relocate an already validated file without reserializing it. A separate mount needs an atomic JSON copy instead. */
64
- function linkArchive(directory: string, from: string, to: string) {
65
- const target = internalPath(directory, to);
66
- try { linkSync(internalPath(directory, from), target); }
67
- catch (error) { if ((error as NodeJS.ErrnoException).code === "EXDEV") return false; throw error; }
68
- syncDirectory(dirname(target)); return true;
173
+
174
+ export function findCandidateJsonFiles(
175
+ directory: string,
176
+ query: string,
177
+ layout: HistoryLayout = "monthly",
178
+ depth: BucketDepth = "month",
179
+ ): string[] {
180
+ if (!ordinaryDirectory(directory)) return [];
181
+ const trimmed = query.trim();
182
+ if (!trimmed) return listLayoutJsonFiles(directory, layout, depth);
183
+
184
+ const relativePattern = depth === "year" ? yearlyRelativeJsonPattern : monthlyRelativeJsonPattern;
185
+
186
+ if (canPrefilterWithRg(trimmed)) {
187
+ const args = [
188
+ "--ignore-case",
189
+ "--fixed-strings",
190
+ "--files-with-matches",
191
+ "--glob", "*.json",
192
+ "--no-ignore",
193
+ "--hidden",
194
+ ...(layout === "flat" ? ["--max-depth", "1"] : []),
195
+ "--",
196
+ trimmed,
197
+ directory,
198
+ ];
199
+ const result = spawnSync("rg", args, { encoding: "utf8", maxBuffer: 8 * 1024 * 1024 });
200
+ if (!result.error && (result.status === 0 || result.status === 1)) {
201
+ if (result.status === 1) return [];
202
+ const base = realpathSync(directory);
203
+ const matched: string[] = [];
204
+ for (const line of result.stdout.split(/\r?\n/)) {
205
+ const trimmedLine = line.trim();
206
+ if (!trimmedLine) continue;
207
+ const rel = relative(base, resolve(trimmedLine)).replaceAll("\\", "/");
208
+ if (layout === "flat") {
209
+ if (!rel.includes("/") && rel.endsWith(".json")) matched.push(rel);
210
+ } else if (relativePattern.test(rel)) {
211
+ matched.push(rel);
212
+ }
213
+ }
214
+ return matched;
215
+ }
216
+ }
217
+
218
+ // Fallback: direct case-insensitive file scan via Node built-ins.
219
+ const needle = trimmed.toLowerCase();
220
+ const matched: string[] = [];
221
+ for (const rel of listLayoutJsonFiles(directory, layout, depth)) {
222
+ try {
223
+ const content = readFileSync(join(directory, rel), "utf8");
224
+ if (content.toLowerCase().includes(needle)) matched.push(rel);
225
+ } catch { /* Individual unreadable files are reported during JSON parse if needed. */ }
226
+ }
227
+ return matched;
69
228
  }
70
- function retire(directory: string, relative: string) {
71
- const path = internalPath(directory, relative);
72
- unlinkSync(path); syncDirectory(dirname(path));
229
+
230
+ export interface FlatHistoryInventory {
231
+ rawCount: number;
232
+ summaryCount: number;
233
+ total: number;
234
+ message?: string;
73
235
  }
74
236
 
75
237
  export class HistoryFiles {
76
238
  #warnings: string[] = [];
77
239
  #rawWarnings: string[] = [];
78
- constructor(readonly directory: string, readonly host: HistoryHost = "pi") { requireThat(isHistoryHost(host), "历史来源无效。"); }
240
+
241
+ constructor(
242
+ readonly directory: string,
243
+ readonly host: HistoryHost = "pi",
244
+ readonly layout: HistoryLayout = "monthly",
245
+ ) {
246
+ requireThat(isHistoryHost(host), "历史来源无效。");
247
+ }
248
+
79
249
  get warnings(): readonly string[] { return this.#warnings; }
80
250
  get rawWarnings(): readonly string[] { return this.#rawWarnings; }
81
251
 
82
- list(legacyRoot?: string): HistoryArchive[] {
83
- this.#warnings = []; this.#rawWarnings = [];
84
- const archives = new Map<string, HistoryArchive>();
85
- const rawWarning = (path: string, error: unknown) => {
86
- const message = diagnostic(path, error); this.#warnings.push(message); this.#rawWarnings.push(message);
87
- };
88
- const scan = (directory: string, layout: "private" | "shared" | "raw") => {
89
- for (const name of names(directory)) {
90
- const path = join(directory, name);
91
- try {
92
- for (;;) {
93
- const before = lstatSync(path, { bigint: true });
94
- const file = readJsonFile(directory, name, (value): OldFile | undefined => {
95
- if (layout !== "private" && object(value) && isHistoryHost(value.host) && value.host !== this.host) return undefined;
96
- return layout === "raw" ? { raw: namedRaw(value, name) } : oldFile(value, name, layout === "private" ? this.host : undefined);
97
- });
98
- if (!file) break;
99
- const { raw } = file;
100
- if (file.summaries) { archives.set(raw.id, { raw, summaries: file.summaries }); break; }
101
- const layer = layout === "raw" ? "summary" : "hierarchical";
102
- let summaries: HistorySummary[] | null, warning: string | undefined;
103
- try { summaries = readSummaries(this.directory, layer, raw)?.summaries ?? []; }
104
- catch (error) { warning = diagnostic(join(this.directory, layer, name), error); summaries = null; }
105
- // Peers take no lock. Retry if a native update replaced the raw file between reads.
106
- const after = lstatSync(path, { bigint: true });
107
- if (before.ino !== after.ino || before.ctimeNs !== after.ctimeNs) continue;
108
- if (warning) this.#warnings.push(warning);
109
- archives.set(raw.id, { raw, summaries }); break;
110
- }
111
- } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") rawWarning(path, error); }
112
- }
113
- };
114
- // Read the destinations last: a concurrent migration publishes both files before retiring its source.
115
- if (legacyRoot && this.host !== "claude") {
116
- try { const directory = legacyDirectory(legacyRoot, this.host); if (directory) scan(directory, "private"); }
117
- catch (error) { rawWarning(join(legacyRoot, "." + this.host, "pbot/history"), error); }
118
- }
119
- try {
120
- if (sharedDirectory(this.directory)) {
121
- scan(this.directory, "shared");
122
- const directory = join(this.directory, "raw");
123
- if (ordinaryDirectory(directory)) scan(directory, "raw");
124
- }
125
- } catch (error) { rawWarning(this.directory, error); }
126
- return [...archives.values()];
252
+ get rawDirectory(): string { return join(this.directory, "raw"); }
253
+ get summariesDirectory(): string { return join(this.directory, "summaries"); }
254
+ summaryDirectory(dimension: string): string {
255
+ requireThat(isSummaryDimension(dimension), "历史摘要维度无效:" + dimension);
256
+ return join(this.summariesDirectory, dimension);
127
257
  }
128
258
 
129
- /** The callback is synchronous: no SDK reads or model work can hold this source's write lock. */
130
- control<T>(operation: () => T): T {
131
- requireThat(this.host !== "claude", "Claude 历史归档只读。");
259
+ private withLock<T>(lockName: string, label: string, operation: () => T): T {
132
260
  ensureDirectory(this.directory);
133
- const lock = join(this.directory, ".write-" + this.host);
261
+ const lock = join(this.directory, lockName);
134
262
  try { mkdirSync(lock, { mode: 0o700 }); }
135
263
  catch (error) {
136
- if ((error as NodeJS.ErrnoException).code === "EEXIST") throw Object.assign(new Error("历史来源写锁被占用:" + this.host), { code: "PBOT_HISTORY_BUSY" });
264
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
265
+ throw Object.assign(new Error("历史写锁被占用:" + label), { code: "PBOT_HISTORY_BUSY" });
266
+ }
137
267
  throw error;
138
268
  }
139
269
  try { return operation(); } finally { rmdirSync(lock); }
140
270
  }
141
271
 
142
- private writable(identity: HistoryIdentity) {
143
- requireThat(this.host !== "claude" && identity.host === this.host, "历史归档只允许所属 Pi/dsh 来源写入。");
144
- const name = filename(identity.id);
145
- requireThat(!lstatSync(join(this.directory, name), { throwIfNoEntry: false }), "根 ID 已有旧历史归档:" + name);
146
- return name;
272
+ /** Synchronous host write lock for raw history files. */
273
+ control<T>(operation: () => T): T {
274
+ return this.withLock(".write-" + this.host, this.host, operation);
275
+ }
276
+
277
+ /** Synchronous dimension write lock for derived summary files. */
278
+ controlSummary<T>(dimension: string, operation: () => T): T {
279
+ requireThat(isSummaryDimension(dimension), "历史摘要维度无效:" + dimension);
280
+ return this.withLock(".write-summary-" + dimension, "summary:" + dimension, operation);
281
+ }
282
+
283
+ /** Synchronous migration lock for explicit layout migration. */
284
+ controlMigration<T>(operation: () => T): T {
285
+ return this.withLock(".write-migrate", "migrate", operation);
286
+ }
287
+
288
+ /** Detect unmigrated top-level flat JSON files when running under monthly layout. */
289
+ detectFlatFiles(): FlatHistoryInventory {
290
+ if (!sharedDirectory(this.directory)) return { rawCount: 0, summaryCount: 0, total: 0 };
291
+ const rawCount = ordinaryDirectory(this.rawDirectory) ? topLevelJsonNames(this.rawDirectory).length : 0;
292
+ let summaryCount = 0;
293
+ for (const dim of this.listDimensions()) {
294
+ const dir = this.summaryDirectory(dim);
295
+ if (ordinaryDirectory(dir)) summaryCount += topLevelJsonNames(dir).length;
296
+ }
297
+ const total = rawCount + summaryCount;
298
+ if (total === 0) return { rawCount: 0, summaryCount: 0, total: 0 };
299
+ return {
300
+ rawCount,
301
+ summaryCount,
302
+ total,
303
+ message:
304
+ `检测到 ${total} 个未迁移的平铺历史文件(raw ${rawCount},summaries ${summaryCount});当前为年月目录布局(history.layout: monthly),未迁移文件不会被读取。` +
305
+ `请运行 /pbot history migrate 整理到 YYYY/MM/ 目录,或在 .pbot/config.json 中设置 "history": { "layout": "flat" } 切回平铺布局。`,
306
+ };
307
+ }
308
+
309
+ listFlatRawFiles(): string[] {
310
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.rawDirectory)) return [];
311
+ return topLevelJsonNames(this.rawDirectory);
312
+ }
313
+
314
+ listFlatSummaryFiles(dimension: string): string[] {
315
+ requireThat(isSummaryDimension(dimension), "历史摘要维度无效:" + dimension);
316
+ const dir = this.summaryDirectory(dimension);
317
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory) || !ordinaryDirectory(dir)) return [];
318
+ return topLevelJsonNames(dir);
319
+ }
320
+
321
+ readFlatRawFile(name: string): RawHistory {
322
+ return readJsonFile(this.directory, "raw/" + name, value => namedRaw(value, name));
323
+ }
324
+
325
+ readFlatSummaryFile(dimension: string, name: string): SummaryArtifact {
326
+ requireThat(isSummaryDimension(dimension), "历史摘要维度无效:" + dimension);
327
+ return readJsonFile(this.directory, `summaries/${dimension}/${name}`, value => namedSummary(value, name, dimension));
328
+ }
329
+
330
+ /** Atomically move a file within .pbot/history/ without ever overwriting an existing destination. */
331
+ moveHistoryFile(fromRelative: string, toRelative: string): "moved" | "conflict" {
332
+ ensureDirectory(this.directory);
333
+ const src = internalPath(this.directory, fromRelative);
334
+ const dstParentRel = dirname(toRelative);
335
+ if (dstParentRel && dstParentRel !== ".") {
336
+ privateDirectory(this.directory, dstParentRel);
337
+ }
338
+ const dst = internalPath(this.directory, toRelative);
339
+ try {
340
+ linkSync(src, dst);
341
+ } catch (error) {
342
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return "conflict";
343
+ throw error;
344
+ }
345
+ unlinkSync(src);
346
+ syncDirectory(dirname(dst));
347
+ syncDirectory(dirname(src));
348
+ return "moved";
349
+ }
350
+
351
+ listRaw(filterHost?: HistoryHost, onlyFiles?: readonly string[]): RawHistory[] {
352
+ this.#warnings = [];
353
+ this.#rawWarnings = [];
354
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.rawDirectory)) return [];
355
+ const files = onlyFiles ?? listLayoutJsonFiles(this.rawDirectory, this.layout);
356
+ const results: RawHistory[] = [];
357
+ for (const rel of files) {
358
+ const path = join(this.rawDirectory, rel);
359
+ try {
360
+ const raw = readJsonFile(this.directory, "raw/" + rel, value => namedRaw(value, rel));
361
+ if (filterHost !== undefined && raw.host !== filterHost) continue;
362
+ results.push(raw);
363
+ } catch (error) {
364
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
365
+ const message = diagnostic(path, error);
366
+ this.#warnings.push(message);
367
+ this.#rawWarnings.push(message);
368
+ }
369
+ }
370
+ }
371
+ return results;
372
+ }
373
+
374
+ readRaw(id: string): RawHistory | undefined {
375
+ const name = filename(id);
376
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.rawDirectory)) return undefined;
377
+ const rel = locateLayoutFile(this.rawDirectory, name, this.layout);
378
+ if (!rel) return undefined;
379
+ return optional(() => readJsonFile(this.directory, "raw/" + rel, value => namedRaw(value, rel)));
147
380
  }
148
381
 
149
382
  saveRaw(raw: RawHistory) {
150
- const name = this.writable(raw);
151
- rawHistory(raw); ensureDirectory(this.directory);
152
- const current = optional(() => readRaw(this.directory, name));
383
+ requireThat(isHistoryHost(raw.host) && raw.host === this.host, "历史归档只允许所属来源写入。");
384
+ rawHistory(raw);
385
+ ensureDirectory(this.directory);
386
+ const name = filename(raw.id);
387
+ const existingRel = ordinaryDirectory(this.rawDirectory)
388
+ ? locateLayoutFile(this.rawDirectory, name, this.layout)
389
+ : undefined;
390
+ const bucket = this.layout === "monthly" ? rawHistoryBucket(raw) : undefined;
391
+ const rel = existingRel ?? (bucket ? `${bucket}/${name}` : name);
392
+ const current = optional(() => readJsonFile(this.directory, "raw/" + rel, value => namedRaw(value, rel)));
153
393
  if (current) {
154
394
  matchIdentity(current, raw);
155
395
  if (isDeepStrictEqual(current, raw)) return;
156
396
  } else {
157
- for (const layer of ["summary", "hierarchical"]) {
158
- const directory = join(this.directory, layer);
159
- if (lstatSync(directory, { throwIfNoEntry: false })?.isDirectory()) {
160
- requireThat(!lstatSync(join(directory, name), { throwIfNoEntry: false }), "历史根 ID 已有关联的摘要文件:" + name);
161
- }
162
- }
163
- privateDirectory(this.directory, "raw");
164
- }
165
- requireThat(writeJsonFile(this.directory, "raw/" + name, raw, rawHistory, !current), "历史根 ID 已被占用:" + name);
166
- }
167
-
168
- saveSummaries(identity: HistoryIdentity, summaries: readonly HistorySummary[]) {
169
- const name = this.writable(identity);
170
- requireThat(sharedDirectory(this.directory), "历史原文目录不存在:" + this.directory);
171
- const raw = readRaw(this.directory, name);
172
- matchIdentity(raw, identity);
173
- this.publishSummaries(raw, summaries);
174
- }
175
-
176
- private publishSummaries(raw: RawHistory, summaries: readonly HistorySummary[], source?: "mixed" | "hierarchical") {
177
- const { host, id, sessionId } = raw, path = "summary/" + filename(id);
178
- const validate = (data: unknown) => hierarchicalHistory(data, raw);
179
- const value = validate({ host, id, sessionId, summaries: summaries.map(summaryData) });
180
- const previous = readSummaries(this.directory, "summary", raw);
181
- if (previous) {
182
- if (isDeepStrictEqual(previous, value)) {
183
- if (source) syncDirectory(join(this.directory, "summary"));
184
- return;
185
- }
186
- requireThat(!source, "历史摘要迁移冲突,请核对已有文件:" + path);
187
- } else {
188
- privateDirectory(this.directory, "summary");
189
- if (source === "hierarchical" && linkArchive(this.directory, "hierarchical/" + filename(id), path)) return;
397
+ privateDirectory(this.directory, bucket ? `raw/${bucket}` : "raw");
190
398
  }
191
- requireThat(writeJsonFile(this.directory, path, value, validate, !previous), "历史摘要文件已被占用:" + path);
192
- }
193
-
194
- private migrateFile(name: string, privateDir?: string) {
195
- const readOld = (directory: string, host?: HistoryHost) => readJsonFile(directory, name, value => oldFile(value, name, host));
196
- const shared = optional(() => readOld(this.directory)), local = privateDir ? readOld(privateDir, this.host) : undefined;
197
- const source = shared ?? local;
198
- if (!source) return;
199
- const { raw } = source;
200
- if (!local && raw.host !== this.host) return;
201
- if (shared && local) requireThat(isDeepStrictEqual(shared.raw, local.raw) && (!shared.mixed || isDeepStrictEqual(shared.mixed, local.mixed)),
202
- "历史归档迁移冲突,请核对新旧文件:" + name);
203
- const target = optional(() => readRaw(this.directory, name));
204
- requireThat(!target || isDeepStrictEqual(target, raw), "历史原文迁移冲突,请核对已有文件:" + name);
205
- const oldLayer = readSummaries(this.directory, "hierarchical", raw), embedded = source.summaries ?? local?.summaries;
206
- requireThat(!oldLayer || !embedded || isDeepStrictEqual(oldLayer.summaries, embedded), "旧历史摘要不一致:" + name);
207
- const summaries = embedded ?? oldLayer?.summaries;
208
- // The raw file makes this pair discoverable. Publish summaries first; never overwrite a migration conflict.
209
- if (summaries) this.publishSummaries(raw, summaries, oldLayer ? "hierarchical" : "mixed");
210
- else requireThat(!readSummaries(this.directory, "summary", raw) || target, "历史摘要迁移冲突:" + name);
211
- if (!target) {
212
- privateDirectory(this.directory, "raw");
213
- const path = "raw/" + name;
214
- if (!shared || shared.mixed || !linkArchive(this.directory, name, path)) {
215
- requireThat(writeJsonFile(this.directory, path, raw, rawHistory, true), "历史原文迁移冲突:" + name);
399
+ requireThat(writeJsonFile(this.directory, "raw/" + rel, raw, rawHistory, !current), "历史根 ID 已被占用:" + rel);
400
+ }
401
+
402
+ listDimensions(): string[] {
403
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory)) return [];
404
+ const entries = readdirSync(this.summariesDirectory, { withFileTypes: true });
405
+ return entries
406
+ .filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && isSummaryDimension(entry.name))
407
+ .map(entry => entry.name)
408
+ .sort();
409
+ }
410
+
411
+ private summaryBucketDepth(dimension: string): BucketDepth {
412
+ return dimension === "monthly" ? "year" : "month";
413
+ }
414
+
415
+ listSummaries(dimension: string, onlyFiles?: readonly string[]): SummaryArtifact[] {
416
+ requireThat(isSummaryDimension(dimension), "历史摘要维度无效:" + dimension);
417
+ const dir = this.summaryDirectory(dimension);
418
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory) || !ordinaryDirectory(dir)) return [];
419
+ const files = onlyFiles ?? listLayoutJsonFiles(dir, this.layout, this.summaryBucketDepth(dimension));
420
+ const results: SummaryArtifact[] = [];
421
+ for (const rel of files) {
422
+ const path = join(dir, rel);
423
+ try {
424
+ results.push(readJsonFile(this.directory, `summaries/${dimension}/${rel}`, value => namedSummary(value, rel, dimension)));
425
+ } catch (error) {
426
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
427
+ this.#warnings.push(diagnostic(path, error));
428
+ }
216
429
  }
217
- } else syncDirectory(join(this.directory, "raw"));
218
- syncDirectory(this.directory);
219
- if (oldLayer) {
220
- retire(this.directory, "hierarchical/" + name);
221
- removeEmptyDirectory(join(this.directory, "hierarchical"));
222
430
  }
223
- if (shared) retire(this.directory, name);
224
- if (privateDir) retire(privateDir, name);
225
- }
226
-
227
- migrate(root: string) {
228
- if (this.host === "claude") return;
229
- const legacy = legacyDirectory(root, this.host);
230
- const shared = sharedDirectory(this.directory) ? names(this.directory).filter(name => {
231
- try { return readJsonFile(this.directory, name, value => object(value) && value.host === this.host); }
232
- catch { return false; } // list reports unreadable roots.
233
- }) : [];
234
- if (!legacy && !shared.length) return;
235
- this.control(() => {
236
- const directory = legacy && legacyDirectory(root, this.host), errors: string[] = [];
237
- const migrateFiles = (local: string[]) => {
238
- const privateNames = new Set(local);
239
- for (const name of new Set([...local, ...shared])) {
240
- try { this.migrateFile(name, privateNames.has(name) ? directory : undefined); }
241
- catch (error) {
242
- if ((error as NodeJS.ErrnoException).code) throw error;
243
- errors.push(diagnostic(name, error));
244
- }
245
- }
246
- };
247
- if (directory) {
248
- requireThat(realpathSync(directory) !== realpathSync(this.directory), "新旧历史目录指向同一位置。");
249
- const lock = join(directory, ".write"); mkdirSync(lock, { mode: 0o700 });
250
- try { migrateFiles(names(directory)); } finally { rmdirSync(lock); }
251
- removeEmptyDirectory(directory); removeEmptyDirectory(dirname(directory));
252
- } else migrateFiles([]);
253
- if (errors.length) throw new Error(errors.join("\n"));
254
- });
431
+ return results;
432
+ }
433
+
434
+ readSummary(dimension: string, id: string): SummaryArtifact | undefined {
435
+ requireThat(isSummaryDimension(dimension), "历史摘要维度无效:" + dimension);
436
+ const dir = this.summaryDirectory(dimension);
437
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory) || !ordinaryDirectory(dir)) return undefined;
438
+ const name = filename(id);
439
+ const rel = locateLayoutFile(dir, name, this.layout, this.summaryBucketDepth(dimension));
440
+ if (!rel) return undefined;
441
+ return optional(() => readJsonFile(this.directory, `summaries/${dimension}/${rel}`, value => namedSummary(value, rel, dimension)));
442
+ }
443
+
444
+ saveSummary(artifact: SummaryArtifact) {
445
+ summaryArtifact(artifact);
446
+ ensureDirectory(this.directory);
447
+ const name = filename(artifact.id);
448
+ const dir = this.summaryDirectory(artifact.dimension);
449
+ const depth = this.summaryBucketDepth(artifact.dimension);
450
+ const existingRel = ordinaryDirectory(this.summariesDirectory) && ordinaryDirectory(dir)
451
+ ? locateLayoutFile(dir, name, this.layout, depth)
452
+ : undefined;
453
+ const bucket = this.layout === "monthly" ? summaryArtifactBucket(artifact) : undefined;
454
+ const rel = existingRel ?? (bucket ? `${bucket}/${name}` : name);
455
+ const relativePath = `summaries/${artifact.dimension}/${rel}`;
456
+ privateDirectory(this.directory, dirname(relativePath));
457
+ const current = optional(() => readJsonFile(this.directory, relativePath, value => namedSummary(value, rel, artifact.dimension)));
458
+ if (current && isDeepStrictEqual(current, artifact)) return;
459
+ requireThat(
460
+ writeJsonFile(this.directory, relativePath, artifact, value => summaryArtifact(value, artifact.dimension), !current),
461
+ "历史摘要文件已被占用:" + relativePath,
462
+ );
463
+ }
464
+
465
+ /** Isolated read-only candidate search across raw/ and summaries/<dimension>/. */
466
+ searchCandidateRaw(query: string): RawHistory[] {
467
+ const names = findCandidateJsonFiles(this.rawDirectory, query, this.layout, "month");
468
+ return this.listRaw(undefined, names);
469
+ }
470
+
471
+ searchCandidateSummaries(dimension: string, query: string): SummaryArtifact[] {
472
+ const dir = this.summaryDirectory(dimension);
473
+ const names = findCandidateJsonFiles(dir, query, this.layout, this.summaryBucketDepth(dimension));
474
+ return this.listSummaries(dimension, names);
255
475
  }
256
476
  }