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
1 change: 1 addition & 0 deletions loopx/control_plane/effect_runtime_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ export function createEffectRuntimeHandlers(
["turn_journal.find_settlement", lazyHandler(() => import("./turn_driver/turn_journal_query.ts"), ({findTurnJournalBySettlement}) => findTurnJournalBySettlement)],
["turn_journal.find_instance", lazyHandler(() => import("./turn_driver/turn_journal_query.ts"), ({findTurnJournalByInstance}) => findTurnJournalByInstance)],
["turn_journal.observed_capabilities", lazyHandler(() => import("./turn_driver/turn_journal_query.ts"), ({readTurnJournalCapabilities}) => readTurnJournalCapabilities)],
["turn_journal.evidence_chain", lazyHandler(() => import("./turn_driver/turn_journal_query.ts"), ({readTurnJournalEvidenceChain}) => readTurnJournalEvidenceChain)],
["todo.priority.plan", lazyHandler(() => import("./todos/priority.ts"), ({evaluateTodoPriority}) => evaluateTodoPriority)],
["todo.read", lazyHandler(() => import("./todos/read_transport.ts"), ({readTodoRuntime}) => readTodoRuntime)],
["capabilities.periodic_report.progress.select", lazyHandler(() => import("./capabilities/periodic_report_progress.ts"), ({selectPeriodicReportProgress}) => selectPeriodicReportProgress)],
Expand Down
33 changes: 33 additions & 0 deletions loopx/control_plane/turn_driver/journal_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,36 @@ def turn_journal_observed_capabilities(
if not isinstance(observed, list) or not all(isinstance(item, str) for item in observed):
return None
return observed


def turn_journal_evidence_chain(
runtime_root: Path,
*,
settlement_identity: Mapping[str, Any],
goal_ref: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
"""Read the exact journal-backed evaluation spine without inferring progress."""

request = {
"runtime_root": str(runtime_root.resolve()),
"settlement_identity": dict(settlement_identity),
}
if goal_ref is not None:
request["goal_ref"] = dict(goal_ref)
payload = effect_runtime_result("turn_journal.evidence_chain", request)
if (
not isinstance(payload, dict)
or set(payload) != {"schema_version", "availability", "evidence_chain"}
or payload.get("schema_version") != "loopx_turn_journal_evidence_chain_v0"
or payload.get("availability") not in {"recorded", "missing"}
or (
payload["availability"] == "recorded"
and not isinstance(payload.get("evidence_chain"), dict)
)
or (
payload["availability"] == "missing"
and payload.get("evidence_chain") is not None
)
):
raise RuntimeError("TypeScript Turn journal evidence-chain shape mismatch")
return dict(payload)
142 changes: 142 additions & 0 deletions loopx/control_plane/turn_driver/turn_journal_query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,48 @@ import { jsonObject, parseJsonSource, parsedSourceNumberTokens, requireJsonObjec
import {
interpretTurnJournal,
parseTurnJournalGoalBinding,
transactionPhases,
} from "./turn_journal.ts";

interface JournalEvidence {
turn_key: string;
observed_capabilities: string[] | null;
evidence_chain: TurnJournalEvidenceChain;
}

export const TURN_JOURNAL_EVIDENCE_CHAIN_SCHEMA_VERSION =
"loopx_turn_journal_evidence_chain_v0";

type EvidenceAvailability = "recorded" | "missing" | "unknown" | "not_applicable";

interface JournalEvidenceFact {
availability: EvidenceAvailability;
value: JsonObject | null;
}

export interface TurnJournalEvidenceChain {
settlement_identity: JsonObject;
turn_key: string;
status: string;
result_kind: string | null;
completed_phases: string[];
failed_phase: string | null;
phases: Array<{
phase: string;
completed: boolean;
failed: boolean;
}>;
host_result: JournalEvidenceFact;
task_validation: JournalEvidenceFact;
writeback: JournalEvidenceFact;
settlement_result: JournalEvidenceFact;
receipt: JournalEvidenceFact;
}

export interface TurnJournalEvidenceChainReadback {
schema_version: typeof TURN_JOURNAL_EVIDENCE_CHAIN_SCHEMA_VERSION;
availability: "recorded" | "missing";
evidence_chain: TurnJournalEvidenceChain | null;
}

function decodeIdentity(value: unknown): BoundSettlementIdentity {
Expand Down Expand Up @@ -75,6 +112,83 @@ function observedCapabilities(envelope: JsonObject): string[] {
return [...observed];
}

function journalEvidenceFact(
value: unknown,
phase: string,
completedPhases: readonly string[],
journalStatus: string,
failedPhase: string | null,
): JournalEvidenceFact {
const recorded = jsonObject(value);
const completed = completedPhases.includes(phase);
if (recorded !== null && (completed || failedPhase === phase)) {
return { availability: "recorded", value: recorded };
}
if (completed || failedPhase === phase) {
return { availability: "missing", value: null };
}
const phaseIndex = transactionPhases.indexOf(phase);
const failedIndex = failedPhase === null ? -1 : transactionPhases.indexOf(failedPhase);
if (
journalStatus === "stopped" ||
(journalStatus === "failed" && failedIndex >= 0 && failedIndex < phaseIndex)
) {
return { availability: "not_applicable", value: null };
}
return { availability: "unknown", value: null };
}

function receiptFact(
value: unknown,
journalStatus: string,
): JournalEvidenceFact {
const recorded = jsonObject(value);
if (recorded !== null) return { availability: "recorded", value: recorded };
if (["committed", "stopped", "failed", "scheduler_action_required"].includes(journalStatus)) {
return { availability: "missing", value: null };
}
return { availability: "unknown", value: null };
}

function projectEvidenceChain(
journal: JsonObject,
turnKey: string,
identity: BoundSettlementIdentity,
completedPhases: string[],
journalStatus: string,
): TurnJournalEvidenceChain {
const receipt = jsonObject(journal.receipt);
const failedPhase = typeof receipt?.failed_phase === "string"
? receipt.failed_phase
: null;
return {
settlement_identity: settlementIdentityPayload(identity),
turn_key: turnKey,
status: journalStatus,
result_kind: typeof journal.result_kind === "string" ? journal.result_kind : null,
completed_phases: [...completedPhases],
failed_phase: failedPhase,
phases: transactionPhases.map(phase => ({

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] 终态收尾失败缺少对应的阶段条目。 用受控 provider 驱动真实 run_loopx_turn_once 写出失败 journal。持久回执和新读口顶层的 failed_phase 都是 terminal_closeout,settlement_result 也记录同一步失败;phases 却没有这个阶段,所有 failed 都为 false。原轮重试只重做收尾,写回和扣额各一次。 从现有 settlement step 和 journal 解释层投影适用的 terminal_closeout,使 phases 与 failed_phase 一致。也可显式分开固定阶段和条件结算步骤,并让调用者从同一个结构找到失败节点。保留原顺序、身份和失败回执。

phase,
completed: completedPhases.includes(phase),
failed: failedPhase === phase,
})),
host_result: journalEvidenceFact(
journal.host_result, "typed_result", completedPhases, journalStatus, failedPhase,
),
task_validation: journalEvidenceFact(
journal.task_validation, "validation", completedPhases, journalStatus, failedPhase,
),
writeback: journalEvidenceFact(
journal.writeback, "durable_writeback", completedPhases, journalStatus, failedPhase,
),
settlement_result: journalEvidenceFact(
journal.settlement_result, "durable_writeback", completedPhases, journalStatus, failedPhase,
),
receipt: receiptFact(journal.receipt, journalStatus),
};
}

// A lost Host acknowledgement may retain the wake address before the caller
// has seen the selected Todo or replan. Its only permitted result is a locator
// for the original journal. Settlement and capability reads remain fully bound.
Expand Down Expand Up @@ -140,6 +254,13 @@ function evidenceForJournal(
? observedCapabilities(turnPlanWorkSource(plan ?? {}, sourceNumberTokens(journal,
parsedSourceNumberTokens(journal, numbers)).filter(({path}) => path[0] === "plan" && path[1] === "work_contract")
.map(({path, token}) => [path.slice(2), token])).work) : null,
evidence_chain: projectEvidenceChain(
journal,
turnKey,
actual,
inspection.completed_phases,
inspection.journal_status,
),
};
}

Expand Down Expand Up @@ -236,3 +357,24 @@ export async function readTurnJournalCapabilities(params: JsonObject): Promise<{
);
return { observed_capabilities: evidence?.observed_capabilities ?? null };
}

/** Exact, read-only facts for evaluators; no field implies execution, progress, or causality. */
export async function readTurnJournalEvidenceChain(
params: JsonObject,
): Promise<TurnJournalEvidenceChainReadback> {
const identity = decodeIdentity(params.settlement_identity);
const goalRef = Object.hasOwn(params, "goal_ref")
? decodeGoalRef(params.goal_ref)
: null;
if (goalRef !== null && goalRef.goalId.value !== identity.goal_id) {
throw new EffectRuntimeRequestError(
"Turn journal query GoalRef conflicts with its settlement identity",
);
}
const evidence = await queryTurnJournal(params.runtime_root, identity, goalRef);
return {
schema_version: TURN_JOURNAL_EVIDENCE_CHAIN_SCHEMA_VERSION,
availability: evidence === null ? "missing" : "recorded",
evidence_chain: evidence?.evidence_chain ?? null,
};
}
65 changes: 65 additions & 0 deletions tests/control_plane/test_turn_journal_observed_capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from loopx.control_plane.turn_driver import journal_store
from loopx.control_plane.turn_driver import turn_journal_runtime
from loopx.control_plane.turn_driver.journal_store import (
turn_journal_evidence_chain,
turn_journal_observed_capabilities,
write_turn_journal_checkpoint,
)
Expand Down Expand Up @@ -178,6 +179,70 @@ def _observed(
return turn_journal_observed_capabilities(runtime, **kwargs)


def test_typescript_evidence_chain_is_available_through_python_readback(
tmp_path: Path,
) -> None:
_commit_journal_via_typescript_writer(tmp_path, _journal())

readback = turn_journal_evidence_chain(
tmp_path,
settlement_identity=_completion_identity(),
)
assert readback["availability"] == "recorded"
chain = readback["evidence_chain"]
assert chain["settlement_identity"] == _completion_identity()
assert chain["turn_key"] == TURN_KEY
assert chain["completed_phases"] == TRANSACTION_PHASES
assert all(phase["completed"] for phase in chain["phases"])


def test_evidence_chain_wrapper_preserves_exact_identity_and_missingness(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
requests: list[tuple[str, dict[str, Any]]] = []
expected = {
"schema_version": "loopx_turn_journal_evidence_chain_v0",
"availability": "missing",
"evidence_chain": None,
}

def readback(method: str, params: dict[str, Any]) -> dict[str, Any]:
requests.append((method, params))
return expected

monkeypatch.setattr(journal_store, "effect_runtime_result", readback)
assert turn_journal_evidence_chain(
tmp_path,
settlement_identity=_completion_identity(),
goal_ref=GOAL_REF_A,
) == expected
assert requests == [("turn_journal.evidence_chain", {
"runtime_root": str(tmp_path.resolve()),
"settlement_identity": _completion_identity(),
"goal_ref": GOAL_REF_A,
})]


@pytest.mark.parametrize("payload", [
{},
{"schema_version": "unknown", "availability": "missing", "evidence_chain": None},
{
"schema_version": "loopx_turn_journal_evidence_chain_v0",
"availability": "recorded",
"evidence_chain": None,
},
])
def test_evidence_chain_wrapper_rejects_transport_shape_drift(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, payload: dict[str, Any],
) -> None:
monkeypatch.setattr(journal_store, "effect_runtime_result", lambda *_args, **_kwargs: payload)
with pytest.raises(RuntimeError, match="evidence-chain shape mismatch"):
turn_journal_evidence_chain(
tmp_path,
settlement_identity=_completion_identity(),
)


def test_typescript_committed_journal_lends_boundary_capabilities(
tmp_path: Path,
) -> None:
Expand Down
7 changes: 7 additions & 0 deletions tests/control_plane_ts/effect_runtime_handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ test("runtime boundary rejects malformed journal inspection request", async () =
);
});

test("runtime exposes settlement-addressed Turn evidence-chain readback", async () => {
await assert.rejects(
dispatchEffectRuntimeMethod(handlers, "turn_journal.evidence_chain", {}),
/settlement_identity must be an object/,
);
});

test("runtime exposes the native task-lease acquire transaction", async () => {
await assert.rejects(
dispatchEffectRuntimeMethod(handlers, "task_lease.acquire.native", {
Expand Down
Loading
Loading