Skip to content

Commit 29f2844

Browse files
authored
Merge pull request #321 from JiusiServe/fix/kb-depth-adjacent-docs-20261006
fix(kb): retrieve adjacent pinned guides during depth extraction
2 parents 5b714d7 + a8309ea commit 29f2844

5 files changed

Lines changed: 314 additions & 6 deletions

File tree

‎doc/architecture/SPEC/kb_service.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,12 @@ documented_manual;人工步骤须来自已有文档并标明本轮未执行。
642642
与验证类型,仍受两页和 6,000 字符预算约束。
643643

644644
共享的源码/测试/文档索引绑定 pin、政策、完整生产范围、版本与摘要;只建立一次。
645+
轻量深化还从该索引定位功能源码父目录中的实际项目文档,到最近组件指南为止,
646+
包括相邻的 SKILL、README、设计文档和 reference;有局部正文时先保留它们,否则
647+
使用通用 owner 文档,不扩展到其他组件的兄弟目录。各文档共享 8 KB 完整行段预算,
648+
优先实际入口文件名附近的行段及评审反馈,最终组包保留已选片段;没有既有操作和
649+
可观察预期的文档仍保持未知,补读不表示执行测试。strict 和未配置共享索引的旧输入不变。
650+
旧草稿和原生审批仍核对原始保存的输入,不重写上下文或重置累计修正次数。
645651
轻量组包保持完整小片段,修正优先补读评审指出的符号和范围。每个缺口至多首轮加三次
646652
自动修正,计数在派发前落盘,恢复或显式 retry 不清零;通过的维度冻结,失败只留在该项。
647653
未派发评审的草稿可在原轮恢复。逐批核对格式、引用、哈希与计数,完整验收集中在交付前。

‎plugins/infermatrix-copilot/skills/imkbinit/SKILL.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,15 @@ points, and separately measures paths-only ambiguity. Retrieval remains bounded
307307
to two documents and 6,000 content characters. Distinguish all `available_facets`
308308
from actually delivered `included_facets`, `not_injected_facets`, and their bases;
309309
read the remaining relevant facets through the existing bounded doc tools.
310+
Lightweight depth also reads existing indexed project documents in each source
311+
file's ancestor directories up to the nearest component guide, including
312+
adjacent SKILL, README, design and reference guides. Generic owner documents
313+
are the fallback when local text is unavailable. Documents share the existing
314+
8 KB budget, favor real source filename windows, and retain exact pinned ranges
315+
in the final packet. Documented manual operations
316+
and observable expected results may support an explicitly unexecuted manual
317+
validation entry; unrelated sibling components and invented tests cannot.
318+
Keep saved native inputs and cumulative correction counts unchanged on resume.
310319
`verified_gaps` describe absent evidence, not tests passed; missing facets remain
311320
unknown. Save reports outside `knowledge/` and report retrieval separately from
312321
breadth/depth and actual PR quality. This audit does not establish bug recall.

‎src/infermatrix_copilot/kb_service/depth_inputs.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,7 @@ def _indexed_test_association(self, feature, docs):
586586
return json.loads(json.dumps(result))
587587

588588
def document_slices(self, docs, *, paths=(), limit=8_000, previous_review=None, evidence_round=0,
589-
facets=(), symbols=()):
589+
facets=(), symbols=(), preferred_ranges=()):
590590
"""Select contiguous real lines from full indexed docs, then fallback input.
591591
592592
References in a rejection take priority over a document prefix. The
@@ -605,6 +605,7 @@ def document_slices(self, docs, *, paths=(), limit=8_000, previous_review=None,
605605
patterns = [re.compile(_FACET_PATTERNS[facet], re.I) for facet in facets if facet in _FACET_PATTERNS]
606606
references = [(match[1], int(match[2]), int(match[3] or match[2]))
607607
for match in re.finditer(r"([\w./-]+):L?(\d+)(?:[-:]L?(\d+))?", review)]
608+
references.extend(preferred_ranges) # indexed filename matches, not approval evidence
608609
ranges, lines_by_path = [], {}
609610
for path in names:
610611
if not safe_source_path(path):
@@ -638,6 +639,16 @@ def document_slices(self, docs, *, paths=(), limit=8_000, previous_review=None,
638639
rotated.extend(tied[shift:] + tied[:shift])
639640
ranges = rotated
640641
selected, used = {}, 0
642+
for path, start, end in preferred_ranges:
643+
lines = lines_by_path.get(path, {})
644+
if not all(number in lines for number in range(start, end + 1)):
645+
continue
646+
pending = {number: lines[number] for number in range(start, end + 1)
647+
if number not in selected.get(path, {})}
648+
size = sum(len(line.encode("utf-8")) + 1 for line in pending.values())
649+
if used + size <= limit:
650+
selected.setdefault(path, {}).update(pending)
651+
used += size
641652
for _, path, start, end in ranges:
642653
for number in range(start, end + 1):
643654
line = lines_by_path[path][number]

‎src/infermatrix_copilot/kb_service/init_knowledge_depth.py‎

Lines changed: 74 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import time
1010
from collections import Counter
1111
from dataclasses import dataclass, replace
12-
from pathlib import Path
12+
from pathlib import Path, PurePosixPath
1313

1414
from ..knowledge_service.lifecycle import Page
1515
from ..knowledge_service.ops import page_over_capacity
@@ -397,7 +397,65 @@ def _slot_result(entry, facet, status, reason):
397397
if visits[key] >= 3:
398398
slot["blocked"] = "three unsuccessful repairs with the same pinned evidence; needs new evidence or a corrected candidate"
399399

400-
def _docs(self, tree: Path, feature, owner) -> list[dict]:
400+
def _docs(self, tree: Path, feature, owner, *, context=None, facets=(),
401+
previous_review=None, evidence_round=0) -> list[dict]:
402+
if context is not None and context.mode == "lightweight" and context.index is not None:
403+
# A source-only feature can still have a README/SKILL/design guide
404+
# beside its implementation. Select only real indexed ancestor
405+
# documents, never another component's sibling directory.
406+
by_parent = {}
407+
for path, fact in context.index.files.items():
408+
document = PurePosixPath(path)
409+
if (document.suffix.lower() not in
410+
{".md", ".mdx", ".rst", ".txt", ".adoc"} or fact["sha256"] is None):
411+
continue
412+
name = document.stem.lower()
413+
priority = next((number for number, prefix in enumerate(
414+
("skill", "readme", "design", "architecture", "reference"))
415+
if name.startswith(prefix)), 5)
416+
by_parent.setdefault(document.parent.as_posix(), []).append((priority, path))
417+
adjacent = []
418+
for source in context._scope(feature):
419+
for distance, parent in enumerate(PurePosixPath(source).parents):
420+
siblings = by_parent.get(parent.as_posix(), ())
421+
adjacent.extend((distance, priority, path) for priority, path in siblings)
422+
if any(priority < 4 for priority, _ in siblings):
423+
break # the nearest component guide is the local boundary
424+
paths = list(dict.fromkeys([*feature.docs, *(path for _, _, path in sorted(adjacent))]))
425+
filenames = {PurePosixPath(path).name for path in context._scope(feature)}
426+
preferred = []
427+
for path in paths:
428+
matches, examples, fenced = [], [], False
429+
for number, line in enumerate(context.index.files.get(path, {}).get("lines", ()), 1):
430+
if line.lstrip().startswith(("```", "~~~")):
431+
fenced = not fenced
432+
if any(name in line for name in filenames):
433+
matches.append(number)
434+
if fenced:
435+
examples.append(number)
436+
# Existing executable examples beat prose lists of unrelated
437+
# tools. Nearby output shapes/criteria remain real line ranges.
438+
preferred.extend((path, max(1, number - 6),
439+
min(len(context.index.files[path]["lines"]), number + 6))
440+
for number in (examples or matches))
441+
# The immutable index supplies complete real line ranges, including
442+
# late manual acceptance steps. The existing 8KB packet cap applies.
443+
docs, used = [], 0
444+
for number, path in enumerate(paths):
445+
selected = context.document_slices([], paths=(path,),
446+
limit=(8000 - used) // (len(paths) - number), facets=facets,
447+
previous_review=previous_review, evidence_round=evidence_round,
448+
preferred_ranges=preferred)
449+
docs.extend(selected)
450+
used += sum(len(line.encode("utf-8")) + 1 for item in selected for line in item["text"])
451+
if docs:
452+
# build() rereads whole indexed documents. Offering a generic
453+
# owner path here would let that reread crowd out the local
454+
# command/criteria despite this first selection's byte cap.
455+
return docs
456+
generic = [item for item in self._docs_for(tree, owner) if item["path"] not in paths]
457+
return context.document_slices(generic, limit=8000, facets=facets,
458+
previous_review=previous_review, evidence_round=evidence_round)
401459
docs = self._sources(tree, list(feature.docs), MAX_DOC_BYTES // 2)
402460
used = sum(len(d["text"].encode("utf-8")) for d in docs)
403461
for item in self._docs_for(tree, owner):
@@ -444,17 +502,28 @@ def _attempt(self, tree, context, feature, entry):
444502
owner = next((o for o in self.owners if o.owner == feature.owner),
445503
Owner(feature.owner, feature.page, tuple(p.split("*", 1)[0] for p in feature.source_globs)))
446504
guidance = getattr(self, "_repair_guidance", None)
447-
docs = [] if guidance else self._docs(tree, feature, owner)
505+
requested = entry.get("requested_facets") or [f for f in FACETS if f not in old_blocks]
506+
docs = [] if guidance else self._docs(tree, feature, owner, context=context,
507+
facets=requested, previous_review=entry.get("reason"),
508+
evidence_round=entry.get("evidence_round", 0))
448509
existing = self._bounded_context(self._existing_knowledge(owner, self.head.get(feature.page, "")))
449510
if lightweight:
450511
docs = self._bounded_slices(docs, 8000)
451512
existing = self._bounded_texts(existing, 4000)
452-
requested = entry.get("requested_facets") or [f for f in FACETS if f not in old_blocks]
453513
retrieval = context.guided(feature, requested, guidance) if guidance else context.build(
454514
feature, self.head.get(feature.page, ""), docs, facets=requested,
455515
previous_review=entry.get("reason"), evidence_round=entry.get("evidence_round", 0))
456516
if lightweight:
457-
docs = retrieval.get("docs", docs)
517+
if context.index is not None and not guidance:
518+
# Preserve the already selected local document ranges; a second
519+
# full-index rerank can replace their commands/criteria. Bind
520+
# the actual final packet, without changing any saved payload.
521+
retrieval["docs"] = docs
522+
retrieval["context_sha256"] = hashlib.sha256(json.dumps(
523+
{key: value for key, value in retrieval.items() if key != "context_sha256"},
524+
sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
525+
else:
526+
docs = retrieval.get("docs", docs)
458527
files = retrieval["files"]
459528
if not files and not (lightweight and docs):
460529
entry["attempts"] = entry.get("attempts", 0) + 1

0 commit comments

Comments
 (0)