Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion loopx/capabilities/native_chat/steward_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from collections.abc import Mapping, Sequence
import subprocess as subprocess

from ...control_plane.runtime.time import chronology_key
from ...control_plane.scheduler.monitor_todo import monitor_todo_is_due
from ...control_plane.todos.list_readback import list_goal_todos
from ...file_lock import exclusive_file_lock
Expand Down Expand Up @@ -157,7 +158,7 @@ def runnable_advancement_todos(
rows,
key=lambda row: (
prio.get(str(row.get("priority") or "P1"), 9),
str(row.get("created_at") or ""),
chronology_key(row.get("created_at")),
str(row["todo_id"]),
),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ const TODO_CONTRACT_REVISION_FIELDS: readonly (readonly string[])[] = [
["completion_result"],
["completion_receipt_id"],
["material_change_scope", "material_change_scope_generations"],
["created_at"],
];

interface HistoricalTodoContract {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ export const COORDINATION_STATE_CONTRACT = deepFreeze({
"note",
"evidence",
"reason",
"created_at",
"completed_at",
"completion_turn_key",
"completion_result",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ def _freeze(value: Any) -> Any:
'note',
'evidence',
'reason',
'created_at',
'completed_at',
'completion_turn_key',
'completion_result',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"note",
"evidence",
"reason",
"created_at",
"completed_at",
"completion_turn_key",
"completion_result",
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/coordination/local_authority_runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,7 @@ export async function createLocalCoordinationTodo(
dry_run: input.dry_run === true,
...(expectedRevision === undefined ? {} : {expected_provider_revision: expectedRevision}),
now: claimObservedAt(input.observed_at),
observed_at: input.observed_at as string,
}, authoritySourcesCurrent);
return {
...result,
Expand Down Expand Up @@ -1461,6 +1462,7 @@ export async function terminalLifecycleLocalCoordinationTodo(
? true : Boolean(input.auto_archive_completed),
dry_run: input.dry_run as boolean,
now: claimObservedAt(input.observed_at),
observed_at: input.observed_at as string,
}, async () => await authoritySourcesCurrent() && researchEvidence.current(),
researchEvidence.qualify, request => verifyReentrySettlement(root, request), observeWorkspace), ...providerEvidence};
} finally {await researchEvidence.close();}
Expand Down
4 changes: 3 additions & 1 deletion loopx/control_plane/coordination/todo_create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface CoordinationTodoCreateInput {
readonly operation_id: string;
readonly dry_run: boolean;
readonly expected_provider_revision?: string;
readonly observed_at?: string;
readonly now: Date;
}

Expand Down Expand Up @@ -120,7 +121,7 @@ function semanticDuplicateResult(
cursor: unknown,
identityDescription = "role/text",
): CoordinationTodoCreateResult {
const ignored = new Set(["schema_version", "todo_id", "created_by", "last_actor_agent_id", "updated_at"]);
const ignored = new Set(["schema_version", "todo_id", "created_by", "last_actor_agent_id", "created_at", "updated_at"]);
const mismatch = Object.entries(todo).find(([field, value]) =>
!ignored.has(field) && !(
// The legacy Markdown read model omits an empty capabilities list;
Expand Down Expand Up @@ -161,6 +162,7 @@ function createCandidate(
schema_version: TODO_DOMAIN_ITEM_SCHEMA,
created_by: input.actor_agent_id,
last_actor_agent_id: input.actor_agent_id,
created_at: input.observed_at ?? input.now.toISOString(),
updated_at: input.now.toISOString().replace(/\.\d{3}Z$/u, "Z"),
};
if (priority.priority === null) { delete candidate.priority; delete candidate.title; }
Expand Down
10 changes: 6 additions & 4 deletions loopx/control_plane/coordination/todo_successor_derivation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ function materializeSuccessorProposals(predecessorId: string, proposals: readonl
function successorCandidate(
todo: JsonObject,
actor: string | null,
now: Date,
timestamps: {readonly created_at: string; readonly updated_at: string},
domainReadModel: boolean,
completionPolicy: JsonObject | null,
): JsonObject {
Expand All @@ -466,7 +466,7 @@ function successorCandidate(
schema_version: TODO_DOMAIN_ITEM_SCHEMA,
created_by: todo.created_by ?? actor,
last_actor_agent_id: actor,
updated_at: now.toISOString().replace(/\.\d{3}Z$/u, "Z"),
...timestamps,
};
if (todo.role === "agent" && completionPolicy !== null && completionPolicy.effective_next_claimed_by === null) {
delete candidate.claimed_by;
Expand Down Expand Up @@ -519,11 +519,12 @@ export function prepareCoordinationTodoTerminalSuccessors(params: {
readonly completionPolicy: JsonObject | null;
readonly completionPolicyRequest: JsonObject | null;
readonly domainReadModel: boolean;
readonly createdAt: string;
readonly now: Date;
}): TerminalSuccessorsPreparation {
const {
command, todoId, todo, todos, registeredAgents, actorAgentId, linkedSuccessorTodoIds,
successorIntents, completionPolicy, completionPolicyRequest, domainReadModel, now,
successorIntents, completionPolicy, completionPolicyRequest, domainReadModel, createdAt, now,
} = params;
const fail = (
reasonCode: string,
Expand Down Expand Up @@ -592,6 +593,7 @@ export function prepareCoordinationTodoTerminalSuccessors(params: {
);
}
}
const timestamps = {created_at: createdAt, updated_at: now.toISOString().replace(/\.\d{3}Z$/u, "Z")};
const successorCandidates: JsonObject[] = [];
for (const successor of successors) {
const successorId = String(successor.todo_id);
Expand All @@ -606,7 +608,7 @@ export function prepareCoordinationTodoTerminalSuccessors(params: {
{todo_id: duplicate.todo_id},
);
}
successorCandidates.push(successorCandidate(successor, actorAgentId, now, domainReadModel, completionPolicy));
successorCandidates.push(successorCandidate(successor, actorAgentId, timestamps, domainReadModel, completionPolicy));
}
return {status: "ready", successorCandidates, successorIds, generatedSuccessorIds};
}
2 changes: 2 additions & 0 deletions loopx/control_plane/coordination/todo_terminal_lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ interface CoordinationTodoTerminalLifecycleBaseInput {
readonly completion_policy_request: JsonObject | null;
readonly auto_archive_completed?: boolean;
readonly dry_run: boolean;
readonly observed_at?: string;
readonly now: Date;
}

Expand Down Expand Up @@ -1412,6 +1413,7 @@ export async function executeCoordinationTodoTerminalLifecycle(
completionPolicy,
completionPolicyRequest: input.completion_policy_request,
domainReadModel,
createdAt: input.observed_at ?? input.now.toISOString(),
now: input.now,
});
if (successorPrep.status === "failed") {
Expand Down
3 changes: 2 additions & 1 deletion loopx/control_plane/scheduler/monitor_batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,10 @@ function planWriteback(input: MonitorBatchInput) {
}
if (todo.task_class === "user_gate") Object.assign(todo, {action_kind: "gate", unblocks_todo_id: monitor.todo_id});
}
const observedAt = String(observation.generated_at);
const created = planCoordinationTodoCreate({goal_id: input.goal_id, operation_id: input.operation_id,
actor_agent_id: actor, registered_agents: input.registered_agents, dry_run: input.dry_run,
now: new Date(String(observation.generated_at)), todo}, plannedTodos,
now: new Date(observedAt), observed_at: observedAt, todo}, plannedTodos,
input.read_model_schema ?? TODO_DOMAIN_READ_RECORD_SCHEMA,
role === "agent" && intent.next_target_key ? "role_target" : "role_text", "actor_owned");
if (created.status !== "planned" && created.status !== "no_change") throw new EffectRuntimeRequestError(String(created.reason));
Expand Down
6 changes: 5 additions & 1 deletion loopx/control_plane/todos/provider_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from ...agent_registry import registered_agent_ids_from_registry
from ..coordination.authority_source_capture import authority_registry_source
from ...state_refresh import now_local
from ..coordination.local_authority import (
LOCAL_AUTHORITY_SOURCES,
LocalCoordinationAuthorityUnavailable,
Expand All @@ -22,6 +21,7 @@
EffectRuntimeResponseAmbiguous,
effect_runtime_result,
)
from ..runtime.time import now_local_iso
from .contract import (
normalize_todo_metadata_for_write,
normalize_todo_task_class,
Expand All @@ -40,6 +40,10 @@
from .provider_projection import settle_canonical_todo_projection


def now_local() -> str:
return now_local_iso(timespec="microseconds")


def create_canonical_todo_if_promoted(
*, registry_path: Path, runtime_root: Path, goal_id: str, role: str,
text: str, status: str, actor_agent_id: str | None,
Expand Down
77 changes: 77 additions & 0 deletions regression/StewardFollowupOrder.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import Std

/-
Run with Lean 4.22.0: `lean -DwarningAsError=true regression/StewardFollowupOrder.lean`.

This models `runnable_advancement_todos` after eligibility and timestamp
parsing. Smaller priority numbers rank first. Timestamps are optional UTC
microseconds, with ranks for the original timestamp and Todo ID strings.
The Python regression covers the actual filters, parser, and sorted output.
-/

namespace StewardFollowupOrder

structure Todo where
eligible : Bool
priority : Nat
time : Option Int
rawRank : Nat
idRank : Nat

abbrev tieBeforeOrAt (a b : Todo) : Prop :=
a.rawRank < b.rawRank ∨ (a.rawRank = b.rawRank ∧ a.idRank ≤ b.idRank)

def timeBeforeOrAt (a b : Todo) : Bool :=
match a.time, b.time with
| some left, some right => decide (left < right ∨ (left = right ∧ tieBeforeOrAt a b))
| none, some _ => true
| some _, none => false
| none, none => decide (tieBeforeOrAt a b)

def beforeOrAt (a b : Todo) : Bool :=
decide (a.priority < b.priority ∨
(a.priority = b.priority ∧ timeBeforeOrAt a b = true))

def runnable (todos : List Todo) : List Todo :=
(todos.filter Todo.eligible).mergeSort beforeOrAt

theorem runnable_keeps_exactly_the_eligible_todos (todos : List Todo) :
(runnable todos).Perm (todos.filter Todo.eligible) :=
List.mergeSort_perm _ _

theorem runnable_is_ordered (todos : List Todo) :
(runnable todos).Pairwise (fun a b => beforeOrAt a b = true) := by
unfold runnable
apply List.sorted_mergeSort
· rintro ⟨_, ap, atime, ar, ai⟩ ⟨_, bp, btime, br, bi⟩ ⟨_, cp, ctime, cr, ci⟩ hab hbc
cases atime <;> cases btime <;> cases ctime <;>
simp [beforeOrAt, timeBeforeOrAt, tieBeforeOrAt] at * <;> omega
· rintro ⟨_, ap, atime, ar, ai⟩ ⟨_, bp, btime, br, bi⟩
cases atime <;> cases btime <;>
simp [beforeOrAt, timeBeforeOrAt, tieBeforeOrAt, Bool.or_eq_true] <;> omega

theorem priority_precedes_time (todos : List Todo) :
(runnable todos).Pairwise (fun a b => a.priority ≤ b.priority) := by
apply (runnable_is_ordered todos).imp
intro a b ordered
simp only [beforeOrAt, decide_eq_true_eq] at ordered
omega

theorem equal_priority_uses_chronological_order (todos : List Todo) :
(runnable todos).Pairwise (fun a b => a.priority = b.priority →
∀ first second, a.time = some first → b.time = some second → first ≤ second) := by
apply (runnable_is_ordered todos).imp
intro a b ordered samePriority first second firstTime secondTime
simp [beforeOrAt, timeBeforeOrAt, firstTime, secondTime, samePriority] at ordered
omega

theorem text_sort_can_put_a_newer_equal_priority_todo_first :
"2026-02-03T10:00:00.000001Z" < "2026-02-03T10:00:00Z" ∧
beforeOrAt ⟨true, 1, some 0, 1, 0⟩ ⟨true, 1, some 1, 0, 1⟩ = true := by decide

#print axioms runnable_keeps_exactly_the_eligible_todos
#print axioms priority_precedes_time
#print axioms equal_priority_uses_chronological_order
#print axioms text_sort_can_put_a_newer_equal_priority_todo_first

end StewardFollowupOrder
Loading
Loading