Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
301 lines (268 loc) · 11.5 KB
/
Copy pathmain.py
File metadata and controls
301 lines (268 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Generated by DSH / q38o · 2026-10-05
"""
memory-cli — 文档驱动记忆系统 CLI
本地 Markdown 工作记录 + ClawMem 广场同步
用法:
python main.py init
python main.py write "内容..." [--template coding] [--agent dsh]
python main.py sync [--agent dsh]
python main.py list [--agent dsh]
python main.py read <文件名或编号>
python main.py agent-list
"""
import argparse
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
# ---------- 路径配置 ----------
# 各 agent 本地工作记录目录(可在 config.json 覆盖)
DEFAULT_AGENT_DIRS = {
"dsh": r"F:\dshdesktopwork",
"doubao": r"F:\doubaowork\工作记录",
"workbuddy": r"E:\workbuddywork\.workbuddy\memory",
"opencode": os.path.expanduser("~/.config/opencode"),
"hermes": r"E:\hermeswork\工作记录",
}
CLAWMEM_TOPIC = "记忆宇宙计划"
CLAWMEM_MAX_CHARS = 8000
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
# ---------- 工具函数 ----------
def now_str() -> str:
return datetime.datetime.now().strftime("%Y%m%d")
def now_hhmm() -> str:
return datetime.datetime.now().strftime("%H%M")
def _fix_console():
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
_fix_console()
def load_agent_dirs() -> dict:
d = {"agent_dirs": dict(DEFAULT_AGENT_DIRS), "clawmem_topic": CLAWMEM_TOPIC}
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
cfg = json.load(f)
d.update(cfg)
except Exception:
pass
return d
def clawmem_cmd(args: list) -> list:
"""clawmem 可能是 .CMD shim(npm global),CreateProcess 不能直接跑 .CMD,需经 cmd"""
c = shutil.which("clawmem")
if c and c.lower().endswith((".cmd", ".bat")):
return ["cmd", "/c", c] + args
return ["clawmem"] + args
def clawmem_available() -> bool:
try:
r = subprocess.run(clawmem_cmd(["--help"]), capture_output=True, timeout=30)
return r.returncode == 0
except Exception:
return False
def clawmem_exec(args: list) -> str:
env = dict(os.environ)
env["CLAWMEM_NO_LOCAL_MODELS"] = "true"
r = subprocess.run(clawmem_cmd(args), capture_output=True, env=env, timeout=180)
out = r.stdout.decode("utf-8", "replace").strip()
if r.returncode != 0:
out += "\n[ERR] " + r.stderr.decode("utf-8", "replace").strip()[:400]
return out
def trunc(text: str, limit: int) -> str:
if len(text) <= limit:
return text
return text[:limit - 20] + "\n\n[...截断至 %d 字...]" % limit
# ---------- 记录文件名 ----------
def record_filename(summary: str, agent: str = "dsh") -> str:
s = re.sub(r"[\\/:*?\"<>|\s]+", "-", summary.strip())[:30].strip("-") or "未命名"
return f"{s}-{now_str()}-{now_hhmm()}-{agent}.md"
# ---------- 记录模板 ----------
RECORD_TEMPLATE = """# Generated by {agent} · {date}
# 工作记录:{summary}
## 任务与结论
{body}
## 实测数据
{evidence}
## 坑与根因
{pits}
## 涌现连接
{emergence}
## 遗留待办
{todo}
## 产物与脚本位置
{artifacts}
"""
def render_record(summary, body, agent, evidence="", pits="", emergence="无",
todo="", artifacts=""):
return RECORD_TEMPLATE.format(
agent=agent, date=now_str() + " " + now_hhmm(), summary=summary,
body=body or "(待补)", evidence=evidence or "(待补)",
pits=pits or "无", emergence=emergence or "无",
todo=todo or "无", artifacts=artifacts or "无")
# ---------- 命令实现 ----------
def cmd_init(args):
d = load_agent_dirs()
os.path.join(os.path.dirname(os.path.abspath(__file__)))
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump({"agent_dirs": d["agent_dirs"], "clawmem_topic": d["clawmem_topic"]},
f, ensure_ascii=False, indent=2)
print("[OK] config.json 已写入:", CONFIG_FILE)
print("agent 目录:"); [print(" %-10s %s" % (k, v)) for k, v in d["agent_dirs"].items()]
def cmd_write(args):
"""写工作记录:本地 Markdown 全文 + clawmem diary ≤8000 字"""
d = load_agent_dirs()
body = args.text
summary = (args.summary or body[:30].split()[0]).strip()
summary = re.sub(r"[\\/:*?\"<>|]", "-", summary)[:30]
# 1) 本地工作记录(全文)
dir_path = d["agent_dirs"].get(args.agent, "F:\\dshdesktopwork")
os.makedirs(dir_path, exist_ok=True)
fname = record_filename(summary, args.agent)
fpath = os.path.join(dir_path, fname)
with open(fpath, "w", encoding="utf-8") as f:
f.write(render_record(summary, body, args.agent,
evidence=args.evidence, pits=args.pits,
emergence=args.emergence, todo=args.todo,
artifacts=args.artifacts))
print("[OK] 本地记录已写:", fpath)
# 2) ClawMem 广场(详细正文 ≤8000 字)
if not args.no_sync:
if clawmem_available():
diary = f"【{args.agent} 工作记录 {now_str()}】{summary}。{body}"
out = clawmem_exec(["diary", "write", trunc(diary, CLAWMEM_MAX_CHARS),
"-t", d["clawmem_topic"]])
print("[OK] ClawMem diary 已写:", out[:120] or "(ok)")
else:
print("[WARN] clawmem 不可用,仅本地记录")
# 3) 兜底自检(可选,若脚本存在)
extract = r"F:\dshdesktopwork\extract-insights-dsh.js"
if os.path.exists(extract) and args.selfcheck:
r = subprocess.run(["node", extract, "--cwd", "E:\\记忆宇宙计划",
"--record", fpath], capture_output=True)
print("兜底自检:", r.stdout.decode("utf-8", "replace")[:300])
def cmd_sync(args):
d = load_agent_dirs()
if not clawmem_available():
print("[WARN] clawmem 不可用"); return
out = clawmem_exec(["update"])
print("clawmem update:", out[:200] or "(ok)")
def cmd_list(args):
d = load_agent_dirs(); os.makedirs(d["agent_dirs"].get(args.agent, "."), exist_ok=True) or True
files = sorted([f for f in os.listdir(d["agent_dirs"].get(args.agent)) if f.endswith(".md")],
key=lambda f: os.path.getmtime(os.path.join(d["agent_dirs"].get(args.agent), f)), reverse=True)
for i, f in enumerate(files[:20], 1):
print(f"{i:3d} {f}")
def cmd_read(args):
d = load_agent_dirs()
base = d["agent_dirs"].get(args.agent)
target = args.which
if target.isdigit():
files = sorted([f for f in os.listdir(base) if f.endswith(".md")],
key=lambda f: os.path.getmtime(os.path.join(base, f)), reverse=True)
if 1 <= int(target) <= len(files):
target = files[int(target) - 1]
else:
print("超出范围"); return
fpath = target if os.path.isabs(target) else os.path.join(base, target)
with open(fpath, "r", encoding="utf-8") as f:
print(f.read()[:args.limit])
def extract_sections(text: str) -> dict:
out, cur, buf = {}, None, []
for line in text.splitlines():
m = re.match(r"^##\s+(.*)$", line)
if m:
if cur:
out[cur] = "\n".join(buf).strip()
cur, buf = m.group(1).strip(), []
elif cur:
buf.append(line)
if cur:
out[cur] = "\n".join(buf).strip()
return out
def cmd_bootstrap(args):
d = load_agent_dirs()
base = d["agent_dirs"].get(args.agent)
if not base or not os.path.isdir(base):
print("目录不存在: %s(先跑 init)" % base); return
files = sorted([f for f in os.listdir(base) if f.endswith(".md")],
key=lambda f: os.path.getmtime(os.path.join(base, f)), reverse=True)
if not files:
print("(暂无工作记录)"); return
fpath = os.path.join(base, files[0])
with open(fpath, "r", encoding="utf-8") as f:
text = f.read()
sec = extract_sections(text)
print("== 最新工作记录: %s" % fpath)
for name in ("涌现连接", "遗留待办", "遗留与待办", "坑与根因"):
if name in sec and sec[name]:
print("## %s\n%s\n" % (name, sec[name]))
if clawmem_available():
out = clawmem_exec(["diary", "read", "-n", "5"])
print("== clawmem 共享记忆(最近 5 条)\n%s\n" % out)
if args.query:
out2 = clawmem_exec(["vsearch", args.query, "-n", "5"])
print("== clawmem vsearch(\"%s\")\n%s" % (args.query, out2))
else:
print("[WARN] clawmem 不可用,跳过共享记忆")
def cmd_emerge(args):
fpath = args.file or r"E:\记忆宇宙计划\金句提炼\32-AI回响-涌现连接.md"
os.makedirs(os.path.dirname(fpath) or ".", exist_ok=True)
date = datetime.datetime.now().strftime("%Y-%m-%d")
entry = "- 连接:[[%s]] × [[%s]] → %s\n <sub>%s · %s · %s</sub>" % (
args.a, args.b, args.sentence, date, args.agent, args.note or "")
if os.path.exists(fpath):
with open(fpath, "r", encoding="utf-8") as f:
text = f.read()
marker = "## " + date
if marker in text:
idx = text.rfind(marker)
nxt = text.find("\n## ", idx + 1)
insert_at = nxt if nxt != -1 else len(text)
text = text[:insert_at].rstrip("\n") + "\n\n" + entry + text[insert_at:]
else:
text = text.rstrip("\n") + "\n\n---\n\n" + "## " + date + "\n\n" + entry + "\n"
with open(fpath, "w", encoding="utf-8") as f:
f.write(text)
print("[OK] 连接已追加: %s" % fpath)
else:
with open(fpath, "w", encoding="utf-8") as f:
f.write("# Generated by %s · %s\n\n## %s\n\n%s\n" % (args.agent, date, date, entry))
print("[OK] 已创建: %s" % fpath)
def cmd_agent_list(args):
d = load_agent_dirs()
for k, v in d["agent_dirs"].items():
n = len([f for f in os.listdir(v) if f.endswith(".md")]) if os.path.isdir(v) else 0
print(f"{k:10s} {v:40s} {n} 条记录")
def main():
p = argparse.ArgumentParser(description="memory-cli 文档驱动记忆系统")
sub = p.add_subparsers(dest="cmd", required=True)
sub.add_parser("init").set_defaults(f=cmd_init)
w = sub.add_parser("write")
w.add_argument("text"); w.add_argument("--agent", default="dsh")
w.add_argument("--summary"); w.add_argument("--evidence")
w.add_argument("--pits"); w.add_argument("--emergence")
w.add_argument("--todo"); w.add_argument("--artifacts")
w.add_argument("--no-sync", action="store_true")
w.add_argument("--selfcheck", action="store_true"); w.set_defaults(f=cmd_write)
s = sub.add_parser("sync"); s.add_argument("--agent", default="dsh"); s.set_defaults(f=cmd_sync)
l = sub.add_parser("list"); l.add_argument("--agent", default="dsh"); l.set_defaults(f=cmd_list)
r = sub.add_parser("read"); r.add_argument("which"); r.add_argument("--agent", default="dsh")
r.add_argument("--limit", type=int, default=6000); r.set_defaults(f=cmd_read)
a = sub.add_parser("agent-list"); a.set_defaults(f=cmd_agent_list)
b = sub.add_parser("bootstrap")
b.add_argument("--agent", default="dsh"); b.add_argument("--query")
b.set_defaults(f=cmd_bootstrap)
e = sub.add_parser("emerge")
e.add_argument("a"); e.add_argument("b"); e.add_argument("sentence")
e.add_argument("--agent", default="dsh"); e.add_argument("--note")
e.add_argument("--file")
e.set_defaults(f=cmd_emerge)
args = p.parse_args()
args.f(args)
if __name__ == "__main__":
main()