diff --git a/docs/reference/protocols/goal-vision-replan-contract-v0.md b/docs/reference/protocols/goal-vision-replan-contract-v0.md index cd48ae231f..5b77a43c5e 100644 --- a/docs/reference/protocols/goal-vision-replan-contract-v0.md +++ b/docs/reference/protocols/goal-vision-replan-contract-v0.md @@ -340,6 +340,35 @@ its evidence references; private transport facts are not returned. The derived `replan-evidence-*` history reference. Changed paths cannot resolve an old decision reference; existing history reference identities are unchanged. +When a Todo record carries a settlement identity, its effect must match the +recorded Goal, Agent, Todo and Turn before it can count as work or support a +claim about a later result. The same check qualifies a Todo-bound decision +before it can consume earlier work. The settlement identity supplies the Turn +for older rows with no outer Turn field. A supplied outer Turn must agree. +When the outer Goal is omitted, use the Goal of the scoped history index. +Apply the settlement owner's v0/v1 validation to a declared Todo binding. +A v1 Todo decision keeps its Todo binding when projected. When a progress +observation is attributed to a planned Todo through its `work_item_id`, +verify any settlement identity against that Todo even if the outer `todo_id` +is missing. A Todo claim paired with a different settlement binding is a +conflict. Observations for another obligation can still describe that +obligation's progress. +Conflicting records, malformed identities, and identities with a missing or +unsupported schema version remain readable in history via existing references. +Records without a settlement identity retain their historical fallback, +including typed observations whose append position is known from the index. + +Todo 记录带有结算身份时,effect 必须与记录中的 Goal、Agent、Todo 和 Turn 一致, +才能计为工作或支持后续结果的判断。绑定 Todo 的复盘决定也须通过同一身份核对,才可 +将前一份成果标为已接续。旧记录没有外层 Turn 时,从结算身份取得 Turn。已有外层 +Turn 时两处必须一致。省略外层 Goal 时,沿用历史索引所属的 Goal。Todo 绑定遵循 +结算方现有的 v0/v1 校验,v1 Todo 决定在投影中保留 Todo 绑定。进展通过 +`work_item_id` 归给计划中的 Todo 时,即使省略外层 `todo_id`,也要用实际归属的 Todo 核对 +已有结算身份。Todo 声明与其他结算绑定并存时视为冲突。其他义务的观测仍可描述该义务的 +进展。结算身份结构错误、 +schema 缺失或不受支持,以及身份冲突的记录和既有引用均可通过历史查询。没有结算 +身份的记录保留原有兼容行为,包括可从索引确定追加顺序的 typed 进展。 + Details are bounded to six distinct progress fingerprints with the full recorded count, omitted count, source completeness and missing-order count. These are recorded observations, not settled-effective-Turn counts or independent trials. diff --git a/loopx/control_plane/work_items/replan_context.ts b/loopx/control_plane/work_items/replan_context.ts index 7e63597d82..1ed7d528c2 100644 --- a/loopx/control_plane/work_items/replan_context.ts +++ b/loopx/control_plane/work_items/replan_context.ts @@ -1,6 +1,6 @@ /** Bounded evidence for the existing replan boundary; no settlement authority. */ import {createHash} from "node:crypto"; -import {settlementIdentityPayload, SETTLEMENT_IDENTITY_SCHEMA_VERSION, +import {settlementIdentityFromPlan, settlementIdentityPayload, SETTLEMENT_IDENTITY_SCHEMA_VERSION, SCOPED_SETTLEMENT_IDENTITY_SCHEMA_VERSION, type JsonObject} from "../effect_program.ts"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import {BARE_SHA256_PATTERN} from "../content_digest.ts"; @@ -43,18 +43,47 @@ function sameSourceDigest(left: JsonObject, right: JsonObject, field: string): b value === objectOrNull(right._source_facts)?.[field + "_digest"]; } -/** Identity evidence is eligibility input only, never a new settlement authority. */ -function accountingMatchKey(row: JsonObject): string | null { +function isRecordedTodoSettlement(identity: JsonObject): boolean { + return identity.schema_version === SETTLEMENT_IDENTITY_SCHEMA_VERSION || + (identity.schema_version === SCOPED_SETTLEMENT_IDENTITY_SCHEMA_VERSION && identity.binding_kind === "todo"); +} + +/** Keep the recorded fields used by existing history references. */ +function recordedTodoIdentity(row: JsonObject, todo: unknown = row.todo_id): string[] | null { const source = objectOrNull(row._source_facts); const identity = objectOrNull(source?.settlement_identity); - if (!source || identity?.schema_version !== "quota_settlement_identity_v0") return null; + if (!source || !identity || !isRecordedTodoSettlement(identity)) return null; const keys = ["goal_id", "agent_id", "todo_id", "turn_instance_id", "effect_id"]; if (keys.some(key => typeof identity[key] !== "string" || !identity[key])) return null; - if (keys.slice(0, 4).some(key => identity[key] !== source[key]) || - ["goal_id", "agent_id", "todo_id"].some(key => identity[key] !== row[key])) return null; - if (typeof source.recommended_action_digest !== "string" || - !BARE_SHA256_PATTERN.test(source.recommended_action_digest) || !row.recommended_action) return null; - return JSON.stringify([...keys.map(key => identity[key]), source.recommended_action_digest]); + const outerTodo = row.todo_id ?? null; + if (["goal_id", "agent_id"].some(key => identity[key] !== source[key] || identity[key] !== row[key]) || + (source.todo_id ?? null) !== outerTodo || (outerTodo !== null && outerTodo !== todo) || identity.todo_id !== todo || + (source.turn_instance_id != null && identity.turn_instance_id !== source.turn_instance_id)) return null; + return keys.map(key => String(identity[key])); +} + +function hasConflictingTodoSettlement(row: JsonObject, attributedTodo: string | null = null): boolean { + const source = objectOrNull(row._source_facts); + const declared = source?.settlement_identity; + if (declared == null) return false; + const identity = objectOrNull(declared); + if (identity?.schema_version !== SETTLEMENT_IDENTITY_SCHEMA_VERSION && + identity?.schema_version !== SCOPED_SETTLEMENT_IDENTITY_SCHEMA_VERSION) return true; + const todoBinding = isRecordedTodoSettlement(identity); + const todo = attributedTodo ?? row.todo_id ?? (todoBinding ? observationTodo(row) : null); + if (!todoBinding && !(todo || source?.todo_id || identity.todo_id)) return false; + if (!recordedTodoIdentity(row, todo)) return true; + const decoded = settlementIdentityFromPlan({settlement_plan: {identity}}); + return !!decoded.failure || decoded.value.binding_kind !== "todo" || + decoded.value.todo_id !== identity.todo_id || decoded.value.effect_id !== identity.effect_id; +} + +function accountingMatchKey(row: JsonObject): string | null { + const identity = recordedTodoIdentity(row); + const actionDigest = objectOrNull(row._source_facts)?.recommended_action_digest; + return identity && typeof actionDigest === "string" && + BARE_SHA256_PATTERN.test(actionDigest) && row.recommended_action + ? JSON.stringify([...identity, actionDigest]) : null; } function repeatedAccounting(rows: JsonObject[]): Map { @@ -88,6 +117,24 @@ function readableEvidenceRow(row: JsonObject): JsonObject { return readableRow; } +function historicalEvidenceRef(row: JsonObject): string { + return "replan-evidence-" + digest(readableEvidenceRow(row)); +} + +function isAccountingRow(row: JsonObject): boolean { + return row.classification === "quota_slot_spent" || Boolean(objectOrNull(row._source_facts)?.quota_spend_commit); +} + +/** Preserve historical references even when a record fails work qualification. */ +function workEvidenceRef(row: JsonObject): string { + const source = objectOrNull(row._source_facts); + if (row.progress_observation !== null || isAccountingRow(row)) return historicalEvidenceRef(row); + const identity = recordedTodoIdentity(row); + if (!identity) return historicalEvidenceRef(row); + const goalRef = objectOrNull(source?.goal_ref); + return "replan-evidence-" + digest([readableEvidenceRow(row), identity, goalRef?.goal_instance_id ?? null]); +} + function evidenceFactsKey(row: JsonObject): string { const {generated_at: _time, evidence_ref: _ref, ...facts} = readableEvidenceRow(row); return digest(facts); @@ -112,17 +159,16 @@ export function projectCoreGoal(value: unknown): JsonObject { })}; } -/** Qualify recorded bindings using the settlement owner, without settling work. - * Keep historical Todo evidence eligible under its existing read contract. - */ -function decisionBindingMatches(row: JsonObject, source: JsonObject, delta: JsonObject | null): boolean { +/** Recognize the historical decision shape used by existing references. */ +function recordedDecisionBindingMatches(row: JsonObject, source: JsonObject, delta: JsonObject | null): boolean { const identity = objectOrNull(source.settlement_identity); - if (!identity || identity.turn_instance_id !== source.turn_instance_id || - typeof identity.turn_instance_id !== "string" || !ID.test(identity.turn_instance_id)) return false; - if (identity.schema_version === SETTLEMENT_IDENTITY_SCHEMA_VERSION) { - return ["goal_id", "agent_id", "todo_id"].every(key => identity[key] === row[key]); + if (!identity || typeof identity.turn_instance_id !== "string" || !ID.test(identity.turn_instance_id)) return false; + if (isRecordedTodoSettlement(identity)) { + return (source.turn_instance_id == null || identity.turn_instance_id === source.turn_instance_id) && + ["goal_id", "agent_id", "todo_id"].every(key => identity[key] === row[key]); } if (identity.schema_version !== SCOPED_SETTLEMENT_IDENTITY_SCHEMA_VERSION || + identity.turn_instance_id !== source.turn_instance_id || typeof row.goal_id !== "string" || typeof row.agent_id !== "string" || [row.todo_id, source.todo_id, identity.todo_id].some(value => value != null && value !== "") || ["goal_id", "agent_id"].some(key => source[key] !== row[key]) || @@ -133,12 +179,12 @@ function decisionBindingMatches(row: JsonObject, source: JsonObject, delta: Json return Object.entries(expected).every(([key, value]) => identity[key] === value); } -function acceptedDecisionSource(row: JsonObject): boolean { +function recordedDecisionSource(row: JsonObject): boolean { const source = objectOrNull(row._source_facts); const vision = objectOrNull(source?.agent_vision); const ack = objectOrNull(source?.autonomous_replan_ack); const delta = objectOrNull(ack?.semantic_delta); - return !!source && decisionBindingMatches(row, source, delta) && + return !!source && recordedDecisionBindingMatches(row, source, delta) && !objectOrNull(source.quota_spend_commit) && vision?.schema_version === "goal_vision_replan_contract_v0" && vision.agent_id === row.agent_id && (vision.goal_id == null || vision.goal_id === row.goal_id) && @@ -147,8 +193,13 @@ function acceptedDecisionSource(row: JsonObject): boolean { Array.isArray(delta.satisfying_outcomes) && delta.satisfying_outcomes.includes("fresh_vision_path_outcome"); } +function acceptedDecisionSource(row: JsonObject): boolean { + // History can resolve a recorded decision whose effect is ineligible for a new review. + return recordedDecisionSource(row) && !hasConflictingTodoSettlement(row); +} + function recordedDecision(row: JsonObject): JsonObject | null { - if (!acceptedDecisionSource(row)) return null; + if (!recordedDecisionSource(row)) return null; const source = objectOrNull(row._source_facts)!; let path: JsonObject | null; try { @@ -162,9 +213,10 @@ function recordedDecision(row: JsonObject): JsonObject | null { let stride: JsonObject | null; try { stride = normalizeRecordedStrideDecision(objectOrNull(source.agent_vision)?.stride_decision); } catch { return null; } - const autonomous = objectOrNull(source.settlement_identity)?.schema_version === SCOPED_SETTLEMENT_IDENTITY_SCHEMA_VERSION; + const identity = objectOrNull(source.settlement_identity)!; + const autonomous = identity.binding_kind === "autonomous_replan"; const decision = {history_evidence_ref: "replan-evidence-" + digest(readableEvidenceRow(row)), - generated_at: row.generated_at, todo_id: autonomous ? null : row.todo_id, turn_instance_id: source.turn_instance_id, + generated_at: row.generated_at, todo_id: autonomous ? null : row.todo_id, turn_instance_id: identity.turn_instance_id, ...(autonomous ? {replan_obligation_id: source.replan_obligation_id} : {}), goal_ref: ref ? {goal_id: ref.goal_id, goal_instance_id: ref.goal_instance_id} : null, path_delta: path, ...(stride ? {stride_decision: stride} : {})}; @@ -197,9 +249,14 @@ function plannedTodoIds(source: JsonObject): string[] { return [...new Set(declared.filter((id): id is string => typeof id === "string" && ID.test(id)))]; } -function observationTodo(row: JsonObject): unknown { - const work = objectOrNull(row.progress_observation)?.work_item_id; - return work == null ? row.todo_id : row.todo_id == null || row.todo_id === work ? work : null; +function observationTodo(row: JsonObject): string | null { + const todo = objectOrNull(row.progress_observation)?.work_item_id ?? row.todo_id; + return typeof todo === "string" && (row.todo_id == null || row.todo_id === todo) ? todo : null; +} + +function plannedObservationTodo(row: JsonObject, targets: ReadonlySet): string | null { + const todo = observationTodo(row); + return todo !== null && targets.has(todo) ? todo : null; } /** Reserve one source-ordered observation per displayed planned Todo before @@ -212,7 +269,7 @@ function boundedWorkEvidence(rows: JsonObject[], todoIds: string[]): JsonObject[ const row = rows.find(row => observationTodo(row) === id); if (row) first.add(row); } - const relevant = rows.filter(row => displayed.has(String(observationTodo(row)))); + const relevant = rows.filter(row => plannedObservationTodo(row, displayed) !== null); for (const row of [...relevant, ...rows]) { if (first.size >= 6) break; first.add(row); @@ -230,9 +287,10 @@ function workResultUse(scoped: JsonObject[]): JsonObject | null { const proposed = new Map(); const followed: JsonObject[] = []; const seen = new Set(); + const legacyResultRefs = new Map(); for (const row of [...scoped].reverse()) { + if (isAccountingRow(row)) continue; const source = objectOrNull(row._source_facts)!; - if (source.quota_spend_commit) continue; if (acceptedDecisionSource(row)) { const decision = recordedDecision(row); if (!decision) { origin.clear(); proposed.clear(); continue; } @@ -241,6 +299,7 @@ function workResultUse(scoped: JsonObject[]): JsonObject | null { const review = objectOrNull(objectOrNull(decision.stride_decision)?.previous_review); const refs = [...(path.evidence_refs as string[]), ...(Array.isArray(review?.evidence_refs) ? review.evidence_refs as string[] : [])] + .map(ref => pending.has(ref) ? ref : legacyResultRefs.get(ref) ?? ref) .filter(ref => pending.has(ref)); for (const todo of targets) { origin.set(todo, id); @@ -256,10 +315,15 @@ function workResultUse(scoped: JsonObject[]): JsonObject | null { // or create a new pending work result. Unknown legacy outcomes stay unknown. // Material gaps remain eligible: this relation certifies neither successful // execution nor scientific gain, and must preserve useful negative evidence. - if (!MATERIAL_DELIVERY_OUTCOMES.some(outcome => outcome === row.delivery_outcome)) continue; - const todo = String(observationTodo(row)); - if (!origin.has(todo)) continue; - const ref = "replan-evidence-" + digest(readableEvidenceRow(row)); + const todo = observationTodo(row); + if (todo === null || !origin.has(todo) || + !MATERIAL_DELIVERY_OUTCOMES.some(outcome => outcome === row.delivery_outcome) || + hasConflictingTodoSettlement(row, todo)) continue; + const ref = workEvidenceRef(row); + // Keep evidence aliases from historical decisions resolvable. When an old + // citation matches multiple formerly collapsed rows, use that alias once. + const legacyRef = historicalEvidenceRef(row); + if (!legacyResultRefs.has(legacyRef)) legacyResultRefs.set(legacyRef, ref); if (seen.has(ref)) continue; seen.add(ref); const adoption = proposed.get(todo); @@ -301,14 +365,15 @@ function reviewEvidence(rows: JsonObject[], request: JsonObject): JsonObject { const source = objectOrNull(previous!._source_facts)!; const targets = new Set(plannedTodoIds(source)); const citations = refs.map(ref => { - const matches = scoped.filter(row => "replan-evidence-" + digest(readableEvidenceRow(row)) === ref + const matches = scoped.filter(row => workEvidenceRef(row) === ref || historicalEvidenceRef(row) === ref || (objectOrNull(row.progress_observation)?.evidence_ids as unknown[] | undefined)?.includes(ref)); const subsequent = matches.filter(row => { const facts = objectOrNull(row._source_facts)!; - return Number(facts.history_position) > Number(source.history_position) && !facts.quota_spend_commit; + return Number(facts.history_position) > Number(source.history_position) && !isAccountingRow(row) + && !hasConflictingTodoSettlement(row, plannedObservationTodo(row, targets)); }); return {evidence_ref: ref, available: matches.length > 0, subsequent: subsequent.length > 0, - declared_work: subsequent.some(row => targets.has(String(observationTodo(row))))}; + declared_work: subsequent.some(row => plannedObservationTodo(row, targets) !== null)}; }); return {previous_decision_ref: decision.evidence_ref, has_declared_work: targets.size > 0, citations}; } @@ -318,7 +383,7 @@ function decisionFollowthrough(rows: JsonObject[], goalFacts: unknown, fromFullI const scoped = orderedDecisionRows(rows, goalFacts); const previous = scoped.find(acceptedDecisionSource); if (!previous) return null; - // Do not fall back to an older decision when the latest basis is corrupt. + // An accepted binding with unreadable decision content makes its basis unavailable. const decision = recordedDecision(previous); if (!decision) return null; const source = objectOrNull(previous._source_facts)!; @@ -329,10 +394,12 @@ function decisionFollowthrough(rows: JsonObject[], goalFacts: unknown, fromFullI const targets = new Set(todoIds); for (const row of scoped) { const facts = objectOrNull(row._source_facts)!; - if (Number(facts.history_position) <= Number(source.history_position) || facts.quota_spend_commit) continue; + const todo = plannedObservationTodo(row, targets); + if (Number(facts.history_position) <= Number(source.history_position) || isAccountingRow(row) || + hasConflictingTodoSettlement(row, todo)) continue; if (!row.progress_observation) { - if (targets.has(String(observationTodo(row)))) { - const ref = "replan-evidence-" + digest(readableEvidenceRow(row)); + if (todo !== null) { + const ref = workEvidenceRef(row); if (!ordinary.has(ref)) ordinary.set(ref, {evidence_ref: ref, generated_at: row.generated_at, todo_id: row.todo_id}); } @@ -574,25 +641,31 @@ export function projectReplanContext(value: unknown): JsonObject { } rows.sort((a, b) => Number(b.observed_at) - Number(a.observed_at) || JSON.stringify(readableEvidenceRow(a)).localeCompare(JSON.stringify(readableEvidenceRow(b)))); + // Unpaired accounting can still explain a failure. It never contributes + // to the Todo result ledger merely by being visible here. + const evidenceRows = request.operation === "resolve" ? rows : rows.filter(row => + isAccountingRow(row) || !hasConflictingTodoSettlement(row)); const unique = new Map(); - for (const row of rows) { + for (const row of evidenceRows) { const readableRow = readableEvidenceRow(row); - const ref = "replan-evidence-" + digest(readableRow); + const ref = workEvidenceRef(row); if (!unique.has(ref)) unique.set(ref, {...readableRow, evidence_ref: ref}); } const evidence = [...unique.values()]; if (request.operation === "resolve") { if (!agent) throw new EffectRuntimeRequestError("evidence resolution requires agent_id"); const ref = identifier(request.evidence_ref, "evidence_ref"); - const match = unique.get(ref) ?? rows.map(recordedDecision).find(decision => decision?.evidence_ref === ref); + const legacy = rows.find(row => historicalEvidenceRef(row) === ref); + const match = unique.get(ref) ?? (legacy && {...readableEvidenceRow(legacy), evidence_ref: ref}) + ?? rows.map(recordedDecision).find(decision => decision?.evidence_ref === ref); if (!match) throw new EffectRuntimeRequestError( "evidence reference is unavailable in this Goal and Agent history window; refresh replan_context", "replan_evidence_unavailable"); return {ok: true, goal_id: goal, agent_id: agent, evidence: match}; } - const repeated = repeatedAccounting(rows); + const repeated = repeatedAccounting(evidenceRows); const repeatedByGroup = new Map(); - for (const row of rows) { + for (const row of evidenceRows) { const key = evidenceFactsKey(row); const work = repeated.get(row); const proof = work ? {workKey: evidenceFactsKey(work), diff --git a/loopx/control_plane/work_items/replan_context_codec.py b/loopx/control_plane/work_items/replan_context_codec.py index 270409e4df..89052855e9 100644 --- a/loopx/control_plane/work_items/replan_context_codec.py +++ b/loopx/control_plane/work_items/replan_context_codec.py @@ -53,6 +53,7 @@ def replan_evidence_rows(runs: Iterable[Mapping[str, Any]], *, goal_id: str, age newest_position = len(runs) - 1 else: newest_position = None + ordered_history = include_decisions and history_newest_first is not None rows = [] for position, run in enumerate(runs): if not isinstance(run, Mapping): @@ -84,20 +85,25 @@ def replan_evidence_rows(runs: Iterable[Mapping[str, Any]], *, goal_id: str, age text = _source_text(run.get(key)) if text: row[key] = text + history_position = newest_position - position if newest_position is not None else position if "settlement_identity" in run or "quota_spend_commit" in run or (include_decisions and "agent_vision" in run): # Transport facts, not a Python eligibility decision. Complete-text # digests prevent a shared display prefix from erasing distinct tails. # This private wire metadata is excluded from public reference identity. - source: dict[str, Any] = {key: run.get(key) for key in ( - "goal_id", "agent_id", "todo_id", "turn_instance_id")} + source: dict[str, Any] = { + "goal_id": run_goal, + "agent_id": run_agent, + "todo_id": run.get("todo_id"), + "turn_instance_id": run.get("turn_instance_id"), + } # Facts only: the typed replan owner qualifies the prior decision # and orders subsequent observations. Do not classify research # progress or infer adoption from prose in this transport codec. if include_decisions: from ..goals.goal_vision_read_model import parse_vision_todo_delta_entries - if history_newest_first is not None: - source["history_position"] = newest_position - position if newest_position is not None else position + if ordered_history: + source["history_position"] = history_position source["goal_ref"] = run.get("goal_ref") source["agent_vision"] = run.get("agent_vision") vision = run.get("agent_vision") @@ -110,14 +116,23 @@ def replan_evidence_rows(runs: Iterable[Mapping[str, Any]], *, goal_id: str, age source["replan_obligation_id"] = run.get("replan_obligation_id") for key, fields in (("settlement_identity", ( "schema_version", "goal_id", "agent_id", "todo_id", "turn_instance_id", "effect_id", - *(("binding_kind", "binding_id", "replan_obligation_id") if include_decisions else ()))), + "binding_kind", "binding_id", "replan_obligation_id", "request_subject")), ("quota_spend_commit", ("schema_version", "effect_id"))): value = run.get(key) - source[key] = {field: value.get(field) for field in fields} if isinstance(value, Mapping) else None + if isinstance(value, Mapping): + source[key] = {field: value[field] for field in fields if field in value} + elif key == "settlement_identity" and value is not None: + # Preserve the presence of a malformed identity without forwarding its contents. + source[key] = {} + else: + source[key] = None for key in ("recommended_action", "health_check", "delivery_outcome"): value = run.get(key) source[key + "_digest"] = hashlib.sha256(value.encode()).hexdigest() if isinstance(value, str) else None row["_source_facts"] = source + elif ordered_history and progress is not None: + # An older typed observation can still have a known index position. + row["_source_facts"] = {"history_position": history_position, "goal_ref": run.get("goal_ref")} rows.append(row) return rows diff --git a/tests/control_plane/test_replan_context_evidence.py b/tests/control_plane/test_replan_context_evidence.py index 29abd418cd..970940fceb 100644 --- a/tests/control_plane/test_replan_context_evidence.py +++ b/tests/control_plane/test_replan_context_evidence.py @@ -305,17 +305,18 @@ def test_dense_context_uses_shared_private_snapshot_transport(monkeypatch): assert project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=[_run()]) == expected -def _settled_pair(): - identity = {"schema_version": "quota_settlement_identity_v0", "goal_id": "evidence-goal", - "agent_id": "agent-a", "todo_id": "todo-a", "turn_instance_id": "turn-a", "effect_id": "settlement-a"} - work = _run(**{key: identity[key] for key in ("todo_id", "turn_instance_id")}, +def _settled_pair(*, goal_id="evidence-goal", agent_id="agent-a", todo_id="todo-a", turn_instance_id="turn-a"): + effect_id = f"{goal_id}:{agent_id}:{todo_id}:{turn_instance_id}" + identity = {"schema_version": "quota_settlement_identity_v0", "goal_id": goal_id, + "agent_id": agent_id, "todo_id": todo_id, "turn_instance_id": turn_instance_id, "effect_id": effect_id} + work = _run(goal_id=goal_id, agent_id=agent_id, todo_id=todo_id, turn_instance_id=turn_instance_id, settlement_identity=identity, recommended_action="Retain the negative finding and try the next route.", progress_observation={"schema_version": "typed_progress_observation_v0", - "result_class": "unchanged", "surface_id": "surface-a", "work_item_id": "todo-a"}) + "result_class": "unchanged", "surface_id": "surface-a", "work_item_id": todo_id}) accounting = {key: value for key, value in work.items() if key != "progress_observation"} accounting.update(classification="quota_slot_spent", generated_at="2026-08-18T01:00:01Z", quota_spend_commit={"schema_version": "quota_spend_commit_receipt_v0", - "effect_id": "settlement-a#quota_spend"}) + "effect_id": f"{effect_id}#quota_spend"}) return work, accounting @@ -356,7 +357,7 @@ def test_matched_accounting_keeps_new_health_and_all_published_references(tmp_pa @pytest.mark.parametrize("change", [ {"settlement_identity": None}, {"quota_spend_commit": None}, {"turn_instance_id": "turn-b"}, - {"quota_spend_commit": {"schema_version": "future", "effect_id": "settlement-a#quota_spend"}}, + {"quota_spend_commit": {"schema_version": "future", "effect_id": "evidence-goal:agent-a:todo-a:turn-a#quota_spend"}}, {"quota_spend_commit": {"schema_version": "quota_spend_commit_receipt_v0", "effect_id": "other#quota_spend"}}, {"classification": "future_accounting"}, {"recommended_action": "Keep an additional obligation."}, {"delivery_outcome": "outcome_failure"}, @@ -391,10 +392,7 @@ def test_real_quota_cli_preserves_the_replan_obligation_while_reducing_accountin from test_replan_successor_guard_reentry import _fixture, _guard, GOAL, AGENT call, runtime, index = _fixture(tmp_path, monkeypatch, provider) - work, accounting = _settled_pair() - for row in (work, accounting): - row.update(goal_id=GOAL, agent_id=AGENT) - row["settlement_identity"] = {**row["settlement_identity"], "goal_id": GOAL, "agent_id": AGENT} + work, accounting = _settled_pair(goal_id=GOAL, agent_id=AGENT) # Keep the fixture's existing required-vision evidence. This changes only # metadata in the disposable read model, never an active authority store. prior = index.read_text() diff --git a/tests/control_plane/test_replan_context_order.py b/tests/control_plane/test_replan_context_order.py index 1c0ced4f04..22a7873b9f 100644 --- a/tests/control_plane/test_replan_context_order.py +++ b/tests/control_plane/test_replan_context_order.py @@ -2,21 +2,22 @@ from __future__ import annotations import json +import subprocess +import sys import pytest from loopx.control_plane.work_items.progress_observation import build_replan_context from loopx.control_plane.work_items.replan_context_codec import project_replan_context +from loopx.history import append_run_index_record, reserve_unique_run_paths from test_replan_context_evidence import _settled_pair -def _rows(): - work, _ = _settled_pair() - +def _rows(*, goal_id="evidence-goal", agent_id="agent-a"): def decision(turn, timestamp): - return {**work, "generated_at": timestamp, "turn_instance_id": turn, - "settlement_identity": {**work["settlement_identity"], "turn_instance_id": turn}, - "agent_vision": {"schema_version": "goal_vision_replan_contract_v0", "agent_id": "agent-a", + work, _ = _settled_pair(goal_id=goal_id, agent_id=agent_id, turn_instance_id=turn) + return {**work, "generated_at": timestamp, + "agent_vision": {"schema_version": "goal_vision_replan_contract_v0", "agent_id": agent_id, "path_delta": {"schema_version": "goal_path_delta_v0", "outcome": "replan", "prior_assumption": "The current route could explain the gap.", "observed_reality": "The gap remains unexplained.", "changed": ["Compare another route."], @@ -27,8 +28,8 @@ def decision(turn, timestamp): older = decision("turn-old", "2026-08-18T03:00:00Z") latest = decision("turn-latest", "2026-08-18T01:00:00Z") - later = {**work, "turn_instance_id": "turn-probe", "generated_at": "2026-08-18T00:00:00Z", - "settlement_identity": {**work["settlement_identity"], "turn_instance_id": "turn-probe"}, + work, _ = _settled_pair(goal_id=goal_id, agent_id=agent_id, turn_instance_id="turn-probe") + later = {**work, "generated_at": "2026-08-18T00:00:00Z", "progress_observation": {**work["progress_observation"], "surface_id": "surface-probe"}} return [older, latest, later] @@ -63,10 +64,8 @@ def test_declared_results_survive_busy_work_through_the_source_codec(typed): decision["agent_vision"]["todo_delta"] = ["retain:todo-busy", "retain:todo-comparison"] def result(todo, index): - item = {**work, "todo_id": todo, "turn_instance_id": f"turn-work-{index}", - "settlement_identity": {**work["settlement_identity"], "todo_id": todo, - "turn_instance_id": f"turn-work-{index}"}, - "health_check": f"Independent measured result {index}."} + settled, _ = _settled_pair(todo_id=todo, turn_instance_id=f"turn-work-{index}") + item = {**settled, "generated_at": work["generated_at"], "health_check": f"Independent measured result {index}."} if typed: item["progress_observation"] = {**work["progress_observation"], "work_item_id": todo, "surface_id": f"surface-{index}"} @@ -101,6 +100,261 @@ def test_real_append_index_ignores_compact_display_order_and_clock_skew(tmp_path assert index.read_bytes() == before +def test_same_second_work_references_resolve_through_the_history_cli(tmp_path): + _, decision, work = _rows() + decision["agent_vision"]["todo_delta"] = ["retain:todo-a"] + work["todo_id"] = "todo-a" + work["delivery_outcome"] = "outcome_progress" + work.pop("progress_observation") + rows = [decision] + for turn in ("turn-negative-a", "turn-negative-b"): + recorded = {**work, "turn_instance_id": turn, "settlement_identity": { + **work["settlement_identity"], "todo_id": "todo-a", "turn_instance_id": turn, + "effect_id": f"evidence-goal:agent-a:todo-a:{turn}", + }} + rows.append(recorded) + first = rows[1] + identity = first["settlement_identity"] + rows.extend([dict(first), {**first, "settlement_identity": { + **identity, "effect_id": "evidence-goal:agent-a:todo-a:turn-unrelated", + }}, {**first, "settlement_identity": {key: value for key, value in identity.items() if key != "effect_id"}}]) + registry = tmp_path / "registry.json" + registry.write_text(json.dumps({"goals": [{"id": "evidence-goal", "repo": str(tmp_path)}]})) + index = tmp_path / "goals/evidence-goal/runs/index.jsonl" + index.parent.mkdir(parents=True) + for position, row in enumerate(rows): + artifact = index.parent / f"run-{position}.json" + row["json_path"] = str(artifact) + artifact.write_text(json.dumps(row)) + index.write_text("".join(json.dumps(row) + "\n" for row in rows)) + before = index.read_bytes() + context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=(), + source_status={"registry": str(registry), "runtime_root": str(tmp_path), + "run_history": {"runs": []}}) + followthrough = context["decision_followthrough"] + evidence = followthrough["ordinary_work"] + refs = {row["evidence_ref"] for row in evidence["evidence"]} + assert evidence["recorded_count"] == len(refs) == 2 + assert followthrough["work_result_use"]["unresolved_count"] == 2 + legacy = {key: value for key, value in work.items() if key != "settlement_identity"} + old_context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=[legacy]) + refs.add(old_context["evidence"][0]["evidence_ref"]) + for ref in refs: + cli = subprocess.run([sys.executable, "-m", "loopx.entrypoint", "--format", "json", + "--registry", str(registry), "--runtime-root", str(tmp_path), "history", + "--goal-id", "evidence-goal", "--agent-id", "agent-a", "--evidence-ref", ref], + text=True, capture_output=True, timeout=30) + assert cli.returncode == 0, cli.stdout + cli.stderr + result = json.loads(cli.stdout) + assert result["evidence"]["evidence_ref"] == ref + assert result["evidence"]["health_check"] == work["health_check"] + assert index.read_bytes() == before + + +def _append_runs(index, *rows): + for row in rows: + artifact, report = reserve_unique_run_paths(index.parent, row["generated_at"]) + record = {**row, "json_path": str(artifact), "markdown_path": str(report)} + artifact.write_text(json.dumps(record), encoding="utf-8") + append_run_index_record(index, record) + + +def _vision_review_request(index): + source = json.loads(index.read_text(encoding="utf-8").splitlines()[-1]) + # Request a fresh vision review after the observed decisions and work. + # This triggers the ordinary quota projection without claiming work itself. + return {key: source[key] for key in ("agent_id", "agent_vision")} | { + "generated_at": "2026-08-18T09:00:00Z", "classification": "vision_review_requested", + } + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("outer_goal", [True, False], ids=["explicit-goal", "index-goal"]) +def test_nested_only_turn_work_survives_quota_and_history_readback(tmp_path, monkeypatch, provider, outer_goal): + from test_replan_successor_guard_reentry import _fixture, _guard, AGENT, GOAL + + call, _, index = _fixture(tmp_path, monkeypatch, provider) + trigger = _vision_review_request(index) + _, decision, work = _rows(goal_id=GOAL, agent_id=AGENT) + decision["agent_vision"]["todo_delta"] = ["retain:todo-a"] + work["delivery_outcome"] = "outcome_progress" + work.pop("progress_observation") + work.pop("turn_instance_id") + if not outer_goal: + work.pop("goal_id") + conflicted = {**work, "turn_instance_id": "turn-unrelated"} + foreign = {**work, "goal_id": "other-goal", "health_check": "Work from a different Goal."} + _append_runs(index, decision, work, conflicted, foreign, trigger) + before = index.read_bytes() + + obligation = _guard(call, "turn-nested-history")["autonomous_replan_obligation"] + follow = obligation["replan_context"]["decision_followthrough"] + ordinary = follow["ordinary_work"] + assert ordinary["recorded_count"] == 1 + assert follow["work_result_use"]["unresolved_count"] == 1 + work_ref = ordinary["evidence"][0]["evidence_ref"] + assert follow["work_result_use"]["unresolved"][0]["evidence_ref"] == work_ref + # References from the original display-based format must also resolve. + historical = {key: value for key, value in work.items() if key != "settlement_identity"} + context = project_replan_context(goal_id=GOAL, agent_id=AGENT, runs=[historical]) + old_ref = context["evidence"][0]["evidence_ref"] + assert work_ref != old_ref + for ref in (work_ref, old_ref): + evidence = call("history", "--goal-id", GOAL, "--agent-id", AGENT, "--evidence-ref", ref)["evidence"] + assert evidence["evidence_ref"] == ref + assert evidence["health_check"] == work["health_check"] + assert index.read_bytes() == before + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("identity_case", [ + "decision-effect", "missing-schema", "unknown-schema", "malformed-identity", "non-todo-binding", "legacy-null", + "v1-todo", "v1-conflicting-binding-id", +]) +def test_settlement_identity_controls_work_attribution_in_quota(tmp_path, monkeypatch, provider, identity_case): + from loopx.control_plane.effect_program import SettlementIdentity + + from test_replan_successor_guard_reentry import _fixture, _guard, AGENT, GOAL + + call, _, index = _fixture(tmp_path, monkeypatch, provider) + trigger = _vision_review_request(index) + original, later_decision, work = _rows(goal_id=GOAL, agent_id=AGENT) + original["agent_vision"]["todo_delta"] = ["retain:todo-a"] + later_decision["agent_vision"]["todo_delta"] = ["retain:todo-b"] + work["delivery_outcome"] = "outcome_progress" + work.pop("progress_observation") + _append_runs(index, original, work, trigger) + first = _guard(call, "turn-result-baseline")["autonomous_replan_obligation"] + pending_ref = first["replan_context"]["decision_followthrough"]["work_result_use"]["unresolved"][0]["evidence_ref"] + later_decision["agent_vision"]["path_delta"]["evidence_refs"] = [pending_ref] + subsequent, _ = _settled_pair(goal_id=GOAL, agent_id=AGENT, todo_id="todo-b", turn_instance_id="turn-b") + subsequent.pop("progress_observation") + subsequent["delivery_outcome"] = "outcome_progress" + + control = project_replan_context(goal_id=GOAL, agent_id=AGENT, + runs=[original, work, later_decision, subsequent], history_newest_first=False) + control_follow = control["decision_followthrough"] + assert control_follow["work_result_use"]["recorded_followthrough_count"] == 1 + + if identity_case == "decision-effect": + # The effect is a private source fact and does not change the decision reference. + reference = control_follow["previous_decision"]["evidence_ref"] + later_decision["settlement_identity"] = {**later_decision["settlement_identity"], + "effect_id": f"other-goal:{AGENT}:todo-a:turn-latest"} + else: + # Resolve work with no usable Todo identity through the historical display-based reference. + legacy = {key: value for key, value in subsequent.items() if key != "settlement_identity"} + reference = project_replan_context(goal_id=GOAL, agent_id=AGENT, runs=[legacy])["evidence"][0]["evidence_ref"] + identity = {**subsequent["settlement_identity"], "effect_id": f"other-goal:{AGENT}:todo-b:turn-b"} + if identity_case == "missing-schema": + identity.pop("schema_version") + elif identity_case == "unknown-schema": + identity["schema_version"] = "unsupported" + elif identity_case == "malformed-identity": + identity = identity["effect_id"] + elif identity_case == "non-todo-binding": + identity = SettlementIdentity(GOAL, AGENT, None, "turn-b", replan_obligation_id="replan-other").as_dict() + elif identity_case in {"v1-todo", "v1-conflicting-binding-id"}: + identity = {**subsequent["settlement_identity"], "schema_version": "quota_settlement_identity_v1", + "binding_kind": "todo", "binding_id": "todo-b" if identity_case == "v1-todo" else "other-todo"} + else: + identity = None + subsequent["settlement_identity"] = identity + _append_runs(index, later_decision, subsequent, trigger) + before = index.read_bytes() + + obligation = _guard(call, "turn-conflicting-settlement")["autonomous_replan_obligation"] + follow = obligation["replan_context"]["decision_followthrough"] + assert follow["previous_decision"]["turn_instance_id"] == ( + "turn-old" if identity_case == "decision-effect" else "turn-latest" + ) + accepted = identity_case in {"legacy-null", "v1-todo"} + assert follow.get("ordinary_work", {}).get("recorded_count", 0) == ( + 1 if accepted or identity_case == "decision-effect" else 0 + ) + use = follow["work_result_use"] + assert use["recorded_followthrough_count"] == int(accepted) + if accepted: + link = use["recorded_followthrough"][0] + assert link["result_evidence_ref"] == pending_ref + followup_ref = link["work_evidence_ref"] + assert (followup_ref == reference) == (identity_case == "legacy-null") + assert [result["evidence_ref"] for result in use["unresolved"]] == [followup_ref] + credited = call("history", "--goal-id", GOAL, "--agent-id", AGENT, + "--evidence-ref", followup_ref)["evidence"] + assert credited["evidence_ref"] == followup_ref + else: + assert [result["evidence_ref"] for result in use["unresolved"]] == [pending_ref] + historical = call("history", "--goal-id", GOAL, "--agent-id", AGENT, + "--evidence-ref", reference)["evidence"] + assert historical["evidence_ref"] == reference + if identity_case == "decision-effect": + assert historical["turn_instance_id"] == "turn-latest" + else: + assert historical["todo_id"] == "todo-b" + assert historical["health_check"] == subsequent["health_check"] + assert index.read_bytes() == before + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("binding", [ + "todo-v1-decision", "typed-todo", "typed-legacy", "typed-autonomous", "other-obligation", "legacy-accounting", +]) +def test_projected_work_uses_the_planned_todos_own_settlement(tmp_path, monkeypatch, provider, binding): + from loopx.control_plane.effect_program import SettlementIdentity + + from test_replan_successor_guard_reentry import _fixture, _guard, AGENT, GOAL + + call, _, index = _fixture(tmp_path, monkeypatch, provider) + trigger = _vision_review_request(index) + original, decision, earlier = _rows(goal_id=GOAL, agent_id=AGENT) + original["agent_vision"]["todo_delta"] = ["retain:todo-a"] + decision["agent_vision"]["todo_delta"] = ["retain:todo-b"] + earlier["delivery_outcome"] = "outcome_progress" + earlier.pop("progress_observation") + _append_runs(index, original, earlier, trigger) + first = _guard(call, "turn-first-attribution")["autonomous_replan_obligation"] + pending = first["replan_context"]["decision_followthrough"]["work_result_use"]["unresolved"][0]["evidence_ref"] + decision["agent_vision"]["path_delta"]["evidence_refs"] = [pending] + later, _ = _settled_pair(goal_id=GOAL, agent_id=AGENT, todo_id="todo-b", turn_instance_id="turn-observed") + later["delivery_outcome"] = "outcome_progress" + if binding == "todo-v1-decision": + decision["settlement_identity"].update(schema_version="quota_settlement_identity_v1", + binding_kind="todo", binding_id=decision["todo_id"]) + else: + later.pop("todo_id") + if binding in {"typed-autonomous", "other-obligation"}: + later["settlement_identity"] = SettlementIdentity( + GOAL, AGENT, None, "turn-observed", replan_obligation_id="replan-other", + ).as_dict() + if binding == "other-obligation": + later["progress_observation"]["work_item_id"] = "replan-other" + elif binding in {"typed-legacy", "legacy-accounting"}: + later.pop("settlement_identity") + if binding == "legacy-accounting": + later["classification"] = "quota_slot_spent" + _append_runs(index, decision, later, trigger) + before = index.read_bytes() + + obligation = _guard(call, "turn-projected-attribution")["autonomous_replan_obligation"] + follow = obligation["replan_context"]["decision_followthrough"] + previous = follow["previous_decision"] + assert previous["turn_instance_id"] == "turn-latest" + assert previous["todo_id"] == decision["todo_id"] + assert "replan_obligation_id" not in previous + accepted = binding in {"todo-v1-decision", "typed-todo", "typed-legacy"} + use = follow["work_result_use"] + assert use["recorded_followthrough_count"] == int(accepted) + assert (use["unresolved"][0]["evidence_ref"] != pending) == accepted + assert follow["recorded_progress_count"] == int(binding not in {"typed-autonomous", "legacy-accounting"}) + planned, = follow["planned_work"] + assert len(planned["observation_refs"]) == int(accepted) + legacy = {key: value for key, value in later.items() if key != "settlement_identity"} + ref = project_replan_context(goal_id=GOAL, agent_id=AGENT, runs=[legacy])["evidence"][0]["evidence_ref"] + assert call("history", "--goal-id", GOAL, "--agent-id", AGENT, "--evidence-ref", ref)["evidence"]["evidence_ref"] == ref + assert index.read_bytes() == before + + @pytest.mark.parametrize("rows", [_rows(), list(reversed(_rows()))]) def test_unknown_order_does_not_fabricate_a_previous_decision_or_later_work(rows): context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, diff --git a/tests/control_plane_ts/replan_context.test.ts b/tests/control_plane_ts/replan_context.test.ts index e9372ad355..5584f95e6b 100644 --- a/tests/control_plane_ts/replan_context.test.ts +++ b/tests/control_plane_ts/replan_context.test.ts @@ -127,11 +127,12 @@ test("references resolve only the exact immutable row within the same Goal and A } }); -function pair(time = 1): [JsonObject, JsonObject] { - const identity = {schema_version: "quota_settlement_identity_v0", goal_id: "goal-a", agent_id: "agent-a", - todo_id: "todo-a", turn_instance_id: "turn-" + time, effect_id: "settlement-" + time}; +function pair(time = 1, todo = "todo-a"): [JsonObject, JsonObject] { + const identity = settlementIdentityPayload({goal_id: "goal-a", agent_id: "agent-a", + todo_id: todo, turn_instance_id: "turn-" + time}); const hash = (text: string) => createHash("sha256").update(text).digest("hex"); - const work = {...row(time), todo_id: "todo-a", classification: "bounded_probe", recommended_action: "Try the next route.", + const work = {...row(time), todo_id: todo, progress_observation: {...progress, work_item_id: todo}, + classification: "bounded_probe", recommended_action: "Try the next route.", _source_facts: {...identity, settlement_identity: identity, quota_spend_commit: null, recommended_action_digest: hash("Try the next route."), health_check_digest: hash(String(row(time).health_check))}}; const accounting = {...work, ...row(time + 0.1), progress_observation: null, classification: "quota_slot_spent", @@ -154,15 +155,48 @@ function reviewed(position = 0): JsonObject { satisfying_outcomes: ["fresh_vision_path_outcome"]}}}}; } -function subsequent(position: number): JsonObject { - const [work] = pair(position + 1); - return {...work, progress_observation: {...progress, result_class: "advanced", +function subsequent(position: number, todo = "todo-a"): JsonObject { + const [work] = pair(position + 1, todo); + return {...work, progress_observation: {...progress, work_item_id: todo, result_class: "advanced", fingerprint: "probe-" + position, hypothesis_id: "hypothesis-local"}, _source_facts: {...work._source_facts, history_position: position}}; } const strideRequest = {...request, stride_strategy: "evidence_conditioned_v1"}; +test("a scoped Todo decision has the same history reference as its v0 representation", () => { + const record = reviewed(); + const source = record._source_facts as JsonObject; + const original = projectReplanContext({...request, rows: [record]}).decision_followthrough.previous_decision; + const identity = {...source.settlement_identity as JsonObject, + schema_version: "quota_settlement_identity_v1", binding_kind: "todo", binding_id: record.todo_id}; + const scoped = {...record, _source_facts: {...source, settlement_identity: identity}}; + assert.deepEqual(projectReplanContext({...request, rows: [scoped]}).decision_followthrough.previous_decision, original); + const conflict = {...scoped, _source_facts: {...source, settlement_identity: {...identity, binding_id: "other-todo"}}}; + assert.equal(projectReplanContext({...request, rows: [conflict]}).decision_followthrough, undefined); +}); + +test("citation replay requires the settlement of the Todo actually attributed", () => { + const decision = reviewed(); + (decision._source_facts as JsonObject).planned_todo_ids = ["todo-a"]; + const {todo_id: _todo, _source_facts: recorded, ...work} = subsequent(2); + const source = recorded as JsonObject; + const settlement_identity = settlementIdentityPayload({goal_id: "goal-a", agent_id: "agent-a", + turn_instance_id: String(source.turn_instance_id), replan_obligation_id: "replan-other"}); + for (const work_item_id of ["todo-a", "replan-other"]) { + const observed = {...work, progress_observation: {...work.progress_observation as JsonObject, work_item_id}, + _source_facts: {...source, todo_id: null, settlement_identity}}; + const ref = projectReplanContext({...request, rows: [observed]}).evidence[0].evidence_ref; + const rows = [decision, observed]; + const follow = projectReplanContext({...strideRequest, rows}).decision_followthrough; + const replay = projectReplanContext({...strideRequest, operation: "review_evidence", rows, + previous_decision_ref: follow.previous_decision.evidence_ref, evidence_refs: [ref]}); + assert.deepEqual(replay.citations, [{evidence_ref: ref, available: true, + subsequent: work_item_id === "replan-other", declared_work: false}]); + assert.equal(follow.recorded_progress_count, Number(work_item_id === "replan-other")); + } +}); + test("unconsumed result survives later reviews and citations alone; recorded work closes only its source relation", () => { const first = reviewed(1); (first._source_facts as JsonObject).planned_todo_ids = ["todo-a"]; @@ -183,13 +217,28 @@ test("unconsumed result survives later reviews and citations alone; recorded wor // pending research result from each status update. for (const delivery_outcome of ["surface_only", null, "future_outcome"]) { for (const progress_observation of [null, {...progress, work_item_id: "todo-b"}]) { - const status = {...subsequent(4), todo_id: "todo-b", delivery_outcome, progress_observation}; + const status = {...subsequent(4, "todo-b"), delivery_outcome, progress_observation}; assert.deepEqual(readUse([first, result, next, status]), proposed); assert.equal((projectReplanContext({...request, rows: [status]}).evidence as JsonObject[]).length, 1); } } - const actual = {...subsequent(4), todo_id: "todo-b", progress_observation: null, + const actual = {...subsequent(4, "todo-b"), progress_observation: null, delivery_outcome: "outcome_progress"}; + const legacy: JsonObject = {...actual}; + delete legacy._source_facts; + const legacyRef = projectReplanContext({...request, rows: [legacy]}).evidence[0].evidence_ref; + const facts = actual._source_facts; + for (const effect_id of ["goal-a:agent-a:todo-b:another-turn", ""]) { + const conflict = {...actual, _source_facts: {...facts, settlement_identity: {...facts.settlement_identity, effect_id}}}; + const rows = [first, result, next, conflict]; + assert.deepEqual(readUse(rows), proposed, "a conflicting settlement cannot close the earlier result"); + const context = projectReplanContext({...strideRequest, rows}); + const follow = context.decision_followthrough; + assert.equal(follow.ordinary_work, undefined); + const replay = projectReplanContext({...strideRequest, operation: "review_evidence", rows, + previous_decision_ref: follow.previous_decision.evidence_ref, evidence_refs: [legacyRef]}); + assert.deepEqual(replay.citations, [{evidence_ref: legacyRef, available: true, subsequent: false, declared_work: false}]); + } const adopted = readUse([first, result, next, actual]); assert.equal(adopted.unresolved_count, 1, "the next result remains available for the next decision"); assert.notEqual((adopted.unresolved as JsonObject[])[0].evidence_ref, ref); @@ -227,7 +276,7 @@ test("ordinary declared-work evidence reaches followthrough without becoming typ health_check: "The alternate implementation regressed; retain the reference."}; const ref = (projectReplanContext({...request, rows: [actual]}).evidence as JsonObject[])[0].evidence_ref; const before = {...subsequent(0), progress_observation: null}; - const other = {...subsequent(3), todo_id: "todo-other", progress_observation: null}; + const other = {...subsequent(3, "todo-other"), progress_observation: null}; const accounting = {...actual, generated_at: row(10).generated_at, _source_facts: {...actual._source_facts as JsonObject, history_position: 10, quota_spend_commit: {schema_version: "quota_spend_commit_receipt_v0", effect_id: "spent"}}}; @@ -262,6 +311,41 @@ test("ordinary declared-work evidence reaches followthrough without becoming typ assert.deepEqual(projectReplanContext({...request, rows: [decision, actual]}).decision_followthrough.ordinary_work.evidence, follow.ordinary_work.evidence); }); +test("same-second ordinary work keeps each admitted result readable", () => { + const decision = reviewed(1); + (decision._source_facts as JsonObject).planned_todo_ids = ["todo-a"]; + const first: JsonObject = {...subsequent(2), progress_observation: null, delivery_outcome: "outcome_progress"}; + const second = {...first, _source_facts: subsequent(3)._source_facts}; + const rows = [decision, first, first, second]; + const context = projectReplanContext({...strideRequest, rows}); + const follow = context.decision_followthrough as OrdinaryFollowthrough; + assert.equal(follow.ordinary_work.recorded_count, 2); + const resultRefs = follow.ordinary_work.evidence.map(item => item.evidence_ref); + assert.equal(new Set(resultRefs).size, 2); + assert.equal((follow as unknown as JsonObject).work_result_use && + ((follow as unknown as JsonObject).work_result_use as JsonObject).unresolved_count, 2); + assert.equal(validateReplanContext(context), context); + + const legacy = {...first}; + delete legacy._source_facts; + const oldRef = (projectReplanContext({...request, rows: [legacy]}).evidence as JsonObject[])[0].evidence_ref; + for (const ref of [...resultRefs, oldRef]) { + const read = projectReplanContext({...request, operation: "resolve", rows: [first, second], evidence_ref: ref}); + assert.equal((read.evidence as JsonObject).recommended_action, first.recommended_action); + } + const retirement = reviewed(4); + const vision = (retirement._source_facts as JsonObject).agent_vision as JsonObject; + (vision.path_delta as JsonObject).evidence_refs = [oldRef]; + (retirement._source_facts as JsonObject).planned_todo_ids = ["todo-a"]; + const later = {...subsequent(5), progress_observation: null, delivery_outcome: "outcome_progress"}; + const next = projectReplanContext({...strideRequest, rows: [...rows, retirement, later]}); + const relation = (next.decision_followthrough as JsonObject).work_result_use as JsonObject; + assert.equal(relation.recorded_followthrough_count, 1); + assert.equal(relation.unresolved_count, 2); + assert.deepEqual(projectReplanContext({...strideRequest, rows: [decision, first, second, first]}) + .decision_followthrough, follow); +}); + test("ordinary followthrough retains corrections and bounded coverage under source scope", () => { const decision = reviewed(1); const current = {goal_id: "goal-a", goal_instance_id: "instance-current"}; @@ -342,7 +426,7 @@ test("busy planned work cannot crowd another declared experiment out of review", const decision = reviewed(1); decision._source_facts.planned_todo_ids = ["todo-busy", "todo-counterexample"]; for (const typed of [true, false]) { - const observation = (position: number, todo: string): JsonObject => ({...subsequent(position), todo_id: todo, + const observation = (position: number, todo: string): JsonObject => ({...subsequent(position, todo), health_check: todo === "todo-counterexample" ? "The comparison rejected the proposed explanation." : "Repeated validation.", progress_observation: typed ? {...progress, work_item_id: todo, fingerprint: `result-${position}`} : null}); const counterexample = observation(2, "todo-counterexample"); @@ -376,11 +460,11 @@ test("busy planned work cannot crowd another declared experiment out of review", test("declared work returns canonical state and only its subsequent observations", () => { const decision = reviewed(2); decision._source_facts.planned_todo_ids = ["todo-experiment", "todo-unavailable"]; - const before = {...subsequent(1), todo_id: "todo-experiment", + const before = {...subsequent(1, "todo-experiment"), progress_observation: {...progress, work_item_id: "todo-experiment", fingerprint: "before"}}; - const experiment = {...subsequent(3), todo_id: "todo-experiment", + const experiment = {...subsequent(3, "todo-experiment"), progress_observation: {...progress, work_item_id: "todo-experiment", fingerprint: "negative-result"}}; - const other = {...subsequent(4), todo_id: "todo-other", + const other = {...subsequent(4, "todo-other"), progress_observation: {...progress, work_item_id: "todo-other", fingerprint: "other"}}; const context = projectReplanContext({...strideRequest, rows: [before, decision, experiment, other], todo_items: [{todo_id: "todo-experiment", role: "agent", status: "done", claimed_by: null, @@ -413,7 +497,7 @@ test("declared work returns canonical state and only its subsequent observations assert.throws(() => validateReplanContext({...context, decision_followthrough: {...follow, ...patch}}), /planned work/); } - const unrelated = Array.from({length: 12}, (_, i) => ({...subsequent(i + 5), todo_id: "todo-other", + const unrelated = Array.from({length: 12}, (_, i) => ({...subsequent(i + 5, "todo-other"), progress_observation: {...progress, work_item_id: "todo-other", fingerprint: "unrelated-" + i}})); const crowded = projectReplanContext({...strideRequest, rows: [decision, experiment, ...unrelated]}); assert.equal(crowded.decision_followthrough.observations.length, 6);