Skip to content
Merged
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
7 changes: 4 additions & 3 deletions loopx/control_plane/work_items/replan_semantics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const ACCEPTANCE_HOLD_TRIGGERS = new Set(["goal_acceptance_stale", "goal_accepta
// These review kinds carry no evidence window, capability or lifecycle duty.
// A vision gap dominates the ordinary outcome gap's discharge policy, so the
// same scalar receipt can retain a mixed review after its work links change.
const SCALAR_REVIEW_KINDS = new Set(["goal_outcome_uncovered", "vision_acceptance_gap"]);
const SCALAR_REVIEW_KINDS = new Set(["goal_outcome_uncovered", "vision_acceptance_gap", "monitor_no_change_streak"]);
const EXTERNAL_REVIEW_TRIGGERS = new Set(["external_progress_review_drift"]);
export const FRESH_PATH_DISPOSITIONS = new Set(["continue", "no_change", "replan"]);
const PROGRESS_CLI_ARGS = "--progress-result-class <advanced|blocked|exploration_exhausted|no_followup> --progress-surface-id <surface-id> --progress-hypothesis-id <hypothesis-id> --progress-probe-kind <probe-kind> --progress-evidence-id <evidence-id>";
Expand Down Expand Up @@ -549,7 +549,7 @@ export function projectReplanSemantics(value: unknown): JsonObject {
if (request.operation === "receipt_review_source") {
const kinds = triggerKinds(obligation);
const triggers = Array.isArray(obligation.triggers) ? obligation.triggers : [];
// Plain vision/outcome reviews share a scalar receipt source. Other mixed,
// Plain frontier reviews share a scalar receipt source. Other mixed,
// restricted, lifecycle and capability obligations must retain their
// source-specific evidence and discharge rules through their own owners.
return {review_source: obligation.schema_version === "autonomous_replan_obligation_v0" &&
Expand All @@ -563,7 +563,8 @@ export function projectReplanSemantics(value: unknown): JsonObject {
obligation.progress_baseline == null && obligation.progress_window == null &&
triggers.every(trigger => object(trigger).progress_baseline == null && object(trigger).progress_window == null) &&
typeof obligation.stop_condition === "string" && obligation.stop_condition.trim() && obligation.stop_condition.length <= 240
? {kind: kinds.includes("vision_acceptance_gap") ? "vision_acceptance_gap" : "goal_outcome_uncovered",
// Fixed precedence keeps the selected kind independent of trigger order.
? {kind: ["vision_acceptance_gap", "goal_outcome_uncovered", "monitor_no_change_streak"].find(kind => kinds.includes(kind)),
stop_condition: obligation.stop_condition} : null};
}
if (request.operation === "transition_eligibility") {
Expand Down
2 changes: 1 addition & 1 deletion skills/loopx-self-repair/references/repair-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ teaches a reusable control-plane lesson.
| `normal_no_user_todo_misflagged` | `action_required=false` and user open count is zero, but the agent reports a state projection fault. | quota payload and user todo summary. | Rule over-applied the "todo not projected" fallback. | Allow "无用户待办/无需通知"; update heartbeat/prompt smoke if needed. |
| `todo_no_followup_global_terminal_overreach` | A completed scoped Todo records `done + no_followup`, but `refresh-state --repair-delta-kind no_followup` becomes `replan_noop` because unrelated advancement or long-running monitor Todos remain open. | rejected repair-delta claim, complete Agent Todo projection, scoped Todo metadata, and the latest local no-follow-up completion. | The repair-delta validator reused Goal-level terminal-frontier completeness to validate a Todo-local closure. | Keep Goal `terminal_no_followup` strict, but validate repair-delta no-follow-up against the latest scoped completed Todo in a complete parser projection; reject other-agent, continuation-required, malformed, or truncated evidence and keep the emitted Todo evidence bounded. Cover the real CLI path with an open monitor regression. |
| `terminal_settlement_ordering_gap` | Final Todo completion succeeds, then the matching refresh or spend is rejected because the Goal is already terminal; different hosts may expose different closeout orders or retry the material effect. | Typed settlement plan and effect identity, Todo completion event, accountable refresh and spend receipts, Turn journal phase prefix, and host task-body projection. | Final `no_followup` was modeled like ordinary pre-settlement Todo completion even though it mutates Goal terminal state and activates the strict no-more-spend guard. | Keep Goal terminal guards strict. Treat ordinary successor completion as Todo lifecycle work, but make final `no_followup` a conditional post-spend terminal closeout under the same effect identity. Require matching writeback and spend receipts at the mutation boundary, prove the closeout event itself carries `no_followup`, and journal it so closeout-only retry cannot repeat writeback or spend. Cover CLI, visible Goal, Codex App, Turn driver, adapter order, failure short-circuit, and replay. |
| `receipt_bound_lifecycle_source_gap` | A lifecycle review is admitted, then closing the original Todo through its settled Turn makes same-review reentry fail with an identity conflict; a blocked refresh may commit without a qualified replan ACK. | Exact original completion identity and closeout receipt, admitted review identity/time, canonical Todo readback, typed blocked observation and writeback/debit receipts. | Lifecycle reconstruction recognized only the completion-key reentry form; writeback could treat a missing selected source like an unrelated future obligation. | Reuse the canonical completion-recovery vocabulary for both legal paths and retain exact actor, identity and timestamp checks. Revalidate every selected replan through the shared owner before writeback. For an already committed unqualified blocked observation with no debit, permit only an exact additive checkpoint requalification; preserve the original run and all receipt history, reject payload changes or later superseding vision, and never infer acceptance or erase a committed debit. |
| `receipt_bound_lifecycle_source_gap` | An admitted lifecycle or Monitor review loses its live source after Todo closeout, so same-Turn guard reentry or refresh fails with an identity conflict; a blocked refresh may commit without a qualified replan ACK. | Exact original completion identity and closeout receipt, admitted review identity/time, canonical Todo readback, typed observation and writeback/debit receipts. | Lifecycle reconstruction recognized only the completion-key reentry form; scalar receipts omitted Monitor review sources; writeback could treat a missing selected source like an unrelated future obligation. | Reuse the canonical completion-recovery vocabulary for both legal paths and retain exact actor, identity and timestamp checks. Retain unqualified Monitor review kinds and their stop conditions through the existing scalar receipt source; lifecycle closeout alone never discharges the required semantic review or authorizes debit. Revalidate every selected replan through the shared owner before writeback. For an already committed unqualified blocked observation with no debit, permit only an exact additive checkpoint requalification; preserve the original run and all receipt history, reject payload changes or later superseding vision, and never infer acceptance or erase a committed debit. |
| `host_settlement_source_projection_gap` | A visible Goal host packet requires `source=visible-goal` without an explicit Turn receipt, but the nested interaction contract tells the agent to spend as `heartbeat` and binds the currently selected Todo. The command can fail after Todo completion or misattribute interactive usage. | Host runtime profile, canonical host quota commands, interaction-contract CLI actions, selected Todo lifecycle order, and the failed spend preview. | The generic interaction projection hard-coded heartbeat accounting and selected-Todo binding instead of deriving the accounting route from the scheduler execution context. | Route spend actions from the typed runtime profile. Native Goal runtimes preserve `source=visible-goal` and host-level attribution; heartbeat automation keeps its Todo- and Turn-bound settlement plan. Cover the exact CLI actions for each native Goal profile and retain the heartbeat regression. |
| `visible_goal_settlement_replan_attribution_gap` | An accountable visible-Goal delivery writeback moves the frontier into capability or control-plane repair; the following unbound spend is recorded against the new repair state with no Todo, Turn, effect, or delivery-workspace causality, and an exact retry cannot replay the committed effect. | Newest same-Agent accountable run, its complete nested settlement identity, top-level Todo/Turn fields, original heartbeat receipt, delivery-workspace causality, current quota frontier, spend classification, and retry run count. | The unbound visible-Goal path used the mutable current frontier as settlement authority and did not recover the completed delivery identity; commit classification also represented eligible, repair, and delivery semantics as overlapping booleans, allowing a later repair projection to overwrite attribution. | Allow unbound recovery only for visible-Goal spend from the newest fully typed same-Agent accountable run; require its top-level and nested identities to match the TypeScript-generated settlement payload and revalidate the original heartbeat receipt. Preserve Todo/Turn/effect/workspace causality, write the CLI receipt under the recovered Turn, and reduce commit semantics to one closed TypeScript disposition where proven delivery completion precedes later frontier repair. Cover missing/legacy identity, capability and control-plane replan, and exact one-run replay. |
| `runtime_capability_user_gate_overreach` | A missing launcher/runtime capability such as `network` becomes `capability_gate.action=ask_owner`, `requires_user_action=true`, or a user notification even though no credential, protected access, or production authority is needed. | quota `capability_gate`, heartbeat `--available-capability` inputs, launcher/runtime observations, interaction contract user channel. | Capability availability and permission authority were collapsed into one owner-held class. | Keep runtime provisioning gaps in the agent repair lane, require truthful runtime observation before declaring availability, and reserve `ask_owner` for credentials or protected/production authority. Cover all-blocked and mixed-capability cases with capability-gate and monitor smokes. |
Expand Down
94 changes: 94 additions & 0 deletions tests/control_plane/test_monitor_replan_closeout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""Closing a Monitor cannot orphan the review Turn which admitted its closeout."""
from __future__ import annotations

import json
import shlex
from pathlib import Path

import pytest

from loopx.control_plane.testing.quota_fixtures import quota_todo_item
from test_replan_successor_guard_reentry import AGENT, GOAL, TURN, _fixture


def _guard(call, turn: str = TURN):
return call("quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT,
"--runtime-profile", "generic_cli", "--turn-instance-id", turn)


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("first", ["guard", "writeback"])
def test_monitor_closeout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, first: str) -> None:
monitor = quota_todo_item(
todo_id="todo_monitor", title="Observe the external gate", archive_state="active",
task_class="continuous_monitor", claimed_by=AGENT, action_kind="monitor",
target_key="external-gate", cadence="30m", consecutive_no_change="5",
next_due_at="2099-01-01T00:00:00Z", expires_at="2099-01-02T00:00:00Z",
)
call, _, index = _fixture(tmp_path, monkeypatch, provider, initial_todos=[monitor])
# Only the live Monitor's current streak admits this review, not run history.
index.write_text("")
state = tmp_path / "project" / "ACTIVE_GOAL_STATE.md"
state.write_text(state.read_text() + "\n## User Todo / Owner Review Reading Queue\n")
admitted = _guard(call)
assert admitted["decision"] == "autonomous_replan_required"
assert admitted["autonomous_replan_obligation"]["triggers"][0]["kind"] == "monitor_no_change_streak"
identity = admitted["heartbeat_receipt"]["settlement_identity"]
assert identity["binding_kind"] == "autonomous_replan"
actions = admitted["interaction_contract"]["cli_channel"]["next_cli_actions"]

claim = call("todo", "claim", "--goal-id", GOAL, "--todo-id", monitor["todo_id"],
"--agent-id", AGENT, "--claimed-by", AGENT)
completed = call("todo", "complete", "--goal-id", GOAL, "--todo-id", monitor["todo_id"],
"--agent-id", AGENT, "--claim-operation-id", claim["claim_operation_id"],
"--evidence", "The declared external gate is covered.", "--no-follow-up")
assert completed["ok"] is True
listed = call("todo", "list", "--goal-id", GOAL, "--todo-id", monitor["todo_id"], "--include-archived")
assert listed["todo"]["status"] == "done"

if first == "guard":
pending = _guard(call)
assert pending["heartbeat_receipt"]["settlement_identity"] == identity
assert pending["autonomous_replan_obligation"]["obligation_id"] == identity["replan_obligation_id"]
assert pending["normal_delivery_allowed"] is False

# A lifecycle transition is not itself the semantic review or a debit.
premature = call(*shlex.split(actions[1])[1:], expected_code=1)
assert premature.get("appended") is not True
vision = tmp_path / "vision.json"
vision.write_text(json.dumps({
"schema_version": "goal_vision_replan_contract_v0", "state": "no_followup",
"vision_patch": {"acceptance_summary": "The independently accepted source outcome is covered."},
"path_delta": {"schema_version": "goal_path_delta_v0", "outcome": "stop",
"prior_assumption": "The external gate still needs observation.",
"observed_reality": "The declared gate is covered and no successor remains.",
"retained": ["the independently accepted source contract"],
"evidence_refs": ["evidence:gate-coverage"]},
}))
refresh = shlex.split(actions[0])[1:]
values = {
"--progress-result-class": "no_followup", "--progress-surface-id": "gate-coverage",
"--progress-hypothesis-id": "covered-gate", "--progress-probe-kind": "closeout-review",
"--progress-evidence-id": "evidence:gate-coverage",
}
for flag, value in values.items():
refresh[refresh.index(flag) + 1] = value
refreshed = call(*refresh, "--agent-vision-json", str(vision),
"--progress-coverage-scope-id", "external-gate", "--progress-coverage-complete",
"--no-global-sync", "--suppress-external-sinks")
assert refreshed["settlement_progress"]["state"] == "spend_required"
pending = _guard(call)
assert pending["heartbeat_receipt"]["settlement_identity"] == identity
assert pending["settlement_progress"]["state"] == "spend_required"
spend = pending["interaction_contract"]["cli_channel"]["next_cli_actions"]
assert len(spend) == 1
spent = call(*shlex.split(spend[0])[1:])
assert spent["appended"] is True
assert spent["settlement_progress"]["state"] == "settled"
assert call(*shlex.split(spend[0])[1:])["appended"] is False
assert _guard(call)["effective_action"] == "heartbeat_settled_skip"
next_turn = _guard(call, "turn-after-monitor-review")
assert next_turn["ok"] is True
assert next_turn["effective_action"] == "terminal_no_followup"
rows = [json.loads(line) for line in index.read_text().splitlines()]
assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 1
31 changes: 30 additions & 1 deletion tests/control_plane_ts/replan_semantics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ test("an open Vision reconstruction must come from the exact scoped receipt sour
}
});

test("only plain vision and outcome reviews have a scalar receipt source", () => {
test("scalar review sources exclude evidence windows and restricted duties", () => {
const source = {schema_version: "autonomous_replan_obligation_v0", required: true,
obligation_id: "replan-1111111111111111", agent_id: "reviewer", trigger_count: 1,
stop_condition: "Stop at owner-only decisions.",
Expand Down Expand Up @@ -228,6 +228,35 @@ test("mixed vision/outcome recovery preserves the dominant policy without discha
}
});

test("Monitor lifecycle changes retain the admitted review without discharging it", () => {
const kind = "monitor_no_change_streak";
const source = {schema_version: "autonomous_replan_obligation_v0", required: true,
obligation_id: "replan-1111111111111111", agent_id: "reviewer", trigger_count: 1,
triggers: [{kind, todo_id: "todo_monitor", run_count: 5, threshold: 5}],
stop_condition: "Stop at owner-only decisions."};
const review = projectReplanSemantics({operation: "receipt_review_source", agent_id: "reviewer",
obligation: source}).review_source;
assert.deepEqual(review, {kind, stop_condition: source.stop_condition});
const request = {operation: "receipt_bound_obligation", guard_scoped: true,
replay_phase: "open", selected_obligation_id: source.obligation_id, current_obligation: null,
transition_candidates: [], agent_id: "reviewer", receipt_review: review};
const recovered = projectReplanSemantics(request).obligation as JsonObject;
assert.equal(recovered.obligation_id, source.obligation_id);
assert.equal(recovered.selection_binding, "heartbeat_receipt");
assert.deepEqual(recovered.triggers, [{kind}]);
assert.deepEqual(requiredSemanticOutcomes(recovered), requiredSemanticOutcomes(source));
assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered}).accepted, false);
assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered,
observation_delta: {delta_kinds: ["new_surface"]}}).accepted, true);
assert.throws(() => projectReplanSemantics({...request, guard_scoped: false}), /identity conflicts/);
for (const restriction of [{progress_baseline: {}}, {progress_window: []},
{capability_guard: {}}, {resolution_mode: "todo_lifecycle_settlement"},
{satisfying_semantic_outcomes: ["new_runnable_successor"]}]) {
assert.equal(projectReplanSemantics({operation: "receipt_review_source", agent_id: "reviewer",
obligation: {...source, ...restriction}}).review_source, null);
}
});

test("a recorded outcome review survives work-link refinement without cached context or discharge", () => {
const id = "replan-1111111111111111";
const request = {operation: "receipt_bound_obligation", guard_scoped: true,
Expand Down
Loading