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