295 lines
9.1 KiB
Python
295 lines
9.1 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
NAC Memory System - Add Tool
|
|
添加新的记录到记忆系统
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
from typing import Dict, Any
|
|
|
|
# 记忆系统根目录
|
|
MEMORY_ROOT = Path(__file__).parent.parent
|
|
|
|
def load_json(file_path: Path) -> Dict[str, Any]:
|
|
"""加载JSON文件"""
|
|
with open(file_path, 'r', encoding='utf-8') as f:
|
|
return json.load(f)
|
|
|
|
def save_json(file_path: Path, data: Dict[str, Any]):
|
|
"""保存JSON文件"""
|
|
with open(file_path, 'w', encoding='utf-8') as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
|
|
|
def get_next_id(index_file: Path, id_prefix: str) -> str:
|
|
"""获取下一个ID"""
|
|
if not index_file.exists():
|
|
return f"{id_prefix}001"
|
|
|
|
index = load_json(index_file)
|
|
items = []
|
|
|
|
if "documents" in index:
|
|
items = index["documents"]
|
|
elif "problems" in index:
|
|
items = index["problems"]
|
|
elif "decisions" in index:
|
|
items = index["decisions"]
|
|
|
|
if not items:
|
|
return f"{id_prefix}001"
|
|
|
|
# 提取最大编号
|
|
max_num = 0
|
|
for item in items:
|
|
for key in ["doc_id", "problem_id", "decision_id"]:
|
|
if key in item:
|
|
id_str = item[key]
|
|
if id_str.startswith(id_prefix):
|
|
try:
|
|
num = int(id_str[len(id_prefix):])
|
|
max_num = max(max_num, num)
|
|
except ValueError:
|
|
pass
|
|
|
|
return f"{id_prefix}{max_num + 1:03d}"
|
|
|
|
def add_document(title: str, path: str, summary: str, concepts: str = None):
|
|
"""添加文档记录"""
|
|
doc_id = get_next_id(MEMORY_ROOT / "documents" / "index.json", "DOC_")
|
|
today = datetime.now().strftime("%Y-%m-%d")
|
|
|
|
# 解析核心概念
|
|
core_concepts = []
|
|
if concepts:
|
|
for concept in concepts.split(','):
|
|
concept = concept.strip()
|
|
if concept:
|
|
core_concepts.append({
|
|
"concept": concept,
|
|
"definition": "待补充",
|
|
"importance": "medium"
|
|
})
|
|
|
|
# 创建文档记录
|
|
doc = {
|
|
"doc_id": doc_id,
|
|
"title": title,
|
|
"path": path,
|
|
"read_date": today,
|
|
"document_type": "general",
|
|
"importance": "medium",
|
|
"summary": summary,
|
|
"core_concepts": core_concepts,
|
|
"key_features": [],
|
|
"related_docs": [],
|
|
"tags": []
|
|
}
|
|
|
|
# 保存文档
|
|
doc_file = MEMORY_ROOT / "documents" / f"{doc_id}.json"
|
|
save_json(doc_file, doc)
|
|
|
|
# 更新索引
|
|
index_file = MEMORY_ROOT / "documents" / "index.json"
|
|
if index_file.exists():
|
|
index = load_json(index_file)
|
|
else:
|
|
index = {
|
|
"index_type": "documents",
|
|
"last_updated": today,
|
|
"total_count": 0,
|
|
"documents": []
|
|
}
|
|
|
|
index["documents"].append({
|
|
"doc_id": doc_id,
|
|
"title": title,
|
|
"importance": "medium",
|
|
"read_date": today,
|
|
"tags": [],
|
|
"file": f"{doc_id}.json"
|
|
})
|
|
index["total_count"] = len(index["documents"])
|
|
index["last_updated"] = today
|
|
|
|
save_json(index_file, index)
|
|
|
|
print(f"✅ 文档记录已添加: {doc_id}")
|
|
print(f" 文件: {doc_file}")
|
|
print(f" 请手动编辑文件补充详细信息")
|
|
|
|
def add_problem(title: str, description: str, solution: str = None):
|
|
"""添加问题记录"""
|
|
problem_id = get_next_id(MEMORY_ROOT / "problems" / "index.json", "P")
|
|
today = datetime.now().strftime("%Y-%m-%d")
|
|
|
|
# 创建问题记录
|
|
problem = {
|
|
"problem_id": problem_id,
|
|
"date": today,
|
|
"title": title,
|
|
"category": "general",
|
|
"severity": "medium",
|
|
"status": "open" if not solution else "resolved",
|
|
"description": description,
|
|
"root_cause": {
|
|
"primary": "待分析",
|
|
"secondary": "待分析"
|
|
},
|
|
"solution": solution or "待解决",
|
|
"code_changes": [],
|
|
"prevention": {
|
|
"rules": [],
|
|
"checklist": []
|
|
},
|
|
"related_docs": [],
|
|
"related_principles": [],
|
|
"lessons_learned": []
|
|
}
|
|
|
|
# 保存问题
|
|
problem_file = MEMORY_ROOT / "problems" / f"{problem_id}_{title.replace(' ', '_')[:30]}.json"
|
|
save_json(problem_file, problem)
|
|
|
|
# 更新索引
|
|
index_file = MEMORY_ROOT / "problems" / "index.json"
|
|
if index_file.exists():
|
|
index = load_json(index_file)
|
|
else:
|
|
index = {
|
|
"index_type": "problems",
|
|
"last_updated": today,
|
|
"total_count": 0,
|
|
"problems": []
|
|
}
|
|
|
|
index["problems"].append({
|
|
"problem_id": problem_id,
|
|
"title": title,
|
|
"category": "general",
|
|
"severity": "medium",
|
|
"status": problem["status"],
|
|
"date": today,
|
|
"file": problem_file.name
|
|
})
|
|
index["total_count"] = len(index["problems"])
|
|
index["last_updated"] = today
|
|
|
|
save_json(index_file, index)
|
|
|
|
print(f"✅ 问题记录已添加: {problem_id}")
|
|
print(f" 文件: {problem_file}")
|
|
print(f" 请手动编辑文件补充详细信息")
|
|
|
|
def add_decision(title: str, decision: str, rationale: str = None):
|
|
"""添加决策记录"""
|
|
decision_id = get_next_id(MEMORY_ROOT / "decisions" / "index.json", "D")
|
|
today = datetime.now().strftime("%Y-%m-%d")
|
|
|
|
# 创建决策记录
|
|
dec = {
|
|
"decision_id": decision_id,
|
|
"date": today,
|
|
"title": title,
|
|
"category": "general",
|
|
"status": "proposed",
|
|
"context": {
|
|
"problem": "待补充",
|
|
"impact": "待补充"
|
|
},
|
|
"decision": {
|
|
"statement": decision,
|
|
"rules": []
|
|
},
|
|
"rationale": [rationale] if rationale else ["待补充"],
|
|
"alternatives": [],
|
|
"impact": {
|
|
"scope": "待评估",
|
|
"files_affected": [],
|
|
"breaking_change": False
|
|
},
|
|
"related_files": [],
|
|
"related_principles": [],
|
|
"lessons_learned": []
|
|
}
|
|
|
|
# 保存决策
|
|
decision_file = MEMORY_ROOT / "decisions" / f"{decision_id}_{title.replace(' ', '_')[:30]}.json"
|
|
save_json(decision_file, dec)
|
|
|
|
# 更新索引
|
|
index_file = MEMORY_ROOT / "decisions" / "index.json"
|
|
if index_file.exists():
|
|
index = load_json(index_file)
|
|
else:
|
|
index = {
|
|
"index_type": "decisions",
|
|
"last_updated": today,
|
|
"total_count": 0,
|
|
"decisions": []
|
|
}
|
|
|
|
index["decisions"].append({
|
|
"decision_id": decision_id,
|
|
"title": title,
|
|
"category": "general",
|
|
"status": "proposed",
|
|
"date": today,
|
|
"file": decision_file.name
|
|
})
|
|
index["total_count"] = len(index["decisions"])
|
|
index["last_updated"] = today
|
|
|
|
save_json(index_file, index)
|
|
|
|
print(f"✅ 决策记录已添加: {decision_id}")
|
|
print(f" 文件: {decision_file}")
|
|
print(f" 请手动编辑文件补充详细信息")
|
|
|
|
def main():
|
|
"""主函数"""
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description='NAC Memory System - Add Tool')
|
|
subparsers = parser.add_subparsers(dest='type', help='记录类型')
|
|
|
|
# 添加文档
|
|
doc_parser = subparsers.add_parser('document', help='添加文档记录')
|
|
doc_parser.add_argument('--title', required=True, help='文档标题')
|
|
doc_parser.add_argument('--path', required=True, help='文档路径')
|
|
doc_parser.add_argument('--summary', required=True, help='文档摘要')
|
|
doc_parser.add_argument('--concepts', help='核心概念(逗号分隔)')
|
|
|
|
# 添加问题
|
|
prob_parser = subparsers.add_parser('problem', help='添加问题记录')
|
|
prob_parser.add_argument('--title', required=True, help='问题标题')
|
|
prob_parser.add_argument('--description', required=True, help='问题描述')
|
|
prob_parser.add_argument('--solution', help='解决方案')
|
|
|
|
# 添加决策
|
|
dec_parser = subparsers.add_parser('decision', help='添加决策记录')
|
|
dec_parser.add_argument('--title', required=True, help='决策标题')
|
|
dec_parser.add_argument('--decision', required=True, help='决策内容')
|
|
dec_parser.add_argument('--rationale', help='决策理由')
|
|
|
|
args = parser.parse_args()
|
|
|
|
if args.type == 'document':
|
|
add_document(args.title, args.path, args.summary, args.concepts)
|
|
elif args.type == 'problem':
|
|
add_problem(args.title, args.description, args.solution)
|
|
elif args.type == 'decision':
|
|
add_decision(args.title, args.decision, args.rationale)
|
|
else:
|
|
parser.print_help()
|
|
print("\n示例:")
|
|
print(' python add.py document --title "文档标题" --path "/path/to/doc" --summary "摘要" --concepts "概念1,概念2"')
|
|
print(' python add.py problem --title "问题标题" --description "问题描述" --solution "解决方案"')
|
|
print(' python add.py decision --title "决策标题" --decision "决策内容" --rationale "理由"')
|
|
|
|
if __name__ == "__main__":
|
|
main()
|