Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Enrichment trust model and optional workflow

The optional enrichment layer adds AI-generated navigation aids on top of deterministic extraction. It never replaces it.

## Contents

- [Trust hierarchy](#trust-hierarchy)
- [Marking and metadata](#marking-and-metadata)
- [Optional workflow](#optional-workflow)
- [Guardrails](#guardrails)
- [Evaluation](#evaluation)
- [Limits](#limits)

## Trust hierarchy

1. Original PDF or authoritative source.
2. Deterministically extracted or OCR content (`raw/extracted.md`, `raw/page_map.json`).
3. AI topic restructuring (`ai-navigation/topics/`): verbatim slices of level 2 cut at AI-chosen boundaries.
4. AI indexes and summaries (`ai-navigation/index.md`, `chapters/`, `navigation.json`).

Levels 3 and 4 are for finding content. Facts and citations come from levels 1 and 2.

## Marking and metadata

Every AI file has front matter (`content_type: ai_generated_navigation`, `trust_level: discovery_only`,
`authoritative: false`, `generated_from`, `source_document`, `extracted_content`, `source_sha256`, `generation_model`,
`prompt_version`, `generation_timestamp`, `source_pages`, `uncertain_boundary`) and a visible "AI-GENERATED NAVIGATION
AID" notice. Deterministic output is described by `deterministic_metadata` (`content_type: deterministic_extraction`,
`trust_level: authoritative_extraction`, `authoritative: true`).

## Optional workflow

1. Extract deterministically (unchanged; the AI layer can be skipped entirely).
2. `assess_structure` scores the document. Good bookmarks and headings are kept; AI is recommended only for gaps or
weak or absent structure. Overrides per document or batch: `enrichment-overrides.json`.
3. Ask the user, one question at a time with the cost shown: add the AI layer, and for which documents. Record the
answer with `record_consent`. The provider sees the document text.
4. Decompose (`decompose.py`), summarise and index (`navigation.py`): the host agent answers request files.
5. A human reviews and `approve`s; `publish` copies only valid, non-stale output to a separate folder.

## Guardrails

Extraction is never modified; output goes to `ai-navigation/`; page provenance is kept; uncertain titles and boundaries
are flagged; model, prompt version, timestamp and hashes are recorded; changed source or extraction marks output stale;
regeneration leaves authoritative files alone; summaries may not copy long source passages; links and page references
are validated before publication.

## Evaluation

`evaluation.py` compares four arms (native PDF, large Markdown, topic Markdown, topic Markdown with navigation) on
retrieval accuracy, completeness, citation correctness, tokens, latency, files retrieved, answer length and failures to
reach authoritative content. Agents write run records; scoring is deterministic.

## Limits

Summaries can still be wrong. Boundaries snap to blank-line block edges, so very long unbroken blocks stay together.
Evaluation results apply to the tested corpus, questions and agent only.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ examples:

Implemented: the structure-quality assessment, overrides, page map, trust metadata, notice and validators (step 1),
agent-mediated decomposition (step 2), and summaries, chapter/document roll-up, relations, the hierarchical index and
approval-gated publication (step 3). **Not implemented yet:** the evaluation mode. Do not offer it until it lands.
approval-gated publication (step 3), and the evaluation mode (step 4). All planned parts are implemented.

## Agent-mediated generation

Expand Down Expand Up @@ -93,3 +93,5 @@ Run `pytest plugins/sharepoint-workbench/tests/test_enrichment_foundations.py`.

- `scripts/enrichment/structure_quality.py`, `scripts/enrichment/provenance.py`, `scripts/enrichment/decompose.py`, `scripts/enrichment/navigation.py`
- [content-extract-pdf.md](content-extract-pdf.md) for `raw/page_map.json`
- [enrichment-trust-model.md](../enrichment-trust-model.md): trust hierarchy, metadata and workflow
- `scripts/enrichment/evaluation.py`: four-arm evaluation (`build_tasks`, `score_run`, `summarize`, `render_report`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""Evaluation mode for the enrichment layer: compare four retrieval arms on the same questions (agent-mediated).

Purpose: measure whether structure and AI navigation aids help an agent reach the smallest authoritative unit. This
module writes task files, validates the run records a host agent writes, scores them deterministically from recorded
facts (no model judges anything) and summarises per arm. Results show this corpus and agent only.

Key Input Dependencies: a questions file, run records written by the host agent, page provenance from the page map.

Key Functions Index:
- build_tasks()
- validate_run()
- is_authoritative()
- score_run()
- summarize()
- render_report()
"""

import json
from pathlib import Path

ARMS = ("native_pdf", "large_markdown", "topic_markdown", "topic_markdown_with_navigation")

TASK_INSTRUCTIONS = (
"Answer the question using only the materials allowed for this arm. Record every file you opened in `retrieved` "
"(path and, when known, source pages [first, last]), cite sources in `citations`, and write the run record JSON to "
"`runs/<arm>__<question id>.json`. Prefer authoritative extracted content or the original PDF as the factual basis; "
"AI-generated navigation aids are for finding content, not for citing facts."
)


def _page_overlap(a, b) -> bool:
return bool(a and b) and a[0] <= b[1] and b[0] <= a[1]


def build_tasks(eval_dir: Path, questions: list, materials: dict, arms=ARMS) -> list:
"""Write `tasks/<arm>__<id>.json` for every question and arm. `materials` maps arm to a description of what the
agent may open (paths). Questions: {id, question, expected_pages: [first, last], expected_facts: [str]}."""
eval_dir = Path(eval_dir)
(eval_dir / "tasks").mkdir(parents=True, exist_ok=True)
tasks = []
for q in questions:
for arm in arms:
task = {"arm": arm, "question_id": q["id"], "question": q["question"],
"allowed_materials": materials.get(arm, []), "instructions": TASK_INSTRUCTIONS}
(eval_dir / "tasks" / f"{arm}__{q['id']}.json").write_text(json.dumps(task, indent=2), encoding="utf-8")
tasks.append(task)
return tasks


def validate_run(run) -> list:
"""Problems with one run record; empty when it can be scored."""
if not isinstance(run, dict):
return ["run must be an object"]
problems = []
if run.get("arm") not in ARMS:
problems.append(f"arm must be one of {ARMS}")
if not run.get("question_id"):
problems.append("question_id is missing")
if not isinstance(run.get("answer", ""), str):
problems.append("answer must be text")
for field in ("retrieved", "citations"):
items = run.get(field, [])
if not isinstance(items, list) or not all(isinstance(i, dict) and isinstance(i.get("path"), str) for i in items):
problems.append(f"{field} must be a list of objects with a path")
for field in ("tokens", "latency_s"):
value = run.get(field)
if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0):
problems.append(f"{field} must be a non-negative number or null")
return problems


def is_authoritative(path: str) -> bool:
"""The original PDF or deterministic extraction, never anything under `ai-navigation/`."""
p = path.replace("\\", "/").lower()
return "ai-navigation/" not in p and p.endswith((".pdf", ".md"))


def score_run(question: dict, run: dict) -> dict:
"""Metrics for one run from recorded facts only (substring and page overlap; no model judging)."""
expected = question.get("expected_pages")
retrieved, citations = run.get("retrieved", []), run.get("citations", [])
reached = any(is_authoritative(r["path"]) and _page_overlap(r.get("pages"), expected) for r in retrieved)
good = [c for c in citations if is_authoritative(c["path"]) and _page_overlap(c.get("pages"), expected)]
facts = question.get("expected_facts", [])
answer = run.get("answer", "")
found = [f for f in facts if f.lower() in answer.lower()]
return {
"arm": run["arm"], "question_id": run["question_id"],
"retrieval_accuracy": 1.0 if reached else 0.0,
"answer_completeness": len(found) / len(facts) if facts else None,
"citation_correctness": len(good) / len(citations) if citations else 0.0,
"citations": len(citations),
"tokens": run.get("tokens"), "latency_s": run.get("latency_s"),
"files_retrieved": len(retrieved), "answer_length": len(answer),
"failed_to_reach_source": not reached,
"error": run.get("error"),
}


def _mean(values):
values = [v for v in values if v is not None]
return round(sum(values) / len(values), 3) if values else None


def summarize(questions: list, runs: list) -> dict:
"""Per-arm means over scored runs; invalid runs are counted, not scored. Missing runs show in `runs` vs `questions`."""
by_id = {q["id"]: q for q in questions}
arms = {}
for run in runs:
arm = run.get("arm") if isinstance(run, dict) else None
bucket = arms.setdefault(arm, {"scores": [], "invalid": 0})
if validate_run(run) or run["question_id"] not in by_id:
bucket["invalid"] += 1
continue
bucket["scores"].append(score_run(by_id[run["question_id"]], run))
summary = {}
for arm, bucket in arms.items():
s = bucket["scores"]
summary[arm] = {
"runs": len(s), "invalid_runs": bucket["invalid"], "questions": len(questions),
"retrieval_accuracy": _mean(x["retrieval_accuracy"] for x in s),
"answer_completeness": _mean(x["answer_completeness"] for x in s),
"citation_correctness": _mean(x["citation_correctness"] for x in s),
"mean_tokens": _mean(x["tokens"] for x in s),
"mean_latency_s": _mean(x["latency_s"] for x in s),
"mean_files_retrieved": _mean(x["files_retrieved"] for x in s),
"mean_answer_length": _mean(x["answer_length"] for x in s),
"failures_to_reach_source": sum(1 for x in s if x["failed_to_reach_source"]),
}
return summary


def render_report(summary: dict) -> str:
"""Markdown table of the summary. Ends with the caveat that results apply to this corpus and agent only."""
cols = ["runs", "invalid_runs", "retrieval_accuracy", "answer_completeness", "citation_correctness", "mean_tokens",
"mean_latency_s", "mean_files_retrieved", "mean_answer_length", "failures_to_reach_source"]
lines = ["| arm | " + " | ".join(cols) + " |", "|---|" + "---|" * len(cols)]
for arm in [a for a in ARMS if a in summary] + [a for a in summary if a not in ARMS]:
lines.append(f"| {arm} | " + " | ".join("n/a" if summary[arm][c] is None else str(summary[arm][c]) for c in cols) + " |")
lines.append("\nResults describe this corpus, question set and agent only; they are not general claims.")
return "\n".join(lines) + "\n"
2 changes: 1 addition & 1 deletion plugins/sharepoint-workbench/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The unified, production-grade SharePoint Knowledge Workbench plugin. Provides 11
|:---:|:---|:---|
| 1 | [`setting-up-sharepoint-workbench`](skills/setting-up-sharepoint-workbench/SKILL.md) | Setup, connection profiles (`config.psd1`), Entra ID app registration requests. |
| 2 | [`assessing-sharepoint-sites`](skills/assessing-sharepoint-sites/SKILL.md) | Read-only discovery: inventories, permissions, webparts, metadata, schema drift. |
| 3 | [`converting-sharepoint-documents`](skills/converting-sharepoint-documents/SKILL.md) | Gated document compiler: DOCX/PDF ➡️ AST analysis ➡️ Markdown/SPO page render. |
| 3 | [`converting-sharepoint-documents`](skills/converting-sharepoint-documents/SKILL.md) | Gated document compiler: DOCX/PDF ➡️ AST analysis ➡️ Markdown/SPO page render. Optional, flagged AI navigation layer (summaries, index) for weakly structured documents. |
| 4 | [`developing-spfx-solutions`](skills/developing-spfx-solutions/SKILL.md) | SPFx developer toolchain: web parts, extensions, hosted workbench, sppkg deploy. |
| 5 | [`managing-sharepoint-lists-and-libraries`](skills/managing-sharepoint-lists-and-libraries/SKILL.md) | Storage containers: lists, document libraries, views, list columns, settings, files. |
| 6 | [`publishing-sharepoint-pages`](skills/publishing-sharepoint-pages/SKILL.md) | Web publishing: modern pages, HTML pages, markdown deployment, CKEditor 5 RTE formatting. |
Expand Down
74 changes: 74 additions & 0 deletions plugins/sharepoint-workbench/tests/test_enrichment_evaluation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Tests for the evaluation mode: task files, run validation, deterministic scoring, per-arm summaries and report.

Purpose: scoring uses recorded facts (page overlap, substrings, counts); nothing depends on generated wording quality.

Key Input Dependencies: scripts/enrichment/evaluation.py.
"""
import json
import sys
from pathlib import Path

_plugin_dir = Path(__file__).resolve().parents[1]
_skill = (_plugin_dir / ".apm" / "skills" if (_plugin_dir / ".apm" / "skills").exists() else _plugin_dir / "skills") \
/ "converting-sharepoint-documents"
sys.path.insert(0, str(_skill / "scripts" / "enrichment"))

import evaluation as ev # noqa: E402

Q = {"id": "q1", "question": "Notice for annual leave?", "expected_pages": [2, 2], "expected_facts": ["10 days", "annual"]}


def _run(arm="topic_markdown", **changes):
run = {"arm": arm, "question_id": "q1", "answer": "Annual leave needs 10 days notice.",
"retrieved": [{"path": "Criminal_md/doc/02-leave.md", "pages": [2, 3]}],
"citations": [{"path": "Criminal_md/doc/02-leave.md", "pages": [2, 2]}], "tokens": 1200, "latency_s": 4.5}
run.update(changes)
return run


def test_tasks_cover_every_question_and_arm(tmp_path):
tasks = ev.build_tasks(tmp_path, [Q, {**Q, "id": "q2"}], {"native_pdf": ["m.pdf"]})
assert len(tasks) == 2 * len(ev.ARMS)
first = json.loads((tmp_path / "tasks" / "native_pdf__q1.json").read_text())
assert first["allowed_materials"] == ["m.pdf"] and "authoritative" in first["instructions"]


def test_scoring_from_recorded_facts():
score = ev.score_run(Q, _run())
assert score["retrieval_accuracy"] == 1.0 and score["answer_completeness"] == 1.0
assert score["citation_correctness"] == 1.0 and not score["failed_to_reach_source"]
assert score["files_retrieved"] == 1 and score["tokens"] == 1200


def test_ai_navigation_files_do_not_count_as_authoritative_source():
nav_only = _run("topic_markdown_with_navigation",
retrieved=[{"path": "doc/ai-navigation/index.md", "pages": [1, 3]}],
citations=[{"path": "doc/ai-navigation/topics/01-x.md", "pages": [2, 2]}])
score = ev.score_run(Q, nav_only)
assert score["failed_to_reach_source"] is True and score["citation_correctness"] == 0.0
assert ev.is_authoritative("source-documents/m.pdf") and not ev.is_authoritative("a\\ai-navigation\\index.md")


def test_wrong_pages_missing_facts_and_no_citations():
wrong = _run(answer="Not sure.", retrieved=[{"path": "doc/05.md", "pages": [9, 9]}], citations=[])
score = ev.score_run(Q, wrong)
assert (score["retrieval_accuracy"], score["answer_completeness"], score["citation_correctness"]) == (0.0, 0.0, 0.0)
assert score["failed_to_reach_source"] is True


def test_run_validation_rejects_malformed_records():
assert ev.validate_run(_run()) == []
assert ev.validate_run("x") and ev.validate_run(_run(arm="other"))
assert ev.validate_run(_run(retrieved=[{"pages": [1, 1]}])) and ev.validate_run(_run(tokens=-1))


def test_summary_counts_invalid_runs_and_model_failures_per_arm_and_report():
runs = [_run("native_pdf"), _run("topic_markdown"), _run("topic_markdown", question_id="q9"),
_run("topic_markdown", error="timeout", answer="", retrieved=[], citations=[], tokens=None)]
summary = ev.summarize([Q], runs)
assert summary["topic_markdown"]["runs"] == 2 and summary["topic_markdown"]["invalid_runs"] == 1
assert summary["topic_markdown"]["failures_to_reach_source"] == 1
assert summary["native_pdf"]["retrieval_accuracy"] == 1.0
report = ev.render_report(summary)
assert "| native_pdf |" in report and "this corpus" in report
assert ev.summarize([Q], []) == {}
1 change: 1 addition & 0 deletions references/map-debt.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,4 @@ Persistent tracking of architectural friction, structural anomalies, and unclose
| DEBT-20261104-06 | No way to tell whether a document's structure supports progressive discovery, and no trust model for AI-generated navigation aids | PARTIAL | M | NO | 2026-11-04 | Step 1 of 4 of the optional enrichment layer (no model calls). `pdf_extraction` writes `raw/page_map.json`; `scripts/enrichment/structure_quality.py` scores structure (sufficient/partial/weak/none/not_assessable) with per-document and batch overrides; `provenance.py` defines the AI notice, trust metadata and validators (notice, trust flags, page refs, links, staleness, verbatim slices). Mode doc `content-enrich-navigation.md`; tests in `test_enrichment_foundations.py`. **Open:** the provider interface and decomposition landed in DEBT-20261104-07; summaries, indexes and evaluation mode remain. | this PR |
| DEBT-20261104-07 | AI topic decomposition needed a provider-neutral, consent-gated, validated path | PARTIAL | M | NO | 2026-11-04 | Step 2 of 4. `scripts/enrichment/decompose.py` is agent-mediated (the host agent answers request files; no API keys, no model calls in code): consent gate, windowed requests, response validation with boundaries snapped to block edges (tables never split), retries and partial completion, verbatim topic files under `ai-navigation/`, `generation.json` with hashes, staleness checks. Tests in `test_enrichment_decompose.py`. **Open:** summaries, hierarchical index, relations, example package (PR 3); evaluation mode and docs (PR 4). | this PR |
| DEBT-20261104-08 | Weakly structured documents had no summaries or hierarchical index for progressive discovery | PARTIAL | M | NO | 2026-11-04 | Step 3 of 4. `scripts/enrichment/navigation.py` (agent-mediated): per-topic summaries with keywords and synonyms, chapter/document roll-up and relations built from summaries only, `index.md`, `chapters/`, `navigation.json`, all carrying the AI notice and discovery-only metadata; human approval and a clean validation (notice, trust, pages, links, staleness) gate `publish`. Worked example in `assets/examples/enrichment-example/` built by `build_example.py`. Tests in `test_enrichment_navigation.py`. **Open:** evaluation mode and trust-model docs (PR 4). | this PR |
| DEBT-20261104-09 | No way to measure whether structure and AI navigation aids help an agent reach authoritative content | RESOLVED | M | NO | 2026-11-04 | Step 4 of 4. `scripts/enrichment/evaluation.py` compares four arms (native PDF, large Markdown, topic Markdown, topic Markdown plus navigation): agent-mediated task files, run-record validation, deterministic scoring (retrieval accuracy, completeness, citation correctness, tokens, latency, files retrieved, answer length, failures to reach source) and a per-arm report. Trust model and optional workflow documented in `references/enrichment-trust-model.md`. Tests in `test_enrichment_evaluation.py`. **Open:** no evaluation has been run on a real corpus; results would apply to that corpus and agent only. | this PR |
Loading