@yottameta/yotta-resume 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,664 @@
1
+ #!/usr/bin/env python3
2
+ """Validate yotta-resume data contracts without network access or writes."""
3
+
4
+ import argparse
5
+ import datetime as dt
6
+ import hashlib
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+
11
+
12
+ CONTRACT_VERSION = "1.0"
13
+ CONTRACT_FILES = (
14
+ "security-role-map.json",
15
+ "security-role-map.schema.json",
16
+ "source-registry.json",
17
+ "source-registry.schema.json",
18
+ "question-bank.json",
19
+ "question-bank.schema.json",
20
+ "evidence-ledger.json",
21
+ "evidence-ledger.schema.json",
22
+ "dual-role-contract.json",
23
+ "dual-role-contract.schema.json",
24
+ )
25
+
26
+ REQUIRED_ROLE_IDS = {
27
+ "soc",
28
+ "incident_response",
29
+ "offensive_security",
30
+ "appsec",
31
+ "security_engineering",
32
+ "grc_data_security",
33
+ }
34
+ REQUIRED_LEVELS = {"junior", "mid", "senior", "lead"}
35
+ REQUIRED_DATA_CLASSES = {
36
+ "private_evidence_ledger",
37
+ "raw_resume",
38
+ "public_resume",
39
+ "analysis_report",
40
+ "interview_plan",
41
+ "scorecard",
42
+ "audit_log",
43
+ }
44
+ SOURCE_LAYERS = {"A", "B", "C", "D"}
45
+ SOURCE_POLICIES = {"facts_only", "link_only", "permission_required"}
46
+ LICENSE_STATUSES = {"unknown", "review_required", "cleared", "restricted"}
47
+ SOURCE_STATUSES = {"active", "draft", "retired"}
48
+ QUESTION_KINDS = {"knowledge", "scenario", "resume_followup"}
49
+ QUESTION_STATUSES = {"draft", "active", "retired"}
50
+ RESPONSIBILITY_VALUES = {"lead", "co_owner", "assist", "participate", "unknown"}
51
+ SENSITIVITY_VALUES = {"public", "internal", "confidential", "restricted"}
52
+
53
+ EVIDENCE_REQUIRED_FIELDS = (
54
+ "evidence_id",
55
+ "section",
56
+ "claim",
57
+ "scenario",
58
+ "goal",
59
+ "responsibility",
60
+ "actions",
61
+ "methods",
62
+ "scale",
63
+ "result",
64
+ "supporting_artifacts",
65
+ "boundaries",
66
+ "user_confirmed",
67
+ "source_refs",
68
+ "sensitivity",
69
+ "export_allowed",
70
+ )
71
+
72
+
73
+ def _error(code, path, message):
74
+ return {
75
+ "code": code,
76
+ "path": path,
77
+ "message": message,
78
+ }
79
+
80
+
81
+ def _read_json(path, errors):
82
+ try:
83
+ payload = json.loads(path.read_text(encoding="utf-8"))
84
+ except FileNotFoundError:
85
+ errors.append(_error("FILE_MISSING", path.name, "契约文件不存在"))
86
+ return None
87
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
88
+ errors.append(_error("JSON_INVALID", path.name, str(exc)))
89
+ return None
90
+ if not isinstance(payload, dict):
91
+ errors.append(_error("ROOT_NOT_OBJECT", path.name, "JSON 根节点必须是对象"))
92
+ return None
93
+ return payload
94
+
95
+
96
+ def _parse_date(value, path, field, errors, allow_none=False):
97
+ if value is None and allow_none:
98
+ return None
99
+ if not isinstance(value, str):
100
+ errors.append(_error("DATE_INVALID", path, "{} 必须是 ISO 日期".format(field)))
101
+ return None
102
+ try:
103
+ return dt.date.fromisoformat(value)
104
+ except ValueError:
105
+ errors.append(_error("DATE_INVALID", path, "{} 不是有效 ISO 日期".format(field)))
106
+ return None
107
+
108
+
109
+ def _canonical_hash(payload):
110
+ filtered = {
111
+ key: value
112
+ for key, value in payload.items()
113
+ if key != "content_hash"
114
+ }
115
+ canonical = json.dumps(
116
+ filtered,
117
+ ensure_ascii=False,
118
+ sort_keys=True,
119
+ separators=(",", ":"),
120
+ )
121
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
122
+
123
+
124
+ def _validate_header(data, filename, errors):
125
+ if data.get("schema_version") != CONTRACT_VERSION:
126
+ errors.append(_error(
127
+ "SCHEMA_VERSION_INVALID",
128
+ filename,
129
+ "schema_version 必须为 {}".format(CONTRACT_VERSION),
130
+ ))
131
+ if data.get("contract_version") != CONTRACT_VERSION:
132
+ errors.append(_error(
133
+ "CONTRACT_VERSION_INVALID",
134
+ filename,
135
+ "contract_version 必须为 {}".format(CONTRACT_VERSION),
136
+ ))
137
+ if "generated_at" in data:
138
+ _parse_date(data["generated_at"], filename, "generated_at", errors)
139
+
140
+
141
+ def _validate_schema_files(loaded, errors):
142
+ for filename in CONTRACT_FILES:
143
+ if not filename.endswith(".schema.json"):
144
+ continue
145
+ data = loaded.get(filename)
146
+ if data is None:
147
+ continue
148
+ if not isinstance(data.get("$schema"), str):
149
+ errors.append(_error("SCHEMA_METADATA_MISSING", filename, "缺少 $schema"))
150
+ if not isinstance(data.get("title"), str) or not data["title"].strip():
151
+ errors.append(_error("SCHEMA_METADATA_MISSING", filename, "缺少 title"))
152
+
153
+
154
+ def _validate_role_map(data, errors):
155
+ filename = "security-role-map.json"
156
+ if data is None:
157
+ return set(), set()
158
+ _validate_header(data, filename, errors)
159
+ levels = data.get("levels")
160
+ if not isinstance(levels, list):
161
+ errors.append(_error("LEVELS_INVALID", filename, "levels 必须是数组"))
162
+ levels = []
163
+ level_set = {item for item in levels if isinstance(item, str)}
164
+ if level_set != REQUIRED_LEVELS or len(levels) != len(REQUIRED_LEVELS):
165
+ errors.append(_error(
166
+ "LEVELS_INVALID",
167
+ filename,
168
+ "levels 必须精确包含 junior / mid / senior / lead",
169
+ ))
170
+
171
+ families = data.get("role_families")
172
+ if not isinstance(families, list):
173
+ errors.append(_error("ROLES_INVALID", filename, "role_families 必须是数组"))
174
+ families = []
175
+
176
+ seen = set()
177
+ for index, family in enumerate(families):
178
+ if not isinstance(family, dict):
179
+ errors.append(_error("ROLE_INVALID", filename, "岗位族 #{} 必须是对象".format(index)))
180
+ continue
181
+ role_id = family.get("id")
182
+ if not isinstance(role_id, str) or not role_id:
183
+ errors.append(_error("ROLE_INVALID", filename, "岗位族缺少 id"))
184
+ continue
185
+ if role_id in seen:
186
+ errors.append(_error("ROLE_DUPLICATE", filename, "岗位族 ID 重复:{}".format(role_id)))
187
+ seen.add(role_id)
188
+ for field in (
189
+ "display_name",
190
+ "aliases",
191
+ "nice_work_roles",
192
+ "evidence_dimensions",
193
+ "interview_dimensions",
194
+ "risk_rules",
195
+ "resume_evidence_requirements",
196
+ ):
197
+ value = family.get(field)
198
+ if field == "display_name":
199
+ if not isinstance(value, str) or not value.strip():
200
+ errors.append(_error("ROLE_FIELD_MISSING", filename, "{} 缺少 {}".format(role_id, field)))
201
+ elif not isinstance(value, list) or not value:
202
+ errors.append(_error("ROLE_FIELD_MISSING", filename, "{} 缺少 {}".format(role_id, field)))
203
+
204
+ if seen != REQUIRED_ROLE_IDS:
205
+ missing = sorted(REQUIRED_ROLE_IDS - seen)
206
+ extra = sorted(seen - REQUIRED_ROLE_IDS)
207
+ if missing:
208
+ errors.append(_error(
209
+ "ROLE_UNKNOWN",
210
+ filename,
211
+ "缺少岗位族:{}".format(", ".join(missing)),
212
+ ))
213
+ if extra:
214
+ errors.append(_error(
215
+ "ROLE_UNKNOWN",
216
+ filename,
217
+ "未登记岗位族:{}".format(", ".join(extra)),
218
+ ))
219
+ return seen, level_set
220
+
221
+
222
+ def _validate_sources(data, today, errors):
223
+ filename = "source-registry.json"
224
+ if data is None:
225
+ return {}
226
+ _validate_header(data, filename, errors)
227
+ sources = data.get("sources")
228
+ if not isinstance(sources, list):
229
+ errors.append(_error("SOURCES_INVALID", filename, "sources 必须是数组"))
230
+ return {}
231
+
232
+ by_id = {}
233
+ for index, source in enumerate(sources):
234
+ if not isinstance(source, dict):
235
+ errors.append(_error("SOURCE_INVALID", filename, "来源 #{} 必须是对象".format(index)))
236
+ continue
237
+ source_id = source.get("source_id")
238
+ if not isinstance(source_id, str) or not source_id:
239
+ errors.append(_error("SOURCE_INVALID", filename, "来源缺少 source_id"))
240
+ continue
241
+ if source_id in by_id:
242
+ errors.append(_error("SOURCE_DUPLICATE", filename, "来源 ID 重复:{}".format(source_id)))
243
+ by_id[source_id] = source
244
+
245
+ if source.get("layer") not in SOURCE_LAYERS:
246
+ errors.append(_error("SOURCE_LAYER_INVALID", filename, "{} layer 非法".format(source_id)))
247
+ for field in ("title", "publisher"):
248
+ if not isinstance(source.get(field), str) or not source[field].strip():
249
+ errors.append(_error("SOURCE_FIELD_MISSING", filename, "{} 缺少 {}".format(source_id, field)))
250
+ url = source.get("url")
251
+ if not isinstance(url, str) or not url.startswith("https://"):
252
+ errors.append(_error("SOURCE_URL_INVALID", filename, "{} URL 必须以 https:// 开头".format(source_id)))
253
+
254
+ _parse_date(source.get("published_at"), filename, "published_at", errors, allow_none=True)
255
+ _parse_date(source.get("retrieved_at"), filename, "retrieved_at", errors)
256
+ verified = _parse_date(source.get("last_verified_at"), filename, "last_verified_at", errors)
257
+ for field in ("refresh_interval_days", "stale_after_days"):
258
+ value = source.get(field)
259
+ if not isinstance(value, int) or isinstance(value, bool) or value < 1:
260
+ errors.append(_error("SOURCE_INTERVAL_INVALID", filename, "{} {} 必须是正整数".format(source_id, field)))
261
+ if source.get("usage_policy") not in SOURCE_POLICIES:
262
+ errors.append(_error("SOURCE_POLICY_INVALID", filename, "{} usage_policy 非法".format(source_id)))
263
+ if source.get("license_review_status") not in LICENSE_STATUSES:
264
+ errors.append(_error("SOURCE_LICENSE_INVALID", filename, "{} license_review_status 非法".format(source_id)))
265
+ if source.get("status") not in SOURCE_STATUSES:
266
+ errors.append(_error("SOURCE_STATUS_INVALID", filename, "{} status 非法".format(source_id)))
267
+
268
+ stale_after = source.get("stale_after_days")
269
+ if verified is not None and isinstance(stale_after, int) and (today - verified).days > stale_after:
270
+ errors.append(_error(
271
+ "SOURCE_EXPIRED",
272
+ filename,
273
+ "{} 已超过 {} 天有效期".format(source_id, stale_after),
274
+ ))
275
+ return by_id
276
+
277
+
278
+ def _validate_questions(data, role_ids, level_ids, sources, today, errors):
279
+ filename = "question-bank.json"
280
+ if data is None:
281
+ return 0
282
+ _validate_header(data, filename, errors)
283
+ questions = data.get("questions")
284
+ if not isinstance(questions, list):
285
+ errors.append(_error("QUESTIONS_INVALID", filename, "questions 必须是数组"))
286
+ return 0
287
+
288
+ seen = set()
289
+ for index, question in enumerate(questions):
290
+ if not isinstance(question, dict):
291
+ errors.append(_error("QUESTION_INVALID", filename, "题目 #{} 必须是对象".format(index)))
292
+ continue
293
+ question_id = question.get("question_id")
294
+ if not isinstance(question_id, str) or not question_id:
295
+ errors.append(_error("QUESTION_INVALID", filename, "题目缺少 question_id"))
296
+ continue
297
+ if question_id in seen:
298
+ errors.append(_error("QUESTION_DUPLICATE", filename, "题目 ID 重复:{}".format(question_id)))
299
+ seen.add(question_id)
300
+
301
+ if question.get("role_family") not in role_ids:
302
+ errors.append(_error("ROLE_UNKNOWN", filename, "{} role_family 未登记".format(question_id)))
303
+ if question.get("level") not in level_ids:
304
+ errors.append(_error("LEVEL_UNKNOWN", filename, "{} level 未登记".format(question_id)))
305
+ if question.get("kind") not in QUESTION_KINDS:
306
+ errors.append(_error("QUESTION_KIND_INVALID", filename, "{} kind 非法".format(question_id)))
307
+ if question.get("status") not in QUESTION_STATUSES:
308
+ errors.append(_error("QUESTION_STATUS_INVALID", filename, "{} status 非法".format(question_id)))
309
+ for field in ("dimension", "prompt", "answer_boundary"):
310
+ if not isinstance(question.get(field), str) or not question[field].strip():
311
+ errors.append(_error("QUESTION_FIELD_MISSING", filename, "{} 缺少 {}".format(question_id, field)))
312
+ for field in ("expected_evidence", "followups", "source_refs"):
313
+ if not isinstance(question.get(field), list):
314
+ errors.append(_error("QUESTION_FIELD_MISSING", filename, "{} 缺少 {}".format(question_id, field)))
315
+
316
+ source_refs = question.get("source_refs")
317
+ refs = source_refs if isinstance(source_refs, list) else []
318
+ if any(not isinstance(item, str) or not item for item in refs):
319
+ errors.append(_error(
320
+ "QUESTION_SOURCE_REF_INVALID",
321
+ filename,
322
+ "{} source_refs 只能包含非空字符串".format(question_id),
323
+ ))
324
+ refs = [item for item in refs if isinstance(item, str) and item]
325
+ missing_refs = [item for item in refs if item not in sources]
326
+ for source_id in missing_refs:
327
+ errors.append(_error(
328
+ "QUESTION_SOURCE_MISSING",
329
+ filename,
330
+ "{} 引用了不存在的来源 {}".format(question_id, source_id),
331
+ ))
332
+ existing = [sources[item] for item in refs if item in sources]
333
+ if not any(item.get("layer") in {"A", "B"} for item in existing):
334
+ errors.append(_error(
335
+ "QUESTION_SOURCE_WEAK",
336
+ filename,
337
+ "{} 至少需要一个 A 或 B 层来源".format(question_id),
338
+ ))
339
+ if any(item.get("status") != "active" for item in existing):
340
+ errors.append(_error(
341
+ "QUESTION_SOURCE_INACTIVE",
342
+ filename,
343
+ "{} 引用了非 active 来源".format(question_id),
344
+ ))
345
+
346
+ verified = _parse_date(
347
+ question.get("last_verified_at"),
348
+ filename,
349
+ "last_verified_at",
350
+ errors,
351
+ )
352
+ stale_after = question.get("stale_after_days")
353
+ if not isinstance(stale_after, int) or isinstance(stale_after, bool) or stale_after < 1:
354
+ errors.append(_error(
355
+ "QUESTION_STALE_POLICY_INVALID",
356
+ filename,
357
+ "{} stale_after_days 必须是正整数".format(question_id),
358
+ ))
359
+ elif verified is not None and (today - verified).days > stale_after:
360
+ if question.get("freshness_label") == "latest":
361
+ errors.append(_error(
362
+ "QUESTION_STALE",
363
+ filename,
364
+ "{} 已过期,不能标记为 latest".format(question_id),
365
+ ))
366
+
367
+ expected_hash = question.get("content_hash")
368
+ actual_hash = _canonical_hash(question)
369
+ if expected_hash != actual_hash:
370
+ errors.append(_error(
371
+ "QUESTION_HASH_MISMATCH",
372
+ filename,
373
+ "{} content_hash 不匹配".format(question_id),
374
+ ))
375
+ return len(questions)
376
+
377
+
378
+ def _validate_ledger(data, sources, errors):
379
+ filename = "evidence-ledger.json"
380
+ if data is None:
381
+ return
382
+ _validate_header(data, filename, errors)
383
+ entries = data.get("entries")
384
+ if not isinstance(entries, list):
385
+ errors.append(_error("LEDGER_INVALID", filename, "entries 必须是数组"))
386
+ return
387
+ seen = set()
388
+ for index, entry in enumerate(entries):
389
+ if not isinstance(entry, dict):
390
+ errors.append(_error("LEDGER_INVALID", filename, "证据 #{} 必须是对象".format(index)))
391
+ continue
392
+ evidence_id = entry.get("evidence_id")
393
+ if evidence_id in seen:
394
+ errors.append(_error("EVIDENCE_DUPLICATE", filename, "证据 ID 重复:{}".format(evidence_id)))
395
+ seen.add(evidence_id)
396
+ for field in EVIDENCE_REQUIRED_FIELDS:
397
+ if field not in entry:
398
+ errors.append(_error(
399
+ "LEDGER_FIELD_MISSING",
400
+ filename,
401
+ "{} 缺少 {}".format(evidence_id or index, field),
402
+ ))
403
+ if entry.get("responsibility") not in RESPONSIBILITY_VALUES:
404
+ errors.append(_error("LEDGER_RESPONSIBILITY_INVALID", filename, "{} responsibility 非法".format(evidence_id or index)))
405
+ if entry.get("sensitivity") not in SENSITIVITY_VALUES:
406
+ errors.append(_error("LEDGER_SENSITIVITY_INVALID", filename, "{} sensitivity 非法".format(evidence_id or index)))
407
+ actions = entry.get("actions")
408
+ if not isinstance(actions, list) or not actions:
409
+ errors.append(_error("LEDGER_ACTIONS_MISSING", filename, "{} actions 不能为空".format(evidence_id or index)))
410
+ if not isinstance(entry.get("user_confirmed"), bool):
411
+ errors.append(_error(
412
+ "LEDGER_FIELD_TYPE_INVALID",
413
+ filename,
414
+ "{} user_confirmed 必须是布尔值".format(evidence_id or index),
415
+ ))
416
+ if not isinstance(entry.get("export_allowed"), bool):
417
+ errors.append(_error(
418
+ "LEDGER_FIELD_TYPE_INVALID",
419
+ filename,
420
+ "{} export_allowed 必须是布尔值".format(evidence_id or index),
421
+ ))
422
+ if entry.get("user_confirmed") is False and entry.get("export_allowed") is True:
423
+ errors.append(_error(
424
+ "LEDGER_UNCONFIRMED_EXPORT",
425
+ filename,
426
+ "{} 未确认事实不得进入导出".format(evidence_id or index),
427
+ ))
428
+ for source_id in entry.get("source_refs", []) if isinstance(entry.get("source_refs"), list) else []:
429
+ if source_id not in sources:
430
+ errors.append(_error(
431
+ "LEDGER_SOURCE_MISSING",
432
+ filename,
433
+ "{} 引用了不存在的来源 {}".format(evidence_id or index, source_id),
434
+ ))
435
+
436
+
437
+ def _validate_dual_role(data, errors):
438
+ filename = "dual-role-contract.json"
439
+ if data is None:
440
+ return
441
+ _validate_header(data, filename, errors)
442
+ if data.get("default_policy") != "deny":
443
+ errors.append(_error("DEFAULT_POLICY_INVALID", filename, "default_policy 必须为 deny"))
444
+ if data.get("roles") != ["candidate", "hr"]:
445
+ errors.append(_error("ROLES_INVALID", filename, "roles 必须为 candidate / hr"))
446
+ data_classes = data.get("data_classes")
447
+ if (
448
+ not isinstance(data_classes, list)
449
+ or any(not isinstance(item, str) for item in data_classes)
450
+ or set(data_classes) != REQUIRED_DATA_CLASSES
451
+ ):
452
+ errors.append(_error("DATA_CLASSES_INVALID", filename, "data_classes 必须精确覆盖固定数据类"))
453
+ permissions = data.get("permissions")
454
+ if not isinstance(permissions, dict):
455
+ errors.append(_error("PERMISSIONS_INVALID", filename, "permissions 必须是对象"))
456
+ permissions = {}
457
+ for role in ("candidate", "hr"):
458
+ if not isinstance(permissions.get(role), dict):
459
+ errors.append(_error("PERMISSIONS_INVALID", filename, "缺少 {} 权限".format(role)))
460
+
461
+ hr = permissions.get("hr", {}) if isinstance(permissions.get("hr"), dict) else {}
462
+ allowed_actions = {"read", "write"}
463
+ for role_name in ("candidate", "hr"):
464
+ role_permissions = permissions.get(role_name)
465
+ if not isinstance(role_permissions, dict):
466
+ continue
467
+ if set(role_permissions) != REQUIRED_DATA_CLASSES:
468
+ errors.append(_error(
469
+ "PERMISSIONS_INVALID",
470
+ filename,
471
+ "{} 权限必须精确覆盖固定数据类".format(role_name),
472
+ ))
473
+ for data_class, actions in role_permissions.items():
474
+ if not isinstance(actions, list) or any(
475
+ action not in allowed_actions for action in actions
476
+ ):
477
+ errors.append(_error(
478
+ "ROLE_ACTION_INVALID",
479
+ filename,
480
+ "{} 的 {} 权限包含非法动作".format(role_name, data_class),
481
+ ))
482
+ for data_class in ("private_evidence_ledger", "raw_resume", "analysis_report"):
483
+ if hr.get(data_class):
484
+ errors.append(_error(
485
+ "ROLE_ACCESS_DENIED",
486
+ filename,
487
+ "HR 不得读取 {}".format(data_class),
488
+ ))
489
+ candidate = permissions.get("candidate", {}) if isinstance(permissions.get("candidate"), dict) else {}
490
+ if not {"read", "write"}.issubset(set(candidate.get("private_evidence_ledger", []))):
491
+ errors.append(_error(
492
+ "CANDIDATE_ACCESS_REQUIRED",
493
+ filename,
494
+ "候选人必须可读写私有证据账本",
495
+ ))
496
+
497
+ protected = data.get("protected_attributes")
498
+ if not isinstance(protected, list) or not protected:
499
+ errors.append(_error("PROTECTED_ATTRIBUTES_INVALID", filename, "受保护属性不能为空"))
500
+ protected = []
501
+ scoring = data.get("scoring_fields")
502
+ if not isinstance(scoring, list):
503
+ errors.append(_error("SCORING_FIELDS_INVALID", filename, "scoring_fields 必须是数组"))
504
+ scoring = []
505
+ overlap = set(protected) & set(scoring)
506
+ if overlap:
507
+ errors.append(_error(
508
+ "PROTECTED_ATTRIBUTE_SCORED",
509
+ filename,
510
+ "受保护属性进入评分:{}".format(", ".join(sorted(overlap))),
511
+ ))
512
+
513
+ export = data.get("cross_role_export")
514
+ if not isinstance(export, dict):
515
+ errors.append(_error(
516
+ "CROSS_ROLE_CONFIRMATION_REQUIRED",
517
+ filename,
518
+ "缺少 cross_role_export 契约",
519
+ ))
520
+ return
521
+ required_true = (
522
+ "requires_field_manifest",
523
+ "requires_confirmation",
524
+ "independent_workdirs",
525
+ "independent_outputs",
526
+ )
527
+ if any(export.get(field) is not True for field in required_true):
528
+ errors.append(_error(
529
+ "CROSS_ROLE_CONFIRMATION_REQUIRED",
530
+ filename,
531
+ "跨角色导出必须保留字段清单、确认和独立目录输出",
532
+ ))
533
+ if export.get("default_export_class") != "public_resume":
534
+ errors.append(_error(
535
+ "CROSS_ROLE_DEFAULT_INVALID",
536
+ filename,
537
+ "跨角色默认导出只能是 public_resume",
538
+ ))
539
+
540
+
541
+ def validate_contracts(root=None, today=None):
542
+ """Return a deterministic, local-only contract validation report."""
543
+ base = Path(root) if root else Path(__file__).resolve().parent.parent / "data"
544
+ if (base / "data" / "security-role-map.json").is_file() and not (base / "security-role-map.json").is_file():
545
+ base = base / "data"
546
+ current = today or dt.date.today()
547
+ if isinstance(current, str):
548
+ try:
549
+ current = dt.date.fromisoformat(current)
550
+ except ValueError:
551
+ return {
552
+ "ok": False,
553
+ "contract_version": CONTRACT_VERSION,
554
+ "checked_files": 0,
555
+ "role_family_count": 0,
556
+ "level_count": 0,
557
+ "question_count": 0,
558
+ "source_count": 0,
559
+ "errors": [_error(
560
+ "TODAY_INVALID",
561
+ "--today",
562
+ "today 必须是 YYYY-MM-DD 格式的有效日期",
563
+ )],
564
+ "warnings": [],
565
+ }
566
+
567
+ errors = []
568
+ loaded = {}
569
+ for filename in CONTRACT_FILES:
570
+ data = _read_json(base / filename, errors)
571
+ if data is not None:
572
+ loaded[filename] = data
573
+
574
+ _validate_schema_files(loaded, errors)
575
+ role_ids, level_ids = _validate_role_map(
576
+ loaded.get("security-role-map.json"),
577
+ errors,
578
+ )
579
+ sources = _validate_sources(
580
+ loaded.get("source-registry.json"),
581
+ current,
582
+ errors,
583
+ )
584
+ question_count = _validate_questions(
585
+ loaded.get("question-bank.json"),
586
+ role_ids,
587
+ level_ids,
588
+ sources,
589
+ current,
590
+ errors,
591
+ )
592
+ _validate_ledger(
593
+ loaded.get("evidence-ledger.json"),
594
+ sources,
595
+ errors,
596
+ )
597
+ _validate_dual_role(
598
+ loaded.get("dual-role-contract.json"),
599
+ errors,
600
+ )
601
+
602
+ errors.sort(key=lambda item: (item["path"], item["code"], item["message"]))
603
+ return {
604
+ "ok": not errors,
605
+ "contract_version": CONTRACT_VERSION,
606
+ "checked_files": len(CONTRACT_FILES),
607
+ "role_family_count": len(role_ids),
608
+ "level_count": len(level_ids),
609
+ "question_count": question_count,
610
+ "source_count": len(sources),
611
+ "errors": errors,
612
+ "warnings": [],
613
+ }
614
+
615
+
616
+ def _render_text(report):
617
+ lines = [
618
+ "元简数据契约校验",
619
+ "状态:{}".format("PASS" if report["ok"] else "FAIL"),
620
+ "契约版本:{}".format(report["contract_version"]),
621
+ "文件:{}".format(report["checked_files"]),
622
+ "岗位族:{}".format(report["role_family_count"]),
623
+ "职级:{}".format(report["level_count"]),
624
+ "题目:{}".format(report["question_count"]),
625
+ "来源:{}".format(report["source_count"]),
626
+ ]
627
+ if report["errors"]:
628
+ lines.append("错误:")
629
+ for item in report["errors"]:
630
+ lines.append("- [{}] {}: {}".format(item["code"], item["path"], item["message"]))
631
+ return "\n".join(lines)
632
+
633
+
634
+ def build_parser():
635
+ parser = argparse.ArgumentParser(
636
+ prog="contract-validate",
637
+ description="离线校验元简岗位族、证据账本、题库、来源与双角色权限契约。",
638
+ )
639
+ parser.add_argument(
640
+ "--root",
641
+ default=str(Path(__file__).resolve().parent.parent / "data"),
642
+ help="data 目录或技能根目录",
643
+ )
644
+ parser.add_argument("--format", choices=("json", "text"), default="json")
645
+ parser.add_argument("--today", help="覆盖校验日期(YYYY-MM-DD),用于测试与回放")
646
+ return parser
647
+
648
+
649
+ def main(argv=None):
650
+ args = build_parser().parse_args(argv)
651
+ report = validate_contracts(args.root, args.today)
652
+ if args.format == "json":
653
+ print(json.dumps(report, ensure_ascii=False, indent=2))
654
+ else:
655
+ print(_render_text(report))
656
+ if report["ok"]:
657
+ return 0
658
+ if any(item["code"] == "TODAY_INVALID" for item in report["errors"]):
659
+ return 2
660
+ return 1
661
+
662
+
663
+ if __name__ == "__main__":
664
+ sys.exit(main())