agent-shared-workspace 0.1.0__py3-none-any.whl
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.
- agent_shared_workspace/__init__.py +3 -0
- agent_shared_workspace/cli.py +1094 -0
- agent_shared_workspace/mcp_server.py +385 -0
- agent_shared_workspace-0.1.0.dist-info/METADATA +218 -0
- agent_shared_workspace-0.1.0.dist-info/RECORD +9 -0
- agent_shared_workspace-0.1.0.dist-info/WHEEL +5 -0
- agent_shared_workspace-0.1.0.dist-info/entry_points.txt +3 -0
- agent_shared_workspace-0.1.0.dist-info/licenses/LICENSE +21 -0
- agent_shared_workspace-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1094 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
r"""Shared Workspace Management CLI Tool.
|
|
3
|
+
|
|
4
|
+
Enforces SOP rules, query/append/update experiences (EXP), manage projects,
|
|
5
|
+
record handoffs, guard dirty working trees, and perform local Git commits
|
|
6
|
+
with cross-process file locking.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import datetime
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
if os.name == "nt":
|
|
23
|
+
import msvcrt
|
|
24
|
+
else:
|
|
25
|
+
import fcntl
|
|
26
|
+
|
|
27
|
+
# Local upstream default; set to None in portable distributions to default to cwd.
|
|
28
|
+
DEFAULT_WORKSPACE_ROOT: Path | None = None
|
|
29
|
+
|
|
30
|
+
DEFAULT_FILES_ZH = {
|
|
31
|
+
"agents": "AGENTS.md",
|
|
32
|
+
"board": "全局工作台.md",
|
|
33
|
+
"log": "全局复用与踩坑日志.md",
|
|
34
|
+
"sop": "新项目创建SOP.md",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
DEFAULT_FILES_EN = {
|
|
38
|
+
"agents": "AGENTS.md",
|
|
39
|
+
"board": "WORKSPACE.md",
|
|
40
|
+
"log": "EXPERIENCES.md",
|
|
41
|
+
"sop": "NEW_PROJECT_SOP.md",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
CONFIG_FILENAME = "workspace.config.json"
|
|
45
|
+
LOCK_FILENAME = ".workspace.lock"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_workspace_root() -> Path:
|
|
49
|
+
"""Resolve workspace root: AGENT_WORKSPACE_ROOT > DEFAULT_WORKSPACE_ROOT > cwd."""
|
|
50
|
+
override = os.environ.get("AGENT_WORKSPACE_ROOT", "").strip()
|
|
51
|
+
if override:
|
|
52
|
+
return Path(override).expanduser().resolve()
|
|
53
|
+
if DEFAULT_WORKSPACE_ROOT is not None:
|
|
54
|
+
return DEFAULT_WORKSPACE_ROOT.resolve()
|
|
55
|
+
return Path.cwd().resolve()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def load_workspace_config(root: Path) -> tuple[str, dict[str, str]]:
|
|
59
|
+
"""Load language and filenames from workspace.config.json or auto-detect layout."""
|
|
60
|
+
cfg_path = root / CONFIG_FILENAME
|
|
61
|
+
if cfg_path.is_file():
|
|
62
|
+
try:
|
|
63
|
+
data = json.loads(cfg_path.read_text(encoding="utf-8"))
|
|
64
|
+
lang = str(data.get("lang", "zh")).lower()
|
|
65
|
+
defaults = DEFAULT_FILES_EN if lang == "en" else DEFAULT_FILES_ZH
|
|
66
|
+
files = dict(defaults)
|
|
67
|
+
if isinstance(data.get("files"), dict):
|
|
68
|
+
for key in ("agents", "board", "log", "sop"):
|
|
69
|
+
val = data["files"].get(key)
|
|
70
|
+
if isinstance(val, str) and val.strip():
|
|
71
|
+
files[key] = val.strip()
|
|
72
|
+
return lang, files
|
|
73
|
+
except (OSError, json.JSONDecodeError):
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
if (root / DEFAULT_FILES_EN["log"]).exists() or (root / DEFAULT_FILES_EN["board"]).exists():
|
|
77
|
+
if not (root / DEFAULT_FILES_ZH["log"]).exists() and not (root / DEFAULT_FILES_ZH["board"]).exists():
|
|
78
|
+
return "en", dict(DEFAULT_FILES_EN)
|
|
79
|
+
|
|
80
|
+
return "zh", dict(DEFAULT_FILES_ZH)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
WORKSPACE_ROOT = resolve_workspace_root()
|
|
84
|
+
WORKSPACE_LANG, WORKSPACE_FILES = load_workspace_config(WORKSPACE_ROOT)
|
|
85
|
+
GLOBAL_LOG = WORKSPACE_ROOT / WORKSPACE_FILES["log"]
|
|
86
|
+
GLOBAL_BOARD = WORKSPACE_ROOT / WORKSPACE_FILES["board"]
|
|
87
|
+
SOP_FILE = WORKSPACE_ROOT / WORKSPACE_FILES["sop"]
|
|
88
|
+
AGENTS_FILE = WORKSPACE_ROOT / WORKSPACE_FILES["agents"]
|
|
89
|
+
LOCK_FILE = WORKSPACE_ROOT / LOCK_FILENAME
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# -------------------------------------------------------------
|
|
93
|
+
# Cross-process Reentrant File Lock (stdlib only)
|
|
94
|
+
# -------------------------------------------------------------
|
|
95
|
+
class WorkspaceLock:
|
|
96
|
+
"""Cross-process exclusive file lock (msvcrt on Windows, fcntl on POSIX).
|
|
97
|
+
|
|
98
|
+
Reentrant within the same Python process so compound commands like
|
|
99
|
+
``handoff`` -> ``project update`` never self-deadlock.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
_held: dict[Path, tuple[int, Any]] = {}
|
|
103
|
+
|
|
104
|
+
def __init__(self, lock_path: Path | None = None, timeout: float | None = None) -> None:
|
|
105
|
+
self.lock_path = (lock_path or LOCK_FILE).resolve()
|
|
106
|
+
if timeout is None:
|
|
107
|
+
env_timeout = os.environ.get("AGENT_WORKSPACE_LOCK_TIMEOUT", "10").strip()
|
|
108
|
+
try:
|
|
109
|
+
timeout = float(env_timeout)
|
|
110
|
+
except ValueError:
|
|
111
|
+
timeout = 10.0
|
|
112
|
+
self.timeout = max(0.0, timeout)
|
|
113
|
+
|
|
114
|
+
def acquire(self) -> None:
|
|
115
|
+
if self.lock_path in self._held:
|
|
116
|
+
depth, handle = self._held[self.lock_path]
|
|
117
|
+
self._held[self.lock_path] = (depth + 1, handle)
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
121
|
+
handle = open(self.lock_path, "a+b")
|
|
122
|
+
deadline = time.monotonic() + self.timeout
|
|
123
|
+
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
if os.name == "nt":
|
|
127
|
+
handle.seek(0)
|
|
128
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
129
|
+
else:
|
|
130
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
131
|
+
self._held[self.lock_path] = (1, handle)
|
|
132
|
+
return
|
|
133
|
+
except OSError:
|
|
134
|
+
if time.monotonic() >= deadline:
|
|
135
|
+
handle.close()
|
|
136
|
+
raise TimeoutError(
|
|
137
|
+
f"等待工作区写锁超时({self.timeout:.1f}s):{self.lock_path}。"
|
|
138
|
+
"可能有其他 Agent 正在写入,请稍后重试。"
|
|
139
|
+
)
|
|
140
|
+
time.sleep(0.05)
|
|
141
|
+
|
|
142
|
+
def release(self) -> None:
|
|
143
|
+
entry = self._held.get(self.lock_path)
|
|
144
|
+
if not entry:
|
|
145
|
+
return
|
|
146
|
+
depth, handle = entry
|
|
147
|
+
if depth > 1:
|
|
148
|
+
self._held[self.lock_path] = (depth - 1, handle)
|
|
149
|
+
return
|
|
150
|
+
|
|
151
|
+
del self._held[self.lock_path]
|
|
152
|
+
try:
|
|
153
|
+
if os.name == "nt":
|
|
154
|
+
handle.seek(0)
|
|
155
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
156
|
+
else:
|
|
157
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
158
|
+
finally:
|
|
159
|
+
handle.close()
|
|
160
|
+
|
|
161
|
+
def __enter__(self) -> WorkspaceLock:
|
|
162
|
+
self.acquire()
|
|
163
|
+
return self
|
|
164
|
+
|
|
165
|
+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
166
|
+
self.release()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# -------------------------------------------------------------
|
|
170
|
+
# Basic Helpers
|
|
171
|
+
# -------------------------------------------------------------
|
|
172
|
+
def read_text(path: Path) -> str:
|
|
173
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def write_text(path: Path, content: str) -> None:
|
|
177
|
+
path.write_text(content, encoding="utf-8")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def run_git(args: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
|
181
|
+
return subprocess.run(
|
|
182
|
+
["git"] + args,
|
|
183
|
+
cwd=str(cwd or WORKSPACE_ROOT),
|
|
184
|
+
capture_output=True,
|
|
185
|
+
text=True,
|
|
186
|
+
encoding="utf-8",
|
|
187
|
+
errors="replace",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def get_dirty_files() -> tuple[bool, list[str], str]:
|
|
192
|
+
"""Return (is_git_repo, dirty_lines, error_message), excluding the lock file."""
|
|
193
|
+
res = run_git(["-c", "core.quotepath=false", "status", "--porcelain"])
|
|
194
|
+
if res.returncode != 0:
|
|
195
|
+
return False, [], res.stderr.strip() or res.stdout.strip()
|
|
196
|
+
lines: list[str] = []
|
|
197
|
+
for raw in res.stdout.splitlines():
|
|
198
|
+
if not raw.strip():
|
|
199
|
+
continue
|
|
200
|
+
path_part = raw[3:].strip().strip('"')
|
|
201
|
+
if path_part == LOCK_FILENAME or path_part.endswith("/" + LOCK_FILENAME):
|
|
202
|
+
continue
|
|
203
|
+
lines.append(raw)
|
|
204
|
+
return True, lines, ""
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def find_project_dir(proj_key: str) -> Path | None:
|
|
208
|
+
"""Find a Project_xxx directory by number (e.g. 13, 013, P013) or name substring."""
|
|
209
|
+
proj_key_clean = proj_key.strip()
|
|
210
|
+
m = re.match(r"^[pP]?(\d+)$", proj_key_clean)
|
|
211
|
+
target_num = int(m.group(1)) if m else None
|
|
212
|
+
|
|
213
|
+
if not WORKSPACE_ROOT.exists():
|
|
214
|
+
return None
|
|
215
|
+
|
|
216
|
+
for entry in WORKSPACE_ROOT.iterdir():
|
|
217
|
+
if entry.is_dir() and entry.name.startswith("Project_"):
|
|
218
|
+
if target_num is not None:
|
|
219
|
+
em = re.match(r"^Project_(\d+)_", entry.name)
|
|
220
|
+
if em and int(em.group(1)) == target_num:
|
|
221
|
+
return entry
|
|
222
|
+
else:
|
|
223
|
+
if proj_key_clean.lower() in entry.name.lower():
|
|
224
|
+
return entry
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def parse_tags(raw_tags: list[str] | None) -> list[str]:
|
|
229
|
+
"""Normalize tags from repeated --tag flags or comma/space-separated values."""
|
|
230
|
+
if not raw_tags:
|
|
231
|
+
return []
|
|
232
|
+
result: list[str] = []
|
|
233
|
+
seen: set[str] = set()
|
|
234
|
+
for item in raw_tags:
|
|
235
|
+
for token in re.split(r"[,,\s]+", item.strip()):
|
|
236
|
+
clean = token.strip().lstrip("#")
|
|
237
|
+
if not clean:
|
|
238
|
+
continue
|
|
239
|
+
key = clean.lower()
|
|
240
|
+
if key not in seen:
|
|
241
|
+
seen.add(key)
|
|
242
|
+
result.append(clean)
|
|
243
|
+
return result
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def extract_hashtags(text: str) -> list[str]:
|
|
247
|
+
"""Extract #tag tokens from markdown text without matching markdown headings."""
|
|
248
|
+
tags: list[str] = []
|
|
249
|
+
for match in re.finditer(r"(?:^|[\s((\[|,,])#([^\s#|,,。)\]]+)", text):
|
|
250
|
+
tag = match.group(1).strip()
|
|
251
|
+
if tag and not re.fullmatch(r"\d+", tag):
|
|
252
|
+
tags.append(tag)
|
|
253
|
+
return tags
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def text_matches_tags(text: str, required_tags: list[str]) -> bool:
|
|
257
|
+
if not required_tags:
|
|
258
|
+
return True
|
|
259
|
+
present = {t.lower() for t in extract_hashtags(text)}
|
|
260
|
+
return all(req.lower() in present for req in required_tags)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# -------------------------------------------------------------
|
|
264
|
+
# Init Operation
|
|
265
|
+
# -------------------------------------------------------------
|
|
266
|
+
def _skeleton_docs(lang: str) -> dict[str, str]:
|
|
267
|
+
if lang == "en":
|
|
268
|
+
return {
|
|
269
|
+
DEFAULT_FILES_EN["agents"]: """# Shared Workspace Rules
|
|
270
|
+
|
|
271
|
+
This workspace is the single source of truth for all coding agents.
|
|
272
|
+
|
|
273
|
+
## First-turn checklist
|
|
274
|
+
1. Read `AGENTS.md`, `WORKSPACE.md`, `NEW_PROJECT_SOP.md`, and the index table of `EXPERIENCES.md`.
|
|
275
|
+
2. Before debugging or adding a dependency, run `exp search` first.
|
|
276
|
+
3. Keep all project artifacts inside `Project_XXX_<Name>/`.
|
|
277
|
+
4. Before ending a task, record `handoff` (when applicable) and run `commit -m "..."`.
|
|
278
|
+
""",
|
|
279
|
+
DEFAULT_FILES_EN["board"]: """# Workspace Board
|
|
280
|
+
|
|
281
|
+
## Projects
|
|
282
|
+
|
|
283
|
+
| ID | Directory | Status | Entry |
|
|
284
|
+
| --- | --- | --- | --- |
|
|
285
|
+
""",
|
|
286
|
+
DEFAULT_FILES_EN["log"]: """# Experience & Pitfall Log
|
|
287
|
+
|
|
288
|
+
## Experience Index
|
|
289
|
+
|
|
290
|
+
### Active Entries (0)
|
|
291
|
+
|
|
292
|
+
| ID | Date | Type | Title | Location |
|
|
293
|
+
| --- | --- | --- | --- | --- |
|
|
294
|
+
|
|
295
|
+
## Records
|
|
296
|
+
""",
|
|
297
|
+
DEFAULT_FILES_EN["sop"]: """# New Project SOP
|
|
298
|
+
|
|
299
|
+
1. Check `WORKSPACE.md` to ensure no duplicate project exists.
|
|
300
|
+
2. Create the project directory using `workspace_tool.py project new "<name>" --owner "<agent>"`.
|
|
301
|
+
3. Update `docs/当前状态与交接.md` via `handoff` before pausing or finishing.
|
|
302
|
+
4. Commit all changes via `commit -m "..."`.
|
|
303
|
+
""",
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
return {
|
|
307
|
+
DEFAULT_FILES_ZH["agents"]: """# 共享工作空间规则
|
|
308
|
+
|
|
309
|
+
本工作空间是所有 Agent 的唯一记忆与项目协作入口。
|
|
310
|
+
|
|
311
|
+
## 启动与操作约定
|
|
312
|
+
1. 新建对话首轮读取 `AGENTS.md`、`全局工作台.md`、`新项目创建SOP.md` 及 `全局复用与踩坑日志.md` 的索引表。
|
|
313
|
+
2. 排查问题或引入新依赖前,先执行 `exp search "关键词"` 检索已有经验。
|
|
314
|
+
3. 所有项目产物必须落盘到对应 `Project_编号_项目名称/` 目录。
|
|
315
|
+
4. 阶段完成用 `handoff` 交接,新经验用 `exp add` / `exp update` 沉淀,结束前用 `commit -m "..."` 固化到 Git。
|
|
316
|
+
""",
|
|
317
|
+
DEFAULT_FILES_ZH["board"]: """# 全局工作台
|
|
318
|
+
|
|
319
|
+
## 项目登记与接续入口
|
|
320
|
+
|
|
321
|
+
| 编号 | 目录 | 当前状态 | 接续入口 |
|
|
322
|
+
| --- | --- | --- | --- |
|
|
323
|
+
""",
|
|
324
|
+
DEFAULT_FILES_ZH["log"]: """# 全局复用与踩坑日志
|
|
325
|
+
|
|
326
|
+
## 经验索引
|
|
327
|
+
|
|
328
|
+
### 现行条目(0 条)
|
|
329
|
+
|
|
330
|
+
| 编号 | 日期 | 类型 | 标题 | 位置 |
|
|
331
|
+
| --- | --- | --- | --- | --- |
|
|
332
|
+
|
|
333
|
+
## 记录
|
|
334
|
+
""",
|
|
335
|
+
DEFAULT_FILES_ZH["sop"]: """# 新项目创建 SOP
|
|
336
|
+
|
|
337
|
+
1. 检查 `全局工作台.md`,确认无同目标项目。
|
|
338
|
+
2. 使用 `workspace_tool.py project new "<名称>" --owner "<agent>"` 建项,不手动建目录。
|
|
339
|
+
3. 阶段完成或暂停前使用 `handoff` 更新交接与登记表。
|
|
340
|
+
4. 结束前使用 `commit -m "..."` 提交工作区变更。
|
|
341
|
+
""",
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def cmd_init(lang: str = "zh", no_git: bool = False) -> None:
|
|
346
|
+
lang = "en" if lang.lower() == "en" else "zh"
|
|
347
|
+
WORKSPACE_ROOT.mkdir(parents=True, exist_ok=True)
|
|
348
|
+
|
|
349
|
+
with WorkspaceLock():
|
|
350
|
+
created: list[str] = []
|
|
351
|
+
skipped: list[str] = []
|
|
352
|
+
|
|
353
|
+
docs = _skeleton_docs(lang)
|
|
354
|
+
for filename, content in docs.items():
|
|
355
|
+
target = WORKSPACE_ROOT / filename
|
|
356
|
+
if target.exists():
|
|
357
|
+
skipped.append(filename)
|
|
358
|
+
else:
|
|
359
|
+
write_text(target, content)
|
|
360
|
+
created.append(filename)
|
|
361
|
+
|
|
362
|
+
cfg_path = WORKSPACE_ROOT / CONFIG_FILENAME
|
|
363
|
+
files_map = DEFAULT_FILES_EN if lang == "en" else DEFAULT_FILES_ZH
|
|
364
|
+
if cfg_path.exists():
|
|
365
|
+
skipped.append(CONFIG_FILENAME)
|
|
366
|
+
else:
|
|
367
|
+
cfg_data = {"lang": lang, "files": files_map}
|
|
368
|
+
write_text(cfg_path, json.dumps(cfg_data, ensure_ascii=False, indent=2) + "\n")
|
|
369
|
+
created.append(CONFIG_FILENAME)
|
|
370
|
+
|
|
371
|
+
gitignore_path = WORKSPACE_ROOT / ".gitignore"
|
|
372
|
+
if not gitignore_path.exists():
|
|
373
|
+
write_text(
|
|
374
|
+
gitignore_path,
|
|
375
|
+
f"{LOCK_FILENAME}\n**/tmp/\n**/__pycache__/\n*.pyc\n.DS_Store\n",
|
|
376
|
+
)
|
|
377
|
+
created.append(".gitignore")
|
|
378
|
+
else:
|
|
379
|
+
gi_text = read_text(gitignore_path)
|
|
380
|
+
if LOCK_FILENAME not in gi_text.splitlines():
|
|
381
|
+
write_text(gitignore_path, gi_text.rstrip() + f"\n{LOCK_FILENAME}\n")
|
|
382
|
+
print(f"已向 .gitignore 追加 {LOCK_FILENAME}")
|
|
383
|
+
skipped.append(".gitignore")
|
|
384
|
+
|
|
385
|
+
if not no_git and not (WORKSPACE_ROOT / ".git").exists():
|
|
386
|
+
res = run_git(["init"])
|
|
387
|
+
if res.returncode == 0:
|
|
388
|
+
run_git(["config", "core.quotepath", "false"])
|
|
389
|
+
print(f"已初始化 Git 仓库: {WORKSPACE_ROOT}")
|
|
390
|
+
else:
|
|
391
|
+
print(f"警告: git init 失败: {res.stderr.strip()}", file=sys.stderr)
|
|
392
|
+
|
|
393
|
+
print(f"工作空间初始化完成(语言: {lang},目录: {WORKSPACE_ROOT})")
|
|
394
|
+
if created:
|
|
395
|
+
print("新建文件: " + ", ".join(created))
|
|
396
|
+
if skipped:
|
|
397
|
+
print("已存在跳过: " + ", ".join(skipped))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# -------------------------------------------------------------
|
|
401
|
+
# EXP Operations (Read, Add, Update, Tags)
|
|
402
|
+
# -------------------------------------------------------------
|
|
403
|
+
def get_max_exp_id() -> int:
|
|
404
|
+
if not GLOBAL_LOG.exists():
|
|
405
|
+
return 0
|
|
406
|
+
content = read_text(GLOBAL_LOG)
|
|
407
|
+
max_id = 0
|
|
408
|
+
for match in re.finditer(r"^\|\s*EXP-(\d+)\s*\|", content, re.MULTILINE):
|
|
409
|
+
val = int(match.group(1))
|
|
410
|
+
if val > max_id:
|
|
411
|
+
max_id = val
|
|
412
|
+
return max_id
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def cmd_exp_list_tags() -> None:
|
|
416
|
+
if not GLOBAL_LOG.exists():
|
|
417
|
+
print(f"Error: {GLOBAL_LOG} not found.", file=sys.stderr)
|
|
418
|
+
sys.exit(1)
|
|
419
|
+
|
|
420
|
+
content = read_text(GLOBAL_LOG)
|
|
421
|
+
counts: dict[str, int] = {}
|
|
422
|
+
display_name: dict[str, str] = {}
|
|
423
|
+
|
|
424
|
+
for line in content.splitlines():
|
|
425
|
+
if line.startswith("| EXP-") or line.startswith("- 标签:") or line.startswith("- Tags:"):
|
|
426
|
+
for tag in extract_hashtags(line):
|
|
427
|
+
key = tag.lower()
|
|
428
|
+
counts[key] = counts.get(key, 0) + 1
|
|
429
|
+
display_name.setdefault(key, tag)
|
|
430
|
+
|
|
431
|
+
if not counts:
|
|
432
|
+
print("当前暂无已登记标签。使用 `exp add --tag <标签>` 为经验打标。")
|
|
433
|
+
return
|
|
434
|
+
|
|
435
|
+
print("=== 经验标签统计 ===")
|
|
436
|
+
for key, cnt in sorted(counts.items(), key=lambda x: (-x[1], x[0])):
|
|
437
|
+
print(f"#{display_name[key]} ({cnt})")
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def cmd_exp_search(query: str = "", raw_tags: list[str] | None = None, list_tags: bool = False) -> None:
|
|
441
|
+
if list_tags:
|
|
442
|
+
cmd_exp_list_tags()
|
|
443
|
+
return
|
|
444
|
+
|
|
445
|
+
tags = parse_tags(raw_tags)
|
|
446
|
+
if not query and not tags:
|
|
447
|
+
print("错误: 请至少提供检索关键词或 --tag 标签。", file=sys.stderr)
|
|
448
|
+
sys.exit(1)
|
|
449
|
+
|
|
450
|
+
if not GLOBAL_LOG.exists():
|
|
451
|
+
print(f"Error: {GLOBAL_LOG} not found.", file=sys.stderr)
|
|
452
|
+
sys.exit(1)
|
|
453
|
+
|
|
454
|
+
content = read_text(GLOBAL_LOG)
|
|
455
|
+
lines = content.splitlines()
|
|
456
|
+
|
|
457
|
+
cond_parts: list[str] = []
|
|
458
|
+
if query:
|
|
459
|
+
cond_parts.append(f"关键词: '{query}'")
|
|
460
|
+
if tags:
|
|
461
|
+
cond_parts.append("标签: " + " ".join(f"#{t}" for t in tags))
|
|
462
|
+
print(f"=== 搜索踩坑与复用经验 ({','.join(cond_parts)}) ===")
|
|
463
|
+
|
|
464
|
+
matches = 0
|
|
465
|
+
in_table = False
|
|
466
|
+
for line in lines:
|
|
467
|
+
if line.startswith("| EXP-") or (in_table and line.startswith("|")):
|
|
468
|
+
in_table = True
|
|
469
|
+
q_ok = (not query) or (query.lower() in line.lower())
|
|
470
|
+
t_ok = text_matches_tags(line, tags)
|
|
471
|
+
if q_ok and t_ok:
|
|
472
|
+
print(line)
|
|
473
|
+
matches += 1
|
|
474
|
+
elif in_table and not line.startswith("|"):
|
|
475
|
+
in_table = False
|
|
476
|
+
|
|
477
|
+
if matches == 0:
|
|
478
|
+
print("未在经验索引表中找到匹配项,尝试检索全文段落...")
|
|
479
|
+
sections = re.split(r"(?=^### EXP-\d+)", content, flags=re.MULTILINE)
|
|
480
|
+
for sec in sections:
|
|
481
|
+
if not sec.startswith("### EXP-"):
|
|
482
|
+
continue
|
|
483
|
+
q_ok = (not query) or (query.lower() in sec.lower())
|
|
484
|
+
t_ok = text_matches_tags(sec, tags)
|
|
485
|
+
if q_ok and t_ok:
|
|
486
|
+
snippet = "\n".join(sec.splitlines()[:10])
|
|
487
|
+
print(f"\n{snippet}\n---")
|
|
488
|
+
matches += 1
|
|
489
|
+
|
|
490
|
+
if matches == 0:
|
|
491
|
+
print("无匹配经验条目。")
|
|
492
|
+
else:
|
|
493
|
+
print(f"\n共找到 {matches} 条匹配记录。使用 'exp get EXP-xxx' 查看具体详情。")
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def cmd_exp_get(exp_id: str) -> None:
|
|
497
|
+
exp_id = exp_id.upper()
|
|
498
|
+
if not exp_id.startswith("EXP-"):
|
|
499
|
+
exp_id = f"EXP-{exp_id}"
|
|
500
|
+
|
|
501
|
+
if not GLOBAL_LOG.exists():
|
|
502
|
+
print(f"Error: {GLOBAL_LOG} not found.", file=sys.stderr)
|
|
503
|
+
sys.exit(1)
|
|
504
|
+
|
|
505
|
+
content = read_text(GLOBAL_LOG)
|
|
506
|
+
lines = content.splitlines()
|
|
507
|
+
|
|
508
|
+
location = None
|
|
509
|
+
for line in lines:
|
|
510
|
+
if f"| {exp_id} |" in line or f"|{exp_id}|" in line:
|
|
511
|
+
print(f"【索引登记】: {line}")
|
|
512
|
+
parts = [p.strip() for p in line.split("|")]
|
|
513
|
+
if len(parts) >= 6:
|
|
514
|
+
location = parts[5]
|
|
515
|
+
break
|
|
516
|
+
|
|
517
|
+
found = False
|
|
518
|
+
captured: list[str] = []
|
|
519
|
+
recording = False
|
|
520
|
+
for line in lines:
|
|
521
|
+
if line.startswith(f"### {exp_id}") or line.startswith(f"## {exp_id}"):
|
|
522
|
+
recording = True
|
|
523
|
+
captured.append(line)
|
|
524
|
+
continue
|
|
525
|
+
if recording:
|
|
526
|
+
if line.startswith("### ") or line.startswith("## "):
|
|
527
|
+
break
|
|
528
|
+
captured.append(line)
|
|
529
|
+
|
|
530
|
+
if captured:
|
|
531
|
+
print("\n".join(captured).strip())
|
|
532
|
+
found = True
|
|
533
|
+
|
|
534
|
+
if not found:
|
|
535
|
+
if location and ("下沉" in location or "sunk" in location.lower()):
|
|
536
|
+
print(f"\n该条目细节已下沉至项目文档: {location}")
|
|
537
|
+
else:
|
|
538
|
+
print(f"\n未在全局日志正文中检索到 {exp_id} 的详情。可能已归档或下沉。")
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def cmd_exp_add(
|
|
542
|
+
title: str,
|
|
543
|
+
exp_type: str = "踩坑+复用方法",
|
|
544
|
+
phenomenon: str = "",
|
|
545
|
+
cause: str = "",
|
|
546
|
+
solution: str = "",
|
|
547
|
+
criteria: str = "",
|
|
548
|
+
sink_proj: str | None = None,
|
|
549
|
+
agent: str = "Agent",
|
|
550
|
+
raw_tags: list[str] | None = None,
|
|
551
|
+
) -> None:
|
|
552
|
+
if not GLOBAL_LOG.exists():
|
|
553
|
+
print(f"错误: 找不到 {GLOBAL_LOG}", file=sys.stderr)
|
|
554
|
+
sys.exit(1)
|
|
555
|
+
|
|
556
|
+
tags = parse_tags(raw_tags)
|
|
557
|
+
tag_str = " ".join(f"#{t}" for t in tags)
|
|
558
|
+
display_title = title.strip()
|
|
559
|
+
if tags:
|
|
560
|
+
existing_tags = {t.lower() for t in extract_hashtags(display_title)}
|
|
561
|
+
missing_tags = [f"#{t}" for t in tags if t.lower() not in existing_tags]
|
|
562
|
+
if missing_tags:
|
|
563
|
+
display_title = f"{display_title} {' '.join(missing_tags)}"
|
|
564
|
+
|
|
565
|
+
with WorkspaceLock():
|
|
566
|
+
next_id = get_max_exp_id() + 1
|
|
567
|
+
exp_tag = f"EXP-{next_id:03d}"
|
|
568
|
+
today = datetime.date.today().strftime("%Y-%m-%d")
|
|
569
|
+
|
|
570
|
+
sink_dir = find_project_dir(sink_proj) if sink_proj else None
|
|
571
|
+
if sink_proj and not sink_dir:
|
|
572
|
+
print(f"警告: 找不到项目 '{sink_proj}',将直接写入全局正文。", file=sys.stderr)
|
|
573
|
+
|
|
574
|
+
tag_meta_line = f"- 标签:{tag_str}\n" if tag_str else ""
|
|
575
|
+
|
|
576
|
+
if sink_dir:
|
|
577
|
+
p_name = sink_dir.name
|
|
578
|
+
docs_dir = sink_dir / "docs"
|
|
579
|
+
docs_dir.mkdir(exist_ok=True)
|
|
580
|
+
sink_file = docs_dir / "踩坑与复用经验.md"
|
|
581
|
+
location_str = f"下沉;{p_name} `docs/踩坑与复用经验.md`"
|
|
582
|
+
|
|
583
|
+
exp_body = (
|
|
584
|
+
f"### {exp_tag}|{today}|{display_title}\n\n"
|
|
585
|
+
f"- 记录主体:{agent};类型:{exp_type}\n"
|
|
586
|
+
f"{tag_meta_line}"
|
|
587
|
+
f"- 现象:{phenomenon or '(无)'}\n"
|
|
588
|
+
f"- 定位:{cause or '(无)'}\n"
|
|
589
|
+
f"- 处理:{solution or '(无)'}\n"
|
|
590
|
+
f"- 判据:{criteria or '(无)'}\n"
|
|
591
|
+
)
|
|
592
|
+
if sink_file.exists():
|
|
593
|
+
old_sink = read_text(sink_file)
|
|
594
|
+
write_text(sink_file, old_sink.rstrip() + "\n\n" + exp_body)
|
|
595
|
+
else:
|
|
596
|
+
header = f"# {p_name} 踩坑与复用经验下沉库\n\n"
|
|
597
|
+
write_text(sink_file, header + exp_body)
|
|
598
|
+
print(f"详细经验已下沉写入: {sink_file}")
|
|
599
|
+
else:
|
|
600
|
+
location_str = "正文"
|
|
601
|
+
|
|
602
|
+
content = read_text(GLOBAL_LOG)
|
|
603
|
+
|
|
604
|
+
def repl_count_zh(m: re.Match[str]) -> str:
|
|
605
|
+
return f"### 现行条目({int(m.group(1)) + 1} 条)"
|
|
606
|
+
|
|
607
|
+
def repl_count_en(m: re.Match[str]) -> str:
|
|
608
|
+
return f"### Active Entries ({int(m.group(1)) + 1})"
|
|
609
|
+
|
|
610
|
+
content, n_zh = re.subn(r"### 现行条目((\d+)\s*条)", repl_count_zh, content, count=1)
|
|
611
|
+
if n_zh == 0:
|
|
612
|
+
content = re.sub(r"### Active Entries \((\d+)\)", repl_count_en, content, count=1)
|
|
613
|
+
|
|
614
|
+
table_header_pat = (
|
|
615
|
+
r"(\|\s*(?:编号|ID)\s*\|\s*(?:日期|Date)\s*\|\s*(?:类型|Type)\s*"
|
|
616
|
+
r"\|\s*(?:标题|Title)\s*\|\s*(?:位置|Location)\s*\|\s*\n\|\s*---[^\n]+\n)"
|
|
617
|
+
)
|
|
618
|
+
m_header = re.search(table_header_pat, content)
|
|
619
|
+
if not m_header:
|
|
620
|
+
print("错误: 无法在全局日志中定位索引表格头!", file=sys.stderr)
|
|
621
|
+
sys.exit(1)
|
|
622
|
+
|
|
623
|
+
new_row = f"| {exp_tag} | {today} | {exp_type} | {display_title} | {location_str} |\n"
|
|
624
|
+
pos = m_header.end()
|
|
625
|
+
content = content[:pos] + new_row + content[pos:]
|
|
626
|
+
|
|
627
|
+
if not sink_dir:
|
|
628
|
+
exp_body = (
|
|
629
|
+
f"### {exp_tag}|{today}|{display_title}\n\n"
|
|
630
|
+
f"- 类型:{exp_type};记录主体:{agent}。\n"
|
|
631
|
+
f"{tag_meta_line}"
|
|
632
|
+
f"- 现象:{phenomenon or '待补充'}\n"
|
|
633
|
+
f"- 定位:{cause or '待补充'}\n"
|
|
634
|
+
f"- 处理:{solution or '待补充'}\n"
|
|
635
|
+
f"- 判据:{criteria or '待补充'}\n\n"
|
|
636
|
+
)
|
|
637
|
+
body_pat = r"(\n### EXP-\d+(?:||\s*\|))"
|
|
638
|
+
m_body = re.search(body_pat, content)
|
|
639
|
+
if m_body:
|
|
640
|
+
b_pos = m_body.start() + 1
|
|
641
|
+
content = content[:b_pos] + exp_body + content[b_pos:]
|
|
642
|
+
else:
|
|
643
|
+
content = content.rstrip() + "\n\n" + exp_body
|
|
644
|
+
|
|
645
|
+
write_text(GLOBAL_LOG, content)
|
|
646
|
+
|
|
647
|
+
print(f"成功沉淀新经验记忆: {exp_tag}")
|
|
648
|
+
print(f"标题: {display_title}")
|
|
649
|
+
if tag_str:
|
|
650
|
+
print(f"标签: {tag_str}")
|
|
651
|
+
print(f"位置: {location_str}")
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def cmd_exp_update(exp_id: str, note: str, agent: str = "Agent") -> None:
|
|
655
|
+
exp_id = exp_id.upper()
|
|
656
|
+
if not exp_id.startswith("EXP-"):
|
|
657
|
+
exp_id = f"EXP-{exp_id}"
|
|
658
|
+
|
|
659
|
+
if not GLOBAL_LOG.exists():
|
|
660
|
+
print(f"错误: 找不到 {GLOBAL_LOG}", file=sys.stderr)
|
|
661
|
+
sys.exit(1)
|
|
662
|
+
|
|
663
|
+
with WorkspaceLock():
|
|
664
|
+
content = read_text(GLOBAL_LOG)
|
|
665
|
+
today = datetime.date.today().strftime("%Y-%m-%d")
|
|
666
|
+
|
|
667
|
+
pat = rf"(### {re.escape(exp_id)}(?:||\s*\|)[^\n]+\n(?:(?!### EXP-).)*)"
|
|
668
|
+
m = re.search(pat, content, re.DOTALL)
|
|
669
|
+
if m:
|
|
670
|
+
original_section = m.group(1).rstrip()
|
|
671
|
+
append_line = f"\n- 补充({today} {agent}):{note}\n"
|
|
672
|
+
updated_section = original_section + append_line
|
|
673
|
+
new_content = content[: m.start(1)] + updated_section + content[m.end(1) :]
|
|
674
|
+
write_text(GLOBAL_LOG, new_content)
|
|
675
|
+
print(f"成功为 {exp_id} 追加补充更新记忆。")
|
|
676
|
+
return
|
|
677
|
+
|
|
678
|
+
for line in content.splitlines():
|
|
679
|
+
if f"| {exp_id} |" in line and ("下沉" in line or "sunk" in line.lower()):
|
|
680
|
+
parts = [p.strip() for p in line.split("|")]
|
|
681
|
+
loc = parts[5] if len(parts) >= 6 else ""
|
|
682
|
+
m_proj = re.search(r"(Project_\d+_[^`\s]+)", loc)
|
|
683
|
+
if m_proj:
|
|
684
|
+
p_dir = WORKSPACE_ROOT / m_proj.group(1)
|
|
685
|
+
sink_file = p_dir / "docs" / "踩坑与复用经验.md"
|
|
686
|
+
if sink_file.exists():
|
|
687
|
+
s_content = read_text(sink_file)
|
|
688
|
+
s_m = re.search(pat, s_content, re.DOTALL)
|
|
689
|
+
if s_m:
|
|
690
|
+
orig_s = s_m.group(1).rstrip()
|
|
691
|
+
up_s = orig_s + f"\n- 补充({today} {agent}):{note}\n"
|
|
692
|
+
new_s_content = s_content[: s_m.start(1)] + up_s + s_content[s_m.end(1) :]
|
|
693
|
+
write_text(sink_file, new_s_content)
|
|
694
|
+
print(f"成功在下沉文件 {sink_file} 中更新 {exp_id}。")
|
|
695
|
+
return
|
|
696
|
+
|
|
697
|
+
print(f"未找到 {exp_id} 的正文段落,无法追加。请核对编号。", file=sys.stderr)
|
|
698
|
+
sys.exit(1)
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
# -------------------------------------------------------------
|
|
702
|
+
# Project Operations (Read, New, Update, Handoff)
|
|
703
|
+
# -------------------------------------------------------------
|
|
704
|
+
def get_max_project_id() -> int:
|
|
705
|
+
max_id = 0
|
|
706
|
+
if not WORKSPACE_ROOT.exists():
|
|
707
|
+
return 0
|
|
708
|
+
for entry in WORKSPACE_ROOT.iterdir():
|
|
709
|
+
if entry.is_dir() and entry.name.startswith("Project_"):
|
|
710
|
+
m = re.match(r"^Project_(\d+)_", entry.name)
|
|
711
|
+
if m:
|
|
712
|
+
num = int(m.group(1))
|
|
713
|
+
if num > max_id:
|
|
714
|
+
max_id = num
|
|
715
|
+
return max_id
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def cmd_project_list() -> None:
|
|
719
|
+
print(f"{'编号':<6} {'目录名':<45} {'更新时间'}")
|
|
720
|
+
print("-" * 75)
|
|
721
|
+
projects: list[tuple[int, str, str]] = []
|
|
722
|
+
if WORKSPACE_ROOT.exists():
|
|
723
|
+
for entry in sorted(WORKSPACE_ROOT.iterdir(), key=lambda x: x.name):
|
|
724
|
+
if entry.is_dir() and entry.name.startswith("Project_"):
|
|
725
|
+
m = re.match(r"^Project_(\d+)_", entry.name)
|
|
726
|
+
pid = int(m.group(1)) if m else 0
|
|
727
|
+
mtime = datetime.datetime.fromtimestamp(entry.stat().st_mtime).strftime("%Y-%m-%d %H:%M")
|
|
728
|
+
projects.append((pid, entry.name, mtime))
|
|
729
|
+
|
|
730
|
+
for pid, name, mtime in sorted(projects, key=lambda x: x[0]):
|
|
731
|
+
print(f"P{pid:03d} {name:<45} {mtime}")
|
|
732
|
+
print(f"\n当前共 {len(projects)} 个项目,最大编号: P{get_max_project_id():03d}")
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def cmd_project_new(name: str, owner: str = "Agent") -> None:
|
|
736
|
+
with WorkspaceLock():
|
|
737
|
+
next_id = get_max_project_id() + 1
|
|
738
|
+
dir_name = f"Project_{next_id:03d}_{name}"
|
|
739
|
+
proj_dir = WORKSPACE_ROOT / dir_name
|
|
740
|
+
|
|
741
|
+
if proj_dir.exists():
|
|
742
|
+
print(f"错误: 目标目录 {proj_dir} 已存在!", file=sys.stderr)
|
|
743
|
+
sys.exit(1)
|
|
744
|
+
|
|
745
|
+
today = datetime.date.today().strftime("%Y-%m-%d")
|
|
746
|
+
|
|
747
|
+
proj_dir.mkdir(parents=True)
|
|
748
|
+
docs_dir = proj_dir / "docs"
|
|
749
|
+
docs_dir.mkdir()
|
|
750
|
+
(proj_dir / "output").mkdir()
|
|
751
|
+
(proj_dir / "tmp").mkdir()
|
|
752
|
+
|
|
753
|
+
readme_content = f"""# {name}
|
|
754
|
+
|
|
755
|
+
- 项目编号:Project_{next_id:03d}
|
|
756
|
+
- 目标与范围:
|
|
757
|
+
- 负责人或执行主体:{owner}
|
|
758
|
+
- 当前状态:进行中
|
|
759
|
+
- 启动日期:{today}
|
|
760
|
+
- 启动前检查:已阅读 `{WORKSPACE_FILES['agents']}`、`{WORKSPACE_FILES['board']}`、`{WORKSPACE_FILES['sop']}` 全文及 `{WORKSPACE_FILES['log']}` 经验索引
|
|
761
|
+
- 相关经验:暂无
|
|
762
|
+
- 主要目录与文件:
|
|
763
|
+
- `docs/`: 状态交接与过程方案
|
|
764
|
+
- `output/`: 构建产物与交付件
|
|
765
|
+
- `tmp/`: 过程临时数据
|
|
766
|
+
- 验证与交付标准:
|
|
767
|
+
"""
|
|
768
|
+
write_text(proj_dir / "README.md", readme_content)
|
|
769
|
+
|
|
770
|
+
handoff_content = f"""# 当前状态与交接
|
|
771
|
+
|
|
772
|
+
- 项目:{dir_name}
|
|
773
|
+
- 记录主体:{owner}
|
|
774
|
+
- 创建时间:{today}
|
|
775
|
+
|
|
776
|
+
## 1. 当前目标与范围
|
|
777
|
+
- 待补充
|
|
778
|
+
|
|
779
|
+
## 2. 已完成工作与一手证据
|
|
780
|
+
- 基础目录结构已按 SOP 初始化完成。
|
|
781
|
+
|
|
782
|
+
## 3. 未完成与下一步
|
|
783
|
+
- 开始业务需求分析与一手事实核验。
|
|
784
|
+
"""
|
|
785
|
+
write_text(docs_dir / "当前状态与交接.md", handoff_content)
|
|
786
|
+
|
|
787
|
+
if GLOBAL_BOARD.exists():
|
|
788
|
+
board_content = read_text(GLOBAL_BOARD)
|
|
789
|
+
new_row = f"| {next_id:03d} | {dir_name} | 进行中:初始化建项 | `README.md` → `docs/当前状态与交接.md` |\n"
|
|
790
|
+
pattern = r"(\| \d{3} \| Project_\d{3}_[^\n]+\n)"
|
|
791
|
+
matches = list(re.finditer(pattern, board_content))
|
|
792
|
+
if matches:
|
|
793
|
+
insert_pos = matches[-1].end()
|
|
794
|
+
else:
|
|
795
|
+
header = re.search(
|
|
796
|
+
r"\|\s*(?:编号|ID)\s*\|\s*(?:目录|Directory)\s*\|\s*(?:当前状态|Status)\s*\|\s*(?:接续入口|Entry)\s*\|\n\|\s*---[^\n]+\n",
|
|
797
|
+
board_content,
|
|
798
|
+
)
|
|
799
|
+
insert_pos = header.end() if header else len(board_content)
|
|
800
|
+
updated_board = board_content[:insert_pos] + new_row + board_content[insert_pos:]
|
|
801
|
+
write_text(GLOBAL_BOARD, updated_board)
|
|
802
|
+
print(f"已自动登记到 {GLOBAL_BOARD.name} 项目登记表。")
|
|
803
|
+
|
|
804
|
+
print(f"成功创建新项目:{dir_name}")
|
|
805
|
+
print(f"路径: {proj_dir}")
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def cmd_project_update(proj_key: str, status: str, entry: str | None = None) -> None:
|
|
809
|
+
with WorkspaceLock():
|
|
810
|
+
p_dir = find_project_dir(proj_key)
|
|
811
|
+
if not p_dir:
|
|
812
|
+
print(f"错误: 找不到项目 '{proj_key}'", file=sys.stderr)
|
|
813
|
+
sys.exit(1)
|
|
814
|
+
|
|
815
|
+
m = re.match(r"^Project_(\d+)_", p_dir.name)
|
|
816
|
+
num_str = m.group(1) if m else ""
|
|
817
|
+
|
|
818
|
+
readme_file = p_dir / "README.md"
|
|
819
|
+
if readme_file.exists():
|
|
820
|
+
r_text = read_text(readme_file)
|
|
821
|
+
r_text = re.sub(r"-\s*(?:当前状态:|Status:\s*)[^\n]+", f"- 当前状态:{status}", r_text)
|
|
822
|
+
write_text(readme_file, r_text)
|
|
823
|
+
print(f"已更新 {p_dir.name}/README.md 中的当前状态。")
|
|
824
|
+
|
|
825
|
+
if GLOBAL_BOARD.exists() and num_str:
|
|
826
|
+
b_text = read_text(GLOBAL_BOARD)
|
|
827
|
+
row_pat = rf"(\|\s*{num_str}\s*\|\s*{re.escape(p_dir.name)}\s*\|)([^|]+)(\|)([^|]+)(\|)"
|
|
828
|
+
m_row = re.search(row_pat, b_text)
|
|
829
|
+
if m_row:
|
|
830
|
+
new_entry_col = f" {entry.strip()} " if entry else m_row.group(4)
|
|
831
|
+
repl = f"\\g<1> {status.strip()} \\g<3>{new_entry_col}\\g<5>"
|
|
832
|
+
b_text = re.sub(row_pat, repl, b_text)
|
|
833
|
+
write_text(GLOBAL_BOARD, b_text)
|
|
834
|
+
print(f"已同步更新 {GLOBAL_BOARD.name} 登记表状态。")
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def cmd_handoff_record(
|
|
838
|
+
proj_key: str,
|
|
839
|
+
agent: str,
|
|
840
|
+
status: str,
|
|
841
|
+
done: str,
|
|
842
|
+
evidence: str = "",
|
|
843
|
+
todo: str = "",
|
|
844
|
+
) -> None:
|
|
845
|
+
with WorkspaceLock():
|
|
846
|
+
p_dir = find_project_dir(proj_key)
|
|
847
|
+
if not p_dir:
|
|
848
|
+
print(f"错误: 找不到项目 '{proj_key}'", file=sys.stderr)
|
|
849
|
+
sys.exit(1)
|
|
850
|
+
|
|
851
|
+
now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
852
|
+
docs_dir = p_dir / "docs"
|
|
853
|
+
docs_dir.mkdir(exist_ok=True)
|
|
854
|
+
handoff_file = docs_dir / "当前状态与交接.md"
|
|
855
|
+
|
|
856
|
+
done_lines = "\n".join(f"- {line.strip()}" for line in done.splitlines() if line.strip())
|
|
857
|
+
todo_lines = "\n".join(f"- {line.strip()}" for line in todo.splitlines() if line.strip()) if todo else "- 待定"
|
|
858
|
+
evidence_section = ""
|
|
859
|
+
if evidence:
|
|
860
|
+
evidence_lines = "\n".join(f"- {line.strip()}" for line in evidence.splitlines() if line.strip())
|
|
861
|
+
evidence_section = f"\n### 证据\n{evidence_lines}\n"
|
|
862
|
+
|
|
863
|
+
turn_block = f"""
|
|
864
|
+
## {agent} 交接({now_str})
|
|
865
|
+
|
|
866
|
+
- 当前状态:{status}
|
|
867
|
+
|
|
868
|
+
### 已完成
|
|
869
|
+
{done_lines}
|
|
870
|
+
{evidence_section}
|
|
871
|
+
### 未完成与下一步
|
|
872
|
+
{todo_lines}
|
|
873
|
+
"""
|
|
874
|
+
|
|
875
|
+
if handoff_file.exists():
|
|
876
|
+
old_text = read_text(handoff_file)
|
|
877
|
+
write_text(handoff_file, old_text.rstrip() + "\n\n" + turn_block.strip() + "\n")
|
|
878
|
+
else:
|
|
879
|
+
header = f"# 当前状态与交接\n\n- 项目:{p_dir.name}\n"
|
|
880
|
+
write_text(handoff_file, header + turn_block.strip() + "\n")
|
|
881
|
+
|
|
882
|
+
print(f"已向 {handoff_file} 写入交接记忆记录。")
|
|
883
|
+
cmd_project_update(proj_key, f"{now_str.split()[0]} {status}")
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
# -------------------------------------------------------------
|
|
887
|
+
# Status, Guard and Git Operations
|
|
888
|
+
# -------------------------------------------------------------
|
|
889
|
+
def cmd_guard() -> None:
|
|
890
|
+
is_repo, dirty_lines, err = get_dirty_files()
|
|
891
|
+
if not is_repo:
|
|
892
|
+
print(f"[GUARD ERROR] 当前目录不是有效的 Git 仓库:{err}", file=sys.stderr)
|
|
893
|
+
sys.exit(2)
|
|
894
|
+
|
|
895
|
+
if dirty_lines:
|
|
896
|
+
print(f"[GUARD WARNING] 检测到 {len(dirty_lines)} 项未提交的工作区变更!")
|
|
897
|
+
for line in dirty_lines:
|
|
898
|
+
print(f" {line}")
|
|
899
|
+
print('建议立即固化版本:python workspace_tool.py commit -m "<变更说明>"')
|
|
900
|
+
sys.exit(1)
|
|
901
|
+
|
|
902
|
+
print("[GUARD OK] 工作树干净,无未提交改动。")
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def cmd_status(guard: bool = False) -> None:
|
|
906
|
+
print(f"=== Workspace 当前全局状态概览 ({WORKSPACE_ROOT}) ===")
|
|
907
|
+
if GLOBAL_BOARD.exists():
|
|
908
|
+
content = read_text(GLOBAL_BOARD)
|
|
909
|
+
print("\n【进行中 / 重点项目】:")
|
|
910
|
+
for line in content.splitlines():
|
|
911
|
+
if re.match(r"^\|\s*\d{3}\s*\|", line) and (
|
|
912
|
+
"进行中" in line or "待" in line or "验证" in line or "in progress" in line.lower()
|
|
913
|
+
):
|
|
914
|
+
print(line)
|
|
915
|
+
|
|
916
|
+
print("\n【Git 变更状态】:")
|
|
917
|
+
is_repo, dirty_lines, err = get_dirty_files()
|
|
918
|
+
if not is_repo:
|
|
919
|
+
print(f"未检测到 Git 仓库:{err}")
|
|
920
|
+
if guard:
|
|
921
|
+
sys.exit(2)
|
|
922
|
+
return
|
|
923
|
+
|
|
924
|
+
if dirty_lines:
|
|
925
|
+
print("\n".join(dirty_lines))
|
|
926
|
+
if guard:
|
|
927
|
+
print(f"\n[GUARD WARNING] 检测到 {len(dirty_lines)} 项未提交变更,退出前请执行 commit。")
|
|
928
|
+
sys.exit(1)
|
|
929
|
+
else:
|
|
930
|
+
print("工作树干净,无未提交改动。")
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
def cmd_commit(msg: str) -> None:
|
|
934
|
+
if not msg:
|
|
935
|
+
print("错误: 必须提供 commit 信息 (-m)", file=sys.stderr)
|
|
936
|
+
sys.exit(1)
|
|
937
|
+
|
|
938
|
+
with WorkspaceLock():
|
|
939
|
+
print(f"=== 提交 Workspace 变更: '{msg}' ===")
|
|
940
|
+
add_res = run_git(["add", "-A"])
|
|
941
|
+
if add_res.returncode != 0:
|
|
942
|
+
print(f"git add 失败: {add_res.stderr}", file=sys.stderr)
|
|
943
|
+
sys.exit(1)
|
|
944
|
+
|
|
945
|
+
# Ensure the transient lock file is never staged even if .gitignore lacks it.
|
|
946
|
+
run_git(["reset", "-q", "--", LOCK_FILENAME])
|
|
947
|
+
|
|
948
|
+
diff_res = run_git(["diff", "--cached", "--quiet"])
|
|
949
|
+
if diff_res.returncode == 0:
|
|
950
|
+
print("无需提交:无文件变更。")
|
|
951
|
+
return
|
|
952
|
+
|
|
953
|
+
commit_res = run_git(["commit", "-m", msg])
|
|
954
|
+
if commit_res.returncode != 0:
|
|
955
|
+
err_msg = commit_res.stderr.strip() or commit_res.stdout.strip()
|
|
956
|
+
print(f"git commit 失败: {err_msg}", file=sys.stderr)
|
|
957
|
+
sys.exit(1)
|
|
958
|
+
|
|
959
|
+
print(commit_res.stdout.strip())
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
# -------------------------------------------------------------
|
|
963
|
+
# Main CLI Router
|
|
964
|
+
# -------------------------------------------------------------
|
|
965
|
+
def main() -> None:
|
|
966
|
+
parser = argparse.ArgumentParser(description="Multi-Agent Workspace Hub CLI")
|
|
967
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
968
|
+
|
|
969
|
+
# --- init ---
|
|
970
|
+
init_p = subparsers.add_parser("init", help="初始化共享工作空间骨架文档与配置")
|
|
971
|
+
init_p.add_argument("--lang", choices=["zh", "en"], default="zh", help="骨架文档语言(默认 zh)")
|
|
972
|
+
init_p.add_argument("--no-git", action="store_true", help="跳过 git init")
|
|
973
|
+
|
|
974
|
+
# --- exp ---
|
|
975
|
+
exp_parser = subparsers.add_parser("exp", help="查询、沉淀与修订踩坑经验")
|
|
976
|
+
exp_sub = exp_parser.add_subparsers(dest="exp_command")
|
|
977
|
+
|
|
978
|
+
# exp search
|
|
979
|
+
exp_search_p = exp_sub.add_parser("search", help="按关键词和/或标签搜索经验索引")
|
|
980
|
+
exp_search_p.add_argument("query", nargs="?", default="", help="关键词(可选,与 --tag 组合或单独使用)")
|
|
981
|
+
exp_search_p.add_argument("--tag", action="append", default=None, help="按标签筛选(支持逗号分隔或多次传参)")
|
|
982
|
+
exp_search_p.add_argument("--list-tags", action="store_true", help="列出所有已登记标签及频次")
|
|
983
|
+
|
|
984
|
+
# exp get
|
|
985
|
+
exp_get_p = exp_sub.add_parser("get", help="查看指定 EXP 条目详情")
|
|
986
|
+
exp_get_p.add_argument("exp_id", help="经验编号,如 EXP-146")
|
|
987
|
+
|
|
988
|
+
# exp add
|
|
989
|
+
exp_add_p = exp_sub.add_parser("add", help="沉淀新增经验条目")
|
|
990
|
+
exp_add_p.add_argument("--title", required=True, help="一句话标题/结论")
|
|
991
|
+
exp_add_p.add_argument("--type", default="踩坑+复用方法", help="类型,默认'踩坑+复用方法'")
|
|
992
|
+
exp_add_p.add_argument("--tag", action="append", default=None, help="分类标签(如 --tag docker,linux)")
|
|
993
|
+
exp_add_p.add_argument("--phenomenon", default="", help="触发条件与现象")
|
|
994
|
+
exp_add_p.add_argument("--cause", default="", help="定位与根本原因")
|
|
995
|
+
exp_add_p.add_argument("--solution", default="", help="解决步骤与处理")
|
|
996
|
+
exp_add_p.add_argument("--criteria", default="", help="判据与验证结论")
|
|
997
|
+
exp_add_p.add_argument("--sink", default=None, help="下沉目标项目编号/目录(若提供则落盘到该项目docs)")
|
|
998
|
+
exp_add_p.add_argument("--agent", default="Agent", help="记录主体 Agent")
|
|
999
|
+
|
|
1000
|
+
# exp update
|
|
1001
|
+
exp_up_p = exp_sub.add_parser("update", help="为已有经验追加补充更新")
|
|
1002
|
+
exp_up_p.add_argument("exp_id", help="经验编号,如 EXP-146")
|
|
1003
|
+
exp_up_p.add_argument("--note", required=True, help="补充内容或验证结论")
|
|
1004
|
+
exp_up_p.add_argument("--agent", default="Agent", help="记录主体 Agent")
|
|
1005
|
+
|
|
1006
|
+
# --- project ---
|
|
1007
|
+
proj_parser = subparsers.add_parser("project", help="项目管理与 SOP 建项")
|
|
1008
|
+
proj_sub = proj_parser.add_subparsers(dest="proj_command")
|
|
1009
|
+
proj_sub.add_parser("list", help="列出所有项目")
|
|
1010
|
+
|
|
1011
|
+
proj_new_p = proj_sub.add_parser("new", help="按 SOP 规范创建新项目")
|
|
1012
|
+
proj_new_p.add_argument("name", help="项目简短名称")
|
|
1013
|
+
proj_new_p.add_argument("--owner", default="Agent", help="负责人或执行主体")
|
|
1014
|
+
|
|
1015
|
+
proj_up_p = proj_sub.add_parser("update", help="更新项目状态与接续入口")
|
|
1016
|
+
proj_up_p.add_argument("project", help="项目编号或名称")
|
|
1017
|
+
proj_up_p.add_argument("--status", required=True, help="最新状态说明")
|
|
1018
|
+
proj_up_p.add_argument("--entry", default=None, help="接续入口路径")
|
|
1019
|
+
|
|
1020
|
+
# --- handoff ---
|
|
1021
|
+
handoff_parser = subparsers.add_parser("handoff", help="多 Agent 交接记录管理")
|
|
1022
|
+
handoff_parser.add_argument("project", help="项目编号或名称")
|
|
1023
|
+
handoff_parser.add_argument("--agent", required=True, help="执行主体 Agent 名字")
|
|
1024
|
+
handoff_parser.add_argument("--status", required=True, help="最新状态")
|
|
1025
|
+
handoff_parser.add_argument("--done", required=True, help="已完成工作清单")
|
|
1026
|
+
handoff_parser.add_argument("--evidence", default="", help="关键证据路径或核验证明")
|
|
1027
|
+
handoff_parser.add_argument("--todo", default="", help="未完成与下一步计划")
|
|
1028
|
+
|
|
1029
|
+
# --- status, guard & commit ---
|
|
1030
|
+
status_p = subparsers.add_parser("status", help="查看活跃项目与工作区状态")
|
|
1031
|
+
status_p.add_argument("--guard", action="store_true", help="若有未提交改动则打印警告并返回退出码 1")
|
|
1032
|
+
subparsers.add_parser("guard", help="巡检工作树是否干净(有未提交改动则返回退出码 1)")
|
|
1033
|
+
commit_p = subparsers.add_parser("commit", help="提交工作区全局文档与项目变更到本地 Git")
|
|
1034
|
+
commit_p.add_argument("-m", "--message", required=True, help="提交日志")
|
|
1035
|
+
|
|
1036
|
+
args = parser.parse_args()
|
|
1037
|
+
|
|
1038
|
+
try:
|
|
1039
|
+
if args.command == "init":
|
|
1040
|
+
cmd_init(lang=args.lang, no_git=args.no_git)
|
|
1041
|
+
elif args.command == "exp":
|
|
1042
|
+
if args.exp_command == "search":
|
|
1043
|
+
cmd_exp_search(args.query, raw_tags=args.tag, list_tags=args.list_tags)
|
|
1044
|
+
elif args.exp_command == "get":
|
|
1045
|
+
cmd_exp_get(args.exp_id)
|
|
1046
|
+
elif args.exp_command == "add":
|
|
1047
|
+
cmd_exp_add(
|
|
1048
|
+
title=args.title,
|
|
1049
|
+
exp_type=args.type,
|
|
1050
|
+
phenomenon=args.phenomenon,
|
|
1051
|
+
cause=args.cause,
|
|
1052
|
+
solution=args.solution,
|
|
1053
|
+
criteria=args.criteria,
|
|
1054
|
+
sink_proj=args.sink,
|
|
1055
|
+
agent=args.agent,
|
|
1056
|
+
raw_tags=args.tag,
|
|
1057
|
+
)
|
|
1058
|
+
elif args.exp_command == "update":
|
|
1059
|
+
cmd_exp_update(args.exp_id, args.note, args.agent)
|
|
1060
|
+
else:
|
|
1061
|
+
exp_parser.print_help()
|
|
1062
|
+
elif args.command == "project":
|
|
1063
|
+
if args.proj_command == "list":
|
|
1064
|
+
cmd_project_list()
|
|
1065
|
+
elif args.proj_command == "new":
|
|
1066
|
+
cmd_project_new(args.name, args.owner)
|
|
1067
|
+
elif args.proj_command == "update":
|
|
1068
|
+
cmd_project_update(args.project, args.status, args.entry)
|
|
1069
|
+
else:
|
|
1070
|
+
proj_parser.print_help()
|
|
1071
|
+
elif args.command == "handoff":
|
|
1072
|
+
cmd_handoff_record(
|
|
1073
|
+
proj_key=args.project,
|
|
1074
|
+
agent=args.agent,
|
|
1075
|
+
status=args.status,
|
|
1076
|
+
done=args.done,
|
|
1077
|
+
evidence=args.evidence,
|
|
1078
|
+
todo=args.todo,
|
|
1079
|
+
)
|
|
1080
|
+
elif args.command == "status":
|
|
1081
|
+
cmd_status(guard=args.guard)
|
|
1082
|
+
elif args.command == "guard":
|
|
1083
|
+
cmd_guard()
|
|
1084
|
+
elif args.command == "commit":
|
|
1085
|
+
cmd_commit(args.message)
|
|
1086
|
+
else:
|
|
1087
|
+
parser.print_help()
|
|
1088
|
+
except TimeoutError as exc:
|
|
1089
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
1090
|
+
sys.exit(1)
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
if __name__ == "__main__":
|
|
1094
|
+
main()
|