Spaces:
Sleeping
Sleeping
Commit ·
0bed39d
1
Parent(s): b9cd345
L2 front matter language authority and delivery-first hardening (#131)
Browse files- L2 front matter language authority and delivery-first hardening (207951ed6eedb3458ec1984f69a86e4b696c50c6)
Files changed (3)
- core/generation_runner.py+215-44
- core/pipeline_agent.py+137-14
- core/production_guard.py+84-38
1809 unmodified lines18101811181218131814181582 unmodified lines1898189919001901190219031904190519061907779 unmodified lines2687268826892690269126925 unmodified lines2698269927002701270227032704270527 unmodified lines27332734273527362737273827392740274127423 unmodified lines274627472748274927502751275245 unmodified lines27982799280028012802280328042805280628072808280928104 unmodified lines281528162817281828192820282125 unmodified lines2847284828492850285128522853104 unmodified lines29582959296029612962296329641364 unmodified lines432943304331433243334334161 unmodified lines449644974498449945004501450219 unmodified lines452245234524452545264527452824 unmodified lines455345544555455645574558455939 unmodified lines459946004601460246034604460514 unmodified lines4620462146224623462446254626188 unmodified lines4815481648174818481948204821112 unmodified lines493449354936493749384939494016 unmodified lines495749584959496049614962496349644965496649674968496915 unmodified lines4985498649874988498949904991196 unmodified lines51885189519051915192519351948 unmodified lines520352045205520652075208520911 unmodified lines522152225223522452255226522714 unmodified lines524252435244524552465247524839 unmodified lines52885289529052915292529352941145 unmodified lines64406441644264436444644564465 unmodified lines645264536454645564566457645864596460646112 unmodified lines647464756476647764786479648064816482648321 unmodified lines65056506650765086509651065115 unmodified lines65176518651965206521652265236524652565266 unmodified lines653365346535653665376538653965406541654244 unmodified lines658765886589659065916592659322 unmodified lines66166617661866196620662166226623662466256626662712 unmodified lines6640664166426643664466451809 unmodified linesreturn rows@staticmethoddef _section_retry_feedback(violations, *, limit=8) -> str:rows = []82 unmodified lines))return "FATAL" if core_citation_section else "ADVISORY"# Unknown validation types remain fail-closed. This keeps C5.5 from# silently downgrading a future integrity contract merely because it is# new to the severity registry.return "FATAL"@staticmethoddef _section_violation_lineage(row) -> str:779 unmodified lines"""return str(topic or "").strip(), str(keywords or "").strip()@staticmethoddef _resolved_front_matter_keyword_policy(data_metadata: dict):"""Resolve one policy object for Working/Final/retry/resume/fallback paths."""5 unmodified lines@staticmethoddef _front_matter_keyword_fallback_terms(data_metadata: dict):"""Derive recoverable generated keywords only from frozen study-design authority."""meta = dict(data_metadata or {})contract = dict(meta.get("study_design_contract") or {})values = []quant = dict(contract.get("quantitative") or {})27 unmodified linespolicy = keyword_policy_from_contract(contract)if str(policy.get("authority_source") or "").upper() != "USER_EXPLICIT":return []return apply_keyword_policy(intent.get("source_keywords") or [],policy,authoritative=intent.get("source_keywords") or [],)@staticmethod3 unmodified linescontract = dict(meta.get("study_design_contract") or meta.get("front_matter_contract") or {})intent = dict(contract.get("user_research_intent") or meta.get("user_research_intent") or {})policy = keyword_policy_from_contract(contract)authoritative = list(intent.get("source_keywords") or [])values = apply_keyword_policy(candidate_keywords,policy,45 unmodified lines@staticmethoddef _target_keyword_heading_aliases(target_lang: str) -> list[str]:code = str(target_lang or '').strip().casefold().replace('_', '-')if code.startswith('zh'):return ['关键词', '关键字']if code.startswith('ru'):return ['Ключевые слова']if code.startswith('kk') or code.startswith('kz'):return ['Түйін сөздер', 'Кілт сөздер']return ['Keywords']4 unmodified linesmeta = dict(data_metadata or {})contract = dict(meta.get('study_design_contract') or {})intent = dict(contract.get('user_research_intent') or meta.get('user_research_intent') or {})source_keywords = list(intent.get('source_keywords') or contract.get('source_keywords') or [])mapping = dict(glossary or {})diagnostics = []25 unmodified linesvalues = [str(row.get('label') or '') for row in construct_rows if role in (row.get('roles') or []) and row.get('label')]if len(values) == 1:role_label[role] = re.sub(r'\s+', ' ', str(mapping.get(values[0]) or values[0])).strip()code = str(target_lang or '').strip().casefold().replace('_', '-')suffixes = []if 'moderation' in missing:label = role_label.get('moderator') or ''104 unmodified lines# R7-R2C-R5: user keywords are research-intent identities, not expendable# planning seeds. Freeze them for multilingual inheritance while still# distinguishing them from empirical construct roles.intent_keywords = list(user_intent.get('source_keywords') or [])if not intent_keywords:intent_keywords = parse_keyword_terms(keywords, explicit_user=True)for seed in intent_keywords:1364 unmodified linesstate.pop("effective_topic", None)state.pop("effective_keywords", None)hypothesis_ledger = dict(data_metadata.get("hypothesis_ledger") or {}) if mode == "amj" else {}hypothesis_contract = self._hypothesis_contract_directive(hypothesis_ledger)if hypothesis_ledger:161 unmodified linesworking_front_error = Nonetry:working_front = agent.generate_working_front_matter(topic, keywords, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),19 unmodified lines)if not working_abstract or not working_keywords:fallback = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(fallback.get("abstract") or "").strip()working_keywords = list(fallback.get("keywords") or [])24 unmodified lines)try:working_front = agent.generate_working_front_matter(topic, keywords, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode, validation_feedback=feedback,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),39 unmodified lines})if not working_abstract or not working_keywords:fallback = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(fallback.get("abstract") or "").strip()working_keywords = list(fallback.get("keywords") or [])14 unmodified linesplan = agent.generate_outline(topic, keywords, mode=mode, data_metadata=data_metadata)# User title is reader-facing authority. Outline planning may adapt# structure but may not silently rename the study.en_topic = str(source_topic or topic).strip()structure = plan.get("structure", [])full_draft_en = (f"# {en_topic}\n\n## Abstract\n{working_abstract}\n\n"188 unmodified lineselse:full_draft_en = str(state.get("full_draft_en") or "")if str(data_metadata.get("source_type") or "") == "system_generated" and mode == "amj":full_draft_en = self._replace_title(full_draft_en, topic)canonical_resume_keywords = self._canonical_quantitative_front_matter_keywords(mode, [], data_metadata)112 unmodified linesfeedback = self._section_retry_feedback(resumed_front_rows)try:working_front = agent.generate_working_front_matter(topic, keywords, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode, validation_feedback=feedback,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),16 unmodified linestype(exc).__name__,)fallback = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)candidate_abstract = str(fallback.get("abstract") or "").strip()candidate_keywords = list(fallback.get("keywords") or [])if not candidate_abstract or not candidate_keywords:fallback = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)candidate_abstract = str(fallback.get("abstract") or "").strip()candidate_keywords = list(fallback.get("keywords") or [])15 unmodified lineslogging.warning("Adaptive resumed Working Abstract accepted with residual diagnostics | count=%s", len(residual_front_rows))if not candidate_abstract:fallback = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)candidate_abstract = str(fallback.get("abstract") or "").strip()candidate_keywords = list(fallback.get("keywords") or candidate_keywords)196 unmodified linesif not working_abstract and not state.get("english_finalized"):try:working_front = agent.generate_working_front_matter(topic, keywords, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),8 unmodified linestype(exc).__name__,)working_front = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)quality_diagnostics.append({"scope": "delivery_first_working_front_matter_fallback",11 unmodified lines)if not working_abstract or not working_keywords:working_front = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(working_front.get("abstract") or "").strip()working_keywords = list(working_front.get("keywords") or [])14 unmodified linesfeedback = self._section_retry_feedback(front_fact_rows)try:working_front = agent.generate_working_front_matter(topic, keywords, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode, validation_feedback=feedback,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),39 unmodified lines})if not working_abstract or not working_keywords:working_front = self._deterministic_working_front_matter(mode, topic, keywords, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(working_front.get("abstract") or "").strip()working_keywords = list(working_front.get("keywords") or [])1145 unmodified linesself._progress(92, "final_front_matter")try:final_front = agent.generate_final_front_matter(topic, keywords, body_only, data_evidence=user_data_md, mode=mode,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),keyword_policy=self._resolved_front_matter_keyword_policy(data_metadata),5 unmodified lines)final_front = {"abstract": self._deterministic_final_abstract(mode, source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger),"keywords": self._canonical_quantitative_front_matter_keywords(mode, parse_keyword_terms(source_keywords or keywords, explicit_user=True), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata),}self._record_adaptive_completion_residual(12 unmodified lines)if not final_abstract or not final_keywords:final_abstract = final_abstract or self._deterministic_final_abstract(mode, source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger)final_keywords = final_keywords or self._canonical_quantitative_front_matter_keywords(mode, parse_keyword_terms(source_keywords or keywords, explicit_user=True), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata)self._record_adaptive_completion_residual(quality_notes, [{21 unmodified lines)try:final_front = agent.generate_final_front_matter(topic, keywords, body_only, data_evidence=user_data_md, mode=mode,validation_feedback=feedback, hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),keyword_policy=self._resolved_front_matter_keyword_policy(data_metadata),5 unmodified lines)final_front = {"abstract": self._deterministic_final_abstract(mode, source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger),"keywords": final_keywords or self._canonical_quantitative_front_matter_keywords(mode, parse_keyword_terms(source_keywords or keywords, explicit_user=True), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata),}final_abstract = str(final_front.get("abstract") or "").strip()6 unmodified lines)if not final_abstract or not final_keywords:final_abstract = final_abstract or self._deterministic_final_abstract(mode, source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger)final_keywords = final_keywords or self._canonical_quantitative_front_matter_keywords(mode, parse_keyword_terms(source_keywords or keywords, explicit_user=True), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata)self._record_adaptive_completion_residual(quality_notes, [{44 unmodified lines)if residual_final_rows:deterministic_abstract = self._deterministic_final_abstract(mode, source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger)hard_rows = self._study_fact_violations(mode, agent, quant_engine, deterministic_abstract, data_metadata, section_name="Final Abstract"22 unmodified lines"examples":final_front_fact_rows[:3],})state.pop("final_abstract_retry_exhausted", None)final_title = str(source_topic or topic or "").strip()if mode == "amj" and str(data_metadata.get("source_type") or "") == "system_generated":semantic_contract = dict(data_metadata.get("front_matter_contract") or {})reconciled_front = agent.reconcile_quantitative_reader_front_matter(topic=source_topic, keywords=source_keywords, contract=semantic_contract,manuscript=body_only,)candidate_title = re.sub(r"\s+", " ", str(reconciled_front.get("title") or "")).strip()candidate_keywords = self._canonical_quantitative_front_matter_keywords(12 unmodified linesfull_draft_en = replace_abstract(full_draft_en, final_abstract)full_draft_en = self._replace_title(full_draft_en, final_title)full_draft_en = self._replace_keywords(full_draft_en, final_keywords)if mode == "amj" and hypothesis_ledger:post_front_hypothesis_rows = self._hypothesis_contract_violations(full_draft_en, hypothesis_ledger, section_name="Full Manuscript", require_all=True1809 unmodified lines1810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187182 unmodified lines19541955195619571958195919601961196219631964779 unmodified lines27442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528165 unmodified lines28222823282428252826282728282829283028312832283327 unmodified lines2861286228632864286528662867286828692870287128723 unmodified lines2876287728782879288028812882288345 unmodified lines292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329544 unmodified lines295929602961296229632964296529662967296829692970297125 unmodified lines2997299829993000300130023003104 unmodified lines310831093110311131123113311431151364 unmodified lines448044814482448344844485448644874488448944904491449244934494161 unmodified lines465646574658465946604661466219 unmodified lines468246834684468546864687468824 unmodified lines471347144715471647174718471939 unmodified lines475947604761476247634764476514 unmodified lines4780478147824783478447854786188 unmodified lines4975497649774978497949804981112 unmodified lines509450955096509750985099510016 unmodified lines511751185119512051215122512351245125512651275128512915 unmodified lines5145514651475148514951505151196 unmodified lines53485349535053515352535353548 unmodified lines536353645365536653675368536911 unmodified lines538153825383538453855386538714 unmodified lines540254035404540554065407540839 unmodified lines54485449545054515452545354541145 unmodified lines66006601660266036604660566065 unmodified lines661266136614661566166617661866196620662112 unmodified lines663466356636663766386639664066416642664321 unmodified lines66656666666766686669667066715 unmodified lines66776678667966806681668266836684668566866 unmodified lines669366946695669666976698669967006701670244 unmodified lines674767486749675067516752675322 unmodified lines67766777677867796780678167826783678467856786678712 unmodified lines680068016802680368046805680668076808680968106811681268136814681568161809 unmodified linesreturn rowsdef _delivery_first_final_abstract_language_guard(self, *, mode: str, agent, quant_engine, final_abstract: str, reader_topic_en: str,final_title: str, data_metadata: dict, hypothesis_ledger: dict | None, quality_notes: list,) -> tuple[str, bool]:"""Repair residual non-English script without turning a reader-surface defect into P0 failure.Returns ``(abstract, rebuilt)``. Explicit P1 integrity validators remainauthoritative; only the language-surface defect is downgraded when aprovider-neutral clean reconstruction cannot be proven safe."""current = str(final_abstract or "").strip()if not agent._english_reader_surface_has_foreign_script(current):return current, Falselanguage_fallback = self._deterministic_final_abstract(mode, reader_topic_en or final_title, data_metadata, hypothesis_ledger=hypothesis_ledger)language_rows = self._study_fact_violations(mode, agent, quant_engine, language_fallback, data_metadata, section_name="Final Abstract")if hypothesis_ledger:language_rows.extend(self._hypothesis_contract_violations(language_fallback, hypothesis_ledger, section_name="Final Abstract"))language_rows.extend(self._final_abstract_finding_violations(mode, language_fallback, data_metadata, hypothesis_ledger=hypothesis_ledger))fatal_language_rows, advisory_language_rows = self._partition_section_violations(language_rows, section_name="Final Abstract", mode=mode, exhausted=True)if (language_fallbackand not agent._english_reader_surface_has_foreign_script(language_fallback)and not fatal_language_rows):self._record_adaptive_completion_residual(quality_notes,advisory_language_rows + [{"type": "final_english_front_matter_language_fallback","reason": "Residual non-English script in the Final Abstract was replaced by a deterministic English reconstruction from frozen research authority."}],section_name="Final Abstract",stage="delivery_first_front_matter_language_fallback",)return language_fallback, Trueself._record_adaptive_completion_residual(quality_notes, [{"type": "final_english_front_matter_language_warning","reason": "Final Abstract still contains non-English script after deterministic language fallback; delivery was preserved under the P0 Delivery-First contract."}],section_name="Final Abstract",stage="delivery_first_front_matter_language_warning",)return current, False@staticmethoddef _section_retry_feedback(violations, *, limit=8) -> str:rows = []82 unmodified lines))return "FATAL" if core_citation_section else "ADVISORY"# Delivery-First hardening: unknown/new validators are not allowed to# create an accidental terminal path merely because a developer forgot# to register their severity. Only explicit P1/hard-failure identities# above may remain fatal after bounded repair.return "ADVISORY"@staticmethoddef _section_violation_lineage(row) -> str:779 unmodified lines"""return str(topic or "").strip(), str(keywords or "").strip()@staticmethoddef _front_matter_language_projection_hash(topic: str, keywords) -> str:terms = parse_keyword_terms(keywords, explicit_user=True)payload = json.dumps({"title": str(topic or "").strip(), "keywords": terms},ensure_ascii=False, sort_keys=True, separators=(",", ":"),).encode("utf-8")return hashlib.sha256(payload).hexdigest()def _resolve_english_front_matter_projection(self, agent, state: dict, data_metadata: dict, source_topic: str, source_keywords) -> dict:"""Resolve/cache a language-only English projection without mutating user intent."""meta = dict(data_metadata or {})contract = dict(meta.get("study_design_contract") or meta.get("front_matter_contract") or {})intent = dict(contract.get("user_research_intent") or meta.get("user_research_intent") or {})semantic_title = str(intent.get("source_topic") or source_topic or "").strip()semantic_keywords = list(intent.get("source_keywords") or parse_keyword_terms(source_keywords, explicit_user=True))source_hash = self._front_matter_language_projection_hash(semantic_title, semantic_keywords)expected_count = len(semantic_keywords)cached = dict(state.get("front_matter_language_projection")or meta.get("front_matter_language_projection")or {})if (cached.get("version") == "front-matter-language-authority-v1"and cached.get("source_hash") == source_hash):try:validated = agent.validate_reader_facing_english_projection(cached, expected_keyword_count=expected_count)return {"version": "front-matter-language-authority-v1","source_hash": source_hash,"english_title": validated["title"],"english_keywords": list(validated["keywords"]),"translation_applied": bool(cached.get("translation_applied")),}except Exception as exc:logging.warning("Cached English front-matter language projection invalid; rebuilding | error=%s",type(exc).__name__,)resolved = agent.normalize_reader_facing_front_matter_to_english(semantic_title, semantic_keywords)validated = agent.validate_reader_facing_english_projection(resolved, expected_keyword_count=expected_count)projection = {"version": "front-matter-language-authority-v1","source_hash": source_hash,"english_title": validated["title"],"english_keywords": list(validated["keywords"]),"translation_applied": bool(resolved.get("translation_applied")),}# Presentation projection is additive metadata only. Original source_topic# and source_keywords inside user_research_intent remain byte-for-byte authority.data_metadata["front_matter_language_projection"] = dict(projection)state["front_matter_language_projection"] = dict(projection)state["data_metadata"] = data_metadatareturn projection@staticmethoddef _resolved_front_matter_keyword_policy(data_metadata: dict):"""Resolve one policy object for Working/Final/retry/resume/fallback paths."""5 unmodified lines@staticmethoddef _front_matter_keyword_fallback_terms(data_metadata: dict):"""Derive recoverable English reader keywords from frozen study-design authority."""meta = dict(data_metadata or {})projection = dict(meta.get("front_matter_language_projection") or {})projected = [str(item).strip() for item in (projection.get("english_keywords") or []) if str(item).strip()]if projected:return projectedcontract = dict(meta.get("study_design_contract") or {})values = []quant = dict(contract.get("quantitative") or {})27 unmodified linespolicy = keyword_policy_from_contract(contract)if str(policy.get("authority_source") or "").upper() != "USER_EXPLICIT":return []projection = dict(meta.get("front_matter_language_projection") or {})authoritative = list(projection.get("english_keywords") or intent.get("source_keywords") or [])return apply_keyword_policy(authoritative,policy,authoritative=authoritative,)@staticmethod3 unmodified linescontract = dict(meta.get("study_design_contract") or meta.get("front_matter_contract") or {})intent = dict(contract.get("user_research_intent") or meta.get("user_research_intent") or {})policy = keyword_policy_from_contract(contract)projection = dict(meta.get("front_matter_language_projection") or {})authoritative = list(projection.get("english_keywords") or intent.get("source_keywords") or [])values = apply_keyword_policy(candidate_keywords,policy,45 unmodified lines@staticmethoddef _target_front_matter_language_code(target_lang: str) -> str:value = str(target_lang or '').strip().casefold().replace('_', '-')if value.startswith('zh') or 'chinese' in value or '中文' in value or '简体中文' in value:return 'zh'if value.startswith('ru') or 'russian' in value or 'рус' in value:return 'ru'if value.startswith('kk') or value.startswith('kz') or 'kazakh' in value or 'қазақ' in value:return 'kk'if value.startswith('en') or 'english' in value:return 'en'return value@classmethoddef _target_keyword_heading_aliases(cls, target_lang: str) -> list[str]:code = cls._target_front_matter_language_code(target_lang)if code == 'zh':return ['关键词', '关键字']if code == 'ru':return ['Ключевые слова']if code == 'kk':return ['Түйін сөздер', 'Кілт сөздер']return ['Keywords']4 unmodified linesmeta = dict(data_metadata or {})contract = dict(meta.get('study_design_contract') or {})intent = dict(contract.get('user_research_intent') or meta.get('user_research_intent') or {})projection = dict(meta.get('front_matter_language_projection') or {})source_keywords = list(projection.get('english_keywords')or intent.get('source_keywords')or contract.get('source_keywords')or [])mapping = dict(glossary or {})diagnostics = []25 unmodified linesvalues = [str(row.get('label') or '') for row in construct_rows if role in (row.get('roles') or []) and row.get('label')]if len(values) == 1:role_label[role] = re.sub(r'\s+', ' ', str(mapping.get(values[0]) or values[0])).strip()code = cls._target_front_matter_language_code(target_lang)suffixes = []if 'moderation' in missing:label = role_label.get('moderator') or ''104 unmodified lines# R7-R2C-R5: user keywords are research-intent identities, not expendable# planning seeds. Freeze them for multilingual inheritance while still# distinguishing them from empirical construct roles.projection = dict(meta.get('front_matter_language_projection') or {})intent_keywords = list(projection.get('english_keywords') or user_intent.get('source_keywords') or [])if not intent_keywords:intent_keywords = parse_keyword_terms(keywords, explicit_user=True)for seed in intent_keywords:1364 unmodified linesstate.pop("effective_topic", None)state.pop("effective_keywords", None)front_matter_projection = self._resolve_english_front_matter_projection(agent, state, data_metadata, source_topic, source_keywords)reader_topic_en = str(front_matter_projection.get("english_title") or source_topic or topic or "").strip()reader_keywords_en = list(front_matter_projection.get("english_keywords") or [])reader_keywords_prompt = "; ".join(reader_keywords_en)data_metadata["front_matter_language_projection"] = dict(front_matter_projection)state["data_metadata"] = data_metadatahypothesis_ledger = dict(data_metadata.get("hypothesis_ledger") or {}) if mode == "amj" else {}hypothesis_contract = self._hypothesis_contract_directive(hypothesis_ledger)if hypothesis_ledger:161 unmodified linesworking_front_error = Nonetry:working_front = agent.generate_working_front_matter(reader_topic_en, reader_keywords_prompt, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),19 unmodified lines)if not working_abstract or not working_keywords:fallback = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(fallback.get("abstract") or "").strip()working_keywords = list(fallback.get("keywords") or [])24 unmodified lines)try:working_front = agent.generate_working_front_matter(reader_topic_en, reader_keywords_prompt, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode, validation_feedback=feedback,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),39 unmodified lines})if not working_abstract or not working_keywords:fallback = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(fallback.get("abstract") or "").strip()working_keywords = list(fallback.get("keywords") or [])14 unmodified linesplan = agent.generate_outline(topic, keywords, mode=mode, data_metadata=data_metadata)# User title is reader-facing authority. Outline planning may adapt# structure but may not silently rename the study.en_topic = str(reader_topic_en or source_topic or topic).strip()structure = plan.get("structure", [])full_draft_en = (f"# {en_topic}\n\n## Abstract\n{working_abstract}\n\n"188 unmodified lineselse:full_draft_en = str(state.get("full_draft_en") or "")if str(data_metadata.get("source_type") or "") == "system_generated" and mode == "amj":full_draft_en = self._replace_title(full_draft_en, reader_topic_en)canonical_resume_keywords = self._canonical_quantitative_front_matter_keywords(mode, [], data_metadata)112 unmodified linesfeedback = self._section_retry_feedback(resumed_front_rows)try:working_front = agent.generate_working_front_matter(reader_topic_en, reader_keywords_prompt, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode, validation_feedback=feedback,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),16 unmodified linestype(exc).__name__,)fallback = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)candidate_abstract = str(fallback.get("abstract") or "").strip()candidate_keywords = list(fallback.get("keywords") or [])if not candidate_abstract or not candidate_keywords:fallback = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)candidate_abstract = str(fallback.get("abstract") or "").strip()candidate_keywords = list(fallback.get("keywords") or [])15 unmodified lineslogging.warning("Adaptive resumed Working Abstract accepted with residual diagnostics | count=%s", len(residual_front_rows))if not candidate_abstract:fallback = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)candidate_abstract = str(fallback.get("abstract") or "").strip()candidate_keywords = list(fallback.get("keywords") or candidate_keywords)196 unmodified linesif not working_abstract and not state.get("english_finalized"):try:working_front = agent.generate_working_front_matter(reader_topic_en, reader_keywords_prompt, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),8 unmodified linestype(exc).__name__,)working_front = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)quality_diagnostics.append({"scope": "delivery_first_working_front_matter_fallback",11 unmodified lines)if not working_abstract or not working_keywords:working_front = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(working_front.get("abstract") or "").strip()working_keywords = list(working_front.get("keywords") or [])14 unmodified linesfeedback = self._section_retry_feedback(front_fact_rows)try:working_front = agent.generate_working_front_matter(reader_topic_en, reader_keywords_prompt, research_logic_contract, synthesis_result,data_evidence=planning_data_md, mode=mode, validation_feedback=feedback,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),39 unmodified lines})if not working_abstract or not working_keywords:working_front = self._deterministic_working_front_matter(mode, reader_topic_en, reader_keywords_prompt, data_metadata, hypothesis_ledger=hypothesis_ledger)working_abstract = str(working_front.get("abstract") or "").strip()working_keywords = list(working_front.get("keywords") or [])1145 unmodified linesself._progress(92, "final_front_matter")try:final_front = agent.generate_final_front_matter(reader_topic_en, reader_keywords_prompt, body_only, data_evidence=user_data_md, mode=mode,hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),keyword_policy=self._resolved_front_matter_keyword_policy(data_metadata),5 unmodified lines)final_front = {"abstract": self._deterministic_final_abstract(mode, reader_topic_en or source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger),"keywords": self._canonical_quantitative_front_matter_keywords(mode, list(reader_keywords_en), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata),}self._record_adaptive_completion_residual(12 unmodified lines)if not final_abstract or not final_keywords:final_abstract = final_abstract or self._deterministic_final_abstract(mode, reader_topic_en or source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger)final_keywords = final_keywords or self._canonical_quantitative_front_matter_keywords(mode, list(reader_keywords_en), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata)self._record_adaptive_completion_residual(quality_notes, [{21 unmodified lines)try:final_front = agent.generate_final_front_matter(reader_topic_en, reader_keywords_prompt, body_only, data_evidence=user_data_md, mode=mode,validation_feedback=feedback, hypothesis_contract=hypothesis_contract,authoritative_keywords=self._user_authoritative_front_matter_keywords(data_metadata),keyword_policy=self._resolved_front_matter_keyword_policy(data_metadata),5 unmodified lines)final_front = {"abstract": self._deterministic_final_abstract(mode, reader_topic_en or source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger),"keywords": final_keywords or self._canonical_quantitative_front_matter_keywords(mode, list(reader_keywords_en), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata),}final_abstract = str(final_front.get("abstract") or "").strip()6 unmodified lines)if not final_abstract or not final_keywords:final_abstract = final_abstract or self._deterministic_final_abstract(mode, reader_topic_en or source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger)final_keywords = final_keywords or self._canonical_quantitative_front_matter_keywords(mode, list(reader_keywords_en), data_metadata) or self._front_matter_keyword_fallback_terms(data_metadata)self._record_adaptive_completion_residual(quality_notes, [{44 unmodified lines)if residual_final_rows:deterministic_abstract = self._deterministic_final_abstract(mode, reader_topic_en or source_topic or topic, data_metadata, hypothesis_ledger=hypothesis_ledger)hard_rows = self._study_fact_violations(mode, agent, quant_engine, deterministic_abstract, data_metadata, section_name="Final Abstract"22 unmodified lines"examples":final_front_fact_rows[:3],})state.pop("final_abstract_retry_exhausted", None)final_title = str(reader_topic_en or source_topic or topic or "").strip()if mode == "amj" and str(data_metadata.get("source_type") or "") == "system_generated":semantic_contract = dict(data_metadata.get("front_matter_contract") or {})reconciled_front = agent.reconcile_quantitative_reader_front_matter(topic=source_topic, keywords=source_keywords, contract=semantic_contract,manuscript=body_only, reader_title=reader_topic_en, reader_keywords=reader_keywords_en,)candidate_title = re.sub(r"\s+", " ", str(reconciled_front.get("title") or "")).strip()candidate_keywords = self._canonical_quantitative_front_matter_keywords(12 unmodified linesfull_draft_en = replace_abstract(full_draft_en, final_abstract)full_draft_en = self._replace_title(full_draft_en, final_title)full_draft_en = self._replace_keywords(full_draft_en, final_keywords)agent.validate_reader_facing_english_projection({"title": final_title, "keywords": final_keywords},expected_keyword_count=(len(reader_keywords_en) if reader_keywords_en else None),)final_abstract, language_rebuilt = self._delivery_first_final_abstract_language_guard(mode=mode, agent=agent, quant_engine=quant_engine, final_abstract=final_abstract,reader_topic_en=reader_topic_en, final_title=final_title, data_metadata=data_metadata,hypothesis_ledger=hypothesis_ledger, quality_notes=quality_notes,)if language_rebuilt:full_draft_en = replace_abstract(full_draft_en, final_abstract)if mode == "amj" and hypothesis_ledger:post_front_hypothesis_rows = self._hypothesis_contract_violations(full_draft_en, hypothesis_ledger, section_name="Full Manuscript", require_all=True
1639 unmodified lines16401641164216431644164533 unmodified lines167916801681168216831684190 unmodified lines18751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189811 unmodified lines191019111912191319141915191682 unmodified lines19992000200120022003200420057 unmodified lines20132014201520162017201820198 unmodified lines202820292030203120322033203430 unmodified lines206520662067206820692070207113 unmodified lines2085208620872088208920901639 unmodified linesreturn cleaned@staticmethoddef _front_matter_has_citation(value):text = str(value or '')33 unmodified linesword_count = cls._working_abstract_word_count(text)if cls._front_matter_has_citation(text):raise DeepSeekRequestError('Working Abstract must not contain citations.')forbidden = (('RESULT_ASSERTION', r'\bwe\s+(?:find|found|show|demonstrate|observe|establish)\b'),('RESULT_ASSERTION', r'\b(?:results?|findings?)\s+(?:show|indicate|reveal|demonstrate|confirm|support)\b'),190 unmodified linesreturn issuesdef reconcile_quantitative_reader_front_matter(self, *, topic, keywords, contract, manuscript=""):"""Preserve R5 user intent while retaining legacy contract reconciliation.Contracts that carry ``user_research_intent`` are authoritative: thefinalizer must not repair an upstream design mismatch by silentlyrenaming the user study. Older contracts without that explicit R5authority retain the pre-R5 bounded reconciliation path so historicalcheckpoints and compatibility behavior remain stable."""record = dict(contract or {})intent = dict(record.get("user_research_intent") or {})policy = keyword_policy_from_contract(record, fallback_keywords=keywords)source_topic = str(intent.get("source_topic") or record.get("source_topic") or topic or "").strip()source_keywords = list(intent.get("source_keywords") or [])if str(policy.get("authority_source") or "").upper() == "USER_EXPLICIT" and source_keywords:return {"title": source_topic,"keywords": apply_keyword_policy(source_keywords, policy, authoritative=source_keywords),}# No explicit user keyword authority: retain user-authoritative title when11 unmodified lineslogging.warning("Front-matter semantic contract missing frozen constructs; using degraded fallback.")fallback = self._quantitative_front_matter_fallback(record)if intent and source_topic:fallback["title"] = source_topicreturn fallbacksource_keywords = list(record.get("source_keywords") or [])82 unmodified linesextra = [str(item).strip() for item in ((critic or {}).get("unmeasured_focal_constructs") or []) if str(item).strip()]missing = [str(item).strip() for item in ((critic or {}).get("missing_frozen_constructs") or []) if str(item).strip()]if not invalid and not extra and not missing:resolved_title = source_topic if intent else re.sub(r"\s+", " ", str(candidate.get("title") or "")).strip()return {"title": resolved_title,"keywords": apply_keyword_policy(candidate.get("keywords") or [], policy),7 unmodified linesfallback = self._quantitative_front_matter_fallback(record)if intent and source_topic:fallback["title"] = source_topiclogging.warning("Adaptive front-matter reconciliation exhausted; using deterministic degraded fallback instead of failing manuscript generation.")return fallback8 unmodified linesprompt = f"""Create WORKING front matter for an empirical {str(mode).upper()}-oriented manuscript before body drafting.Return JSON only: {{\"abstract\":\"...\",\"keywords\":[\"...\"]}}.Aim for approximately 120-180 English words, have no citations, and function only as a continuity anchor. Word count is guidance, not a failure condition; prioritize Conciseness, Accuracy, and Rigor over mechanical compliance. It may state the research problem, theoretical tension, focal concepts, question/hypothesis architecture, design or method class, and intended contribution domain. It MUST NOT state coefficients, p-values, fit statistics, sample statistics unless already indispensable to define the design, supported/unsupported hypotheses, result direction, substantive findings, or a conclusion that has not yet been frozen. Do not predict findings.Preserve the user keyword identities and research scope. Do not silently replace, delete, or reinterpret an explicit construct/relation because direct literature support is sparse. The user-supplied keyword list is authoritative for reader-facing keyword identity; wording changes belong only to target-language translation.TOPIC: {topic}USER KEYWORDS: {keywords}<PROVISIONAL_RESEARCH_LOGIC>30 unmodified linesprompt = f"""Write FINAL English front matter for this completed {str(mode).upper()} manuscript.Return JSON only: {{\"abstract\":\"...\",\"keywords\":[\"...\"]}}.Aim for a concise Abstract of roughly 120-200 words, use no citations, and accurately state the research problem, validated design, main frozen finding(s), and contribution. Word count is guidance, not a failure condition; prioritize Conciseness, Accuracy, and Rigor. Include only the minimum numerical evidence required; do not list coefficients, p-values, and fit statistics unless one value is indispensable. Do not infer beyond the frozen evidence or completed manuscript.Preserve the user keyword identities and research scope. Do not silently replace, delete, or reinterpret an explicit construct/relation because direct literature support is sparse. The user-supplied keyword list is authoritative for reader-facing keyword identity; wording changes belong only to target-language translation.TOPIC: {topic}USER KEYWORDS: {keywords}<FROZEN_RESEARCH_EVIDENCE>13 unmodified linesabstract = re.sub(r'(?im)^#+\s*abstract\s*', '', str(parsed.get('abstract') or '')).strip()if self._front_matter_has_citation(abstract):raise DeepSeekRequestError('Final Abstract must not contain citations.')meta_findings = self.inspect_authorial_ai_meta(abstract)if meta_findings:raise DeepSeekRequestError('Final Abstract contains high-confidence authorial AI-writing meta-commentary.')1639 unmodified lines16401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175633 unmodified lines17901791179217931794179517961797190 unmodified lines198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201511 unmodified lines202720282029203020312032203382 unmodified lines21162117211821192120212121227 unmodified lines213021312132213321342135213621372138213921408 unmodified lines214921502151215221532154215530 unmodified lines218621872188218921902191219213 unmodified lines220622072208220922102211221222131639 unmodified linesreturn cleaned@staticmethoddef _english_reader_surface_has_foreign_script(value):"""Return True only for scripts that cannot remain in an English reader-facing surface.User intent may be entered in Chinese, Russian, or Kazakh, but the Englishmanuscript projection must not leak Han or Cyrillic source text. Latinacronyms, numerals, punctuation, and ordinary English remain untouched."""return bool(re.search(r'[\u3400-\u9fff\u3040-\u30ff\u0400-\u052f]', str(value or '')))@classmethoddef validate_reader_facing_english_projection(cls, projection, *, expected_keyword_count=None):"""Validate a language projection without changing the user's semantic authority."""record = dict(projection or {})title = str(record.get('title') or record.get('english_title') or '').strip()raw_keywords = record.get('keywords')if raw_keywords is None:raw_keywords = record.get('english_keywords')keywords = [str(item).strip() for item in (raw_keywords or []) if str(item).strip()]if not title:raise DeepSeekRequestError('English reader-facing title is empty.')if expected_keyword_count is not None and len(keywords) != int(expected_keyword_count):raise DeepSeekRequestError(f'English reader-facing keyword cardinality changed: expected={int(expected_keyword_count)} observed={len(keywords)}.')combined = ' '.join([title] + keywords)if cls._english_reader_surface_has_foreign_script(combined):raise DeepSeekRequestError('English reader-facing title/keywords contain untranslated Han or Cyrillic source text.')return {'title': title, 'keywords': keywords}def normalize_reader_facing_front_matter_to_english(self, topic, keywords):"""Create a faithful English language projection of user Title/Keywords.The original user strings remain semantic authority in the study contract.This method is presentation-only: English input is passed through without amodel call; non-English/mixed-script input is translated, never optimized.Keyword cardinality and order are invariant."""source_title = str(topic or '').strip()source_keywords = parse_keyword_terms(keywords, explicit_user=True)if not source_title:raise DeepSeekRequestError('User research title is empty before English language projection.')source_surface = ' '.join([source_title] + source_keywords)if not self._english_reader_surface_has_foreign_script(source_surface):return {'title': source_title,'keywords': list(source_keywords),'translation_applied': False,}indexed_keywords = [{'index': index, 'text': value}for index, value in enumerate(source_keywords, start=1)]payload = {'title': source_title, 'keywords': indexed_keywords}base_prompt = f"""Translate ONLY the supplied user research Title and Keywords into academic English.Return JSON only: {{"title":"...","keywords":["..."]}}.LANGUAGE-AUTHORITY CONTRACT:1. This is translation, not title optimization, rewriting, topic expansion, or keyword generation.2. Preserve the complete research meaning: focal constructs, direction/relationship wording, mediator/moderator roles, population/context, method qualifiers, acronyms, numbers, and scope.3. Do not add, delete, merge, split, reorder, generalize, specialize, or reinterpret any keyword. Return exactly {len(source_keywords)} keywords in the supplied order.4. Preserve existing English technical identities and acronyms. Translate/transliterate Han or Cyrillic reader-facing text so the returned Title/Keywords contain no Chinese, Russian, or Kazakh script.5. Do not mention the translation process and do not wrap JSON in Markdown.<SOURCE_USER_FRONT_MATTER>{json.dumps(payload, ensure_ascii=False)}</SOURCE_USER_FRONT_MATTER>"""current_prompt = base_promptlast_error = Nonefor local_attempt in range(2):response = self.call_deepseek('You are a precise academic translator. Preserve research semantics exactly and change only language surface.',current_prompt,max_tokens=max(700, min(1600, 500 + len(source_keywords) * 90)),temp=0.0,model_role='writing',thinking=False,allow_fallback=False,response_format={'type': 'json_object'},logical_node='front_matter_writing',)try:parsed = self._extract_json_from_text(response)if not isinstance(parsed, dict):raise DeepSeekRequestError('English front-matter language projection was not valid JSON.')candidate = self.validate_reader_facing_english_projection(parsed, expected_keyword_count=len(source_keywords))return {'title': candidate['title'],'keywords': candidate['keywords'],'translation_applied': True,}except DeepSeekRequestError as exc:last_error = excif local_attempt >= 1:raiselogging.warning('English front-matter language projection retry | attempt=%s/2 | reason=%s',local_attempt + 1, self._safe_source_error(exc),)current_prompt = base_prompt + ('\n\nLOCAL VALIDATION RETRY: The prior response violated the language/cardinality contract. ''Return a fresh complete JSON object only. Translate the same Title and the same indexed Keywords ''faithfully into English, preserve keyword order/count exactly, and remove all Han/Cyrillic source text. ''Do not optimize or rewrite the research intent.')raise DeepSeekRequestError(f'English front-matter language projection failed: {last_error}')@staticmethoddef _front_matter_has_citation(value):text = str(value or '')33 unmodified linesword_count = cls._working_abstract_word_count(text)if cls._front_matter_has_citation(text):raise DeepSeekRequestError('Working Abstract must not contain citations.')if cls._english_reader_surface_has_foreign_script(text):raise DeepSeekRequestError('Working Abstract contains untranslated Han or Cyrillic source text.')forbidden = (('RESULT_ASSERTION', r'\bwe\s+(?:find|found|show|demonstrate|observe|establish)\b'),('RESULT_ASSERTION', r'\b(?:results?|findings?)\s+(?:show|indicate|reveal|demonstrate|confirm|support)\b'),190 unmodified linesreturn issuesdef reconcile_quantitative_reader_front_matter(self, *, topic, keywords, contract, manuscript="", reader_title=None, reader_keywords=None):"""Preserve source semantic authority while allowing a faithful English surface.``user_research_intent`` remains the immutable semantic authority. When``reader_title``/``reader_keywords`` are supplied they are a language-onlyEnglish projection of that same authority; they may change script/languagebut not constructs, relations, scope, order, or keyword cardinality."""record = dict(contract or {})intent = dict(record.get("user_research_intent") or {})policy = keyword_policy_from_contract(record, fallback_keywords=keywords)source_topic = str(intent.get("source_topic") or record.get("source_topic") or topic or "").strip()source_keywords = list(intent.get("source_keywords") or [])reader_source_topic = str(reader_title or source_topic or topic or "").strip()reader_source_keywords = parse_keyword_terms(reader_keywords, explicit_user=True) if reader_keywords is not None else list(source_keywords)if str(policy.get("authority_source") or "").upper() == "USER_EXPLICIT" and source_keywords:authoritative_reader = reader_source_keywords or source_keywordsreturn {"title": reader_source_topic,"keywords": apply_keyword_policy(authoritative_reader, policy, authoritative=authoritative_reader),}# No explicit user keyword authority: retain user-authoritative title when11 unmodified lineslogging.warning("Front-matter semantic contract missing frozen constructs; using degraded fallback.")fallback = self._quantitative_front_matter_fallback(record)if intent and source_topic:fallback["title"] = reader_source_topicreturn fallbacksource_keywords = list(record.get("source_keywords") or [])82 unmodified linesextra = [str(item).strip() for item in ((critic or {}).get("unmeasured_focal_constructs") or []) if str(item).strip()]missing = [str(item).strip() for item in ((critic or {}).get("missing_frozen_constructs") or []) if str(item).strip()]if not invalid and not extra and not missing:resolved_title = reader_source_topic if intent else re.sub(r"\s+", " ", str(candidate.get("title") or "")).strip()return {"title": resolved_title,"keywords": apply_keyword_policy(candidate.get("keywords") or [], policy),7 unmodified linesfallback = self._quantitative_front_matter_fallback(record)if intent and source_topic:fallback["title"] = reader_source_topicif str(policy.get("authority_source") or "").upper() == "USER_EXPLICIT" and reader_source_keywords:fallback["keywords"] = apply_keyword_policy(reader_source_keywords, policy, authoritative=reader_source_keywords)logging.warning("Adaptive front-matter reconciliation exhausted; using deterministic degraded fallback instead of failing manuscript generation.")return fallback8 unmodified linesprompt = f"""Create WORKING front matter for an empirical {str(mode).upper()}-oriented manuscript before body drafting.Return JSON only: {{\"abstract\":\"...\",\"keywords\":[\"...\"]}}.Aim for approximately 120-180 English words, have no citations, and function only as a continuity anchor. Word count is guidance, not a failure condition; prioritize Conciseness, Accuracy, and Rigor over mechanical compliance. It may state the research problem, theoretical tension, focal concepts, question/hypothesis architecture, design or method class, and intended contribution domain. It MUST NOT state coefficients, p-values, fit statistics, sample statistics unless already indispensable to define the design, supported/unsupported hypotheses, result direction, substantive findings, or a conclusion that has not yet been frozen. Do not predict findings.Preserve the supplied English keyword identities and research scope. They are a faithful language projection of the user input. Do not silently replace, delete, reorder, or reinterpret an explicit construct/relation because direct literature support is sparse. Do not translate them back into the source input language.TOPIC: {topic}USER KEYWORDS: {keywords}<PROVISIONAL_RESEARCH_LOGIC>30 unmodified linesprompt = f"""Write FINAL English front matter for this completed {str(mode).upper()} manuscript.Return JSON only: {{\"abstract\":\"...\",\"keywords\":[\"...\"]}}.Aim for a concise Abstract of roughly 120-200 words, use no citations, and accurately state the research problem, validated design, main frozen finding(s), and contribution. Word count is guidance, not a failure condition; prioritize Conciseness, Accuracy, and Rigor. Include only the minimum numerical evidence required; do not list coefficients, p-values, and fit statistics unless one value is indispensable. Do not infer beyond the frozen evidence or completed manuscript.Preserve the supplied English keyword identities and research scope. They are a faithful language projection of the user input. Do not silently replace, delete, reorder, or reinterpret an explicit construct/relation because direct literature support is sparse. Do not translate them back into the source input language.TOPIC: {topic}USER KEYWORDS: {keywords}<FROZEN_RESEARCH_EVIDENCE>13 unmodified linesabstract = re.sub(r'(?im)^#+\s*abstract\s*', '', str(parsed.get('abstract') or '')).strip()if self._front_matter_has_citation(abstract):raise DeepSeekRequestError('Final Abstract must not contain citations.')if self._english_reader_surface_has_foreign_script(abstract):raise DeepSeekRequestError('Final Abstract contains untranslated Han or Cyrillic source text.')meta_findings = self.inspect_authorial_ai_meta(abstract)if meta_findings:raise DeepSeekRequestError('Final Abstract contains high-confidence authorial AI-writing meta-commentary.')
847 unmodified lines8488498508518528535 unmodified lines8598608618628638649 unmodified lines87487587687787887988088188288388488534 unmodified lines92092192292392492592692792892993093193293393493593693793893994094113 unmodified lines95595695795895996034 unmodified lines9959969979989991000117 unmodified lines11181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311542 unmodified lines1157115811591160116111628 unmodified lines117111721173117411751176117711781179118011811182118311841185847 unmodified linesreturn visible_label_for_language(filename)def _validate_zip_bytes(zip_bytes: bytes,*,5 unmodified linesquantitative_manifest: dict[str, Any] | None,qualitative_mode: bool,safe_mode: bool,) -> None:try:with zipfile.ZipFile(io.BytesIO(zip_bytes), "r") as archive:9 unmodified linesfor name in (english_filename, translated_filename):archived_docx = archive.read(name)validate_docx_bytes(archived_docx)try:validate_aigc_output_label_resilient(archived_docx, expected_visible_label=_aigc_visible_label_for_docx(name))except Exception as exc:raise OutputValidationError(f"Archived DOCX AI output label invalid: {exc}") from excif quantitative_manifest:archived_markdown = english_markdown if name == english_filename else translated_markdownvalidate_quantitative_table_contract(34 unmodified linestranslated_docx = _render_delivery_docx(translated_markdown, qualitative_mode=qualitative_mode, safe_mode=safe_mode,)# E3-B: label only the already-rendered delivery artifact. Manuscript# Markdown, generation, translation and academic-content gates stay frozen.try:english_label = _aigc_visible_label_for_docx(english_filename)translated_label = _aigc_visible_label_for_docx(translated_filename)english_docx = ensure_aigc_output_label(english_docx, visible_label=english_label)translated_docx = ensure_aigc_output_label(translated_docx, visible_label=translated_label)except Exception as exc:raise OutputValidationError(f"Post-generation AI output labeling failed: {exc}") from excvalidate_docx_bytes(english_docx)validate_docx_bytes(translated_docx)try:validate_aigc_output_label_resilient(english_docx, expected_visible_label=english_label)validate_aigc_output_label_resilient(translated_docx, expected_visible_label=translated_label)except Exception as exc:raise OutputValidationError(f"Post-generation AI output label validation failed: {exc}") from excquantitative_manifest = ((data_metadata or {}).get("quantitative_table_manifest")13 unmodified linesappendix_prefix = "Appendix/" if organize_appendix else ""notes = list(quality_notes or [])if safe_mode:notes.append({"severity": "ADVISORY",34 unmodified linesquantitative_manifest=quantitative_manifest,qualitative_mode=qualitative_mode,safe_mode=safe_mode,)return PackageResult(zip_bytes=zip_bytes,117 unmodified linesraise OutputValidationError("Recovery package requires a materially complete frozen English manuscript.")try:english_docx = _render_delivery_docx(english, qualitative_mode=False, safe_mode=True)english_label = _aigc_visible_label_for_docx(english_filename)english_docx = ensure_aigc_output_label(english_docx, visible_label=english_label)validate_docx_bytes(english_docx)validate_aigc_output_label_resilient(english_docx, expected_visible_label=english_label)except Exception:english_docx = _plain_recovery_docx(english)english_label = _aigc_visible_label_for_docx(english_filename)english_docx = ensure_aigc_output_label(english_docx, visible_label=english_label)validate_docx_bytes(english_docx)validate_aigc_output_label_resilient(english_docx, expected_visible_label=english_label)entries: dict[str, bytes] = {english_filename: english_docx}target = str(translated_markdown or "").strip()if len(target) >= 800:try:target_docx = _render_delivery_docx(target, qualitative_mode=False, safe_mode=True)target_label = _aigc_visible_label_for_docx(translated_filename)target_docx = ensure_aigc_output_label(target_docx, visible_label=target_label)validate_docx_bytes(target_docx)validate_aigc_output_label_resilient(target_docx, expected_visible_label=target_label)except Exception:try:target_docx = _plain_recovery_docx(target)target_label = _aigc_visible_label_for_docx(translated_filename)target_docx = ensure_aigc_output_label(target_docx, visible_label=target_label)validate_docx_bytes(target_docx)validate_aigc_output_label_resilient(target_docx, expected_visible_label=target_label)except Exception:target_docx = b""if target_docx:entries[translated_filename] = target_docxnote = ("SmartPaper Recovery Package\n\n"2 unmodified lines"This recovery artifact must not be represented as a completed paid paper.\n\n"f"Terminal detail: {str(error_detail or '')[:1000]}\n")entries["RECOVERY_NOTES.txt"] = note.encode("utf-8")manifest = _manifest(entries)entries["FILE_MANIFEST_SHA256.txt"] = manifest.encode("utf-8")8 unmodified linesraise OutputValidationError(f"Recovery ZIP integrity failed at {bad}.")archived_english = archive.read(english_filename)validate_docx_bytes(archived_english)validate_aigc_output_label_resilient(archived_english, expected_visible_label=_aigc_visible_label_for_docx(english_filename))if translated_filename in archive.namelist():archived_target = archive.read(translated_filename)validate_docx_bytes(archived_target)validate_aigc_output_label_resilient(archived_target, expected_visible_label=_aigc_visible_label_for_docx(translated_filename))return PackageResult(zip_bytes=zip_bytes,file_names=tuple(sorted(entries)),847 unmodified lines8488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868875 unmodified lines8938948958968978988999 unmodified lines90991091191291391491591691791891992092134 unmodified lines95695795895996096196296396496596696796896997097197297397497597613 unmodified lines99099199299399499599699799834 unmodified lines1033103410351036103710381039117 unmodified lines1157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111922 unmodified lines1195119611971198119912001201120212031204120512068 unmodified lines12151216121712181219122012211222122312241225122612271228122912301231847 unmodified linesreturn visible_label_for_language(filename)def _apply_aigc_label_delivery_first(docx_bytes: bytes, filename: str):"""Apply/validate the AI-output label without making it a delivery blocker.The label subsystem already has two independent writer/validator paths. Ifboth mechanisms fail unexpectedly, P0 Delivery-First keeps the alreadyvalidated DOCX bytes and records an advisory. Academic manuscript text andP1 result/reference identity are never changed by this fallback."""original = bytes(docx_bytes or b"")validate_docx_bytes(original)label = _aigc_visible_label_for_docx(filename)try:labeled = ensure_aigc_output_label(original, visible_label=label)validate_docx_bytes(labeled)validate_aigc_output_label_resilient(labeled, expected_visible_label=label)return labeled, label, True, Noneexcept Exception as exc:# Never keep a partially-mutated artifact after label failure. Reuse the# pre-label DOCX only after independently proving it still opens.validate_docx_bytes(original)warning = {"severity": "ADVISORY","section": "Output package","issue_type": "aigc_output_label_best_effort_fallback","detail": ("AI output labeling could not be completed after the independent label "f"fallbacks ({type(exc).__name__}). The validated pre-label DOCX was preserved ""so generation/download was not interrupted."),"user_action": "Add/verify the required AI-output label before external distribution if this warning appears.",}return original, label, False, warningdef _validate_zip_bytes(zip_bytes: bytes,*,5 unmodified linesquantitative_manifest: dict[str, Any] | None,qualitative_mode: bool,safe_mode: bool,aigc_label_status: dict[str, bool] | None = None,) -> None:try:with zipfile.ZipFile(io.BytesIO(zip_bytes), "r") as archive:9 unmodified linesfor name in (english_filename, translated_filename):archived_docx = archive.read(name)validate_docx_bytes(archived_docx)if (aigc_label_status or {}).get(name, True):try:validate_aigc_output_label_resilient(archived_docx, expected_visible_label=_aigc_visible_label_for_docx(name))except Exception as exc:raise OutputValidationError(f"Archived DOCX AI output label invalid: {exc}") from excif quantitative_manifest:archived_markdown = english_markdown if name == english_filename else translated_markdownvalidate_quantitative_table_contract(34 unmodified linestranslated_docx = _render_delivery_docx(translated_markdown, qualitative_mode=qualitative_mode, safe_mode=safe_mode,)# E3-B/E3-C + Delivery-First hardening: label only the already-rendered# delivery artifact. A total label-subsystem failure is advisory rather than# a reason to destroy an otherwise valid downloadable paper.english_docx, english_label, english_labeled, english_label_warning = _apply_aigc_label_delivery_first(english_docx, english_filename)translated_docx, translated_label, translated_labeled, translated_label_warning = _apply_aigc_label_delivery_first(translated_docx, translated_filename)validate_docx_bytes(english_docx)validate_docx_bytes(translated_docx)aigc_label_status = {english_filename: bool(english_labeled),translated_filename: bool(translated_labeled),}quantitative_manifest = ((data_metadata or {}).get("quantitative_table_manifest")13 unmodified linesappendix_prefix = "Appendix/" if organize_appendix else ""notes = list(quality_notes or [])for label_warning in (english_label_warning, translated_label_warning):if label_warning:notes.append(label_warning)if safe_mode:notes.append({"severity": "ADVISORY",34 unmodified linesquantitative_manifest=quantitative_manifest,qualitative_mode=qualitative_mode,safe_mode=safe_mode,aigc_label_status=aigc_label_status,)return PackageResult(zip_bytes=zip_bytes,117 unmodified linesraise OutputValidationError("Recovery package requires a materially complete frozen English manuscript.")try:english_docx = _render_delivery_docx(english, qualitative_mode=False, safe_mode=True)validate_docx_bytes(english_docx)except Exception:english_docx = _plain_recovery_docx(english)validate_docx_bytes(english_docx)english_docx, english_label, english_labeled, english_label_warning = _apply_aigc_label_delivery_first(english_docx, english_filename)entries: dict[str, bytes] = {english_filename: english_docx}recovery_label_status = {english_filename: bool(english_labeled)}recovery_label_warnings = [english_label_warning] if english_label_warning else []target = str(translated_markdown or "").strip()if len(target) >= 800:try:target_docx = _render_delivery_docx(target, qualitative_mode=False, safe_mode=True)validate_docx_bytes(target_docx)except Exception:try:target_docx = _plain_recovery_docx(target)validate_docx_bytes(target_docx)except Exception:target_docx = b""if target_docx:target_docx, target_label, target_labeled, target_label_warning = _apply_aigc_label_delivery_first(target_docx, translated_filename)entries[translated_filename] = target_docxrecovery_label_status[translated_filename] = bool(target_labeled)if target_label_warning:recovery_label_warnings.append(target_label_warning)note = ("SmartPaper Recovery Package\n\n"2 unmodified lines"This recovery artifact must not be represented as a completed paid paper.\n\n"f"Terminal detail: {str(error_detail or '')[:1000]}\n")if recovery_label_warnings:note += ("\nAI-output labeling warning: the label subsystem failed after independent fallbacks. ""The validated pre-label DOCX was preserved so the recovery download remains usable. ""Add/verify the required AI-output label before external distribution.\n")entries["RECOVERY_NOTES.txt"] = note.encode("utf-8")manifest = _manifest(entries)entries["FILE_MANIFEST_SHA256.txt"] = manifest.encode("utf-8")8 unmodified linesraise OutputValidationError(f"Recovery ZIP integrity failed at {bad}.")archived_english = archive.read(english_filename)validate_docx_bytes(archived_english)if recovery_label_status.get(english_filename, True):validate_aigc_output_label_resilient(archived_english, expected_visible_label=_aigc_visible_label_for_docx(english_filename))if translated_filename in archive.namelist():archived_target = archive.read(translated_filename)validate_docx_bytes(archived_target)if recovery_label_status.get(translated_filename, True):validate_aigc_output_label_resilient(archived_target, expected_visible_label=_aigc_visible_label_for_docx(translated_filename))return PackageResult(zip_bytes=zip_bytes,file_names=tuple(sorted(entries)),
core/generation_runner.py+215-44
core/pipeline_agent.py+137-14
core/production_guard.py+84-38