@joshua-zyy/pi-claude-memory 0.0.0-stage → 1.0.0-beta.1
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.
- package/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +82 -3
- package/README.zh-CN.md +82 -0
- package/package.json +61 -6
- package/src/constants.ts +3 -0
- package/src/handlers/index-sessions.ts +16 -0
- package/src/handlers/session-backfill.ts +163 -0
- package/src/handlers/session-live-index.ts +120 -0
- package/src/handlers/standing-pin.ts +125 -0
- package/src/index.ts +71 -0
- package/src/lifecycle-timing.ts +54 -0
- package/src/paths.ts +12 -0
- package/src/project.ts +39 -0
- package/src/prompt-context.ts +49 -0
- package/src/store/atomic-lock-coordinator.ts +403 -0
- package/src/store/canonical-storage-path.ts +54 -0
- package/src/store/content-scanner.ts +101 -0
- package/src/store/db.ts +870 -0
- package/src/store/fts-query.ts +215 -0
- package/src/store/markdown-mutation-lock.ts +38 -0
- package/src/store/schema.ts +69 -0
- package/src/store/session-anchor-search.ts +472 -0
- package/src/store/session-indexer.ts +730 -0
- package/src/store/session-parser.ts +292 -0
- package/src/store/session-search.ts +220 -0
- package/src/store/sqlite-native.ts +241 -0
- package/src/store/standing-instructions.ts +258 -0
- package/src/store/topic-store.ts +212 -0
- package/src/tools/session-search-tool.ts +245 -0
- package/src/tools/shared-output-view.ts +170 -0
- package/src/tools/tool-result-views.ts +105 -0
- package/src/tools/topic-tools.ts +69 -0
- package/src/types.ts +3 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
This file records changes to the Pi Claude Memory fork. For previous Hermes releases, see the [upstream changelog](docs/upstream/CHANGELOG.md) in the repository.
|
|
4
|
+
|
|
5
|
+
## [1.0.0-beta.1]
|
|
6
|
+
|
|
7
|
+
First independent Beta candidate.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Global and project Markdown topic indexes, with user-authored standing instructions in either scope.
|
|
12
|
+
- Topic search (including short Chinese terms), read, explicit create and delete, and exact-fragment patching that preserves unrelated text.
|
|
13
|
+
- Stable project scoping for linked worktrees and isolation for unrelated repositories with the same name.
|
|
14
|
+
- An explicit empty-index hint at session start. Session history search stays available through SQLite snippets or raw JSONL line anchors.
|
|
15
|
+
- English and Simplified Chinese usage guides, with automated checks on Linux and Windows.
|
|
16
|
+
|
|
17
|
+
### Changed from Hermes
|
|
18
|
+
|
|
19
|
+
- Durable topics are stored as Markdown, not in SQLite. The fork uses its own data directory and does not import the Hermes store.
|
|
20
|
+
- Removed background learning, consolidation, pre-compaction memory flushes, and the Hermes skill manager. Pi's own compaction and skill support are unchanged.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Chandra Teja
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# Pi Claude Memory
|
|
2
|
+
|
|
3
|
+
English | [简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
Claude Code–style topic memory for [Pi](https://pi.dev), built as an independent fork of [pi-hermes-memory](https://github.com/chandra447/pi-hermes-memory).
|
|
6
|
+
|
|
7
|
+
- **Two short indexes.** Pi sees separate global and project topic summaries, then reads the matching Markdown file instead of loading every note.
|
|
8
|
+
- **Five topic tools.** Search, read, create, patch an exact fragment, or delete a topic explicitly. Creating a topic never overwrites another one.
|
|
9
|
+
- **Repository isolation.** Two repositories with the same name do not share memory; linked worktrees of one repository do.
|
|
10
|
+
- **No background learning.** `session_search` can find past Pi conversations without turning work updates into permanent notes. There is no Dreaming, automatic migration, or change to Pi compaction in v1.
|
|
11
|
+
|
|
12
|
+
## Install the Beta
|
|
13
|
+
|
|
14
|
+
Requires Pi 1.7+ and Node 22.19+. Use a separate Pi profile by setting `PI_CODING_AGENT_DIR` and `PI_CODING_AGENT_SESSION_DIR` before installing and starting Pi. Do not load this extension and Hermes together: both register some of the same tool names.
|
|
15
|
+
|
|
16
|
+
Once the Beta is on npm, install the pinned version from Bash:
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
npm_config_ignore_scripts=true pi install npm:@joshua-zyy/pi-claude-memory@1.0.0-beta.1
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
On Windows PowerShell, run in a separate terminal:
|
|
23
|
+
|
|
24
|
+
```powershell
|
|
25
|
+
$env:npm_config_ignore_scripts = 'true'
|
|
26
|
+
pi install npm:@joshua-zyy/pi-claude-memory@1.0.0-beta.1
|
|
27
|
+
Remove-Item Env:npm_config_ignore_scripts
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Disabling install scripts lets npm use the SQLite dependency’s bundled binaries on supported platforms instead of triggering a native rebuild. It does not change the profile’s npm configuration.
|
|
31
|
+
|
|
32
|
+
## Try from source
|
|
33
|
+
|
|
34
|
+
From a checkout of this repository (Git is also needed by the tests):
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
npm ci --ignore-scripts
|
|
38
|
+
npm run check
|
|
39
|
+
npm test
|
|
40
|
+
pi -e ./src/index.ts
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Memory layout
|
|
44
|
+
|
|
45
|
+
The root is `$PI_CODING_AGENT_DIR/pi-claude-memory` (default agent directory: `~/.pi/agent`). This extension neither loads nor migrates Hermes memory.
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
pi-claude-memory/
|
|
49
|
+
config.json # optional
|
|
50
|
+
global/
|
|
51
|
+
STANDING.md
|
|
52
|
+
MEMORY.md
|
|
53
|
+
topics/*.md
|
|
54
|
+
projects/<project-id>/
|
|
55
|
+
STANDING.md
|
|
56
|
+
MEMORY.md
|
|
57
|
+
topics/*.md
|
|
58
|
+
sessions.db # rebuildable session search index only
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Global topics hold preferences and cross-project knowledge. Project topics use the canonical repository root of the Pi session's working directory; linked worktrees share an ID and unrelated repositories with the same name do not. Non-Git projects use their canonical working directory. Running commands in another repository does not switch project memory. If you work from a coordination directory, start Pi inside the target repository when you want that repository's own memory.
|
|
62
|
+
|
|
63
|
+
Topic files are the source of truth. Each has one summary line (up to 120 characters) followed by its Markdown body. Put important constraints directly in the summary. Tools cap each scope at 30 topics and each new body at 4,000 characters. The generated `MEMORY.md` is bounded to 100 lines and 3,000 characters per scope; omitted topics are still searchable. The index and user-authored standing instructions are snapshotted when the session starts and attached on each run. Changes appear in the prompt in a new session; tools read live data.
|
|
64
|
+
|
|
65
|
+
Only users should author `STANDING.md`: use `/memory-pin <rule>` for global rules or `/memory-pin --project <rule>` for the current project. Use `list`, `remove <n>`, or `clear` after the same prefix. A topic summary is reference context, not authority to run an action.
|
|
66
|
+
|
|
67
|
+
| Tool | Purpose |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `memory_read` | Read a topic by `scope` and `topic`. |
|
|
70
|
+
| `memory_write` | Create a new topic; never overwrites an existing one. |
|
|
71
|
+
| `memory_patch` | Replace a unique exact `old_text` fragment with `new_text`. Optionally update the summary. |
|
|
72
|
+
| `memory_delete` | Explicitly remove a topic. |
|
|
73
|
+
| `memory_search` | Find topics globally and in the current project, including short Chinese terms. |
|
|
74
|
+
| `session_search` | Search past Pi sessions locally. |
|
|
75
|
+
|
|
76
|
+
The default session search returns SQLite-indexed text snippets. Use `/memory-index-sessions` to import all available sessions. To use raw JSONL line-range anchors instead, set `{"sessionSearch":{"variant":"anchors"}}` in `config.json`. The anchor variant does not build a database. Both modes honor `PI_CODING_AGENT_SESSION_DIR`.
|
|
77
|
+
|
|
78
|
+
## Development and project history
|
|
79
|
+
|
|
80
|
+
GitHub Actions checks types, runs tests, and previews the npm package on Linux and Windows. This workflow does not publish anything.
|
|
81
|
+
|
|
82
|
+
`PLAN.md` describes this fork’s direction; [CHANGELOG.md](./CHANGELOG.md) records its releases. See [the v1 validation plan](https://github.com/joshua-zyy/pi-claude-memory/blob/main/docs/v1-validation.md) for the test criteria. The original Hermes plan and changelog are preserved under `docs/upstream/`. The older versioned docs describe Hermes, not this fork.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Pi Claude Memory
|
|
2
|
+
|
|
3
|
+
简体中文 | [English](README.md)
|
|
4
|
+
|
|
5
|
+
给 [Pi](https://pi.dev) 用的主题记忆插件,采用类似 Claude Code 的目录方式,独立 fork 自 [pi-hermes-memory](https://github.com/chandra447/pi-hermes-memory)。
|
|
6
|
+
|
|
7
|
+
- **全局和项目各一份短目录。** Pi 先看主题摘要,再按需读 Markdown 正文,不用把所有记忆塞进提示词。
|
|
8
|
+
- **五个主题工具。** 支持搜索、读取、新建、精确修改片段和显式删除。新建不会覆盖已有主题。
|
|
9
|
+
- **按仓库隔离。** 同名的不同仓库不共享记忆;同一仓库的关联 worktree 共用记忆。
|
|
10
|
+
- **不后台自动写记忆。** `session_search` 用来翻过往对话,不会把任务进度自动写成长久记忆。v1 不含 Dreaming 或自动迁移,也不修改 Pi 的上下文压缩逻辑。
|
|
11
|
+
|
|
12
|
+
## 安装 Beta
|
|
13
|
+
|
|
14
|
+
需要 Pi 1.7+ 和 Node 22.19+。安装和启动前,用 `PI_CODING_AGENT_DIR` 和 `PI_CODING_AGENT_SESSION_DIR` 配置一套独立的 Pi 环境。不要和 Hermes 同时加载:两个插件有同名工具。
|
|
15
|
+
|
|
16
|
+
Beta 上架 npm 后,Bash 用户可以安装指定版本:
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
npm_config_ignore_scripts=true pi install npm:@joshua-zyy/pi-claude-memory@1.0.0-beta.1
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Windows PowerShell 用户在单独的终端里运行:
|
|
23
|
+
|
|
24
|
+
```powershell
|
|
25
|
+
$env:npm_config_ignore_scripts = 'true'
|
|
26
|
+
pi install npm:@joshua-zyy/pi-claude-memory@1.0.0-beta.1
|
|
27
|
+
Remove-Item Env:npm_config_ignore_scripts
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
跳过安装脚本后,在支持的平台上会使用 SQLite 依赖自带的预编译二进制,不触发本地编译。这不会写入 npm 配置文件。
|
|
31
|
+
|
|
32
|
+
## 从源码试用
|
|
33
|
+
|
|
34
|
+
在本仓库根目录运行(测试需要 Git):
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
npm ci --ignore-scripts
|
|
38
|
+
npm run check
|
|
39
|
+
npm test
|
|
40
|
+
pi -e ./src/index.ts
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 记忆放在哪里
|
|
44
|
+
|
|
45
|
+
根目录为 `$PI_CODING_AGENT_DIR/pi-claude-memory`(Pi 的默认配置目录是 `~/.pi/agent`)。本插件不会读取或迁移 Hermes 的记忆库。
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
pi-claude-memory/
|
|
49
|
+
config.json # 可选的插件配置
|
|
50
|
+
global/ # 全局记忆
|
|
51
|
+
STANDING.md # 用户置顶的规则
|
|
52
|
+
MEMORY.md # 自动生成的主题目录
|
|
53
|
+
topics/*.md # 主题正文
|
|
54
|
+
projects/<project-id>/ # 项目记忆
|
|
55
|
+
STANDING.md
|
|
56
|
+
MEMORY.md
|
|
57
|
+
topics/*.md
|
|
58
|
+
sessions.db # 可重建的会话搜索索引,不存主题正文
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
全局主题存偏好或跨项目知识。项目主题按当前 Pi 会话工作目录对应的仓库根路径归属;没有 Git 仓库时则用工作目录的真实路径。在工具里运行 `cd` 去另一个仓库不会切换项目记忆。如果经常从中枢目录调度任务,想使用某个仓库自己的记忆时,请从那个仓库里启动 Pi。
|
|
62
|
+
|
|
63
|
+
`topics/*.md` 是记忆内容的唯一来源。每个主题有一行摘要(最多 120 字符)和 Markdown 正文,关键约束建议写进摘要。工具限制每个作用域最多 30 个主题,新建正文最多 4,000 字符;自动生成的 `MEMORY.md` 最多 100 行、3,000 字符,没放进目录的主题仍可以搜到。目录和置顶规则在会话开始时加入提示词;更新后的提示词在新会话生效,工具则直接读最新内容。
|
|
64
|
+
|
|
65
|
+
`STANDING.md` 由用户管理:用 `/memory-pin <规则>` 给全局置顶,或用 `/memory-pin --project <规则>` 给当前项目置顶。相同前缀下也支持 `list`、`remove <编号>` 和 `clear`。主题摘要是参考信息,不能代替用户对操作的授权。
|
|
66
|
+
|
|
67
|
+
| 工具 | 用途 |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `memory_read` | 按 `scope` 和 `topic` 读完整主题。 |
|
|
70
|
+
| `memory_write` | 新建主题,不会覆盖旧主题。 |
|
|
71
|
+
| `memory_patch` | 将唯一匹配的 `old_text` 换成 `new_text`,可同时更新摘要。 |
|
|
72
|
+
| `memory_delete` | 显式删除指定主题。 |
|
|
73
|
+
| `memory_search` | 在全局或当前项目查主题,支持中文短词和中英混写。 |
|
|
74
|
+
| `session_search` | 在本地查过去的 Pi 对话。 |
|
|
75
|
+
|
|
76
|
+
默认的会话搜索会返回 SQLite 索引里的文本片段。可以用 `/memory-index-sessions` 补建索引;想改为直接返回 JSONL 的行号范围,在 `config.json` 写 `{"sessionSearch":{"variant":"anchors"}}`。`anchors` 模式不建数据库;两个模式都支持 `PI_CODING_AGENT_SESSION_DIR`。
|
|
77
|
+
|
|
78
|
+
## 开发和项目历史
|
|
79
|
+
|
|
80
|
+
GitHub Actions 在 Linux 和 Windows 上跑类型检查、测试和 npm 打包预检,不会自动发布。
|
|
81
|
+
|
|
82
|
+
`PLAN.md` 是这份 fork 的计划;[CHANGELOG.md](./CHANGELOG.md) 记录自己的版本变化。[v1 验收说明](https://github.com/joshua-zyy/pi-claude-memory/blob/main/docs/v1-validation.md) 列出了验收标准。上游 Hermes 的计划和变更日志保留在 `docs/upstream/`,旧版分期文档也只作为历史参考。
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@joshua-zyy/pi-claude-memory",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@joshua-zyy/pi-claude-memory",
|
|
3
|
+
"version": "1.0.0-beta.1",
|
|
4
|
+
"description": "Two-level Markdown memory for Pi with exact topic edits and local session search.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"src",
|
|
9
|
+
"README.md",
|
|
10
|
+
"README.zh-CN.md",
|
|
11
|
+
"CHANGELOG.md",
|
|
12
|
+
"LICENSE"
|
|
13
|
+
],
|
|
14
|
+
"pi": {
|
|
15
|
+
"extensions": [
|
|
16
|
+
"./src/index.ts"
|
|
17
|
+
]
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"check": "tsc --noEmit",
|
|
21
|
+
"test": "node --import tsx --test --test-timeout=30000 \"tests/**/*.test.ts\""
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"pi-package",
|
|
25
|
+
"pi-extension",
|
|
26
|
+
"memory",
|
|
27
|
+
"topic-memory",
|
|
28
|
+
"markdown",
|
|
29
|
+
"session-search"
|
|
30
|
+
],
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"tag": "beta"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/joshua-zyy/pi-claude-memory.git"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22.19.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@earendil-works/pi-coding-agent": ">=1.7.0",
|
|
45
|
+
"@earendil-works/pi-tui": "*",
|
|
46
|
+
"typebox": "*"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@earendil-works/pi-coding-agent": "1.7.0",
|
|
50
|
+
"@earendil-works/pi-tui": "1.7.0",
|
|
51
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
52
|
+
"@types/node": "^22.19.0",
|
|
53
|
+
"tsx": "^4.21.0",
|
|
54
|
+
"typebox": "^1.1.33",
|
|
55
|
+
"typescript": "^6.0.3"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"better-sqlite3": "13.0.3",
|
|
59
|
+
"strip-ansi": "7.2.0"
|
|
60
|
+
}
|
|
61
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { DatabaseManager } from "../store/db.js";
|
|
3
|
+
import { indexAllSessions } from "../store/session-indexer.js";
|
|
4
|
+
|
|
5
|
+
export function registerIndexSessionsCommand(pi: ExtensionAPI, db: DatabaseManager, sessionsDir: string): void {
|
|
6
|
+
pi.registerCommand("memory-index-sessions", {
|
|
7
|
+
description: "Import Pi sessions into the local search index",
|
|
8
|
+
handler: async (_args, ctx) => {
|
|
9
|
+
const result = indexAllSessions(db, sessionsDir);
|
|
10
|
+
ctx.ui.notify(
|
|
11
|
+
`Indexed ${result.messagesIndexed} messages across ${result.sessionsIndexed} sessions. ${result.errors.join("; ")}`.trim(),
|
|
12
|
+
result.errors.length ? "warning" : "info",
|
|
13
|
+
);
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { measureLifecycleSync } from '../lifecycle-timing.js';
|
|
2
|
+
import type { DatabaseManager } from '../store/db.js';
|
|
3
|
+
import {
|
|
4
|
+
indexChangedSessions,
|
|
5
|
+
needsBackfill,
|
|
6
|
+
touchBackfillTimestamp,
|
|
7
|
+
type BulkIndexResult,
|
|
8
|
+
} from '../store/session-indexer.js';
|
|
9
|
+
|
|
10
|
+
export const SESSION_BACKFILL_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
11
|
+
export const SESSION_BACKFILL_MAX_FILES = 50;
|
|
12
|
+
|
|
13
|
+
type NotifyLevel = 'info' | 'warning' | 'error';
|
|
14
|
+
type NotifyFn = (message: string, level: NotifyLevel) => void;
|
|
15
|
+
|
|
16
|
+
type SetTimeoutFn = (callback: () => void, ms: number) => unknown;
|
|
17
|
+
|
|
18
|
+
export interface SessionBackfillState {
|
|
19
|
+
inProgress: boolean;
|
|
20
|
+
promise: Promise<void> | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const sessionBackfillState: SessionBackfillState = {
|
|
24
|
+
inProgress: false,
|
|
25
|
+
promise: null,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export interface ScheduleSessionBackfillOptions {
|
|
29
|
+
notify?: NotifyFn;
|
|
30
|
+
state?: SessionBackfillState;
|
|
31
|
+
setTimeoutFn?: SetTimeoutFn;
|
|
32
|
+
needsBackfillFn?: typeof needsBackfill;
|
|
33
|
+
indexSessionsFn?: typeof indexChangedSessions;
|
|
34
|
+
maxFilesToIndex?: number;
|
|
35
|
+
/** First-level dirs to skip in the all-projects scan (sessionIndexExclude config). */
|
|
36
|
+
sessionIndexExclude?: string[];
|
|
37
|
+
touchBackfillTimestampFn?: typeof touchBackfillTimestamp;
|
|
38
|
+
/**
|
|
39
|
+
* Optional retention cutoff (ms epoch). Files older than this are excluded
|
|
40
|
+
* from the backfill file set so that sessions pruned by retention are not
|
|
41
|
+
* re-indexed and do not repeatedly schedule a startup backfill.
|
|
42
|
+
*/
|
|
43
|
+
retentionCutoffMs?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function formatBackfillResult(result: BulkIndexResult): string {
|
|
47
|
+
const errorSuffix = result.errors.length > 0 ? ` (${result.errors.length} file error${result.errors.length === 1 ? '' : 's'})` : '';
|
|
48
|
+
const nonSessionSuffix = (result.nonSessionSkipped ?? 0) > 0 ? ` (${result.nonSessionSkipped} non-session files skipped)` : '';
|
|
49
|
+
const limitSuffix = result.reachedLimit ? ' (startup limit reached)' : '';
|
|
50
|
+
return `🧠 Session backfill complete: ${result.sessionsIndexed} indexed, ${result.sessionsSkipped} skipped, ${result.messagesIndexed} messages${errorSuffix}${nonSessionSuffix}${limitSuffix}.`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function notifyBestEffort(notify: NotifyFn | undefined, message: string, level: NotifyLevel): void {
|
|
54
|
+
try {
|
|
55
|
+
notify?.(message, level);
|
|
56
|
+
} catch {
|
|
57
|
+
// Notification failures must never affect backfill.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Schedule a best-effort, bounded incremental backfill of unindexed Pi sessions.
|
|
63
|
+
*
|
|
64
|
+
* The JSONL parsing work is deferred with setTimeout(0) so session_start can
|
|
65
|
+
* resolve first. The scheduled pass only parses files without matching stored
|
|
66
|
+
* metadata and caps the number of files parsed per startup.
|
|
67
|
+
*
|
|
68
|
+
* @returns true when a backfill task was scheduled; false when it was skipped.
|
|
69
|
+
*/
|
|
70
|
+
export function scheduleSessionBackfill(
|
|
71
|
+
dbManager: DatabaseManager,
|
|
72
|
+
sessionsDir: string,
|
|
73
|
+
options: ScheduleSessionBackfillOptions = {},
|
|
74
|
+
): boolean {
|
|
75
|
+
const state = options.state ?? sessionBackfillState;
|
|
76
|
+
const setTimeoutFn = options.setTimeoutFn ?? setTimeout;
|
|
77
|
+
const needsBackfillFn = options.needsBackfillFn ?? needsBackfill;
|
|
78
|
+
const indexSessionsFn = options.indexSessionsFn ?? indexChangedSessions;
|
|
79
|
+
const maxFilesToIndex = options.maxFilesToIndex ?? SESSION_BACKFILL_MAX_FILES;
|
|
80
|
+
const touchBackfillTimestampFn = options.touchBackfillTimestampFn ?? touchBackfillTimestamp;
|
|
81
|
+
const retentionCutoffMs = options.retentionCutoffMs ?? 0;
|
|
82
|
+
|
|
83
|
+
if (state.inProgress) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
if (!measureLifecycleSync(
|
|
89
|
+
'session-backfill.check',
|
|
90
|
+
() => needsBackfillFn(dbManager, sessionsDir, undefined, retentionCutoffMs, options.sessionIndexExclude),
|
|
91
|
+
)) {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
} catch (err) {
|
|
95
|
+
notifyBestEffort(
|
|
96
|
+
options.notify,
|
|
97
|
+
`⚠️ Session backfill check failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
98
|
+
'warning',
|
|
99
|
+
);
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
state.inProgress = true;
|
|
104
|
+
state.promise = new Promise<void>((resolve) => {
|
|
105
|
+
setTimeoutFn(() => {
|
|
106
|
+
measureLifecycleSync('session-backfill.callback', () => {
|
|
107
|
+
try {
|
|
108
|
+
const result = indexSessionsFn(dbManager, sessionsDir, { maxFilesToIndex, retentionCutoffMs, excludeDirs: options.sessionIndexExclude });
|
|
109
|
+
if (!result.reachedLimit) touchBackfillTimestampFn(dbManager);
|
|
110
|
+
notifyBestEffort(options.notify, formatBackfillResult(result), result.errors.length > 0 || result.reachedLimit ? 'warning' : 'info');
|
|
111
|
+
} catch (err) {
|
|
112
|
+
notifyBestEffort(
|
|
113
|
+
options.notify,
|
|
114
|
+
`⚠️ Session backfill failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
115
|
+
'warning',
|
|
116
|
+
);
|
|
117
|
+
} finally {
|
|
118
|
+
state.inProgress = false;
|
|
119
|
+
state.promise = null;
|
|
120
|
+
resolve();
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}, 0);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* First-use readiness has no shutdown deadline: the scheduled pass must settle
|
|
131
|
+
* before a search can read its index. Each extension owns its own state.
|
|
132
|
+
*/
|
|
133
|
+
export async function joinSessionBackfill(state: SessionBackfillState = sessionBackfillState): Promise<void> {
|
|
134
|
+
await state.promise;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Wait briefly for an in-progress backfill before shutdown closes SQLite.
|
|
139
|
+
*
|
|
140
|
+
* @returns true if no backfill was running or it completed before the timeout;
|
|
141
|
+
* false if the timeout elapsed first.
|
|
142
|
+
*/
|
|
143
|
+
export async function waitForSessionBackfill(
|
|
144
|
+
timeoutMs = SESSION_BACKFILL_SHUTDOWN_TIMEOUT_MS,
|
|
145
|
+
state: SessionBackfillState = sessionBackfillState,
|
|
146
|
+
): Promise<boolean> {
|
|
147
|
+
const promise = state.promise;
|
|
148
|
+
if (!state.inProgress || !promise) {
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
153
|
+
try {
|
|
154
|
+
return await Promise.race([
|
|
155
|
+
promise.then(() => true),
|
|
156
|
+
new Promise<boolean>((resolve) => {
|
|
157
|
+
timeout = setTimeout(() => resolve(false), timeoutMs);
|
|
158
|
+
}),
|
|
159
|
+
]);
|
|
160
|
+
} finally {
|
|
161
|
+
if (timeout) clearTimeout(timeout);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { measureLifecycleSync } from '../lifecycle-timing.js';
|
|
2
|
+
import { isDatabaseClosedError, type DatabaseManager } from '../store/db.js';
|
|
3
|
+
import { indexLiveSession } from '../store/session-indexer.js';
|
|
4
|
+
|
|
5
|
+
export const SESSION_LIVE_INDEX_DELAY_MS = 50;
|
|
6
|
+
export const SESSION_LIVE_INDEX_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
7
|
+
|
|
8
|
+
type SetTimeoutFn = (callback: () => void, ms: number) => unknown;
|
|
9
|
+
|
|
10
|
+
type SessionManagerSnapshot = Parameters<typeof indexLiveSession>[1];
|
|
11
|
+
|
|
12
|
+
export interface SessionLiveIndexState {
|
|
13
|
+
inProgress: boolean;
|
|
14
|
+
promise: Promise<void> | null;
|
|
15
|
+
/**
|
|
16
|
+
* Set once the session has closed the database. Scheduling is a no-op from
|
|
17
|
+
* then on: a `message_end` that lands during or after teardown must not queue
|
|
18
|
+
* a timer that can only run into the closed-DB guard (#313).
|
|
19
|
+
*/
|
|
20
|
+
closed?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const sessionLiveIndexState: SessionLiveIndexState = {
|
|
24
|
+
inProgress: false,
|
|
25
|
+
promise: null,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Stop live indexing for this session. Call before the database is closed.
|
|
30
|
+
*/
|
|
31
|
+
export function closeLiveSessionIndex(state: SessionLiveIndexState = sessionLiveIndexState): void {
|
|
32
|
+
state.closed = true;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Report a live-index failure, except for the intentional close. The closed-DB
|
|
37
|
+
* error is only reachable after `session_shutdown` closed the database, so
|
|
38
|
+
* warning about it reads as a mid-session failure that never happened (#313).
|
|
39
|
+
*/
|
|
40
|
+
export function reportLiveSessionIndexError(
|
|
41
|
+
error: unknown,
|
|
42
|
+
warn: (message: string) => void,
|
|
43
|
+
): void {
|
|
44
|
+
if (isDatabaseClosedError(error)) return;
|
|
45
|
+
warn(`⚠️ Live session indexing failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ScheduleLiveSessionIndexOptions {
|
|
49
|
+
state?: SessionLiveIndexState;
|
|
50
|
+
setTimeoutFn?: SetTimeoutFn;
|
|
51
|
+
indexLiveSessionFn?: typeof indexLiveSession;
|
|
52
|
+
delayMs?: number;
|
|
53
|
+
onError?: (error: unknown) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Schedule non-blocking indexing of the current live session.
|
|
58
|
+
*
|
|
59
|
+
* Pi emits message_end before it appends the finalized message to the JSONL
|
|
60
|
+
* session file/session manager. Deferring briefly lets Pi persist the entry
|
|
61
|
+
* first, then we index any message ids not already present in SQLite. Multiple
|
|
62
|
+
* message_end events in the same window coalesce into one all-missing sync.
|
|
63
|
+
*/
|
|
64
|
+
export function scheduleLiveSessionIndex(
|
|
65
|
+
dbManager: DatabaseManager,
|
|
66
|
+
sessionManager: SessionManagerSnapshot,
|
|
67
|
+
options: ScheduleLiveSessionIndexOptions = {},
|
|
68
|
+
): boolean {
|
|
69
|
+
const state = options.state ?? sessionLiveIndexState;
|
|
70
|
+
if (state.closed || state.inProgress) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const setTimeoutFn = options.setTimeoutFn ?? setTimeout;
|
|
75
|
+
const indexLiveSessionFn = options.indexLiveSessionFn ?? indexLiveSession;
|
|
76
|
+
const delayMs = options.delayMs ?? SESSION_LIVE_INDEX_DELAY_MS;
|
|
77
|
+
|
|
78
|
+
state.inProgress = true;
|
|
79
|
+
state.promise = new Promise<void>((resolve) => {
|
|
80
|
+
setTimeoutFn(() => {
|
|
81
|
+
measureLifecycleSync('live-index.callback', () => {
|
|
82
|
+
try {
|
|
83
|
+
dbManager.withCorruptionRecovery(() => {
|
|
84
|
+
indexLiveSessionFn(dbManager, sessionManager);
|
|
85
|
+
});
|
|
86
|
+
} catch (err) {
|
|
87
|
+
try { options.onError?.(err); } catch { /* best effort */ }
|
|
88
|
+
} finally {
|
|
89
|
+
state.inProgress = false;
|
|
90
|
+
state.promise = null;
|
|
91
|
+
resolve();
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}, delayMs);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function waitForLiveSessionIndex(
|
|
101
|
+
timeoutMs = SESSION_LIVE_INDEX_SHUTDOWN_TIMEOUT_MS,
|
|
102
|
+
state: SessionLiveIndexState = sessionLiveIndexState,
|
|
103
|
+
): Promise<boolean> {
|
|
104
|
+
const promise = state.promise;
|
|
105
|
+
if (!state.inProgress || !promise) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
110
|
+
try {
|
|
111
|
+
return await Promise.race([
|
|
112
|
+
promise.then(() => true),
|
|
113
|
+
new Promise<boolean>((resolve) => {
|
|
114
|
+
timeout = setTimeout(() => resolve(false), timeoutMs);
|
|
115
|
+
}),
|
|
116
|
+
]);
|
|
117
|
+
} finally {
|
|
118
|
+
if (timeout) clearTimeout(timeout);
|
|
119
|
+
}
|
|
120
|
+
}
|