lingshu-skill 0.0.0-stage → 3.82.0
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 +2605 -0
- package/LICENSE +21 -0
- package/README.md +698 -3
- package/SKILL-lite.md +45 -0
- package/SKILL-tiny.md +37 -0
- package/SKILL.md +379 -0
- package/assets/panel.html +5616 -0
- package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-cron/index.js +4 -0
- package/cordis-plugin/lingshu-cron/package.json +34 -0
- package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
- package/cordis-plugin/lingshu-guard/plugin.js +473 -0
- package/cordis-plugin/lingshu-im/plugin.js +635 -0
- package/cordis-plugin/lingshu-startup/README.md +123 -0
- package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-startup/index.js +4 -0
- package/cordis-plugin/lingshu-startup/package.json +25 -0
- package/cordis-plugin/lingshu-startup/plugin.js +352 -0
- package/cordis.patch.yml +3 -0
- package/docs/commands.md +243 -0
- package/docs/mechanics.md +610 -0
- package/docs/models.md +52 -0
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
- package/docs/panel-api.md +198 -0
- package/docs/recovery.md +90 -0
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
- package/index.js +102 -0
- package/package.json +52 -6
- package/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/_smoke_v299.py +31 -0
- package/scripts/_sync_trae_cn.py +34 -0
- package/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
- package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
- package/scripts/astrbot_plugin_lingshu/README.md +58 -0
- package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
- package/scripts/astrbot_plugin_lingshu/main.py +703 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
- package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
- package/scripts/behavior_baseline.py +280 -0
- package/scripts/bench.py +192 -0
- package/scripts/brain.py +46 -0
- package/scripts/check_pressure_sync.py +55 -0
- package/scripts/check_tag.py +215 -0
- package/scripts/check_version.py +265 -0
- package/scripts/checkpoint.py +165 -0
- package/scripts/cli.py +4867 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2028 -0
- package/scripts/dream.py +1137 -0
- package/scripts/emotion.py +1180 -0
- package/scripts/failures.py +107 -0
- package/scripts/fallback_embed.py +114 -0
- package/scripts/growth.py +4745 -0
- package/scripts/growth_parts.py +263 -0
- package/scripts/hooks/pre-commit +18 -0
- package/scripts/hooks/pre-push +20 -0
- package/scripts/insights.py +131 -0
- package/scripts/make_dsh_tgz.py +92 -0
- package/scripts/make_manifest.py +254 -0
- package/scripts/make_plugin_zip.py +88 -0
- package/scripts/mem_dialogue.py +242 -0
- package/scripts/mem_embed.py +159 -0
- package/scripts/mem_lesson.py +160 -0
- package/scripts/mem_score.py +210 -0
- package/scripts/mem_topic.py +177 -0
- package/scripts/memory.py +4417 -0
- package/scripts/npm_prepack.py +31 -0
- package/scripts/panel_build.py +115 -0
- package/scripts/panel_cloud.py +609 -0
- package/scripts/panel_server.py +2703 -0
- package/scripts/panels.py +591 -0
- package/scripts/persona.py +2309 -0
- package/scripts/recreate_push.ps1 +117 -0
- package/scripts/retriever.py +195 -0
- package/scripts/run_tests.py +91 -0
- package/scripts/safety.py +368 -0
- package/scripts/session_import.py +736 -0
- package/scripts/session_rag.py +228 -0
- package/scripts/session_summary.py +123 -0
- package/scripts/summarizer.py +252 -0
- package/scripts/sync_engine.py +139 -0
- package/scripts/update_dsh_copy.ps1 +107 -0
- package/start-panel.bat +60 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢发版 tag 守卫:推送 main 之前,确认当前版本号有对应的 git tag。
|
|
4
|
+
|
|
5
|
+
为什么需要它:插件市场显示的「版本说明」来自仓库 tag/Release 那条线;
|
|
6
|
+
仓库不打 tag 时(历史上有 3.05–3.13 一段空档),市场就一直显示旧版本,
|
|
7
|
+
用户会以为更新到了旧版本。这个钩子在 push 时把「打 tag」变成硬动作。
|
|
8
|
+
|
|
9
|
+
用法:
|
|
10
|
+
python scripts/check_tag.py # pre-push 钩子调用(读 stdin 的 refs)
|
|
11
|
+
python scripts/check_tag.py --check # 只检查、不建 tag(CI / 手动核对)
|
|
12
|
+
python scripts/check_tag.py --install # 安装 pre-commit + pre-push 钩子
|
|
13
|
+
|
|
14
|
+
行为:
|
|
15
|
+
· 推送到 main/master 时,若当前版本没有对应 tag → 自动在 HEAD 打一个
|
|
16
|
+
带注释的 vX.Y tag,然后拒绝本次推送,并给出下一步命令;
|
|
17
|
+
· tag 存在但打在**更早的提交**上:只要它是 HEAD 的祖先、且那个提交里的
|
|
18
|
+
SKILL.md 版本就是当前版本 → 放行(v3.50 起)。打完 tag 再改文档/CI 是
|
|
19
|
+
正常收尾动作,旧规则要求"tag 必须正好指向 HEAD",逼得人用 SKIP 绕过;
|
|
20
|
+
· tag 打在别的分支上、或打在另一个版本的提交上 → 拒绝;
|
|
21
|
+
· 推送标签或其它分支 → 直接放行;
|
|
22
|
+
· 真的要走捷径也可用 LINGSHU_SKIP_TAG_CHECK=1 临时跳过(不建议)。
|
|
23
|
+
|
|
24
|
+
退出码:0 放行;1 拒绝(缺 tag / tag 指向不对)。
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
36
|
+
VERSION_RE = re.compile(r"^version:\s*([0-9][0-9.]*)\s*$", re.MULTILINE)
|
|
37
|
+
PROTECTED_BRANCHES = ("refs/heads/main", "refs/heads/master")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _git(args: list[str]) -> str | None:
|
|
41
|
+
try:
|
|
42
|
+
r = subprocess.run(["git", *args], cwd=str(ROOT), capture_output=True, text=True,
|
|
43
|
+
encoding="utf-8", errors="replace")
|
|
44
|
+
except OSError:
|
|
45
|
+
return None
|
|
46
|
+
return r.stdout.strip() if r.returncode == 0 else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def skill_version() -> str | None:
|
|
50
|
+
try:
|
|
51
|
+
text = (ROOT / "SKILL.md").read_text(encoding="utf-8-sig")
|
|
52
|
+
except OSError:
|
|
53
|
+
return None
|
|
54
|
+
m = VERSION_RE.search(text)
|
|
55
|
+
return m.group(1) if m else None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def head_sha() -> str | None:
|
|
59
|
+
return _git(["rev-parse", "HEAD"])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def tag_candidates(version: str) -> list[str]:
|
|
63
|
+
return [f"v{version}", version]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def find_tag(version: str) -> tuple[str | None, str | None]:
|
|
67
|
+
"""返回 (tag 名, tag 指向的提交 sha);没有则 (None, None)。
|
|
68
|
+
|
|
69
|
+
注意用 ^{commit} 解引用:带注释的 tag 是独立对象,直接 rev-parse
|
|
70
|
+
拿到的是 tag 对象 sha,会和 HEAD 的提交 sha 永远不等。
|
|
71
|
+
"""
|
|
72
|
+
for name in tag_candidates(version):
|
|
73
|
+
sha = _git(["rev-parse", "-q", "--verify", f"refs/tags/{name}^{{commit}}"])
|
|
74
|
+
if sha:
|
|
75
|
+
return name, sha
|
|
76
|
+
return None, None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def is_ancestor(sha: str, head: str) -> bool:
|
|
80
|
+
"""sha 是否是 head 的祖先(含相等)。"""
|
|
81
|
+
try:
|
|
82
|
+
r = subprocess.run(["git", "merge-base", "--is-ancestor", sha, head],
|
|
83
|
+
cwd=str(ROOT), capture_output=True)
|
|
84
|
+
except OSError:
|
|
85
|
+
return False
|
|
86
|
+
return r.returncode == 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def commit_version(sha: str) -> str | None:
|
|
90
|
+
"""读某个提交里 SKILL.md 的 version(校验"tag 确实打在那个版本上")。"""
|
|
91
|
+
text = _git(["show", f"{sha}:SKILL.md"])
|
|
92
|
+
m = VERSION_RE.search(text or "")
|
|
93
|
+
return m.group(1) if m else None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def pushed_refs(stdin_text: str) -> list[str]:
|
|
97
|
+
"""pre-push 的 stdin:每行 <local ref> <local sha> <remote ref> <remote sha>"""
|
|
98
|
+
refs = []
|
|
99
|
+
for line in stdin_text.splitlines():
|
|
100
|
+
parts = line.split()
|
|
101
|
+
if len(parts) >= 3:
|
|
102
|
+
refs.append(parts[2])
|
|
103
|
+
return refs
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def create_tag(version: str) -> str | None:
|
|
107
|
+
name = f"v{version}"
|
|
108
|
+
r = subprocess.run(["git", "tag", "-a", name, "-m", name], cwd=str(ROOT),
|
|
109
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
110
|
+
return name if r.returncode == 0 else None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def check(create_if_missing: bool) -> int:
|
|
114
|
+
if os.environ.get("LINGSHU_SKIP_TAG_CHECK") == "1":
|
|
115
|
+
print("[tag] LINGSHU_SKIP_TAG_CHECK=1,跳过 tag 检查", file=sys.stderr)
|
|
116
|
+
return 0
|
|
117
|
+
|
|
118
|
+
version = skill_version()
|
|
119
|
+
if not version:
|
|
120
|
+
print("[tag] 读不到 SKILL.md 的 version,跳过检查", file=sys.stderr)
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
head = head_sha()
|
|
124
|
+
name, sha = find_tag(version)
|
|
125
|
+
if name and sha and head and sha == head:
|
|
126
|
+
print(f"[tag] OK:v{version} 已存在并指向 HEAD({name})")
|
|
127
|
+
return 0
|
|
128
|
+
|
|
129
|
+
if name and sha and head:
|
|
130
|
+
# tag 在 HEAD 之前的老提交上:只要①它确实是 HEAD 的祖先(没跑到别的分支去)、
|
|
131
|
+
# ②那个提交里的 SKILL.md 版本就是这个版本,就放行。
|
|
132
|
+
# 为什么放宽(v3.50):打完 tag 再改文档/CI 是很正常的收尾动作,旧规则要求
|
|
133
|
+
# "tag 必须正好指向 HEAD",于是每次收尾都要么改 tag(公有 tag 不该动)、
|
|
134
|
+
# 要么用 LINGSHU_SKIP_TAG_CHECK=1 绕过——绕过一次就失去这道闸的意义。
|
|
135
|
+
# 语义没变:marketplace 的版本说明仍然来自「那一个 tag 指向的提交」。
|
|
136
|
+
if not is_ancestor(sha, head):
|
|
137
|
+
print(f"[tag] 拒绝:tag {name} 指向 {sha[:8]},它不在当前分支上"
|
|
138
|
+
f"(HEAD {head[:8]})。发版 tag 必须打在这个版本所在的提交上。", file=sys.stderr)
|
|
139
|
+
print(f" 修正:git tag -d {name} && git tag -a v{version} -m v{version} && "
|
|
140
|
+
f"git push --force <remote> v{version}", file=sys.stderr)
|
|
141
|
+
return 1
|
|
142
|
+
tagged_ver = commit_version(sha)
|
|
143
|
+
if tagged_ver != version:
|
|
144
|
+
print(f"[tag] 拒绝:tag {name} 打在 {sha[:8]} 上,但那个提交的 SKILL.md 版本是"
|
|
145
|
+
f" {tagged_ver or '读不出'},不是 v{version}。tag 打错了位置。", file=sys.stderr)
|
|
146
|
+
return 1
|
|
147
|
+
print(f"[tag] OK:v{version} 的 tag 在 {sha[:8]}(HEAD 的祖先),"
|
|
148
|
+
f"其后的提交不改版本 → 放行")
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
if create_if_missing and head:
|
|
152
|
+
created = create_tag(version)
|
|
153
|
+
if created:
|
|
154
|
+
print(f"[tag] 当前版本 v{version} 还没有 tag —— 已在 HEAD 自动创建 {created}。",
|
|
155
|
+
file=sys.stderr)
|
|
156
|
+
print(" 下一步:git push --follow-tags <remote> main", file=sys.stderr)
|
|
157
|
+
print(" (或用 git push <remote> v" + version + " 单独推 tag)", file=sys.stderr)
|
|
158
|
+
return 1
|
|
159
|
+
|
|
160
|
+
print(f"[tag] 拒绝:当前版本 v{version} 没有对应的 tag。", file=sys.stderr)
|
|
161
|
+
print(" 下一步:git tag -a v" + version + " -m v" + version + " 然后 git push --follow-tags",
|
|
162
|
+
file=sys.stderr)
|
|
163
|
+
return 1
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def install_hooks() -> int:
|
|
167
|
+
hook_dir = ROOT / "scripts" / "hooks"
|
|
168
|
+
git_dir = _git(["rev-parse", "--git-dir"])
|
|
169
|
+
if git_dir is None:
|
|
170
|
+
print("[tag] 不是 git 仓库,无法安装钩子", file=sys.stderr)
|
|
171
|
+
return 2
|
|
172
|
+
target_dir = (ROOT / git_dir.strip()).resolve() / "hooks"
|
|
173
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
installed = []
|
|
175
|
+
for src in sorted(hook_dir.glob("*")):
|
|
176
|
+
if not src.is_file():
|
|
177
|
+
continue
|
|
178
|
+
target = target_dir / src.name
|
|
179
|
+
if target.exists() and target.read_bytes() != src.read_bytes():
|
|
180
|
+
import time
|
|
181
|
+
import shutil
|
|
182
|
+
backup = target.with_name(f"{src.name}.bak-{time.strftime('%Y%m%d%H%M%S')}")
|
|
183
|
+
shutil.copy2(target, backup)
|
|
184
|
+
print(f"[tag] 已备份原钩子:{backup}")
|
|
185
|
+
target.write_bytes(src.read_bytes())
|
|
186
|
+
try:
|
|
187
|
+
target.chmod(target.stat().st_mode | 0o111)
|
|
188
|
+
except OSError:
|
|
189
|
+
pass
|
|
190
|
+
installed.append(src.name)
|
|
191
|
+
print(f"[tag] 已安装钩子:{', '.join(installed)} → {target_dir}")
|
|
192
|
+
print(" · pre-commit:代码变更必须升 SKILL.md 版本")
|
|
193
|
+
print(" · pre-push :推 main 前必须有与版本对应的 tag(缺则自动创建并拒绝本次推送)")
|
|
194
|
+
return 0
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def main(argv: list[str] | None = None) -> int:
|
|
198
|
+
ap = argparse.ArgumentParser(description="灵枢:推送前检查发版 tag")
|
|
199
|
+
ap.add_argument("--check", action="store_true", help="只检查,不自动创建 tag")
|
|
200
|
+
ap.add_argument("--install", action="store_true", help="安装 pre-commit + pre-push 钩子")
|
|
201
|
+
args = ap.parse_args(argv)
|
|
202
|
+
if args.install:
|
|
203
|
+
return install_hooks()
|
|
204
|
+
|
|
205
|
+
if args.check:
|
|
206
|
+
return check(create_if_missing=False)
|
|
207
|
+
|
|
208
|
+
refs = pushed_refs(sys.stdin.read() if not sys.stdin.isatty() else "")
|
|
209
|
+
if refs and not any(r in PROTECTED_BRANCHES for r in refs):
|
|
210
|
+
return 0 # 只推 tag / 其它分支,不拦
|
|
211
|
+
return check(create_if_missing=True)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
if __name__ == "__main__":
|
|
215
|
+
sys.exit(main())
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""任务/项目收尾清点(checkpoint)。
|
|
4
|
+
|
|
5
|
+
动机:任务做完就散了,记忆里只剩零碎的过程,没有"这件事收尾时是什么状态"。
|
|
6
|
+
本模块在收尾时用**可验证的证据**(git 状态、提交、版本号)写一条 episode,
|
|
7
|
+
不靠模型编、也不需要你复述。
|
|
8
|
+
|
|
9
|
+
规则:
|
|
10
|
+
- 只在证据变化时写(HEAD 变了 / 工作区有改动),同一状态不重复写;
|
|
11
|
+
- 写一条 `source=checkpoint` 的 episode,tags 带「收尾 + 项目名」;
|
|
12
|
+
- 上次清点记录在 `~/.brain-memory/sessions/checkpoints.json`,按仓库路径存 HEAD。
|
|
13
|
+
|
|
14
|
+
CLI:
|
|
15
|
+
brain.py checkpoint [--repo 路径] [--note "一句话"] [--dry-run] [--json] [--force]
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import subprocess
|
|
21
|
+
import time
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _home() -> Path:
|
|
26
|
+
try:
|
|
27
|
+
import core
|
|
28
|
+
return Path(core.HOME)
|
|
29
|
+
except Exception:
|
|
30
|
+
return Path.home() / ".brain-memory"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _state_path(home: Path | None = None) -> Path:
|
|
34
|
+
return (home or _home()) / "sessions" / "checkpoints.json"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _load_state(home: Path | None = None) -> dict:
|
|
38
|
+
"""只读状态:不加锁、不建目录/锁文件(面板等只读调用不能有写副作用)。"""
|
|
39
|
+
try:
|
|
40
|
+
data = json.loads(_state_path(home).read_text(encoding="utf-8"))
|
|
41
|
+
return data if isinstance(data, dict) else {}
|
|
42
|
+
except (OSError, ValueError):
|
|
43
|
+
return {}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _save_state(state: dict, home: Path | None = None) -> None:
|
|
47
|
+
"""写回状态:整个「重读最新 → 合并 → 落盘」持 core._locked 写锁。
|
|
48
|
+
|
|
49
|
+
checkpoint 是先 load 判断要不要写、再写记忆、最后 save,所以调用方手里的
|
|
50
|
+
state 可能已是旧快照;直接整档覆盖会把另一个进程刚写进去的仓库抹掉。
|
|
51
|
+
这里在锁内重读磁盘再 update,两个进程各写各的仓库时都能留下(不丢更新)。
|
|
52
|
+
锁文件与状态文件同目录(core._locked 用 `<状态文件>.lock`),超时/陈旧锁
|
|
53
|
+
清理沿用 core._locked 的统一语义;落盘用 core.atomic_json,锁外只读者
|
|
54
|
+
不会读到写了一半的 JSON。
|
|
55
|
+
"""
|
|
56
|
+
p = _state_path(home)
|
|
57
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
import core
|
|
59
|
+
with core._locked(p):
|
|
60
|
+
disk = _load_state(home)
|
|
61
|
+
disk.update(state or {})
|
|
62
|
+
core.atomic_json(p, disk)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _git(repo: str, *args: str) -> str:
|
|
66
|
+
try:
|
|
67
|
+
r = subprocess.run(["git", "-C", repo, *args], capture_output=True,
|
|
68
|
+
text=True, encoding="utf-8", errors="replace", timeout=15)
|
|
69
|
+
return r.stdout.strip() if r.returncode == 0 else ""
|
|
70
|
+
except Exception:
|
|
71
|
+
return ""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def collect(repo: str | None = None) -> dict | None:
|
|
75
|
+
"""收集收尾证据;不是 git 仓库返回 None。"""
|
|
76
|
+
base = str(repo or ".")
|
|
77
|
+
root = _git(base, "rev-parse", "--show-toplevel")
|
|
78
|
+
if not root:
|
|
79
|
+
return None
|
|
80
|
+
head = _git(root, "rev-parse", "--short", "HEAD")
|
|
81
|
+
branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD")
|
|
82
|
+
subject = _git(root, "log", "-1", "--format=%s")
|
|
83
|
+
last_ts = _git(root, "log", "-1", "--format=%ct")
|
|
84
|
+
status = _git(root, "status", "--porcelain")
|
|
85
|
+
changed = len([x for x in status.splitlines() if x.strip()])
|
|
86
|
+
version = ""
|
|
87
|
+
for cand, pat in (("SKILL.md", "version:"), ("package.json", '"version"')):
|
|
88
|
+
f = Path(root) / cand
|
|
89
|
+
try:
|
|
90
|
+
for line in f.read_text(encoding="utf-8").splitlines():
|
|
91
|
+
if pat in line:
|
|
92
|
+
version = line.split(pat, 1)[1].strip().strip('":, ').strip()
|
|
93
|
+
break
|
|
94
|
+
except OSError:
|
|
95
|
+
pass
|
|
96
|
+
if version:
|
|
97
|
+
break
|
|
98
|
+
return {
|
|
99
|
+
"repo": root,
|
|
100
|
+
"name": Path(root).name,
|
|
101
|
+
"head": head,
|
|
102
|
+
"branch": branch,
|
|
103
|
+
"subject": subject,
|
|
104
|
+
"commit_ts": int(last_ts) if last_ts.isdigit() else 0,
|
|
105
|
+
"changed": changed,
|
|
106
|
+
"version": version,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def decide(ev: dict, state: dict, force: bool = False) -> dict:
|
|
111
|
+
"""是否需要写:HEAD 变了 / 工作区有改动 / 强制。"""
|
|
112
|
+
prev = state.get(ev["repo"]) or {}
|
|
113
|
+
if force:
|
|
114
|
+
return {"write": True, "reason": "force"}
|
|
115
|
+
if not prev:
|
|
116
|
+
return {"write": True, "reason": "首次收尾"}
|
|
117
|
+
if prev.get("head") != ev["head"]:
|
|
118
|
+
return {"write": True, "reason": f"HEAD {prev.get('head', '?')} → {ev['head']}"}
|
|
119
|
+
if ev["changed"] > 0:
|
|
120
|
+
return {"write": True, "reason": f"工作区有 {ev['changed']} 处未提交改动"}
|
|
121
|
+
return {"write": False, "reason": "与上次收尾一致,不重复记"}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def build_text(ev: dict, note: str = "", extra: str = "") -> str:
|
|
125
|
+
head_line = f"项目:{ev['name']}(分支 {ev['branch'] or '?'},HEAD {ev['head'] or '?'})"
|
|
126
|
+
lines = [f"任务收尾:{ev['name']}", head_line]
|
|
127
|
+
if ev["subject"]:
|
|
128
|
+
lines.append(f"最后提交:{ev['subject']}")
|
|
129
|
+
lines.append("工作区:" + ("干净" if ev["changed"] == 0 else f"还有 {ev['changed']} 处未提交改动"))
|
|
130
|
+
if ev["version"]:
|
|
131
|
+
lines.append(f"版本:{ev['version']}")
|
|
132
|
+
if note.strip():
|
|
133
|
+
lines.append(f"收尾备注:{note.strip()}")
|
|
134
|
+
if extra.strip():
|
|
135
|
+
lines.append(extra.strip())
|
|
136
|
+
return "\n".join(lines)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def checkpoint(repo: str | None = None, note: str = "", *, dry_run: bool = False,
|
|
140
|
+
force: bool = False, home: Path | None = None) -> dict:
|
|
141
|
+
"""一步到位:收集 → 判断 → 写记忆 + 记状态。"""
|
|
142
|
+
ev = collect(repo)
|
|
143
|
+
if ev is None:
|
|
144
|
+
return {"ok": False, "skipped": True, "reason": "不是 git 仓库,没法取证(可显式传 --repo)"}
|
|
145
|
+
state = _load_state(home)
|
|
146
|
+
d = decide(ev, state, force)
|
|
147
|
+
text = build_text(ev, note)
|
|
148
|
+
if not d["write"]:
|
|
149
|
+
return {"ok": True, "skipped": True, "reason": d["reason"], "text": text, "evidence": ev}
|
|
150
|
+
mid = ""
|
|
151
|
+
if not dry_run:
|
|
152
|
+
try:
|
|
153
|
+
import memory
|
|
154
|
+
mid, _rec = memory.remember(
|
|
155
|
+
text, kind="episode", importance=0.55,
|
|
156
|
+
tags=["收尾", ev["name"]], source="checkpoint",
|
|
157
|
+
project=ev["name"])
|
|
158
|
+
except Exception as exc: # noqa: BLE001
|
|
159
|
+
return {"ok": False, "skipped": False, "reason": f"写记忆失败:{exc}",
|
|
160
|
+
"text": text, "evidence": ev}
|
|
161
|
+
state[ev["repo"]] = {"head": ev["head"], "ts": int(time.time()),
|
|
162
|
+
"changed": ev["changed"], "version": ev["version"]}
|
|
163
|
+
_save_state(state, home)
|
|
164
|
+
return {"ok": True, "skipped": False, "reason": d["reason"], "text": text,
|
|
165
|
+
"memory_id": mid, "evidence": ev, "dry_run": dry_run}
|