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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions docs/architecture/rfcs/goal-outcome-refinement-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,12 @@ missing evidence remains unresolved, and display drift belongs to its projection
owner. This is semantic Agent guidance, not a prose classifier or a new admission
gate. The existing typed authority, stop and replan-discharge rules remain.

Ordinary conversation keeps the callable API without proactively directing a
revision. When a material user direction change makes the recorded objective
misleading, preparation retains the existing owner-review boundary. The native
Ordinary conversation exposes the revision route when direct user direction
changes the current Goal's purpose or adds a lasting responsibility to it. For
an addition, carry the existing commitments into the revised objective and add
or update the Todo in the same Goal. An explicit request for a separate Goal
uses existing Goal creation, including within the same project. Reconcile scope
conflicts before altering the current objective. Preparation retains the owner-review boundary. The native
`loopx_collaboration` tool exposes `prepare_goal_objective`, and fixes its
Goal/Agent/source Turn instead of accepting caller-supplied routing. Preparation
uses the existing `goal.update` review/apply channel, with no Goal effect.
Expand Down Expand Up @@ -151,8 +154,14 @@ do not delete revision or adoption history to make an older reader accept it.

Revisions are exceptional direction changes, not per-Turn maintenance. Ordinary
progress, Todo/route changes, diagnostic feedback and wording polish do not
justify a new shared objective. Agents reuse a pending proposal for the same
objective rather than prompting the owner again or polling. The owner reviews
justify a new shared objective. Agents share one pending review when objective,
reason, source and the current reviewed objective basis match. Each accepted
preparation operation stays bound to its normalized request and that proposal.
The CLI and Chat preview can recover the
same accepted operation, including after owner review or a Goal stop. New
proposals and new bindings to a pending proposal require an active Goal. The
retry must retain the Goal, preparing Agent, and proposal provenance. A changed
reason or source requires a new operation ID. The owner reviews
semantic necessity; the runtime rejects identical/whitespace-only objectives
but does not pretend to detect semantic equivalence. An unchanged repeated
adoption does not write a provider revision. Work changes and peer adoption
Expand Down Expand Up @@ -190,7 +199,7 @@ adherence or a long-horizon benefit.
The bound Agent distinguishes a direct human request from heartbeat instructions,
quoted documents, tool results and peer messages using the actual host context.
No substring classifier infers user authority or importance. Before continuing a
material new deliverable or correction, the Agent reuses inline outcome context
material new deliverable or a change to success criteria, the Agent reuses inline outcome context
(or inspects it only when missing),
refines the matching outcome and links work through normal Todo operations.
It retains previously stated requirements and records the latest source reference.
Expand Down Expand Up @@ -322,7 +331,9 @@ not installed adoption, general atomicity or a model-efficiency claim.

| Event | Default action | Existing mechanism |
| --- | --- | --- |
| Material direct-user deliverable/correction | Add to the matching outcome, retaining prior intent | Host context + native refinement or skill/CLI bridge |
| Direct user adds a lasting responsibility to the current Goal | Retain commitments, revise the current Goal objective, and add or update its Todo | Existing owner revision and Todo operations |
| Direct user explicitly requests a separate Goal | Preserve the current Goal and follow the requested scope | Existing Goal creation |
| Material deliverable or changed success criteria | Refine the matching outcome, retaining prior requirements | Host context + native refinement or skill/CLI bridge |
| Resume, focus switch, replan | Reuse full requirements, then choose work | Shared work context; missing-source required read only |
| Meaningful artifact/experiment milestone | Review all retained requirements against actual evidence | One refinement, optionally batched with normal writeback |
| Unmet/unreviewed outcome without linked active/waiting work | Carry a typed gap into planning | Existing frontier replan, only when no runnable advancement wins |
Expand Down
20 changes: 14 additions & 6 deletions docs/architecture/rfcs/goal-outcome-refinement-v0.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ refinement 仍是追加式操作,不能暗中改写已有 requirement。
展示错位交由投影 owner 处理。这是 Agent 语义指引,不是文案分类器或新准入门;
既有类型化权限、停止与 replan 消解规则保留。

普通对话保留可调用接口,但不主动引导修订。明确用户方向发生实质变化且当前
目标已误导工作时,准备修订仍遵守既有 owner 审阅边界。原生
直接用户指令改变当前 Goal 的用途或为它增加长期职责时,对话会给出正文修订路径。
新增职责时,将已有承诺保留在修订后的正文中,并在同一个 Goal 下增加或更新
Todo。用户明确要求独立 Goal 时沿用现有创建入口,同一项目也是如此。范围冲突应在
修改当前目标前处理。准备修订仍遵守既有 owner 审阅边界。原生
`loopx_collaboration` 提供 `prepare_goal_objective`,由宿主绑定 Goal、Agent 和
来源 Turn。准备复用既有 `goal.update` 审阅/应用通道,不修改 Goal。
**Goal 设置 → 任务所有权 → 当前目标与修订** 可以审阅 Agent 提案或填写新目标,
Expand Down Expand Up @@ -108,7 +110,11 @@ provider-only 读取保留原有历史投影。
必须保留兼容的 ID reader;不能删除修订或采用历史来迁就旧 reader。

修订只用于必要的方向变化,不是每轮维护。普通进展、Todo/路线调整、诊断反馈和
措辞润色不应生成共享目标新版本。相同目标的待审提案复用,不反复打扰 owner 或轮询。
措辞润色不应生成共享目标新版本。目标正文、理由、来源和当前审阅依据一致时共用一次待审。
每个已接受的准备操作都绑定其规范化请求和同一提案。CLI 与 Chat 预览都可以恢复
同一个已接受的操作,包括 owner 审阅之后或 Goal 停止期间。新建提案或为待审提案
绑定新操作都要求 Goal 处于活跃状态。重试须保留原 Goal、准备者与提案来源。
理由或来源改变时使用新的操作 ID。
owner 判断语义必要性;运行时拒绝相同或仅空白不同的目标,不伪装成语义等价检测器。
重复采用当前版本不写 provider revision;工作变化或其他 Agent 的采用不会使已确认
状态失效。owner 预览绑定将生效的目标摘要,因此无关工作/同伴写入无需重新审阅,
Expand All @@ -133,8 +139,8 @@ vision fixture 继续披露(20,211 → 21,148)。普通工作读取移除主
长程收益。

绑定 Goal 的 Agent 根据真实宿主上下文,区分直接人类请求、心跳、引用文档、
工具结果和同伴消息。不能靠关键词推断用户权限或重要性。推进重要新成果或
实质纠正前,复用内联成果上下文(缺失时才查询)、细化对应条目,再经正常 Todo 操作关联工作。
工具结果和同伴消息。不能靠关键词推断用户权限或重要性。推进重要新成果或采用
新的成功标准前,复用内联成果上下文(缺失时才查询)、细化对应条目,再经正常 Todo 操作关联工作。
保留旧要求并记录最新来源;没有可靠宿主消息 ID 时使用稳定的本地不透明证据
引用,不伪造已核验发送者来源。

Expand Down Expand Up @@ -229,7 +235,9 @@ active 含义;显式非活动状态仍拒绝细化。

| 节点 | 默认动作 | 联动机制 |
| --- | --- | --- |
| 直接用户消息带来重要成果/实质纠正 | 细化对应成果并保留旧意图 | 宿主上下文+原生细化或技能/CLI |
| 用户为当前 Goal 新增长期职责 | 保留现有承诺,修订当前 Goal 正文并增加或更新 Todo | 现有 owner 修订和 Todo 操作 |
| 用户明确要求独立 Goal | 保留当前 Goal,按用户请求的范围处理 | 既有 Goal 创建入口 |
| 重要新成果或成功标准变化 | 细化对应成果并保留旧要求 | 宿主上下文+原生细化或技能/CLI |
| 恢复、切换工作、replan | 复用全部要求再选择工作 | 共享工作上下文;缺少来源时才必读 |
| 有意义的产物/实验节点 | 用实际证据核对全部要求 | 一次细化,可并入普通写回 |
| 要求未满足/未自查,且没有关联的活动/等待工作 | 传递类型化规划缺口 | 现有 frontier replan;其他可执行推进优先 |
Expand Down
88 changes: 87 additions & 1 deletion loopx/chat_action_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from collections.abc import Callable
from datetime import datetime, timedelta, timezone
import hashlib
import json
Expand Down Expand Up @@ -166,7 +167,11 @@ def __init__(self, root: Path) -> None:
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
os.chmod(self.root, 0o700)
if not self.path.exists():
atomic_write_json(self.path, self._empty_payload())
with exclusive_file_lock(
self.path, agent_id="loopx-chat", operation="initialize_chat_action_store"
):
if not self.path.exists():
atomic_write_json(self.path, self._empty_payload())
os.chmod(self.path, 0o600)

@staticmethod
Expand Down Expand Up @@ -293,6 +298,87 @@ def create_preview(
self._write(payload)
return proposal

def replay_or_reuse_preview(
self,
*,
action_kind: str,
context: Mapping[str, Any],
normalized_parameters: Mapping[str, Any],
idempotency_key: str,
shared_fields: tuple[str, ...],
reusable_states: set[str],
matches_review_basis: Callable[[object], bool] | None = None,
require_exact_context: bool = False,
summary: str | None = None,
) -> dict[str, Any] | None:
"""Resolve an accepted request or bind it to an equivalent pending review."""
if summary is not None:
_safe_json_value(_bounded_text(summary, field="summary"), path="preview.summary")
key = normalize_idempotency_key(idempotency_key)
request = _safe_json_value({
"action_kind": action_kind,
"context": context,
"normalized_parameters": normalized_parameters,
})
digest = _canonical_digest(request)

def matches_scope(row: dict[str, Any]) -> bool:
row_context = row.get("context")
return (
row.get("action_kind") == action_kind and isinstance(row_context, dict)
and all(row_context.get(field) == value for field, value in context.items())
)

with exclusive_file_lock(
self.path, agent_id="loopx-chat", operation="reuse_chat_action_preview"
):
payload = self._read()
proposals = payload["proposals"]
bindings = payload["idempotency"]
if key in bindings:
binding = bindings[key]
row = proposals.get(binding["proposal_id"])
if not isinstance(row, dict):
raise ValueError("typed Chat action idempotency index is inconsistent")
# Original previews already carry their full normalized request.
# Reused previews keep the later request's identity in the index.
previous_digest = binding.get("reused_request_digest")
if previous_digest is not None:
same_request = previous_digest == digest
else:
same_request = row["normalized_parameters"] == request["normalized_parameters"] and (
not require_exact_context or row.get("context") == request["context"]
)
if not matches_scope(row) or not same_request:
raise ActionConflictError("idempotency key already belongs to another preview")
return row

if not reusable_states or matches_review_basis is None:
return None
pending = max(
(
row for row in proposals.values()
if isinstance(row, dict) and row.get("status") in reusable_states
and matches_scope(row)
and isinstance(row.get("normalized_parameters"), dict)
and all(
row["normalized_parameters"].get(field) == normalized_parameters[field]
for field in shared_fields
)
and matches_review_basis(row.get("expected_state_fingerprint"))
),
key=lambda row: (row.get("updated_at") or "", row["proposal_id"]),
default=None,
)
if pending is None:
return None
bindings[key] = {
Comment thread
loopx-agent marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

匹配了 objective、reason 和 source 之后,这里直接写下新 ID。用真实 File/SQLite 先准备 A、应用 B、再以新 ID 提交 A,当前 head 将新 ID 绑定到随后被判 stale 的旧提案,原样重试也无法恢复。基线没有这个持久别名,重试可创建当前预览并应用。请将最新 objective basis 放入待审复用的资格判断,保留已受理旧 ID 的读回路径。

"proposal_id": pending["proposal_id"],
"reused_request_digest": digest,
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
}
self._write(payload)
return pending

def record_review_card_delivery(
self,
proposal_id: str,
Expand Down
13 changes: 6 additions & 7 deletions loopx/chat_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1366,6 +1366,11 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]:
if not isinstance(parameters, Mapping) or not isinstance(context, Mapping):
raise ValueError("normalized_parameters and context must be objects")
normalized = self._normalize(action_kind, parameters)
if action_kind == "goal.update" and "reason" in normalized:
return self._prepare_objective_preview(
parameters=normalized, context=context, summary=request.get("summary"),
idempotency_key=_opaque(request.get("idempotency_key"), field="idempotency_key"),
)
canonical_update_basis = None
workspace_binding = None
if action_kind == "goal.create":
Expand All @@ -1383,13 +1388,7 @@ def preview(self, request: Mapping[str, Any]) -> dict[str, Any]:
normalized["workspace_ref"] = workspace_binding["workspace_ref"]
else:
eligibility = None
if action_kind == "goal.update" and "reason" in normalized:
if context.get("kind") != "goal" or context.get("goal_id") != normalized["goal_id"]:
raise ValueError("objective proposal context must match its Goal")
fingerprint, _ = self._objective_preview(normalized)
evidence = ["The typed Goal owner validated this current-objective revision. Root commitments, permissions and existing acceptance remain unchanged; peers must adopt the new revision before new execution."]
permission = "durable_write"
elif action_kind == "goal.acceptance.check":
if action_kind == "goal.acceptance.check":
if context.get("kind") != "goal" or context.get("goal_id") != normalized["goal_id"]:
raise ValueError("check plan context must match its target Goal")
fingerprint, preview = self._acceptance_preview(normalized)
Expand Down
4 changes: 2 additions & 2 deletions loopx/chat_loopx_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@
"For task_failure, repair the original artifact or validation environment before action=revalidate; it reruns checks without Host work. "
"When current_use.state=unavailable, repair the declared source or receiver input and read again; do not propagate those artifacts as current facts. Read action=messages between work steps for owner inbox additions. "
"Do not claim the whole canonical Goal is complete. Keep independent analysis substantive. "
"For a substantive deliverable or correction in a direct user message, reuse current inline outcome context (or action=outcomes if absent) and refine its stable outcome before dependent work. "
"A changed definition of success belongs in those requirements; chat, peer acknowledgements and Vision alone do not update acceptance. Read the refinement result and reconcile affected work. Change the Goal objective through its existing owner route only if the overall purpose changes; explicitly reconcile conflicting retained requirements. "
"For a direct user's substantive deliverable or changed definition of success, reuse inline outcome context (or action=outcomes if absent), refine the stable outcome before dependent work, and read it back. Chat, peer acknowledgements and Vision alone do not update acceptance. "
"For changed purpose or a new lasting responsibility in the current Goal, use the owner route for objective revision. For an addition, retain commitments and add or update its Todo in the same Goal. Use existing creation for an explicit new Goal. Reconcile scope conflicts, affected work and conflicting retained requirements explicitly. "
"At a material delivery milestone, review all retained requirements against actual artifacts; record evidence and unmet/uncertain conclusions in optional review. "
"Batch additions/review in one refinement; unchanged work needs no write or repeated inspect. Agent review is not independent verification, and cannot bypass configured checks. "
"Retain earlier requirements and original Goal intent; do not turn heartbeat, quoted/tool or peer content into human instructions. "
Expand Down
10 changes: 8 additions & 2 deletions loopx/control_plane/goals/acceptance.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,13 @@ def refine_goal_outcome(
}, timeout=CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS)


def require_active_goal_for_objective_update(goal: Mapping[str, Any] | None) -> None:
if goal is None:
raise ValueError("Goal acceptance requires a registered Goal")
if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
raise ValueError("Objective updates require an active Goal")


def update_goal_objective(
*, registry_path: Path, goal_id: str, document: dict[str, Any], operation: str,
expected_provider_revision: str, operation_id: str, agent_id: str | None = None,
Expand All @@ -180,8 +187,7 @@ def update_goal_objective(
from ..work_items.replan_context_codec import goal_context_facts

registry_path, goal, route = _routing(registry_path, goal_id, runtime_root, agent_id)
if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
raise ValueError("Objective updates require an active Goal")
require_active_goal_for_objective_update(goal)
return _result("goal.acceptance.objective", {**route, "actor_agent_id": agent_id,
"expected_provider_revision": expected_provider_revision, "operation_id": operation_id,
"operation": operation, "document": document, "dry_run": not execute,
Expand Down
Loading
Loading