Skip to content

Commit 4fd710b

Browse files
committed
feat: centralized 布局 MCP 全量扫缺陷修复(7 项)
- init_wiki 按设计方案 §6 路由集中式业务仓进工作区 corpus (默认 output_dir 路由 + modules 分区幂等确保 + schema 不覆盖 + 不注入业务仓 AGENTS.md;显式 output_dir 不劫持)——替代原先的直接拒绝 - get_module_tree 解析 <ws>/.codewiki/<repo>/ 命名空间树,回退 corpus .meta - ingest_note 集中 corpus 下无来源仓时显式 provenance_warning(防静默全局化) - 共享池 provenance 落 metadata: 节点(OKF v0.2 §4/§5,顶层 repo: 会触发 okf_conformance),merge_provenance 迁移存量顶层标并清理空节点 - evidence_roots 多根解析:stamp 记录 repo 字段,lint 按 repo 字段路由 验证(无字段的旧条目按 hash 多根回退),成员仓 + 状态 quo 根兜底 - resolve_session 支持 store=None 降级(无会话直调/测试/CLI) - run_git_bounded 硬墙钟超时 + 进程树击杀(名义 15s 实测挂 204s); ok_only=False 保留 rc/stderr,session_ff_only 分叉告警分支复活(D12)
1 parent 93d693e commit 4fd710b

12 files changed

Lines changed: 968 additions & 107 deletions

‎codewiki/mcp/tools/evidence.py‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,60 @@
2222
_SOURCES_KEY_RE = re.compile(r"(?m)^sources\s*:")
2323

2424

25+
def evidence_roots(output_dir: Path, repo_name: Optional[str] = None) -> List[Path]:
26+
"""Candidate roots for resolving ``repo://`` evidence, best guess first.
27+
28+
Colocated / single-repo workspaces keep the status quo: the code lives at
29+
``output_dir.parent`` (``<repo>/repowiki`` → ``<repo>``).
30+
31+
Centralized workspaces break that assumption: the corpus is
32+
``<ws>/repowiki`` while the code lives in ``<ws>/<repo>/``, so
33+
``output_dir.parent`` is the workspace root and every repo-relative
34+
evidence path looks "disappeared". Resolution order:
35+
36+
1. the entry's own ``repo`` field (recorded by :func:`handle_stamp_evidence`);
37+
2. every business repo registered in the workspace;
38+
3. ``output_dir.parent`` (status quo, also covers colocated).
39+
"""
40+
od = Path(output_dir).resolve()
41+
fallback = od.parent
42+
roots: List[Path] = []
43+
44+
def _add(candidate: Path) -> None:
45+
try:
46+
rp = candidate.resolve()
47+
except OSError:
48+
return
49+
if rp.is_dir() and rp not in roots:
50+
roots.append(rp)
51+
52+
if repo_name:
53+
_add(fallback / str(repo_name))
54+
55+
try:
56+
from codewiki.mcp.tools.workspace_layout import (
57+
LAYOUT_CENTRALIZED,
58+
find_workspace_root,
59+
is_centralized_corpus,
60+
read_layout,
61+
)
62+
63+
if is_centralized_corpus(od):
64+
root = find_workspace_root(od)
65+
if root is not None and read_layout(root) == LAYOUT_CENTRALIZED:
66+
from codewiki.mcp.tools.workspace_bootstrap import (
67+
read_registration_table_names,
68+
)
69+
70+
for name in read_registration_table_names(root):
71+
_add(root / name)
72+
except Exception as e: # pragma: no cover - layout lookups are advisory
73+
logger.debug("evidence root expansion skipped: %s", e)
74+
75+
_add(fallback)
76+
return roots
77+
78+
2579
def _resolve_targets(
2680
arguments: Dict[str, Any], store: SessionStore
2781
) -> Tuple[Optional[Path], Optional[Path]]:
@@ -214,6 +268,17 @@ def handle_stamp_evidence(arguments: Dict[str, Any], store: SessionStore) -> str
214268
return json.dumps({"error": f"page has no frontmatter: {page_arg!r}"}, ensure_ascii=False)
215269
frontmatter, body = parsed
216270

271+
# Centralized layout: record WHICH repo these repo:// paths are relative to.
272+
# Without it a shared corpus leaves the path ambiguous and stale_evidence
273+
# cannot resolve it (see evidence_roots).
274+
repo_name: Optional[str] = None
275+
try:
276+
from codewiki.mcp.tools.workspace_layout import routing_for_write
277+
278+
repo_name = routing_for_write(output_dir, repo_root)
279+
except Exception as e: # pragma: no cover - attribution is advisory
280+
logger.debug("evidence repo attribution skipped: %s", e)
281+
217282
entries: List[Dict[str, Any]] = []
218283
skipped: List[Dict[str, str]] = []
219284
for item in evidence:
@@ -233,7 +298,7 @@ def handle_stamp_evidence(arguments: Dict[str, Any], store: SessionStore) -> str
233298
if content_hash is None:
234299
skipped.append({"resource": resource, "reason": f"file not found under {repo_root}"})
235300
continue
236-
entries.append(make_entry(rel, start, end, content_hash))
301+
entries.append(make_entry(rel, start, end, content_hash, repo_name))
237302

238303
if not entries:
239304
return json.dumps(

‎codewiki/mcp/tools/init_wiki.py‎

Lines changed: 124 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44
template (preserving comments), and injects wiki usage instructions into
55
the project's AGENTS.md. This is a zero-config bootstrap: run it once
66
before starting any wiki generation or knowledge ingestion workflow.
7+
8+
Under a centralized workspace layout (design doc §6), a business repo's
9+
knowledge lives in the workspace corpus: the default output_dir routes to
10+
the workspace ``repowiki/``, ``wiki/modules/<repo>/`` is ensured, the
11+
workspace's customized ``schema.yaml`` is never clobbered, and no AGENTS.md
12+
block is injected into the business repo (``add_workspace_repo`` removed it
13+
on purpose). Explicit ``output_dir`` arguments are never hijacked.
714
"""
815

916
from __future__ import annotations
@@ -148,9 +155,35 @@ def handle_init_wiki(arguments: dict) -> str:
148155
ensure_ascii=False,
149156
)
150157

151-
# Resolve output_dir
158+
# ── Step 0: centralized-layout routing (design doc §6) ─────────────
159+
# A business repo registered in a centralized workspace is pure code:
160+
# its knowledge lives in the workspace corpus (modules →
161+
# wiki/modules/<repo>/, shared-pool dirs → workspace repowiki/).
162+
# Running init_wiki here must therefore route the default output_dir
163+
# to the corpus instead of scaffolding <repo>/repowiki/ (which
164+
# lint_wiki's layout_violations check would flag) or re-injecting the
165+
# AGENTS.md wiki block that add_workspace_repo just removed.
166+
# The routing must never break init: any resolution failure falls
167+
# back to the status-quo path.
168+
_centralized = False
169+
try:
170+
from codewiki.mcp.tools.workspace_layout import resolve_workspace
171+
172+
_resolution = resolve_workspace(repo_path_p)
173+
_centralized = _resolution.centralized
174+
except Exception as e: # pragma: no cover - routing must never break init
175+
logger.warning("centralized-layout routing skipped: %s", e)
176+
177+
# Resolve output_dir — the default routes to the workspace corpus under
178+
# centralized; an explicit output_dir is the caller's directory-level
179+
# choice and is never hijacked (same semantics as routing_for_write).
152180
if not output_dir:
153-
output_dir_p = repo_path_p / "repowiki"
181+
if _centralized:
182+
from codewiki.mcp.tools.workspace_layout import default_output_dir
183+
184+
output_dir_p = default_output_dir(repo_path_p)
185+
else:
186+
output_dir_p = repo_path_p / "repowiki"
154187
elif os.path.isabs(output_dir):
155188
output_dir_p = Path(output_dir).resolve()
156189
else:
@@ -168,62 +201,108 @@ def handle_init_wiki(arguments: dict) -> str:
168201
}
169202

170203
# ── Steps 1-2: Create directory structure and copy template assets ──
171-
tree = initialize_wiki_tree(repo_path_p, output_dir_p, overwrite_schema=True)
204+
# Under centralized the corpus already carries the workspace's customized
205+
# schema.yaml — a business-repo re-run must not clobber it (same rule as
206+
# workspace re-runs, see initialize_wiki_tree).
207+
tree = initialize_wiki_tree(repo_path_p, output_dir_p, overwrite_schema=not _centralized)
172208
results["created_dirs"] = tree["created_dirs"]
173209
results["schema_yaml"] = tree["schema_yaml"]
174210
results["ontology_yaml"] = tree["ontology_yaml"]
175211
results["review_checklist_yaml"] = tree["review_checklist_yaml"]
176212

213+
# ── Step 1.5: ensure the repo's modules partition (centralized, §6) ─
214+
# modules → wiki/modules/<repo>/. add_workspace_repo scaffolds this at
215+
# registration; ensuring it here keeps init_wiki idempotent for members
216+
# registered through other paths.
217+
if _centralized:
218+
try:
219+
from codewiki.mcp.tools.workspace_layout import routing_for_write
220+
221+
partition = routing_for_write(output_dir_p, repo_path_p)
222+
if partition:
223+
partition_dir = output_dir_p / "wiki" / "modules" / partition
224+
if not partition_dir.exists():
225+
partition_dir.mkdir(parents=True, exist_ok=True)
226+
results["created_dirs"].append(str(partition_dir))
227+
except Exception as e: # best-effort: analyze_repo re-creates it anyway
228+
logger.warning("modules partition ensure skipped: %s", e)
229+
177230
# ── Step 2.5: Team-layout gitignore hygiene (Phase 1, D1) ──────────
178231
# Rebuildable derived files (wiki/index.md, .meta/*.json indexes,
179232
# tasks/.index.json, ...) must stay untracked; init appends the ignore
180233
# block idempotently so a fresh project starts on the team layout.
181234
# Best-effort: never blocks init when the repo is not a git repo or
182-
# .gitignore is not writable.
183-
try:
184-
from codewiki.mcp.tools.team_layout import (
185-
ensure_gitignore_entries,
186-
find_repo_root,
187-
)
188-
189-
repo_root = find_repo_root(repo_path_p)
190-
if repo_root is not None:
191-
changed, added = ensure_gitignore_entries(repo_root, output_dir_p)
192-
results["gitignore"] = {
193-
"repo_root": str(repo_root),
194-
"entries_added": added,
195-
"status": "updated" if changed else "already-present",
196-
}
197-
else:
198-
results["gitignore"] = "skipped: not a git repository"
199-
except Exception as e:
200-
results["gitignore"] = f"WARNING: failed to update .gitignore: {e}"
201-
logger.warning("Failed to update .gitignore for team layout: %s", e)
235+
# .gitignore is not writable. Skipped under centralized routing: the
236+
# corpus belongs to the workspace repo, whose .gitignore is managed by
237+
# init_workspace — the business repo must not gain ignore entries for
238+
# paths outside itself.
239+
if _centralized:
240+
results["gitignore"] = "skipped: centralized routing (workspace corpus)"
241+
else:
242+
try:
243+
from codewiki.mcp.tools.team_layout import (
244+
ensure_gitignore_entries,
245+
find_repo_root,
246+
)
247+
248+
repo_root = find_repo_root(repo_path_p)
249+
if repo_root is not None:
250+
changed, added = ensure_gitignore_entries(repo_root, output_dir_p)
251+
results["gitignore"] = {
252+
"repo_root": str(repo_root),
253+
"entries_added": added,
254+
"status": "updated" if changed else "already-present",
255+
}
256+
else:
257+
results["gitignore"] = "skipped: not a git repository"
258+
except Exception as e:
259+
results["gitignore"] = f"WARNING: failed to update .gitignore: {e}"
260+
logger.warning("Failed to update .gitignore for team layout: %s", e)
202261

203262
# ── Step 3: Write AGENTS.md ─────────────────────────────────────────
204-
try:
205-
from codewiki.mcp.tools.agents_md import write_agents_md
206-
207-
write_agents_md(
208-
repo_path=str(repo_path_p),
209-
output_dir=str(output_dir_p),
210-
module_tree=None,
263+
# Under centralized, business-repo AGENTS.md stays clean: the CodeWiki
264+
# block was removed by add_workspace_repo (§7.2) and re-injecting it
265+
# would point at a repowiki/ that must not exist. The workspace root's
266+
# AGENTS.md (written by init_workspace) carries the routing guidance.
267+
if _centralized:
268+
results["agents_md"] = (
269+
"skipped: centralized business repo (workspace AGENTS.md governs routing)"
211270
)
212-
agents_path = repo_path_p / "AGENTS.md"
213-
results["agents_md"] = str(agents_path)
214-
logger.info("Wrote AGENTS.md at %s", agents_path)
215-
except Exception as e:
216-
results["agents_md"] = f"WARNING: failed to write AGENTS.md: {e}"
217-
logger.warning("Failed to write AGENTS.md: %s", e)
271+
else:
272+
try:
273+
from codewiki.mcp.tools.agents_md import write_agents_md
274+
275+
write_agents_md(
276+
repo_path=str(repo_path_p),
277+
output_dir=str(output_dir_p),
278+
module_tree=None,
279+
)
280+
agents_path = repo_path_p / "AGENTS.md"
281+
results["agents_md"] = str(agents_path)
282+
logger.info("Wrote AGENTS.md at %s", agents_path)
283+
except Exception as e:
284+
results["agents_md"] = f"WARNING: failed to write AGENTS.md: {e}"
285+
logger.warning("Failed to write AGENTS.md: %s", e)
218286

219287
results["status"] = "ok"
220-
results["next_steps"] = (
221-
"Wiki workspace initialized. Next: "
222-
"1) Edit schema.yaml to set 'purpose' and adjust conventions; "
223-
"2) Edit ontology.yaml to define project terms and aliases for search; "
224-
"3) Optionally edit review_checklist.yaml to add team review rules "
225-
"(merged into review_changes, same id overrides builtin); "
226-
"4) Run analyze_repo to parse code and generate docs; "
227-
"5) Or use ingest_note/query_wiki for knowledge management."
228-
)
288+
if _centralized:
289+
results["layout"] = "centralized"
290+
results["next_steps"] = (
291+
"Business repo initialized into the centralized workspace corpus "
292+
f"({output_dir_p}). The workspace's schema.yaml/ontology.yaml were "
293+
"left untouched; no AGENTS.md block was injected into the business "
294+
"repo. Next: run analyze_repo on this repo (modules route to "
295+
"wiki/modules/<repo>/), or use ingest_note/query_wiki with "
296+
"output_dir=<workspace repowiki> and repo=<name> filtering."
297+
)
298+
else:
299+
results["next_steps"] = (
300+
"Wiki workspace initialized. Next: "
301+
"1) Edit schema.yaml to set 'purpose' and adjust conventions; "
302+
"2) Edit ontology.yaml to define project terms and aliases for search; "
303+
"3) Optionally edit review_checklist.yaml to add team review rules "
304+
"(merged into review_changes, same id overrides builtin); "
305+
"4) Run analyze_repo to parse code and generate docs; "
306+
"5) Or use ingest_note/query_wiki for knowledge management."
307+
)
229308
return json.dumps(results, ensure_ascii=False, indent=2)

‎codewiki/mcp/tools/knowledge_loop.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,22 @@ def handle_ingest_note(
540540
except ValueError as e:
541541
return json.dumps({"error": f"invalid scope: {e}"}, ensure_ascii=False)
542542

543+
# Silent-global guard: inside a centralized corpus, a note written without
544+
# a resolvable writing repo is stored as product-line (global) knowledge.
545+
# routing_for_write() needs repo_path, so "pass only output_dir" silently
546+
# degrades to global — surface it here instead of leaving lint_wiki's
547+
# "no repo:/repos: provenance" info as the first signal.
548+
_prov_warning = None
549+
if _scope is None and _prov_repo is None:
550+
from codewiki.mcp.tools.workspace_layout import is_centralized_corpus
551+
552+
if is_centralized_corpus(output_dir):
553+
_prov_warning = (
554+
"No provenance stamped: repo_path is missing, so the writing repo cannot "
555+
"be determined — this note lands as product-line (global) knowledge. Pass "
556+
"repo_path (or scope=[<repo>]) to tag it with repo:."
557+
)
558+
543559
from codewiki.src.config import NOTES_DIR
544560

545561
notes_dir = output_dir / NOTES_DIR
@@ -727,6 +743,8 @@ def handle_ingest_note(
727743
"related_modules": related_modules,
728744
"tags": tags,
729745
}
746+
if _prov_warning:
747+
result["provenance_warning"] = _prov_warning
730748
# Team-layout Phase 4 first slice (D14): read-only remote-drift advisory,
731749
# once per process per repo — relayed into the conversation, never blocks.
732750
try:

‎codewiki/mcp/tools/legacy_tools.py‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,13 +184,25 @@ async def handle_get_module_tree(arguments: dict, store=None) -> str:
184184
raw_od = Path(arguments.get("output_dir", "repowiki")).expanduser()
185185
output_dir = raw_od.resolve() if raw_od.is_absolute() else (repo_path / raw_od).resolve()
186186

187-
from codewiki.src.config import meta_resolve
187+
from codewiki.src.config import MODULE_TREE_FILENAME, meta_resolve
188188

189-
module_tree_path = Path(meta_resolve(output_dir, "module_tree.json"))
189+
from codewiki.mcp.cache import resolve_analysis_meta_file
190+
191+
# Centralized workspaces keep per-repo analysis state (module_tree.json
192+
# included) in the namespaced <ws>/.codewiki/<repo>/ directory — NOT in
193+
# the shared corpus' .meta/. Resolve through the shared helper so both
194+
# layouts work and legacy per-output_dir locations keep loading.
195+
module_tree_path = Path(
196+
resolve_analysis_meta_file(str(repo_path), str(output_dir), MODULE_TREE_FILENAME)
197+
)
190198
if not module_tree_path.exists():
191199
return json.dumps(
192200
{
193-
"error": f"Module tree not found at {module_tree_path}. Run 'codewiki generate' first."
201+
"error": (
202+
f"Module tree not found at {module_tree_path} (also checked "
203+
f"{Path(meta_resolve(output_dir, MODULE_TREE_FILENAME))}). "
204+
"Call save_module_tree first (legacy 'codewiki generate' also works)."
205+
)
194206
}
195207
)
196208

‎codewiki/mcp/tools/team_layout.py‎

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
from __future__ import annotations
2222

2323
import logging
24-
import subprocess
2524
from pathlib import Path
2625
from typing import List, Optional, Tuple
2726

@@ -50,22 +49,20 @@ def find_repo_root(start: Path) -> Optional[Path]:
5049

5150

5251
def _run_git(repo_root: Path, args: List[str]) -> Optional[str]:
53-
"""Run a git subcommand in *repo_root*; return stdout or None on failure."""
52+
"""Run a git subcommand in *repo_root*; return stdout or None on failure.
53+
54+
Delegates to :func:`codewiki.src.git_sync.run_git_bounded` so ``timeout``
55+
is a hard wall-clock bound — ``subprocess.run(timeout=...)`` alone keeps
56+
waiting on pipes held by git's grandchildren (see that helper).
57+
"""
5458
try:
55-
proc = subprocess.run(
56-
["git", "-C", str(repo_root), *args],
57-
capture_output=True,
58-
text=True,
59-
encoding="utf-8",
60-
errors="replace",
61-
timeout=_GIT_TIMEOUT,
62-
)
63-
if proc.returncode == 0:
64-
return proc.stdout
65-
logger.debug("git %s failed (rc=%s): %s", args[0], proc.returncode, proc.stderr.strip())
66-
except Exception as e: # timeout, missing git, ...
67-
logger.debug("git %s raised: %s", args[0], e)
68-
return None
59+
from codewiki.src.git_sync import run_git_bounded
60+
61+
res = run_git_bounded(repo_root, args, timeout=_GIT_TIMEOUT)
62+
return res.stdout if res is not None else None
63+
except Exception as e: # import failure, missing git, ...
64+
logger.debug("git %s unavailable: %s", args[0], e)
65+
return None
6966

7067

7168
def list_tracked_rebuildables(repo_root: Path, output_dir: Path) -> List[str]:

0 commit comments

Comments
 (0)