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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#!/usr/bin/env python3
"""Classify every file below docs/ and research/ and fail on invalid governance.

The classifier is intentionally conservative: paths get a declared scientific
role, but classification never upgrades a document to accepted evidence.
Use --write to materialize the complete per-file catalogue for human review.
"""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
OVERRIDES = ROOT / "research/document_governance_overrides.json"
OUTPUTS = {
    "docs": ROOT / "docs/DOCUMENT_CATALOG.json",
    "research": ROOT / "research/RESEARCH_CATALOG.json",
}
SKIP = {
    "docs/DOCUMENT_CATALOG.json",
    "research/RESEARCH_CATALOG.json",
}


def _load_overrides() -> dict[str, dict[str, Any]]:
    payload = json.loads(OVERRIDES.read_text(encoding="utf-8"))
    overrides = payload.get("overrides")
    if not isinstance(overrides, dict):
        raise ValueError(
            "document governance overrides must contain an object named overrides"
        )
    return {str(key).rstrip("/"): dict(value) for key, value in overrides.items()}


def _base(path: str) -> dict[str, Any]:
    return {
        "path": path,
        "domain": path.split("/", 1)[0],
        "kind": "documentation",
        "status": "current",
        "authority": "contextual_documentation",
        "mutability": "editable",
        "citation": "cite_exact_path_and_revision",
        "evidence_role": "not_evidence_by_itself",
        "rationale": (
            "Rule-classified repository documentation; exact scientific authority "
            "depends on referenced DATA/EVID."
        ),
    }


def _apply_prefix_override(
    path: str,
    item: dict[str, Any],
    overrides: dict[str, dict[str, Any]],
) -> None:
    matches = [
        prefix
        for prefix in overrides
        if path == prefix or path.startswith(prefix + "/")
    ]
    if not matches:
        return
    prefix = max(matches, key=len)
    item.update(overrides[prefix])
    item["classification_rule"] = f"override:{prefix}"


def _research_rule(path: str, item: dict[str, Any]) -> None:
    lower = path.lower()
    parts = path.split("/")
    top = parts[1] if len(parts) > 1 else ""

    normative = {
        "registry": (
            "registry",
            "normative_research_registry",
            "research_definition_not_evidence_by_itself",
        ),
        "schemas": ("schema", "normative_schema", "contract_not_evidence"),
        "protocols": (
            "protocol",
            "normative_protocol_or_method",
            "protocol_not_result",
        ),
        "ethics": (
            "ethics_policy",
            "normative_ethics_context",
            "policy_not_evidence",
        ),
        "critique": ("critique", "critical_analysis", "interpretation_only"),
        "literature": (
            "literature",
            "source_index",
            "external_source_provenance",
        ),
        "specifications": (
            "specification",
            "normative_design_contract",
            "contract_not_evidence",
        ),
        "preregistrations": (
            "preregistration",
            "frozen_or_versioned_experiment_plan",
            "preregistration_not_result",
        ),
        "benchmarks": (
            "benchmark",
            "benchmark_reference_or_method",
            "benchmark_definition_not_evidence_by_itself",
        ),
        "prompts": (
            "analysis_prompt",
            "analysis_method_configuration",
            "prompt_not_evidence",
        ),
        "frontiers": (
            "frontier_programme",
            "research_planning",
            "planning_only",
        ),
    }
    if top in normative:
        kind, authority, evidence_role = normative[top]
        item.update(kind=kind, authority=authority, evidence_role=evidence_role)
        item["classification_rule"] = f"research-zone:{top}"
        if top == "preregistrations":
            item.update(
                mutability="immutable_after_registration_or_versioned_replacement",
                citation="cite_preregistration_id_and_revision",
            )
        elif top == "frontiers":
            item.update(citation="cite_as_planning_not_result")
    elif top == "experiments":
        item.update(
            kind="experiment",
            status="experimental",
            authority="experiment_artifact",
            mutability="append_only_or_immutable_after_completion",
            citation="cite_experiment_id_path_digest",
            evidence_role="data_or_review_state_as_declared_by_manifest",
            rationale=(
                "Experimental artifact; execution and DATA do not automatically "
                "imply accepted EVID."
            ),
        )
        item["classification_rule"] = "research-zone:experiments"
    elif top == "workflows":
        item.update(
            kind="experiment_workflow",
            status="experimental",
            authority="workflow_execution_record",
            mutability="append_only_or_immutable_after_completion",
            citation="cite_workflow_or_experiment_id_and_revision",
            evidence_role="workflow_record_not_evidence_by_itself",
        )
        item["classification_rule"] = "research-zone:workflows"
    elif top == "proposals":
        item.update(
            kind="research_proposal",
            status="experimental",
            authority="proposal_only",
            citation="cite_as_proposal_not_result",
            evidence_role="proposal_not_evidence",
        )
        item["classification_rule"] = "research-zone:proposals"
    elif top == "generated":
        item.update(
            kind="generated",
            status="generated",
            authority="generated_projection",
            mutability="regenerable",
            citation="cite_underlying_source_not_projection_when_possible",
            evidence_role="projection_not_evidence_by_itself",
        )
        item["classification_rule"] = "research-zone:generated"
    elif top == "publications":
        item.update(
            kind="publication",
            status=(
                "historical"
                if "2026-09-15_recursive-epistemics_v1.7" not in path
                else "current_wip"
            ),
            authority="publication_interpretation",
            citation="cite_with_edition",
            evidence_role="interpretation_only",
        )
        item["classification_rule"] = "research-zone:publications"
    elif top in {"external_review", "reviews"}:
        item.update(
            kind="review",
            authority="human_or_external_review_record",
            evidence_role="review_state",
        )
        item["classification_rule"] = f"research-zone:{top}"
    elif top in {"data", "datasets", "raw", "artifacts"}:
        item.update(
            kind="data",
            status="experimental",
            authority="data_artifact",
            mutability="immutable_or_append_only",
            citation="cite_path_digest_and_origin",
            evidence_role="data_not_accepted_evidence_by_itself",
        )
        item["classification_rule"] = f"research-zone:{top}"
    else:
        item.update(
            kind="research_document",
            authority="research_context",
            evidence_role="interpretation_or_navigation",
        )
        item["classification_rule"] = "research-zone:top-level-context"

    if (
        "/archive" in lower
        or "/archives" in lower
        or lower.endswith((".zip", ".tar", ".gz"))
    ):
        item.update(
            status="archive",
            mutability="immutable",
            citation="cite_archive_and_digest",
        )
        item["classification_rule"] += "+archive"
    if any(
        token in lower for token in ("historical", "legacy", "deprecated", "superseded")
    ):
        item.update(
            status="historical",
            authority="historical_context",
            evidence_role="historical_only",
        )
        item["classification_rule"] += "+historical-name"


def _docs_rule(path: str, item: dict[str, Any]) -> None:
    lower = path.lower()
    parts = path.split("/")
    top = parts[1] if len(parts) > 1 else ""
    zone_map = {
        "00-governance": (
            "governance",
            "normative_document_governance",
            "policy_not_evidence",
            "current",
        ),
        "01-guides": (
            "guide",
            "operator_or_developer_guidance",
            "not_evidence",
            "current",
        ),
        "02-architecture": (
            "architecture",
            "current_architecture_documentation",
            "design_contract_not_evidence",
            "current",
        ),
        "03-dashboard": (
            "dashboard_contract",
            "technical_interface_documentation",
            "contract_not_evidence",
            "current",
        ),
        "04-integration": (
            "integration_record",
            "historical_integration_context",
            "historical_only",
            "historical",
        ),
        "05-quality": (
            "quality_policy",
            "normative_quality_contract",
            "quality_contract_not_evidence",
            "current",
        ),
        "06-research": (
            "research_documentation",
            "research_context",
            "interpretation_only",
            "current",
        ),
        "07-changelog": (
            "changelog",
            "historical_change_record",
            "historical_only",
            "historical",
        ),
        "08-roadmap": (
            "roadmap",
            "planning",
            "planning_only",
            "current",
        ),
        "09-sprints": (
            "sprint_record",
            "historical_planning_record",
            "historical_only",
            "historical",
        ),
        "10-releases": (
            "release_record",
            "historical_release_provenance",
            "historical_only",
            "historical",
        ),
        "11-readme": (
            "historical_readme",
            "historical_context",
            "historical_only",
            "historical",
        ),
        "12-updates": (
            "update_record",
            "historical_change_record",
            "historical_only",
            "historical",
        ),
        "99-archive": (
            "archive",
            "archived_context",
            "historical_only",
            "archive",
        ),
    }
    if top in zone_map:
        kind, authority, evidence_role, status = zone_map[top]
        item.update(
            kind=kind,
            authority=authority,
            evidence_role=evidence_role,
            status=status,
        )
        item["classification_rule"] = f"docs-zone:{top}"
        if status == "archive":
            item.update(mutability="immutable", citation="cite_archive_and_digest")
        elif status == "historical":
            item.update(citation="cite_with_version_or_date")
    else:
        item.update(
            kind="documentation",
            authority="project_documentation",
            evidence_role="not_evidence_by_itself",
        )
        item["classification_rule"] = "docs-zone:top-level-context"

    if top == "08-roadmap":
        item.update(citation="cite_as_planning_not_result")
    if top == "06-research" and "/old/" in lower:
        item.update(
            status="historical",
            authority="historical_research_context",
            evidence_role="historical_only",
            citation="cite_as_historical_draft",
        )
        item["classification_rule"] += "+old"
    if top in {"01-guides", "03-dashboard", "06-research"} and any(
        token in lower
        for token in (
            "v040",
            "v050",
            "v0.5",
            "alpha4",
            "alpha5",
            "alpha7",
            "brain-5d",
            "geliehene_intelligenz",
        )
    ):
        item.update(
            status="historical",
            authority="historical_versioned_context",
            evidence_role="historical_only",
            citation="cite_with_version_and_date",
        )
        item["classification_rule"] += "+versioned-history"


def classify(path: str, overrides: dict[str, dict[str, Any]]) -> dict[str, Any]:
    item = _base(path)
    if path.startswith("research/"):
        _research_rule(path, item)
    elif path.startswith("docs/"):
        _docs_rule(path, item)
    else:
        raise ValueError(f"path outside governance scope: {path}")
    _apply_prefix_override(path, item, overrides)
    item.setdefault("classification_rule", "base")
    item["review_required"] = "top-level-context" in item["classification_rule"]
    return item


def inventory(
    domain: str,
    overrides: dict[str, dict[str, Any]],
) -> list[dict[str, Any]]:
    base = ROOT / domain
    files = []
    for file in sorted(path for path in base.rglob("*") if path.is_file()):
        rel = file.relative_to(ROOT).as_posix()
        if rel in SKIP:
            continue
        files.append(classify(rel, overrides))
    return files


def _validate(items: list[dict[str, Any]], errors: list[str]) -> None:
    required = {
        "path",
        "domain",
        "kind",
        "status",
        "authority",
        "mutability",
        "citation",
        "evidence_role",
        "rationale",
        "classification_rule",
    }
    valid_status = {
        "current",
        "current_wip",
        "frozen",
        "historical",
        "generated",
        "experimental",
        "superseded",
        "archive",
    }
    paths: set[str] = set()
    for item in items:
        missing = required - set(item)
        if missing:
            errors.append(f"{item.get('path')}: missing {sorted(missing)}")
        if item.get("status") not in valid_status:
            errors.append(f"{item.get('path')}: invalid status {item.get('status')!r}")
        path = str(item.get("path"))
        if path in paths:
            errors.append(f"duplicate catalogue path: {path}")
        paths.add(path)
        if item.get("evidence_role") == "accepted_evidence" and "EVID" not in path:
            errors.append(
                f"{path}: accepted evidence may not be inferred from location"
            )


def _write(domain: str, items: list[dict[str, Any]]) -> None:
    summary = {
        "file_count": len(items),
        "status": dict(sorted(Counter(str(item["status"]) for item in items).items())),
        "kind": dict(sorted(Counter(str(item["kind"]) for item in items).items())),
        "authority": dict(
            sorted(Counter(str(item["authority"]) for item in items).items())
        ),
        "review_required": sum(bool(item.get("review_required")) for item in items),
    }
    payload = {
        "schema_version": 1,
        "generated_by": "scripts/audit_document_governance.py",
        "scope": domain,
        "warning": (
            "Classification describes document role; it does not promote DATA "
            "to EVID or certify scientific validity."
        ),
        "summary": summary,
        "files": items,
    }
    OUTPUTS[domain].write_text(
        json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--write",
        action="store_true",
        help="materialize complete per-file catalogues",
    )
    parser.add_argument(
        "--strict-review",
        action="store_true",
        help="fail if generic top-level contextual files remain",
    )
    args = parser.parse_args()

    overrides = _load_overrides()
    errors: list[str] = []
    all_items: dict[str, list[dict[str, Any]]] = {}
    for domain in ("docs", "research"):
        items = inventory(domain, overrides)
        all_items[domain] = items
        _validate(items, errors)
        if args.strict_review:
            for item in items:
                if item.get("review_required"):
                    errors.append(
                        f"{item['path']}: requires explicit governance review"
                    )
        if args.write:
            _write(domain, items)

    for domain, items in all_items.items():
        counts = Counter(str(item["status"]) for item in items)
        print(
            f"{domain}: {len(items)} files declared; "
            f"status={dict(sorted(counts.items()))}"
        )
    if errors:
        print("Document governance audit: FAILED")
        for error in errors:
            print(f"- {error}")
        return 1
    print("Document governance audit: PASS")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())