Skip to content

Commit 23d692b

Browse files
authored
Merge pull request #10212 from loopx-project/codex/c1-ready-opening-dedup-20261205
Reuse observed Vision guidance in the native work opening
2 parents 4f03143 + c865948 commit 23d692b

5 files changed

Lines changed: 155 additions & 41 deletions

File tree

‎loopx/control_plane/quota/progressive_context.ts‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {quotaSummaryReferences, contextSourceIdentity, contextProjectionChanges,
1717
import {encodeContextDelivery, fileNavigationPaths, supportingIndexSource,
1818
SUPPORTING_INDEX_HEADER_FIELDS} from "./context_delivery.ts";
1919
import {capturedContextSelection} from "./context_selection.ts";
20-
import {COMPLETE_TURN_DECISION_VERSION} from "./turn_envelope_codec.ts";
20+
import {COMPLETE_TURN_DECISION_VERSION, contextWithCliVisionAudit} from "./turn_envelope_codec.ts";
2121
import {SCOPED_OUTCOME_PROJECTION_MODE, SCOPED_OUTCOME_THRESHOLD} from "./turn_envelope_scoping.ts";
2222
import {createHash} from "node:crypto";
2323

@@ -183,9 +183,9 @@ function hasBoundDatedTodoReentry(context: JsonObject, interaction: JsonObject,
183183
&& isDeepStrictEqual(identity, receipt.settlement_identity);
184184
}
185185

186-
function reusableWritebackPrecondition(context: JsonObject): ReusableReadField | undefined {
186+
function reusableSettlementReadFields(context: JsonObject): ReusableReadField[] {
187187
const interaction = jsonObject(context.interaction_contract);
188-
if (interaction?.schema_version !== "loopx_interaction_contract_v0") return undefined;
188+
if (interaction?.schema_version !== "loopx_interaction_contract_v0") return [];
189189
const plan = jsonObject(at(context, SETTLEMENT_PLAN_PATH)), steps = orderedSettlementSteps(plan);
190190
const identity = readySettlementIdentity(context, interaction, plan);
191191
const identityAgent = jsonObject(context.agent_identity)?.agent_id;
@@ -194,25 +194,35 @@ function reusableWritebackPrecondition(context: JsonObject): ReusableReadField |
194194
|| (identityAgent !== undefined && identityAgent !== agent)
195195
|| typeof context.goal_id !== "string" || context.goal_id !== identity.goal_id
196196
|| typeof context.registry !== "string" || !context.registry
197-
|| typeof context.runtime_root !== "string" || !context.runtime_root) return undefined;
197+
|| typeof context.runtime_root !== "string" || !context.runtime_root) return [];
198198
const writebacks = steps.map((value, index) => ({step: jsonObject(value), index}))
199199
.filter(({step}) => step?.kind === "durable_writeback");
200-
if (writebacks.length !== 1) return undefined;
200+
if (writebacks.length !== 1) return [];
201201
const {step, index} = writebacks[0]!;
202-
if (step?.owner !== "agent" || typeof step.precondition !== "string") return undefined;
203-
return {path: [...SETTLEMENT_PLAN_PATH, "ordered_steps", index, "precondition"],
204-
freshKeys: [], minimumBytes: MIN_REUSABLE_BODY_BYTES,
205-
sourceIdentity: JSON.stringify([context.registry, context.runtime_root, context.goal_ref ?? null,
206-
plan.schema_version, identity.goal_id, agent, identity.todo_id, step.kind, step.owner])};
202+
if (step?.owner !== "agent" || typeof step.precondition !== "string") return [];
203+
const sourceIdentity = JSON.stringify([context.registry, context.runtime_root, context.goal_ref ?? null,
204+
plan.schema_version, identity.goal_id, agent, identity.todo_id, step.kind, step.owner]);
205+
const fields: ReusableReadField[] = [{
206+
path: [...SETTLEMENT_PLAN_PATH, "ordered_steps", index, "precondition"],
207+
freshKeys: [], minimumBytes: MIN_REUSABLE_BODY_BYTES, sourceIdentity,
208+
}];
209+
const path = ["interaction_contract", "cli_channel", "vision_continuation_audit"];
210+
const audit = jsonObject(at(context, path));
211+
const judge = jsonObject(audit?.vision_gap_judge);
212+
if (audit?.required === true && judge?.decision === "continue" && judge.done === false) {
213+
// Keep the current audit requirement visible. Reuse the guidance only
214+
// when the entire view still matches the observed, scoped source.
215+
fields.push({path, freshKeys: ["required"], minimumBytes: MIN_REUSABLE_BODY_BYTES, sourceIdentity});
216+
}
217+
return fields;
207218
}
208219

209220
/** One registry for bodies eligible for observed reuse, regardless of whether
210221
* the reader delivered the body itself or packaged it in a complete parent. */
211222
function reusableFirstReadFields(context: JsonObject, exactBody?: ReusableExactBody): ReusableReadField[] {
212223
const exactFields = exactBody && at(context, exactBody.path) !== undefined
213224
? [{...exactBody, freshKeys: [], minimumBytes: MIN_REUSABLE_BODY_BYTES}] : [];
214-
const writeback = reusableWritebackPrecondition(context);
215-
const fields = [...exactFields, ...(writeback ? [writeback] : [])];
225+
const fields = [...exactFields, ...reusableSettlementReadFields(context)];
216226
const workPath: Path = ["interaction_contract", "agent_channel", "work_context"];
217227
const work = jsonObject(at(context, workPath));
218228
const base = [...workPath, "sources"];
@@ -499,7 +509,7 @@ export function contextReadSectionDigests(request: JsonObject, paths: Path[], ex
499509
/** Only registered, previously delivered bodies may use a reference. Current
500510
* decisions, stops, selection, settlement and unknown source shapes stay inline. */
501511
function observedFirstRead(request: JsonObject, pointers: string[], exactBody?: ReusableExactBody): JsonObject | undefined {
502-
const context = requireJsonObject(request.context, "current first read");
512+
const context = contextWithCliVisionAudit(requireJsonObject(request.context, "current first read"));
503513
const seen = requireJsonObject(request.consumed_pointers, "observed sections");
504514
if (typeof jsonObject(context.selected_todo)?.todo_id !== "string") return undefined;
505515
const fields = new Map(reusableFirstReadFields(context, exactBody).map(field => [pointer(field.path), field]));
@@ -1605,8 +1615,9 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
16051615
sourceRows.sort((left, right) => Number(hasText(right.source)) - Number(hasText(left.source)));
16061616
sourceRows.forEach(({source: _source, index, agenda}) => {
16071617
const source = [...work, "sources", index];
1618+
// A verified pending Inbox agenda uses the exact route in required_reads.
16081619
for (const field of ["source", "kind", "reason", "ordering", "command"])
1609-
include(...source, field);
1620+
if (field !== "command" || !agenda) include(...source, field);
16101621
// Current Goal/Todo text and source obligations stay whole. Expansive
16111622
// evidence pages, example recipes and historical bodies remain on demand.
16121623
include(...source, "content", "text");

‎loopx/control_plane/quota/turn_envelope_codec.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createHash } from "node:crypto";
22
import { inflateSync } from "node:zlib";
3+
import { isDeepStrictEqual } from "node:util";
34

45
import { authorityUnicodeCompare } from "../coordination/authority_store_codec.ts";
56
import { contextSourceIdentity } from "./diagnostic_projection.ts";
@@ -37,6 +38,38 @@ export function pickOwn(source: JsonObject, fields: readonly string[]): JsonObje
3738
return picked;
3839
}
3940

41+
export const CLI_VISION_AUDIT_REFERENCE = {
42+
projection_ref: "$.vision_continuation_audit", projection_view: "cli_channel", required: true,
43+
};
44+
45+
/** The writer checks the entire view against the root fields before sharing
46+
* them. The capture reader uses the existing interaction owner to present it. */
47+
export function cliVisionAuditView(owner: JsonObject): JsonObject | undefined {
48+
if (owner.schema_version !== "vision_continuation_audit_v0" || owner.required !== true) return undefined;
49+
const view = pickOwn(owner, ["required", "required_before_closeout", "recommended_action"]);
50+
const judge = object(owner.vision_gap_judge);
51+
if (Object.keys(judge).length) view.vision_gap_judge = pickOwn(judge, [
52+
"done", "decision", "reason", "agent_judge_instruction", "evidence_read_instruction",
53+
"registry_read_instruction", "done_only_when", "continue_when", "otherwise",
54+
]);
55+
return view;
56+
}
57+
58+
/** Use the same CLI view as the capture reader when estimating retained output.
59+
* This copy never replaces the sealed source or changes its read addresses. */
60+
export function contextWithCliVisionAudit(payload: JsonObject): JsonObject {
61+
if (payload.schema_version !== COMPLETE_TURN_DECISION_VERSION) return payload;
62+
const interaction = object(payload.interaction_contract), cli = object(interaction.cli_channel);
63+
if (!isDeepStrictEqual(cli.vision_continuation_audit, CLI_VISION_AUDIT_REFERENCE)) return payload;
64+
const owner = object(payload.vision_continuation_audit), judge = object(owner.vision_gap_judge);
65+
if (Object.hasOwn(owner, "projection_ref") || Object.hasOwn(owner, "projection_view") ||
66+
Object.hasOwn(judge, "projection_ref")) return payload;
67+
const audit = cliVisionAuditView(owner);
68+
return audit ? {...payload, interaction_contract: {...interaction, cli_channel: {
69+
...cli, vision_continuation_audit: audit,
70+
}}} : payload;
71+
}
72+
4073
export function isNonEmptyFilePath(value: unknown): value is string {
4174
return typeof value === "string" && value.trim().length > 0 && !value.includes("\0");
4275
}

‎loopx/control_plane/quota/turn_envelope_references.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ import { EFFECTIVE_ACTIONS, EffectiveAction } from "./effective_action.generated
1616
import { scopedReplanMetaGoalMeasurements, scopedReplanYardstickReversal } from "./progressive_context.ts";
1717
import { resolveSettlementWorkspaceRequirement } from "./settlement_workspace_causality.ts";
1818
import {
19-
COMPLETE_TURN_DECISION_VERSION, COMPLETE_TURN_HASH_CODEC, canonicalHash, canonicalValue,
19+
CLI_VISION_AUDIT_REFERENCE, COMPLETE_TURN_DECISION_VERSION, COMPLETE_TURN_HASH_CODEC, canonicalHash, canonicalValue,
20+
cliVisionAuditView,
2021
compactFields, completeSourceHash, decisionSourceHash, integer, isNonEmptyFilePath,
2122
object, pickNonNull, pickOwn, scalarString, shellQuote, text, textList,
2223
} from "./turn_envelope_codec.ts";
@@ -396,23 +397,7 @@ export function referenceExploreGuidance(payload: JsonObject): JsonObject {
396397
work_context: {...context, sources}}}};
397398
}
398399

399-
const VISION_AUDIT_PATH = "$.vision_continuation_audit";
400-
const CLI_VISION_AUDIT_REFERENCE = {
401-
projection_ref: VISION_AUDIT_PATH, projection_view: "cli_channel", required: true,
402-
};
403-
404-
/** The writer checks the entire view against the root fields before sharing
405-
* them. The capture reader uses the existing interaction owner to present it. */
406-
function cliVisionAuditView(owner: JsonObject): JsonObject | undefined {
407-
if (owner.schema_version !== "vision_continuation_audit_v0" || owner.required !== true) return undefined;
408-
const view = pickOwn(owner, ["required", "required_before_closeout", "recommended_action"]);
409-
const judge = object(owner.vision_gap_judge);
410-
if (Object.keys(judge).length) view.vision_gap_judge = pickOwn(judge, [
411-
"done", "decision", "reason", "agent_judge_instruction", "evidence_read_instruction",
412-
"registry_read_instruction", "done_only_when", "continue_when", "otherwise",
413-
]);
414-
return view;
415-
}
400+
const VISION_AUDIT_PATH = CLI_VISION_AUDIT_REFERENCE.projection_ref;
416401

417402
/** Exact copies use the complete root as their projection. */
418403
function visionAuditReference(audit: JsonObject): JsonObject {

‎tests/control_plane/test_context_first_read.py‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2875,8 +2875,10 @@ def bind(turn):
28752875
_, explicit = read(replay, authoring)
28762876
assert explicit == original
28772877
@pytest.mark.parametrize("version", ["quota_settlement_plan_v1", "quota_settlement_plan_v2"])
2878-
@pytest.mark.parametrize("transition", ["same", "changed", "wrong_binding", "unknown_version", "rebound"])
2879-
def test_native_first_read_reuses_only_observed_writeback_precondition(
2878+
@pytest.mark.parametrize("transition", [
2879+
"same", "changed", "audit_changed", "audit_closed", "wrong_binding", "unknown_version", "rebound",
2880+
])
2881+
def test_native_first_read_reuses_only_observed_settlement_guidance(
28802882
tmp_path, monkeypatch, decision, version, transition,
28812883
):
28822884
from test_codex_context_lifecycle import deliver, setup
@@ -2903,6 +2905,17 @@ def test_native_first_read_reuses_only_observed_writeback_precondition(
29032905
root = "/interaction_contract/cli_channel/settlement_plan"
29042906
precondition = root + "/ordered_steps/0/precondition"
29052907
command = root + "/ordered_steps/0/command_template"
2908+
audit = "/interaction_contract/cli_channel/vision_continuation_audit"
2909+
original_audit = {
2910+
"required": True,
2911+
"recommended_action": "Use existing Goal evidence before continuing or completing work.",
2912+
"required_before_closeout": ["Preserve the observed evidence and the accepted stop."],
2913+
"vision_gap_judge": {
2914+
"decision": "continue", "done": False,
2915+
"evidence_read_instruction": "Read the currently applicable outcome and confirm its owner. " * 22,
2916+
},
2917+
}
2918+
cli["vision_continuation_audit"] = deepcopy(original_audit)
29062919

29072920
def capture(turn):
29082921
identity = {"goal_id": "fixture", "agent_id": "agent", "todo_id": "todo_current",
@@ -2920,10 +2933,15 @@ def capture(turn):
29202933
first = capture("first")
29212934
page, facts = read_selection(first["first_read_command"])
29222935
assert facts[precondition] == text and "previously_delivered_fields" not in page
2936+
assert facts[audit] == original_audit
29232937
deliver(tmp_path, event, [page])
29242938

29252939
if transition == "changed":
29262940
step["precondition"] += " Await the updated external approval."
2941+
elif transition == "audit_changed":
2942+
cli["vision_continuation_audit"]["recommended_action"] = "Inspect the newly required evidence."
2943+
elif transition == "audit_closed":
2944+
cli["vision_continuation_audit"]["vision_gap_judge"].update(decision="done", done=True)
29272945
elif transition == "unknown_version":
29282946
plan["schema_version"] = "unknown"
29292947
elif transition == "rebound":
@@ -2934,19 +2952,27 @@ def capture(turn):
29342952
assert facts[command] == "loopx refresh-state --turn-instance-id next"
29352953
assert facts["/goal_boundary"] == decision["goal_boundary"]
29362954
assert facts[root + "/identity/effect_id"] == plan["identity"]["effect_id"]
2955+
reused = set(page.get("previously_delivered_fields", []))
2956+
if transition in {"same", "audit_changed", "audit_closed"}:
2957+
assert precondition in reused and precondition not in facts
2958+
else:
2959+
assert precondition not in reused and facts[precondition] == step["precondition"]
2960+
if transition in {"same", "changed"}:
2961+
assert audit in reused and audit not in facts
2962+
assert facts[audit + "/required"] is True
2963+
else:
2964+
assert audit not in reused and facts[audit] == cli["vision_continuation_audit"]
29372965
if transition != "same":
2938-
assert precondition not in page.get("previously_delivered_fields", [])
2939-
assert facts[precondition] == step["precondition"]
29402966
return
29412967

2942-
assert set(page["previously_delivered_fields"]) == {goal_text, precondition}
2943-
assert goal_text not in facts and precondition not in facts
2944-
_, recovered = read_selection(second["recovery"]["command"] + " --select " + precondition)
2945-
assert recovered[precondition] == text
2968+
assert reused == {goal_text, precondition, audit}
2969+
assert goal_text not in facts
2970+
_, recovered = read_selection(second["recovery"]["command"] + " --select " + precondition + " --select " + audit)
2971+
assert recovered[precondition] == text and recovered[audit] == original_audit
29462972
codex_context.codex_context_hook(str(tmp_path), {**event, "hook_event_name": "PostCompact"})
29472973
page, facts = read_selection(second["first_read_command"])
29482974
assert "previously_delivered_fields" not in page and facts[precondition] == text
2949-
assert facts[goal_text] == narrative
2975+
assert facts[goal_text] == narrative and facts[audit] == original_audit
29502976

29512977
@pytest.mark.parametrize("provider", ["file", "sqlite"])
29522978
@pytest.mark.parametrize("invalidation", ["compact", "journal_write"])

‎tests/control_plane_ts/progressive_context.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,60 @@ const source = {source: "goal_acceptance", reason: "Adopt the current objective.
1616
content: {status: "loaded", goal_acceptance_contract: {outcome_requirements: {
1717
schema_version: "loopx_goal_outcomes_v0", outcomes: [outcome]}}}};
1818

19+
test("observed opening reuses the verified CLI audit view without consuming a reference as text", () => {
20+
const identity = {goal_id: "goal", agent_id: "agent", todo_id: "todo", effect_id: "next-effect"};
21+
const auditAddress = ["interaction_contract", "cli_channel", "vision_continuation_audit"];
22+
const auditPointer = "/" + auditAddress.join("/");
23+
const audit = {
24+
required: true, recommended_action: "Verify current closeout evidence.",
25+
required_before_closeout: ["Scope verification"],
26+
vision_gap_judge: {done: false, decision: "continue", reason: "Read evidence from the current verified source. ".repeat(32)},
27+
};
28+
const context = {
29+
schema_version: "loopx_turn_envelope_v1", effective_action: "normal_run", ok: true,
30+
goal_id: "goal", agent_id: "agent", registry: "registry", runtime_root: "runtime",
31+
normal_delivery_allowed: true, selected_todo: {todo_id: "todo"}, heartbeat_receipt: {settlement_identity: identity},
32+
vision_continuation_audit: {schema_version: "vision_continuation_audit_v0", ...audit, acceptance_gaps: []},
33+
interaction_contract: {
34+
schema_version: "loopx_interaction_contract_v0", agent_channel: {delivery_allowed: true},
35+
cli_channel: {
36+
execution_preparation: {state: "ready", todo_id: "todo"},
37+
settlement_plan: {schema_version: "quota_settlement_plan_v2", identity,
38+
ordered_steps: [{kind: "durable_writeback", owner: "agent", precondition: "Verify delivery."}]},
39+
vision_continuation_audit: {
40+
projection_ref: "$.vision_continuation_audit", projection_view: "cli_channel", required: true,
41+
},
42+
},
43+
},
44+
};
45+
const {interaction_contract: contract} = context;
46+
const shown = {...context, interaction_contract: {...contract, cli_channel: {...contract.cli_channel,
47+
vision_continuation_audit: audit}}};
48+
const consumed = contextReadSectionDigests({context: shown}, [auditAddress]);
49+
50+
function observed(value: typeof context, consumed_pointers: Record<string, unknown>) {
51+
const request = {context: value, consumed_pointers, observe_first_read: true, include_initial_read_plan: true,
52+
scope: {goal_id: "goal", agent_id: "agent", session_id: "session", context_epoch: "epoch"},
53+
capture_id: "cap", surface: "complete_turn", native_projection: {path: "projection.json", sha256: "a".repeat(64)}};
54+
const result = prepareProgressiveContextDelivery(request, [], ["ok", "goal_id", "effective_action"]);
55+
const edits = result.changes as {path: string[]; value?: unknown}[];
56+
const observed = edits.filter(edit => edit.path[0] === "observed_first_read" && edit.path[1] === "reused");
57+
const record = observed.find(edit => edit.path.length === 2)?.value as Record<string, unknown> | undefined;
58+
return observed.find(edit => edit.path[2] === auditPointer)?.value ?? record?.[auditPointer];
59+
}
60+
const before = structuredClone(context);
61+
assert.equal(observed(context, {}), undefined);
62+
assert.equal(observed(context, consumed), consumed[auditPointer]);
63+
assert.deepEqual(context, before);
64+
65+
const changed = structuredClone(context);
66+
changed.vision_continuation_audit.recommended_action = "Apply the fresh approval condition.";
67+
assert.equal(observed(changed, consumed), undefined);
68+
const wrong = structuredClone(context);
69+
wrong.interaction_contract.cli_channel.vision_continuation_audit.projection_ref = "$.other_audit";
70+
assert.equal(observed(wrong, consumed), undefined);
71+
});
72+
1973
test("initial navigation keeps unknown supporting-index obligations whole", () => {
2074
const known = {coverage_confirmed: false, read_before_dependent_work: true,
2175
pointers: ["/supporting/evidence"], source: {path: "complete.json", sha256: "fixture-digest"}};
@@ -1004,6 +1058,11 @@ test("progressiveContextPlan handles agent_review basis_digest, defers large man
10041058
...details.unread_context_index, pointers: ["/unrelated/items"],
10051059
}}).includes(agendaPath));
10061060

1061+
const agendaCommand = "/interaction_contract/agent_channel/work_context/sources/0/command";
1062+
assert.ok(!first.includes(agendaCommand));
1063+
const changedRead = opening({...compact, read_command: "loopx manager-inbox read --different-route"});
1064+
assert.ok(changedRead.includes(agendaPath) && changedRead.includes(agendaCommand));
1065+
10071066
// When selected_todo explicitly requires explore, keep Explore graph history & templates inline.
10081067
const exploreTurn = structuredClone(payload);
10091068
exploreTurn.selected_todo = {todo_id: "todo-active", required_capabilities: ["explore"]};

0 commit comments

Comments
 (0)