Skip to content

Commit 4392e81

Browse files
committed
refactor(quota): split turn_envelope and deduplicate codec helpers
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent d210e4c commit 4392e81

8 files changed

Lines changed: 1339 additions & 1383 deletions

File tree

‎loopx/control_plane/effect_program.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import {assertActionSelectionConsistency} from "./work_items/action_selection_admission.ts";
22
import { EffectRuntimeRequestError } from "./effect_runtime_errors.ts";
3-
import { isStringLiteral, type JsonObject } from "./runtime_decode.ts";
3+
import { isStringLiteral, pythonString, type JsonObject } from "./runtime_decode.ts";
44
import { decodeInteractionContract } from "./work_items/interaction_contract.ts";
55
import { EffectiveAction } from "./quota/effective_action.generated.ts";
66
import {BARE_SHA256_PATTERN} from "./content_digest.ts";
@@ -258,13 +258,6 @@ function asObject(value: unknown): JsonObject {
258258
: {};
259259
}
260260

261-
function pythonString(value: unknown): string {
262-
if (value === null || value === undefined) return "None";
263-
if (value === true) return "True";
264-
if (value === false) return "False";
265-
return String(value);
266-
}
267-
268261
function truthyString(value: unknown): string {
269262
return value ? pythonString(value) : "";
270263
}

‎loopx/control_plane/quota/turn_envelope.py‎

Lines changed: 10 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -302,19 +302,23 @@ def quota_capability_automation_source(payload: Mapping[str, Any]) -> dict[str,
302302
return _turn_envelope_result("capability_automation_source", payload=dict(payload))
303303

304304

305-
def turn_envelope_replan_settlement_identity(
306-
envelope: Mapping[str, Any], *, turn_instance_id: str | None,
305+
def _turn_settlement_identity(
306+
operation: str, envelope: Mapping[str, Any], *, turn_instance_id: str | None,
307307
) -> dict[str, Any] | None:
308-
result = _turn_envelope_result("replan_settlement_identity", envelope=dict(envelope),
309-
turn_instance_id=turn_instance_id)
310-
identity = result.get("identity")
308+
identity = _turn_envelope_result(operation, envelope=dict(envelope), turn_instance_id=turn_instance_id).get("identity")
311309
if identity is None:
312310
return None
313311
if not isinstance(identity, Mapping):
314312
raise RuntimeError("TypeScript Turn settlement identity must be an object")
315313
return dict(identity)
316314

317315

316+
def turn_envelope_replan_settlement_identity(
317+
envelope: Mapping[str, Any], *, turn_instance_id: str | None,
318+
) -> dict[str, Any] | None:
319+
return _turn_settlement_identity("replan_settlement_identity", envelope, turn_instance_id=turn_instance_id)
320+
321+
318322
def compose_turn_decision(
319323
payload: Mapping[str, Any], *, scheduler_execution_context: (
320324
Mapping[str, Any] | SchedulerExecutionContextResolution | None
@@ -347,11 +351,7 @@ def assert_complete_turn_decision(payload: Mapping[str, Any]) -> None:
347351
def turn_envelope_scoped_settlement_identity(
348352
envelope: Mapping[str, Any], *, turn_instance_id: str | None,
349353
) -> dict[str, Any] | None:
350-
identity = _turn_envelope_result("scoped_settlement_identity", envelope=dict(envelope),
351-
turn_instance_id=turn_instance_id).get("identity")
352-
if identity is not None and not isinstance(identity, Mapping):
353-
raise RuntimeError("TypeScript Turn settlement identity must be an object")
354-
return dict(identity) if identity is not None else None
354+
return _turn_settlement_identity("scoped_settlement_identity", envelope, turn_instance_id=turn_instance_id)
355355

356356

357357
def build_turn_envelope(
@@ -363,19 +363,6 @@ def build_turn_envelope(
363363
captured_decision_path: str | None = None,
364364
) -> dict[str, Any]:
365365
"""Project one full quota decision through the canonical TS transaction."""
366-
367-
return _build_turn_projection(payload,
368-
scheduler_execution_context=scheduler_execution_context,
369-
captured_decision_path=captured_decision_path)
370-
371-
372-
def _build_turn_projection(
373-
payload: Mapping[str, Any], *, scheduler_execution_context: (
374-
Mapping[str, Any] | SchedulerExecutionContextResolution | None
375-
) = None,
376-
captured_decision_path: str | None = None,
377-
) -> dict[str, Any]:
378-
379366
resolution = resolve_scheduler_execution_context(scheduler_execution_context)
380367
scheduler_execution_args: object = ""
381368
if resolution.ok and resolution.context is not None:

‎loopx/control_plane/quota/turn_envelope.ts‎

Lines changed: 121 additions & 1343 deletions
Large diffs are not rendered by default.
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
import { createHash } from "node:crypto";
2+
import { inflateSync } from "node:zlib";
3+
4+
import { authorityUnicodeCompare } from "../coordination/authority_store_codec.ts";
5+
import { contextSourceIdentity } from "./diagnostic_projection.ts";
6+
import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
7+
import { pythonString, requireJsonObject, type JsonObject } from "../runtime_decode.ts";
8+
9+
export const COMPLETE_TURN_DECISION_VERSION = "loopx_turn_envelope_v1";
10+
// Sparse producer metadata is a different identity from the earlier
11+
// experimental all-float binding; its saved contracts need their pinned reader.
12+
export const COMPLETE_TURN_HASH_CODEC = "context_source_numbers_v2";
13+
14+
const EXECUTABLE_CLI_ARGS_MAX_ITEMS = 64;
15+
const EXECUTABLE_CLI_ARGS_MAX_ITEM_CHARS = 512;
16+
const EXECUTABLE_CLI_ARGS_MAX_TOTAL_CHARS = 2_048;
17+
18+
export function object(value: unknown): JsonObject {
19+
return typeof value === "object" && value !== null && !Array.isArray(value)
20+
? { ...(value as JsonObject) }
21+
: {};
22+
}
23+
24+
export function pickNonNull(source: JsonObject, fields: readonly string[]): JsonObject {
25+
const picked: JsonObject = {};
26+
for (const field of fields) {
27+
if (source[field] !== null && source[field] !== undefined) picked[field] = source[field];
28+
}
29+
return picked;
30+
}
31+
32+
export function pickOwn(source: JsonObject, fields: readonly string[]): JsonObject {
33+
const picked: JsonObject = {};
34+
for (const field of fields) {
35+
if (Object.hasOwn(source, field)) picked[field] = source[field];
36+
}
37+
return picked;
38+
}
39+
40+
export function isNonEmptyFilePath(value: unknown): value is string {
41+
return typeof value === "string" && value.trim().length > 0 && !value.includes("\0");
42+
}
43+
44+
export function scalarString(value: unknown, label: string, fallback = ""): string {
45+
if (value === null || value === undefined || value === "") return fallback;
46+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
47+
throw new EffectRuntimeRequestError(`${label} must be scalar-compatible`);
48+
}
49+
return pythonString(value);
50+
}
51+
52+
export function integer(value: unknown, label: string): number {
53+
if (value === null || value === undefined || value === "") return 0;
54+
if (typeof value === "boolean") return Number(value);
55+
if (typeof value === "number" && Number.isFinite(value)) return Math.trunc(value);
56+
if (typeof value === "string" && /^[+-]?\d+$/u.test(value.trim())) return Number.parseInt(value, 10);
57+
throw new EffectRuntimeRequestError(`${label} must be integer-compatible`);
58+
}
59+
60+
export function text(value: unknown, limit: number): string | null {
61+
if (value === null || value === undefined) return null;
62+
const compact = scalarString(value, "text value").trim().split(/\s+/u).join(" ");
63+
if (!compact) return null;
64+
return compact.length <= limit ? compact : `${compact.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
65+
}
66+
67+
export function textList(value: unknown, limit: number, itemLimit = 240): string[] {
68+
if (!Array.isArray(value)) return [];
69+
const result: string[] = [];
70+
for (const item of value) {
71+
const rendered = text(item, itemLimit);
72+
if (!rendered || result.includes(rendered)) continue;
73+
result.push(rendered);
74+
if (result.length >= limit) break;
75+
}
76+
return result;
77+
}
78+
79+
export function compactFields(
80+
value: unknown, fields: readonly string[], limits: Readonly<Record<string, number>> = {},
81+
): JsonObject {
82+
const source = object(value);
83+
const compact: JsonObject = {};
84+
for (const field of fields) {
85+
const raw = source[field];
86+
if (raw === null || raw === undefined) continue;
87+
if (limits[field] !== undefined) {
88+
const rendered = text(raw, limits[field]);
89+
if (rendered) compact[field] = rendered;
90+
} else if (Array.isArray(raw)) {
91+
const values = textList(raw, 6, 140);
92+
if (values.length > 0) compact[field] = values;
93+
} else compact[field] = raw;
94+
}
95+
return compact;
96+
}
97+
98+
export function executableCliArgs(value: unknown): string[] {
99+
if (!Array.isArray(value) || value.length === 0 || value.length > EXECUTABLE_CLI_ARGS_MAX_ITEMS) return [];
100+
const result: string[] = [];
101+
let totalChars = 0;
102+
for (const item of value) {
103+
if (typeof item !== "string" || !item || item.length > EXECUTABLE_CLI_ARGS_MAX_ITEM_CHARS) return [];
104+
totalChars += item.length + 1;
105+
if (totalChars > EXECUTABLE_CLI_ARGS_MAX_TOTAL_CHARS) return [];
106+
result.push(item);
107+
}
108+
return result;
109+
}
110+
111+
export function canonicalValue(value: unknown): unknown {
112+
if (Array.isArray(value)) return value.map(canonicalValue);
113+
if (typeof value !== "object" || value === null) return value;
114+
const source = value as JsonObject;
115+
return Object.fromEntries(
116+
Object.keys(source).sort(authorityUnicodeCompare).map((key) => [key, canonicalValue(source[key])]),
117+
);
118+
}
119+
120+
export function canonicalHash(value: unknown): string {
121+
return `sha256:${createHash("sha256").update(JSON.stringify(canonicalValue(value)), "utf8").digest("hex")}`;
122+
}
123+
124+
export function completeSourceHash(value: JsonObject, identity = contextSourceIdentity(value, [])): string {
125+
return `sha256:${createHash("sha256").update(identity(value, []), "utf8").digest("hex")}`;
126+
}
127+
128+
/** Complete references reuse the checked content binding. Historical captures
129+
* retain their old JSON hash; never rewrite a stored action or Turn key. */
130+
export function decisionSourceHash(payload: JsonObject): string {
131+
if (payload.schema_version !== COMPLETE_TURN_DECISION_VERSION) return canonicalHash(payload);
132+
const digest = object(payload.contract_binding).content_hash;
133+
if (typeof digest !== "string") throw new EffectRuntimeRequestError("complete Turn decision content binding is missing");
134+
return digest;
135+
}
136+
137+
export function shellQuote(value: string): string {
138+
return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
139+
}
140+
141+
export function commandPrefix(runtimeRoot: unknown, registry?: unknown): string {
142+
const runtimeRootText = scalarString(runtimeRoot, "quota payload runtime_root").trim();
143+
const registryText = scalarString(registry, "quota payload registry").trim();
144+
return "loopx" + (registryText ? ` --registry ${shellQuote(registryText)}` : "") +
145+
(runtimeRootText ? ` --runtime-root ${shellQuote(runtimeRootText)}` : "");
146+
}
147+
148+
export function coldPath(
149+
payload: JsonObject, agentId: string | null, schedulerExecutionArgs: string, capturedDecisionPath?: string,
150+
): JsonObject {
151+
const goalId = scalarString(payload.goal_id, "quota payload goal_id", "<goal-id>");
152+
const agentArg = agentId ? ` --agent-id ${agentId}` : "";
153+
const prefix = commandPrefix(payload.runtime_root, payload.registry);
154+
return {
155+
full_decision: capturedDecisionPath ? `cat -- ${shellQuote(capturedDecisionPath)}` : schedulerExecutionArgs
156+
? `${prefix} --format json quota should-run --goal-id ${goalId}${agentArg}${schedulerExecutionArgs}`
157+
: "rerun the typed quota_guard from the current host packet",
158+
...(capturedDecisionPath ? {
159+
captured_decision: {
160+
path: capturedDecisionPath,
161+
goal_id: payload.goal_id ?? null,
162+
agent_id: agentId,
163+
turn_instance_id: object(payload.heartbeat_receipt).turn_instance_id ?? null,
164+
source_hash_ref: "$.action_signature.source_decision_hash",
165+
instruction: "Read this saved observation for omitted context. Check ok, Goal/Agent/Turn and source hash before use. " +
166+
"It grants no fresh authority: selection, lease/workspace changes, cancellation or quota revalidation require " +
167+
"the current host guard and a new capture directory. Missing or invalid capture requires recovery, not blind guard replay.",
168+
},
169+
} : {}),
170+
todo_detail: `${prefix} --format json todo list --goal-id ${goalId}`,
171+
status_detail: `${prefix} --format json status --goal-id ${goalId}`,
172+
};
173+
}
174+
175+
export function decodeTurnSource(request: JsonObject, inlineField: "payload" | "source"): JsonObject {
176+
const transport = requireJsonObject(request.source_transport, "Turn composition source transport");
177+
const { encoding, data } = transport;
178+
const maxSourceBytes = 1024 * 1024;
179+
if (Object.hasOwn(request, inlineField) || encoding !== "deflate-base64-json-v0" ||
180+
typeof data !== "string" || data.length > maxSourceBytes ||
181+
data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
182+
throw new EffectRuntimeRequestError("invalid Turn composition source transport");
183+
}
184+
let source: unknown;
185+
try {
186+
const compressed = Buffer.from(data, "base64");
187+
// Inflate may stop at the first stream and silently leave input unread.
188+
// The synchronous info result reports consumed bytes on supported Node versions.
189+
const { buffer, engine } = inflateSync(compressed,
190+
{ info: true, maxOutputLength: maxSourceBytes }) as unknown as { buffer: Buffer; engine: { bytesWritten: number } };
191+
if (engine.bytesWritten !== compressed.length) throw new Error("trailing compressed source data");
192+
source = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer));
193+
} catch {
194+
throw new EffectRuntimeRequestError("Turn composition source must be valid compressed JSON within 1 MiB");
195+
}
196+
return requireJsonObject(source, "complete Turn decision source");
197+
}

0 commit comments

Comments
 (0)