Skip to content

Commit 3ce41a0

Browse files
authored
Bound suggested outcomes in native quota openings (#9005)
* fix(quota): bound suggested outcomes in native openings Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> * docs: resolve the benchmark runtime guide on Frontstage Pages Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --------- Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 9e9aada commit 3ce41a0

11 files changed

Lines changed: 428 additions & 38 deletions

File tree

‎docs/reference/protocols/quota-cli-hot-path-compaction-v0.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,23 @@ TypeScript 上下文 owner 同时约束 `quota context-read --initial-read`。
2929
停止和结算不变;改变的只是起始视图,不是完整 capture 或显式读取。总成本比较须计入
3030
后续索引补读及额外调用;初读字节减少本身不证明保留、理解或收益。
3131

32+
A prepared native turn with a matching settlement receipt can open a large
33+
batch of suggested outcomes with their IDs, objectives, revisions, and exact
34+
addresses. This applies when the complete suggested bodies exceed the native
35+
first-read window and every suggested outcome has a verified supporting
36+
address. Instead of claiming complete requirements inline, the opening
37+
identifies those omitted outcome parent paths (the parent of each `/id` pointer)
38+
and requires selecting every applicable complete outcome from the current
39+
recovery capture before dependent work. A small batch retains its complete
40+
opening bodies. Explicit initial reads and saved selection references retain
41+
their own read plans.
42+
43+
原生 Turn 准备就绪后,若结算回执匹配、建议验收项的完整正文超过首读窗口,且各项
44+
都有核验过的支撑地址,首读先提供各项目标、ID、版本和精确地址。该首读不再声称
45+
已保留完整要求,而是标明省略的验收父路径(各 `/id` 指针的父路径),并要求在
46+
依赖工作前沿当前恢复 capture 读取适用验收项的完整正文。小批量仍在首读展开完整
47+
正文。显式初读和已保存的选择引用沿各自的读取计划运行。
48+
3249
## Ownership Boundary
3350

3451
Successful JSON `refresh-state` output keeps the complete `explore_result` once.

‎loopx/cli_commands/quota_capture.py‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,14 @@ def native_context_capture_view(projected: dict[str, Any], directory: Path, *,
112112
# Its recovery recipe does not require an extra root index to be planned.
113113
stateless_first_read = progressive_enabled and page_attached and captured_recovery is not None
114114

115-
def pin_initial_selection(plan: dict[str, Any]) -> None:
115+
def pin_initial_selection(plan: dict[str, Any], *, opening_context_instruction: str | None = None) -> None:
116116
nonlocal initial_read_pointers, initial_read_reference, initial_read_content
117117
selections = plan["selections"]
118118
initial_read_pointers = [item["pointer"] for item in selections]
119119
try:
120-
initial_read_reference, initial_read_content = write_initial_context_read_reference(Path(current["path"]), current["sha256"],
121-
current_document, selections)
120+
initial_read_reference, initial_read_content = write_initial_context_read_reference(
121+
Path(current["path"]), current["sha256"], current_document, selections,
122+
opening_context_instruction=opening_context_instruction)
122123
except OSError:
123124
# Read-only capture roots keep the existing initial recipe;
124125
# metadata is optional and never a read/authority receipt.
@@ -145,7 +146,7 @@ def pin_initial_selection(plan: dict[str, Any]) -> None:
145146
try:
146147
initial, plan = initial_read_plan["initial"], initial_read_plan["plan"]
147148
if initial:
148-
pin_initial_selection(plan)
149+
pin_initial_selection(plan, opening_context_instruction=initial_read_plan.get("opening_context_instruction"))
149150
else:
150151
field_index = _context_index_fields(current_document, plan["selections"][0]["children"])
151152
except (EffectRuntimeRemoteError, EffectRuntimeStartupError):
@@ -307,7 +308,8 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa
307308
surface=quota_context_surface(payload),
308309
capture_id=capture_id, continuity_generation=getattr(args, "_context_delivery_generation", None),
309310
progressive_enabled=progressive_enabled,
310-
captured_decision=decision_ref)
311+
captured_decision=decision_ref,
312+
max_page_output_bytes=getattr(args, "max_page_output_bytes", None))
311313
recovery = prepared.delivery.get("recovery")
312314
view = native_context_capture_view(prepared.delivery, capture_directory, context_directory=directory,
313315
progressive_enabled=progressive_enabled, initial_read_plan=prepared.initial_read_plan,

‎loopx/cli_commands/quota_context_reader.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -256,11 +256,17 @@ def _validate_context_page_window(offset: int, size: int, output_limit: int | No
256256

257257

258258
def _validate_pinned_selection(selection: dict[str, Any]) -> None:
259-
if (set(selection) - {"present_goal_narrative"} != {"select", "initial_read", "list_fields", "list_depth", "sha256"}
259+
if (set(selection) - {"present_goal_narrative", "opening_context_instruction"}
260+
!= {"select", "initial_read", "list_fields", "list_depth", "sha256"}
260261
or type(selection["initial_read"]) is not bool or type(selection["list_fields"]) is not bool
261262
or ("present_goal_narrative" in selection and (
262263
selection["present_goal_narrative"] is not True
263264
or selection["list_fields"] or selection["initial_read"]))
265+
or ("opening_context_instruction" in selection and (
266+
not isinstance(selection["opening_context_instruction"], str)
267+
or not selection["opening_context_instruction"]
268+
or selection["list_fields"] or selection["initial_read"]
269+
or "/context_details/instruction" not in (selection.get("select") or ())))
264270
or not isinstance(selection["sha256"], str)
265271
or BARE_SHA256_PATTERN.fullmatch(selection["sha256"]) is None):
266272
raise ValueError("reader selection reference is incomplete or unsupported")
@@ -393,7 +399,9 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An
393399
present_goal_narrative=(pinned_selection.get("present_goal_narrative") is True
394400
if pinned_selection is not None else None),
395401
selection_paths=reference.get("selection_paths") if pinned_selection is not None else None,
396-
text_append=text_append)
402+
text_append=text_append,
403+
opening_context_instruction=(pinned_selection.get("opening_context_instruction")
404+
if pinned_selection is not None else None))
397405
except ContextSelectionDigestChanged as exc:
398406
# A verified file digest only binds bytes. Preserve an explicit
399407
# selection or listing, including a receipt-only diagnostic.
@@ -720,12 +728,15 @@ def _bounded_initial_read(navigation: dict[str, Any], plan: dict[str, Any], *,
720728
digest = plan["capture"]["sha256"]
721729
if ordinary_page and _contains_ordinary_opening(ordinary_page["content"], document, plan):
722730
return None
723-
opening, content = write_initial_context_read_reference(path, digest, document, plan["opening"]["selections"])
731+
opening_instruction = plan.get("opening_context_instruction")
732+
opening, content = write_initial_context_read_reference(path, digest, document, plan["opening"]["selections"],
733+
opening_context_instruction=opening_instruction)
724734
if len(content) > page_bytes or len(content) >= output_bytes:
725735
return None
726736
remaining = remaining_reference
727737
if remaining is None:
728-
remaining, _ = write_initial_context_read_reference(path, digest, document, plan["remaining"]["selections"])
738+
remaining, _ = write_initial_context_read_reference(path, digest, document, plan["remaining"]["selections"],
739+
opening_context_instruction=opening_instruction)
729740

730741
def command(reference: Path) -> str:
731742
return context_capture_read_command(path, digest, page_bytes=page_bytes,

‎loopx/cli_commands/quota_native_context.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,8 @@ def authority_refusal(error: Exception) -> dict[str, Any]:
278278
goal_id=args.goal_id, agent_id=args.agent_id, surface="complete_turn" if complete else "quota_packet",
279279
capture_id=args.capture_sha256,
280280
continuity_generation=getattr(args, "_context_delivery_generation", None),
281-
progressive_enabled=activation["progressive_enabled"], selection_command_args_template=transport,
281+
progressive_enabled=activation["progressive_enabled"], max_page_output_bytes=caller_output_limit,
282+
selection_command_args_template=transport,
282283
captured_decision=captured_decision if activation["progressive_enabled"]
283284
and not args.select and not getattr(args, "list_fields", False)
284285
and (args.initial_read or "sha256" in captured_decision) else None,

‎loopx/control_plane/quota/progressive_context.ts‎

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export type ReusableExactBody = {path: Path; sourceIdentity: string};
2828
const MIN_REUSABLE_BODY_BYTES = 1024;
2929
const SETTLEMENT_PLAN_PATH = ["interaction_contract", "cli_channel", "settlement_plan"];
3030
const REPLAN_CONTEXT_PATH = ["autonomous_replan_obligation", "replan_context"];
31+
const COMPLETE_REQUIREMENTS_CLAUSE = "This view retains complete requirements and current review/check states. ";
3132
const pointer = (path: Path): string => path.length ? "/" + path.map(key =>
3233
String(key).replaceAll("~", "~0").replaceAll("/", "~1")).join("/") : "";
3334
const at = (root: unknown, path: Path): unknown => path.reduce<unknown>((row, key) =>
@@ -647,7 +648,7 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour
647648
}) : [],
648649
},
649650
instruction: deferred.map(edit => typeof edit.read_instruction === "string" ? edit.read_instruction : "").join("")
650-
+ "This view retains complete requirements and current review/check states. "
651+
+ COMPLETE_REQUIREMENTS_CLAUSE
651652
+ "Source history, review reasoning and evidence references are supporting material. "
652653
+ "Read them from this same immutable capture when a decision, verification or review depends on them. "
653654
+ "Use the outcome's supporting_material_pointer when shown, or remove /id from its selected JSON pointer. "
@@ -742,8 +743,11 @@ export function prepareProgressiveContextDelivery(request: JsonObject, legacyFie
742743
// Full native delivery can use that copy; delta still carries its own edits.
743744
if (request.source_edits === true && delivery.mode === "full") delete delivery.context;
744745
const observe = request.observe_first_read === true && !!jsonObject(required.context.selected_todo)?.todo_id;
746+
const firstReadBytes = jsonObject(request.native_projection)?.initial_read_output_bytes;
747+
const openingBudget = typeof firstReadBytes === "number" && Number.isSafeInteger(firstReadBytes) && firstReadBytes > 0
748+
? firstReadBytes : undefined;
745749
const groups = observe || request.include_initial_read_plan === true
746-
? initialContextReadGroups(required.context, decisionFields) : undefined;
750+
? initialContextReadGroups(required.context, decisionFields, openingBudget) : undefined;
747751
const openingSplit = request.include_initial_read_plan === true && groups
748752
? prepareInitialOpening(required.context, groups, exactBody?.path) : undefined;
749753
const pointers = groups ? [...groups.opening, ...groups.remaining] : [];
@@ -830,12 +834,27 @@ function prepareInitialOpening(context: JsonObject, groups: ReturnType<typeof in
830834
return {controls, details, linkedDetail};
831835
}
832836

837+
function deferredOutcomesInstruction(context: JsonObject, deferredOutcomes: readonly string[]): string | undefined {
838+
if (!deferredOutcomes.length) return undefined;
839+
const details = jsonObject(context.context_details);
840+
const instruction = typeof details?.instruction === "string" ? details.instruction : undefined;
841+
if (!instruction) return undefined;
842+
const notice =
843+
"This opening omits full requirement bodies for large suggested outcomes, delivering only their id, objective and revision. "
844+
+ "Before dependent work, read each applicable complete outcome from recovery.command "
845+
+ `(--select <pointer>): ${deferredOutcomes.join(", ")}. `
846+
+ "Supporting material below still comes from the original capture in context_details. ";
847+
return instruction.includes(COMPLETE_REQUIREMENTS_CLAUSE)
848+
? instruction.replace(COMPLETE_REQUIREMENTS_CLAUSE, notice)
849+
: notice + instruction;
850+
}
851+
833852
/** Invocation-local navigation, not captured input or a read/retention receipt.
834853
* Decision vocabulary comes from the same owner as standalone initial reads. */
835854
function nativeContextReadPlan(context: JsonObject, pointers: string[],
836855
groups: ReturnType<typeof initialContextReadGroups>, openingSplit?: ReturnType<typeof prepareInitialOpening>): {
837856
initial: boolean; plan: JsonObject; opening?: JsonObject; remaining?: JsonObject; linked_opening_detail?: string;
838-
ordinary_opening_rows?: number;
857+
ordinary_opening_rows?: number; deferred_suggested_outcomes?: string[]; opening_context_instruction?: string;
839858
} {
840859
if (!pointers.length) return {initial: false,
841860
plan: capturedContextSelection({context, select: [""], list_fields: true})};
@@ -850,10 +869,15 @@ function nativeContextReadPlan(context: JsonObject, pointers: string[],
850869
const ordinaryRows = openingSplit ? (plan.selections as ReadSelection[]).reduce((end, row, index) =>
851870
groups.opening.some(field => field === row.pointer || field.startsWith(row.pointer + "/"))
852871
? index + 1 : end, 0) : undefined;
872+
const deferredOutcomes = groups.deferredSuggestedOutcomes ?? [];
873+
const openingInstruction = deferredOutcomes.length && pointers.includes("/context_details/instruction")
874+
? deferredOutcomesInstruction(context, deferredOutcomes) : undefined;
853875
// Keep the ordinary fallback in the same order as the observed selection.
854876
return {initial: true, plan, ...(opening.length && remaining.length
855877
? {opening: select(opening), remaining: select(remaining)} : {}),
856-
...(openingSplit ? {linked_opening_detail: openingSplit.linkedDetail, ordinary_opening_rows: ordinaryRows} : {})};
878+
...(openingSplit ? {linked_opening_detail: openingSplit.linkedDetail, ordinary_opening_rows: ordinaryRows} : {}),
879+
...(deferredOutcomes.length ? {deferred_suggested_outcomes: deferredOutcomes} : {}),
880+
...(openingInstruction ? {opening_context_instruction: openingInstruction} : {})};
857881
}
858882

859883
export function initialContextReadPointers(context: JsonObject, decisionFields: readonly string[]): string[] {
@@ -951,8 +975,8 @@ function managerReturnAttention(value: unknown, requiredReads: unknown[]): JsonO
951975
return attention;
952976
}
953977

954-
function initialContextReadGroups(context: JsonObject, decisionFields: readonly string[]): {
955-
opening: string[]; remaining: string[];
978+
function initialContextReadGroups(context: JsonObject, decisionFields: readonly string[], openingBudget?: number): {
979+
opening: string[]; remaining: string[]; deferredSuggestedOutcomes?: string[];
956980
} {
957981
const object = (value: unknown): JsonObject | undefined =>
958982
value !== null && typeof value === "object" && !Array.isArray(value) ? value as JsonObject : undefined;
@@ -1015,6 +1039,7 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
10151039
include("interaction_contract", "agent_channel", field);
10161040
const cli = object(interaction.cli_channel), planPath = SETTLEMENT_PLAN_PATH;
10171041
const plan = object(cli?.settlement_plan);
1042+
const readyIdentity = readySettlementIdentity(context, interaction, plan);
10181043
const deferredReentry = hasBoundDatedTodoReentry(context, interaction, plan);
10191044
const turnBindingRequired = cli?.turn_binding_required === true;
10201045
const admissionFields = ["next_cli_actions", "spend_allowed_now", "spend_after_validation", "spend_policy"];
@@ -1109,6 +1134,7 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
11091134
// before selecting other sources' metadata: complete-parent coalescing keeps
11101135
// the first selected child's position. Preserve stable order within each group.
11111136
const hasText = (source: unknown): boolean => typeof object(object(source)?.content)?.text === "string";
1137+
const deferredSuggestedOutcomes: string[] = [];
11121138
sourceRows.sort((left, right) => Number(hasText(right.source)) - Number(hasText(left.source)));
11131139
sourceRows.forEach(({source: _source, index}) => {
11141140
const source = [...work, "sources", index];
@@ -1157,11 +1183,31 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
11571183
&& suggested.every(id => typeof id === "string"
11581184
&& outcomes.filter(value => object(value)?.id === id).length === 1);
11591185
const expanded = new Set(expand ? suggested as string[] : []);
1186+
const outcomesPath = [...source, "content", "goal_acceptance_contract", "outcome_requirements", "outcomes"];
1187+
const canDeferSuggested = openingBudget !== undefined && readyIdentity !== undefined && expanded.size > 0
1188+
&& inlineSupportingDetails && details?.outcome_support_from_id === true
1189+
&& details.path === supportingSource?.path && details.sha256 === supportingSource?.sha256
1190+
&& typeof details.command_template === "string" && details.command_template.length > 0;
1191+
const referenced = canDeferSuggested && Array.isArray(outcomes) ? outcomes.filter((value, index) => {
1192+
const row = object(value);
1193+
return typeof row?.id === "string" && expanded.has(row.id)
1194+
&& row.supporting_material_pointer === pointer([...outcomesPath, index]);
1195+
}) : [];
1196+
// The whole suggested set must have exact supporting addresses before
1197+
// exceeding the native opening window moves its bodies to selected reads.
1198+
const deferSuggested = canDeferSuggested && referenced.length === expanded.size
1199+
&& Buffer.byteLength(JSON.stringify(referenced), "utf8") > openingBudget;
11601200
if (Array.isArray(outcomes)) outcomes.forEach((_outcome, outcomeIndex) => {
1161-
const outcome = [...source, "content", "goal_acceptance_contract", "outcome_requirements", "outcomes", outcomeIndex];
1201+
const outcome = [...outcomesPath, outcomeIndex];
11621202
const row = object(_outcome), outcomeId = row?.id;
1163-
if (typeof outcomeId === "string" && expanded.has(outcomeId)) { include(...outcome); return; }
1203+
const suggested = typeof outcomeId === "string" && expanded.has(outcomeId);
1204+
if (suggested && !deferSuggested) { include(...outcome); return; }
11641205
include(...outcome, "id");
1206+
if (suggested) {
1207+
include(...outcome, "objective");
1208+
include(...outcome, "revision");
1209+
deferredSuggestedOutcomes.push(pointer(outcome));
1210+
}
11651211
// The id selection already carries the same absolute outcome address.
11661212
// Keep aliases whose source, value or read guidance cannot be verified.
11671213
if (!(inlineSupportingDetails && details?.outcome_support_from_id === true
@@ -1188,7 +1234,7 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
11881234
// A ready Turn already shows its ordered writeback and spend with their
11891235
// conditions. Hide only the exact duplicate fallback in this first read;
11901236
// recovery, legacy readers and the original capture keep both forms.
1191-
const repeatsSettlement = readySettlementIdentity(context, interaction, plan) !== undefined
1237+
const repeatsSettlement = readyIdentity !== undefined
11921238
&& settlementSteps?.length === 2 && writeback?.kind === "durable_writeback" && spend?.kind === "quota_spend"
11931239
&& templates?.every(command => typeof command === "string" && command.length > 0)
11941240
&& isDeepStrictEqual(cli?.next_cli_actions, templates);
@@ -1251,5 +1297,6 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
12511297
} else if (details && known(details, ["command_template", "path", "sha256"])) {
12521298
include("context_details");
12531299
} else include("context_details", "unread_context_index");
1254-
return {opening, remaining: pointers};
1300+
return {opening, remaining: pointers,
1301+
...(deferredSuggestedOutcomes.length ? {deferredSuggestedOutcomes} : {})};
12551302
}

0 commit comments

Comments
 (0)