clouds-coder 2026.10.31__tar.gz → 2026.11.4__tar.gz

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.
Files changed (130) hide show
  1. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/Clouds_Coder.py +1175 -307
  2. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/PKG-INFO +1 -1
  3. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/clouds_coder.egg-info/PKG-INFO +1 -1
  4. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/clouds_coder.egg-info/SOURCES.txt +4 -0
  5. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/pyproject.toml +1 -1
  6. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_ide_v2.py +1 -1
  7. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_json_restart_defenses.py +16 -0
  8. clouds_coder-2026.11.4/tests/test_l3_l4_todo_runtime.py +244 -0
  9. clouds_coder-2026.11.4/tests/test_semantic_task_routing.py +365 -0
  10. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_session_llm_concurrency.py +61 -11
  11. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_shared_context_runtime.py +56 -0
  12. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_single_no_plan_todo_bootstrap.py +1 -1
  13. clouds_coder-2026.11.4/tests/test_skill_execution_permissions.py +278 -0
  14. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_thinking_only_recovery.py +4 -11
  15. clouds_coder-2026.11.4/tests/test_todo_finish_mode_matrix.py +176 -0
  16. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_todo_llm_budget.py +18 -7
  17. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_todo_short_ids.py +3 -5
  18. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_todo_tree_revision_guard.py +1 -1
  19. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/.github/workflows/python-app.yml +0 -0
  20. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/.github/workflows/python-publish.yml +0 -0
  21. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/LICENSE +0 -0
  22. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/MANIFEST.in +0 -0
  23. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/README-ja.md +0 -0
  24. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/README-zh.md +0 -0
  25. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/README.md +0 -0
  26. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/RELEASE_NOTES.md +0 -0
  27. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/Split Tools/run_split.bat +0 -0
  28. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/Split Tools/run_split.command +0 -0
  29. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/Split Tools/run_split.py +0 -0
  30. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/Split Tools/run_split.sh +0 -0
  31. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/Split Tools/split_coder.py +0 -0
  32. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/clouds_coder.egg-info/dependency_links.txt +0 -0
  33. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/clouds_coder.egg-info/entry_points.txt +0 -0
  34. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/clouds_coder.egg-info/requires.txt +0 -0
  35. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/clouds_coder.egg-info/top_level.txt +0 -0
  36. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/docs/liquid_kernel_delivery_verification_20261030.md +0 -0
  37. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/README.md +0 -0
  38. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/__init__.py +0 -0
  39. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/agentic.py +0 -0
  40. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/context.py +0 -0
  41. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/control.py +0 -0
  42. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/execution.py +0 -0
  43. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/liquid_kernel/models.py +0 -0
  44. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-03-07.md +0 -0
  45. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-03-16.md +0 -0
  46. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-03-20.md +0 -0
  47. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-03-25.md +0 -0
  48. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-03-31.md +0 -0
  49. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-05-02.md +0 -0
  50. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-05-28.md +0 -0
  51. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-06-05.md +0 -0
  52. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-06-22.md +0 -0
  53. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-08-10.md +0 -0
  54. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-08-16.md +0 -0
  55. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-08-20.md +0 -0
  56. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-09-12.md +0 -0
  57. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/log/CHANGELOG-2026-10-30.md +0 -0
  58. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/requirements.txt +0 -0
  59. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/ruff.toml +0 -0
  60. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/setup.cfg +0 -0
  61. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/split_coder.py +0 -0
  62. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/conftest.py +0 -0
  63. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_acceptance_portability.py +0 -0
  64. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_admin_bootstrap_compatibility.py +0 -0
  65. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_admin_i18n.py +0 -0
  66. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_admin_output_limits.py +0 -0
  67. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_agentic_evolution.py +0 -0
  68. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_agentic_flow_compatibility.py +0 -0
  69. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_authoritative_prompt_delivery.py +0 -0
  70. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_cache_runtime.py +0 -0
  71. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_candidate_retention.py +0 -0
  72. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_collaboration.py +0 -0
  73. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_context_auto_compact.py +0 -0
  74. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_context_memory_recall.py +0 -0
  75. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_cross_platform_runtime.py +0 -0
  76. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_dynamic_agent_loop.py +0 -0
  77. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_evaluator_transport_defenses.py +0 -0
  78. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_evolution_browser.py +0 -0
  79. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_evolution_integration.py +0 -0
  80. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_evolution_policy_safety.py +0 -0
  81. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_evolution_progress.py +0 -0
  82. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_external_skill_permissions.py +0 -0
  83. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_http_incomplete_read.py +0 -0
  84. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_kernel_bootstrap.py +0 -0
  85. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_kernel_restart_persistence.py +0 -0
  86. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_kimi_tool_history_compat.py +0 -0
  87. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_liquid_kernel.py +0 -0
  88. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_live_harness_repairs.py +0 -0
  89. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_long_content_enrichment_pileup.py +0 -0
  90. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_mcp_workspace_trust.py +0 -0
  91. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_model_configuration.py +0 -0
  92. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_native_output_recovery.py +0 -0
  93. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_optimization_opportunities.py +0 -0
  94. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_optional_evolution_quotas.py +0 -0
  95. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_outcome_scoring.py +0 -0
  96. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_pair_deployment_policy.py +0 -0
  97. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_plan_structure.py +0 -0
  98. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_plan_todo_progression.py +0 -0
  99. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_portable_capabilities.py +0 -0
  100. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_process_manager.py +0 -0
  101. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_prompt_enhancement_recovery.py +0 -0
  102. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_proposal_schema_recovery.py +0 -0
  103. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_rag_admin_auth.py +0 -0
  104. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_read_compaction_visibility.py +0 -0
  105. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_requirements_coverage.py +0 -0
  106. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_screenshot_regressions.py +0 -0
  107. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_session_performance.py +0 -0
  108. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_shell_timeout_modes.py +0 -0
  109. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_skill_selection.py +0 -0
  110. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_skills_studio_v2.py +0 -0
  111. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_split_distribution.py +0 -0
  112. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_sqlite_connection_lifecycle.py +0 -0
  113. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_step_skill_runtime.py +0 -0
  114. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_sync_routing_scope.py +0 -0
  115. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_todo_no_progress.py +0 -0
  116. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_todo_update_recovery.py +0 -0
  117. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_web_search_local_graph.py +0 -0
  118. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tests/test_web_search_public_discovery.py +0 -0
  119. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/__init__.py +0 -0
  120. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/inspect_evolution_progress.py +0 -0
  121. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/sync_liquid_kernel_bundle.py +0 -0
  122. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_admin_restart_real.py +0 -0
  123. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_context_runtime_real.py +0 -0
  124. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_evolution_entrypoint.py +0 -0
  125. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_evolution_progress_real.py +0 -0
  126. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_evolution_real.py +0 -0
  127. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_frozen_review_real.py +0 -0
  128. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_json_semantic_real.py +0 -0
  129. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_model_compatibility_real.py +0 -0
  130. {clouds_coder-2026.10.31 → clouds_coder-2026.11.4}/tools/verify_transport_parity_real.py +0 -0
@@ -5535,6 +5535,8 @@ SESSION_DEFERRED_START_QUEUE_MAX = max(
5535
5535
  SESSION_SUBMISSION_DEDUPE_MAX = 32
5536
5536
  SESSION_SUBMISSION_DEDUPE_SECONDS = 0.75
5537
5537
  SCHEDULER_SUBMISSION_DEDUPE_MAX = 256
5538
+ # This selects only the inexpensive complexity pre-screen. The task-level
5539
+ # router always asks for a semantic decision unless the user pinned a level.
5538
5540
  FAST_START_LOCAL_CLASSIFICATION = str(
5539
5541
  os.getenv("AGENT_FAST_START_LOCAL_CLASSIFICATION", "true") or "true"
5540
5542
  ).strip().lower() in {"1", "true", "yes", "on"}
@@ -5903,9 +5905,12 @@ DEFAULT_SHELL_COMMAND_TIMEOUT_SECONDS = max(
5903
5905
  # whose default is ``force`` and whose explicit alternatives are ``auto`` and
5904
5906
  # ``off``.
5905
5907
  DEFAULT_SINGLE_NO_PLAN_TODO_PROMPT = (
5906
- "Use the evidence from the completed read-only perception round to think "
5907
- "through the actual user goal for one planning turn. Then call TodoWrite "
5908
- "(or TodoWriteRescue) now and create a realistic list of 1-40 next actions. "
5908
+ "Understand the actual user goal, relevant current state and available skills "
5909
+ "before committing a checklist. One read or directory listing does not establish readiness. "
5910
+ "Continue read-only discovery, read selected workflows completely, or ask_user "
5911
+ "while material gaps remain. Existing user-provided or recalled state can be sufficient; "
5912
+ "there is no fixed read count or preparation turn count. Once ready, call TodoWrite "
5913
+ "(or TodoWriteRescue) with a brief preparation assessment and a realistic list of 1-40 next actions. "
5909
5914
  "When the request contains explicit ordered stages, preserve them one-for-one "
5910
5915
  "in the same order instead of merging them to fit a smaller list. Keep exactly "
5911
5916
  "one item in_progress, base items on observed "
@@ -6216,6 +6221,7 @@ BLACKBOARD_STATUSES = (
6216
6221
  "TESTING",
6217
6222
  "REVIEWING",
6218
6223
  "COMPLETED",
6224
+ "ABORTED",
6219
6225
  "PAUSED",
6220
6226
  )
6221
6227
  TASK_COMPLEXITY_LEVELS = ("simple", "moderate", "complex", "expert")
@@ -6485,7 +6491,7 @@ PLAN_STEP_FULL_CONTENT_MAX_CHARS = 24_000
6485
6491
  PLAN_MODE_RESEARCH_TOOL_ALLOWLIST = {
6486
6492
  "bash", "read_file", "context_recall", "task_get", "task_list",
6487
6493
  "check_background", "list_background_processes", "read_from_blackboard", "write_to_blackboard",
6488
- "list_skills", "load_skill", "unload_skill", "compress", "agent_web_search",
6494
+ "list_skills", "load_skill", "unload_skill", "compress", "agent_web_search", "ask_user",
6489
6495
  # rag_remember writes only to the RAG knowledge library (never user files), so it is
6490
6496
  # safe during read-only planning — analogous to write_to_blackboard scratch persistence.
6491
6497
  "rag_remember",
@@ -7763,7 +7769,7 @@ BACKEND_I18N["en"].update(
7763
7769
  "plan_risk_medium": "medium",
7764
7770
  "plan_risk_high": "high",
7765
7771
  "plan_read_instruction": "Plan approved. `{path}` is a read-only execution mirror; use it to inspect step order and current status.\nRuntime todos and tool-evidence events remain authoritative. Execute steps in order, finish the current step before advancing, and load any referenced skill or workflow before starting.",
7766
- "plan_read_todo_note": "\nTODO PLANNING: At the START of work, call TodoWrite to create 3-6 subtasks for {step_label} only (parent_step_id='{parent_step_id}'), exactly one in_progress, and a final Acceptance item with its check and evidence shape. The initial subplan is a rolling execution hypothesis, not an immutable script. Before every update, read CANONICAL SUBTASKS plus the latest current-step tool/reviewer evidence; normally continue the current in_progress item. Only when concrete new evidence proves the OPEN portion is incomplete, obsolete, wrongly ordered, or poorly split, submit the complete revised open snapshot with update_mode='revise_open', revision_reason, and exact revision_evidence references; the runtime audits it atomically. Never revise for stylistic preference, cross parent steps, or erase completed evidence. Use update_mode='rework_completed' only when cited failure/reviewer evidence requires reopening completed work. Use update_mode='status_update' for ordinary progress and update immediately after each completed subtask. Do NOT use finish_current_task for a subtask or one plan step.\n",
7772
+ "plan_read_todo_note": "\nTODO PLANNING: First understand the goal and actual current-step state, consider available skills and read selected full workflows; continue observation or clarification until ready. Then call TodoWrite with a preparation assessment to create the necessary subtasks for {step_label} only (parent_step_id='{parent_step_id}'), exactly one in_progress, and a final Acceptance item with its check and evidence shape. The initial subplan is a rolling execution hypothesis, not an immutable script. Before every update, read CANONICAL SUBTASKS plus the latest current-step tool/reviewer evidence; normally continue the current in_progress item. Only when concrete new evidence proves the OPEN portion is incomplete, obsolete, wrongly ordered, or poorly split, submit the complete revised open snapshot with update_mode='revise_open', revision_reason, and exact revision_evidence references; the runtime audits it atomically. Never revise for stylistic preference, cross parent steps, or erase completed evidence. Use update_mode='rework_completed' only when cited failure/reviewer evidence requires reopening completed work. Use update_mode='status_update' for ordinary progress and update immediately after each completed subtask. Do NOT use finish_current_task for a subtask or one plan step.\n",
7767
7773
  "plan_proposal_title": "## 📋 Execution Plans\n",
7768
7774
  "plan_proposal_background": "### Background Analysis\n{context}\n",
7769
7775
  "plan_proposal_option": "### Option {id}: {title}",
@@ -7864,7 +7870,7 @@ BACKEND_I18N["zh-CN"].update(
7864
7870
  "plan_risk_medium": "中",
7865
7871
  "plan_risk_high": "高",
7866
7872
  "plan_read_instruction": "计划已批准。`{path}` 是只读执行镜像,可用 `read_file {path}` 查看步骤顺序和当前状态;运行时 Todo 与工具证据事件才是权威状态。\n按顺序执行,完成当前步骤后再推进下一步;如果步骤引用了 skill 或 workflow,开始前先调用 load_skill。",
7867
- "plan_read_todo_note": "\nTODO 更新:一开始调用 TodoWrite,只为当前步骤({step_label})创建 3-6 个子任务,每项必须包含 parent_step_id='{parent_step_id}',只能有一个 in_progress,最后一项必须是写明检查动作与证据形态的“验收”。初始子计划是可滚动修订的执行假设,不是不可改变的脚本。每次更新前,先阅读 CANONICAL SUBTASKS 和当前步骤最新的工具/审核证据;通常优先继续当前 in_progress。只有切实的新证据表明开放部分存在遗漏、失效、顺序错误或拆分不合理时,才提交完整的新开放清单,并设置 update_mode='revise_open'、revision_reason 和精确的 revision_evidence;运行时会原子审核。不要为了措辞或偏好盲目改动,不要跨母步骤,也不要抹掉已完成证据。只有失败证据或审核不通过要求返工时才使用 update_mode='rework_completed'。普通状态推进使用 update_mode='status_update';每完成一项立即更新并把下一项切为 in_progress。不要用 finish_current_task 完成子任务或单个计划步骤。\n",
7873
+ "plan_read_todo_note": "\nTODO 更新:先理解目标和当前步骤的真实状态,考虑可用技能并阅读选定技能的完整流程;缺少关键上下文时继续只读感知或澄清。准备充分后携带 preparation 评估调用 TodoWrite,只为当前步骤({step_label})创建必要的子任务,每项必须包含 parent_step_id='{parent_step_id}',只能有一个 in_progress,最后一项必须是写明检查动作与证据形态的“验收”。初始子计划是可滚动修订的执行假设,不是不可改变的脚本。每次更新前,先阅读 CANONICAL SUBTASKS 和当前步骤最新的工具/审核证据;通常优先继续当前 in_progress。只有切实的新证据表明开放部分存在遗漏、失效、顺序错误或拆分不合理时,才提交完整的新开放清单,并设置 update_mode='revise_open'、revision_reason 和精确的 revision_evidence;运行时会原子审核。不要为了措辞或偏好盲目改动,不要跨母步骤,也不要抹掉已完成证据。只有失败证据或审核不通过要求返工时才使用 update_mode='rework_completed'。普通状态推进使用 update_mode='status_update';每完成一项立即更新并把下一项切为 in_progress。不要用 finish_current_task 完成子任务或单个计划步骤。\n",
7868
7874
  "plan_proposal_title": "## 📋 执行方案\n",
7869
7875
  "plan_proposal_background": "### 背景分析\n{context}\n",
7870
7876
  "plan_proposal_option": "### 方案 {id}:{title}",
@@ -7965,7 +7971,7 @@ BACKEND_I18N["zh-TW"].update(
7965
7971
  "plan_risk_medium": "中",
7966
7972
  "plan_risk_high": "高",
7967
7973
  "plan_read_instruction": "計畫已核准。`{path}` 是唯讀執行鏡像,可用 `read_file {path}` 查看步驟順序與目前狀態;執行階段 Todo 與工具證據事件才是權威狀態。\n請依序執行,完成目前步驟後再推進下一步;如果步驟引用了 skill 或 workflow,開始前先呼叫 load_skill。",
7968
- "plan_read_todo_note": "\nTODO 更新:一開始呼叫 TodoWrite,只為目前步驟({step_label})建立 3-6 個子任務,每項包含 parent_step_id='{parent_step_id}',只能有一個 in_progress,最後一項是寫明檢查動作與證據形態的「驗收」。初始子計畫是可滾動修訂的執行假設。每次更新前先閱讀 CANONICAL SUBTASKS 與目前步驟最新工具/審核證據;通常先延續目前 in_progress。只有具體新證據證明開放部分有遺漏、失效、順序錯誤或拆分不合理時,才提交完整新開放清單,並設定 update_mode='revise_open'、revision_reason 與精確 revision_evidence;執行階段會原子審核。不要為措辭或偏好盲目修改,不要跨母步驟,也不要抹除已完成證據。只有失敗證據或審核未通過要求返工時才使用 update_mode='rework_completed'。普通狀態推進使用 update_mode='status_update';每完成一項立即更新並切換下一項為 in_progress。不要用 finish_current_task 完成子任務或單一計畫步驟。\n",
7974
+ "plan_read_todo_note": "\nTODO 更新:先理解目標和目前步驟的真實狀態,考慮可用技能並閱讀選定技能的完整流程;關鍵上下文不足時繼續唯讀觀察或澄清。準備充分後附帶 preparation 評估呼叫 TodoWrite,只為目前步驟({step_label})建立必要子任務,每項包含 parent_step_id='{parent_step_id}',只能有一個 in_progress,最後一項是寫明檢查動作與證據形態的「驗收」。初始子計畫是可滾動修訂的執行假設。每次更新前先閱讀 CANONICAL SUBTASKS 與目前步驟最新工具/審核證據;通常先延續目前 in_progress。只有具體新證據證明開放部分有遺漏、失效、順序錯誤或拆分不合理時,才提交完整新開放清單,並設定 update_mode='revise_open'、revision_reason 與精確 revision_evidence;執行階段會原子審核。不要為措辭或偏好盲目修改,不要跨母步驟,也不要抹除已完成證據。只有失敗證據或審核未通過要求返工時才使用 update_mode='rework_completed'。普通狀態推進使用 update_mode='status_update';每完成一項立即更新並切換下一項為 in_progress。不要用 finish_current_task 完成子任務或單一計畫步驟。\n",
7969
7975
  "plan_proposal_title": "## 📋 執行方案\n",
7970
7976
  "plan_proposal_background": "### 背景分析\n{context}\n",
7971
7977
  "plan_proposal_option": "### 方案 {id}:{title}",
@@ -8066,7 +8072,7 @@ BACKEND_I18N["ja"].update(
8066
8072
  "plan_risk_medium": "中",
8067
8073
  "plan_risk_high": "高",
8068
8074
  "plan_read_instruction": "計画が承認されました。`{path}` は読み取り専用の実行ミラーです。`read_file {path}` で手順と現在状態を確認できますが、正式な状態はランタイム Todo とツール証拠イベントです。\n必ず順番に実行し、現在のステップを完了してから次へ進んでください。ステップが skill や workflow を参照している場合は、開始前に load_skill を呼び出してください。",
8069
- "plan_read_todo_note": "\nTODO 更新: 最初に TodoWrite で現在のステップ({step_label})だけを 3-6 件に分解し、各行に parent_step_id='{parent_step_id}' を含め、in_progress は 1 件、最後は確認内容と証拠形を明記した「受入確認」にします。初期サブプランは固定スクリプトではなく、証拠に基づくローリング仮説です。更新前に CANONICAL SUBTASKS と現在ステップの最新ツール/レビュー証拠を読み、通常は現在の in_progress を続行します。具体的な新証拠が未完了部分の不足・陳腐化・順序誤り・分割不良を示す場合だけ、完全な新しい未完了スナップショットを update_mode='revise_open'、revision_reason、revision_evidence とともに提出してください。ランタイムが原子的に監査します。表現上の好みだけで変更せず、親ステップを越えず、完了済み証拠を消さないでください。失敗証拠またはレビュー不合格で完了作業の再実行が必要な場合のみ update_mode='rework_completed' を使います。通常の進捗は update_mode='status_update' とし、各サブタスク完了直後に更新して次を in_progress にしてください。\n",
8075
+ "plan_read_todo_note": "\nTODO 更新: 目標と現在の状態を理解し、利用可能なスキルを検討して選択した手順の全文を読みます。重要な情報が不足する場合は観察や確認を続け、準備が整ってから preparation 評価を添えた TodoWrite で現在のステップ({step_label})だけを必要な項目に分解し、各行に parent_step_id='{parent_step_id}' を含め、in_progress は 1 件、最後は確認内容と証拠形を明記した「受入確認」にします。初期サブプランは固定スクリプトではなく、証拠に基づくローリング仮説です。更新前に CANONICAL SUBTASKS と現在ステップの最新ツール/レビュー証拠を読み、通常は現在の in_progress を続行します。具体的な新証拠が未完了部分の不足・陳腐化・順序誤り・分割不良を示す場合だけ、完全な新しい未完了スナップショットを update_mode='revise_open'、revision_reason、revision_evidence とともに提出してください。ランタイムが原子的に監査します。表現上の好みだけで変更せず、親ステップを越えず、完了済み証拠を消さないでください。失敗証拠またはレビュー不合格で完了作業の再実行が必要な場合のみ update_mode='rework_completed' を使います。通常の進捗は update_mode='status_update' とし、各サブタスク完了直後に更新して次を in_progress にしてください。\n",
8070
8076
  "plan_proposal_title": "## 📋 実行プラン\n",
8071
8077
  "plan_proposal_background": "### 背景分析\n{context}\n",
8072
8078
  "plan_proposal_option": "### 案 {id}: {title}",
@@ -31289,6 +31295,8 @@ TOOLS = [
31289
31295
  "(e.g. {\"id\": \"t3\", \"status\": \"completed\"}). Preserve ids of retained rows in revisions; "
31290
31296
  "omit an id only for genuinely new work. Unknown or out-of-scope ids reject the update. "
31291
31297
  "A partial update selecting in_progress moves that owner's active cursor."
31298
+ " In Sync mode submit only the active role's rows: peers are preserved automatically "
31299
+ "and remain part of the independent review's full proposed tree."
31292
31300
  ),
31293
31301
  {
31294
31302
  "items": {"type": "array", "items": {}},
@@ -31312,6 +31320,16 @@ TOOLS = [
31312
31320
  "continue": {"type": "boolean"},
31313
31321
  "resume_existing": {"type": "boolean"},
31314
31322
  "in_progress_index": {"type": "integer"},
31323
+ "preparation": {
31324
+ "type": "object",
31325
+ "description": "For the first list of this task/role/plan step, summarize understanding after sufficient context and skill consideration; do not include private reasoning. Existing progress updates do not need another preparation.",
31326
+ "properties": {
31327
+ "goal": {"type": "string"}, "state": {"type": "string"},
31328
+ "skills": {"type": "string"}, "ready": {"type": "boolean"},
31329
+ "basis": {"type": "string", "enum": ["user_context", "observed_context", "continuation"]},
31330
+ "missing": {"type": "array", "items": {"type": "string"}},
31331
+ },
31332
+ },
31315
31333
  "update_mode": {
31316
31334
  "type": "string",
31317
31335
  "enum": ["status_update", "revise_open", "rework_completed"],
@@ -31350,6 +31368,16 @@ TOOLS = [
31350
31368
  "continue": {"type": "boolean"},
31351
31369
  "resume_existing": {"type": "boolean"},
31352
31370
  "in_progress_index": {"type": "integer"},
31371
+ "preparation": {
31372
+ "type": "object",
31373
+ "description": "For the first list of this task/role/plan step, summarize understanding after sufficient context and skill consideration; do not include private reasoning. Existing progress updates do not need another preparation.",
31374
+ "properties": {
31375
+ "goal": {"type": "string"}, "state": {"type": "string"},
31376
+ "skills": {"type": "string"}, "ready": {"type": "boolean"},
31377
+ "basis": {"type": "string", "enum": ["user_context", "observed_context", "continuation"]},
31378
+ "missing": {"type": "array", "items": {"type": "string"}},
31379
+ },
31380
+ },
31353
31381
  "update_mode": {"type": "string", "enum": ["status_update", "revise_open", "rework_completed"]},
31354
31382
  "revision_reason": {"type": "string"},
31355
31383
  "revision_evidence": {},
@@ -31385,6 +31413,16 @@ TOOLS = [
31385
31413
  "continue": {"type": "boolean"},
31386
31414
  "resume_existing": {"type": "boolean"},
31387
31415
  "in_progress_index": {"type": "integer"},
31416
+ "preparation": {
31417
+ "type": "object",
31418
+ "description": "For the first list of this task/role/plan step, summarize understanding after sufficient context and skill consideration; do not include private reasoning. Existing progress updates do not need another preparation.",
31419
+ "properties": {
31420
+ "goal": {"type": "string"}, "state": {"type": "string"},
31421
+ "skills": {"type": "string"}, "ready": {"type": "boolean"},
31422
+ "basis": {"type": "string", "enum": ["user_context", "observed_context", "continuation"]},
31423
+ "missing": {"type": "array", "items": {"type": "string"}},
31424
+ },
31425
+ },
31388
31426
  "update_mode": {"type": "string"},
31389
31427
  "mode": {"type": "string"},
31390
31428
  "operation": {"type": "string"},
@@ -33383,6 +33421,7 @@ class SessionState:
33383
33421
  default_llm_config or {}
33384
33422
  )
33385
33423
  self.single_no_plan_todo_enabled = bool(cfg_single_todo_enabled)
33424
+ self._task_preparation_required = True
33386
33425
  self.single_no_plan_todo_prompt = str(cfg_single_todo_prompt or "").strip()
33387
33426
  self.single_no_plan_todo_bootstrap_state = "idle"
33388
33427
  self.single_no_plan_todo_bootstrap_attempts = 0
@@ -36811,6 +36850,11 @@ class SessionState:
36811
36850
 
36812
36851
  def _previous_task_context_snapshot(self, board: dict | None = None) -> dict:
36813
36852
  bb = board if isinstance(board, dict) else self._ensure_blackboard()
36853
+ profile = bb.get("task_profile", {}) if isinstance(bb.get("task_profile"), dict) else {}
36854
+ try:
36855
+ previous_level = int(profile.get("task_level", getattr(self, "runtime_task_level", 0)) or 0)
36856
+ except (TypeError, ValueError):
36857
+ previous_level = 0
36814
36858
  completion = self._normalize_completion_state(bb.get("completion", {}))
36815
36859
  approval = bb.get("approval", {}) if isinstance(bb.get("approval"), dict) else {}
36816
36860
  artifacts = bb.get("code_artifacts", {}) if isinstance(bb.get("code_artifacts"), dict) else {}
@@ -36849,6 +36893,8 @@ class SessionState:
36849
36893
  break
36850
36894
  out = {
36851
36895
  "goal": trim(str(bb.get("original_goal", "") or ""), 800),
36896
+ "task_level": previous_level if previous_level in TASK_LEVEL_CHOICES else None,
36897
+ "execution_mode": str(profile.get("execution_mode", "") or ""),
36852
36898
  "status": self._normalize_blackboard_status(bb.get("status", "INITIALIZING")),
36853
36899
  "summary": summary,
36854
36900
  "artifact_paths": artifact_paths,
@@ -36867,6 +36913,10 @@ class SessionState:
36867
36913
  if not ctx:
36868
36914
  return ""
36869
36915
  lines: list[str] = []
36916
+ if ctx.get("task_level") in TASK_LEVEL_CHOICES:
36917
+ lines.append(f"previous_task_level: L{ctx['task_level']}")
36918
+ if ctx.get("status"):
36919
+ lines.append(f"previous_task_status: {ctx['status']}")
36870
36920
  goal = trim(str(ctx.get("goal", "") or ""), 240)
36871
36921
  if goal:
36872
36922
  lines.append(f"previous_goal: {goal}")
@@ -36933,6 +36983,10 @@ class SessionState:
36933
36983
  bb = board if isinstance(board, dict) else self._ensure_blackboard()
36934
36984
  if self._blackboard_is_finished_or_aborted(bb):
36935
36985
  return False
36986
+ if str(bb.get("original_goal", "") or "").strip() and self._unfinished_task_level(bb):
36987
+ # A classified task may be paused before its first artifact/tool.
36988
+ # Absence of progress evidence is not evidence of task completion.
36989
+ return True
36936
36990
  if self._has_resumable_plan_state():
36937
36991
  return True
36938
36992
  todos = bb.get("project_todos", []) if isinstance(bb.get("project_todos"), list) else []
@@ -37707,6 +37761,169 @@ class SessionState:
37707
37761
  if prev_fp and self.skills.fingerprint and prev_fp != self.skills.fingerprint:
37708
37762
  self.skill_load_cache = {}
37709
37763
 
37764
+ def _prepare_skill_execution_workspace(self, skill_id: str) -> dict:
37765
+ """Materialize selected resources with their original relative layout.
37766
+
37767
+ Published/global sources stay immutable. Directories in the verified
37768
+ task-local mirror are writable for script caches and generated outputs;
37769
+ source files are verified separately from those generated files.
37770
+ """
37771
+ if not getattr(self, "files_root", None):
37772
+ return {}
37773
+ gate = getattr(self, "_skill_execution_workspace_lock", None)
37774
+ if gate is None:
37775
+ gate = self._skill_execution_workspace_lock = threading.RLock()
37776
+ with gate:
37777
+ sources: dict[str, bytes] = {}
37778
+ hard = getattr(self, "skill_mode", "dynamic") == "hard"
37779
+ if hard:
37780
+ bound = list(getattr(self, "bound_skill_ids", []))
37781
+ if skill_id not in bound:
37782
+ raise ValueError("Only bound application skills have execution resources")
37783
+ order = bound.index(skill_id) + 1
37784
+ snapshot = self._application_snapshot_root()
37785
+ source = snapshot / f"{order:02d}"
37786
+ if not (source / "SKILL.md").is_file():
37787
+ return {"skill_id": skill_id, "status": "legacy-instructions-only"}
37788
+ valid, error = self._application_snapshot_manifest_valid()
37789
+ if not valid:
37790
+ raise ValueError(error)
37791
+ manifest = json.loads((snapshot / "MANIFEST.json").read_text(encoding="utf-8"))
37792
+ for row in manifest.get("resources", []):
37793
+ if int(row.get("skill_order", 0) or 0) == order:
37794
+ rel = str(row.get("path", "") or "")
37795
+ sources[rel] = safe_path(rel, source).read_bytes()
37796
+ source_path = f"/workspace/.application_skills/{order:02d}/SKILL.md"
37797
+ else:
37798
+ skill = getattr(getattr(self, "skills", None), "skills", {}).get(skill_id, {})
37799
+ if not skill:
37800
+ raise ValueError("Skill is not in the current catalog")
37801
+ source_path = str(skill.get("skill_path", "") or "")
37802
+ raw_source = str(skill.get("skill_abs_path", "") or "")
37803
+ source = Path(raw_source) if raw_source and not _is_http_url(raw_source) else None
37804
+ if source is not None and source.is_file() and not source.is_symlink():
37805
+ sources["SKILL.md"] = source.read_bytes()
37806
+ base = source.resolve().parent
37807
+ for row in skill.get("attachments", []):
37808
+ rel = str(row.get("path", "") or "")
37809
+ raw_path = str(row.get("abs_path", "") or "")
37810
+ if not rel or not raw_path:
37811
+ continue
37812
+ target = Path(raw_path)
37813
+ resolved = target.resolve()
37814
+ if target.is_symlink() or not resolved.is_relative_to(base):
37815
+ raise ValueError("Skill resource is outside its approved source directory")
37816
+ if target.is_file():
37817
+ sources[rel] = target.read_bytes()
37818
+ else:
37819
+ # Remote and builtin instructions can still be read in
37820
+ # full; this does not grant their scripts host access.
37821
+ body = str(skill.get("body", "") or "")
37822
+ if body:
37823
+ sources["SKILL.md"] = body.encode("utf-8", errors="backslashreplace")
37824
+ if not sources:
37825
+ return {"skill_id": skill_id, "status": "instructions-only"}
37826
+ if len(sources) > ADMIN_MAX_APP_RESOURCE_FILES or sum(map(len, sources.values())) > ADMIN_MAX_APP_RESOURCE_BYTES:
37827
+ raise ValueError("Selected skill resources exceed the configured snapshot capacity; no partial copy was made")
37828
+ hashes, seen = {}, set()
37829
+ for rel, raw in sources.items():
37830
+ normalized = rel.replace("\\", "/")
37831
+ parts = PurePosixPath(normalized).parts
37832
+ folded = unicodedata.normalize("NFC", normalized).casefold()
37833
+ if (not parts or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized)
37834
+ or any(part in {".", ".."} for part in parts) or folded in seen):
37835
+ raise ValueError("Invalid or cross-platform ambiguous skill resource path")
37836
+ seen.add(folded)
37837
+ hashes[normalized] = hashlib.sha256(raw).hexdigest()
37838
+ bundle = hashlib.sha256(json.dumps(hashes, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
37839
+ slug = hashlib.sha256(skill_id.encode("utf-8", errors="backslashreplace")).hexdigest()[:12]
37840
+ relative = f".skill_runtime/skill-{slug}-{bundle[:12]}"
37841
+ target_root = safe_path(relative, self.files_root)
37842
+ target_root.mkdir(parents=True, exist_ok=True)
37843
+ for rel, raw in sources.items():
37844
+ rel = rel.replace("\\", "/")
37845
+ target = safe_path(rel, target_root)
37846
+ target.parent.mkdir(parents=True, exist_ok=True)
37847
+ if target.is_symlink():
37848
+ raise ValueError("Skill execution resource must not be a symlink")
37849
+ if target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == hashes[rel]:
37850
+ continue
37851
+ if target.exists():
37852
+ raise ValueError("Verified execution source changed; reload in a fresh task instead of executing modified skill code")
37853
+ temporary = target.with_name(target.name + "." + uuid.uuid4().hex + ".tmp")
37854
+ try:
37855
+ temporary.write_bytes(raw)
37856
+ os.replace(temporary, target)
37857
+ try:
37858
+ os.chmod(target, 0o500 if target.suffix.lower() in {".py", ".sh", ".js", ".mjs"} else 0o400)
37859
+ except OSError:
37860
+ # Windows permissions are enforced by workspace scope
37861
+ # and content checks, not POSIX executable mode bits.
37862
+ pass
37863
+ finally:
37864
+ if temporary.exists():
37865
+ temporary.unlink()
37866
+ record = {"skill_id": skill_id, "root": f"/workspace/{relative}", "relative_root": relative,
37867
+ "workflow": f"/workspace/{relative}/SKILL.md", "authoritative_source": source_path,
37868
+ "source_directory": str(source.resolve().parent) if not hard and source is not None and source.is_file() else "",
37869
+ "bundle_digest": bundle, "files": hashes, "status": "ready"}
37870
+ records = getattr(self, "_skill_execution_workspaces", None)
37871
+ if not isinstance(records, dict):
37872
+ records = self._skill_execution_workspaces = {}
37873
+ records[skill_id] = record
37874
+ return dict(record)
37875
+
37876
+ def _skill_execution_workspace_note(self, skill_ids: list[str]) -> str:
37877
+ rows = []
37878
+ for skill_id in skill_ids:
37879
+ try:
37880
+ row = self._prepare_skill_execution_workspace(skill_id)
37881
+ if row.get("status") == "ready":
37882
+ rows.append({key: row[key] for key in ("skill_id", "root", "workflow", "authoritative_source")})
37883
+ except Exception as exc:
37884
+ rows.append({"skill_id": skill_id, "error": str(exc)[:400]})
37885
+ if not rows:
37886
+ return ""
37887
+ return ("\nSELECTED SKILL EXECUTION RESOURCES: " + json_dumps(rows, ensure_ascii=False)
37888
+ + "\nUse read_file(mode='full') on the workflow locator to read the COMPLETE procedure before committing Todos or substantive execution. "
37889
+ "Excerpts are navigation hints, not the full procedure. Run the supplied unchanged scripts "
37890
+ "from these verified task-local mirrors; their relative resource layout is preserved. "
37891
+ "Use task workspace paths for inputs/outputs and keep the ordinary task working directory. "
37892
+ "Cache files beside scripts are allowed in the mirror, never in the original global or frozen source. "
37893
+ "In ordinary sessions, selected /skills shell aliases also resolve to this mirror; seeing a cache there is not evidence of a global-source write. "
37894
+ "Do not retype the source, chmod the published snapshot, or broaden host permissions.\n")
37895
+
37896
+ def _verify_skill_execution_workspaces(self) -> str:
37897
+ for row in list(getattr(self, "_skill_execution_workspaces", {}).values()):
37898
+ try:
37899
+ root = safe_path(row["relative_root"], self.files_root)
37900
+ for rel, expected in row["files"].items():
37901
+ path = safe_path(rel, root)
37902
+ if path.is_symlink() or not path.is_file() or not hmac.compare_digest(_sha256_file(path), expected):
37903
+ return "verified skill execution source changed: " + rel
37904
+ except Exception as exc:
37905
+ return "skill execution resources are inaccessible: " + type(exc).__name__
37906
+ return ""
37907
+
37908
+ def _selected_skill_shell_mappings(self) -> list[tuple[str, str]]:
37909
+ """Selected global aliases resolve to verified copies, never to host grants."""
37910
+ if getattr(self, "skill_mode", "dynamic") == "hard":
37911
+ return []
37912
+ records = getattr(self, "_skill_execution_workspaces", {})
37913
+ if not isinstance(records, dict) or not records:
37914
+ return []
37915
+ active = self._loaded_skill_rows()
37916
+ mappings = []
37917
+ for key, row in records.items():
37918
+ if key not in active or not row.get("source_directory"):
37919
+ continue
37920
+ target = str(safe_path(row["relative_root"], self.files_root))
37921
+ source = str(row.get("authoritative_source", "")).partition("#")[0]
37922
+ if source.startswith("/skills/"):
37923
+ mappings.append((str(PurePosixPath(source).parent), target))
37924
+ mappings.append((str(row["source_directory"]), target))
37925
+ return sorted(mappings, key=lambda pair: len(pair[0]), reverse=True)
37926
+
37710
37927
  def _load_skill_with_cache(self, name: str, load_source: str = "manual", *, purpose: str = "", evidence: list | None = None, keep_for_step: bool = False) -> str:
37711
37928
  if self.skill_mode == "hard":
37712
37929
  requested = str(name or "").strip()
@@ -37715,7 +37932,8 @@ class SessionState:
37715
37932
  order = self.bound_skill_ids.index(requested) + 1
37716
37933
  frozen = f"/workspace/.application_skills/{order:02d}/SKILL.md"
37717
37934
  if (self._application_snapshot_root() / f"{order:02d}" / "SKILL.md").exists():
37718
- return f"Skill is hard-bound and active. Its complete immutable source is {frozen}; read that file before execution."
37935
+ return (f"Skill is hard-bound and active. Its complete immutable source is {frozen}; read that file before execution."
37936
+ + self._skill_execution_workspace_note([requested]))
37719
37937
  return "Skill is already active from the legacy immutable application snapshot."
37720
37938
  self._ensure_skills_ready(force=False)
37721
37939
  resolution = self.skills.canonicalize_id(name)
@@ -37751,7 +37969,7 @@ class SessionState:
37751
37969
  self.blackboard = board
37752
37970
  self._record_skill_operation("load", key, source=load_source, purpose=purpose, evidence=evidence,
37753
37971
  keep_for_step=keep_for_step or was_active)
37754
- return text
37972
+ return self._skill_execution_workspace_note([key]) + text
37755
37973
 
37756
37974
  def _record_skill_operation(self, operation: str, skill_id: str, *, source: str, purpose: str = "", evidence: list | None = None, keep_for_step: bool = False):
37757
37975
  board = self._ensure_blackboard()
@@ -38677,7 +38895,8 @@ class SessionState:
38677
38895
  "`/workspace/.application_skills/MANIFEST.json` and use only those immutable copies. "
38678
38896
  "Do not access the mutable global `/skills` tree.\n"
38679
38897
  )
38680
- return header + str(self.bound_skill_capsule or "")
38898
+ return (header + self._skill_execution_workspace_note(list(getattr(self, "bound_skill_ids", [])))
38899
+ + str(self.bound_skill_capsule or ""))
38681
38900
  loaded = self._loaded_skill_rows()
38682
38901
  if not loaded:
38683
38902
  return ""
@@ -38685,8 +38904,10 @@ class SessionState:
38685
38904
  parts: list[str] = [
38686
38905
  "ACTIVE SKILL WORKFLOWS (rehydrated):",
38687
38906
  "Treat these instructions as active operating procedure for matching steps. "
38688
- "If they conflict with a generic plan, the skill workflow wins.",
38907
+ "Follow the complete workflow, subject to the user's request and runtime permissions. "
38908
+ "Do not replace its concrete tools or checks with a generic plan.",
38689
38909
  ]
38910
+ execution_note = self._skill_execution_workspace_note(list(loaded))
38690
38911
  remaining = budget
38691
38912
  for skill_key, row_obj in list(loaded.items())[:10]:
38692
38913
  row = row_obj if isinstance(row_obj, dict) else {}
@@ -38725,7 +38946,9 @@ class SessionState:
38725
38946
  "\nWorker duty: before acting, map the current step to the active skill workflow and "
38726
38947
  "use the specified tools/scripts/files when applicable."
38727
38948
  )
38728
- return ("\n".join(parts) + role_note + "\n")[:budget]
38949
+ # Keep the complete-workflow locator outside the excerpt truncation so
38950
+ # compaction or a long first skill cannot hide it from later roles.
38951
+ return execution_note + ("\n".join(parts) + role_note + "\n")[:budget]
38729
38952
 
38730
38953
  def _clear_loaded_skill_contexts(self):
38731
38954
  def _filter_rows(rows: list[dict]) -> list[dict]:
@@ -39249,6 +39472,29 @@ class SessionState:
39249
39472
  def _todo_contract_prompt_block(self) -> str:
39250
39473
  """Build the level-driven Todo contract injected into agent prompts."""
39251
39474
  level = self._runtime_task_level_for_todo_policy()
39475
+ preparation_note = (
39476
+ " INITIAL LIST PREPARATION: understand the goal and actual state, consider available skills even outside "
39477
+ "an application, and read selected workflows completely. Continue observation or ask_user until material "
39478
+ "gaps are resolved; the first read is not a readiness signal. When ready, include preparation={goal, state, "
39479
+ "skills, basis:user_context|observed_context|continuation, ready:true, missing:[]} in the first TodoWrite "
39480
+ "for this role/current step. Use concise conclusions, not private reasoning. Omit ids for new rows; "
39481
+ "never invent t1/t2. Existing progress updates keep their original ids and need no repeat assessment. "
39482
+ )
39483
+ if level >= 3 and self._runtime_level_requires_todos():
39484
+ if bool(getattr(self, "runtime_plan_mode_needed", False)) and not bool(getattr(self, "runtime_plan_approved", False)):
39485
+ return (f"MANDATORY L{level} TODO CONTRACT: complete the pending Plan and await its approval first. "
39486
+ "Do not invent an execution Todo graph or finish while the Plan is unapproved.")
39487
+ if bool(getattr(self, "runtime_plan_approved", False)):
39488
+ return (f"MANDATORY L{level} TODO CONTRACT: maintain the approved current-step Todo graph. "
39489
+ "Preserve parent scope, identities and peer ownership. Update progress after real changes. "
39490
+ "Use plan_updates plus revise_open for supported goal/acceptance changes; diagnose failures, "
39491
+ "repair and verify again. Do not finish with incomplete steps or subtasks." + preparation_note)
39492
+ return (f"MANDATORY L{level} TODO CONTRACT: after read-only orientation, use TodoWrite to create "
39493
+ "a compact goal-based checklist for your own assigned work before side effects; another owner's "
39494
+ "rows do not initialize your tracking. Maintain the same IDs, keep peer-owned "
39495
+ "rows and exactly one current item per owner. Revise open goals when requirements change; "
39496
+ "on errors diagnose, repair and revalidate, then update the same rows. Never finish while "
39497
+ "the required list is absent or any owner still has unfinished work." + preparation_note)
39252
39498
  if level != 2 or not self._runtime_level_requires_todos():
39253
39499
  return ""
39254
39500
  l2_policy = normalize_l2_todo_policy(
@@ -39269,17 +39515,17 @@ class SessionState:
39269
39515
  "represented by Todo rows. Because a plan is active, use the existing "
39270
39516
  "plan/runtime step-local Todo graph and preserve its parent scope; do "
39271
39517
  "not create a second flat graph. Keep exactly one current item "
39272
- "in_progress and update it after each real status change."
39518
+ "in_progress and update it after each real status change." + preparation_note
39273
39519
  )
39274
39520
  return (
39275
39521
  f"{contract_label}: this run is level 2 and must have a compact, "
39276
39522
  "evidence-based Todo list even when the startup single/no-plan Todo option "
39277
- "is disabled. First perform a short read-only perception pass, then call "
39523
+ "is disabled. First assess whether the actual context is sufficient, then call "
39278
39524
  "TodoWrite or TodoWriteRescue before any mutation. Create 1-40 realistic "
39279
39525
  "next actions with exactly one item in_progress. If the request defines ordered "
39280
39526
  "stages, preserve every stage one-for-one and in order; update the same list after "
39281
39527
  "each real status change. Do not write files or claim completion while the "
39282
- "required Todo list is absent."
39528
+ "required Todo list is absent." + preparation_note
39283
39529
  )
39284
39530
 
39285
39531
  def _agent_language_preference(self) -> dict:
@@ -40401,6 +40647,7 @@ class SessionState:
40401
40647
  }
40402
40648
  compact_plan = {
40403
40649
  "phase": plan.get("phase", ""),
40650
+ "preparation_state": plan.get("preparation_state", ""),
40404
40651
  "chosen": plan.get("chosen", ""),
40405
40652
  "steps": plan.get("steps", []),
40406
40653
  "charter": {
@@ -53810,8 +54057,8 @@ body{padding:18px}
53810
54057
  )
53811
54058
  short_instruction = (
53812
54059
  "The previous completed responses contained reasoning but no final action. "
53813
- "Use the existing reasoning and return the required TodoWrite/TodoWriteRescue call now. "
53814
- "Do not repeat analysis."
54060
+ "Return one preparation action: observe or ask_user if material context is missing; "
54061
+ "use TodoWrite with an honest preparation assessment only when ready. Do not invent readiness to escape this retry."
53815
54062
  if bootstrap
53816
54063
  else
53817
54064
  "The previous completed responses contained reasoning but no final action. "
@@ -53859,16 +54106,15 @@ body{padding:18px}
53859
54106
  call for call in calls1
53860
54107
  if canonicalize_tool_name(
53861
54108
  (call.get("function", {}) if isinstance(call, dict) else {}).get("name", "")
53862
- ) in {"TodoWrite", "TodoWriteRescue"}
54109
+ ) in {canonicalize_tool_name(spec.get("function", {}).get("name", "")) for spec in tools}
53863
54110
  ]
53864
54111
  if calls1 or (text1.strip() and not bootstrap):
53865
54112
  return {"ok": True, "response": {"content": text1, "thinking": thinking1, "tool_calls": calls1}, "stage": "short"}
53866
54113
 
53867
- forced_name = "TodoWrite" if bootstrap and self._provider_supports_native_tool_choice() else ""
53868
54114
  second_instruction = (
53869
54115
  "/no_think\nThinking is disabled for this compatibility retry. "
53870
- "Call TodoWrite now with 1-40 evidence-based items and exactly one in_progress item. "
53871
- "Output no prose."
54116
+ "Take one real preparation action. Continue observation or ask_user for missing context; "
54117
+ "submit TodoWrite with preparation only if ready. Output no analysis."
53872
54118
  if bootstrap
53873
54119
  else
53874
54120
  "/no_think\nThinking is disabled for this compatibility retry. "
@@ -53876,7 +54122,7 @@ body{padding:18px}
53876
54122
  )
53877
54123
  try:
53878
54124
  forced_kwargs = {
53879
- "tools": (self._single_no_plan_todo_bootstrap_tools() if bootstrap else tools),
54125
+ "tools": tools,
53880
54126
  "system": self._system_prompt(),
53881
54127
  "max_tokens": max_tokens,
53882
54128
  "think": False,
@@ -53887,8 +54133,6 @@ body{padding:18px}
53887
54133
  "media_inputs": None,
53888
54134
  "effort": EFFORT_OFF,
53889
54135
  }
53890
- if forced_name:
53891
- forced_kwargs["tool_choice"] = forced_name
53892
54136
  second = self._chat_with_same_model_retry(
53893
54137
  list(self.messages) + [{"role": "user", "content": second_instruction, "ts": now_ts()}],
53894
54138
  **forced_kwargs,
@@ -53906,7 +54150,7 @@ body{padding:18px}
53906
54150
  call for call in calls2
53907
54151
  if canonicalize_tool_name(
53908
54152
  (call.get("function", {}) if isinstance(call, dict) else {}).get("name", "")
53909
- ) in {"TodoWrite", "TodoWriteRescue"}
54153
+ ) in {canonicalize_tool_name(spec.get("function", {}).get("name", "")) for spec in tools}
53910
54154
  ]
53911
54155
  if calls2 or (text2.strip() and not bootstrap):
53912
54156
  return {"ok": True, "response": {"content": text2, "thinking": thinking2, "tool_calls": calls2}, "stage": "forced"}
@@ -55744,9 +55988,9 @@ body{padding:18px}
55744
55988
  if not raw:
55745
55989
  return raw
55746
55990
  try:
55747
- workspace_root = str(cwd.resolve())
55991
+ workspace_root = str(self.files_root.resolve())
55748
55992
  except Exception:
55749
- workspace_root = str(cwd)
55993
+ workspace_root = str(self.files_root)
55750
55994
  try:
55751
55995
  skills_root = str(self.skills.skills_root.resolve())
55752
55996
  except Exception:
@@ -55755,7 +55999,7 @@ body{padding:18px}
55755
55999
  js_lib_root = str(self.js_lib_root.resolve())
55756
56000
  except Exception:
55757
56001
  js_lib_root = str(self.js_lib_root)
55758
- mappings = self.skills.shell_virtual_mappings() + [
56002
+ mappings = self._selected_skill_shell_mappings() + self.skills.shell_virtual_mappings() + [
55759
56003
  ("/workspace", workspace_root),
55760
56004
  (SKILLS_VIRTUAL_PREFIX, skills_root),
55761
56005
  ("/js_lib", js_lib_root),
@@ -55927,7 +56171,17 @@ body{padding:18px}
55927
56171
  if not raw.strip():
55928
56172
  return False
55929
56173
  low = raw.lower()
55930
- if re.search(r"(?<!<)>{1,2}(?![>&])", raw):
56174
+ # Shell redirection is outside quoted program arguments. A comparison
56175
+ # such as python -c "print(actual > expected)" does not write a file.
56176
+ try:
56177
+ lexer = shlex.shlex(raw, posix=True, punctuation_chars="<>")
56178
+ lexer.whitespace_split = True
56179
+ lexer.commenters = ""
56180
+ shell_tokens = list(lexer)
56181
+ if any(token in {">", ">>"} and not (index + 1 < len(shell_tokens) and shell_tokens[index + 1].startswith("&"))
56182
+ for index, token in enumerate(shell_tokens)):
56183
+ return True
56184
+ except ValueError:
55931
56185
  return True
55932
56186
  if re.search(
55933
56187
  r"(?im)(?:^|[;&|]\s*)(?:command\s+|sudo\s+|env\s+)*"
@@ -55981,6 +56235,8 @@ body{padding:18px}
55981
56235
  text = str(command or "")
55982
56236
  if not text.strip():
55983
56237
  return False
56238
+ if self._selected_skill_shell_mappings():
56239
+ text = self._rewrite_shell_virtual_paths(text, self.files_root)
55984
56240
  try:
55985
56241
  skills_root = str(self.skills.skills_root.resolve()).rstrip(os.sep)
55986
56242
  except Exception:
@@ -56264,12 +56520,55 @@ body{padding:18px}
56264
56520
  raw,
56265
56521
  )
56266
56522
  )
56267
- return bool(
56268
- references_snapshot
56269
- and (self._shell_command_has_mutation_intent(raw) or scripted_mutation)
56270
- )
56523
+ if not references_snapshot:
56524
+ return False
56525
+ if scripted_mutation:
56526
+ return True
56527
+ # A read-only source in a compound command is not a write target.
56528
+ # In particular cp SOURCE WORKSPACE and a validation command followed
56529
+ # by ls SOURCE were rejected by the old whole-command heuristic. The
56530
+ # OS read-only overlay and post-command integrity check remain the
56531
+ # enforcement layer for indirect/obfuscated writes.
56532
+ in_snapshot = False
56533
+ for clause in re.split(r"&&|\|\||[;\n]", raw):
56534
+ try:
56535
+ tokens = shlex.split(clause)
56536
+ except ValueError:
56537
+ continue
56538
+ if not tokens:
56539
+ continue
56540
+ if tokens[0] in {"if", "elif", "!"}:
56541
+ tokens = tokens[1:]
56542
+ if not tokens:
56543
+ continue
56544
+ executable = tokens[0].replace("\\", "/").rsplit("/", 1)[-1].casefold()
56545
+ args = [token for token in tokens[1:] if not token.startswith("-")]
56546
+ def touches(value):
56547
+ path_text = str(value).replace("\\", "/").casefold()
56548
+ return ".application_skills" in path_text or bool(root and root in path_text)
56549
+ if executable == "cd":
56550
+ in_snapshot = bool(args and touches(args[-1]))
56551
+ continue
56552
+ if re.search(r">{1,2}\s*['\"]?[^\s;|]*\.application_skills", clause, flags=re.IGNORECASE):
56553
+ return True
56554
+ if executable in {"cp", "copy", "xcopy", "robocopy", "install"}:
56555
+ if args and (touches(args[-1]) or in_snapshot):
56556
+ return True
56557
+ continue
56558
+ if executable in {"rm", "rmdir", "del", "erase", "mv", "move", "rename", "chmod", "chown", "touch", "mkdir", "truncate", "tee"}:
56559
+ if in_snapshot or any(touches(token) for token in args):
56560
+ return True
56561
+ if (in_snapshot or any(touches(token) for token in args)) and executable not in {
56562
+ "ls", "dir", "cat", "type", "head", "tail", "wc", "stat", "file", "grep", "rg",
56563
+ "sha256sum", "shasum", "echo", "printf", "diff", "cmp", "test", "[",
56564
+ } and self._shell_command_has_mutation_intent(clause):
56565
+ return True
56566
+ return False
56271
56567
 
56272
56568
  def _hard_snapshot_integrity_callback(self, phase: str, command: str = "") -> str:
56569
+ resource_error = self._verify_skill_execution_workspaces()
56570
+ if resource_error:
56571
+ return resource_error
56273
56572
  if self.skill_mode != "hard":
56274
56573
  return ""
56275
56574
  if str(phase or "") == "before":
@@ -56611,7 +56910,8 @@ body{padding:18px}
56611
56910
  return bool(self._hard_snapshot_shell_prefix())
56612
56911
 
56613
56912
  def _shell_process_env(self) -> dict:
56614
- if not bool(getattr(self, "ide_remote_sandbox_required", False)):
56913
+ if not (bool(getattr(self, "ide_remote_sandbox_required", False))
56914
+ or getattr(self, "skill_mode", "dynamic") == "hard"):
56615
56915
  env = os.environ.copy()
56616
56916
  env.update({"PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"})
56617
56917
  if os.name == "nt":
@@ -56621,7 +56921,7 @@ body{padding:18px}
56621
56921
  else:
56622
56922
  env.update({"LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "LC_CTYPE": "C.UTF-8"})
56623
56923
  return env
56624
- sandbox_tmp = self.files_root / ".clouds_coder" / "tmp"
56924
+ sandbox_tmp = safe_path(".clouds_coder/tmp", self.files_root)
56625
56925
  sandbox_tmp.mkdir(parents=True, exist_ok=True)
56626
56926
  backend_name = str(_detect_ide_sandbox_backend().get("name", "") or "")
56627
56927
  virtual_root = backend_name in {"bubblewrap", "docker", "podman"}
@@ -56655,6 +56955,25 @@ body{padding:18px}
56655
56955
  "PYTHONUTF8": "1",
56656
56956
  }
56657
56957
  )
56958
+ # App sessions use the same workspace write sandbox even on a local
56959
+ # connection. Host HOME/TMP defaults made tempfile and many libraries
56960
+ # write outside it. Allocate real, symlink-checked private directories
56961
+ # and expose their virtual paths when the backend mounts /workspace.
56962
+ cache_dirs = {
56963
+ "XDG_CACHE_HOME": ".clouds_coder/cache/xdg",
56964
+ "XDG_CONFIG_HOME": ".clouds_coder/cache/config",
56965
+ "XDG_DATA_HOME": ".clouds_coder/cache/data",
56966
+ "MPLCONFIGDIR": ".clouds_coder/cache/matplotlib",
56967
+ "PYTHONPYCACHEPREFIX": ".clouds_coder/cache/pycache",
56968
+ "APPDATA": ".clouds_coder/cache/appdata",
56969
+ "LOCALAPPDATA": ".clouds_coder/cache/localappdata",
56970
+ }
56971
+ for key, relative in cache_dirs.items():
56972
+ target = safe_path(relative, self.files_root)
56973
+ target.mkdir(parents=True, exist_ok=True)
56974
+ env[key] = f"/workspace/{relative}" if virtual_root else str(target)
56975
+ if os.name == "nt":
56976
+ env["USERPROFILE"] = process_home
56658
56977
  shared_mounts = self._remote_shared_read_mounts()
56659
56978
  shared_roots = [host for host, _virtual in shared_mounts]
56660
56979
  virtual_shared = {os.path.normcase(str(host)): virtual for host, virtual in shared_mounts}
@@ -58646,7 +58965,7 @@ body{padding:18px}
58646
58965
  "Final output must be a structured markdown deep-analysis report."
58647
58966
  )
58648
58967
 
58649
- def _latest_user_goal_text(self) -> str:
58968
+ def _latest_user_goal_text(self, max_chars: int = 220) -> str:
58650
58969
  for msg in reversed(self.messages):
58651
58970
  if msg.get("role") != "user":
58652
58971
  continue
@@ -58657,7 +58976,7 @@ body{padding:18px}
58657
58976
  continue
58658
58977
  task_text = self._unwrap_program_ide_task_text(text)
58659
58978
  if task_text:
58660
- return trim(task_text.replace("\n", " "), 220)
58979
+ return trim(task_text.replace("\n", " "), max_chars)
58661
58980
  return "current task"
58662
58981
 
58663
58982
  @staticmethod
@@ -59045,6 +59364,7 @@ body{padding:18px}
59045
59364
  last_blocking_idx = -1
59046
59365
  last_success_idx = -1
59047
59366
  last_blocking_ts = 0.0
59367
+ blocking_command = ""
59048
59368
  for idx, row in enumerate(recent):
59049
59369
  row_step_id = str(row.get("plan_step_id", "") or "")
59050
59370
  if current_step_id and row_step_id and row_step_id != current_step_id:
@@ -59057,11 +59377,21 @@ body{padding:18px}
59057
59377
  continue
59058
59378
  if self._execution_log_entry_is_blocking_error(row):
59059
59379
  last_blocking_idx = idx
59380
+ header = re.match(r"^(?:bash|worktree_run|check_background)\s+([^\n]+)", str(row.get("content", "")).strip())
59381
+ blocking_command = str(row.get("command", "") or (header.group(1) if header else ""))
59060
59382
  try:
59061
59383
  last_blocking_ts = float(row.get("ts", 0.0) or 0.0)
59062
59384
  except Exception:
59063
59385
  last_blocking_ts = 0.0
59064
59386
  if self._execution_log_entry_is_success_evidence(row):
59387
+ header = re.match(r"^(?:bash|worktree_run|check_background)\s+([^\n]+)", str(row.get("content", "")).strip())
59388
+ command = str(row.get("command", "") or (header.group(1) if header else ""))
59389
+ if (last_blocking_idx >= 0 and command
59390
+ and self._single_no_plan_todo_bash_is_read_only(command)
59391
+ and (not blocking_command or not self._single_no_plan_todo_bash_is_read_only(blocking_command))):
59392
+ # A successful ls/cat/grep is not a repaired test or run.
59393
+ # Corrected read-only failures can still resolve each other.
59394
+ continue
59065
59395
  last_success_idx = idx
59066
59396
  if last_blocking_idx < 0:
59067
59397
  return False
@@ -59244,7 +59574,10 @@ body{padding:18px}
59244
59574
  if self._todo_has_plan_steps(bb):
59245
59575
  active = self._current_plan_step_row(bb)
59246
59576
  if not isinstance(active, dict):
59247
- return []
59577
+ parents = {str(row.get("id", "")) for row in bb.get("project_todos", [])
59578
+ if isinstance(row, dict) and row.get("category") == "plan_step"}
59579
+ return [row for row in open_rows if self._todo_row_kind(row) == "plan_worker"
59580
+ and str(row.get("parent_step_id", "")) in parents]
59248
59581
  step_id = trim(str(active.get("id", "") or ""), 20)
59249
59582
  if not step_id:
59250
59583
  return []
@@ -59255,7 +59588,7 @@ body{padding:18px}
59255
59588
  ]
59256
59589
  route_kind = self._todo_route_kind(board=bb)
59257
59590
  if route_kind == "pure_sync":
59258
- return [row for row in open_rows if self._todo_row_kind(row) == "owner_worker"]
59591
+ return [row for row in open_rows if self._todo_row_kind(row) in {"owner_worker", "flat"}]
59259
59592
  if route_kind == "pure_single":
59260
59593
  # Single-mode TodoWrite stamps rows with the active owner for UI
59261
59594
  # attribution. Include those rows as well as legacy owner-less
@@ -59272,8 +59605,29 @@ body{padding:18px}
59272
59605
  mode = self._effective_execution_mode()
59273
59606
  profile = self._ensure_blackboard_task_profile(bb)
59274
59607
  assigned = self._sanitize_agent_role(profile.get("assigned_expert", "")) or "developer"
59608
+ if reason_key == "required-todo-missing":
59609
+ return {"target": assigned, "instruction": (
59610
+ "Use TodoWrite to establish the required goal-based checklist from the actual task and observations. "
59611
+ "Do not invent completion or repeat implementation. Track remaining work, verify actual results, "
59612
+ "update the same identities and request finish only when all required work is complete."),
59613
+ "reason": reason_key, "source": "finish-gate", "is_mandatory": True}
59614
+ if reason_key == "plan-approval-pending":
59615
+ return {"target": "explorer", "instruction": (
59616
+ "Complete the pending Plan and request its user approval. Do not execute or finish the task "
59617
+ "before approval; resume planning on the next continuation."),
59618
+ "reason": reason_key, "source": "finish-gate", "is_mandatory": True}
59275
59619
  if reason_key.startswith("plan-steps-incomplete:") or reason_key.startswith("worker-todo-pending:"):
59276
59620
  step = self._current_plan_step_row(bb)
59621
+ if not isinstance(step, dict) and reason_key.startswith("worker-todo-pending:"):
59622
+ pending = self._completion_scoped_open_todo_rows(bb)
59623
+ current = next((row for row in pending if row.get("status") == "in_progress"), pending[0] if pending else {})
59624
+ target = self._sanitize_agent_role(current.get("owner", "")) or assigned
59625
+ identity = current.get("short_id") or current.get("subtask_id") or current.get("id") or ""
59626
+ return {"target": target, "instruction": (
59627
+ f"Finish is blocked by your unfinished canonical Todo {identity}: {trim(str(current.get('content', '')), 220)}. "
59628
+ "Inspect the latest actual evidence, complete or repair this work, then update your own existing "
59629
+ "Todo ID. Preserve peer rows; do not ask another owner to overwrite this row."),
59630
+ "reason": reason_key, "source": "finish-gate", "is_mandatory": True}
59277
59631
  if isinstance(step, dict):
59278
59632
  snapshot = self._active_plan_progress_snapshot(bb)
59279
59633
  step_idx = int(snapshot.get("step_index", 0) or 0) + 1
@@ -59385,11 +59739,18 @@ body{padding:18px}
59385
59739
  ) -> dict:
59386
59740
  bb = board if isinstance(board, dict) else self._ensure_blackboard()
59387
59741
  can_finish, reason = self._can_auto_finish_from_approval(bb, latest_user_ts=latest_user_ts)
59742
+ requires_todos = self._runtime_task_level_for_todo_policy() >= 2 and self._runtime_level_requires_todos()
59743
+ plan = bb.get("plan", {}) if isinstance(bb.get("plan"), dict) else {}
59744
+ if reason not in {"goal-reset-pending", "approval-stale-new-user-input"}:
59745
+ if str(plan.get("phase", "")) in {"research", "synthesis", "awaiting_choice"} and not bool(getattr(self, "runtime_plan_approved", False)):
59746
+ can_finish, reason = False, "plan-approval-pending"
59747
+ elif requires_todos and not self._todo_has_plan_steps(bb) and not self._single_no_plan_todo_has_rows():
59748
+ can_finish, reason = False, "required-todo-missing"
59388
59749
  if can_finish:
59389
59750
  profile = self._ensure_blackboard_task_profile(bb)
59390
59751
  task_type = str(profile.get("task_type", "general") or "general")
59391
59752
  open_rows = self._completion_scoped_open_todo_rows(bb)
59392
- if open_rows and task_type != "simple_qa":
59753
+ if open_rows and (task_type != "simple_qa" or requires_todos):
59393
59754
  can_finish = False
59394
59755
  reason = f"worker-todo-pending:{len(open_rows)}"
59395
59756
  if can_finish and self._manager_has_error_log(bb):
@@ -60850,9 +61211,12 @@ body{padding:18px}
60850
61211
  # and restart without retaining full tool output.
60851
61212
  "plan_subtask_evidence_bindings": {},
60852
61213
  "plan_step_evidence": {},
61214
+ "plan_control_evidence": {},
60853
61215
  "plan_step_quality_reviews": {},
60854
61216
  "plan_step_recovery": {},
60855
61217
  "plan_todo_revisions": [],
61218
+ "user_plan_adjustments": [],
61219
+ "plan_subtask_semantic_reviews": {},
60856
61220
  # Root TodoWrite plans (single and sync without an approved Plan)
60857
61221
  # need the same durable revision protection as plan-step subtasks.
60858
61222
  # The baseline never changes inside a task epoch; accepted/rejected
@@ -60952,16 +61316,49 @@ body{padding:18px}
60952
61316
  board["version"] = 1
60953
61317
  board["updated_at"] = float(src.get("updated_at", now_ts()) or now_ts())
60954
61318
  board["status"] = self._normalize_blackboard_status(src.get("status", board["status"]))
61319
+ preparation_rows = src.get("preparation_decisions", [])
61320
+ if isinstance(preparation_rows, list):
61321
+ board["preparation_decisions"] = [
61322
+ {**{key: str(row.get(key, "") or "")[:limit]
61323
+ for key, limit in (("goal", 1000), ("state", 1600), ("skills", 1200),
61324
+ ("basis", 32), ("owner", 32), ("step_id", 40), ("goal_digest", 64))},
61325
+ "ready": True,
61326
+ "ts": float(row.get("ts", 0)) if isinstance(row.get("ts", 0), (int, float)) else 0.0}
61327
+ for row in preparation_rows[-40:]
61328
+ if isinstance(row, dict) and row.get("ready") is True
61329
+ and row.get("basis") in {"user_context", "observed_context", "continuation"}
61330
+ and re.fullmatch(r"[a-f0-9]{64}", str(row.get("goal_digest", "") or ""))
61331
+ ]
60955
61332
  previous = src.get("previous_task_context", {})
60956
61333
  if isinstance(previous, dict) and previous:
60957
61334
  board["previous_task_context"] = {
60958
61335
  "goal": str(previous.get("goal", "") or "")[:800],
60959
61336
  "summary": str(previous.get("summary", "") or "")[:800],
60960
61337
  "status": str(previous.get("status", "") or "")[:40],
61338
+ **({"task_level": int(previous["task_level"])}
61339
+ if str(previous.get("task_level", "")) in {"1", "2", "3", "4", "5"} else {}),
61340
+ "execution_mode": normalize_execution_mode(previous.get("execution_mode", ""), default=""),
60961
61341
  **{key: [str(value)[:300] for value in previous.get(key, [])[:12]]
60962
61342
  for key in ("artifact_paths", "file_paths", "completed_plan_steps") if isinstance(previous.get(key), list)},
60963
61343
  }
60964
61344
  continuity = src.get("continuation_memory", {})
61345
+ adjustments = src.get("user_plan_adjustments", [])
61346
+ if isinstance(adjustments, list):
61347
+ board["user_plan_adjustments"] = [
61348
+ {"id": str(row["id"])[:80], "step_id": str(row.get("step_id", ""))[:40],
61349
+ "kind": "user_input", "tool": "user_request", "actor": "user", "ok": True,
61350
+ "summary": str(row.get("summary", ""))[:12000], "ts": float(row.get("ts", 0.0) or 0.0)}
61351
+ for row in adjustments[-40:] if isinstance(row, dict)
61352
+ and str(row.get("id", "")).startswith("user:") and row.get("actor") == "user"
61353
+ ]
61354
+ semantic_reviews = src.get("plan_subtask_semantic_reviews", {})
61355
+ if isinstance(semantic_reviews, dict):
61356
+ board["plan_subtask_semantic_reviews"] = {
61357
+ str(step_id)[:40]: {str(row_id)[:100]: dict(review)
61358
+ for row_id, review in list(rows.items())[-40:] if isinstance(review, dict)
61359
+ and review.get("available") and review.get("evidence_signature")}
61360
+ for step_id, rows in list(semantic_reviews.items())[-80:] if isinstance(rows, dict)
61361
+ }
60965
61362
  if isinstance(continuity, dict) and isinstance(continuity.get("keys"), list):
60966
61363
  board["continuation_memory"] = {
60967
61364
  "keys": [str(key)[:40] for key in continuity["keys"][:4]],
@@ -61229,6 +61626,14 @@ body{padding:18px}
61229
61626
  if clean_evidence:
61230
61627
  board["plan_step_evidence"] = clean_evidence
61231
61628
  raw_bindings = src.get("plan_subtask_evidence_bindings")
61629
+ raw_control = src.get("plan_control_evidence", {})
61630
+ if isinstance(raw_control, dict):
61631
+ board["plan_control_evidence"] = {
61632
+ str(step_id)[:40]: [self._normalize_plan_evidence_record(row) for row in rows[-40:]
61633
+ if isinstance(row, dict) and row.get("kind") == "control" and row.get("id")
61634
+ and row.get("step_id") == step_id]
61635
+ for step_id, rows in list(raw_control.items())[-80:] if isinstance(rows, list)
61636
+ }
61232
61637
  if isinstance(raw_bindings, dict):
61233
61638
  clean_bindings: dict[str, dict[str, dict]] = {}
61234
61639
  for raw_step_id, raw_step_bindings in list(raw_bindings.items())[:80]:
@@ -62683,8 +63088,11 @@ body{padding:18px}
62683
63088
  preserved_worker_todos = old_bb.get("plan_worker_todos", {})
62684
63089
  preserved_subtask_bindings = old_bb.get("plan_subtask_evidence_bindings", {})
62685
63090
  preserved_step_evidence = old_bb.get("plan_step_evidence", {})
63091
+ preserved_control_evidence = old_bb.get("plan_control_evidence", {})
62686
63092
  preserved_quality_reviews = old_bb.get("plan_step_quality_reviews", {})
62687
63093
  preserved_todo_revisions = old_bb.get("plan_todo_revisions", [])
63094
+ preserved_user_adjustments = old_bb.get("user_plan_adjustments", [])
63095
+ preserved_semantic_reviews = old_bb.get("plan_subtask_semantic_reviews", {})
62688
63096
  preserved_tree_baseline = old_bb.get("todo_tree_baseline", [])
62689
63097
  preserved_tree_revisions = old_bb.get("todo_tree_revisions", [])
62690
63098
  preserved_step_files = old_bb.get("step_files", {})
@@ -62729,10 +63137,13 @@ body{padding:18px}
62729
63137
  self.blackboard["plan_subtask_evidence_bindings"] = preserved_subtask_bindings
62730
63138
  if isinstance(preserved_step_evidence, dict):
62731
63139
  self.blackboard["plan_step_evidence"] = preserved_step_evidence
63140
+ self.blackboard["plan_control_evidence"] = preserved_control_evidence
62732
63141
  if isinstance(preserved_quality_reviews, dict):
62733
63142
  self.blackboard["plan_step_quality_reviews"] = preserved_quality_reviews
62734
63143
  if isinstance(preserved_todo_revisions, list):
62735
63144
  self.blackboard["plan_todo_revisions"] = preserved_todo_revisions
63145
+ self.blackboard["user_plan_adjustments"] = preserved_user_adjustments
63146
+ self.blackboard["plan_subtask_semantic_reviews"] = preserved_semantic_reviews
62736
63147
  if isinstance(preserved_tree_baseline, list):
62737
63148
  self.blackboard["todo_tree_baseline"] = preserved_tree_baseline
62738
63149
  if isinstance(preserved_tree_revisions, list):
@@ -64010,7 +64421,7 @@ body{padding:18px}
64010
64421
  row = raw if isinstance(raw, dict) else {}
64011
64422
  tool = canonicalize_tool_name(str(row.get("tool", "") or ""))
64012
64423
  kind = str(row.get("kind", "") or "").strip().lower()
64013
- if kind not in {"runtime", "file", "research", "blackboard", "generic"}:
64424
+ if kind not in {"runtime", "file", "research", "blackboard", "generic", "control"}:
64014
64425
  kind = "generic"
64015
64426
  try:
64016
64427
  ts = float(row.get("ts", 0.0) or 0.0)
@@ -64032,6 +64443,7 @@ body{padding:18px}
64032
64443
  "command": trim(str(row.get("command", "") or ""), 500),
64033
64444
  "path": trim(str(row.get("path", "") or ""), 300),
64034
64445
  "summary": trim(str(row.get("summary", "") or ""), 900),
64446
+ "evidence_ref": trim(str(row.get("evidence_ref", "") or ""), 80),
64035
64447
  "changed_files": [
64036
64448
  normalize_rel_preview_path(str(value or ""))
64037
64449
  for value in (row.get("changed_files", []) if isinstance(row.get("changed_files"), list) else [])[:12]
@@ -64094,6 +64506,25 @@ body{padding:18px}
64094
64506
  board=bb,
64095
64507
  since_ts=since_ts,
64096
64508
  )
64509
+ path_revisions: dict[str, float] = {}
64510
+ def path_key(value):
64511
+ return os.path.normcase(str(value or "").replace("\\", "/"))
64512
+ for raw in raw_rows:
64513
+ mutation = self._normalize_plan_evidence_record(raw)
64514
+ if mutation.get("tool") in {"write_file", "edit_file"}:
64515
+ key = path_key(mutation["path"])
64516
+ path_revisions[key] = max(path_revisions.get(key, 0.0), mutation["ts"])
64517
+ for changed_path in mutation.get("changed_files", []):
64518
+ key = path_key(changed_path)
64519
+ path_revisions[key] = max(path_revisions.get(key, 0.0), mutation["ts"])
64520
+ step_files = bb.get("step_files", {})
64521
+ for mutation in step_files.get(str(step_id or ""), []) if isinstance(step_files, dict) else []:
64522
+ if isinstance(mutation, dict) and mutation.get("op") in {"write_file", "edit_file"}:
64523
+ key = path_key(mutation.get("path", ""))
64524
+ try:
64525
+ path_revisions[key] = max(path_revisions.get(key, 0.0), float(mutation.get("ts", 0.0) or 0.0))
64526
+ except (TypeError, ValueError):
64527
+ continue
64097
64528
  out: list[dict] = []
64098
64529
  for raw in raw_rows[-40:]:
64099
64530
  row = self._normalize_plan_evidence_record(raw)
@@ -64101,11 +64532,12 @@ body{padding:18px}
64101
64532
  continue
64102
64533
  if since_ts > 0 and float(row.get("ts", 0.0) or 0.0) + 1e-6 < since_ts:
64103
64534
  continue
64535
+ revision_ts = path_revisions.get(path_key(row.get("path", "")), 0.0) if row.get("tool") == "read_file" else quality_since
64104
64536
  if (
64105
- quality_since > 0
64537
+ revision_ts > 0
64106
64538
  and str(row.get("kind", "") or "") in {"runtime", "file"}
64107
64539
  and str(row.get("tool", "") or "") not in {"write_file", "edit_file"}
64108
- and float(row.get("ts", 0.0) or 0.0) + 1e-6 < quality_since
64540
+ and float(row.get("ts", 0.0) or 0.0) + 1e-6 < revision_ts
64109
64541
  ):
64110
64542
  continue
64111
64543
  out.append(row)
@@ -64153,13 +64585,27 @@ body{padding:18px}
64153
64585
  if normalize_rel_preview_path(str(value or ""))
64154
64586
  ]
64155
64587
  elif tool == "read_file":
64156
- if self._is_plan_infrastructure_read_result(item):
64157
- return {}
64158
- kind = "file"
64588
+ kind = "control" if self._is_plan_infrastructure_read_result(item) else "file"
64159
64589
  command = ""
64160
64590
  path = str(args.get("path", "") or "")
64161
64591
  ok = bool(item.get("ok", False)) and bool(self._tool_result_output_excerpt(item, 80))
64162
64592
  exit_code = None
64593
+ elif tool in {"TodoWrite", "TodoWriteRescue"}:
64594
+ kind = "control"
64595
+ command = path = ""
64596
+ ok = bool(item.get("ok", False)) and not output.lstrip().startswith(("Error:", "Control["))
64597
+ exit_code = None
64598
+ # Store the committed graph, never a model's completion claim.
64599
+ scoped = [row for row in self.todo.snapshot() if row.get("parent_step_id") == step_id]
64600
+ identities = [str(row.get("subtask_id", "") or row.get("short_id", "")) for row in scoped]
64601
+ output = (
64602
+ f"Runtime canonical Todo state: rows={len(scoped)}; unique_ids={len(set(identities)) == len(identities)}\n"
64603
+ + "\n".join(
64604
+ f"{row.get('short_id', '')} [{row.get('status', '')}] {row.get('owner', '')}: "
64605
+ f"{trim(str(row.get('content', '') or ''), 65)}"
64606
+ for row in scoped
64607
+ )
64608
+ )
64163
64609
  elif tool in {"query_code_library", "query_knowledge_library", "agent_web_search"}:
64164
64610
  kind = "research"
64165
64611
  command = ""
@@ -64230,6 +64676,7 @@ body{padding:18px}
64230
64676
  ),
64231
64677
  900,
64232
64678
  ),
64679
+ "evidence_ref": next(iter(reversed(re.findall(r"\[evidence_ref id=([a-f0-9]{24})\b", str(item.get("output", "") or "")))), ""),
64233
64680
  "changed_files": changed_files,
64234
64681
  "exit_code": exit_code,
64235
64682
  "assertion_kind": trim(str(item.get("assertion_kind", "") or ""), 80),
@@ -64239,11 +64686,12 @@ body{padding:18px}
64239
64686
  "actor": self._sanitize_agent_role(role) or "developer",
64240
64687
  "ts": stamp,
64241
64688
  }
64242
- raw_map = dict(bb.get("plan_step_evidence", {}) if isinstance(bb.get("plan_step_evidence"), dict) else {})
64689
+ ledger_key = "plan_control_evidence" if kind == "control" else "plan_step_evidence"
64690
+ raw_map = dict(bb.get(ledger_key, {}) if isinstance(bb.get(ledger_key), dict) else {})
64243
64691
  rows = list(raw_map.get(step_id, []) if isinstance(raw_map.get(step_id), list) else [])
64244
64692
  rows.append(record)
64245
64693
  raw_map[step_id] = rows[-40:]
64246
- bb["plan_step_evidence"] = raw_map
64694
+ bb[ledger_key] = raw_map
64247
64695
  self.blackboard = bb
64248
64696
  return record
64249
64697
 
@@ -66835,7 +67283,7 @@ body{padding:18px}
66835
67283
  plan_step: dict,
66836
67284
  *,
66837
67285
  limit: int = 6,
66838
- max_chars: int = 500,
67286
+ max_chars: int | None = 500,
66839
67287
  ) -> list[dict]:
66840
67288
  rows = bb.get(section, []) if isinstance(bb.get(section), list) else []
66841
67289
  if not rows:
@@ -66847,7 +67295,8 @@ body{padding:18px}
66847
67295
  for row in rows[-40:]:
66848
67296
  if not isinstance(row, dict):
66849
67297
  continue
66850
- txt = trim(str(row.get("content", "") or "").strip(), max_chars)
67298
+ full_text = str(row.get("content", "") or "").strip()
67299
+ txt = full_text if max_chars is None else trim(full_text, max_chars)
66851
67300
  if not txt:
66852
67301
  continue
66853
67302
  clean = {
@@ -66956,12 +67405,26 @@ body{padding:18px}
66956
67405
  for row in context["file_excerpts"]:
66957
67406
  if "_full_content" in row:
66958
67407
  reader.add(row["path"], row.pop("_full_content"))
67408
+ # Excerpts are an input-window optimization, not the archive itself.
67409
+ # Delivery reports and reviewer findings often live on the blackboard;
67410
+ # archiving only their 500-character summaries made their remaining
67411
+ # evidence impossible to retrieve from an independent review context.
67412
+ context["frozen_blackboard_sources"] = []
67413
+ for section, limit in (("execution_logs", 6), ("review_feedback", 6), ("research_notes", 4)):
67414
+ for number, row in enumerate(self._plan_step_quality_recent_rows(
67415
+ bb, section, plan_step, limit=limit, max_chars=None,
67416
+ )):
67417
+ path = f"blackboard/{section}/{number + 1}.txt"
67418
+ reader.add(path, row["content"])
67419
+ context["frozen_blackboard_sources"].append({"path": path, "actor": row["actor"],
67420
+ "meaning": "Frozen report/observation; runtime success still requires actual execution evidence."})
66959
67421
  context["frozen_artifact_index"] = reader.index
66960
67422
  rendered = json_dumps(trajectory_model_view(context), indent=2)
66961
67423
  return (rendered, reader) if return_runtime else rendered
66962
67424
 
66963
67425
  def _read_only_review_json(self, prompt: str, system: str, reader, *, max_tokens: int = 420) -> dict:
66964
- from liquid_kernel.context import RECALL_TOOL, ContextWindow
67426
+ from liquid_kernel.context import RECALL_TOOL, ContextWindow, estimate_tokens
67427
+ max_tokens = max(1, int(getattr(self, "max_output_tokens", AGENT_MAX_OUTPUT_TOKENS) or AGENT_MAX_OUTPUT_TOKENS))
66965
67428
  messages = [{"role": "user", "content": prompt}]
66966
67429
  window = ContextWindow(reader.archive, self.context_token_upper_bound, "review")
66967
67430
  # Each review owns its conversation and JSON-mode flag; all clients
@@ -66977,8 +67440,14 @@ body{padding:18px}
66977
67440
  request_system, request_messages = system, messages
66978
67441
  if format_attempts == 2:
66979
67442
  request_system, request_messages = semantic_json_repair_request(system + "\n" + prompt, damaged_output, "review_json_invalid")
66980
- visible = window.prepare(request_messages, request_system, tools, max_tokens)
66981
- response = client.chat(visible, tools=tools, system=request_system, max_tokens=max_tokens, temperature=0.1,
67443
+ # Honor Admin's output ceiling whenever it fits. A smaller context
67444
+ # cannot physically reserve a larger output window; compact first
67445
+ # and use the actual remaining capacity, without a fixed token cap.
67446
+ fixed_tokens = estimate_tokens(request_system) + estimate_tokens(tools or [])
67447
+ reserve = min(max_tokens, max(128, window.context_limit - fixed_tokens - estimate_tokens(request_messages) - 1024))
67448
+ visible = window.prepare(request_messages, request_system, tools, reserve)
67449
+ request_max_tokens = min(max_tokens, max(1, window.context_limit - fixed_tokens - estimate_tokens(visible) - 128))
67450
+ response = client.chat(visible, tools=tools, system=request_system, max_tokens=request_max_tokens, temperature=0.1,
66982
67451
  think=bool(getattr(self, "thinking", False)),
66983
67452
  effort="off" if format_attempts == 2 else self._profile_effort_bounds()[0], label="independent_review")
66984
67453
  calls = response.get("tool_calls") or []
@@ -68381,6 +68850,34 @@ body{padding:18px}
68381
68850
  except Exception:
68382
68851
  pass
68383
68852
 
68853
+ def _todo_json_response(self, messages: list[dict], **kwargs) -> dict:
68854
+ """Obtain a final JSON answer without treating reasoning as a verdict.
68855
+
68856
+ Reasoning and answer tokens share the output allowance on some APIs.
68857
+ Small audit-only caps can therefore prevent a perfectly healthy model
68858
+ from ever returning its verdict. Use the session's Admin output limit;
68859
+ one format retry still consumes the existing TodoWrite call budget.
68860
+ """
68861
+ kwargs["max_tokens"] = max(1, int(getattr(self, "max_output_tokens", AGENT_MAX_OUTPUT_TOKENS) or AGENT_MAX_OUTPUT_TOKENS))
68862
+ kwargs.setdefault("label", "todo_audit")
68863
+ kwargs.setdefault("request_timeout", TODO_LLM_TIMEOUT_SECONDS)
68864
+ original = [dict(row) for row in messages]
68865
+ for attempt in range(2):
68866
+ response = self.ollama.chat(messages, **kwargs)
68867
+ text = str(response.get("content", "") or response.get("text", "") or "").strip()
68868
+ payload = extract_json_object_from_text(text, {})
68869
+ if isinstance(payload, dict) and payload:
68870
+ return response
68871
+ if attempt == 0:
68872
+ # Re-evaluate the same evidence. An unfinished reasoning trace
68873
+ # is neither a submitted decision nor proof of completion.
68874
+ messages = original + [{"role": "user", "content": (
68875
+ "Your previous response did not contain a complete final JSON object. "
68876
+ "Evaluate the same supplied evidence and submit the requested JSON now. "
68877
+ "Keep reasons concise. Return no prose outside JSON; do not invent missing evidence."
68878
+ )}]
68879
+ return response
68880
+
68384
68881
  def _llm_verify_subtask_acceptance(self, plan_step: dict, completed_subtasks: list[dict], bb: dict) -> dict:
68385
68882
  """Use LLM semantic analysis to verify if subtasks are truly completed.
68386
68883
 
@@ -68420,7 +68917,7 @@ body{padding:18px}
68420
68917
  "Reply ONLY as JSON: {\"all_passed\": true/false, \"rework_items\": [\"description of what failed\"]}\n"
68421
68918
  "If all subtasks pass, return {\"all_passed\": true, \"rework_items\": []}"
68422
68919
  )
68423
- resp = self.ollama.chat(
68920
+ resp = self._todo_json_response(
68424
68921
  [{"role": "user", "content": prompt}],
68425
68922
  system=self._inject_runtime_environment_context("You are a strict QA reviewer. Verify task completion against evidence. Reply ONLY valid JSON."),
68426
68923
  max_tokens=300,
@@ -68567,7 +69064,7 @@ body{padding:18px}
68567
69064
  "\"evidence\": \"<cite the specific evidence you relied on>\", "
68568
69065
  "\"rework_items\": [\"<what concretely must still be fixed if FAIL>\"]}"
68569
69066
  )
68570
- resp = self.ollama.chat(
69067
+ resp = self._todo_json_response(
68571
69068
  [{"role": "user", "content": prompt}],
68572
69069
  system=self._inject_runtime_environment_context(
68573
69070
  "You are a strict, evidence-driven QA judge for plan-step acceptance. "
@@ -69161,6 +69658,11 @@ body{padding:18px}
69161
69658
  "CURRENT PLAN:\n" + ("\n".join(lines) or "(none)")
69162
69659
  + "\n\nCURRENT WORKER TODOs:\n" + ("\n".join(worker_lines) or "(none)")
69163
69660
  + "\n\nRECENT PROGRESS EVIDENCE:\n" + ("\n".join(f"- {item}" for item in evidence[-16:]) or "(none)")
69661
+ + "\n\nAUTHENTICATED USER ADJUSTMENTS (requirements, not completion proof):\n"
69662
+ + ("\n".join(
69663
+ f"- {row.get('id', '')}: {trim(str(row.get('summary', '') or ''), 1200)}"
69664
+ for row in (bb.get("user_plan_adjustments", []) or [])[-8:] if isinstance(row, dict)
69665
+ ) or "(none)")
69164
69666
  )
69165
69667
 
69166
69668
  def _semantic_audit_plan_step_updates(
@@ -69208,7 +69710,7 @@ body{padding:18px}
69208
69710
  + self._plan_step_revision_context(bb)
69209
69711
  )
69210
69712
  try:
69211
- response = self.ollama.chat(
69713
+ response = self._todo_json_response(
69212
69714
  [{"role": "user", "content": prompt}],
69213
69715
  system=self._inject_runtime_environment_context(
69214
69716
  "/no_think\nYou audit multi-step execution-plan edits. Reply only valid JSON."
@@ -69338,7 +69840,7 @@ body{padding:18px}
69338
69840
  try:
69339
69841
  target = next(
69340
69842
  row for row in plan_rows
69341
- if int(row.get("plan_step_index", -1) or -1) == int(update.get("plan_step_index"))
69843
+ if int(row.get("plan_step_index", -1)) == int(update.get("plan_step_index"))
69342
69844
  )
69343
69845
  except Exception:
69344
69846
  target = None
@@ -69379,6 +69881,8 @@ body{padding:18px}
69379
69881
  if (
69380
69882
  normalize_embedded_newlines(str(proposal.get("content", "") or ""))
69381
69883
  != normalize_embedded_newlines(str(target.get("content", "") or ""))
69884
+ or normalize_embedded_newlines(str(proposal.get("full_content", "") or ""))
69885
+ != normalize_embedded_newlines(str(target.get("full_content", "") or ""))
69382
69886
  or proposal.get("status") != target.get("status")
69383
69887
  ):
69384
69888
  changed_ids.append(target_id)
@@ -69586,7 +70090,7 @@ body{padding:18px}
69586
70090
  + self._plan_step_revision_context(bb)
69587
70091
  )
69588
70092
  try:
69589
- response = self.ollama.chat(
70093
+ response = self._todo_json_response(
69590
70094
  [{"role": "user", "content": prompt}],
69591
70095
  system=self._inject_runtime_environment_context(
69592
70096
  "/no_think\nClassify Todo intent. Reply only valid JSON."
@@ -69692,7 +70196,7 @@ body{padding:18px}
69692
70196
  f"EXISTING CANONICAL ROOT TODOS:\n{rows_text}"
69693
70197
  )
69694
70198
  try:
69695
- response = self.ollama.chat(
70199
+ response = self._todo_json_response(
69696
70200
  [{"role": "user", "content": prompt}],
69697
70201
  system=self._inject_runtime_environment_context(
69698
70202
  "/no_think\nResolve Todo identity from the supplied canonical rows. Reply only valid JSON."
@@ -70121,6 +70625,27 @@ body{padding:18px}
70121
70625
  )
70122
70626
  return bool(trusted)
70123
70627
 
70628
+ def _plan_evidence_full_observation(self, record: dict) -> str:
70629
+ """Resolve an immutable host tool result, never a current-file substitute."""
70630
+ reference = str(record.get("evidence_ref", "") or "")
70631
+ if not re.fullmatch(r"[a-f0-9]{24}", reference):
70632
+ return ""
70633
+ try:
70634
+ matches = self._evidence_controller().recall(eid=reference, limit=1)
70635
+ if not matches:
70636
+ return ""
70637
+ observation = matches[0]
70638
+ if canonicalize_tool_name(observation.get("tool", "")) != record.get("tool"):
70639
+ return ""
70640
+ arguments = json.loads(observation.get("args", "{}"))
70641
+ if record.get("command") and trim(str(arguments.get("command", "")), 500) != record["command"]:
70642
+ return ""
70643
+ if record.get("path") and trim(str(arguments.get("path", "")), 300) != record["path"]:
70644
+ return ""
70645
+ return str(observation.get("body", "") or "")
70646
+ except (OSError, ValueError, TypeError, sqlite3.Error):
70647
+ return ""
70648
+
70124
70649
  def _plan_subtask_semantic_evidence_signature(
70125
70650
  self,
70126
70651
  plan_step: dict,
@@ -70144,7 +70669,16 @@ body{padding:18px}
70144
70669
  board=bb,
70145
70670
  since_ts=lower_bound,
70146
70671
  ) if step_id else []
70672
+ # Planning operations are observable work only for a semantic audit
70673
+ # of a planning/maintenance subtask. Keep them out of product/acceptance
70674
+ # ledgers so editing a checklist cannot prove implementation or tests.
70675
+ control_map = bb.get("plan_control_evidence", {})
70676
+ controls = control_map.get(step_id, []) if isinstance(control_map, dict) else []
70677
+ candidates.extend(dict(record) for record in controls if isinstance(record, dict)
70678
+ and float(record.get("ts", 0.0) or 0.0) >= lower_bound)
70679
+ candidates.sort(key=lambda record: float(record.get("ts", 0.0) or 0.0))
70147
70680
  payload = {
70681
+ "protocol": "full-observation-v2",
70148
70682
  "step_id": step_id,
70149
70683
  "subtask_id": stable_id,
70150
70684
  "subtask": trim(str(row.get("content", "") or ""), 800),
@@ -70158,6 +70692,7 @@ body{padding:18px}
70158
70692
  str(record.get("path", "") or ""),
70159
70693
  tuple(str(value or "") for value in (record.get("changed_files", []) or [])),
70160
70694
  trim(str(record.get("summary", "") or ""), 500),
70695
+ str(record.get("evidence_ref", "") or ""),
70161
70696
  )
70162
70697
  for record in candidates[-16:]
70163
70698
  ],
@@ -70291,6 +70826,19 @@ body{padding:18px}
70291
70826
  )
70292
70827
  for record in candidates
70293
70828
  ]
70829
+ from liquid_kernel.context import HistoryArchive, ReviewEvidence
70830
+ reader = None
70831
+ for record in candidates:
70832
+ body = self._plan_evidence_full_observation(record)
70833
+ if not body:
70834
+ continue
70835
+ if reader is None:
70836
+ reader = ReviewEvidence(HistoryArchive(self.root / "context_archive" / "todo_reviews" / uuid.uuid4().hex / "full_history.jsonl"),
70837
+ excerpt_head=3000, excerpt_tail=1000, max_inline_chars=6000)
70838
+ path = f"tool_observations/{record['id'].replace(':', '_')}.txt"
70839
+ reader.add(path, body)
70840
+ preview = body if len(body) <= 6000 else body[:3000] + "\n[omitted immutable output; use context_recall]\n" + body[-1000:]
70841
+ evidence_lines.append(f"EXACT OBSERVATION ID={record['id']} path={path}:\n{preview}")
70294
70842
  review = dict(default)
70295
70843
  review["evidence_signature"] = signature
70296
70844
  review["subtask_id"] = stable_id
@@ -70301,6 +70849,11 @@ body{padding:18px}
70301
70849
  "not the verdict. Decide pass only when the records concretely prove this subtask's intended result. "
70302
70850
  "Equivalent implementation/verification methods are allowed, but evidence for another subtask is not. "
70303
70851
  "Use verify when proof is insufficient and repair only when a real defect is shown. Never pass a claim without tool evidence.\n\n"
70852
+ "Records marked control prove only the actual Todo/plan maintenance they show; "
70853
+ "they cannot establish product implementation, test execution, or artifact correctness.\n\n"
70854
+ "For a Todo-maintenance subtask, audit the recorded mutations and retained identities. "
70855
+ "Do not require this target's completed bit to be set before this completion audit; "
70856
+ "that would make the requested transition circular.\n\n"
70304
70857
  f"PARENT STEP:\n{trim(str(plan_step.get('full_content', '') or plan_step.get('content', '') or ''), 1400)}\n\n"
70305
70858
  f"SUBTASK:\n{trim(str(row.get('content', '') or ''), 800)}\n\n"
70306
70859
  f"EVIDENCE RECORDS:\n{chr(10).join(evidence_lines)}\n\n"
@@ -70308,17 +70861,23 @@ body{padding:18px}
70308
70861
  "\"confidence\":\"high|medium|low\",\"reason\":\"...\",\"evidence\":\"...\","
70309
70862
  "\"evidence_ids\":[\"ID from records\"]}"
70310
70863
  )
70311
- resp = self.ollama.chat(
70312
- [{"role": "user", "content": prompt}],
70313
- system=self._inject_runtime_environment_context(
70314
- "/no_think\nYou are a strict evidence-grounded subtask auditor. Reply only valid JSON."
70315
- ),
70316
- max_tokens=360,
70317
- temperature=0.1,
70318
- think=False,
70319
- label="todo_audit",
70320
- request_timeout=TODO_LLM_TIMEOUT_SECONDS,
70864
+ audit_system = self._inject_runtime_environment_context(
70865
+ "/no_think\nYou are a strict evidence-grounded subtask auditor. Reply only valid JSON."
70321
70866
  )
70867
+ if reader is not None:
70868
+ prompt += "\nFROZEN TOOL OBSERVATIONS:\n" + json_dumps(reader.index)
70869
+ payload = self._read_only_review_json(prompt, audit_system, reader)
70870
+ resp = {"content": json_dumps(payload)}
70871
+ else:
70872
+ resp = self._todo_json_response(
70873
+ [{"role": "user", "content": prompt}],
70874
+ system=audit_system,
70875
+ max_tokens=360,
70876
+ temperature=0.1,
70877
+ think=False,
70878
+ label="todo_audit",
70879
+ request_timeout=TODO_LLM_TIMEOUT_SECONDS,
70880
+ )
70322
70881
  raw = str(resp.get("content", "") or resp.get("text", "") or "").strip()
70323
70882
  payload = extract_json_object_from_text(raw, {})
70324
70883
  if isinstance(payload, dict) and "passed" in payload:
@@ -71708,6 +72267,15 @@ body{padding:18px}
71708
72267
  step_id = trim(str((plan_step or {}).get("id", "") or ""), 40)
71709
72268
  rows = self._plan_step_evidence_records(step_id, board=bb, since_ts=since_ts)
71710
72269
  feedback = bb.get("review_feedback", []) if isinstance(bb.get("review_feedback"), list) else []
72270
+ # These records originate at user-input injection, not model tool calls.
72271
+ # A changed requirement can justify a revision, never task completion.
72272
+ plan_ids = {str(row.get("id", "")) for row in bb.get("project_todos", [])
72273
+ if isinstance(row, dict) and row.get("category") == "plan_step"}
72274
+ rows.extend(
72275
+ dict(row) for row in (bb.get("user_plan_adjustments", []) or [])
72276
+ if isinstance(row, dict) and row.get("tool") == "user_request" and row.get("actor") == "user"
72277
+ and (row.get("step_id") == step_id or row.get("step_id") in plan_ids)
72278
+ )
71711
72279
  for index, raw in enumerate(feedback[-16:]):
71712
72280
  if not isinstance(raw, dict):
71713
72281
  continue
@@ -71838,7 +72406,9 @@ body{padding:18px}
71838
72406
  "Audit a proposed rolling revision of only the OPEN subtasks under one approved plan step.\n"
71839
72407
  "Approve only when the cited observable evidence logically requires or materially justifies the exact additions, removals, rewrites, splits, merges, or reorderings.\n"
71840
72408
  "Reject speculative optimization, unrelated evidence, scope drift into another plan step, deletion of still-required work, or a reason that merely restates the proposal.\n"
71841
- "Completed history is protected outside this proposal. Judge the open-part revision against the approved parent step.\n"
72409
+ "Completed history is protected outside this proposal. Judge the open-part revision against the approved parent step. "
72410
+ "Authenticated user_request records may change requirements and take precedence over older plan details; "
72411
+ "they do not prove work completed. Acceptance criteria must remain covered.\n"
71842
72412
  "Return JSON only: {\"approved\":true|false,\"confidence\":\"high|medium|low\",\"reason\":\"...\",\"unsupported_changes\":[\"...\"]}.\n\n"
71843
72413
  f"APPROVED PARENT STEP:\n{step_text}\n\n"
71844
72414
  f"REVISION REASON:\n{trim(reason, 600)}\n\n"
@@ -71850,7 +72420,7 @@ body{padding:18px}
71850
72420
  + ("\n".join(evidence_lines) or "(none)")
71851
72421
  )
71852
72422
  try:
71853
- response = self.ollama.chat(
72423
+ response = self._todo_json_response(
71854
72424
  [{"role": "user", "content": prompt}],
71855
72425
  system=self._inject_runtime_environment_context(
71856
72426
  "/no_think\nYou are an independent execution-plan revision auditor. Reply only valid JSON."
@@ -71994,14 +72564,12 @@ body{padding:18px}
71994
72564
  for row in existing_rows
71995
72565
  if isinstance(row, dict)
71996
72566
  and str(row.get("status", "pending") or "pending").lower() != "completed"
71997
- and not self._is_plan_step_acceptance_subtask(row.get("content", ""))
71998
72567
  ]
71999
72568
  after_open = [
72000
72569
  self._plan_worker_content_core(row.get("content", ""))
72001
72570
  for row in proposed_rows
72002
72571
  if isinstance(row, dict)
72003
72572
  and str(row.get("status", "pending") or "pending").lower() != "completed"
72004
- and not self._is_plan_step_acceptance_subtask(row.get("content", ""))
72005
72573
  ]
72006
72574
  if before_open == after_open:
72007
72575
  return {"ok": True, "structural": False, "evidence_ids": [], "reason": "status-only update"}
@@ -72407,7 +72975,7 @@ body{padding:18px}
72407
72975
  + ("\n".join(f"- {value}" for value in evidence) or "(none)")
72408
72976
  )
72409
72977
  try:
72410
- response = self.ollama.chat(
72978
+ response = self._todo_json_response(
72411
72979
  [{"role": "user", "content": prompt}],
72412
72980
  system=self._inject_runtime_environment_context(
72413
72981
  "/no_think\nYou audit Todo-tree rewrites for requirement preservation. Reply only valid JSON."
@@ -72969,11 +73537,17 @@ body{padding:18px}
72969
73537
  before_open, after_open, removed = self._root_todo_material_changes(existing_scope, proposed_scope)
72970
73538
  evidence = self._root_todo_revision_evidence(revision_evidence, board=bb)
72971
73539
  baseline = self._ensure_root_todo_baseline(existing_scope, board=bb)
73540
+ # The transaction replaces only this owner's slice, but the reviewer
73541
+ # must see the actual complete graph that will be committed. Showing a
73542
+ # global baseline beside an owner-only proposal falsely reports every
73543
+ # peer obligation as deleted, then tells the model to write peer IDs
73544
+ # that the ownership guard correctly rejects.
73545
+ peer_rows = [dict(row) for row in preserved_rows if self._todo_row_kind(row) != "system"]
72972
73546
  review = self._semantic_audit_root_todo_revision(
72973
73547
  reason=reason,
72974
73548
  baseline=baseline,
72975
- current_rows=existing_scope,
72976
- proposed_rows=proposed_scope,
73549
+ current_rows=peer_rows + existing_scope,
73550
+ proposed_rows=peer_rows + proposed_scope,
72977
73551
  removed_objectives=removed,
72978
73552
  evidence=evidence,
72979
73553
  )
@@ -73325,6 +73899,7 @@ body{padding:18px}
73325
73899
  subtask_id, _matched = _existing_match(row)
73326
73900
  row["subtask_id"] = subtask_id or self._stable_plan_worker_subtask_id(step_id, row)
73327
73901
 
73902
+ matched_existing: list[tuple[dict, str, dict]] = []
73328
73903
  if trusted_restore:
73329
73904
  current_step_rows = [dict(row) for row in incoming_worker_rows]
73330
73905
  elif not target_rows:
@@ -73432,7 +74007,7 @@ body{padding:18px}
73432
74007
  incoming_status = "completed"
73433
74008
  if prior_status != "completed" and incoming_status == "completed":
73434
74009
  since_value = float(prior.get("created_at", 0.0) or prior.get("started_at", 0.0) or 0.0)
73435
- completion_candidate = {**prior, **incoming, "subtask_id": subtask_id}
74010
+ completion_candidate = {**prior, **incoming, "subtask_id": subtask_id, "content": prior["content"]}
73436
74011
  if not self._plan_worker_completion_has_evidence(
73437
74012
  active_step,
73438
74013
  completion_candidate,
@@ -73718,6 +74293,24 @@ body{padding:18px}
73718
74293
  # the canonical N.M scheme instead of inventing a parallel set.
73719
74294
  if mode == "status_update":
73720
74295
  result = self._todo_status_update_result(result, status_update_omitted)
74296
+ ignored_edits = [
74297
+ str(prior.get("short_id", "") or subtask_id)
74298
+ for incoming, subtask_id, prior in matched_existing
74299
+ if self._plan_worker_content_core(incoming.get("content", ""))
74300
+ and self._plan_worker_content_core(incoming.get("content", ""))
74301
+ != self._plan_worker_content_core(prior.get("content", ""))
74302
+ and not self._plan_worker_content_core(prior.get("content", "")).startswith(
74303
+ self._plan_worker_content_core(incoming.get("content", ""))
74304
+ )
74305
+ ] if target_rows else []
74306
+ if ignored_edits:
74307
+ result += (
74308
+ "\nCONTENT NOT REVISED: status_update preserved the stored contract for "
74309
+ + ", ".join(ignored_edits[:8])
74310
+ + ". For changed user requirements use plan_updates for affected OPEN parent contracts "
74311
+ "and revise_open for the full open child snapshot, including acceptance; cite the user: "
74312
+ "revision evidence from the live-input notice. Do not repeat checks against an obsolete contract."
74313
+ )
73721
74314
  committed_rows = [row for row in self.todo.snapshot() if row.get("parent_step_id") == step_id]
73722
74315
  canonical = self._render_plan_worker_todo_canonical(step_id, committed_rows)
73723
74316
  if canonical:
@@ -74873,7 +75466,7 @@ body{padding:18px}
74873
75466
  f"ACTIVE PLAN STEP:\n{step_text}\n\n"
74874
75467
  f"WORK SUBTASKS BEFORE ACCEPTANCE:\n{work_text or '(none)'}"
74875
75468
  )
74876
- resp = self.ollama.chat(
75469
+ resp = self._todo_json_response(
74877
75470
  [{"role": "user", "content": prompt}],
74878
75471
  system=self._inject_runtime_environment_context(
74879
75472
  "/no_think\nYou write one final acceptance TodoWrite subtask. Reply only valid JSON."
@@ -76061,7 +76654,7 @@ body{padding:18px}
76061
76654
  f"Return JSON only: {{\"subtasks\":[\"...\" ]}} with 3-{max_items} concise items.\n\n"
76062
76655
  f"ACTIVE PLAN STEP:\n{step_text}"
76063
76656
  )
76064
- resp = self.ollama.chat(
76657
+ resp = self._todo_json_response(
76065
76658
  [{"role": "user", "content": prompt}],
76066
76659
  system=self._inject_runtime_environment_context(
76067
76660
  "/no_think\nYou decompose one active plan step into concrete, ordered worker subtasks. Reply only valid JSON."
@@ -76951,7 +77544,11 @@ body{padding:18px}
76951
77544
  bb = board if isinstance(board, dict) else self._ensure_blackboard()
76952
77545
  route_kind = self._todo_route_kind(board=bb)
76953
77546
  has_plan_steps = route_kind in {"plan_single", "plan_sync"}
76954
- if route_kind == "pure_single":
77547
+ if route_kind in {"pure_single", "pure_sync"}:
77548
+ # Without an approved Plan, TodoWrite owns the canonical graph.
77549
+ # Rebuilding a sync projection from only the currently active owner
77550
+ # discarded peer rows and inserted a second generic roadmap.
77551
+ # Owner-scoped writes already preserve every other owner's rows.
76955
77552
  return
76956
77553
  self._init_project_todos(bb)
76957
77554
  self._update_project_todo_status(bb)
@@ -77444,6 +78041,14 @@ body{padding:18px}
77444
78041
  "semantic_confidence": {"type": "string", "enum": list(SEMANTIC_CONFIDENCE_CHOICES)},
77445
78042
  "low_confidence_reason": {"type": "string"},
77446
78043
  "inherit_previous_state": {"type": "boolean"},
78044
+ "followup_development": {
78045
+ "type": "boolean",
78046
+ "description": (
78047
+ "Whether the latest request asks for implementation, changes, or validation "
78048
+ "after a completed L4 development task. Pure questions, explanations, greetings "
78049
+ "and thanks are false, even when they mention code or the previous project."
78050
+ ),
78051
+ },
77447
78052
  "plan_change_scope": {
77448
78053
  "type": "string",
77449
78054
  "enum": ["preserve", "replace_entire_plan"],
@@ -77486,6 +78091,7 @@ body{padding:18px}
77486
78091
  "judgement",
77487
78092
  "requires_todos",
77488
78093
  "inherit_previous_state",
78094
+ "followup_development",
77489
78095
  "plan_change_scope",
77490
78096
  "plan_change_evidence",
77491
78097
  "requires_plan",
@@ -77588,6 +78194,8 @@ body{padding:18px}
77588
78194
  f"Automatic task-level ceiling is L{cap}. Do not emit or route a level above L{cap}. "
77589
78195
  f"If the request would normally need a higher level, choose L{cap}, keep the objective concrete, "
77590
78196
  "and mention in judgement that the automatic ceiling was applied. "
78197
+ "The ceiling limits execution policy, not the user's requested deliverables; do not silently "
78198
+ "drop requirements or replace their objective with a smaller demonstration. "
77591
78199
  "This cap only affects automatic classification; explicit user task-level overrides are handled elsewhere.\n"
77592
78200
  )
77593
78201
 
@@ -77656,34 +78264,12 @@ body{padding:18px}
77656
78264
  return out
77657
78265
 
77658
78266
  def _fallback_task_level_decision(self, goal_text: str) -> dict:
78267
+ goal_text = self._unwrap_program_ide_task_text(goal_text)
77659
78268
  profile = self._infer_task_profile(goal_text)
77660
78269
  task_type = str(profile.get("task_type", "general") or "general")
77661
78270
  complexity = normalize_task_complexity(profile.get("complexity", "simple"), default="simple")
77662
78271
  low = str(goal_text or "").lower()
77663
- inherit_previous_state = False
77664
- if bool(self.runtime_goal_reset_pending):
77665
- board = self._ensure_blackboard()
77666
- progress = self._manager_progress_state(board)
77667
- has_progress = bool(
77668
- len(board.get("research_notes", []) or [])
77669
- or len(board.get("code_artifacts", {}) or {})
77670
- or len(board.get("execution_logs", []) or [])
77671
- or len(board.get("review_feedback", []) or [])
77672
- )
77673
- if has_progress and progress in {"in_progress", "almost_done", "blocked", "initializing"}:
77674
- inherit_previous_state = True
77675
- # Also inherit if there's an active high-level task regardless of goal_reset_pending
77676
- if not inherit_previous_state and int(self.runtime_task_level or 0) >= 3:
77677
- board = self._ensure_blackboard()
77678
- progress = self._manager_progress_state(board)
77679
- has_progress = bool(
77680
- len(board.get("research_notes", []) or [])
77681
- or len(board.get("code_artifacts", {}) or {})
77682
- or len(board.get("execution_logs", []) or [])
77683
- or len(board.get("review_feedback", []) or [])
77684
- )
77685
- if has_progress and progress in {"in_progress", "almost_done", "blocked", "initializing"}:
77686
- inherit_previous_state = True
78272
+ inherit_previous_state = bool(self._unfinished_task_level())
77687
78273
  if bool(inherit_previous_state):
77688
78274
  board = self._ensure_blackboard()
77689
78275
  current_profile = self._ensure_blackboard_task_profile(board)
@@ -77861,9 +78447,11 @@ body{padding:18px}
77861
78447
  base = (
77862
78448
  "You are Manager. Classify the latest user request by semantic intent, not by keyword templates.\n"
77863
78449
  "Decide whether this latest turn should inherit the previous blackboard/task state.\n"
77864
- "Set inherit_previous_state=true only for genuine follow-up/continuation/refinement of the same ongoing work; "
77865
- "set it false for a new independent objective.\n"
77866
- "If an approved plan is executing, default plan_change_scope='preserve' and inherit_previous_state=true. "
78450
+ "An unfinished task retains its previous level and execution state, subject to the automatic level ceiling. "
78451
+ "Set inherit_previous_state=true while that task is unfinished. Once the previous task is completed or "
78452
+ "aborted, set it false and classify the latest request afresh; old artifacts and message length do not "
78453
+ "justify retaining its level.\n"
78454
+ "If an approved plan is executing and the task has not ended, default plan_change_scope='preserve' and inherit_previous_state=true. "
77867
78455
  "Feedback, current-step repair, acceptance work, and current-subtask changes preserve the roadmap. "
77868
78456
  "Use plan_change_scope='replace_entire_plan' only when the latest user message explicitly asks to discard, "
77869
78457
  "replace, or redesign the whole approved roadmap. plan_change_evidence must be the shortest exact quote "
@@ -77873,6 +78461,14 @@ body{padding:18px}
77873
78461
  "LEVEL SELECTION CRITERIA (choose the single best-fit level):\n"
77874
78462
  "Level 1 — Instant answer: pure Q&A, factual lookup, brief explanation, single-concept clarification. "
77875
78463
  "No file I/O, no tool use, no multi-turn needed. Budget: 2-4 rounds.\n"
78464
+ "Greetings, thanks, and short conceptual programming questions (for example 'What is Python?', "
78465
+ "'What is an API?' or 'Explain a function') are L1 when only an answer is requested. "
78466
+ "A programming topic, workspace path, IDE metadata, or available skill is not an instruction to edit files. "
78467
+ "Classify the requested action and deliverable, not isolated topic keywords.\n"
78468
+ "AFTER A COMPLETED L4 TASK: emit followup_development=true for a new development requirement. "
78469
+ "Choose L3 for bounded implementation/verification and L4 for coordinated multi-component work, "
78470
+ "subject to the automatic ceiling. Pure conceptual questions or explanations remain eligible for L1 "
78471
+ "and must use followup_development=false; do not inherit an ended task merely to answer a question.\n"
77876
78472
  "Level 2 — Multi-turn answer / light task: longer explanation, code snippet review, minor single-file edit, "
77877
78473
  "short script, quick translation or summary. Single agent, no collaboration needed. Budget: 4-8 rounds. "
77878
78474
  "The Todo requirement for L2 is controlled by the runtime policy below; when requires_todos=true, "
@@ -77946,6 +78542,13 @@ body{padding:18px}
77946
78542
  def _extract_classify_task_level_row(self, response: dict | None) -> dict:
77947
78543
  if not isinstance(response, dict):
77948
78544
  return {}
78545
+ def valid_row(value: object) -> dict:
78546
+ if not isinstance(value, dict):
78547
+ return {}
78548
+ raw = value.get("level")
78549
+ if isinstance(raw, bool) or not re.fullmatch(r"[1-5]", str(raw).strip()):
78550
+ return {}
78551
+ return {**value, "level": int(raw)}
77949
78552
  tool_calls = response.get("tool_calls", []) if isinstance(response.get("tool_calls", []), list) else []
77950
78553
  for tc in tool_calls:
77951
78554
  fn = tc.get("function", {}) if isinstance(tc, dict) else {}
@@ -77953,16 +78556,18 @@ body{padding:18px}
77953
78556
  continue
77954
78557
  args = fn.get("arguments", {}) if isinstance(fn, dict) else {}
77955
78558
  if isinstance(args, dict):
77956
- return dict(args)
78559
+ parsed = valid_row(args)
78560
+ if parsed:
78561
+ return parsed
77957
78562
  if isinstance(args, str):
77958
78563
  parsed, _ = parse_tool_arguments_with_error(args)
77959
- if isinstance(parsed, dict):
77960
- return dict(parsed)
78564
+ parsed = valid_row(parsed)
78565
+ if parsed:
78566
+ return parsed
77961
78567
  content = str(response.get("content", "") or "").strip()
77962
78568
  if content:
77963
78569
  parsed, _ = parse_tool_arguments_with_error(content)
77964
- if isinstance(parsed, dict) and parsed.get("level") is not None:
77965
- return dict(parsed)
78570
+ return valid_row(parsed)
77966
78571
  return {}
77967
78572
 
77968
78573
  def _skill_aware_reeval_task_level(
@@ -78128,15 +78733,32 @@ body{padding:18px}
78128
78733
  }
78129
78734
 
78130
78735
  def _apply_runtime_task_decision(self, goal_text: str, decision: dict):
78736
+ goal_text = self._unwrap_program_ide_task_text(goal_text)
78131
78737
  row = dict(decision or {})
78132
78738
  inherit_previous_state = _to_bool_like(row.get("inherit_previous_state", False), default=False)
78133
78739
  board_before_decision = self._ensure_blackboard()
78134
- active_plan_protected = self._approved_plan_has_unfinished_steps(board_before_decision)
78740
+ previous_ended = self._blackboard_is_finished_or_aborted(board_before_decision)
78741
+ unfinished_level = self._unfinished_task_level(board_before_decision)
78742
+ # A manual level is restored before classification. On a newly reset
78743
+ # board that preset is not evidence that an older task is still active.
78744
+ judgement_before = board_before_decision.get("manager_judgement", {})
78745
+ manual_fresh_submission = (
78746
+ int(getattr(self, "user_task_level_override", 0) or 0) > 0
78747
+ and board_before_decision.get("status") == "INITIALIZING"
78748
+ and isinstance(judgement_before, dict)
78749
+ and str(judgement_before.get("progress", "")).strip().lower() == "initializing"
78750
+ and not str((board_before_decision.get("plan") or {}).get("phase", ""))
78751
+ and not self._todo_has_plan_steps(board_before_decision)
78752
+ and not self._single_no_plan_todo_has_rows()
78753
+ and not any(board_before_decision.get(key) for key in ("execution_logs", "code_artifacts", "research_notes", "review_feedback"))
78754
+ )
78755
+ if manual_fresh_submission:
78756
+ unfinished_level = 0
78135
78757
  explicit_full_replan = self._runtime_decision_requests_full_replan(goal_text, row)
78136
78758
  if explicit_full_replan:
78137
78759
  inherit_previous_state = False
78138
78760
  row["inherit_previous_state"] = False
78139
- elif active_plan_protected:
78761
+ elif unfinished_level:
78140
78762
  inherit_previous_state = True
78141
78763
  row["inherit_previous_state"] = True
78142
78764
  row["requires_plan"] = False
@@ -78144,12 +78766,27 @@ body{padding:18px}
78144
78766
  "status",
78145
78767
  {
78146
78768
  "summary": (
78147
- "active approved plan preserved; latest input is scoped to the current "
78148
- "parent step unless the user explicitly requests a whole-roadmap replan"
78769
+ "unfinished task level and execution state preserved"
78149
78770
  )
78150
78771
  },
78151
78772
  )
78152
- if bool(self.runtime_goal_reset_pending):
78773
+ elif previous_ended or manual_fresh_submission:
78774
+ inherit_previous_state = False
78775
+ row["inherit_previous_state"] = False
78776
+ if previous_ended:
78777
+ previous_context = self._previous_task_context_snapshot(board_before_decision)
78778
+ self._reset_blackboard_plan_state_locked(
78779
+ new_goal=goal_text,
78780
+ previous_context=previous_context,
78781
+ clear_progress=True,
78782
+ reset_agent_contexts=True,
78783
+ )
78784
+ self.runtime_authoritative_goal = goal_text
78785
+ self.runtime_task_type = ""
78786
+ self.runtime_task_complexity = ""
78787
+ self.runtime_direct_objective = ""
78788
+ self._mark_runtime_goal_reset_handled(reason="ended-task-reclassified")
78789
+ elif bool(self.runtime_goal_reset_pending):
78153
78790
  if not inherit_previous_state and not explicit_full_replan:
78154
78791
  self.runtime_authoritative_goal = str(goal_text or "").strip()
78155
78792
  if bool(inherit_previous_state):
@@ -78176,29 +78813,17 @@ body{padding:18px}
78176
78813
  if previous_complexity not in TASK_COMPLEXITY_LEVELS:
78177
78814
  previous_complexity = ""
78178
78815
  preserve_existing_complexity = False
78179
- # Complexity inheritance: if user didn't mention complexity, inherit previous level
78180
- previous_level = int(getattr(self, "runtime_task_level", 0) or 0)
78181
- if previous_level > 0 and not explicit_complexity:
78182
- # Inherit when: plan choice, explicit inherit flag, OR active high-level task has progress
78816
+ # Only unfinished work can donate its previous level. Retained logs or
78817
+ # an optimistic model continuation flag cannot revive an ended task.
78818
+ if unfinished_level > 0 and not explicit_full_replan:
78183
78819
  _should_inherit = (
78184
78820
  bool(inherit_previous_state)
78185
78821
  or self._is_plan_choice_response(str(goal_text or ""))
78186
78822
  or bool(int(getattr(self, "user_task_level_override", 0) or 0) > 0)
78187
78823
  )
78188
- if not _should_inherit and previous_level >= 3:
78189
- board = self._ensure_blackboard()
78190
- has_progress = bool(
78191
- len(board.get("research_notes", []) or [])
78192
- or len(board.get("code_artifacts", {}) or {})
78193
- or len(board.get("execution_logs", []) or [])
78194
- or len(board.get("review_feedback", []) or [])
78195
- )
78196
- progress_state = self._manager_progress_state(board)
78197
- if has_progress and progress_state in {"in_progress", "almost_done", "blocked", "initializing"}:
78198
- _should_inherit = True
78199
78824
  if _should_inherit:
78200
- level = previous_level
78201
- preserve_existing_complexity = bool(previous_complexity)
78825
+ level = unfinished_level
78826
+ preserve_existing_complexity = bool(previous_complexity) and not explicit_complexity
78202
78827
  if int(getattr(self, 'user_task_level_override', 0) or 0) > 0:
78203
78828
  level = int(self.user_task_level_override)
78204
78829
  _level_floor = int(getattr(self, 'runtime_task_level_floor', 0) or 0)
@@ -78382,6 +79007,12 @@ body{padding:18px}
78382
79007
  requires_plan = False
78383
79008
  elif user_pref == "on":
78384
79009
  requires_plan = True
79010
+ elif level in PLAN_MODE_ENABLED_LEVELS and str(
79011
+ (self._ensure_blackboard().get("plan") or {}).get("phase", "")
79012
+ ).strip().lower() in {"research", "synthesis"}:
79013
+ # An interrupted, unapproved Plan is pending work. A continuation
79014
+ # must finish planning before any normal execution can start.
79015
+ requires_plan = True
78385
79016
  elif bool(getattr(self, "runtime_first_task_in_session", False)) and level in PLAN_MODE_ENABLED_LEVELS:
78386
79017
  requires_plan = True
78387
79018
  elif level in PLAN_MODE_ENABLED_LEVELS:
@@ -78469,6 +79100,7 @@ body{padding:18px}
78469
79100
  pinned_selection: str,
78470
79101
  media_inputs_round: list[dict] | None = None,
78471
79102
  ) -> dict:
79103
+ goal_text = self._unwrap_program_ide_task_text(goal_text)
78472
79104
  # Build the current skills context for the manager prompt.
78473
79105
  skills_ctx = ""
78474
79106
  try:
@@ -78507,6 +79139,10 @@ body{padding:18px}
78507
79139
  f"Previous blackboard goal:\n{trim(str(self._ensure_blackboard().get('original_goal', '') or ''), 1200) or '(none)'}\n"
78508
79140
  f"Previous task context:\n{self._format_previous_task_context_for_prompt(max_chars=1000) or '(none)'}\n"
78509
79141
  f"Current blackboard progress: {self._manager_progress_state(self._ensure_blackboard())}\n\n"
79142
+ f"Previous task ended: {self._blackboard_is_finished_or_aborted(self._ensure_blackboard()) or (not self._unfinished_task_level() and self._blackboard_is_finished_or_aborted(self._ensure_blackboard().get('previous_task_context', {})))}. "
79143
+ f"Current task already active: {bool(self._unfinished_task_level())}. "
79144
+ "A new initialized board is not an unfinished previous task. Inherit only an actually active task; "
79145
+ "an ended task must not donate its old execution state.\n\n"
78510
79146
  f"Current runtime policy: level={int(self.runtime_task_level or 0)}, "
78511
79147
  f"mode={self._effective_execution_mode()}, "
78512
79148
  f"participants={','.join(self.runtime_participants or []) or '-'}, "
@@ -78522,8 +79158,8 @@ body{padding:18px}
78522
79158
  "Infer scale_preference by semantics (fast/balanced/thorough). "
78523
79159
  "When user preference is clear, prioritize it over your default plan. "
78524
79160
  "Remember: budget controls internal thought depth/round compactness, not early stop messaging. "
78525
- "Also decide inherit_previous_state by semantic continuity with prior blackboard state. "
78526
- "If this is pure continuation, keep current runtime policy unchanged.\n"
79161
+ "The task lifecycle controls inheritance: keep an unfinished task's level even if this turn asks "
79162
+ "an unrelated short question; once that task has ended, judge the latest request afresh.\n"
78527
79163
  f"User configured execution mode: {self.execution_mode}\n"
78528
79164
  )
78529
79165
  if normalize_execution_mode(self.execution_mode, default="") == EXECUTION_MODE_SINGLE:
@@ -78531,14 +79167,12 @@ body{padding:18px}
78531
79167
  "IMPORTANT: User has configured Single-agent mode. "
78532
79168
  "Prefer level 1-2 for simple tasks. Only escalate to level 3+ if truly complex.\n"
78533
79169
  )
78534
- prev_level = int(self.runtime_task_level or 0)
78535
- if prev_level > 0 and self._is_minor_followup_input(goal_text):
79170
+ prev_level = self._unfinished_task_level()
79171
+ if prev_level > 0:
78536
79172
  prompt += (
78537
- f"\nIMPORTANT: The previous task was classified as level {prev_level}. "
78538
- f"This appears to be a follow-up input, NOT a new task. "
78539
- f"Unless the user is clearly starting a completely different task, "
78540
- f"you MUST inherit the previous level={prev_level} and set inherit_previous_state=true. "
78541
- f"Do NOT downgrade the level for follow-up inputs.\n"
79173
+ f"\nIMPORTANT: The unfinished task is level {prev_level}. "
79174
+ "Keep its level (subject to the automatic ceiling), set inherit_previous_state=true, "
79175
+ "and resume its execution state. Reclassify afresh only after it has ended.\n"
78542
79176
  )
78543
79177
  with self.lock:
78544
79178
  self.current_phase = "manager:classify:model-call"
@@ -78548,7 +79182,7 @@ body{padding:18px}
78548
79182
  [{"role": "user", "content": prompt, "ts": now_ts()}],
78549
79183
  tools=self._manager_task_classify_tools(),
78550
79184
  system=self._manager_classification_system_prompt(),
78551
- max_tokens=320,
79185
+ max_tokens=min(1024, max(1, int(getattr(self, "max_output_tokens", 1024) or 1024))),
78552
79186
  think=False,
78553
79187
  stream_thinking=False,
78554
79188
  on_thinking_chunk=self._append_live_thinking,
@@ -78570,7 +79204,7 @@ body{padding:18px}
78570
79204
  ],
78571
79205
  tools=self._manager_task_classify_tools(),
78572
79206
  system=self._manager_classification_system_prompt(),
78573
- max_tokens=220,
79207
+ max_tokens=min(1024, max(1, int(getattr(self, "max_output_tokens", 1024) or 1024))),
78574
79208
  think=False,
78575
79209
  stream_thinking=False,
78576
79210
  on_thinking_chunk=self._append_live_thinking,
@@ -78617,6 +79251,17 @@ body{padding:18px}
78617
79251
  # Continuation / follow-up detection (complexity inheritance)
78618
79252
  # ------------------------------------------------------------------
78619
79253
 
79254
+ def _unfinished_task_level(self, board: dict | None = None) -> int:
79255
+ """Share the submission boundary: ended work cannot donate a level."""
79256
+ try:
79257
+ level = int(getattr(self, "runtime_task_level", 0) or 0)
79258
+ except (TypeError, ValueError):
79259
+ return 0
79260
+ if level not in TASK_LEVEL_CHOICES:
79261
+ return 0
79262
+ bb = board if isinstance(board, dict) else self._ensure_blackboard()
79263
+ return 0 if self._blackboard_is_finished_or_aborted(bb) else level
79264
+
78620
79265
  _CONTINUATION_PHRASES = frozenset({
78621
79266
  "继续", "continue", "go", "proceed", "go ahead", "ok", "好", "好的",
78622
79267
  "是", "是的", "确认", "执行", "开始", "start", "yes", "do it", "run it",
@@ -78639,19 +79284,8 @@ body{padding:18px}
78639
79284
  )
78640
79285
 
78641
79286
  def _is_minor_followup_input(self, text: str) -> bool:
78642
- """Return True if *text* looks like a lightweight follow-up, not a brand-new task."""
78643
- t = str(text or "").strip()
78644
- if not t or len(t) > 80:
78645
- return False
78646
- t_lower = t.lower()
78647
- for prefix in self._NEW_TASK_PREFIXES:
78648
- if t_lower.startswith(prefix):
78649
- return False
78650
- board = self._ensure_blackboard()
78651
- progress = str(board.get("progress", "") or "").strip().lower()
78652
- if progress in ("done", "completed"):
78653
- return False
78654
- return True
79287
+ """Only recognize explicit continuation while the prior task is open."""
79288
+ return bool(self._unfinished_task_level() and self._is_continuation_input(text))
78655
79289
 
78656
79290
  def _is_plan_choice_response(self, text: str) -> bool:
78657
79291
  """Check if user text is a response to a plan proposal."""
@@ -78831,6 +79465,77 @@ body{padding:18px}
78831
79465
  text = f"{phase_rule}\n{text}"
78832
79466
  return executor, trim(text, MANAGER_INSTRUCTION_MAX_CHARS)
78833
79467
 
79468
+ def _semantic_task_level_decision(
79469
+ self,
79470
+ goal_text: str,
79471
+ *,
79472
+ pinned_selection: str,
79473
+ media_inputs_round: list[dict] | None = None,
79474
+ ) -> dict:
79475
+ """Semantic routing is authoritative; rules are an explicit failure fallback."""
79476
+ goal = self._unwrap_program_ide_task_text(goal_text)
79477
+ try:
79478
+ decision = self._manager_classify_task_level(
79479
+ goal,
79480
+ pinned_selection=pinned_selection,
79481
+ media_inputs_round=media_inputs_round,
79482
+ )
79483
+ except OllamaError as exc:
79484
+ if bool(getattr(self, "cancel_requested", False)):
79485
+ raise
79486
+ self._emit("status", {"summary": f"semantic task classification unavailable; using bounded fallback: {trim(str(exc), 160)}"})
79487
+ decision = self._fallback_task_level_decision(goal)
79488
+ decision["source"] = "fallback-model-error"
79489
+ if self._unfinished_task_level() and not self._runtime_decision_requests_full_replan(goal, decision):
79490
+ inherited = self._fallback_task_level_decision(goal)
79491
+ for key in ("judgement", "semantic_confidence", "low_confidence_reason"):
79492
+ if key in decision:
79493
+ inherited[key] = decision[key]
79494
+ inherited["source"] = str(decision.get("source", "manager")) + "+unfinished-inherit"
79495
+ if decision.get("level") != inherited.get("level") or not decision.get("inherit_previous_state"):
79496
+ inherited["judgement"] = (
79497
+ f"unfinished task retains L{inherited.get('level')}; "
79498
+ f"this turn's semantic L{decision.get('level')} cannot replace the active task level"
79499
+ )
79500
+ decision = inherited
79501
+ else:
79502
+ # Submission has already cleared a completed task's board. The
79503
+ # classifier may call the new goal a continuation of the same
79504
+ # project, but there is no active task whose execution can resume.
79505
+ decision["inherit_previous_state"] = False
79506
+ if not self._unfinished_task_level():
79507
+ board = self._ensure_blackboard()
79508
+ previous = (
79509
+ self._previous_task_context_snapshot(board)
79510
+ if self._blackboard_is_finished_or_aborted(board)
79511
+ else board.get("previous_task_context", {})
79512
+ )
79513
+ previous = previous if isinstance(previous, dict) else {}
79514
+ is_development = _to_bool_like(decision.get("followup_development", False), default=False)
79515
+ # Older compatible classifiers may omit the new boolean. Their
79516
+ # semantic task type can still identify an L2 implementation task;
79517
+ # an L1 answer never becomes engineering from topic words alone.
79518
+ if "followup_development" not in decision:
79519
+ is_development = decision.get("task_type") in {"simple_code", "engineering"} and decision.get("level", 0) >= 2
79520
+ if previous.get("task_level") == 4 and is_development and decision.get("level", 0) < 3:
79521
+ decision = dict(decision)
79522
+ decision.update(
79523
+ level=3, task_level=3, complexity="moderate", requires_todos=True,
79524
+ execution_mode=EXECUTION_MODE_SINGLE, participants=["developer"],
79525
+ assigned_expert="developer", round_budget=TASK_LEVEL_POLICIES[3]["round_budget"],
79526
+ requires_plan=True,
79527
+ )
79528
+ decision["source"] = str(decision.get("source", "manager")) + "+completed-L4-development"
79529
+ decision["judgement"] = trim(
79530
+ str(decision.get("judgement", "")) + "; completed L4 development follow-up uses at least L3 before the automatic ceiling",
79531
+ 220,
79532
+ )
79533
+ if decision.get("level") == 1:
79534
+ decision.setdefault("task_type", "simple_qa")
79535
+ decision.setdefault("complexity", "simple")
79536
+ decision.setdefault("direct_objective", "Directly answer the latest user request in natural language.")
79537
+ return self._apply_auto_task_level_ceiling_to_decision(decision, source="semantic")
79538
+
78834
79539
  def _refresh_runtime_task_policy(
78835
79540
  self,
78836
79541
  *,
@@ -78846,6 +79551,7 @@ body{padding:18px}
78846
79551
  or self._latest_user_goal_text()
78847
79552
  or ""
78848
79553
  ).strip()
79554
+ goal = self._unwrap_program_ide_task_text(goal)
78849
79555
  if not goal:
78850
79556
  return {}
78851
79557
  # --- User override short-circuit: user manually set level, skip manager ---
@@ -78872,14 +79578,10 @@ body{padding:18px}
78872
79578
  ) == "auto"
78873
79579
  and not self._is_continuation_input(goal)
78874
79580
  ):
78875
- semantic_row = (
78876
- self._fallback_task_level_decision(goal)
78877
- if FAST_START_LOCAL_CLASSIFICATION
78878
- else self._manager_classify_task_level(
78879
- goal,
78880
- pinned_selection=pinned_selection,
78881
- media_inputs_round=media_inputs_round,
78882
- )
79581
+ semantic_row = self._manager_classify_task_level(
79582
+ goal,
79583
+ pinned_selection=pinned_selection,
79584
+ media_inputs_round=media_inputs_round,
78883
79585
  )
78884
79586
  manual_requires_todos = self._resolve_todo_requirement(
78885
79587
  _utlo,
@@ -78906,15 +79608,11 @@ body{padding:18px}
78906
79608
  }
78907
79609
  user_pref = str(self.plan_mode_user_preference or "auto").strip().lower()
78908
79610
  if user_pref == "auto":
78909
- plan_auto = (
78910
- self._local_plan_mode_decision(goal, decision)
78911
- if FAST_START_LOCAL_CLASSIFICATION
78912
- else self._manager_decide_plan_mode_needed(
78913
- goal,
78914
- pinned_selection=pinned_selection,
78915
- decision=decision,
78916
- media_inputs_round=media_inputs_round,
78917
- )
79611
+ plan_auto = self._manager_decide_plan_mode_needed(
79612
+ goal,
79613
+ pinned_selection=pinned_selection,
79614
+ decision=decision,
79615
+ media_inputs_round=media_inputs_round,
78918
79616
  )
78919
79617
  decision["requires_plan"] = bool(plan_auto.get("requires_plan", False))
78920
79618
  decision["plan_mode_reason"] = trim(
@@ -78932,7 +79630,7 @@ body{padding:18px}
78932
79630
  self._apply_runtime_task_decision(goal, decision)
78933
79631
  return dict(decision)
78934
79632
  # --- Continuation input short-circuit: inherit previous complexity ---
78935
- prev_level = int(self.runtime_task_level or 0)
79633
+ prev_level = self._unfinished_task_level()
78936
79634
  if prev_level > 0 and self._is_continuation_input(goal):
78937
79635
  decision = {
78938
79636
  "level": prev_level,
@@ -78958,12 +79656,18 @@ body{padding:18px}
78958
79656
  "requires_plan": False,
78959
79657
  "plan_mode_reason": "continuation input inherits execution without restarting plan mode",
78960
79658
  }
79659
+ decision = self._apply_auto_task_level_ceiling_to_decision(decision, source="continuation")
78961
79660
  self._apply_runtime_task_decision(goal, decision)
78962
79661
  return dict(decision)
78963
79662
  need = bool(
78964
79663
  force
78965
79664
  or self.runtime_reclassify_required
78966
79665
  or self.runtime_goal_reset_pending
79666
+ or self._blackboard_is_finished_or_aborted(self._ensure_blackboard())
79667
+ or (
79668
+ self._auto_task_level_ceiling_value() > 0
79669
+ and int(self.runtime_task_level or 0) > self._auto_task_level_ceiling_value()
79670
+ )
78967
79671
  or int(self.runtime_task_level or 0) not in TASK_LEVEL_CHOICES
78968
79672
  )
78969
79673
  if not need:
@@ -78979,26 +79683,11 @@ body{padding:18px}
78979
79683
  "inherit_previous_state": False,
78980
79684
  "source": "cached",
78981
79685
  }
78982
- if FAST_START_LOCAL_CLASSIFICATION:
78983
- decision = self._fallback_task_level_decision(goal)
78984
- decision = self._apply_auto_task_level_ceiling_to_decision(
78985
- decision,
78986
- source="local-fast",
78987
- )
78988
- decision["source"] = "local-fast"
78989
- decision["semantic_confidence"] = "medium"
78990
- plan_auto = self._local_plan_mode_decision(goal, decision)
78991
- decision["requires_plan"] = bool(plan_auto.get("requires_plan", False))
78992
- decision["plan_mode_reason"] = trim(
78993
- str(plan_auto.get("reason", "local bounded plan decision") or "local bounded plan decision"),
78994
- 240,
78995
- )
78996
- else:
78997
- decision = self._manager_classify_task_level(
78998
- goal,
78999
- pinned_selection=pinned_selection,
79000
- media_inputs_round=media_inputs_round,
79001
- )
79686
+ decision = self._semantic_task_level_decision(
79687
+ goal,
79688
+ pinned_selection=pinned_selection,
79689
+ media_inputs_round=media_inputs_round,
79690
+ )
79002
79691
  self._apply_runtime_task_decision(goal, decision)
79003
79692
  return dict(decision or {})
79004
79693
 
@@ -80726,7 +81415,7 @@ body{padding:18px}
80726
81415
  self.manager_context,
80727
81416
  tools=self._manager_route_tools(),
80728
81417
  system=self._manager_system_prompt(),
80729
- max_tokens=600,
81418
+ max_tokens=self.max_output_tokens,
80730
81419
  think=False,
80731
81420
  stream_thinking=False,
80732
81421
  on_thinking_chunk=self._append_live_thinking,
@@ -80776,7 +81465,7 @@ body{padding:18px}
80776
81465
  self.manager_context,
80777
81466
  tools=self._manager_route_tools(),
80778
81467
  system=self._manager_system_prompt(),
80779
- max_tokens=600,
81468
+ max_tokens=self.max_output_tokens,
80780
81469
  think=False,
80781
81470
  stream_thinking=False,
80782
81471
  on_thinking_chunk=self._append_live_thinking,
@@ -82357,6 +83046,24 @@ body{padding:18px}
82357
83046
  )
82358
83047
  return row
82359
83048
 
83049
+ def _required_no_plan_todo_initialization_needed(self, role: str = "") -> bool:
83050
+ """Require a real model-authored checklist for L3+ before side effects."""
83051
+ if self._runtime_task_level_for_todo_policy() < 3 or not self._runtime_level_requires_todos():
83052
+ return False
83053
+ if bool(getattr(self, "runtime_plan_mode_needed", False)) or bool(getattr(self, "runtime_plan_approved", False)):
83054
+ return False
83055
+ board = self._ensure_blackboard()
83056
+ plan = board.get("plan", {}) if isinstance(board.get("plan"), dict) else {}
83057
+ if str(plan.get("phase", "")) in {"research", "synthesis", "awaiting_choice", "executing"}:
83058
+ return False
83059
+ if self._todo_has_plan_steps(board):
83060
+ return False
83061
+ role_key = self._sanitize_agent_role(role)
83062
+ if self._is_multi_agent_mode() and role_key in {"explorer", "developer", "reviewer"}:
83063
+ return not any(self._todo_row_kind(row) == "flat" or row.get("owner") == role_key
83064
+ for row in self.todo.snapshot() if self._todo_row_kind(row) != "system")
83065
+ return not self._single_no_plan_todo_has_rows()
83066
+
82360
83067
  def _single_no_plan_todo_policy_enabled(self) -> bool:
82361
83068
  """Return whether the bounded single/no-plan Todo gate is enabled.
82362
83069
 
@@ -82382,7 +83089,7 @@ body{padding:18px}
82382
83089
  def _single_no_plan_todo_perception_tools(self) -> list[dict]:
82383
83090
  """Expose only observation tools until the mandatory L2 Todo exists.
82384
83091
 
82385
- This is a narrow, one-turn safety boundary. It prevents a model from
83092
+ This is a preparation boundary, without a fixed read count. It prevents a model from
82386
83093
  bypassing the level contract by emitting ``write_file`` before the
82387
83094
  normal perception-to-Todo bootstrap has had a chance to run. MCP and
82388
83095
  browser tools are admitted only when their names advertise a read-only
@@ -82392,7 +83099,7 @@ body{padding:18px}
82392
83099
  read_names = {
82393
83100
  "read_file", "list_files", "search_files", "context_recall", "tool_memory",
82394
83101
  "task_get", "task_list", "read_from_blackboard", "check_background", "read_inbox",
82395
- "list_background_processes",
83102
+ "list_background_processes", "ask_user",
82396
83103
  "list_teammates", "worktree_list", "worktree_status", "worktree_events",
82397
83104
  "query_code_library", "query_knowledge_library", "agent_web_search",
82398
83105
  "list_skills", "list_skill_providers", "list_skill_protocols", "scan_skills", "load_skill", "unload_skill",
@@ -82590,7 +83297,7 @@ body{padding:18px}
82590
83297
  "list_teammates", "worktree_list", "worktree_status", "worktree_events",
82591
83298
  "query_code_library", "query_knowledge_library", "agent_web_search",
82592
83299
  "list_skills", "list_skill_providers", "list_skill_protocols",
82593
- "scan_skills", "load_skill", "unload_skill",
83300
+ "scan_skills", "load_skill", "unload_skill", "ask_user",
82594
83301
  }:
82595
83302
  return True
82596
83303
  if name == "bash" or name == "worktree_run":
@@ -82673,67 +83380,12 @@ body{padding:18px}
82673
83380
  return tools
82674
83381
 
82675
83382
  def _deterministic_bootstrap_todo_call(self) -> dict | None:
82676
- """Build the smallest safe Todo call from the authoritative user goal.
83383
+ """Retired compatibility hook: task understanding must come from the model.
82677
83384
 
82678
- This is a last-resort protocol bridge, not another planner. Explicitly
82679
- numbered user stages are preserved in order; otherwise one goal-bound
82680
- item is enough. Returning a normal synthetic tool call lets the main
82681
- dispatcher perform the same validation, persistence, UI refresh, and
82682
- later status updates as a model-emitted TodoWrite call.
83385
+ Missing or thinking-only output is not a readiness verdict and must
83386
+ never fabricate an executable Todo graph from the user goal.
82683
83387
  """
82684
- goal = str(
82685
- self._authoritative_user_goal_for_model()
82686
- or self._latest_user_goal_text()
82687
- or ""
82688
- ).strip()
82689
- if not goal or goal.casefold() == "current task":
82690
- return None
82691
- normalized = normalize_embedded_newlines(goal)
82692
- numbered: list[tuple[int, str]] = []
82693
- stage_pattern = re.compile(
82694
- r"(?:^|\n|(?<=\s))(\d{1,2})[\.\)、:]\s*"
82695
- r"(.+?)(?=(?:\n|\s)+(?:\d{1,2})[\.\)、:]\s*|$)",
82696
- flags=re.DOTALL,
82697
- )
82698
- for match in stage_pattern.finditer(normalized):
82699
- try:
82700
- order = int(match.group(1))
82701
- except Exception:
82702
- continue
82703
- content = trim(re.sub(r"\s+", " ", str(match.group(2) or "")).strip(" -;;"), 500)
82704
- if content:
82705
- numbered.append((order, content))
82706
- items: list[dict] = []
82707
- if numbered:
82708
- # Preserve appearance order rather than sorting: users sometimes
82709
- # intentionally repeat or restart numbering in nested stages.
82710
- seen: set[str] = set()
82711
- for _, content in numbered[:40]:
82712
- identity = content.casefold()
82713
- if identity in seen:
82714
- continue
82715
- seen.add(identity)
82716
- items.append({"content": content, "status": "pending"})
82717
- if not items:
82718
- concise_goal = trim(re.sub(r"\s+", " ", normalized).strip(), 500)
82719
- if not concise_goal:
82720
- return None
82721
- items = [{"content": concise_goal, "status": "pending"}]
82722
- items[0]["status"] = "in_progress"
82723
- return {
82724
- "id": make_id("tool"),
82725
- "type": "function",
82726
- "function": {
82727
- "name": "TodoWriteRescue",
82728
- "arguments": {
82729
- "items": items,
82730
- "in_progress_index": 0,
82731
- # Plain status_update: a bootstrap seeds an empty tree and
82732
- # must never enter the audited revision path.
82733
- "update_mode": "status_update",
82734
- },
82735
- },
82736
- }
83388
+ return None
82737
83389
 
82738
83390
  def _single_no_plan_todo_remove_bootstrap_hints(self) -> None:
82739
83391
  if not isinstance(getattr(self, "messages", None), list):
@@ -82764,11 +83416,12 @@ body{padding:18px}
82764
83416
  "content": (
82765
83417
  "<single-no-plan-todo-bootstrap>\n"
82766
83418
  f"{trim(prompt, 6000)}\n\n"
82767
- "This is the planning phase after read-only perception. Use the "
83419
+ "This is an open preparation phase after initial observation. Use the "
82768
83420
  "preceding evidence and the read-only tools available in this phase "
82769
83421
  "to fill any material gaps. Once you have enough evidence, return "
82770
- "exactly one TodoWrite or TodoWriteRescue call with 1-40 next actions. "
82771
- "Do not call implementation tools or finish_task.\n"
83422
+ "one TodoWrite or TodoWriteRescue call with suitable next actions and the preparation assessment. "
83423
+ "Do not create a list while context is materially missing. ask_user is available for a necessary "
83424
+ "clarification. Do not call implementation tools or finish_task.\n"
82772
83425
  "</single-no-plan-todo-bootstrap>"
82773
83426
  ),
82774
83427
  "ts": now_ts(),
@@ -82776,7 +83429,7 @@ body{padding:18px}
82776
83429
  )
82777
83430
  self._emit(
82778
83431
  "status",
82779
- {"summary": "single/no-plan perception complete; Todo bootstrap turn required"},
83432
+ {"summary": "single/no-plan preparation open; continue observation until ready for Todos"},
82780
83433
  )
82781
83434
  try:
82782
83435
  self._persist()
@@ -82802,9 +83455,10 @@ body{padding:18px}
82802
83455
  "content": (
82803
83456
  "<single-no-plan-todo-bootstrap-retry>\n"
82804
83457
  f"The required Todo bootstrap turn did not complete: {reason_text}. "
82805
- "Retry once now. Call exactly one TodoWrite or TodoWriteRescue "
82806
- "with 1-40 evidence-based items, preserving explicit ordered stages one-for-one, and exactly one in_progress item; "
82807
- "do not use any implementation tool.\n"
83458
+ "Resolve the reported protocol problem. Continue observation or ask_user if context is missing; "
83459
+ "once ready, submit the model's own evidence-based TodoWrite or TodoWriteRescue and preparation "
83460
+ "assessment, preserving ordered stages and exactly one in_progress item. "
83461
+ "Do not manufacture a checklist merely to escape this phase.\n"
82808
83462
  "</single-no-plan-todo-bootstrap-retry>"
82809
83463
  ),
82810
83464
  "ts": now_ts(),
@@ -84561,6 +85215,90 @@ body{padding:18px}
84561
85215
  f"Current work: {target}; continue it only if it is still appropriate."
84562
85216
  )
84563
85217
 
85218
+ def _selected_skill_reading_gaps(self, role: str = "") -> list[dict]:
85219
+ """Full observed workflows survive compaction as exact read coverage."""
85220
+ gaps = []
85221
+ hard = getattr(self, "skill_mode", "dynamic") == "hard"
85222
+ ids = list(getattr(self, "bound_skill_ids", [])) if hard else list(self._loaded_skill_rows())
85223
+ for skill_id in ids:
85224
+ try:
85225
+ row = self._prepare_skill_execution_workspace(skill_id)
85226
+ if row.get("status") != "ready":
85227
+ continue
85228
+ expected = row["files"].get("SKILL.md", "")
85229
+ seen = any(
85230
+ isinstance(memory, dict) and memory.get("source_sha256") == expected
85231
+ and not memory.get("stale")
85232
+ and self._ranges_cover(memory.get("read_ranges", []), 1, int(memory.get("total_lines", 0) or 1))
85233
+ for memory in getattr(self, "long_content_memory", {}).values()
85234
+ )
85235
+ if not seen and not hard:
85236
+ # A short auto-loaded workflow may already have been
85237
+ # delivered in full in the recurring execution prompt.
85238
+ loaded_row = self._loaded_skill_rows().get(skill_id, {})
85239
+ rendered = self._loaded_skill_body_from_cache(skill_id, loaded_row)
85240
+ seen = bool(rendered and rendered in self._loaded_skills_context_block(for_role=role, max_chars=3500))
85241
+ if not seen:
85242
+ gaps.append({"skill_id": skill_id, "workflow": row.get("authoritative_source") if hard else row["workflow"]})
85243
+ except Exception as exc:
85244
+ gaps.append({"skill_id": skill_id, "error": str(exc)[:300]})
85245
+ return gaps
85246
+
85247
+ def _todo_preparation_guard(self, source: dict, *, role: str, existing_rows: list[dict], board: dict) -> str:
85248
+ """Require a concise model decision, never infer readiness from a read count.
85249
+
85250
+ The execution model supplies the decision in the same call as the first
85251
+ Todo graph. This adds no independent planning request and stores no
85252
+ private reasoning. A material gap keeps observation/clarification open.
85253
+ """
85254
+ if not bool(getattr(self, "_task_preparation_required", False)) or self._runtime_task_level_for_todo_policy() < 1:
85255
+ return ""
85256
+ goal = str(self._authoritative_user_goal_for_model() or board.get("original_goal", "") or "").strip()
85257
+ if not goal or self._blackboard_is_terminal_completion(board):
85258
+ return ""
85259
+ owner = self._sanitize_agent_role(role)
85260
+ if any(str(row.get("owner", "") or "") in {"", owner} for row in existing_rows if isinstance(row, dict)):
85261
+ return ""
85262
+ if getattr(self, "pending_user_question", None):
85263
+ return self._plan_control_feedback("task_preparation_pending", "An actual ask_user question is still awaiting its answer. Keep preparation open; do not turn an unanswered choice into an executable blocking Todo.")
85264
+ preparation = source.get("preparation")
85265
+ if isinstance(preparation, str):
85266
+ preparation = extract_json_object_from_text(preparation, {})
85267
+ if not isinstance(preparation, dict):
85268
+ return self._plan_control_feedback(
85269
+ "task_preparation_required",
85270
+ "Before initializing Todos, understand the actual goal and current state, consider available skills, "
85271
+ "and read selected workflows completely. Continue read-only discovery or ask_user for material gaps. "
85272
+ "When ready, resubmit the same intended new rows (omit invented ids) with preparation="
85273
+ '{"goal":"brief understood objective","state":"relevant observed or user-provided state",'
85274
+ '"skills":"selection or reason no skill is relevant","basis":"user_context|observed_context|continuation",'
85275
+ '"ready":true,"missing":[]}. One read is not proof of readiness; no fixed read count is required.')
85276
+ goal_summary = str(preparation.get("goal", "") or "").strip()
85277
+ state_summary = str(preparation.get("state", "") or "").strip()
85278
+ skill_decision = str(preparation.get("skills", "") or "").strip()
85279
+ ready = self._optional_bool_value(preparation.get("ready"))
85280
+ missing = preparation.get("missing", [])
85281
+ basis = str(preparation.get("basis", "") or "").strip()
85282
+ if not isinstance(missing, list) or not all(isinstance(item, str) for item in missing):
85283
+ return self._plan_control_feedback("task_preparation_invalid", "preparation.missing must be a list of actual unresolved context gaps.")
85284
+ missing = [item.strip() for item in missing if item.strip()]
85285
+ if ready is not True or missing:
85286
+ return self._plan_control_feedback("task_preparation_pending", "Do not create a Todo graph yet. Resolve the stated gaps through observation or ask_user: " + json_dumps(missing))
85287
+ if not all((goal_summary, state_summary, skill_decision)) or basis not in {"user_context", "observed_context", "continuation"}:
85288
+ return self._plan_control_feedback("task_preparation_invalid", "Supply brief goal/state/skills summaries and a valid basis; do not substitute a generic planning slogan.")
85289
+ gaps = self._selected_skill_reading_gaps(owner)
85290
+ if gaps:
85291
+ return self._plan_control_feedback("selected_skill_reading_required", "Complete the selected workflow reads before committing the list: " + json_dumps(gaps))
85292
+ step = self._get_active_plan_step(board) or {}
85293
+ record = {"goal": trim(goal_summary, 1000), "state": trim(state_summary, 1600),
85294
+ "skills": trim(skill_decision, 1200), "basis": basis, "ready": True,
85295
+ "owner": owner, "step_id": str(step.get("id", "") or ""),
85296
+ "goal_digest": hashlib.sha256(goal.encode("utf-8", errors="backslashreplace")).hexdigest(), "ts": now_ts()}
85297
+ rows = [row for row in board.get("preparation_decisions", []) if isinstance(row, dict)]
85298
+ board["preparation_decisions"] = (rows + [record])[-40:]
85299
+ self.blackboard = board
85300
+ return ""
85301
+
84564
85302
  def _dispatch_todo_update_inner(self, args: dict, *, role: str = "", resume: bool = False) -> str:
84565
85303
  """Canonical dispatcher shared by TodoWrite, Rescue, and Resume aliases."""
84566
85304
  source = args if isinstance(args, dict) else {}
@@ -84585,6 +85323,9 @@ body{padding:18px}
84585
85323
  # classification, or row mutation. A bad id rejects the whole payload.
84586
85324
  route_before = self._todo_route_kind(role=role_key, board=bb)
84587
85325
  reference_rows = self._todo_route_rows(route_before, role=role_key, board=bb)
85326
+ preparation_error = self._todo_preparation_guard(source, role=role_key, existing_rows=reference_rows, board=bb)
85327
+ if preparation_error:
85328
+ return preparation_error
84588
85329
  if route_before in {"plan_single", "plan_sync"}:
84589
85330
  reference_rows = [
84590
85331
  {**row, "subtask_id": self._stable_plan_worker_subtask_id(active_step_id, row)}
@@ -86262,6 +87003,14 @@ body{padding:18px}
86262
87003
  out = self._trace_tool_result(name, args, role_guard, role_key)
86263
87004
  self._maybe_record_tool_memory_after_result(name, args, out, role_key)
86264
87005
  return out
87006
+ if (bool(getattr(self, "running", False)) and self._required_no_plan_todo_initialization_needed(role_key or self.active_agent_role)
87007
+ and name not in {"TodoWrite", "TodoWriteRescue", "ask_user", "compress", "stop_background_process",
87008
+ "finish_task", "finish_current_task", "mark_done"}
87009
+ and self._single_no_plan_todo_is_mutation_result({"name": name, "args": args, "ok": True})):
87010
+ return self._plan_control_feedback("todo_initialization_required",
87011
+ f"The current role {role_key or self.active_agent_role} has no required Todo tracking. "
87012
+ "Use TodoWrite to create your own assigned work from actual read-only observations; "
87013
+ "another owner's rows do not count. Preserve peers and IDs. This tool was not executed.")
86265
87014
  try:
86266
87015
  # Shell-backed tools have their own timeout/state mechanism; keep
86267
87016
  # them on this thread so structured outcome metadata is not lost at
@@ -86456,6 +87205,20 @@ body{padding:18px}
86456
87205
  raw = re.sub(r"\s+", " ", str(command or "").strip())
86457
87206
  if not raw or not self._bash_looks_like_file_read(raw):
86458
87207
  return ""
87208
+ # A script can import code, read data, query a live service or mutate
87209
+ # files outside its own source path. The read cache tracks explicit
87210
+ # file operands only, so treating `python check.py` as a source read
87211
+ # can replay an obsolete test verdict after the product has changed.
87212
+ try:
87213
+ words = shlex.split(raw)
87214
+ except ValueError:
87215
+ return ""
87216
+ if any(re.fullmatch(
87217
+ r"(?:python(?:\d+(?:\.\d+)*)?|pypy[\d.]*|node|npx|npm|pnpm|yarn|pytest|uv|"
87218
+ r"bash|zsh|sh|cmd|powershell|pwsh|ruby|perl|php|cargo|go|make)(?:\.exe)?",
87219
+ word.replace("\\", "/").rsplit("/", 1)[-1], re.I,
87220
+ ) for word in words):
87221
+ return ""
86459
87222
  if re.search(r"(?:^|[;&|]\s*)(?:rm|mv|cp|touch|chmod|chown|mkdir|rmdir|sed\s+-i|perl\s+-i)\b", raw, re.I):
86460
87223
  return ""
86461
87224
  # Discarding stderr or stdout (2>/dev/null, 2>&1, >/dev/null) writes no
@@ -86685,7 +87448,7 @@ body{padding:18px}
86685
87448
  "Error: hard application mode cannot read the mutable global skills store. "
86686
87449
  "Use load_skill for one of the immutable bound skill ids."
86687
87450
  )
86688
- if self.skill_mode == "hard" and str(args.get("path", "") or "").replace("\\", "/").lstrip("/").startswith("workspace/.application_skills"):
87451
+ if self.skill_mode == "hard" and str(args.get("path", "") or "").replace("\\", "/").startswith("workspace/.application_skills"):
86689
87452
  return "Error: use /workspace/.application_skills/... or .application_skills/... for the immutable application snapshot."
86690
87453
  try:
86691
87454
  rel = self._normalize_tool_path_text(args["path"])
@@ -87891,6 +88654,28 @@ body{padding:18px}
87891
88654
  break
87892
88655
  step_desc = trim(str(current_step.get("content", "") if current_step else "none"), 200)
87893
88656
  is_plan_executing = plan.get("phase") == "executing"
88657
+ revision_note = ""
88658
+ if is_plan_executing and current_step and str(user_text or "").strip():
88659
+ step_id = str(current_step.get("id", "") or "")
88660
+ adjustment_id = "user:" + hashlib.sha256(
88661
+ (step_id + "\n" + user_text).encode("utf-8", "backslashreplace")
88662
+ ).hexdigest()[:24]
88663
+ adjustments = list(bb.get("user_plan_adjustments", []) or [])
88664
+ if not any(row.get("id") == adjustment_id for row in adjustments if isinstance(row, dict)):
88665
+ adjustments.append({
88666
+ "id": adjustment_id, "step_id": step_id, "kind": "user_input",
88667
+ "tool": "user_request", "actor": "user", "ok": True,
88668
+ "summary": str(user_text), "ts": float(now_ts()),
88669
+ })
88670
+ bb["user_plan_adjustments"] = adjustments[-40:]
88671
+ self.blackboard = bb
88672
+ revision_note = (
88673
+ f"\nRequirement revision evidence: {adjustment_id}. If this changes the contract, "
88674
+ "use TodoWrite plan_updates to update affected OPEN parent steps, plus revise_open "
88675
+ "with revision_reason and this revision_evidence to revise the complete open child snapshot. "
88676
+ "Preserve retained row IDs and completed evidence. Revise acceptance criteria too; "
88677
+ "status_update does not change stored titles or contracts. Do this before repeating obsolete checks.\n"
88678
+ )
87894
88679
  conflict_score = self._user_feedback_conflict_score(user_text, step_desc)
87895
88680
  if conflict_score >= 0.8:
87896
88681
  conflict_level = "HIGH"
@@ -87918,7 +88703,7 @@ body{padding:18px}
87918
88703
  f"<user-feedback-merge conflict=\"{conflict_level}\" score=\"{conflict_score:.2f}\">\n"
87919
88704
  f"User provided new input during plan execution: {trim(user_text, 500)}\n"
87920
88705
  f"Current plan step: {step_desc}\n"
87921
- f"{directive}\n"
88706
+ f"{directive}\n{revision_note}"
87922
88707
  f"</user-feedback-merge>"
87923
88708
  )
87924
88709
  else:
@@ -89686,7 +90471,13 @@ body{padding:18px}
89686
90471
  self._emit("status", {"summary": "plan-mode: research phase started"})
89687
90472
  bb = self._ensure_blackboard()
89688
90473
  bb["status"] = "PLANNING"
89689
- bb["plan"] = {"phase": "research", "findings": []}
90474
+ previous_plan = bb.get("plan", {})
90475
+ continuing_preparation = isinstance(previous_plan, dict) and (
90476
+ previous_plan.get("preparation_state") in {"pending", "awaiting_clarification"}
90477
+ or previous_plan.get("phase") in {"preparation_pending", "awaiting_clarification"}
90478
+ )
90479
+ previous_findings = previous_plan.get("findings", []) if continuing_preparation else []
90480
+ bb["plan"] = {"phase": "research", "findings": previous_findings}
89690
90481
  self.blackboard = bb
89691
90482
 
89692
90483
  # Perform one bounded, high-confidence discovery pass before research
@@ -89701,10 +90492,11 @@ body{padding:18px}
89701
90492
  research_prompt = self._plan_mode_research_prompt()
89702
90493
  self._seed_plan_mode_explorer_context(research_prompt)
89703
90494
 
89704
- productive_rounds = 0
89705
90495
  stale_rounds = 0
89706
90496
  research_sig = self._plan_mode_research_signature()
89707
- for r in range(PLAN_MODE_EXPLORER_MAX_ROUNDS):
90497
+ preparation_ready = False
90498
+ research_round_limit = max(1, int(getattr(self, "runtime_round_budget", 0) or self.max_agent_rounds))
90499
+ for r in range(research_round_limit):
89708
90500
  if self.cancel_requested:
89709
90501
  return {"status": "interrupted"}
89710
90502
  self._inject_pending_user_inputs()
@@ -89712,24 +90504,32 @@ body{padding:18px}
89712
90504
  status = str(step.get("status", "") or "")
89713
90505
  if status == "interrupted":
89714
90506
  return {"status": "interrupted"}
90507
+ if status == "awaiting_clarification":
90508
+ return {"status": status}
90509
+ if status == "ready":
90510
+ preparation_ready = True
90511
+ break
89715
90512
  if status in {"ok", "findings-only", "no-tools"}:
89716
90513
  self._plan_mode_update_findings(step)
89717
90514
  new_sig = self._plan_mode_research_signature()
89718
90515
  if new_sig != research_sig:
89719
- productive_rounds += 1
89720
90516
  stale_rounds = 0
89721
90517
  research_sig = new_sig
89722
90518
  else:
89723
90519
  stale_rounds += 1
89724
- if status in ("no-tools", "findings-only", "skip"):
89725
- break
89726
- if productive_rounds >= PLAN_MODE_EXPLORER_PRODUCTIVE_ROUNDS:
89727
- self._emit("status", {"summary": "plan-mode: evidence budget satisfied; synthesizing now"})
89728
- break
89729
90520
  if stale_rounds >= PLAN_MODE_EXPLORER_STALE_ROUNDS:
89730
- self._emit("status", {"summary": "plan-mode: no new evidence; synthesizing current findings"})
90521
+ self._emit("status", {"summary": "plan-mode: preparation has not demonstrated readiness; preserving research"})
89731
90522
  break
89732
90523
 
90524
+ if not preparation_ready:
90525
+ bb = self._ensure_blackboard()
90526
+ bb["status"] = "PAUSED"
90527
+ bb["plan"]["phase"] = "research"
90528
+ bb["plan"]["preparation_state"] = "pending"
90529
+ self.blackboard = bb
90530
+ self._emit("status", {"summary": "plan-mode: research paused without a readiness decision; no executable plan was fabricated"})
90531
+ return {"status": "preparation_pending"}
90532
+
89733
90533
  # Phase 2: manager synthesis of structured executable options
89734
90534
  # Inject pending user inputs before synthesis
89735
90535
  self._inject_pending_user_inputs()
@@ -89816,10 +90616,31 @@ body{padding:18px}
89816
90616
  self._emit("status", {"summary": "plan-mode: awaiting user choice"})
89817
90617
  return {"status": "awaiting_choice", "options": len(proposal.get("options", []) or [])}
89818
90618
 
90619
+ @staticmethod
90620
+ def _plan_todo_runtime_contract() -> str:
90621
+ return (
90622
+ "TODO RUNTIME CONTRACT: approved major steps automatically become canonical Todo rows. "
90623
+ "Maintain current-step subtasks and statuses throughout execution; keep this tracking rule "
90624
+ "in global_constraints, not a standalone major phase. Never append duplicate rows for "
90625
+ "future/past major steps or activate future implementation inside a research step. "
90626
+ "Reuse stable IDs; only executable current-step work belongs under the active parent. "
90627
+ "Before choosing stages or subtasks, understand the actual goal/current state, consider available skills "
90628
+ "and read selected full workflows. Continue research or clarification until material gaps are resolved. "
90629
+ "Do not equate one observation with readiness. Choose the smallest complete set of stages that covers "
90630
+ "dependencies and independent verification. Preparation already completed during research is context, not future work; "
90631
+ "schedule additional research only for demonstrated remaining gaps. Include a concise preparation assessment with initial step-local Todos.\n"
90632
+ )
90633
+
89819
90634
  def _plan_mode_research_prompt(self) -> str:
89820
90635
  goal = self._authoritative_user_goal_for_model() or str(
89821
90636
  self.runtime_reclassify_goal or self._latest_user_goal_text() or ""
89822
90637
  )
90638
+ latest_input = self._latest_user_goal_text(max_chars=6000)
90639
+ clarification_context = (
90640
+ "## Latest User Input\n" + trim(latest_input, 6000)
90641
+ + "\nUse this reply to resolve earlier questions while preserving the overall goal. Do not ask an already answered question again.\n\n"
90642
+ if latest_input and latest_input.strip() != goal.strip() else ""
90643
+ )
89823
90644
  lang_note = model_language_instruction(self.ui_language)
89824
90645
  os_note = _detect_os_shell_instruction()
89825
90646
  # Include loaded skill summaries in research prompt
@@ -89847,8 +90668,10 @@ body{padding:18px}
89847
90668
  f"You are in plan-mode research phase. Your task is to analyze the following request "
89848
90669
  f"WITHOUT making any modifications.\n\n"
89849
90670
  f"## User Request\n{goal}\n\n"
90671
+ f"{clarification_context}"
89850
90672
  f"{skills_section}"
89851
90673
  f"## Instructions\n"
90674
+ f"{self._plan_todo_runtime_contract()}\n"
89852
90675
  f"1. Start from the user request and inspect only evidence needed to choose an executable architecture. "
89853
90676
  f"Use `list_skills` only when the requested artifact or workflow plausibly maps to a specialized skill.\n"
89854
90677
  f"2. Inspect focused workspace paths or uploaded inputs that actually exist; do not perform a generic full-directory inventory.\n"
@@ -89858,6 +90681,7 @@ body{padding:18px}
89858
90681
  f"6. Assess risks and note only ambiguities that materially require user input\n"
89859
90682
  f"7. DO NOT write, edit, or create any files. Read-only analysis only. Stop once new reads no longer change the proposed execution path.\n"
89860
90683
  f"8. Write only decision-relevant findings to the blackboard under 'plan_findings'. Include relevant paths/APIs, constraints, validation commands, and any loaded-skill workflow requirements. Omit empty sections and generic inventories.\n"
90684
+ f"When the goal, necessary current state and complete selected workflows are understood, call assess_task_preparation with brief goal/state/skills summaries, basis, ready=true and missing=[]. This is the only signal to finish research. No read quota or round count implies readiness. If material user choices are missing, call ask_user and wait; otherwise continue focused observations. User-provided or recalled context can suffice without new reads.\n"
89861
90685
  f"9. For coding tasks, identify the test strategy:\n"
89862
90686
  f" - What build/compilation commands are available? (Makefile, npm, cargo, cmake, etc.)\n"
89863
90687
  f" - What test frameworks/suites exist? (pytest, jest, go test, etc.)\n"
@@ -89908,6 +90732,14 @@ body{padding:18px}
89908
90732
  name = str(fn.get("name", "")).strip()
89909
90733
  if name in PLAN_MODE_RESEARCH_TOOL_ALLOWLIST or name.startswith(MCP_TOOL_PREFIX):
89910
90734
  filtered_tools.append(tool)
90735
+ preparation_schema = next(
90736
+ tool["function"]["parameters"]["properties"]["preparation"]
90737
+ for tool in self._available_tools() if tool.get("function", {}).get("name") == "TodoWrite"
90738
+ )
90739
+ filtered_tools.append(tool_def(
90740
+ "assess_task_preparation", "Finish research only when the actual task and selected complete workflows are understood; otherwise keep observing or ask_user.",
90741
+ preparation_schema["properties"], ["goal", "state", "skills", "basis", "ready", "missing"],
90742
+ ))
89911
90743
  if not filtered_tools:
89912
90744
  filtered_tools = self._tools_for_agent("explorer")
89913
90745
  with self.lock:
@@ -90009,6 +90841,7 @@ body{padding:18px}
90009
90841
  return {"status": "no-tools", "text": "", "thinking": thinking_text}
90010
90842
  # Execute tool calls (read-only)
90011
90843
  evidence_rows: list[str] = []
90844
+ preparation_ready = False
90012
90845
  for tc in tool_calls:
90013
90846
  if self.cancel_requested:
90014
90847
  return {"status": "interrupted"}
@@ -90036,12 +90869,17 @@ body{padding:18px}
90036
90869
  }, mirror_to_global=False)
90037
90870
  continue
90038
90871
  try:
90039
- raw_output = self._dispatch_tool(
90040
- fn_name,
90041
- fn_args,
90042
- agent_role="explorer",
90043
- tool_call_id=str(tc.get("id", "") or ""),
90044
- )
90872
+ if fn_name == "assess_task_preparation":
90873
+ feedback = self._todo_preparation_guard({"preparation": fn_args}, role="explorer", existing_rows=[], board=self._ensure_blackboard())
90874
+ preparation_ready = not feedback
90875
+ raw_output = feedback or "Task preparation ready; synthesize from the verified context and findings."
90876
+ else:
90877
+ raw_output = self._dispatch_tool(
90878
+ fn_name,
90879
+ fn_args,
90880
+ agent_role="explorer",
90881
+ tool_call_id=str(tc.get("id", "") or ""),
90882
+ )
90045
90883
  except Exception as exc:
90046
90884
  raw_output = f"Error: {exc}"
90047
90885
  result_content = str(raw_output or "")
@@ -90075,6 +90913,18 @@ body{padding:18px}
90075
90913
  "conversation_visible": canonicalize_tool_name(fn_name) in CONVERSATION_VISIBLE_TOOL_EVENTS,
90076
90914
  "summary": f"plan-mode research: {fn_name}",
90077
90915
  })
90916
+ if self._consume_ask_user_pause():
90917
+ bb = self._ensure_blackboard()
90918
+ bb["plan"]["phase"] = "research"
90919
+ bb["plan"]["preparation_state"] = "awaiting_clarification"
90920
+ self.blackboard = bb
90921
+ self._enter_ask_user_paused_state("explorer")
90922
+ return {"status": "awaiting_clarification"}
90923
+ if preparation_ready:
90924
+ # A ready signal closes the preparation transaction; any
90925
+ # later calls in the batch cannot revise that evidence.
90926
+ self._plan_mode_update_findings({"text": json_dumps(fn_args), "finding_source": "preparation"})
90927
+ return {"status": "ready"}
90078
90928
  finding_text = str(text or "").strip()
90079
90929
  finding_source = "content"
90080
90930
  if not finding_text and thinking_text:
@@ -90986,6 +91836,13 @@ body{padding:18px}
90986
91836
  goal = self._authoritative_user_goal_for_model() or str(
90987
91837
  self.runtime_reclassify_goal or self._latest_user_goal_text() or ""
90988
91838
  )
91839
+ latest_input = self._latest_user_goal_text(max_chars=6000)
91840
+ preparation_context = (
91841
+ "\n## Current Preparation Decision\n"
91842
+ + json_dumps((bb.get("preparation_decisions") or [{}])[-1])
91843
+ + ("\nLatest user input: " + trim(latest_input, 6000) if latest_input and latest_input.strip() != goal.strip() else "")
91844
+ + "\nResolved questions are completed context, not future blocking phases. Plan only remaining work.\n\n"
91845
+ )
90989
91846
  # Include loaded skill guidance in synthesis
90990
91847
  bb_skills = bb.get("loaded_skills", {})
90991
91848
  skills_section = ""
@@ -91005,13 +91862,14 @@ body{padding:18px}
91005
91862
  "- Which tool to call (bash, read_file, write_file, etc.)\n"
91006
91863
  "- Which specific file paths to use (e.g., 'Read uploaded/IEDM_.parsed.md')\n"
91007
91864
  "- What output to produce at each step\n"
91008
- "Decompose each skill's workflow into 3-5 substeps based on the skill's instructions.\n\n"
91865
+ "Use only the workflow steps required by this task and its actual dependencies; do not impose a fixed substep count.\n\n"
91009
91866
  )
91010
91867
  synthesis_prompt = (
91011
91868
  f"Based on the research findings below, generate a structured plan proposal "
91012
91869
  f"with up to {PLAN_MODE_MAX_OPTIONS} options for the user to choose from.\n\n"
91013
91870
  f"## User Request\n{goal}\n\n"
91014
91871
  f"## Research Findings\n{trim(findings_text, 6000)}\n\n"
91872
+ f"{preparation_context}"
91015
91873
  f"{skills_section}"
91016
91874
  f"## Instructions\n"
91017
91875
  f"You MUST call the submit_plan_proposal tool exactly once with:\n"
@@ -91032,7 +91890,7 @@ body{padding:18px}
91032
91890
  f"DO NOT invent script names like 'analyze_reports.py' or 'generate_pptx.js' that don't exist. "
91033
91891
  f"Use the real scripts found in /skills/ directories (e.g., project_manager.py, svg_to_pptx.py).\n"
91034
91892
  f"- When a loaded skill defines a specific workflow, follow that workflow's actual tools and scripts.\n"
91035
- f"- For complex tasks, produce 8-15 detailed steps, not 3-5 vague ones\n"
91893
+ f"- Choose major steps from actual dependencies and ownership boundaries. Honor the user's requested stages; do not inflate a small task to meet a step-count target.\n"
91036
91894
  f"- Each step should be completable in 1-3 tool calls\n"
91037
91895
  f"- Every major step must include an explicit acceptance signal: how to know the step is done.\n"
91038
91896
  f"- Acceptance signals must use observable evidence such as exit code, test summary, API response, rendered output, parsed rows, numerical thresholds, or screenshot/result inspection.\n"
@@ -91041,6 +91899,7 @@ body{padding:18px}
91041
91899
  f"- Never combine implementation with independent testing/review in the same major step. Put independent verification in the following major step so it can have a distinct owner.\n"
91042
91900
  f"- A developer may run a fast local smoke check while implementing, but the independent test/review major step remains separate for complex multi-agent plans.\n"
91043
91901
  f"- Do not create a full research->implementation->review chain for every micro-task; add phase boundaries only when ownership or risk changes.\n"
91902
+ f"{self._plan_todo_runtime_contract()}\n"
91044
91903
  f"\nSTEP STRUCTURE — MAJOR STEPS WITH SUB-STEPS:\n"
91045
91904
  f"Organize steps into MAJOR numbered groups. Each major step has:\n"
91046
91905
  f" 1) A summary title line: \"N. Summary Title\" (e.g., \"1. Project Initialization\")\n"
@@ -91071,7 +91930,7 @@ body{padding:18px}
91071
91930
  f"- Each major step = one array element with summary title + 2-5 sub-steps\n"
91072
91931
  f"- Summary title captures the THEME of that group (not just repeat the first sub-step)\n"
91073
91932
  f"- Sub-steps include specific file paths, commands, or expected outputs\n"
91074
- f"- Aim for 5-8 major steps for complex tasks, 3-5 for simpler ones\n"
91933
+ f"- Prefer the smallest complete set of major steps that preserves research, implementation, and independent verification when needed.\n"
91075
91934
  f"\n"
91076
91935
  f"Make options meaningfully different across their END-TO-END architecture, deliverable, scope, or trade-off. "
91077
91936
  f"Changing only initialization folders, filenames, or the first step does not create a distinct option.\n"
@@ -91124,7 +91983,7 @@ body{padding:18px}
91124
91983
  synthesis_ctx,
91125
91984
  tools=synthesis_tools,
91126
91985
  system=synthesis_system,
91127
- max_tokens=PLAN_MODE_MANAGER_SYNTHESIS_MAX_TOKENS,
91986
+ max_tokens=self.max_output_tokens,
91128
91987
  think=False,
91129
91988
  stream_thinking=False,
91130
91989
  on_thinking_chunk=self._append_live_thinking,
@@ -91148,7 +92007,7 @@ body{padding:18px}
91148
92007
  ],
91149
92008
  tools=synthesis_tools,
91150
92009
  system="You MUST call submit_plan_proposal exactly once. Do not answer with plain text.",
91151
- max_tokens=PLAN_MODE_MANAGER_SYNTHESIS_MAX_TOKENS,
92010
+ max_tokens=self.max_output_tokens,
91152
92011
  think=False,
91153
92012
  stream_thinking=False,
91154
92013
  on_thinking_chunk=self._append_live_thinking,
@@ -91175,7 +92034,8 @@ body{padding:18px}
91175
92034
  f"Generate ONE simple plan for this task. You MUST call submit_plan_proposal with exactly 1 option.\n\n"
91176
92035
  f"Task: {goal}\n\nFindings: {trim(findings_text, 3000)}\n\n"
91177
92036
  f"Return a single option with id='A', an unnumbered option-level title, "
91178
- f"a one-sentence decision summary, and 5-10 concrete steps. "
92037
+ f"a one-sentence decision summary, and concrete steps proportional to the task. "
92038
+ f"{self._plan_todo_runtime_contract()}\n"
91179
92039
  f"Do not reuse the first step as the title or summary.\n"
91180
92040
  f"Do NOT answer with prose-only markdown. A response without submit_plan_proposal tool call is invalid.\n"
91181
92041
  f"{model_language_instruction(self.ui_language)}"
@@ -91196,7 +92056,7 @@ body{padding:18px}
91196
92056
  ctx,
91197
92057
  tools=self._plan_mode_synthesis_tools(),
91198
92058
  system="You MUST call submit_plan_proposal exactly once. Do not answer with plain text.",
91199
- max_tokens=6000,
92059
+ max_tokens=self.max_output_tokens,
91200
92060
  think=False,
91201
92061
  stream_thinking=False,
91202
92062
  on_thinking_chunk=self._append_live_thinking,
@@ -91220,7 +92080,7 @@ body{padding:18px}
91220
92080
  ],
91221
92081
  tools=self._plan_mode_synthesis_tools(),
91222
92082
  system="You MUST call submit_plan_proposal exactly once. Do not answer with plain text.",
91223
- max_tokens=6000,
92083
+ max_tokens=self.max_output_tokens,
91224
92084
  think=False,
91225
92085
  stream_thinking=False,
91226
92086
  on_thinking_chunk=self._append_live_thinking,
@@ -91753,7 +92613,7 @@ body{padding:18px}
91753
92613
  text = normalize_embedded_newlines(title).strip()
91754
92614
  if not text:
91755
92615
  return True
91756
- first = re.split(r"\s+", text, 1)[0].strip(" \t,,;;::.。()[]{}")
92616
+ first = re.split(r"\s+", text, maxsplit=1)[0].strip(" \t,,;;::.。()[]{}")
91757
92617
  if not first:
91758
92618
  return True
91759
92619
  if re.match(r"^[A-Za-zµμ%°]+(?:[/._^·-][A-Za-z0-9µμ%°]+)+$", first):
@@ -92683,9 +93543,14 @@ body{padding:18px}
92683
93543
  base_level = int(current_level or 3)
92684
93544
  if base_level not in TASK_LEVEL_CHOICES:
92685
93545
  base_level = 3
92686
- shift = {"low": -1, "medium": 0, "high": 1}.get(str(risk or "").strip().lower(), 0)
93546
+ # Low execution risk does not reduce the semantic scope or remove an
93547
+ # executor/reviewer from an approved L3/L4 task. High-risk escalation
93548
+ # still follows the automatic ceiling; explicit user levels win above.
93549
+ shift = 1 if str(risk or "").strip().lower() == "high" else 0
92687
93550
  target = base_level + int(shift)
92688
- return max(min(TASK_LEVEL_CHOICES), min(max(TASK_LEVEL_CHOICES), int(target)))
93551
+ target = max(min(TASK_LEVEL_CHOICES), min(max(TASK_LEVEL_CHOICES), int(target)))
93552
+ ceiling = self._auto_task_level_ceiling_value()
93553
+ return min(target, ceiling) if ceiling > 0 else target
92689
93554
 
92690
93555
  def _prune_planner_context_after_plan_approval(self, choice_id: str, chosen: dict, grouped_steps: list):
92691
93556
  planner_rows = [
@@ -93017,9 +93882,11 @@ body{padding:18px}
93017
93882
  self._set_runtime_phase(self._startup_phase("model-ready"))
93018
93883
  self._ensure_runtime_model_ready()
93019
93884
  pinned_selection = self._active_runtime_selection()
93020
- # Keep startup classification local and bounded by default. The
93021
- # legacy model classifier remains available behind an opt-out env.
93022
- goal_for_classify = self.runtime_reclassify_goal or self._latest_user_goal_text()
93885
+ # The local pre-screen supplies hints; the policy router below
93886
+ # still makes the semantic decision over the actual user request.
93887
+ goal_for_classify = self._unwrap_program_ide_task_text(
93888
+ self.runtime_reclassify_goal or self._latest_user_goal_text()
93889
+ )
93023
93890
  self._set_runtime_phase(self._startup_phase("complexity-precheck"))
93024
93891
  try:
93025
93892
  self._cached_llm_complexity = (
@@ -93372,8 +94239,9 @@ body{padding:18px}
93372
94239
  f"This is continuation {consecutive_empty_action_rounds + 1} of "
93373
94240
  f"{EMPTY_ACTION_BOOTSTRAP_THINKING_GRACE_ROUNDS} before compatibility recovery. "
93374
94241
  "The prior response completed internal reasoning but emitted no TodoWrite action. "
93375
- "Do not restart perception or describe the analysis; convert the existing reasoning "
93376
- "and observed evidence into exactly one TodoWrite or TodoWriteRescue call now."
94242
+ "Use the existing observations to decide whether preparation is complete. If material context is missing, "
94243
+ "choose the next read-only discovery or ask_user; otherwise submit your own TodoWrite with "
94244
+ "the brief preparation assessment. Do not manufacture a checklist to satisfy a turn count."
93377
94245
  )
93378
94246
  if bootstrap_thinking_signal:
93379
94247
  continuation += (
@@ -93428,7 +94296,7 @@ body{padding:18px}
93428
94296
  parsed_args = raw_args
93429
94297
  if not isinstance(parsed_args, dict):
93430
94298
  parsed_args = parse_tool_arguments(raw_args)
93431
- if self._single_no_plan_todo_is_perception_result(
94299
+ if call_name == "ask_user" or self._single_no_plan_todo_is_perception_result(
93432
94300
  {"name": call_name, "args": parsed_args, "ok": True}
93433
94301
  ):
93434
94302
  # Read-only calls are deliberately allowed during
@@ -100379,7 +101247,7 @@ Object.assign(I18N['en'],{
100379
101247
  event_truncation_recovery:'Truncation Recovery',event_truncation_state:'Structured truncation recovery state',event_truncation_note:'Model output hit a truncation boundary and entered recovery mode.',
100380
101248
  event_live_model_call_title:'Agent Turn Model Call',event_live_model_call_note:'The active agent is in a model call. This timer updates live while generation is in progress.',
100381
101249
  event_scheduler_queued_title:'Queued Task',event_scheduler_queued_note:'This message is saved and waiting for an execution slot.',event_scheduler_queue_position:'queue position',event_scheduler_reason:'reason',event_scheduler_queued_hint:'queued',
100382
- event_auto_continue:'Auto Continue',event_arbiter_continue:'Arbiter Continue',event_continuation_briefing:'Continuation Briefing',event_reminder:'Reminder',event_todo_rescue:'Todo Rescue',event_tool_retry:'Tool Retry',event_segmented_retry:'Segmented Retry',event_forced_converge:'Forced Converge',event_no_tool_recovery:'No-Tool Recovery',event_context_recall:'Context Recall',event_failure_recovery:'Failure Recovery',event_truncate_rescue:'Truncation Rescue',event_thinking_recovery:'Thinking Recovery',event_fault_prefill:'Fault Prefill',event_edit_recovery:'Edit Recovery',event_todo_bootstrap_title:'Todo Initialization',event_todo_bootstrap_retry_title:'Todo Initialization Retry',event_todo_bootstrap_subtitle:'Planning state after read-only perception',event_todo_bootstrap_note:'The next Todo list is being shaped from observed evidence before execution resumes.',event_todo_bootstrap_retry_note:'The Todo writer did not complete; the bounded retry is being requested.',event_todo_bootstrap_perception:'perception complete',event_todo_bootstrap_item_count:'1-40 items · stage-aligned',event_todo_bootstrap_one_active:'exactly 1 active',event_reason:'reason',event_query:'query',event_archive:'archive',event_details:'Details',event_matches:'matches',event_returned:'returned',
101250
+ event_auto_continue:'Auto Continue',event_arbiter_continue:'Arbiter Continue',event_continuation_briefing:'Continuation Briefing',event_reminder:'Reminder',event_todo_rescue:'Todo Rescue',event_tool_retry:'Tool Retry',event_segmented_retry:'Segmented Retry',event_forced_converge:'Forced Converge',event_no_tool_recovery:'No-Tool Recovery',event_context_recall:'Context Recall',event_failure_recovery:'Failure Recovery',event_truncate_rescue:'Truncation Rescue',event_thinking_recovery:'Thinking Recovery',event_fault_prefill:'Fault Prefill',event_edit_recovery:'Edit Recovery',event_todo_bootstrap_title:'Todo Initialization',event_todo_bootstrap_retry_title:'Todo Initialization Retry',event_todo_bootstrap_subtitle:'Assessing the goal, current state and selected workflows',event_todo_bootstrap_note:'Observe or clarify material gaps; commit Todos when the context is sufficient.',event_todo_bootstrap_retry_note:'Preparation continues; a retry does not imply that the task is ready to plan.',event_todo_bootstrap_perception:'preparation open',event_todo_bootstrap_item_count:'1-40 items · stage-aligned',event_todo_bootstrap_one_active:'exactly 1 active',event_reason:'reason',event_query:'query',event_archive:'archive',event_details:'Details',event_matches:'matches',event_returned:'returned',
100383
101251
  state_on:'on',state_off:'off',
100384
101252
  rt_session:'session',rt_model:'model',rt_thinking:'thinking',rt_thinking_stream:'thinking_stream',rt_response_stream:'response_stream',rt_mode:'mode',rt_active_agent:'active_agent',rt_blackboard:'bb',rt_task:'task',rt_complexity:'complexity',rt_judgement:'judgement',rt_budget:'budget',rt_remaining:'remaining',rt_blackboard_cycles:'bb_cycles',rt_round_limit:'round_limit',rt_round:'round',rt_phase:'phase',rt_queued_inputs:'queued_inputs',rt_run_timeout:'run_timeout',rt_ctx_used:'ctx_used',rt_ctx_limit:'ctx_limit',rt_ctx_mode:'ctx_mode',rt_manual_lock:'manual-lock',rt_adaptive:'adaptive',rt_ctx_left:'ctx_left',rt_ctx_left_for:'{label} left',rt_ctx_live_title:'Remaining context budget by active call',rt_truncation:'truncation',rt_trunc_retry:'trunc_retry',rt_trunc_tokens:'trunc_tokens~',rt_archive:'archive',rt_last_compact:'last_compact',compact_ago:'ago',compact_just_now:'just now',rt_ollama:'ollama',rt_files:'files',rt_ui_mode:'ui_mode',rt_state:'state',rt_awaiting_user:'awaiting user',ask_user_title:'Agent needs your input',ask_user_free_hint:'Pick an option above, or type your answer below and send.',ask_user_pick_hint:'Pick one of the options above to continue.',
100385
101253
  preview_download:'Download',preview_source:'Source',preview_rendered:'Preview',preview_copy_link:'Copy Link',preview_open:'Open in Browser',preview_link_copied:'Link Copied',
@@ -100408,7 +101276,7 @@ Object.assign(I18N['zh-CN'],{
100408
101276
  event_truncation_recovery:'截断恢复',event_truncation_state:'结构化截断恢复状态',event_truncation_note:'模型输出触发了截断边界,已进入恢复流程。',
100409
101277
  event_live_model_call_title:'Agent 轮次模型调用',event_live_model_call_note:'当前活跃 agent 正在进行模型调用。计时器会在生成期间实时更新。',
100410
101278
  event_scheduler_queued_title:'任务已排队',event_scheduler_queued_note:'这条消息已保存,正在等待后台执行名额。',event_scheduler_queue_position:'队列位置',event_scheduler_reason:'原因',event_scheduler_queued_hint:'已排队',
100411
- event_auto_continue:'自动继续',event_arbiter_continue:'裁决继续',event_continuation_briefing:'续跑简报',event_reminder:'提醒',event_todo_rescue:'待办救援',event_tool_retry:'工具重试',event_segmented_retry:'分段重试',event_forced_converge:'强制收敛',event_no_tool_recovery:'无工具恢复',event_context_recall:'上下文召回',event_failure_recovery:'故障恢复',event_truncate_rescue:'截断救援',event_thinking_recovery:'思考恢复',event_fault_prefill:'故障预填',event_edit_recovery:'编辑恢复',event_todo_bootstrap_title:'Todo 初始化',event_todo_bootstrap_retry_title:'Todo 初始化重试',event_todo_bootstrap_subtitle:'只读感知后的规划状态',event_todo_bootstrap_note:'系统正在根据已观察证据整理下一组 Todo,然后继续执行。',event_todo_bootstrap_retry_note:'Todo 写入未完成,系统正在进行有限次数的重试。',event_todo_bootstrap_perception:'感知已完成',event_todo_bootstrap_item_count:'1-40 项 · 对齐阶段',event_todo_bootstrap_one_active:'恰好 1 项进行中',event_reason:'原因',event_query:'查询',event_archive:'归档',event_details:'详细内容',event_matches:'条匹配',event_returned:'条召回',
101279
+ event_auto_continue:'自动继续',event_arbiter_continue:'裁决继续',event_continuation_briefing:'续跑简报',event_reminder:'提醒',event_todo_rescue:'待办救援',event_tool_retry:'工具重试',event_segmented_retry:'分段重试',event_forced_converge:'强制收敛',event_no_tool_recovery:'无工具恢复',event_context_recall:'上下文召回',event_failure_recovery:'故障恢复',event_truncate_rescue:'截断救援',event_thinking_recovery:'思考恢复',event_fault_prefill:'故障预填',event_edit_recovery:'编辑恢复',event_todo_bootstrap_title:'Todo 初始化',event_todo_bootstrap_retry_title:'Todo 初始化重试',event_todo_bootstrap_subtitle:'理解目标、当前状态与已选技能流程',event_todo_bootstrap_note:'必要信息不明时继续观察或澄清,充分理解后再建立 Todo。',event_todo_bootstrap_retry_note:'系统继续准备;重试不代表任务已满足建表条件。',event_todo_bootstrap_perception:'准备中',event_todo_bootstrap_item_count:'1-40 项 · 对齐阶段',event_todo_bootstrap_one_active:'恰好 1 项进行中',event_reason:'原因',event_query:'查询',event_archive:'归档',event_details:'详细内容',event_matches:'条匹配',event_returned:'条召回',
100412
101280
  state_on:'开',state_off:'关',
100413
101281
  rt_session:'会话',rt_model:'模型',rt_thinking:'思考',rt_thinking_stream:'思考流',rt_response_stream:'正文流',rt_mode:'模式',rt_active_agent:'活跃代理',rt_blackboard:'黑板',rt_task:'任务',rt_complexity:'复杂度',rt_judgement:'裁决',rt_budget:'预算',rt_remaining:'剩余',rt_blackboard_cycles:'黑板轮次',rt_round_limit:'轮次上限',rt_round:'轮次',rt_phase:'阶段',rt_queued_inputs:'排队输入',rt_run_timeout:'运行超时',rt_ctx_used:'上下文已用',rt_ctx_limit:'上下文上限',rt_ctx_mode:'上下文模式',rt_manual_lock:'手动锁定',rt_adaptive:'自适应',rt_ctx_left:'上下文剩余',rt_ctx_left_for:'{label}剩余',rt_ctx_live_title:'按真实调用显示上下文剩余',rt_truncation:'截断数',rt_trunc_retry:'截断重试',rt_trunc_tokens:'截断Token~',rt_archive:'归档',rt_last_compact:'最近压缩',compact_ago:'前',compact_just_now:'刚刚',rt_ollama:'Ollama',rt_files:'文件根目录',rt_ui_mode:'界面模式',rt_state:'状态',rt_awaiting_user:'等待用户',ask_user_title:'需要你的输入',ask_user_free_hint:'点击上方选项,或在下方输入答复后发送。',ask_user_pick_hint:'请选择上方其中一个选项以继续。',
100414
101282
  preview_download:'下载',preview_source:'源码',preview_rendered:'预览',preview_copy_link:'复制链接',preview_open:'浏览器打开',preview_link_copied:'已复制链接',
@@ -100440,7 +101308,7 @@ Object.assign(I18N['zh-TW'],{
100440
101308
  event_truncation_recovery:'截斷恢復',event_truncation_state:'結構化截斷恢復狀態',event_truncation_note:'模型輸出觸發截斷邊界,已進入恢復流程。',
100441
101309
  event_live_model_call_title:'Agent 輪次模型呼叫',event_live_model_call_note:'目前活躍 agent 正在進行模型呼叫。計時器會在生成期間即時更新。',
100442
101310
  event_scheduler_queued_title:'任務已排隊',event_scheduler_queued_note:'這則訊息已保存,正在等待背景執行名額。',event_scheduler_queue_position:'佇列位置',event_scheduler_reason:'原因',event_scheduler_queued_hint:'已排隊',
100443
- event_auto_continue:'自動繼續',event_arbiter_continue:'裁決繼續',event_continuation_briefing:'續跑簡報',event_reminder:'提醒',event_todo_rescue:'待辦救援',event_tool_retry:'工具重試',event_segmented_retry:'分段重試',event_forced_converge:'強制收斂',event_no_tool_recovery:'無工具恢復',event_context_recall:'上下文召回',event_failure_recovery:'故障恢復',event_truncate_rescue:'截斷救援',event_thinking_recovery:'思考恢復',event_fault_prefill:'故障預填',event_edit_recovery:'編輯恢復',event_todo_bootstrap_title:'Todo 初始化',event_todo_bootstrap_retry_title:'Todo 初始化重試',event_todo_bootstrap_subtitle:'唯讀感知後的規劃狀態',event_todo_bootstrap_note:'系統會根據已觀察證據整理下一組 Todo,再繼續執行。',event_todo_bootstrap_retry_note:'Todo 寫入未完成,系統正在進行有限次重試。',event_todo_bootstrap_perception:'感知已完成',event_todo_bootstrap_item_count:'1-40 項 · 對齊階段',event_todo_bootstrap_one_active:'恰好 1 項進行中',event_reason:'原因',event_query:'查詢',event_archive:'歸檔',event_details:'詳細內容',event_matches:'筆匹配',event_returned:'筆召回',
101311
+ event_auto_continue:'自動繼續',event_arbiter_continue:'裁決繼續',event_continuation_briefing:'續跑簡報',event_reminder:'提醒',event_todo_rescue:'待辦救援',event_tool_retry:'工具重試',event_segmented_retry:'分段重試',event_forced_converge:'強制收斂',event_no_tool_recovery:'無工具恢復',event_context_recall:'上下文召回',event_failure_recovery:'故障恢復',event_truncate_rescue:'截斷救援',event_thinking_recovery:'思考恢復',event_fault_prefill:'故障預填',event_edit_recovery:'編輯恢復',event_todo_bootstrap_title:'Todo 初始化',event_todo_bootstrap_retry_title:'Todo 初始化重試',event_todo_bootstrap_subtitle:'理解目標、目前狀態與已選技能流程',event_todo_bootstrap_note:'必要資訊不明時繼續觀察或釐清,充分理解後再建立 Todo。',event_todo_bootstrap_retry_note:'系統繼續準備;重試不代表任務已滿足建表條件。',event_todo_bootstrap_perception:'准备中',event_todo_bootstrap_item_count:'1-40 項 · 對齊階段',event_todo_bootstrap_one_active:'恰好 1 項進行中',event_reason:'原因',event_query:'查詢',event_archive:'歸檔',event_details:'詳細內容',event_matches:'筆匹配',event_returned:'筆召回',
100444
101312
  state_on:'開',state_off:'關',
100445
101313
  rt_session:'會話',rt_model:'模型',rt_thinking:'思考',rt_thinking_stream:'思考流',rt_response_stream:'正文串流',rt_mode:'模式',rt_active_agent:'活躍代理',rt_blackboard:'黑板',rt_task:'任務',rt_complexity:'複雜度',rt_judgement:'裁決',rt_budget:'預算',rt_remaining:'剩餘',rt_blackboard_cycles:'黑板輪次',rt_round_limit:'輪次上限',rt_round:'輪次',rt_phase:'階段',rt_queued_inputs:'排隊輸入',rt_run_timeout:'執行逾時',rt_ctx_used:'上下文已用',rt_ctx_limit:'上下文上限',rt_ctx_mode:'上下文模式',rt_manual_lock:'手動鎖定',rt_adaptive:'自適應',rt_ctx_left:'上下文剩餘',rt_ctx_left_for:'{label}剩餘',rt_ctx_live_title:'依真實呼叫顯示上下文剩餘',rt_truncation:'截斷數',rt_trunc_retry:'截斷重試',rt_trunc_tokens:'截斷Token~',rt_archive:'封存',rt_last_compact:'最近壓縮',compact_ago:'前',compact_just_now:'剛剛',rt_ollama:'Ollama',rt_files:'檔案根目錄',rt_ui_mode:'介面模式',rt_state:'狀態',rt_awaiting_user:'等待使用者',ask_user_title:'需要你的輸入',ask_user_free_hint:'點擊上方選項,或在下方輸入答覆後送出。',ask_user_pick_hint:'請選擇上方其中一個選項以繼續。',
100446
101314
  preview_download:'下載',preview_source:'原始碼',preview_rendered:'預覽',preview_copy_link:'複製連結',preview_open:'瀏覽器開啟',preview_link_copied:'已複製連結',
@@ -100470,7 +101338,7 @@ Object.assign(I18N['ja'],{
100470
101338
  event_truncation_recovery:'切り詰め復旧',event_truncation_state:'構造化切り詰め復旧状態',event_truncation_note:'モデル出力が切り詰め境界に達したため、復旧フローに入りました。',
100471
101339
  event_live_model_call_title:'Agent ターンモデル呼び出し',event_live_model_call_note:'現在のアクティブ agent はモデル呼び出し中です。生成中はこのタイマーがリアルタイム更新されます。',
100472
101340
  event_scheduler_queued_title:'キュー済みタスク',event_scheduler_queued_note:'このメッセージは保存され、実行枠を待っています。',event_scheduler_queue_position:'キュー位置',event_scheduler_reason:'理由',event_scheduler_queued_hint:'キュー済み',
100473
- event_auto_continue:'自動継続',event_arbiter_continue:'判定継続',event_continuation_briefing:'継続ブリーフ',event_reminder:'リマインダー',event_todo_rescue:'Todo 救援',event_tool_retry:'ツール再試行',event_segmented_retry:'分割再試行',event_forced_converge:'強制収束',event_no_tool_recovery:'ツールなし復旧',event_context_recall:'コンテキスト再呼び出し',event_failure_recovery:'障害復旧',event_truncate_rescue:'切り詰め救援',event_thinking_recovery:'思考復旧',event_fault_prefill:'障害プリフィル',event_edit_recovery:'編集復旧',event_todo_bootstrap_title:'Todo 初期化',event_todo_bootstrap_retry_title:'Todo 初期化の再試行',event_todo_bootstrap_subtitle:'読み取り専用の認識後に行う計画状態',event_todo_bootstrap_note:'観測した証拠から次の Todo を整理してから実行を続けます。',event_todo_bootstrap_retry_note:'Todo の書き込みが完了せず、回数を制限した再試行を行います。',event_todo_bootstrap_perception:'認識完了',event_todo_bootstrap_item_count:'1-40 項目 · 段階整合',event_todo_bootstrap_one_active:'進行中は 1 項目のみ',event_reason:'理由',event_query:'検索',event_archive:'アーカイブ',event_details:'詳細',event_matches:'件一致',event_returned:'件取得',
101341
+ event_auto_continue:'自動継続',event_arbiter_continue:'判定継続',event_continuation_briefing:'継続ブリーフ',event_reminder:'リマインダー',event_todo_rescue:'Todo 救援',event_tool_retry:'ツール再試行',event_segmented_retry:'分割再試行',event_forced_converge:'強制収束',event_no_tool_recovery:'ツールなし復旧',event_context_recall:'コンテキスト再呼び出し',event_failure_recovery:'障害復旧',event_truncate_rescue:'切り詰め救援',event_thinking_recovery:'思考復旧',event_fault_prefill:'障害プリフィル',event_edit_recovery:'編集復旧',event_todo_bootstrap_title:'Todo 初期化',event_todo_bootstrap_retry_title:'Todo 初期化の再試行',event_todo_bootstrap_subtitle:'目標・現状・選択したスキルの手順を確認',event_todo_bootstrap_note:'必要な情報を観察・確認し、十分に理解してから Todo を作成します。',event_todo_bootstrap_retry_note:'準備を継続します。再試行だけでは計画の準備完了を意味しません。',event_todo_bootstrap_perception:'準備中',event_todo_bootstrap_item_count:'1-40 項目 · 段階整合',event_todo_bootstrap_one_active:'進行中は 1 項目のみ',event_reason:'理由',event_query:'検索',event_archive:'アーカイブ',event_details:'詳細',event_matches:'件一致',event_returned:'件取得',
100474
101342
  state_on:'オン',state_off:'オフ',
100475
101343
  rt_session:'セッション',rt_model:'モデル',rt_thinking:'思考',rt_thinking_stream:'思考ストリーム',rt_response_stream:'レスポンスストリーム',rt_mode:'モード',rt_active_agent:'アクティブAgent',rt_blackboard:'黒板',rt_task:'タスク',rt_complexity:'複雑度',rt_judgement:'判定',rt_budget:'予算',rt_remaining:'残り',rt_blackboard_cycles:'黒板サイクル',rt_round_limit:'ラウンド上限',rt_round:'ラウンド',rt_phase:'フェーズ',rt_queued_inputs:'待機入力',rt_run_timeout:'実行タイムアウト',rt_ctx_used:'コンテキスト使用量',rt_ctx_limit:'コンテキスト上限',rt_ctx_mode:'コンテキストモード',rt_manual_lock:'手動固定',rt_adaptive:'適応',rt_ctx_left:'残りコンテキスト',rt_ctx_left_for:'{label}残り',rt_ctx_live_title:'実際の呼び出し別の残りコンテキスト',rt_truncation:'切り詰め数',rt_trunc_retry:'切り詰め再試行',rt_trunc_tokens:'切り詰めToken~',rt_archive:'アーカイブ',rt_last_compact:'直近 compact',compact_ago:'前',compact_just_now:'たった今',rt_ollama:'Ollama',rt_files:'ファイルルート',rt_ui_mode:'UIモード',rt_state:'状態',rt_awaiting_user:'ユーザー待ち',ask_user_title:'入力が必要です',ask_user_free_hint:'上のオプションを選ぶか、下に回答を入力して送信してください。',ask_user_pick_hint:'続行するには上のオプションを選んでください。',
100476
101344
  preview_download:'ダウンロード',preview_source:'ソース',preview_rendered:'プレビュー',preview_copy_link:'リンクをコピー',preview_open:'ブラウザで開く',preview_link_copied:'リンクをコピーしました',